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