win32: fix build after bug 674452
[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 #ifdef G_OS_WIN32
52
53 #include <windows.h>
54
55 static char *
56 get_registry_classes_key (const char    *subdir,
57                           const wchar_t *key_name)
58 {
59   wchar_t *wc_key;
60   HKEY reg_key = NULL;
61   DWORD key_type;
62   DWORD nbytes;
63   char *value_utf8;
64
65   value_utf8 = NULL;
66   
67   nbytes = 0;
68   wc_key = g_utf8_to_utf16 (subdir, -1, NULL, NULL, NULL);
69   if (RegOpenKeyExW (HKEY_CLASSES_ROOT, wc_key, 0,
70                      KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS &&
71       RegQueryValueExW (reg_key, key_name, 0,
72                         &key_type, NULL, &nbytes) == ERROR_SUCCESS &&
73       (key_type == REG_SZ || key_type == REG_EXPAND_SZ))
74     {
75       wchar_t *wc_temp = g_new (wchar_t, (nbytes+1)/2 + 1);
76       RegQueryValueExW (reg_key, key_name, 0,
77                         &key_type, (LPBYTE) wc_temp, &nbytes);
78       wc_temp[nbytes/2] = '\0';
79       if (key_type == REG_EXPAND_SZ)
80         {
81           wchar_t dummy[1];
82           int len = ExpandEnvironmentStringsW (wc_temp, dummy, 1);
83           if (len > 0)
84             {
85               wchar_t *wc_temp_expanded = g_new (wchar_t, len);
86               if (ExpandEnvironmentStringsW (wc_temp, wc_temp_expanded, len) == len)
87                 value_utf8 = g_utf16_to_utf8 (wc_temp_expanded, -1, NULL, NULL, NULL);
88               g_free (wc_temp_expanded);
89             }
90         }
91       else
92         {
93           value_utf8 = g_utf16_to_utf8 (wc_temp, -1, NULL, NULL, NULL);
94         }
95       g_free (wc_temp);
96       
97     }
98   g_free (wc_key);
99   
100   if (reg_key != NULL)
101     RegCloseKey (reg_key);
102
103   return value_utf8;
104 }
105
106 gboolean
107 g_content_type_equals (const gchar *type1,
108                        const gchar *type2)
109 {
110   char *progid1, *progid2;
111   gboolean res;
112   
113   g_return_val_if_fail (type1 != NULL, FALSE);
114   g_return_val_if_fail (type2 != NULL, FALSE);
115
116   if (g_ascii_strcasecmp (type1, type2) == 0)
117     return TRUE;
118
119   res = FALSE;
120   progid1 = get_registry_classes_key (type1, NULL);
121   progid2 = get_registry_classes_key (type2, NULL);
122   if (progid1 != NULL && progid2 != NULL &&
123       strcmp (progid1, progid2) == 0)
124     res = TRUE;
125   g_free (progid1);
126   g_free (progid2);
127   
128   return res;
129 }
130
131 gboolean
132 g_content_type_is_a (const gchar *type,
133                      const gchar *supertype)
134 {
135   gboolean res;
136   char *value_utf8;
137
138   g_return_val_if_fail (type != NULL, FALSE);
139   g_return_val_if_fail (supertype != NULL, FALSE);
140
141   if (g_content_type_equals (type, supertype))
142     return TRUE;
143
144   res = FALSE;
145   value_utf8 = get_registry_classes_key (type, L"PerceivedType");
146   if (value_utf8 && strcmp (value_utf8, supertype) == 0)
147     res = TRUE;
148   g_free (value_utf8);
149   
150   return res;
151 }
152
153 gboolean
154 g_content_type_is_unknown (const gchar *type)
155 {
156   g_return_val_if_fail (type != NULL, FALSE);
157
158   return strcmp ("*", type) == 0;
159 }
160
161 gchar *
162 g_content_type_get_description (const gchar *type)
163 {
164   char *progid;
165   char *description;
166
167   g_return_val_if_fail (type != NULL, NULL);
168
169   progid = get_registry_classes_key (type, NULL);
170   if (progid)
171     {
172       description = get_registry_classes_key (progid, NULL);
173       g_free (progid);
174
175       if (description)
176         return description;
177     }
178
179   if (g_content_type_is_unknown (type))
180     return g_strdup (_("Unknown type"));
181   return g_strdup_printf (_("%s filetype"), type);
182 }
183
184 gchar *
185 g_content_type_get_mime_type (const gchar *type)
186 {
187   char *mime;
188
189   g_return_val_if_fail (type != NULL, NULL);
190
191   mime = get_registry_classes_key (type, L"Content Type");
192   if (mime)
193     return mime;
194   else if (g_content_type_is_unknown (type))
195     return g_strdup ("application/octet-stream");
196   else if (*type == '.')
197     return g_strdup_printf ("application/x-ext-%s", type+1);
198   /* TODO: Map "image" to "image/ *", etc? */
199
200   return g_strdup ("application/octet-stream");
201 }
202
203 G_LOCK_DEFINE_STATIC (_type_icons);
204 static GHashTable *_type_icons = NULL;
205
206 GIcon *
207 g_content_type_get_icon (const gchar *type)
208 {
209   GIcon *themed_icon;
210   char *name = NULL;
211
212   g_return_val_if_fail (type != NULL, NULL);
213
214   /* In the Registry icons are the default value of
215      HKEY_CLASSES_ROOT\<progid>\DefaultIcon with typical values like:
216      <type>: <value>
217      REG_EXPAND_SZ: %SystemRoot%\System32\Wscript.exe,3
218      REG_SZ: shimgvw.dll,3
219   */
220   G_LOCK (_type_icons);
221   if (!_type_icons)
222     _type_icons = g_hash_table_new (g_str_hash, g_str_equal);
223   name = g_hash_table_lookup (_type_icons, type);
224   if (!name && type[0] == '.')
225     {
226       /* double lookup by extension */
227       gchar *key = get_registry_classes_key (type, NULL);
228       if (!key)
229         key = g_strconcat (type+1, "file\\DefaultIcon", NULL);
230       else
231         {
232           gchar *key2 = g_strconcat (key, "\\DefaultIcon", NULL);
233           g_free (key);
234           key = key2;
235         }
236       name = get_registry_classes_key (key, NULL);
237       if (name && strcmp (name, "%1") == 0)
238         {
239           g_free (name);
240           name = NULL;
241         }
242       if (name)
243         g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
244       g_free (key);
245     }
246
247   /* icon-name similar to how it was with gtk-2-12 */
248   if (name)
249     {
250       themed_icon = g_themed_icon_new (name);
251     }
252   else
253     {
254       /* if not found an icon fall back to gtk-builtins */
255       name = strcmp (type, "inode/directory") == 0 ? "gtk-directory" : 
256                            g_content_type_can_be_executable (type) ? "gtk-execute" : "gtk-file";
257       g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
258       themed_icon = g_themed_icon_new_with_default_fallbacks (name);
259     }
260   G_UNLOCK (_type_icons);
261
262   return G_ICON (themed_icon);
263 }
264
265 gboolean
266 g_content_type_can_be_executable (const gchar *type)
267 {
268   g_return_val_if_fail (type != NULL, FALSE);
269
270   if (strcmp (type, ".exe") == 0 ||
271       strcmp (type, ".com") == 0 ||
272       strcmp (type, ".bat") == 0)
273     return TRUE;
274
275   /* TODO: Also look at PATHEXT, which lists the extensions for
276    * "scripts" in addition to those for true binary executables.
277    *
278    * (PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH for me
279    * right now, for instance). And in a sense, all associated file
280    * types are "executable" on Windows... You can just type foo.jpg as
281    * a command name in cmd.exe, and it will run the application
282    * associated with .jpg. Hard to say what this API actually means
283    * with "executable".
284    */
285
286   return FALSE;
287 }
288
289 static gboolean
290 looks_like_text (const guchar *data, 
291                  gsize         data_size)
292 {
293   gsize i;
294   guchar c;
295   for (i = 0; i < data_size; i++)
296     {
297       c = data[i];
298       if (g_ascii_iscntrl (c) && !g_ascii_isspace (c) && c != '\b')
299         return FALSE;
300     }
301   return TRUE;
302 }
303
304 gchar *
305 g_content_type_from_mime_type (const gchar *mime_type)
306 {
307   char *key, *content_type;
308
309   g_return_val_if_fail (mime_type != NULL, NULL);
310
311   key = g_strconcat ("MIME\\DataBase\\Content Type\\", mime_type, NULL);
312   content_type = get_registry_classes_key (key, L"Extension");
313   g_free (key);
314
315   return content_type;
316 }
317
318 gchar *
319 g_content_type_guess (const gchar  *filename,
320                       const guchar *data,
321                       gsize         data_size,
322                       gboolean     *result_uncertain)
323 {
324   char *basename;
325   char *type;
326   char *dot;
327
328   type = NULL;
329
330   if (result_uncertain)
331     *result_uncertain = FALSE;
332
333   /* our test suite and potentially other code used -1 in the past, which is
334    * not documented and not allowed; guard against that */
335   g_return_val_if_fail (data_size != (gsize) -1, g_strdup ("*"));
336
337   if (filename)
338     {
339       basename = g_path_get_basename (filename);
340       dot = strrchr (basename, '.');
341       if (dot)
342         type = g_strdup (dot);
343       g_free (basename);
344     }
345
346   if (type)
347     return type;
348
349   if (data && looks_like_text (data, data_size))
350     return g_strdup (".txt");
351
352   return g_strdup ("*");
353 }
354
355 GList *
356 g_content_types_get_registered (void)
357 {
358   DWORD index;
359   wchar_t keyname[256];
360   DWORD key_len;
361   char *key_utf8;
362   GList *types;
363
364   types = NULL;
365   index = 0;
366   key_len = 256;
367   while (RegEnumKeyExW(HKEY_CLASSES_ROOT,
368                        index,
369                        keyname,
370                        &key_len,
371                        NULL,
372                        NULL,
373                        NULL,
374                        NULL) == ERROR_SUCCESS)
375     {
376       key_utf8 = g_utf16_to_utf8 (keyname, -1, NULL, NULL, NULL);
377       if (key_utf8)
378         {
379           if (*key_utf8 == '.')
380             types = g_list_prepend (types, key_utf8);
381           else
382             g_free (key_utf8);
383         }
384       index++;
385       key_len = 256;
386     }
387   
388   return g_list_reverse (types);
389 }
390
391 gchar **
392 g_content_type_guess_for_tree (GFile *root)
393 {
394   /* FIXME: implement */
395   return NULL;
396 }
397
398 #else /* !G_OS_WIN32 - Unix specific version */
399
400 #include <dirent.h>
401
402 #define XDG_PREFIX _gio_xdg
403 #include "xdgmime/xdgmime.h"
404
405 /* We lock this mutex whenever we modify global state in this module.  */
406 G_LOCK_DEFINE_STATIC (gio_xdgmime);
407
408 gsize
409 _g_unix_content_type_get_sniff_len (void)
410 {
411   gsize size;
412
413   G_LOCK (gio_xdgmime);
414   size = xdg_mime_get_max_buffer_extents ();
415   G_UNLOCK (gio_xdgmime);
416
417   return size;
418 }
419
420 gchar *
421 _g_unix_content_type_unalias (const gchar *type)
422 {
423   gchar *res;
424
425   G_LOCK (gio_xdgmime);
426   res = g_strdup (xdg_mime_unalias_mime_type (type));
427   G_UNLOCK (gio_xdgmime);
428
429   return res;
430 }
431
432 gchar **
433 _g_unix_content_type_get_parents (const gchar *type)
434 {
435   const gchar *umime;
436   gchar **parents;
437   GPtrArray *array;
438   int i;
439
440   array = g_ptr_array_new ();
441
442   G_LOCK (gio_xdgmime);
443
444   umime = xdg_mime_unalias_mime_type (type);
445
446   g_ptr_array_add (array, g_strdup (umime));
447
448   parents = xdg_mime_list_mime_parents (umime);
449   for (i = 0; parents && parents[i] != NULL; i++)
450     g_ptr_array_add (array, g_strdup (parents[i]));
451
452   free (parents);
453
454   G_UNLOCK (gio_xdgmime);
455
456   g_ptr_array_add (array, NULL);
457
458   return (gchar **)g_ptr_array_free (array, FALSE);
459 }
460
461 /**
462  * g_content_type_equals:
463  * @type1: a content type string
464  * @type2: a content type string
465  *
466  * Compares two content types for equality.
467  *
468  * Returns: %TRUE if the two strings are identical or equivalent,
469  *     %FALSE otherwise.
470  */
471 gboolean
472 g_content_type_equals (const gchar *type1,
473                        const gchar *type2)
474 {
475   gboolean res;
476
477   g_return_val_if_fail (type1 != NULL, FALSE);
478   g_return_val_if_fail (type2 != NULL, FALSE);
479
480   G_LOCK (gio_xdgmime);
481   res = xdg_mime_mime_type_equal (type1, type2);
482   G_UNLOCK (gio_xdgmime);
483
484   return res;
485 }
486
487 /**
488  * g_content_type_is_a:
489  * @type: a content type string
490  * @supertype: a content type string
491  *
492  * Determines if @type is a subset of @supertype.
493  *
494  * Returns: %TRUE if @type is a kind of @supertype,
495  *     %FALSE otherwise.
496  */
497 gboolean
498 g_content_type_is_a (const gchar *type,
499                      const gchar *supertype)
500 {
501   gboolean res;
502
503   g_return_val_if_fail (type != NULL, FALSE);
504   g_return_val_if_fail (supertype != NULL, FALSE);
505
506   G_LOCK (gio_xdgmime);
507   res = xdg_mime_mime_type_subclass (type, supertype);
508   G_UNLOCK (gio_xdgmime);
509
510   return res;
511 }
512
513 /**
514  * g_content_type_is_unknown:
515  * @type: a content type string
516  *
517  * Checks if the content type is the generic "unknown" type.
518  * On UNIX this is the "application/octet-stream" mimetype,
519  * while on win32 it is "*".
520  *
521  * Returns: %TRUE if the type is the unknown type.
522  */
523 gboolean
524 g_content_type_is_unknown (const gchar *type)
525 {
526   g_return_val_if_fail (type != NULL, FALSE);
527
528   return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
529 }
530
531
532 typedef enum {
533   MIME_TAG_TYPE_OTHER,
534   MIME_TAG_TYPE_COMMENT
535 } MimeTagType;
536
537 typedef struct {
538   int current_type;
539   int current_lang_level;
540   int comment_lang_level;
541   char *comment;
542 } MimeParser;
543
544
545 static int
546 language_level (const char *lang)
547 {
548   const char * const *lang_list;
549   int i;
550
551   /* The returned list is sorted from most desirable to least
552      desirable and always contains the default locale "C". */
553   lang_list = g_get_language_names ();
554
555   for (i = 0; lang_list[i]; i++)
556     if (strcmp (lang_list[i], lang) == 0)
557       return 1000-i;
558
559   return 0;
560 }
561
562 static void
563 mime_info_start_element (GMarkupParseContext  *context,
564                          const gchar          *element_name,
565                          const gchar         **attribute_names,
566                          const gchar         **attribute_values,
567                          gpointer              user_data,
568                          GError              **error)
569 {
570   int i;
571   const char *lang;
572   MimeParser *parser = user_data;
573
574   if (strcmp (element_name, "comment") == 0)
575     {
576       lang = "C";
577       for (i = 0; attribute_names[i]; i++)
578         if (strcmp (attribute_names[i], "xml:lang") == 0)
579           {
580             lang = attribute_values[i];
581             break;
582           }
583
584       parser->current_lang_level = language_level (lang);
585       parser->current_type = MIME_TAG_TYPE_COMMENT;
586     }
587   else
588     parser->current_type = MIME_TAG_TYPE_OTHER;
589 }
590
591 static void
592 mime_info_end_element (GMarkupParseContext  *context,
593                        const gchar          *element_name,
594                        gpointer              user_data,
595                        GError              **error)
596 {
597   MimeParser *parser = user_data;
598
599   parser->current_type = MIME_TAG_TYPE_OTHER;
600 }
601
602 static void
603 mime_info_text (GMarkupParseContext  *context,
604                 const gchar          *text,
605                 gsize                 text_len,
606                 gpointer              user_data,
607                 GError              **error)
608 {
609   MimeParser *parser = user_data;
610
611   if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
612       parser->current_lang_level > parser->comment_lang_level)
613     {
614       g_free (parser->comment);
615       parser->comment = g_strndup (text, text_len);
616       parser->comment_lang_level = parser->current_lang_level;
617     }
618 }
619
620 static char *
621 load_comment_for_mime_helper (const char *dir,
622                               const char *basename)
623 {
624   GMarkupParseContext *context;
625   char *filename, *data;
626   gsize len;
627   gboolean res;
628   MimeParser parse_data = {0};
629   GMarkupParser parser = {
630     mime_info_start_element,
631     mime_info_end_element,
632     mime_info_text
633   };
634
635   filename = g_build_filename (dir, "mime", basename, NULL);
636
637   res = g_file_get_contents (filename,  &data,  &len,  NULL);
638   g_free (filename);
639   if (!res)
640     return NULL;
641
642   context = g_markup_parse_context_new   (&parser, 0, &parse_data, NULL);
643   res = g_markup_parse_context_parse (context, data, len, NULL);
644   g_free (data);
645   g_markup_parse_context_free (context);
646
647   if (!res)
648     return NULL;
649
650   return parse_data.comment;
651 }
652
653
654 static char *
655 load_comment_for_mime (const char *mimetype)
656 {
657   const char * const* dirs;
658   char *basename;
659   char *comment;
660   int i;
661
662   basename = g_strdup_printf ("%s.xml", mimetype);
663
664   comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
665   if (comment)
666     {
667       g_free (basename);
668       return comment;
669     }
670
671   dirs = g_get_system_data_dirs ();
672
673   for (i = 0; dirs[i] != NULL; i++)
674     {
675       comment = load_comment_for_mime_helper (dirs[i], basename);
676       if (comment)
677         {
678           g_free (basename);
679           return comment;
680         }
681     }
682   g_free (basename);
683
684   return g_strdup_printf (_("%s type"), mimetype);
685 }
686
687 /**
688  * g_content_type_get_description:
689  * @type: a content type string
690  *
691  * Gets the human readable description of the content type.
692  *
693  * Returns: a short description of the content type @type. Free the
694  *     returned string with g_free()
695  */
696 gchar *
697 g_content_type_get_description (const gchar *type)
698 {
699   static GHashTable *type_comment_cache = NULL;
700   gchar *comment;
701
702   g_return_val_if_fail (type != NULL, NULL);
703
704   G_LOCK (gio_xdgmime);
705   type = xdg_mime_unalias_mime_type (type);
706
707   if (type_comment_cache == NULL)
708     type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
709
710   comment = g_hash_table_lookup (type_comment_cache, type);
711   comment = g_strdup (comment);
712   G_UNLOCK (gio_xdgmime);
713
714   if (comment != NULL)
715     return comment;
716
717   comment = load_comment_for_mime (type);
718
719   G_LOCK (gio_xdgmime);
720   g_hash_table_insert (type_comment_cache,
721                        g_strdup (type),
722                        g_strdup (comment));
723   G_UNLOCK (gio_xdgmime);
724
725   return comment;
726 }
727
728 /**
729  * g_content_type_get_mime_type:
730  * @type: a content type string
731  *
732  * Gets the mime type for the content type, if one is registered.
733  *
734  * Returns: (allow-none): the registered mime type for the given @type,
735  *     or %NULL if unknown.
736  */
737 char *
738 g_content_type_get_mime_type (const char *type)
739 {
740   g_return_val_if_fail (type != NULL, NULL);
741
742   return g_strdup (type);
743 }
744
745 /**
746  * g_content_type_get_icon:
747  * @type: a content type string
748  *
749  * Gets the icon for a content type.
750  *
751  * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
752  *     object with g_object_unref()
753  */
754 GIcon *
755 g_content_type_get_icon (const gchar *type)
756 {
757   char *mimetype_icon, *generic_mimetype_icon, *q;
758   char *xdg_mimetype_icon, *legacy_mimetype_icon;
759   char *xdg_mimetype_generic_icon;
760   char *icon_names[5];
761   int n = 0;
762   const char *p;
763   GIcon *themed_icon;
764
765   g_return_val_if_fail (type != NULL, NULL);
766
767   G_LOCK (gio_xdgmime);
768   xdg_mimetype_icon = g_strdup (xdg_mime_get_icon (type));
769   xdg_mimetype_generic_icon = g_strdup (xdg_mime_get_generic_icon (type));
770   G_UNLOCK (gio_xdgmime);
771
772   mimetype_icon = g_strdup (type);
773
774   while ((q = strchr (mimetype_icon, '/')) != NULL)
775     *q = '-';
776
777   p = strchr (type, '/');
778   if (p == NULL)
779     p = type + strlen (type);
780
781   /* Not all icons have migrated to the new icon theme spec, look for old names too */
782   legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
783
784   generic_mimetype_icon = g_malloc (p - type + strlen ("-x-generic") + 1);
785   memcpy (generic_mimetype_icon, type, p - type);
786   memcpy (generic_mimetype_icon + (p - type), "-x-generic", strlen ("-x-generic"));
787   generic_mimetype_icon[(p - type) + strlen ("-x-generic")] = 0;
788
789   if (xdg_mimetype_icon)
790     icon_names[n++] = xdg_mimetype_icon;
791
792   icon_names[n++] = mimetype_icon;
793   icon_names[n++] = legacy_mimetype_icon;
794
795   if (xdg_mimetype_generic_icon)
796     icon_names[n++] = xdg_mimetype_generic_icon;
797
798   icon_names[n++] = generic_mimetype_icon;
799
800   themed_icon = g_themed_icon_new_from_names (icon_names, n);
801
802   g_free (xdg_mimetype_icon);
803   g_free (xdg_mimetype_generic_icon);
804   g_free (mimetype_icon);
805   g_free (legacy_mimetype_icon);
806   g_free (generic_mimetype_icon);
807
808   return themed_icon;
809 }
810
811 /**
812  * g_content_type_can_be_executable:
813  * @type: a content type string
814  *
815  * Checks if a content type can be executable. Note that for instance
816  * things like text files can be executables (i.e. scripts and batch files).
817  *
818  * Returns: %TRUE if the file type corresponds to a type that
819  *     can be executable, %FALSE otherwise.
820  */
821 gboolean
822 g_content_type_can_be_executable (const gchar *type)
823 {
824   g_return_val_if_fail (type != NULL, FALSE);
825
826   if (g_content_type_is_a (type, "application/x-executable")  ||
827       g_content_type_is_a (type, "text/plain"))
828     return TRUE;
829
830   return FALSE;
831 }
832
833 static gboolean
834 looks_like_text (const guchar *data, gsize data_size)
835 {
836   gsize i;
837   char c;
838
839   for (i = 0; i < data_size; i++)
840     {
841       c = data[i];
842
843       if (g_ascii_iscntrl (c) &&
844           !g_ascii_isspace (c) &&
845           c != '\b')
846         return FALSE;
847     }
848   return TRUE;
849 }
850
851 /**
852  * g_content_type_from_mime_type:
853  * @mime_type: a mime type string
854  *
855  * Tries to find a content type based on the mime type name.
856  *
857  * Returns: (allow-none): Newly allocated string with content type
858  *     or %NULL. Free with g_free()
859  *
860  * Since: 2.18
861  **/
862 gchar *
863 g_content_type_from_mime_type (const gchar *mime_type)
864 {
865   char *umime;
866
867   g_return_val_if_fail (mime_type != NULL, NULL);
868
869   G_LOCK (gio_xdgmime);
870   /* mime type and content type are same on unixes */
871   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
872   G_UNLOCK (gio_xdgmime);
873
874   return umime;
875 }
876
877 /**
878  * g_content_type_guess:
879  * @filename: (allow-none): a string, or %NULL
880  * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
881  * @data_size: the size of @data
882  * @result_uncertain: (allow-none) (out): return location for the certainty
883  *     of the result, or %NULL
884  *
885  * Guesses the content type based on example data. If the function is
886  * uncertain, @result_uncertain will be set to %TRUE. Either @filename
887  * or @data may be %NULL, in which case the guess will be based solely
888  * on the other argument.
889  *
890  * Returns: a string indicating a guessed content type for the
891  *     given data. Free with g_free()
892  */
893 gchar *
894 g_content_type_guess (const gchar  *filename,
895                       const guchar *data,
896                       gsize         data_size,
897                       gboolean     *result_uncertain)
898 {
899   char *basename;
900   const char *name_mimetypes[10], *sniffed_mimetype;
901   char *mimetype;
902   int i;
903   int n_name_mimetypes;
904   int sniffed_prio;
905
906   sniffed_prio = 0;
907   n_name_mimetypes = 0;
908   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
909
910   if (result_uncertain)
911     *result_uncertain = FALSE;
912
913   /* our test suite and potentially other code used -1 in the past, which is
914    * not documented and not allowed; guard against that */
915   g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));
916
917   G_LOCK (gio_xdgmime);
918
919   if (filename)
920     {
921       i = strlen (filename);
922       if (filename[i - 1] == '/')
923         {
924           name_mimetypes[0] = "inode/directory";
925           name_mimetypes[1] = NULL;
926           n_name_mimetypes = 1;
927           if (result_uncertain)
928             *result_uncertain = TRUE;
929         }
930       else
931         {
932           basename = g_path_get_basename (filename);
933           n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
934           g_free (basename);
935         }
936     }
937
938   /* Got an extension match, and no conflicts. This is it. */
939   if (n_name_mimetypes == 1)
940     {
941       G_UNLOCK (gio_xdgmime);
942       return g_strdup (name_mimetypes[0]);
943     }
944
945   if (data)
946     {
947       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
948       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
949           data &&
950           looks_like_text (data, data_size))
951         sniffed_mimetype = "text/plain";
952
953       /* For security reasons we don't ever want to sniff desktop files
954        * where we know the filename and it doesn't have a .desktop extension.
955        * This is because desktop files allow executing any application and
956        * we don't want to make it possible to hide them looking like something
957        * else.
958        */
959       if (filename != NULL &&
960           strcmp (sniffed_mimetype, "application/x-desktop") == 0)
961         sniffed_mimetype = "text/plain";
962     }
963
964   if (n_name_mimetypes == 0)
965     {
966       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
967           result_uncertain)
968         *result_uncertain = TRUE;
969
970       mimetype = g_strdup (sniffed_mimetype);
971     }
972   else
973     {
974       mimetype = NULL;
975       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
976         {
977           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
978             mimetype = g_strdup (sniffed_mimetype);
979           else
980             {
981               /* There are conflicts between the name matches and we
982                * have a sniffed type, use that as a tie breaker.
983                */
984               for (i = 0; i < n_name_mimetypes; i++)
985                 {
986                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
987                     {
988                       /* This nametype match is derived from (or the same as)
989                        * the sniffed type). This is probably it.
990                        */
991                       mimetype = g_strdup (name_mimetypes[i]);
992                       break;
993                     }
994                 }
995             }
996         }
997
998       if (mimetype == NULL)
999         {
1000           /* Conflicts, and sniffed type was no help or not there.
1001            * Guess on the first one
1002            */
1003           mimetype = g_strdup (name_mimetypes[0]);
1004           if (result_uncertain)
1005             *result_uncertain = TRUE;
1006         }
1007     }
1008
1009   G_UNLOCK (gio_xdgmime);
1010
1011   return mimetype;
1012 }
1013
1014 static void
1015 enumerate_mimetypes_subdir (const char *dir,
1016                             const char *prefix,
1017                             GHashTable *mimetypes)
1018 {
1019   DIR *d;
1020   struct dirent *ent;
1021   char *mimetype;
1022
1023   d = opendir (dir);
1024   if (d)
1025     {
1026       while ((ent = readdir (d)) != NULL)
1027         {
1028           if (g_str_has_suffix (ent->d_name, ".xml"))
1029             {
1030               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
1031               g_hash_table_replace (mimetypes, mimetype, NULL);
1032             }
1033         }
1034       closedir (d);
1035     }
1036 }
1037
1038 static void
1039 enumerate_mimetypes_dir (const char *dir,
1040                          GHashTable *mimetypes)
1041 {
1042   DIR *d;
1043   struct dirent *ent;
1044   char *mimedir;
1045   char *name;
1046
1047   mimedir = g_build_filename (dir, "mime", NULL);
1048
1049   d = opendir (mimedir);
1050   if (d)
1051     {
1052       while ((ent = readdir (d)) != NULL)
1053         {
1054           if (strcmp (ent->d_name, "packages") != 0)
1055             {
1056               name = g_build_filename (mimedir, ent->d_name, NULL);
1057               if (g_file_test (name, G_FILE_TEST_IS_DIR))
1058                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
1059               g_free (name);
1060             }
1061         }
1062       closedir (d);
1063     }
1064
1065   g_free (mimedir);
1066 }
1067
1068 /**
1069  * g_content_types_get_registered:
1070  *
1071  * Gets a list of strings containing all the registered content types
1072  * known to the system. The list and its data should be freed using
1073  * <programlisting>
1074  * g_list_free_full (list, g_free);
1075  * </programlisting>
1076  *
1077  * Returns: (element-type utf8) (transfer full): #GList of the registered content types
1078  */
1079 GList *
1080 g_content_types_get_registered (void)
1081 {
1082   const char * const* dirs;
1083   GHashTable *mimetypes;
1084   GHashTableIter iter;
1085   gpointer key;
1086   int i;
1087   GList *l;
1088
1089   mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
1090
1091   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
1092   dirs = g_get_system_data_dirs ();
1093
1094   for (i = 0; dirs[i] != NULL; i++)
1095     enumerate_mimetypes_dir (dirs[i], mimetypes);
1096
1097   l = NULL;
1098   g_hash_table_iter_init (&iter, mimetypes);
1099   while (g_hash_table_iter_next (&iter, &key, NULL))
1100     {
1101       l = g_list_prepend (l, key);
1102       g_hash_table_iter_steal (&iter);
1103     }
1104
1105   g_hash_table_destroy (mimetypes);
1106
1107   return l;
1108 }
1109
1110
1111 /* tree magic data */
1112 static GList *tree_matches = NULL;
1113 static gboolean need_reload = FALSE;
1114
1115 G_LOCK_DEFINE_STATIC (gio_treemagic);
1116
1117 typedef struct
1118 {
1119   gchar *path;
1120   GFileType type;
1121   guint match_case : 1;
1122   guint executable : 1;
1123   guint non_empty  : 1;
1124   guint on_disc    : 1;
1125   gchar *mimetype;
1126   GList *matches;
1127 } TreeMatchlet;
1128
1129 typedef struct
1130 {
1131   gchar *contenttype;
1132   gint priority;
1133   GList *matches;
1134 } TreeMatch;
1135
1136
1137 static void
1138 tree_matchlet_free (TreeMatchlet *matchlet)
1139 {
1140   g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
1141   g_free (matchlet->path);
1142   g_free (matchlet->mimetype);
1143   g_slice_free (TreeMatchlet, matchlet);
1144 }
1145
1146 static void
1147 tree_match_free (TreeMatch *match)
1148 {
1149   g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
1150   g_free (match->contenttype);
1151   g_slice_free (TreeMatch, match);
1152 }
1153
1154 static TreeMatch *
1155 parse_header (gchar *line)
1156 {
1157   gint len;
1158   gchar *s;
1159   TreeMatch *match;
1160
1161   len = strlen (line);
1162
1163   if (line[0] != '[' || line[len - 1] != ']')
1164     return NULL;
1165
1166   line[len - 1] = 0;
1167   s = strchr (line, ':');
1168
1169   match = g_slice_new0 (TreeMatch);
1170   match->priority = atoi (line + 1);
1171   match->contenttype = g_strdup (s + 1);
1172
1173   return match;
1174 }
1175
1176 static TreeMatchlet *
1177 parse_match_line (gchar *line,
1178                   gint  *depth)
1179 {
1180   gchar *s, *p;
1181   TreeMatchlet *matchlet;
1182   gchar **parts;
1183   gint i;
1184
1185   matchlet = g_slice_new0 (TreeMatchlet);
1186
1187   if (line[0] == '>')
1188     {
1189       *depth = 0;
1190       s = line;
1191     }
1192   else
1193     {
1194       *depth = atoi (line);
1195       s = strchr (line, '>');
1196     }
1197   s += 2;
1198   p = strchr (s, '"');
1199   *p = 0;
1200
1201   matchlet->path = g_strdup (s);
1202   s = p + 1;
1203   parts = g_strsplit (s, ",", 0);
1204   if (strcmp (parts[0], "=file") == 0)
1205     matchlet->type = G_FILE_TYPE_REGULAR;
1206   else if (strcmp (parts[0], "=directory") == 0)
1207     matchlet->type = G_FILE_TYPE_DIRECTORY;
1208   else if (strcmp (parts[0], "=link") == 0)
1209     matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
1210   else
1211     matchlet->type = G_FILE_TYPE_UNKNOWN;
1212   for (i = 1; parts[i]; i++)
1213     {
1214       if (strcmp (parts[i], "executable") == 0)
1215         matchlet->executable = 1;
1216       else if (strcmp (parts[i], "match-case") == 0)
1217         matchlet->match_case = 1;
1218       else if (strcmp (parts[i], "non-empty") == 0)
1219         matchlet->non_empty = 1;
1220       else if (strcmp (parts[i], "on-disc") == 0)
1221         matchlet->on_disc = 1;
1222       else
1223         matchlet->mimetype = g_strdup (parts[i]);
1224     }
1225
1226   g_strfreev (parts);
1227
1228   return matchlet;
1229 }
1230
1231 static gint
1232 cmp_match (gconstpointer a, gconstpointer b)
1233 {
1234   const TreeMatch *aa = (const TreeMatch *)a;
1235   const TreeMatch *bb = (const TreeMatch *)b;
1236
1237   return bb->priority - aa->priority;
1238 }
1239
1240 static void
1241 insert_match (TreeMatch *match)
1242 {
1243   tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
1244 }
1245
1246 static void
1247 insert_matchlet (TreeMatch    *match,
1248                  TreeMatchlet *matchlet,
1249                  gint          depth)
1250 {
1251   if (depth == 0)
1252     match->matches = g_list_append (match->matches, matchlet);
1253   else
1254     {
1255       GList *last;
1256       TreeMatchlet *m;
1257
1258       last = g_list_last (match->matches);
1259       if (!last)
1260         {
1261           tree_matchlet_free (matchlet);
1262           g_warning ("can't insert tree matchlet at depth %d", depth);
1263           return;
1264         }
1265
1266       m = (TreeMatchlet *) last->data;
1267       while (--depth > 0)
1268         {
1269           last = g_list_last (m->matches);
1270           if (!last)
1271             {
1272               tree_matchlet_free (matchlet);
1273               g_warning ("can't insert tree matchlet at depth %d", depth);
1274               return;
1275             }
1276
1277           m = (TreeMatchlet *) last->data;
1278         }
1279       m->matches = g_list_append (m->matches, matchlet);
1280     }
1281 }
1282
1283 static void
1284 read_tree_magic_from_directory (const gchar *prefix)
1285 {
1286   gchar *filename;
1287   gchar *text;
1288   gsize len;
1289   gchar **lines;
1290   gint i;
1291   TreeMatch *match;
1292   TreeMatchlet *matchlet;
1293   gint depth;
1294
1295   filename = g_build_filename (prefix, "mime", "treemagic", NULL);
1296
1297   if (g_file_get_contents (filename, &text, &len, NULL))
1298     {
1299       if (strcmp (text, "MIME-TreeMagic") == 0)
1300         {
1301           lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
1302           match = NULL;
1303           for (i = 0; lines[i] && lines[i][0]; i++)
1304             {
1305               if (lines[i][0] == '[')
1306                 {
1307                   match = parse_header (lines[i]);
1308                   insert_match (match);
1309                 }
1310               else
1311                 {
1312                   matchlet = parse_match_line (lines[i], &depth);
1313                   insert_matchlet (match, matchlet, depth);
1314                 }
1315             }
1316
1317           g_strfreev (lines);
1318         }
1319       else
1320         g_warning ("%s: header not found, skipping\n", filename);
1321
1322       g_free (text);
1323     }
1324
1325   g_free (filename);
1326 }
1327
1328
1329 static void
1330 xdg_mime_reload (void *user_data)
1331 {
1332   need_reload = TRUE;
1333 }
1334
1335 static void
1336 tree_magic_shutdown (void)
1337 {
1338   g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1339   tree_matches = NULL;
1340 }
1341
1342 static void
1343 tree_magic_init (void)
1344 {
1345   static gboolean initialized = FALSE;
1346   const gchar *dir;
1347   const gchar * const * dirs;
1348   int i;
1349
1350   if (!initialized)
1351     {
1352       initialized = TRUE;
1353
1354       xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1355       need_reload = TRUE;
1356     }
1357
1358   if (need_reload)
1359     {
1360       need_reload = FALSE;
1361
1362       tree_magic_shutdown ();
1363
1364       dir = g_get_user_data_dir ();
1365       read_tree_magic_from_directory (dir);
1366       dirs = g_get_system_data_dirs ();
1367       for (i = 0; dirs[i]; i++)
1368         read_tree_magic_from_directory (dirs[i]);
1369     }
1370 }
1371
1372 /* a filtering enumerator */
1373
1374 typedef struct
1375 {
1376   gchar *path;
1377   gint depth;
1378   gboolean ignore_case;
1379   gchar **components;
1380   gchar **case_components;
1381   GFileEnumerator **enumerators;
1382   GFile **children;
1383 } Enumerator;
1384
1385 static gboolean
1386 component_match (Enumerator  *e,
1387                  gint         depth,
1388                  const gchar *name)
1389 {
1390   gchar *case_folded, *key;
1391   gboolean found;
1392
1393   if (strcmp (name, e->components[depth]) == 0)
1394     return TRUE;
1395
1396   if (!e->ignore_case)
1397     return FALSE;
1398
1399   case_folded = g_utf8_casefold (name, -1);
1400   key = g_utf8_collate_key (case_folded, -1);
1401
1402   found = strcmp (key, e->case_components[depth]) == 0;
1403
1404   g_free (case_folded);
1405   g_free (key);
1406
1407   return found;
1408 }
1409
1410 static GFile *
1411 next_match_recurse (Enumerator *e,
1412                     gint        depth)
1413 {
1414   GFile *file;
1415   GFileInfo *info;
1416   const gchar *name;
1417
1418   while (TRUE)
1419     {
1420       if (e->enumerators[depth] == NULL)
1421         {
1422           if (depth > 0)
1423             {
1424               file = next_match_recurse (e, depth - 1);
1425               if (file)
1426                 {
1427                   e->children[depth] = file;
1428                   e->enumerators[depth] = g_file_enumerate_children (file,
1429                                                                      G_FILE_ATTRIBUTE_STANDARD_NAME,
1430                                                                      G_FILE_QUERY_INFO_NONE,
1431                                                                      NULL,
1432                                                                      NULL);
1433                 }
1434             }
1435           if (e->enumerators[depth] == NULL)
1436             return NULL;
1437         }
1438
1439       while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1440         {
1441           name = g_file_info_get_name (info);
1442           if (component_match (e, depth, name))
1443             {
1444               file = g_file_get_child (e->children[depth], name);
1445               g_object_unref (info);
1446               return file;
1447             }
1448           g_object_unref (info);
1449         }
1450
1451       g_object_unref (e->enumerators[depth]);
1452       e->enumerators[depth] = NULL;
1453       g_object_unref (e->children[depth]);
1454       e->children[depth] = NULL;
1455     }
1456 }
1457
1458 static GFile *
1459 enumerator_next (Enumerator *e)
1460 {
1461   return next_match_recurse (e, e->depth - 1);
1462 }
1463
1464 static Enumerator *
1465 enumerator_new (GFile      *root,
1466                 const char *path,
1467                 gboolean    ignore_case)
1468 {
1469   Enumerator *e;
1470   gint i;
1471   gchar *case_folded;
1472
1473   e = g_new0 (Enumerator, 1);
1474   e->path = g_strdup (path);
1475   e->ignore_case = ignore_case;
1476
1477   e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1478   e->depth = g_strv_length (e->components);
1479   if (e->ignore_case)
1480     {
1481       e->case_components = g_new0 (char *, e->depth + 1);
1482       for (i = 0; e->components[i]; i++)
1483         {
1484           case_folded = g_utf8_casefold (e->components[i], -1);
1485           e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1486           g_free (case_folded);
1487         }
1488     }
1489
1490   e->children = g_new0 (GFile *, e->depth);
1491   e->children[0] = g_object_ref (root);
1492   e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1493   e->enumerators[0] = g_file_enumerate_children (root,
1494                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
1495                                                  G_FILE_QUERY_INFO_NONE,
1496                                                  NULL,
1497                                                  NULL);
1498
1499   return e;
1500 }
1501
1502 static void
1503 enumerator_free (Enumerator *e)
1504 {
1505   gint i;
1506
1507   for (i = 0; i < e->depth; i++)
1508     {
1509       if (e->enumerators[i])
1510         g_object_unref (e->enumerators[i]);
1511       if (e->children[i])
1512         g_object_unref (e->children[i]);
1513     }
1514
1515   g_free (e->enumerators);
1516   g_free (e->children);
1517   g_strfreev (e->components);
1518   if (e->case_components)
1519     g_strfreev (e->case_components);
1520   g_free (e->path);
1521   g_free (e);
1522 }
1523
1524 static gboolean
1525 matchlet_match (TreeMatchlet *matchlet,
1526                 GFile        *root)
1527 {
1528   GFile *file;
1529   GFileInfo *info;
1530   gboolean result;
1531   const gchar *attrs;
1532   Enumerator *e;
1533   GList *l;
1534
1535   e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1536
1537   do
1538     {
1539       file = enumerator_next (e);
1540       if (!file)
1541         {
1542           enumerator_free (e);
1543           return FALSE;
1544         }
1545
1546       if (matchlet->mimetype)
1547         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1548                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1549                 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1550       else
1551         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1552                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1553       info = g_file_query_info (file,
1554                                 attrs,
1555                                 G_FILE_QUERY_INFO_NONE,
1556                                 NULL,
1557                                 NULL);
1558       if (info)
1559         {
1560           result = TRUE;
1561
1562           if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1563               g_file_info_get_file_type (info) != matchlet->type)
1564             result = FALSE;
1565
1566           if (matchlet->executable &&
1567               !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1568             result = FALSE;
1569         }
1570       else
1571         result = FALSE;
1572
1573       if (result && matchlet->non_empty)
1574         {
1575           GFileEnumerator *child_enum;
1576           GFileInfo *child_info;
1577
1578           child_enum = g_file_enumerate_children (file,
1579                                                   G_FILE_ATTRIBUTE_STANDARD_NAME,
1580                                                   G_FILE_QUERY_INFO_NONE,
1581                                                   NULL,
1582                                                   NULL);
1583
1584           if (child_enum)
1585             {
1586               child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1587               if (child_info)
1588                 g_object_unref (child_info);
1589               else
1590                 result = FALSE;
1591               g_object_unref (child_enum);
1592             }
1593           else
1594             result = FALSE;
1595         }
1596
1597       if (result && matchlet->mimetype)
1598         {
1599           if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1600             result = FALSE;
1601         }
1602
1603       g_object_unref (info);
1604       g_object_unref (file);
1605     }
1606   while (!result);
1607
1608   enumerator_free (e);
1609
1610   if (!matchlet->matches)
1611     return TRUE;
1612
1613   for (l = matchlet->matches; l; l = l->next)
1614     {
1615       TreeMatchlet *submatchlet;
1616
1617       submatchlet = l->data;
1618       if (matchlet_match (submatchlet, root))
1619         return TRUE;
1620     }
1621
1622   return FALSE;
1623 }
1624
1625 static void
1626 match_match (TreeMatch    *match,
1627              GFile        *root,
1628              GPtrArray    *types)
1629 {
1630   GList *l;
1631
1632   for (l = match->matches; l; l = l->next)
1633     {
1634       TreeMatchlet *matchlet = l->data;
1635       if (matchlet_match (matchlet, root))
1636         {
1637           g_ptr_array_add (types, g_strdup (match->contenttype));
1638           break;
1639         }
1640     }
1641 }
1642
1643 /**
1644  * g_content_type_guess_for_tree:
1645  * @root: the root of the tree to guess a type for
1646  *
1647  * Tries to guess the type of the tree with root @root, by
1648  * looking at the files it contains. The result is an array
1649  * of content types, with the best guess coming first.
1650  *
1651  * The types returned all have the form x-content/foo, e.g.
1652  * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1653  * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
1654  * specification for more on x-content types.
1655  *
1656  * This function is useful in the implementation of
1657  * g_mount_guess_content_type().
1658  *
1659  * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1660  *     array of zero or more content types. Free with g_strfreev()
1661  *
1662  * Since: 2.18
1663  */
1664 gchar **
1665 g_content_type_guess_for_tree (GFile *root)
1666 {
1667   GPtrArray *types;
1668   GList *l;
1669
1670   types = g_ptr_array_new ();
1671
1672   G_LOCK (gio_treemagic);
1673
1674   tree_magic_init ();
1675   for (l = tree_matches; l; l = l->next)
1676     {
1677       TreeMatch *match = l->data;
1678       match_match (match, root, types);
1679     }
1680
1681   G_UNLOCK (gio_treemagic);
1682
1683   g_ptr_array_add (types, NULL);
1684
1685   return (gchar **)g_ptr_array_free (types, FALSE);
1686 }
1687
1688 #endif /* Unix version */