Convert external links to markdown syntax
[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
44  * [mime type](http://www.wikipedia.org/wiki/Internet_media_type)
45  * 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  *xdg_icon;
412   const char *suffix;
413
414   g_return_val_if_fail (type != NULL, NULL);
415
416   if (symbolic)
417     suffix = "-symbolic";
418   else
419     suffix = "";
420
421   G_LOCK (gio_xdgmime);
422   xdg_icon = xdg_mime_get_icon (type);
423   G_UNLOCK (gio_xdgmime);
424    if (xdg_icon != NULL)
425     xdg_mimetype_icon = g_strconcat (xdg_icon, suffix, NULL);
426
427   if (xdg_mimetype_icon)
428     icon_names[n++] = xdg_mimetype_icon;
429
430   mimetype_icon = g_strconcat (type, suffix, NULL);
431   while ((q = strchr (mimetype_icon, '/')) != NULL)
432     *q = '-';
433
434   icon_names[n++] = mimetype_icon;
435
436   xdg_mimetype_generic_icon = g_content_type_get_generic_icon_name (type);
437   if (xdg_mimetype_generic_icon)
438     generic_mimetype_icon = g_strconcat (xdg_mimetype_generic_icon, suffix, NULL);
439   if (generic_mimetype_icon)
440     icon_names[n++] = generic_mimetype_icon;
441
442   themed_icon = g_themed_icon_new_from_names (icon_names, n);
443
444   g_free (xdg_mimetype_icon);
445   g_free (xdg_mimetype_generic_icon);
446   g_free (mimetype_icon);
447   g_free (generic_mimetype_icon);
448
449   return themed_icon;
450 }
451 #pragma GCC diagnostic pop
452
453 /**
454  * g_content_type_get_icon:
455  * @type: a content type string
456  *
457  * Gets the icon for a content type.
458  *
459  * Returns: (transfer full): #GIcon corresponding to the content type. Free the returned
460  *     object with g_object_unref()
461  */
462 GIcon *
463 g_content_type_get_icon (const gchar *type)
464 {
465   return g_content_type_get_icon_internal (type, FALSE);
466 }
467
468 /**
469  * g_content_type_get_symbolic_icon:
470  * @type: a content type string
471  *
472  * Gets the symbolic icon for a content type.
473  *
474  * Returns: (transfer full): symbolic #GIcon corresponding to the content type.
475  *     Free the returned object with g_object_unref()
476  *
477  * Since: 2.34
478  */
479 GIcon *
480 g_content_type_get_symbolic_icon (const gchar *type)
481 {
482   return g_content_type_get_icon_internal (type, TRUE);
483 }
484
485 /**
486  * g_content_type_get_generic_icon_name:
487  * @type: a content type string
488  *
489  * Gets the generic icon name for a content type.
490  *
491  * See the
492  * [shared-mime-info](http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec)
493  * specification for more on the generic icon name.
494  *
495  * Returns: (allow-none): the registered generic icon name for the given @type,
496  *     or %NULL if unknown. Free with g_free()
497  *
498  * Since: 2.34
499  */
500 gchar *
501 g_content_type_get_generic_icon_name (const gchar *type)
502 {
503   const gchar *xdg_icon_name;
504   gchar *icon_name;
505
506   G_LOCK (gio_xdgmime);
507   xdg_icon_name = xdg_mime_get_generic_icon (type);
508   G_UNLOCK (gio_xdgmime);
509
510   if (!xdg_icon_name)
511     {
512       const char *p;
513       const char *suffix = "-x-generic";
514
515       p = strchr (type, '/');
516       if (p == NULL)
517         p = type + strlen (type);
518
519       icon_name = g_malloc (p - type + strlen (suffix) + 1);
520       memcpy (icon_name, type, p - type);
521       memcpy (icon_name + (p - type), suffix, strlen (suffix));
522       icon_name[(p - type) + strlen (suffix)] = 0;
523     }
524   else
525     {
526       icon_name = g_strdup (xdg_icon_name);
527     }
528
529   return icon_name;
530 }
531
532 /**
533  * g_content_type_can_be_executable:
534  * @type: a content type string
535  *
536  * Checks if a content type can be executable. Note that for instance
537  * things like text files can be executables (i.e. scripts and batch files).
538  *
539  * Returns: %TRUE if the file type corresponds to a type that
540  *     can be executable, %FALSE otherwise.
541  */
542 gboolean
543 g_content_type_can_be_executable (const gchar *type)
544 {
545   g_return_val_if_fail (type != NULL, FALSE);
546
547   if (g_content_type_is_a (type, "application/x-executable")  ||
548       g_content_type_is_a (type, "text/plain"))
549     return TRUE;
550
551   return FALSE;
552 }
553
554 static gboolean
555 looks_like_text (const guchar *data, gsize data_size)
556 {
557   gsize i;
558   char c;
559
560   for (i = 0; i < data_size; i++)
561     {
562       c = data[i];
563
564       if (g_ascii_iscntrl (c) &&
565           !g_ascii_isspace (c) &&
566           c != '\b')
567         return FALSE;
568     }
569   return TRUE;
570 }
571
572 /**
573  * g_content_type_from_mime_type:
574  * @mime_type: a mime type string
575  *
576  * Tries to find a content type based on the mime type name.
577  *
578  * Returns: (allow-none): Newly allocated string with content type
579  *     or %NULL. Free with g_free()
580  *
581  * Since: 2.18
582  **/
583 gchar *
584 g_content_type_from_mime_type (const gchar *mime_type)
585 {
586   char *umime;
587
588   g_return_val_if_fail (mime_type != NULL, NULL);
589
590   G_LOCK (gio_xdgmime);
591   /* mime type and content type are same on unixes */
592   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
593   G_UNLOCK (gio_xdgmime);
594
595   return umime;
596 }
597
598 /**
599  * g_content_type_guess:
600  * @filename: (allow-none): a string, or %NULL
601  * @data: (allow-none) (array length=data_size): a stream of data, or %NULL
602  * @data_size: the size of @data
603  * @result_uncertain: (allow-none) (out): return location for the certainty
604  *     of the result, or %NULL
605  *
606  * Guesses the content type based on example data. If the function is
607  * uncertain, @result_uncertain will be set to %TRUE. Either @filename
608  * or @data may be %NULL, in which case the guess will be based solely
609  * on the other argument.
610  *
611  * Returns: a string indicating a guessed content type for the
612  *     given data. Free with g_free()
613  */
614 gchar *
615 g_content_type_guess (const gchar  *filename,
616                       const guchar *data,
617                       gsize         data_size,
618                       gboolean     *result_uncertain)
619 {
620   char *basename;
621   const char *name_mimetypes[10], *sniffed_mimetype;
622   char *mimetype;
623   int i;
624   int n_name_mimetypes;
625   int sniffed_prio;
626
627   sniffed_prio = 0;
628   n_name_mimetypes = 0;
629   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
630
631   if (result_uncertain)
632     *result_uncertain = FALSE;
633
634   /* our test suite and potentially other code used -1 in the past, which is
635    * not documented and not allowed; guard against that */
636   g_return_val_if_fail (data_size != (gsize) -1, g_strdup (XDG_MIME_TYPE_UNKNOWN));
637
638   G_LOCK (gio_xdgmime);
639
640   if (filename)
641     {
642       i = strlen (filename);
643       if (filename[i - 1] == '/')
644         {
645           name_mimetypes[0] = "inode/directory";
646           name_mimetypes[1] = NULL;
647           n_name_mimetypes = 1;
648           if (result_uncertain)
649             *result_uncertain = TRUE;
650         }
651       else
652         {
653           basename = g_path_get_basename (filename);
654           n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
655           g_free (basename);
656         }
657     }
658
659   /* Got an extension match, and no conflicts. This is it. */
660   if (n_name_mimetypes == 1)
661     {
662       gchar *s = g_strdup (name_mimetypes[0]);
663       G_UNLOCK (gio_xdgmime);
664       return s;
665     }
666
667   if (data)
668     {
669       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
670       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
671           data &&
672           looks_like_text (data, data_size))
673         sniffed_mimetype = "text/plain";
674
675       /* For security reasons we don't ever want to sniff desktop files
676        * where we know the filename and it doesn't have a .desktop extension.
677        * This is because desktop files allow executing any application and
678        * we don't want to make it possible to hide them looking like something
679        * else.
680        */
681       if (filename != NULL &&
682           strcmp (sniffed_mimetype, "application/x-desktop") == 0)
683         sniffed_mimetype = "text/plain";
684     }
685
686   if (n_name_mimetypes == 0)
687     {
688       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
689           result_uncertain)
690         *result_uncertain = TRUE;
691
692       mimetype = g_strdup (sniffed_mimetype);
693     }
694   else
695     {
696       mimetype = NULL;
697       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
698         {
699           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
700             mimetype = g_strdup (sniffed_mimetype);
701           else
702             {
703               /* There are conflicts between the name matches and we
704                * have a sniffed type, use that as a tie breaker.
705                */
706               for (i = 0; i < n_name_mimetypes; i++)
707                 {
708                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
709                     {
710                       /* This nametype match is derived from (or the same as)
711                        * the sniffed type). This is probably it.
712                        */
713                       mimetype = g_strdup (name_mimetypes[i]);
714                       break;
715                     }
716                 }
717             }
718         }
719
720       if (mimetype == NULL)
721         {
722           /* Conflicts, and sniffed type was no help or not there.
723            * Guess on the first one
724            */
725           mimetype = g_strdup (name_mimetypes[0]);
726           if (result_uncertain)
727             *result_uncertain = TRUE;
728         }
729     }
730
731   G_UNLOCK (gio_xdgmime);
732
733   return mimetype;
734 }
735
736 static void
737 enumerate_mimetypes_subdir (const char *dir,
738                             const char *prefix,
739                             GHashTable *mimetypes)
740 {
741   DIR *d;
742   struct dirent *ent;
743   char *mimetype;
744
745   d = opendir (dir);
746   if (d)
747     {
748       while ((ent = readdir (d)) != NULL)
749         {
750           if (g_str_has_suffix (ent->d_name, ".xml"))
751             {
752               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
753               g_hash_table_replace (mimetypes, mimetype, NULL);
754             }
755         }
756       closedir (d);
757     }
758 }
759
760 static void
761 enumerate_mimetypes_dir (const char *dir,
762                          GHashTable *mimetypes)
763 {
764   DIR *d;
765   struct dirent *ent;
766   char *mimedir;
767   char *name;
768
769   mimedir = g_build_filename (dir, "mime", NULL);
770
771   d = opendir (mimedir);
772   if (d)
773     {
774       while ((ent = readdir (d)) != NULL)
775         {
776           if (strcmp (ent->d_name, "packages") != 0)
777             {
778               name = g_build_filename (mimedir, ent->d_name, NULL);
779               if (g_file_test (name, G_FILE_TEST_IS_DIR))
780                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
781               g_free (name);
782             }
783         }
784       closedir (d);
785     }
786
787   g_free (mimedir);
788 }
789
790 /**
791  * g_content_types_get_registered:
792  *
793  * Gets a list of strings containing all the registered content types
794  * known to the system. The list and its data should be freed using
795  * g_list_free_full (list, g_free).
796  *
797  * Returns: (element-type utf8) (transfer full): list of the registered
798  *     content types
799  */
800 GList *
801 g_content_types_get_registered (void)
802 {
803   const char * const* dirs;
804   GHashTable *mimetypes;
805   GHashTableIter iter;
806   gpointer key;
807   int i;
808   GList *l;
809
810   mimetypes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
811
812   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
813   dirs = g_get_system_data_dirs ();
814
815   for (i = 0; dirs[i] != NULL; i++)
816     enumerate_mimetypes_dir (dirs[i], mimetypes);
817
818   l = NULL;
819   g_hash_table_iter_init (&iter, mimetypes);
820   while (g_hash_table_iter_next (&iter, &key, NULL))
821     {
822       l = g_list_prepend (l, key);
823       g_hash_table_iter_steal (&iter);
824     }
825
826   g_hash_table_destroy (mimetypes);
827
828   return l;
829 }
830
831
832 /* tree magic data */
833 static GList *tree_matches = NULL;
834 static gboolean need_reload = FALSE;
835
836 G_LOCK_DEFINE_STATIC (gio_treemagic);
837
838 typedef struct
839 {
840   gchar *path;
841   GFileType type;
842   guint match_case : 1;
843   guint executable : 1;
844   guint non_empty  : 1;
845   guint on_disc    : 1;
846   gchar *mimetype;
847   GList *matches;
848 } TreeMatchlet;
849
850 typedef struct
851 {
852   gchar *contenttype;
853   gint priority;
854   GList *matches;
855 } TreeMatch;
856
857
858 static void
859 tree_matchlet_free (TreeMatchlet *matchlet)
860 {
861   g_list_free_full (matchlet->matches, (GDestroyNotify) tree_matchlet_free);
862   g_free (matchlet->path);
863   g_free (matchlet->mimetype);
864   g_slice_free (TreeMatchlet, matchlet);
865 }
866
867 static void
868 tree_match_free (TreeMatch *match)
869 {
870   g_list_free_full (match->matches, (GDestroyNotify) tree_matchlet_free);
871   g_free (match->contenttype);
872   g_slice_free (TreeMatch, match);
873 }
874
875 static TreeMatch *
876 parse_header (gchar *line)
877 {
878   gint len;
879   gchar *s;
880   TreeMatch *match;
881
882   len = strlen (line);
883
884   if (line[0] != '[' || line[len - 1] != ']')
885     return NULL;
886
887   line[len - 1] = 0;
888   s = strchr (line, ':');
889
890   match = g_slice_new0 (TreeMatch);
891   match->priority = atoi (line + 1);
892   match->contenttype = g_strdup (s + 1);
893
894   return match;
895 }
896
897 static TreeMatchlet *
898 parse_match_line (gchar *line,
899                   gint  *depth)
900 {
901   gchar *s, *p;
902   TreeMatchlet *matchlet;
903   gchar **parts;
904   gint i;
905
906   matchlet = g_slice_new0 (TreeMatchlet);
907
908   if (line[0] == '>')
909     {
910       *depth = 0;
911       s = line;
912     }
913   else
914     {
915       *depth = atoi (line);
916       s = strchr (line, '>');
917     }
918   s += 2;
919   p = strchr (s, '"');
920   *p = 0;
921
922   matchlet->path = g_strdup (s);
923   s = p + 1;
924   parts = g_strsplit (s, ",", 0);
925   if (strcmp (parts[0], "=file") == 0)
926     matchlet->type = G_FILE_TYPE_REGULAR;
927   else if (strcmp (parts[0], "=directory") == 0)
928     matchlet->type = G_FILE_TYPE_DIRECTORY;
929   else if (strcmp (parts[0], "=link") == 0)
930     matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
931   else
932     matchlet->type = G_FILE_TYPE_UNKNOWN;
933   for (i = 1; parts[i]; i++)
934     {
935       if (strcmp (parts[i], "executable") == 0)
936         matchlet->executable = 1;
937       else if (strcmp (parts[i], "match-case") == 0)
938         matchlet->match_case = 1;
939       else if (strcmp (parts[i], "non-empty") == 0)
940         matchlet->non_empty = 1;
941       else if (strcmp (parts[i], "on-disc") == 0)
942         matchlet->on_disc = 1;
943       else
944         matchlet->mimetype = g_strdup (parts[i]);
945     }
946
947   g_strfreev (parts);
948
949   return matchlet;
950 }
951
952 static gint
953 cmp_match (gconstpointer a, gconstpointer b)
954 {
955   const TreeMatch *aa = (const TreeMatch *)a;
956   const TreeMatch *bb = (const TreeMatch *)b;
957
958   return bb->priority - aa->priority;
959 }
960
961 static void
962 insert_match (TreeMatch *match)
963 {
964   tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
965 }
966
967 static void
968 insert_matchlet (TreeMatch    *match,
969                  TreeMatchlet *matchlet,
970                  gint          depth)
971 {
972   if (depth == 0)
973     match->matches = g_list_append (match->matches, matchlet);
974   else
975     {
976       GList *last;
977       TreeMatchlet *m;
978
979       last = g_list_last (match->matches);
980       if (!last)
981         {
982           tree_matchlet_free (matchlet);
983           g_warning ("can't insert tree matchlet at depth %d", depth);
984           return;
985         }
986
987       m = (TreeMatchlet *) last->data;
988       while (--depth > 0)
989         {
990           last = g_list_last (m->matches);
991           if (!last)
992             {
993               tree_matchlet_free (matchlet);
994               g_warning ("can't insert tree matchlet at depth %d", depth);
995               return;
996             }
997
998           m = (TreeMatchlet *) last->data;
999         }
1000       m->matches = g_list_append (m->matches, matchlet);
1001     }
1002 }
1003
1004 static void
1005 read_tree_magic_from_directory (const gchar *prefix)
1006 {
1007   gchar *filename;
1008   gchar *text;
1009   gsize len;
1010   gchar **lines;
1011   gint i;
1012   TreeMatch *match;
1013   TreeMatchlet *matchlet;
1014   gint depth;
1015
1016   filename = g_build_filename (prefix, "mime", "treemagic", NULL);
1017
1018   if (g_file_get_contents (filename, &text, &len, NULL))
1019     {
1020       if (strcmp (text, "MIME-TreeMagic") == 0)
1021         {
1022           lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
1023           match = NULL;
1024           for (i = 0; lines[i] && lines[i][0]; i++)
1025             {
1026               if (lines[i][0] == '[')
1027                 {
1028                   match = parse_header (lines[i]);
1029                   insert_match (match);
1030                 }
1031               else if (match != NULL)
1032                 {
1033                   matchlet = parse_match_line (lines[i], &depth);
1034                   insert_matchlet (match, matchlet, depth);
1035                 }
1036               else
1037                 {
1038                   g_warning ("%s: header corrupt; skipping\n", filename);
1039                   break;
1040                 }
1041             }
1042
1043           g_strfreev (lines);
1044         }
1045       else
1046         g_warning ("%s: header not found, skipping\n", filename);
1047
1048       g_free (text);
1049     }
1050
1051   g_free (filename);
1052 }
1053
1054
1055 static void
1056 xdg_mime_reload (void *user_data)
1057 {
1058   need_reload = TRUE;
1059 }
1060
1061 static void
1062 tree_magic_shutdown (void)
1063 {
1064   g_list_free_full (tree_matches, (GDestroyNotify) tree_match_free);
1065   tree_matches = NULL;
1066 }
1067
1068 static void
1069 tree_magic_init (void)
1070 {
1071   static gboolean initialized = FALSE;
1072   const gchar *dir;
1073   const gchar * const * dirs;
1074   int i;
1075
1076   if (!initialized)
1077     {
1078       initialized = TRUE;
1079
1080       xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1081       need_reload = TRUE;
1082     }
1083
1084   if (need_reload)
1085     {
1086       need_reload = FALSE;
1087
1088       tree_magic_shutdown ();
1089
1090       dir = g_get_user_data_dir ();
1091       read_tree_magic_from_directory (dir);
1092       dirs = g_get_system_data_dirs ();
1093       for (i = 0; dirs[i]; i++)
1094         read_tree_magic_from_directory (dirs[i]);
1095     }
1096 }
1097
1098 /* a filtering enumerator */
1099
1100 typedef struct
1101 {
1102   gchar *path;
1103   gint depth;
1104   gboolean ignore_case;
1105   gchar **components;
1106   gchar **case_components;
1107   GFileEnumerator **enumerators;
1108   GFile **children;
1109 } Enumerator;
1110
1111 static gboolean
1112 component_match (Enumerator  *e,
1113                  gint         depth,
1114                  const gchar *name)
1115 {
1116   gchar *case_folded, *key;
1117   gboolean found;
1118
1119   if (strcmp (name, e->components[depth]) == 0)
1120     return TRUE;
1121
1122   if (!e->ignore_case)
1123     return FALSE;
1124
1125   case_folded = g_utf8_casefold (name, -1);
1126   key = g_utf8_collate_key (case_folded, -1);
1127
1128   found = strcmp (key, e->case_components[depth]) == 0;
1129
1130   g_free (case_folded);
1131   g_free (key);
1132
1133   return found;
1134 }
1135
1136 static GFile *
1137 next_match_recurse (Enumerator *e,
1138                     gint        depth)
1139 {
1140   GFile *file;
1141   GFileInfo *info;
1142   const gchar *name;
1143
1144   while (TRUE)
1145     {
1146       if (e->enumerators[depth] == NULL)
1147         {
1148           if (depth > 0)
1149             {
1150               file = next_match_recurse (e, depth - 1);
1151               if (file)
1152                 {
1153                   e->children[depth] = file;
1154                   e->enumerators[depth] = g_file_enumerate_children (file,
1155                                                                      G_FILE_ATTRIBUTE_STANDARD_NAME,
1156                                                                      G_FILE_QUERY_INFO_NONE,
1157                                                                      NULL,
1158                                                                      NULL);
1159                 }
1160             }
1161           if (e->enumerators[depth] == NULL)
1162             return NULL;
1163         }
1164
1165       while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1166         {
1167           name = g_file_info_get_name (info);
1168           if (component_match (e, depth, name))
1169             {
1170               file = g_file_get_child (e->children[depth], name);
1171               g_object_unref (info);
1172               return file;
1173             }
1174           g_object_unref (info);
1175         }
1176
1177       g_object_unref (e->enumerators[depth]);
1178       e->enumerators[depth] = NULL;
1179       g_object_unref (e->children[depth]);
1180       e->children[depth] = NULL;
1181     }
1182 }
1183
1184 static GFile *
1185 enumerator_next (Enumerator *e)
1186 {
1187   return next_match_recurse (e, e->depth - 1);
1188 }
1189
1190 static Enumerator *
1191 enumerator_new (GFile      *root,
1192                 const char *path,
1193                 gboolean    ignore_case)
1194 {
1195   Enumerator *e;
1196   gint i;
1197   gchar *case_folded;
1198
1199   e = g_new0 (Enumerator, 1);
1200   e->path = g_strdup (path);
1201   e->ignore_case = ignore_case;
1202
1203   e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1204   e->depth = g_strv_length (e->components);
1205   if (e->ignore_case)
1206     {
1207       e->case_components = g_new0 (char *, e->depth + 1);
1208       for (i = 0; e->components[i]; i++)
1209         {
1210           case_folded = g_utf8_casefold (e->components[i], -1);
1211           e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1212           g_free (case_folded);
1213         }
1214     }
1215
1216   e->children = g_new0 (GFile *, e->depth);
1217   e->children[0] = g_object_ref (root);
1218   e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1219   e->enumerators[0] = g_file_enumerate_children (root,
1220                                                  G_FILE_ATTRIBUTE_STANDARD_NAME,
1221                                                  G_FILE_QUERY_INFO_NONE,
1222                                                  NULL,
1223                                                  NULL);
1224
1225   return e;
1226 }
1227
1228 static void
1229 enumerator_free (Enumerator *e)
1230 {
1231   gint i;
1232
1233   for (i = 0; i < e->depth; i++)
1234     {
1235       if (e->enumerators[i])
1236         g_object_unref (e->enumerators[i]);
1237       if (e->children[i])
1238         g_object_unref (e->children[i]);
1239     }
1240
1241   g_free (e->enumerators);
1242   g_free (e->children);
1243   g_strfreev (e->components);
1244   if (e->case_components)
1245     g_strfreev (e->case_components);
1246   g_free (e->path);
1247   g_free (e);
1248 }
1249
1250 static gboolean
1251 matchlet_match (TreeMatchlet *matchlet,
1252                 GFile        *root)
1253 {
1254   GFile *file;
1255   GFileInfo *info;
1256   gboolean result;
1257   const gchar *attrs;
1258   Enumerator *e;
1259   GList *l;
1260
1261   e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1262
1263   do
1264     {
1265       file = enumerator_next (e);
1266       if (!file)
1267         {
1268           enumerator_free (e);
1269           return FALSE;
1270         }
1271
1272       if (matchlet->mimetype)
1273         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1274                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1275                 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1276       else
1277         attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1278                 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1279       info = g_file_query_info (file,
1280                                 attrs,
1281                                 G_FILE_QUERY_INFO_NONE,
1282                                 NULL,
1283                                 NULL);
1284       if (info)
1285         {
1286           result = TRUE;
1287
1288           if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1289               g_file_info_get_file_type (info) != matchlet->type)
1290             result = FALSE;
1291
1292           if (matchlet->executable &&
1293               !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1294             result = FALSE;
1295         }
1296       else
1297         result = FALSE;
1298
1299       if (result && matchlet->non_empty)
1300         {
1301           GFileEnumerator *child_enum;
1302           GFileInfo *child_info;
1303
1304           child_enum = g_file_enumerate_children (file,
1305                                                   G_FILE_ATTRIBUTE_STANDARD_NAME,
1306                                                   G_FILE_QUERY_INFO_NONE,
1307                                                   NULL,
1308                                                   NULL);
1309
1310           if (child_enum)
1311             {
1312               child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1313               if (child_info)
1314                 g_object_unref (child_info);
1315               else
1316                 result = FALSE;
1317               g_object_unref (child_enum);
1318             }
1319           else
1320             result = FALSE;
1321         }
1322
1323       if (result && matchlet->mimetype)
1324         {
1325           if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1326             result = FALSE;
1327         }
1328
1329       if (info)
1330         g_object_unref (info);
1331       g_object_unref (file);
1332     }
1333   while (!result);
1334
1335   enumerator_free (e);
1336
1337   if (!matchlet->matches)
1338     return TRUE;
1339
1340   for (l = matchlet->matches; l; l = l->next)
1341     {
1342       TreeMatchlet *submatchlet;
1343
1344       submatchlet = l->data;
1345       if (matchlet_match (submatchlet, root))
1346         return TRUE;
1347     }
1348
1349   return FALSE;
1350 }
1351
1352 static void
1353 match_match (TreeMatch    *match,
1354              GFile        *root,
1355              GPtrArray    *types)
1356 {
1357   GList *l;
1358
1359   for (l = match->matches; l; l = l->next)
1360     {
1361       TreeMatchlet *matchlet = l->data;
1362       if (matchlet_match (matchlet, root))
1363         {
1364           g_ptr_array_add (types, g_strdup (match->contenttype));
1365           break;
1366         }
1367     }
1368 }
1369
1370 /**
1371  * g_content_type_guess_for_tree:
1372  * @root: the root of the tree to guess a type for
1373  *
1374  * Tries to guess the type of the tree with root @root, by
1375  * looking at the files it contains. The result is an array
1376  * of content types, with the best guess coming first.
1377  *
1378  * The types returned all have the form x-content/foo, e.g.
1379  * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1380  * (for a camera memory card). See the
1381  * [shared-mime-info](http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec)
1382  * specification for more on x-content types.
1383  *
1384  * This function is useful in the implementation of
1385  * g_mount_guess_content_type().
1386  *
1387  * Returns: (transfer full) (array zero-terminated=1): an %NULL-terminated
1388  *     array of zero or more content types. Free with g_strfreev()
1389  *
1390  * Since: 2.18
1391  */
1392 gchar **
1393 g_content_type_guess_for_tree (GFile *root)
1394 {
1395   GPtrArray *types;
1396   GList *l;
1397
1398   types = g_ptr_array_new ();
1399
1400   G_LOCK (gio_treemagic);
1401
1402   tree_magic_init ();
1403   for (l = tree_matches; l; l = l->next)
1404     {
1405       TreeMatch *match = l->data;
1406       match_match (match, root, types);
1407     }
1408
1409   G_UNLOCK (gio_treemagic);
1410
1411   g_ptr_array_add (types, NULL);
1412
1413   return (gchar **)g_ptr_array_free (types, FALSE);
1414 }