glade-utils.c 45.4 KB
Newer Older
Chema Celorio's avatar
Chema Celorio committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Copyright (C) 2001 Ximian, Inc.
 *
 * 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
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chema Celorio's avatar
Chema Celorio committed
18 19 20 21
 *
 * Authors:
 *   Chema Celorio <chema@celorio.com>
 */
22
 
23
#include <config.h>
24

25 26 27 28 29 30 31 32
/**
 * SECTION:glade-utils
 * @Title: Glade Utils
 * @Short_Description: Welcome to the zoo.
 *
 * This is where all of that really usefull miscalanious stuff lands up.
 */

33
#include "glade.h"
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
34 35 36
#include "glade-project.h"
#include "glade-command.h"
#include "glade-debug.h"
37
#include "glade-placeholder.h"
38
#include "glade-widget.h"
39
#include "glade-widget-adaptor.h"
40 41
#include "glade-property.h"
#include "glade-property-class.h"
42
#include "glade-clipboard.h"
Tristan Van Berkom's avatar
Tristan Van Berkom committed
43
#include "glade-fixed.h"
Chema Celorio's avatar
Chema Celorio committed
44

45 46 47 48 49 50 51 52
#include <string.h>
#include <gtk/gtktooltips.h>
#include <gdk/gdkkeysyms.h>
#include <gmodule.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <errno.h>

Tristan Van Berkom's avatar
Tristan Van Berkom committed
53
#ifdef G_OS_WIN32
54 55 56
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
Tristan Van Berkom's avatar
Tristan Van Berkom committed
57 58
#endif

Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
59
#define GLADE_UTIL_SELECTION_NODE_SIZE 7
60
#define GLADE_UTIL_COPY_BUFFSIZE       1024
Chema Celorio's avatar
Chema Celorio committed
61

Tristan Van Berkom's avatar
Tristan Van Berkom committed
62 63 64
#define GLADE_DEVHELP_ICON_NAME           "devhelp"
#define GLADE_DEVHELP_FALLBACK_ICON_FILE  "devhelp.png"

65 66 67 68
/* List of widgets that have selection
 */
static GList *glade_util_selection = NULL;

Tristan Van Berkom's avatar
Tristan Van Berkom committed
69
static GtkTooltips *glade_tooltips = NULL;
70

71 72 73 74 75 76 77
/**
 * glade_util_widget_set_tooltip:
 * @widget: a #GtkWidget
 * @str: a string
 *
 * Creates a new tooltip from @str and sets @widget to use it.
 */
Archit Baweja's avatar
Archit Baweja committed
78 79 80
void
glade_util_widget_set_tooltip (GtkWidget *widget, const gchar *str)
{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
81 82 83
	g_return_if_fail (widget != NULL);
	if (str == NULL)
		return;
Archit Baweja's avatar
Archit Baweja committed
84

Tristan Van Berkom's avatar
Tristan Van Berkom committed
85 86 87
	if (glade_tooltips == NULL)
	{
		glade_tooltips = gtk_tooltips_new ();
88
	
Tristan Van Berkom's avatar
Tristan Van Berkom committed
89 90 91 92 93
		g_object_ref (G_OBJECT (glade_tooltips));
		gtk_object_sink (GTK_OBJECT (glade_tooltips));	
	}

	gtk_tooltips_set_tip (glade_tooltips, widget, str, NULL);
Archit Baweja's avatar
Archit Baweja committed
94
}
95

96 97 98 99 100 101 102 103
/**
 * glade_util_compose_get_type_func:
 * @name:
 *
 * TODO: write me
 *
 * Returns:
 */
104 105
static gchar *
glade_util_compose_get_type_func (const gchar *name)
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
{
	gchar *retval;
	GString *tmp;
	gint i = 1, j;

	tmp = g_string_new (name);

	while (tmp->str[i])
	{
		if (g_ascii_isupper (tmp->str[i]))
		{
			tmp = g_string_insert_c (tmp, i++, '_');

			j = 0;
			while (g_ascii_isupper (tmp->str[i++]))
				j++;

			if (j > 2)
				g_string_insert_c (tmp, i-2, '_');

			continue;
		}
		i++;
	}

	tmp = g_string_append (tmp, "_get_type");
        retval = g_ascii_strdown (tmp->str, tmp->len);
	g_string_free (tmp, TRUE);

	return retval;
}

138 139
/**
 * glade_util_get_type_from_name:
140 141
 * @name: the name of the #GType - like 'GtkWidget' or a "get-type" function.
 * @have_func: function-name flag -- true if the name is a "get-type" function.
142
 *
143 144 145
 * Returns the type using the "get type" function name based on @name.  
 * If the @have_func flag is true,@name is used directly, otherwise the get-type 
 * function is contrived from @name then used.
146
 *
147
 * Returns: the new #GType
148
 */
149
GType
150
glade_util_get_type_from_name (const gchar *name, gboolean have_func)
151
{
152
	static GModule *allsymbols = NULL;
153
	GType (*get_type) ();
154
	GType type = 0;
155
	gchar  *func_name = (gchar*)name;
156 157
	
	if ((type = g_type_from_name (name)) == 0 &&
158
	    (have_func || (func_name = glade_util_compose_get_type_func (name)) != NULL))
159 160 161 162
	{
		
		if (!allsymbols)
			allsymbols = g_module_open (NULL, 0);
163

164 165 166 167 168
		if (g_module_symbol (allsymbols, func_name,
				      (gpointer) &get_type))
		{
			g_assert (get_type);
			type = get_type ();
169 170 171
		}
		else
		{
172 173 174 175
			g_warning (_("We could not find the symbol \"%s\""),
				   func_name);
		}
		g_free (func_name);
176 177
	}

178 179
	if (type == 0)
		g_warning(_("Could not get the type from \"%s\""), name);
180
	
181 182 183 184 185
	return type;
}

/**
 * glade_utils_get_pspec_from_funcname:
186
 * @funcname: the symbol name of a function to generate a #GParamSpec
187
 *
188 189
 * Returns: A #GParamSpec created by the delagate function
 *          specified by @funcname
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
 */
GParamSpec *
glade_utils_get_pspec_from_funcname (const gchar *funcname)
{
	static GModule *allsymbols     = NULL;
	GParamSpec     *pspec          = NULL;
	GParamSpec     *(*get_pspec)() = NULL;
	
	if (!allsymbols)
		allsymbols = g_module_open (NULL, 0);

	if (!g_module_symbol (allsymbols, funcname,
			      (gpointer) &get_pspec)) {
		g_warning (_("We could not find the symbol \"%s\""),
			   funcname);
205 206 207
		return FALSE;
	}

208 209 210 211
	g_assert (get_pspec);
	pspec = get_pspec ();

	return pspec;
212 213
}

214
/**
215
 * glade_util_ui_message:
216
 * @parent: a #GtkWindow cast as a #GtkWidget
217 218 219
 * @format: a printf style format string
 * @type:   a #GladeUIMessageType
 * @...:    args for the format.
220 221
 *
 * Creates a new warning dialog window as a child of @parent containing
222 223 224 225 226 227
 * the text of @format, runs it, then destroys it on close. Depending
 * on @type, a cancel button may apear or the icon may change.
 *
 * Returns: True if the @type was GLADE_UI_ARE_YOU_SURE and the user
 *          selected "OK", True if the @type was GLADE_UI_YES_OR_NO and
 *          the user selected "YES"; False otherwise.
228
 */
