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