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