d821f27e859be15912ea6b8d31cacdf711c0411a
[platform/upstream/glib.git] / gio / gicon.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include "gicon.h"
28 #include "gthemedicon.h"
29 #include "gfileicon.h"
30 #include "gemblemedicon.h"
31 #include "gfile.h"
32 #include "gioerror.h"
33
34 #include "glibintl.h"
35
36
37 /* There versioning of this is implicit, version 1 would be ".1 " */
38 #define G_ICON_SERIALIZATION_MAGIC0 ". "
39
40 /**
41  * SECTION:gicon
42  * @short_description: Interface for icons
43  * @include: gio/gio.h
44  *
45  * #GIcon is a very minimal interface for icons. It provides functions
46  * for checking the equality of two icons, hashing of icons and
47  * serializing an icon to and from strings.
48  *
49  * #GIcon does not provide the actual pixmap for the icon as this is out 
50  * of GIO's scope, however implementations of #GIcon may contain the name 
51  * of an icon (see #GThemedIcon), or the path to an icon (see #GLoadableIcon). 
52  * 
53  * To obtain a hash of a #GIcon, see g_icon_hash().
54  * 
55  * To check if two #GIcons are equal, see g_icon_equal().
56  *
57  * For serializing a #GIcon, use g_icon_to_string() and
58  * g_icon_new_for_string().
59  *
60  * If your application or library provides one or more #GIcon
61  * implementations you need to ensure that each #GType is registered
62  * with the type system prior to calling g_icon_new_for_string().
63  **/
64
65 typedef GIconIface GIconInterface;
66 G_DEFINE_INTERFACE(GIcon, g_icon, G_TYPE_OBJECT)
67
68 static void
69 g_icon_default_init (GIconInterface *iface)
70 {
71 }
72
73 /**
74  * g_icon_hash:
75  * @icon: #gconstpointer to an icon object.
76  * 
77  * Gets a hash for an icon.
78  * 
79  * Returns: a #guint containing a hash for the @icon, suitable for 
80  * use in a #GHashTable or similar data structure.
81  **/
82 guint
83 g_icon_hash (gconstpointer icon)
84 {
85   GIconIface *iface;
86
87   g_return_val_if_fail (G_IS_ICON (icon), 0);
88
89   iface = G_ICON_GET_IFACE (icon);
90
91   return (* iface->hash) ((GIcon *)icon);
92 }
93
94 /**
95  * g_icon_equal:
96  * @icon1: pointer to the first #GIcon.
97  * @icon2: pointer to the second #GIcon.
98  * 
99  * Checks if two icons are equal.
100  * 
101  * Returns: %TRUE if @icon1 is equal to @icon2. %FALSE otherwise.
102  **/
103 gboolean
104 g_icon_equal (GIcon *icon1,
105               GIcon *icon2)
106 {
107   GIconIface *iface;
108
109   if (icon1 == NULL && icon2 == NULL)
110     return TRUE;
111
112   if (icon1 == NULL || icon2 == NULL)
113     return FALSE;
114   
115   if (G_TYPE_FROM_INSTANCE (icon1) != G_TYPE_FROM_INSTANCE (icon2))
116     return FALSE;
117
118   iface = G_ICON_GET_IFACE (icon1);
119   
120   return (* iface->equal) (icon1, icon2);
121 }
122
123 static gboolean
124 g_icon_to_string_tokenized (GIcon *icon, GString *s)
125 {
126   char *ret;
127   GPtrArray *tokens;
128   gint version;
129   GIconIface *icon_iface;
130   int i;
131
132   g_return_val_if_fail (icon != NULL, FALSE);
133   g_return_val_if_fail (G_IS_ICON (icon), FALSE);
134
135   ret = NULL;
136
137   icon_iface = G_ICON_GET_IFACE (icon);
138   if (icon_iface->to_tokens == NULL)
139     return FALSE;
140
141   tokens = g_ptr_array_new ();
142   if (!icon_iface->to_tokens (icon, tokens, &version))
143     {
144       g_ptr_array_free (tokens, TRUE);
145       return FALSE;
146     }
147
148   /* format: TypeName[.Version] <token_0> .. <token_N-1>
149      version 0 is implicit and can be omitted
150      all the tokens are url escaped to ensure they have no spaces in them */
151   
152   g_string_append (s, g_type_name_from_instance ((GTypeInstance *)icon));
153   if (version != 0)
154     g_string_append_printf (s, ".%d", version);
155   
156   for (i = 0; i < tokens->len; i++)
157     {
158       char *token;
159
160       token = g_ptr_array_index (tokens, i);
161
162       g_string_append_c (s, ' ');
163       /* We really only need to escape spaces here, so allow lots of otherwise reserved chars */
164       g_string_append_uri_escaped (s, token,
165                                    G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
166
167       g_free (token);
168     }
169   
170   g_ptr_array_free (tokens, TRUE);
171   
172   return TRUE;
173 }
174
175 /**
176  * g_icon_to_string:
177  * @icon: a #GIcon.
178  *
179  * Generates a textual representation of @icon that can be used for
180  * serialization such as when passing @icon to a different process or
181  * saving it to persistent storage. Use g_icon_new_for_string() to
182  * get @icon back from the returned string.
183  *
184  * The encoding of the returned string is proprietary to #GIcon except
185  * in the following two cases
186  *
187  * <itemizedlist>
188  * <listitem><para>
189  *     If @icon is a #GFileIcon, the returned string is a native path
190  *     (such as <literal>/path/to/my icon.png</literal>) without escaping
191  *     if the #GFile for @icon is a native file.  If the file is not
192  *     native, the returned string is the result of g_file_get_uri()
193  *     (such as <literal>sftp://path/to/my%%20icon.png</literal>).
194  * </para></listitem>
195  * <listitem><para>
196  *    If @icon is a #GThemedIcon with exactly one name, the encoding is
197  *    simply the name (such as <literal>network-server</literal>).
198  * </para></listitem>
199  * </itemizedlist>
200  *
201  * Returns: An allocated NUL-terminated UTF8 string or %NULL if @icon can't
202  * be serialized. Use g_free() to free.
203  *
204  * Since: 2.20
205  */
206 gchar *
207 g_icon_to_string (GIcon *icon)
208 {
209   gchar *ret;
210
211   g_return_val_if_fail (icon != NULL, NULL);
212   g_return_val_if_fail (G_IS_ICON (icon), NULL);
213
214   ret = NULL;
215
216   if (G_IS_FILE_ICON (icon))
217     {
218       GFile *file;
219
220       file = g_file_icon_get_file (G_FILE_ICON (icon));
221       if (g_file_is_native (file))
222         {
223           ret = g_file_get_path (file);
224           if (!g_utf8_validate (ret, -1, NULL))
225             {
226               g_free (ret);
227               ret = NULL;
228             }
229         }
230       else
231         ret = g_file_get_uri (file);
232     }
233   else if (G_IS_THEMED_ICON (icon))
234     {
235       const char * const *names;
236
237       names = g_themed_icon_get_names (G_THEMED_ICON (icon));
238       if (names != NULL &&
239           names[0] != NULL &&
240           names[0][0] != '.' && /* Allowing icons starting with dot would break G_ICON_SERIALIZATION_MAGIC0 */
241           g_utf8_validate (names[0], -1, NULL) && /* Only return utf8 strings */
242           names[1] == NULL)
243         ret = g_strdup (names[0]);
244     }
245
246   if (ret == NULL)
247     {
248       GString *s;
249
250       s = g_string_new (G_ICON_SERIALIZATION_MAGIC0);
251
252       if (g_icon_to_string_tokenized (icon, s))
253         ret = g_string_free (s, FALSE);
254       else
255         g_string_free (s, TRUE);
256     }
257
258   return ret;
259 }
260
261 static GIcon *
262 g_icon_new_from_tokens (char   **tokens,
263                         GError **error)
264 {
265   GIcon *icon;
266   char *typename, *version_str;
267   GType type;
268   gpointer klass;
269   GIconIface *icon_iface;
270   gint version;
271   char *endp;
272   int num_tokens;
273   int i;
274
275   icon = NULL;
276   klass = NULL;
277
278   num_tokens = g_strv_length (tokens);
279
280   if (num_tokens < 1)
281     {
282       g_set_error (error,
283                    G_IO_ERROR,
284                    G_IO_ERROR_INVALID_ARGUMENT,
285                    _("Wrong number of tokens (%d)"),
286                    num_tokens);
287       goto out;
288     }
289   
290   typename = tokens[0];
291   version_str = strchr (typename, '.');
292   if (version_str)
293     {
294       *version_str = 0;
295       version_str += 1;
296     }
297   
298   
299   type = g_type_from_name (tokens[0]);
300   if (type == 0)
301     {
302       g_set_error (error,
303                    G_IO_ERROR,
304                    G_IO_ERROR_INVALID_ARGUMENT,
305                    _("No type for class name %s"),
306                    tokens[0]);
307       goto out;
308     }
309
310   if (!g_type_is_a (type, G_TYPE_ICON))
311     {
312       g_set_error (error,
313                    G_IO_ERROR,
314                    G_IO_ERROR_INVALID_ARGUMENT,
315                    _("Type %s does not implement the GIcon interface"),
316                    tokens[0]);
317       goto out;
318     }
319
320   klass = g_type_class_ref (type);
321   if (klass == NULL)
322     {
323       g_set_error (error,
324                    G_IO_ERROR,
325                    G_IO_ERROR_INVALID_ARGUMENT,
326                    _("Type %s is not classed"),
327                    tokens[0]);
328       goto out;
329     }
330
331   version = 0;
332   if (version_str)
333     {
334       version = strtol (version_str, &endp, 10);
335       if (endp == NULL || *endp != '\0')
336         {
337           g_set_error (error,
338                        G_IO_ERROR,
339                        G_IO_ERROR_INVALID_ARGUMENT,
340                        _("Malformed version number: %s"),
341                        version_str);
342           goto out;
343         }
344     }
345
346   icon_iface = g_type_interface_peek (klass, G_TYPE_ICON);
347   g_assert (icon_iface != NULL);
348
349   if (icon_iface->from_tokens == NULL)
350     {
351       g_set_error (error,
352                    G_IO_ERROR,
353                    G_IO_ERROR_INVALID_ARGUMENT,
354                    _("Type %s does not implement from_tokens() on the GIcon interface"),
355                    tokens[0]);
356       goto out;
357     }
358
359   for (i = 1;  i < num_tokens; i++)
360     {
361       char *escaped;
362
363       escaped = tokens[i];
364       tokens[i] = g_uri_unescape_string (escaped, NULL);
365       g_free (escaped);
366     }
367   
368   icon = icon_iface->from_tokens (tokens + 1, num_tokens - 1, version, error);
369
370  out:
371   if (klass != NULL)
372     g_type_class_unref (klass);
373   return icon;
374 }
375
376 static void
377 ensure_builtin_icon_types (void)
378 {
379   static volatile GType t;
380   t = g_themed_icon_get_type ();
381   t = g_file_icon_get_type ();
382   t = g_emblemed_icon_get_type ();
383   t = g_emblem_get_type ();
384 }
385
386 /**
387  * g_icon_new_for_string:
388  * @str: A string obtained via g_icon_to_string().
389  * @error: Return location for error.
390  *
391  * Generate a #GIcon instance from @str. This function can fail if
392  * @str is not valid - see g_icon_to_string() for discussion.
393  *
394  * If your application or library provides one or more #GIcon
395  * implementations you need to ensure that each #GType is registered
396  * with the type system prior to calling g_icon_new_for_string().
397  *
398  * Returns: An object implementing the #GIcon interface or %NULL if
399  * @error is set.
400  *
401  * Since: 2.20
402  **/
403 GIcon *
404 g_icon_new_for_string (const gchar   *str,
405                        GError       **error)
406 {
407   GIcon *icon;
408
409   g_return_val_if_fail (str != NULL, NULL);
410
411   ensure_builtin_icon_types ();
412
413   icon = NULL;
414
415   if (*str == '.')
416     {
417       if (g_str_has_prefix (str, G_ICON_SERIALIZATION_MAGIC0))
418         {
419           gchar **tokens;
420           
421           /* handle tokenized encoding */
422           tokens = g_strsplit (str + sizeof (G_ICON_SERIALIZATION_MAGIC0) - 1, " ", 0);
423           icon = g_icon_new_from_tokens (tokens, error);
424           g_strfreev (tokens);
425         }
426       else
427         g_set_error_literal (error,
428                              G_IO_ERROR,
429                              G_IO_ERROR_INVALID_ARGUMENT,
430                              _("Can't handle the supplied version the icon encoding"));
431     }
432   else
433     {
434       gchar *scheme;
435
436       /* handle special GFileIcon and GThemedIcon cases */
437       scheme = g_uri_parse_scheme (str);
438       if (scheme != NULL || str[0] == '/')
439         {
440           GFile *location;
441           location = g_file_new_for_commandline_arg (str);
442           icon = g_file_icon_new (location);
443           g_object_unref (location);
444         }
445       else
446         icon = g_themed_icon_new (str);
447       g_free (scheme);
448     }
449
450   return icon;
451 }