229 230 231 232 233
gboolean
glade_util_ui_message (GtkWidget           *parent, 
		       GladeUIMessageType   type,
		       const gchar         *format,
		       ...)
234
{
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 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
	GtkWidget      *dialog;
	GtkMessageType  message_type = GTK_MESSAGE_INFO;
	GtkButtonsType  buttons_type = GTK_BUTTONS_OK;
	va_list         args;
	gchar          *string;
	gint            response;

	va_start (args, format);
	string = g_strdup_vprintf (format, args);
	va_end (args);

	/* Get message_type */
	switch (type)
	{
	case GLADE_UI_INFO: message_type = GTK_MESSAGE_INFO; break;
	case GLADE_UI_WARN:
	case GLADE_UI_ARE_YOU_SURE:
		message_type = GTK_MESSAGE_WARNING;
		break;
	case GLADE_UI_ERROR:      message_type = GTK_MESSAGE_ERROR;    break;
	case GLADE_UI_YES_OR_NO:  message_type = GTK_MESSAGE_QUESTION; break;
		break;
	default: 
		g_critical ("Bad arg for glade_util_ui_message");
		break;
	}


	/* Get buttons_type */
	switch (type)
	{
	case GLADE_UI_INFO:
	case GLADE_UI_WARN:
	case GLADE_UI_ERROR:
		buttons_type = GTK_BUTTONS_OK;
		break;
	case GLADE_UI_ARE_YOU_SURE: buttons_type = GTK_BUTTONS_OK_CANCEL; break;
	case GLADE_UI_YES_OR_NO:    buttons_type = GTK_BUTTONS_YES_NO; break;
		break;
	default: 
		g_critical ("Bad arg for glade_util_ui_message");
		break;
	}
278

279
	dialog = gtk_message_dialog_new (GTK_WINDOW (parent),
280
					 GTK_DIALOG_DESTROY_WITH_PARENT,
281 282 283 284 285
					 message_type,
					 buttons_type,
					 string);

	response = gtk_dialog_run (GTK_DIALOG (dialog));
286 287

	gtk_widget_destroy (dialog);
288 289 290
	g_free (string);

	return (response == GTK_RESPONSE_OK || response == GTK_RESPONSE_YES);
291
}
292

293 294 295 296




297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
typedef struct {
	GtkStatusbar *statusbar;
	guint context_id;
	guint message_id;
} FlashInfo;

static const guint32 flash_length = 3000;

static gboolean
remove_message_timeout (FlashInfo * fi) 
{
	gtk_statusbar_remove (fi->statusbar, fi->context_id, fi->message_id);
	g_free (fi);

	/* remove the timeout */
  	return FALSE;
}

/**
 * glade_utils_flash_message:
317
 * @statusbar: The statusbar
318 319 320 321
 * @context_id: The message context_id
 * @format: The message to flash on the statusbar
 *
 * Flash a temporary message on the statusbar.
322
 */
323
void
324
glade_util_flash_message (GtkWidget *statusbar, guint context_id, gchar *format, ...)
325 326 327 328 329
{
	va_list args;
	FlashInfo *fi;
	gchar *message;

330 331
	g_return_if_fail (GTK_IS_STATUSBAR (statusbar));
	g_return_if_fail (format != NULL);
332 333 334 335 336 337

	va_start (args, format);
	message = g_strdup_vprintf (format, args);
	va_end (args);

	fi = g_new (FlashInfo, 1);
338
	fi->statusbar = GTK_STATUSBAR (statusbar);
339 340 341 342 343 344 345 346
	fi->context_id = context_id;	
	fi->message_id = gtk_statusbar_push (fi->statusbar, fi->context_id, message);

	gtk_timeout_add (flash_length, (GtkFunction) remove_message_timeout, fi);

	g_free (message);
}

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
static gint
glade_util_compare_uline_labels (const gchar *labela, const gchar *labelb)
{
	for (;;) {
		gunichar c1, c2;

		if (*labela == '\0')
			return (*labelb == '\0') ? 0 : -1;
		if (*labelb == '\0')
			return 1;

		c1 = g_utf8_get_char (labela);
		if (c1 == '_') {
			labela = g_utf8_next_char (labela);
			c1 = g_utf8_get_char (labela);
		}

		c2 = g_utf8_get_char (labelb);
		if (c2 == '_') {
			labelb = g_utf8_next_char (labelb);
			c2 = g_utf8_get_char (labelb);
		}

		if (c1 < c2)
			return -1;
		if (c1 > c2)
			return 1;

		labela = g_utf8_next_char (labela);
		labelb = g_utf8_next_char (labelb);
	}

	/* Shouldn't be reached. */
	return 0;
}

383 384 385 386 387 388 389 390 391 392 393
/**
 * glade_util_compare_stock_labels:
 * @a: a #gconstpointer to a #GtkStockItem
 * @b: a #gconstpointer to a #GtkStockItem
 *
 * This is a #GCompareFunc that compares the labels of two stock items, 
 * ignoring any '_' characters. It isn't particularly efficient.
 *
 * Returns: negative value if @a < @b; zero if @a = @b; 
 *          positive value if @a > @b
 */
394 395 396 397 398 399 400 401 402 403 404
gint
glade_util_compare_stock_labels (gconstpointer a, gconstpointer b)
{
	const gchar *stock_ida = a, *stock_idb = b;
	GtkStockItem itema, itemb;
	gboolean founda, foundb;
	gint retval;

	founda = gtk_stock_lookup (stock_ida, &itema);
	foundb = gtk_stock_lookup (stock_idb, &itemb);

405 406
	if (founda)
	{
407 408 409 410 411 412
		if (!foundb)
			retval = -1;
		else
			/* FIXME: Not ideal for UTF-8. */
			retval = glade_util_compare_uline_labels (itema.label, itemb.label);
	}
413 414
	else
	{
415 416 417 418 419 420 421 422 423
		if (!foundb)
			retval = 0;
		else
			retval = 1;
	}

	return retval;
}

424 425 426 427 428 429 430 431
/**
 * glade_util_gtk_combo_func:
 * @data:
 *
 * TODO: write me
 *
 * Returns:
 */
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
gchar *
glade_util_gtk_combo_func (gpointer data)
{
	GtkListItem * listitem = data;

	/* I needed to pinch this as well - Damon. */
	static const gchar *gtk_combo_string_key = "gtk-combo-string-value";

	GtkWidget *label;
	gchar *ltext = NULL;

	ltext = (gchar *) gtk_object_get_data (GTK_OBJECT (listitem),
					       gtk_combo_string_key);
	if (!ltext) {
		label = GTK_BIN (listitem)->child;
		if (!label || !GTK_IS_LABEL (label))
			return NULL;
		ltext = (gchar*) gtk_label_get_text (GTK_LABEL (label));
	}

	return ltext;
}

