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