Add a GIcon implementation that can add an emblem to another icon.
[glib.git] / gio / gcontenttype.c
blob88f25bec8dc9c581cf3e44c73cd9083de0bd1dda
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
3 /* GIO - GLib Input, Output and Streaming Library
4 *
5 * Copyright (C) 2006-2007 Red Hat, Inc.
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.
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.
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.
22 * Author: Alexander Larsson <alexl@redhat.com>
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"
38 #include "gioalias.h"
40 /**
41 * SECTION:gcontenttype
42 * @short_description: Platform-specific content typing
43 * @include: gio/gio.h
45 * A content type is a platform specific string that defines the type
46 * of a file. On unix it is a mime type, on win32 it is an extension string
47 * like ".doc", ".txt" or a percieved string like "audio". Such strings
48 * can be looked up in the registry at HKEY_CLASSES_ROOT.
49 **/
51 #ifdef G_OS_WIN32
53 #include <windows.h>
55 static char *
56 get_registry_classes_key (const char *subdir,
57 const wchar_t *key_name)
59 wchar_t *wc_key;
60 HKEY reg_key = NULL;
61 DWORD key_type;
62 DWORD nbytes;
63 char *value_utf8;
65 value_utf8 = NULL;
67 nbytes = 0;
68 wc_key = g_utf8_to_utf16 (subdir, -1, NULL, NULL, NULL);
69 if (RegOpenKeyExW (HKEY_CLASSES_ROOT, wc_key, 0,
70 KEY_QUERY_VALUE, &reg_key) == ERROR_SUCCESS &&
71 RegQueryValueExW (reg_key, key_name, 0,
72 &key_type, NULL, &nbytes) == ERROR_SUCCESS &&
73 (key_type == REG_SZ || key_type == REG_EXPAND_SZ))
75 wchar_t *wc_temp = g_new (wchar_t, (nbytes+1)/2 + 1);
76 RegQueryValueExW (reg_key, key_name, 0,
77 &key_type, (LPBYTE) wc_temp, &nbytes);
78 wc_temp[nbytes/2] = '\0';
79 if (key_type == REG_EXPAND_SZ)
81 wchar_t dummy[1];
82 int len = ExpandEnvironmentStringsW (wc_temp, dummy, 1);
83 if (len > 0)
85 wchar_t *wc_temp_expanded = g_new (wchar_t, len);
86 if (ExpandEnvironmentStringsW (wc_temp, wc_temp_expanded, len) == len)
87 value_utf8 = g_utf16_to_utf8 (wc_temp_expanded, -1, NULL, NULL, NULL);
88 g_free (wc_temp_expanded);
91 else
93 value_utf8 = g_utf16_to_utf8 (wc_temp, -1, NULL, NULL, NULL);
95 g_free (wc_temp);
98 g_free (wc_key);
100 if (reg_key != NULL)
101 RegCloseKey (reg_key);
103 return value_utf8;
106 gboolean
107 g_content_type_equals (const char *type1,
108 const char *type2)
110 char *progid1, *progid2;
111 gboolean res;
113 g_return_val_if_fail (type1 != NULL, FALSE);
114 g_return_val_if_fail (type2 != NULL, FALSE);
116 if (g_ascii_strcasecmp (type1, type2) == 0)
117 return TRUE;
119 res = FALSE;
120 progid1 = get_registry_classes_key (type1, NULL);
121 progid2 = get_registry_classes_key (type2, NULL);
122 if (progid1 != NULL && progid2 != NULL &&
123 strcmp (progid1, progid2) == 0)
124 res = TRUE;
125 g_free (progid1);
126 g_free (progid2);
128 return res;
131 gboolean
132 g_content_type_is_a (const char *type,
133 const char *supertype)
135 gboolean res;
136 char *value_utf8;
138 g_return_val_if_fail (type != NULL, FALSE);
139 g_return_val_if_fail (supertype != NULL, FALSE);
141 if (g_content_type_equals (type, supertype))
142 return TRUE;
144 res = FALSE;
145 value_utf8 = get_registry_classes_key (type, L"PerceivedType");
146 if (value_utf8 && strcmp (value_utf8, supertype) == 0)
147 res = TRUE;
148 g_free (value_utf8);
150 return res;
153 gboolean
154 g_content_type_is_unknown (const char *type)
156 g_return_val_if_fail (type != NULL, FALSE);
158 return strcmp ("*", type) == 0;
161 char *
162 g_content_type_get_description (const char *type)
164 char *progid;
165 char *description;
167 g_return_val_if_fail (type != NULL, NULL);
169 progid = get_registry_classes_key (type, NULL);
170 if (progid)
172 description = get_registry_classes_key (progid, NULL);
173 g_free (progid);
175 if (description)
176 return description;
179 if (g_content_type_is_unknown (type))
180 return g_strdup (_("Unknown type"));
181 return g_strdup_printf (_("%s filetype"), type);
184 char *
185 g_content_type_get_mime_type (const char *type)
187 char *mime;
189 g_return_val_if_fail (type != NULL, NULL);
191 mime = get_registry_classes_key (type, L"Content Type");
192 if (mime)
193 return mime;
194 else if (g_content_type_is_unknown (type))
195 return g_strdup ("application/octet-stream");
196 else if (*type == '.')
197 return g_strdup_printf ("application/x-ext-%s", type+1);
198 /* TODO: Map "image" to "image/ *", etc? */
200 return g_strdup ("application/octet-stream");
203 G_LOCK_DEFINE_STATIC (_type_icons);
204 static GHashTable *_type_icons = NULL;
206 GIcon *
207 g_content_type_get_icon (const char *type)
209 GIcon *themed_icon;
210 char *name = NULL;
212 g_return_val_if_fail (type != NULL, NULL);
214 /* In the Registry icons are the default value of
215 HKEY_CLASSES_ROOT\<progid>\DefaultIcon with typical values like:
216 <type>: <value>
217 REG_EXPAND_SZ: %SystemRoot%\System32\Wscript.exe,3
218 REG_SZ: shimgvw.dll,3
220 G_LOCK (_type_icons);
221 if (!_type_icons)
222 _type_icons = g_hash_table_new (g_str_hash, g_str_equal);
223 name = g_hash_table_lookup (_type_icons, type);
224 if (!name && type[0] == '.')
226 /* double lookup by extension */
227 gchar *key = get_registry_classes_key (type, NULL);
228 if (!key)
229 key = g_strconcat (type+1, "file\\DefaultIcon", NULL);
230 else
232 gchar *key2 = g_strconcat (key, "\\DefaultIcon", NULL);
233 g_free (key);
234 key = key2;
236 name = get_registry_classes_key (key, NULL);
237 if (name && strcmp (name, "%1") == 0)
239 g_free (name);
240 name = NULL;
242 if (name)
243 g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
244 g_free (key);
247 /* icon-name similar to how it was with gtk-2-12 */
248 if (name)
250 themed_icon = g_themed_icon_new (name);
252 else
254 /* if not found an icon fall back to gtk-builtins */
255 name = strcmp (type, "inode/directory") == 0 ? "gtk-directory" :
256 g_content_type_can_be_executable (type) ? "gtk-execute" : "gtk-file";
257 g_hash_table_insert (_type_icons, g_strdup (type), g_strdup (name));
258 themed_icon = g_themed_icon_new_with_default_fallbacks (name);
260 G_UNLOCK (_type_icons);
262 return G_ICON (themed_icon);
265 gboolean
266 g_content_type_can_be_executable (const char *type)
268 g_return_val_if_fail (type != NULL, FALSE);
270 if (strcmp (type, ".exe") == 0 ||
271 strcmp (type, ".com") == 0 ||
272 strcmp (type, ".bat") == 0)
273 return TRUE;
275 /* TODO: Also look at PATHEXT, which lists the extensions for
276 * "scripts" in addition to those for true binary executables.
278 * (PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH for me
279 * right now, for instance). And in a sense, all associated file
280 * types are "executable" on Windows... You can just type foo.jpg as
281 * a command name in cmd.exe, and it will run the application
282 * associated with .jpg. Hard to say what this API actually means
283 * with "executable".
286 return FALSE;
289 static gboolean
290 looks_like_text (const guchar *data,
291 gsize data_size)
293 gsize i;
294 guchar c;
295 for (i = 0; i < data_size; i++)
297 c = data[i];
298 if (g_ascii_iscntrl (c) && !g_ascii_isspace (c))
299 return FALSE;
301 return TRUE;
304 char *
305 g_content_type_from_mime_type (const char *mime_type)
307 char *key, *content_type;
309 g_return_val_if_fail (mime_type != NULL, NULL);
311 key = g_strconcat ("MIME\\DataBase\\Content Type\\", mime_type, NULL);
312 content_type = get_registry_classes_key (key, L"Extension");
313 g_free (key);
315 return content_type;
318 char *
319 g_content_type_guess (const char *filename,
320 const guchar *data,
321 gsize data_size,
322 gboolean *result_uncertain)
324 char *basename;
325 char *type;
326 char *dot;
328 type = NULL;
330 if (filename)
332 basename = g_path_get_basename (filename);
333 dot = strrchr (basename, '.');
334 if (dot)
335 type = g_strdup (dot);
336 g_free (basename);
339 if (type)
340 return type;
342 if (data && looks_like_text (data, data_size))
343 return g_strdup (".txt");
345 return g_strdup ("*");
348 GList *
349 g_content_types_get_registered (void)
351 DWORD index;
352 wchar_t keyname[256];
353 DWORD key_len;
354 char *key_utf8;
355 GList *types;
357 types = NULL;
358 index = 0;
359 key_len = 256;
360 while (RegEnumKeyExW(HKEY_CLASSES_ROOT,
361 index,
362 keyname,
363 &key_len,
364 NULL,
365 NULL,
366 NULL,
367 NULL) == ERROR_SUCCESS)
369 key_utf8 = g_utf16_to_utf8 (keyname, -1, NULL, NULL, NULL);
370 if (key_utf8)
372 if (*key_utf8 == '.')
373 types = g_list_prepend (types, key_utf8);
374 else
375 g_free (key_utf8);
377 index++;
378 key_len = 256;
381 return g_list_reverse (types);
384 char **
385 g_content_type_guess_for_tree (GFile *root)
387 /* FIXME: implement */
388 return NULL;
391 #else /* !G_OS_WIN32 - Unix specific version */
393 #include <dirent.h>
395 #define XDG_PREFIX _gio_xdg
396 #include "xdgmime/xdgmime.h"
398 /* We lock this mutex whenever we modify global state in this module. */
399 G_LOCK_DEFINE_STATIC (gio_xdgmime);
401 gsize
402 _g_unix_content_type_get_sniff_len (void)
404 gsize size;
406 G_LOCK (gio_xdgmime);
407 size = xdg_mime_get_max_buffer_extents ();
408 G_UNLOCK (gio_xdgmime);
410 return size;
413 char *
414 _g_unix_content_type_unalias (const char *type)
416 char *res;
418 G_LOCK (gio_xdgmime);
419 res = g_strdup (xdg_mime_unalias_mime_type (type));
420 G_UNLOCK (gio_xdgmime);
422 return res;
425 char **
426 _g_unix_content_type_get_parents (const char *type)
428 const char *umime;
429 char **parents;
430 GPtrArray *array;
431 int i;
433 array = g_ptr_array_new ();
435 G_LOCK (gio_xdgmime);
437 umime = xdg_mime_unalias_mime_type (type);
439 g_ptr_array_add (array, g_strdup (umime));
441 parents = xdg_mime_list_mime_parents (umime);
442 for (i = 0; parents && parents[i] != NULL; i++)
443 g_ptr_array_add (array, g_strdup (parents[i]));
445 free (parents);
447 G_UNLOCK (gio_xdgmime);
449 g_ptr_array_add (array, NULL);
451 return (char **)g_ptr_array_free (array, FALSE);
455 * g_content_type_equals:
456 * @type1: a content type string.
457 * @type2: a content type string.
459 * Compares two content types for equality.
461 * Returns: %TRUE if the two strings are identical or equivalent,
462 * %FALSE otherwise.
463 **/
464 gboolean
465 g_content_type_equals (const char *type1,
466 const char *type2)
468 gboolean res;
470 g_return_val_if_fail (type1 != NULL, FALSE);
471 g_return_val_if_fail (type2 != NULL, FALSE);
473 G_LOCK (gio_xdgmime);
474 res = xdg_mime_mime_type_equal (type1, type2);
475 G_UNLOCK (gio_xdgmime);
477 return res;
481 * g_content_type_is_a:
482 * @type: a content type string.
483 * @supertype: a string.
485 * Determines if @type is a subset of @supertype.
487 * Returns: %TRUE if @type is a kind of @supertype,
488 * %FALSE otherwise.
489 **/
490 gboolean
491 g_content_type_is_a (const char *type,
492 const char *supertype)
494 gboolean res;
496 g_return_val_if_fail (type != NULL, FALSE);
497 g_return_val_if_fail (supertype != NULL, FALSE);
499 G_LOCK (gio_xdgmime);
500 res = xdg_mime_mime_type_subclass (type, supertype);
501 G_UNLOCK (gio_xdgmime);
503 return res;
507 * g_content_type_is_unknown:
508 * @type: a content type string.
510 * Checks if the content type is the generic "unknown" type.
511 * On unix this is the "application/octet-stream" mimetype,
512 * while on win32 it is "*".
514 * Returns: %TRUE if the type is the unknown type.
515 **/
516 gboolean
517 g_content_type_is_unknown (const char *type)
519 g_return_val_if_fail (type != NULL, FALSE);
521 return strcmp (XDG_MIME_TYPE_UNKNOWN, type) == 0;
525 typedef enum {
526 MIME_TAG_TYPE_OTHER,
527 MIME_TAG_TYPE_COMMENT
528 } MimeTagType;
530 typedef struct {
531 int current_type;
532 int current_lang_level;
533 int comment_lang_level;
534 char *comment;
535 } MimeParser;
538 static int
539 language_level (const char *lang)
541 const char * const *lang_list;
542 int i;
544 /* The returned list is sorted from most desirable to least
545 desirable and always contains the default locale "C". */
546 lang_list = g_get_language_names ();
548 for (i = 0; lang_list[i]; i++)
549 if (strcmp (lang_list[i], lang) == 0)
550 return 1000-i;
552 return 0;
555 static void
556 mime_info_start_element (GMarkupParseContext *context,
557 const gchar *element_name,
558 const gchar **attribute_names,
559 const gchar **attribute_values,
560 gpointer user_data,
561 GError **error)
563 int i;
564 const char *lang;
565 MimeParser *parser = user_data;
567 if (strcmp (element_name, "comment") == 0)
569 lang = "C";
570 for (i = 0; attribute_names[i]; i++)
571 if (strcmp (attribute_names[i], "xml:lang") == 0)
573 lang = attribute_values[i];
574 break;
577 parser->current_lang_level = language_level (lang);
578 parser->current_type = MIME_TAG_TYPE_COMMENT;
580 else
581 parser->current_type = MIME_TAG_TYPE_OTHER;
585 static void
586 mime_info_end_element (GMarkupParseContext *context,
587 const gchar *element_name,
588 gpointer user_data,
589 GError **error)
591 MimeParser *parser = user_data;
593 parser->current_type = MIME_TAG_TYPE_OTHER;
596 static void
597 mime_info_text (GMarkupParseContext *context,
598 const gchar *text,
599 gsize text_len,
600 gpointer user_data,
601 GError **error)
603 MimeParser *parser = user_data;
605 if (parser->current_type == MIME_TAG_TYPE_COMMENT &&
606 parser->current_lang_level > parser->comment_lang_level)
608 g_free (parser->comment);
609 parser->comment = g_strndup (text, text_len);
610 parser->comment_lang_level = parser->current_lang_level;
614 static char *
615 load_comment_for_mime_helper (const char *dir,
616 const char *basename)
618 GMarkupParseContext *context;
619 char *filename, *data;
620 gsize len;
621 gboolean res;
622 MimeParser parse_data = {0};
623 GMarkupParser parser = {
624 mime_info_start_element,
625 mime_info_end_element,
626 mime_info_text
629 filename = g_build_filename (dir, "mime", basename, NULL);
631 res = g_file_get_contents (filename, &data, &len, NULL);
632 g_free (filename);
633 if (!res)
634 return NULL;
636 context = g_markup_parse_context_new (&parser, 0, &parse_data, NULL);
637 res = g_markup_parse_context_parse (context, data, len, NULL);
638 g_free (data);
639 g_markup_parse_context_free (context);
641 if (!res)
642 return NULL;
644 return parse_data.comment;
648 static char *
649 load_comment_for_mime (const char *mimetype)
651 const char * const* dirs;
652 char *basename;
653 char *comment;
654 int i;
656 basename = g_strdup_printf ("%s.xml", mimetype);
658 comment = load_comment_for_mime_helper (g_get_user_data_dir (), basename);
659 if (comment)
661 g_free (basename);
662 return comment;
665 dirs = g_get_system_data_dirs ();
667 for (i = 0; dirs[i] != NULL; i++)
669 comment = load_comment_for_mime_helper (dirs[i], basename);
670 if (comment)
672 g_free (basename);
673 return comment;
676 g_free (basename);
678 return g_strdup_printf (_("%s type"), mimetype);
682 * g_content_type_get_description:
683 * @type: a content type string.
685 * Gets the human readable description of the content type.
687 * Returns: a short description of the content type @type.
688 **/
689 char *
690 g_content_type_get_description (const char *type)
692 static GHashTable *type_comment_cache = NULL;
693 char *comment;
695 g_return_val_if_fail (type != NULL, NULL);
697 G_LOCK (gio_xdgmime);
698 type = xdg_mime_unalias_mime_type (type);
700 if (type_comment_cache == NULL)
701 type_comment_cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
703 comment = g_hash_table_lookup (type_comment_cache, type);
704 comment = g_strdup (comment);
705 G_UNLOCK (gio_xdgmime);
707 if (comment != NULL)
708 return comment;
710 comment = load_comment_for_mime (type);
712 G_LOCK (gio_xdgmime);
713 g_hash_table_insert (type_comment_cache,
714 g_strdup (type),
715 g_strdup (comment));
716 G_UNLOCK (gio_xdgmime);
718 return comment;
722 * g_content_type_get_mime_type:
723 * @type: a content type string.
725 * Gets the mime-type for the content type. If one is registered
727 * Returns: the registered mime-type for the given @type, or NULL if unknown.
728 **/
729 char *
730 g_content_type_get_mime_type (const char *type)
732 g_return_val_if_fail (type != NULL, NULL);
734 return g_strdup (type);
738 * g_content_type_get_icon:
739 * @type: a content type string.
741 * Gets the icon for a content type.
743 * Returns: #GIcon corresponding to the content type.
744 **/
745 GIcon *
746 g_content_type_get_icon (const char *type)
748 char *mimetype_icon, *generic_mimetype_icon, *q;
749 char *xdg_mimetype_icon, *legacy_mimetype_icon;
750 char *icon_names[4];
751 int n = 0;
752 const char *p;
753 GIcon *themed_icon;
755 g_return_val_if_fail (type != NULL, NULL);
757 G_LOCK (gio_xdgmime);
758 xdg_mimetype_icon = g_strdup (xdg_mime_get_icon (type));
759 G_UNLOCK (gio_xdgmime);
761 mimetype_icon = g_strdup (type);
763 while ((q = strchr (mimetype_icon, '/')) != NULL)
764 *q = '-';
766 p = strchr (type, '/');
767 if (p == NULL)
768 p = type + strlen (type);
770 /* Not all icons have migrated to the new icon theme spec, look for old names too */
771 legacy_mimetype_icon = g_strconcat ("gnome-mime-", mimetype_icon, NULL);
773 generic_mimetype_icon = g_malloc (p - type + strlen ("-x-generic") + 1);
774 memcpy (generic_mimetype_icon, type, p - type);
775 memcpy (generic_mimetype_icon + (p - type), "-x-generic", strlen ("-x-generic"));
776 generic_mimetype_icon[(p - type) + strlen ("-x-generic")] = 0;
778 if (xdg_mimetype_icon)
779 icon_names[n++] = xdg_mimetype_icon;
781 icon_names[n++] = mimetype_icon;
782 icon_names[n++] = legacy_mimetype_icon;
783 icon_names[n++] = generic_mimetype_icon;
785 themed_icon = g_themed_icon_new_from_names (icon_names, n);
787 g_free (xdg_mimetype_icon);
788 g_free (mimetype_icon);
789 g_free (legacy_mimetype_icon);
790 g_free (generic_mimetype_icon);
792 return themed_icon;
796 * g_content_type_can_be_executable:
797 * @type: a content type string.
799 * Checks if a content type can be executable. Note that for instance
800 * things like text files can be executables (i.e. scripts and batch files).
802 * Returns: %TRUE if the file type corresponds to a type that
803 * can be executable, %FALSE otherwise.
804 **/
805 gboolean
806 g_content_type_can_be_executable (const char *type)
808 g_return_val_if_fail (type != NULL, FALSE);
810 if (g_content_type_is_a (type, "application/x-executable") ||
811 g_content_type_is_a (type, "text/plain"))
812 return TRUE;
814 return FALSE;
817 static gboolean
818 looks_like_text (const guchar *data, gsize data_size)
820 gsize i;
821 char c;
823 for (i = 0; i < data_size; i++)
825 c = data[i];
827 if (g_ascii_iscntrl (c) &&
828 !g_ascii_isspace (c))
829 return FALSE;
831 return TRUE;
835 * g_content_type_from_mime_type:
836 * @mime_type: a mime type string.
838 * Tries to find a content type based on the mime type name.
840 * Returns: Newly allocated string with content type or NULL when does not know.
842 * Since: 2.18
844 char *
845 g_content_type_from_mime_type (const char *mime_type)
847 char *umime;
849 g_return_val_if_fail (mime_type != NULL, NULL);
851 G_LOCK (gio_xdgmime);
852 /* mime type and content type are same on unixes */
853 umime = g_strdup (xdg_mime_unalias_mime_type (mime_type));
854 G_UNLOCK (gio_xdgmime);
856 return umime;
860 * g_content_type_guess:
861 * @filename: a string, or %NULL
862 * @data: a stream of data, or %NULL
863 * @data_size: the size of @data
864 * @result_uncertain: a flag indicating the certainty of the result
866 * Guesses the content type based on example data. If the function is
867 * uncertain, @result_uncertain will be set to %TRUE. Either @filename
868 * or @data may be %NULL, in which case the guess will be based solely
869 * on the other argument.
871 * Returns: a string indicating a guessed content type for the
872 * given data.
873 **/
874 char *
875 g_content_type_guess (const char *filename,
876 const guchar *data,
877 gsize data_size,
878 gboolean *result_uncertain)
880 char *basename;
881 const char *name_mimetypes[10], *sniffed_mimetype;
882 char *mimetype;
883 int i;
884 int n_name_mimetypes;
885 int sniffed_prio;
887 sniffed_prio = 0;
888 n_name_mimetypes = 0;
889 sniffed_mimetype = XDG_MIME_TYPE_UNKNOWN;
891 if (result_uncertain)
892 *result_uncertain = FALSE;
894 G_LOCK (gio_xdgmime);
896 if (filename)
898 basename = g_path_get_basename (filename);
899 n_name_mimetypes = xdg_mime_get_mime_types_from_file_name (basename, name_mimetypes, 10);
900 g_free (basename);
903 /* Got an extension match, and no conflicts. This is it. */
904 if (n_name_mimetypes == 1)
906 G_UNLOCK (gio_xdgmime);
907 return g_strdup (name_mimetypes[0]);
910 if (data)
912 sniffed_mimetype = xdg_mime_get_mime_type_for_data (data, data_size, &sniffed_prio);
913 if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
914 data &&
915 looks_like_text (data, data_size))
916 sniffed_mimetype = "text/plain";
919 if (n_name_mimetypes == 0)
921 if (sniffed_mimetype == XDG_MIME_TYPE_UNKNOWN &&
922 result_uncertain)
923 *result_uncertain = TRUE;
925 mimetype = g_strdup (sniffed_mimetype);
927 else
929 mimetype = NULL;
930 if (sniffed_mimetype != XDG_MIME_TYPE_UNKNOWN)
932 if (sniffed_prio >= 80) /* High priority sniffing match, use that */
933 mimetype = g_strdup (sniffed_mimetype);
934 else
936 /* There are conflicts between the name matches and we have a sniffed
937 type, use that as a tie breaker. */
939 for (i = 0; i < n_name_mimetypes; i++)
941 if ( xdg_mime_mime_type_subclass (name_mimetypes[i], sniffed_mimetype))
943 /* This nametype match is derived from (or the same as) the sniffed type).
944 This is probably it. */
945 mimetype = g_strdup (name_mimetypes[i]);
946 break;
952 if (mimetype == NULL)
954 /* Conflicts, and sniffed type was no help or not there. Guess on the first one */
955 mimetype = g_strdup (name_mimetypes[0]);
956 if (result_uncertain)
957 *result_uncertain = TRUE;
961 G_UNLOCK (gio_xdgmime);
963 return mimetype;
966 static void
967 enumerate_mimetypes_subdir (const char *dir,
968 const char *prefix,
969 GHashTable *mimetypes)
971 DIR *d;
972 struct dirent *ent;
973 char *mimetype;
975 d = opendir (dir);
976 if (d)
978 while ((ent = readdir (d)) != NULL)
980 if (g_str_has_suffix (ent->d_name, ".xml"))
982 mimetype = g_strdup_printf ("%s/%.*s", prefix, (int) strlen (ent->d_name) - 4, ent->d_name);
983 g_hash_table_insert (mimetypes, mimetype, NULL);
986 closedir (d);
990 static void
991 enumerate_mimetypes_dir (const char *dir,
992 GHashTable *mimetypes)
994 DIR *d;
995 struct dirent *ent;
996 char *mimedir;
997 char *name;
999 mimedir = g_build_filename (dir, "mime", NULL);
1001 d = opendir (mimedir);
1002 if (d)
1004 while ((ent = readdir (d)) != NULL)
1006 if (strcmp (ent->d_name, "packages") != 0)
1008 name = g_build_filename (mimedir, ent->d_name, NULL);
1009 if (g_file_test (name, G_FILE_TEST_IS_DIR))
1010 enumerate_mimetypes_subdir (name, ent->d_name, mimetypes);
1011 g_free (name);
1014 closedir (d);
1017 g_free (mimedir);
1021 * g_content_types_get_registered:
1023 * Gets a list of strings containing all the registered content types
1024 * known to the system. The list and its data should be freed using
1025 * @g_list_foreach(list, g_free, NULL) and @g_list_free(list)
1026 * Returns: #GList of the registered content types.
1027 **/
1028 GList *
1029 g_content_types_get_registered (void)
1031 const char * const* dirs;
1032 GHashTable *mimetypes;
1033 GHashTableIter iter;
1034 gpointer key;
1035 int i;
1036 GList *l;
1038 mimetypes = g_hash_table_new (g_str_hash, g_str_equal);
1040 enumerate_mimetypes_dir (g_get_user_data_dir (), mimetypes);
1041 dirs = g_get_system_data_dirs ();
1043 for (i = 0; dirs[i] != NULL; i++)
1044 enumerate_mimetypes_dir (dirs[i], mimetypes);
1046 l = NULL;
1047 g_hash_table_iter_init (&iter, mimetypes);
1048 while (g_hash_table_iter_next (&iter, &key, NULL))
1049 l = g_list_prepend (l, key);
1051 g_hash_table_destroy (mimetypes);
1053 return l;
1057 /* tree magic data */
1058 static GList *tree_matches = NULL;
1059 static gboolean need_reload = FALSE;
1061 G_LOCK_DEFINE_STATIC (gio_treemagic);
1063 typedef struct
1065 gchar *path;
1066 GFileType type;
1067 guint match_case : 1;
1068 guint executable : 1;
1069 guint non_empty : 1;
1070 guint on_disc : 1;
1071 gchar *mimetype;
1072 GList *matches;
1073 } TreeMatchlet;
1075 typedef struct
1077 gchar *contenttype;
1078 gint priority;
1079 GList *matches;
1080 } TreeMatch;
1083 static void
1084 tree_matchlet_free (TreeMatchlet *matchlet)
1086 g_list_foreach (matchlet->matches, (GFunc)tree_matchlet_free, NULL);
1087 g_list_free (matchlet->matches);
1088 g_free (matchlet->path);
1089 g_free (matchlet->mimetype);
1090 g_slice_free (TreeMatchlet, matchlet);
1093 static void
1094 tree_match_free (TreeMatch *match)
1096 g_list_foreach (match->matches, (GFunc)tree_matchlet_free, NULL);
1097 g_list_free (match->matches);
1098 g_free (match->contenttype);
1099 g_slice_free (TreeMatch, match);
1102 static TreeMatch *
1103 parse_header (gchar *line)
1105 gint len;
1106 gchar *s;
1107 TreeMatch *match;
1109 len = strlen (line);
1111 if (line[0] != '[' || line[len - 1] != ']')
1112 return NULL;
1114 line[len - 1] = 0;
1115 s = strchr (line, ':');
1117 match = g_slice_new0 (TreeMatch);
1118 match->priority = atoi (line + 1);
1119 match->contenttype = g_strdup (s + 1);
1121 return match;
1124 static TreeMatchlet *
1125 parse_match_line (gchar *line,
1126 gint *depth)
1128 gchar *s, *p;
1129 TreeMatchlet *matchlet;
1130 gchar **parts;
1131 gint i;
1133 matchlet = g_slice_new0 (TreeMatchlet);
1135 if (line[0] == '>')
1137 *depth = 0;
1138 s = line;
1140 else
1142 *depth = atoi (line);
1143 s = strchr (line, '>');
1145 s += 2;
1146 p = strchr (s, '"');
1147 *p = 0;
1149 matchlet->path = g_strdup (s);
1150 s = p + 1;
1151 parts = g_strsplit (s, ",", 0);
1152 if (strcmp (parts[0], "=file") == 0)
1153 matchlet->type = G_FILE_TYPE_REGULAR;
1154 else if (strcmp (parts[0], "=directory") == 0)
1155 matchlet->type = G_FILE_TYPE_DIRECTORY;
1156 else if (strcmp (parts[0], "=link") == 0)
1157 matchlet->type = G_FILE_TYPE_SYMBOLIC_LINK;
1158 else
1159 matchlet->type = G_FILE_TYPE_UNKNOWN;
1160 for (i = 1; parts[i]; i++)
1162 if (strcmp (parts[i], "executable") == 0)
1163 matchlet->executable = 1;
1164 else if (strcmp (parts[i], "match-case") == 0)
1165 matchlet->match_case = 1;
1166 else if (strcmp (parts[i], "non-empty") == 0)
1167 matchlet->non_empty = 1;
1168 else if (strcmp (parts[i], "on-disc") == 0)
1169 matchlet->on_disc = 1;
1170 else
1171 matchlet->mimetype = g_strdup (parts[i]);
1174 g_strfreev (parts);
1176 return matchlet;
1179 static gint
1180 cmp_match (gconstpointer a, gconstpointer b)
1182 const TreeMatch *aa = (const TreeMatch *)a;
1183 const TreeMatch *bb = (const TreeMatch *)b;
1185 return bb->priority - aa->priority;
1188 static void
1189 insert_match (TreeMatch *match)
1191 tree_matches = g_list_insert_sorted (tree_matches, match, cmp_match);
1194 static void
1195 insert_matchlet (TreeMatch *match,
1196 TreeMatchlet *matchlet,
1197 gint depth)
1199 if (depth == 0)
1200 match->matches = g_list_append (match->matches, matchlet);
1201 else
1203 GList *last;
1204 TreeMatchlet *m;
1206 last = g_list_last (match->matches);
1207 if (!last)
1209 tree_matchlet_free (matchlet);
1210 g_warning ("can't insert tree matchlet at depth %d", depth);
1211 return;
1214 m = (TreeMatchlet *) last->data;
1215 while (--depth > 0)
1217 last = g_list_last (m->matches);
1218 if (!last)
1220 tree_matchlet_free (matchlet);
1221 g_warning ("can't insert tree matchlet at depth %d", depth);
1222 return;
1225 m = (TreeMatchlet *) last->data;
1227 m->matches = g_list_append (m->matches, matchlet);
1231 static void
1232 read_tree_magic_from_directory (const gchar *prefix)
1234 gchar *filename;
1235 gchar *text;
1236 gsize len;
1237 gchar **lines;
1238 gint i;
1239 TreeMatch *match;
1240 TreeMatchlet *matchlet;
1241 gint depth;
1243 filename = g_build_filename (prefix, "mime", "treemagic", NULL);
1245 if (g_file_get_contents (filename, &text, &len, NULL))
1247 if (strcmp (text, "MIME-TreeMagic") == 0)
1249 lines = g_strsplit (text + strlen ("MIME-TreeMagic") + 2, "\n", 0);
1250 match = NULL;
1251 for (i = 0; lines[i] && lines[i][0]; i++)
1253 if (lines[i][0] == '[')
1255 match = parse_header (lines[i]);
1256 insert_match (match);
1258 else
1260 matchlet = parse_match_line (lines[i], &depth);
1261 insert_matchlet (match, matchlet, depth);
1265 g_strfreev (lines);
1267 else
1268 g_warning ("%s: header not found, skipping\n", filename);
1270 g_free (text);
1273 g_free (filename);
1277 static void
1278 xdg_mime_reload (void *user_data)
1280 need_reload = TRUE;
1283 static void
1284 tree_magic_shutdown (void)
1286 g_list_foreach (tree_matches, (GFunc)tree_match_free, NULL);
1287 g_list_free (tree_matches);
1288 tree_matches = NULL;
1291 static void
1292 tree_magic_init (void)
1294 static gboolean initialized = FALSE;
1295 const gchar *dir;
1296 const gchar * const * dirs;
1297 int i;
1299 if (!initialized)
1301 initialized = TRUE;
1303 xdg_mime_register_reload_callback (xdg_mime_reload, NULL, NULL);
1304 need_reload = TRUE;
1307 if (need_reload)
1309 need_reload = FALSE;
1311 tree_magic_shutdown ();
1313 dir = g_get_user_data_dir ();
1314 read_tree_magic_from_directory (dir);
1315 dirs = g_get_system_data_dirs ();
1316 for (i = 0; dirs[i]; i++)
1317 read_tree_magic_from_directory (dirs[i]);
1321 /* a filtering enumerator */
1323 typedef struct
1325 gchar *path;
1326 gint depth;
1327 gboolean ignore_case;
1328 gchar **components;
1329 gchar **case_components;
1330 GFileEnumerator **enumerators;
1331 GFile **children;
1332 } Enumerator;
1334 static gboolean
1335 component_match (Enumerator *e,
1336 gint depth,
1337 const gchar *name)
1339 gchar *case_folded, *key;
1340 gboolean found;
1342 if (strcmp (name, e->components[depth]) == 0)
1343 return TRUE;
1345 if (!e->ignore_case)
1346 return FALSE;
1348 case_folded = g_utf8_casefold (name, -1);
1349 key = g_utf8_collate_key (case_folded, -1);
1351 found = strcmp (key, e->case_components[depth]) == 0;
1353 g_free (case_folded);
1354 g_free (key);
1356 return found;
1359 static GFile *
1360 next_match_recurse (Enumerator *e,
1361 gint depth)
1363 GFile *file;
1364 GFileInfo *info;
1365 const gchar *name;
1367 while (TRUE)
1369 if (e->enumerators[depth] == NULL)
1371 if (depth > 0)
1373 file = next_match_recurse (e, depth - 1);
1374 if (file)
1376 e->children[depth] = file;
1377 e->enumerators[depth] = g_file_enumerate_children (file,
1378 G_FILE_ATTRIBUTE_STANDARD_NAME,
1379 G_FILE_QUERY_INFO_NONE,
1380 NULL,
1381 NULL);
1384 if (e->enumerators[depth] == NULL)
1385 return NULL;
1388 while ((info = g_file_enumerator_next_file (e->enumerators[depth], NULL, NULL)))
1390 name = g_file_info_get_name (info);
1391 if (component_match (e, depth, name))
1393 file = g_file_get_child (e->children[depth], name);
1394 g_object_unref (info);
1395 return file;
1397 g_object_unref (info);
1400 g_object_unref (e->enumerators[depth]);
1401 e->enumerators[depth] = NULL;
1402 g_object_unref (e->children[depth]);
1403 e->children[depth] = NULL;
1407 static GFile *
1408 enumerator_next (Enumerator *e)
1410 return next_match_recurse (e, e->depth - 1);
1413 static Enumerator *
1414 enumerator_new (GFile *root,
1415 const char *path,
1416 gboolean ignore_case)
1418 Enumerator *e;
1419 gint i;
1420 gchar *case_folded;
1422 e = g_new0 (Enumerator, 1);
1423 e->path = g_strdup (path);
1424 e->ignore_case = ignore_case;
1426 e->components = g_strsplit (e->path, G_DIR_SEPARATOR_S, -1);
1427 e->depth = g_strv_length (e->components);
1428 if (e->ignore_case)
1430 e->case_components = g_new0 (char *, e->depth + 1);
1431 for (i = 0; e->components[i]; i++)
1433 case_folded = g_utf8_casefold (e->components[i], -1);
1434 e->case_components[i] = g_utf8_collate_key (case_folded, -1);
1435 g_free (case_folded);
1439 e->children = g_new0 (GFile *, e->depth);
1440 e->children[0] = g_object_ref (root);
1441 e->enumerators = g_new0 (GFileEnumerator *, e->depth);
1442 e->enumerators[0] = g_file_enumerate_children (root,
1443 G_FILE_ATTRIBUTE_STANDARD_NAME,
1444 G_FILE_QUERY_INFO_NONE,
1445 NULL,
1446 NULL);
1448 return e;
1451 static void
1452 enumerator_free (Enumerator *e)
1454 gint i;
1456 for (i = 0; i < e->depth; i++)
1458 if (e->enumerators[i])
1459 g_object_unref (e->enumerators[i]);
1460 if (e->children[i])
1461 g_object_unref (e->children[i]);
1464 g_free (e->enumerators);
1465 g_free (e->children);
1466 g_strfreev (e->components);
1467 if (e->case_components)
1468 g_strfreev (e->case_components);
1469 g_free (e->path);
1470 g_free (e);
1473 static gboolean
1474 matchlet_match (TreeMatchlet *matchlet,
1475 GFile *root)
1477 GFile *file;
1478 GFileInfo *info;
1479 gboolean result;
1480 const gchar *attrs;
1481 Enumerator *e;
1482 GList *l;
1484 e = enumerator_new (root, matchlet->path, !matchlet->match_case);
1488 file = enumerator_next (e);
1489 if (!file)
1491 enumerator_free (e);
1492 return FALSE;
1495 if (matchlet->mimetype)
1496 attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1497 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE ","
1498 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE;
1499 else
1500 attrs = G_FILE_ATTRIBUTE_STANDARD_TYPE ","
1501 G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE;
1502 info = g_file_query_info (file,
1503 attrs,
1504 G_FILE_QUERY_INFO_NONE,
1505 NULL,
1506 NULL);
1507 if (info)
1509 result = TRUE;
1511 if (matchlet->type != G_FILE_TYPE_UNKNOWN &&
1512 g_file_info_get_file_type (info) != matchlet->type)
1513 result = FALSE;
1515 if (matchlet->executable &&
1516 !g_file_info_get_attribute_boolean (info, G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE))
1517 result = FALSE;
1519 else
1520 result = FALSE;
1522 if (result && matchlet->non_empty)
1524 GFileEnumerator *child_enum;
1525 GFileInfo *child_info;
1527 child_enum = g_file_enumerate_children (file,
1528 G_FILE_ATTRIBUTE_STANDARD_NAME,
1529 G_FILE_QUERY_INFO_NONE,
1530 NULL,
1531 NULL);
1533 if (child_enum)
1535 child_info = g_file_enumerator_next_file (child_enum, NULL, NULL);
1536 if (child_info)
1537 g_object_unref (child_info);
1538 else
1539 result = FALSE;
1540 g_object_unref (child_enum);
1542 else
1543 result = FALSE;
1546 if (result && matchlet->mimetype)
1548 if (strcmp (matchlet->mimetype, g_file_info_get_content_type (info)) != 0)
1549 result = FALSE;
1552 g_object_unref (info);
1553 g_object_unref (file);
1555 while (!result);
1557 enumerator_free (e);
1559 if (!matchlet->matches)
1560 return TRUE;
1562 for (l = matchlet->matches; l; l = l->next)
1564 TreeMatchlet *submatchlet;
1566 submatchlet = l->data;
1567 if (matchlet_match (submatchlet, root))
1568 return TRUE;
1571 return FALSE;
1574 static void
1575 match_match (TreeMatch *match,
1576 GFile *root,
1577 GPtrArray *types)
1579 GList *l;
1581 for (l = match->matches; l; l = l->next)
1583 TreeMatchlet *matchlet = l->data;
1584 if (matchlet_match (matchlet, root))
1586 g_ptr_array_add (types, g_strdup (match->contenttype));
1587 break;
1593 * g_content_type_guess_for_tree:
1594 * @root: the root of the tree to guess a type for
1596 * Tries to guess the type of the tree with root @root, by
1597 * looking at the files it contains. The result is an array
1598 * of content types, with the best guess coming first.
1600 * The types returned all have the form x-content/foo, e.g.
1601 * x-content/audio-cdda (for audio CDs) or x-content/image-dcf
1602 * (for a camera memory card). See the <ulink url="http://www.freedesktop.org/wiki/Specifications/shared-mime-info-spec">shared-mime-info</ulink>
1603 * specification for more on x-content types.
1605 * This function is useful in the implementation of g_mount_guess_content_type().
1607 * Returns: an %NULL-terminated array of zero or more content types, or %NULL.
1608 * Free with g_strfreev()
1610 * Since: 2.18
1612 char **
1613 g_content_type_guess_for_tree (GFile *root)
1615 GPtrArray *types;
1616 GList *l;
1618 types = g_ptr_array_new ();
1620 G_LOCK (gio_treemagic);
1622 tree_magic_init ();
1623 for (l = tree_matches; l; l = l->next)
1625 TreeMatch *match = l->data;
1626 match_match (match, root, types);
1629 G_UNLOCK (gio_treemagic);
1631 g_ptr_array_add (types, NULL);
1633 return (char **)g_ptr_array_free (types, FALSE);
1636 #endif /* Unix version */
1638 #define __G_CONTENT_TYPE_C__
1639 #include "gioaliasdef.c"