/* These are pinched from gtkcombo.c */
456 457 458 459 460 461 462 463
/**
 * glade_util_gtk_combo_find:
 * @combo:
 *
 * TODO: write me
 *
 * Returns:
 */
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
gpointer /* GtkListItem *  */
glade_util_gtk_combo_find (GtkCombo * combo)
{
	gchar *text;
	gchar *ltext;
	GList *clist;
	int (*string_compare) (const char *, const char *);

	if (combo->case_sensitive)
		string_compare = strcmp;
	else
		string_compare = g_strcasecmp;

	text = (gchar*) gtk_entry_get_text (GTK_ENTRY (combo->entry));
	clist = GTK_LIST (combo->list)->children;

	while (clist && clist->data) {
		ltext = glade_util_gtk_combo_func (GTK_LIST_ITEM (clist->data));
		if (!ltext)
			continue;
		if (!(*string_compare) (ltext, text))
			return (GtkListItem *) clist->data;
		clist = clist->next;
	}

	return NULL;
}

492 493
/**
 * glade_util_hide_window:
494
 * @window: a #GtkWindow
495 496 497 498
 *
 * If you use this function to handle the delete_event of a window, when it
 * will be shown again it will appear in the position where it was before
 * beeing hidden.
499
 */
500 501
void
glade_util_hide_window (GtkWindow *window)
502 503 504
{
	gint x, y;

505
	g_return_if_fail (GTK_IS_WINDOW (window));
506

507 508
	/* remember position of window for when it is used again */
	gtk_window_get_position (window, &x, &y);
509

510
	gtk_widget_hide (GTK_WIDGET (window));
511

512
	gtk_window_move(window, x, y);
513 514
}

515
/**
516
 * glade_util_file_dialog_new:
517
 * @title: dialog title
518
 * @parent: the parent #GtkWindow for the dialog
519
 * @action: a #GladeUtilFileDialogType to say if the dialog will open or save
520
 *
521
 * Returns: a "glade file" file chooser dialog. The caller is responsible 
522
 *          for showing the dialog
523
 */
524
GtkWidget *
525 526
glade_util_file_dialog_new (const gchar *title, GtkWindow *parent, 
			     GladeUtilFileDialogType action)
527
{
528
	GtkWidget *file_dialog;
529
	GtkFileFilter *file_filter;
530

531 532
	g_return_val_if_fail ((action == GLADE_FILE_DIALOG_ACTION_OPEN ||
			       action == GLADE_FILE_DIALOG_ACTION_SAVE), NULL);
533
	
534
	file_dialog = gtk_file_chooser_dialog_new (title, parent, action,
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
						   GTK_STOCK_CANCEL,
						   GTK_RESPONSE_CANCEL,
						   action == GLADE_FILE_DIALOG_ACTION_OPEN ?
						   GTK_STOCK_OPEN : GTK_STOCK_SAVE,
						   GTK_RESPONSE_OK,
						   NULL);
	
	file_filter = gtk_file_filter_new ();
	gtk_file_filter_add_pattern (file_filter, "*");
	gtk_file_filter_set_name (file_filter, _("All Files"));
	gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (file_dialog), file_filter);

	file_filter = gtk_file_filter_new ();
	gtk_file_filter_add_pattern (file_filter, "*.glade");
	gtk_file_filter_set_name (file_filter, _("Glade Files"));
	gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (file_dialog), file_filter);

	gtk_file_chooser_set_filter (GTK_FILE_CHOOSER (file_dialog), file_filter);

554
	gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (file_dialog), TRUE);
555
	gtk_dialog_set_default_response (GTK_DIALOG (file_dialog), GTK_RESPONSE_OK);
556

557 558
	return file_dialog;
}
559

560
/**
561 562
 * glade_util_replace:
 * @str: a string
563 564
 * @a: a #gchar
 * @b: a #gchar
565 566
 *
 * Replaces each occurance of the character @a in @str to @b.
567 568
 */
void
569
glade_util_replace (gchar *str, gchar a, gchar b)
570 571 572
{
	g_return_if_fail (str != NULL);

573 574
	while (*str != 0)
	{
575 576 577 578 579 580
		if (*str == a)
			*str = b;

		str = g_utf8_next_char (str);
	}
}
581

Tristan Van Berkom's avatar
Tristan Van Berkom committed
582 583 584 585 586 587 588 589 590 591
/**
 * glade_util_read_prop_name:
 * @str: a string
 *
 * Return a usable version of a property identifier as found
 * in a freshly parserd #GladeInterface
 */
gchar *
glade_util_read_prop_name (const gchar *str)
{
592 593 594 595 596
	gchar *id;

	g_return_val_if_fail (str != NULL, NULL);

	id = g_strdup (str);
Tristan Van Berkom's avatar
Tristan Van Berkom committed
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

	glade_util_replace (id, '_', '-');

	if (strstr (id, "::"))
	{
		/* Extract the second half of "AtkObject::accessible_name"
		 */
		gchar **split = g_strsplit (id, "::", 0);
		g_free (id);
		id = g_strdup (split[1]);
		g_strfreev (split);
	}
	return id;
}


613
/**
614 615 616 617 618 619 620
 * glade_util_duplicate_underscores:
 * @name: a string
 *
 * Duplicates @name, but the copy has two underscores in place of any single
 * underscore in the original.
 *
 * Returns: a newly allocated string
621
 */
Tristan Van Berkom's avatar
Tristan Van Berkom committed
622 623
gchar *
glade_util_duplicate_underscores (const gchar *name)
624
{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
625 626 627 628
	const gchar *tmp;
	const gchar *last_tmp = name;
	gchar *underscored_name = g_malloc (strlen (name) * 2 + 1);
	gchar *tmp_underscored = underscored_name;
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

	for (tmp = last_tmp; *tmp; tmp = g_utf8_next_char (tmp))
	{
		if (*tmp == '_')
		{
			memcpy (tmp_underscored, last_tmp, tmp - last_tmp + 1);
			tmp_underscored += tmp - last_tmp + 1;
			last_tmp = tmp + 1;
			*tmp_underscored++ = '_';
		}
	}

	memcpy (tmp_underscored, last_tmp, tmp - last_tmp + 1);

	return underscored_name;
}
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
645

646 647 648 649
/* This returns the window that the given widget's position is relative to.
   Usually this is the widget's parent's window. But if the widget is a
   toplevel, we use its own window, as it doesn't have a parent.
   Some widgets also lay out widgets in different ways. */
650
static GdkWindow*
651
glade_util_get_window_positioned_in (GtkWidget *widget)
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
{
	GtkWidget *parent;

	parent = widget->parent;

#ifdef USE_GNOME
	/* BonoboDockItem widgets use a different window when floating.
	   FIXME: I've left this here so we remember to add it when we add
	   GNOME support. */
	if (BONOBO_IS_DOCK_ITEM (widget)
	    && BONOBO_DOCK_ITEM (widget)->is_floating) {
		return BONOBO_DOCK_ITEM (widget)->float_window;
	}

	if (parent && BONOBO_IS_DOCK_ITEM (parent)
	    && BONOBO_DOCK_ITEM (parent)->is_floating) {
		return BONOBO_DOCK_ITEM (parent)->float_window;
	}
#endif

	if (parent)
		return parent->window;

	return widget->window;
}

