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