]> Pileus Git - ~andy/gtk/blob - gtk/gtkiconfactory.c
Silence new gcc warnings
[~andy/gtk] / gtk / gtkiconfactory.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 2000 Red Hat, Inc.
3  *               2008 Johan Dahlin
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 #include "config.h"
28
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <string.h>
32
33 #include "gtkiconfactory.h"
34 #include "gtkiconcache.h"
35 #include "gtkdebug.h"
36 #include "gtkicontheme.h"
37 #include "gtksettingsprivate.h"
38 #include "gtkstock.h"
39 #include "gtkwidget.h"
40 #include "gtkintl.h"
41 #include "gtkbuildable.h"
42 #include "gtkbuilderprivate.h"
43 #include "gtktypebuiltins.h"
44
45 static GSList *all_icon_factories = NULL;
46
47 struct _GtkIconFactoryPrivate
48 {
49   GHashTable *icons;
50 };
51
52 typedef enum {
53   GTK_ICON_SOURCE_EMPTY,
54   GTK_ICON_SOURCE_ICON_NAME,
55   GTK_ICON_SOURCE_STATIC_ICON_NAME,
56   GTK_ICON_SOURCE_FILENAME,
57   GTK_ICON_SOURCE_PIXBUF
58 } GtkIconSourceType;
59
60 struct _GtkIconSource
61 {
62   GtkIconSourceType type;
63
64   union {
65     gchar *icon_name;
66     gchar *filename;
67     GdkPixbuf *pixbuf;
68   } source;
69
70   GdkPixbuf *filename_pixbuf;
71
72   GtkTextDirection direction;
73   GtkStateType state;
74   GtkIconSize size;
75
76   /* If TRUE, then the parameter is wildcarded, and the above
77    * fields should be ignored. If FALSE, the parameter is
78    * specified, and the above fields should be valid.
79    */
80   guint any_direction : 1;
81   guint any_state : 1;
82   guint any_size : 1;
83 };
84
85
86 static void
87 gtk_icon_factory_buildable_init  (GtkBuildableIface      *iface);
88
89 static gboolean gtk_icon_factory_buildable_custom_tag_start (GtkBuildable     *buildable,
90                                                              GtkBuilder       *builder,
91                                                              GObject          *child,
92                                                              const gchar      *tagname,
93                                                              GMarkupParser    *parser,
94                                                              gpointer         *data);
95 static void gtk_icon_factory_buildable_custom_tag_end (GtkBuildable *buildable,
96                                                        GtkBuilder   *builder,
97                                                        GObject      *child,
98                                                        const gchar  *tagname,
99                                                        gpointer     *user_data);
100 static void gtk_icon_factory_finalize   (GObject             *object);
101 static void get_default_icons           (GtkIconFactory      *icon_factory);
102 static void icon_source_clear           (GtkIconSource       *source);
103
104 static GtkIconSize icon_size_register_intern (const gchar *name,
105                                               gint         width,
106                                               gint         height);
107
108 #define GTK_ICON_SOURCE_INIT(any_direction, any_state, any_size)        \
109   { GTK_ICON_SOURCE_EMPTY, { NULL }, NULL,                              \
110    0, 0, 0,                                                             \
111    any_direction, any_state, any_size }
112
113 G_DEFINE_TYPE_WITH_CODE (GtkIconFactory, gtk_icon_factory, G_TYPE_OBJECT,
114                          G_IMPLEMENT_INTERFACE (GTK_TYPE_BUILDABLE,
115                                                 gtk_icon_factory_buildable_init))
116
117 static void
118 gtk_icon_factory_init (GtkIconFactory *factory)
119 {
120   GtkIconFactoryPrivate *priv;
121
122   factory->priv = G_TYPE_INSTANCE_GET_PRIVATE (factory,
123                                                GTK_TYPE_ICON_FACTORY,
124                                                GtkIconFactoryPrivate);
125   priv = factory->priv;
126
127   priv->icons = g_hash_table_new (g_str_hash, g_str_equal);
128   all_icon_factories = g_slist_prepend (all_icon_factories, factory);
129 }
130
131 static void
132 gtk_icon_factory_class_init (GtkIconFactoryClass *klass)
133 {
134   GObjectClass *object_class = G_OBJECT_CLASS (klass);
135
136   object_class->finalize = gtk_icon_factory_finalize;
137
138   g_type_class_add_private (klass, sizeof (GtkIconFactoryPrivate));
139 }
140
141 static void
142 gtk_icon_factory_buildable_init (GtkBuildableIface *iface)
143 {
144   iface->custom_tag_start = gtk_icon_factory_buildable_custom_tag_start;
145   iface->custom_tag_end = gtk_icon_factory_buildable_custom_tag_end;
146 }
147
148 static void
149 free_icon_set (gpointer key, gpointer value, gpointer data)
150 {
151   g_free (key);
152   gtk_icon_set_unref (value);
153 }
154
155 static void
156 gtk_icon_factory_finalize (GObject *object)
157 {
158   GtkIconFactory *factory = GTK_ICON_FACTORY (object);
159   GtkIconFactoryPrivate *priv = factory->priv;
160
161   all_icon_factories = g_slist_remove (all_icon_factories, factory);
162
163   g_hash_table_foreach (priv->icons, free_icon_set, NULL);
164
165   g_hash_table_destroy (priv->icons);
166
167   G_OBJECT_CLASS (gtk_icon_factory_parent_class)->finalize (object);
168 }
169
170 /**
171  * gtk_icon_factory_new:
172  *
173  * Creates a new #GtkIconFactory. An icon factory manages a collection
174  * of #GtkIconSet<!-- -->s; a #GtkIconSet manages a set of variants of a
175  * particular icon (i.e. a #GtkIconSet contains variants for different
176  * sizes and widget states). Icons in an icon factory are named by a
177  * stock ID, which is a simple string identifying the icon. Each
178  * #GtkStyle has a list of #GtkIconFactory<!-- -->s derived from the current
179  * theme; those icon factories are consulted first when searching for
180  * an icon. If the theme doesn't set a particular icon, GTK+ looks for
181  * the icon in a list of default icon factories, maintained by
182  * gtk_icon_factory_add_default() and
183  * gtk_icon_factory_remove_default(). Applications with icons should
184  * add a default icon factory with their icons, which will allow
185  * themes to override the icons for the application.
186  *
187  * Return value: a new #GtkIconFactory
188  */
189 GtkIconFactory*
190 gtk_icon_factory_new (void)
191 {
192   return g_object_new (GTK_TYPE_ICON_FACTORY, NULL);
193 }
194
195 /**
196  * gtk_icon_factory_add:
197  * @factory: a #GtkIconFactory
198  * @stock_id: icon name
199  * @icon_set: icon set
200  *
201  * Adds the given @icon_set to the icon factory, under the name
202  * @stock_id.  @stock_id should be namespaced for your application,
203  * e.g. "myapp-whatever-icon".  Normally applications create a
204  * #GtkIconFactory, then add it to the list of default factories with
205  * gtk_icon_factory_add_default(). Then they pass the @stock_id to
206  * widgets such as #GtkImage to display the icon. Themes can provide
207  * an icon with the same name (such as "myapp-whatever-icon") to
208  * override your application's default icons. If an icon already
209  * existed in @factory for @stock_id, it is unreferenced and replaced
210  * with the new @icon_set.
211  */
212 void
213 gtk_icon_factory_add (GtkIconFactory *factory,
214                       const gchar    *stock_id,
215                       GtkIconSet     *icon_set)
216 {
217   GtkIconFactoryPrivate *priv = factory->priv;
218   gpointer old_key = NULL;
219   gpointer old_value = NULL;
220
221   g_return_if_fail (GTK_IS_ICON_FACTORY (factory));
222   g_return_if_fail (stock_id != NULL);
223   g_return_if_fail (icon_set != NULL);
224
225   g_hash_table_lookup_extended (priv->icons, stock_id,
226                                 &old_key, &old_value);
227
228   if (old_value == icon_set)
229     return;
230
231   gtk_icon_set_ref (icon_set);
232
233   /* GHashTable key memory management is so fantastically broken. */
234   if (old_key)
235     g_hash_table_insert (priv->icons, old_key, icon_set);
236   else
237     g_hash_table_insert (priv->icons, g_strdup (stock_id), icon_set);
238
239   if (old_value)
240     gtk_icon_set_unref (old_value);
241 }
242
243 /**
244  * gtk_icon_factory_lookup:
245  * @factory: a #GtkIconFactory
246  * @stock_id: an icon name
247  *
248  * Looks up @stock_id in the icon factory, returning an icon set
249  * if found, otherwise %NULL. For display to the user, you should
250  * use gtk_style_lookup_icon_set() on the #GtkStyle for the
251  * widget that will display the icon, instead of using this
252  * function directly, so that themes are taken into account.
253  *
254  * Return value: (transfer none): icon set of @stock_id.
255  */
256 GtkIconSet *
257 gtk_icon_factory_lookup (GtkIconFactory *factory,
258                          const gchar    *stock_id)
259 {
260   GtkIconFactoryPrivate *priv;
261
262   g_return_val_if_fail (GTK_IS_ICON_FACTORY (factory), NULL);
263   g_return_val_if_fail (stock_id != NULL, NULL);
264
265   priv = factory->priv;
266
267   return g_hash_table_lookup (priv->icons, stock_id);
268 }
269
270 static GtkIconFactory *gtk_default_icons = NULL;
271 static GSList *default_factories = NULL;
272
273 /**
274  * gtk_icon_factory_add_default:
275  * @factory: a #GtkIconFactory
276  *
277  * Adds an icon factory to the list of icon factories searched by
278  * gtk_style_lookup_icon_set(). This means that, for example,
279  * gtk_image_new_from_stock() will be able to find icons in @factory.
280  * There will normally be an icon factory added for each library or
281  * application that comes with icons. The default icon factories
282  * can be overridden by themes.
283  */
284 void
285 gtk_icon_factory_add_default (GtkIconFactory *factory)
286 {
287   g_return_if_fail (GTK_IS_ICON_FACTORY (factory));
288
289   g_object_ref (factory);
290
291   default_factories = g_slist_prepend (default_factories, factory);
292 }
293
294 /**
295  * gtk_icon_factory_remove_default:
296  * @factory: a #GtkIconFactory previously added with gtk_icon_factory_add_default()
297  *
298  * Removes an icon factory from the list of default icon
299  * factories. Not normally used; you might use it for a library that
300  * can be unloaded or shut down.
301  */
302 void
303 gtk_icon_factory_remove_default (GtkIconFactory  *factory)
304 {
305   g_return_if_fail (GTK_IS_ICON_FACTORY (factory));
306
307   default_factories = g_slist_remove (default_factories, factory);
308
309   g_object_unref (factory);
310 }
311
312 void
313 _gtk_icon_factory_ensure_default_icons (void)
314 {
315   if (gtk_default_icons == NULL)
316     {
317       gtk_default_icons = gtk_icon_factory_new ();
318
319       get_default_icons (gtk_default_icons);
320     }
321 }
322
323 /**
324  * gtk_icon_factory_lookup_default:
325  * @stock_id: an icon name
326  *
327  * Looks for an icon in the list of default icon factories.  For
328  * display to the user, you should use gtk_style_lookup_icon_set() on
329  * the #GtkStyle for the widget that will display the icon, instead of
330  * using this function directly, so that themes are taken into
331  * account.
332  *
333  * Return value: (transfer none): a #GtkIconSet, or %NULL
334  */
335 GtkIconSet *
336 gtk_icon_factory_lookup_default (const gchar *stock_id)
337 {
338   GSList *tmp_list;
339
340   g_return_val_if_fail (stock_id != NULL, NULL);
341
342   tmp_list = default_factories;
343   while (tmp_list != NULL)
344     {
345       GtkIconSet *icon_set =
346         gtk_icon_factory_lookup (GTK_ICON_FACTORY (tmp_list->data),
347                                  stock_id);
348
349       if (icon_set)
350         return icon_set;
351
352       tmp_list = g_slist_next (tmp_list);
353     }
354
355   _gtk_icon_factory_ensure_default_icons ();
356
357   return gtk_icon_factory_lookup (gtk_default_icons, stock_id);
358 }
359
360 static void
361 register_stock_icon (GtkIconFactory *factory,
362                      const gchar    *stock_id,
363                      const gchar    *icon_name)
364 {
365   GtkIconSet *set = gtk_icon_set_new ();
366   GtkIconSource source = GTK_ICON_SOURCE_INIT (TRUE, TRUE, TRUE);
367
368   source.type = GTK_ICON_SOURCE_STATIC_ICON_NAME;
369   source.source.icon_name = (gchar *)icon_name;
370   source.direction = GTK_TEXT_DIR_NONE;
371   gtk_icon_set_add_source (set, &source);
372
373   gtk_icon_factory_add (factory, stock_id, set);
374   gtk_icon_set_unref (set);
375 }
376
377 static void
378 register_bidi_stock_icon (GtkIconFactory *factory,
379                           const gchar    *stock_id,
380                           const gchar    *icon_name)
381 {
382   GtkIconSet *set = gtk_icon_set_new ();
383   GtkIconSource source = GTK_ICON_SOURCE_INIT (FALSE, TRUE, TRUE);
384
385   source.type = GTK_ICON_SOURCE_STATIC_ICON_NAME;
386   source.source.icon_name = (gchar *)icon_name;
387   source.direction = GTK_TEXT_DIR_LTR;
388   gtk_icon_set_add_source (set, &source);
389
390   source.type = GTK_ICON_SOURCE_STATIC_ICON_NAME;
391   source.source.icon_name = (gchar *)icon_name;
392   source.direction = GTK_TEXT_DIR_RTL;
393   gtk_icon_set_add_source (set, &source);
394
395   gtk_icon_factory_add (factory, stock_id, set);
396   gtk_icon_set_unref (set);
397 }
398
399 static void
400 get_default_icons (GtkIconFactory *factory)
401 {
402   /* KEEP IN SYNC with gtkstock.c */
403
404   register_stock_icon (factory, GTK_STOCK_DIALOG_AUTHENTICATION, "dialog-password");
405   register_stock_icon (factory, GTK_STOCK_DIALOG_ERROR, "dialog-error");
406   register_stock_icon (factory, GTK_STOCK_DIALOG_INFO, "dialog-information");
407   register_stock_icon (factory, GTK_STOCK_DIALOG_QUESTION, "dialog-question");
408   register_stock_icon (factory, GTK_STOCK_DIALOG_WARNING, "dialog-warning");
409   register_stock_icon (factory, GTK_STOCK_DND, GTK_STOCK_DND);
410   register_stock_icon (factory, GTK_STOCK_DND_MULTIPLE, GTK_STOCK_DND_MULTIPLE);
411   register_stock_icon (factory, GTK_STOCK_APPLY, GTK_STOCK_APPLY);
412   register_stock_icon (factory, GTK_STOCK_CANCEL, GTK_STOCK_CANCEL);
413   register_stock_icon (factory, GTK_STOCK_NO, GTK_STOCK_NO);
414   register_stock_icon (factory, GTK_STOCK_OK, GTK_STOCK_OK);
415   register_stock_icon (factory, GTK_STOCK_YES, GTK_STOCK_YES);
416   register_stock_icon (factory, GTK_STOCK_CLOSE, "window-close");
417   register_stock_icon (factory, GTK_STOCK_ADD, "list-add");
418   register_stock_icon (factory, GTK_STOCK_JUSTIFY_CENTER, "format-justify-center");
419   register_stock_icon (factory, GTK_STOCK_JUSTIFY_FILL, "format-justify-fill");
420   register_stock_icon (factory, GTK_STOCK_JUSTIFY_LEFT, "format-justify-left");
421   register_stock_icon (factory, GTK_STOCK_JUSTIFY_RIGHT, "format-justify-right");
422   register_stock_icon (factory, GTK_STOCK_GOTO_BOTTOM, "go-bottom");
423   register_stock_icon (factory, GTK_STOCK_CDROM, "media-optical");
424   register_stock_icon (factory, GTK_STOCK_CONVERT, GTK_STOCK_CONVERT);
425   register_stock_icon (factory, GTK_STOCK_COPY, "edit-copy");
426   register_stock_icon (factory, GTK_STOCK_CUT, "edit-cut");
427   register_stock_icon (factory, GTK_STOCK_GO_DOWN, "go-down");
428   register_stock_icon (factory, GTK_STOCK_EXECUTE, "system-run");
429   register_stock_icon (factory, GTK_STOCK_QUIT, "application-exit");
430   register_bidi_stock_icon (factory, GTK_STOCK_GOTO_FIRST, "go-first");
431   register_stock_icon (factory, GTK_STOCK_SELECT_FONT, GTK_STOCK_SELECT_FONT);
432   register_stock_icon (factory, GTK_STOCK_FULLSCREEN, "view-fullscreen");
433   register_stock_icon (factory, GTK_STOCK_LEAVE_FULLSCREEN, "view-restore");
434   register_stock_icon (factory, GTK_STOCK_HARDDISK, "drive-harddisk");
435   register_stock_icon (factory, GTK_STOCK_HELP, "help-contents");
436   register_stock_icon (factory, GTK_STOCK_HOME, "go-home");
437   register_stock_icon (factory, GTK_STOCK_INFO, "dialog-information");
438   register_bidi_stock_icon (factory, GTK_STOCK_JUMP_TO, "go-jump");
439   register_bidi_stock_icon (factory, GTK_STOCK_GOTO_LAST, "go-last");
440   register_bidi_stock_icon (factory, GTK_STOCK_GO_BACK, "go-previous");
441   register_stock_icon (factory, GTK_STOCK_MISSING_IMAGE, "image-missing");
442   register_stock_icon (factory, GTK_STOCK_NETWORK, "network-idle");
443   register_stock_icon (factory, GTK_STOCK_NEW, "document-new");
444   register_stock_icon (factory, GTK_STOCK_OPEN, "document-open");
445   register_stock_icon (factory, GTK_STOCK_ORIENTATION_PORTRAIT, GTK_STOCK_ORIENTATION_PORTRAIT);
446   register_stock_icon (factory, GTK_STOCK_ORIENTATION_LANDSCAPE, GTK_STOCK_ORIENTATION_LANDSCAPE);
447   register_stock_icon (factory, GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT, GTK_STOCK_ORIENTATION_REVERSE_PORTRAIT);
448   register_stock_icon (factory, GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE, GTK_STOCK_ORIENTATION_REVERSE_LANDSCAPE);
449   register_stock_icon (factory, GTK_STOCK_PAGE_SETUP, GTK_STOCK_PAGE_SETUP);
450   register_stock_icon (factory, GTK_STOCK_PASTE, "edit-paste");
451   register_stock_icon (factory, GTK_STOCK_PREFERENCES, GTK_STOCK_PREFERENCES);
452   register_stock_icon (factory, GTK_STOCK_PRINT, "document-print");
453   register_stock_icon (factory, GTK_STOCK_PRINT_ERROR, "printer-error");
454   register_stock_icon (factory, GTK_STOCK_PRINT_PAUSED, "printer-paused");
455   register_stock_icon (factory, GTK_STOCK_PRINT_PREVIEW, "document-print-preview");
456   register_stock_icon (factory, GTK_STOCK_PRINT_REPORT, "printer-info");
457   register_stock_icon (factory, GTK_STOCK_PRINT_WARNING, "printer-warning");
458   register_stock_icon (factory, GTK_STOCK_PROPERTIES, "document-properties");
459   register_bidi_stock_icon (factory, GTK_STOCK_REDO, "edit-redo");
460   register_stock_icon (factory, GTK_STOCK_REMOVE, "list-remove");
461   register_stock_icon (factory, GTK_STOCK_REFRESH, "view-refresh");
462   register_bidi_stock_icon (factory, GTK_STOCK_REVERT_TO_SAVED, "document-revert");
463   register_bidi_stock_icon (factory, GTK_STOCK_GO_FORWARD, "go-next");
464   register_stock_icon (factory, GTK_STOCK_SAVE, "document-save");
465   register_stock_icon (factory, GTK_STOCK_FLOPPY, "media-floppy");
466   register_stock_icon (factory, GTK_STOCK_SAVE_AS, "document-save-as");
467   register_stock_icon (factory, GTK_STOCK_FIND, "edit-find");
468   register_stock_icon (factory, GTK_STOCK_FIND_AND_REPLACE, "edit-find-replace");
469   register_stock_icon (factory, GTK_STOCK_SORT_DESCENDING, "view-sort-descending");
470   register_stock_icon (factory, GTK_STOCK_SORT_ASCENDING, "view-sort-ascending");
471   register_stock_icon (factory, GTK_STOCK_SPELL_CHECK, "tools-check-spelling");
472   register_stock_icon (factory, GTK_STOCK_STOP, "process-stop");
473   register_stock_icon (factory, GTK_STOCK_BOLD, "format-text-bold");
474   register_stock_icon (factory, GTK_STOCK_ITALIC, "format-text-italic");
475   register_stock_icon (factory, GTK_STOCK_STRIKETHROUGH, "format-text-strikethrough");
476   register_stock_icon (factory, GTK_STOCK_UNDERLINE, "format-text-underline");
477   register_bidi_stock_icon (factory, GTK_STOCK_INDENT, "format-indent-more");
478   register_bidi_stock_icon (factory, GTK_STOCK_UNINDENT, "format-indent-less");
479   register_stock_icon (factory, GTK_STOCK_GOTO_TOP, "go-top");
480   register_stock_icon (factory, GTK_STOCK_DELETE, "edit-delete");
481   register_bidi_stock_icon (factory, GTK_STOCK_UNDELETE, GTK_STOCK_UNDELETE);
482   register_bidi_stock_icon (factory, GTK_STOCK_UNDO, "edit-undo");
483   register_stock_icon (factory, GTK_STOCK_GO_UP, "go-up");
484   register_stock_icon (factory, GTK_STOCK_FILE, "document-x-generic");
485   register_stock_icon (factory, GTK_STOCK_DIRECTORY, "folder");
486   register_stock_icon (factory, GTK_STOCK_ABOUT, "help-about");
487   register_stock_icon (factory, GTK_STOCK_CONNECT, GTK_STOCK_CONNECT);
488   register_stock_icon (factory, GTK_STOCK_DISCONNECT, GTK_STOCK_DISCONNECT);
489   register_stock_icon (factory, GTK_STOCK_EDIT, GTK_STOCK_EDIT);
490   register_stock_icon (factory, GTK_STOCK_CAPS_LOCK_WARNING, GTK_STOCK_CAPS_LOCK_WARNING);
491   register_bidi_stock_icon (factory, GTK_STOCK_MEDIA_FORWARD, "media-seek-forward");
492   register_bidi_stock_icon (factory, GTK_STOCK_MEDIA_NEXT, "media-skip-forward");
493   register_stock_icon (factory, GTK_STOCK_MEDIA_PAUSE, "media-playback-pause");
494   register_bidi_stock_icon (factory, GTK_STOCK_MEDIA_PLAY, "media-playback-start");
495   register_bidi_stock_icon (factory, GTK_STOCK_MEDIA_PREVIOUS, "media-skip-backward");
496   register_stock_icon (factory, GTK_STOCK_MEDIA_RECORD, "media-record");
497   register_bidi_stock_icon (factory, GTK_STOCK_MEDIA_REWIND, "media-seek-backward");
498   register_stock_icon (factory, GTK_STOCK_MEDIA_STOP, "media-playback-stop");
499   register_stock_icon (factory, GTK_STOCK_INDEX, GTK_STOCK_INDEX);
500   register_stock_icon (factory, GTK_STOCK_ZOOM_100, "zoom-original");
501   register_stock_icon (factory, GTK_STOCK_ZOOM_IN, "zoom-in");
502   register_stock_icon (factory, GTK_STOCK_ZOOM_OUT, "zoom-out");
503   register_stock_icon (factory, GTK_STOCK_ZOOM_FIT, "zoom-fit-best");
504   register_stock_icon (factory, GTK_STOCK_SELECT_ALL, "edit-select-all");
505   register_stock_icon (factory, GTK_STOCK_CLEAR, "edit-clear");
506   register_stock_icon (factory, GTK_STOCK_SELECT_COLOR, GTK_STOCK_SELECT_COLOR);
507   register_stock_icon (factory, GTK_STOCK_COLOR_PICKER, GTK_STOCK_COLOR_PICKER);
508 }
509
510 /************************************************************
511  *                    Icon size handling                    *
512  ************************************************************/
513
514 typedef struct _IconSize IconSize;
515
516 struct _IconSize
517 {
518   gint size;
519   gchar *name;
520
521   gint width;
522   gint height;
523 };
524
525 typedef struct _IconAlias IconAlias;
526
527 struct _IconAlias
528 {
529   gchar *name;
530   gint   target;
531 };
532
533 typedef struct _SettingsIconSize SettingsIconSize;
534
535 struct _SettingsIconSize
536 {
537   gint width;
538   gint height;
539 };
540
541 static GHashTable *icon_aliases = NULL;
542 static IconSize *icon_sizes = NULL;
543 static gint      icon_sizes_allocated = 0;
544 static gint      icon_sizes_used = 0;
545
546 static void
547 init_icon_sizes (void)
548 {
549   if (icon_sizes == NULL)
550     {
551 #define NUM_BUILTIN_SIZES 7
552       gint i;
553
554       icon_aliases = g_hash_table_new (g_str_hash, g_str_equal);
555
556       icon_sizes = g_new (IconSize, NUM_BUILTIN_SIZES);
557       icon_sizes_allocated = NUM_BUILTIN_SIZES;
558       icon_sizes_used = NUM_BUILTIN_SIZES;
559
560       icon_sizes[GTK_ICON_SIZE_INVALID].size = 0;
561       icon_sizes[GTK_ICON_SIZE_INVALID].name = NULL;
562       icon_sizes[GTK_ICON_SIZE_INVALID].width = 0;
563       icon_sizes[GTK_ICON_SIZE_INVALID].height = 0;
564
565       /* the name strings aren't copied since we don't ever remove
566        * icon sizes, so we don't need to know whether they're static.
567        * Even if we did I suppose removing the builtin sizes would be
568        * disallowed.
569        */
570
571       icon_sizes[GTK_ICON_SIZE_MENU].size = GTK_ICON_SIZE_MENU;
572       icon_sizes[GTK_ICON_SIZE_MENU].name = "gtk-menu";
573       icon_sizes[GTK_ICON_SIZE_MENU].width = 16;
574       icon_sizes[GTK_ICON_SIZE_MENU].height = 16;
575
576       icon_sizes[GTK_ICON_SIZE_BUTTON].size = GTK_ICON_SIZE_BUTTON;
577       icon_sizes[GTK_ICON_SIZE_BUTTON].name = "gtk-button";
578       icon_sizes[GTK_ICON_SIZE_BUTTON].width = 20;
579       icon_sizes[GTK_ICON_SIZE_BUTTON].height = 20;
580
581       icon_sizes[GTK_ICON_SIZE_SMALL_TOOLBAR].size = GTK_ICON_SIZE_SMALL_TOOLBAR;
582       icon_sizes[GTK_ICON_SIZE_SMALL_TOOLBAR].name = "gtk-small-toolbar";
583       icon_sizes[GTK_ICON_SIZE_SMALL_TOOLBAR].width = 18;
584       icon_sizes[GTK_ICON_SIZE_SMALL_TOOLBAR].height = 18;
585
586       icon_sizes[GTK_ICON_SIZE_LARGE_TOOLBAR].size = GTK_ICON_SIZE_LARGE_TOOLBAR;
587       icon_sizes[GTK_ICON_SIZE_LARGE_TOOLBAR].name = "gtk-large-toolbar";
588       icon_sizes[GTK_ICON_SIZE_LARGE_TOOLBAR].width = 24;
589       icon_sizes[GTK_ICON_SIZE_LARGE_TOOLBAR].height = 24;
590
591       icon_sizes[GTK_ICON_SIZE_DND].size = GTK_ICON_SIZE_DND;
592       icon_sizes[GTK_ICON_SIZE_DND].name = "gtk-dnd";
593       icon_sizes[GTK_ICON_SIZE_DND].width = 32;
594       icon_sizes[GTK_ICON_SIZE_DND].height = 32;
595
596       icon_sizes[GTK_ICON_SIZE_DIALOG].size = GTK_ICON_SIZE_DIALOG;
597       icon_sizes[GTK_ICON_SIZE_DIALOG].name = "gtk-dialog";
598       icon_sizes[GTK_ICON_SIZE_DIALOG].width = 48;
599       icon_sizes[GTK_ICON_SIZE_DIALOG].height = 48;
600
601       g_assert ((GTK_ICON_SIZE_DIALOG + 1) == NUM_BUILTIN_SIZES);
602
603       /* Alias everything to itself. */
604       i = 1; /* skip invalid size */
605       while (i < NUM_BUILTIN_SIZES)
606         {
607           gtk_icon_size_register_alias (icon_sizes[i].name, icon_sizes[i].size);
608
609           ++i;
610         }
611
612 #undef NUM_BUILTIN_SIZES
613     }
614 }
615
616 static void
617 free_settings_sizes (gpointer data)
618 {
619   g_array_free (data, TRUE);
620 }
621
622 static GArray *
623 get_settings_sizes (GtkSettings *settings,
624                     gboolean    *created)
625 {
626   GArray *settings_sizes;
627   static GQuark sizes_quark = 0;
628
629   if (!sizes_quark)
630     sizes_quark = g_quark_from_static_string ("gtk-icon-sizes");
631
632   settings_sizes = g_object_get_qdata (G_OBJECT (settings), sizes_quark);
633   if (!settings_sizes)
634     {
635       settings_sizes = g_array_new (FALSE, FALSE, sizeof (SettingsIconSize));
636       g_object_set_qdata_full (G_OBJECT (settings), sizes_quark,
637                                settings_sizes, free_settings_sizes);
638       if (created)
639         *created = TRUE;
640     }
641
642   return settings_sizes;
643 }
644
645 static void
646 icon_size_set_for_settings (GtkSettings *settings,
647                             const gchar *size_name,
648                             gint         width,
649                             gint         height)
650 {
651   GtkIconSize size;
652   GArray *settings_sizes;
653   SettingsIconSize *settings_size;
654
655   g_return_if_fail (size_name != NULL);
656
657   size = gtk_icon_size_from_name (size_name);
658   if (size == GTK_ICON_SIZE_INVALID)
659     /* Reserve a place */
660     size = icon_size_register_intern (size_name, -1, -1);
661
662   settings_sizes = get_settings_sizes (settings, NULL);
663   if (size >= settings_sizes->len)
664     {
665       SettingsIconSize unset = { -1, -1 };
666       gint i;
667
668       for (i = settings_sizes->len; i <= size; i++)
669         g_array_append_val (settings_sizes, unset);
670     }
671
672   settings_size = &g_array_index (settings_sizes, SettingsIconSize, size);
673
674   settings_size->width = width;
675   settings_size->height = height;
676 }
677
678 /* Like pango_parse_word, but accept - as well
679  */
680 static gboolean
681 scan_icon_size_name (const char **pos, GString *out)
682 {
683   const char *p = *pos;
684
685   while (g_ascii_isspace (*p))
686     p++;
687
688   if (!((*p >= 'A' && *p <= 'Z') ||
689         (*p >= 'a' && *p <= 'z') ||
690         *p == '_' || *p == '-'))
691     return FALSE;
692
693   g_string_truncate (out, 0);
694   g_string_append_c (out, *p);
695   p++;
696
697   while ((*p >= 'A' && *p <= 'Z') ||
698          (*p >= 'a' && *p <= 'z') ||
699          (*p >= '0' && *p <= '9') ||
700          *p == '_' || *p == '-')
701     {
702       g_string_append_c (out, *p);
703       p++;
704     }
705
706   *pos = p;
707
708   return TRUE;
709 }
710
711 static void
712 icon_size_setting_parse (GtkSettings *settings,
713                          const gchar *icon_size_string)
714 {
715   GString *name_buf = g_string_new (NULL);
716   const gchar *p = icon_size_string;
717
718   while (pango_skip_space (&p))
719     {
720       gint width, height;
721
722       if (!scan_icon_size_name (&p, name_buf))
723         goto err;
724
725       if (!pango_skip_space (&p))
726         goto err;
727
728       if (*p != '=')
729         goto err;
730
731       p++;
732
733       if (!pango_scan_int (&p, &width))
734         goto err;
735
736       if (!pango_skip_space (&p))
737         goto err;
738
739       if (*p != ',')
740         goto err;
741
742       p++;
743
744       if (!pango_scan_int (&p, &height))
745         goto err;
746
747       if (width > 0 && height > 0)
748         {
749           icon_size_set_for_settings (settings, name_buf->str,
750                                       width, height);
751         }
752       else
753         {
754           g_warning ("Invalid size in gtk-icon-sizes: %d,%d\n", width, height);
755         }
756
757       pango_skip_space (&p);
758       if (*p == '\0')
759         break;
760       if (*p == ':')
761         p++;
762       else
763         goto err;
764     }
765
766   g_string_free (name_buf, TRUE);
767   return;
768
769  err:
770   g_warning ("Error parsing gtk-icon-sizes string:\n\t'%s'", icon_size_string);
771   g_string_free (name_buf, TRUE);
772 }
773
774 static void
775 icon_size_set_all_from_settings (GtkSettings *settings)
776 {
777   GArray *settings_sizes;
778   gchar *icon_size_string;
779
780   /* Reset old settings */
781   settings_sizes = get_settings_sizes (settings, NULL);
782   g_array_set_size (settings_sizes, 0);
783
784   g_object_get (settings,
785                 "gtk-icon-sizes", &icon_size_string,
786                 NULL);
787
788   if (icon_size_string)
789     {
790       icon_size_setting_parse (settings, icon_size_string);
791       g_free (icon_size_string);
792     }
793 }
794
795 static void
796 icon_size_settings_changed (GtkSettings  *settings,
797                             GParamSpec   *pspec)
798 {
799   icon_size_set_all_from_settings (settings);
800
801   gtk_style_context_reset_widgets (_gtk_settings_get_screen (settings));
802 }
803
804 static void
805 icon_sizes_init_for_settings (GtkSettings *settings)
806 {
807   g_signal_connect (settings,
808                     "notify::gtk-icon-sizes",
809                     G_CALLBACK (icon_size_settings_changed),
810                     NULL);
811
812   icon_size_set_all_from_settings (settings);
813 }
814
815 static gboolean
816 icon_size_lookup_intern (GtkSettings *settings,
817                          GtkIconSize  size,
818                          gint        *widthp,
819                          gint        *heightp)
820 {
821   GArray *settings_sizes;
822   gint width_for_settings = -1;
823   gint height_for_settings = -1;
824
825   init_icon_sizes ();
826
827   if (size == (GtkIconSize)-1)
828     return FALSE;
829
830   if (size >= icon_sizes_used)
831     return FALSE;
832
833   if (size == GTK_ICON_SIZE_INVALID)
834     return FALSE;
835
836   if (settings)
837     {
838       gboolean initial = FALSE;
839
840       settings_sizes = get_settings_sizes (settings, &initial);
841
842       if (initial)
843         icon_sizes_init_for_settings (settings);
844
845       if (size < settings_sizes->len)
846         {
847           SettingsIconSize *settings_size;
848
849           settings_size = &g_array_index (settings_sizes, SettingsIconSize, size);
850
851           width_for_settings = settings_size->width;
852           height_for_settings = settings_size->height;
853         }
854     }
855
856   if (widthp)
857     *widthp = width_for_settings >= 0 ? width_for_settings : icon_sizes[size].width;
858
859   if (heightp)
860     *heightp = height_for_settings >= 0 ? height_for_settings : icon_sizes[size].height;
861
862   return TRUE;
863 }
864
865 /**
866  * gtk_icon_size_lookup_for_settings:
867  * @settings: a #GtkSettings object, used to determine
868  *   which set of user preferences to used.
869  * @size: (type int): an icon size
870  * @width: (out): location to store icon width
871  * @height: (out): location to store icon height
872  *
873  * Obtains the pixel size of a semantic icon size, possibly
874  * modified by user preferences for a particular
875  * #GtkSettings. Normally @size would be
876  * #GTK_ICON_SIZE_MENU, #GTK_ICON_SIZE_BUTTON, etc.  This function
877  * isn't normally needed, gtk_widget_render_icon_pixbuf() is the usual
878  * way to get an icon for rendering, then just look at the size of
879  * the rendered pixbuf. The rendered pixbuf may not even correspond to
880  * the width/height returned by gtk_icon_size_lookup(), because themes
881  * are free to render the pixbuf however they like, including changing
882  * the usual size.
883  *
884  * Return value: %TRUE if @size was a valid size
885  *
886  * Since: 2.2
887  */
888 gboolean
889 gtk_icon_size_lookup_for_settings (GtkSettings *settings,
890                                    GtkIconSize  size,
891                                    gint        *width,
892                                    gint        *height)
893 {
894   g_return_val_if_fail (GTK_IS_SETTINGS (settings), FALSE);
895
896   return icon_size_lookup_intern (settings, size, width, height);
897 }
898
899 /**
900  * gtk_icon_size_lookup:
901  * @size: (type int): an icon size
902  * @width: (out): location to store icon width
903  * @height: (out): location to store icon height
904  *
905  * Obtains the pixel size of a semantic icon size, possibly
906  * modified by user preferences for the default #GtkSettings.
907  * (See gtk_icon_size_lookup_for_settings().)
908  * Normally @size would be
909  * #GTK_ICON_SIZE_MENU, #GTK_ICON_SIZE_BUTTON, etc.  This function
910  * isn't normally needed, gtk_widget_render_icon_pixbuf() is the usual
911  * way to get an icon for rendering, then just look at the size of
912  * the rendered pixbuf. The rendered pixbuf may not even correspond to
913  * the width/height returned by gtk_icon_size_lookup(), because themes
914  * are free to render the pixbuf however they like, including changing
915  * the usual size.
916  *
917  * Return value: %TRUE if @size was a valid size
918  */
919 gboolean
920 gtk_icon_size_lookup (GtkIconSize  size,
921                       gint        *widthp,
922                       gint        *heightp)
923 {
924   GTK_NOTE (MULTIHEAD,
925             g_warning ("gtk_icon_size_lookup ()) is not multihead safe"));
926
927   return gtk_icon_size_lookup_for_settings (gtk_settings_get_default (),
928                                             size, widthp, heightp);
929 }
930
931 static GtkIconSize
932 icon_size_register_intern (const gchar *name,
933                            gint         width,
934                            gint         height)
935 {
936   IconAlias *old_alias;
937   GtkIconSize size;
938
939   init_icon_sizes ();
940
941   old_alias = g_hash_table_lookup (icon_aliases, name);
942   if (old_alias && icon_sizes[old_alias->target].width > 0)
943     {
944       g_warning ("Icon size name '%s' already exists", name);
945       return GTK_ICON_SIZE_INVALID;
946     }
947
948   if (old_alias)
949     {
950       size = old_alias->target;
951     }
952   else
953     {
954       if (icon_sizes_used == icon_sizes_allocated)
955         {
956           icon_sizes_allocated *= 2;
957           icon_sizes = g_renew (IconSize, icon_sizes, icon_sizes_allocated);
958         }
959
960       size = icon_sizes_used++;
961
962       /* alias to self. */
963       gtk_icon_size_register_alias (name, size);
964
965       icon_sizes[size].size = size;
966       icon_sizes[size].name = g_strdup (name);
967     }
968
969   icon_sizes[size].width = width;
970   icon_sizes[size].height = height;
971
972   return size;
973 }
974
975 /**
976  * gtk_icon_size_register:
977  * @name: name of the icon size
978  * @width: the icon width
979  * @height: the icon height
980  *
981  * Registers a new icon size, along the same lines as #GTK_ICON_SIZE_MENU,
982  * etc. Returns the integer value for the size.
983  *
984  * Returns: (type int): integer value representing the size
985  */
986 GtkIconSize
987 gtk_icon_size_register (const gchar *name,
988                         gint         width,
989                         gint         height)
990 {
991   g_return_val_if_fail (name != NULL, 0);
992   g_return_val_if_fail (width > 0, 0);
993   g_return_val_if_fail (height > 0, 0);
994
995   return icon_size_register_intern (name, width, height);
996 }
997
998 /**
999  * gtk_icon_size_register_alias:
1000  * @alias: an alias for @target
1001  * @target: (type int): an existing icon size
1002  *
1003  * Registers @alias as another name for @target.
1004  * So calling gtk_icon_size_from_name() with @alias as argument
1005  * will return @target.
1006  */
1007 void
1008 gtk_icon_size_register_alias (const gchar *alias,
1009                               GtkIconSize  target)
1010 {
1011   IconAlias *ia;
1012
1013   g_return_if_fail (alias != NULL);
1014
1015   init_icon_sizes ();
1016
1017   if (!icon_size_lookup_intern (NULL, target, NULL, NULL))
1018     g_warning ("gtk_icon_size_register_alias: Icon size %u does not exist", target);
1019
1020   ia = g_hash_table_lookup (icon_aliases, alias);
1021   if (ia)
1022     {
1023       if (icon_sizes[ia->target].width > 0)
1024         {
1025           g_warning ("gtk_icon_size_register_alias: Icon size name '%s' already exists", alias);
1026           return;
1027         }
1028
1029       ia->target = target;
1030     }
1031
1032   if (!ia)
1033     {
1034       ia = g_new (IconAlias, 1);
1035       ia->name = g_strdup (alias);
1036       ia->target = target;
1037
1038       g_hash_table_insert (icon_aliases, ia->name, ia);
1039     }
1040 }
1041
1042 /**
1043  * gtk_icon_size_from_name:
1044  * @name: the name to look up.
1045  *
1046  * Looks up the icon size associated with @name.
1047  *
1048  * Return value: (type int): the icon size
1049  */
1050 GtkIconSize
1051 gtk_icon_size_from_name (const gchar *name)
1052 {
1053   IconAlias *ia;
1054
1055   init_icon_sizes ();
1056
1057   ia = g_hash_table_lookup (icon_aliases, name);
1058
1059   if (ia && icon_sizes[ia->target].width > 0)
1060     return ia->target;
1061   else
1062     return GTK_ICON_SIZE_INVALID;
1063 }
1064
1065 /**
1066  * gtk_icon_size_get_name:
1067  * @size: (type int): a #GtkIconSize.
1068  * @returns: the name of the given icon size.
1069  *
1070  * Gets the canonical name of the given icon size. The returned string
1071  * is statically allocated and should not be freed.
1072  */
1073 G_CONST_RETURN gchar*
1074 gtk_icon_size_get_name (GtkIconSize  size)
1075 {
1076   if (size >= icon_sizes_used)
1077     return NULL;
1078   else
1079     return icon_sizes[size].name;
1080 }
1081
1082 /************************************************************/
1083
1084 /* Icon Set */
1085
1086
1087 static GdkPixbuf *find_in_cache     (GtkIconSet       *icon_set,
1088                                      GtkStyleContext  *style_context,
1089                                      GtkTextDirection  direction,
1090                                      GtkStateType      state,
1091                                      GtkIconSize       size);
1092 static void       add_to_cache      (GtkIconSet       *icon_set,
1093                                      GtkStyleContext  *style_context,
1094                                      GtkTextDirection  direction,
1095                                      GtkStateType      state,
1096                                      GtkIconSize       size,
1097                                      GdkPixbuf        *pixbuf);
1098 /* Clear icon set contents, drop references to all contained
1099  * GdkPixbuf objects and forget all GtkIconSources. Used to
1100  * recycle an icon set.
1101  */
1102 static void       clear_cache       (GtkIconSet       *icon_set,
1103                                      gboolean          style_detach);
1104 static GSList*    copy_cache        (GtkIconSet       *icon_set,
1105                                      GtkIconSet       *copy_recipient);
1106 static void       attach_to_style   (GtkIconSet       *icon_set,
1107                                      GtkStyleContext  *style_context);
1108 static void       detach_from_style (GtkIconSet       *icon_set,
1109                                      GtkStyleContext  *style_context);
1110 static void       style_dnotify     (gpointer          data);
1111
1112 struct _GtkIconSet
1113 {
1114   guint ref_count;
1115
1116   GSList *sources;
1117
1118   /* Cache of the last few rendered versions of the icon. */
1119   GSList *cache;
1120
1121   guint cache_size;
1122
1123   guint cache_serial;
1124 };
1125
1126 static guint cache_serial = 0;
1127
1128 /**
1129  * gtk_icon_set_new:
1130  *
1131  * Creates a new #GtkIconSet. A #GtkIconSet represents a single icon
1132  * in various sizes and widget states. It can provide a #GdkPixbuf
1133  * for a given size and state on request, and automatically caches
1134  * some of the rendered #GdkPixbuf objects.
1135  *
1136  * Normally you would use gtk_widget_render_icon_pixbuf() instead of
1137  * using #GtkIconSet directly. The one case where you'd use
1138  * #GtkIconSet is to create application-specific icon sets to place in
1139  * a #GtkIconFactory.
1140  *
1141  * Return value: a new #GtkIconSet
1142  */
1143 GtkIconSet*
1144 gtk_icon_set_new (void)
1145 {
1146   GtkIconSet *icon_set;
1147
1148   icon_set = g_new (GtkIconSet, 1);
1149
1150   icon_set->ref_count = 1;
1151   icon_set->sources = NULL;
1152   icon_set->cache = NULL;
1153   icon_set->cache_size = 0;
1154   icon_set->cache_serial = cache_serial;
1155
1156   return icon_set;
1157 }
1158
1159 /**
1160  * gtk_icon_set_new_from_pixbuf:
1161  * @pixbuf: a #GdkPixbuf
1162  *
1163  * Creates a new #GtkIconSet with @pixbuf as the default/fallback
1164  * source image. If you don't add any additional #GtkIconSource to the
1165  * icon set, all variants of the icon will be created from @pixbuf,
1166  * using scaling, pixelation, etc. as required to adjust the icon size
1167  * or make the icon look insensitive/prelighted.
1168  *
1169  * Return value: a new #GtkIconSet
1170  */
1171 GtkIconSet *
1172 gtk_icon_set_new_from_pixbuf (GdkPixbuf *pixbuf)
1173 {
1174   GtkIconSet *set;
1175
1176   GtkIconSource source = GTK_ICON_SOURCE_INIT (TRUE, TRUE, TRUE);
1177
1178   g_return_val_if_fail (pixbuf != NULL, NULL);
1179
1180   set = gtk_icon_set_new ();
1181
1182   gtk_icon_source_set_pixbuf (&source, pixbuf);
1183   gtk_icon_set_add_source (set, &source);
1184   gtk_icon_source_set_pixbuf (&source, NULL);
1185
1186   return set;
1187 }
1188
1189
1190 /**
1191  * gtk_icon_set_ref:
1192  * @icon_set: a #GtkIconSet.
1193  *
1194  * Increments the reference count on @icon_set.
1195  *
1196  * Return value: @icon_set.
1197  */
1198 GtkIconSet*
1199 gtk_icon_set_ref (GtkIconSet *icon_set)
1200 {
1201   g_return_val_if_fail (icon_set != NULL, NULL);
1202   g_return_val_if_fail (icon_set->ref_count > 0, NULL);
1203
1204   icon_set->ref_count += 1;
1205
1206   return icon_set;
1207 }
1208
1209 /**
1210  * gtk_icon_set_unref:
1211  * @icon_set: a #GtkIconSet
1212  *
1213  * Decrements the reference count on @icon_set, and frees memory
1214  * if the reference count reaches 0.
1215  */
1216 void
1217 gtk_icon_set_unref (GtkIconSet *icon_set)
1218 {
1219   g_return_if_fail (icon_set != NULL);
1220   g_return_if_fail (icon_set->ref_count > 0);
1221
1222   icon_set->ref_count -= 1;
1223
1224   if (icon_set->ref_count == 0)
1225     {
1226       GSList *tmp_list = icon_set->sources;
1227       while (tmp_list != NULL)
1228         {
1229           gtk_icon_source_free (tmp_list->data);
1230
1231           tmp_list = g_slist_next (tmp_list);
1232         }
1233       g_slist_free (icon_set->sources);
1234
1235       clear_cache (icon_set, TRUE);
1236
1237       g_free (icon_set);
1238     }
1239 }
1240
1241 G_DEFINE_BOXED_TYPE (GtkIconSet, gtk_icon_set,
1242                      gtk_icon_set_ref,
1243                      gtk_icon_set_unref)
1244
1245 /**
1246  * gtk_icon_set_copy:
1247  * @icon_set: a #GtkIconSet
1248  *
1249  * Copies @icon_set by value.
1250  *
1251  * Return value: a new #GtkIconSet identical to the first.
1252  **/
1253 GtkIconSet*
1254 gtk_icon_set_copy (GtkIconSet *icon_set)
1255 {
1256   GtkIconSet *copy;
1257   GSList *tmp_list;
1258
1259   copy = gtk_icon_set_new ();
1260
1261   tmp_list = icon_set->sources;
1262   while (tmp_list != NULL)
1263     {
1264       copy->sources = g_slist_prepend (copy->sources,
1265                                        gtk_icon_source_copy (tmp_list->data));
1266
1267       tmp_list = g_slist_next (tmp_list);
1268     }
1269
1270   copy->sources = g_slist_reverse (copy->sources);
1271
1272   copy->cache = copy_cache (icon_set, copy);
1273   copy->cache_size = icon_set->cache_size;
1274   copy->cache_serial = icon_set->cache_serial;
1275
1276   return copy;
1277 }
1278
1279 static gboolean
1280 sizes_equivalent (GtkIconSize lhs,
1281                   GtkIconSize rhs)
1282 {
1283   /* We used to consider sizes equivalent if they were
1284    * the same pixel size, but we don't have the GtkSettings
1285    * here, so we can't do that. Plus, it's not clear that
1286    * it is right... it was just a workaround for the fact
1287    * that we register icons by logical size, not pixel size.
1288    */
1289 #if 1
1290   return lhs == rhs;
1291 #else
1292
1293   gint r_w, r_h, l_w, l_h;
1294
1295   icon_size_lookup_intern (NULL, rhs, &r_w, &r_h);
1296   icon_size_lookup_intern (NULL, lhs, &l_w, &l_h);
1297
1298   return r_w == l_w && r_h == l_h;
1299 #endif
1300 }
1301
1302 static GtkIconSource *
1303 find_best_matching_source (GtkIconSet       *icon_set,
1304                            GtkTextDirection  direction,
1305                            GtkStateType      state,
1306                            GtkIconSize       size,
1307                            GSList           *failed)
1308 {
1309   GtkIconSource *source;
1310   GSList *tmp_list;
1311
1312   /* We need to find the best icon source.  Direction matters more
1313    * than state, state matters more than size. icon_set->sources
1314    * is sorted according to wildness, so if we take the first
1315    * match we find it will be the least-wild match (if there are
1316    * multiple matches for a given "wildness" then the RC file contained
1317    * dumb stuff, and we end up with an arbitrary matching source)
1318    */
1319
1320   source = NULL;
1321   tmp_list = icon_set->sources;
1322   while (tmp_list != NULL)
1323     {
1324       GtkIconSource *s = tmp_list->data;
1325
1326       if ((s->any_direction || (s->direction == direction)) &&
1327           (s->any_state || (s->state == state)) &&
1328           (s->any_size || size == (GtkIconSize)-1 || (sizes_equivalent (size, s->size))))
1329         {
1330           if (!g_slist_find (failed, s))
1331             {
1332               source = s;
1333               break;
1334             }
1335         }
1336
1337       tmp_list = g_slist_next (tmp_list);
1338     }
1339
1340   return source;
1341 }
1342
1343 static gboolean
1344 ensure_filename_pixbuf (GtkIconSet    *icon_set,
1345                         GtkIconSource *source)
1346 {
1347   if (source->filename_pixbuf == NULL)
1348     {
1349       GError *error = NULL;
1350
1351       source->filename_pixbuf = gdk_pixbuf_new_from_file (source->source.filename, &error);
1352
1353       if (source->filename_pixbuf == NULL)
1354         {
1355           /* Remove this icon source so we don't keep trying to
1356            * load it.
1357            */
1358           g_warning (_("Error loading icon: %s"), error->message);
1359           g_error_free (error);
1360
1361           icon_set->sources = g_slist_remove (icon_set->sources, source);
1362
1363           gtk_icon_source_free (source);
1364
1365           return FALSE;
1366         }
1367     }
1368
1369   return TRUE;
1370 }
1371
1372 static GdkPixbuf *
1373 render_icon_name_pixbuf (GtkIconSource    *icon_source,
1374                          GtkStyleContext  *context,
1375                          GtkIconSize       size)
1376 {
1377   GdkPixbuf *pixbuf;
1378   GdkPixbuf *tmp_pixbuf;
1379   GtkIconSource tmp_source;
1380   GdkScreen *screen;
1381   GtkIconTheme *icon_theme;
1382   GtkSettings *settings;
1383   gint width, height, pixel_size;
1384   gint *sizes, *s, dist;
1385   GError *error = NULL;
1386
1387   screen = gtk_style_context_get_screen (context);
1388   icon_theme = gtk_icon_theme_get_for_screen (screen);
1389   settings = gtk_settings_get_for_screen (screen);
1390
1391   if (!gtk_icon_size_lookup_for_settings (settings, size, &width, &height))
1392     {
1393       if (size == (GtkIconSize)-1)
1394         {
1395           /* Find an available size close to 48 */
1396           sizes = gtk_icon_theme_get_icon_sizes (icon_theme, icon_source->source.icon_name);
1397           dist = 1000;
1398           width = height = 48;
1399           for (s = sizes; *s; s++)
1400             {
1401               if (*s == -1)
1402                 {
1403                   width = height = 48;
1404                   break;
1405                 }
1406               if (*s < 48)
1407                 {
1408                   if (48 - *s < dist)
1409                     {
1410                       width = height = *s;
1411                       dist = 48 - *s;
1412                     }
1413                 }
1414               else
1415                 {
1416                   if (*s - 48 < dist)
1417                     {
1418                       width = height = *s;
1419                       dist = *s - 48;
1420                     }
1421                 }
1422             }
1423
1424           g_free (sizes);
1425         }
1426       else
1427         {
1428           g_warning ("Invalid icon size %u\n", size);
1429           width = height = 24;
1430         }
1431     }
1432
1433   pixel_size = MIN (width, height);
1434
1435   if (icon_source->direction != GTK_TEXT_DIR_NONE)
1436     {
1437       gchar *suffix[3] = { NULL, "-ltr", "-rtl" };
1438       gchar *names[3];
1439       GtkIconInfo *info;
1440
1441       names[0] = g_strconcat (icon_source->source.icon_name, suffix[icon_source->direction], NULL);
1442       names[1] = icon_source->source.icon_name;
1443       names[2] = NULL;
1444
1445       info = gtk_icon_theme_choose_icon (icon_theme,
1446                                          (const char **) names,
1447                                          pixel_size, GTK_ICON_LOOKUP_USE_BUILTIN);
1448       g_free (names[0]);
1449       if (info)
1450         {
1451           tmp_pixbuf = gtk_icon_info_load_icon (info, &error);
1452           gtk_icon_info_free (info);
1453         }
1454       else
1455         tmp_pixbuf = NULL;
1456     }
1457   else
1458     {
1459       tmp_pixbuf = gtk_icon_theme_load_icon (icon_theme,
1460                                              icon_source->source.icon_name,
1461                                              pixel_size, 0,
1462                                              &error);
1463     }
1464
1465   if (!tmp_pixbuf)
1466     {
1467       g_warning ("Error loading theme icon '%s' for stock: %s",
1468                  icon_source->source.icon_name, error ? error->message : "");
1469       if (error)
1470         g_error_free (error);
1471       return NULL;
1472     }
1473
1474   tmp_source = *icon_source;
1475   tmp_source.type = GTK_ICON_SOURCE_PIXBUF;
1476   tmp_source.source.pixbuf = tmp_pixbuf;
1477
1478   pixbuf = gtk_render_icon_pixbuf (context, &tmp_source, -1);
1479
1480   if (!pixbuf)
1481     g_warning ("Failed to render icon");
1482
1483   g_object_unref (tmp_pixbuf);
1484
1485   return pixbuf;
1486 }
1487
1488 static GdkPixbuf *
1489 find_and_render_icon_source (GtkIconSet       *icon_set,
1490                              GtkStyleContext  *context,
1491                              GtkTextDirection  direction,
1492                              GtkStateType      state,
1493                              GtkIconSize       size)
1494 {
1495   GSList *failed = NULL;
1496   GdkPixbuf *pixbuf = NULL;
1497
1498   /* We treat failure in two different ways:
1499    *
1500    *  A) If loading a source that specifies a filename fails,
1501    *     we treat that as permanent, and remove the source
1502    *     from the GtkIconSet. (in ensure_filename_pixbuf ()
1503    *  B) If loading a themed icon fails, or scaling an icon
1504    *     fails, we treat that as transient and will try
1505    *     again next time the icon falls out of the cache
1506    *     and we need to recreate it.
1507    */
1508   while (pixbuf == NULL)
1509     {
1510       GtkIconSource *source = find_best_matching_source (icon_set, direction, state, size, failed);
1511
1512       if (source == NULL)
1513         break;
1514
1515       switch (source->type)
1516         {
1517         case GTK_ICON_SOURCE_FILENAME:
1518           if (!ensure_filename_pixbuf (icon_set, source))
1519             break;
1520           /* Fall through */
1521         case GTK_ICON_SOURCE_PIXBUF:
1522           pixbuf = gtk_render_icon_pixbuf (context, source, size);
1523           if (!pixbuf)
1524             {
1525               g_warning ("Failed to render icon");
1526               failed = g_slist_prepend (failed, source);
1527             }
1528           break;
1529         case GTK_ICON_SOURCE_ICON_NAME:
1530         case GTK_ICON_SOURCE_STATIC_ICON_NAME:
1531           pixbuf = render_icon_name_pixbuf (source, context, size);
1532           if (!pixbuf)
1533             failed = g_slist_prepend (failed, source);
1534           break;
1535         case GTK_ICON_SOURCE_EMPTY:
1536           g_assert_not_reached ();
1537         }
1538     }
1539
1540   g_slist_free (failed);
1541
1542   return pixbuf;
1543 }
1544
1545 extern GtkIconCache *_builtin_cache;
1546
1547 static GdkPixbuf*
1548 render_fallback_image (GtkStyleContext   *context,
1549                        GtkTextDirection   direction,
1550                        GtkStateType       state,
1551                        GtkIconSize        size)
1552 {
1553   /* This icon can be used for any direction/state/size */
1554   static GtkIconSource fallback_source = GTK_ICON_SOURCE_INIT (TRUE, TRUE, TRUE);
1555
1556   if (fallback_source.type == GTK_ICON_SOURCE_EMPTY)
1557     {
1558       gint index;
1559       GdkPixbuf *pixbuf;
1560
1561       _gtk_icon_theme_ensure_builtin_cache ();
1562
1563       index = _gtk_icon_cache_get_directory_index (_builtin_cache, "24");
1564       pixbuf = _gtk_icon_cache_get_icon (_builtin_cache,
1565                                          GTK_STOCK_MISSING_IMAGE,
1566                                          index);
1567       gtk_icon_source_set_pixbuf (&fallback_source, pixbuf);
1568       g_object_unref (pixbuf);
1569     }
1570
1571   return gtk_render_icon_pixbuf (context, &fallback_source, size);
1572 }
1573
1574 /**
1575  * gtk_icon_set_render_icon_pixbuf:
1576  * @icon_set: a #GtkIconSet
1577  * @context: a #GtkStyleContext
1578  * @size: (type int): icon size. A size of (GtkIconSize)-1
1579  *        means render at the size of the source and don't scale.
1580  *
1581  * Renders an icon using gtk_render_icon_pixbuf(). In most cases,
1582  * gtk_widget_render_icon_pixbuf() is better, since it automatically provides
1583  * most of the arguments from the current widget settings.  This
1584  * function never returns %NULL; if the icon can't be rendered
1585  * (perhaps because an image file fails to load), a default "missing
1586  * image" icon will be returned instead.
1587  *
1588  * Return value: (transfer full): a #GdkPixbuf to be displayed
1589  *
1590  * Since: 3.0
1591  */
1592 GdkPixbuf *
1593 gtk_icon_set_render_icon_pixbuf (GtkIconSet        *icon_set,
1594                                  GtkStyleContext   *context,
1595                                  GtkIconSize        size)
1596 {
1597   GdkPixbuf *icon = NULL;
1598   GtkStateFlags flags = 0;
1599   GtkStateType state;
1600   GtkTextDirection direction;
1601
1602   g_return_val_if_fail (icon_set != NULL, NULL);
1603   g_return_val_if_fail (GTK_IS_STYLE_CONTEXT (context), NULL);
1604
1605   flags = gtk_style_context_get_state (context);
1606   if (flags & GTK_STATE_FLAG_INSENSITIVE)
1607     state = GTK_STATE_INSENSITIVE;
1608   else if (flags & GTK_STATE_FLAG_PRELIGHT)
1609     state = GTK_STATE_PRELIGHT;
1610   else
1611     state = GTK_STATE_NORMAL;
1612
1613   direction = gtk_style_context_get_direction (context);
1614
1615   if (icon_set->sources)
1616     {
1617       icon = find_in_cache (icon_set, context, direction, state, size);
1618       if (icon)
1619         {
1620           g_object_ref (icon);
1621           return icon;
1622         }
1623     }
1624
1625   if (icon_set->sources)
1626     icon = find_and_render_icon_source (icon_set, context, direction, state, size);
1627
1628   if (icon == NULL)
1629     icon = render_fallback_image (context, direction, state, size);
1630
1631   add_to_cache (icon_set, context, direction, state, size, icon);
1632
1633   return icon;
1634 }
1635
1636 /**
1637  * gtk_icon_set_render_icon:
1638  * @icon_set: a #GtkIconSet
1639  * @style: (allow-none): a #GtkStyle associated with @widget, or %NULL
1640  * @direction: text direction
1641  * @state: widget state
1642  * @size: (type int): icon size. A size of (GtkIconSize)-1
1643  *        means render at the size of the source and don't scale.
1644  * @widget: (allow-none): widget that will display the icon, or %NULL.
1645  *          The only use that is typically made of this
1646  *          is to determine the appropriate #GdkScreen.
1647  * @detail: (allow-none): detail to pass to the theme engine, or %NULL.
1648  *          Note that passing a detail of anything but %NULL
1649  *          will disable caching.
1650  *
1651  * Renders an icon using gtk_style_render_icon(). In most cases,
1652  * gtk_widget_render_icon() is better, since it automatically provides
1653  * most of the arguments from the current widget settings.  This
1654  * function never returns %NULL; if the icon can't be rendered
1655  * (perhaps because an image file fails to load), a default "missing
1656  * image" icon will be returned instead.
1657  *
1658  * Return value: (transfer full): a #GdkPixbuf to be displayed
1659  *
1660  * Deprecated: 3.0: Use gtk_icon_set_render_icon_pixbuf() instead
1661  */
1662 GdkPixbuf*
1663 gtk_icon_set_render_icon (GtkIconSet        *icon_set,
1664                           GtkStyle          *style,
1665                           GtkTextDirection   direction,
1666                           GtkStateType       state,
1667                           GtkIconSize        size,
1668                           GtkWidget         *widget,
1669                           const char        *detail)
1670 {
1671   GdkPixbuf *icon;
1672   GtkStyleContext *context = NULL;
1673   GtkStateFlags flags = 0;
1674
1675   g_return_val_if_fail (icon_set != NULL, NULL);
1676   g_return_val_if_fail (style == NULL || GTK_IS_STYLE (style), NULL);
1677
1678   if (style && gtk_style_has_context (style))
1679     {
1680       g_object_get (style, "context", &context, NULL);
1681       /* g_object_get returns a refed object */
1682       if (context)
1683         g_object_unref (context);
1684     }
1685   else if (widget)
1686     {
1687       context = gtk_widget_get_style_context (widget);
1688     }
1689
1690   if (!context)
1691     return render_fallback_image (context, direction, state, size);
1692
1693   gtk_style_context_save (context);
1694
1695   switch (state)
1696     {
1697     case GTK_STATE_PRELIGHT:
1698       flags |= GTK_STATE_FLAG_PRELIGHT;
1699       break;
1700     case GTK_STATE_INSENSITIVE:
1701       flags |= GTK_STATE_FLAG_INSENSITIVE;
1702       break;
1703     default:
1704       break;
1705     }
1706
1707   gtk_style_context_set_state (context, flags);
1708   gtk_style_context_set_direction (context, direction);
1709
1710   icon = gtk_icon_set_render_icon_pixbuf (icon_set, context, size);
1711
1712   gtk_style_context_restore (context);
1713
1714   return icon;
1715 }
1716
1717 /* Order sources by their "wildness", so that "wilder" sources are
1718  * greater than "specific" sources; for determining ordering,
1719  * direction beats state beats size.
1720  */
1721
1722 static int
1723 icon_source_compare (gconstpointer ap, gconstpointer bp)
1724 {
1725   const GtkIconSource *a = ap;
1726   const GtkIconSource *b = bp;
1727
1728   if (!a->any_direction && b->any_direction)
1729     return -1;
1730   else if (a->any_direction && !b->any_direction)
1731     return 1;
1732   else if (!a->any_state && b->any_state)
1733     return -1;
1734   else if (a->any_state && !b->any_state)
1735     return 1;
1736   else if (!a->any_size && b->any_size)
1737     return -1;
1738   else if (a->any_size && !b->any_size)
1739     return 1;
1740   else
1741     return 0;
1742 }
1743
1744 /**
1745  * gtk_icon_set_add_source:
1746  * @icon_set: a #GtkIconSet
1747  * @source: a #GtkIconSource
1748  *
1749  * Icon sets have a list of #GtkIconSource, which they use as base
1750  * icons for rendering icons in different states and sizes. Icons are
1751  * scaled, made to look insensitive, etc. in
1752  * gtk_icon_set_render_icon(), but #GtkIconSet needs base images to
1753  * work with. The base images and when to use them are described by
1754  * a #GtkIconSource.
1755  *
1756  * This function copies @source, so you can reuse the same source immediately
1757  * without affecting the icon set.
1758  *
1759  * An example of when you'd use this function: a web browser's "Back
1760  * to Previous Page" icon might point in a different direction in
1761  * Hebrew and in English; it might look different when insensitive;
1762  * and it might change size depending on toolbar mode (small/large
1763  * icons). So a single icon set would contain all those variants of
1764  * the icon, and you might add a separate source for each one.
1765  *
1766  * You should nearly always add a "default" icon source with all
1767  * fields wildcarded, which will be used as a fallback if no more
1768  * specific source matches. #GtkIconSet always prefers more specific
1769  * icon sources to more generic icon sources. The order in which you
1770  * add the sources to the icon set does not matter.
1771  *
1772  * gtk_icon_set_new_from_pixbuf() creates a new icon set with a
1773  * default icon source based on the given pixbuf.
1774  */
1775 void
1776 gtk_icon_set_add_source (GtkIconSet          *icon_set,
1777                          const GtkIconSource *source)
1778 {
1779   g_return_if_fail (icon_set != NULL);
1780   g_return_if_fail (source != NULL);
1781
1782   if (source->type == GTK_ICON_SOURCE_EMPTY)
1783     {
1784       g_warning ("Useless empty GtkIconSource");
1785       return;
1786     }
1787
1788   icon_set->sources = g_slist_insert_sorted (icon_set->sources,
1789                                              gtk_icon_source_copy (source),
1790                                              icon_source_compare);
1791 }
1792
1793 /**
1794  * gtk_icon_set_get_sizes:
1795  * @icon_set: a #GtkIconSet
1796  * @sizes: (array length=n_sizes) (out) (type int): return location
1797  *     for array of sizes
1798  * @n_sizes: location to store number of elements in returned array
1799  *
1800  * Obtains a list of icon sizes this icon set can render. The returned
1801  * array must be freed with g_free().
1802  */
1803 void
1804 gtk_icon_set_get_sizes (GtkIconSet   *icon_set,
1805                         GtkIconSize **sizes,
1806                         gint         *n_sizes)
1807 {
1808   GSList *tmp_list;
1809   gboolean all_sizes = FALSE;
1810   GSList *specifics = NULL;
1811
1812   g_return_if_fail (icon_set != NULL);
1813   g_return_if_fail (sizes != NULL);
1814   g_return_if_fail (n_sizes != NULL);
1815
1816   tmp_list = icon_set->sources;
1817   while (tmp_list != NULL)
1818     {
1819       GtkIconSource *source;
1820
1821       source = tmp_list->data;
1822
1823       if (source->any_size)
1824         {
1825           all_sizes = TRUE;
1826           break;
1827         }
1828       else
1829         specifics = g_slist_prepend (specifics, GINT_TO_POINTER (source->size));
1830
1831       tmp_list = g_slist_next (tmp_list);
1832     }
1833
1834   if (all_sizes)
1835     {
1836       /* Need to find out what sizes exist */
1837       gint i;
1838
1839       init_icon_sizes ();
1840
1841       *sizes = g_new (GtkIconSize, icon_sizes_used);
1842       *n_sizes = icon_sizes_used - 1;
1843
1844       i = 1;
1845       while (i < icon_sizes_used)
1846         {
1847           (*sizes)[i - 1] = icon_sizes[i].size;
1848           ++i;
1849         }
1850     }
1851   else
1852     {
1853       gint i;
1854
1855       *n_sizes = g_slist_length (specifics);
1856       *sizes = g_new (GtkIconSize, *n_sizes);
1857
1858       i = 0;
1859       tmp_list = specifics;
1860       while (tmp_list != NULL)
1861         {
1862           (*sizes)[i] = GPOINTER_TO_INT (tmp_list->data);
1863
1864           ++i;
1865           tmp_list = g_slist_next (tmp_list);
1866         }
1867     }
1868
1869   g_slist_free (specifics);
1870 }
1871
1872
1873 /**
1874  * gtk_icon_source_new:
1875  *
1876  * Creates a new #GtkIconSource. A #GtkIconSource contains a #GdkPixbuf (or
1877  * image filename) that serves as the base image for one or more of the
1878  * icons in a #GtkIconSet, along with a specification for which icons in the
1879  * icon set will be based on that pixbuf or image file. An icon set contains
1880  * a set of icons that represent "the same" logical concept in different states,
1881  * different global text directions, and different sizes.
1882  *
1883  * So for example a web browser's "Back to Previous Page" icon might
1884  * point in a different direction in Hebrew and in English; it might
1885  * look different when insensitive; and it might change size depending
1886  * on toolbar mode (small/large icons). So a single icon set would
1887  * contain all those variants of the icon. #GtkIconSet contains a list
1888  * of #GtkIconSource from which it can derive specific icon variants in
1889  * the set.
1890  *
1891  * In the simplest case, #GtkIconSet contains one source pixbuf from
1892  * which it derives all variants. The convenience function
1893  * gtk_icon_set_new_from_pixbuf() handles this case; if you only have
1894  * one source pixbuf, just use that function.
1895  *
1896  * If you want to use a different base pixbuf for different icon
1897  * variants, you create multiple icon sources, mark which variants
1898  * they'll be used to create, and add them to the icon set with
1899  * gtk_icon_set_add_source().
1900  *
1901  * By default, the icon source has all parameters wildcarded. That is,
1902  * the icon source will be used as the base icon for any desired text
1903  * direction, widget state, or icon size.
1904  *
1905  * Return value: a new #GtkIconSource
1906  */
1907 GtkIconSource*
1908 gtk_icon_source_new (void)
1909 {
1910   GtkIconSource *src;
1911
1912   src = g_new0 (GtkIconSource, 1);
1913
1914   src->direction = GTK_TEXT_DIR_NONE;
1915   src->size = GTK_ICON_SIZE_INVALID;
1916   src->state = GTK_STATE_NORMAL;
1917
1918   src->any_direction = TRUE;
1919   src->any_state = TRUE;
1920   src->any_size = TRUE;
1921
1922   return src;
1923 }
1924
1925 /**
1926  * gtk_icon_source_copy:
1927  * @source: a #GtkIconSource
1928  *
1929  * Creates a copy of @source; mostly useful for language bindings.
1930  *
1931  * Return value: a new #GtkIconSource
1932  */
1933 GtkIconSource*
1934 gtk_icon_source_copy (const GtkIconSource *source)
1935 {
1936   GtkIconSource *copy;
1937
1938   g_return_val_if_fail (source != NULL, NULL);
1939
1940   copy = g_new (GtkIconSource, 1);
1941
1942   *copy = *source;
1943
1944   switch (copy->type)
1945     {
1946     case GTK_ICON_SOURCE_EMPTY:
1947     case GTK_ICON_SOURCE_STATIC_ICON_NAME:
1948       break;
1949     case GTK_ICON_SOURCE_ICON_NAME:
1950       copy->source.icon_name = g_strdup (copy->source.icon_name);
1951       break;
1952     case GTK_ICON_SOURCE_FILENAME:
1953       copy->source.filename = g_strdup (copy->source.filename);
1954       if (copy->filename_pixbuf)
1955         g_object_ref (copy->filename_pixbuf);
1956       break;
1957     case GTK_ICON_SOURCE_PIXBUF:
1958       g_object_ref (copy->source.pixbuf);
1959       break;
1960     default:
1961       g_assert_not_reached();
1962     }
1963
1964   return copy;
1965 }
1966
1967 /**
1968  * gtk_icon_source_free:
1969  * @source: a #GtkIconSource
1970  *
1971  * Frees a dynamically-allocated icon source, along with its
1972  * filename, size, and pixbuf fields if those are not %NULL.
1973  */
1974 void
1975 gtk_icon_source_free (GtkIconSource *source)
1976 {
1977   g_return_if_fail (source != NULL);
1978
1979   icon_source_clear (source);
1980   g_free (source);
1981 }
1982
1983 G_DEFINE_BOXED_TYPE (GtkIconSource, gtk_icon_source,
1984                      gtk_icon_source_copy,
1985                      gtk_icon_source_free)
1986
1987 static void
1988 icon_source_clear (GtkIconSource *source)
1989 {
1990   switch (source->type)
1991     {
1992     case GTK_ICON_SOURCE_EMPTY:
1993       break;
1994     case GTK_ICON_SOURCE_ICON_NAME:
1995       g_free (source->source.icon_name);
1996       /* fall thru */
1997     case GTK_ICON_SOURCE_STATIC_ICON_NAME:
1998       source->source.icon_name = NULL;
1999       break;
2000     case GTK_ICON_SOURCE_FILENAME:
2001       g_free (source->source.filename);
2002       source->source.filename = NULL;
2003       if (source->filename_pixbuf) 
2004         g_object_unref (source->filename_pixbuf);
2005       source->filename_pixbuf = NULL;
2006       break;
2007     case GTK_ICON_SOURCE_PIXBUF:
2008       g_object_unref (source->source.pixbuf);
2009       source->source.pixbuf = NULL;
2010       break;
2011     default:
2012       g_assert_not_reached();
2013     }
2014
2015   source->type = GTK_ICON_SOURCE_EMPTY;
2016 }
2017
2018 /**
2019  * gtk_icon_source_set_filename:
2020  * @source: a #GtkIconSource
2021  * @filename: (type filename): image file to use
2022  *
2023  * Sets the name of an image file to use as a base image when creating
2024  * icon variants for #GtkIconSet. The filename must be absolute.
2025  */
2026 void
2027 gtk_icon_source_set_filename (GtkIconSource *source,
2028                               const gchar   *filename)
2029 {
2030   g_return_if_fail (source != NULL);
2031   g_return_if_fail (filename == NULL || g_path_is_absolute (filename));
2032
2033   if (source->type == GTK_ICON_SOURCE_FILENAME &&
2034       source->source.filename == filename)
2035     return;
2036
2037   icon_source_clear (source);
2038
2039   if (filename != NULL)
2040     {
2041       source->type = GTK_ICON_SOURCE_FILENAME;
2042       source->source.filename = g_strdup (filename);
2043     }
2044 }
2045
2046 /**
2047  * gtk_icon_source_set_icon_name
2048  * @source: a #GtkIconSource
2049  * @icon_name: (allow-none): name of icon to use
2050  *
2051  * Sets the name of an icon to look up in the current icon theme
2052  * to use as a base image when creating icon variants for #GtkIconSet.
2053  */
2054 void
2055 gtk_icon_source_set_icon_name (GtkIconSource *source,
2056                                const gchar   *icon_name)
2057 {
2058   g_return_if_fail (source != NULL);
2059
2060   if (source->type == GTK_ICON_SOURCE_ICON_NAME &&
2061       source->source.icon_name == icon_name)
2062     return;
2063
2064   icon_source_clear (source);
2065
2066   if (icon_name != NULL)
2067     {
2068       source->type = GTK_ICON_SOURCE_ICON_NAME;
2069       source->source.icon_name = g_strdup (icon_name);
2070     }
2071 }
2072
2073 /**
2074  * gtk_icon_source_set_pixbuf:
2075  * @source: a #GtkIconSource
2076  * @pixbuf: pixbuf to use as a source
2077  *
2078  * Sets a pixbuf to use as a base image when creating icon variants
2079  * for #GtkIconSet.
2080  */
2081 void
2082 gtk_icon_source_set_pixbuf (GtkIconSource *source,
2083                             GdkPixbuf     *pixbuf)
2084 {
2085   g_return_if_fail (source != NULL);
2086   g_return_if_fail (pixbuf == NULL || GDK_IS_PIXBUF (pixbuf));
2087
2088   if (source->type == GTK_ICON_SOURCE_PIXBUF &&
2089       source->source.pixbuf == pixbuf)
2090     return;
2091
2092   icon_source_clear (source);
2093
2094   if (pixbuf != NULL)
2095     {
2096       source->type = GTK_ICON_SOURCE_PIXBUF;
2097       source->source.pixbuf = g_object_ref (pixbuf);
2098     }
2099 }
2100
2101 /**
2102  * gtk_icon_source_get_filename:
2103  * @source: a #GtkIconSource
2104  *
2105  * Retrieves the source filename, or %NULL if none is set. The
2106  * filename is not a copy, and should not be modified or expected to
2107  * persist beyond the lifetime of the icon source.
2108  *
2109  * Return value: (type filename): image filename. This string must not
2110  * be modified or freed.
2111  */
2112 G_CONST_RETURN gchar*
2113 gtk_icon_source_get_filename (const GtkIconSource *source)
2114 {
2115   g_return_val_if_fail (source != NULL, NULL);
2116
2117   if (source->type == GTK_ICON_SOURCE_FILENAME)
2118     return source->source.filename;
2119   else
2120     return NULL;
2121 }
2122
2123 /**
2124  * gtk_icon_source_get_icon_name:
2125  * @source: a #GtkIconSource
2126  *
2127  * Retrieves the source icon name, or %NULL if none is set. The
2128  * icon_name is not a copy, and should not be modified or expected to
2129  * persist beyond the lifetime of the icon source.
2130  *
2131  * Return value: icon name. This string must not be modified or freed.
2132  */
2133 G_CONST_RETURN gchar*
2134 gtk_icon_source_get_icon_name (const GtkIconSource *source)
2135 {
2136   g_return_val_if_fail (source != NULL, NULL);
2137
2138   if (source->type == GTK_ICON_SOURCE_ICON_NAME ||
2139      source->type == GTK_ICON_SOURCE_STATIC_ICON_NAME)
2140     return source->source.icon_name;
2141   else
2142     return NULL;
2143 }
2144
2145 /**
2146  * gtk_icon_source_get_pixbuf:
2147  * @source: a #GtkIconSource
2148  *
2149  * Retrieves the source pixbuf, or %NULL if none is set.
2150  * In addition, if a filename source is in use, this
2151  * function in some cases will return the pixbuf from
2152  * loaded from the filename. This is, for example, true
2153  * for the GtkIconSource passed to the GtkStyle::render_icon()
2154  * virtual function. The reference count on the pixbuf is
2155  * not incremented.
2156  *
2157  * Return value: (transfer none): source pixbuf
2158  */
2159 GdkPixbuf*
2160 gtk_icon_source_get_pixbuf (const GtkIconSource *source)
2161 {
2162   g_return_val_if_fail (source != NULL, NULL);
2163
2164   if (source->type == GTK_ICON_SOURCE_PIXBUF)
2165     return source->source.pixbuf;
2166   else if (source->type == GTK_ICON_SOURCE_FILENAME)
2167     return source->filename_pixbuf;
2168   else
2169     return NULL;
2170 }
2171
2172 /**
2173  * gtk_icon_source_set_direction_wildcarded:
2174  * @source: a #GtkIconSource
2175  * @setting: %TRUE to wildcard the text direction
2176  *
2177  * If the text direction is wildcarded, this source can be used
2178  * as the base image for an icon in any #GtkTextDirection.
2179  * If the text direction is not wildcarded, then the
2180  * text direction the icon source applies to should be set
2181  * with gtk_icon_source_set_direction(), and the icon source
2182  * will only be used with that text direction.
2183  *
2184  * #GtkIconSet prefers non-wildcarded sources (exact matches) over
2185  * wildcarded sources, and will use an exact match when possible.
2186  */
2187 void
2188 gtk_icon_source_set_direction_wildcarded (GtkIconSource *source,
2189                                           gboolean       setting)
2190 {
2191   g_return_if_fail (source != NULL);
2192
2193   source->any_direction = setting != FALSE;
2194 }
2195
2196 /**
2197  * gtk_icon_source_set_state_wildcarded:
2198  * @source: a #GtkIconSource
2199  * @setting: %TRUE to wildcard the widget state
2200  *
2201  * If the widget state is wildcarded, this source can be used as the
2202  * base image for an icon in any #GtkStateType.  If the widget state
2203  * is not wildcarded, then the state the source applies to should be
2204  * set with gtk_icon_source_set_state() and the icon source will
2205  * only be used with that specific state.
2206  *
2207  * #GtkIconSet prefers non-wildcarded sources (exact matches) over
2208  * wildcarded sources, and will use an exact match when possible.
2209  *
2210  * #GtkIconSet will normally transform wildcarded source images to
2211  * produce an appropriate icon for a given state, for example
2212  * lightening an image on prelight, but will not modify source images
2213  * that match exactly.
2214  */
2215 void
2216 gtk_icon_source_set_state_wildcarded (GtkIconSource *source,
2217                                       gboolean       setting)
2218 {
2219   g_return_if_fail (source != NULL);
2220
2221   source->any_state = setting != FALSE;
2222 }
2223
2224
2225 /**
2226  * gtk_icon_source_set_size_wildcarded:
2227  * @source: a #GtkIconSource
2228  * @setting: %TRUE to wildcard the widget state
2229  *
2230  * If the icon size is wildcarded, this source can be used as the base
2231  * image for an icon of any size.  If the size is not wildcarded, then
2232  * the size the source applies to should be set with
2233  * gtk_icon_source_set_size() and the icon source will only be used
2234  * with that specific size.
2235  *
2236  * #GtkIconSet prefers non-wildcarded sources (exact matches) over
2237  * wildcarded sources, and will use an exact match when possible.
2238  *
2239  * #GtkIconSet will normally scale wildcarded source images to produce
2240  * an appropriate icon at a given size, but will not change the size
2241  * of source images that match exactly.
2242  */
2243 void
2244 gtk_icon_source_set_size_wildcarded (GtkIconSource *source,
2245                                      gboolean       setting)
2246 {
2247   g_return_if_fail (source != NULL);
2248
2249   source->any_size = setting != FALSE;
2250 }
2251
2252 /**
2253  * gtk_icon_source_get_size_wildcarded:
2254  * @source: a #GtkIconSource
2255  *
2256  * Gets the value set by gtk_icon_source_set_size_wildcarded().
2257  *
2258  * Return value: %TRUE if this icon source is a base for any icon size variant
2259  */
2260 gboolean
2261 gtk_icon_source_get_size_wildcarded (const GtkIconSource *source)
2262 {
2263   g_return_val_if_fail (source != NULL, TRUE);
2264
2265   return source->any_size;
2266 }
2267
2268 /**
2269  * gtk_icon_source_get_state_wildcarded:
2270  * @source: a #GtkIconSource
2271  *
2272  * Gets the value set by gtk_icon_source_set_state_wildcarded().
2273  *
2274  * Return value: %TRUE if this icon source is a base for any widget state variant
2275  */
2276 gboolean
2277 gtk_icon_source_get_state_wildcarded (const GtkIconSource *source)
2278 {
2279   g_return_val_if_fail (source != NULL, TRUE);
2280
2281   return source->any_state;
2282 }
2283
2284 /**
2285  * gtk_icon_source_get_direction_wildcarded:
2286  * @source: a #GtkIconSource
2287  *
2288  * Gets the value set by gtk_icon_source_set_direction_wildcarded().
2289  *
2290  * Return value: %TRUE if this icon source is a base for any text direction variant
2291  */
2292 gboolean
2293 gtk_icon_source_get_direction_wildcarded (const GtkIconSource *source)
2294 {
2295   g_return_val_if_fail (source != NULL, TRUE);
2296
2297   return source->any_direction;
2298 }
2299
2300 /**
2301  * gtk_icon_source_set_direction:
2302  * @source: a #GtkIconSource
2303  * @direction: text direction this source applies to
2304  *
2305  * Sets the text direction this icon source is intended to be used
2306  * with.
2307  *
2308  * Setting the text direction on an icon source makes no difference
2309  * if the text direction is wildcarded. Therefore, you should usually
2310  * call gtk_icon_source_set_direction_wildcarded() to un-wildcard it
2311  * in addition to calling this function.
2312  */
2313 void
2314 gtk_icon_source_set_direction (GtkIconSource   *source,
2315                                GtkTextDirection direction)
2316 {
2317   g_return_if_fail (source != NULL);
2318
2319   source->direction = direction;
2320 }
2321
2322 /**
2323  * gtk_icon_source_set_state:
2324  * @source: a #GtkIconSource
2325  * @state: widget state this source applies to
2326  *
2327  * Sets the widget state this icon source is intended to be used
2328  * with.
2329  *
2330  * Setting the widget state on an icon source makes no difference
2331  * if the state is wildcarded. Therefore, you should usually
2332  * call gtk_icon_source_set_state_wildcarded() to un-wildcard it
2333  * in addition to calling this function.
2334  */
2335 void
2336 gtk_icon_source_set_state (GtkIconSource *source,
2337                            GtkStateType   state)
2338 {
2339   g_return_if_fail (source != NULL);
2340
2341   source->state = state;
2342 }
2343
2344 /**
2345  * gtk_icon_source_set_size:
2346  * @source: a #GtkIconSource
2347  * @size: (type int): icon size this source applies to
2348  *
2349  * Sets the icon size this icon source is intended to be used
2350  * with.
2351  *
2352  * Setting the icon size on an icon source makes no difference
2353  * if the size is wildcarded. Therefore, you should usually
2354  * call gtk_icon_source_set_size_wildcarded() to un-wildcard it
2355  * in addition to calling this function.
2356  */
2357 void
2358 gtk_icon_source_set_size (GtkIconSource *source,
2359                           GtkIconSize    size)
2360 {
2361   g_return_if_fail (source != NULL);
2362
2363   source->size = size;
2364 }
2365
2366 /**
2367  * gtk_icon_source_get_direction:
2368  * @source: a #GtkIconSource
2369  *
2370  * Obtains the text direction this icon source applies to. The return
2371  * value is only useful/meaningful if the text direction is <emphasis>not</emphasis>
2372  * wildcarded.
2373  *
2374  * Return value: text direction this source matches
2375  */
2376 GtkTextDirection
2377 gtk_icon_source_get_direction (const GtkIconSource *source)
2378 {
2379   g_return_val_if_fail (source != NULL, 0);
2380
2381   return source->direction;
2382 }
2383
2384 /**
2385  * gtk_icon_source_get_state:
2386  * @source: a #GtkIconSource
2387  *
2388  * Obtains the widget state this icon source applies to. The return
2389  * value is only useful/meaningful if the widget state is <emphasis>not</emphasis>
2390  * wildcarded.
2391  *
2392  * Return value: widget state this source matches
2393  */
2394 GtkStateType
2395 gtk_icon_source_get_state (const GtkIconSource *source)
2396 {
2397   g_return_val_if_fail (source != NULL, 0);
2398
2399   return source->state;
2400 }
2401
2402 /**
2403  * gtk_icon_source_get_size:
2404  * @source: a #GtkIconSource
2405  *
2406  * Obtains the icon size this source applies to. The return value
2407  * is only useful/meaningful if the icon size is <emphasis>not</emphasis> wildcarded.
2408  *
2409  * Return value: (type int): icon size this source matches.
2410  */
2411 GtkIconSize
2412 gtk_icon_source_get_size (const GtkIconSource *source)
2413 {
2414   g_return_val_if_fail (source != NULL, 0);
2415
2416   return source->size;
2417 }
2418
2419 #define NUM_CACHED_ICONS 8
2420
2421 typedef struct _CachedIcon CachedIcon;
2422
2423 struct _CachedIcon
2424 {
2425   /* These must all match to use the cached pixbuf.
2426    * If any don't match, we must re-render the pixbuf.
2427    */
2428   GtkStyleContext *style;
2429   GtkTextDirection direction;
2430   GtkStateType state;
2431   GtkIconSize size;
2432
2433   GdkPixbuf *pixbuf;
2434 };
2435
2436 static void
2437 ensure_cache_up_to_date (GtkIconSet *icon_set)
2438 {
2439   if (icon_set->cache_serial != cache_serial)
2440     {
2441       clear_cache (icon_set, TRUE);
2442       icon_set->cache_serial = cache_serial;
2443     }
2444 }
2445
2446 static void
2447 cached_icon_free (CachedIcon *icon)
2448 {
2449   g_object_unref (icon->pixbuf);
2450   g_object_unref (icon->style);
2451
2452   g_free (icon);
2453 }
2454
2455 static GdkPixbuf *
2456 find_in_cache (GtkIconSet      *icon_set,
2457                GtkStyleContext *style_context,
2458                GtkTextDirection direction,
2459                GtkStateType     state,
2460                GtkIconSize      size)
2461 {
2462   GSList *tmp_list;
2463   GSList *prev;
2464
2465   ensure_cache_up_to_date (icon_set);
2466
2467   prev = NULL;
2468   tmp_list = icon_set->cache;
2469   while (tmp_list != NULL)
2470     {
2471       CachedIcon *icon = tmp_list->data;
2472
2473       if (icon->style == style_context &&
2474           icon->direction == direction &&
2475           icon->state == state &&
2476           (size == (GtkIconSize)-1 || icon->size == size))
2477         {
2478           if (prev)
2479             {
2480               /* Move this icon to the front of the list. */
2481               prev->next = tmp_list->next;
2482               tmp_list->next = icon_set->cache;
2483               icon_set->cache = tmp_list;
2484             }
2485
2486           return icon->pixbuf;
2487         }
2488
2489       prev = tmp_list;
2490       tmp_list = g_slist_next (tmp_list);
2491     }
2492
2493   return NULL;
2494 }
2495
2496 static void
2497 add_to_cache (GtkIconSet      *icon_set,
2498               GtkStyleContext *style_context,
2499               GtkTextDirection direction,
2500               GtkStateType     state,
2501               GtkIconSize      size,
2502               GdkPixbuf       *pixbuf)
2503 {
2504   CachedIcon *icon;
2505
2506   ensure_cache_up_to_date (icon_set);
2507
2508   g_object_ref (pixbuf);
2509
2510   icon = g_new (CachedIcon, 1);
2511   icon_set->cache = g_slist_prepend (icon_set->cache, icon);
2512   icon_set->cache_size++;
2513
2514   icon->style = g_object_ref (style_context);
2515   icon->direction = direction;
2516   icon->state = state;
2517   icon->size = size;
2518   icon->pixbuf = pixbuf;
2519   attach_to_style (icon_set, icon->style);
2520
2521   if (icon_set->cache_size >= NUM_CACHED_ICONS)
2522     {
2523       /* Remove oldest item in the cache */
2524       GSList *tmp_list;
2525
2526       tmp_list = icon_set->cache;
2527
2528       /* Find next-to-last link */
2529       g_assert (NUM_CACHED_ICONS > 2);
2530       while (tmp_list->next->next)
2531         tmp_list = tmp_list->next;
2532
2533       g_assert (tmp_list != NULL);
2534       g_assert (tmp_list->next != NULL);
2535       g_assert (tmp_list->next->next == NULL);
2536
2537       /* Free the last icon */
2538       icon = tmp_list->next->data;
2539
2540       g_slist_free (tmp_list->next);
2541       tmp_list->next = NULL;
2542
2543       cached_icon_free (icon);
2544     }
2545 }
2546
2547 static void
2548 clear_cache (GtkIconSet *icon_set,
2549              gboolean    style_detach)
2550 {
2551   GSList *cache, *tmp_list;
2552   GtkStyleContext *last_style = NULL;
2553
2554   cache = icon_set->cache;
2555   icon_set->cache = NULL;
2556   icon_set->cache_size = 0;
2557   tmp_list = cache;
2558   while (tmp_list != NULL)
2559     {
2560       CachedIcon *icon = tmp_list->data;
2561
2562       if (style_detach)
2563         {
2564           /* simple optimization for the case where the cache
2565            * contains contiguous icons from the same style.
2566            * it's safe to call detach_from_style more than
2567            * once on the same style though.
2568            */
2569           if (last_style != icon->style)
2570             {
2571               detach_from_style (icon_set, icon->style);
2572               last_style = icon->style;
2573             }
2574         }
2575
2576       cached_icon_free (icon);
2577
2578       tmp_list = g_slist_next (tmp_list);
2579     }
2580
2581   g_slist_free (cache);
2582 }
2583
2584 static GSList*
2585 copy_cache (GtkIconSet *icon_set,
2586             GtkIconSet *copy_recipient)
2587 {
2588   GSList *tmp_list;
2589   GSList *copy = NULL;
2590
2591   ensure_cache_up_to_date (icon_set);
2592
2593   tmp_list = icon_set->cache;
2594   while (tmp_list != NULL)
2595     {
2596       CachedIcon *icon = tmp_list->data;
2597       CachedIcon *icon_copy = g_new (CachedIcon, 1);
2598
2599       *icon_copy = *icon;
2600
2601       attach_to_style (copy_recipient, icon_copy->style);
2602       g_object_ref (icon_copy->style);
2603
2604       g_object_ref (icon_copy->pixbuf);
2605
2606       icon_copy->size = icon->size;
2607
2608       copy = g_slist_prepend (copy, icon_copy);
2609
2610       tmp_list = g_slist_next (tmp_list);
2611     }
2612
2613   return g_slist_reverse (copy);
2614 }
2615
2616 static void
2617 attach_to_style (GtkIconSet      *icon_set,
2618                  GtkStyleContext *style_context)
2619 {
2620   GHashTable *table;
2621
2622   table = g_object_get_qdata (G_OBJECT (style_context),
2623                               g_quark_try_string ("gtk-style-icon-sets"));
2624
2625   if (table == NULL)
2626     {
2627       table = g_hash_table_new (NULL, NULL);
2628       g_object_set_qdata_full (G_OBJECT (style_context),
2629                                g_quark_from_static_string ("gtk-style-icon-sets"),
2630                                table,
2631                                style_dnotify);
2632     }
2633
2634   g_hash_table_insert (table, icon_set, icon_set);
2635 }
2636
2637 static void
2638 detach_from_style (GtkIconSet       *icon_set,
2639                    GtkStyleContext  *style_context)
2640 {
2641   GHashTable *table;
2642
2643   table = g_object_get_qdata (G_OBJECT (style_context),
2644                               g_quark_try_string ("gtk-style-icon-sets"));
2645
2646   if (table != NULL)
2647     g_hash_table_remove (table, icon_set);
2648 }
2649
2650 static void
2651 iconsets_foreach (gpointer key,
2652                   gpointer value,
2653                   gpointer user_data)
2654 {
2655   GtkIconSet *icon_set = key;
2656
2657   /* We only need to remove cache entries for the given style;
2658    * but that complicates things because in destroy notify
2659    * we don't know which style got destroyed, and 95% of the
2660    * time all cache entries will have the same style,
2661    * so this is faster anyway.
2662    */
2663
2664   clear_cache (icon_set, FALSE);
2665 }
2666
2667 static void
2668 style_dnotify (gpointer data)
2669 {
2670   GHashTable *table = data;
2671
2672   g_hash_table_foreach (table, iconsets_foreach, NULL);
2673
2674   g_hash_table_destroy (table);
2675 }
2676
2677 /* This allows the icon set to detect that its cache is out of date. */
2678 void
2679 _gtk_icon_set_invalidate_caches (void)
2680 {
2681   ++cache_serial;
2682 }
2683
2684 /**
2685  * _gtk_icon_factory_list_ids:
2686  *
2687  * Gets all known IDs stored in an existing icon factory.
2688  * The strings in the returned list aren't copied.
2689  * The list itself should be freed.
2690  *
2691  * Return value: List of ids in icon factories
2692  */
2693 GList*
2694 _gtk_icon_factory_list_ids (void)
2695 {
2696   GSList *tmp_list;
2697   GList *ids;
2698
2699   ids = NULL;
2700
2701   _gtk_icon_factory_ensure_default_icons ();
2702
2703   tmp_list = all_icon_factories;
2704   while (tmp_list != NULL)
2705     {
2706       GList *these_ids;
2707       GtkIconFactory *factory = GTK_ICON_FACTORY (tmp_list->data);
2708       GtkIconFactoryPrivate *priv = factory->priv;
2709
2710       these_ids = g_hash_table_get_keys (priv->icons);
2711
2712       ids = g_list_concat (ids, these_ids);
2713
2714       tmp_list = g_slist_next (tmp_list);
2715     }
2716
2717   return ids;
2718 }
2719
2720 typedef struct {
2721   GSList *sources;
2722   gboolean in_source;
2723
2724 } IconFactoryParserData;
2725
2726 typedef struct {
2727   gchar            *stock_id;
2728   gchar            *filename;
2729   gchar            *icon_name;
2730   GtkTextDirection  direction;
2731   GtkIconSize       size;
2732   GtkStateType      state;
2733 } IconSourceParserData;
2734
2735 static void
2736 icon_source_start_element (GMarkupParseContext  *context,
2737                            const gchar          *element_name,
2738                            const gchar         **names,
2739                            const gchar         **values,
2740                            gpointer              user_data,
2741                            GError              **error)
2742 {
2743   gint i;
2744   gchar *stock_id = NULL;
2745   gchar *filename = NULL;
2746   gchar *icon_name = NULL;
2747   gint size = -1;
2748   gint direction = -1;
2749   gint state = -1;
2750   IconFactoryParserData *parser_data;
2751   IconSourceParserData *source_data;
2752   gchar *error_msg;
2753   GQuark error_domain;
2754
2755   parser_data = (IconFactoryParserData*)user_data;
2756
2757   if (!parser_data->in_source)
2758     {
2759       if (strcmp (element_name, "sources") != 0)
2760         {
2761           error_msg = g_strdup_printf ("Unexpected element %s, expected <sources>", element_name);
2762           error_domain = GTK_BUILDER_ERROR_INVALID_TAG;
2763           goto error;
2764         }
2765       parser_data->in_source = TRUE;
2766       return;
2767     }
2768   else
2769     {
2770       if (strcmp (element_name, "source") != 0)
2771         {
2772           error_msg = g_strdup_printf ("Unexpected element %s, expected <source>", element_name);
2773           error_domain = GTK_BUILDER_ERROR_INVALID_TAG;
2774           goto error;
2775         }
2776     }
2777
2778   for (i = 0; names[i]; i++)
2779     {
2780       if (strcmp (names[i], "stock-id") == 0)
2781         stock_id = g_strdup (values[i]);
2782       else if (strcmp (names[i], "filename") == 0)
2783         filename = g_strdup (values[i]);
2784       else if (strcmp (names[i], "icon-name") == 0)
2785         icon_name = g_strdup (values[i]);
2786       else if (strcmp (names[i], "size") == 0)
2787         {
2788           if (!_gtk_builder_enum_from_string (GTK_TYPE_ICON_SIZE,
2789                                               values[i],
2790                                               &size,
2791                                               error))
2792             return;
2793         }
2794       else if (strcmp (names[i], "direction") == 0)
2795         {
2796           if (!_gtk_builder_enum_from_string (GTK_TYPE_TEXT_DIRECTION,
2797                                               values[i],
2798                                               &direction,
2799                                               error))
2800             return;
2801         }
2802       else if (strcmp (names[i], "state") == 0)
2803         {
2804           if (!_gtk_builder_enum_from_string (GTK_TYPE_STATE_TYPE,
2805                                               values[i],
2806                                               &state,
2807                                               error))
2808             return;
2809         }
2810       else
2811         {
2812           error_msg = g_strdup_printf ("'%s' is not a valid attribute of <%s>",
2813                                        names[i], "source");
2814           error_domain = GTK_BUILDER_ERROR_INVALID_ATTRIBUTE;
2815           goto error;
2816         }
2817     }
2818
2819   if (!stock_id)
2820     {
2821       error_msg = g_strdup_printf ("<source> requires a stock_id");
2822       error_domain = GTK_BUILDER_ERROR_MISSING_ATTRIBUTE;
2823       goto error;
2824     }
2825
2826   source_data = g_slice_new (IconSourceParserData);
2827   source_data->stock_id = stock_id;
2828   source_data->filename = filename;
2829   source_data->icon_name = icon_name;
2830   source_data->size = size;
2831   source_data->direction = direction;
2832   source_data->state = state;
2833
2834   parser_data->sources = g_slist_prepend (parser_data->sources, source_data);
2835   return;
2836
2837  error:
2838   {
2839     gchar *tmp;
2840     gint line_number, char_number;
2841
2842     g_markup_parse_context_get_position (context, &line_number, &char_number);
2843
2844     tmp = g_strdup_printf ("%s:%d:%d %s", "input",
2845                            line_number, char_number, error_msg);
2846     g_set_error_literal (error, GTK_BUILDER_ERROR, error_domain, tmp);
2847     g_free (tmp);
2848     g_free (stock_id);
2849     g_free (filename);
2850     g_free (icon_name);
2851     return;
2852   }
2853 }
2854
2855 static const GMarkupParser icon_source_parser =
2856   {
2857     icon_source_start_element,
2858   };
2859
2860 static gboolean
2861 gtk_icon_factory_buildable_custom_tag_start (GtkBuildable     *buildable,
2862                                              GtkBuilder       *builder,
2863                                              GObject          *child,
2864                                              const gchar      *tagname,
2865                                              GMarkupParser    *parser,
2866                                              gpointer         *data)
2867 {
2868   g_assert (buildable);
2869
2870   if (strcmp (tagname, "sources") == 0)
2871     {
2872       IconFactoryParserData *parser_data;
2873
2874       parser_data = g_slice_new0 (IconFactoryParserData);
2875       *parser = icon_source_parser;
2876       *data = parser_data;
2877       return TRUE;
2878     }
2879   return FALSE;
2880 }
2881
2882 static void
2883 gtk_icon_factory_buildable_custom_tag_end (GtkBuildable *buildable,
2884                                            GtkBuilder   *builder,
2885                                            GObject      *child,
2886                                            const gchar  *tagname,
2887                                            gpointer     *user_data)
2888 {
2889   GtkIconFactory *icon_factory;
2890
2891   icon_factory = GTK_ICON_FACTORY (buildable);
2892
2893   if (strcmp (tagname, "sources") == 0)
2894     {
2895       IconFactoryParserData *parser_data;
2896       GtkIconSource *icon_source;
2897       GtkIconSet *icon_set;
2898       GSList *l;
2899
2900       parser_data = (IconFactoryParserData*)user_data;
2901
2902       for (l = parser_data->sources; l; l = l->next)
2903         {
2904           IconSourceParserData *source_data = l->data;
2905
2906           icon_set = gtk_icon_factory_lookup (icon_factory, source_data->stock_id);
2907           if (!icon_set)
2908             {
2909               icon_set = gtk_icon_set_new ();
2910               gtk_icon_factory_add (icon_factory, source_data->stock_id, icon_set);
2911               gtk_icon_set_unref (icon_set);
2912             }
2913
2914           icon_source = gtk_icon_source_new ();
2915
2916           if (source_data->filename)
2917             {
2918               gchar *filename;
2919               filename = _gtk_builder_get_absolute_filename (builder, source_data->filename);
2920               gtk_icon_source_set_filename (icon_source, filename);
2921               g_free (filename);
2922             }
2923           if (source_data->icon_name)
2924             gtk_icon_source_set_icon_name (icon_source, source_data->icon_name);
2925           if (source_data->size != -1)
2926             {
2927               gtk_icon_source_set_size (icon_source, source_data->size);
2928               gtk_icon_source_set_size_wildcarded (icon_source, FALSE);
2929             }
2930           if (source_data->direction != -1)
2931             {
2932               gtk_icon_source_set_direction (icon_source, source_data->direction);
2933               gtk_icon_source_set_direction_wildcarded (icon_source, FALSE);
2934             }
2935           if (source_data->state != -1)
2936             {
2937               gtk_icon_source_set_state (icon_source, source_data->state);
2938               gtk_icon_source_set_state_wildcarded (icon_source, FALSE);
2939             }
2940
2941           /* Inline source_add() to avoid creating a copy */
2942           g_assert (icon_source->type != GTK_ICON_SOURCE_EMPTY);
2943           icon_set->sources = g_slist_insert_sorted (icon_set->sources,
2944                                                      icon_source,
2945                                                      icon_source_compare);
2946
2947           g_free (source_data->stock_id);
2948           g_free (source_data->filename);
2949           g_free (source_data->icon_name);
2950           g_slice_free (IconSourceParserData, source_data);
2951         }
2952       g_slist_free (parser_data->sources);
2953       g_slice_free (IconFactoryParserData, parser_data);
2954
2955       /* TODO: Add an attribute/tag to prevent this.
2956        * Usually it's the right thing to do though.
2957        */
2958       gtk_icon_factory_add_default (icon_factory);
2959     }
2960 }