678
static void
679 680 681
glade_util_draw_nodes (GdkWindow *window, GdkGC *gc,
		       gint x, gint y,
		       gint width, gint height)
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
682 683 684 685
{
	if (width > GLADE_UTIL_SELECTION_NODE_SIZE && height > GLADE_UTIL_SELECTION_NODE_SIZE) {
		gdk_draw_rectangle (window, gc, TRUE,
				    x, y,
686 687
				    GLADE_UTIL_SELECTION_NODE_SIZE,
				    GLADE_UTIL_SELECTION_NODE_SIZE);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
688 689
		gdk_draw_rectangle (window, gc, TRUE,
				    x, y + height - GLADE_UTIL_SELECTION_NODE_SIZE,
690 691
				    GLADE_UTIL_SELECTION_NODE_SIZE,
				    GLADE_UTIL_SELECTION_NODE_SIZE);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
692 693
		gdk_draw_rectangle (window, gc, TRUE,
				    x + width - GLADE_UTIL_SELECTION_NODE_SIZE, y,
694 695
				    GLADE_UTIL_SELECTION_NODE_SIZE,
				    GLADE_UTIL_SELECTION_NODE_SIZE);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
696 697 698
		gdk_draw_rectangle (window, gc, TRUE,
				    x + width - GLADE_UTIL_SELECTION_NODE_SIZE,
				    y + height - GLADE_UTIL_SELECTION_NODE_SIZE,
699 700
				    GLADE_UTIL_SELECTION_NODE_SIZE,
				    GLADE_UTIL_SELECTION_NODE_SIZE);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
701 702 703
	}

	gdk_draw_rectangle (window, gc, FALSE, x, y, width - 1, height - 1);
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
}

/* This calculates the offset of the given window within its toplevel.
   It also returns the toplevel. */
static void
glade_util_calculate_window_offset (GdkWindow *window,
				    gint *x, gint *y,
				    GdkWindow **toplevel)
{
	gint tmp_x, tmp_y;

	/* Calculate the offset of the window within its toplevel. */
	*x = 0;
	*y = 0;

	for (;;) {
		if (gdk_window_get_window_type (window) != GDK_WINDOW_CHILD)
			break;
		gdk_window_get_position (window, &tmp_x, &tmp_y);
		*x += tmp_x;
		*y += tmp_y;
		window = gdk_window_get_parent (window);
	}

	*toplevel = window;
}

/* This returns TRUE if it is OK to draw the selection nodes for the given
   selected widget inside the given window that has received an expose event.
   For most widgets it returns TRUE, but if a selected widget is inside a
   widget like a viewport, that uses its own coordinate system, then it only
   returns TRUE if the expose window is inside the viewport as well. */
static gboolean
glade_util_can_draw_nodes (GtkWidget *sel_widget, GdkWindow *sel_win,
			   GdkWindow *expose_win)
{
	GtkWidget *widget, *viewport = NULL;
	GdkWindow *viewport_win = NULL;

	/* Check if the selected widget is inside a viewport. */
	for (widget = sel_widget->parent; widget; widget = widget->parent) {
		if (GTK_IS_VIEWPORT (widget)) {
			viewport = widget;
			viewport_win = GTK_VIEWPORT (widget)->bin_window;
			break;
		}
	}

	/* If there is no viewport-type widget above the selected widget,
	   it is OK to draw the selection anywhere. */
	if (!viewport)
		return TRUE;

	/* If we have a viewport-type widget, check if the expose_win is
	   beneath the viewport. If it is, we can draw in it. If not, we
	   can't.*/
	for (;;) {
		if (expose_win == sel_win)
			return TRUE;
		if (expose_win == viewport_win)
			return FALSE;
		if (gdk_window_get_window_type (expose_win) != GDK_WINDOW_CHILD)
			break;
		expose_win = gdk_window_get_parent (expose_win);
	}

	return FALSE;
}

773
/**
774
 * glade_util_draw_selection_nodes:
775 776 777 778 779 780 781
 * @expose_win: a #GdkWindow
 *
 * Redraws any selection nodes that intersect @expose_win. Steps through all
 * selected widgets, finds their coordinates, and calls glade_util_draw_nodes()
 * if appropriate.
 *
 */
782 783
void
glade_util_draw_selection_nodes (GdkWindow *expose_win)
784 785 786 787
{
	GtkWidget *expose_widget;
	gint expose_win_x, expose_win_y;
	gint expose_win_w, expose_win_h;
788
	GdkWindow   *expose_toplevel;
789 790 791
	GdkGC *gc;
	GList *elem;

792
	g_return_if_fail (GDK_IS_WINDOW (expose_win));
793

794
	/* Find the corresponding GtkWidget */
795
	gdk_window_get_user_data (expose_win, (gpointer)&expose_widget);
796

797 798 799 800 801 802 803 804 805 806 807
	gc = expose_widget->style->black_gc;

	/* Calculate the offset of the expose window within its toplevel. */
	glade_util_calculate_window_offset (expose_win,
					    &expose_win_x,
					    &expose_win_y,
					    &expose_toplevel);

	gdk_drawable_get_size (expose_win,
			       &expose_win_w, &expose_win_h);

808 809 810
	/* Step through all the selected widgets. */
	for (elem = glade_util_selection; elem; elem = elem->next) {

811 812 813 814 815
		GtkWidget *sel_widget;
		GdkWindow *sel_win, *sel_toplevel;
		gint sel_x, sel_y, x, y, w, h;

		sel_widget = elem->data;
816 817 818 819
		
		if ((sel_win = glade_util_get_window_positioned_in (sel_widget)) == NULL)
			continue;
		
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
		/* Calculate the offset of the selected widget's window
		   within its toplevel. */
		glade_util_calculate_window_offset (sel_win, &sel_x, &sel_y,
						    &sel_toplevel);

		/* We only draw the nodes if the window that got the expose
		   event is in the same toplevel as the selected widget. */
		if (expose_toplevel == sel_toplevel
		    && glade_util_can_draw_nodes (sel_widget, sel_win,
						  expose_win)) {
			x = sel_x + sel_widget->allocation.x - expose_win_x;
			y = sel_y + sel_widget->allocation.y - expose_win_y;
			w = sel_widget->allocation.width;
			h = sel_widget->allocation.height;

			/* Draw the selection nodes if they intersect the
			   expose window bounds. */
			if (x < expose_win_w && x + w >= 0
			    && y < expose_win_h && y + h >= 0) {
				glade_util_draw_nodes (expose_win, gc,
						       x, y, w, h);
			}
		}
	}
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
844 845
}

846
/**
847
 * glade_util_add_selection:
848 849
 * @widget: a #GtkWidget
 *
850
 * Add visual selection to this GtkWidget
851
 */
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
852
void
853
glade_util_add_selection (GtkWidget *widget)
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
854
{
855 856 857 858 859 860
	g_return_if_fail (GTK_IS_WIDGET (widget));
	if (glade_util_has_selection (widget))
		return;

	glade_util_selection = 
		g_list_prepend (glade_util_selection, widget);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
861 862 863
	gtk_widget_queue_draw (widget);
}

