format.c 23.3 KB
Newer Older
1
/* format.c - attempts to emulate excel's number formatting ability.
Arturo Espinosa's avatar
Arturo Espinosa committed
2
 * Copyright (C) 1998 Chris Lahey, Miguel de Icaza
3
 *
4 5
 * Redid the format parsing routine to make it accept more of the Excel
 * formats.  The number rendeing code from Chris has not been touched,
Arturo Espinosa's avatar
Arturo Espinosa committed
6
 * that routine is pretty good.
7
 *
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

Chris Lahey's avatar
Chris Lahey committed
23
#include <config.h>
24
#include <gnome.h>
25 26
#include <stdio.h>
#include <string.h>
27
#include <time.h>
28
#include <math.h>
29
#include <locale.h>
Morten Welinder's avatar
Morten Welinder committed
30
#include <limits.h>
Arturo Espinosa's avatar
Arturo Espinosa committed
31
#include <ctype.h>
32 33 34
#ifdef HAVE_IEEEFP_H
#    include <ieeefp.h>
#endif
35 36 37
#include "gnumeric.h"
#include "format.h"
#include "dates.h"
38
#include "utils.h"
39

40 41 42
/* Points to the locale information for number display */
static struct lconv *lc;

Morten Welinder's avatar
Morten Welinder committed
43 44 45 46 47
#define DECIMAL_CHAR_OF_LC(lc) ((lc)->decimal_point[0] ? (lc)->decimal_point[0] : '.')
#define THOUSAND_CHAR_OF_LC(lc) ((lc)->thousands_sep[0] ? (lc)->thousands_sep[0] : ',')
#define CHAR_DECIMAL (CHAR_MAX + 1)
#define CHAR_THOUSAND (CHAR_MAX + 2)

48
static void style_entry_free (gpointer data, gpointer user_data);
49 50


Chris Lahey's avatar
Chris Lahey committed
51
/*
52 53 54 55 56 57 58 59 60 61 62 63 64 65
 * The returned string is newly allocated.
 *
 * Current format is an optional date specification followed by an
 * optional number specification.
 *
 * A date specification is an arbitrary sequence of characters (other
 * than '#', '0', '?', or '.') which is copied to the output.  The
 * standard date fields are substituted for.  If it ever finds an a or
 * a p it lists dates in 12 hour time, otherwise, it lists dates in 24
 * hour time.
 *
 * A number specification is as described in the relavent portions of
 * the excel formatting information.  Commas can currently only appear
 * at the end of the number specification.  Fractions are not yet
Arturo Espinosa's avatar
Arturo Espinosa committed
66
 * supported.
67
 */
68

69

70 71 72 73
/*
 * Parses the year field at the beginning of the format.  Returns the
 * number of characters used.
 */
