* add ModestIconFactory implementation
[modest] / src / modest-icon-factory.c
1 /* modest-icon-factory.c */
2
3 #include <string.h>
4 #include "modest-icon-factory.h"
5
6 static GHashTable *icon_hash = NULL;
7
8 static
9 gboolean equal_func (const gchar *s1, const gchar *s2)
10 {
11         return strcmp (s1, s2) == 0;
12 }
13
14 static
15 void free_pixbuf (GdkPixbuf *pixbuf)
16 {
17         if (pixbuf)
18                 g_object_unref (G_OBJECT(pixbuf));
19 }
20
21
22 void
23 modest_icon_factory_init   (void)
24 {
25         if (icon_hash) {
26                 g_warning ("modest_icon_factory_init "
27                            "should be called only once");
28                 return;
29         }
30
31         icon_hash = g_hash_table_new_full (g_str_hash,
32                                            (GEqualFunc)equal_func,
33                                            (GDestroyNotify)g_free,
34                                            (GDestroyNotify)free_pixbuf);
35 }
36
37
38 void
39 modest_icon_factory_uninit (void)
40 {
41         if (!icon_hash) {
42                 g_warning ("modest_icon_factory_uninit "
43                            "must only be called with initialized "
44                            "ModestIconFactories");
45                 return;
46         }
47
48         g_hash_table_destroy (icon_hash);
49         icon_hash = NULL;
50 }
51
52
53
54 GdkPixbuf*
55 modest_icon_factory_get_icon (const gchar *name)
56 {
57         GError *err = NULL;
58         GdkPixbuf *pixbuf;
59         gpointer orig_key;
60         
61         if (!icon_hash) {
62                 g_warning ("ModestIconFactory must be initialized first");
63                 return NULL;
64         }
65
66         /* is it already in the hashtable?
67          * note: this can be NULL
68          */
69         if (!g_hash_table_lookup_extended (icon_hash, name, &orig_key,
70                                            (gpointer*)&pixbuf)) {
71                 pixbuf = gdk_pixbuf_new_from_file (name, &err);
72                 if (!pixbuf) {
73                         g_warning (err->message);
74                         g_error_free (err);
75                 }
76                 /* if we cannot find it, we still insert, so we get the error
77                  * only once */
78                 g_hash_table_insert (icon_hash, g_strdup(name),
79                                      (gpointer)pixbuf);
80         }
81         return pixbuf;
82 }