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