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