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