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