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