95d47d4c6d43523dd66ce1a01b0be169dc4056c4
[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 "gbytesicon.h"
32 #include "gfile.h"
33 #include "gioerror.h"
34 #include "gioenumtypes.h"
35 #include "gvfs.h"
36
37 #include "glibintl.h"
38
39
40 /* There versioning of this is implicit, version 1 would be ".1 " */
41 #define G_ICON_SERIALIZATION_MAGIC0 ". "
42
43 /**
44  * SECTION:gicon
45  * @short_description: Interface for icons
46  * @include: gio/gio.h
47  *
48  * #GIcon is a very minimal interface for icons. It provides functions
49  * for checking the equality of two icons, hashing of icons and
50  * serializing an icon to and from strings.
51  *
52  * #GIcon does not provide the actual pixmap for the icon as this is out 
53  * of GIO's scope, however implementations of #GIcon may contain the name 
54  * of an icon (see #GThemedIcon), or the path to an icon (see #GLoadableIcon). 
55  *
56  * To obtain a hash of a #GIcon, see g_icon_hash().
57  *
58  * To check if two #GIcons are equal, see g_icon_equal().
59  *
60  * For serializing a #GIcon, use g_icon_serialize() and
61  * g_icon_deserialize().
62  *
63  * If you want to consume #GIcon (for example, in a toolkit) you must
64  * be prepared to handle at least the three following cases:
65  * #GLoadableIcon, #GThemedIcon and #GEmblemedIcon.  It may also make
66  * sense to have fast-paths for other cases (like handling #GdkPixbuf
67  * directly, for example) but all compliant #GIcon implementations
68  * outside of GIO must implement #GLoadableIcon.
69  *
70  * If your application or library provides one or more #GIcon
71  * implementations you need to ensure that your new implementation also
72  * implements #GLoadableIcon.  Additionally, you must provide an
73  * implementation of g_icon_serialize() that gives a result that is
74  * understood by g_icon_deserialize(), yielding one of the built-in icon
75  * types.
76  **/
77
78 typedef GIconIface GIconInterface;
79 G_DEFINE_INTERFACE(GIcon, g_icon, G_TYPE_OBJECT)
80
81 static void
82 g_icon_default_init (GIconInterface *iface)
83 {
84 }
85
86 /**
87  * g_icon_hash:
88  * @icon: #gconstpointer to an icon object.
89  * 
90  * Gets a hash for an icon.
91  *
92  * Virtual: hash
93  * Returns: a #guint containing a hash for the @icon, suitable for 
94  * use in a #GHashTable or similar data structure.
95  **/
96 guint
97 g_icon_hash (gconstpointer icon)
98 {
99   GIconIface *iface;
100
101   g_return_val_if_fail (G_IS_ICON (icon), 0);
102
103   iface = G_ICON_GET_IFACE (icon);
104
105   return (* iface->hash) ((GIcon *)icon);
106 }
107
108 /**
109  * g_icon_equal:
110  * @icon1: (allow-none): pointer to the first #GIcon.
111  * @icon2: (allow-none): pointer to the second #GIcon.
112  * 
113  * Checks if two icons are equal.
114  * 
115  * Returns: %TRUE if @icon1 is equal to @icon2. %FALSE otherwise.
116  **/
117 gboolean
118 g_icon_equal (GIcon *icon1,
119               GIcon *icon2)
120 {
121   GIconIface *iface;
122
123   if (icon1 == NULL && icon2 == NULL)
124     return TRUE;
125
126   if (icon1 == NULL || icon2 == NULL)
127     return FALSE;
128   
129   if (G_TYPE_FROM_INSTANCE (icon1) != G_TYPE_FROM_INSTANCE (icon2))
130     return FALSE;
131
132   iface = G_ICON_GET_IFACE (icon1);
133   
134   return (* iface->equal) (icon1, icon2);
135 }
136
137 static gboolean
138 g_icon_to_string_tokenized (GIcon *icon, GString *s)
139 {
140   GPtrArray *tokens;
141   gint version;
142   GIconIface *icon_iface;
143   int i;
144
145   g_return_val_if_fail (icon != NULL, FALSE);
146   g_return_val_if_fail (G_IS_ICON (icon), FALSE);
147
148   icon_iface = G_ICON_GET_IFACE (icon);
149   if (icon_iface->to_tokens == NULL)
150     return FALSE;
151
152   tokens = g_ptr_array_new ();
153   if (!icon_iface->to_tokens (icon, tokens, &version))
154     {
155       g_ptr_array_free (tokens, TRUE);
156       return FALSE;
157     }
158
159   /* format: TypeName[.Version] <token_0> .. <token_N-1>
160      version 0 is implicit and can be omitted
161      all the tokens are url escaped to ensure they have no spaces in them */
162   
163   g_string_append (s, g_type_name_from_instance ((GTypeInstance *)icon));
164   if (version != 0)
165     g_string_append_printf (s, ".%d", version);
166   
167   for (i = 0; i < tokens->len; i++)
168     {
169       char *token;
170
171       token = g_ptr_array_index (tokens, i);
172
173       g_string_append_c (s, ' ');
174       /* We really only need to escape spaces here, so allow lots of otherwise reserved chars */
175       g_string_append_uri_escaped (s, token,
176                                    G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
177
178       g_free (token);
179     }
180   
181   g_ptr_array_free (tokens, TRUE);
182   
183   return TRUE;
184 }
185
186 /**
187  * g_icon_to_string:
188  * @icon: a #GIcon.
189  *
190  * Generates a textual representation of @icon that can be used for
191  * serialization such as when passing @icon to a different process or
192  * saving it to persistent storage. Use g_icon_new_for_string() to
193  * get @icon back from the returned string.
194  *
195  * The encoding of the returned string is proprietary to #GIcon except
196  * in the following two cases
197  *
198  * <itemizedlist>
199  * <listitem><para>
200  *     If @icon is a #GFileIcon, the returned string is a native path
201  *     (such as <literal>/path/to/my icon.png</literal>) without escaping
202  *     if the #GFile for @icon is a native file.  If the file is not
203  *     native, the returned string is the result of g_file_get_uri()
204  *     (such as <literal>sftp://path/to/my&percnt;20icon.png</literal>).
205  * </para></listitem>
206  * <listitem><para>
207  *    If @icon is a #GThemedIcon with exactly one name, the encoding is
208  *    simply the name (such as <literal>network-server</literal>).
209  * </para></listitem>
210  * </itemizedlist>
211  *
212  * Virtual: to_tokens
213  * Returns: An allocated NUL-terminated UTF8 string or %NULL if @icon can't
214  * be serialized. Use g_free() to free.
215  *
216  * Since: 2.20
217  */
218 gchar *
219 g_icon_to_string (GIcon *icon)
220 {
221   gchar *ret;
222
223   g_return_val_if_fail (icon != NULL, NULL);
224   g_return_val_if_fail (G_IS_ICON (icon), NULL);
225
226   ret = NULL;
227
228   if (G_IS_FILE_ICON (icon))
229     {
230       GFile *file;
231
232       file = g_file_icon_get_file (G_FILE_ICON (icon));
233       if (g_file_is_native (file))
234         {
235           ret = g_file_get_path (file);
236           if (!g_utf8_validate (ret, -1, NULL))
237             {
238               g_free (ret);
239               ret = NULL;
240             }
241         }
242       else
243         ret = g_file_get_uri (file);
244     }
245   else if (G_IS_THEMED_ICON (icon))
246     {
247       const char * const *names;
248
249       names = g_themed_icon_get_names (G_THEMED_ICON (icon));
250       if (names != NULL &&
251           names[0] != NULL &&
252           names[0][0] != '.' && /* Allowing icons starting with dot would break G_ICON_SERIALIZATION_MAGIC0 */
253           g_utf8_validate (names[0], -1, NULL) && /* Only return utf8 strings */
254           names[1] == NULL)
255         ret = g_strdup (names[0]);
256     }
257
258   if (ret == NULL)
259     {
260       GString *s;
261
262       s = g_string_new (G_ICON_SERIALIZATION_MAGIC0);
263
264       if (g_icon_to_string_tokenized (icon, s))
265         ret = g_string_free (s, FALSE);
266       else
267         g_string_free (s, TRUE);
268     }
269
270   return ret;
271 }
272
273 static GIcon *
274 g_icon_new_from_tokens (char   **tokens,
275                         GError **error)
276 {
277   GIcon *icon;
278   char *typename, *version_str;
279   GType type;
280   gpointer klass;
281   GIconIface *icon_iface;
282   gint version;
283   char *endp;
284   int num_tokens;
285   int i;
286
287   num_tokens = g_strv_length (tokens);
288
289   g_return_val_if_fail (num_tokens >= 1, NULL);
290   
291   typename = tokens[0];
292   version_str = strchr (typename, '.');
293   if (version_str)
294     {
295       *version_str = 0;
296       version_str += 1;
297     }
298   
299   
300   type = g_type_from_name (tokens[0]);
301   g_return_val_if_fail (type != 0, NULL);
302   g_return_val_if_fail (g_type_is_a (type, G_TYPE_ICON), NULL);
303
304   klass = g_type_class_ref (type);
305   g_return_val_if_fail (klass, NULL);
306
307   version = 0;
308   if (version_str)
309     {
310       version = strtol (version_str, &endp, 10);
311       g_return_val_if_fail (endp && *endp, NULL);
312     }
313
314   icon_iface = g_type_interface_peek (klass, G_TYPE_ICON);
315   g_assert (icon_iface != NULL);
316
317   g_return_val_if_fail (icon_iface->from_tokens, NULL);
318
319   for (i = 1;  i < num_tokens; i++)
320     {
321       char *escaped;
322
323       escaped = tokens[i];
324       tokens[i] = g_uri_unescape_string (escaped, NULL);
325       g_free (escaped);
326     }
327   
328   icon = icon_iface->from_tokens (tokens + 1, num_tokens - 1, version, error);
329
330   g_type_class_unref (klass);
331   return icon;
332 }
333
334 static void
335 ensure_builtin_icon_types (void)
336 {
337   g_type_ensure (G_TYPE_THEMED_ICON);
338   g_type_ensure (G_TYPE_FILE_ICON);
339   g_type_ensure (G_TYPE_EMBLEMED_ICON);
340   g_type_ensure (G_TYPE_EMBLEM);
341 }
342
343 /* handles the 'simple' cases: GFileIcon and GThemedIcon */
344 static GIcon *
345 g_icon_new_for_string_simple (const gchar *str)
346 {
347   gchar *scheme;
348   GIcon *icon;
349
350   if (str[0] == '.')
351     return NULL;
352
353   /* handle special GFileIcon and GThemedIcon cases */
354   scheme = g_uri_parse_scheme (str);
355   if (scheme != NULL || str[0] == '/' || str[0] == G_DIR_SEPARATOR)
356     {
357       GFile *location;
358       location = g_file_new_for_commandline_arg (str);
359       icon = g_file_icon_new (location);
360       g_object_unref (location);
361     }
362   else
363     icon = g_themed_icon_new (str);
364
365   g_free (scheme);
366
367   return icon;
368 }
369
370 /**
371  * g_icon_new_for_string:
372  * @str: A string obtained via g_icon_to_string().
373  * @error: Return location for error.
374  *
375  * Generate a #GIcon instance from @str. This function can fail if
376  * @str is not valid - see g_icon_to_string() for discussion.
377  *
378  * If your application or library provides one or more #GIcon
379  * implementations you need to ensure that each #GType is registered
380  * with the type system prior to calling g_icon_new_for_string().
381  *
382  * Returns: (transfer full): An object implementing the #GIcon
383  *          interface or %NULL if @error is set.
384  *
385  * Since: 2.20
386  **/
387 GIcon *
388 g_icon_new_for_string (const gchar   *str,
389                        GError       **error)
390 {
391   GIcon *icon = NULL;
392
393   g_return_val_if_fail (str != NULL, NULL);
394
395   icon = g_icon_new_for_string_simple (str);
396   if (icon)
397     return icon;
398
399   ensure_builtin_icon_types ();
400
401   if (g_str_has_prefix (str, G_ICON_SERIALIZATION_MAGIC0))
402     {
403       gchar **tokens;
404
405       /* handle tokenized encoding */
406       tokens = g_strsplit (str + sizeof (G_ICON_SERIALIZATION_MAGIC0) - 1, " ", 0);
407       icon = g_icon_new_from_tokens (tokens, error);
408       g_strfreev (tokens);
409     }
410   else
411     g_set_error_literal (error,
412                          G_IO_ERROR,
413                          G_IO_ERROR_INVALID_ARGUMENT,
414                          "Can't handle the supplied version of the icon encoding");
415
416   return icon;
417 }
418
419 static GEmblem *
420 g_icon_deserialize_emblem (GVariant *value)
421 {
422   GVariant *emblem_metadata;
423   GVariant *emblem_data;
424   const gchar *origin_nick;
425   GIcon *emblem_icon;
426   GEmblem *emblem;
427
428   g_variant_get (value, "(v@a{sv})", &emblem_data, &emblem_metadata);
429
430   emblem = NULL;
431
432   emblem_icon = g_icon_deserialize (emblem_data);
433   if (emblem_icon != NULL)
434     {
435       /* Check if we should create it with an origin. */
436       if (g_variant_lookup (emblem_metadata, "origin", "&s", &origin_nick))
437         {
438           GEnumClass *origin_class;
439           GEnumValue *origin_value;
440
441           origin_class = g_type_class_ref (G_TYPE_EMBLEM_ORIGIN);
442           origin_value = g_enum_get_value_by_nick (origin_class, origin_nick);
443           if (origin_value)
444             emblem = g_emblem_new_with_origin (emblem_icon, origin_value->value);
445           g_type_class_unref (origin_class);
446         }
447
448       /* We didn't create it with an origin, so do it without. */
449       if (emblem == NULL)
450         emblem = g_emblem_new (emblem_icon);
451
452       g_object_unref (emblem_icon);
453     }
454
455   g_variant_unref (emblem_metadata);
456   g_variant_unref (emblem_data);
457
458   return emblem;
459 }
460
461 static GIcon *
462 g_icon_deserialize_emblemed (GVariant *value)
463 {
464   GVariantIter *emblems;
465   GVariant *icon_data;
466   GIcon *main_icon;
467   GIcon *icon;
468
469   g_variant_get (value, "(va(va{sv}))", &icon_data, &emblems);
470   main_icon = g_icon_deserialize (icon_data);
471
472   if (main_icon)
473     {
474       GVariant *emblem_data;
475
476       icon = g_emblemed_icon_new (main_icon, NULL);
477
478       while ((emblem_data = g_variant_iter_next_value (emblems)))
479         {
480           GEmblem *emblem;
481
482           emblem = g_icon_deserialize_emblem (emblem_data);
483
484           if (emblem)
485             {
486               g_emblemed_icon_add_emblem (G_EMBLEMED_ICON (icon), emblem);
487               g_object_unref (emblem);
488             }
489
490           g_variant_unref (emblem_data);
491         }
492
493       g_object_unref (main_icon);
494     }
495   else
496     icon = NULL;
497
498   g_variant_iter_free (emblems);
499   g_variant_unref (icon_data);
500
501   return icon;
502 }
503
504 /**
505  * g_icon_deserialize:
506  * @value: a #GVariant created with g_icon_serialize()
507  *
508  * Deserializes a #GIcon previously serialized using g_icon_serialize().
509  *
510  * Returns: (transfer full): a #GIcon, or %NULL when deserialization fails.
511  *
512  * Since: 2.38
513  */
514 GIcon *
515 g_icon_deserialize (GVariant *value)
516 {
517   const gchar *tag;
518   GVariant *val;
519   GIcon *icon;
520
521   g_return_val_if_fail (value != NULL, NULL);
522   g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING) ||
523                         g_variant_is_of_type (value, G_VARIANT_TYPE ("(sv)")), NULL);
524
525   /* Handle some special cases directly so that people can hard-code
526    * stuff into GMenuModel xml files without resorting to using GVariant
527    * text format to describe one of the explicitly-tagged possibilities
528    * below.
529    */
530   if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
531     return g_icon_new_for_string_simple (g_variant_get_string (value, NULL));
532
533   /* Otherwise, use the tagged union format */
534   g_variant_get (value, "(&sv)", &tag, &val);
535
536   icon = NULL;
537
538   if (g_str_equal (tag, "file") && g_variant_is_of_type (val, G_VARIANT_TYPE_STRING))
539     {
540       GFile *file;
541
542       file = g_file_new_for_commandline_arg (g_variant_get_string (val, NULL));
543       icon = g_file_icon_new (file);
544       g_object_unref (file);
545     }
546   else if (g_str_equal (tag, "themed") && g_variant_is_of_type (val, G_VARIANT_TYPE_STRING_ARRAY))
547     {
548       const gchar **names;
549       gsize size;
550
551       names = g_variant_get_strv (val, &size);
552       icon = g_themed_icon_new_from_names ((gchar **) names, size);
553       g_free (names);
554     }
555   else if (g_str_equal (tag, "bytes") && g_variant_is_of_type (val, G_VARIANT_TYPE_BYTESTRING))
556     {
557       GBytes *bytes;
558
559       bytes = g_variant_get_data_as_bytes (val);
560       icon = g_bytes_icon_new (bytes);
561       g_bytes_unref (bytes);
562     }
563   else if (g_str_equal (tag, "emblem") && g_variant_is_of_type (val, G_VARIANT_TYPE ("(va{sv})")))
564     {
565       GEmblem *emblem;
566
567       emblem = g_icon_deserialize_emblem (val);
568       if (emblem)
569         icon = G_ICON (emblem);
570     }
571   else if (g_str_equal (tag, "emblemed") && g_variant_is_of_type (val, G_VARIANT_TYPE ("(va(va{sv}))")))
572     {
573       icon = g_icon_deserialize_emblemed (val);
574     }
575   else if (g_str_equal (tag, "gvfs"))
576     {
577       GVfsClass *class;
578       GVfs *vfs;
579
580       vfs = g_vfs_get_default ();
581       class = G_VFS_GET_CLASS (vfs);
582       if (class->deserialize_icon)
583         icon = (* class->deserialize_icon) (vfs, val);
584     }
585
586   g_variant_unref (val);
587
588   return icon;
589 }
590
591 /**
592  * g_icon_serialize:
593  * @icon: a #GIcon
594  *
595  * Serializes a #GIcon into a #GVariant. An equivalent #GIcon can be retrieved
596  * back by calling g_icon_deserialize() on the returned value.
597  * As serialization will avoid using raw icon data when possible, it only
598  * makes sense to transfer the #GVariant between processes on the same machine,
599  * (as opposed to over the network), and within the same file system namespace.
600  *
601  * Returns: (transfer full): a #GVariant, or %NULL when serialization fails.
602  *
603  * Since: 2.38
604  */
605 GVariant *
606 g_icon_serialize (GIcon *icon)
607 {
608   GIconInterface *iface;
609   GVariant *result;
610
611   iface = G_ICON_GET_IFACE (icon);
612
613   if (!iface->serialize)
614     {
615       g_critical ("g_icon_serialize() on icon type '%s' is not implemented", G_OBJECT_TYPE_NAME (icon));
616       return NULL;
617     }
618
619   result = (* iface->serialize) (icon);
620
621   if (result)
622     {
623       g_variant_take_ref (result);
624
625       if (!g_variant_is_of_type (result, G_VARIANT_TYPE ("(sv)")))
626         {
627           g_critical ("g_icon_serialize() on icon type '%s' returned GVariant of type '%s' but it must return "
628                       "one with type '(sv)'", G_OBJECT_TYPE_NAME (icon), g_variant_get_type_string (result));
629           g_variant_unref (result);
630           result = NULL;
631         }
632     }
633
634   return result;
635 }