]> Pileus Git - ~andy/gtk/blob - gtk/gtkicontheme.c
build: Remove now-unused GTK_DISABLE_DEPRECATED undefs
[~andy/gtk] / gtk / gtkicontheme.c
1 /* GtkIconTheme - a loader for icon themes
2  * gtk-icon-theme.c Copyright (C) 2002, 2003 Red Hat, Inc.
3  *
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, see <http://www.gnu.org/licenses/>.
16  */
17
18 #include "config.h"
19
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #ifdef HAVE_UNISTD_H
23 #include <unistd.h>
24 #endif
25 #include <string.h>
26 #include <stdlib.h>
27 #include <glib.h>
28 #include <glib/gstdio.h>
29
30 #ifdef G_OS_WIN32
31 #ifndef S_ISDIR
32 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
33 #endif
34 #define WIN32_MEAN_AND_LEAN
35 #include <windows.h>
36 #include "win32/gdkwin32.h"
37 #endif /* G_OS_WIN32 */
38
39 #include "gtkicontheme.h"
40 #include "gtkdebug.h"
41 #include "gtkiconfactory.h"
42 #include "gtkiconcache.h"
43 #include "gtkbuiltincache.h"
44 #include "gtkintl.h"
45 #include "gtkmain.h"
46 #include "gtknumerableiconprivate.h"
47 #include "gtksettings.h"
48 #include "gtkprivate.h"
49
50 #undef GDK_DEPRECATED
51 #undef GDK_DEPRECATED_FOR
52 #define GDK_DEPRECATED
53 #define GDK_DEPRECATED_FOR(f)
54
55 #include "deprecated/gtkstyle.h"
56
57
58 /**
59  * SECTION:gtkicontheme
60  * @Short_description: Looking up icons by name
61  * @Title: GtkIconTheme
62  *
63  * #GtkIconTheme provides a facility for looking up icons by name
64  * and size. The main reason for using a name rather than simply
65  * providing a filename is to allow different icons to be used
66  * depending on what <firstterm>icon theme</firstterm> is selected
67  * by the user. The operation of icon themes on Linux and Unix
68  * follows the <ulink
69  * url="http://www.freedesktop.org/Standards/icon-theme-spec">Icon
70  * Theme Specification</ulink>. There is a default icon theme,
71  * named <literal>hicolor</literal> where applications should install
72  * their icons, but more additional application themes can be
73  * installed as operating system vendors and users choose.
74  *
75  * Named icons are similar to the <xref linkend="gtk3-Themeable-Stock-Images"/>
76  * facility, and the distinction between the two may be a bit confusing.
77  * A few things to keep in mind:
78  * <itemizedlist>
79  * <listitem>
80  * Stock images usually are used in conjunction with
81  * <xref linkend="gtk3-Stock-Items"/>, such as %GTK_STOCK_OK or
82  * %GTK_STOCK_OPEN. Named icons are easier to set up and therefore
83  * are more useful for new icons that an application wants to
84  * add, such as application icons or window icons.
85  * </listitem>
86  * <listitem>
87  * Stock images can only be loaded at the symbolic sizes defined
88  * by the #GtkIconSize enumeration, or by custom sizes defined
89  * by gtk_icon_size_register(), while named icons are more flexible
90  * and any pixel size can be specified.
91  * </listitem>
92  * <listitem>
93  * Because stock images are closely tied to stock items, and thus
94  * to actions in the user interface, stock images may come in
95  * multiple variants for different widget states or writing
96  * directions.
97  * </listitem>
98  * </itemizedlist>
99  * A good rule of thumb is that if there is a stock image for what
100  * you want to use, use it, otherwise use a named icon. It turns
101  * out that internally stock images are generally defined in
102  * terms of one or more named icons. (An example of the
103  * more than one case is icons that depend on writing direction;
104  * %GTK_STOCK_GO_FORWARD uses the two themed icons
105  * "gtk-stock-go-forward-ltr" and "gtk-stock-go-forward-rtl".)
106  *
107  * In many cases, named themes are used indirectly, via #GtkImage
108  * or stock items, rather than directly, but looking up icons
109  * directly is also simple. The #GtkIconTheme object acts
110  * as a database of all the icons in the current theme. You
111  * can create new #GtkIconTheme objects, but its much more
112  * efficient to use the standard icon theme for the #GdkScreen
113  * so that the icon information is shared with other people
114  * looking up icons. In the case where the default screen is
115  * being used, looking up an icon can be as simple as:
116  * <informalexample>
117  * <programlisting>
118  * GError *error = NULL;
119  * GtkIconTheme *icon_theme;
120  * GdkPixbuf *pixbuf;
121  *
122  * icon_theme = gtk_icon_theme_get_default ();
123  * pixbuf = gtk_icon_theme_load_icon (icon_theme,
124  *                                    "my-icon-name", // icon name
125  *                                    48, // size
126  *                                    0,  // flags
127  *                                    &error);
128  * if (!pixbuf)
129  *   {
130  *     g_warning ("Couldn't load icon: &percnt;s", error->message);
131  *     g_error_free (error);
132  *   }
133  * else
134  *   {
135  *     // Use the pixbuf
136  *     g_object_unref (pixbuf);
137  *   }
138  * </programlisting>
139  * </informalexample>
140  */
141
142
143 #define DEFAULT_THEME_NAME "hicolor"
144
145 typedef enum
146 {
147   ICON_THEME_DIR_FIXED,  
148   ICON_THEME_DIR_SCALABLE,  
149   ICON_THEME_DIR_THRESHOLD,
150   ICON_THEME_DIR_UNTHEMED
151 } IconThemeDirType;
152
153 /* In reverse search order: */
154 typedef enum
155 {
156   ICON_SUFFIX_NONE = 0,
157   ICON_SUFFIX_XPM = 1 << 0,
158   ICON_SUFFIX_SVG = 1 << 1,
159   ICON_SUFFIX_PNG = 1 << 2,
160   HAS_ICON_FILE = 1 << 3
161 } IconSuffix;
162
163
164 struct _GtkIconThemePrivate
165 {
166   gchar *current_theme;
167   gchar *fallback_theme;
168   gchar **search_path;
169   gint search_path_len;
170
171   guint custom_theme        : 1;
172   guint is_screen_singleton : 1;
173   guint pixbuf_supports_svg : 1;
174   guint themes_valid        : 1;
175   guint check_reload        : 1;
176   guint loading_themes      : 1;
177
178   /* A list of all the themes needed to look up icons.
179    * In search order, without duplicates
180    */
181   GList *themes;
182   GHashTable *unthemed_icons;
183
184   /* Note: The keys of this hashtable are owned by the
185    * themedir and unthemed hashtables.
186    */
187   GHashTable *all_icons;
188
189   /* GdkScreen for the icon theme (may be NULL)
190    */
191   GdkScreen *screen;
192
193   /* time when we last stat:ed for theme changes */
194   glong last_stat_time;
195   GList *dir_mtimes;
196
197   gulong reset_styles_idle;
198 };
199
200 struct _GtkIconInfo
201 {
202   /* Information about the source
203    */
204   gchar *filename;
205   GLoadableIcon *loadable;
206   GSList *emblem_infos;
207
208   /* Cache pixbuf (if there is any) */
209   GdkPixbuf *cache_pixbuf;
210
211   GtkIconData *data;
212
213   /* Information about the directory where
214    * the source was found
215    */
216   IconThemeDirType dir_type;
217   gint dir_size;
218   gint threshold;
219
220   /* Parameters influencing the scaled icon
221    */
222   gint desired_size;
223   guint raw_coordinates : 1;
224   guint forced_size     : 1;
225   guint emblems_applied : 1;
226
227   guint ref_count;
228
229   /* Cached information if we go ahead and try to load
230    * the icon.
231    */
232   GdkPixbuf *pixbuf;
233   GError *load_error;
234   gdouble scale;
235 };
236
237 typedef struct
238 {
239   char *name;
240   char *display_name;
241   char *comment;
242   char *example;
243
244   /* In search order */
245   GList *dirs;
246 } IconTheme;
247
248 typedef struct
249 {
250   IconThemeDirType type;
251   GQuark context;
252
253   int size;
254   int min_size;
255   int max_size;
256   int threshold;
257
258   char *dir;
259   char *subdir;
260   int subdir_index;
261   
262   GtkIconCache *cache;
263   
264   GHashTable *icons;
265   GHashTable *icon_data;
266 } IconThemeDir;
267
268 typedef struct
269 {
270   char *svg_filename;
271   char *no_svg_filename;
272 } UnthemedIcon;
273
274 typedef struct
275 {
276   gint size;
277   GdkPixbuf *pixbuf;
278 } BuiltinIcon;
279
280 typedef struct 
281 {
282   char *dir;
283   time_t mtime; /* 0 == not existing or not a dir */
284
285   GtkIconCache *cache;
286 } IconThemeDirMtime;
287
288 static void  gtk_icon_theme_finalize   (GObject              *object);
289 static void  theme_dir_destroy         (IconThemeDir         *dir);
290
291 static void         theme_destroy     (IconTheme        *theme);
292 static GtkIconInfo *theme_lookup_icon (IconTheme        *theme,
293                                        const char       *icon_name,
294                                        int               size,
295                                        gboolean          allow_svg,
296                                        gboolean          use_default_icons);
297 static void         theme_list_icons  (IconTheme        *theme,
298                                        GHashTable       *icons,
299                                        GQuark            context);
300 static void         theme_list_contexts  (IconTheme        *theme,
301                                           GHashTable       *contexts);
302 static void         theme_subdir_load (GtkIconTheme     *icon_theme,
303                                        IconTheme        *theme,
304                                        GKeyFile         *theme_file,
305                                        char             *subdir);
306 static void         do_theme_change   (GtkIconTheme     *icon_theme);
307
308 static void     blow_themes               (GtkIconTheme    *icon_themes);
309 static gboolean rescan_themes             (GtkIconTheme    *icon_themes);
310
311 static void  icon_data_free            (GtkIconData     *icon_data);
312 static void load_icon_data             (IconThemeDir    *dir,
313                                         const char      *path,
314                                         const char      *name);
315
316 static IconSuffix theme_dir_get_icon_suffix (IconThemeDir *dir,
317                                              const gchar  *icon_name,
318                                              gboolean     *has_icon_file);
319
320
321 static GtkIconInfo *icon_info_new             (void);
322 static GtkIconInfo *icon_info_new_builtin     (BuiltinIcon *icon);
323
324 static IconSuffix suffix_from_name (const char *name);
325
326 static BuiltinIcon *find_builtin_icon (const gchar *icon_name,
327                                        gint        size,
328                                        gint        *min_difference_p,
329                                        gboolean    *has_larger_p);
330
331 static guint signal_changed = 0;
332
333 static GHashTable *icon_theme_builtin_icons;
334
335 /* also used in gtkiconfactory.c */
336 GtkIconCache *_builtin_cache = NULL;
337 static GList *builtin_dirs = NULL;
338
339 G_DEFINE_TYPE (GtkIconTheme, gtk_icon_theme, G_TYPE_OBJECT)
340
341 /**
342  * gtk_icon_theme_new:
343  * 
344  * Creates a new icon theme object. Icon theme objects are used
345  * to lookup up an icon by name in a particular icon theme.
346  * Usually, you'll want to use gtk_icon_theme_get_default()
347  * or gtk_icon_theme_get_for_screen() rather than creating
348  * a new icon theme object for scratch.
349  * 
350  * Return value: the newly created #GtkIconTheme object.
351  *
352  * Since: 2.4
353  **/
354 GtkIconTheme *
355 gtk_icon_theme_new (void)
356 {
357   return g_object_new (GTK_TYPE_ICON_THEME, NULL);
358 }
359
360 /**
361  * gtk_icon_theme_get_default:
362  * 
363  * Gets the icon theme for the default screen. See
364  * gtk_icon_theme_get_for_screen().
365  *
366  * Return value: (transfer none): A unique #GtkIconTheme associated with
367  *  the default screen. This icon theme is associated with
368  *  the screen and can be used as long as the screen
369  *  is open. Do not ref or unref it.
370  *
371  * Since: 2.4
372  **/
373 GtkIconTheme *
374 gtk_icon_theme_get_default (void)
375 {
376   return gtk_icon_theme_get_for_screen (gdk_screen_get_default ());
377 }
378
379 /**
380  * gtk_icon_theme_get_for_screen:
381  * @screen: a #GdkScreen
382  * 
383  * Gets the icon theme object associated with @screen; if this
384  * function has not previously been called for the given
385  * screen, a new icon theme object will be created and
386  * associated with the screen. Icon theme objects are
387  * fairly expensive to create, so using this function
388  * is usually a better choice than calling than gtk_icon_theme_new()
389  * and setting the screen yourself; by using this function
390  * a single icon theme object will be shared between users.
391  *
392  * Return value: (transfer none): A unique #GtkIconTheme associated with
393  *  the given screen. This icon theme is associated with
394  *  the screen and can be used as long as the screen
395  *  is open. Do not ref or unref it.
396  *
397  * Since: 2.4
398  **/
399 GtkIconTheme *
400 gtk_icon_theme_get_for_screen (GdkScreen *screen)
401 {
402   GtkIconTheme *icon_theme;
403
404   g_return_val_if_fail (GDK_IS_SCREEN (screen), NULL);
405
406   icon_theme = g_object_get_data (G_OBJECT (screen), "gtk-icon-theme");
407   if (!icon_theme)
408     {
409       GtkIconThemePrivate *priv;
410
411       icon_theme = gtk_icon_theme_new ();
412       gtk_icon_theme_set_screen (icon_theme, screen);
413
414       priv = icon_theme->priv;
415       priv->is_screen_singleton = TRUE;
416
417       g_object_set_data (G_OBJECT (screen), I_("gtk-icon-theme"), icon_theme);
418     }
419
420   return icon_theme;
421 }
422
423 static void
424 gtk_icon_theme_class_init (GtkIconThemeClass *klass)
425 {
426   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
427
428   gobject_class->finalize = gtk_icon_theme_finalize;
429
430 /**
431  * GtkIconTheme::changed:
432  * @icon_theme: the icon theme
433  * 
434  * Emitted when the current icon theme is switched or GTK+ detects
435  * that a change has occurred in the contents of the current
436  * icon theme.
437  **/
438   signal_changed = g_signal_new (I_("changed"),
439                                  G_TYPE_FROM_CLASS (klass),
440                                  G_SIGNAL_RUN_LAST,
441                                  G_STRUCT_OFFSET (GtkIconThemeClass, changed),
442                                  NULL, NULL,
443                                  g_cclosure_marshal_VOID__VOID,
444                                  G_TYPE_NONE, 0);
445
446   g_type_class_add_private (klass, sizeof (GtkIconThemePrivate));
447 }
448
449
450 /* Callback when the display that the icon theme is attached to
451  * is closed; unset the screen, and if it's the unique theme
452  * for the screen, drop the reference
453  */
454 static void
455 display_closed (GdkDisplay   *display,
456                 gboolean      is_error,
457                 GtkIconTheme *icon_theme)
458 {
459   GtkIconThemePrivate *priv = icon_theme->priv;
460   GdkScreen *screen = priv->screen;
461   gboolean was_screen_singleton = priv->is_screen_singleton;
462
463   if (was_screen_singleton)
464     {
465       g_object_set_data (G_OBJECT (screen), I_("gtk-icon-theme"), NULL);
466       priv->is_screen_singleton = FALSE;
467     }
468
469   gtk_icon_theme_set_screen (icon_theme, NULL);
470
471   if (was_screen_singleton)
472     {
473       g_object_unref (icon_theme);
474     }
475 }
476
477 static void
478 update_current_theme (GtkIconTheme *icon_theme)
479 {
480 #define theme_changed(_old, _new) \
481   ((_old && !_new) || (!_old && _new) || \
482    (_old && _new && strcmp (_old, _new) != 0))
483   GtkIconThemePrivate *priv = icon_theme->priv;
484
485   if (!priv->custom_theme)
486     {
487       gchar *theme = NULL;
488       gchar *fallback_theme = NULL;
489       gboolean changed = FALSE;
490
491       if (priv->screen)
492         {
493           GtkSettings *settings = gtk_settings_get_for_screen (priv->screen);
494           g_object_get (settings, 
495                         "gtk-icon-theme-name", &theme, 
496                         "gtk-fallback-icon-theme", &fallback_theme, NULL);
497         }
498
499       /* ensure that the current theme (even when just the default)
500        * is searched before any fallback theme
501        */
502       if (!theme && fallback_theme)
503         theme = g_strdup (DEFAULT_THEME_NAME);
504
505       if (theme_changed (priv->current_theme, theme))
506         {
507           g_free (priv->current_theme);
508           priv->current_theme = theme;
509           changed = TRUE;
510         }
511       else
512         g_free (theme);
513
514       if (theme_changed (priv->fallback_theme, fallback_theme))
515         {
516           g_free (priv->fallback_theme);
517           priv->fallback_theme = fallback_theme;
518           changed = TRUE;
519         }
520       else
521         g_free (fallback_theme);
522
523       if (changed)
524         do_theme_change (icon_theme);
525     }
526 #undef theme_changed
527 }
528
529 /* Callback when the icon theme GtkSetting changes
530  */
531 static void
532 theme_changed (GtkSettings  *settings,
533                GParamSpec   *pspec,
534                GtkIconTheme *icon_theme)
535 {
536   update_current_theme (icon_theme);
537 }
538
539 static void
540 unset_screen (GtkIconTheme *icon_theme)
541 {
542   GtkIconThemePrivate *priv = icon_theme->priv;
543   GtkSettings *settings;
544   GdkDisplay *display;
545   
546   if (priv->screen)
547     {
548       settings = gtk_settings_get_for_screen (priv->screen);
549       display = gdk_screen_get_display (priv->screen);
550       
551       g_signal_handlers_disconnect_by_func (display,
552                                             (gpointer) display_closed,
553                                             icon_theme);
554       g_signal_handlers_disconnect_by_func (settings,
555                                             (gpointer) theme_changed,
556                                             icon_theme);
557
558       priv->screen = NULL;
559     }
560 }
561
562 /**
563  * gtk_icon_theme_set_screen:
564  * @icon_theme: a #GtkIconTheme
565  * @screen: a #GdkScreen
566  * 
567  * Sets the screen for an icon theme; the screen is used
568  * to track the user's currently configured icon theme,
569  * which might be different for different screens.
570  *
571  * Since: 2.4
572  **/
573 void
574 gtk_icon_theme_set_screen (GtkIconTheme *icon_theme,
575                            GdkScreen    *screen)
576 {
577   GtkIconThemePrivate *priv;
578   GtkSettings *settings;
579   GdkDisplay *display;
580
581   g_return_if_fail (GTK_ICON_THEME (icon_theme));
582   g_return_if_fail (screen == NULL || GDK_IS_SCREEN (screen));
583
584   priv = icon_theme->priv;
585
586   unset_screen (icon_theme);
587   
588   if (screen)
589     {
590       display = gdk_screen_get_display (screen);
591       settings = gtk_settings_get_for_screen (screen);
592       
593       priv->screen = screen;
594       
595       g_signal_connect (display, "closed",
596                         G_CALLBACK (display_closed), icon_theme);
597       g_signal_connect (settings, "notify::gtk-icon-theme-name",
598                         G_CALLBACK (theme_changed), icon_theme);
599       g_signal_connect (settings, "notify::gtk-fallback-icon-theme-name",
600                         G_CALLBACK (theme_changed), icon_theme);
601     }
602
603   update_current_theme (icon_theme);
604 }
605
606 /* Checks whether a loader for SVG files has been registered
607  * with GdkPixbuf.
608  */
609 static gboolean
610 pixbuf_supports_svg (void)
611 {
612   GSList *formats;
613   GSList *tmp_list;
614   static gint found_svg = -1;
615
616   if (found_svg != -1)
617     return found_svg;
618
619   formats = gdk_pixbuf_get_formats ();
620
621   found_svg = FALSE; 
622   for (tmp_list = formats; tmp_list && !found_svg; tmp_list = tmp_list->next)
623     {
624       gchar **mime_types = gdk_pixbuf_format_get_mime_types (tmp_list->data);
625       gchar **mime_type;
626       
627       for (mime_type = mime_types; *mime_type && !found_svg; mime_type++)
628         {
629           if (strcmp (*mime_type, "image/svg") == 0)
630             found_svg = TRUE;
631         }
632
633       g_strfreev (mime_types);
634     }
635
636   g_slist_free (formats);
637   
638   return found_svg;
639 }
640
641 static void
642 gtk_icon_theme_init (GtkIconTheme *icon_theme)
643 {
644   GtkIconThemePrivate *priv;
645   const gchar * const *xdg_data_dirs;
646   int i, j;
647
648   priv = G_TYPE_INSTANCE_GET_PRIVATE (icon_theme,
649                                       GTK_TYPE_ICON_THEME,
650                                       GtkIconThemePrivate);
651   icon_theme->priv = priv;
652
653   priv->custom_theme = FALSE;
654
655   xdg_data_dirs = g_get_system_data_dirs ();
656   for (i = 0; xdg_data_dirs[i]; i++) ;
657
658   priv->search_path_len = 2 * i + 2;
659   
660   priv->search_path = g_new (char *, priv->search_path_len);
661   
662   i = 0;
663   priv->search_path[i++] = g_build_filename (g_get_user_data_dir (), "icons", NULL);
664   priv->search_path[i++] = g_build_filename (g_get_home_dir (), ".icons", NULL);
665   
666   for (j = 0; xdg_data_dirs[j]; j++) 
667     priv->search_path[i++] = g_build_filename (xdg_data_dirs[j], "icons", NULL);
668
669   for (j = 0; xdg_data_dirs[j]; j++) 
670     priv->search_path[i++] = g_build_filename (xdg_data_dirs[j], "pixmaps", NULL);
671
672   priv->themes_valid = FALSE;
673   priv->themes = NULL;
674   priv->unthemed_icons = NULL;
675   
676   priv->pixbuf_supports_svg = pixbuf_supports_svg ();
677 }
678
679 static void
680 free_dir_mtime (IconThemeDirMtime *dir_mtime)
681 {
682   if (dir_mtime->cache)
683     _gtk_icon_cache_unref (dir_mtime->cache);
684
685   g_free (dir_mtime->dir);
686   g_slice_free (IconThemeDirMtime, dir_mtime);
687
688 }
689
690 static gboolean
691 reset_styles_idle (gpointer user_data)
692 {
693   GtkIconTheme *icon_theme;
694   GtkIconThemePrivate *priv;
695
696   icon_theme = GTK_ICON_THEME (user_data);
697   priv = icon_theme->priv;
698
699   if (priv->screen && priv->is_screen_singleton)
700     gtk_style_context_reset_widgets (priv->screen);
701
702   priv->reset_styles_idle = 0;
703
704   return FALSE;
705 }
706
707 static void
708 do_theme_change (GtkIconTheme *icon_theme)
709 {
710   GtkIconThemePrivate *priv = icon_theme->priv;
711
712   if (!priv->themes_valid)
713     return;
714   
715   GTK_NOTE (ICONTHEME, 
716             g_print ("change to icon theme \"%s\"\n", priv->current_theme));
717   blow_themes (icon_theme);
718   g_signal_emit (icon_theme, signal_changed, 0);
719
720   if (!priv->reset_styles_idle)
721     priv->reset_styles_idle = 
722       gdk_threads_add_idle_full (GTK_PRIORITY_RESIZE - 2, 
723                        reset_styles_idle, icon_theme, NULL);
724 }
725
726 static void
727 blow_themes (GtkIconTheme *icon_theme)
728 {
729   GtkIconThemePrivate *priv = icon_theme->priv;
730   
731   if (priv->themes_valid)
732     {
733       g_hash_table_destroy (priv->all_icons);
734       g_list_free_full (priv->themes, (GDestroyNotify) theme_destroy);
735       g_list_free_full (priv->dir_mtimes, (GDestroyNotify) free_dir_mtime);
736       g_hash_table_destroy (priv->unthemed_icons);
737     }
738   priv->themes = NULL;
739   priv->unthemed_icons = NULL;
740   priv->dir_mtimes = NULL;
741   priv->all_icons = NULL;
742   priv->themes_valid = FALSE;
743 }
744
745 static void
746 gtk_icon_theme_finalize (GObject *object)
747 {
748   GtkIconTheme *icon_theme;
749   GtkIconThemePrivate *priv;
750   int i;
751
752   icon_theme = GTK_ICON_THEME (object);
753   priv = icon_theme->priv;
754
755   if (priv->reset_styles_idle)
756     {
757       g_source_remove (priv->reset_styles_idle);
758       priv->reset_styles_idle = 0;
759     }
760
761   unset_screen (icon_theme);
762
763   g_free (priv->current_theme);
764   priv->current_theme = NULL;
765
766   for (i = 0; i < priv->search_path_len; i++)
767     g_free (priv->search_path[i]);
768
769   g_free (priv->search_path);
770   priv->search_path = NULL;
771
772   blow_themes (icon_theme);
773
774   G_OBJECT_CLASS (gtk_icon_theme_parent_class)->finalize (object);  
775 }
776
777 /**
778  * gtk_icon_theme_set_search_path:
779  * @icon_theme: a #GtkIconTheme
780  * @path: (array length=n_elements) (element-type filename): array of
781  *     directories that are searched for icon themes
782  * @n_elements: number of elements in @path.
783  * 
784  * Sets the search path for the icon theme object. When looking
785  * for an icon theme, GTK+ will search for a subdirectory of
786  * one or more of the directories in @path with the same name
787  * as the icon theme. (Themes from multiple of the path elements
788  * are combined to allow themes to be extended by adding icons
789  * in the user's home directory.)
790  *
791  * In addition if an icon found isn't found either in the current
792  * icon theme or the default icon theme, and an image file with
793  * the right name is found directly in one of the elements of
794  * @path, then that image will be used for the icon name.
795  * (This is legacy feature, and new icons should be put
796  * into the default icon theme, which is called DEFAULT_THEME_NAME,
797  * rather than directly on the icon path.)
798  *
799  * Since: 2.4
800  **/
801 void
802 gtk_icon_theme_set_search_path (GtkIconTheme *icon_theme,
803                                 const gchar  *path[],
804                                 gint          n_elements)
805 {
806   GtkIconThemePrivate *priv;
807   gint i;
808
809   g_return_if_fail (GTK_IS_ICON_THEME (icon_theme));
810
811   priv = icon_theme->priv;
812   for (i = 0; i < priv->search_path_len; i++)
813     g_free (priv->search_path[i]);
814
815   g_free (priv->search_path);
816
817   priv->search_path = g_new (gchar *, n_elements);
818   priv->search_path_len = n_elements;
819
820   for (i = 0; i < priv->search_path_len; i++)
821     priv->search_path[i] = g_strdup (path[i]);
822
823   do_theme_change (icon_theme);
824 }
825
826
827 /**
828  * gtk_icon_theme_get_search_path:
829  * @icon_theme: a #GtkIconTheme
830  * @path: (allow-none) (array length=n_elements) (element-type filename) (out):
831  *     location to store a list of icon theme path directories or %NULL.
832  *     The stored value should be freed with g_strfreev().
833  * @n_elements: location to store number of elements in @path, or %NULL
834  *
835  * Gets the current search path. See gtk_icon_theme_set_search_path().
836  *
837  * Since: 2.4
838  */
839 void
840 gtk_icon_theme_get_search_path (GtkIconTheme  *icon_theme,
841                                 gchar        **path[],
842                                 gint          *n_elements)
843 {
844   GtkIconThemePrivate *priv;
845   int i;
846
847   g_return_if_fail (GTK_IS_ICON_THEME (icon_theme));
848
849   priv = icon_theme->priv;
850
851   if (n_elements)
852     *n_elements = priv->search_path_len;
853   
854   if (path)
855     {
856       *path = g_new (gchar *, priv->search_path_len + 1);
857       for (i = 0; i < priv->search_path_len; i++)
858         (*path)[i] = g_strdup (priv->search_path[i]);
859       (*path)[i] = NULL;
860     }
861 }
862
863 /**
864  * gtk_icon_theme_append_search_path:
865  * @icon_theme: a #GtkIconTheme
866  * @path: (type filename): directory name to append to the icon path
867  * 
868  * Appends a directory to the search path. 
869  * See gtk_icon_theme_set_search_path(). 
870  *
871  * Since: 2.4
872  **/
873 void
874 gtk_icon_theme_append_search_path (GtkIconTheme *icon_theme,
875                                    const gchar  *path)
876 {
877   GtkIconThemePrivate *priv;
878
879   g_return_if_fail (GTK_IS_ICON_THEME (icon_theme));
880   g_return_if_fail (path != NULL);
881
882   priv = icon_theme->priv;
883   
884   priv->search_path_len++;
885
886   priv->search_path = g_renew (gchar *, priv->search_path, priv->search_path_len);
887   priv->search_path[priv->search_path_len-1] = g_strdup (path);
888
889   do_theme_change (icon_theme);
890 }
891
892 /**
893  * gtk_icon_theme_prepend_search_path:
894  * @icon_theme: a #GtkIconTheme
895  * @path: (type filename): directory name to prepend to the icon path
896  * 
897  * Prepends a directory to the search path. 
898  * See gtk_icon_theme_set_search_path().
899  *
900  * Since: 2.4
901  **/
902 void
903 gtk_icon_theme_prepend_search_path (GtkIconTheme *icon_theme,
904                                     const gchar  *path)
905 {
906   GtkIconThemePrivate *priv;
907   int i;
908
909   g_return_if_fail (GTK_IS_ICON_THEME (icon_theme));
910   g_return_if_fail (path != NULL);
911
912   priv = icon_theme->priv;
913   
914   priv->search_path_len++;
915   priv->search_path = g_renew (gchar *, priv->search_path, priv->search_path_len);
916
917   for (i = priv->search_path_len - 1; i > 0; i--)
918     priv->search_path[i] = priv->search_path[i - 1];
919   
920   priv->search_path[0] = g_strdup (path);
921
922   do_theme_change (icon_theme);
923 }
924
925 /**
926  * gtk_icon_theme_set_custom_theme:
927  * @icon_theme: a #GtkIconTheme
928  * @theme_name: (allow-none): name of icon theme to use instead of
929  *   configured theme, or %NULL to unset a previously set custom theme
930  * 
931  * Sets the name of the icon theme that the #GtkIconTheme object uses
932  * overriding system configuration. This function cannot be called
933  * on the icon theme objects returned from gtk_icon_theme_get_default()
934  * and gtk_icon_theme_get_for_screen().
935  *
936  * Since: 2.4
937  **/
938 void
939 gtk_icon_theme_set_custom_theme (GtkIconTheme *icon_theme,
940                                  const gchar  *theme_name)
941 {
942   GtkIconThemePrivate *priv;
943
944   g_return_if_fail (GTK_IS_ICON_THEME (icon_theme));
945
946   priv = icon_theme->priv;
947
948   g_return_if_fail (!priv->is_screen_singleton);
949   
950   if (theme_name != NULL)
951     {
952       priv->custom_theme = TRUE;
953       if (!priv->current_theme || strcmp (theme_name, priv->current_theme) != 0)
954         {
955           g_free (priv->current_theme);
956           priv->current_theme = g_strdup (theme_name);
957
958           do_theme_change (icon_theme);
959         }
960     }
961   else
962     {
963       if (priv->custom_theme)
964         {
965           priv->custom_theme = FALSE;
966
967           update_current_theme (icon_theme);
968         }
969     }
970 }
971
972 static void
973 insert_theme (GtkIconTheme *icon_theme, const char *theme_name)
974 {
975   int i;
976   GList *l;
977   char **dirs;
978   char **themes;
979   GtkIconThemePrivate *priv;
980   IconTheme *theme = NULL;
981   char *path;
982   GKeyFile *theme_file;
983   GError *error = NULL;
984   IconThemeDirMtime *dir_mtime;
985   GStatBuf stat_buf;
986   
987   priv = icon_theme->priv;
988
989   for (l = priv->themes; l != NULL; l = l->next)
990     {
991       theme = l->data;
992       if (strcmp (theme->name, theme_name) == 0)
993         return;
994     }
995   
996   for (i = 0; i < priv->search_path_len; i++)
997     {
998       path = g_build_filename (priv->search_path[i],
999                                theme_name,
1000                                NULL);
1001       dir_mtime = g_slice_new (IconThemeDirMtime);
1002       dir_mtime->cache = NULL;
1003       dir_mtime->dir = path;
1004       if (g_stat (path, &stat_buf) == 0 && S_ISDIR (stat_buf.st_mode))
1005         dir_mtime->mtime = stat_buf.st_mtime;
1006       else
1007         dir_mtime->mtime = 0;
1008
1009       priv->dir_mtimes = g_list_prepend (priv->dir_mtimes, dir_mtime);
1010     }
1011   priv->dir_mtimes = g_list_reverse (priv->dir_mtimes);
1012
1013   theme_file = NULL;
1014   for (i = 0; i < priv->search_path_len && !theme_file; i++)
1015     {
1016       path = g_build_filename (priv->search_path[i],
1017                                theme_name,
1018                                "index.theme",
1019                                NULL);
1020       if (g_file_test (path, G_FILE_TEST_IS_REGULAR)) 
1021         {
1022           theme_file = g_key_file_new ();
1023           g_key_file_set_list_separator (theme_file, ',');
1024           g_key_file_load_from_file (theme_file, path, 0, &error);
1025           if (error)
1026             {
1027               g_key_file_free (theme_file);
1028               theme_file = NULL;
1029               g_error_free (error);
1030               error = NULL;
1031             }
1032         }
1033       g_free (path);
1034     }
1035
1036   if (theme_file || strcmp (theme_name, DEFAULT_THEME_NAME) == 0)
1037     {
1038       theme = g_new0 (IconTheme, 1);
1039       theme->name = g_strdup (theme_name);
1040       priv->themes = g_list_prepend (priv->themes, theme);
1041     }
1042
1043   if (theme_file == NULL)
1044     return;
1045
1046   theme->display_name = 
1047     g_key_file_get_locale_string (theme_file, "Icon Theme", "Name", NULL, NULL);
1048   if (!theme->display_name)
1049     g_warning ("Theme file for %s has no name\n", theme_name);
1050
1051   dirs = g_key_file_get_string_list (theme_file, "Icon Theme", "Directories", NULL, NULL);
1052   if (!dirs)
1053     {
1054       g_warning ("Theme file for %s has no directories\n", theme_name);
1055       priv->themes = g_list_remove (priv->themes, theme);
1056       g_free (theme->name);
1057       g_free (theme->display_name);
1058       g_free (theme);
1059       g_key_file_free (theme_file);
1060       return;
1061     }
1062   
1063   theme->comment = 
1064     g_key_file_get_locale_string (theme_file, 
1065                                   "Icon Theme", "Comment",
1066                                   NULL, NULL);
1067   theme->example = 
1068     g_key_file_get_string (theme_file, 
1069                            "Icon Theme", "Example",
1070                            NULL);
1071
1072   theme->dirs = NULL;
1073   for (i = 0; dirs[i] != NULL; i++)
1074     theme_subdir_load (icon_theme, theme, theme_file, dirs[i]);
1075
1076   g_strfreev (dirs);
1077
1078   theme->dirs = g_list_reverse (theme->dirs);
1079
1080   themes = g_key_file_get_string_list (theme_file,
1081                                        "Icon Theme",
1082                                        "Inherits",
1083                                        NULL,
1084                                        NULL);
1085   if (themes)
1086     {
1087       for (i = 0; themes[i] != NULL; i++)
1088         insert_theme (icon_theme, themes[i]);
1089       
1090       g_strfreev (themes);
1091     }
1092
1093   g_key_file_free (theme_file);
1094 }
1095
1096 static void
1097 free_unthemed_icon (UnthemedIcon *unthemed_icon)
1098 {
1099   g_free (unthemed_icon->svg_filename);
1100   g_free (unthemed_icon->no_svg_filename);
1101   g_slice_free (UnthemedIcon, unthemed_icon);
1102 }
1103
1104 static char *
1105 strip_suffix (const char *filename)
1106 {
1107   const char *dot;
1108
1109   dot = strrchr (filename, '.');
1110
1111   if (dot == NULL)
1112     return g_strdup (filename);
1113
1114   return g_strndup (filename, dot - filename);
1115 }
1116
1117 static void
1118 load_themes (GtkIconTheme *icon_theme)
1119 {
1120   GtkIconThemePrivate *priv;
1121   GDir *gdir;
1122   int base;
1123   char *dir;
1124   const char *file;
1125   UnthemedIcon *unthemed_icon;
1126   IconSuffix old_suffix, new_suffix;
1127   GTimeVal tv;
1128   IconThemeDirMtime *dir_mtime;
1129   GStatBuf stat_buf;
1130   
1131   priv = icon_theme->priv;
1132
1133   priv->all_icons = g_hash_table_new (g_str_hash, g_str_equal);
1134   
1135   if (priv->current_theme)
1136     insert_theme (icon_theme, priv->current_theme);
1137
1138   /* Always look in the "default" icon theme, and in a fallback theme */
1139   if (priv->fallback_theme)
1140     insert_theme (icon_theme, priv->fallback_theme);
1141   insert_theme (icon_theme, DEFAULT_THEME_NAME);
1142   priv->themes = g_list_reverse (priv->themes);
1143
1144
1145   priv->unthemed_icons = g_hash_table_new_full (g_str_hash, g_str_equal,
1146                                                 g_free, (GDestroyNotify)free_unthemed_icon);
1147
1148   for (base = 0; base < icon_theme->priv->search_path_len; base++)
1149     {
1150       dir = icon_theme->priv->search_path[base];
1151
1152       dir_mtime = g_slice_new (IconThemeDirMtime);
1153       priv->dir_mtimes = g_list_append (priv->dir_mtimes, dir_mtime);
1154       
1155       dir_mtime->dir = g_strdup (dir);
1156       dir_mtime->mtime = 0;
1157       dir_mtime->cache = NULL;
1158
1159       if (g_stat (dir, &stat_buf) != 0 || !S_ISDIR (stat_buf.st_mode))
1160         continue;
1161       dir_mtime->mtime = stat_buf.st_mtime;
1162
1163       dir_mtime->cache = _gtk_icon_cache_new_for_path (dir);
1164       if (dir_mtime->cache != NULL)
1165         continue;
1166
1167       gdir = g_dir_open (dir, 0, NULL);
1168       if (gdir == NULL)
1169         continue;
1170
1171       while ((file = g_dir_read_name (gdir)))
1172         {
1173           new_suffix = suffix_from_name (file);
1174           
1175           if (new_suffix != ICON_SUFFIX_NONE)
1176             {
1177               char *abs_file;
1178               char *base_name;
1179
1180               abs_file = g_build_filename (dir, file, NULL);
1181               base_name = strip_suffix (file);
1182
1183               if ((unthemed_icon = g_hash_table_lookup (priv->unthemed_icons,
1184                                                         base_name)))
1185                 {
1186                   if (new_suffix == ICON_SUFFIX_SVG)
1187                     {
1188                       if (unthemed_icon->svg_filename)
1189                         g_free (abs_file);
1190                       else
1191                         unthemed_icon->svg_filename = abs_file;
1192                     }
1193                   else
1194                     {
1195                       if (unthemed_icon->no_svg_filename)
1196                         {
1197                           old_suffix = suffix_from_name (unthemed_icon->no_svg_filename);
1198                           if (new_suffix > old_suffix)
1199                             {
1200                               g_free (unthemed_icon->no_svg_filename);
1201                               unthemed_icon->no_svg_filename = abs_file;                              
1202                             }
1203                           else
1204                             g_free (abs_file);
1205                         }
1206                       else
1207                         unthemed_icon->no_svg_filename = abs_file;                            
1208                     }
1209
1210                   g_free (base_name);
1211                 }
1212               else
1213                 {
1214                   unthemed_icon = g_slice_new0 (UnthemedIcon);
1215                   
1216                   if (new_suffix == ICON_SUFFIX_SVG)
1217                     unthemed_icon->svg_filename = abs_file;
1218                   else
1219                     unthemed_icon->no_svg_filename = abs_file;
1220
1221                   /* takes ownership of base_name */
1222                   g_hash_table_replace (priv->unthemed_icons,
1223                                         base_name,
1224                                         unthemed_icon);
1225                   g_hash_table_insert (priv->all_icons,
1226                                        base_name, NULL);
1227                 }
1228             }
1229         }
1230       g_dir_close (gdir);
1231     }
1232
1233   priv->themes_valid = TRUE;
1234   
1235   g_get_current_time(&tv);
1236   priv->last_stat_time = tv.tv_sec;
1237 }
1238
1239 void
1240 _gtk_icon_theme_ensure_builtin_cache (void)
1241 {
1242   static gboolean initialized = FALSE;
1243   IconThemeDir *dir;
1244   static IconThemeDir dirs[5] = 
1245     {
1246       { ICON_THEME_DIR_THRESHOLD, 0, 16, 16, 16, 2, NULL, "16", -1, NULL, NULL, NULL },
1247       { ICON_THEME_DIR_THRESHOLD, 0, 20, 20, 20, 2, NULL, "20", -1,  NULL, NULL, NULL },
1248       { ICON_THEME_DIR_THRESHOLD, 0, 24, 24, 24, 2, NULL, "24", -1, NULL, NULL, NULL },
1249       { ICON_THEME_DIR_THRESHOLD, 0, 32, 32, 32, 2, NULL, "32", -1, NULL, NULL, NULL },
1250       { ICON_THEME_DIR_THRESHOLD, 0, 48, 48, 48, 2, NULL, "48", -1, NULL, NULL, NULL }
1251     };
1252   gint i;
1253
1254   if (!initialized)
1255     {
1256       initialized = TRUE;
1257
1258       _builtin_cache = _gtk_icon_cache_new ((gchar *)builtin_icons);
1259
1260       for (i = 0; i < G_N_ELEMENTS (dirs); i++)
1261         {
1262           dir = &(dirs[i]);
1263           dir->cache = _gtk_icon_cache_ref (_builtin_cache);
1264           dir->subdir_index = _gtk_icon_cache_get_directory_index (dir->cache, dir->subdir);
1265
1266           builtin_dirs = g_list_append (builtin_dirs, dir);
1267         }
1268     }
1269 }
1270
1271 static void
1272 ensure_valid_themes (GtkIconTheme *icon_theme)
1273 {
1274   GtkIconThemePrivate *priv = icon_theme->priv;
1275   GTimeVal tv;
1276   gboolean was_valid = priv->themes_valid;
1277
1278   if (priv->loading_themes)
1279     return;
1280   priv->loading_themes = TRUE;
1281
1282   _gtk_icon_theme_ensure_builtin_cache ();
1283
1284   if (priv->themes_valid)
1285     {
1286       g_get_current_time (&tv);
1287
1288       if (ABS (tv.tv_sec - priv->last_stat_time) > 5 &&
1289           rescan_themes (icon_theme))
1290         blow_themes (icon_theme);
1291     }
1292   
1293   if (!priv->themes_valid)
1294     {
1295       load_themes (icon_theme);
1296
1297       if (was_valid)
1298         {
1299           g_signal_emit (icon_theme, signal_changed, 0);
1300         }
1301     }
1302
1303   priv->loading_themes = FALSE;
1304 }
1305
1306 static GtkIconInfo *
1307 choose_icon (GtkIconTheme       *icon_theme,
1308              const gchar        *icon_names[],
1309              gint                size,
1310              GtkIconLookupFlags  flags)
1311 {
1312   GtkIconThemePrivate *priv;
1313   GList *l;
1314   GtkIconInfo *icon_info = NULL;
1315   UnthemedIcon *unthemed_icon = NULL;
1316   gboolean allow_svg;
1317   gboolean use_builtin;
1318   gint i;
1319
1320   priv = icon_theme->priv;
1321
1322   if (flags & GTK_ICON_LOOKUP_NO_SVG)
1323     allow_svg = FALSE;
1324   else if (flags & GTK_ICON_LOOKUP_FORCE_SVG)
1325     allow_svg = TRUE;
1326   else
1327     allow_svg = priv->pixbuf_supports_svg;
1328
1329   use_builtin = flags & GTK_ICON_LOOKUP_USE_BUILTIN;
1330   
1331   ensure_valid_themes (icon_theme);
1332
1333   /* for symbolic icons, do a search in all registered themes first;
1334    * a theme that inherits them from a parent theme might provide
1335    * an alternative highcolor version, but still expect the symbolic icon
1336    * to show up instead.
1337    */
1338   if (icon_names[0] &&
1339       g_str_has_suffix (icon_names[0], "-symbolic"))
1340     {
1341       for (l = priv->themes; l; l = l->next)
1342         {
1343           IconTheme *theme = l->data;
1344           icon_info = theme_lookup_icon (theme, icon_names[0], size, allow_svg, use_builtin);
1345           if (icon_info)
1346             goto out;
1347         }
1348     }
1349
1350   for (l = priv->themes; l; l = l->next)
1351     {
1352       IconTheme *theme = l->data;
1353       
1354       for (i = 0; icon_names[i]; i++)
1355         {
1356           icon_info = theme_lookup_icon (theme, icon_names[i], size, allow_svg, use_builtin);
1357           if (icon_info)
1358             goto out;
1359         }
1360     }
1361
1362   for (i = 0; icon_names[i]; i++)
1363     {
1364       unthemed_icon = g_hash_table_lookup (priv->unthemed_icons, icon_names[i]);
1365       if (unthemed_icon)
1366         break;
1367     }
1368 #ifdef G_OS_WIN32
1369   /* Still not found an icon, check if reference to a Win32 resource */
1370   if (!unthemed_icon)
1371     {
1372       gchar **resources;
1373       HICON hIcon = NULL;
1374       
1375       resources = g_strsplit (icon_names[0], ",", 0);
1376       if (resources[0])
1377         {
1378           wchar_t *wfile = g_utf8_to_utf16 (resources[0], -1, NULL, NULL, NULL);
1379           ExtractIconExW (wfile, resources[1] ? atoi (resources[1]) : 0, &hIcon, NULL, 1);
1380           g_free (wfile);
1381         }
1382       
1383       if (hIcon)
1384         {
1385           icon_info = icon_info_new ();
1386           icon_info->cache_pixbuf = gdk_win32_icon_to_pixbuf_libgtk_only (hIcon);
1387           DestroyIcon (hIcon);
1388           icon_info->dir_type = ICON_THEME_DIR_UNTHEMED;
1389           icon_info->dir_size = size;
1390         }
1391       g_strfreev (resources);
1392     }
1393 #endif
1394
1395   if (unthemed_icon)
1396     {
1397       icon_info = icon_info_new ();
1398
1399       /* A SVG icon, when allowed, beats out a XPM icon, but not
1400        * a PNG icon
1401        */
1402       if (allow_svg &&
1403           unthemed_icon->svg_filename &&
1404           (!unthemed_icon->no_svg_filename ||
1405            suffix_from_name (unthemed_icon->no_svg_filename) != ICON_SUFFIX_PNG))
1406         icon_info->filename = g_strdup (unthemed_icon->svg_filename);
1407       else if (unthemed_icon->no_svg_filename)
1408         icon_info->filename = g_strdup (unthemed_icon->no_svg_filename);
1409
1410       icon_info->dir_type = ICON_THEME_DIR_UNTHEMED;
1411       icon_info->dir_size = size;
1412     }
1413
1414  out:
1415   if (icon_info) 
1416     {
1417       icon_info->desired_size = size;
1418       icon_info->forced_size = (flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0;
1419     }
1420   else
1421     {
1422       static gboolean check_for_default_theme = TRUE;
1423       char *default_theme_path;
1424       gboolean found = FALSE;
1425       unsigned i;
1426
1427       if (check_for_default_theme)
1428         {
1429           check_for_default_theme = FALSE;
1430
1431           for (i = 0; !found && i < priv->search_path_len; i++)
1432             {
1433               default_theme_path = g_build_filename (priv->search_path[i],
1434                                                      DEFAULT_THEME_NAME,
1435                                                      "index.theme",
1436                                                      NULL);
1437               found = g_file_test (default_theme_path, G_FILE_TEST_IS_REGULAR);
1438               g_free (default_theme_path);
1439             }
1440
1441           if (!found)
1442             {
1443               g_warning ("Could not find the icon '%s'. The '%s' theme\n"
1444                          "was not found either, perhaps you need to install it.\n"
1445                          "You can get a copy from:\n"
1446                          "\t%s",
1447                          icon_names[0], DEFAULT_THEME_NAME, "http://icon-theme.freedesktop.org/releases");
1448             }
1449         }
1450     }
1451
1452   return icon_info;
1453 }
1454
1455
1456 /**
1457  * gtk_icon_theme_lookup_icon:
1458  * @icon_theme: a #GtkIconTheme
1459  * @icon_name: the name of the icon to lookup
1460  * @size: desired icon size
1461  * @flags: flags modifying the behavior of the icon lookup
1462  * 
1463  * Looks up a named icon and returns a structure containing
1464  * information such as the filename of the icon. The icon
1465  * can then be rendered into a pixbuf using
1466  * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon()
1467  * combines these two steps if all you need is the pixbuf.)
1468  * 
1469  * Return value: a #GtkIconInfo structure containing information
1470  * about the icon, or %NULL if the icon wasn't found. Free with
1471  * gtk_icon_info_free()
1472  *
1473  * Since: 2.4
1474  */
1475 GtkIconInfo *
1476 gtk_icon_theme_lookup_icon (GtkIconTheme       *icon_theme,
1477                             const gchar        *icon_name,
1478                             gint                size,
1479                             GtkIconLookupFlags  flags)
1480 {
1481   GtkIconInfo *info;
1482
1483   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
1484   g_return_val_if_fail (icon_name != NULL, NULL);
1485   g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
1486                         (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
1487
1488   GTK_NOTE (ICONTHEME, 
1489             g_print ("gtk_icon_theme_lookup_icon %s\n", icon_name));
1490
1491   if (flags & GTK_ICON_LOOKUP_GENERIC_FALLBACK)
1492     {
1493       gchar **names;
1494       gint dashes, i;
1495       gchar *p;
1496  
1497       dashes = 0;
1498       for (p = (gchar *) icon_name; *p; p++)
1499         if (*p == '-')
1500           dashes++;
1501
1502       names = g_new (gchar *, dashes + 2);
1503       names[0] = g_strdup (icon_name);
1504       for (i = 1; i <= dashes; i++)
1505         {
1506           names[i] = g_strdup (names[i - 1]);
1507           p = strrchr (names[i], '-');
1508           *p = '\0';
1509         }
1510       names[dashes + 1] = NULL;
1511    
1512       info = choose_icon (icon_theme, (const gchar **) names, size, flags);
1513       
1514       g_strfreev (names);
1515     }
1516   else 
1517     {
1518       const gchar *names[2];
1519       
1520       names[0] = icon_name;
1521       names[1] = NULL;
1522
1523       info = choose_icon (icon_theme, names, size, flags);
1524     }
1525
1526   return info;
1527 }
1528
1529 /**
1530  * gtk_icon_theme_choose_icon:
1531  * @icon_theme: a #GtkIconTheme
1532  * @icon_names: (array zero-terminated=1): %NULL-terminated array of
1533  *     icon names to lookup
1534  * @size: desired icon size
1535  * @flags: flags modifying the behavior of the icon lookup
1536  * 
1537  * Looks up a named icon and returns a structure containing
1538  * information such as the filename of the icon. The icon
1539  * can then be rendered into a pixbuf using
1540  * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon()
1541  * combines these two steps if all you need is the pixbuf.)
1542  *
1543  * If @icon_names contains more than one name, this function 
1544  * tries them all in the given order before falling back to 
1545  * inherited icon themes.
1546  * 
1547  * Return value: a #GtkIconInfo structure containing information
1548  * about the icon, or %NULL if the icon wasn't found. Free with
1549  * gtk_icon_info_free()
1550  *
1551  * Since: 2.12
1552  */
1553 GtkIconInfo *
1554 gtk_icon_theme_choose_icon (GtkIconTheme       *icon_theme,
1555                             const gchar        *icon_names[],
1556                             gint                size,
1557                             GtkIconLookupFlags  flags)
1558 {
1559   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
1560   g_return_val_if_fail (icon_names != NULL, NULL);
1561   g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
1562                         (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
1563
1564   return choose_icon (icon_theme, icon_names, size, flags);
1565 }
1566
1567 /* Error quark */
1568 GQuark
1569 gtk_icon_theme_error_quark (void)
1570 {
1571   return g_quark_from_static_string ("gtk-icon-theme-error-quark");
1572 }
1573
1574 /**
1575  * gtk_icon_theme_load_icon:
1576  * @icon_theme: a #GtkIconTheme
1577  * @icon_name: the name of the icon to lookup
1578  * @size: the desired icon size. The resulting icon may not be
1579  *     exactly this size; see gtk_icon_info_load_icon().
1580  * @flags: flags modifying the behavior of the icon lookup
1581  * @error: (allow-none): Location to store error information on failure,
1582  *     or %NULL.
1583  *
1584  * Looks up an icon in an icon theme, scales it to the given size
1585  * and renders it into a pixbuf. This is a convenience function;
1586  * if more details about the icon are needed, use
1587  * gtk_icon_theme_lookup_icon() followed by gtk_icon_info_load_icon().
1588  *
1589  * Note that you probably want to listen for icon theme changes and
1590  * update the icon. This is usually done by connecting to the
1591  * GtkWidget::style-set signal. If for some reason you do not want to
1592  * update the icon when the icon theme changes, you should consider
1593  * using gdk_pixbuf_copy() to make a private copy of the pixbuf
1594  * returned by this function. Otherwise GTK+ may need to keep the old
1595  * icon theme loaded, which would be a waste of memory.
1596  *
1597  * Return value: (transfer full): the rendered icon; this may be a
1598  *     newly created icon or a new reference to an internal icon, so
1599  *     you must not modify the icon. Use g_object_unref() to release
1600  *     your reference to the icon. %NULL if the icon isn't found.
1601  *
1602  * Since: 2.4
1603  **/
1604 GdkPixbuf *
1605 gtk_icon_theme_load_icon (GtkIconTheme         *icon_theme,
1606                           const gchar          *icon_name,
1607                           gint                  size,
1608                           GtkIconLookupFlags    flags,
1609                           GError              **error)
1610 {
1611   GtkIconInfo *icon_info;
1612   GdkPixbuf *pixbuf = NULL;
1613   
1614   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
1615   g_return_val_if_fail (icon_name != NULL, NULL);
1616   g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
1617                         (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
1618   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1619   
1620   icon_info = gtk_icon_theme_lookup_icon (icon_theme, icon_name, size,
1621                                           flags | GTK_ICON_LOOKUP_USE_BUILTIN);
1622   if (!icon_info)
1623     {
1624       g_set_error (error, GTK_ICON_THEME_ERROR,  GTK_ICON_THEME_NOT_FOUND,
1625                    _("Icon '%s' not present in theme"), icon_name);
1626       return NULL;
1627     }
1628
1629   pixbuf = gtk_icon_info_load_icon (icon_info, error);
1630   gtk_icon_info_free (icon_info);
1631
1632   return pixbuf;
1633 }
1634
1635 /**
1636  * gtk_icon_theme_has_icon:
1637  * @icon_theme: a #GtkIconTheme
1638  * @icon_name: the name of an icon
1639  * 
1640  * Checks whether an icon theme includes an icon
1641  * for a particular name.
1642  * 
1643  * Return value: %TRUE if @icon_theme includes an
1644  *  icon for @icon_name.
1645  *
1646  * Since: 2.4
1647  **/
1648 gboolean 
1649 gtk_icon_theme_has_icon (GtkIconTheme *icon_theme,
1650                          const char   *icon_name)
1651 {
1652   GtkIconThemePrivate *priv;
1653   GList *l;
1654
1655   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), FALSE);
1656   g_return_val_if_fail (icon_name != NULL, FALSE);
1657
1658   priv = icon_theme->priv;
1659   
1660   ensure_valid_themes (icon_theme);
1661
1662   for (l = priv->dir_mtimes; l; l = l->next)
1663     {
1664       IconThemeDirMtime *dir_mtime = l->data;
1665       GtkIconCache *cache = dir_mtime->cache;
1666       
1667       if (cache && _gtk_icon_cache_has_icon (cache, icon_name))
1668         return TRUE;
1669     }
1670
1671   if (g_hash_table_lookup_extended (priv->all_icons,
1672                                     icon_name, NULL, NULL))
1673     return TRUE;
1674
1675   if (_builtin_cache &&
1676       _gtk_icon_cache_has_icon (_builtin_cache, icon_name))
1677     return TRUE;
1678
1679   if (icon_theme_builtin_icons &&
1680       g_hash_table_lookup_extended (icon_theme_builtin_icons,
1681                                     icon_name, NULL, NULL))
1682     return TRUE;
1683
1684   return FALSE;
1685 }
1686
1687 static void
1688 add_size (gpointer  key,
1689           gpointer  value,
1690           gpointer  user_data)
1691 {
1692   gint **res_p = user_data;
1693
1694   **res_p = GPOINTER_TO_INT (key);
1695
1696   (*res_p)++;
1697 }
1698
1699 /**
1700  * gtk_icon_theme_get_icon_sizes:
1701  * @icon_theme: a #GtkIconTheme
1702  * @icon_name: the name of an icon
1703  * 
1704  * Returns an array of integers describing the sizes at which
1705  * the icon is available without scaling. A size of -1 means 
1706  * that the icon is available in a scalable format. The array 
1707  * is zero-terminated.
1708  * 
1709  * Return value: (array zero-terminated=1): An newly allocated array
1710  * describing the sizes at which the icon is available. The array
1711  * should be freed with g_free() when it is no longer needed.
1712  *
1713  * Since: 2.6
1714  **/
1715 gint *
1716 gtk_icon_theme_get_icon_sizes (GtkIconTheme *icon_theme,
1717                                const char   *icon_name)
1718 {
1719   GList *l, *d, *icons;
1720   GHashTable *sizes;
1721   gint *result, *r;
1722   guint suffix;  
1723   GtkIconThemePrivate *priv;
1724
1725   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
1726   
1727   priv = icon_theme->priv;
1728
1729   ensure_valid_themes (icon_theme);
1730
1731   sizes = g_hash_table_new (g_direct_hash, g_direct_equal);
1732
1733   for (l = priv->themes; l; l = l->next)
1734     {
1735       IconTheme *theme = l->data;
1736       for (d = theme->dirs; d; d = d->next)
1737         {
1738           IconThemeDir *dir = d->data;
1739
1740           if (dir->type != ICON_THEME_DIR_SCALABLE && g_hash_table_lookup_extended (sizes, GINT_TO_POINTER (dir->size), NULL, NULL))
1741             continue;
1742
1743           suffix = theme_dir_get_icon_suffix (dir, icon_name, NULL);      
1744           if (suffix != ICON_SUFFIX_NONE)
1745             {
1746               if (suffix == ICON_SUFFIX_SVG)
1747                 g_hash_table_insert (sizes, GINT_TO_POINTER (-1), NULL);
1748               else
1749                 g_hash_table_insert (sizes, GINT_TO_POINTER (dir->size), NULL);
1750             }
1751         }
1752     }
1753
1754   for (d = builtin_dirs; d; d = d->next)
1755     {
1756       IconThemeDir *dir = d->data;
1757       
1758       if (dir->type != ICON_THEME_DIR_SCALABLE && g_hash_table_lookup_extended (sizes, GINT_TO_POINTER (dir->size), NULL, NULL))
1759         continue;
1760
1761       suffix = theme_dir_get_icon_suffix (dir, icon_name, NULL);          
1762       if (suffix != ICON_SUFFIX_NONE)
1763         {
1764           if (suffix == ICON_SUFFIX_SVG)
1765             g_hash_table_insert (sizes, GINT_TO_POINTER (-1), NULL);
1766           else
1767             g_hash_table_insert (sizes, GINT_TO_POINTER (dir->size), NULL);
1768         }
1769     }
1770
1771   if (icon_theme_builtin_icons)
1772     {
1773       icons = g_hash_table_lookup (icon_theme_builtin_icons, icon_name);
1774       
1775       while (icons)
1776         {
1777           BuiltinIcon *icon = icons->data;
1778         
1779           g_hash_table_insert (sizes, GINT_TO_POINTER (icon->size), NULL);
1780           icons = icons->next;
1781         }      
1782     }
1783
1784   r = result = g_new0 (gint, g_hash_table_size (sizes) + 1);
1785
1786   g_hash_table_foreach (sizes, add_size, &r);
1787   g_hash_table_destroy (sizes);
1788   
1789   return result;
1790 }
1791
1792 static void
1793 add_key_to_hash (gpointer  key,
1794                  gpointer  value,
1795                  gpointer  user_data)
1796 {
1797   GHashTable *hash = user_data;
1798
1799   g_hash_table_insert (hash, key, NULL);
1800 }
1801
1802 static void
1803 add_key_to_list (gpointer  key,
1804                  gpointer  value,
1805                  gpointer  user_data)
1806 {
1807   GList **list = user_data;
1808
1809   *list = g_list_prepend (*list, g_strdup (key));
1810 }
1811
1812 /**
1813  * gtk_icon_theme_list_icons:
1814  * @icon_theme: a #GtkIconTheme
1815  * @context: (allow-none): a string identifying a particular type of
1816  *           icon, or %NULL to list all icons.
1817  * 
1818  * Lists the icons in the current icon theme. Only a subset
1819  * of the icons can be listed by providing a context string.
1820  * The set of values for the context string is system dependent,
1821  * but will typically include such values as "Applications" and
1822  * "MimeTypes".
1823  *
1824  * Return value: (element-type utf8) (transfer full): a #GList list
1825  *  holding the names of all the icons in the theme. You must first
1826  *  free each element in the list with g_free(), then free the list
1827  *  itself with g_list_free().
1828  *
1829  * Since: 2.4
1830  **/
1831 GList *
1832 gtk_icon_theme_list_icons (GtkIconTheme *icon_theme,
1833                            const char   *context)
1834 {
1835   GtkIconThemePrivate *priv;
1836   GHashTable *icons;
1837   GList *list, *l;
1838   GQuark context_quark;
1839   
1840   priv = icon_theme->priv;
1841   
1842   ensure_valid_themes (icon_theme);
1843
1844   if (context)
1845     {
1846       context_quark = g_quark_try_string (context);
1847
1848       if (!context_quark)
1849         return NULL;
1850     }
1851   else
1852     context_quark = 0;
1853
1854   icons = g_hash_table_new (g_str_hash, g_str_equal);
1855   
1856   l = priv->themes;
1857   while (l != NULL)
1858     {
1859       theme_list_icons (l->data, icons, context_quark);
1860       l = l->next;
1861     }
1862
1863   if (context_quark == 0)
1864     g_hash_table_foreach (priv->unthemed_icons,
1865                           add_key_to_hash,
1866                           icons);
1867
1868   list = NULL;
1869   
1870   g_hash_table_foreach (icons,
1871                         add_key_to_list,
1872                         &list);
1873
1874   g_hash_table_destroy (icons);
1875   
1876   return list;
1877 }
1878
1879 /**
1880  * gtk_icon_theme_list_contexts:
1881  * @icon_theme: a #GtkIconTheme
1882  *
1883  * Gets the list of contexts available within the current
1884  * hierarchy of icon themes
1885  *
1886  * Return value: (element-type utf8) (transfer full): a #GList list
1887  *  holding the names of all the contexts in the theme. You must first
1888  *  free each element in the list with g_free(), then free the list
1889  *  itself with g_list_free().
1890  *
1891  * Since: 2.12
1892  **/
1893 GList *
1894 gtk_icon_theme_list_contexts (GtkIconTheme *icon_theme)
1895 {
1896   GtkIconThemePrivate *priv;
1897   GHashTable *contexts;
1898   GList *list, *l;
1899
1900   priv = icon_theme->priv;
1901   
1902   ensure_valid_themes (icon_theme);
1903
1904   contexts = g_hash_table_new (g_str_hash, g_str_equal);
1905
1906   l = priv->themes;
1907   while (l != NULL)
1908     {
1909       theme_list_contexts (l->data, contexts);
1910       l = l->next;
1911     }
1912
1913   list = NULL;
1914
1915   g_hash_table_foreach (contexts,
1916                         add_key_to_list,
1917                         &list);
1918
1919   g_hash_table_destroy (contexts);
1920
1921   return list;
1922 }
1923
1924 /**
1925  * gtk_icon_theme_get_example_icon_name:
1926  * @icon_theme: a #GtkIconTheme
1927  * 
1928  * Gets the name of an icon that is representative of the
1929  * current theme (for instance, to use when presenting
1930  * a list of themes to the user.)
1931  * 
1932  * Return value: the name of an example icon or %NULL.
1933  *  Free with g_free().
1934  *
1935  * Since: 2.4
1936  **/
1937 char *
1938 gtk_icon_theme_get_example_icon_name (GtkIconTheme *icon_theme)
1939 {
1940   GtkIconThemePrivate *priv;
1941   GList *l;
1942   IconTheme *theme;
1943
1944   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
1945   
1946   priv = icon_theme->priv;
1947   
1948   ensure_valid_themes (icon_theme);
1949
1950   l = priv->themes;
1951   while (l != NULL)
1952     {
1953       theme = l->data;
1954       if (theme->example)
1955         return g_strdup (theme->example);
1956       
1957       l = l->next;
1958     }
1959   
1960   return NULL;
1961 }
1962
1963
1964 static gboolean
1965 rescan_themes (GtkIconTheme *icon_theme)
1966 {
1967   GtkIconThemePrivate *priv;
1968   IconThemeDirMtime *dir_mtime;
1969   GList *d;
1970   int stat_res;
1971   GStatBuf stat_buf;
1972   GTimeVal tv;
1973
1974   priv = icon_theme->priv;
1975
1976   for (d = priv->dir_mtimes; d != NULL; d = d->next)
1977     {
1978       dir_mtime = d->data;
1979
1980       stat_res = g_stat (dir_mtime->dir, &stat_buf);
1981
1982       /* dir mtime didn't change */
1983       if (stat_res == 0 &&
1984           S_ISDIR (stat_buf.st_mode) &&
1985           dir_mtime->mtime == stat_buf.st_mtime)
1986         continue;
1987       /* didn't exist before, and still doesn't */
1988       if (dir_mtime->mtime == 0 &&
1989           (stat_res != 0 || !S_ISDIR (stat_buf.st_mode)))
1990         continue;
1991
1992       return TRUE;
1993     }
1994
1995   g_get_current_time (&tv);
1996   priv->last_stat_time = tv.tv_sec;
1997
1998   return FALSE;
1999 }
2000
2001 /**
2002  * gtk_icon_theme_rescan_if_needed:
2003  * @icon_theme: a #GtkIconTheme
2004  * 
2005  * Checks to see if the icon theme has changed; if it has, any
2006  * currently cached information is discarded and will be reloaded
2007  * next time @icon_theme is accessed.
2008  * 
2009  * Return value: %TRUE if the icon theme has changed and needed
2010  *   to be reloaded.
2011  *
2012  * Since: 2.4
2013  **/
2014 gboolean
2015 gtk_icon_theme_rescan_if_needed (GtkIconTheme *icon_theme)
2016 {
2017   gboolean retval;
2018
2019   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), FALSE);
2020
2021   retval = rescan_themes (icon_theme);
2022   if (retval)
2023       do_theme_change (icon_theme);
2024
2025   return retval;
2026 }
2027
2028 static void
2029 theme_destroy (IconTheme *theme)
2030 {
2031   g_free (theme->display_name);
2032   g_free (theme->comment);
2033   g_free (theme->name);
2034   g_free (theme->example);
2035
2036   g_list_free_full (theme->dirs, (GDestroyNotify) theme_dir_destroy);
2037   
2038   g_free (theme);
2039 }
2040
2041 static void
2042 theme_dir_destroy (IconThemeDir *dir)
2043 {
2044   if (dir->cache)
2045       _gtk_icon_cache_unref (dir->cache);
2046   else
2047     g_hash_table_destroy (dir->icons);
2048   
2049   if (dir->icon_data)
2050     g_hash_table_destroy (dir->icon_data);
2051   g_free (dir->dir);
2052   g_free (dir->subdir);
2053   g_free (dir);
2054 }
2055
2056 static int
2057 theme_dir_size_difference (IconThemeDir *dir, int size, gboolean *smaller)
2058 {
2059   int min, max;
2060   switch (dir->type)
2061     {
2062     case ICON_THEME_DIR_FIXED:
2063       *smaller = size < dir->size;
2064       return abs (size - dir->size);
2065       break;
2066     case ICON_THEME_DIR_SCALABLE:
2067       *smaller = size < dir->min_size;
2068       if (size < dir->min_size)
2069         return dir->min_size - size;
2070       if (size > dir->max_size)
2071         return size - dir->max_size;
2072       return 0;
2073       break;
2074     case ICON_THEME_DIR_THRESHOLD:
2075       min = dir->size - dir->threshold;
2076       max = dir->size + dir->threshold;
2077       *smaller = size < min;
2078       if (size < min)
2079         return min - size;
2080       if (size > max)
2081         return size - max;
2082       return 0;
2083       break;
2084     case ICON_THEME_DIR_UNTHEMED:
2085       g_assert_not_reached ();
2086       break;
2087     }
2088   g_assert_not_reached ();
2089   return 1000;
2090 }
2091
2092 static const char *
2093 string_from_suffix (IconSuffix suffix)
2094 {
2095   switch (suffix)
2096     {
2097     case ICON_SUFFIX_XPM:
2098       return ".xpm";
2099     case ICON_SUFFIX_SVG:
2100       return ".svg";
2101     case ICON_SUFFIX_PNG:
2102       return ".png";
2103     default:
2104       g_assert_not_reached();
2105     }
2106   return NULL;
2107 }
2108
2109 static IconSuffix
2110 suffix_from_name (const char *name)
2111 {
2112   IconSuffix retval;
2113
2114   if (g_str_has_suffix (name, ".png"))
2115     retval = ICON_SUFFIX_PNG;
2116   else if (g_str_has_suffix (name, ".svg"))
2117     retval = ICON_SUFFIX_SVG;
2118   else if (g_str_has_suffix (name, ".xpm"))
2119     retval = ICON_SUFFIX_XPM;
2120   else
2121     retval = ICON_SUFFIX_NONE;
2122
2123   return retval;
2124 }
2125
2126 static IconSuffix
2127 best_suffix (IconSuffix suffix,
2128              gboolean   allow_svg)
2129 {
2130   if ((suffix & ICON_SUFFIX_PNG) != 0)
2131     return ICON_SUFFIX_PNG;
2132   else if (allow_svg && ((suffix & ICON_SUFFIX_SVG) != 0))
2133     return ICON_SUFFIX_SVG;
2134   else if ((suffix & ICON_SUFFIX_XPM) != 0)
2135     return ICON_SUFFIX_XPM;
2136   else
2137     return ICON_SUFFIX_NONE;
2138 }
2139
2140
2141 static IconSuffix
2142 theme_dir_get_icon_suffix (IconThemeDir *dir,
2143                            const gchar  *icon_name,
2144                            gboolean     *has_icon_file)
2145 {
2146   IconSuffix suffix;
2147
2148   if (dir->cache)
2149     {
2150       suffix = (IconSuffix)_gtk_icon_cache_get_icon_flags (dir->cache,
2151                                                            icon_name,
2152                                                            dir->subdir_index);
2153
2154       if (has_icon_file)
2155         *has_icon_file = suffix & HAS_ICON_FILE;
2156
2157       suffix = suffix & ~HAS_ICON_FILE;
2158     }
2159   else
2160     suffix = GPOINTER_TO_UINT (g_hash_table_lookup (dir->icons, icon_name));
2161
2162   GTK_NOTE (ICONTHEME, 
2163             g_print ("get_icon_suffix%s %u\n", dir->cache ? " (cached)" : "", suffix));
2164
2165   return suffix;
2166 }
2167
2168 static GtkIconInfo *
2169 theme_lookup_icon (IconTheme          *theme,
2170                    const char         *icon_name,
2171                    int                 size,
2172                    gboolean            allow_svg,
2173                    gboolean            use_builtin)
2174 {
2175   GList *dirs, *l;
2176   IconThemeDir *dir, *min_dir;
2177   char *file;
2178   int min_difference, difference;
2179   BuiltinIcon *closest_builtin = NULL;
2180   gboolean smaller, has_larger, match;
2181   IconSuffix suffix;
2182
2183   min_difference = G_MAXINT;
2184   min_dir = NULL;
2185   has_larger = FALSE;
2186   match = FALSE;
2187
2188   /* Builtin icons are logically part of the default theme and
2189    * are searched before other subdirectories of the default theme.
2190    */
2191   if (use_builtin && strcmp (theme->name, DEFAULT_THEME_NAME) == 0)
2192     {
2193       closest_builtin = find_builtin_icon (icon_name, 
2194                                            size,
2195                                            &min_difference,
2196                                            &has_larger);
2197
2198       if (min_difference == 0)
2199         return icon_info_new_builtin (closest_builtin);
2200
2201       dirs = builtin_dirs;
2202     }
2203   else
2204     dirs = theme->dirs;
2205
2206   l = dirs;
2207   while (l != NULL)
2208     {
2209       dir = l->data;
2210
2211       GTK_NOTE (ICONTHEME,
2212                 g_print ("theme_lookup_icon dir %s\n", dir->dir));
2213       suffix = theme_dir_get_icon_suffix (dir, icon_name, NULL);
2214       if (best_suffix (suffix, allow_svg) != ICON_SUFFIX_NONE)
2215         {
2216           difference = theme_dir_size_difference (dir, size, &smaller);
2217
2218           if (difference == 0)
2219             {
2220               if (dir->type == ICON_THEME_DIR_SCALABLE)
2221                 {
2222                   /* don't pick scalable if we already found
2223                    * a matching non-scalable dir
2224                    */
2225                   if (!match)
2226                     {
2227                       min_dir = dir;
2228                       break;
2229                     }
2230                 }
2231               else
2232                 {
2233                   /* for a matching non-scalable dir keep
2234                    * going and look for a closer match
2235                    */             
2236                   difference = abs (size - dir->size);
2237                   if (!match || difference < min_difference)
2238                     {
2239                       match = TRUE;
2240                       min_difference = difference;
2241                       min_dir = dir;
2242                     }
2243                   if (difference == 0)
2244                     break;
2245                 }
2246             } 
2247   
2248           if (!match)
2249             {
2250               if (!has_larger)
2251                 {
2252                   if (difference < min_difference || smaller)
2253                     {
2254                       min_difference = difference;
2255                       min_dir = dir;
2256                       has_larger = smaller;
2257                     }
2258                 }
2259               else
2260                 {
2261                   if (difference < min_difference && smaller)
2262                     {
2263                       min_difference = difference;
2264                       min_dir = dir;
2265                     }
2266                 }
2267             }
2268         }
2269
2270       l = l->next;
2271
2272       if (l == NULL && dirs == builtin_dirs)
2273         {
2274           dirs = theme->dirs;
2275           l = dirs;
2276         }
2277     }
2278
2279   if (min_dir)
2280     {
2281       GtkIconInfo *icon_info = icon_info_new ();
2282       gboolean has_icon_file = FALSE;
2283       
2284       suffix = theme_dir_get_icon_suffix (min_dir, icon_name, &has_icon_file);
2285       suffix = best_suffix (suffix, allow_svg);
2286       g_assert (suffix != ICON_SUFFIX_NONE);
2287       
2288       if (min_dir->dir)
2289         {
2290           file = g_strconcat (icon_name, string_from_suffix (suffix), NULL);
2291           icon_info->filename = g_build_filename (min_dir->dir, file, NULL);
2292           g_free (file);
2293         }
2294       else
2295         {
2296           icon_info->filename = NULL;
2297         }
2298       
2299       if (min_dir->icon_data != NULL)
2300         icon_info->data = g_hash_table_lookup (min_dir->icon_data, icon_name);
2301
2302       if (icon_info->data == NULL && min_dir->cache != NULL)
2303         {
2304           icon_info->data = _gtk_icon_cache_get_icon_data (min_dir->cache, icon_name, min_dir->subdir_index);
2305           if (icon_info->data)
2306             {
2307               if (min_dir->icon_data == NULL)
2308                 min_dir->icon_data = g_hash_table_new_full (g_str_hash, g_str_equal,
2309                                                             g_free, (GDestroyNotify)icon_data_free);
2310
2311               g_hash_table_replace (min_dir->icon_data, g_strdup (icon_name), icon_info->data);
2312             }
2313         }
2314
2315       if (icon_info->data == NULL && has_icon_file)
2316         {
2317           gchar *icon_file_name, *icon_file_path;
2318
2319           icon_file_name = g_strconcat (icon_name, ".icon", NULL);
2320           icon_file_path = g_build_filename (min_dir->dir, icon_file_name, NULL);
2321
2322           if (g_file_test (icon_file_path, G_FILE_TEST_IS_REGULAR))
2323             {
2324               if (min_dir->icon_data == NULL)   
2325                 min_dir->icon_data = g_hash_table_new_full (g_str_hash, g_str_equal,
2326                                                             g_free, (GDestroyNotify)icon_data_free);
2327               load_icon_data (min_dir, icon_file_path, icon_file_name);
2328               
2329               icon_info->data = g_hash_table_lookup (min_dir->icon_data, icon_name);
2330             }
2331           g_free (icon_file_name);
2332           g_free (icon_file_path);
2333         }
2334
2335       if (min_dir->cache)
2336         {
2337           icon_info->cache_pixbuf = _gtk_icon_cache_get_icon (min_dir->cache, icon_name,
2338                                                               min_dir->subdir_index);
2339         }
2340
2341       icon_info->dir_type = min_dir->type;
2342       icon_info->dir_size = min_dir->size;
2343       icon_info->threshold = min_dir->threshold;
2344       
2345       return icon_info;
2346     }
2347
2348   if (closest_builtin)
2349     return icon_info_new_builtin (closest_builtin);
2350   
2351   return NULL;
2352 }
2353
2354 static void
2355 theme_list_icons (IconTheme  *theme, 
2356                   GHashTable *icons,
2357                   GQuark      context)
2358 {
2359   GList *l = theme->dirs;
2360   IconThemeDir *dir;
2361   
2362   while (l != NULL)
2363     {
2364       dir = l->data;
2365
2366       if (context == dir->context ||
2367           context == 0)
2368         {
2369           if (dir->cache)
2370             {
2371               _gtk_icon_cache_add_icons (dir->cache,
2372                                          dir->subdir,
2373                                          icons);
2374                                          
2375             }
2376           else
2377             {
2378               g_hash_table_foreach (dir->icons,
2379                                     add_key_to_hash,
2380                                     icons);
2381             }
2382         }
2383       l = l->next;
2384     }
2385 }
2386
2387 static void
2388 theme_list_contexts (IconTheme  *theme, 
2389                      GHashTable *contexts)
2390 {
2391   GList *l = theme->dirs;
2392   IconThemeDir *dir;
2393   const char *context;
2394
2395   while (l != NULL)
2396     {
2397       dir = l->data;
2398
2399       context = g_quark_to_string (dir->context);
2400       g_hash_table_replace (contexts, (gpointer) context, NULL);
2401
2402       l = l->next;
2403     }
2404 }
2405
2406 static void
2407 load_icon_data (IconThemeDir *dir, const char *path, const char *name)
2408 {
2409   GKeyFile *icon_file;
2410   char *base_name;
2411   char **split;
2412   gsize length;
2413   char *str;
2414   char *split_point;
2415   int i;
2416   gint *ivalues;
2417   GError *error = NULL;
2418   
2419   GtkIconData *data;
2420
2421   icon_file = g_key_file_new ();
2422   g_key_file_set_list_separator (icon_file, ',');
2423   g_key_file_load_from_file (icon_file, path, 0, &error);
2424   if (error)
2425     {
2426       g_error_free (error);
2427       g_key_file_free (icon_file);      
2428       return;
2429     }
2430   else
2431     {
2432       base_name = strip_suffix (name);
2433       
2434       data = g_slice_new0 (GtkIconData);
2435       /* takes ownership of base_name */
2436       g_hash_table_replace (dir->icon_data, base_name, data);
2437       
2438       ivalues = g_key_file_get_integer_list (icon_file, 
2439                                              "Icon Data", "EmbeddedTextRectangle",
2440                                               &length, NULL);
2441       if (ivalues)
2442         {
2443           if (length == 4)
2444             {
2445               data->has_embedded_rect = TRUE;
2446               data->x0 = ivalues[0];
2447               data->y0 = ivalues[1];
2448               data->x1 = ivalues[2];
2449               data->y1 = ivalues[3];
2450             }
2451           
2452           g_free (ivalues);
2453         }
2454       
2455       str = g_key_file_get_string (icon_file, "Icon Data", "AttachPoints", NULL);
2456       if (str)
2457         {
2458           split = g_strsplit (str, "|", -1);
2459           
2460           data->n_attach_points = g_strv_length (split);
2461           data->attach_points = g_new (GdkPoint, data->n_attach_points);
2462
2463           i = 0;
2464           while (split[i] != NULL && i < data->n_attach_points)
2465             {
2466               split_point = strchr (split[i], ',');
2467               if (split_point)
2468                 {
2469                   *split_point = 0;
2470                   split_point++;
2471                   data->attach_points[i].x = atoi (split[i]);
2472                   data->attach_points[i].y = atoi (split_point);
2473                 }
2474               i++;
2475             }
2476           
2477           g_strfreev (split);
2478           g_free (str);
2479         }
2480       
2481       data->display_name = g_key_file_get_locale_string (icon_file, 
2482                                                          "Icon Data", "DisplayName",
2483                                                          NULL, NULL);
2484       g_key_file_free (icon_file);
2485     }
2486 }
2487
2488 static void
2489 scan_directory (GtkIconThemePrivate *icon_theme,
2490                 IconThemeDir *dir, char *full_dir)
2491 {
2492   GDir *gdir;
2493   const char *name;
2494
2495   GTK_NOTE (ICONTHEME, 
2496             g_print ("scanning directory %s\n", full_dir));
2497   dir->icons = g_hash_table_new_full (g_str_hash, g_str_equal,
2498                                       g_free, NULL);
2499   
2500   gdir = g_dir_open (full_dir, 0, NULL);
2501
2502   if (gdir == NULL)
2503     return;
2504
2505   while ((name = g_dir_read_name (gdir)))
2506     {
2507       char *path;
2508       char *base_name;
2509       IconSuffix suffix, hash_suffix;
2510
2511       if (g_str_has_suffix (name, ".icon"))
2512         {
2513           if (dir->icon_data == NULL)
2514             dir->icon_data = g_hash_table_new_full (g_str_hash, g_str_equal,
2515                                                     g_free, (GDestroyNotify)icon_data_free);
2516           
2517           path = g_build_filename (full_dir, name, NULL);
2518           if (g_file_test (path, G_FILE_TEST_IS_REGULAR))
2519             load_icon_data (dir, path, name);
2520           
2521           g_free (path);
2522           
2523           continue;
2524         }
2525
2526       suffix = suffix_from_name (name);
2527       if (suffix == ICON_SUFFIX_NONE)
2528         continue;
2529
2530       base_name = strip_suffix (name);
2531
2532       hash_suffix = GPOINTER_TO_INT (g_hash_table_lookup (dir->icons, base_name));
2533       g_hash_table_replace (icon_theme->all_icons, base_name, NULL);
2534       /* takes ownership of base_name */
2535       g_hash_table_replace (dir->icons, base_name, GUINT_TO_POINTER (hash_suffix| suffix));
2536     }
2537   
2538   g_dir_close (gdir);
2539 }
2540
2541 static void
2542 theme_subdir_load (GtkIconTheme *icon_theme,
2543                    IconTheme    *theme,
2544                    GKeyFile     *theme_file,
2545                    char         *subdir)
2546 {
2547   GList *d;
2548   char *type_string;
2549   IconThemeDir *dir;
2550   IconThemeDirType type;
2551   char *context_string;
2552   GQuark context;
2553   int size;
2554   int min_size;
2555   int max_size;
2556   int threshold;
2557   char *full_dir;
2558   GError *error = NULL;
2559   IconThemeDirMtime *dir_mtime;
2560
2561   size = g_key_file_get_integer (theme_file, subdir, "Size", &error);
2562   if (error)
2563     {
2564       g_error_free (error);
2565       g_warning ("Theme directory %s of theme %s has no size field\n", 
2566                  subdir, theme->name);
2567       return;
2568     }
2569   
2570   type = ICON_THEME_DIR_THRESHOLD;
2571   type_string = g_key_file_get_string (theme_file, subdir, "Type", NULL);
2572   if (type_string)
2573     {
2574       if (strcmp (type_string, "Fixed") == 0)
2575         type = ICON_THEME_DIR_FIXED;
2576       else if (strcmp (type_string, "Scalable") == 0)
2577         type = ICON_THEME_DIR_SCALABLE;
2578       else if (strcmp (type_string, "Threshold") == 0)
2579         type = ICON_THEME_DIR_THRESHOLD;
2580
2581       g_free (type_string);
2582     }
2583   
2584   context = 0;
2585   context_string = g_key_file_get_string (theme_file, subdir, "Context", NULL);
2586   if (context_string)
2587     {
2588       context = g_quark_from_string (context_string);
2589       g_free (context_string);
2590     }
2591
2592   if (g_key_file_has_key (theme_file, subdir, "MaxSize", NULL))
2593     max_size = g_key_file_get_integer (theme_file, subdir, "MaxSize", NULL);
2594   else
2595     max_size = size;
2596
2597   if (g_key_file_has_key (theme_file, subdir, "MinSize", NULL))
2598     min_size = g_key_file_get_integer (theme_file, subdir, "MinSize", NULL);
2599   else
2600     min_size = size;
2601
2602   if (g_key_file_has_key (theme_file, subdir, "Threshold", NULL))
2603     threshold = g_key_file_get_integer (theme_file, subdir, "Threshold", NULL);
2604   else
2605     threshold = 2;
2606
2607   for (d = icon_theme->priv->dir_mtimes; d; d = d->next)
2608     {
2609       dir_mtime = (IconThemeDirMtime *)d->data;
2610
2611       if (dir_mtime->mtime == 0)
2612         continue; /* directory doesn't exist */
2613
2614        full_dir = g_build_filename (dir_mtime->dir, subdir, NULL);
2615
2616       /* First, see if we have a cache for the directory */
2617       if (dir_mtime->cache != NULL || g_file_test (full_dir, G_FILE_TEST_IS_DIR))
2618         {
2619           if (dir_mtime->cache == NULL)
2620             {
2621               /* This will return NULL if the cache doesn't exist or is outdated */
2622               dir_mtime->cache = _gtk_icon_cache_new_for_path (dir_mtime->dir);
2623             }
2624           
2625           dir = g_new (IconThemeDir, 1);
2626           dir->type = type;
2627           dir->context = context;
2628           dir->size = size;
2629           dir->min_size = min_size;
2630           dir->max_size = max_size;
2631           dir->threshold = threshold;
2632           dir->dir = full_dir;
2633           dir->icon_data = NULL;
2634           dir->subdir = g_strdup (subdir);
2635           if (dir_mtime->cache != NULL)
2636             {
2637               dir->cache = _gtk_icon_cache_ref (dir_mtime->cache);
2638               dir->subdir_index = _gtk_icon_cache_get_directory_index (dir->cache, dir->subdir);
2639             }
2640           else
2641             {
2642               dir->cache = NULL;
2643               dir->subdir_index = -1;
2644               scan_directory (icon_theme->priv, dir, full_dir);
2645             }
2646
2647           theme->dirs = g_list_prepend (theme->dirs, dir);
2648         }
2649       else
2650         g_free (full_dir);
2651     }
2652 }
2653
2654 static void
2655 icon_data_free (GtkIconData *icon_data)
2656 {
2657   g_free (icon_data->attach_points);
2658   g_free (icon_data->display_name);
2659   g_slice_free (GtkIconData, icon_data);
2660 }
2661
2662 /*
2663  * GtkIconInfo
2664  */
2665
2666 G_DEFINE_BOXED_TYPE (GtkIconInfo, gtk_icon_info,
2667                      gtk_icon_info_copy,
2668                      gtk_icon_info_free)
2669
2670 static GtkIconInfo *
2671 icon_info_new (void)
2672 {
2673   GtkIconInfo *icon_info = g_slice_new0 (GtkIconInfo);
2674
2675   icon_info->scale = -1.;
2676   icon_info->ref_count = 1;
2677
2678   return icon_info;
2679 }
2680
2681 static GtkIconInfo *
2682 icon_info_new_builtin (BuiltinIcon *icon)
2683 {
2684   GtkIconInfo *icon_info = icon_info_new ();
2685
2686   icon_info->cache_pixbuf = g_object_ref (icon->pixbuf);
2687   icon_info->dir_type = ICON_THEME_DIR_THRESHOLD;
2688   icon_info->dir_size = icon->size;
2689   icon_info->threshold = 2;
2690
2691   return icon_info;
2692 }
2693
2694 /**
2695  * gtk_icon_info_copy:
2696  * @icon_info: a #GtkIconInfo
2697  * 
2698  * Make a copy of a #GtkIconInfo.
2699  * 
2700  * Return value: the new GtkIconInfo
2701  *
2702  * Since: 2.4
2703  **/
2704 GtkIconInfo *
2705 gtk_icon_info_copy (GtkIconInfo *icon_info)
2706 {
2707   
2708   g_return_val_if_fail (icon_info != NULL, NULL);
2709
2710   icon_info->ref_count++;
2711
2712   return icon_info;
2713 }
2714
2715 /**
2716  * gtk_icon_info_free:
2717  * @icon_info: a #GtkIconInfo
2718  * 
2719  * Free a #GtkIconInfo and associated information
2720  *
2721  * Since: 2.4
2722  **/
2723 void
2724 gtk_icon_info_free (GtkIconInfo *icon_info)
2725 {
2726   g_return_if_fail (icon_info != NULL);
2727
2728   icon_info->ref_count--;
2729   if (icon_info->ref_count > 0)
2730     return;
2731  
2732   g_free (icon_info->filename);
2733   if (icon_info->loadable)
2734     g_object_unref (icon_info->loadable);
2735   g_slist_free_full (icon_info->emblem_infos, (GDestroyNotify) gtk_icon_info_free);
2736   if (icon_info->pixbuf)
2737     g_object_unref (icon_info->pixbuf);
2738   if (icon_info->cache_pixbuf)
2739     g_object_unref (icon_info->cache_pixbuf);
2740
2741   g_slice_free (GtkIconInfo, icon_info);
2742 }
2743
2744 /**
2745  * gtk_icon_info_get_base_size:
2746  * @icon_info: a #GtkIconInfo
2747  * 
2748  * Gets the base size for the icon. The base size
2749  * is a size for the icon that was specified by
2750  * the icon theme creator. This may be different
2751  * than the actual size of image; an example of
2752  * this is small emblem icons that can be attached
2753  * to a larger icon. These icons will be given
2754  * the same base size as the larger icons to which
2755  * they are attached.
2756  * 
2757  * Return value: the base size, or 0, if no base
2758  *  size is known for the icon.
2759  *
2760  * Since: 2.4
2761  **/
2762 gint
2763 gtk_icon_info_get_base_size (GtkIconInfo *icon_info)
2764 {
2765   g_return_val_if_fail (icon_info != NULL, 0);
2766
2767   return icon_info->dir_size;
2768 }
2769
2770 /**
2771  * gtk_icon_info_get_filename:
2772  * @icon_info: a #GtkIconInfo
2773  * 
2774  * Gets the filename for the icon. If the
2775  * %GTK_ICON_LOOKUP_USE_BUILTIN flag was passed
2776  * to gtk_icon_theme_lookup_icon(), there may be
2777  * no filename if a builtin icon is returned; in this
2778  * case, you should use gtk_icon_info_get_builtin_pixbuf().
2779  * 
2780  * Return value: (type filename): the filename for the icon, or %NULL
2781  *  if gtk_icon_info_get_builtin_pixbuf() should be used instead. The
2782  *  return value is owned by GTK+ and should not be modified or freed.
2783  *
2784  * Since: 2.4
2785  **/
2786 const gchar *
2787 gtk_icon_info_get_filename (GtkIconInfo *icon_info)
2788 {
2789   g_return_val_if_fail (icon_info != NULL, NULL);
2790
2791   return icon_info->filename;
2792 }
2793
2794 /**
2795  * gtk_icon_info_get_builtin_pixbuf:
2796  * @icon_info: a #GtkIconInfo structure
2797  * 
2798  * Gets the built-in image for this icon, if any. To allow
2799  * GTK+ to use built in icon images, you must pass the
2800  * %GTK_ICON_LOOKUP_USE_BUILTIN to
2801  * gtk_icon_theme_lookup_icon().
2802  *
2803  * Return value: (transfer none): the built-in image pixbuf, or %NULL. No
2804  *  extra reference is added to the returned pixbuf, so if
2805  *  you want to keep it around, you must use g_object_ref().
2806  *  The returned image must not be modified.
2807  *
2808  * Since: 2.4
2809  **/
2810 GdkPixbuf *
2811 gtk_icon_info_get_builtin_pixbuf (GtkIconInfo *icon_info)
2812 {
2813   g_return_val_if_fail (icon_info != NULL, NULL);
2814
2815   if (icon_info->filename)
2816     return NULL;
2817   
2818   return icon_info->cache_pixbuf;
2819 }
2820
2821 static gboolean icon_info_ensure_scale_and_pixbuf (GtkIconInfo*, gboolean);
2822
2823 /* Combine the icon with all emblems, the first emblem is placed 
2824  * in the southeast corner. Scale emblems to be at most 3/4 of the
2825  * size of the icon itself.
2826  */
2827 static void 
2828 apply_emblems (GtkIconInfo *info)
2829 {
2830   GdkPixbuf *icon = NULL;
2831   gint w, h, pos;
2832   GSList *l;
2833
2834   if (info->emblem_infos == NULL)
2835     return;
2836
2837   if (info->emblems_applied)
2838     return;
2839
2840   w = gdk_pixbuf_get_width (info->pixbuf);
2841   h = gdk_pixbuf_get_height (info->pixbuf);
2842
2843   for (l = info->emblem_infos, pos = 0; l; l = l->next, pos++)
2844     {
2845       GtkIconInfo *emblem_info = l->data;
2846
2847       if (icon_info_ensure_scale_and_pixbuf (emblem_info, FALSE))
2848         {
2849           GdkPixbuf *emblem = emblem_info->pixbuf;
2850           gint ew, eh;
2851           gint x = 0, y = 0; /* silence compiler */
2852           gdouble scale;
2853
2854           ew = gdk_pixbuf_get_width (emblem);
2855           eh = gdk_pixbuf_get_height (emblem);
2856           if (ew >= w)
2857             {
2858               scale = 0.75;
2859               ew = ew * 0.75;
2860               eh = eh * 0.75;
2861             }
2862           else
2863             scale = 1.0;
2864
2865           switch (pos % 4)
2866             {
2867             case 0:
2868               x = w - ew;
2869               y = h - eh;
2870               break;
2871             case 1:
2872               x = w - ew;
2873               y = 0;
2874               break;
2875             case 2:
2876               x = 0;
2877               y = h - eh;
2878               break;
2879             case 3:
2880               x = 0;
2881               y = 0;
2882               break;
2883             }
2884
2885           if (icon == NULL)
2886             {
2887               icon = gdk_pixbuf_copy (info->pixbuf);
2888               if (icon == NULL)
2889                 break;
2890             }
2891
2892           gdk_pixbuf_composite (emblem, icon, x, y, ew, eh, x, y,
2893                                 scale, scale, GDK_INTERP_BILINEAR, 255);
2894        }
2895    }
2896
2897   if (icon)
2898     {
2899       g_object_unref (info->pixbuf);
2900       info->pixbuf = icon;
2901     }
2902
2903   info->emblems_applied = TRUE;
2904 }
2905
2906 /* This function contains the complicated logic for deciding
2907  * on the size at which to load the icon and loading it at
2908  * that size.
2909  */
2910 static gboolean
2911 icon_info_ensure_scale_and_pixbuf (GtkIconInfo  *icon_info,
2912                                    gboolean      scale_only)
2913 {
2914   int image_width, image_height;
2915   GdkPixbuf *source_pixbuf;
2916   gboolean is_svg;
2917
2918   /* First check if we already succeeded have the necessary
2919    * information (or failed earlier)
2920    */
2921   if (scale_only && icon_info->scale >= 0)
2922     return TRUE;
2923
2924   if (icon_info->pixbuf)
2925     {
2926       apply_emblems (icon_info);
2927       return TRUE;
2928     }
2929
2930   if (icon_info->load_error)
2931     return FALSE;
2932
2933   /* SVG icons are a special case - we just immediately scale them
2934    * to the desired size
2935    */
2936   if (icon_info->filename && !icon_info->loadable) 
2937     {
2938       GFile *file;
2939
2940       file = g_file_new_for_path (icon_info->filename);
2941       icon_info->loadable = G_LOADABLE_ICON (g_file_icon_new (file));
2942       g_object_unref (file);
2943     }
2944
2945   is_svg = FALSE;
2946   if (G_IS_FILE_ICON (icon_info->loadable))
2947     {
2948       GFile *file;
2949       GFileInfo *file_info;
2950       const gchar *content_type;
2951
2952       file = g_file_icon_get_file (G_FILE_ICON (icon_info->loadable));
2953       file_info = g_file_query_info (file, 
2954                                      G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
2955                                      G_FILE_QUERY_INFO_NONE,
2956                                      NULL, NULL);
2957       if (file_info) 
2958         {
2959           content_type = g_file_info_get_content_type (file_info);
2960
2961           if (content_type && strcmp (content_type, "image/svg+xml") == 0)
2962             is_svg = TRUE;
2963
2964           g_object_unref (file_info);
2965        }
2966     }
2967
2968   if (is_svg)
2969     {
2970       GInputStream *stream;
2971
2972       icon_info->scale = icon_info->desired_size / 1000.;
2973
2974       if (scale_only)
2975         return TRUE;
2976       
2977       stream = g_loadable_icon_load (icon_info->loadable,
2978                                      icon_info->desired_size,
2979                                      NULL, NULL,
2980                                      &icon_info->load_error);
2981       if (stream)
2982         {
2983           icon_info->pixbuf = gdk_pixbuf_new_from_stream_at_scale (stream,
2984                                                                    icon_info->desired_size,
2985                                                                    icon_info->desired_size,
2986                                                                    TRUE,
2987                                                                    NULL,
2988                                                                    &icon_info->load_error);
2989           g_object_unref (stream);
2990         }
2991
2992       if (!icon_info->pixbuf)
2993         return FALSE;
2994
2995       apply_emblems (icon_info);
2996         
2997       return TRUE;
2998     }
2999
3000   /* In many cases, the scale can be determined without actual access
3001    * to the icon file. This is generally true when we have a size
3002    * for the directory where the icon is; the image size doesn't
3003    * matter in that case.
3004    */
3005   if (icon_info->forced_size)
3006     icon_info->scale = -1;
3007   else if (icon_info->dir_type == ICON_THEME_DIR_FIXED)
3008     icon_info->scale = 1.0;
3009   else if (icon_info->dir_type == ICON_THEME_DIR_THRESHOLD)
3010     {
3011       if (icon_info->desired_size >= icon_info->dir_size - icon_info->threshold &&
3012           icon_info->desired_size <= icon_info->dir_size + icon_info->threshold)
3013         icon_info->scale = 1.0;
3014       else if (icon_info->dir_size > 0)
3015         icon_info->scale =(gdouble) icon_info->desired_size / icon_info->dir_size;
3016     }
3017   else if (icon_info->dir_type == ICON_THEME_DIR_SCALABLE)
3018     {
3019       if (icon_info->dir_size > 0)
3020         icon_info->scale = (gdouble) icon_info->desired_size / icon_info->dir_size;
3021     }
3022
3023   if (icon_info->scale >= 0. && scale_only)
3024     return TRUE;
3025
3026   /* At this point, we need to actually get the icon; either from the
3027    * builtin image or by loading the file
3028    */
3029   source_pixbuf = NULL;
3030   if (icon_info->cache_pixbuf)
3031     source_pixbuf = g_object_ref (icon_info->cache_pixbuf);
3032   else
3033     {
3034       GInputStream *stream;
3035
3036       stream = g_loadable_icon_load (icon_info->loadable,
3037                                      icon_info->desired_size,
3038                                      NULL, NULL,
3039                                      &icon_info->load_error);
3040       if (stream)
3041         {
3042           source_pixbuf = gdk_pixbuf_new_from_stream (stream,
3043                                                       NULL,
3044                                                       &icon_info->load_error);
3045           g_object_unref (stream);
3046         }
3047     }
3048
3049   if (!source_pixbuf)
3050     return FALSE;
3051
3052   /* Do scale calculations that depend on the image size
3053    */
3054   image_width = gdk_pixbuf_get_width (source_pixbuf);
3055   image_height = gdk_pixbuf_get_height (source_pixbuf);
3056
3057   if (icon_info->scale < 0.0)
3058     {
3059       gint image_size = MAX (image_width, image_height);
3060       if (image_size > 0)
3061         icon_info->scale = (gdouble)icon_info->desired_size / (gdouble)image_size;
3062       else
3063         icon_info->scale = 1.0;
3064       
3065       if (icon_info->dir_type == ICON_THEME_DIR_UNTHEMED && 
3066           !icon_info->forced_size)
3067         icon_info->scale = MIN (icon_info->scale, 1.0);
3068     }
3069
3070   /* We don't short-circuit out here for scale_only, since, now
3071    * we've loaded the icon, we might as well go ahead and finish
3072    * the job. This is a bit of a waste when we scale here
3073    * and never get the final pixbuf; at the cost of a bit of
3074    * extra complexity, we could keep the source pixbuf around
3075    * but not actually scale it until needed.
3076    */
3077   if (icon_info->scale == 1.0)
3078     icon_info->pixbuf = source_pixbuf;
3079   else
3080     {
3081       icon_info->pixbuf = gdk_pixbuf_scale_simple (source_pixbuf,
3082                                                    0.5 + image_width * icon_info->scale,
3083                                                    0.5 + image_height * icon_info->scale,
3084                                                    GDK_INTERP_BILINEAR);
3085       g_object_unref (source_pixbuf);
3086     }
3087
3088   apply_emblems (icon_info);
3089
3090   return TRUE;
3091 }
3092
3093 /**
3094  * gtk_icon_info_load_icon:
3095  * @icon_info: a #GtkIconInfo structure from gtk_icon_theme_lookup_icon()
3096  * @error: (allow-none): location to store error information on failure,
3097  *     or %NULL.
3098  *
3099  * Renders an icon previously looked up in an icon theme using
3100  * gtk_icon_theme_lookup_icon(); the size will be based on the size
3101  * passed to gtk_icon_theme_lookup_icon(). Note that the resulting
3102  * pixbuf may not be exactly this size; an icon theme may have icons
3103  * that differ slightly from their nominal sizes, and in addition GTK+
3104  * will avoid scaling icons that it considers sufficiently close to the
3105  * requested size or for which the source image would have to be scaled
3106  * up too far. (This maintains sharpness.). This behaviour can be changed
3107  * by passing the %GTK_ICON_LOOKUP_FORCE_SIZE flag when obtaining
3108  * the #GtkIconInfo. If this flag has been specified, the pixbuf
3109  * returned by this function will be scaled to the exact size.
3110  *
3111  * Return value: (transfer full): the rendered icon; this may be a newly
3112  *     created icon or a new reference to an internal icon, so you must
3113  *     not modify the icon. Use g_object_unref() to release your reference
3114  *     to the icon.
3115  *
3116  * Since: 2.4
3117  **/
3118 GdkPixbuf *
3119 gtk_icon_info_load_icon (GtkIconInfo *icon_info,
3120                          GError     **error)
3121 {
3122   g_return_val_if_fail (icon_info != NULL, NULL);
3123   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3124
3125   if (!icon_info_ensure_scale_and_pixbuf (icon_info, FALSE))
3126     {
3127       if (icon_info->load_error)
3128         g_propagate_error (error, icon_info->load_error);
3129       else
3130         g_set_error_literal (error,  
3131                              GTK_ICON_THEME_ERROR,  
3132                              GTK_ICON_THEME_NOT_FOUND,
3133                              _("Failed to load icon"));
3134  
3135       return NULL;
3136     }
3137
3138   return g_object_ref (icon_info->pixbuf);
3139 }
3140
3141 static gchar *
3142 gdk_color_to_css (GdkColor *color)
3143 {
3144   return g_strdup_printf ("rgb(%d,%d,%d)",
3145                           color->red >> 8,
3146                           color->green >> 8,
3147                           color->blue >> 8);
3148 }
3149
3150 static gchar *
3151 gdk_rgba_to_css (const GdkRGBA *color)
3152 {
3153   /* drop alpha for now, since librsvg does not understand rgba() */
3154   return g_strdup_printf ("rgb(%d,%d,%d)",
3155                           (gint)(color->red * 255),
3156                           (gint)(color->green * 255),
3157                           (gint)(color->blue * 255));
3158 }
3159
3160 static GdkPixbuf *
3161 _gtk_icon_info_load_symbolic_internal (GtkIconInfo  *icon_info,
3162                                        const gchar  *css_fg,
3163                                        const gchar  *css_success,
3164                                        const gchar  *css_warning,
3165                                        const gchar  *css_error,
3166                                        GError      **error)
3167 {
3168   GInputStream *stream;
3169   GdkPixbuf *pixbuf;
3170   gchar *data;
3171   gchar *success, *warning, *err;
3172
3173   /* css_fg can't possibly have failed, otherwise
3174    * that would mean we have a broken style */
3175   g_return_val_if_fail (css_fg != NULL, NULL);
3176
3177   success = warning = err = NULL;
3178
3179   if (!css_success)
3180     {
3181       GdkColor success_default_color = { 0, 0x4e00, 0x9a00, 0x0600 };
3182       success = gdk_color_to_css (&success_default_color);
3183     }
3184   if (!css_warning)
3185     {
3186       GdkColor warning_default_color = { 0, 0xf500, 0x7900, 0x3e00 };
3187       warning = gdk_color_to_css (&warning_default_color);
3188     }
3189   if (!css_error)
3190     {
3191       GdkColor error_default_color = { 0, 0xcc00, 0x0000, 0x0000 };
3192       err = gdk_color_to_css (&error_default_color);
3193     }
3194
3195
3196   data = g_strconcat ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
3197                       "<svg version=\"1.1\"\n"
3198                       "     xmlns=\"http://www.w3.org/2000/svg\"\n"
3199                       "     xmlns:xi=\"http://www.w3.org/2001/XInclude\"\n"
3200                       "     width=\"16\"\n"
3201                       "     height=\"16\">\n"
3202                       "  <style type=\"text/css\">\n"
3203                       "    rect,path {\n"
3204                       "      fill: ", css_fg," !important;\n"
3205                       "    }\n"
3206                       "    .warning {\n"
3207                       "      fill: ", css_warning ? css_warning : warning," !important;\n"
3208                       "    }\n"
3209                       "    .error {\n"
3210                       "      fill: ", css_error ? css_error : err," !important;\n"
3211                       "    }\n"
3212                       "    .success {\n"
3213                       "      fill: ", css_success ? css_success : success," !important;\n"
3214                       "    }\n"
3215                       "  </style>\n"
3216                       "  <xi:include href=\"", icon_info->filename, "\"/>\n"
3217                       "</svg>",
3218                       NULL);
3219   g_free (warning);
3220   g_free (err);
3221   g_free (success);
3222
3223   stream = g_memory_input_stream_new_from_data (data, -1, g_free);
3224   pixbuf = gdk_pixbuf_new_from_stream_at_scale (stream,
3225                                                 icon_info->desired_size,
3226                                                 icon_info->desired_size,
3227                                                 TRUE,
3228                                                 NULL,
3229                                                 error);
3230   g_object_unref (stream);
3231
3232   return pixbuf;
3233 }
3234
3235 /**
3236  * gtk_icon_info_load_symbolic:
3237  * @icon_info: a #GtkIconInfo
3238  * @fg: a #GdkRGBA representing the foreground color of the icon
3239  * @success_color: (allow-none): a #GdkRGBA representing the warning color
3240  *     of the icon or %NULL to use the default color
3241  * @warning_color: (allow-none): a #GdkRGBA representing the warning color
3242  *     of the icon or %NULL to use the default color
3243  * @error_color: (allow-none): a #GdkRGBA representing the error color
3244  *     of the icon or %NULL to use the default color (allow-none)
3245  * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
3246  *     loaded icon was a symbolic one and whether the @fg color was
3247  *     applied to it.
3248  * @error: (allow-none): location to store error information on failure,
3249  *     or %NULL.
3250  *
3251  * Loads an icon, modifying it to match the system colours for the foreground,
3252  * success, warning and error colors provided. If the icon is not a symbolic
3253  * one, the function will return the result from gtk_icon_info_load_icon().
3254  *
3255  * This allows loading symbolic icons that will match the system theme.
3256  *
3257  * Unless you are implementing a widget, you will want to use
3258  * g_themed_icon_new_with_default_fallbacks() to load the icon.
3259  *
3260  * As implementation details, the icon loaded needs to be of SVG type,
3261  * contain the "symbolic" term as the last component of the icon name,
3262  * and use the 'fg', 'success', 'warning' and 'error' CSS styles in the
3263  * SVG file itself.
3264  *
3265  * See the <ulink url="http://www.freedesktop.org/wiki/SymbolicIcons">Symbolic Icons spec</ulink>
3266  * for more information about symbolic icons.
3267  *
3268  * Return value: (transfer full): a #GdkPixbuf representing the loaded icon
3269  *
3270  * Since: 3.0
3271  **/
3272 GdkPixbuf *
3273 gtk_icon_info_load_symbolic (GtkIconInfo    *icon_info,
3274                              const GdkRGBA  *fg,
3275                              const GdkRGBA  *success_color,
3276                              const GdkRGBA  *warning_color,
3277                              const GdkRGBA  *error_color,
3278                              gboolean       *was_symbolic,
3279                              GError        **error)
3280 {
3281   GdkPixbuf *pixbuf;
3282   gchar *css_fg;
3283   gchar *css_success;
3284   gchar *css_warning;
3285   gchar *css_error;
3286
3287   g_return_val_if_fail (fg != NULL, NULL);
3288
3289   if (!icon_info->filename ||
3290       !g_str_has_suffix (icon_info->filename, "-symbolic.svg"))
3291     {
3292       if (was_symbolic)
3293         *was_symbolic = FALSE;
3294       return gtk_icon_info_load_icon (icon_info, error);
3295     }
3296
3297   if (was_symbolic)
3298     *was_symbolic = TRUE;
3299
3300   css_fg = gdk_rgba_to_css (fg);
3301
3302   css_success = css_warning = css_error = NULL;
3303
3304   if (warning_color)
3305     css_warning = gdk_rgba_to_css (warning_color);
3306
3307   if (error_color)
3308     css_error = gdk_rgba_to_css (error_color);
3309
3310   if (success_color)
3311     css_success = gdk_rgba_to_css (success_color);
3312
3313   pixbuf = _gtk_icon_info_load_symbolic_internal (icon_info,
3314                                                   css_fg, css_success,
3315                                                   css_warning, css_error,
3316                                                   error);
3317   g_free (css_fg);
3318   g_free (css_warning);
3319   g_free (css_success);
3320   g_free (css_error);
3321
3322   return pixbuf;
3323 }
3324
3325 /**
3326  * gtk_icon_info_load_symbolic_for_context:
3327  * @icon_info: a #GtkIconInfo
3328  * @context: a #GtkStyleContext
3329  * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
3330  *     loaded icon was a symbolic one and whether the @fg color was
3331  *     applied to it.
3332  * @error: (allow-none): location to store error information on failure,
3333  *     or %NULL.
3334  *
3335  * Loads an icon, modifying it to match the system colors for the foreground,
3336  * success, warning and error colors provided. If the icon is not a symbolic
3337  * one, the function will return the result from gtk_icon_info_load_icon().
3338  * This function uses the regular foreground color and the symbolic colors
3339  * with the names "success_color", "warning_color" and "error_color" from
3340  * the context.
3341  *
3342  * This allows loading symbolic icons that will match the system theme.
3343  *
3344  * See gtk_icon_info_load_symbolic() for more details.
3345  *
3346  * Return value: (transfer full): a #GdkPixbuf representing the loaded icon
3347  *
3348  * Since: 3.0
3349  **/
3350 GdkPixbuf *
3351 gtk_icon_info_load_symbolic_for_context (GtkIconInfo      *icon_info,
3352                                          GtkStyleContext  *context,
3353                                          gboolean         *was_symbolic,
3354                                          GError          **error)
3355 {
3356   GdkPixbuf *pixbuf;
3357   GdkRGBA *color = NULL;
3358   GdkRGBA rgba;
3359   gchar *css_fg = NULL, *css_success;
3360   gchar *css_warning, *css_error;
3361   GtkStateFlags state;
3362
3363   if (!icon_info->filename ||
3364       !g_str_has_suffix (icon_info->filename, "-symbolic.svg"))
3365     {
3366       if (was_symbolic)
3367         *was_symbolic = FALSE;
3368       return gtk_icon_info_load_icon (icon_info, error);
3369     }
3370
3371   if (was_symbolic)
3372     *was_symbolic = TRUE;
3373
3374   state = gtk_style_context_get_state (context);
3375   gtk_style_context_get (context, state, "color", &color, NULL);
3376   if (color)
3377     {
3378       css_fg = gdk_rgba_to_css (color);
3379       gdk_rgba_free (color);
3380     }
3381
3382   css_success = css_warning = css_error = NULL;
3383
3384   if (gtk_style_context_lookup_color (context, "success_color", &rgba))
3385     css_success = gdk_rgba_to_css (&rgba);
3386
3387   if (gtk_style_context_lookup_color (context, "warning_color", &rgba))
3388     css_warning = gdk_rgba_to_css (&rgba);
3389
3390   if (gtk_style_context_lookup_color (context, "error_color", &rgba))
3391     css_error = gdk_rgba_to_css (&rgba);
3392
3393   pixbuf = _gtk_icon_info_load_symbolic_internal (icon_info,
3394                                                   css_fg, css_success,
3395                                                   css_warning, css_error,
3396                                                   error);
3397
3398   g_free (css_fg);
3399   g_free (css_success);
3400   g_free (css_warning);
3401   g_free (css_error);
3402
3403   return pixbuf;
3404 }
3405
3406 /**
3407  * gtk_icon_info_load_symbolic_for_style:
3408  * @icon_info: a #GtkIconInfo
3409  * @style: a #GtkStyle to take the colors from
3410  * @state: the widget state to use for colors
3411  * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
3412  *     loaded icon was a symbolic one and whether the @fg color was
3413  *     applied to it.
3414  * @error: (allow-none): location to store error information on failure,
3415  *     or %NULL.
3416  *
3417  * Loads an icon, modifying it to match the system colours for the foreground,
3418  * success, warning and error colors provided. If the icon is not a symbolic
3419  * one, the function will return the result from gtk_icon_info_load_icon().
3420  *
3421  * This allows loading symbolic icons that will match the system theme.
3422  *
3423  * See gtk_icon_info_load_symbolic() for more details.
3424  *
3425  * Return value: (transfer full): a #GdkPixbuf representing the loaded icon
3426  *
3427  * Since: 3.0
3428  *
3429  * Deprecated: 3.0: Use gtk_icon_info_load_symbolic_for_context() instead
3430  **/
3431 GdkPixbuf *
3432 gtk_icon_info_load_symbolic_for_style (GtkIconInfo   *icon_info,
3433                                        GtkStyle      *style,
3434                                        GtkStateType   state,
3435                                        gboolean      *was_symbolic,
3436                                        GError       **error)
3437 {
3438   GdkPixbuf *pixbuf;
3439   GdkColor success_color;
3440   GdkColor warning_color;
3441   GdkColor error_color;
3442   GdkColor *fg;
3443   gchar *css_fg, *css_success;
3444   gchar *css_warning, *css_error;
3445
3446   if (!icon_info->filename ||
3447       !g_str_has_suffix (icon_info->filename, "-symbolic.svg"))
3448     {
3449       if (was_symbolic)
3450         *was_symbolic = FALSE;
3451       return gtk_icon_info_load_icon (icon_info, error);
3452     }
3453
3454   if (was_symbolic)
3455     *was_symbolic = TRUE;
3456
3457   fg = &style->fg[state];
3458   css_fg = gdk_color_to_css (fg);
3459
3460   css_success = css_warning = css_error = NULL;
3461
3462   if (gtk_style_lookup_color (style, "success_color", &success_color))
3463     css_success = gdk_color_to_css (&success_color);
3464
3465   if (gtk_style_lookup_color (style, "warning_color", &warning_color))
3466     css_warning = gdk_color_to_css (&warning_color);
3467
3468   if (gtk_style_lookup_color (style, "error_color", &error_color))
3469     css_error = gdk_color_to_css (&error_color);
3470
3471   pixbuf = _gtk_icon_info_load_symbolic_internal (icon_info,
3472                                                   css_fg, css_success,
3473                                                   css_warning, css_error,
3474                                                   error);
3475
3476   g_free (css_fg);
3477   g_free (css_success);
3478   g_free (css_warning);
3479   g_free (css_error);
3480
3481   return pixbuf;
3482 }
3483
3484 /**
3485  * gtk_icon_info_set_raw_coordinates:
3486  * @icon_info: a #GtkIconInfo
3487  * @raw_coordinates: whether the coordinates of embedded rectangles
3488  *   and attached points should be returned in their original
3489  *   (unscaled) form.
3490  * 
3491  * Sets whether the coordinates returned by gtk_icon_info_get_embedded_rect()
3492  * and gtk_icon_info_get_attach_points() should be returned in their
3493  * original form as specified in the icon theme, instead of scaled
3494  * appropriately for the pixbuf returned by gtk_icon_info_load_icon().
3495  *
3496  * Raw coordinates are somewhat strange; they are specified to be with
3497  * respect to the unscaled pixmap for PNG and XPM icons, but for SVG
3498  * icons, they are in a 1000x1000 coordinate space that is scaled
3499  * to the final size of the icon.  You can determine if the icon is an SVG
3500  * icon by using gtk_icon_info_get_filename(), and seeing if it is non-%NULL
3501  * and ends in '.svg'.
3502  *
3503  * This function is provided primarily to allow compatibility wrappers
3504  * for older API's, and is not expected to be useful for applications.
3505  *
3506  * Since: 2.4
3507  **/
3508 void
3509 gtk_icon_info_set_raw_coordinates (GtkIconInfo *icon_info,
3510                                    gboolean     raw_coordinates)
3511 {
3512   g_return_if_fail (icon_info != NULL);
3513   
3514   icon_info->raw_coordinates = raw_coordinates != FALSE;
3515 }
3516
3517 /* Scale coordinates from the icon data prior to returning
3518  * them to the user.
3519  */
3520 static gboolean
3521 icon_info_scale_point (GtkIconInfo  *icon_info,
3522                        gint          x,
3523                        gint          y,
3524                        gint         *x_out,
3525                        gint         *y_out)
3526 {
3527   if (icon_info->raw_coordinates)
3528     {
3529       *x_out = x;
3530       *y_out = y;
3531     }
3532   else
3533     {
3534       if (!icon_info_ensure_scale_and_pixbuf (icon_info, TRUE))
3535         return FALSE;
3536
3537       *x_out = 0.5 + x * icon_info->scale;
3538       *y_out = 0.5 + y * icon_info->scale;
3539     }
3540
3541   return TRUE;
3542 }
3543
3544 /**
3545  * gtk_icon_info_get_embedded_rect:
3546  * @icon_info: a #GtkIconInfo
3547  * @rectangle: (out): #GdkRectangle in which to store embedded
3548  *   rectangle coordinates; coordinates are only stored
3549  *   when this function returns %TRUE.
3550  *
3551  * Gets the coordinates of a rectangle within the icon
3552  * that can be used for display of information such
3553  * as a preview of the contents of a text file.
3554  * See gtk_icon_info_set_raw_coordinates() for further
3555  * information about the coordinate system.
3556  * 
3557  * Return value: %TRUE if the icon has an embedded rectangle
3558  *
3559  * Since: 2.4
3560  **/
3561 gboolean
3562 gtk_icon_info_get_embedded_rect (GtkIconInfo  *icon_info,
3563                                  GdkRectangle *rectangle)
3564 {
3565   g_return_val_if_fail (icon_info != NULL, FALSE);
3566
3567   if (icon_info->data && icon_info->data->has_embedded_rect &&
3568       icon_info_ensure_scale_and_pixbuf (icon_info, TRUE))
3569     {
3570       gint scaled_x0, scaled_y0;
3571       gint scaled_x1, scaled_y1;
3572       
3573       if (rectangle)
3574         {
3575           icon_info_scale_point (icon_info,
3576                                  icon_info->data->x0, icon_info->data->y0,
3577                                  &scaled_x0, &scaled_y0);
3578           icon_info_scale_point (icon_info,
3579                                  icon_info->data->x1, icon_info->data->y1,
3580                                  &scaled_x1, &scaled_y1);
3581           
3582           rectangle->x = scaled_x0;
3583           rectangle->y = scaled_y0;
3584           rectangle->width = scaled_x1 - rectangle->x;
3585           rectangle->height = scaled_y1 - rectangle->y;
3586         }
3587
3588       return TRUE;
3589     }
3590   else
3591     return FALSE;
3592 }
3593
3594 /**
3595  * gtk_icon_info_get_attach_points:
3596  * @icon_info: a #GtkIconInfo
3597  * @points: (allow-none) (array length=n_points) (out): location to store pointer to an array of points, or %NULL
3598  *          free the array of points with g_free().
3599  * @n_points: (allow-none): location to store the number of points in @points, or %NULL
3600  * 
3601  * Fetches the set of attach points for an icon. An attach point
3602  * is a location in the icon that can be used as anchor points for attaching
3603  * emblems or overlays to the icon.
3604  * 
3605  * Return value: %TRUE if there are any attach points for the icon.
3606  *
3607  * Since: 2.4
3608  **/
3609 gboolean
3610 gtk_icon_info_get_attach_points (GtkIconInfo *icon_info,
3611                                  GdkPoint   **points,
3612                                  gint        *n_points)
3613 {
3614   g_return_val_if_fail (icon_info != NULL, FALSE);
3615   
3616   if (icon_info->data && icon_info->data->n_attach_points &&
3617       icon_info_ensure_scale_and_pixbuf (icon_info, TRUE))
3618     {
3619       if (points)
3620         {
3621           gint i;
3622           
3623           *points = g_new (GdkPoint, icon_info->data->n_attach_points);
3624           for (i = 0; i < icon_info->data->n_attach_points; i++)
3625             icon_info_scale_point (icon_info,
3626                                    icon_info->data->attach_points[i].x,
3627                                    icon_info->data->attach_points[i].y,
3628                                    &(*points)[i].x,
3629                                    &(*points)[i].y);
3630         }
3631           
3632       if (n_points)
3633         *n_points = icon_info->data->n_attach_points;
3634
3635       return TRUE;
3636     }
3637   else
3638     {
3639       if (points)
3640         *points = NULL;
3641       if (n_points)
3642         *n_points = 0;
3643       
3644       return FALSE;
3645     }
3646 }
3647
3648 /**
3649  * gtk_icon_info_get_display_name:
3650  * @icon_info: a #GtkIconInfo
3651  * 
3652  * Gets the display name for an icon. A display name is a
3653  * string to be used in place of the icon name in a user
3654  * visible context like a list of icons.
3655  * 
3656  * Return value: the display name for the icon or %NULL, if
3657  *  the icon doesn't have a specified display name. This value
3658  *  is owned @icon_info and must not be modified or free.
3659  *
3660  * Since: 2.4
3661  **/
3662 const gchar *
3663 gtk_icon_info_get_display_name (GtkIconInfo *icon_info)
3664 {
3665   g_return_val_if_fail (icon_info != NULL, NULL);
3666
3667   if (icon_info->data)
3668     return icon_info->data->display_name;
3669   else
3670     return NULL;
3671 }
3672
3673 /*
3674  * Builtin icons
3675  */
3676
3677
3678 /**
3679  * gtk_icon_theme_add_builtin_icon:
3680  * @icon_name: the name of the icon to register
3681  * @size: the size at which to register the icon (different
3682  *        images can be registered for the same icon name
3683  *        at different sizes.)
3684  * @pixbuf: #GdkPixbuf that contains the image to use
3685  *          for @icon_name.
3686  * 
3687  * Registers a built-in icon for icon theme lookups. The idea
3688  * of built-in icons is to allow an application or library
3689  * that uses themed icons to function requiring files to
3690  * be present in the file system. For instance, the default
3691  * images for all of GTK+'s stock icons are registered
3692  * as built-icons.
3693  *
3694  * In general, if you use gtk_icon_theme_add_builtin_icon()
3695  * you should also install the icon in the icon theme, so
3696  * that the icon is generally available.
3697  *
3698  * This function will generally be used with pixbufs loaded
3699  * via gdk_pixbuf_new_from_inline().
3700  *
3701  * Since: 2.4
3702  **/
3703 void
3704 gtk_icon_theme_add_builtin_icon (const gchar *icon_name,
3705                                  gint         size,
3706                                  GdkPixbuf   *pixbuf)
3707 {
3708   BuiltinIcon *default_icon;
3709   GSList *icons;
3710   gpointer key;
3711
3712   g_return_if_fail (icon_name != NULL);
3713   g_return_if_fail (GDK_IS_PIXBUF (pixbuf));
3714   
3715   if (!icon_theme_builtin_icons)
3716     icon_theme_builtin_icons = g_hash_table_new (g_str_hash, g_str_equal);
3717
3718   icons = g_hash_table_lookup (icon_theme_builtin_icons, icon_name);
3719   if (!icons)
3720     key = g_strdup (icon_name);
3721   else
3722     key = (gpointer)icon_name;  /* Won't get stored */
3723
3724   default_icon = g_new (BuiltinIcon, 1);
3725   default_icon->size = size;
3726   default_icon->pixbuf = g_object_ref (pixbuf);
3727   icons = g_slist_prepend (icons, default_icon);
3728
3729   /* Replaces value, leaves key untouched
3730    */
3731   g_hash_table_insert (icon_theme_builtin_icons, key, icons);
3732 }
3733
3734 /* Look up a builtin icon; the min_difference_p and
3735  * has_larger_p out parameters allow us to combine
3736  * this lookup with searching through the actual directories
3737  * of the "hicolor" icon theme. See theme_lookup_icon()
3738  * for how they are used.
3739  */
3740 static BuiltinIcon *
3741 find_builtin_icon (const gchar *icon_name,
3742                    gint         size,
3743                    gint        *min_difference_p,
3744                    gboolean    *has_larger_p)
3745 {
3746   GSList *icons = NULL;
3747   gint min_difference = G_MAXINT;
3748   gboolean has_larger = FALSE;
3749   BuiltinIcon *min_icon = NULL;
3750   
3751   if (!icon_theme_builtin_icons)
3752     return NULL;
3753
3754   icons = g_hash_table_lookup (icon_theme_builtin_icons, icon_name);
3755
3756   while (icons)
3757     {
3758       BuiltinIcon *default_icon = icons->data;
3759       int min, max, difference;
3760       gboolean smaller;
3761       
3762       min = default_icon->size - 2;
3763       max = default_icon->size + 2;
3764       smaller = size < min;
3765       if (size < min)
3766         difference = min - size;
3767       else if (size > max)
3768         difference = size - max;
3769       else
3770         difference = 0;
3771       
3772       if (difference == 0)
3773         {
3774           min_icon = default_icon;
3775           break;
3776         }
3777       
3778       if (!has_larger)
3779         {
3780           if (difference < min_difference || smaller)
3781             {
3782               min_difference = difference;
3783               min_icon = default_icon;
3784               has_larger = smaller;
3785             }
3786         }
3787       else
3788         {
3789           if (difference < min_difference && smaller)
3790             {
3791               min_difference = difference;
3792               min_icon = default_icon;
3793             }
3794         }
3795       
3796       icons = icons->next;
3797     }
3798
3799   if (min_difference_p)
3800     *min_difference_p = min_difference;
3801   if (has_larger_p)
3802     *has_larger_p = has_larger;
3803
3804   return min_icon;
3805 }
3806
3807 void
3808 _gtk_icon_theme_check_reload (GdkDisplay *display)
3809 {
3810   gint n_screens, i;
3811   GdkScreen *screen;
3812   GtkIconTheme *icon_theme;
3813
3814   n_screens = gdk_display_get_n_screens (display);
3815   
3816   for (i = 0; i < n_screens; i++)
3817     {
3818       screen = gdk_display_get_screen (display, i);
3819
3820       icon_theme = g_object_get_data (G_OBJECT (screen), "gtk-icon-theme");
3821       if (icon_theme)
3822         {
3823           icon_theme->priv->check_reload = TRUE;
3824           ensure_valid_themes (icon_theme);
3825           icon_theme->priv->check_reload = FALSE;
3826         }
3827     }
3828 }
3829
3830
3831 /**
3832  * gtk_icon_theme_lookup_by_gicon:
3833  * @icon_theme: a #GtkIconTheme
3834  * @icon: the #GIcon to look up
3835  * @size: desired icon size
3836  * @flags: flags modifying the behavior of the icon lookup
3837  * 
3838  * Looks up an icon and returns a structure containing
3839  * information such as the filename of the icon. 
3840  * The icon can then be rendered into a pixbuf using
3841  * gtk_icon_info_load_icon().
3842  *
3843  * Return value: a #GtkIconInfo structure containing 
3844  *     information about the icon, or %NULL if the icon 
3845  *     wasn't found. Free with gtk_icon_info_free()
3846  *
3847  * Since: 2.14
3848  */
3849 GtkIconInfo *
3850 gtk_icon_theme_lookup_by_gicon (GtkIconTheme       *icon_theme,
3851                                 GIcon              *icon,
3852                                 gint                size,
3853                                 GtkIconLookupFlags  flags)
3854 {
3855   GtkIconInfo *info;
3856
3857   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
3858   g_return_val_if_fail (G_IS_ICON (icon), NULL);
3859
3860   if (G_IS_LOADABLE_ICON (icon))
3861     {
3862       info = icon_info_new ();
3863       info->loadable = G_LOADABLE_ICON (g_object_ref (icon));
3864
3865       info->dir_type = ICON_THEME_DIR_UNTHEMED;
3866       info->dir_size = size;
3867       info->desired_size = size;
3868       info->threshold = 2;
3869       info->forced_size = (flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0;
3870
3871       return info;
3872     }
3873   else if (G_IS_THEMED_ICON (icon))
3874     {
3875       const gchar **names;
3876
3877       names = (const gchar **)g_themed_icon_get_names (G_THEMED_ICON (icon));
3878       info = gtk_icon_theme_choose_icon (icon_theme, names, size, flags);
3879
3880       return info;
3881     }
3882   else if (G_IS_EMBLEMED_ICON (icon))
3883     {
3884       GIcon *base, *emblem;
3885       GList *list, *l;
3886       GtkIconInfo *emblem_info;
3887
3888       if (GTK_IS_NUMERABLE_ICON (icon))
3889         _gtk_numerable_icon_set_background_icon_size (GTK_NUMERABLE_ICON (icon), size / 2);
3890
3891       base = g_emblemed_icon_get_icon (G_EMBLEMED_ICON (icon));
3892       info = gtk_icon_theme_lookup_by_gicon (icon_theme, base, size, flags);
3893       if (info)
3894         {
3895           list = g_emblemed_icon_get_emblems (G_EMBLEMED_ICON (icon));
3896           for (l = list; l; l = l->next)
3897             {
3898               emblem = g_emblem_get_icon (G_EMBLEM (l->data));
3899               /* always force size for emblems */
3900               emblem_info = gtk_icon_theme_lookup_by_gicon (icon_theme, emblem, size / 2, flags | GTK_ICON_LOOKUP_FORCE_SIZE);
3901               if (emblem_info)
3902                 info->emblem_infos = g_slist_prepend (info->emblem_infos, emblem_info);
3903             }
3904         }
3905
3906       return info;
3907     }
3908   else if (GDK_IS_PIXBUF (icon))
3909     {
3910       GdkPixbuf *pixbuf;
3911
3912       pixbuf = GDK_PIXBUF (icon);
3913
3914       if ((flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0)
3915         {
3916           gint width, height, max;
3917           gdouble scale;
3918           GdkPixbuf *scaled;
3919
3920           width = gdk_pixbuf_get_width (pixbuf);
3921           height = gdk_pixbuf_get_height (pixbuf);
3922           max = MAX (width, height);
3923           scale = (gdouble) size / (gdouble) max;
3924
3925           scaled = gdk_pixbuf_scale_simple (pixbuf,
3926                                             0.5 + width * scale,
3927                                             0.5 + height * scale,
3928                                             GDK_INTERP_BILINEAR);
3929
3930           info = gtk_icon_info_new_for_pixbuf (icon_theme, scaled);
3931
3932           g_object_unref (scaled);
3933         }
3934       else
3935         {
3936           info = gtk_icon_info_new_for_pixbuf (icon_theme, pixbuf);
3937         }
3938
3939       return info;
3940     }
3941
3942   return NULL;
3943 }
3944
3945 /**
3946  * gtk_icon_info_new_for_pixbuf:
3947  * @icon_theme: a #GtkIconTheme
3948  * @pixbuf: the pixbuf to wrap in a #GtkIconInfo
3949  *
3950  * Creates a #GtkIconInfo for a #GdkPixbuf.
3951  *
3952  * Returns: a #GtkIconInfo
3953  *
3954  * Since: 2.14
3955  */
3956 GtkIconInfo *
3957 gtk_icon_info_new_for_pixbuf (GtkIconTheme *icon_theme,
3958                               GdkPixbuf    *pixbuf)
3959 {
3960   GtkIconInfo *info;
3961
3962   g_return_val_if_fail (GTK_IS_ICON_THEME (icon_theme), NULL);
3963   g_return_val_if_fail (GDK_IS_PIXBUF (pixbuf), NULL);
3964
3965   info = icon_info_new ();
3966   info->pixbuf = g_object_ref (pixbuf);
3967   info->scale = 1.0;
3968   info->dir_type = ICON_THEME_DIR_UNTHEMED;
3969
3970   return info;
3971 }