Unalias. Patch by Markus Bergman
[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 <string.h>
28 #include <stdio.h>
29 #include "gcontenttypeprivate.h"
30 #include "gthemedicon.h"
31 #include "glibintl.h"
32
33 #include "gioalias.h"
34
35 /**
36  * SECTION:gcontenttype
37  * @short_description: Platform-specific content typing
38  * @include: gio/gio.h
39  *
40  * A content type is a platform specific string that defines the type
41  * of a file. On unix it is a mime type, on win32 it is an extension string
42  * like ".doc", ".txt" or a percieved string like "audio". Such strings
43  * can be looked up in the registry at HKEY_CLASSES_ROOT.
44  **/
45
46 #ifdef G_OS_WIN32
47
48 #include <windows.h>
49
50 static char *
51 get_registry_classes_key (const char    *subdir,
52                           const wchar_t *key_name)
53 {
54   wchar_t *wc_key;
55   HKEY reg_key = NULL;
56   DWORD key_type;
57   DWORD nbytes;
58   char *value_utf8;
59
60   value_utf8 = NULL;
61   
62   nbytes = 0;
63   wc_key = g_utf8_to_utf16 (subdir, -1, NULL, NULL, NULL);
64   if (RegOpenKeyExW (HKEY_CLASSES_ROOT, wc_key, 0,
65                      KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS &&
66       RegQueryValueExW (reg_key, key_name, 0,
67                         &key_type, NULL, &nbytes) == ERROR_SUCCESS &&
68       (key_type == REG_SZ || key_type == REG_EXPAND_SZ))
69     {
70       wchar_t *wc_temp = g_new (wchar_t, (nbytes+1)/2 + 1);
71       RegQueryValueExW (reg_key, key_name, 0,
72                         &key_type, (LPBYTE) wc_temp, &nbytes);
73       wc_temp[nbytes/2] = '\0';
74       if (key_type == REG_EXPAND_SZ)
75         {
76           wchar_t dummy[1];
77           int len = ExpandEnvironmentStringsW (wc_temp, dummy, 1);
78           if (len > 0)
79             {
80               wchar_t *wc_temp_expanded = g_new (wchar_t, len);
81               if (ExpandEnvironmentStringsW (wc_temp, wc_temp_expanded, len) == len)
82                 value_utf8 = g_utf16_to_utf8 (wc_temp_expanded, -1, NULL, NULL, NULL);
83               g_free (wc_temp_expanded);
84             }
85         }
86       else
87         {
88           value_utf8 = g_utf16_to_utf8 (wc_temp, -1, NULL, NULL, NULL);
89         }
90       g_free (wc_temp);
91       
92     }
93   g_free (wc_key);
94   
95   if (reg_key != NULL)
96     RegCloseKey (reg_key);
97
98   return value_utf8;
99 }
100
101 gboolean
102 g_content_type_equals (const char *type1,
103                        const char *type2)
104 {
105   char *progid1, *progid2;
106   gboolean res;
107   
108   g_return_val_if_fail (type1 != NULL, FALSE);
109   g_return_val_if_fail (type2 != NULL, FALSE);
110
111   if (g_ascii_strcasecmp (type1, type2) == 0)
112     return TRUE;
113
114   res = FALSE;
115   progid1 = get_registry_classes_key (type1, NULL);
116   progid2 = get_registry_classes_key (type2, NULL);
117   if (progid1 != NULL && progid2 != NULL &&
118       strcmp (progid1, progid2) == 0)
119     res = TRUE;
120   g_free (progid1);
121   g_free (progid2);
122   
123   return res;
124 }
125
126 gboolean
127 g_content_type_is_a (const char *type,
128                      const char *supertype)
129 {
130   gboolean res;
131   char *value_utf8;
132
133   g_return_val_if_fail (type != NULL, FALSE);
134   g_return_val_if_fail (supertype != NULL, FALSE);
135
136   if (g_content_type_equals (type, supertype))
137     return TRUE;
138
139   res = FALSE;
140   value_utf8 = get_registry_classes_key (type, L"PerceivedType");
141   if (value_utf8 && strcmp (value_utf8, supertype) == 0)
142     res = TRUE;
143   g_free (value_utf8);
144   
145   return res;
146 }
147
148 gboolean
149 g_content_type_is_unknown (const char *type)
150 {
151   g_return_val_if_fail (type != NULL, FALSE);
152
153   return strcmp ("*", type) == 0;
154 }
155
156 char *
157 g_content_type_get_description (const char *type)
158 {
159   char *progid;
160   char *description;
161
162   g_return_val_if_fail (type != NULL, NULL);
163
164   progid = get_registry_classes_key (type, NULL);
165   if (progid)
166     {
167       description = get_registry_classes_key (progid, NULL);
168       g_free (progid);
169
170       if (description)
171         return description;
172     }
173
174   if (g_content_type_is_unknown (type))
175     return g_strdup (_("Unknown type"));
176   return g_strdup_printf (_("%s filetype"), type);
177 }
178
179 char *
180 g_content_type_get_mime_type (const char *type)
181 {
182   char *mime;
183
184   g_return_val_if_fail (type != NULL, NULL);
185
186   mime = get_registry_classes_key (type, L"Content Type");
187   if (mime)
188     return mime;
189   else if (g_content_type_is_unknown (type))
190     return g_strdup ("application/octet-stream");
191   else if (*type == '.')
192     return g_strdup_printf ("application/x-ext-%s", type+1);
193   /* TODO: Map "image" to "image/ *", etc? */
194
195   return g_strdup ("application/octet-stream");
196 }
197
198 G_LOCK_DEFINE_STATIC (_type_icons);
199 static GHashTable *_type_icons = NULL;
200
201 GIcon *
202 g_content_type_get_icon (const char *type)
203 {
204   GIcon *themed_icon;
205   char *name = NULL;
206
207   g_return_val_if_fail (type != NULL, NULL);
208
209   /* In the Registry icons are the default value of
210      HKEY_CLASSES_ROOT\<progid>\DefaultIcon with typical values like:
211      <type>: <value>
212      REG_EXPAND_SZ: %SystemRoot%\System32\Wscript.exe,3
213      REG_SZ: shimgvw.dll,3
214   */
215   G_LOCK (_type_icons);
216   if (!_type_icons)
217     _type_icons = g_hash_table_new (g_str_hash, g_str_equal);
218   name = g_hash_table_lookup (_type_icons, type);
219   if (!name && type[0] == '.')
220     {
221       /* double lookup by extension */
222       gchar *key = get_registry_classes_key (type, NULL);
223       if (!key)
224         key = g_strconcat (type+1, "file\\DefaultIcon", NULL);
225       else
226         {
227           gchar *key2 = g_strconcat (key, "\\DefaultIcon", NULL);
228           g_free (key);
229           key = key2;
230         }
231       name = get_registry_classes_key (key, NULL);
232       if (name && strcmp (name, "%1") == 0)
233         {
234           g_free (name);
235           name = NULL;
236         }
237       if (name)
238         g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
239       g_free (key);
240     }
241
242   /* icon-name similar to how it was with gtk-2-12 */
243   if (name)
244     {
245       themed_icon = g_themed_icon_new (name);
246     }
247   else
248     {
249       /* if not found an icon fall back to gtk-builtins */
250       name = strcmp (type, "inode/directory") == 0 ? "gtk-directory" : 
251                            g_content_type_can_be_executable (type) ? "gtk-execute" : "gtk-file";
252       g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
253       themed_icon = g_themed_icon_new_with_default_fallbacks (name);
254     }
255   G_UNLOCK (_type_icons);
256
257   return G_ICON (themed_icon);
258 }
259
260 gboolean
261 g_content_type_can_be_executable (const char *type)
262 {
263   g_return_val_if_fail (type != NULL, FALSE);
264
265   if (strcmp (type, ".exe") == 0 ||
266       strcmp (type, ".com") == 0 ||
267       strcmp (type, ".bat") == 0)
268     return TRUE;
269
270   /* TODO: Also look at PATHEXT, which lists the extensions for
271    * "scripts" in addition to those for true binary executables.
272    *
273    * (PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH for me
274    * right now, for instance). And in a sense, all associated file
275    * types are "executable" on Windows... You can just type foo.jpg as
276    * a command name in cmd.exe, and it will run the application
277    * associated with .jpg. Hard to say what this API actually means
278    * with "executable".
279    */
280
281   return FALSE;
282 }
283
284 static gboolean
285 looks_like_text (const guchar *data, 
286                  gsize         data_size)
287 {
288   gsize i;
289   guchar c;
290   for (i = 0; i < data_size; i++)
291     {
292       c = data[i];
293       if (g_ascii_iscntrl (c) && !g_ascii_isspace (c))
294         return FALSE;
295     }
296   return TRUE;
297 }
298
299 char *
300 g_content_type_from_mime_type (const char *mime_type)
301 {
302   char *key, *content_type;
303
304   g_return_val_if_fail (mime_type != NULL, NULL);
305
306   key = g_strconcat ("MIME\\DataBase\\Content Type\\", mime_type, NULL);
307   content_type = get_registry_classes_key (key, L"Extension");
308   g_free (key);
309
310   return content_type;
311 }
312
313 char *
314 g_content_type_guess (const char   *filename,
315                       const guchar *data,
316                       gsize         data_size,
317                       gboolean     *result_uncertain)
318 {
319   char *basename;
320   char *type;
321   char *dot;
322
323   type = NULL;
324
325   if (filename)
326     {
327       basename = g_path_get_basename (filename);
328       dot = strrchr (basename, '.');
329       if (dot)
330         type = g_strdup (dot);
331       g_free (basename);
332     }
333
334   if (type)
335     return type;
336
337   if (data && looks_like_text (data, data_size))
338     return g_strdup (".txt");
339
340   return g_strdup ("*");
341 }
342
343 GList *
344 g_content_types_get_registered (void)
345 {
346   DWORD index;
347   wchar_t keyname[256];
348   DWORD key_len;
349   char *key_utf8;
350   GList *types;
351
352   types = NULL;
353   index = 0;
354   key_len = 256;
355   while (RegEnumKeyExW(HKEY_CLASSES_ROOT,
356                        index,
357                        keyname,
358                        &key_len,
359                        NULL,
360                        NULL,
361                        NULL,
362                        NULL) == ERROR_SUCCESS)
363     {
364       key_utf8 = g_utf16_to_utf8 (keyname, -1, NULL, NULL, NULL);
365       if (key_utf8)
366         {
367           if (*key_utf8 == '.')
368             types = g_list_prepend (types, key_utf8);
369           else
370             g_free (key_utf8);
371         }
372       index++;
373       key_len = 256;
374     }
375   
376   return g_list_reverse (types);
377 }
378
379 #else /* !G_OS_WIN32 - Unix specific version */
380
381 #include <dirent.h>
382
383 #define XDG_PREFIX _gio_xdg
384 #include "xdgmime/xdgmime.h"
385
386 /* We lock this mutex whenever we modify global state in this module.  */
387 G_LOCK_DEFINE_STATIC (gio_xdgmime);
388
389 gsize
390 _g_unix_content_type_get_sniff_len (void)
391 {
392   gsize size;
393
394   G_LOCK (gio_xdgmime);
395   size = xdg_mime_get_max_buffer_extents ();
396   G_UNLOCK (gio_xdgmime);
397
398   return size;
399 }
400
401 char *
402 _g_unix_content_type_unalias (const char *type)
403 {
404   char *res;
405   
406   G_LOCK (gio_xdgmime);
407   res = g_strdup (xdg_mime_unalias_mime_type (type));
408   G_UNLOCK (gio_xdgmime);
409   
410   return res;
411 }
412
413 char **
414 _g_unix_content_type_get_parents (const char *type)
415 {
416   const char *umime;
417   char **parents;
418   GPtrArray *array;
419   int i;
420
421   array = g_ptr_array_new ();
422   
423   G_LOCK (gio_xdgmime);
424   
425   umime = xdg_mime_unalias_mime_type (type);
426   
427   g_ptr_array_add (array, g_strdup (umime));
428   
429   parents = xdg_mime_list_mime_parents (umime);
430   for (i = 0; parents && parents[i] != NULL; i++)
431     g_ptr_array_add (array, g_strdup (parents[i]));
432   
433   free (parents);
434   
435   G_UNLOCK (gio_xdgmime);
436   
437   g_ptr_array_add (array, NULL);
438   
439   return (char **)g_ptr_array_free (array, FALSE);
440 }
441
442 /**
443  * g_content_type_equals:
444  * @type1: a content type string.
445  * @type2: a content type string.
446  *
447  * Compares two content types for equality.
448  *
449  * Returns: %TRUE if the two strings are identical or equivalent,
450  * %FALSE otherwise.
451  **/  
452 gboolean
453 g_content_type_equals (const char *type1,
454                        const char *type2)
455 {
456   gboolean res;
457   
458   g_return_val_if_fail (type1 != NULL, FALSE);
459   g_return_val_if_fail (type2 != NULL, FALSE);
460   
461   G_LOCK (gio_xdgmime);
462   res = xdg_mime_mime_type_equal (type1, type2);
463   G_UNLOCK (gio_xdgmime);
464         
465   return res;
466 }
467
468 /**
469  * g_content_type_is_a:
470  * @type: a content type string. 
471  * @supertype: a string.
472  *
473  * Determines if @type is a subset of @supertype.  
474  *
475  * Returns: %TRUE if @type is a kind of @supertype,
476  * %FALSE otherwise. 
477  **/  
478 gboolean
479 g_content_type_is_a (const char *type,
480                      const char *supertype)
481 {
482   gboolean res;
483     
484   g_return_val_if_fail (type != NULL, FALSE);
485   g_return_val_if_fail (supertype != NULL, FALSE);
486   
487   G_LOCK (gio_xdgmime);
488   res = xdg_mime_mime_type_subclass (type, supertype);
489   G_UNLOCK (gio_xdgmime);
490         
491   return res;
492 }
493
494 /**
495  * g_content_type_is_unknown:
496  * @type: a content type string. 
497  * 
498  * Checks if the content type is the generic "unknown" type.
499  * On unix this is the "application/octet-stream" mimetype,
500  * while on win32 it is "*".
501  * 
502  * Returns: %TRUE if the type is the unknown type.
503  **/  
504 gboolean
505 g_content_type_is_unknown (const char *type)
506 {
507   g_return_val_if_fail (type != NULL, FALSE);
508
509   return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
510 }
511
512
513 typedef enum {
514   MIME_TAG_TYPE_OTHER,
515   MIME_TAG_TYPE_COMMENT
516 } MimeTagType;
517
518 typedef struct {
519   int current_type;
520   int current_lang_level;
521   int comment_lang_level;
522   char *comment;
523 } MimeParser;
524
525
526 static int
527 language_level (const char *lang)
528 {
529   const char * const *lang_list;
530   int i;
531   
532   /* The returned list is sorted from most desirable to least
533      desirable and always contains the default locale "C". */
534   lang_list = g_get_language_names ();
535   
536   for (i = 0; lang_list[i]; i++)
537     if (strcmp (lang_list[i], lang) == 0)
538       return 1000-i;
539   
540   return 0;
541 }
542
543 static void
544 mime_info_start_element (GMarkupParseContext  *context,
545                          const gchar          *element_name,
546                          const gchar         **attribute_names,
547                          const gchar         **attribute_values,
548                          gpointer              user_data,
549                          GError              **error)
550 {
551   int i;
552   const char *lang;
553   MimeParser *parser = user_data;
554   
555   if (strcmp (element_name, "comment") == 0)
556     {
557       lang = "C";
558       for (i = 0; attribute_names[i]; i++)
559         if (strcmp (attribute_names[i], "xml:lang") == 0)
560           {
561             lang = attribute_values[i];
562             break;
563           }
564       
565       parser->current_lang_level = language_level (lang);
566       parser->current_type = MIME_TAG_TYPE_COMMENT;
567     }
568   else
569     parser->current_type = MIME_TAG_TYPE_OTHER;
570   
571 }
572
573 static void
574 mime_info_end_element (GMarkupParseContext  *context,
575                        const gchar          *element_name,
576                        gpointer              user_data,
577                        GError              **error)
578 {
579   MimeParser *parser = user_data;
580   
581   parser->current_type = MIME_TAG_TYPE_OTHER;
582 }
583
584 static void
585 mime_info_text (GMarkupParseContext  *context,
586                 const gchar          *text,
587                 gsize                 text_len,  
588                 gpointer              user_data,
589                 GError              **error)
590 {
591   MimeParser *parser = user_data;
592
593   if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
594       parser->current_lang_level > parser->comment_lang_level)
595     {
596       g_free (parser->comment);
597       parser->comment = g_strndup (text, text_len);
598       parser->comment_lang_level = parser->current_lang_level;
599     }
600 }
601
602 static char *
603 load_comment_for_mime_helper (const char *dir, 
604                               const char *basename)
605 {
606   GMarkupParseContext *context;
607   char *filename, *data;
608   gsize len;
609   gboolean res;
610   MimeParser parse_data = {0};
611   GMarkupParser parser = {
612     mime_info_start_element,
613     mime_info_end_element,
614     mime_info_text
615   };
616
617   filename = g_build_filename (dir, "mime", basename, NULL);
618   
619   res = g_file_get_contents (filename,  &data,  &len,  NULL);
620   g_free (filename);
621   if (!res)
622     return NULL;
623   
624   context = g_markup_parse_context_new   (&parser, 0, &parse_data, NULL);
625   res = g_markup_parse_context_parse (context, data, len, NULL);
626   g_free (data);
627   g_markup_parse_context_free (context);
628   
629   if (!res)
630     return NULL;
631
632   return parse_data.comment;
633 }
634
635
636 static char *
637 load_comment_for_mime (const char *mimetype)
638 {
639   const char * const* dirs;
640   char *basename;
641   char *comment;
642   int i;
643
644   basename = g_strdup_printf ("%s.xml", mimetype);
645
646   comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
647   if (comment)
648     {
649       g_free (basename);
650       return comment;
651     }
652   
653   dirs = g_get_system_data_dirs ();
654
655   for (i = 0; dirs[i] != NULL; i++)
656     {
657       comment = load_comment_for_mime_helper (dirs[i], basename);
658       if (comment)
659         {
660           g_free (basename);
661           return comment;
662         }
663     }
664   g_free (basename);
665   
666   return g_strdup_printf (_("%s type"), mimetype);
667 }
668
669 /**
670  * g_content_type_get_description:
671  * @type: a content type string. 
672  * 
673  * Gets the human readable description of the content type.
674  * 
675  * Returns: a short description of the content type @type. 
676  **/  
677 char *
678 g_content_type_get_description (const char *type)
679 {
680   static GHashTable *type_comment_cache = NULL;
681   char *comment;
682
683   g_return_val_if_fail (type != NULL, NULL);
684   
685   G_LOCK (gio_xdgmime);
686   type = xdg_mime_unalias_mime_type (type);
687
688   if (type_comment_cache == NULL)
689     type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
690
691   comment = g_hash_table_lookup (type_comment_cache, type);
692   comment = g_strdup (comment);
693   G_UNLOCK (gio_xdgmime);
694   
695   if (comment != NULL)
696     return comment;
697
698   comment = load_comment_for_mime (type);
699   
700   G_LOCK (gio_xdgmime);
701   g_hash_table_insert (type_comment_cache,
702                        g_strdup (type),
703                        g_strdup (comment));
704   G_UNLOCK (gio_xdgmime);
705
706   return comment;
707 }
708
709 /**
710  * g_content_type_get_mime_type:
711  * @type: a content type string. 
712  * 
713  * Gets the mime-type for the content type. If one is registered
714  * 
715  * Returns: the registered mime-type for the given @type, or NULL if unknown.
716  **/  
717 char *
718 g_content_type_get_mime_type (const char *type)
719 {
720   g_return_val_if_fail (type != NULL, NULL);
721
722   return g_strdup (type);
723 }
724
725 /**
726  * g_content_type_get_icon:
727  * @type: a content type string.
728  * 
729  * Gets the icon for a content type.
730  * 
731  * Returns: #GIcon corresponding to the content type.
732  **/  
733 GIcon *
734 g_content_type_get_icon (const char *type)
735 {
736   char *mimetype_icon, *generic_mimetype_icon, *q;
737   char *xdg_mimetype_icon, *legacy_mimetype_icon;
738   char *icon_names[4];
739   int n = 0;
740   const char *p;
741   GIcon *themed_icon;
742   
743   g_return_val_if_fail (type != NULL, NULL);
744   
745   G_LOCK (gio_xdgmime);
746   xdg_mimetype_icon = g_strdup (xdg_mime_get_icon (type));
747   G_UNLOCK (gio_xdgmime);
748
749   mimetype_icon = g_strdup (type);
750   
751   while ((q = strchr (mimetype_icon, '/')) != NULL)
752     *q = '-';
753   
754   p = strchr (type, '/');
755   if (p == NULL)
756     p = type + strlen (type);
757
758   /* Not all icons have migrated to the new icon theme spec, look for old names too */
759   legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
760   
761   generic_mimetype_icon = g_malloc (p - type + strlen ("-x-generic") + 1);
762   memcpy (generic_mimetype_icon, type, p - type);
763   memcpy (generic_mimetype_icon + (p - type), "-x-generic", strlen ("-x-generic"));
764   generic_mimetype_icon[(p - type) + strlen ("-x-generic")] = 0;
765   
766   if (xdg_mimetype_icon)
767     icon_names[n++] = xdg_mimetype_icon;
768
769   icon_names[n++] = mimetype_icon;
770   icon_names[n++] = legacy_mimetype_icon;
771   icon_names[n++] = generic_mimetype_icon;
772   
773   themed_icon = g_themed_icon_new_from_names (icon_names, n);
774   
775   g_free (xdg_mimetype_icon);
776   g_free (mimetype_icon);
777   g_free (legacy_mimetype_icon);
778   g_free (generic_mimetype_icon);
779   
780   return themed_icon;
781 }
782
783 /**
784  * g_content_type_can_be_executable:
785  * @type: a content type string.
786  * 
787  * Checks if a content type can be executable. Note that for instance
788  * things like text files can be executables (i.e. scripts and batch files).
789  * 
790  * Returns: %TRUE if the file type corresponds to a type that
791  * can be executable, %FALSE otherwise. 
792  **/  
793 gboolean
794 g_content_type_can_be_executable (const char *type)
795 {
796   g_return_val_if_fail (type != NULL, FALSE);
797
798   if (g_content_type_is_a (type, "application/x-executable")  ||
799       g_content_type_is_a (type, "text/plain"))
800     return TRUE;
801
802   return FALSE;
803 }
804
805 static gboolean
806 looks_like_text (const guchar *data, gsize data_size)
807 {
808   gsize i;
809   char c;
810   
811   for (i = 0; i < data_size; i++)
812     {
813       c = data[i];
814       
815       if (g_ascii_iscntrl (c) &&
816           !g_ascii_isspace (c))
817         return FALSE;
818     }
819   return TRUE;
820 }
821
822 /**
823  * g_content_type_from_mime_type:
824  * @mime_type: a mime type string.
825  *
826  * Tries to find a content type based on the mime type name.
827  *
828  * Returns: Newly allocated string with content type or NULL when does not know.
829  *
830  * Since: 2.18
831  **/
832 char *
833 g_content_type_from_mime_type (const char *mime_type)
834 {
835   char *umime;
836
837   g_return_val_if_fail (mime_type != NULL, NULL);
838
839   G_LOCK (gio_xdgmime);
840   /* mime type and content type are same on unixes */
841   umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
842   G_LOCK (gio_xdgmime);
843
844   return umime;
845 }
846
847 /**
848  * g_content_type_guess:
849  * @filename: a string.
850  * @data: a stream of data.
851  * @data_size: the size of @data.
852  * @result_uncertain: a flag indicating the certainty of the 
853  * result.
854  * 
855  * Guesses the content type based on example data. If the function is 
856  * uncertain, @result_uncertain will be set to %TRUE.
857  * 
858  * Returns: a string indicating a guessed content type for the 
859  * given data. 
860  **/  
861 char *
862 g_content_type_guess (const char   *filename,
863                       const guchar *data,
864                       gsize         data_size,
865                       gboolean     *result_uncertain)
866 {
867   char *basename;
868   const char *name_mimetypes[10], *sniffed_mimetype;
869   char *mimetype;
870   int i;
871   int n_name_mimetypes;
872   int sniffed_prio;
873
874   sniffed_prio = 0;
875   n_name_mimetypes = 0;
876   sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
877
878   if (result_uncertain)
879     *result_uncertain = FALSE;
880   
881   G_LOCK (gio_xdgmime);
882   
883   if (filename)
884     {
885       basename = g_path_get_basename (filename);
886       n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
887       g_free (basename);
888     }
889
890   /* Got an extension match, and no conflicts. This is it. */
891   if (n_name_mimetypes == 1)
892     {
893       G_UNLOCK (gio_xdgmime);
894       return g_strdup (name_mimetypes[0]);
895     }
896   
897   if (data)
898     {
899       sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
900       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
901           data &&
902           looks_like_text (data, data_size))
903         sniffed_mimetype = "text/plain";
904     }
905   
906   if (n_name_mimetypes == 0)
907     {
908       if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
909           result_uncertain)
910         *result_uncertain = TRUE;
911       
912       mimetype = g_strdup (sniffed_mimetype);
913     }
914   else
915     {
916       mimetype = NULL;
917       if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
918         {
919           if (sniffed_prio >= 80) /* High priority sniffing match, use that */
920             mimetype = g_strdup (sniffed_mimetype);
921           else
922             {
923               /* There are conflicts between the name matches and we have a sniffed
924                  type, use that as a tie breaker. */
925               
926               for (i = 0; i < n_name_mimetypes; i++)
927                 {
928                   if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
929                     {
930                       /* This nametype match is derived from (or the same as) the sniffed type).
931                          This is probably it. */
932                       mimetype = g_strdup (name_mimetypes[i]);
933                       break;
934                     }
935                 }
936             }
937         }
938       
939       if (mimetype == NULL)
940         {
941           /* Conflicts, and sniffed type was no help or not there. Guess on the first one */
942           mimetype = g_strdup (name_mimetypes[0]);
943           if (result_uncertain)
944             *result_uncertain = TRUE;
945         }
946     }
947   
948   G_UNLOCK (gio_xdgmime);
949
950   return mimetype;
951 }
952
953 static void
954 enumerate_mimetypes_subdir (const char *dir, 
955                             const char *prefix, 
956                             GHashTable *mimetypes)
957 {
958   DIR *d;
959   struct dirent *ent;
960   char *mimetype;
961
962   d = opendir (dir);
963   if (d)
964     {
965       while ((ent = readdir (d)) != NULL)
966         {
967           if (g_str_has_suffix (ent->d_name, ".xml"))
968             {
969               mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
970               g_hash_table_insert (mimetypes, mimetype, NULL);
971             }
972         }
973       closedir (d);
974     }
975 }
976
977 static void
978 enumerate_mimetypes_dir (const char *dir, 
979                          GHashTable *mimetypes)
980 {
981   DIR *d;
982   struct dirent *ent;
983   char *mimedir;
984   char *name;
985
986   mimedir = g_build_filename (dir, "mime", NULL);
987   
988   d = opendir (mimedir);
989   if (d)
990     {
991       while ((ent = readdir (d)) != NULL)
992         {
993           if (strcmp (ent->d_name, "packages") != 0)
994             {
995               name = g_build_filename (mimedir, ent->d_name, NULL);
996               if (g_file_test (name, G_FILE_TEST_IS_DIR))
997                 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
998               g_free (name);
999             }
1000         }
1001       closedir (d);
1002     }
1003   
1004   g_free (mimedir);
1005 }
1006
1007 /**
1008  * g_content_types_get_registered:
1009  * 
1010  * Gets a list of strings containing all the registered content types
1011  * known to the system. The list and its data should be freed using 
1012  * @g_list_foreach(list, g_free, NULL) and @g_list_free(list)
1013  * Returns: #GList of the registered content types.
1014  **/  
1015 GList *
1016 g_content_types_get_registered (void)
1017 {
1018   const char * const* dirs;
1019   GHashTable *mimetypes;
1020   GHashTableIter iter;
1021   gpointer key;
1022   int i;
1023   GList *l;
1024
1025   mimetypes = g_hash_table_new (g_str_hash, g_str_equal);
1026
1027   enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
1028   dirs = g_get_system_data_dirs ();
1029
1030   for (i = 0; dirs[i] != NULL; i++)
1031     enumerate_mimetypes_dir (dirs[i], mimetypes);
1032
1033   l = NULL;
1034   g_hash_table_iter_init (&iter, mimetypes);
1035   while (g_hash_table_iter_next (&iter, &key, NULL))
1036     l = g_list_prepend (l, key);
1037
1038   g_hash_table_destroy (mimetypes);
1039
1040   return l;
1041 }
1042
1043 #endif /* Unix version */
1044
1045 #define __G_CONTENT_TYPE_C__
1046 #include "gioaliasdef.c"