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