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