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