gutils.c 14.4 KB
Newer Older
1 2 3
/*
 * utils.c:  Various utility routines that do not depend on the GUI of Gnumeric
 *
Chyla Zbigniew's avatar
Chyla Zbigniew committed
4
 * Authors:
5
 *    Miguel de Icaza (miguel@gnu.org)
6
 *    Jukka-Pekka Iivonen (iivonen@iki.fi)
Chyla Zbigniew's avatar
Chyla Zbigniew committed
7
 *    Zbigniew Chyla (cyba@gnome.pl)
8
 */
9 10
#include <gnumeric-config.h>
#include "gnumeric.h"
Jody Goldberg's avatar
Jody Goldberg committed
11
#include "gutils.h"
12

Jody Goldberg's avatar
Jody Goldberg committed
13 14
#include "sheet.h"
#include "ranges.h"
Morten Welinder's avatar
Morten Welinder committed
15
#include "mathfunc.h"
Jody Goldberg's avatar
Jody Goldberg committed
16

17 18
#include <libgnome/gnome-i18n.h>
#include <libgnome/gnome-config.h>
19
#include <stdlib.h>
20
#include <math.h>
21
#include <stdio.h>
22
#include <string.h>
23
#include <ctype.h>
Chyla Zbigniew's avatar
Chyla Zbigniew committed
24 25 26
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
27
#include <unistd.h>
Chyla Zbigniew's avatar
Chyla Zbigniew committed
28
#include <fcntl.h>
29
#include <gal/util/e-util.h>
Morten Welinder's avatar
Morten Welinder committed
30 31 32
#ifdef HAVE_FLOATINGPOINT_H
#include <floatingpoint.h>
#endif
33

Chyla Zbigniew's avatar
Chyla Zbigniew committed
34 35
/* ------------------------------------------------------------------------- */

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
static GList *timers_stack = NULL;

void
gnumeric_time_counter_push (void)
{
	GTimer *timer;

	timer = g_timer_new ();
	timers_stack = g_list_prepend (timers_stack, timer);
}

gdouble
gnumeric_time_counter_pop (void)
{
	GTimer *timer;
	gdouble ret_val;

	g_assert (timers_stack != NULL);

	timer = (GTimer *) timers_stack->data;
	timers_stack = g_list_remove (timers_stack, timers_stack->data);
	ret_val = g_timer_elapsed (timer, NULL);
	g_timer_destroy (timer);

	return ret_val;
}

Chyla Zbigniew's avatar
Chyla Zbigniew committed
63 64
/**
 * gnumeric_config_get_string_list:
Jody Goldberg's avatar
Jody Goldberg committed
65
 * @config_path: GNOME configuration path or its prefix if
Chyla Zbigniew's avatar
Chyla Zbigniew committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
 *               @item_name_prefix != NULL.
 * @item_name_prefix: Prefix of key name when reading multiple strings from
 *                    configuration.
 *
 * Reads list of string values from GNOME configuration.
 * If @item_name_prefix == NULL it gets a vector from configuration and then
 * converts it to GList. If @item_name_prefix != NULL, it gets string values
 * with keys of the form @item_name_prefix%d.
 *
 * Return value: list of newly allocated strings which you should free after
 * use using function e_free_string_list().
 */
GList *
gnumeric_config_get_string_list (const gchar *config_path,
                                 const gchar *item_name_prefix)
{
	GList *items = NULL;
	gint i;

	if (item_name_prefix != NULL) {
		gnome_config_push_prefix (config_path);
		for (i = 0; ; i++) {
			gchar *key, *value;

			key = g_strdup_printf ("%s%d", item_name_prefix, i);
			value = gnome_config_get_string (key);
			g_free (key);
			if (value != NULL) {
				items = g_list_prepend (items, value);
			} else {
				break;
			}
		}
		gnome_config_pop_prefix ();
		items = g_list_reverse (items);
	} else {
		gchar **itemv;
		gint n_items;

		gnome_config_get_vector (config_path, &n_items, &itemv);
		for (i = 0; i < n_items; i++) {
			items = g_list_prepend (items, itemv[i]);
		}
		g_free (itemv);
	}

	return items;;
}

/**
 * gnumeric_config_set_string_list:
Jody Goldberg's avatar
Jody Goldberg committed
117
 * @config_path: GNOME configuration path or its prefix if
Chyla Zbigniew's avatar
Chyla Zbigniew committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
 *               @item_name_prefix != NULL.
 * @item_name_prefix: Prefix of key name when writing multiple strings to
 *                    configuration.
 *
 * Stores list of string values in GNOME configuration.
 * If @item_name_prefix == NULL it converts @items to vector and stores it in
 * configuration. If @item_name_prefix != NULL, it stores mulitple strings
 * with keys of the form @item_name_prefix%d.
 */
