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