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