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