864
/**
865
 * glade_util_remove_selection:
866 867
 * @widget: a #GtkWidget
 *
868
 * Remove visual selection from this GtkWidget
869
 */
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
870
void
871
glade_util_remove_selection (GtkWidget *widget)
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
872
{
873 874 875 876 877 878
	g_return_if_fail (GTK_IS_WIDGET (widget));
	if (!glade_util_has_selection (widget))
		return;

	glade_util_selection = 
		g_list_remove (glade_util_selection, widget);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
879

880 881
	/* We redraw the parent, since the selection rectangle may not be
	   cleared if we just redraw the widget itself. */
882 883
	gtk_widget_queue_draw (widget->parent ?
			       widget->parent : widget);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
884 885
}

886
/**
887
 * glade_util_clear_selection:
888
 *
889
 * Clear all visual selections
890
 */
891 892
void
glade_util_clear_selection (void)
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
893
{
894 895 896 897 898 899 900 901 902 903 904 905 906
	GtkWidget *widget;
	GList     *list;

	for (list = glade_util_selection;
	     list && list->data;
	     list = list->next)
	{
		widget = list->data;
		gtk_widget_queue_draw (widget->parent ?
				       widget->parent : widget);
	}
	glade_util_selection =
		(g_list_free (glade_util_selection), NULL);
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
907 908
}

909
/**
910
 * glade_util_has_selection:
911
 * @widget: a #GtkWidget
912
 *
913
 * Returns: %TRUE if @widget has visual selection, %FALSE otherwise
914
 */
915 916
gboolean
glade_util_has_selection (GtkWidget *widget)
Joaquín Cuenca Abela's avatar
Joaquín Cuenca Abela committed
917
{
918 919
	g_return_val_if_fail (GTK_IS_WIDGET (widget), FALSE);
	return g_list_find (glade_util_selection, widget) != NULL;
920 921
}

922
/**
923
 * glade_util_get_selectoin:
924
 *
925
 * Returns: The list of selected #GtkWidgets
926
 */
927 928
GList *
glade_util_get_selection ()
929
{
930
	return glade_util_selection;
931 932
}

933 934 935 936 937 938 939 940 941 942 943 944 945 946
/*
 * taken from gtk... maybe someday we can convince them to
 * expose gtk_container_get_all_children
 */
static void
gtk_container_children_callback (GtkWidget *widget,
				 gpointer client_data)
{
	GList **children;

	children = (GList**) client_data;
	*children = g_list_prepend (*children, widget);
}

947 948 949 950
/**
 * glade_util_container_get_all_children:
 * @container: a #GtkContainer
 *
951 952 953 954 955 956 957
 * Use this to itterate over all children in a GtkContainer,
 * as it used _forall() instead of _foreach() (and the GTK+ version
 * of this function is simply not exposed).
 *
 * Note that glade_widget_class_get_children() is the high-level
 * abstraction and will usually end up calling this function.
 *
958 959
 * Returns: a #GList giving the contents of @container
 */
960 961 962 963 964 965 966
GList *
glade_util_container_get_all_children (GtkContainer *container)
{
	GList *children = NULL;

	g_return_val_if_fail (GTK_IS_CONTAINER (container), NULL);

967 968 969
	gtk_container_forall (container,
			      gtk_container_children_callback,
			      &children);
970

971
	/* Preserve the natural order by reversing the list */
972 973
	return g_list_reverse (children);
}
974

975
/**
976
 * glade_util_count_placeholders:
977 978 979 980 981 982 983 984 985 986 987
 * @parent: a #GladeWidget
 *
 * Returns the amount of #GladePlaceholders parented by @parent
 */
gint
glade_util_count_placeholders (GladeWidget *parent)
{
	gint placeholders = 0;
	GList *list, *children;

	/* count placeholders */
988 989
	if ((children = glade_widget_adaptor_get_children
	     (parent->adaptor, parent->object)) != NULL)
990 991 992 993 994 995 996 997
	{
		for (list = children; list && list->data; list = list->next)
		{
			if (GLADE_IS_PLACEHOLDER (list->data))
				placeholders++;
		}
		g_list_free (children);
	}
998

999 1000
	return placeholders;
}
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071

static GtkTreeIter *
glade_util_find_iter (GtkTreeModel *model,
		      GtkTreeIter  *iter,
		      GladeWidget  *findme,
		      gint          column)
{
	GtkTreeIter *retval = NULL;
	GladeWidget *widget;
	GtkTreeIter *next;

	g_return_val_if_fail (GTK_IS_TREE_MODEL (model), NULL);
	g_return_val_if_fail (iter != NULL, NULL);

	next = gtk_tree_iter_copy (iter);
	g_return_val_if_fail (next != NULL, NULL);

	while (retval == NULL)
	{
		gtk_tree_model_get (model, next, column, &widget, -1);
		if (widget == NULL) {
			g_warning ("Could not get the glade widget from the model");
			break;
		}
		else if (widget == findme)
		{
			retval = gtk_tree_iter_copy (next);
			break;
		}
		else if (gtk_tree_model_iter_has_child (model, next))
		{
			GtkTreeIter  child;
			gtk_tree_model_iter_children (model, &child, next);
			if ((retval = glade_util_find_iter
			     (model, &child, findme, column)) != NULL)
				break;
		}

		if (!gtk_tree_model_iter_next (model, next))
			break;
	}
	gtk_tree_iter_free (next);

	return retval;
}

/**
 * glade_util_find_iter_by_widget:
 * @model: a #GtkTreeModel
 * @findme: a #GladeWidget
 * @column: a #gint
 *
 * Looks through @model for the #GtkTreeIter corresponding to 
 * @findme under @column.
 *
 * Returns: a newly allocated #GtkTreeIter from @model corresponding
 * to @findme which should be freed with gtk_tree_iter_free()
 * 
 */
GtkTreeIter *
glade_util_find_iter_by_widget (GtkTreeModel *model,
				GladeWidget  *findme,
				gint          column)
{
	GtkTreeIter iter;
	if (gtk_tree_model_get_iter_first (model, &iter))
	{
		return glade_util_find_iter (model, &iter, findme, column);
	}
	return NULL;
}
1072

1073
gboolean
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
glade_util_basenames_match  (const gchar  *path1,
			     const gchar  *path2)
{
	gboolean match = FALSE;
	gchar *bname1;
	gchar *bname2;
	
	if (path1 && path2)
	{
		bname1 = g_path_get_basename (path1);
		bname2 = g_path_get_basename (path2);
1085

1086 1087 1088 1089 1090 1091 1092
		match = !strcmp (bname1, bname2);
		
		g_free (bname1);
		g_free (bname2);
	}
	return match;
}
1093 1094 1095 1096 1097

/**
 * glade_util_purify_list:
 * @list: A #GList
 *
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1098 1099
 * Returns: A newly allocated version of @list with no 
 *          duplicate data entries
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
 */
GList *
glade_util_purify_list (GList *list)
{
	GList *l, *newlist = NULL;

	for (l = list; l; l = l->next)
		if (!g_list_find (newlist, l->data))
			newlist = g_list_prepend (newlist, l->data);

	g_list_free (list);

	return g_list_reverse (newlist);
}
1114

