gdesktopappinfo: Asynchronously flush after sending notification
[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
947   if (session_bus == NULL)
948     return;
949
950   g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
951   for (iter = uris; iter; iter = iter->next)
952     g_variant_builder_add (&uri_variant, "s", iter->data);
953
954   g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
955   if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
956     g_variant_builder_add (&extras_variant, "{sv}",
957                            "startup-id",
958                            g_variant_new ("s",
959                                           sn_id));
960
961   if (info->filename)
962     desktop_file_id = info->filename;
963   else if (info->desktop_id)
964     desktop_file_id = info->desktop_id;
965   else
966     desktop_file_id = "";
967   
968   msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
969                                    "org.gtk.gio.DesktopAppInfo",
970                                    "Launched");
971   g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
972                                                g_variant_new_bytestring (desktop_file_id),
973                                                display ? display : "",
974                                                (gint64)pid,
975                                                &uri_variant,
976                                                &extras_variant));
977   g_dbus_connection_send_message (session_bus,
978                                   msg, 0,
979                                   NULL,
980                                   NULL);
981   g_object_unref (msg);
982 }
983
984 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
985
986 static gboolean
987 _g_desktop_app_info_launch_uris_internal (GAppInfo                   *appinfo,
988                                           GList                      *uris,
989                                           GAppLaunchContext          *launch_context,
990                                           GSpawnFlags                 spawn_flags,
991                                           GSpawnChildSetupFunc        user_setup,
992                                           gpointer                    user_setup_data,
993                                           GDesktopAppLaunchCallback   pid_callback,
994                                           gpointer                    pid_callback_data,
995                                           GError                     **error)
996 {
997   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
998   GDBusConnection *session_bus;
999   gboolean completed = FALSE;
1000   GList *old_uris;
1001   char **argv;
1002   int argc;
1003   ChildSetupData data;
1004
1005   g_return_val_if_fail (appinfo != NULL, FALSE);
1006
1007   argv = NULL;
1008
1009   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
1010
1011   do
1012     {
1013       GPid pid;
1014       GList *launched_uris;
1015       GList *iter;
1016
1017       old_uris = uris;
1018       if (!expand_application_parameters (info, &uris,
1019                                           &argc, &argv, error))
1020         goto out;
1021
1022       /* Get the subset of URIs we're launching with this process */
1023       launched_uris = NULL;
1024       for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
1025         launched_uris = g_list_prepend (launched_uris, iter->data);
1026       launched_uris = g_list_reverse (launched_uris);
1027       
1028       if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
1029         {
1030           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1031                                _("Unable to find terminal required for application"));
1032           goto out;
1033         }
1034
1035       data.user_setup = user_setup;
1036       data.user_setup_data = user_setup_data;
1037       data.display = NULL;
1038       data.sn_id = NULL;
1039       data.desktop_file = info->filename;
1040
1041       if (launch_context)
1042         {
1043           GList *launched_files = create_files_for_uris (launched_uris);
1044
1045           data.display = g_app_launch_context_get_display (launch_context,
1046                                                            appinfo,
1047                                                            launched_files);
1048
1049           if (info->startup_notify)
1050             data.sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
1051                                                                      appinfo,
1052                                                                      launched_files);
1053           g_list_foreach (launched_files, (GFunc)g_object_unref, NULL);
1054           g_list_free (launched_files);
1055         }
1056
1057       if (!g_spawn_async (info->path,
1058                           argv,
1059                           NULL,
1060                           spawn_flags,
1061                           child_setup,
1062                           &data,
1063                           &pid,
1064                           error))
1065         {
1066           if (data.sn_id)
1067             g_app_launch_context_launch_failed (launch_context, data.sn_id);
1068
1069           g_free (data.sn_id);
1070           g_free (data.display);
1071           g_list_free (launched_uris);
1072
1073           goto out;
1074         }
1075
1076       if (pid_callback != NULL)
1077         pid_callback (info, pid, pid_callback_data);
1078
1079       notify_desktop_launch (session_bus,
1080                              info,
1081                              pid,
1082                              data.display,
1083                              data.sn_id,
1084                              launched_uris);
1085
1086       g_free (data.sn_id);
1087       g_free (data.display);
1088       g_list_free (launched_uris);
1089
1090       g_strfreev (argv);
1091       argv = NULL;
1092     }
1093   while (uris != NULL);
1094
1095   /* TODO - need to handle the process exiting immediately
1096    * after launching an app.  See http://bugzilla.gnome.org/606960
1097    */
1098   if (session_bus != NULL)
1099     {
1100       /* This asynchronous flush holds a reference until it completes,
1101        * which ensures that the following unref won't immediately kill
1102        * the connection if we were the initial owner.
1103        */
1104       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
1105       g_object_unref (session_bus);
1106     }
1107
1108   completed = TRUE;
1109
1110  out:
1111   g_strfreev (argv);
1112
1113   return completed;
1114 }
1115
1116 static gboolean
1117 g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
1118                                 GList              *uris,
1119                                 GAppLaunchContext  *launch_context,
1120                                 GError            **error)
1121 {
1122   return _g_desktop_app_info_launch_uris_internal (appinfo, uris,
1123                                                    launch_context,
1124                                                    _SPAWN_FLAGS_DEFAULT,
1125                                                    NULL, NULL, NULL, NULL,
1126                                                    error);
1127 }
1128
1129 static gboolean
1130 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
1131 {
1132   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1133  
1134   return info->exec && 
1135     ((strstr (info->exec, "%u") != NULL) ||
1136      (strstr (info->exec, "%U") != NULL));
1137 }
1138
1139 static gboolean
1140 g_desktop_app_info_supports_files (GAppInfo *appinfo)
1141 {
1142   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1143  
1144   return info->exec && 
1145     ((strstr (info->exec, "%f") != NULL) ||
1146      (strstr (info->exec, "%F") != NULL));
1147 }
1148
1149 static gboolean
1150 g_desktop_app_info_launch (GAppInfo           *appinfo,
1151                            GList              *files,
1152                            GAppLaunchContext  *launch_context,
1153                            GError            **error)
1154 {
1155   GList *uris;
1156   char *uri;
1157   gboolean res;
1158
1159   uris = NULL;
1160   while (files)
1161     {
1162       uri = g_file_get_uri (files->data);
1163       uris = g_list_prepend (uris, uri);
1164       files = files->next;
1165     }
1166   
1167   uris = g_list_reverse (uris);
1168   
1169   res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
1170   
1171   g_list_foreach  (uris, (GFunc)g_free, NULL);
1172   g_list_free (uris);
1173   
1174   return res;
1175 }
1176
1177 /**
1178  * g_desktop_app_info_launch_uris_as_manager:
1179  * @appinfo: a #GDesktopAppInfo
1180  * @uris: (element-type utf8): List of URIs
1181  * @launch_context: a #GAppLaunchContext
1182  * @spawn_flags: #GSpawnFlags, used for each process
1183  * @user_setup: (scope call): a #GSpawnChildSetupFunc, used once for
1184  *     each process.
1185  * @user_setup_data: (closure user_setup): User data for @user_setup
1186  * @pid_callback: (scope call): Callback for child processes
1187  * @pid_callback_data: (closure pid_callback): User data for @callback
1188  * @error: a #GError
1189  *
1190  * This function performs the equivalent of g_app_info_launch_uris(),
1191  * but is intended primarily for operating system components that
1192  * launch applications.  Ordinary applications should use
1193  * g_app_info_launch_uris().
1194  *
1195  * In contrast to g_app_info_launch_uris(), all processes created will
1196  * always be run directly as children as if by the UNIX fork()/exec()
1197  * calls.
1198  *
1199  * This guarantee allows additional control over the exact environment
1200  * of the child processes, which is provided via a setup function
1201  * @setup, as well as the process identifier of each child process via
1202  * @pid_callback.  See g_spawn_async() for more information about the
1203  * semantics of the @setup function.
1204  */
1205 gboolean
1206 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo            *appinfo,
1207                                            GList                      *uris,
1208                                            GAppLaunchContext          *launch_context,
1209                                            GSpawnFlags                 spawn_flags,
1210                                            GSpawnChildSetupFunc        user_setup,
1211                                            gpointer                    user_setup_data,
1212                                            GDesktopAppLaunchCallback   pid_callback,
1213                                            gpointer                    pid_callback_data,
1214                                            GError                    **error)
1215 {
1216   return _g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
1217                                                    uris,
1218                                                    launch_context,
1219                                                    spawn_flags,
1220                                                    user_setup,
1221                                                    user_setup_data,
1222                                                    pid_callback,
1223                                                    pid_callback_data,
1224                                                    error);
1225 }
1226
1227 G_LOCK_DEFINE_STATIC (g_desktop_env);
1228 static gchar *g_desktop_env = NULL;
1229
1230 /**
1231  * g_desktop_app_info_set_desktop_env:
1232  * @desktop_env: a string specifying what desktop this is
1233  *
1234  * Sets the name of the desktop that the application is running in.
1235  * This is used by g_app_info_should_show() to evaluate the
1236  * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal>
1237  * desktop entry fields.
1238  *
1239  * The <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Desktop 
1240  * Menu specification</ulink> recognizes the following:
1241  * <simplelist>
1242  *   <member>GNOME</member>
1243  *   <member>KDE</member>
1244  *   <member>ROX</member>
1245  *   <member>XFCE</member>
1246  *   <member>Old</member> 
1247  * </simplelist>
1248  *
1249  * Should be called only once; subsequent calls are ignored.
1250  */
1251 void
1252 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
1253 {
1254   G_LOCK (g_desktop_env);
1255   if (!g_desktop_env)
1256     g_desktop_env = g_strdup (desktop_env);
1257   G_UNLOCK (g_desktop_env);
1258 }
1259
1260 static gboolean
1261 g_desktop_app_info_should_show (GAppInfo *appinfo)
1262 {
1263   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1264   gboolean found;
1265   const gchar *desktop_env;
1266   int i;
1267
1268   if (info->nodisplay)
1269     return FALSE;
1270
1271   G_LOCK (g_desktop_env);
1272   desktop_env = g_desktop_env;
1273   G_UNLOCK (g_desktop_env);
1274
1275   if (info->only_show_in)
1276     {
1277       if (desktop_env == NULL)
1278         return FALSE;
1279       
1280       found = FALSE;
1281       for (i = 0; info->only_show_in[i] != NULL; i++)
1282         {
1283           if (strcmp (info->only_show_in[i], desktop_env) == 0)
1284             {
1285               found = TRUE;
1286               break;
1287             }
1288         }
1289       if (!found)
1290         return FALSE;
1291     }
1292
1293   if (info->not_show_in && desktop_env)
1294     {
1295       for (i = 0; info->not_show_in[i] != NULL; i++)
1296         {
1297           if (strcmp (info->not_show_in[i], desktop_env) == 0)
1298             return FALSE;
1299         }
1300     }
1301   
1302   return TRUE;
1303 }
1304
1305 typedef enum {
1306   APP_DIR,
1307   MIMETYPE_DIR
1308 } DirType;
1309
1310 static char *
1311 ensure_dir (DirType   type,
1312             GError  **error)
1313 {
1314   char *path, *display_name;
1315   int errsv;
1316
1317   if (type == APP_DIR)
1318     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1319   else
1320     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
1321
1322   errno = 0;
1323   if (g_mkdir_with_parents (path, 0700) == 0)
1324     return path;
1325
1326   errsv = errno;
1327   display_name = g_filename_display_name (path);
1328   if (type == APP_DIR)
1329     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1330                  _("Can't create user application configuration folder %s: %s"),
1331                  display_name, g_strerror (errsv));
1332   else
1333     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1334                  _("Can't create user MIME configuration folder %s: %s"),
1335                  display_name, g_strerror (errsv));
1336
1337   g_free (display_name);
1338   g_free (path);
1339
1340   return NULL;
1341 }
1342
1343 static gboolean
1344 update_mimeapps_list (const char  *desktop_id, 
1345                       const char  *content_type,
1346                       UpdateMimeFlags flags,
1347                       GError     **error)
1348 {
1349   char *dirname, *filename, *string;
1350   GKeyFile *key_file;
1351   gboolean load_succeeded, res, explicit_default;
1352   char **old_list, **list;
1353   GList *system_list;
1354   gsize length, data_size;
1355   char *data;
1356   int i, j, k;
1357   char **content_types;
1358
1359   /* Don't add both at start and end */
1360   g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
1361               (flags & UPDATE_MIME_SET_NON_DEFAULT)));
1362
1363   dirname = ensure_dir (APP_DIR, error);
1364   if (!dirname)
1365     return FALSE;
1366
1367   filename = g_build_filename (dirname, "mimeapps.list", NULL);
1368   g_free (dirname);
1369
1370   key_file = g_key_file_new ();
1371   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
1372   if (!load_succeeded || !g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP))
1373     {
1374       g_key_file_free (key_file);
1375       key_file = g_key_file_new ();
1376     }
1377
1378   if (content_type)
1379     {
1380       content_types = g_new (char *, 2);
1381       content_types[0] = g_strdup (content_type);
1382       content_types[1] = NULL;
1383     }
1384   else
1385     {
1386       content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
1387     }
1388
1389   explicit_default = FALSE;
1390
1391   for (k = 0; content_types && content_types[k]; k++)
1392     {
1393       /* set as default, if requested so */
1394       string = g_key_file_get_string (key_file,
1395                                       DEFAULT_APPLICATIONS_GROUP,
1396                                       content_types[k],
1397                                       NULL);
1398
1399       if (g_strcmp0 (string, desktop_id) != 0 &&
1400           (flags & UPDATE_MIME_SET_DEFAULT))
1401         {
1402           g_free (string);
1403           string = g_strdup (desktop_id);
1404
1405           /* add in the non-default list too, if it's not already there */
1406           flags |= UPDATE_MIME_SET_NON_DEFAULT;
1407         }
1408
1409       if (string == NULL || desktop_id == NULL)
1410         g_key_file_remove_key (key_file,
1411                                DEFAULT_APPLICATIONS_GROUP,
1412                                content_types[k],
1413                                NULL);
1414       else
1415         {
1416           g_key_file_set_string (key_file,
1417                                  DEFAULT_APPLICATIONS_GROUP,
1418                                  content_types[k],
1419                                  string);
1420
1421           explicit_default = TRUE;
1422         }
1423
1424       g_free (string);
1425     }
1426
1427   if (content_type)
1428     {
1429       /* reuse the list from above */
1430     }
1431   else
1432     {
1433       g_strfreev (content_types);
1434       content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
1435     }
1436   
1437   for (k = 0; content_types && content_types[k]; k++)
1438     { 
1439       /* Add to the right place in the list */
1440   
1441       length = 0;
1442       old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
1443                                              content_types[k], &length, NULL);
1444
1445       list = g_new (char *, 1 + length + 1);
1446
1447       i = 0;
1448
1449       /* if we're adding a last-used hint, just put the application in front of the list */
1450       if (flags & UPDATE_MIME_SET_LAST_USED)
1451         {
1452           /* avoid adding this again as non-default later */
1453           if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1454             flags ^= UPDATE_MIME_SET_NON_DEFAULT;
1455
1456           list[i++] = g_strdup (desktop_id);
1457         }
1458
1459       if (old_list)
1460         {
1461           for (j = 0; old_list[j] != NULL; j++)
1462             {
1463               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1464                 {
1465                   /* rewrite other entries if they're different from the new one */
1466                   list[i++] = g_strdup (old_list[j]);
1467                 }
1468               else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1469                 {
1470                   /* we encountered an old entry which is equal to the one we're adding as non-default,
1471                    * don't change its position in the list.
1472                    */
1473                   flags ^= UPDATE_MIME_SET_NON_DEFAULT;
1474                   list[i++] = g_strdup (old_list[j]);
1475                 }
1476             }
1477         }
1478
1479       /* add it at the end of the list */
1480       if (flags & UPDATE_MIME_SET_NON_DEFAULT)
1481         list[i++] = g_strdup (desktop_id);
1482
1483       list[i] = NULL;
1484   
1485       g_strfreev (old_list);
1486
1487       if (list[0] == NULL || desktop_id == NULL)
1488         g_key_file_remove_key (key_file,
1489                                ADDED_ASSOCIATIONS_GROUP,
1490                                content_types[k],
1491                                NULL);
1492       else
1493         {
1494           g_key_file_set_string_list (key_file,
1495                                       ADDED_ASSOCIATIONS_GROUP,
1496                                       content_types[k],
1497                                       (const char * const *)list, i);
1498
1499           /* if we had no explicit default set, we should add the system default to the
1500            * list, to avoid overriding it with applications from this list.
1501            */
1502           if (!explicit_default)
1503             {
1504               system_list = get_all_desktop_entries_for_mime_type (content_type, (const char **) list, FALSE, NULL);
1505
1506               if (system_list != NULL)
1507                 {
1508                   string = system_list->data;
1509
1510                   g_key_file_set_string (key_file,
1511                                          DEFAULT_APPLICATIONS_GROUP,
1512                                          content_types[k],
1513                                          string);
1514                 }
1515
1516               g_list_free_full (system_list, g_free);
1517             }
1518         }
1519    
1520       g_strfreev (list);
1521     }
1522   
1523   if (content_type)
1524     {
1525       /* reuse the list from above */
1526     }
1527   else
1528     {
1529       g_strfreev (content_types);
1530       content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
1531     }
1532
1533   for (k = 0; content_types && content_types[k]; k++) 
1534     {
1535       /* Remove from removed associations group (unless remove) */
1536   
1537       length = 0;
1538       old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
1539                                              content_types[k], &length, NULL);
1540
1541       list = g_new (char *, 1 + length + 1);
1542
1543       i = 0;
1544       if (flags & UPDATE_MIME_REMOVE)
1545         list[i++] = g_strdup (desktop_id);
1546       if (old_list)
1547         {
1548           for (j = 0; old_list[j] != NULL; j++)
1549             {
1550               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1551                 list[i++] = g_strdup (old_list[j]);
1552             }
1553         }
1554       list[i] = NULL;
1555   
1556       g_strfreev (old_list);
1557
1558       if (list[0] == NULL || desktop_id == NULL)
1559         g_key_file_remove_key (key_file,
1560                                REMOVED_ASSOCIATIONS_GROUP,
1561                                content_types[k],
1562                                NULL);
1563       else
1564         g_key_file_set_string_list (key_file,
1565                                     REMOVED_ASSOCIATIONS_GROUP,
1566                                     content_types[k],
1567                                     (const char * const *)list, i);
1568
1569       g_strfreev (list);
1570     }
1571
1572   g_strfreev (content_types);  
1573
1574   data = g_key_file_to_data (key_file, &data_size, error);
1575   g_key_file_free (key_file);
1576   
1577   res = g_file_set_contents (filename, data, data_size, error);
1578
1579   mime_info_cache_reload (NULL);
1580                           
1581   g_free (filename);
1582   g_free (data);
1583   
1584   return res;
1585 }
1586
1587 static gboolean
1588 g_desktop_app_info_set_as_last_used_for_type (GAppInfo    *appinfo,
1589                                               const char  *content_type,
1590                                               GError     **error)
1591 {
1592   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1593
1594   if (!g_desktop_app_info_ensure_saved (info, error))
1595     return FALSE;
1596
1597   /* both add support for the content type and set as last used */
1598   return update_mimeapps_list (info->desktop_id, content_type,
1599                                UPDATE_MIME_SET_NON_DEFAULT |
1600                                UPDATE_MIME_SET_LAST_USED,
1601                                error);
1602 }
1603
1604 static gboolean
1605 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
1606                                             const char  *content_type,
1607                                             GError     **error)
1608 {
1609   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1610
1611   if (!g_desktop_app_info_ensure_saved (info, error))
1612     return FALSE;  
1613   
1614   return update_mimeapps_list (info->desktop_id, content_type,
1615                                UPDATE_MIME_SET_DEFAULT,
1616                                error);
1617 }
1618
1619 static void
1620 update_program_done (GPid     pid,
1621                      gint     status,
1622                      gpointer data)
1623 {
1624   /* Did the application exit correctly */
1625   if (WIFEXITED (status) &&
1626       WEXITSTATUS (status) == 0)
1627     {
1628       /* Here we could clean out any caches in use */
1629     }
1630 }
1631
1632 static void
1633 run_update_command (char *command,
1634                     char *subdir)
1635 {
1636         char *argv[3] = {
1637                 NULL,
1638                 NULL,
1639                 NULL,
1640         };
1641         GPid pid = 0;
1642         GError *error = NULL;
1643
1644         argv[0] = command;
1645         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
1646
1647         if (g_spawn_async ("/", argv,
1648                            NULL,       /* envp */
1649                            G_SPAWN_SEARCH_PATH |
1650                            G_SPAWN_STDOUT_TO_DEV_NULL |
1651                            G_SPAWN_STDERR_TO_DEV_NULL |
1652                            G_SPAWN_DO_NOT_REAP_CHILD,
1653                            NULL, NULL, /* No setup function */
1654                            &pid,
1655                            &error)) 
1656           g_child_watch_add (pid, update_program_done, NULL);
1657         else
1658           {
1659             /* If we get an error at this point, it's quite likely the user doesn't
1660              * have an installed copy of either 'update-mime-database' or
1661              * 'update-desktop-database'.  I don't think we want to popup an error
1662              * dialog at this point, so we just do a g_warning to give the user a
1663              * chance of debugging it.
1664              */
1665             g_warning ("%s", error->message);
1666           }
1667         
1668         g_free (argv[1]);
1669 }
1670
1671 static gboolean
1672 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
1673                                                  const char  *extension,
1674                                                  GError     **error)
1675 {
1676   char *filename, *basename, *mimetype;
1677   char *dirname;
1678   gboolean res;
1679
1680   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
1681     return FALSE;  
1682   
1683   dirname = ensure_dir (MIMETYPE_DIR, error);
1684   if (!dirname)
1685     return FALSE;
1686   
1687   basename = g_strdup_printf ("user-extension-%s.xml", extension);
1688   filename = g_build_filename (dirname, basename, NULL);
1689   g_free (basename);
1690   g_free (dirname);
1691
1692   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
1693   
1694   if (!g_file_test (filename, G_FILE_TEST_EXISTS)) 
1695     {
1696       char *contents;
1697
1698       contents =
1699         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1700                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
1701                          " <mime-type type=\"%s\">\n"
1702                          "  <comment>%s document</comment>\n"
1703                          "  <glob pattern=\"*.%s\"/>\n"
1704                          " </mime-type>\n"
1705                          "</mime-info>\n", mimetype, extension, extension);
1706
1707       g_file_set_contents (filename, contents, -1, NULL);
1708       g_free (contents);
1709
1710       run_update_command ("update-mime-database", "mime");
1711     }
1712   g_free (filename);
1713   
1714   res = g_desktop_app_info_set_as_default_for_type (appinfo,
1715                                                     mimetype,
1716                                                     error);
1717
1718   g_free (mimetype);
1719   
1720   return res;
1721 }
1722
1723 static gboolean
1724 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
1725                                       const char  *content_type,
1726                                       GError     **error)
1727 {
1728   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1729
1730   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1731     return FALSE;  
1732   
1733   return update_mimeapps_list (info->desktop_id, content_type,
1734                                UPDATE_MIME_SET_NON_DEFAULT,
1735                                error);
1736 }
1737
1738 static gboolean
1739 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
1740 {
1741   return TRUE;
1742 }
1743
1744 static gboolean
1745 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
1746                                          const char  *content_type,
1747                                          GError     **error)
1748 {
1749   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1750
1751   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1752     return FALSE;
1753   
1754   return update_mimeapps_list (info->desktop_id, content_type,
1755                                UPDATE_MIME_REMOVE,
1756                                error);
1757 }
1758
1759 static gboolean
1760 g_desktop_app_info_ensure_saved (GDesktopAppInfo  *info,
1761                                  GError          **error)
1762 {
1763   GKeyFile *key_file;
1764   char *dirname;
1765   char *filename;
1766   char *data, *desktop_id;
1767   gsize data_size;
1768   int fd;
1769   gboolean res;
1770   
1771   if (info->filename != NULL)
1772     return TRUE;
1773
1774   /* This is only used for object created with
1775    * g_app_info_create_from_commandline. All other
1776    * object should have a filename
1777    */
1778   
1779   dirname = ensure_dir (APP_DIR, error);
1780   if (!dirname)
1781     return FALSE;
1782   
1783   key_file = g_key_file_new ();
1784
1785   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1786                          "Encoding", "UTF-8");
1787   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1788                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
1789   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1790                          G_KEY_FILE_DESKTOP_KEY_TYPE,
1791                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
1792   if (info->terminal) 
1793     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1794                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
1795
1796   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1797                          G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
1798
1799   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1800                          G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
1801
1802   if (info->fullname != NULL)
1803     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1804                            FULL_NAME_KEY, info->fullname);
1805
1806   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1807                          G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
1808   
1809   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1810                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
1811
1812   data = g_key_file_to_data (key_file, &data_size, NULL);
1813   g_key_file_free (key_file);
1814
1815   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
1816   filename = g_build_filename (dirname, desktop_id, NULL);
1817   g_free (desktop_id);
1818   g_free (dirname);
1819   
1820   fd = g_mkstemp (filename);
1821   if (fd == -1)
1822     {
1823       char *display_name;
1824
1825       display_name = g_filename_display_name (filename);
1826       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1827                    _("Can't create user desktop file %s"), display_name);
1828       g_free (display_name);
1829       g_free (filename);
1830       g_free (data);
1831       return FALSE;
1832     }
1833
1834   desktop_id = g_path_get_basename (filename);
1835
1836   close (fd);
1837   
1838   res = g_file_set_contents (filename, data, data_size, error);
1839   if (!res)
1840     {
1841       g_free (desktop_id);
1842       g_free (filename);
1843       return FALSE;
1844     }
1845
1846   info->filename = filename;
1847   info->desktop_id = desktop_id;
1848   
1849   run_update_command ("update-desktop-database", "applications");
1850   
1851   return TRUE;
1852 }
1853
1854 static gboolean
1855 g_desktop_app_info_can_delete (GAppInfo *appinfo)
1856 {
1857   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1858
1859   if (info->filename)
1860     {
1861       if (strstr (info->filename, "/userapp-"))
1862         return g_access (info->filename, W_OK) == 0;
1863     }
1864
1865   return FALSE;
1866 }
1867
1868 static gboolean
1869 g_desktop_app_info_delete (GAppInfo *appinfo)
1870 {
1871   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1872   
1873   if (info->filename)
1874     { 
1875       if (g_remove (info->filename) == 0)
1876         {
1877           update_mimeapps_list (info->desktop_id, NULL,
1878                                 UPDATE_MIME_NONE,
1879                                 NULL);
1880
1881           g_free (info->filename);
1882           info->filename = NULL;
1883           g_free (info->desktop_id);
1884           info->desktop_id = NULL;
1885
1886           return TRUE;
1887         }
1888     }
1889
1890   return FALSE;
1891 }
1892
1893 /**
1894  * g_app_info_create_from_commandline:
1895  * @commandline: the commandline to use
1896  * @application_name: (allow-none): the application name, or %NULL to use @commandline
1897  * @flags: flags that can specify details of the created #GAppInfo
1898  * @error: a #GError location to store the error occuring, %NULL to ignore.
1899  *
1900  * Creates a new #GAppInfo from the given information.
1901  *
1902  * Returns: (transfer full): new #GAppInfo for given command.
1903  **/
1904 GAppInfo *
1905 g_app_info_create_from_commandline (const char           *commandline,
1906                                     const char           *application_name,
1907                                     GAppInfoCreateFlags   flags,
1908                                     GError              **error)
1909 {
1910   char **split;
1911   char *basename;
1912   GDesktopAppInfo *info;
1913
1914   g_return_val_if_fail (commandline, NULL);
1915
1916   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1917
1918   info->filename = NULL;
1919   info->desktop_id = NULL;
1920   
1921   info->terminal = flags & G_APP_INFO_CREATE_NEEDS_TERMINAL;
1922   info->startup_notify = flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION;
1923   info->hidden = FALSE;
1924   if (flags & G_APP_INFO_CREATE_SUPPORTS_URIS)
1925     info->exec = g_strconcat (commandline, " %u", NULL);
1926   else
1927     info->exec = g_strconcat (commandline, " %f", NULL);
1928   info->nodisplay = TRUE;
1929   info->binary = binary_from_exec (info->exec);
1930   
1931   if (application_name)
1932     info->name = g_strdup (application_name);
1933   else
1934     {
1935       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
1936       split = g_strsplit (commandline, " ", 2);
1937       basename = split[0] ? g_path_get_basename (split[0]) : NULL;
1938       g_strfreev (split);
1939       info->name = basename;
1940       if (info->name == NULL)
1941         info->name = g_strdup ("custom");
1942     }
1943   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
1944   
1945   return G_APP_INFO (info);
1946 }
1947
1948 static void
1949 g_desktop_app_info_iface_init (GAppInfoIface *iface)
1950 {
1951   iface->dup = g_desktop_app_info_dup;
1952   iface->equal = g_desktop_app_info_equal;
1953   iface->get_id = g_desktop_app_info_get_id;
1954   iface->get_name = g_desktop_app_info_get_name;
1955   iface->get_description = g_desktop_app_info_get_description;
1956   iface->get_executable = g_desktop_app_info_get_executable;
1957   iface->get_icon = g_desktop_app_info_get_icon;
1958   iface->launch = g_desktop_app_info_launch;
1959   iface->supports_uris = g_desktop_app_info_supports_uris;
1960   iface->supports_files = g_desktop_app_info_supports_files;
1961   iface->launch_uris = g_desktop_app_info_launch_uris;
1962   iface->should_show = g_desktop_app_info_should_show;
1963   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
1964   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
1965   iface->add_supports_type = g_desktop_app_info_add_supports_type;
1966   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
1967   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
1968   iface->can_delete = g_desktop_app_info_can_delete;
1969   iface->do_delete = g_desktop_app_info_delete;
1970   iface->get_commandline = g_desktop_app_info_get_commandline;
1971   iface->get_display_name = g_desktop_app_info_get_display_name;
1972   iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
1973 }
1974
1975 static gboolean
1976 app_info_in_list (GAppInfo *info, 
1977                   GList    *list)
1978 {
1979   while (list != NULL)
1980     {
1981       if (g_app_info_equal (info, list->data))
1982         return TRUE;
1983       list = list->next;
1984     }
1985   return FALSE;
1986 }
1987
1988 /**
1989  * g_app_info_get_recommended_for_type:
1990  * @content_type: the content type to find a #GAppInfo for
1991  * 
1992  * Gets a list of recommended #GAppInfos for a given content type, i.e.
1993  * those applications which claim to support the given content type exactly,
1994  * and not by MIME type subclassing.
1995  * Note that the first application of the list is the last used one, i.e.
1996  * the last one for which #g_app_info_set_as_last_used_for_type has been
1997  * called.
1998  *
1999  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2000  *     for given @content_type or %NULL on error.
2001  *
2002  * Since: 2.28
2003  **/
2004 GList *
2005 g_app_info_get_recommended_for_type (const gchar *content_type)
2006 {
2007   GList *desktop_entries, *l;
2008   GList *infos;
2009   GDesktopAppInfo *info;
2010
2011   g_return_val_if_fail (content_type != NULL, NULL);
2012
2013   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, FALSE, NULL);
2014
2015   infos = NULL;
2016   for (l = desktop_entries; l != NULL; l = l->next)
2017     {
2018       char *desktop_entry = l->data;
2019
2020       info = g_desktop_app_info_new (desktop_entry);
2021       if (info)
2022         {
2023           if (app_info_in_list (G_APP_INFO (info), infos))
2024             g_object_unref (info);
2025           else
2026             infos = g_list_prepend (infos, info);
2027         }
2028       g_free (desktop_entry);
2029     }
2030
2031   g_list_free (desktop_entries);
2032
2033   return g_list_reverse (infos);
2034 }
2035
2036 /**
2037  * g_app_info_get_fallback_for_type:
2038  * @content_type: the content type to find a #GAppInfo for
2039  * 
2040  * Gets a list of fallback #GAppInfos for a given content type, i.e.
2041  * those applications which claim to support the given content type
2042  * by MIME type subclassing and not directly.
2043  *
2044  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2045  *     for given @content_type or %NULL on error.
2046  *
2047  * Since: 2.28
2048  **/
2049 GList *
2050 g_app_info_get_fallback_for_type (const gchar *content_type)
2051 {
2052   GList *desktop_entries, *l;
2053   GList *infos, *recommended_infos;
2054   GDesktopAppInfo *info;
2055
2056   g_return_val_if_fail (content_type != NULL, NULL);
2057
2058   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, NULL);
2059   recommended_infos = g_app_info_get_recommended_for_type (content_type);
2060
2061   infos = NULL;
2062   for (l = desktop_entries; l != NULL; l = l->next)
2063     {
2064       char *desktop_entry = l->data;
2065
2066       info = g_desktop_app_info_new (desktop_entry);
2067       if (info)
2068         {
2069           if (app_info_in_list (G_APP_INFO (info), infos) ||
2070               app_info_in_list (G_APP_INFO (info), recommended_infos))
2071             g_object_unref (info);
2072           else
2073             infos = g_list_prepend (infos, info);
2074         }
2075       g_free (desktop_entry);
2076     }
2077
2078   g_list_free (desktop_entries);
2079   g_list_free_full (recommended_infos, g_object_unref);
2080
2081   return g_list_reverse (infos);
2082 }
2083
2084 /**
2085  * g_app_info_get_all_for_type:
2086  * @content_type: the content type to find a #GAppInfo for
2087  * 
2088  * Gets a list of all #GAppInfos for a given content type.
2089  *
2090  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
2091  *     for given @content_type or %NULL on error.
2092  **/
2093 GList *
2094 g_app_info_get_all_for_type (const char *content_type)
2095 {
2096   GList *desktop_entries, *l;
2097   GList *infos;
2098   char *user_default = NULL;
2099   GDesktopAppInfo *info;
2100
2101   g_return_val_if_fail (content_type != NULL, NULL);
2102   
2103   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
2104   infos = NULL;
2105
2106   /* put the user default in front of the list, for compatibility */
2107   if (user_default != NULL)
2108     {
2109       info = g_desktop_app_info_new (user_default);
2110
2111       if (info != NULL)
2112         infos = g_list_prepend (infos, info);
2113     }
2114
2115   g_free (user_default);
2116
2117   for (l = desktop_entries; l != NULL; l = l->next)
2118     {
2119       char *desktop_entry = l->data;
2120
2121       info = g_desktop_app_info_new (desktop_entry);
2122       if (info)
2123         {
2124           if (app_info_in_list (G_APP_INFO (info), infos))
2125             g_object_unref (info);
2126           else
2127             infos = g_list_prepend (infos, info);
2128         }
2129       g_free (desktop_entry);
2130     }
2131
2132   g_list_free (desktop_entries);
2133   
2134   return g_list_reverse (infos);
2135 }
2136
2137 /**
2138  * g_app_info_reset_type_associations:
2139  * @content_type: a content type 
2140  *
2141  * Removes all changes to the type associations done by
2142  * g_app_info_set_as_default_for_type(), 
2143  * g_app_info_set_as_default_for_extension(), 
2144  * g_app_info_add_supports_type() or g_app_info_remove_supports_type().
2145  *
2146  * Since: 2.20
2147  */
2148 void
2149 g_app_info_reset_type_associations (const char *content_type)
2150 {
2151   update_mimeapps_list (NULL, content_type,
2152                         UPDATE_MIME_NONE,
2153                         NULL);
2154 }
2155
2156 /**
2157  * g_app_info_get_default_for_type:
2158  * @content_type: the content type to find a #GAppInfo for
2159  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
2160  *     support URIs
2161  * 
2162  * Gets the #GAppInfo that corresponds to a given content type.
2163  *
2164  * Returns: (transfer full): #GAppInfo for given @content_type or
2165  *     %NULL on error.
2166  **/
2167 GAppInfo *
2168 g_app_info_get_default_for_type (const char *content_type,
2169                                  gboolean    must_support_uris)
2170 {
2171   GList *desktop_entries, *l;
2172   char *user_default = NULL;
2173   GAppInfo *info;
2174
2175   g_return_val_if_fail (content_type != NULL, NULL);
2176   
2177   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
2178
2179   info = NULL;
2180
2181   if (user_default != NULL)
2182     {
2183       info = (GAppInfo *) g_desktop_app_info_new (user_default);
2184
2185       if (info)
2186         {
2187           if (must_support_uris && !g_app_info_supports_uris (info))
2188             {
2189               g_object_unref (info);
2190               info = NULL;
2191             }
2192         }
2193     }
2194
2195   g_free (user_default);
2196
2197   if (info != NULL)
2198     {
2199       g_list_free_full (desktop_entries, g_free);
2200       return info;
2201     }
2202
2203   /* pick the first from the other list that matches our URI
2204    * requirements.
2205    */
2206   for (l = desktop_entries; l != NULL; l = l->next)
2207     {
2208       char *desktop_entry = l->data;
2209
2210       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
2211       if (info)
2212         {
2213           if (must_support_uris && !g_app_info_supports_uris (info))
2214             {
2215               g_object_unref (info);
2216               info = NULL;
2217             }
2218           else
2219             break;
2220         }
2221     }
2222   
2223   g_list_free_full (desktop_entries, g_free);
2224
2225   return info;
2226 }
2227
2228 /**
2229  * g_app_info_get_default_for_uri_scheme:
2230  * @uri_scheme: a string containing a URI scheme.
2231  *
2232  * Gets the default application for launching applications 
2233  * using this URI scheme. A URI scheme is the initial part 
2234  * of the URI, up to but not including the ':', e.g. "http", 
2235  * "ftp" or "sip".
2236  * 
2237  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
2238  **/
2239 GAppInfo *
2240 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
2241 {
2242   GAppInfo *app_info;
2243   char *content_type, *scheme_down;
2244
2245   scheme_down = g_ascii_strdown (uri_scheme, -1);
2246   content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
2247   g_free (scheme_down);
2248   app_info = g_app_info_get_default_for_type (content_type, FALSE);
2249   g_free (content_type);
2250
2251   return app_info;
2252 }
2253
2254 static void
2255 get_apps_from_dir (GHashTable *apps, 
2256                    const char *dirname, 
2257                    const char *prefix)
2258 {
2259   GDir *dir;
2260   const char *basename;
2261   char *filename, *subprefix, *desktop_id;
2262   gboolean hidden;
2263   GDesktopAppInfo *appinfo;
2264   
2265   dir = g_dir_open (dirname, 0, NULL);
2266   if (dir)
2267     {
2268       while ((basename = g_dir_read_name (dir)) != NULL)
2269         {
2270           filename = g_build_filename (dirname, basename, NULL);
2271           if (g_str_has_suffix (basename, ".desktop"))
2272             {
2273               desktop_id = g_strconcat (prefix, basename, NULL);
2274
2275               /* Use _extended so we catch NULLs too (hidden) */
2276               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
2277                 {
2278                   appinfo = g_desktop_app_info_new_from_filename (filename);
2279                   hidden = FALSE;
2280
2281                   if (appinfo && g_desktop_app_info_get_is_hidden (appinfo))
2282                     {
2283                       g_object_unref (appinfo);
2284                       appinfo = NULL;
2285                       hidden = TRUE;
2286                     }
2287                                       
2288                   if (appinfo || hidden)
2289                     {
2290                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
2291
2292                       if (appinfo)
2293                         {
2294                           /* Reuse instead of strdup here */
2295                           appinfo->desktop_id = desktop_id;
2296                           desktop_id = NULL;
2297                         }
2298                     }
2299                 }
2300               g_free (desktop_id);
2301             }
2302           else
2303             {
2304               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
2305                 {
2306                   subprefix = g_strconcat (prefix, basename, "-", NULL);
2307                   get_apps_from_dir (apps, filename, subprefix);
2308                   g_free (subprefix);
2309                 }
2310             }
2311           g_free (filename);
2312         }
2313       g_dir_close (dir);
2314     }
2315 }
2316
2317
2318 /**
2319  * g_app_info_get_all:
2320  *
2321  * Gets a list of all of the applications currently registered 
2322  * on this system.
2323  * 
2324  * For desktop files, this includes applications that have 
2325  * <literal>NoDisplay=true</literal> set or are excluded from 
2326  * display by means of <literal>OnlyShowIn</literal> or
2327  * <literal>NotShowIn</literal>. See g_app_info_should_show().
2328  * The returned list does not include applications which have
2329  * the <literal>Hidden</literal> key set. 
2330  * 
2331  * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfo<!---->s.
2332  **/
2333 GList *
2334 g_app_info_get_all (void)
2335 {
2336   const char * const *dirs;
2337   GHashTable *apps;
2338   GHashTableIter iter;
2339   gpointer value;
2340   int i;
2341   GList *infos;
2342
2343   dirs = get_applications_search_path ();
2344
2345   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
2346                                 g_free, NULL);
2347
2348   
2349   for (i = 0; dirs[i] != NULL; i++)
2350     get_apps_from_dir (apps, dirs[i], "");
2351
2352
2353   infos = NULL;
2354   g_hash_table_iter_init (&iter, apps);
2355   while (g_hash_table_iter_next (&iter, NULL, &value))
2356     {
2357       if (value)
2358         infos = g_list_prepend (infos, value);
2359     }
2360
2361   g_hash_table_destroy (apps);
2362
2363   return g_list_reverse (infos);
2364 }
2365
2366 /* Cacheing of mimeinfo.cache and defaults.list files */
2367
2368 typedef struct {
2369   char *path;
2370   GHashTable *mime_info_cache_map;
2371   GHashTable *defaults_list_map;
2372   GHashTable *mimeapps_list_added_map;
2373   GHashTable *mimeapps_list_removed_map;
2374   GHashTable *mimeapps_list_defaults_map;
2375   time_t mime_info_cache_timestamp;
2376   time_t defaults_list_timestamp;
2377   time_t mimeapps_list_timestamp;
2378 } MimeInfoCacheDir;
2379
2380 typedef struct {
2381   GList *dirs;                       /* mimeinfo.cache and defaults.list */
2382   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
2383   time_t last_stat_time;
2384   guint should_ping_mime_monitor : 1;
2385 } MimeInfoCache;
2386
2387 static MimeInfoCache *mime_info_cache = NULL;
2388 G_LOCK_DEFINE_STATIC (mime_info_cache);
2389
2390 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2391                                                      const char        *mime_type,
2392                                                      char             **new_desktop_file_ids);
2393
2394 static MimeInfoCache * mime_info_cache_new (void);
2395
2396 static void
2397 destroy_info_cache_value (gpointer  key, 
2398                           GList    *value, 
2399                           gpointer  data)
2400 {
2401   g_list_foreach (value, (GFunc)g_free, NULL);
2402   g_list_free (value);
2403 }
2404
2405 static void
2406 destroy_info_cache_map (GHashTable *info_cache_map)
2407 {
2408   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
2409   g_hash_table_destroy (info_cache_map);
2410 }
2411
2412 static gboolean
2413 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
2414                                  const char       *cache_file,
2415                                  time_t           *timestamp)
2416 {
2417   struct stat buf;
2418   char *filename;
2419   
2420   filename = g_build_filename (dir->path, cache_file, NULL);
2421   
2422   if (g_stat (filename, &buf) < 0)
2423     {
2424       g_free (filename);
2425       return TRUE;
2426     }
2427   g_free (filename);
2428
2429   if (buf.st_mtime != *timestamp) 
2430     return TRUE;
2431   
2432   return FALSE;
2433 }
2434
2435 /* Call with lock held */
2436 static gboolean
2437 remove_all (gpointer  key,
2438             gpointer  value,
2439             gpointer  user_data)
2440 {
2441   return TRUE;
2442 }
2443
2444
2445 static void
2446 mime_info_cache_blow_global_cache (void)
2447 {
2448   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
2449                                remove_all, NULL);
2450 }
2451
2452 static void
2453 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
2454 {
2455   GError *load_error;
2456   GKeyFile *key_file;
2457   gchar *filename, **mime_types;
2458   int i;
2459   struct stat buf;
2460   
2461   load_error = NULL;
2462   mime_types = NULL;
2463   
2464   if (dir->mime_info_cache_map != NULL &&
2465       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
2466                                         &dir->mime_info_cache_timestamp))
2467     return;
2468   
2469   if (dir->mime_info_cache_map != NULL)
2470     destroy_info_cache_map (dir->mime_info_cache_map);
2471   
2472   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2473                                                     (GDestroyNotify) g_free,
2474                                                     NULL);
2475   
2476   key_file = g_key_file_new ();
2477   
2478   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
2479   
2480   if (g_stat (filename, &buf) < 0)
2481     goto error;
2482   
2483   if (dir->mime_info_cache_timestamp > 0) 
2484     mime_info_cache->should_ping_mime_monitor = TRUE;
2485   
2486   dir->mime_info_cache_timestamp = buf.st_mtime;
2487   
2488   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2489   
2490   g_free (filename);
2491   filename = NULL;
2492   
2493   if (load_error != NULL)
2494     goto error;
2495   
2496   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
2497                                     NULL, &load_error);
2498   
2499   if (load_error != NULL)
2500     goto error;
2501   
2502   for (i = 0; mime_types[i] != NULL; i++)
2503     {
2504       gchar **desktop_file_ids;
2505       char *unaliased_type;
2506       desktop_file_ids = g_key_file_get_string_list (key_file,
2507                                                      MIME_CACHE_GROUP,
2508                                                      mime_types[i],
2509                                                      NULL,
2510                                                      NULL);
2511       
2512       if (desktop_file_ids == NULL)
2513         continue;
2514
2515       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2516       mime_info_cache_dir_add_desktop_entries (dir,
2517                                                unaliased_type,
2518                                                desktop_file_ids);
2519       g_free (unaliased_type);
2520     
2521       g_strfreev (desktop_file_ids);
2522     }
2523   
2524   g_strfreev (mime_types);
2525   g_key_file_free (key_file);
2526   
2527   return;
2528  error:
2529   g_free (filename);
2530   g_key_file_free (key_file);
2531   
2532   if (mime_types != NULL)
2533     g_strfreev (mime_types);
2534   
2535   if (load_error)
2536     g_error_free (load_error);
2537 }
2538
2539 static void
2540 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
2541 {
2542   GKeyFile *key_file;
2543   GError *load_error;
2544   gchar *filename, **mime_types;
2545   char *unaliased_type;
2546   char **desktop_file_ids;
2547   int i;
2548   struct stat buf;
2549
2550   load_error = NULL;
2551   mime_types = NULL;
2552
2553   if (dir->defaults_list_map != NULL &&
2554       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
2555                                         &dir->defaults_list_timestamp))
2556     return;
2557   
2558   if (dir->defaults_list_map != NULL)
2559     g_hash_table_destroy (dir->defaults_list_map);
2560   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2561                                                   g_free, (GDestroyNotify)g_strfreev);
2562   
2563
2564   key_file = g_key_file_new ();
2565   
2566   filename = g_build_filename (dir->path, "defaults.list", NULL);
2567   if (g_stat (filename, &buf) < 0)
2568     goto error;
2569
2570   if (dir->defaults_list_timestamp > 0) 
2571     mime_info_cache->should_ping_mime_monitor = TRUE;
2572
2573   dir->defaults_list_timestamp = buf.st_mtime;
2574
2575   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2576   g_free (filename);
2577   filename = NULL;
2578
2579   if (load_error != NULL)
2580     goto error;
2581
2582   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2583                                     NULL, NULL);
2584   if (mime_types != NULL)
2585     {
2586       for (i = 0; mime_types[i] != NULL; i++)
2587         {
2588           desktop_file_ids = g_key_file_get_string_list (key_file,
2589                                                          DEFAULT_APPLICATIONS_GROUP,
2590                                                          mime_types[i],
2591                                                          NULL,
2592                                                          NULL);
2593           if (desktop_file_ids == NULL)
2594             continue;
2595           
2596           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2597           g_hash_table_replace (dir->defaults_list_map,
2598                                 unaliased_type,
2599                                 desktop_file_ids);
2600         }
2601       
2602       g_strfreev (mime_types);
2603     }
2604
2605   g_key_file_free (key_file);
2606   return;
2607   
2608  error:
2609   g_free (filename);
2610   g_key_file_free (key_file);
2611   
2612   if (mime_types != NULL)
2613     g_strfreev (mime_types);
2614   
2615   if (load_error)
2616     g_error_free (load_error);
2617 }
2618
2619 static void
2620 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
2621 {
2622   GKeyFile *key_file;
2623   GError *load_error;
2624   gchar *filename, **mime_types;
2625   char *unaliased_type;
2626   char **desktop_file_ids;
2627   char *desktop_id;
2628   int i;
2629   struct stat buf;
2630
2631   load_error = NULL;
2632   mime_types = NULL;
2633
2634   if (dir->mimeapps_list_added_map != NULL &&
2635       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
2636                                         &dir->mimeapps_list_timestamp))
2637     return;
2638   
2639   if (dir->mimeapps_list_added_map != NULL)
2640     g_hash_table_destroy (dir->mimeapps_list_added_map);
2641   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2642                                                         g_free, (GDestroyNotify)g_strfreev);
2643   
2644   if (dir->mimeapps_list_removed_map != NULL)
2645     g_hash_table_destroy (dir->mimeapps_list_removed_map);
2646   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2647                                                           g_free, (GDestroyNotify)g_strfreev);
2648
2649   if (dir->mimeapps_list_defaults_map != NULL)
2650     g_hash_table_destroy (dir->mimeapps_list_defaults_map);
2651   dir->mimeapps_list_defaults_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2652                                                            g_free, g_free);
2653
2654   key_file = g_key_file_new ();
2655   
2656   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
2657   if (g_stat (filename, &buf) < 0)
2658     goto error;
2659
2660   if (dir->mimeapps_list_timestamp > 0) 
2661     mime_info_cache->should_ping_mime_monitor = TRUE;
2662
2663   dir->mimeapps_list_timestamp = buf.st_mtime;
2664
2665   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2666   g_free (filename);
2667   filename = NULL;
2668
2669   if (load_error != NULL)
2670     goto error;
2671
2672   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
2673                                     NULL, NULL);
2674   if (mime_types != NULL)
2675     {
2676       for (i = 0; mime_types[i] != NULL; i++)
2677         {
2678           desktop_file_ids = g_key_file_get_string_list (key_file,
2679                                                          ADDED_ASSOCIATIONS_GROUP,
2680                                                          mime_types[i],
2681                                                          NULL,
2682                                                          NULL);
2683           if (desktop_file_ids == NULL)
2684             continue;
2685           
2686           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2687           g_hash_table_replace (dir->mimeapps_list_added_map,
2688                                 unaliased_type,
2689                                 desktop_file_ids);
2690         }
2691       
2692       g_strfreev (mime_types);
2693     }
2694
2695   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
2696                                     NULL, NULL);
2697   if (mime_types != NULL)
2698     {
2699       for (i = 0; mime_types[i] != NULL; i++)
2700         {
2701           desktop_file_ids = g_key_file_get_string_list (key_file,
2702                                                          REMOVED_ASSOCIATIONS_GROUP,
2703                                                          mime_types[i],
2704                                                          NULL,
2705                                                          NULL);
2706           if (desktop_file_ids == NULL)
2707             continue;
2708           
2709           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2710           g_hash_table_replace (dir->mimeapps_list_removed_map,
2711                                 unaliased_type,
2712                                 desktop_file_ids);
2713         }
2714       
2715       g_strfreev (mime_types);
2716     }
2717
2718   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2719                                     NULL, NULL);
2720   if (mime_types != NULL)
2721     {
2722       for (i = 0; mime_types[i] != NULL; i++)
2723         {
2724           desktop_id = g_key_file_get_string (key_file,
2725                                               DEFAULT_APPLICATIONS_GROUP,
2726                                               mime_types[i],
2727                                               NULL);
2728           if (desktop_id == NULL)
2729             continue;
2730
2731           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2732           g_hash_table_replace (dir->mimeapps_list_defaults_map,
2733                                 unaliased_type,
2734                                 desktop_id);
2735         }
2736
2737       g_strfreev (mime_types);
2738     }
2739
2740   g_key_file_free (key_file);
2741   return;
2742   
2743  error:
2744   g_free (filename);
2745   g_key_file_free (key_file);
2746   
2747   if (mime_types != NULL)
2748     g_strfreev (mime_types);
2749   
2750   if (load_error)
2751     g_error_free (load_error);
2752 }
2753
2754 static MimeInfoCacheDir *
2755 mime_info_cache_dir_new (const char *path)
2756 {
2757   MimeInfoCacheDir *dir;
2758
2759   dir = g_new0 (MimeInfoCacheDir, 1);
2760   dir->path = g_strdup (path);
2761   
2762   return dir;
2763 }
2764
2765 static void
2766 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
2767 {
2768   if (dir == NULL)
2769     return;
2770   
2771   if (dir->mime_info_cache_map != NULL)
2772     {
2773       destroy_info_cache_map (dir->mime_info_cache_map);
2774       dir->mime_info_cache_map = NULL;
2775       
2776   }
2777   
2778   if (dir->defaults_list_map != NULL)
2779     {
2780       g_hash_table_destroy (dir->defaults_list_map);
2781       dir->defaults_list_map = NULL;
2782     }
2783   
2784   if (dir->mimeapps_list_added_map != NULL)
2785     {
2786       g_hash_table_destroy (dir->mimeapps_list_added_map);
2787       dir->mimeapps_list_added_map = NULL;
2788     }
2789   
2790   if (dir->mimeapps_list_removed_map != NULL)
2791     {
2792       g_hash_table_destroy (dir->mimeapps_list_removed_map);
2793       dir->mimeapps_list_removed_map = NULL;
2794     }
2795
2796   if (dir->mimeapps_list_defaults_map != NULL)
2797     {
2798       g_hash_table_destroy (dir->mimeapps_list_defaults_map);
2799       dir->mimeapps_list_defaults_map = NULL;
2800     }
2801
2802   g_free (dir);
2803 }
2804
2805 static void
2806 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2807                                          const char        *mime_type,
2808                                          char             **new_desktop_file_ids)
2809 {
2810   GList *desktop_file_ids;
2811   int i;
2812   
2813   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2814                                           mime_type);
2815   
2816   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2817     {
2818       if (!g_list_find_custom (desktop_file_ids, new_desktop_file_ids[i], (GCompareFunc) strcmp))
2819         desktop_file_ids = g_list_append (desktop_file_ids,
2820                                           g_strdup (new_desktop_file_ids[i]));
2821     }
2822   
2823   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2824 }
2825
2826 static void
2827 mime_info_cache_init_dir_lists (void)
2828 {
2829   const char * const *dirs;
2830   int i;
2831   
2832   mime_info_cache = mime_info_cache_new ();
2833   
2834   dirs = get_applications_search_path ();
2835   
2836   for (i = 0; dirs[i] != NULL; i++)
2837     {
2838       MimeInfoCacheDir *dir;
2839       
2840       dir = mime_info_cache_dir_new (dirs[i]);
2841       
2842       if (dir != NULL)
2843         {
2844           mime_info_cache_dir_init (dir);
2845           mime_info_cache_dir_init_defaults_list (dir);
2846           mime_info_cache_dir_init_mimeapps_list (dir);
2847           
2848           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2849         }
2850     }
2851 }
2852
2853 static void
2854 mime_info_cache_update_dir_lists (void)
2855 {
2856   GList *tmp;
2857   
2858   tmp = mime_info_cache->dirs;
2859   
2860   while (tmp != NULL)
2861     {
2862       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2863
2864       /* No need to do this if we had file monitors... */
2865       mime_info_cache_blow_global_cache ();
2866       mime_info_cache_dir_init (dir);
2867       mime_info_cache_dir_init_defaults_list (dir);
2868       mime_info_cache_dir_init_mimeapps_list (dir);
2869       
2870       tmp = tmp->next;
2871     }
2872 }
2873
2874 static void
2875 mime_info_cache_init (void)
2876 {
2877   G_LOCK (mime_info_cache);
2878   if (mime_info_cache == NULL)
2879     mime_info_cache_init_dir_lists ();
2880   else
2881     {
2882       time_t now;
2883       
2884       time (&now);
2885       if (now >= mime_info_cache->last_stat_time + 10)
2886         {
2887           mime_info_cache_update_dir_lists ();
2888           mime_info_cache->last_stat_time = now;
2889         }
2890     }
2891   
2892   if (mime_info_cache->should_ping_mime_monitor)
2893     {
2894       /* g_idle_add (emit_mime_changed, NULL); */
2895       mime_info_cache->should_ping_mime_monitor = FALSE;
2896     }
2897   
2898   G_UNLOCK (mime_info_cache);
2899 }
2900
2901 static MimeInfoCache *
2902 mime_info_cache_new (void)
2903 {
2904   MimeInfoCache *cache;
2905   
2906   cache = g_new0 (MimeInfoCache, 1);
2907   
2908   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2909                                                         (GDestroyNotify) g_free,
2910                                                         (GDestroyNotify) g_free);
2911   return cache;
2912 }
2913
2914 static void
2915 mime_info_cache_free (MimeInfoCache *cache)
2916 {
2917   if (cache == NULL)
2918     return;
2919   
2920   g_list_foreach (cache->dirs,
2921                   (GFunc) mime_info_cache_dir_free,
2922                   NULL);
2923   g_list_free (cache->dirs);
2924   g_hash_table_destroy (cache->global_defaults_cache);
2925   g_free (cache);
2926 }
2927
2928 /**
2929  * mime_info_cache_reload:
2930  * @dir: directory path which needs reloading.
2931  * 
2932  * Reload the mime information for the @dir.
2933  */
2934 static void
2935 mime_info_cache_reload (const char *dir)
2936 {
2937   /* FIXME: just reload the dir that needs reloading,
2938    * don't blow the whole cache
2939    */
2940   if (mime_info_cache != NULL)
2941     {
2942       G_LOCK (mime_info_cache);
2943       mime_info_cache_free (mime_info_cache);
2944       mime_info_cache = NULL;
2945       G_UNLOCK (mime_info_cache);
2946     }
2947 }
2948
2949 static GList *
2950 append_desktop_entry (GList      *list, 
2951                       const char *desktop_entry,
2952                       GList      *removed_entries)
2953 {
2954   /* Add if not already in list, and valid */
2955   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
2956       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
2957     list = g_list_prepend (list, g_strdup (desktop_entry));
2958   
2959   return list;
2960 }
2961
2962 /**
2963  * get_all_desktop_entries_for_mime_type:
2964  * @mime_type: a mime type.
2965  * @except: NULL or a strv list
2966  *
2967  * Returns all the desktop ids for @mime_type. The desktop files
2968  * are listed in an order so that default applications are listed before
2969  * non-default ones, and handlers for inherited mimetypes are listed
2970  * after the base ones.
2971  *
2972  * Optionally doesn't list the desktop ids given in the @except 
2973  *
2974  * Return value: a #GList containing the desktop ids which claim
2975  *    to handle @mime_type.
2976  */
2977 static GList *
2978 get_all_desktop_entries_for_mime_type (const char  *base_mime_type,
2979                                        const char **except,
2980                                        gboolean     include_fallback,
2981                                        char       **explicit_default)
2982 {
2983   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
2984   MimeInfoCacheDir *dir;
2985   char *mime_type, *default_entry = NULL;
2986   const char *entry;
2987   char **mime_types;
2988   char **default_entries;
2989   char **removed_associations;
2990   int i, j, k;
2991   GPtrArray *array;
2992   char **anc;
2993   
2994   mime_info_cache_init ();
2995
2996   if (include_fallback)
2997     {
2998       /* collect all ancestors */
2999       mime_types = _g_unix_content_type_get_parents (base_mime_type);
3000       array = g_ptr_array_new ();
3001       for (i = 0; mime_types[i]; i++)
3002         g_ptr_array_add (array, mime_types[i]);
3003       g_free (mime_types);
3004       for (i = 0; i < array->len; i++)
3005         {
3006           anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
3007           for (j = 0; anc[j]; j++)
3008             {
3009               for (k = 0; k < array->len; k++)
3010                 {
3011                   if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
3012                     break;
3013                 }
3014               if (k == array->len) /* not found */
3015                 g_ptr_array_add (array, g_strdup (anc[j]));
3016             }
3017           g_strfreev (anc);
3018         }
3019       g_ptr_array_add (array, NULL);
3020       mime_types = (char **)g_ptr_array_free (array, FALSE);
3021     }
3022   else
3023     {
3024       mime_types = g_malloc0 (2 * sizeof (gchar *));
3025       mime_types[0] = g_strdup (base_mime_type);
3026       mime_types[1] = NULL;
3027     }
3028
3029   G_LOCK (mime_info_cache);
3030   
3031   removed_entries = NULL;
3032   desktop_entries = NULL;
3033
3034   for (i = 0; except != NULL && except[i] != NULL; i++)
3035     removed_entries = g_list_prepend (removed_entries, g_strdup (except[i]));
3036   
3037   for (i = 0; mime_types[i] != NULL; i++)
3038     {
3039       mime_type = mime_types[i];
3040
3041       /* Go through all apps listed in user and system dirs */
3042       for (dir_list = mime_info_cache->dirs;
3043            dir_list != NULL;
3044            dir_list = dir_list->next)
3045         {
3046           dir = dir_list->data;
3047
3048           /* Pick the explicit default application */
3049           entry = g_hash_table_lookup (dir->mimeapps_list_defaults_map, mime_type);
3050
3051           if (entry != NULL)
3052             {
3053               /* Save the default entry if it's the first one we encounter */
3054               if (default_entry == NULL)
3055                 default_entry = g_strdup (entry);
3056             }
3057
3058           /* Then added associations from mimeapps.list */
3059           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
3060           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
3061             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
3062
3063           /* Then removed associations from mimeapps.list */
3064           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
3065           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
3066             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
3067
3068           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
3069           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
3070           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
3071             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
3072         }
3073
3074       /* Go through all entries that support the mimetype */
3075       for (dir_list = mime_info_cache->dirs;
3076            dir_list != NULL;
3077            dir_list = dir_list->next) 
3078         {
3079           dir = dir_list->data;
3080         
3081           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
3082           for (tmp = list; tmp != NULL; tmp = tmp->next)
3083             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
3084         }
3085     }
3086   
3087   G_UNLOCK (mime_info_cache);
3088
3089   g_strfreev (mime_types);
3090
3091   if (explicit_default != NULL)
3092     *explicit_default = default_entry;
3093   else
3094     g_free (default_entry);
3095
3096   g_list_foreach (removed_entries, (GFunc)g_free, NULL);
3097   g_list_free (removed_entries);
3098
3099   desktop_entries = g_list_reverse (desktop_entries);
3100   
3101   return desktop_entries;
3102 }
3103
3104 /* GDesktopAppInfoLookup interface: */
3105
3106 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
3107 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
3108
3109 static void
3110 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
3111 {
3112 }
3113
3114 /**
3115  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
3116  * @lookup: a #GDesktopAppInfoLookup
3117  * @uri_scheme: a string containing a URI scheme.
3118  *
3119  * Gets the default application for launching applications 
3120  * using this URI scheme for a particular GDesktopAppInfoLookup
3121  * implementation.
3122  *
3123  * The GDesktopAppInfoLookup interface and this function is used
3124  * to implement g_app_info_get_default_for_uri_scheme() backends
3125  * in a GIO module. There is no reason for applications to use it
3126  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
3127  * 
3128  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
3129  *
3130  * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
3131  */
3132 GAppInfo *
3133 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
3134                                                       const char            *uri_scheme)
3135 {
3136   GDesktopAppInfoLookupIface *iface;
3137   
3138   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
3139
3140   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
3141
3142   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
3143 }