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