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