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