Tristan Van Berkom's avatar
Tristan Van Berkom committed
1115 1116
/**
 * glade_util_added_in_list:
1117 1118
 * @old_list: the old #GList
 * @new_list: the new #GList
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1119 1120 1121 1122 1123 1124
 *
 * Returns: A newly allocated #GList of elements that
 *          are in @new but not in @old
 *
 */
GList *
1125 1126
glade_util_added_in_list (GList *old_list,
			  GList *new_list)
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1127 1128 1129
{
	GList *added = NULL, *list;

1130
	for (list = new_list; list; list = list->next)
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1131
	{
1132
		if (!g_list_find (old_list, list->data))
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1133 1134 1135 1136 1137 1138 1139 1140
			added = g_list_prepend (added, list->data);
	} 

	return g_list_reverse (added);
}

/**
 * glade_util_removed_from_list:
1141 1142
 * @old_list: the old #GList
 * @new_list: the new #GList
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1143 1144 1145 1146 1147 1148
 *
 * Returns: A newly allocated #GList of elements that
 *          are in @old no longer in @new
 *
 */
GList *
1149 1150
glade_util_removed_from_list (GList *old_list,
			      GList *new_list)
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1151 1152 1153
{
	GList *added = NULL, *list;

1154
	for (list = old_list; list; list = list->next)
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1155
	{
1156
		if (!g_list_find (new_list, list->data))
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1157 1158 1159 1160 1161 1162 1163
			added = g_list_prepend (added, list->data);
	} 

	return g_list_reverse (added);
}


1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
/**
 * glade_util_canonical_path:
 * @path: any path that may contain ".." or "." components
 *
 * Returns: an absolute path to the specified file or directory
 *          that contains no ".." or "." components (this does
 *          not call readlink like realpath() does).
 *
 * Note: on some systems; I think its possible that we dont have
 *       permission to execute in the directory in which the glade
 *       file resides; I decided finally to do it this way anyway
 *       since libc's realpath() does exactly the same.
 */
gchar *
glade_util_canonical_path (const gchar *path)
{
	gchar *orig_dir, *dirname, *basename, *direct_dir, *direct_name = NULL;

1182 1183
	g_return_val_if_fail (path != NULL, NULL);

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
	basename = g_path_get_basename (path);

	if ((orig_dir = g_get_current_dir ()) != NULL)
	{
		if ((dirname = g_path_get_dirname (path)) != NULL)
		{
			if (g_chdir (dirname) == 0)
			{
				if ((direct_dir = g_get_current_dir ()) != NULL)
					direct_name = 
						g_build_filename (direct_dir, basename, NULL);
				else
					g_warning ("g_path");

				if (g_chdir (orig_dir) != 0)
					g_warning ("Unable to chdir back to %s directory (%s)",
						   orig_dir, g_strerror (errno));

			} else g_warning ("Unable to chdir to %s directory (%s)", 
					  dirname, g_strerror (errno));

			g_free (dirname);
		} else g_warning ("Unable to get directory component of %s\n", path);
		g_free (orig_dir);
	}

	if (basename) g_free (basename);

	return direct_name;
}
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

static gboolean
glade_util_canonical_match (const gchar  *src_path,
			    const gchar  *dest_path)
{
	gchar      *canonical_src, *canonical_dest;
	gboolean    match;
	canonical_src  = glade_util_canonical_path (src_path);
	canonical_dest = glade_util_canonical_path (dest_path);

	match = (strcmp (canonical_src, canonical_dest) == 0);

	g_free (canonical_src);
	g_free (canonical_dest);
	
	return match;
}

/**
 * glade_util_copy_file:
 * @src_path:  the path to the source file
 * @dest_path: the path to the destination file to create or overwrite.
 *
 * Copies a file from @src to @dest, queries the user
 * if it involves overwriting the target and displays an
 * error message upon failure.
 *
 * Returns: True if the copy was successfull.
 */
gboolean
glade_util_copy_file (const gchar  *src_path,
		      const gchar  *dest_path)
{
	GIOChannel *src, *dest;
	GError     *error = NULL;
1249
	GIOStatus   read_status, write_status = G_IO_STATUS_ERROR;
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
	gchar       buffer[GLADE_UTIL_COPY_BUFFSIZE];
	gsize       bytes_read, bytes_written, written;
	gboolean    success = FALSE;

	/* FIXME: This may break if src_path & dest_path are actually 
	 * the same file, right now the canonical comparison is the
	 * best check I have.
	 */
	if (glade_util_canonical_match (src_path, dest_path))
		return FALSE;

1261
	if (g_file_test (dest_path, G_FILE_TEST_IS_REGULAR) != FALSE)
1262
		if (glade_util_ui_message
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1263
		    (glade_app_get_window(), GLADE_UI_YES_OR_NO,
1264
		     _("%s exists.\nDo you want to replace it?"), dest_path) == FALSE)
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
		    return FALSE;


	if ((src = g_io_channel_new_file (src_path, "r", &error)) != NULL)
	{
		g_io_channel_set_encoding (src, NULL, NULL);

		if ((dest = g_io_channel_new_file (dest_path, "w", &error)) != NULL)
		{
			g_io_channel_set_encoding (dest, NULL, NULL);

			while ((read_status = g_io_channel_read_chars 
				(src, buffer, GLADE_UTIL_COPY_BUFFSIZE,
				 &bytes_read, &error)) != G_IO_STATUS_ERROR)
			{
				bytes_written = 0;
				while ((write_status = g_io_channel_write_chars 
					(dest, buffer + bytes_written, 
					 bytes_read - bytes_written, 
					 &written, &error)) != G_IO_STATUS_ERROR &&
1285
				       (bytes_written + written) < bytes_read)
1286 1287 1288 1289
					bytes_written += written;
				
				if (write_status == G_IO_STATUS_ERROR)
				{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1290
					glade_util_ui_message (glade_app_get_window(),
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
							       GLADE_UI_ERROR,
							       _("Error writing to %s: %s"),
							       dest_path, error->message);
					error = (g_error_free (error), NULL);
					break;
				}

				/* Break on EOF & ERROR but not AGAIN and not NORMAL */
				if (read_status == G_IO_STATUS_EOF) break;
			}
			
			if (read_status == G_IO_STATUS_ERROR)
			{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1304
				glade_util_ui_message (glade_app_get_window(),
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
						       GLADE_UI_ERROR,
						       _("Error reading %s: %s"),
						       src_path, error->message);
				error = (g_error_free (error), NULL);
			}


			/* From here on, unless we have problems shutting down, succuss ! */
			success = (read_status == G_IO_STATUS_EOF && 
				   write_status == G_IO_STATUS_NORMAL);

			if (g_io_channel_shutdown (dest, TRUE, &error) != G_IO_STATUS_NORMAL)
			{
				glade_util_ui_message
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1319
					(glade_app_get_window(),
1320
					 GLADE_UI_ERROR,
1321
					 _("Error shutting down I/O channel %s: %s"),
1322 1323 1324 1325 1326 1327 1328
						       dest_path, error->message);
				error = (g_error_free (error), NULL);
				success = FALSE;
			}
		}
		else
		{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1329
			glade_util_ui_message (glade_app_get_window(),
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
					       GLADE_UI_ERROR,
					       _("Failed to open %s for writing: %s"), 
					       dest_path, error->message);
			error = (g_error_free (error), NULL);

		}


		if (g_io_channel_shutdown (src, TRUE, &error) != G_IO_STATUS_NORMAL)
		{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1340
			glade_util_ui_message (glade_app_get_window(),
1341 1342 1343 1344 1345 1346 1347 1348
					       GLADE_UI_ERROR,
					       _("Error shutting down io channel %s: %s"),
					       src_path, error->message);
			success = FALSE;
		}
	}
	else 
	{
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1349
		glade_util_ui_message (glade_app_get_window(),
1350 1351 1352 1353 1354 1355 1356
				       GLADE_UI_ERROR,
				       _("Failed to open %s for reading: %s"), 
				       src_path, error->message);
		error = (g_error_free (error), NULL);
	}
	return success;
}
1357