void
gnumeric_config_set_string_list (GList *items,
                                 const gchar *config_path,
                                 const gchar *item_name_prefix)
{
	GList *l;
	gint i;

	if (item_name_prefix != NULL) {
		gchar *key;

		gnome_config_push_prefix (config_path);
		for (l = items, i = 0; l != NULL; l = l->next, i++) {

			key = g_strdup_printf ("%s%d", item_name_prefix, i);
			gnome_config_set_string (key, (gchar *) l->data);
			g_free (key);
		}
		key = g_strdup_printf ("%s%d", item_name_prefix, i);
		gnome_config_clean_key (key);
		g_free (key);
		gnome_config_pop_prefix ();
	} else {
		const gchar **itemv;
		gint n_items;

		n_items = g_list_length (items);
		if (n_items > 0) {
			itemv = g_new (const gchar *, n_items);
			for (l = items, i = 0; l != NULL; l = l->next, i++) {
				itemv[i] = (const gchar *) l->data;
			}
			gnome_config_set_vector (config_path, n_items, itemv);
			g_free (itemv);
		} else {
			gnome_config_set_vector (config_path, 0, NULL);
		}
	}
}

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
void
g_ptr_array_insert (GPtrArray *array, gpointer value, int index)
{
	if ((int)array->len != index) {
		int i = array->len - 1;
		gpointer last = g_ptr_array_index (array, i);
		g_ptr_array_add (array, last);

		while (i-- > index) {
			gpointer tmp = g_ptr_array_index (array, i);
			g_ptr_array_index (array, i+1) = tmp;
		}
		g_ptr_array_index (array, index) = value;
	} else
		g_ptr_array_add (array, value);
}

Chyla Zbigniew's avatar
Chyla Zbigniew committed
184 185 186 187 188 189 190 191
/**
 * g_create_list:
 * @item1: First item.
 *
 * Creates a GList from NULL-terminated list of arguments.
 *
 * Return value: created list.
 */
