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