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