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