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