192 193 194 195 196 197 198 199 200 201
GList *
g_create_list (gpointer item1, ...)
{
	va_list args;
	GList *list = NULL;
	gpointer item;

	va_start (args, item1);
	for (item = item1; item != NULL; item = va_arg (args, gpointer)) {
		list = g_list_prepend (list, item);
Jody Goldberg's avatar
Jody Goldberg committed
202
	}
Chyla Zbigniew's avatar
Chyla Zbigniew committed
203
	va_end (args);
204 205 206 207

	return g_list_reverse (list);
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
gint
g_list_index_custom (GList *list, gpointer data, GCompareFunc cmp_func)
{
	GList *l;
	gint i;

	for (l = list, i = 0; l != NULL; l = l->next, i++) {
		if (cmp_func (l->data, data) == 0) {
			return i;
		}
	}

	return -1;
}

223 224 225 226 227
/**
 * g_list_free_custom:
 * @list: list of some items
 * @free_func: function freeing list item
 *
228
 * Clears a list, calling @free_func for each list item.
229 230 231 232 233 234 235 236 237 238 239 240 241
 *
 */
void
g_list_free_custom (GList *list, GFreeFunc free_func)
{
	GList *l;

	for (l = list; l != NULL; l = l->next) {
		free_func (l->data);
	}
	g_list_free (list);
}

Chyla Zbigniew's avatar
Chyla Zbigniew committed
242 243 244 245 246 247 248 249
/**
 * g_string_list_copy:
 * @list: List of strings.
 *
 * Creates a copy of the given string list (strings are also copied using
 * g_strdup).
 *
 * Return value: new copy of the list which you should free after use using
Jody Goldberg's avatar
Jody Goldberg committed
250
 *               function e_free_string_list()
Chyla Zbigniew's avatar
Chyla Zbigniew committed
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
 */
GList *
g_string_list_copy (GList *list)
{
	GList *list_copy = NULL, *l;

	for (l = list; l != NULL; l = l->next) {
		list_copy = g_list_prepend (list_copy, g_strdup ((gchar *) l->data));
	}
	list_copy = g_list_reverse (list_copy);

	return list_copy;
}

/**
 * g_strsplit_to_list:
 * @string: String to split
 * @delimiter: Token delimiter
 *
 * Splits up string into tokens at delim and returns a string list.
 *
 * Return value: string list which you should free after use using function
 * e_free_string_list().
 *
 */
GList *
g_strsplit_to_list (const gchar *string, const gchar *delimiter)
{
	gchar **token_v;
	GList *string_list = NULL;
	gint i;

	token_v = g_strsplit (string, delimiter, 0);
	if (token_v != NULL) {
		for (i = 0; token_v[i] != NULL; i++) {
			string_list = g_list_prepend (string_list, token_v[i]);
		}
		string_list = g_list_reverse (string_list);
		g_free (token_v);
	}

	return string_list;
}

295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
/**
 * g_slist_free_custom:
 * @list: list of some items
 * @free_func: function freeing list item
 *
 * Clears a list, calling g_free() for each list item.
 *
 */
void
g_slist_free_custom (GSList *list, GFreeFunc free_func)
{
	GSList *l;

	for (l = list; l != NULL; l = l->next) {
		free_func (l->data);
	}
	g_slist_free (list);
}

Chyla Zbigniew's avatar
Chyla Zbigniew committed
314 315 316 317
/**
 * g_lang_score_in_lang_list:
 *
 */
318 319 320
gint
g_lang_score_in_lang_list (gchar *lang, GList *lang_list)
{
Jody Goldberg's avatar
Jody Goldberg committed
321 322 323
	if (lang_list == NULL)
		lang_list = (GList *)gnome_i18n_get_language_list ("LC_MESSAGES");

324 325 326 327 328 329 330 331 332 333 334 335 336 337
	if (lang == NULL) {
		return g_list_length (lang_list);
	} else {
		GList *lang_item;

		lang_item = g_list_find_custom (lang_list, lang, g_str_compare);
		if (lang_item != NULL) {
			return g_list_position (lang_list, lang_item);
		} else {
			return G_MAXINT;
		}
	}
}

338 339 340
gint
gnumeric_strcase_equal (gconstpointer v, gconstpointer v2)
{
341
	return g_strcasecmp ((const gchar*) v, (const gchar*)v2) == 0;
342 343 344 345 346 347
}

/* a char* hash function from ASU */
guint
gnumeric_strcase_hash (gconstpointer v)
{
348
	const unsigned char *s = (const unsigned char *)v;
349
	const unsigned char *p;
350
	guint h = 0, g;
Morten Welinder's avatar
Morten Welinder committed
351

352 353 354 355 356 357 358
	for(p = s; *p != '\0'; p += 1) {
		h = ( h << 4 ) + tolower (*p);
		if ( ( g = h & 0xf0000000 ) ) {
			h = h ^ (g >> 24);
			h = h ^ g;
		}
	}
Morten Welinder's avatar
Morten Welinder committed
359

360 361 362
	return h /* % M */;
}

363
extern char *gnumeric_data_dir;
364 365 366
char *
gnumeric_sys_data_dir (const char *subdir)
{
367 368
	return g_strconcat (gnumeric_data_dir, G_DIR_SEPARATOR_S,
			    subdir, G_DIR_SEPARATOR_S, NULL);
369 370
}

371
extern char *gnumeric_lib_dir;
372 373 374
char *
gnumeric_sys_lib_dir (const char *subdir)
{
375 376
	return g_strconcat (gnumeric_lib_dir, G_DIR_SEPARATOR_S,
			    subdir, G_DIR_SEPARATOR_S, NULL);
377 378 379
}

#define GLADE_SUFFIX	"glade"
Jody Goldberg's avatar
Jody Goldberg committed
380
#define PLUGIN_SUFFIX	"plugins"
381

Miguel de Icaza's avatar
Miguel de Icaza committed
382 383 384 385 386 387 388 389 390 391 392
char *
gnumeric_sys_glade_dir (void)
{
	return gnumeric_sys_data_dir (GLADE_SUFFIX);
}

char *
gnumeric_sys_plugin_dir (void)
{
	return gnumeric_sys_lib_dir (PLUGIN_SUFFIX);
}
393 394 395 396

char *
gnumeric_usr_dir (const char *subdir)
{
Morten Welinder's avatar
Morten Welinder committed
397
	const char *home_dir = g_get_home_dir ();
Miguel de Icaza's avatar
Miguel de Icaza committed
398

Morten Welinder's avatar
Morten Welinder committed
399 400 401 402 403 404 405
	if (home_dir != NULL) {
		gboolean has_slash = (home_dir[strlen (home_dir) - 1] == G_DIR_SEPARATOR);
		return g_strconcat (home_dir, (has_slash ? "" : G_DIR_SEPARATOR_S),
				    ".gnumeric" G_DIR_SEPARATOR_S GNUMERIC_VERSION G_DIR_SEPARATOR_S,
				    subdir, G_DIR_SEPARATOR_S,
				    NULL);
	}
406 407 408
	return NULL;
}

Miguel de Icaza's avatar
Miguel de Icaza committed
409 410 411 412 413
char *
gnumeric_usr_plugin_dir (void)
{
	return gnumeric_usr_dir (PLUGIN_SUFFIX);
}
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519

/* ------------------------------------------------------------------------- */
/*
 * Note: the code below might look awful, but fixed-sized memcpy ought to
 * produce reasonable code.
 */

gint16
gnumeric_get_le_int16 (const void *p)
{
	gint16 data;
	memcpy (&data, p, sizeof (data));
	return GINT16_FROM_LE (data);
}

guint16
gnumeric_get_le_uint16 (const void *p)
{
	guint16 data;
	memcpy (&data, p, sizeof (data));
	return GUINT16_FROM_LE (data);
}

gint32
gnumeric_get_le_int32 (const void *p)
{
	gint32 data;
	memcpy (&data, p, sizeof (data));
	return GINT32_FROM_LE (data);
}

guint32
gnumeric_get_le_uint32 (const void *p)
{
	guint32 data;
	memcpy (&data, p, sizeof (data));
	return GUINT32_FROM_LE (data);
}

double
gnumeric_get_le_double (const void *p)
{
#if G_BYTE_ORDER == G_BIG_ENDIAN
	if (sizeof (double) == 8) {
		double  d;
		int     i;
		guint8 *t  = (guint8 *)&d;
		guint8 *p2 = (guint8 *)p;
		int     sd = sizeof (d);

		for (i = 0; i < sd; i++)
			t[i] = p2[sd - 1 - i];

		return d;
	} else {
		g_error ("Big endian machine, but weird size of doubles");
	}
#elif G_BYTE_ORDER == G_LITTLE_ENDIAN
	if (sizeof (double) == 8) {
		/*
		 * On i86, we could access directly, but Alphas require
		 * aligned access.
		 */
		double data;
		memcpy (&data, p, sizeof (data));
		return data;
	} else {
		g_error ("Little endian machine, but weird size of doubles");
	}
#else
#error "Byte order not recognised -- out of luck"
#endif
}


void
gnumeric_set_le_double (void *p, double d)
{
#if G_BYTE_ORDER == G_BIG_ENDIAN
	if (sizeof (double) == 8) {
		int     i;
		guint8 *t  = (guint8 *)&d;
		guint8 *p2 = (guint8 *)p;
		int     sd = sizeof (d);

		for (i = 0; i < sd; i++)
			p2[sd - 1 - i] = t[i];
	} else {
		g_error ("Big endian machine, but weird size of doubles");
	}
#elif G_BYTE_ORDER == G_LITTLE_ENDIAN
	if (sizeof (double) == 8) {
		/*
		 * On i86, we could access directly, but Alphas require
		 * aligned access.
		 */
		memcpy (p, &d, sizeof (d));
	} else {
		g_error ("Little endian machine, but weird size of doubles");
	}
#else
#error "Byte order not recognised -- out of luck"
#endif
}

/* ------------------------------------------------------------------------- */
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

/*
 * Escapes all backslashes and quotes in a string. It is based on glib's
 * g_strescape.
 *
 * Also adds quotes around the result.
 */
char *
gnumeric_strescape (const char *string)
{
	char *q, *escaped;
	int escapechars = 0;
	const char *p;

	g_return_val_if_fail (string != NULL, NULL);

	for (p = string; *p; p++)
		if (*p == '\\' || *p == '\"')
			escapechars++;

	q = escaped = g_new (char, strlen (string) + escapechars + 3);
	*q++ = '\"';
	for (p = string; *p; p++) {
		if (*p == '\\' || *p == '\"')
			*q++ = '\\';
		*q++ = *p;
	}
	*q++ = '\"';
	*q = '\000';

	return escaped;
}

/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
554

Morten Welinder's avatar
Morten Welinder committed
555
#ifdef NEED_FAKE_MODFGNUM
Morten Welinder's avatar
Morten Welinder committed
556
gnum_float
Morten Welinder's avatar
Morten Welinder committed
557
modfgnum (gnum_float x, gnum_float *iptr)
Morten Welinder's avatar
Morten Welinder committed
558 559
{
	double di;
Morten Welinder's avatar
Morten Welinder committed
560
	static gboolean warned = FALSE;
Morten Welinder's avatar
Morten Welinder committed
561

Morten Welinder's avatar
Morten Welinder committed
562 563 564 565 566 567 568
	if (!warned) {
		warned = TRUE;
		g_warning (_("This version of Gnumeric has been compiled with inadequate precision in modfgnum."));
	}

	/* Throw away the fractional part.  Hope the integer part fits.  */
	(void)modf (x, &di);
Morten Welinder's avatar
Morten Welinder committed
569
	*iptr = di;
Morten Welinder's avatar
Morten Welinder committed
570 571 572 573 574 575 576 577

	return x - di;
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_STRTOGNUM
Morten Welinder's avatar
Morten Welinder committed
578 579 580 581
gnum_float
strtognum (const char *str, char **end)
{
#if defined(HAVE_STRING_TO_DECIMAL) && defined(HAVE_DECIMAL_TO_QUADRUPLE)
Morten Welinder's avatar
Morten Welinder committed
582
	gnum_float res;
Morten Welinder's avatar
Morten Welinder committed
583 584 585 586 587 588
	decimal_record dr;
	enum decimal_string_form form;
	decimal_mode dm;
	fp_exception_field_type excp;
	char *echar;

Morten Welinder's avatar
Morten Welinder committed
589 590
	string_to_decimal ((char **)&str, INT_MAX, 0,
			   &dr, &form, &echar);
Morten Welinder's avatar
Morten Welinder committed
591 592 593 594 595 596 597 598 599
	if (end) *end = (char *)str;

	if (form == invalid_form) {
		errno = EINVAL;
		return 0.0;
	}

	dm.rd = fp_nearest;
	decimal_to_quadruple (&res, &dm, &dr, &excp);
Morten Welinder's avatar
Morten Welinder committed
600 601 602
        if (excp & ((1 << fp_overflow) | (1 << fp_underflow)))
                errno = ERANGE;
	return res;
Morten Welinder's avatar
Morten Welinder committed
603
#else
Morten Welinder's avatar
Morten Welinder committed
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
	char *myend;
	gnum_float res;
	int count;

	if (end == 0) end = &myend;
	(void) strtod (str, end);
	if (str == *end)
		return 0;

	errno = 0;
	count = sscanf (str, "%Lf", &res);
	if (count == 1)
		return res;

	/* Now what?  */
	*end = (char *)str;
	errno = ERANGE;
	return 0.0;
Morten Welinder's avatar
Morten Welinder committed
622 623 624 625 626
#endif
}
#endif

/* ------------------------------------------------------------------------- */
Morten Welinder's avatar
Morten Welinder committed
627 628 629 630 631

#ifdef NEED_FAKE_LDEXPGNUM
gnum_float
ldexpgnum (gnum_float x, int exp)
{
632
	if (!finitegnum (x) || x == 0)
Morten Welinder's avatar
Morten Welinder committed
633 634 635
		return x;
	else {
		gnum_float res = x * gpow2 (exp);
636
		if (finitegnum (res))
Morten Welinder's avatar
Morten Welinder committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
			return res;
		else {
			errno = ERANGE;
			return (x > 0) ? HUGE_VAL : -HUGE_VAL;
		}			
	}	
}
#endif

/* ------------------------------------------------------------------------- */

#ifdef NEED_FAKE_FREXPGNUM
gnum_float
frexpgnum (gnum_float x, int *exp)
{
	static gboolean warned = FALSE;
	double dbl_res;
	gnum_float res;

	if (!warned) {
		warned = TRUE;
		g_warning (_("This version of Gnumeric has been compiled with inadequate precision in frexpgnum."));
	}

	/* This might underflow or overflow in the cast.  */
	dbl_res = frexp ((double)x, exp);
663
	if (!finitegnum (x) || x == 0)
Morten Welinder's avatar
Morten Welinder committed
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
		return dbl_res;

	/*
	 * Now correct the result and adjust things that might have gotten
	 * off-by-one due to rounding.  This part has all the precision it
	 * needs.
	 */
	res = x / gpow2 (*exp);
	if (gnumabs (res) >= 1.0)
		res /= 2, (*exp)++;
	else if (gnumabs (res) < 0.5)
		res *= 2, (*exp)--;

	return res;
}
#endif

/* ------------------------------------------------------------------------- */