74
static int
75
append_year (GString *string, const guchar *format, const struct tm *time_split)
76
{
77
	char temp [5];
Arturo Espinosa's avatar
Arturo Espinosa committed
78

79
	if (tolower (format [1]) != 'y'){
80 81 82
		g_string_append_c (string, 'y');
		return 1;
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
83

Arturo Espinosa's avatar
Arturo Espinosa committed
84
	if (tolower (format [2]) != 'y' || tolower (format [3]) != 'y'){
Miguel de Icaza's avatar
Miguel de Icaza committed
85
		sprintf (temp, "%02d", time_split->tm_year % 100);
86 87 88 89 90 91 92 93
		g_string_append (string, temp);
		return 2;
	}

	sprintf (temp, "%04d", time_split->tm_year + 1900);
	g_string_append (string, temp);

	return 4;
94 95
}

96 97 98 99 100
/*
 * Parses the month field at the beginning of the format.  Returns the
 * number of characters used.
 */
static int
101
append_month (GString *string, const guchar *format, const struct tm *time_split)
102
{
103
	char temp [3];
Arturo Espinosa's avatar
Arturo Espinosa committed
104

105
	if (tolower (format [1]) != 'm'){
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
106
		sprintf (temp, "%d", time_split->tm_mon+1);
107 108 109
		g_string_append( string, temp);
		return 1;
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
110

111
	if (tolower (format [2]) != 'm')
112
	{
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
113
		sprintf (temp, "%02d", time_split->tm_mon+1);
114 115 116
		g_string_append (string, temp);
		return 2;
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
117

118
	if (tolower (format [3]) != 'm'){
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
119
		g_string_append (string, _(month_short [time_split->tm_mon])+1);
120 121 122 123 124
		return 3;
	}

	g_string_append (string, _(month_long [time_split->tm_mon]));
	return 4;
125 126
}

127 128 129 130 131
/*
 * Parses the hour field at the beginning of the format.  Returns the
 * number of characters used.
 */
static int
132
append_hour (GString *string, const guchar *format, const struct tm *time_split, int timeformat)
133
{
134 135
	char temp[3];

136
	if (tolower (format [1]) != 'h'){
137 138 139 140 141 142 143
	    sprintf (temp, "%d", timeformat ? (time_split->tm_hour % 12) : time_split->tm_hour);
	    g_string_append (string, temp);
	    return 1;
	}
	sprintf (temp, "%02d", timeformat ? (time_split->tm_hour % 12) : time_split->tm_hour);
	g_string_append (string, temp);
	return 2;
144 145
}

146 147 148 149 150
/*
 * Parses the day field at the beginning of the format.  Returns the
 * number of characters used.
 */
static int
151
append_day (GString *string, const guchar *format, const struct tm *time_split)
152
{
153 154
	char temp[3];

155
	if (tolower (format [1]) != 'd'){
156 157 158 159 160
		sprintf (temp, "%d", time_split->tm_mday);
		g_string_append (string, temp);
		return 1;
	}

161
	if (tolower (format [2]) != 'd'){
162 163 164 165 166
		sprintf (temp, "%02d", time_split->tm_mday);
		g_string_append (string, temp);
		return 2;
	}

167
	if (tolower (format [3]) != 'd'){
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
168
		g_string_append (string, _(day_short[time_split->tm_wday])+1);
169 170 171 172 173 174
		return 3;
	}

	g_string_append (string, _(day_long[time_split->tm_wday]));

	return 4;
175 176
}

177 178 179 180 181
/*
 * Parses the minute field at the beginning of the format.  Returns the
 * number of characters used.
 */
static int
182
append_minute (GString *string, const guchar *format, const struct tm *time_split)
183
{
184 185
	char temp [3];

186
	if (tolower (format [1]) != 'm'){
187 188 189 190 191 192 193 194 195
		sprintf (temp, "%d", time_split->tm_min);
		g_string_append (string, temp);
		return 1;
	}

	sprintf (temp, "%02d", time_split->tm_min);
	g_string_append (string, temp);

	return 2;
196 197
}

198 199 200 201 202
/*
 * Parses the second field at the beginning of the format.  Returns the
 * number of characters used.
 */
static int
203
append_second (GString *string, const guchar *format, const struct tm *time_split)
204
{
205
	char temp[3];
Arturo Espinosa's avatar
Arturo Espinosa committed
206

207
	if (tolower (format [1]) != 's'){
208 209 210 211 212 213 214 215 216
		sprintf (temp, "%d", time_split->tm_sec);
		g_string_append (string, temp);
		return 1;
	}

	sprintf (temp, "%02d", time_split->tm_sec);
	g_string_append (string, temp);

	return 2;
217 218
}

Morten Welinder's avatar
Morten Welinder committed
219
#if 0
220 221 222 223 224
/*
 * Parses the day part field at the beginning of the format.  Returns
 * the number of characters used.
 */
static int
225
append_half (GString *string, const guchar *format, const struct tm *time_split)
Chris Lahey's avatar
Chris Lahey committed
226
{
227
	if (time_split->tm_hour <= 11){
228
		if (tolower (format [0]) == 'a' || tolower (format [0]) == 'p')
229 230 231 232 233
			g_string_append_c (string, 'a');
		else
			g_string_append_c (string, 'A');
	}
	else {
234
		if (tolower (format [0]) == 'a' || tolower (format [0]) == 'p')
235 236 237 238
			g_string_append_c (string, 'p');
		else
			g_string_append_c (string, 'P');
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
239

240
	if (tolower (format [1]) == 'm'){
241 242 243 244
		g_string_append_c (string, format [1]);
		return 2;
	} else
		return 1;
Chris Lahey's avatar
Chris Lahey committed
245
}
Morten Welinder's avatar
Morten Welinder committed
246
#endif
Chris Lahey's avatar
Chris Lahey committed
247

248
/*
Miguel de Icaza's avatar
Miguel de Icaza committed
249
 * Since the Excel formating codes contain a number of ambiguities,
Morten Welinder's avatar
Morten Welinder committed
250
 * this routine does some analysis on the format first.
251 252 253 254
 */
static void
pre_parse_format (StyleFormatEntry *style)
{
255
	const unsigned char *format;
256 257 258 259 260 261 262 263 264 265

	style->want_am_pm = 0;
	for (format = style->format; *format; format++){
		switch (*format){
		case '"':
			for (format++; *format && *format != '"'; format++)
				;
			if (*format)
				format++;
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
266

267 268 269 270 271 272 273 274 275 276 277
		case '\\':
			if (*(format+1))
				format++;
			else
				return;
			break;

		case 'a':
		case 'p':
		case 'A':
		case 'P':
278
			if (tolower (*(format+1) == 'm'))
279 280 281 282 283 284
				style->want_am_pm = 1;
			break;
		}
	}
}

Chris Lahey's avatar
Chris Lahey committed
285 286
typedef struct
{
287 288 289
	int decimal;
	int timeformat;
	int hasnumbers;
290
} xformat_info;
Chris Lahey's avatar
Chris Lahey committed
291

292
/*
293
 * This routine should always return, it cannot fail, in the worst
Miguel de Icaza's avatar
Miguel de Icaza committed
294
 * case it should just downgrade to simplistic formatting
Chris Lahey's avatar
Chris Lahey committed
295
 */
296 297 298
void
format_compile (StyleFormat *format)
{
299 300 301 302 303 304
	GString *string = g_string_new ("");
	int i;
	int which = 0;
	int length = strlen (format->format);
	StyleFormatEntry standard_entries[4];
	StyleFormatEntry *temp;
Arturo Espinosa's avatar
Arturo Espinosa committed
305

306 307
	g_list_free (format->format_list);
	format->format_list = 0;
Arturo Espinosa's avatar
Arturo Espinosa committed
308

309
	/* g_string_maybe_expand (string, length); */
Arturo Espinosa's avatar
Arturo Espinosa committed
310

311
	for (i = 0; i < length; i++){
Chris Lahey's avatar
Chris Lahey committed
312

Miguel de Icaza's avatar
Miguel de Icaza committed
313 314
		switch (format->format[i]){

315
		case ';':
Miguel de Icaza's avatar
Miguel de Icaza committed
316
			if (which < 4){
317 318 319 320 321 322 323 324 325 326 327 328 329
				standard_entries [which].format = g_malloc0 (string->len + 1);
				strncpy (standard_entries[which].format, string->str, string->len);
				standard_entries [which].format[string->len] = 0;
				standard_entries [which].restriction_type = '*';
				which++;
			}
			string = g_string_truncate (string, 0);
			break;
		default:
			string = g_string_append_c (string, format->format [i]);
			break;
		}
	}
Chris Lahey's avatar
Chris Lahey committed
330

331 332 333 334 335 336 337
	if (which < 4){
		standard_entries[which].format = g_malloc0 (string->len + 1);
		strncpy (standard_entries[which].format, string->str, string->len);
		standard_entries[which].format[string->len] = 0;
		standard_entries[which].restriction_type = '*';
		which++;
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
338

339 340 341
	/* Set up restriction types. */
	standard_entries[1].restriction_type = '<';
	standard_entries[1].restriction_value = 0;
Miguel de Icaza's avatar
Miguel de Icaza committed
342 343
	switch (which){

344 345 346 347 348 349 350 351 352 353 354 355 356
	case 4:
		standard_entries[3].restriction_type = '@';
		/* Fall through. */
	case 3:
		standard_entries[2].restriction_type = '=';
		standard_entries[2].restriction_value = 0;
		standard_entries[0].restriction_type = '>';
		standard_entries[0].restriction_value = 0;
		break;
	case 2:
		standard_entries[0].restriction_type = '.';  /* . >= */
		standard_entries[0].restriction_value = 0;
		break;
Chris Lahey's avatar
Chris Lahey committed
357
	}
Miguel de Icaza's avatar
Miguel de Icaza committed
358 359

	for (i = 0; i < which; i++){
360 361 362 363 364
		temp = g_new (StyleFormatEntry, 1);
		*temp = standard_entries[i];
		pre_parse_format (temp);
		format->format_list = g_list_append (format->format_list, temp);
	}
Miguel de Icaza's avatar
Miguel de Icaza committed
365

366
	g_string_free (string, TRUE);
Chris Lahey's avatar
Chris Lahey committed
367 368 369
}

static void
370
style_entry_free(gpointer data, gpointer user_data)
Chris Lahey's avatar
Chris Lahey committed
371
{
372
	StyleFormatEntry *entry = data;
Arturo Espinosa's avatar
Arturo Espinosa committed
373

374
	g_free (entry->format);
375
	g_free (entry);
376 377
}

Miguel de Icaza's avatar
Miguel de Icaza committed
378 379 380 381 382 383 384
/*
 * This routine is invoked when the last user of the
 * format is gone (ie, refcount has reached zero) just
 * before the StyleFormat structure is actually released.
 *
 * resources allocated in format_compile should be disposed here
 */
385 386 387
void
format_destroy (StyleFormat *format)
{
388 389
	g_list_foreach (format->format_list, style_entry_free, NULL);
	g_list_free (format->format_list);
Arturo Espinosa's avatar
Arturo Espinosa committed
390
	format->format_list = NULL;
391 392
}

393 394 395 396 397 398 399 400 401 402 403 404 405
static struct {
	char       *name;
	StyleColor *color;
} format_colors [] = {
	{ N_("black")   },
	{ N_("blue")    },
	{ N_("cyan")    },
	{ N_("green")   },
	{ N_("magenta") },
	{ N_("red")     },
	{ N_("white")   },
	{ N_("yellow")  },
	{ NULL, NULL }
406 407
};

408 409 410 411 412 413 414 415
void
format_color_init (void)
{
	int i;

	for (i = 0; format_colors [i].name; i++){
		StyleColor *sc;
		GdkColor c;
Arturo Espinosa's avatar
Arturo Espinosa committed
416

417 418
		gdk_color_parse (format_colors [i].name, &c);
		sc = style_color_new (c.red, c.green, c.blue);
Arturo Espinosa's avatar
Arturo Espinosa committed
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433
		format_colors [i].color = sc;
	}
}

void
format_color_shutdown (void)
{
	int i;

	for (i = 0; format_colors [i].name; i++)
		style_color_unref (format_colors [i].color);
}

static StyleColor *
Morten Welinder's avatar
Morten Welinder committed
434
lookup_color (const char *str, const char *end)
435 436 437
{
	int i;

438 439
	for (i = 0; format_colors [i].name; i++){
		int len = strlen (format_colors [i].name);
440

441
		if ((strncasecmp (format_colors [i].name, str, len) == 0) ||
Miguel de Icaza's avatar
Miguel de Icaza committed
442
		    (strncasecmp (_(format_colors [i].name), str, len) == 0)){
443 444
			style_color_ref (format_colors [i].color);
			return format_colors [i].color;
445 446 447 448 449 450 451 452 453 454 455 456
		}
	}
	return NULL;
}

static GString *
render_number (gdouble number,
	       int left_req,
	       int right_req,
	       int left_spaces,
	       int right_spaces,
	       int right_allowed,
457
	       int use_thousand_sep,
458 459 460
	       int negative,
	       int supress_minus,
	       int decimal,
Morten Welinder's avatar
Morten Welinder committed
461
	       const char *show_decimal)
462 463
{
	GString *number_string = g_string_new ("");
Arturo Espinosa's avatar
Arturo Espinosa committed
464
	gint zero_count;
465 466 467
	gdouble temp;
	int group = 0;

Arturo Espinosa's avatar
Arturo Espinosa committed
468 469 470 471 472 473 474 475 476 477 478
	if (right_allowed >= 0) {
		/* Change "rounding" into "truncating".  */
		gdouble delta = 0.5;
		int i;
		for (i = 0; i < right_allowed; i++)
			delta /= 10.0;
		/* Note, that we assume number >= 0 here.  */
		number += delta;
	}

	for (temp = number; temp >= 1.0; temp /= 10.0){
479 480
		double r = floor (temp);
		int digit;
Arturo Espinosa's avatar
Arturo Espinosa committed
481

482
		if (use_thousand_sep){
483 484
			group++;
			if (group == 4){
485
				int c;
Arturo Espinosa's avatar
Arturo Espinosa committed
486

487
				group = 1;
488 489 490 491
				if (lc->thousands_sep [0] == 0)
					c = ',';
				else
					c = lc->thousands_sep [0];
Arturo Espinosa's avatar
Arturo Espinosa committed
492

493
				g_string_prepend_c (number_string, c);
494 495
			}
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
496

497 498
		digit = r - floor (r / 10) * 10;
		g_string_prepend_c (number_string, (digit) + '0');
499 500 501 502
		if (left_req > 0)
			left_req --;
		if (left_spaces > 0)
			left_spaces --;
Arturo Espinosa's avatar
Arturo Espinosa committed
503

504
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
505

506 507 508 509 510 511 512 513 514 515
	for (; left_req > 0; left_req--, left_spaces--)
		g_string_prepend_c (number_string, '0');

	for (; left_spaces > 0; left_spaces--)
		g_string_prepend_c (number_string, ' ');

	if (negative && !supress_minus)
		g_string_prepend_c (number_string, '-');

	if (decimal > 0)
516
		g_string_append (number_string, lc->decimal_point);
517 518 519
	else
		g_string_append (number_string, show_decimal);

Arturo Espinosa's avatar
Arturo Espinosa committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
	temp = number - floor (number);

	for (; right_req > 0; right_req --, right_allowed --, right_spaces --)
	{
		gint digit;
		temp *= 10.0;
		digit = (gint)temp;
		temp -= digit;
		g_string_append_c (number_string, digit + '0');
	}

	zero_count = 0;

	for (; right_allowed > 0; right_allowed --)
	{
		gint digit;
		temp *= 10.0;
		digit = (gint)temp;
		temp -= digit;

		if (digit == 0)
			zero_count ++;
		else
		{
			right_spaces -= zero_count + 1;
			zero_count = 0;
		}

		g_string_append_c (number_string, digit + '0');
	}

	g_string_truncate (number_string, number_string->len - zero_count);

	for (; right_spaces > 0; right_spaces--)
	{
		g_string_append_c (number_string, ' ');
	}

	return number_string;
559 560
}

561 562 563 564 565 566 567 568 569 570 571 572 573
typedef struct {
	char *decimal_point, *append_after_number;
	int  right_optional, right_spaces, right_req, right_allowed;
	int  left_spaces, left_req;
	int  scientific;
	int  scientific_shows_plus;
	int  scientific_exp;
	int  rendered;
	int  negative;
	int  decimal_separator_seen;
	int  supress_minus;
	int  comma_separator_seen;
} format_info_t;
Chris Lahey's avatar
Chris Lahey committed
574

575 576 577 578 579
static char *
do_render_number (gdouble number, format_info_t *info)
{
	GString *res;
	char *result;
580
	char decimal_point [2];
Arturo Espinosa's avatar
Arturo Espinosa committed
581

582
	info->rendered = 1;
Chris Lahey's avatar
Chris Lahey committed
583

584 585 586 587 588
	/*
	 * If the format contains only "#"s to the left of the decimal
	 * point, number in the [0.0,1.0] range are prefixed with a
	 * decimal point
	 */
589 590 591 592 593
	if (number > 0.0 && number < 1.0 && info->right_allowed == 0 && info->right_optional > 0){
		decimal_point [0] = lc->decimal_point [0];
		decimal_point [1] = 0;
	} else
		decimal_point [0] = 0;
Chris Lahey's avatar
Chris Lahey committed
594

Arturo Espinosa's avatar
Arturo Espinosa committed
595
#if 0
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	printf ("Rendering: %g with:\n", number);
	printf ("left_req:    %d\n"
		"right_req:   %d\n"
		"left_spaces: %d\n"
		"right_spaces:%d\n"
		"right_allow: %d\n"
		"negative:    %d\n"
		"supress:     %d\n"
		"decimalseen: %d\n"
		"decimalp:    %s\n",
		info->left_req,
		info->right_req,
		info->left_spaces,
		info->right_spaces,
		info->right_allowed + info->right_optional,
		info->negative,
		info->supress_minus,
		info->decimal_separator_seen,
		decimal_point);
#endif
Arturo Espinosa's avatar
Arturo Espinosa committed
616

617 618 619 620 621 622 623 624 625 626 627 628
	res = render_number (
		number,
		info->left_req,
		info->right_req,
		info->left_spaces,
		info->right_spaces,
		info->right_allowed + info->right_optional,
		info->comma_separator_seen,
		info->negative,
		info->supress_minus,
		info->decimal_separator_seen,
		decimal_point);
Chris Lahey's avatar
Chris Lahey committed
629

630 631
	if (info->append_after_number)
		g_string_append (res, info->append_after_number);
Arturo Espinosa's avatar
Arturo Espinosa committed
632

633 634
	result = g_strdup (res->str);
	g_string_free (res, TRUE);
Arturo Espinosa's avatar
Arturo Espinosa committed
635

636 637 638
	return result;
}

639 640 641 642 643 644 645
/*
 * Microsoft Excel has a bug in the handling of year 1900,
 * I quote from http://catless.ncl.ac.uk/Risks/19.64.html#subj9.1
 *
 * > Microsoft EXCEL version 6.0 ("Office 95 version") and version 7.0 ("Office
 * > 97 version") believe that year 1900 is a leap year.  The extra February 29
 * > cause the following problems.
Arturo Espinosa's avatar
Arturo Espinosa committed
646
 * >
647 648 649
 * > 1)  All day-of-week before March 1, 1900 are incorrect;
 * > 2)  All date sequence (serial number) on and after March 1, 1900 are incorrect.
 * > 3)  Calculations of number of days across March 1, 1900 are incorrect.
Arturo Espinosa's avatar
Arturo Espinosa committed
650
 * >
651 652 653 654
 * > The risk of the error will cause must be little.  Especially case 1.
 * > However, import or export date using serial date number will be a problem.
 * > If no one noticed anything wrong, it must be that no one did it that way.
 */
655 656 657 658
static struct tm *
split_time (gdouble number)
{
	static struct tm tm;
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
659
	double secs;
660

661
	GDate* date = g_date_new_serial (number);
Arturo Espinosa's avatar
Arturo Espinosa committed
662

663
	g_date_to_struct_tm (date, &tm);
664

Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
665
	secs = (number - floor (number)) * 86400.0;
666
	tm.tm_hour = secs / 3600;
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
667 668 669 670
	secs -= tm.tm_hour * 3600;
	tm.tm_min  = secs / 60;
	secs -= tm.tm_min * 60;
	tm.tm_sec  = floor (secs);
671

Morten Welinder's avatar
Morten Welinder committed
672 673
	g_date_free (date);

674 675 676
	return &tm;
}

677
static gchar *
Morten Welinder's avatar
Morten Welinder committed
678
format_number (gdouble number, const StyleFormatEntry *style_format_entry)
679 680
{
	GString *result = g_string_new ("");
Morten Welinder's avatar
Morten Welinder committed
681
	const char *format = style_format_entry->format;
682 683 684
	format_info_t info;
	int can_render_number = 0;
	int hour_seen = 0;
685
	struct tm *time_split = 0;
686
	char *res;
Arturo Espinosa's avatar
Arturo Espinosa committed
687

Morten Welinder's avatar
Morten Welinder committed
688 689 690
	if (!lc)
		lc = localeconv ();

691 692 693 694
	memset (&info, 0, sizeof (info));
	if (number < 0.0){
		info.negative = TRUE;
		number = -number;
Chris Lahey's avatar
Chris Lahey committed
695
	}
696

697
	while (*format){
Morten Welinder's avatar
Morten Welinder committed
698 699 700 701 702 703 704
		int c = *format;
		if (c == DECIMAL_CHAR_OF_LC (lc))
			c = CHAR_DECIMAL;
		else if (c == THOUSAND_CHAR_OF_LC (lc))
			c = CHAR_THOUSAND;

		switch (c) {
705 706 707 708 709
		case '#':
			can_render_number = 1;
			if (info.decimal_separator_seen)
				info.right_optional++;
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
710

711 712 713 714 715 716 717
		case '?':
			can_render_number = 1;
			if (info.decimal_separator_seen)
				info.right_spaces++;
			else
				info.left_spaces++;
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
718

719 720 721 722 723 724 725 726 727 728 729
		case '0':
			can_render_number = 1;
			if (info.decimal_separator_seen){
				info.right_req++;
				info.right_allowed++;
				info.right_spaces++;
			} else {
				info.left_spaces++;
				info.left_req++;
			}
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
730

Morten Welinder's avatar
Morten Welinder committed
731 732
		case CHAR_DECIMAL: {
			int c = *(format+1);
Arturo Espinosa's avatar
Arturo Espinosa committed
733

Morten Welinder's avatar
Morten Welinder committed
734 735 736 737 738 739 740 741 742 743 744
			can_render_number = 1;
			if (c && (c != '0' && c != '#' && c != '?'))
				number /= 1000;
			else
				info.decimal_separator_seen = TRUE;
			break;
		}

		case CHAR_THOUSAND: {
			info.comma_separator_seen = TRUE;
			break;
745
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
746

747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
		case 'E': case 'e':
			can_render_number = 1;
			info.scientific = TRUE;
			format++;
			for (format++; *format;){
				if (*format == '+'){
					info.scientific_shows_plus = TRUE;
					format++;
				} else if (*format == '-')
					format++;
				else if (*format == '0'){
					info.scientific_exp++;
					format++;
				} else
					break;
			}
			/* FIXME: this is a gross hack */
			{
Morten Welinder's avatar
Morten Welinder committed
765 766
				char buffer [40 + DBL_DIG];
				sprintf (buffer, "%.*g", DBL_DIG, number);
Arturo Espinosa's avatar
Arturo Espinosa committed
767

768 769 770
				g_string_append (result, buffer);
				goto finish;
			}
Arturo Espinosa's avatar
Arturo Espinosa committed
771

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
		/* percent */
		case '%':
			can_render_number = 1;
			number *= 100;
			info.append_after_number = "%";
			break;

		case '\\':
			if (*(format+1)){
				if (can_render_number && !info.rendered)
					g_string_append (result, do_render_number (number, &info));
				g_string_append_c (result, *format);
			}
			break;

		case '"': {
			if (can_render_number && !info.rendered)
				g_string_append (result, do_render_number (number, &info));

			for (format++; *format && *format != '"'; format++)
				g_string_append_c (result, *format);
			break;
Chris Lahey's avatar
Chris Lahey committed
794 795 796

		}

797 798 799 800 801 802 803 804
		case '-':
		case '/':
		case '(':
		case '+':
		case ' ':
		case ':':
			info.supress_minus = TRUE;
			/* fall down */
Arturo Espinosa's avatar
Arturo Espinosa committed
805

806 807 808
		case '$':
			g_string_append_c (result, *format);
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
809

810 811 812
		case '£':
			g_string_append_c (result, *format);
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
813

814 815 816 817 818
		case ')':
			if (can_render_number && !info.rendered)
				g_string_append (result, do_render_number (number, &info));
			g_string_append_c (result, *format);
			break;
Chris Lahey's avatar
Chris Lahey committed
819

820 821 822 823 824
		case '_':
			if (*(format+1))
				format++;
			g_string_append_c (result, ' ');
			break;
825

826
		case 'M':
827
		case 'm':
828 829
			if (!time_split)
				time_split = split_time (number);
830 831 832 833 834 835
			if (hour_seen)
				format += append_minute (result, format, time_split) - 1;
			else
				format += append_month (result, format, time_split) - 1;
			break;

836
		case 'D':
837
		case 'd':
838 839
			if (!time_split)
				time_split = split_time (number);
840 841 842
			format += append_day (result, format, time_split) -1;
			break;

843
		case 'Y':
844
		case 'y':
845 846
			if (!time_split)
				time_split = split_time (number);
847 848 849
			format += append_year (result, format, time_split) - 1;
			break;

850
		case 'S':
851
		case 's':
852 853
			if (!time_split)
				time_split = split_time (number);
854 855 856 857 858 859 860
			format += append_second (result, format, time_split) - 1;
			break;

		case '*':
			g_warning ("REPEAT FORMAT NOT YET SUPPORTED\n");
			break;

861
		case 'H':
862
		case 'h':
863 864
			if (!time_split)
				time_split = split_time (number);
865
			format += append_hour (result, format, time_split, style_format_entry->want_am_pm) - 1;
Miguel de Icaza's avatar
New:  
Miguel de Icaza committed
866
			hour_seen = TRUE;
867
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
868

869 870
		case 'A':
		case 'a':
871 872
			if (!time_split)
				time_split = split_time (number);
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
			if (time_split->tm_hour < 12){
				g_string_append_c (result, *format);
				format++;
				if (*format == 'm' || *format == 'M'){
					g_string_append_c (result, *format);
					if (*(format+1) == '/')
						format++;
				}
			} else {
				if (*(format+1) == 'm' || *(format+1) == 'M')
					format++;
				if (*(format+1) == '/')
					format++;
			}
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
888

889
		case 'P': case 'p':
890 891
			if (!time_split)
				time_split = split_time (number);
892 893 894 895 896 897 898 899 900 901 902
			if (time_split->tm_hour >= 12){
				g_string_append_c (result, *format);
				if (*(format+1) == 'm' || *(format+1) == 'M'){
					format++;
					g_string_append_c (result, *format);
				}
			} else {
				if (*(format+1) == 'm' || *(format+1) == 'M')
					format++;
			}
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
903

904 905 906 907 908
		default:
			break;
		}
		format++;
	}
Miguel de Icaza's avatar
Miguel de Icaza committed
909 910
	if (!info.rendered && can_render_number){
		char *rendered_string = do_render_number (number, &info);
Arturo Espinosa's avatar
Arturo Espinosa committed
911

Miguel de Icaza's avatar
Miguel de Icaza committed
912 913 914
		g_string_append (result, rendered_string);
		g_free (rendered_string);
	}
915 916 917 918
 finish:
	res = g_strdup (result->str);
	g_string_free (result, TRUE);
	return res;
919
}
Chris Lahey's avatar
Chris Lahey committed
920

921
static gboolean
Morten Welinder's avatar
Morten Welinder committed
922
check_valid (const StyleFormatEntry *entry, const Value *value)
923
{
Miguel de Icaza's avatar
Miguel de Icaza committed
924 925 926 927 928 929 930 931
	switch (value->type){

	case VALUE_STRING:
		return entry->restriction_type == '@';

	case VALUE_FLOAT:
		switch (entry->restriction_type){

Arturo Espinosa's avatar
Arturo Espinosa committed
932
		case '*':
Miguel de Icaza's avatar
Miguel de Icaza committed
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
			return TRUE;
		case '<':
			return value->v.v_float < entry->restriction_value;
		case '>':
			return value->v.v_float > entry->restriction_value;
		case '=':
			return value->v.v_float == entry->restriction_value;
		case ',':
			return value->v.v_float <= entry->restriction_value;
		case '.':
			return value->v.v_float >= entry->restriction_value;
		case '+':
			return value->v.v_float != entry->restriction_value;
		default:
			return FALSE;
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
949

Miguel de Icaza's avatar
Miguel de Icaza committed
950 951 952
	case VALUE_INTEGER:
		switch (entry->restriction_type){

Arturo Espinosa's avatar
Arturo Espinosa committed
953
		case '*':
Miguel de Icaza's avatar
Miguel de Icaza committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
			return TRUE;
		case '<':
			return value->v.v_int < entry->restriction_value;
		case '>':
			return value->v.v_int > entry->restriction_value;
		case '=':
			return value->v.v_int == entry->restriction_value;
		case ',':
			return value->v.v_int <= entry->restriction_value;
		case '.':
			return value->v.v_int >= entry->restriction_value;
		case '+':
			return value->v.v_int != entry->restriction_value;
		default:
			return FALSE;
		}
Arturo Espinosa's avatar
Arturo Espinosa committed
970

971
	default:
Miguel de Icaza's avatar
Miguel de Icaza committed
972
		return FALSE;
973
	}
Chris Lahey's avatar
Chris Lahey committed
974 975 976
}

gchar *
Morten Welinder's avatar
Morten Welinder committed
977
format_value (StyleFormat *format, const Value *value, StyleColor **color)
Chris Lahey's avatar
Chris Lahey committed
978
{
979 980 981 982
	char *v = NULL;
	StyleFormatEntry entry;
	GList *list;
	int is_general = 0;
Arturo Espinosa's avatar
Arturo Espinosa committed
983

984 985
	if (color)
		*color = NULL;
Arturo Espinosa's avatar
Arturo Espinosa committed
986

987 988 989 990
	/* get format */
	for (list = format->format_list; list; list = g_list_next (list))
		if (check_valid (list->data, value))
			break;
Arturo Espinosa's avatar
Arturo Espinosa committed
991

992 993 994 995
	if (list)
		entry = *(StyleFormatEntry *)(list->data);
	else
		entry.format = format->format;
996

997 998 999
	/* Try to parse a color specification */
	if (entry.format [0] == '['){
		char *end = strchr (entry.format, ']');
Arturo Espinosa's avatar
Arturo Espinosa committed
1000

1001
		if (end){
1002 1003
			if (color)
				*color = lookup_color (&entry.format [1], end);
1004 1005 1006 1007
			entry.format = end+1;
		}
	}

Miguel de Icaza's avatar
Miguel de Icaza committed
1008 1009
	if (entry.format [0] == 0)
		is_general = 1;
Morten Welinder's avatar
Morten Welinder committed
1010
	else if (strcmp (entry.format, "General") == 0) {
1011 1012
		entry.format += 7;
		is_general = 1;
Arturo Espinosa's avatar
Arturo Espinosa committed
1013
	}
Morten Welinder's avatar
Morten Welinder committed
1014
	/* FIXME: what about translated "General"?  */
Arturo Espinosa's avatar
Arturo Espinosa committed
1015

1016 1017
	switch (value->type){
	case VALUE_FLOAT:
Morten Welinder's avatar
Morten Welinder committed
1018 1019 1020 1021 1022 1023 1024
		if (finite (value->v.v_float)) {
			if (is_general){
				if (floor (value->v.v_float) == value->v.v_float)
					entry.format = "0";
				else
					entry.format = _("0.0########");
			}
1025
			v = format_number (value->v.v_float, &entry);
Morten Welinder's avatar
Morten Welinder committed
1026
		} else
Morten Welinder's avatar
Morten Welinder committed
1027
			return g_strdup (gnumeric_err_VALUE);
1028
		break;
Arturo Espinosa's avatar
Arturo Espinosa committed
1029

1030 1031
	case VALUE_INTEGER:
		if (is_general)
1032
			entry.format = "0";
1033 1034
		v = format_number (value->v.v_int, &entry);
		break;
Arturo Espinosa's avatar
Arturo Espinosa committed
1035

1036 1037
	case VALUE_STRING:
		return g_strdup (value->v.str->str);
Arturo Espinosa's avatar
Arturo Espinosa committed
1038

1039 1040 1041 1042 1043 1044
	case VALUE_CELLRANGE:
		return g_strdup (_("CELLRANGE"));

	case VALUE_ARRAY:
		return g_strdup (_("ARRAY"));
		
1045 1046 1047
	default:
		return g_strdup ("Internal error");
	}
Arturo Espinosa's avatar
Arturo Espinosa committed
1048

1049 1050
	/* Format error, return a default value */
	if (v == NULL)
Michael Meeks's avatar
Michael Meeks committed
1051
		return value_get_as_string (value);
Arturo Espinosa's avatar
Arturo Espinosa committed
1052

1053
	return v;
1054
}