Updated FSF's address
[platform/upstream/glib.git] / gio / gcontenttype.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2
3 /* GIO - GLib Input, Output and Streaming Library
4  *
5  * Copyright (C) 2006-2007 Red Hat, Inc.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Author: Alexander Larsson <alexl@redhat.com>
21  */
22
23 #include "config.h"
24 #include <sys/types.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include "gcontenttypeprivate.h"
29 #include "gthemedicon.h"
30 #include "gicon.h"
31 #include "gfile.h"
32 #include "gfileenumerator.h"
33 #include "gfileinfo.h"
34 #include "glibintl.h"
35
36
37 /**
38  * SECTION:gcontenttype
39  * @short_description: Platform-specific content typing
40  * @include: gio/gio.h
41  *
42  * A content type is a platform specific string that defines the type
43  * of a file. On UNIX it is a <ulink url="http://www.wikipedia.org/wiki/Internet_media_type">mime type</ulink> like "text/plain" or "image/png".
44  * On Win32 it is an extension string like ".doc", ".txt" or a perceived
45  * string like "audio". Such strings can be looked up in the registry at
46  * HKEY_CLASSES_ROOT.
47  **/
48
49 #include <dirent.h>
50
51 #define XDG_PREFIX _gio_xdg
52 #include "xdgmime/xdgmime.h"
53
54 /* We lock this mutex whenever we modify global state in this module.  */
55 G_LOCK_DEFINE_STATIC (gio_xdgmime);
56
57 gsize
58 _g_unix_content_type_get_sniff_len (void)
59 {
60   gsize size;
61
62   G_LOCK (gio_xdgmime);
63   size = xdg_mime_get_max_buffer_extents ();
64   G_UNLOCK (gio_xdgmime);
65
66   return size;
67 }
68
69 gchar *
70 _g_unix_content_type_unalias (const gchar *type)
71 {
72   gchar *res;
73
74   G_LOCK (gio_xdgmime);
75   res = g_strdup (xdg_mime_unalias_mime_type (type));
76   G_UNLOCK (gio_xdgmime);
77
78   return res;
79 }
80
81 gchar **
82 _g_unix_content_type_get_parents (const gchar *type)
83 {
84   const gchar *umime;
85   gchar **parents;
86   GPtrArray *array;
87   int i;
88
89   array = g_ptr_array_new ();
90
91   G_LOCK (gio_xdgmime);
92
93   umime = xdg_mime_unalias_mime_type (type);
94
95   g_ptr_array_add (array, g_strdup (umime));
96
97   parents = xdg_mime_list_mime_parents (umime);
98   for (i = 0; parents && parents[i] != NULL; i++)
99     g_ptr_array_add (array, g_strdup (parents[i]));
100
101   free (parents);
102
103   G_UNLOCK (gio_xdgmime);
104
105   g_ptr_array_add (array, NULL);
106
107   return (gchar **)g_ptr_array_free (array, FALSE);
108 }
109
110 /**
111  * g_content_type_equals:
112  * @type1: a content type string
113  * @type2: a content type string
114  *
115  * Compares two content types for equality.
116  *
117  * Returns: %TRUE if the two strings are identical or equivalent,
118  *     %FALSE otherwise.
119  */
120 gboolean
121 g_content_type_equals (const gchar *type1,
122                        const gchar *type2)
123 {
124   gboolean res;
125
126   g_return_val_if_fail (type1 != NULL, FALSE);
127   g_return_val_if_fail (type2 != NULL, FALSE);
128
129   G_LOCK (gio_xdgmime);
130   res = xdg_mime_mime_type_equal (type1, type2);
131   G_UNLOCK (gio_xdgmime);
132
133   return res;
134 }
135
136 /**
137  * g_content_type_is_a:
138  * @type: a content type string
139  * @supertype: a content type string
140  *
141  * Determines if @type is a subset of @supertype.
142  *
143  * Returns: %TRUE if @type is a kind of @supertype,
144  *     %FALSE otherwise.
145  */
146 gboolean
147 g_content_type_is_a (const gchar *type,
148                      const gchar *supertype)
149 {
150   gboolean res;
151
152   g_return_val_if_fail (type != NULL, FALSE);
153   g_return_val_if_fail (supertype != NULL, FALSE);
154
155   G_LOCK (gio_xdgmime);
156   res = xdg_mime_mime_type_subclass (type, supertype);
157   G_UNLOCK (gio_xdgmime);
158
159   return res;
160 }
161
162 /**
163  * g_content_type_is_unknown:
164  * @type: a content type string
165  *
166  * Checks if the content type is the generic "unknown" type.
167  * On UNIX this is the "application/octet-stream" mimetype,
168  * while on win32 it is "*".
169  *
170  * Returns: %TRUE if the type is the unknown type.
171  */
172 gboolean
173 g_content_type_is_unknown (const gchar *type)
174 {
175   g_return_val_if_fail (type != NULL, FALSE);
176
177   return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
178 }
179
180
181 typedef enum {
182   MIME_TAG_TYPE_OTHER,
183   MIME_TAG_TYPE_COMMENT
184 } MimeTagType;
185
186 typedef struct {
187   int current_type;
188   int current_lang_level;
189   int comment_lang_level;
190   char *comment;
191 } MimeParser;
192
193
194 static int
195 language_level (const char *lang)
196 {
197   const char * const *lang_list;
198   int i;
199
200   /* The returned list is sorted from most desirable to least
201      desirable and always contains the default locale "C". */
202   lang_list = g_get_language_names ();
203
204   for (i = 0; lang_list[i]; i++)
205     if (strcmp (lang_list[i], lang) == 0)
206       return 1000-i;
207
208   return 0;
209 }
210
211 static void
212 mime_info_start_element (GMarkupParseContext  *context,
213                          const gchar          *element_name,
214                          const gchar         **attribute_names,
215                          const gchar         **attribute_values,
216                          gpointer              user_data,
217                          GError              **error)
218 {
219   int i;
220   const char *lang;
221   MimeParser *parser = user_data;
222
223   if (strcmp (element_name, "comment") == 0)
224     {
225       lang = "C";
226       for (i = 0; attribute_names[i]; i++)
227         if (strcmp (attribute_names[i], "xml:lang") == 0)
228           {
229             lang = attribute_values[i];
230             break;
231           }
232
233       parser->current_lang_level = language_level (lang);
234       parser->current_type = MIME_TAG_TYPE_COMMENT;
235     }
236   else
237     parser->current_type = MIME_TAG_TYPE_OTHER;
238 }
239
240 static void
241 mime_info_end_element (GMarkupParseContext  *context,
242                        const gchar          *element_name,
243                        gpointer              user_data,
244                        GError              **error)
245 {
246   MimeParser *parser = user_data;
247
248   parser->current_type = MIME_TAG_TYPE_OTHER;
249 }
250
251 static void
252 mime_info_text (GMarkupParseContext  *context,
253                 const gchar          *text,
254                 gsize                 text_len,
255                 gpointer              user_data,
256                 GError              **error)
257 {
258   MimeParser *parser = user_data;
259
260   if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
261       parser->current_lang_level > parser->comment_lang_level)
262     {
263       g_free (parser->comment);
264       parser->comment = g_strndup (text, text_len);
265       parser->comment_lang_level = parser->current_lang_level;
266     }
267 }
268
269 static char *
270 load_comment_for_mime_helper (const char *dir,
271                               const char *basename)
272 {
273   GMarkupParseContext *context;
274   char *filename, *data;
275   gsize len;
276   gboolean res;
277   MimeParser parse_data = {0};
278   GMarkupParser parser = {
279     mime_info_start_element,
280     mime_info_end_element,
281     mime_info_text
282   };
283
284   filename = g_build_filename (dir, "mime", basename, NULL);
285
286   res = g_file_get_contents (filename,  &data,  &len,  NULL);
287   g_free (filename);
288   if (!res)
289     return NULL;
290
291   context = g_markup_parse_context_new   (&parser, 0, &parse_data, NULL);
292   res = g_markup_parse_context_parse (context, data, len, NULL);
293   g_free (data);
294   g_markup_parse_context_free (context);
295
296   if (!res)
297     return NULL;
298
299   return parse_data.comment;
300 }
301
302
303 static char *
304 load_comment_for_mime (const char *mimetype)
305 {
306   const char * const* dirs;
307   char *basename;
308   char *comment;
309   int i;
310
311   basename = g_strdup_printf ("%s.xml", mimetype);
312
313   comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
314   if (comment)
315     {
316       g_free (basename);
317       return comment;
318     }
319
320   dirs = g_get_system_data_dirs ();
321
322   for (i = 0; dirs[i] != NULL; i++)
323     {
324       comment = load_comment_for_mime_helper (dirs[i], basename);
325       if (comment)
326         {
327           g_free (basename);
328           return comment;
329         }
330     }
331   g_free (basename);
332
333   return g_strdup_printf (_("%s type"), mimetype);
334 }
335
336 /**
337  * g_content_type_get_description:
338  * @type: a content type string
339  *
340  * Gets the human readable description of the content type.
341  *
342  * Returns: a short description of the content type @type. Free the
343  *     returned string with g_free()
344  */
345 gchar *
346 g_content_type_get_description (const gchar *type)
347 {
348   static GHashTable *type_comment_cache = NULL;
349   gchar *comment;
350
351   g_return_val_if_fail (type != NULL, NULL);
352
353   G_LOCK (gio_xdgmime);
354   type = xdg_mime_unalias_mime_type (type);
355
356   if (type_comment_cache == NULL)
357     type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
358
359   comment = g_hash_table_lookup (type_comment_cache, type);
360   comment = g_strdup (comment);
361   G_UNLOCK (gio_xdgmime);
362
363   if (comment != NULL)
364     return comment;
365
366   comment = load_comment_for_mime (type);
367
368   G_LOCK (gio_xdgmime);
369   g_hash_table_insert (type_comment_cache,
370                        g_strdup (type),
371                        g_strdup (comment));
372   G_UNLOCK (gio_xdgmime);
373
374   return comment;
375 }
376
377 /**
378  * g_content_type_get_mime_type:
379  * @type: a content type string
380  *
381  * Gets the mime type for the content type, if one is registered.
382  *
383  * Returns: (allow-none): the registered mime type for the given @type,
384  *     or %NULL if unknown.
385  */
386 char *
387 g_content_type_get_mime_type (const char *type)
388 {
389   g_return_val_if_fail (type != NULL, NULL);
390
391   return g_strdup (type);
392 }
393
394 #pragma GCC diagnostic push
395 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
396
397 static GIcon *
398 g_content_type_get_icon_internal (const gchar *type,
399                                   gboolean     symbolic)
400 {
401   char *mimetype_icon;
402   char *generic_mimetype_icon = NULL;
403   char *q;
404   char *xdg_mimetype_icon = NULL;
405   char *xdg_mimetype_generic_icon;
406   char *icon_names[3];
407   int n = 0;
408   GIcon *themed_icon;
409   const char  *xdg_icon;
410   const char *suffix;
411
412   g_return_val_if_fail (type != NULL, NULL);
413
414   if (symbolic)
415     suffix = "-symbolic";
416   else
417     suffix = "";
418
419   G_LOCK (gio_xdgmime);
420   xdg_icon = xdg_mime_get_icon (type);
421   G_UNLOCK (gio_xdgmime);
422    if (xdg_icon != NULL)
423     xdg_mimetype_icon = g_strconcat (xdg_icon, suffix, NULL);
424
425   if (xdg_mimetype_icon)
426     icon_names[n++] = xdg_mimetype_icon;
427
428   mimetype_icon = g_strconcat (type, suffix, NULL);
429   while ((q = strchr (mimetype_icon, '/')) != NULL)
430     *q = '-';
431
432   icon_names[n++] = mimetype_icon;
433
434   xdg_mimetype_generic_icon = g_content_type_get_generic_icon_name (type);
435   if (xdg_mimetype_generic_icon)
436     generic_mimetype_icon = g_strconcat (xdg_mimetype_generic_icon, suffix, NULL);
437   if (generic_mimetype_icon)
438     icon_names[n++] = generic_mimetype_icon;
439
440   themed_icon = g_themed_icon_new_from_names (icon_names, n);
441
442   g_free (xdg_mimetype_icon);
443   g_free (xdg_mimetype_generic_icon);
444   g_free (mimetype_icon);
445   g_free (generic_mimetype_icon);
446
447   return themed_icon;
448 }
449 #pragma GCC diagnostic pop
450
451 /**
452  * g_content_type_get_icon:
453  * @type: a content type string
454  *
455  * Gets the icon for a content type.
456  *
457  * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
458  *     object with g_object_unref()
459  */
460 GIcon *
461 g_content_type_get_icon (const gchar *type)
462 {
463   return g_content_type_get_icon_internal (type, FALSE);
464 }
465
466 /**
467  * g_content_type_get_symbolic_icon:
468  * @type: a content type string
469  *
470  * Gets the symbolic icon for a content type.
471  *
472  * Returns: (transfer full): symbolic #GIcon corresponding to the content type.
473  *     Free the returned object with g_object_unref()
474  *
475  * Since: 2.34
476  */
477 GIcon *
478 g_content_type_get_symbolic_icon (const gchar *type)
479 {
480   return g_content_type_get_icon_internal (type, TRUE);
481 }
482
483 /**
484  * g_content_type_get_generic_icon_name:
485  * @type: a content type string
486  *
487  * Gets the generic icon name for a content type.
488  *
489  * See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
490  * specification for more on the generic icon name.
491  *
492  * Returns: (allow-none): the registered generic icon name for the given @type,
493  *     or %NULL if unknown. Free with g_free()
494  *
495  * Since: 2.34
496  */
497 gchar *
498 g_content_type_get_generic_icon_name (const gchar *type)
499 {
500   const gchar *xdg_icon_name;
501   gchar *icon_name;
502
503   G_LOCK (gio_xdgmime);
504   xdg_icon_name = xdg_mime_get_generic_icon (type);
505   G_UNLOCK (gio_xdgmime);
506
507   if (!xdg_icon_name)
508     {
509       const char *p;
510       const char *suffix = "-x-generic";
511
512       p = strchr (type, '/');
513       if (p == NULL)
514         p = type + strlen (type);
515
516       icon_name = g_malloc (p - type + strlen (suffix) + 1);
517       memcpy (icon_name, type, p - type);
518       memcpy (icon_name + (p - type), suffix, strlen (suffix));
519       icon_name[(p - type) + strlen (suffix)] = 0;
520     }
521   else
522     {
523       icon_name = g_strdup (xdg_icon_name);
524     }
525
526   return icon_name;
527 }
528
529 /**
530  * g_content_type_can_be_executable:
531  * @type: a content type string
532  *
533  * Checks if a content type can be executable. Note that for instance
534  * things like text files can be executables (i.e. scripts and batch files).
535  *
536  * Returns: %TRUE if the file type corresponds to a type that
537  *     can be executable, %FALSE otherwise.
538  */
539 gboolean
540 g_content_type_can_be_executable (const gchar *type)
541 {
542   g_return_val_if_fail (type != NULL, FALSE);
543
544   if (g_content_type_is_a (type, "application/x-executable")  ||
545       g_content_type_is_a (type, "text/plain"))
546     return TRUE;
547
548   return FALSE;
549 }
550
551 static gboolean
552 looks_like_text (const guchar *data, gsize data_size)
553 {
554   gsize i;
555   char c;
556
557   for (i = 0; i < data_size; i++)
558     {
559       c = data[i];
560
561       if (g_ascii_iscntrl (c) &&
562           !g_ascii_isspace (c) &&
563           c != '\b')
564         return FALSE;
565     }
566   return TRUE;
567 }
568
569 /**
570  * g_content_type_from_mime_type:
571  * @mime_type: a mime type string
572  *
573  * Tries to find a content type based on the mime type name.
574  *
575  * Returns: (allow-none): Newly allocated string with content type
576  *     or %NULL. Free with g_free()
577  *
578  * Since: 2.18
579  **/
580 gchar *
581 g_content_type_from_mime_type (const gchar *mime_type)
582 {
583   char *umime;
584
585   g_return_val_if_fail (mime_type != NULL, NULL);
586
587   G_LOCK (gio_xdgmime);
588   /* mime type and content type are same on unixes */
589   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
590   G_UNLOCK (gio_xdgmime);
591
592   return umime;
593 }
594
595 /**
596  * g_content_type_guess:
597  * @filename: (allow-none): a string, or %NULL
598  * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
599  * @data_size: the size of @data
600  * @result_uncertain: (allow-none) (out): return location for the certainty
601  *     of the result, or %NULL
602  *
603  * Guesses the content type based on example data. If the function is
604  * uncertain, @result_uncertain will be set to %TRUE. Either @filename
605  * or @data may be %NULL, in which case the guess will be based solely
606  * on the other argument.
607  *
608  * Returns: a string indicating a guessed content type for the
609  *     given data. Free with g_free()
610  */
611 gchar *
612 g_content_type_guess (const gchar  *filename,
613                       const guchar *data,
614                       gsize         data_size,
615                       gboolean     *result_uncertain)
616 {
617   char *basename;
618   const char *name_mimetypes[10], *sniffed_mimetype;
619   char *mimetype;
620   int i;
621   int n_name_mimetypes;
622   int sniffed_prio;
623
624   sniffed_prio = 0;
625   n_name_mimetypes = 0;
626   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
627
628   if (result_uncertain)
629     *result_uncertain = FALSE;
630
631   /* our test suite and potentially other code used -1 in the past, which is
632    * not documented and not allowed; guard against that */
633   g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));
634
635   G_LOCK (gio_xdgmime);
636
637   if (filename)
638     {
639       i = strlen (filename);
640       if (filename[i - 1] == '/')
641         {
642           name_mimetypes[0] = "inode/directory";
643           name_mimetypes[1] = NULL;
644           n_name_mimetypes = 1;
645           if (result_uncertain)
646             *result_uncertain = TRUE;
647         }
648       else
649         {
650           basename = g_path_get_basename (filename);
651           n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
652           g_free (basename);
653         }
654     }
655
656   /* Got an extension match, and no conflicts. This is it. */
657   if (n_name_mimetypes == 1)
658     {
659       gchar *s = g_strdup (name_mimetypes[0]);
660       G_UNLOCK (gio_xdgmime);
661       return s;
662     }
663
664   if (data)
665     {
666       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
667       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
668           data &&
669           looks_like_text (data, data_size))
670         sniffed_mimetype = "text/plain";
671
672       /* For security reasons we don't ever want to sniff desktop files
673        * where we know the filename and it doesn't have a .desktop extension.
674        * This is because desktop files allow executing any application and
675        * we don't want to make it possible to hide them looking like something
676        * else.
677        */
678       if (filename != NULL &&
679           strcmp (sniffed_mimetype, "application/x-desktop") == 0)
680         sniffed_mimetype = "text/plain";
681     }
682
683   if (n_name_mimetypes == 0)
684     {
685       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
686           result_uncertain)
687         *result_uncertain = TRUE;
688
689       mimetype = g_strdup (sniffed_mimetype);
690     }
691   else
692     {
693       mimetype = NULL;
694       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
695         {
696           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
697             mimetype = g_strdup (sniffed_mimetype);
698           else
699             {
700               /* There are conflicts between the name matches and we
701                * have a sniffed type, use that as a tie breaker.
702                */
703               for (i = 0; i < n_name_mimetypes; i++)
704                 {
705                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
706                     {
707                       /* This nametype match is derived from (or the same as)
708                        * the sniffed type). This is probably it.
709                        */
710                       mimetype = g_strdup (name_mimetypes[i]);
711                       break;
712                     }
713                 }
714             }
715         }
716
717       if (mimetype == NULL)
718         {
719           /* Conflicts, and sniffed type was no help or not there.
720            * Guess on the first one
721            */
722           mimetype = g_strdup (name_mimetypes[0]);
723           if (result_uncertain)
724             *result_uncertain = TRUE;
725         }
726     }
727
728   G_UNLOCK (gio_xdgmime);
729
730   return mimetype;
731 }
732
733 static void
734 enumerate_mimetypes_subdir (const char *dir,
735                             const char *prefix,
736                             GHashTable *mimetypes)
737 {
738   DIR *d;
739   struct dirent *ent;
740   char *mimetype;
741
742   d = opendir (dir);
743   if (d)
744     {
745       while ((ent = readdir (d)) != NULL)
746         {
747           if (g_str_has_suffix (ent->d_name, ".xml"))
748             {
749               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
750               g_hash_table_replace (mimetypes, mimetype, NULL);
751             }
752         }
753       closedir (d);
754     }
755 }
756
757 static void
758 enumerate_mimetypes_dir (const char *dir,
759                          GHashTable *mimetypes)
760 {
761   DIR *d;
762   struct dirent *ent;
763   char *mimedir;
764   char *name;
765
766   mimedir = g_build_filename (dir, "mime", NULL);
767
768   d = opendir (mimedir);
769   if (d)
770     {
771       while ((ent = readdir (d)) != NULL)
772         {
773           if (strcmp (ent->d_name, "packages") != 0)
774             {
775               name = g_build_filename (mimedir, ent->d_name, NULL);
776               if (g_file_test (name, G_FILE_TEST_IS_DIR))
777                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
778               g_free (name);
779             }
780         }
781       closedir (d);
782     }
783
784   g_free (mimedir);
785 }
786
787 /**
788  * g_content_types_get_registered:
789  *
790  * Gets a list of strings containing all the registered content types
791  * known to the system. The list and its data should be freed using
792  * <programlisting>
793  * g_list_free_full (list, g_free);
794  * </programlisting>
795  *
796  * Returns: (element-type utf8) (transfer full): #GList of the registered content types
797  */
798 GList *
799 g_content_types_get_registered (void)
800 {
801   const char * const* dirs;
802   GHashTable *mimetypes;
803   GHashTableIter iter;
804   gpointer key;
805   int i;
806   GList *l;
807
808   mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
809
810   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
811   dirs = g_get_system_data_dirs ();
812
813   for (i = 0; dirs[i] != NULL; i++)
814     enumerate_mimetypes_dir (dirs[i], mimetypes);
815
816   l = NULL;
817   g_hash_table_iter_init (&iter, mimetypes);
818   while (g_hash_table_iter_next (&iter, &key, NULL))
819     {
820       l = g_list_prepend (l, key);
821       g_hash_table_iter_steal (&iter);
822     }
823
824   g_hash_table_destroy (mimetypes);
825
826   return l;
827 }
828
829
830 /* tree magic data */
831 static GList *tree_matches = NULL;
832 static gboolean need_reload = FALSE;
833
834 G_LOCK_DEFINE_STATIC (gio_treemagic);
835
836 typedef struct
837 {
838   gchar *path;
839   GFileType type;
840   guint match_case : 1;
841   guint executable : 1;
842   guint non_empty  : 1;
843   guint on_disc    : 1;
844   gchar *mimetype;
845   GList *matches;
846 } TreeMatchlet;
847
848 typedef struct
849 {
850   gchar *contenttype;
851   gint priority;
852   GList *matches;
853 } TreeMatch;
854
855
856 static void
857 tree_matchlet_free (TreeMatchlet *matchlet)
858 {
859   g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
860   g_free (matchlet->path);
861   g_free (matchlet->mimetype);
862   g_slice_free (TreeMatchlet, matchlet);
863 }
864
865 static void
866 tree_match_free (TreeMatch *match)
867 {
868   g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
869   g_free (match->contenttype);
870   g_slice_free (TreeMatch, match);
871 }
872
873 static TreeMatch *
874 parse_header (gchar *line)
875 {
876   gint len;
877   gchar *s;
878   TreeMatch *match;
879
880   len = strlen (line);
881
882   if (line[0] != '[' || line[len - 1] != ']')
883     return NULL;
884
885   line[len - 1] = 0;
886   s = strchr (line, ':');
887
888   match = g_slice_new0 (TreeMatch);
889   match->priority = atoi (line + 1);
890   match->contenttype = g_strdup (s + 1);
891
892   return match;
893 }
894
895 static TreeMatchlet *
896 parse_match_line (gchar *line,
897                   gint  *depth)
898 {
899   gchar *s, *p;
900   TreeMatchlet *matchlet;
901   gchar **parts;
902   gint i;
903
904   matchlet = g_slice_new0 (TreeMatchlet);
905
906   if (line[0] == '>')
907     {
908       *depth = 0;
909       s = line;
910     }
911   else
912     {
913       *depth = atoi (line);
914       s = strchr (line, '>');
915     }
916   s += 2;
917   p = strchr (s, '"');
918   *p = 0;
919
920   matchlet->path = g_strdup (s);
921   s = p + 1;
922   parts = g_strsplit (s, ",", 0);
923   if (strcmp (parts[0], "=file") == 0)
924     matchlet->type = G_FILE_TYPE_REGULAR;
925   else if (strcmp (parts[0], "=directory") == 0)
926     matchlet->type = G_FILE_TYPE_DIRECTORY;
927   else if (strcmp (parts[0], "=link") == 0)
928     matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
929   else
930     matchlet->type = G_FILE_TYPE_UNKNOWN;
931   for (i = 1; parts[i]; i++)
932     {
933       if (strcmp (parts[i], "executable") == 0)
934         matchlet->executable = 1;
935       else if (strcmp (parts[i], "match-case") == 0)
936         matchlet->match_case = 1;
937       else if (strcmp (parts[i], "non-empty") == 0)
938         matchlet->non_empty = 1;
939       else if (strcmp (parts[i], "on-disc") == 0)
940         matchlet->on_disc = 1;
941       else
942         matchlet->mimetype = g_strdup (parts[i]);
943     }
944
945   g_strfreev (parts);
946
947   return matchlet;
948 }
949
950 static gint
951 cmp_match (gconstpointer a, gconstpointer b)
952 {
953   const TreeMatch *aa = (const TreeMatch *)a;
954   const TreeMatch *bb = (const TreeMatch *)b;
955
956   return bb->priority - aa->priority;
957 }
958
959 static void
960 insert_match (TreeMatch *match)
961 {
962   tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
963 }
964
965 static void
966 insert_matchlet (TreeMatch    *match,
967                  TreeMatchlet *matchlet,
968                  gint          depth)
969 {
970   if (depth == 0)
971     match->matches = g_list_append (match->matches, matchlet);
972   else
973     {
974       GList *last;
975       TreeMatchlet *m;
976
977       last = g_list_last (match->matches);
978       if (!last)
979         {
980           tree_matchlet_free (matchlet);
981           g_warning ("can't insert tree matchlet at depth %d", depth);
982           return;
983         }
984
985       m = (TreeMatchlet *) last->data;
986       while (--depth > 0)
987         {
988           last = g_list_last (m->matches);
989           if (!last)
990             {
991               tree_matchlet_free (matchlet);
992               g_warning ("can't insert tree matchlet at depth %d", depth);
993               return;
994             }
995
996           m = (TreeMatchlet *) last->data;
997         }
998       m->matches = g_list_append (m->matches, matchlet);
999     }
1000 }
1001
1002 static void
1003 read_tree_magic_from_directory (const gchar *prefix)
1004 {
1005   gchar *filename;
1006   gchar *text;
1007   gsize len;
1008   gchar **lines;
1009   gint i;
1010   TreeMatch *match;
1011   TreeMatchlet *matchlet;
1012   gint depth;
1013
1014   filename = g_build_filename (prefix, "mime", "treemagic", NULL);
1015
1016   if (g_file_get_contents (filename, &text, &len, NULL))
1017     {
1018       if (strcmp (text, "MIME-TreeMagic") == 0)
1019         {
1020           lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
1021           match = NULL;
1022           for (i = 0; lines[i] && lines[i][0]; i++)
1023             {
1024               if (lines[i][0] == '[')
1025                 {
1026                   match = parse_header (lines[i]);
1027                   insert_match (match);
1028                 }
1029               else if (match != NULL)
1030                 {
1031                   matchlet = parse_match_line (lines[i], &depth);
1032                   insert_matchlet (match, matchlet, depth);
1033                 }
1034               else
1035                 {
1036                   g_warning ("%s: header corrupt; skipping\n", filename);
1037                   break;
1038                 }
1039             }
1040
1041           g_strfreev (lines);
1042         }
1043       else
1044         g_warning ("%s: header not found, skipping\n", filename);
1045
1046       g_free (text);
1047     }
1048
1049   g_free (filename);
1050 }
1051
1052
1053 static void
1054 xdg_mime_reload (void *user_data)
1055 {
1056   need_reload = TRUE;
1057 }
1058
1059 static void
1060 tree_magic_shutdown (void)
1061 {
1062   g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1063   tree_matches = NULL;
1064 }
1065
1066 static void
1067 tree_magic_init (void)
1068 {
1069   static gboolean initialized = FALSE;
1070   const gchar *dir;
1071   const gchar * const * dirs;
1072   int i;
1073
1074   if (!initialized)
1075     {
1076       initialized = TRUE;
1077
1078       xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1079       need_reload = TRUE;
1080     }
1081
1082   if (need_reload)
1083     {
1084       need_reload = FALSE;
1085
1086       tree_magic_shutdown ();
1087
1088       dir = g_get_user_data_dir ();
1089       read_tree_magic_from_directory (dir);
1090       dirs = g_get_system_data_dirs ();
1091       for (i = 0; dirs[i]; i++)
1092         read_tree_magic_from_directory (dirs[i]);
1093     }
1094 }
1095
1096 /* a filtering enumerator */
1097
1098 typedef struct
1099 {
1100   gchar *path;
1101   gint depth;
1102   gboolean ignore_case;
1103   gchar **components;
1104   gchar **case_components;
1105   GFileEnumerator **enumerators;
1106   GFile **children;
1107 } Enumerator;
1108
1109 static gboolean
1110 component_match (Enumerator  *e,
1111                  gint         depth,
1112                  const gchar *name)
1113 {
1114   gchar *case_folded, *key;
1115   gboolean found;
1116
1117   if (strcmp (name, e->components[depth]) == 0)
1118     return TRUE;
1119
1120   if (!e->ignore_case)
1121     return FALSE;
1122
1123   case_folded = g_utf8_casefold (name, -1);
1124   key = g_utf8_collate_key (case_folded, -1);
1125
1126   found = strcmp (key, e->case_components[depth]) == 0;
1127
1128   g_free (case_folded);
1129   g_free (key);
1130
1131   return found;
1132 }
1133
1134 static GFile *
1135 next_match_recurse (Enumerator *e,
1136                     gint        depth)
1137 {
1138   GFile *file;
1139   GFileInfo *info;
1140   const gchar *name;
1141
1142   while (TRUE)
1143     {
1144       if (e->enumerators[depth] == NULL)
1145         {
1146           if (depth > 0)
1147             {
1148               file = next_match_recurse (e, depth - 1);
1149               if (file)
1150                 {
1151                   e->children[depth] = file;
1152                   e->enumerators[depth] = g_file_enumerate_children (file,
1153                                                                      G_FILE_ATTRIBUTE_STANDARD_NAME,
1154                                                                      G_FILE_QUERY_INFO_NONE,
1155                                                                      NULL,
1156                                                                      NULL);
1157                 }
1158             }
1159           if (e->enumerators[depth] == NULL)
1160             return NULL;
1161         }
1162
1163       while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1164         {
1165           name = g_file_info_get_name (info);
1166           if (component_match (e, depth, name))
1167             {
1168               file = g_file_get_child (e->children[depth], name);
1169               g_object_unref (info);
1170               return file;
1171             }
1172           g_object_unref (info);
1173         }
1174
1175       g_object_unref (e->enumerators[depth]);
1176       e->enumerators[depth] = NULL;
1177       g_object_unref (e->children[depth]);
1178       e->children[depth] = NULL;
1179     }
1180 }
1181
1182 static GFile *
1183 enumerator_next (Enumerator *e)
1184 {
1185   return next_match_recurse (e, e->depth - 1);
1186 }
1187
1188 static Enumerator *
1189 enumerator_new (GFile      *root,
1190                 const char *path,
1191                 gboolean    ignore_case)
1192 {
1193   Enumerator *e;
1194   gint i;
1195   gchar *case_folded;
1196
1197   e = g_new0 (Enumerator, 1);
1198   e->path = g_strdup (path);
1199   e->ignore_case = ignore_case;
1200
1201   e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1202   e->depth = g_strv_length (e->components);
1203   if (e->ignore_case)
1204     {
1205       e->case_components = g_new0 (char *, e->depth + 1);
1206       for (i = 0; e->components[i]; i++)
1207         {
1208           case_folded = g_utf8_casefold (e->components[i], -1);
1209           e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1210           g_free (case_folded);
1211         }
1212     }
1213
1214   e->children = g_new0 (GFile *, e->depth);
1215   e->children[0] = g_object_ref (root);
1216   e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1217   e->enumerators[0] = g_file_enumerate_children (root,
1218                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
1219                                                  G_FILE_QUERY_INFO_NONE,
1220                                                  NULL,
1221                                                  NULL);
1222
1223   return e;
1224 }
1225
1226 static void
1227 enumerator_free (Enumerator *e)
1228 {
1229   gint i;
1230
1231   for (i = 0; i < e->depth; i++)
1232     {
1233       if (e->enumerators[i])
1234         g_object_unref (e->enumerators[i]);
1235       if (e->children[i])
1236         g_object_unref (e->children[i]);
1237     }
1238
1239   g_free (e->enumerators);
1240   g_free (e->children);
1241   g_strfreev (e->components);
1242   if (e->case_components)
1243     g_strfreev (e->case_components);
1244   g_free (e->path);
1245   g_free (e);
1246 }
1247
1248 static gboolean
1249 matchlet_match (TreeMatchlet *matchlet,
1250                 GFile        *root)
1251 {
1252   GFile *file;
1253   GFileInfo *info;
1254   gboolean result;
1255   const gchar *attrs;
1256   Enumerator *e;
1257   GList *l;
1258
1259   e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1260
1261   do
1262     {
1263       file = enumerator_next (e);
1264       if (!file)
1265         {
1266           enumerator_free (e);
1267           return FALSE;
1268         }
1269
1270       if (matchlet->mimetype)
1271         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1272                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1273                 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1274       else
1275         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1276                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1277       info = g_file_query_info (file,
1278                                 attrs,
1279                                 G_FILE_QUERY_INFO_NONE,
1280                                 NULL,
1281                                 NULL);
1282       if (info)
1283         {
1284           result = TRUE;
1285
1286           if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1287               g_file_info_get_file_type (info) != matchlet->type)
1288             result = FALSE;
1289
1290           if (matchlet->executable &&
1291               !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1292             result = FALSE;
1293         }
1294       else
1295         result = FALSE;
1296
1297       if (result && matchlet->non_empty)
1298         {
1299           GFileEnumerator *child_enum;
1300           GFileInfo *child_info;
1301
1302           child_enum = g_file_enumerate_children (file,
1303                                                   G_FILE_ATTRIBUTE_STANDARD_NAME,
1304                                                   G_FILE_QUERY_INFO_NONE,
1305                                                   NULL,
1306                                                   NULL);
1307
1308           if (child_enum)
1309             {
1310               child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1311               if (child_info)
1312                 g_object_unref (child_info);
1313               else
1314                 result = FALSE;
1315               g_object_unref (child_enum);
1316             }
1317           else
1318             result = FALSE;
1319         }
1320
1321       if (result && matchlet->mimetype)
1322         {
1323           if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1324             result = FALSE;
1325         }
1326
1327       if (info)
1328         g_object_unref (info);
1329       g_object_unref (file);
1330     }
1331   while (!result);
1332
1333   enumerator_free (e);
1334
1335   if (!matchlet->matches)
1336     return TRUE;
1337
1338   for (l = matchlet->matches; l; l = l->next)
1339     {
1340       TreeMatchlet *submatchlet;
1341
1342       submatchlet = l->data;
1343       if (matchlet_match (submatchlet, root))
1344         return TRUE;
1345     }
1346
1347   return FALSE;
1348 }
1349
1350 static void
1351 match_match (TreeMatch    *match,
1352              GFile        *root,
1353              GPtrArray    *types)
1354 {
1355   GList *l;
1356
1357   for (l = match->matches; l; l = l->next)
1358     {
1359       TreeMatchlet *matchlet = l->data;
1360       if (matchlet_match (matchlet, root))
1361         {
1362           g_ptr_array_add (types, g_strdup (match->contenttype));
1363           break;
1364         }
1365     }
1366 }
1367
1368 /**
1369  * g_content_type_guess_for_tree:
1370  * @root: the root of the tree to guess a type for
1371  *
1372  * Tries to guess the type of the tree with root @root, by
1373  * looking at the files it contains. The result is an array
1374  * of content types, with the best guess coming first.
1375  *
1376  * The types returned all have the form x-content/foo, e.g.
1377  * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1378  * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
1379  * specification for more on x-content types.
1380  *
1381  * This function is useful in the implementation of
1382  * g_mount_guess_content_type().
1383  *
1384  * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1385  *     array of zero or more content types. Free with g_strfreev()
1386  *
1387  * Since: 2.18
1388  */
1389 gchar **
1390 g_content_type_guess_for_tree (GFile *root)
1391 {
1392   GPtrArray *types;
1393   GList *l;
1394
1395   types = g_ptr_array_new ();
1396
1397   G_LOCK (gio_treemagic);
1398
1399   tree_magic_init ();
1400   for (l = tree_matches; l; l = l->next)
1401     {
1402       TreeMatch *match = l->data;
1403       match_match (match, root, types);
1404     }
1405
1406   G_UNLOCK (gio_treemagic);
1407
1408   g_ptr_array_add (types, NULL);
1409
1410   return (gchar **)g_ptr_array_free (types, FALSE);
1411 }