g_unix_set_fd_nonblocking: New API to control file descriptor blocking state
[platform/upstream/glib.git] / gio / gdesktopappinfo.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  * Copyright © 2007 Ryan Lortie
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Author: Alexander Larsson <alexl@redhat.com>
22  */
23
24 #include "config.h"
25
26 #include <errno.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/wait.h>
30
31 #ifdef HAVE_CRT_EXTERNS_H
32 #include <crt_externs.h>
33 #endif
34
35 #undef G_DISABLE_DEPRECATED
36
37 #include "gcontenttypeprivate.h"
38 #include "gdesktopappinfo.h"
39 #include "gfile.h"
40 #include "gioerror.h"
41 #include "gthemedicon.h"
42 #include "gfileicon.h"
43 #include <glib/gstdio.h>
44 #include "glibintl.h"
45 #include "giomodule-priv.h"
46 #include "gappinfo.h"
47
48
49 /**
50  * SECTION:gdesktopappinfo
51  * @title: GDesktopAppInfo
52  * @short_description: Application information from desktop files
53  * @include: gio/gdesktopappinfo.h
54  *
55  * #GDesktopAppInfo is an implementation of #GAppInfo based on
56  * desktop files.
57  *
58  * Note that <filename>&lt;gio/gdesktopappinfo.h&gt;</filename> belongs to
59  * the UNIX-specific GIO interfaces, thus you have to use the
60  * <filename>gio-unix-2.0.pc</filename> pkg-config file when using it.
61  */
62
63 #define DEFAULT_APPLICATIONS_GROUP  "Default Applications"
64 #define ADDED_ASSOCIATIONS_GROUP    "Added Associations"
65 #define REMOVED_ASSOCIATIONS_GROUP  "Removed Associations"
66 #define MIME_CACHE_GROUP            "MIME Cache"
67 #define GENERIC_NAME_KEY            "GenericName"
68 #define FULL_NAME_KEY               "X-GNOME-FullName"
69
70 enum {
71   PROP_0,
72   PROP_FILENAME
73 };
74
75 static void     g_desktop_app_info_iface_init         (GAppInfoIface    *iface);
76 static GList *  get_all_desktop_entries_for_mime_type (const char       *base_mime_type,
77                                                        const char      **except,
78                                                        gboolean          include_fallback,
79                                                        char            **explicit_default);
80 static void     mime_info_cache_reload                (const char       *dir);
81 static gboolean g_desktop_app_info_ensure_saved       (GDesktopAppInfo  *info,
82                                                        GError          **error);
83
84 /**
85  * GDesktopAppInfo:
86  * 
87  * Information about an installed application from a desktop file.
88  */
89 struct _GDesktopAppInfo
90 {
91   GObject parent_instance;
92
93   char *desktop_id;
94   char *filename;
95
96   char *name;
97   char *generic_name;
98   char *fullname;
99   char *comment;
100   char *icon_name;
101   GIcon *icon;
102   char **only_show_in;
103   char **not_show_in;
104   char *try_exec;
105   char *exec;
106   char *binary;
107   char *path;
108   char *categories;
109
110   guint nodisplay       : 1;
111   guint hidden          : 1;
112   guint terminal        : 1;
113   guint startup_notify  : 1;
114   guint no_fuse         : 1;
115   /* FIXME: what about StartupWMClass ? */
116 };
117
118 typedef enum {
119   UPDATE_MIME_NONE = 1 << 0,
120   UPDATE_MIME_SET_DEFAULT = 1 << 1,
121   UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
122   UPDATE_MIME_REMOVE = 1 << 3,
123   UPDATE_MIME_SET_LAST_USED = 1 << 4,
124 } UpdateMimeFlags;
125
126 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
127                          G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO,
128                                                 g_desktop_app_info_iface_init))
129
130 static gpointer
131 search_path_init (gpointer data)
132 {
133   char **args = NULL;
134   const char * const *data_dirs;
135   const char *user_data_dir;
136   int i, length, j;
137
138   data_dirs = g_get_system_data_dirs ();
139   length = g_strv_length ((char **) data_dirs);
140   
141   args = g_new (char *, length + 2);
142   
143   j = 0;
144   user_data_dir = g_get_user_data_dir ();
145   args[j++] = g_build_filename (user_data_dir, "applications", NULL);
146   for (i = 0; i < length; i++)
147     args[j++] = g_build_filename (data_dirs[i],
148                                   "applications", NULL);
149   args[j++] = NULL;
150   
151   return args;
152 }
153   
154 static const char * const *
155 get_applications_search_path (void)
156 {
157   static GOnce once_init = G_ONCE_INIT;
158   return g_once (&once_init, search_path_init, NULL);
159 }
160
161 static void
162 g_desktop_app_info_finalize (GObject *object)
163 {
164   GDesktopAppInfo *info;
165
166   info = G_DESKTOP_APP_INFO (object);
167
168   g_free (info->desktop_id);
169   g_free (info->filename);
170   g_free (info->name);
171   g_free (info->generic_name);
172   g_free (info->fullname);
173   g_free (info->comment);
174   g_free (info->icon_name);
175   if (info->icon)
176     g_object_unref (info->icon);
177   g_strfreev (info->only_show_in);
178   g_strfreev (info->not_show_in);
179   g_free (info->try_exec);
180   g_free (info->exec);
181   g_free (info->binary);
182   g_free (info->path);
183   g_free (info->categories);
184   
185   G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
186 }
187
188 static void
189 g_desktop_app_info_set_property(GObject         *object,
190                                 guint            prop_id,
191                                 const GValue    *value,
192                                 GParamSpec      *pspec)
193 {
194   GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
195
196   switch (prop_id)
197     {
198     case PROP_FILENAME:
199       self->filename = g_value_dup_string (value);
200       break;
201
202     default:
203       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
204       break;
205     }
206 }
207
208 static void
209 g_desktop_app_info_get_property(GObject         *object,
210                                 guint            prop_id,
211                                 GValue          *value,
212                                 GParamSpec      *pspec)
213 {
214   GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
215
216   switch (prop_id)
217     {
218     case PROP_FILENAME:
219       g_value_set_string (value, self->filename);
220       break;
221     default:
222       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
223       break;
224     }
225 }
226
227 static void
228 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
229 {
230   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
231   
232   gobject_class->get_property = g_desktop_app_info_get_property;
233   gobject_class->set_property = g_desktop_app_info_set_property;
234   gobject_class->finalize = g_desktop_app_info_finalize;
235
236   /**
237    * GDesktopAppInfo:filename
238    *
239    * The origin filename of this #GDesktopAppInfo
240    */
241   g_object_class_install_property (gobject_class,
242                                    PROP_FILENAME,
243                                    g_param_spec_string ("filename", "Filename", "",
244                                                         NULL,
245                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
246 }
247
248 static void
249 g_desktop_app_info_init (GDesktopAppInfo *local)
250 {
251 }
252
253 static char *
254 binary_from_exec (const char *exec)
255 {
256   const char *p, *start;
257   
258   p = exec;
259   while (*p == ' ')
260     p++;
261   start = p;
262   while (*p != ' ' && *p != 0)
263     p++;
264   
265   return g_strndup (start, p - start);
266   
267 }
268
269 static gboolean
270 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info, 
271                                       GKeyFile        *key_file)
272 {
273   char *start_group;
274   char *type;
275   char *try_exec;
276
277   start_group = g_key_file_get_start_group (key_file);
278   if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
279     {
280       g_free (start_group);
281       return FALSE;
282     }
283   g_free (start_group);
284
285   type = g_key_file_get_string (key_file,
286                                 G_KEY_FILE_DESKTOP_GROUP,
287                                 G_KEY_FILE_DESKTOP_KEY_TYPE,
288                                 NULL);
289   if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
290     {
291       g_free (type);
292       return FALSE;
293     }
294   g_free (type);
295
296   try_exec = g_key_file_get_string (key_file,
297                                     G_KEY_FILE_DESKTOP_GROUP,
298                                     G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
299                                     NULL);
300   if (try_exec && try_exec[0] != '\0')
301     {
302       char *t;
303       t = g_find_program_in_path (try_exec);
304       if (t == NULL)
305         {
306           g_free (try_exec);
307           return FALSE;
308         }
309       g_free (t);
310     }
311
312   info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
313   info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
314   info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
315   info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
316   info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
317   info->icon_name =  g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
318   info->only_show_in = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN, NULL, NULL);
319   info->not_show_in = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN, NULL, NULL);
320   info->try_exec = try_exec;
321   info->exec = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_EXEC, NULL);
322   info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
323   info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
324   info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
325   info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
326   info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
327   info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
328   
329   info->icon = NULL;
330   if (info->icon_name)
331     {
332       if (g_path_is_absolute (info->icon_name))
333         {
334           GFile *file;
335           
336           file = g_file_new_for_path (info->icon_name);
337           info->icon = g_file_icon_new (file);
338           g_object_unref (file);
339         }
340       else
341         {
342           char *p;
343
344           /* Work around a common mistake in desktop files */    
345           if ((p = strrchr (info->icon_name, '.')) != NULL &&
346               (strcmp (p, ".png") == 0 ||
347                strcmp (p, ".xpm") == 0 ||
348                strcmp (p, ".svg") == 0)) 
349             *p = 0;
350
351           info->icon = g_themed_icon_new (info->icon_name);
352         }
353     }
354   
355   if (info->exec)
356     info->binary = binary_from_exec (info->exec);
357   
358   if (info->path && info->path[0] == '\0')
359     {
360       g_free (info->path);
361       info->path = NULL;
362     }
363
364   return TRUE;
365 }
366
367 static gboolean
368 g_desktop_app_info_load_file (GDesktopAppInfo *self)
369 {
370   GKeyFile *key_file;
371   gboolean retval = FALSE;
372   
373   g_return_val_if_fail (self->filename != NULL, FALSE);
374
375   key_file = g_key_file_new ();
376   
377   if (g_key_file_load_from_file (key_file,
378                                  self->filename,
379                                  G_KEY_FILE_NONE,
380                                  NULL))
381     {
382       retval = g_desktop_app_info_load_from_keyfile (self, key_file);
383     }
384
385   g_key_file_free (key_file);
386   return retval;
387 }
388
389 /**
390  * g_desktop_app_info_new_from_keyfile:
391  * @key_file: an opened #GKeyFile
392  * 
393  * Creates a new #GDesktopAppInfo.
394  *
395  * Returns: a new #GDesktopAppInfo or %NULL on error.
396  *
397  * Since: 2.18
398  **/
399 GDesktopAppInfo *
400 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
401 {
402   GDesktopAppInfo *info;
403
404   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
405   info->filename = NULL;
406   if (!g_desktop_app_info_load_from_keyfile (info, key_file))
407     {
408       g_object_unref (info);
409       return NULL;
410     }
411   return info;
412 }
413
414 /**
415  * g_desktop_app_info_new_from_filename:
416  * @filename: the path of a desktop file, in the GLib filename encoding
417  * 
418  * Creates a new #GDesktopAppInfo.
419  *
420  * Returns: a new #GDesktopAppInfo or %NULL on error.
421  **/
422 GDesktopAppInfo *
423 g_desktop_app_info_new_from_filename (const char *filename)
424 {
425   GDesktopAppInfo *info = NULL;
426
427   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
428   if (!g_desktop_app_info_load_file (info))
429     {
430       g_object_unref (info);
431       return NULL;
432     }
433   return info;
434 }
435
436 /**
437  * g_desktop_app_info_new:
438  * @desktop_id: the desktop file id
439  * 
440  * Creates a new #GDesktopAppInfo based on a desktop file id. 
441  *
442  * A desktop file id is the basename of the desktop file, including the 
443  * .desktop extension. GIO is looking for a desktop file with this name 
444  * in the <filename>applications</filename> subdirectories of the XDG data
445  * directories (i.e. the directories specified in the 
446  * <envar>XDG_DATA_HOME</envar> and <envar>XDG_DATA_DIRS</envar> environment 
447  * variables). GIO also supports the prefix-to-subdirectory mapping that is
448  * described in the <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Menu Spec</ulink> 
449  * (i.e. a desktop id of kde-foo.desktop will match
450  * <filename>/usr/share/applications/kde/foo.desktop</filename>).
451  * 
452  * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
453  */
454 GDesktopAppInfo *
455 g_desktop_app_info_new (const char *desktop_id)
456 {
457   GDesktopAppInfo *appinfo;
458   const char * const *dirs;
459   char *basename;
460   int i;
461
462   dirs = get_applications_search_path ();
463
464   basename = g_strdup (desktop_id);
465   
466   for (i = 0; dirs[i] != NULL; i++)
467     {
468       char *filename;
469       char *p;
470
471       filename = g_build_filename (dirs[i], desktop_id, NULL);
472       appinfo = g_desktop_app_info_new_from_filename (filename);
473       g_free (filename);
474       if (appinfo != NULL)
475         goto found;
476
477       p = basename;
478       while ((p = strchr (p, '-')) != NULL)
479         {
480           *p = '/';
481           
482           filename = g_build_filename (dirs[i], basename, NULL);
483           appinfo = g_desktop_app_info_new_from_filename (filename);
484           g_free (filename);
485           if (appinfo != NULL)
486             goto found;
487           *p = '-';
488           p++;
489         }
490     }
491   
492   g_free (basename);
493   return NULL;
494
495  found:
496   g_free (basename);
497   
498   appinfo->desktop_id = g_strdup (desktop_id);
499
500   if (g_desktop_app_info_get_is_hidden (appinfo))
501     {
502       g_object_unref (appinfo);
503       appinfo = NULL;
504     }
505   
506   return appinfo;
507 }
508
509 static GAppInfo *
510 g_desktop_app_info_dup (GAppInfo *appinfo)
511 {
512   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
513   GDesktopAppInfo *new_info;
514   
515   new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
516
517   new_info->filename = g_strdup (info->filename);
518   new_info->desktop_id = g_strdup (info->desktop_id);
519   
520   new_info->name = g_strdup (info->name);
521   new_info->generic_name = g_strdup (info->generic_name);
522   new_info->fullname = g_strdup (info->fullname);
523   new_info->comment = g_strdup (info->comment);
524   new_info->nodisplay = info->nodisplay;
525   new_info->icon_name = g_strdup (info->icon_name);
526   if (info->icon)
527     new_info->icon = g_object_ref (info->icon);
528   new_info->only_show_in = g_strdupv (info->only_show_in);
529   new_info->not_show_in = g_strdupv (info->not_show_in);
530   new_info->try_exec = g_strdup (info->try_exec);
531   new_info->exec = g_strdup (info->exec);
532   new_info->binary = g_strdup (info->binary);
533   new_info->path = g_strdup (info->path);
534   new_info->hidden = info->hidden;
535   new_info->terminal = info->terminal;
536   new_info->startup_notify = info->startup_notify;
537   
538   return G_APP_INFO (new_info);
539 }
540
541 static gboolean
542 g_desktop_app_info_equal (GAppInfo *appinfo1,
543                           GAppInfo *appinfo2)
544 {
545   GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
546   GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
547
548   if (info1->desktop_id == NULL ||
549       info2->desktop_id == NULL)
550     return info1 == info2;
551
552   return strcmp (info1->desktop_id, info2->desktop_id) == 0;
553 }
554
555 static const char *
556 g_desktop_app_info_get_id (GAppInfo *appinfo)
557 {
558   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
559
560   return info->desktop_id;
561 }
562
563 static const char *
564 g_desktop_app_info_get_name (GAppInfo *appinfo)
565 {
566   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
567
568   if (info->name == NULL)
569     return _("Unnamed");
570   return info->name;
571 }
572
573 static const char *
574 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
575 {
576   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
577
578   if (info->fullname == NULL)
579     return g_desktop_app_info_get_name (appinfo);
580   return info->fullname;
581 }
582
583 /**
584  * g_desktop_app_info_get_is_hidden:
585  * @info: a #GDesktopAppInfo.
586  *
587  * A desktop file is hidden if the Hidden key in it is
588  * set to True.
589  *
590  * Returns: %TRUE if hidden, %FALSE otherwise. 
591  **/
592 gboolean
593 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
594 {
595   return info->hidden;
596 }
597
598 /**
599  * g_desktop_app_info_get_filename:
600  * @info: a #GDesktopAppInfo
601  *
602  * When @info was created from a known filename, return it.  In some
603  * situations such as the #GDesktopAppInfo returned from
604  * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
605  *
606  * Returns: The full path to the file for @info, or %NULL if not known.
607  * Since: 2.24
608  */
609 const char *
610 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
611 {
612   return info->filename;
613 }
614
615 static const char *
616 g_desktop_app_info_get_description (GAppInfo *appinfo)
617 {
618   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
619   
620   return info->comment;
621 }
622
623 static const char *
624 g_desktop_app_info_get_executable (GAppInfo *appinfo)
625 {
626   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
627   
628   return info->binary;
629 }
630
631 static const char *
632 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
633 {
634   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
635   
636   return info->exec;
637 }
638
639 static GIcon *
640 g_desktop_app_info_get_icon (GAppInfo *appinfo)
641 {
642   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
643
644   return info->icon;
645 }
646
647 /**
648  * g_desktop_app_info_get_categories:
649  * @info: a #GDesktopAppInfo
650  *
651  * Gets the categories from the desktop file.
652  *
653  * Returns: The unparsed Categories key from the desktop file;
654  *     i.e. no attempt is made to split it by ';' or validate it.
655  */
656 const char *
657 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
658 {
659   return info->categories;
660 }
661
662 /**
663  * g_desktop_app_info_get_generic_name:
664  * @info: a #GDesktopAppInfo
665  *
666  * Gets the generic name from the destkop file.
667  *
668  * Returns: The value of the GenericName key
669  */
670 const char *
671 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
672 {
673   return info->generic_name;
674 }
675
676 static char *
677 expand_macro_single (char macro, char *uri)
678 {
679   GFile *file;
680   char *result = NULL;
681   char *path, *name;
682
683   file = g_file_new_for_uri (uri);
684   path = g_file_get_path (file);
685   g_object_unref (file);
686   
687   switch (macro)
688     {
689     case 'u':
690     case 'U':   
691       result = g_shell_quote (uri);
692       break;
693     case 'f':
694     case 'F':
695       if (path)
696         result = g_shell_quote (path);
697       break;
698     case 'd':
699     case 'D':
700       if (path)
701         {
702           name = g_path_get_dirname (path);
703           result = g_shell_quote (name);
704           g_free (name);
705         }
706       break;
707     case 'n':
708     case 'N':
709       if (path)
710         {
711           name = g_path_get_basename (path);
712           result = g_shell_quote (name);
713           g_free (name);
714         }
715       break;
716     }
717
718   g_free (path);
719   
720   return result;
721 }
722
723 static void
724 expand_macro (char              macro, 
725               GString          *exec, 
726               GDesktopAppInfo  *info, 
727               GList           **uri_list)
728 {
729   GList *uris = *uri_list;
730   char *expanded;
731   gboolean force_file_uri;
732   char force_file_uri_macro;
733   char *uri;
734
735   g_return_if_fail (exec != NULL);
736
737   /* On %u and %U, pass POSIX file path pointing to the URI via
738    * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
739    * running or the URI doesn't have a POSIX file path via FUSE
740    * we'll just pass the URI.
741    */
742   force_file_uri_macro = macro;
743   force_file_uri = FALSE;
744   if (!info->no_fuse)
745     {
746       switch (macro)
747         {
748         case 'u':
749           force_file_uri_macro = 'f';
750           force_file_uri = TRUE;
751           break;
752         case 'U':
753           force_file_uri_macro = 'F';
754           force_file_uri = TRUE;
755           break;
756         default:
757           break;
758         }
759     }
760
761   switch (macro)
762     {
763     case 'u':
764     case 'f':
765     case 'd':
766     case 'n':
767       if (uris)
768         {
769           uri = uris->data;
770           if (!force_file_uri ||
771               /* Pass URI if it contains an anchor */
772               strchr (uri, '#') != NULL)
773             {
774               expanded = expand_macro_single (macro, uri);
775             }
776           else
777             {
778               expanded = expand_macro_single (force_file_uri_macro, uri);
779               if (expanded == NULL)
780                 expanded = expand_macro_single (macro, uri);
781             }
782
783           if (expanded)
784             {
785               g_string_append (exec, expanded);
786               g_free (expanded);
787             }
788           uris = uris->next;
789         }
790
791       break;
792
793     case 'U':   
794     case 'F':
795     case 'D':
796     case 'N':
797       while (uris)
798         {
799           uri = uris->data;
800           
801           if (!force_file_uri ||
802               /* Pass URI if it contains an anchor */
803               strchr (uri, '#') != NULL)
804             {
805               expanded = expand_macro_single (macro, uri);
806             }
807           else
808             {
809               expanded = expand_macro_single (force_file_uri_macro, uri);
810               if (expanded == NULL)
811                 expanded = expand_macro_single (macro, uri);
812             }
813
814           if (expanded)
815             {
816               g_string_append (exec, expanded);
817               g_free (expanded);
818             }
819           
820           uris = uris->next;
821           
822           if (uris != NULL && expanded)
823             g_string_append_c (exec, ' ');
824         }
825
826       break;
827
828     case 'i':
829       if (info->icon_name)
830         {
831           g_string_append (exec, "--icon ");
832           expanded = g_shell_quote (info->icon_name);
833           g_string_append (exec, expanded);
834           g_free (expanded);
835         }
836       break;
837
838     case 'c':
839       if (info->name) 
840         {
841           expanded = g_shell_quote (info->name);
842           g_string_append (exec, expanded);
843           g_free (expanded);
844         }
845       break;
846
847     case 'k':
848       if (info->filename) 
849         {
850           expanded = g_shell_quote (info->filename);
851           g_string_append (exec, expanded);
852           g_free (expanded);
853         }
854       break;
855
856     case 'm': /* deprecated */
857       break;
858
859     case '%':
860       g_string_append_c (exec, '%');
861       break;
862     }
863   
864   *uri_list = uris;
865 }
866
867 static gboolean
868 expand_application_parameters (GDesktopAppInfo   *info,
869                                GList            **uris,
870                                int               *argc,
871                                char            ***argv,
872                                GError           **error)
873 {
874   GList *uri_list = *uris;
875   const char *p = info->exec;
876   GString *expanded_exec;
877   gboolean res;
878
879   if (info->exec == NULL)
880     {
881       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
882                            _("Desktop file didn't specify Exec field"));
883       return FALSE;
884     }
885
886   expanded_exec = g_string_new (NULL);
887
888   while (*p)
889     {
890       if (p[0] == '%' && p[1] != '\0')
891         {
892           expand_macro (p[1], expanded_exec, info, uris);
893           p++;
894         }
895       else
896         g_string_append_c (expanded_exec, *p);
897
898       p++;
899     }
900
901   /* No file substitutions */
902   if (uri_list == *uris && uri_list != NULL)
903     {
904       /* If there is no macro default to %f. This is also what KDE does */
905       g_string_append_c (expanded_exec, ' ');
906       expand_macro ('f', expanded_exec, info, uris);
907     }
908
909   res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
910   g_string_free (expanded_exec, TRUE);
911   return res;
912 }
913
914 static gboolean
915 prepend_terminal_to_vector (int    *argc,
916                             char ***argv)
917 {
918 #ifndef G_OS_WIN32
919   char **real_argv;
920   int real_argc;
921   int i, j;
922   char **term_argv = NULL;
923   int term_argc = 0;
924   char *check;
925   char **the_argv;
926   
927   g_return_val_if_fail (argc != NULL, FALSE);
928   g_return_val_if_fail (argv != NULL, FALSE);
929         
930   /* sanity */
931   if(*argv == NULL)
932     *argc = 0;
933   
934   the_argv = *argv;
935
936   /* compute size if not given */
937   if (*argc < 0)
938     {
939       for (i = 0; the_argv[i] != NULL; i++)
940         ;
941       *argc = i;
942     }
943   
944   term_argc = 2;
945   term_argv = g_new0 (char *, 3);
946
947   check = g_find_program_in_path ("gnome-terminal");
948   if (check != NULL)
949     {
950       term_argv[0] = check;
951       /* Note that gnome-terminal takes -x and
952        * as -e in gnome-terminal is broken we use that. */
953       term_argv[1] = g_strdup ("-x");
954     }
955   else
956     {
957       if (check == NULL)
958         check = g_find_program_in_path ("nxterm");
959       if (check == NULL)
960         check = g_find_program_in_path ("color-xterm");
961       if (check == NULL)
962         check = g_find_program_in_path ("rxvt");
963       if (check == NULL)
964         check = g_find_program_in_path ("xterm");
965       if (check == NULL)
966         check = g_find_program_in_path ("dtterm");
967       if (check == NULL)
968         {
969           check = g_strdup ("xterm");
970           g_warning ("couldn't find a terminal, falling back to xterm");
971         }
972       term_argv[0] = check;
973       term_argv[1] = g_strdup ("-e");
974     }
975
976   real_argc = term_argc + *argc;
977   real_argv = g_new (char *, real_argc + 1);
978   
979   for (i = 0; i < term_argc; i++)
980     real_argv[i] = term_argv[i];
981   
982   for (j = 0; j < *argc; j++, i++)
983     real_argv[i] = (char *)the_argv[j];
984   
985   real_argv[i] = NULL;
986   
987   g_free (*argv);
988   *argv = real_argv;
989   *argc = real_argc;
990   
991   /* we use g_free here as we sucked all the inner strings
992    * out from it into real_argv */
993   g_free (term_argv);
994   return TRUE;
995 #else
996   return FALSE;
997 #endif /* G_OS_WIN32 */
998 }
999
1000 static GList *
1001 create_files_for_uris (GList *uris)
1002 {
1003   GList *res;
1004   GList *iter;
1005
1006   res = NULL;
1007
1008   for (iter = uris; iter; iter = iter->next)
1009     {
1010       GFile *file = g_file_new_for_uri ((char *)iter->data);
1011       res = g_list_prepend (res, file);
1012     }
1013
1014   return g_list_reverse (res);
1015 }
1016
1017 typedef struct
1018 {
1019   GSpawnChildSetupFunc user_setup;
1020   gpointer user_setup_data;
1021   char *display;
1022   char *sn_id;
1023   char *desktop_file;
1024 } ChildSetupData;
1025
1026 static void
1027 child_setup (gpointer user_data)
1028 {
1029   ChildSetupData *data = user_data;
1030
1031   if (data->display)
1032     g_setenv ("DISPLAY", data->display, TRUE);
1033
1034   if (data->sn_id)
1035     g_setenv ("DESKTOP_STARTUP_ID", data->sn_id, TRUE);
1036
1037   if (data->desktop_file)
1038     {
1039       gchar pid[20];
1040
1041       g_setenv ("GIO_LAUNCHED_DESKTOP_FILE", data->desktop_file, TRUE);
1042
1043       g_snprintf (pid, 20, "%ld", (long)getpid ());
1044       g_setenv ("GIO_LAUNCHED_DESKTOP_FILE_PID", pid, TRUE);
1045     }
1046
1047   if (data->user_setup)
1048     data->user_setup (data->user_setup_data);
1049 }
1050
1051 static void
1052 notify_desktop_launch (GDBusConnection  *session_bus,
1053                        GDesktopAppInfo  *info,
1054                        long              pid,
1055                        const char       *display,
1056                        const char       *sn_id,
1057                        GList            *uris)
1058 {
1059   GDBusMessage *msg;
1060   GVariantBuilder uri_variant;
1061   GVariantBuilder extras_variant;
1062   GList *iter;
1063   const char *desktop_file_id;
1064   const char *gio_desktop_file;
1065
1066   if (session_bus == NULL)
1067     return;
1068
1069   g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
1070   for (iter = uris; iter; iter = iter->next)
1071     g_variant_builder_add (&uri_variant, "s", iter->data);
1072
1073   g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
1074   if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
1075     g_variant_builder_add (&extras_variant, "{sv}",
1076                            "startup-id",
1077                            g_variant_new ("s",
1078                                           sn_id));
1079   gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
1080   if (gio_desktop_file != NULL)
1081     g_variant_builder_add (&extras_variant, "{sv}",
1082                            "origin-desktop-file",
1083                            g_variant_new_bytestring (gio_desktop_file));
1084   if (g_get_prgname () != NULL)
1085     g_variant_builder_add (&extras_variant, "{sv}",
1086                            "origin-prgname",
1087                            g_variant_new_bytestring (g_get_prgname ()));
1088   g_variant_builder_add (&extras_variant, "{sv}",
1089                          "origin-pid",
1090                          g_variant_new ("x",
1091                                         (gint64)getpid ()));
1092
1093   if (info->filename)
1094     desktop_file_id = info->filename;
1095   else if (info->desktop_id)
1096     desktop_file_id = info->desktop_id;
1097   else
1098     desktop_file_id = "";
1099   
1100   msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
1101                                    "org.gtk.gio.DesktopAppInfo",
1102                                    "Launched");
1103   g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
1104                                                g_variant_new_bytestring (desktop_file_id),
1105                                                display ? display : "",
1106                                                (gint64)pid,
1107                                                &uri_variant,
1108                                                &extras_variant));
1109   g_dbus_connection_send_message (session_bus,
1110                                   msg, 0,
1111                                   NULL,
1112                                   NULL);
1113   g_object_unref (msg);
1114 }
1115
1116 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
1117
1118 static gboolean
1119 _g_desktop_app_info_launch_uris_internal (GAppInfo                   *appinfo,
1120                                           GList                      *uris,
1121                                           GAppLaunchContext          *launch_context,
1122                                           GSpawnFlags                 spawn_flags,
1123                                           GSpawnChildSetupFunc        user_setup,
1124                                           gpointer                    user_setup_data,
1125                                           GDesktopAppLaunchCallback   pid_callback,
1126                                           gpointer                    pid_callback_data,
1127                                           GError                     **error)
1128 {
1129   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1130   GDBusConnection *session_bus;
1131   gboolean completed = FALSE;
1132   GList *old_uris;
1133   char **argv;
1134   int argc;
1135   ChildSetupData data;
1136
1137   g_return_val_if_fail (appinfo != NULL, FALSE);
1138
1139   argv = NULL;
1140
1141   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
1142
1143   do
1144     {
1145       GPid pid;
1146       GList *launched_uris;
1147       GList *iter;
1148
1149       old_uris = uris;
1150       if (!expand_application_parameters (info, &uris,
1151                                           &argc, &argv, error))
1152         goto out;
1153
1154       /* Get the subset of URIs we're launching with this process */
1155       launched_uris = NULL;
1156       for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
1157         launched_uris = g_list_prepend (launched_uris, iter->data);
1158       launched_uris = g_list_reverse (launched_uris);
1159       
1160       if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
1161         {
1162           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1163                                _("Unable to find terminal required for application"));
1164           goto out;
1165         }
1166
1167       data.user_setup = user_setup;
1168       data.user_setup_data = user_setup_data;
1169       data.display = NULL;
1170       data.sn_id = NULL;
1171       data.desktop_file = info->filename;
1172
1173       if (launch_context)
1174         {
1175           GList *launched_files = create_files_for_uris (launched_uris);
1176
1177           data.display = g_app_launch_context_get_display (launch_context,
1178                                                            appinfo,
1179                                                            launched_files);
1180
1181           if (info->startup_notify)
1182             data.sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
1183                                                                      appinfo,
1184                                                                      launched_files);
1185           g_list_foreach (launched_files, (GFunc)g_object_unref, NULL);
1186           g_list_free (launched_files);
1187         }
1188
1189       if (!g_spawn_async (info->path,
1190                           argv,
1191                           NULL,
1192                           spawn_flags,
1193                           child_setup,
1194                           &data,
1195                           &pid,
1196                           error))
1197         {
1198           if (data.sn_id)
1199             g_app_launch_context_launch_failed (launch_context, data.sn_id);
1200
1201           g_free (data.sn_id);
1202           g_free (data.display);
1203           g_list_free (launched_uris);
1204
1205           goto out;
1206         }
1207
1208       if (pid_callback != NULL)
1209         pid_callback (info, pid, pid_callback_data);
1210
1211       notify_desktop_launch (session_bus,
1212                              info,
1213                              pid,
1214                              data.display,
1215                              data.sn_id,
1216                              launched_uris);
1217
1218       g_free (data.sn_id);
1219       g_free (data.display);
1220       g_list_free (launched_uris);
1221
1222       g_strfreev (argv);
1223       argv = NULL;
1224     }
1225   while (uris != NULL);
1226
1227   /* TODO - need to handle the process exiting immediately
1228    * after launching an app.  See http://bugzilla.gnome.org/606960
1229    */
1230   if (session_bus != NULL)
1231     {
1232       /* This asynchronous flush holds a reference until it completes,
1233        * which ensures that the following unref won't immediately kill
1234        * the connection if we were the initial owner.
1235        */
1236       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
1237       g_object_unref (session_bus);
1238     }
1239
1240   completed = TRUE;
1241
1242  out:
1243   g_strfreev (argv);
1244
1245   return completed;
1246 }
1247
1248 static gboolean
1249 g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
1250                                 GList              *uris,
1251                                 GAppLaunchContext  *launch_context,
1252                                 GError            **error)
1253 {
1254   return _g_desktop_app_info_launch_uris_internal (appinfo, uris,
1255                                                    launch_context,
1256                                                    _SPAWN_FLAGS_DEFAULT,
1257                                                    NULL, NULL, NULL, NULL,
1258                                                    error);
1259 }
1260
1261 static gboolean
1262 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
1263 {
1264   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1265  
1266   return info->exec && 
1267     ((strstr (info->exec, "%u") != NULL) ||
1268      (strstr (info->exec, "%U") != NULL));
1269 }
1270
1271 static gboolean
1272 g_desktop_app_info_supports_files (GAppInfo *appinfo)
1273 {
1274   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1275  
1276   return info->exec && 
1277     ((strstr (info->exec, "%f") != NULL) ||
1278      (strstr (info->exec, "%F") != NULL));
1279 }
1280
1281 static gboolean
1282 g_desktop_app_info_launch (GAppInfo           *appinfo,
1283                            GList              *files,
1284                            GAppLaunchContext  *launch_context,
1285                            GError            **error)
1286 {
1287   GList *uris;
1288   char *uri;
1289   gboolean res;
1290
1291   uris = NULL;
1292   while (files)
1293     {
1294       uri = g_file_get_uri (files->data);
1295       uris = g_list_prepend (uris, uri);
1296       files = files->next;
1297     }
1298   
1299   uris = g_list_reverse (uris);
1300   
1301   res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
1302   
1303   g_list_foreach  (uris, (GFunc)g_free, NULL);
1304   g_list_free (uris);
1305   
1306   return res;
1307 }
1308
1309 /**
1310  * g_desktop_app_info_launch_uris_as_manager:
1311  * @appinfo: a #GDesktopAppInfo
1312  * @uris: (element-type utf8): List of URIs
1313  * @launch_context: a #GAppLaunchContext
1314  * @spawn_flags: #GSpawnFlags, used for each process
1315  * @user_setup: (scope call): a #GSpawnChildSetupFunc, used once for
1316  *     each process.
1317  * @user_setup_data: (closure user_setup): User data for @user_setup
1318  * @pid_callback: (scope call): Callback for child processes
1319  * @pid_callback_data: (closure pid_callback): User data for @callback
1320  * @error: return location for a #GError, or %NULL
1321  *
1322  * This function performs the equivalent of g_app_info_launch_uris(),
1323  * but is intended primarily for operating system components that
1324  * launch applications.  Ordinary applications should use
1325  * g_app_info_launch_uris().
1326  *
1327  * In contrast to g_app_info_launch_uris(), all processes created will
1328  * always be run directly as children as if by the UNIX fork()/exec()
1329  * calls.
1330  *
1331  * This guarantee allows additional control over the exact environment
1332  * of the child processes, which is provided via a setup function
1333  * @setup, as well as the process identifier of each child process via
1334  * @pid_callback.  See g_spawn_async() for more information about the
1335  * semantics of the @setup function.
1336  *
1337  * Returns: %TRUE on successful launch, %FALSE otherwise.
1338  */
1339 gboolean
1340 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo            *appinfo,
1341                                            GList                      *uris,
1342                                            GAppLaunchContext          *launch_context,
1343                                            GSpawnFlags                 spawn_flags,
1344                                            GSpawnChildSetupFunc        user_setup,
1345                                            gpointer                    user_setup_data,
1346                                            GDesktopAppLaunchCallback   pid_callback,
1347                                            gpointer                    pid_callback_data,
1348                                            GError                    **error)
1349 {
1350   return _g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
1351                                                    uris,
1352                                                    launch_context,
1353                                                    spawn_flags,
1354                                                    user_setup,
1355                                                    user_setup_data,
1356                                                    pid_callback,
1357                                                    pid_callback_data,
1358                                                    error);
1359 }
1360
1361 G_LOCK_DEFINE_STATIC (g_desktop_env);
1362 static gchar *g_desktop_env = NULL;
1363
1364 /**
1365  * g_desktop_app_info_set_desktop_env:
1366  * @desktop_env: a string specifying what desktop this is
1367  *
1368  * Sets the name of the desktop that the application is running in.
1369  * This is used by g_app_info_should_show() to evaluate the
1370  * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal>
1371  * desktop entry fields.
1372  *
1373  * The <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Desktop 
1374  * Menu specification</ulink> recognizes the following:
1375  * <simplelist>
1376  *   <member>GNOME</member>
1377  *   <member>KDE</member>
1378  *   <member>ROX</member>
1379  *   <member>XFCE</member>
1380  *   <member>Old</member> 
1381  * </simplelist>
1382  *
1383  * Should be called only once; subsequent calls are ignored.
1384  */
1385 void
1386 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
1387 {
1388   G_LOCK (g_desktop_env);
1389   if (!g_desktop_env)
1390     g_desktop_env = g_strdup (desktop_env);
1391   G_UNLOCK (g_desktop_env);
1392 }
1393
1394 static gboolean
1395 g_desktop_app_info_should_show (GAppInfo *appinfo)
1396 {
1397   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1398   gboolean found;
1399   const gchar *desktop_env;
1400   int i;
1401
1402   if (info->nodisplay)
1403     return FALSE;
1404
1405   G_LOCK (g_desktop_env);
1406   desktop_env = g_desktop_env;
1407   G_UNLOCK (g_desktop_env);
1408
1409   if (info->only_show_in)
1410     {
1411       if (desktop_env == NULL)
1412         return FALSE;
1413       
1414       found = FALSE;
1415       for (i = 0; info->only_show_in[i] != NULL; i++)
1416         {
1417           if (strcmp (info->only_show_in[i], desktop_env) == 0)
1418             {
1419               found = TRUE;
1420               break;
1421             }
1422         }
1423       if (!found)
1424         return FALSE;
1425     }
1426
1427   if (info->not_show_in && desktop_env)
1428     {
1429       for (i = 0; info->not_show_in[i] != NULL; i++)
1430         {
1431           if (strcmp (info->not_show_in[i], desktop_env) == 0)
1432             return FALSE;
1433         }
1434     }
1435   
1436   return TRUE;
1437 }
1438
1439 typedef enum {
1440   APP_DIR,
1441   MIMETYPE_DIR
1442 } DirType;
1443
1444 static char *
1445 ensure_dir (DirType   type,
1446             GError  **error)
1447 {
1448   char *path, *display_name;
1449   int errsv;
1450
1451   if (type == APP_DIR)
1452     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1453   else
1454     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
1455
1456   errno = 0;
1457   if (g_mkdir_with_parents (path, 0700) == 0)
1458     return path;
1459
1460   errsv = errno;
1461   display_name = g_filename_display_name (path);
1462   if (type == APP_DIR)
1463     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1464                  _("Can't create user application configuration folder %s: %s"),
1465                  display_name, g_strerror (errsv));
1466   else
1467     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1468                  _("Can't create user MIME configuration folder %s: %s"),
1469                  display_name, g_strerror (errsv));
1470
1471   g_free (display_name);
1472   g_free (path);
1473
1474   return NULL;
1475 }
1476
1477 static gboolean
1478 update_mimeapps_list (const char  *desktop_id, 
1479                       const char  *content_type,
1480                       UpdateMimeFlags flags,
1481                       GError     **error)
1482 {
1483   char *dirname, *filename, *string;
1484   GKeyFile *key_file;
1485   gboolean load_succeeded, res, explicit_default;
1486   char **old_list, **list;
1487   GList *system_list;
1488   gsize length, data_size;
1489   char *data;
1490   int i, j, k;
1491   char **content_types;
1492
1493   /* Don't add both at start and end */
1494   g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
1495               (flags & UPDATE_MIME_SET_NON_DEFAULT)));
1496
1497   dirname = ensure_dir (APP_DIR, error);
1498   if (!dirname)
1499     return FALSE;
1500
1501   filename = g_build_filename (dirname, "mimeapps.list", NULL);
1502   g_free (dirname);
1503
1504   key_file = g_key_file_new ();
1505   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
1506   if (!load_succeeded || !g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP))
1507     {
1508       g_key_file_free (key_file);
1509       key_file = g_key_file_new ();
1510     }
1511
1512   if (content_type)
1513     {
1514       content_types = g_new (char *, 2);
1515       content_types[0] = g_strdup (content_type);
1516       content_types[1] = NULL;
1517     }
1518   else
1519     {
1520       content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
1521     }
1522
1523   explicit_default = FALSE;
1524
1525   for (k = 0; content_types && content_types[k]; k++)
1526     {
1527       /* set as default, if requested so */
1528       string = g_key_file_get_string (key_file,
1529                                       DEFAULT_APPLICATIONS_GROUP,
1530                                       content_types[k],
1531                                       NULL);
1532
1533       if (g_strcmp0 (string, desktop_id) != 0 &&
1534           (flags & UPDATE_MIME_SET_DEFAULT))
1535         {
1536           g_free (string);
1537           string = g_strdup (desktop_id);
1538
1539           /* add in the non-default list too, if it's not already there */
1540           flags |= UPDATE_MIME_SET_NON_DEFAULT;
1541         }
1542
1543       if (string == NULL || desktop_id == NULL)
1544         g_key_file_remove_key (key_file,
1545                                DEFAULT_APPLICATIONS_GROUP,
1546                                content_types[k],
1547                                NULL);
1548       else
1549         {
1550           g_key_file_set_string (key_file,
1551                                  DEFAULT_APPLICATIONS_GROUP,
1552                                  content_types[k],
1553                                  string);
1554
1555           explicit_default = TRUE;
1556         }
1557
1558       g_free (string);
1559     }
1560
1561   if (content_type)
1562     {
1563       /* reuse the list from above */
1564     }
1565   else
1566     {
1567       g_strfreev (content_types);
1568       content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
1569     }
1570   
1571   for (k = 0; content_types && content_types[k]; k++)
1572     { 
1573       /* Add to the right place in the list */
1574   
1575       length = 0;
1576       old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
1577                                              content_types[k], &length, NULL);
1578
1579       list = g_new (char *, 1 + length + 1);
1580
1581       i = 0;
1582
1583       /* if we're adding a last-used hint, just put the application in front of the list */
1584       if (flags & UPDATE_MIME_SET_LAST_USED)
1585         {
1586           /* avoid adding this again as non-default later */
1587           if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1588             flags ^= UPDATE_MIME_SET_NON_DEFAULT;
1589
1590           list[i++] = g_strdup (desktop_id);
1591         }
1592
1593       if (old_list)
1594         {
1595           for (j = 0; old_list[j] != NULL; j++)
1596             {
1597               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1598                 {
1599                   /* rewrite other entries if they're different from the new one */
1600                   list[i++] = g_strdup (old_list[j]);
1601                 }
1602               else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1603                 {
1604                   /* we encountered an old entry which is equal to the one we're adding as non-default,
1605                    * don't change its position in the list.
1606                    */
1607                   flags ^= UPDATE_MIME_SET_NON_DEFAULT;
1608                   list[i++] = g_strdup (old_list[j]);
1609                 }
1610             }
1611         }
1612
1613       /* add it at the end of the list */
1614       if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1615         list[i++] = g_strdup (desktop_id);
1616
1617       list[i] = NULL;
1618   
1619       g_strfreev (old_list);
1620
1621       if (list[0] == NULL || desktop_id == NULL)
1622         g_key_file_remove_key (key_file,
1623                                ADDED_ASSOCIATIONS_GROUP,
1624                                content_types[k],
1625                                NULL);
1626       else
1627         {
1628           g_key_file_set_string_list (key_file,
1629                                       ADDED_ASSOCIATIONS_GROUP,
1630                                       content_types[k],
1631                                       (const char * const *)list, i);
1632
1633           /* if we had no explicit default set, we should add the system default to the
1634            * list, to avoid overriding it with applications from this list.
1635            */
1636           if (!explicit_default)
1637             {
1638               system_list = get_all_desktop_entries_for_mime_type (content_type, (const char **) list, FALSE, NULL);
1639
1640               if (system_list != NULL)
1641                 {
1642                   string = system_list->data;
1643
1644                   g_key_file_set_string (key_file,
1645                                          DEFAULT_APPLICATIONS_GROUP,
1646                                          content_types[k],
1647                                          string);
1648                 }
1649
1650               g_list_free_full (system_list, g_free);
1651             }
1652         }
1653    
1654       g_strfreev (list);
1655     }
1656   
1657   if (content_type)
1658     {
1659       /* reuse the list from above */
1660     }
1661   else
1662     {
1663       g_strfreev (content_types);
1664       content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
1665     }
1666
1667   for (k = 0; content_types && content_types[k]; k++) 
1668     {
1669       /* Remove from removed associations group (unless remove) */
1670   
1671       length = 0;
1672       old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
1673                                              content_types[k], &length, NULL);
1674
1675       list = g_new (char *, 1 + length + 1);
1676
1677       i = 0;
1678       if (flags & UPDATE_MIME_REMOVE)
1679         list[i++] = g_strdup (desktop_id);
1680       if (old_list)
1681         {
1682           for (j = 0; old_list[j] != NULL; j++)
1683             {
1684               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1685                 list[i++] = g_strdup (old_list[j]);
1686             }
1687         }
1688       list[i] = NULL;
1689   
1690       g_strfreev (old_list);
1691
1692       if (list[0] == NULL || desktop_id == NULL)
1693         g_key_file_remove_key (key_file,
1694                                REMOVED_ASSOCIATIONS_GROUP,
1695                                content_types[k],
1696                                NULL);
1697       else
1698         g_key_file_set_string_list (key_file,
1699                                     REMOVED_ASSOCIATIONS_GROUP,
1700                                     content_types[k],
1701                                     (const char * const *)list, i);
1702
1703       g_strfreev (list);
1704     }
1705
1706   g_strfreev (content_types);  
1707
1708   data = g_key_file_to_data (key_file, &data_size, error);
1709   g_key_file_free (key_file);
1710   
1711   res = g_file_set_contents (filename, data, data_size, error);
1712
1713   mime_info_cache_reload (NULL);
1714                           
1715   g_free (filename);
1716   g_free (data);
1717   
1718   return res;
1719 }
1720
1721 static gboolean
1722 g_desktop_app_info_set_as_last_used_for_type (GAppInfo    *appinfo,
1723                                               const char  *content_type,
1724                                               GError     **error)
1725 {
1726   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1727
1728   if (!g_desktop_app_info_ensure_saved (info, error))
1729     return FALSE;
1730
1731   /* both add support for the content type and set as last used */
1732   return update_mimeapps_list (info->desktop_id, content_type,
1733                                UPDATE_MIME_SET_NON_DEFAULT |
1734                                UPDATE_MIME_SET_LAST_USED,
1735                                error);
1736 }
1737
1738 static gboolean
1739 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
1740                                             const char  *content_type,
1741                                             GError     **error)
1742 {
1743   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1744
1745   if (!g_desktop_app_info_ensure_saved (info, error))
1746     return FALSE;  
1747   
1748   return update_mimeapps_list (info->desktop_id, content_type,
1749                                UPDATE_MIME_SET_DEFAULT,
1750                                error);
1751 }
1752
1753 static void
1754 update_program_done (GPid     pid,
1755                      gint     status,
1756                      gpointer data)
1757 {
1758   /* Did the application exit correctly */
1759   if (WIFEXITED (status) &&
1760       WEXITSTATUS (status) == 0)
1761     {
1762       /* Here we could clean out any caches in use */
1763     }
1764 }
1765
1766 static void
1767 run_update_command (char *command,
1768                     char *subdir)
1769 {
1770         char *argv[3] = {
1771                 NULL,
1772                 NULL,
1773                 NULL,
1774         };
1775         GPid pid = 0;
1776         GError *error = NULL;
1777
1778         argv[0] = command;
1779         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
1780
1781         if (g_spawn_async ("/", argv,
1782                            NULL,       /* envp */
1783                            G_SPAWN_SEARCH_PATH |
1784                            G_SPAWN_STDOUT_TO_DEV_NULL |
1785                            G_SPAWN_STDERR_TO_DEV_NULL |
1786                            G_SPAWN_DO_NOT_REAP_CHILD,
1787                            NULL, NULL, /* No setup function */
1788                            &pid,
1789                            &error)) 
1790           g_child_watch_add (pid, update_program_done, NULL);
1791         else
1792           {
1793             /* If we get an error at this point, it's quite likely the user doesn't
1794              * have an installed copy of either 'update-mime-database' or
1795              * 'update-desktop-database'.  I don't think we want to popup an error
1796              * dialog at this point, so we just do a g_warning to give the user a
1797              * chance of debugging it.
1798              */
1799             g_warning ("%s", error->message);
1800           }
1801         
1802         g_free (argv[1]);
1803 }
1804
1805 static gboolean
1806 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
1807                                                  const char  *extension,
1808                                                  GError     **error)
1809 {
1810   char *filename, *basename, *mimetype;
1811   char *dirname;
1812   gboolean res;
1813
1814   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
1815     return FALSE;  
1816   
1817   dirname = ensure_dir (MIMETYPE_DIR, error);
1818   if (!dirname)
1819     return FALSE;
1820   
1821   basename = g_strdup_printf ("user-extension-%s.xml", extension);
1822   filename = g_build_filename (dirname, basename, NULL);
1823   g_free (basename);
1824   g_free (dirname);
1825
1826   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
1827   
1828   if (!g_file_test (filename, G_FILE_TEST_EXISTS)) 
1829     {
1830       char *contents;
1831
1832       contents =
1833         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1834                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
1835                          " <mime-type type=\"%s\">\n"
1836                          "  <comment>%s document</comment>\n"
1837                          "  <glob pattern=\"*.%s\"/>\n"
1838                          " </mime-type>\n"
1839                          "</mime-info>\n", mimetype, extension, extension);
1840
1841       g_file_set_contents (filename, contents, -1, NULL);
1842       g_free (contents);
1843
1844       run_update_command ("update-mime-database", "mime");
1845     }
1846   g_free (filename);
1847   
1848   res = g_desktop_app_info_set_as_default_for_type (appinfo,
1849                                                     mimetype,
1850                                                     error);
1851
1852   g_free (mimetype);
1853   
1854   return res;
1855 }
1856
1857 static gboolean
1858 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
1859                                       const char  *content_type,
1860                                       GError     **error)
1861 {
1862   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1863
1864   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1865     return FALSE;  
1866   
1867   return update_mimeapps_list (info->desktop_id, content_type,
1868                                UPDATE_MIME_SET_NON_DEFAULT,
1869                                error);
1870 }
1871
1872 static gboolean
1873 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
1874 {
1875   return TRUE;
1876 }
1877
1878 static gboolean
1879 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
1880                                          const char  *content_type,
1881                                          GError     **error)
1882 {
1883   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1884
1885   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1886     return FALSE;
1887   
1888   return update_mimeapps_list (info->desktop_id, content_type,
1889                                UPDATE_MIME_REMOVE,
1890                                error);
1891 }
1892
1893 static gboolean
1894 g_desktop_app_info_ensure_saved (GDesktopAppInfo  *info,
1895                                  GError          **error)
1896 {
1897   GKeyFile *key_file;
1898   char *dirname;
1899   char *filename;
1900   char *data, *desktop_id;
1901   gsize data_size;
1902   int fd;
1903   gboolean res;
1904   
1905   if (info->filename != NULL)
1906     return TRUE;
1907
1908   /* This is only used for object created with
1909    * g_app_info_create_from_commandline. All other
1910    * object should have a filename
1911    */
1912   
1913   dirname = ensure_dir (APP_DIR, error);
1914   if (!dirname)
1915     return FALSE;
1916   
1917   key_file = g_key_file_new ();
1918
1919   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1920                          "Encoding", "UTF-8");
1921   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1922                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
1923   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1924                          G_KEY_FILE_DESKTOP_KEY_TYPE,
1925                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
1926   if (info->terminal) 
1927     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1928                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
1929
1930   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1931                          G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
1932
1933   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1934                          G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
1935
1936   if (info->generic_name != NULL)
1937     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1938                            GENERIC_NAME_KEY, info->generic_name);
1939
1940   if (info->fullname != NULL)
1941     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1942                            FULL_NAME_KEY, info->fullname);
1943
1944   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1945                          G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
1946   
1947   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1948                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
1949
1950   data = g_key_file_to_data (key_file, &data_size, NULL);
1951   g_key_file_free (key_file);
1952
1953   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
1954   filename = g_build_filename (dirname, desktop_id, NULL);
1955   g_free (desktop_id);
1956   g_free (dirname);
1957   
1958   fd = g_mkstemp (filename);
1959   if (fd == -1)
1960     {
1961       char *display_name;
1962
1963       display_name = g_filename_display_name (filename);
1964       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1965                    _("Can't create user desktop file %s"), display_name);
1966       g_free (display_name);
1967       g_free (filename);
1968       g_free (data);
1969       return FALSE;
1970     }
1971
1972   desktop_id = g_path_get_basename (filename);
1973
1974   close (fd);
1975   
1976   res = g_file_set_contents (filename, data, data_size, error);
1977   if (!res)
1978     {
1979       g_free (desktop_id);
1980       g_free (filename);
1981       return FALSE;
1982     }
1983
1984   info->filename = filename;
1985   info->desktop_id = desktop_id;
1986   
1987   run_update_command ("update-desktop-database", "applications");
1988   
1989   return TRUE;
1990 }
1991
1992 static gboolean
1993 g_desktop_app_info_can_delete (GAppInfo *appinfo)
1994 {
1995   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1996
1997   if (info->filename)
1998     {
1999       if (strstr (info->filename, "/userapp-"))
2000         return g_access (info->filename, W_OK) == 0;
2001     }
2002
2003   return FALSE;
2004 }
2005
2006 static gboolean
2007 g_desktop_app_info_delete (GAppInfo *appinfo)
2008 {
2009   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2010   
2011   if (info->filename)
2012     { 
2013       if (g_remove (info->filename) == 0)
2014         {
2015           update_mimeapps_list (info->desktop_id, NULL,
2016                                 UPDATE_MIME_NONE,
2017                                 NULL);
2018
2019           g_free (info->filename);
2020           info->filename = NULL;
2021           g_free (info->desktop_id);
2022           info->desktop_id = NULL;
2023
2024           return TRUE;
2025         }
2026     }
2027
2028   return FALSE;
2029 }
2030
2031 /**
2032  * g_app_info_create_from_commandline:
2033  * @commandline: the commandline to use
2034  * @application_name: (allow-none): the application name, or %NULL to use @commandline
2035  * @flags: flags that can specify details of the created #GAppInfo
2036  * @error: a #GError location to store the error occuring, %NULL to ignore.
2037  *
2038  * Creates a new #GAppInfo from the given information.
2039  *
2040  * Returns: (transfer full): new #GAppInfo for given command.
2041  **/
2042 GAppInfo *
2043 g_app_info_create_from_commandline (const char           *commandline,
2044                                     const char           *application_name,
2045                                     GAppInfoCreateFlags   flags,
2046                                     GError              **error)
2047 {
2048   char **split;
2049   char *basename;
2050   GDesktopAppInfo *info;
2051
2052   g_return_val_if_fail (commandline, NULL);
2053
2054   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2055
2056   info->filename = NULL;
2057   info->desktop_id = NULL;
2058   
2059   info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
2060   info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
2061   info->hidden = FALSE;
2062   if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
2063     info->exec = g_strconcat (commandline, " %u", NULL);
2064   else
2065     info->exec = g_strconcat (commandline, " %f", NULL);
2066   info->nodisplay = TRUE;
2067   info->binary = binary_from_exec (info->exec);
2068   
2069   if (application_name)
2070     info->name = g_strdup (application_name);
2071   else
2072     {
2073       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
2074       split = g_strsplit (commandline, " ", 2);
2075       basename = split[0] ? g_path_get_basename (split[0]) : NULL;
2076       g_strfreev (split);
2077       info->name = basename;
2078       if (info->name == NULL)
2079         info->name = g_strdup ("custom");
2080     }
2081   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
2082   
2083   return G_APP_INFO (info);
2084 }
2085
2086 static void
2087 g_desktop_app_info_iface_init (GAppInfoIface *iface)
2088 {
2089   iface->dup = g_desktop_app_info_dup;
2090   iface->equal = g_desktop_app_info_equal;
2091   iface->get_id = g_desktop_app_info_get_id;
2092   iface->get_name = g_desktop_app_info_get_name;
2093   iface->get_description = g_desktop_app_info_get_description;
2094   iface->get_executable = g_desktop_app_info_get_executable;
2095   iface->get_icon = g_desktop_app_info_get_icon;
2096   iface->launch = g_desktop_app_info_launch;
2097   iface->supports_uris = g_desktop_app_info_supports_uris;
2098   iface->supports_files = g_desktop_app_info_supports_files;
2099   iface->launch_uris = g_desktop_app_info_launch_uris;
2100   iface->should_show = g_desktop_app_info_should_show;
2101   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
2102   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
2103   iface->add_supports_type = g_desktop_app_info_add_supports_type;
2104   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
2105   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
2106   iface->can_delete = g_desktop_app_info_can_delete;
2107   iface->do_delete = g_desktop_app_info_delete;
2108   iface->get_commandline = g_desktop_app_info_get_commandline;
2109   iface->get_display_name = g_desktop_app_info_get_display_name;
2110   iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
2111 }
2112
2113 static gboolean
2114 app_info_in_list (GAppInfo *info, 
2115                   GList    *list)
2116 {
2117   while (list != NULL)
2118     {
2119       if (g_app_info_equal (info, list->data))
2120         return TRUE;
2121       list = list->next;
2122     }
2123   return FALSE;
2124 }
2125
2126 /**
2127  * g_app_info_get_recommended_for_type:
2128  * @content_type: the content type to find a #GAppInfo for
2129  * 
2130  * Gets a list of recommended #GAppInfos for a given content type, i.e.
2131  * those applications which claim to support the given content type exactly,
2132  * and not by MIME type subclassing.
2133  * Note that the first application of the list is the last used one, i.e.
2134  * the last one for which #g_app_info_set_as_last_used_for_type has been
2135  * called.
2136  *
2137  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2138  *     for given @content_type or %NULL on error.
2139  *
2140  * Since: 2.28
2141  **/
2142 GList *
2143 g_app_info_get_recommended_for_type (const gchar *content_type)
2144 {
2145   GList *desktop_entries, *l;
2146   GList *infos;
2147   GDesktopAppInfo *info;
2148
2149   g_return_val_if_fail (content_type != NULL, NULL);
2150
2151   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, FALSE, NULL);
2152
2153   infos = NULL;
2154   for (l = desktop_entries; l != NULL; l = l->next)
2155     {
2156       char *desktop_entry = l->data;
2157
2158       info = g_desktop_app_info_new (desktop_entry);
2159       if (info)
2160         {
2161           if (app_info_in_list (G_APP_INFO (info), infos))
2162             g_object_unref (info);
2163           else
2164             infos = g_list_prepend (infos, info);
2165         }
2166       g_free (desktop_entry);
2167     }
2168
2169   g_list_free (desktop_entries);
2170
2171   return g_list_reverse (infos);
2172 }
2173
2174 /**
2175  * g_app_info_get_fallback_for_type:
2176  * @content_type: the content type to find a #GAppInfo for
2177  * 
2178  * Gets a list of fallback #GAppInfos for a given content type, i.e.
2179  * those applications which claim to support the given content type
2180  * by MIME type subclassing and not directly.
2181  *
2182  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2183  *     for given @content_type or %NULL on error.
2184  *
2185  * Since: 2.28
2186  **/
2187 GList *
2188 g_app_info_get_fallback_for_type (const gchar *content_type)
2189 {
2190   GList *desktop_entries, *l;
2191   GList *infos, *recommended_infos;
2192   GDesktopAppInfo *info;
2193
2194   g_return_val_if_fail (content_type != NULL, NULL);
2195
2196   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, NULL);
2197   recommended_infos = g_app_info_get_recommended_for_type (content_type);
2198
2199   infos = NULL;
2200   for (l = desktop_entries; l != NULL; l = l->next)
2201     {
2202       char *desktop_entry = l->data;
2203
2204       info = g_desktop_app_info_new (desktop_entry);
2205       if (info)
2206         {
2207           if (app_info_in_list (G_APP_INFO (info), infos) ||
2208               app_info_in_list (G_APP_INFO (info), recommended_infos))
2209             g_object_unref (info);
2210           else
2211             infos = g_list_prepend (infos, info);
2212         }
2213       g_free (desktop_entry);
2214     }
2215
2216   g_list_free (desktop_entries);
2217   g_list_free_full (recommended_infos, g_object_unref);
2218
2219   return g_list_reverse (infos);
2220 }
2221
2222 /**
2223  * g_app_info_get_all_for_type:
2224  * @content_type: the content type to find a #GAppInfo for
2225  * 
2226  * Gets a list of all #GAppInfos for a given content type.
2227  *
2228  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2229  *     for given @content_type or %NULL on error.
2230  **/
2231 GList *
2232 g_app_info_get_all_for_type (const char *content_type)
2233 {
2234   GList *desktop_entries, *l;
2235   GList *infos;
2236   char *user_default = NULL;
2237   GDesktopAppInfo *info;
2238
2239   g_return_val_if_fail (content_type != NULL, NULL);
2240   
2241   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
2242   infos = NULL;
2243
2244   /* put the user default in front of the list, for compatibility */
2245   if (user_default != NULL)
2246     {
2247       info = g_desktop_app_info_new (user_default);
2248
2249       if (info != NULL)
2250         infos = g_list_prepend (infos, info);
2251     }
2252
2253   g_free (user_default);
2254
2255   for (l = desktop_entries; l != NULL; l = l->next)
2256     {
2257       char *desktop_entry = l->data;
2258
2259       info = g_desktop_app_info_new (desktop_entry);
2260       if (info)
2261         {
2262           if (app_info_in_list (G_APP_INFO (info), infos))
2263             g_object_unref (info);
2264           else
2265             infos = g_list_prepend (infos, info);
2266         }
2267       g_free (desktop_entry);
2268     }
2269
2270   g_list_free (desktop_entries);
2271   
2272   return g_list_reverse (infos);
2273 }
2274
2275 /**
2276  * g_app_info_reset_type_associations:
2277  * @content_type: a content type 
2278  *
2279  * Removes all changes to the type associations done by
2280  * g_app_info_set_as_default_for_type(), 
2281  * g_app_info_set_as_default_for_extension(), 
2282  * g_app_info_add_supports_type() or g_app_info_remove_supports_type().
2283  *
2284  * Since: 2.20
2285  */
2286 void
2287 g_app_info_reset_type_associations (const char *content_type)
2288 {
2289   update_mimeapps_list (NULL, content_type,
2290                         UPDATE_MIME_NONE,
2291                         NULL);
2292 }
2293
2294 /**
2295  * g_app_info_get_default_for_type:
2296  * @content_type: the content type to find a #GAppInfo for
2297  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
2298  *     support URIs
2299  * 
2300  * Gets the #GAppInfo that corresponds to a given content type.
2301  *
2302  * Returns: (transfer full): #GAppInfo for given @content_type or
2303  *     %NULL on error.
2304  **/
2305 GAppInfo *
2306 g_app_info_get_default_for_type (const char *content_type,
2307                                  gboolean    must_support_uris)
2308 {
2309   GList *desktop_entries, *l;
2310   char *user_default = NULL;
2311   GAppInfo *info;
2312
2313   g_return_val_if_fail (content_type != NULL, NULL);
2314   
2315   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
2316
2317   info = NULL;
2318
2319   if (user_default != NULL)
2320     {
2321       info = (GAppInfo *) g_desktop_app_info_new (user_default);
2322
2323       if (info)
2324         {
2325           if (must_support_uris && !g_app_info_supports_uris (info))
2326             {
2327               g_object_unref (info);
2328               info = NULL;
2329             }
2330         }
2331     }
2332
2333   g_free (user_default);
2334
2335   if (info != NULL)
2336     {
2337       g_list_free_full (desktop_entries, g_free);
2338       return info;
2339     }
2340
2341   /* pick the first from the other list that matches our URI
2342    * requirements.
2343    */
2344   for (l = desktop_entries; l != NULL; l = l->next)
2345     {
2346       char *desktop_entry = l->data;
2347
2348       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
2349       if (info)
2350         {
2351           if (must_support_uris && !g_app_info_supports_uris (info))
2352             {
2353               g_object_unref (info);
2354               info = NULL;
2355             }
2356           else
2357             break;
2358         }
2359     }
2360   
2361   g_list_free_full (desktop_entries, g_free);
2362
2363   return info;
2364 }
2365
2366 /**
2367  * g_app_info_get_default_for_uri_scheme:
2368  * @uri_scheme: a string containing a URI scheme.
2369  *
2370  * Gets the default application for launching applications 
2371  * using this URI scheme. A URI scheme is the initial part 
2372  * of the URI, up to but not including the ':', e.g. "http", 
2373  * "ftp" or "sip".
2374  * 
2375  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
2376  **/
2377 GAppInfo *
2378 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
2379 {
2380   GAppInfo *app_info;
2381   char *content_type, *scheme_down;
2382
2383   scheme_down = g_ascii_strdown (uri_scheme, -1);
2384   content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
2385   g_free (scheme_down);
2386   app_info = g_app_info_get_default_for_type (content_type, FALSE);
2387   g_free (content_type);
2388
2389   return app_info;
2390 }
2391
2392 static void
2393 get_apps_from_dir (GHashTable *apps, 
2394                    const char *dirname, 
2395                    const char *prefix)
2396 {
2397   GDir *dir;
2398   const char *basename;
2399   char *filename, *subprefix, *desktop_id;
2400   gboolean hidden;
2401   GDesktopAppInfo *appinfo;
2402   
2403   dir = g_dir_open (dirname, 0, NULL);
2404   if (dir)
2405     {
2406       while ((basename = g_dir_read_name (dir)) != NULL)
2407         {
2408           filename = g_build_filename (dirname, basename, NULL);
2409           if (g_str_has_suffix (basename, ".desktop"))
2410             {
2411               desktop_id = g_strconcat (prefix, basename, NULL);
2412
2413               /* Use _extended so we catch NULLs too (hidden) */
2414               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
2415                 {
2416                   appinfo = g_desktop_app_info_new_from_filename (filename);
2417                   hidden = FALSE;
2418
2419                   if (appinfo && g_desktop_app_info_get_is_hidden (appinfo))
2420                     {
2421                       g_object_unref (appinfo);
2422                       appinfo = NULL;
2423                       hidden = TRUE;
2424                     }
2425                                       
2426                   if (appinfo || hidden)
2427                     {
2428                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
2429
2430                       if (appinfo)
2431                         {
2432                           /* Reuse instead of strdup here */
2433                           appinfo->desktop_id = desktop_id;
2434                           desktop_id = NULL;
2435                         }
2436                     }
2437                 }
2438               g_free (desktop_id);
2439             }
2440           else
2441             {
2442               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
2443                 {
2444                   subprefix = g_strconcat (prefix, basename, "-", NULL);
2445                   get_apps_from_dir (apps, filename, subprefix);
2446                   g_free (subprefix);
2447                 }
2448             }
2449           g_free (filename);
2450         }
2451       g_dir_close (dir);
2452     }
2453 }
2454
2455
2456 /**
2457  * g_app_info_get_all:
2458  *
2459  * Gets a list of all of the applications currently registered 
2460  * on this system.
2461  * 
2462  * For desktop files, this includes applications that have 
2463  * <literal>NoDisplay=true</literal> set or are excluded from 
2464  * display by means of <literal>OnlyShowIn</literal> or
2465  * <literal>NotShowIn</literal>. See g_app_info_should_show().
2466  * The returned list does not include applications which have
2467  * the <literal>Hidden</literal> key set. 
2468  * 
2469  * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfo<!---->s.
2470  **/
2471 GList *
2472 g_app_info_get_all (void)
2473 {
2474   const char * const *dirs;
2475   GHashTable *apps;
2476   GHashTableIter iter;
2477   gpointer value;
2478   int i;
2479   GList *infos;
2480
2481   dirs = get_applications_search_path ();
2482
2483   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
2484                                 g_free, NULL);
2485
2486   
2487   for (i = 0; dirs[i] != NULL; i++)
2488     get_apps_from_dir (apps, dirs[i], "");
2489
2490
2491   infos = NULL;
2492   g_hash_table_iter_init (&iter, apps);
2493   while (g_hash_table_iter_next (&iter, NULL, &value))
2494     {
2495       if (value)
2496         infos = g_list_prepend (infos, value);
2497     }
2498
2499   g_hash_table_destroy (apps);
2500
2501   return g_list_reverse (infos);
2502 }
2503
2504 /* Cacheing of mimeinfo.cache and defaults.list files */
2505
2506 typedef struct {
2507   char *path;
2508   GHashTable *mime_info_cache_map;
2509   GHashTable *defaults_list_map;
2510   GHashTable *mimeapps_list_added_map;
2511   GHashTable *mimeapps_list_removed_map;
2512   GHashTable *mimeapps_list_defaults_map;
2513   time_t mime_info_cache_timestamp;
2514   time_t defaults_list_timestamp;
2515   time_t mimeapps_list_timestamp;
2516 } MimeInfoCacheDir;
2517
2518 typedef struct {
2519   GList *dirs;                       /* mimeinfo.cache and defaults.list */
2520   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
2521   time_t last_stat_time;
2522   guint should_ping_mime_monitor : 1;
2523 } MimeInfoCache;
2524
2525 static MimeInfoCache *mime_info_cache = NULL;
2526 G_LOCK_DEFINE_STATIC (mime_info_cache);
2527
2528 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2529                                                      const char        *mime_type,
2530                                                      char             **new_desktop_file_ids);
2531
2532 static MimeInfoCache * mime_info_cache_new (void);
2533
2534 static void
2535 destroy_info_cache_value (gpointer  key, 
2536                           GList    *value, 
2537                           gpointer  data)
2538 {
2539   g_list_foreach (value, (GFunc)g_free, NULL);
2540   g_list_free (value);
2541 }
2542
2543 static void
2544 destroy_info_cache_map (GHashTable *info_cache_map)
2545 {
2546   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
2547   g_hash_table_destroy (info_cache_map);
2548 }
2549
2550 static gboolean
2551 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
2552                                  const char       *cache_file,
2553                                  time_t           *timestamp)
2554 {
2555   struct stat buf;
2556   char *filename;
2557   
2558   filename = g_build_filename (dir->path, cache_file, NULL);
2559   
2560   if (g_stat (filename, &buf) < 0)
2561     {
2562       g_free (filename);
2563       return TRUE;
2564     }
2565   g_free (filename);
2566
2567   if (buf.st_mtime != *timestamp) 
2568     return TRUE;
2569   
2570   return FALSE;
2571 }
2572
2573 /* Call with lock held */
2574 static gboolean
2575 remove_all (gpointer  key,
2576             gpointer  value,
2577             gpointer  user_data)
2578 {
2579   return TRUE;
2580 }
2581
2582
2583 static void
2584 mime_info_cache_blow_global_cache (void)
2585 {
2586   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
2587                                remove_all, NULL);
2588 }
2589
2590 static void
2591 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
2592 {
2593   GError *load_error;
2594   GKeyFile *key_file;
2595   gchar *filename, **mime_types;
2596   int i;
2597   struct stat buf;
2598   
2599   load_error = NULL;
2600   mime_types = NULL;
2601   
2602   if (dir->mime_info_cache_map != NULL &&
2603       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
2604                                         &dir->mime_info_cache_timestamp))
2605     return;
2606   
2607   if (dir->mime_info_cache_map != NULL)
2608     destroy_info_cache_map (dir->mime_info_cache_map);
2609   
2610   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2611                                                     (GDestroyNotify) g_free,
2612                                                     NULL);
2613   
2614   key_file = g_key_file_new ();
2615   
2616   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
2617   
2618   if (g_stat (filename, &buf) < 0)
2619     goto error;
2620   
2621   if (dir->mime_info_cache_timestamp > 0) 
2622     mime_info_cache->should_ping_mime_monitor = TRUE;
2623   
2624   dir->mime_info_cache_timestamp = buf.st_mtime;
2625   
2626   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2627   
2628   g_free (filename);
2629   filename = NULL;
2630   
2631   if (load_error != NULL)
2632     goto error;
2633   
2634   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
2635                                     NULL, &load_error);
2636   
2637   if (load_error != NULL)
2638     goto error;
2639   
2640   for (i = 0; mime_types[i] != NULL; i++)
2641     {
2642       gchar **desktop_file_ids;
2643       char *unaliased_type;
2644       desktop_file_ids = g_key_file_get_string_list (key_file,
2645                                                      MIME_CACHE_GROUP,
2646                                                      mime_types[i],
2647                                                      NULL,
2648                                                      NULL);
2649       
2650       if (desktop_file_ids == NULL)
2651         continue;
2652
2653       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2654       mime_info_cache_dir_add_desktop_entries (dir,
2655                                                unaliased_type,
2656                                                desktop_file_ids);
2657       g_free (unaliased_type);
2658     
2659       g_strfreev (desktop_file_ids);
2660     }
2661   
2662   g_strfreev (mime_types);
2663   g_key_file_free (key_file);
2664   
2665   return;
2666  error:
2667   g_free (filename);
2668   g_key_file_free (key_file);
2669   
2670   if (mime_types != NULL)
2671     g_strfreev (mime_types);
2672   
2673   if (load_error)
2674     g_error_free (load_error);
2675 }
2676
2677 static void
2678 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
2679 {
2680   GKeyFile *key_file;
2681   GError *load_error;
2682   gchar *filename, **mime_types;
2683   char *unaliased_type;
2684   char **desktop_file_ids;
2685   int i;
2686   struct stat buf;
2687
2688   load_error = NULL;
2689   mime_types = NULL;
2690
2691   if (dir->defaults_list_map != NULL &&
2692       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
2693                                         &dir->defaults_list_timestamp))
2694     return;
2695   
2696   if (dir->defaults_list_map != NULL)
2697     g_hash_table_destroy (dir->defaults_list_map);
2698   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2699                                                   g_free, (GDestroyNotify)g_strfreev);
2700   
2701
2702   key_file = g_key_file_new ();
2703   
2704   filename = g_build_filename (dir->path, "defaults.list", NULL);
2705   if (g_stat (filename, &buf) < 0)
2706     goto error;
2707
2708   if (dir->defaults_list_timestamp > 0) 
2709     mime_info_cache->should_ping_mime_monitor = TRUE;
2710
2711   dir->defaults_list_timestamp = buf.st_mtime;
2712
2713   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2714   g_free (filename);
2715   filename = NULL;
2716
2717   if (load_error != NULL)
2718     goto error;
2719
2720   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2721                                     NULL, NULL);
2722   if (mime_types != NULL)
2723     {
2724       for (i = 0; mime_types[i] != NULL; i++)
2725         {
2726           desktop_file_ids = g_key_file_get_string_list (key_file,
2727                                                          DEFAULT_APPLICATIONS_GROUP,
2728                                                          mime_types[i],
2729                                                          NULL,
2730                                                          NULL);
2731           if (desktop_file_ids == NULL)
2732             continue;
2733           
2734           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2735           g_hash_table_replace (dir->defaults_list_map,
2736                                 unaliased_type,
2737                                 desktop_file_ids);
2738         }
2739       
2740       g_strfreev (mime_types);
2741     }
2742
2743   g_key_file_free (key_file);
2744   return;
2745   
2746  error:
2747   g_free (filename);
2748   g_key_file_free (key_file);
2749   
2750   if (mime_types != NULL)
2751     g_strfreev (mime_types);
2752   
2753   if (load_error)
2754     g_error_free (load_error);
2755 }
2756
2757 static void
2758 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
2759 {
2760   GKeyFile *key_file;
2761   GError *load_error;
2762   gchar *filename, **mime_types;
2763   char *unaliased_type;
2764   char **desktop_file_ids;
2765   char *desktop_id;
2766   int i;
2767   struct stat buf;
2768
2769   load_error = NULL;
2770   mime_types = NULL;
2771
2772   if (dir->mimeapps_list_added_map != NULL &&
2773       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
2774                                         &dir->mimeapps_list_timestamp))
2775     return;
2776   
2777   if (dir->mimeapps_list_added_map != NULL)
2778     g_hash_table_destroy (dir->mimeapps_list_added_map);
2779   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2780                                                         g_free, (GDestroyNotify)g_strfreev);
2781   
2782   if (dir->mimeapps_list_removed_map != NULL)
2783     g_hash_table_destroy (dir->mimeapps_list_removed_map);
2784   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2785                                                           g_free, (GDestroyNotify)g_strfreev);
2786
2787   if (dir->mimeapps_list_defaults_map != NULL)
2788     g_hash_table_destroy (dir->mimeapps_list_defaults_map);
2789   dir->mimeapps_list_defaults_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2790                                                            g_free, g_free);
2791
2792   key_file = g_key_file_new ();
2793   
2794   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
2795   if (g_stat (filename, &buf) < 0)
2796     goto error;
2797
2798   if (dir->mimeapps_list_timestamp > 0) 
2799     mime_info_cache->should_ping_mime_monitor = TRUE;
2800
2801   dir->mimeapps_list_timestamp = buf.st_mtime;
2802
2803   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2804   g_free (filename);
2805   filename = NULL;
2806
2807   if (load_error != NULL)
2808     goto error;
2809
2810   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
2811                                     NULL, NULL);
2812   if (mime_types != NULL)
2813     {
2814       for (i = 0; mime_types[i] != NULL; i++)
2815         {
2816           desktop_file_ids = g_key_file_get_string_list (key_file,
2817                                                          ADDED_ASSOCIATIONS_GROUP,
2818                                                          mime_types[i],
2819                                                          NULL,
2820                                                          NULL);
2821           if (desktop_file_ids == NULL)
2822             continue;
2823           
2824           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2825           g_hash_table_replace (dir->mimeapps_list_added_map,
2826                                 unaliased_type,
2827                                 desktop_file_ids);
2828         }
2829       
2830       g_strfreev (mime_types);
2831     }
2832
2833   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
2834                                     NULL, NULL);
2835   if (mime_types != NULL)
2836     {
2837       for (i = 0; mime_types[i] != NULL; i++)
2838         {
2839           desktop_file_ids = g_key_file_get_string_list (key_file,
2840                                                          REMOVED_ASSOCIATIONS_GROUP,
2841                                                          mime_types[i],
2842                                                          NULL,
2843                                                          NULL);
2844           if (desktop_file_ids == NULL)
2845             continue;
2846           
2847           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2848           g_hash_table_replace (dir->mimeapps_list_removed_map,
2849                                 unaliased_type,
2850                                 desktop_file_ids);
2851         }
2852       
2853       g_strfreev (mime_types);
2854     }
2855
2856   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2857                                     NULL, NULL);
2858   if (mime_types != NULL)
2859     {
2860       for (i = 0; mime_types[i] != NULL; i++)
2861         {
2862           desktop_id = g_key_file_get_string (key_file,
2863                                               DEFAULT_APPLICATIONS_GROUP,
2864                                               mime_types[i],
2865                                               NULL);
2866           if (desktop_id == NULL)
2867             continue;
2868
2869           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2870           g_hash_table_replace (dir->mimeapps_list_defaults_map,
2871                                 unaliased_type,
2872                                 desktop_id);
2873         }
2874
2875       g_strfreev (mime_types);
2876     }
2877
2878   g_key_file_free (key_file);
2879   return;
2880   
2881  error:
2882   g_free (filename);
2883   g_key_file_free (key_file);
2884   
2885   if (mime_types != NULL)
2886     g_strfreev (mime_types);
2887   
2888   if (load_error)
2889     g_error_free (load_error);
2890 }
2891
2892 static MimeInfoCacheDir *
2893 mime_info_cache_dir_new (const char *path)
2894 {
2895   MimeInfoCacheDir *dir;
2896
2897   dir = g_new0 (MimeInfoCacheDir, 1);
2898   dir->path = g_strdup (path);
2899   
2900   return dir;
2901 }
2902
2903 static void
2904 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
2905 {
2906   if (dir == NULL)
2907     return;
2908   
2909   if (dir->mime_info_cache_map != NULL)
2910     {
2911       destroy_info_cache_map (dir->mime_info_cache_map);
2912       dir->mime_info_cache_map = NULL;
2913       
2914   }
2915   
2916   if (dir->defaults_list_map != NULL)
2917     {
2918       g_hash_table_destroy (dir->defaults_list_map);
2919       dir->defaults_list_map = NULL;
2920     }
2921   
2922   if (dir->mimeapps_list_added_map != NULL)
2923     {
2924       g_hash_table_destroy (dir->mimeapps_list_added_map);
2925       dir->mimeapps_list_added_map = NULL;
2926     }
2927   
2928   if (dir->mimeapps_list_removed_map != NULL)
2929     {
2930       g_hash_table_destroy (dir->mimeapps_list_removed_map);
2931       dir->mimeapps_list_removed_map = NULL;
2932     }
2933
2934   if (dir->mimeapps_list_defaults_map != NULL)
2935     {
2936       g_hash_table_destroy (dir->mimeapps_list_defaults_map);
2937       dir->mimeapps_list_defaults_map = NULL;
2938     }
2939
2940   g_free (dir);
2941 }
2942
2943 static void
2944 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2945                                          const char        *mime_type,
2946                                          char             **new_desktop_file_ids)
2947 {
2948   GList *desktop_file_ids;
2949   int i;
2950   
2951   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2952                                           mime_type);
2953   
2954   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2955     {
2956       if (!g_list_find_custom (desktop_file_ids, new_desktop_file_ids[i], (GCompareFunc) strcmp))
2957         desktop_file_ids = g_list_append (desktop_file_ids,
2958                                           g_strdup (new_desktop_file_ids[i]));
2959     }
2960   
2961   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2962 }
2963
2964 static void
2965 mime_info_cache_init_dir_lists (void)
2966 {
2967   const char * const *dirs;
2968   int i;
2969   
2970   mime_info_cache = mime_info_cache_new ();
2971   
2972   dirs = get_applications_search_path ();
2973   
2974   for (i = 0; dirs[i] != NULL; i++)
2975     {
2976       MimeInfoCacheDir *dir;
2977       
2978       dir = mime_info_cache_dir_new (dirs[i]);
2979       
2980       if (dir != NULL)
2981         {
2982           mime_info_cache_dir_init (dir);
2983           mime_info_cache_dir_init_defaults_list (dir);
2984           mime_info_cache_dir_init_mimeapps_list (dir);
2985           
2986           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2987         }
2988     }
2989 }
2990
2991 static void
2992 mime_info_cache_update_dir_lists (void)
2993 {
2994   GList *tmp;
2995   
2996   tmp = mime_info_cache->dirs;
2997   
2998   while (tmp != NULL)
2999     {
3000       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
3001
3002       /* No need to do this if we had file monitors... */
3003       mime_info_cache_blow_global_cache ();
3004       mime_info_cache_dir_init (dir);
3005       mime_info_cache_dir_init_defaults_list (dir);
3006       mime_info_cache_dir_init_mimeapps_list (dir);
3007       
3008       tmp = tmp->next;
3009     }
3010 }
3011
3012 static void
3013 mime_info_cache_init (void)
3014 {
3015   G_LOCK (mime_info_cache);
3016   if (mime_info_cache == NULL)
3017     mime_info_cache_init_dir_lists ();
3018   else
3019     {
3020       time_t now;
3021       
3022       time (&now);
3023       if (now >= mime_info_cache->last_stat_time + 10)
3024         {
3025           mime_info_cache_update_dir_lists ();
3026           mime_info_cache->last_stat_time = now;
3027         }
3028     }
3029   
3030   if (mime_info_cache->should_ping_mime_monitor)
3031     {
3032       /* g_idle_add (emit_mime_changed, NULL); */
3033       mime_info_cache->should_ping_mime_monitor = FALSE;
3034     }
3035   
3036   G_UNLOCK (mime_info_cache);
3037 }
3038
3039 static MimeInfoCache *
3040 mime_info_cache_new (void)
3041 {
3042   MimeInfoCache *cache;
3043   
3044   cache = g_new0 (MimeInfoCache, 1);
3045   
3046   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
3047                                                         (GDestroyNotify) g_free,
3048                                                         (GDestroyNotify) g_free);
3049   return cache;
3050 }
3051
3052 static void
3053 mime_info_cache_free (MimeInfoCache *cache)
3054 {
3055   if (cache == NULL)
3056     return;
3057   
3058   g_list_foreach (cache->dirs,
3059                   (GFunc) mime_info_cache_dir_free,
3060                   NULL);
3061   g_list_free (cache->dirs);
3062   g_hash_table_destroy (cache->global_defaults_cache);
3063   g_free (cache);
3064 }
3065
3066 /**
3067  * mime_info_cache_reload:
3068  * @dir: directory path which needs reloading.
3069  * 
3070  * Reload the mime information for the @dir.
3071  */
3072 static void
3073 mime_info_cache_reload (const char *dir)
3074 {
3075   /* FIXME: just reload the dir that needs reloading,
3076    * don't blow the whole cache
3077    */
3078   if (mime_info_cache != NULL)
3079     {
3080       G_LOCK (mime_info_cache);
3081       mime_info_cache_free (mime_info_cache);
3082       mime_info_cache = NULL;
3083       G_UNLOCK (mime_info_cache);
3084     }
3085 }
3086
3087 static GList *
3088 append_desktop_entry (GList      *list, 
3089                       const char *desktop_entry,
3090                       GList      *removed_entries)
3091 {
3092   /* Add if not already in list, and valid */
3093   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
3094       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
3095     list = g_list_prepend (list, g_strdup (desktop_entry));
3096   
3097   return list;
3098 }
3099
3100 /**
3101  * get_all_desktop_entries_for_mime_type:
3102  * @mime_type: a mime type.
3103  * @except: NULL or a strv list
3104  *
3105  * Returns all the desktop ids for @mime_type. The desktop files
3106  * are listed in an order so that default applications are listed before
3107  * non-default ones, and handlers for inherited mimetypes are listed
3108  * after the base ones.
3109  *
3110  * Optionally doesn't list the desktop ids given in the @except 
3111  *
3112  * Return value: a #GList containing the desktop ids which claim
3113  *    to handle @mime_type.
3114  */
3115 static GList *
3116 get_all_desktop_entries_for_mime_type (const char  *base_mime_type,
3117                                        const char **except,
3118                                        gboolean     include_fallback,
3119                                        char       **explicit_default)
3120 {
3121   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
3122   MimeInfoCacheDir *dir;
3123   char *mime_type, *default_entry = NULL;
3124   const char *entry;
3125   char **mime_types;
3126   char **default_entries;
3127   char **removed_associations;
3128   int i, j, k;
3129   GPtrArray *array;
3130   char **anc;
3131   
3132   mime_info_cache_init ();
3133
3134   if (include_fallback)
3135     {
3136       /* collect all ancestors */
3137       mime_types = _g_unix_content_type_get_parents (base_mime_type);
3138       array = g_ptr_array_new ();
3139       for (i = 0; mime_types[i]; i++)
3140         g_ptr_array_add (array, mime_types[i]);
3141       g_free (mime_types);
3142       for (i = 0; i < array->len; i++)
3143         {
3144           anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
3145           for (j = 0; anc[j]; j++)
3146             {
3147               for (k = 0; k < array->len; k++)
3148                 {
3149                   if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
3150                     break;
3151                 }
3152               if (k == array->len) /* not found */
3153                 g_ptr_array_add (array, g_strdup (anc[j]));
3154             }
3155           g_strfreev (anc);
3156         }
3157       g_ptr_array_add (array, NULL);
3158       mime_types = (char **)g_ptr_array_free (array, FALSE);
3159     }
3160   else
3161     {
3162       mime_types = g_malloc0 (2 * sizeof (gchar *));
3163       mime_types[0] = g_strdup (base_mime_type);
3164       mime_types[1] = NULL;
3165     }
3166
3167   G_LOCK (mime_info_cache);
3168   
3169   removed_entries = NULL;
3170   desktop_entries = NULL;
3171
3172   for (i = 0; except != NULL && except[i] != NULL; i++)
3173     removed_entries = g_list_prepend (removed_entries, g_strdup (except[i]));
3174   
3175   for (i = 0; mime_types[i] != NULL; i++)
3176     {
3177       mime_type = mime_types[i];
3178
3179       /* Go through all apps listed in user and system dirs */
3180       for (dir_list = mime_info_cache->dirs;
3181            dir_list != NULL;
3182            dir_list = dir_list->next)
3183         {
3184           dir = dir_list->data;
3185
3186           /* Pick the explicit default application if we got no result earlier
3187            * (ie, for more specific mime types)
3188            */
3189           if (desktop_entries == NULL)
3190             {
3191               entry = g_hash_table_lookup (dir->mimeapps_list_defaults_map, mime_type);
3192
3193               if (entry != NULL)
3194                 {
3195                   /* Save the default entry if it's the first one we encounter */
3196                   if (default_entry == NULL)
3197                     default_entry = g_strdup (entry);
3198                 }
3199             }
3200
3201           /* Then added associations from mimeapps.list */
3202           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
3203           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
3204             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
3205
3206           /* Then removed associations from mimeapps.list */
3207           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
3208           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
3209             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
3210
3211           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
3212           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
3213           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
3214             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
3215         }
3216
3217       /* Go through all entries that support the mimetype */
3218       for (dir_list = mime_info_cache->dirs;
3219            dir_list != NULL;
3220            dir_list = dir_list->next) 
3221         {
3222           dir = dir_list->data;
3223         
3224           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
3225           for (tmp = list; tmp != NULL; tmp = tmp->next)
3226             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
3227         }
3228     }
3229   
3230   G_UNLOCK (mime_info_cache);
3231
3232   g_strfreev (mime_types);
3233
3234   if (explicit_default != NULL)
3235     *explicit_default = default_entry;
3236   else
3237     g_free (default_entry);
3238
3239   g_list_foreach (removed_entries, (GFunc)g_free, NULL);
3240   g_list_free (removed_entries);
3241
3242   desktop_entries = g_list_reverse (desktop_entries);
3243   
3244   return desktop_entries;
3245 }
3246
3247 /* GDesktopAppInfoLookup interface: */
3248
3249 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
3250 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
3251
3252 static void
3253 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
3254 {
3255 }
3256
3257 /**
3258  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
3259  * @lookup: a #GDesktopAppInfoLookup
3260  * @uri_scheme: a string containing a URI scheme.
3261  *
3262  * Gets the default application for launching applications 
3263  * using this URI scheme for a particular GDesktopAppInfoLookup
3264  * implementation.
3265  *
3266  * The GDesktopAppInfoLookup interface and this function is used
3267  * to implement g_app_info_get_default_for_uri_scheme() backends
3268  * in a GIO module. There is no reason for applications to use it
3269  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
3270  * 
3271  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
3272  *
3273  * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
3274  */
3275 GAppInfo *
3276 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
3277                                                       const char            *uri_scheme)
3278 {
3279   GDesktopAppInfoLookupIface *iface;
3280   
3281   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
3282
3283   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
3284
3285   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
3286 }