Tristan Van Berkom's avatar
Tristan Van Berkom committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
/**
 * glade_util_class_implements_interface:
 * @class_type: A #GType
 * @iface_type: A #GType
 *
 * Returns: whether @class_type implements the @iface_type interface
 */
gboolean
glade_util_class_implements_interface (GType class_type, 
				       GType iface_type)
{
	GType    *ifaces;
	guint     n_ifaces, i;
	gboolean  implemented = FALSE;

	if ((ifaces = g_type_interfaces (class_type, &n_ifaces)) != NULL)
	{
		for (i = 0; i < n_ifaces; i++)
			if (ifaces[i] == iface_type)
			{
				implemented = TRUE;
				break;
			}
		g_free (ifaces);
	}
	return implemented;
}

1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
static GModule *
try_load_library (const gchar *library_path,
		  const gchar *library_name)
{
	GModule *module;
	gchar   *path;

	path = g_module_build_path (library_path, library_name);
	module = g_module_open (path, G_MODULE_BIND_LAZY);
	g_free (path);

	return module;
}

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
/**
 * glade_util_load_library:
 * @library_name: name of the library
 *
 * Loads the named library from the Glade modules directory, or failing that
 * from the standard platform specific directories.
 *
 * The @library_name should not include any platform specifix prefix or suffix,
 * those are automatically added, if needed, by g_module_build_path()
 *
 * Returns: a #GModule on success, or %NULL on failure.
 */
GModule *
glade_util_load_library (const gchar *library_name)
{
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
	GModule      *module = NULL;
	const gchar  *default_paths[] = { glade_app_get_modules_dir (), "/lib", "/usr/lib", "/usr/local/lib", NULL };
	const gchar  *search_path;
	gchar       **split;
	gint          i;
	
	if ((search_path = g_getenv (GLADE_ENV_MODULE_PATH)) != NULL)
	{
		if ((split = g_strsplit (search_path, ":", 0)) != NULL)
		{
			for (i = 0; split[i] != NULL; i++)
				if ((module = try_load_library (split[i], library_name)) != NULL)
					break;
1429

1430 1431 1432
			g_strfreev (split);
		}
	}
1433

1434
	if (!module)
1435
	{
1436 1437 1438
		for (i = 0; default_paths[i] != NULL; i++)
			if ((module = try_load_library (default_paths[i], library_name)) != NULL)
				break;
1439 1440
	}

1441 1442 1443
	if (!module)
		g_critical ("Unable to load module '%s' from any search paths", library_name);
	
1444 1445
	return module;
}
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457

/**
 * glade_util_file_is_writeable:
 * @path:  the path to the file
 *
 * Checks whether the file at @path is writeable
 *
 * Returns: TRUE if file is writeable
 */
gboolean
glade_util_file_is_writeable (const gchar *path)
{
1458 1459
	GIOChannel *channel;
	g_return_val_if_fail (path != NULL, FALSE);
1460

1461
	/* The only way to really know if the file is writable */
1462
	if ((channel = g_io_channel_new_file (path, "a+", NULL)) != NULL)
1463 1464 1465 1466 1467
	{
		g_io_channel_unref (channel);
		return TRUE;
	}
	return FALSE;
1468
}
1469 1470

/**
1471
 * glade_util_have_devhelp:
1472
 *
1473
 * Returns: whether the devhelp module is loaded
1474
 */
1475 1476
gboolean
glade_util_have_devhelp (void)
1477
{
1478 1479 1480 1481
	static gint  have_devhelp = -1;
	gchar       *ptr;
	gint         cnt, ret, major, minor;
	GError      *error = NULL;
1482

1483 1484 1485 1486 1487 1488 1489
#define DEVHELP_OLD_MESSAGE  \
    "The DevHelp installed on your system is too old, " \
    "devhelp feature will be disabled."

#define DEVHELP_MISSING_MESSAGE  \
    "No DevHelp installed on your system, " \
    "devhelp feature will be disabled."
1490

1491 1492 1493 1494 1495
	if (have_devhelp >= 0) return have_devhelp;
	
	have_devhelp = 0;

	if ((ptr = g_find_program_in_path ("devhelp")) != NULL)
1496
	{
1497
		g_free (ptr);
1498

1499 1500
		if (g_spawn_command_line_sync ("devhelp --version", 
					       &ptr, NULL, &ret, &error))
1501
		{
1502 1503 1504
			/* If we have a successfull return code.. parse the output.
			 */
			if (ret == 0)
1505
			{
1506 1507 1508
				gchar name[16];
				if ((cnt = sscanf (ptr, "%15s %d.%d\n", 
						   name, &major, &minor)) == 3)
1509
				{
1510 1511 1512 1513 1514 1515 1516 1517
					/* Devhelp 0.12 required.
					 */
					if (major >= 0 && minor >= 12)
						have_devhelp = 1;
					else	
						g_message (DEVHELP_OLD_MESSAGE);
				}
				else
1518
					
1519 1520
				{
					if (ptr != NULL || strlen (ptr) > 0)
1521 1522 1523 1524
						g_warning ("devhelp had unparsable output: "
							   "'%s' (parsed %d elements)", ptr, cnt);
					else
						g_message (DEVHELP_OLD_MESSAGE);
1525
				}
1526
			}
1527 1528 1529 1530 1531 1532 1533 1534
			else g_warning ("devhelp had bad return code: '%d'", ret);
		}
		else
		{
			g_warning ("Error trying to launch devhelp: %s",
				   error->message);
			g_error_free (error);
		}
1535
	}
1536 1537
	else g_message (DEVHELP_MISSING_MESSAGE);
	
1538
	return have_devhelp;
1539 1540
}

Tristan Van Berkom's avatar
Tristan Van Berkom committed
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
/**
 * glade_util_get_devhelp_icon:
 * @size: the preferred icon size
 *
 * Creates an image displaying the devhelp icon.
 *
 * Returns: a #GtkImage
 */
