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