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