GtkWidget*
glade_util_get_devhelp_icon (GtkIconSize size)
{
	GtkIconTheme *icon_theme;
	GdkScreen *screen;
	GtkWidget *image;
	gchar *path;

	image = gtk_image_new ();
	screen = gtk_widget_get_screen (GTK_WIDGET (image));
	icon_theme = gtk_icon_theme_get_for_screen (screen);

	if (gtk_icon_theme_has_icon (icon_theme, GLADE_DEVHELP_ICON_NAME))
	{
		gtk_image_set_from_icon_name (GTK_IMAGE (image), GLADE_DEVHELP_ICON_NAME, size);
	}
	else
	{
1567
		path = g_build_filename (glade_app_get_pixmaps_dir (), GLADE_DEVHELP_FALLBACK_ICON_FILE, NULL);
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1568 1569 1570 1571 1572 1573 1574 1575 1576

		gtk_image_set_from_file (GTK_IMAGE (image), path);

		g_free (path);
	}

	return image;
}

1577 1578
/**
 * glade_util_search_devhep:
1579
 * @devhelp: the devhelp widget created by the devhelp module.
1580 1581 1582 1583
 * @book: the devhelp book (or %NULL)
 * @page: the page in the book (or %NULL)
 * @search: the search string (or %NULL)
 *
1584
 * Envokes devhelp with the appropriate search string
1585 1586 1587
 *
 */
void
1588
glade_util_search_devhelp (const gchar *book,
1589 1590 1591
			   const gchar *page,
			   const gchar *search)
{
1592 1593 1594
	GError *error = NULL;
	gchar  *book_comm = NULL, *page_comm = NULL;
	gchar  *string;
1595 1596

	g_return_if_fail (glade_util_have_devhelp ());
1597 1598 1599 1600

	if (book) book_comm = g_strdup_printf ("book:%s ", book);
	if (page) page_comm = g_strdup_printf ("page:%s ", page);

1601
	string = g_strdup_printf ("devhelp -s \"%s%s%s\"", 
1602 1603 1604 1605
				   book_comm ? book_comm : "",
				   page_comm ? page_comm : "",
				   search ? search : "");

1606 1607 1608 1609 1610
	if (g_spawn_command_line_async (string, &error) == FALSE)
	{
		g_warning ("Error envoking devhelp: %s", error->message);
		g_error_free (error);
	}
1611

1612
	g_free (string);
1613 1614 1615
	if (book_comm) g_free (book_comm);
	if (page_comm) g_free (page_comm);
}
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1616

1617 1618 1619
GtkWidget *
glade_util_get_placeholder_from_pointer (GtkContainer *container)
{
1620
	GtkWidget *toplevel;
1621 1622
	GtkWidget *retval = NULL, *child;
	GList *c, *l;
1623
	gint x, y, x2, y2;
1624 1625

	g_return_val_if_fail (GTK_IS_CONTAINER (container), NULL);
1626

1627 1628 1629
	toplevel = gtk_widget_get_toplevel (GTK_WIDGET (container));

	gtk_widget_get_pointer (toplevel, &x, &y);
1630 1631 1632 1633 1634 1635 1636
	
	for (c = l = glade_util_container_get_all_children (container);
	     l;
	     l = g_list_next (l))
	{
		child = l->data;
		
1637 1638
		if (GLADE_IS_PLACEHOLDER (child) &&
		    GTK_WIDGET_MAPPED (child))
1639
		{
1640
			gtk_widget_translate_coordinates (toplevel, child,
1641 1642
							  x, y, &x2, &y2);

1643
			
1644 1645 1646
			if (x2 >= 0 && y2 >= 0 &&
			    x2 <= child->allocation.width &&
			    y2 <= child->allocation.height)
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
			{
				retval = child;
				break;
			}
		}
	}
	
	g_list_free (c);

	return retval;
}
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680

/**
 * glade_util_object_is_loading:
 * @object: A #GObject
 *
 * Returns: Whether the object's project is being loaded or not.
 *       
 */
gboolean
glade_util_object_is_loading (GObject *object)
{
	GladeProject *project;
	GladeWidget *widget;

	g_return_val_if_fail (G_IS_OBJECT (object), FALSE);
	
	widget = glade_widget_get_from_gobject (object);
	g_return_val_if_fail (GLADE_IS_WIDGET (widget), FALSE);
	
	project = glade_widget_get_project (widget);
	
	return glade_project_is_loading (project);
}
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1681 1682 1683 1684 1685 1686

#ifdef G_OS_WIN32

static gboolean
glade_util_url_show_win32 (const gchar *url)
{
1687 1688 1689
	HINSTANCE h;
	
	h = ShellExecuteA (NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1690
	
1691
	if ((int)h <= 32)
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
		return FALSE;

	return TRUE;
}

#else

/* pilfered from Beast - birnetutils.cc */
static gboolean
glade_util_url_show_unix (const gchar *url)
{
	static struct {
	const gchar   *prg, *arg1, *prefix, *postfix;
	gboolean       asyncronous; /* start asyncronously and check exit code to catch launch errors */
	volatile gboolean disabled;
	} browsers[] = {

	/* configurable, working browser launchers */
	{ "gnome-open",             NULL,           "", "", 0 }, /* opens in background, correct exit_code */
	{ "exo-open",               NULL,           "", "", 0 }, /* opens in background, correct exit_code */

	/* non-configurable working browser launchers */
	{ "kfmclient",              "openURL",      "", "", 0 }, /* opens in background, correct exit_code */
	{ "gnome-moz-remote",       "--newwin",     "", "", 0 }, /* opens in background, correct exit_code */

#if 0   /* broken/unpredictable browser launchers */
	{ "browser-config",         NULL,            "", "", 0 }, /* opens in background (+ sleep 5), broken exit_code (always 0) */
	{ "xdg-open",               NULL,            "", "", 0 }, /* opens in foreground (first browser) or background, correct exit_code */
	{ "sensible-browser",       NULL,            "", "", 0 }, /* opens in foreground (first browser) or background, correct exit_code */
	{ "htmlview",               NULL,            "", "", 0 }, /* opens in foreground (first browser) or background, correct exit_code */
#endif

	/* direct browser invocation */
	{ "x-www-browser",          NULL,           "", "", 1 }, /* opens in foreground, browser alias */
	{ "firefox",                NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "mozilla-firefox",        NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "mozilla",                NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "konqueror",              NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "opera",                  "-newwindow",   "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "epiphany",               NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */	
	{ "galeon",                 NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "amaya",                  NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */
	{ "dillo",                  NULL,           "", "", 1 }, /* opens in foreground, correct exit_code */

	};
  
	guint i;
	for (i = 0; i < G_N_ELEMENTS (browsers); i++)

		if (!browsers[i].disabled)
		{
		        gchar *args[128] = { 0, };
		        guint n = 0;
1745 1746 1747 1748
		        gchar *string;
		        gchar fallback_error[64] = "Ok";
		        gboolean success;

Tristan Van Berkom's avatar
Tristan Van Berkom committed
1749 1750 1751 1752 1753
		        args[n++] = (gchar*) browsers[i].prg;
		        
		        if (browsers[i].arg1)
		        	args[n++] = (gchar*) browsers[i].arg1;
		        
1754
		        string = g_strconcat (browsers[i].prefix, url, browsers[i].postfix, NULL);
Tristan Van Berkom's avatar
Tristan Van Berkom committed
1755 1756