If possible, always pass FUSE file:// URIs (such as
[platform/upstream/glib.git] / gio / gdesktopappinfo.c
1 /* GIO - GLib Input, Output and Streaming Library
2  * 
3  * Copyright (C) 2006-2007 Red Hat, Inc.
4  * Copyright © 2007 Ryan Lortie
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Author: Alexander Larsson <alexl@redhat.com>
22  */
23
24 #include "config.h"
25
26 #include <errno.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/wait.h>
30
31 #ifdef HAVE_CRT_EXTERNS_H
32 #include <crt_externs.h>
33 #endif
34
35 #include "gcontenttypeprivate.h"
36 #include "gdesktopappinfo.h"
37 #include "gfile.h"
38 #include "gioerror.h"
39 #include "gthemedicon.h"
40 #include "gfileicon.h"
41 #include <glib/gstdio.h>
42 #include "glibintl.h"
43 #include "giomodule-priv.h"
44 #include "gappinfo.h"
45
46 #include "gioalias.h"
47
48 /**
49  * SECTION:gdesktopappinfo
50  * @short_description: Application information from desktop files
51  * @include: gio/gdesktopappinfo.h 
52  * 
53  * #GDesktopAppInfo is an implementation of #GAppInfo based on
54  * desktop files.
55  *
56  **/
57
58 #define DEFAULT_APPLICATIONS_GROUP  "Default Applications" 
59 #define ADDED_ASSOCIATIONS_GROUP    "Added Associations" 
60 #define REMOVED_ASSOCIATIONS_GROUP  "Removed Associations" 
61 #define MIME_CACHE_GROUP            "MIME Cache"
62
63 static void     g_desktop_app_info_iface_init         (GAppInfoIface    *iface);
64 static GList *  get_all_desktop_entries_for_mime_type (const char       *base_mime_type);
65 static void     mime_info_cache_reload                (const char       *dir);
66 static gboolean g_desktop_app_info_ensure_saved       (GDesktopAppInfo  *info,
67                                                        GError          **error);
68
69 /**
70  * GDesktopAppInfo:
71  * 
72  * Information about an installed application from a desktop file.
73  */
74 struct _GDesktopAppInfo
75 {
76   GObject parent_instance;
77
78   char *desktop_id;
79   char *filename;
80
81   char *name;
82   /* FIXME: what about GenericName ? */
83   char *comment;
84   char *icon_name;
85   GIcon *icon;
86   char **only_show_in;
87   char **not_show_in;
88   char *try_exec;
89   char *exec;
90   char *binary;
91   char *path;
92
93   guint nodisplay       : 1;
94   guint hidden          : 1;
95   guint terminal        : 1;
96   guint startup_notify  : 1;
97   /* FIXME: what about StartupWMClass ? */
98 };
99
100 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
101                          G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO,
102                                                 g_desktop_app_info_iface_init))
103
104 static gpointer
105 search_path_init (gpointer data)
106 {
107   char **args = NULL;
108   const char * const *data_dirs;
109   const char *user_data_dir;
110   int i, length, j;
111
112   data_dirs = g_get_system_data_dirs ();
113   length = g_strv_length ((char **) data_dirs);
114   
115   args = g_new (char *, length + 2);
116   
117   j = 0;
118   user_data_dir = g_get_user_data_dir ();
119   args[j++] = g_build_filename (user_data_dir, "applications", NULL);
120   for (i = 0; i < length; i++)
121     args[j++] = g_build_filename (data_dirs[i],
122                                   "applications", NULL);
123   args[j++] = NULL;
124   
125   return args;
126 }
127   
128 static const char * const *
129 get_applications_search_path (void)
130 {
131   static GOnce once_init = G_ONCE_INIT;
132   return g_once (&once_init, search_path_init, NULL);
133 }
134
135 static void
136 g_desktop_app_info_finalize (GObject *object)
137 {
138   GDesktopAppInfo *info;
139
140   info = G_DESKTOP_APP_INFO (object);
141
142   g_free (info->desktop_id);
143   g_free (info->filename);
144   g_free (info->name);
145   g_free (info->comment);
146   g_free (info->icon_name);
147   if (info->icon)
148     g_object_unref (info->icon);
149   g_strfreev (info->only_show_in);
150   g_strfreev (info->not_show_in);
151   g_free (info->try_exec);
152   g_free (info->exec);
153   g_free (info->binary);
154   g_free (info->path);
155   
156   G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
157 }
158
159 static void
160 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
161 {
162   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
163   
164   gobject_class->finalize = g_desktop_app_info_finalize;
165 }
166
167 static void
168 g_desktop_app_info_init (GDesktopAppInfo *local)
169 {
170 }
171
172 static char *
173 binary_from_exec (const char *exec)
174 {
175   const char *p, *start;
176   
177   p = exec;
178   while (*p == ' ')
179     p++;
180   start = p;
181   while (*p != ' ' && *p != 0)
182     p++;
183   
184   return g_strndup (start, p - start);
185   
186 }
187
188 /**
189  * g_desktop_app_info_new_from_keyfile:
190  * @key_file: an opened #GKeyFile
191  * 
192  * Creates a new #GDesktopAppInfo.
193  *
194  * Returns: a new #GDesktopAppInfo or %NULL on error.
195  *
196  * Since: 2.18
197  **/
198 GDesktopAppInfo *
199 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
200 {
201   GDesktopAppInfo *info;
202   char *start_group;
203   char *type;
204   char *try_exec;
205   
206   start_group = g_key_file_get_start_group (key_file);
207   if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
208     {
209       g_free (start_group);
210       return NULL;
211     }
212   g_free (start_group);
213
214   type = g_key_file_get_string (key_file,
215                                 G_KEY_FILE_DESKTOP_GROUP,
216                                 G_KEY_FILE_DESKTOP_KEY_TYPE,
217                                 NULL);
218   if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
219     {
220       g_free (type);
221       return NULL;
222     }
223   g_free (type);
224
225   try_exec = g_key_file_get_string (key_file,
226                                     G_KEY_FILE_DESKTOP_GROUP,
227                                     G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
228                                     NULL);
229   if (try_exec && try_exec[0] != '\0')
230     {
231       char *t;
232       t = g_find_program_in_path (try_exec);
233       if (t == NULL)
234         {
235           g_free (try_exec);
236           return NULL;
237         }
238       g_free (t);
239     }
240
241   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
242   info->filename = NULL;
243
244   info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
245   info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
246   info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
247   info->icon_name =  g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
248   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);
249   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);
250   info->try_exec = try_exec;
251   info->exec = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_EXEC, NULL);
252   info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
253   info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
254   info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
255   info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
256   
257   info->icon = NULL;
258   if (info->icon_name)
259     {
260       if (g_path_is_absolute (info->icon_name))
261         {
262           GFile *file;
263           
264           file = g_file_new_for_path (info->icon_name);
265           info->icon = g_file_icon_new (file);
266           g_object_unref (file);
267         }
268       else
269         info->icon = g_themed_icon_new (info->icon_name);
270     }
271   
272   if (info->exec)
273     info->binary = binary_from_exec (info->exec);
274   
275   if (info->path && info->path[0] == '\0')
276     {
277       g_free (info->path);
278       info->path = NULL;
279     }
280
281   return info;
282 }
283
284 /**
285  * g_desktop_app_info_new_from_filename:
286  * @filename: the path of a desktop file, in the GLib filename encoding
287  * 
288  * Creates a new #GDesktopAppInfo.
289  *
290  * Returns: a new #GDesktopAppInfo or %NULL on error.
291  **/
292 GDesktopAppInfo *
293 g_desktop_app_info_new_from_filename (const char *filename)
294 {
295   GKeyFile *key_file;
296   GDesktopAppInfo *info = NULL;
297
298   key_file = g_key_file_new ();
299   
300   if (g_key_file_load_from_file (key_file,
301                                  filename,
302                                  G_KEY_FILE_NONE,
303                                  NULL))
304     {
305       info = g_desktop_app_info_new_from_keyfile (key_file);
306       if (info)
307         info->filename = g_strdup (filename);
308     }  
309
310   g_key_file_free (key_file);
311
312   return info;
313 }
314
315 /**
316  * g_desktop_app_info_new:
317  * @desktop_id: the desktop file id
318  * 
319  * Creates a new #GDesktopAppInfo.
320  * 
321  * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
322  **/
323 GDesktopAppInfo *
324 g_desktop_app_info_new (const char *desktop_id)
325 {
326   GDesktopAppInfo *appinfo;
327   const char * const *dirs;
328   char *basename;
329   int i;
330
331   dirs = get_applications_search_path ();
332
333   basename = g_strdup (desktop_id);
334   
335   for (i = 0; dirs[i] != NULL; i++)
336     {
337       char *filename;
338       char *p;
339
340       filename = g_build_filename (dirs[i], desktop_id, NULL);
341       appinfo = g_desktop_app_info_new_from_filename (filename);
342       g_free (filename);
343       if (appinfo != NULL)
344         goto found;
345
346       p = basename;
347       while ((p = strchr (p, '-')) != NULL)
348         {
349           *p = '/';
350           
351           filename = g_build_filename (dirs[i], basename, NULL);
352           appinfo = g_desktop_app_info_new_from_filename (filename);
353           g_free (filename);
354           if (appinfo != NULL)
355             goto found;
356           *p = '-';
357           p++;
358         }
359     }
360   
361   g_free (basename);
362   return NULL;
363
364  found:
365   g_free (basename);
366   
367   appinfo->desktop_id = g_strdup (desktop_id);
368
369   if (g_desktop_app_info_get_is_hidden (appinfo))
370     {
371       g_object_unref (appinfo);
372       appinfo = NULL;
373     }
374   
375   return appinfo;
376 }
377
378 static GAppInfo *
379 g_desktop_app_info_dup (GAppInfo *appinfo)
380 {
381   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
382   GDesktopAppInfo *new_info;
383   
384   new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
385
386   new_info->filename = g_strdup (info->filename);
387   new_info->desktop_id = g_strdup (info->desktop_id);
388   
389   new_info->name = g_strdup (info->name);
390   new_info->comment = g_strdup (info->comment);
391   new_info->nodisplay = info->nodisplay;
392   new_info->icon_name = g_strdup (info->icon_name);
393   new_info->icon = g_object_ref (info->icon);
394   new_info->only_show_in = g_strdupv (info->only_show_in);
395   new_info->not_show_in = g_strdupv (info->not_show_in);
396   new_info->try_exec = g_strdup (info->try_exec);
397   new_info->exec = g_strdup (info->exec);
398   new_info->binary = g_strdup (info->binary);
399   new_info->path = g_strdup (info->path);
400   new_info->hidden = info->hidden;
401   new_info->terminal = info->terminal;
402   new_info->startup_notify = info->startup_notify;
403   
404   return G_APP_INFO (new_info);
405 }
406
407 static gboolean
408 g_desktop_app_info_equal (GAppInfo *appinfo1,
409                           GAppInfo *appinfo2)
410 {
411   GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
412   GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
413
414   if (info1->desktop_id == NULL ||
415       info2->desktop_id == NULL)
416     return info1 == info2;
417
418   return strcmp (info1->desktop_id, info2->desktop_id) == 0;
419 }
420
421 static const char *
422 g_desktop_app_info_get_id (GAppInfo *appinfo)
423 {
424   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
425
426   return info->desktop_id;
427 }
428
429 static const char *
430 g_desktop_app_info_get_name (GAppInfo *appinfo)
431 {
432   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
433
434   if (info->name == NULL)
435     return _("Unnamed");
436   return info->name;
437 }
438
439 /**
440  * g_desktop_app_info_get_is_hidden:
441  * @info: a #GDesktopAppInfo.
442  *
443  * A desktop file is hidden if the Hidden key in it is
444  * set to True.
445  *
446  * Returns: %TRUE if hidden, %FALSE otherwise. 
447  **/
448 gboolean
449 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
450 {
451   return info->hidden;
452 }
453
454 static const char *
455 g_desktop_app_info_get_description (GAppInfo *appinfo)
456 {
457   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
458   
459   return info->comment;
460 }
461
462 static const char *
463 g_desktop_app_info_get_executable (GAppInfo *appinfo)
464 {
465   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
466   
467   return info->binary;
468 }
469
470 static GIcon *
471 g_desktop_app_info_get_icon (GAppInfo *appinfo)
472 {
473   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
474
475   return info->icon;
476 }
477
478 static char *
479 expand_macro_single (char macro, char *uri)
480 {
481   GFile *file;
482   char *result = NULL;
483   char *path, *name;
484
485   file = g_file_new_for_uri (uri);
486   path = g_file_get_path (file);
487   g_object_unref (file);
488   
489   switch (macro)
490     {
491     case 'u':
492     case 'U':   
493       result = g_shell_quote (uri);
494       break;
495     case 'f':
496     case 'F':
497       if (path)
498         result = g_shell_quote (path);
499       break;
500     case 'd':
501     case 'D':
502       if (path)
503         {
504           name = g_path_get_dirname (path);
505           result = g_shell_quote (name);
506           g_free (name);
507         }
508       break;
509     case 'n':
510     case 'N':
511       if (path)
512         {
513           name = g_path_get_basename (path);
514           result = g_shell_quote (name);
515           g_free (name);
516         }
517       break;
518     }
519
520   g_free (path);
521   
522   return result;
523 }
524
525 static void
526 expand_macro (char              macro, 
527               GString          *exec, 
528               GDesktopAppInfo  *info, 
529               GList           **uri_list)
530 {
531   GList *uris = *uri_list;
532   char *expanded;
533   gboolean force_file_uri;
534   char force_file_uri_macro;
535
536   g_return_if_fail (exec != NULL);
537
538   /* On %u and %U, pass POSIX file path pointing to the URI via
539    * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
540    * running or the URI doesn't have a POSIX file path via FUSE
541    * we'll just pass the URI.
542    */
543   switch (macro)
544     {
545     case 'u':
546       force_file_uri_macro = 'f';
547       force_file_uri = TRUE;
548       break;
549     case 'U':
550       force_file_uri_macro = 'F';
551       force_file_uri = TRUE;
552       break;
553     default:
554       force_file_uri_macro = macro;
555       force_file_uri = FALSE;
556       break;
557     }
558
559   switch (macro)
560     {
561     case 'u':
562     case 'f':
563     case 'd':
564     case 'n':
565       if (uris)
566         {
567           if (!force_file_uri)
568             {
569               expanded = expand_macro_single (macro, uris->data);
570             }
571           else
572             {
573               expanded = expand_macro_single (force_file_uri_macro, uris->data);
574               if (expanded == NULL)
575                 expanded = expand_macro_single (macro, uris->data);
576             }
577
578           if (expanded)
579             {
580               g_string_append (exec, expanded);
581               g_free (expanded);
582             }
583           uris = uris->next;
584         }
585
586       break;
587
588     case 'U':   
589     case 'F':
590     case 'D':
591     case 'N':
592       while (uris)
593         {
594           if (!force_file_uri)
595             {
596               expanded = expand_macro_single (macro, uris->data);
597             }
598           else
599             {
600               expanded = expand_macro_single (force_file_uri_macro, uris->data);
601               if (expanded == NULL)
602                 expanded = expand_macro_single (macro, uris->data);
603             }
604
605           if (expanded)
606             {
607               g_string_append (exec, expanded);
608               g_free (expanded);
609             }
610           
611           uris = uris->next;
612           
613           if (uris != NULL && expanded)
614             g_string_append_c (exec, ' ');
615         }
616
617       break;
618
619     case 'i':
620       if (info->icon_name)
621         {
622           g_string_append (exec, "--icon ");
623           g_string_append (exec, info->icon_name);
624         }
625       break;
626
627     case 'c':
628       if (info->name) 
629         g_string_append (exec, info->name);
630       break;
631
632     case 'k':
633       if (info->filename) 
634         g_string_append (exec, info->filename);
635       break;
636
637     case 'm': /* deprecated */
638       break;
639
640     case '%':
641       g_string_append_c (exec, '%');
642       break;
643     }
644   
645   *uri_list = uris;
646 }
647
648 static gboolean
649 expand_application_parameters (GDesktopAppInfo   *info,
650                                GList            **uris,
651                                int               *argc,
652                                char            ***argv,
653                                GError           **error)
654 {
655   GList *uri_list = *uris;
656   const char *p = info->exec;
657   GString *expanded_exec = g_string_new (NULL);
658   gboolean res;
659   
660   if (info->exec == NULL)
661     {
662       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
663                            _("Desktop file didn't specify Exec field"));
664       return FALSE;
665     }
666   
667   while (*p)
668     {
669       if (p[0] == '%' && p[1] != '\0')
670         {
671           expand_macro (p[1], expanded_exec, info, uris);
672           p++;
673         }
674       else
675         g_string_append_c (expanded_exec, *p);
676       
677       p++;
678     }
679   
680   /* No file substitutions */
681   if (uri_list == *uris && uri_list != NULL)
682     {
683       /* If there is no macro default to %f. This is also what KDE does */
684       g_string_append_c (expanded_exec, ' ');
685       expand_macro ('f', expanded_exec, info, uris);
686     }
687   
688   res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
689   g_string_free (expanded_exec, TRUE);
690   return res;
691 }
692
693 static gboolean
694 prepend_terminal_to_vector (int    *argc,
695                             char ***argv)
696 {
697 #ifndef G_OS_WIN32
698   char **real_argv;
699   int real_argc;
700   int i, j;
701   char **term_argv = NULL;
702   int term_argc = 0;
703   char *check;
704   char **the_argv;
705   
706   g_return_val_if_fail (argc != NULL, FALSE);
707   g_return_val_if_fail (argv != NULL, FALSE);
708         
709   /* sanity */
710   if(*argv == NULL)
711     *argc = 0;
712   
713   the_argv = *argv;
714
715   /* compute size if not given */
716   if (*argc < 0)
717     {
718       for (i = 0; the_argv[i] != NULL; i++)
719         ;
720       *argc = i;
721     }
722   
723   term_argc = 2;
724   term_argv = g_new0 (char *, 3);
725
726   check = g_find_program_in_path ("gnome-terminal");
727   if (check != NULL)
728     {
729       term_argv[0] = check;
730       /* Note that gnome-terminal takes -x and
731        * as -e in gnome-terminal is broken we use that. */
732       term_argv[1] = g_strdup ("-x");
733     }
734   else
735     {
736       if (check == NULL)
737         check = g_find_program_in_path ("nxterm");
738       if (check == NULL)
739         check = g_find_program_in_path ("color-xterm");
740       if (check == NULL)
741         check = g_find_program_in_path ("rxvt");
742       if (check == NULL)
743         check = g_find_program_in_path ("xterm");
744       if (check == NULL)
745         check = g_find_program_in_path ("dtterm");
746       if (check == NULL)
747         {
748           check = g_strdup ("xterm");
749           g_warning ("couldn't find a terminal, falling back to xterm");
750         }
751       term_argv[0] = check;
752       term_argv[1] = g_strdup ("-e");
753     }
754
755   real_argc = term_argc + *argc;
756   real_argv = g_new (char *, real_argc + 1);
757   
758   for (i = 0; i < term_argc; i++)
759     real_argv[i] = term_argv[i];
760   
761   for (j = 0; j < *argc; j++, i++)
762     real_argv[i] = (char *)the_argv[j];
763   
764   real_argv[i] = NULL;
765   
766   g_free (*argv);
767   *argv = real_argv;
768   *argc = real_argc;
769   
770   /* we use g_free here as we sucked all the inner strings
771    * out from it into real_argv */
772   g_free (term_argv);
773   return TRUE;
774 #else
775   return FALSE;
776 #endif /* G_OS_WIN32 */
777 }
778
779 /* '=' is the new '\0'.
780  * DO NOT CALL unless at least one string ends with '='
781  */
782 static gboolean
783 is_env (const char *a,
784         const char *b)
785 {
786   while (*a == *b)
787   {
788     if (*a == 0 || *b == 0)
789       return FALSE;
790     
791     if (*a == '=')
792       return TRUE;
793
794     a++;
795     b++;
796   }
797
798   return FALSE;
799 }
800
801 /* free with g_strfreev */
802 static char **
803 replace_env_var (char       **old_environ,
804                  const char  *env_var,
805                  const char  *new_value)
806 {
807   int length, new_length;
808   int index, new_index;
809   char **new_environ;
810   int i, new_i;
811
812   /* do two things at once:
813    *  - discover the length of the environment ('length')
814    *  - find the location (if any) of the env var ('index')
815    */
816   index = -1;
817   for (length = 0; old_environ[length]; length++)
818     {
819       /* if we already have it in our environment, replace */
820       if (is_env (old_environ[length], env_var))
821         index = length;
822     }
823
824   
825   /* no current env var, no desired env value.
826    * this is easy :)
827    */
828   if (new_value == NULL && index == -1)
829     return old_environ;
830
831   /* in all cases now, we will be using a modified environment.
832    * determine its length and allocated it.
833    * 
834    * after this block:
835    *   new_index   = location to insert, if any
836    *   new_length  = length of the new array
837    *   new_environ = the pointer array for the new environment
838    */
839   
840   if (new_value == NULL && index >= 0)
841     {
842       /* in this case, we will be removing an entry */
843       new_length = length - 1;
844       new_index = -1;
845     }
846   else if (new_value != NULL && index < 0)
847     {
848       /* in this case, we will be adding an entry to the end */
849       new_length = length + 1;
850       new_index = length;
851     }
852   else
853     /* in this case, we will be replacing the existing entry */
854     {
855       new_length = length;
856       new_index = index;
857     }
858
859   new_environ = g_malloc (sizeof (char *) * (new_length + 1));
860   new_environ[new_length] = NULL;
861
862   /* now we do the copying.
863    * for each entry in the new environment, we decide what to do
864    */
865   
866   i = 0;
867   for (new_i = 0; new_i < new_length; new_i++)
868     {
869       if (new_i == new_index)
870         {
871           /* insert our new item */
872           new_environ[new_i] = g_strconcat (env_var,
873                                             "=",
874                                             new_value,
875                                             NULL);
876           
877           /* if we had an old entry, skip it now */
878           if (index >= 0)
879             i++;
880         }
881       else
882         {
883           /* if this is the old DESKTOP_STARTUP_ID, skip it */
884           if (i == index)
885             i++;
886           
887           /* copy an old item */
888           new_environ[new_i] = g_strdup (old_environ[i]);
889           i++;
890         }
891     }
892
893   g_strfreev (old_environ);
894   
895   return new_environ;
896 }
897
898 static GList *
899 uri_list_segment_to_files (GList *start,
900                            GList *end)
901 {
902   GList *res;
903   GFile *file;
904
905   res = NULL;
906   while (start != NULL && start != end)
907     {
908       file = g_file_new_for_uri ((char *)start->data);
909       res = g_list_prepend (res, file);
910       start = start->next;
911     }
912
913   return g_list_reverse (res);
914 }
915
916 #ifdef HAVE__NSGETENVIRON
917 #define environ (*_NSGetEnviron())
918 #elif !defined(G_OS_WIN32)
919
920 /* According to the Single Unix Specification, environ is not in 
921  *  * any system header, although unistd.h often declares it.
922  *   */
923 extern char **environ;
924 #endif
925
926 static gboolean
927 g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
928                                 GList              *uris,
929                                 GAppLaunchContext  *launch_context,
930                                 GError            **error)
931 {
932   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
933   gboolean completed = FALSE;
934   GList *old_uris;
935   GList *launched_files;
936   char **envp;
937   char **argv;
938   int argc;
939   char *display;
940   char *sn_id;
941
942   g_return_val_if_fail (appinfo != NULL, FALSE);
943
944   argv = NULL;
945   envp = NULL;
946       
947   do 
948     {
949       old_uris = uris;
950       if (!expand_application_parameters (info, &uris,
951                                           &argc, &argv, error))
952         goto out;
953       
954       if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
955         {
956           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
957                                _("Unable to find terminal required for application"));
958           goto out;
959         }
960
961       sn_id = NULL;
962       if (launch_context)
963         {
964           launched_files = uri_list_segment_to_files (old_uris, uris);
965           
966           display = g_app_launch_context_get_display (launch_context,
967                                                       appinfo,
968                                                       launched_files);
969
970           sn_id = NULL;
971           if (info->startup_notify)
972             sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
973                                                                 appinfo,
974                                                                 launched_files);
975           
976           if (display || sn_id)
977             {
978 #ifdef G_OS_WIN32
979               /* FIXME */
980               envp = g_new0 (char *, 1);
981 #else
982               envp = g_strdupv (environ);
983 #endif
984               
985               if (display)
986                 envp = replace_env_var (envp,
987                                         "DISPLAY",
988                                         display);
989               
990               if (sn_id)
991                 envp = replace_env_var (envp,
992                                         "DESKTOP_STARTUP_ID",
993                                         sn_id);
994             }
995
996           g_free (display);
997           
998           g_list_foreach (launched_files, (GFunc)g_object_unref, NULL);
999           g_list_free (launched_files);
1000         }
1001       
1002       if (!g_spawn_async (info->path,  /* working directory */
1003                           argv,
1004                           envp,
1005                           G_SPAWN_SEARCH_PATH /* flags */,
1006                           NULL /* child_setup */,
1007                           NULL /* data */,
1008                           NULL /* child_pid */,
1009                           error))
1010         {
1011           if (sn_id)
1012             {
1013               g_app_launch_context_launch_failed (launch_context, sn_id);
1014               g_free (sn_id);
1015             }
1016           goto out;
1017         }
1018
1019       
1020       g_free (sn_id);
1021       
1022       g_strfreev (envp);
1023       g_strfreev (argv);
1024       envp = NULL;
1025       argv = NULL;
1026     }
1027   while (uris != NULL);
1028
1029   completed = TRUE;
1030
1031  out:
1032   g_strfreev (argv);
1033   g_strfreev (envp);
1034
1035   return completed;
1036 }
1037
1038 static gboolean
1039 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
1040 {
1041   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1042  
1043   return info->exec && 
1044     ((strstr (info->exec, "%u") != NULL) ||
1045      (strstr (info->exec, "%U") != NULL));
1046 }
1047
1048 static gboolean
1049 g_desktop_app_info_supports_files (GAppInfo *appinfo)
1050 {
1051   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1052  
1053   return info->exec && 
1054     ((strstr (info->exec, "%f") != NULL) ||
1055      (strstr (info->exec, "%F") != NULL));
1056 }
1057
1058 static gboolean
1059 g_desktop_app_info_launch (GAppInfo           *appinfo,
1060                            GList              *files,
1061                            GAppLaunchContext  *launch_context,
1062                            GError            **error)
1063 {
1064   GList *uris;
1065   char *uri;
1066   gboolean res;
1067
1068   uris = NULL;
1069   while (files)
1070     {
1071       uri = g_file_get_uri (files->data);
1072       uris = g_list_prepend (uris, uri);
1073       files = files->next;
1074     }
1075   
1076   uris = g_list_reverse (uris);
1077   
1078   res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
1079   
1080   g_list_foreach  (uris, (GFunc)g_free, NULL);
1081   g_list_free (uris);
1082   
1083   return res;
1084 }
1085
1086 G_LOCK_DEFINE_STATIC (g_desktop_env);
1087 static gchar *g_desktop_env = NULL;
1088
1089 /**
1090  * g_desktop_app_info_set_desktop_env:
1091  * @desktop_env: a string specifying what desktop this is
1092  *
1093  * Sets the name of the desktop that the application is running in.
1094  * This is used by g_app_info_should_show() to evaluate the
1095  * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal>
1096  * desktop entry fields.
1097  *
1098  * The <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Desktop 
1099  * Menu specification</ulink> recognizes the following:
1100  * <simplelist>
1101  *   <member>GNOME</member>
1102  *   <member>KDE</member>
1103  *   <member>ROX</member>
1104  *   <member>XFCE</member>
1105  *   <member>Old</member> 
1106  * </simplelist>
1107  *
1108  * Should be called only once; subsequent calls are ignored.
1109  */
1110 void
1111 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
1112 {
1113   G_LOCK (g_desktop_env);
1114   if (!g_desktop_env)
1115     g_desktop_env = g_strdup (desktop_env);
1116   G_UNLOCK (g_desktop_env);
1117 }
1118
1119 static gboolean
1120 g_desktop_app_info_should_show (GAppInfo *appinfo)
1121 {
1122   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1123   gboolean found;
1124   const gchar *desktop_env;
1125   int i;
1126
1127   if (info->nodisplay)
1128     return FALSE;
1129
1130   G_LOCK (g_desktop_env);
1131   desktop_env = g_desktop_env;
1132   G_UNLOCK (g_desktop_env);
1133
1134   if (info->only_show_in)
1135     {
1136       if (desktop_env == NULL)
1137         return FALSE;
1138       
1139       found = FALSE;
1140       for (i = 0; info->only_show_in[i] != NULL; i++)
1141         {
1142           if (strcmp (info->only_show_in[i], desktop_env) == 0)
1143             {
1144               found = TRUE;
1145               break;
1146             }
1147         }
1148       if (!found)
1149         return FALSE;
1150     }
1151
1152   if (info->not_show_in && desktop_env)
1153     {
1154       for (i = 0; info->not_show_in[i] != NULL; i++)
1155         {
1156           if (strcmp (info->not_show_in[i], desktop_env) == 0)
1157             return FALSE;
1158         }
1159     }
1160   
1161   return TRUE;
1162 }
1163
1164 typedef enum {
1165   APP_DIR,
1166   MIMETYPE_DIR
1167 } DirType;
1168
1169 static char *
1170 ensure_dir (DirType   type,
1171             GError  **error)
1172 {
1173   char *path, *display_name;
1174   int errsv;
1175
1176   if (type == APP_DIR)
1177     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1178   else
1179     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
1180
1181   errno = 0;
1182   if (g_mkdir_with_parents (path, 0700) == 0)
1183     return path;
1184
1185   errsv = errno;
1186   display_name = g_filename_display_name (path);
1187   if (type == APP_DIR)
1188     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1189                  _("Can't create user application configuration folder %s: %s"),
1190                  display_name, g_strerror (errsv));
1191   else
1192     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
1193                  _("Can't create user MIME configuration folder %s: %s"),
1194                  display_name, g_strerror (errsv));
1195
1196   g_free (display_name);
1197   g_free (path);
1198
1199   return NULL;
1200 }
1201
1202 static gboolean
1203 update_mimeapps_list (const char  *desktop_id, 
1204                       const char  *content_type, 
1205                       gboolean     add_at_start, 
1206                       gboolean     add_at_end, 
1207                       gboolean     remove, 
1208                       GError     **error)
1209 {
1210   char *dirname, *filename;
1211   GKeyFile *key_file;
1212   gboolean load_succeeded, res;
1213   char **old_list;
1214   char **list;
1215   gsize length, data_size;
1216   char *data;
1217   int i, j, k;
1218   char **content_types;
1219
1220   /* Don't add both at start and end */
1221   g_assert (!(add_at_start && add_at_end));
1222   
1223   dirname = ensure_dir (APP_DIR, error);
1224   if (!dirname)
1225     return FALSE;
1226
1227   filename = g_build_filename (dirname, "mimeapps.list", NULL);
1228   g_free (dirname);
1229
1230   key_file = g_key_file_new ();
1231   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
1232   if (!load_succeeded || !g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP))
1233     {
1234       g_key_file_free (key_file);
1235       key_file = g_key_file_new ();
1236     }
1237
1238   if (content_type)
1239     {
1240       content_types = g_new (char *, 2);
1241       content_types[0] = g_strdup (content_type);
1242       content_types[1] = NULL;
1243     }
1244   else
1245     {
1246       content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
1247     }
1248
1249   for (k = 0; content_types && content_types[k]; k++)
1250     { 
1251       /* Add to the right place in the list */
1252   
1253       length = 0;
1254       old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
1255                                              content_types[k], &length, NULL);
1256
1257       list = g_new (char *, 1 + length + 1);
1258
1259       i = 0;
1260       if (add_at_start)
1261         list[i++] = g_strdup (desktop_id);
1262       if (old_list)
1263         {
1264           for (j = 0; old_list[j] != NULL; j++)
1265             {
1266               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1267                 list[i++] = g_strdup (old_list[j]);
1268             }
1269         }
1270       if (add_at_end)
1271         list[i++] = g_strdup (desktop_id);
1272       list[i] = NULL;
1273   
1274       g_strfreev (old_list);
1275
1276       if (list[0] == NULL || desktop_id == NULL)
1277         g_key_file_remove_key (key_file,
1278                                ADDED_ASSOCIATIONS_GROUP,
1279                                content_types[k],
1280                                NULL);
1281       else
1282         g_key_file_set_string_list (key_file,
1283                                     ADDED_ASSOCIATIONS_GROUP,
1284                                     content_types[k],
1285                                     (const char * const *)list, i);
1286    
1287       g_strfreev (list);
1288     }
1289   
1290   if (content_type)
1291     {
1292       /* reuse the list from above */
1293     }
1294   else
1295     {
1296       g_strfreev (content_types);
1297       content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
1298     }
1299
1300   for (k = 0; content_types && content_types[k]; k++) 
1301     {
1302       /* Remove from removed associations group (unless remove) */
1303   
1304       length = 0;
1305       old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
1306                                              content_types[k], &length, NULL);
1307
1308       list = g_new (char *, 1 + length + 1);
1309
1310       i = 0;
1311       if (remove)
1312         list[i++] = g_strdup (desktop_id);
1313       if (old_list)
1314         {
1315           for (j = 0; old_list[j] != NULL; j++)
1316             {
1317               if (g_strcmp0 (old_list[j], desktop_id) != 0)
1318                 list[i++] = g_strdup (old_list[j]);
1319             }
1320         }
1321       list[i] = NULL;
1322   
1323       g_strfreev (old_list);
1324
1325       if (list[0] == NULL || desktop_id == NULL)
1326         g_key_file_remove_key (key_file,
1327                                REMOVED_ASSOCIATIONS_GROUP,
1328                                content_types[k],
1329                                NULL);
1330       else
1331         g_key_file_set_string_list (key_file,
1332                                     REMOVED_ASSOCIATIONS_GROUP,
1333                                     content_types[k],
1334                                     (const char * const *)list, i);
1335
1336       g_strfreev (list);
1337     }
1338   
1339   g_strfreev (content_types);  
1340
1341   data = g_key_file_to_data (key_file, &data_size, error);
1342   g_key_file_free (key_file);
1343   
1344   res = g_file_set_contents (filename, data, data_size, error);
1345
1346   mime_info_cache_reload (NULL);
1347                           
1348   g_free (filename);
1349   g_free (data);
1350   
1351   return res;
1352 }
1353
1354 static gboolean
1355 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
1356                                             const char  *content_type,
1357                                             GError     **error)
1358 {
1359   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1360
1361   if (!g_desktop_app_info_ensure_saved (info, error))
1362     return FALSE;  
1363   
1364   return update_mimeapps_list (info->desktop_id, content_type, TRUE, FALSE, FALSE, error);
1365 }
1366
1367 static void
1368 update_program_done (GPid     pid,
1369                      gint     status,
1370                      gpointer data)
1371 {
1372   /* Did the application exit correctly */
1373   if (WIFEXITED (status) &&
1374       WEXITSTATUS (status) == 0)
1375     {
1376       /* Here we could clean out any caches in use */
1377     }
1378 }
1379
1380 static void
1381 run_update_command (char *command,
1382                     char *subdir)
1383 {
1384         char *argv[3] = {
1385                 NULL,
1386                 NULL,
1387                 NULL,
1388         };
1389         GPid pid = 0;
1390         GError *error = NULL;
1391
1392         argv[0] = command;
1393         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
1394
1395         if (g_spawn_async ("/", argv,
1396                            NULL,       /* envp */
1397                            G_SPAWN_SEARCH_PATH |
1398                            G_SPAWN_STDOUT_TO_DEV_NULL |
1399                            G_SPAWN_STDERR_TO_DEV_NULL |
1400                            G_SPAWN_DO_NOT_REAP_CHILD,
1401                            NULL, NULL, /* No setup function */
1402                            &pid,
1403                            NULL)) 
1404           g_child_watch_add (pid, update_program_done, NULL);
1405         else
1406           {
1407             /* If we get an error at this point, it's quite likely the user doesn't
1408              * have an installed copy of either 'update-mime-database' or
1409              * 'update-desktop-database'.  I don't think we want to popup an error
1410              * dialog at this point, so we just do a g_warning to give the user a
1411              * chance of debugging it.
1412              */
1413             g_warning ("%s", error->message);
1414           }
1415         
1416         g_free (argv[1]);
1417 }
1418
1419 static gboolean
1420 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
1421                                                  const char  *extension,
1422                                                  GError     **error)
1423 {
1424   char *filename, *basename, *mimetype;
1425   char *dirname;
1426   gboolean res;
1427
1428   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
1429     return FALSE;  
1430   
1431   dirname = ensure_dir (MIMETYPE_DIR, error);
1432   if (!dirname)
1433     return FALSE;
1434   
1435   basename = g_strdup_printf ("user-extension-%s.xml", extension);
1436   filename = g_build_filename (dirname, basename, NULL);
1437   g_free (basename);
1438   g_free (dirname);
1439
1440   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
1441   
1442   if (!g_file_test (filename, G_FILE_TEST_EXISTS)) 
1443     {
1444       char *contents;
1445
1446       contents =
1447         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1448                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
1449                          " <mime-type type=\"%s\">\n"
1450                          "  <comment>%s document</comment>\n"
1451                          "  <glob pattern=\"*.%s\"/>\n"
1452                          " </mime-type>\n"
1453                          "</mime-info>\n", mimetype, extension, extension);
1454
1455       g_file_set_contents (filename, contents, -1, NULL);
1456       g_free (contents);
1457
1458       run_update_command ("update-mime-database", "mime");
1459     }
1460   g_free (filename);
1461   
1462   res = g_desktop_app_info_set_as_default_for_type (appinfo,
1463                                                     mimetype,
1464                                                     error);
1465
1466   g_free (mimetype);
1467   
1468   return res;
1469 }
1470
1471 static gboolean
1472 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
1473                                       const char  *content_type,
1474                                       GError     **error)
1475 {
1476   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1477
1478   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1479     return FALSE;  
1480   
1481   return update_mimeapps_list (info->desktop_id, content_type, FALSE, TRUE, FALSE, error);
1482 }
1483
1484 static gboolean
1485 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
1486 {
1487   return TRUE;
1488 }
1489
1490 static gboolean
1491 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
1492                                          const char  *content_type,
1493                                          GError     **error)
1494 {
1495   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1496
1497   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
1498     return FALSE;
1499   
1500   return update_mimeapps_list (info->desktop_id, content_type, FALSE, FALSE, TRUE, error);
1501 }
1502
1503 static gboolean
1504 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
1505                                  GError **error)
1506 {
1507   GKeyFile *key_file;
1508   char *dirname;
1509   char *filename;
1510   char *data, *desktop_id;
1511   gsize data_size;
1512   int fd;
1513   gboolean res;
1514   
1515   if (info->filename != NULL)
1516     return TRUE;
1517
1518   /* This is only used for object created with
1519    * g_app_info_create_from_commandline. All other
1520    * object should have a filename
1521    */
1522   
1523   dirname = ensure_dir (APP_DIR, error);
1524   if (!dirname)
1525     return FALSE;
1526   
1527   key_file = g_key_file_new ();
1528
1529   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1530                          "Encoding", "UTF-8");
1531   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1532                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
1533   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1534                          G_KEY_FILE_DESKTOP_KEY_TYPE,
1535                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
1536   if (info->terminal) 
1537     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1538                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
1539
1540   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1541                          G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
1542
1543   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1544                          G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
1545
1546   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1547                          G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
1548   
1549   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1550                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
1551
1552   data = g_key_file_to_data (key_file, &data_size, NULL);
1553   g_key_file_free (key_file);
1554
1555   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
1556   filename = g_build_filename (dirname, desktop_id, NULL);
1557   g_free (desktop_id);
1558   g_free (dirname);
1559   
1560   fd = g_mkstemp (filename);
1561   if (fd == -1)
1562     {
1563       char *display_name;
1564
1565       display_name = g_filename_display_name (filename);
1566       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1567                    _("Can't create user desktop file %s"), display_name);
1568       g_free (display_name);
1569       g_free (filename);
1570       g_free (data);
1571       return FALSE;
1572     }
1573
1574   desktop_id = g_path_get_basename (filename);
1575
1576   close (fd);
1577   
1578   res = g_file_set_contents (filename, data, data_size, error);
1579   if (!res)
1580     {
1581       g_free (desktop_id);
1582       g_free (filename);
1583       return FALSE;
1584     }
1585
1586   info->filename = filename;
1587   info->desktop_id = desktop_id;
1588   
1589   run_update_command ("update-desktop-database", "applications");
1590   
1591   return TRUE;
1592 }
1593
1594 static gboolean
1595 g_desktop_app_info_can_delete (GAppInfo *appinfo)
1596 {
1597   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1598
1599   if (info->filename)
1600     return g_access (info->filename, W_OK) == 0;
1601
1602   return FALSE;
1603 }
1604
1605 static gboolean
1606 g_desktop_app_info_delete (GAppInfo *appinfo)
1607 {
1608   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1609   
1610   if (info->filename)
1611     { 
1612       if (g_remove (info->filename) == 0)
1613         {
1614           update_mimeapps_list (info->desktop_id, NULL, FALSE, FALSE, FALSE, NULL);
1615
1616           g_free (info->filename);
1617           info->filename = NULL;
1618           g_free (info->desktop_id);
1619           info->desktop_id = NULL;
1620
1621           return TRUE;
1622         }
1623     }
1624
1625   return FALSE;
1626 }
1627
1628 /**
1629  * g_app_info_create_from_commandline:
1630  * @commandline: the commandline to use
1631  * @application_name: the application name, or %NULL to use @commandline
1632  * @flags: flags that can specify details of the created #GAppInfo
1633  * @error: a #GError location to store the error occuring, %NULL to ignore.
1634  *
1635  * Creates a new #GAppInfo from the given information.
1636  *
1637  * Returns: new #GAppInfo for given command.
1638  **/
1639 GAppInfo *
1640 g_app_info_create_from_commandline (const char           *commandline,
1641                                     const char           *application_name,
1642                                     GAppInfoCreateFlags   flags,
1643                                     GError              **error)
1644 {
1645   char **split;
1646   char *basename;
1647   GDesktopAppInfo *info;
1648
1649   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1650
1651   info->filename = NULL;
1652   info->desktop_id = NULL;
1653   
1654   info->terminal = flags & G_APP_INFO_CREATE_NEEDS_TERMINAL;
1655   info->startup_notify = FALSE;
1656   info->hidden = FALSE;
1657   if (flags & G_APP_INFO_CREATE_SUPPORTS_URIS)
1658     info->exec = g_strconcat (commandline, " %u", NULL);
1659   else
1660     info->exec = g_strconcat (commandline, " %f", NULL);
1661   info->nodisplay = TRUE;
1662   info->binary = binary_from_exec (info->exec);
1663   
1664   if (application_name)
1665     info->name = g_strdup (application_name);
1666   else
1667     {
1668       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
1669       split = g_strsplit (commandline, " ", 2);
1670       basename = g_path_get_basename (split[0]);
1671       g_strfreev (split);
1672       info->name = basename;
1673       if (info->name == NULL)
1674         info->name = g_strdup ("custom");
1675     }
1676   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
1677   
1678   return G_APP_INFO (info);
1679 }
1680
1681 static void
1682 g_desktop_app_info_iface_init (GAppInfoIface *iface)
1683 {
1684   iface->dup = g_desktop_app_info_dup;
1685   iface->equal = g_desktop_app_info_equal;
1686   iface->get_id = g_desktop_app_info_get_id;
1687   iface->get_name = g_desktop_app_info_get_name;
1688   iface->get_description = g_desktop_app_info_get_description;
1689   iface->get_executable = g_desktop_app_info_get_executable;
1690   iface->get_icon = g_desktop_app_info_get_icon;
1691   iface->launch = g_desktop_app_info_launch;
1692   iface->supports_uris = g_desktop_app_info_supports_uris;
1693   iface->supports_files = g_desktop_app_info_supports_files;
1694   iface->launch_uris = g_desktop_app_info_launch_uris;
1695   iface->should_show = g_desktop_app_info_should_show;
1696   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
1697   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
1698   iface->add_supports_type = g_desktop_app_info_add_supports_type;
1699   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
1700   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
1701   iface->can_delete = g_desktop_app_info_can_delete;
1702   iface->do_delete = g_desktop_app_info_delete;
1703 }
1704
1705 static gboolean
1706 app_info_in_list (GAppInfo *info, 
1707                   GList    *list)
1708 {
1709   while (list != NULL)
1710     {
1711       if (g_app_info_equal (info, list->data))
1712         return TRUE;
1713       list = list->next;
1714     }
1715   return FALSE;
1716 }
1717
1718
1719 /**
1720  * g_app_info_get_all_for_type:
1721  * @content_type: the content type to find a #GAppInfo for
1722  * 
1723  * Gets a list of all #GAppInfo s for a given content type.
1724  *
1725  * Returns: #GList of #GAppInfo s for given @content_type
1726  *    or %NULL on error.
1727  **/
1728 GList *
1729 g_app_info_get_all_for_type (const char *content_type)
1730 {
1731   GList *desktop_entries, *l;
1732   GList *infos;
1733   GDesktopAppInfo *info;
1734
1735   g_return_val_if_fail (content_type != NULL, NULL);
1736   
1737   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1738
1739   infos = NULL;
1740   for (l = desktop_entries; l != NULL; l = l->next)
1741     {
1742       char *desktop_entry = l->data;
1743
1744       info = g_desktop_app_info_new (desktop_entry);
1745       if (info)
1746         {
1747           if (app_info_in_list (G_APP_INFO (info), infos))
1748             g_object_unref (info);
1749           else
1750             infos = g_list_prepend (infos, info);
1751         }
1752       g_free (desktop_entry);
1753     }
1754
1755   g_list_free (desktop_entries);
1756   
1757   return g_list_reverse (infos);
1758 }
1759
1760 /**
1761  * g_app_info_reset_type_associations:
1762  * content_type: a content type 
1763  *
1764  * Removes all changes to the type associations done by
1765  * g_app_info_set_as_default_for_type(), 
1766  * g_app_info_set_as_default_for_extension(), 
1767  * g_app_info_add_supports_type() of g_app_info_remove_supports_type().
1768  *
1769  * Since: 2.20
1770  */
1771 void
1772 g_app_info_reset_type_associations (const char *content_type)
1773 {
1774   update_mimeapps_list (NULL, content_type, FALSE, FALSE, FALSE, NULL);
1775 }
1776
1777 /**
1778  * g_app_info_get_default_for_type:
1779  * @content_type: the content type to find a #GAppInfo for
1780  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
1781  *     support URIs
1782  * 
1783  * Gets the #GAppInfo that correspond to a given content type.
1784  *
1785  * Returns: #GAppInfo for given @content_type or %NULL on error.
1786  **/
1787 GAppInfo *
1788 g_app_info_get_default_for_type (const char *content_type,
1789                                  gboolean    must_support_uris)
1790 {
1791   GList *desktop_entries, *l;
1792   GAppInfo *info;
1793
1794   g_return_val_if_fail (content_type != NULL, NULL);
1795   
1796   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1797
1798   info = NULL;
1799   for (l = desktop_entries; l != NULL; l = l->next)
1800     {
1801       char *desktop_entry = l->data;
1802
1803       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
1804       if (info)
1805         {
1806           if (must_support_uris && !g_app_info_supports_uris (info))
1807             {
1808               g_object_unref (info);
1809               info = NULL;
1810             }
1811           else
1812             break;
1813         }
1814     }
1815   
1816   g_list_foreach  (desktop_entries, (GFunc)g_free, NULL);
1817   g_list_free (desktop_entries);
1818   
1819   return info;
1820 }
1821
1822 /**
1823  * g_app_info_get_default_for_uri_scheme:
1824  * @uri_scheme: a string containing a URI scheme.
1825  *
1826  * Gets the default application for launching applications 
1827  * using this URI scheme. A URI scheme is the initial part 
1828  * of the URI, up to but not including the ':', e.g. "http", 
1829  * "ftp" or "sip".
1830  * 
1831  * Returns: #GAppInfo for given @uri_scheme or %NULL on error.
1832  **/
1833 GAppInfo *
1834 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
1835 {
1836   static gsize lookup = 0;
1837   
1838   if (g_once_init_enter (&lookup))
1839     {
1840       gsize setup_value = 1;
1841       GDesktopAppInfoLookup *lookup_instance;
1842       const char *use_this;
1843       GIOExtensionPoint *ep;
1844       GIOExtension *extension;
1845       GList *l;
1846
1847       use_this = g_getenv ("GIO_USE_URI_ASSOCIATION");
1848       
1849       /* Ensure vfs in modules loaded */
1850       _g_io_modules_ensure_loaded ();
1851       
1852       ep = g_io_extension_point_lookup (G_DESKTOP_APP_INFO_LOOKUP_EXTENSION_POINT_NAME);
1853
1854       lookup_instance = NULL;
1855       if (use_this)
1856         {
1857           extension = g_io_extension_point_get_extension_by_name (ep, use_this);
1858           if (extension)
1859             lookup_instance = g_object_new (g_io_extension_get_type (extension), NULL);
1860         }
1861       
1862       if (lookup_instance == NULL)
1863         {
1864           for (l = g_io_extension_point_get_extensions (ep); l != NULL; l = l->next)
1865             {
1866               extension = l->data;
1867               lookup_instance = g_object_new (g_io_extension_get_type (extension), NULL);
1868               if (lookup_instance != NULL)
1869                 break;
1870             }
1871         }
1872
1873       if (lookup_instance != NULL)
1874         setup_value = (gsize)lookup_instance;
1875       
1876       g_once_init_leave (&lookup, setup_value);
1877     }
1878
1879   if (lookup == 1)
1880     return NULL;
1881
1882   return g_desktop_app_info_lookup_get_default_for_uri_scheme (G_DESKTOP_APP_INFO_LOOKUP (lookup),
1883                                                                uri_scheme);
1884 }
1885
1886
1887 static void
1888 get_apps_from_dir (GHashTable *apps, 
1889                    const char *dirname, 
1890                    const char *prefix)
1891 {
1892   GDir *dir;
1893   const char *basename;
1894   char *filename, *subprefix, *desktop_id;
1895   gboolean hidden;
1896   GDesktopAppInfo *appinfo;
1897   
1898   dir = g_dir_open (dirname, 0, NULL);
1899   if (dir)
1900     {
1901       while ((basename = g_dir_read_name (dir)) != NULL)
1902         {
1903           filename = g_build_filename (dirname, basename, NULL);
1904           if (g_str_has_suffix (basename, ".desktop"))
1905             {
1906               desktop_id = g_strconcat (prefix, basename, NULL);
1907
1908               /* Use _extended so we catch NULLs too (hidden) */
1909               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
1910                 {
1911                   appinfo = g_desktop_app_info_new_from_filename (filename);
1912
1913                   if (appinfo && g_desktop_app_info_get_is_hidden (appinfo))
1914                     {
1915                       g_object_unref (appinfo);
1916                       appinfo = NULL;
1917                       hidden = TRUE;
1918                     }
1919                                       
1920                   if (appinfo || hidden)
1921                     {
1922                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
1923
1924                       if (appinfo)
1925                         {
1926                           /* Reuse instead of strdup here */
1927                           appinfo->desktop_id = desktop_id;
1928                           desktop_id = NULL;
1929                         }
1930                     }
1931                 }
1932               g_free (desktop_id);
1933             }
1934           else
1935             {
1936               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
1937                 {
1938                   subprefix = g_strconcat (prefix, basename, "-", NULL);
1939                   get_apps_from_dir (apps, filename, subprefix);
1940                   g_free (subprefix);
1941                 }
1942             }
1943           g_free (filename);
1944         }
1945       g_dir_close (dir);
1946     }
1947 }
1948
1949
1950 /**
1951  * g_app_info_get_all:
1952  *
1953  * Gets a list of all of the applications currently registered 
1954  * on this system.
1955  * 
1956  * For desktop files, this includes applications that have 
1957  * <literal>NoDisplay=true</literal> set or are excluded from 
1958  * display by means of <literal>OnlyShowIn</literal> or
1959  * <literal>NotShowIn</literal>. See g_app_info_should_show().
1960  * The returned list does not include applications which have
1961  * the <literal>Hidden</literal> key set. 
1962  * 
1963  * Returns: a newly allocated #GList of references to #GAppInfo<!---->s.
1964  **/
1965 GList *
1966 g_app_info_get_all (void)
1967 {
1968   const char * const *dirs;
1969   GHashTable *apps;
1970   GHashTableIter iter;
1971   gpointer value;
1972   int i;
1973   GList *infos;
1974
1975   dirs = get_applications_search_path ();
1976
1977   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
1978                                 g_free, NULL);
1979
1980   
1981   for (i = 0; dirs[i] != NULL; i++)
1982     get_apps_from_dir (apps, dirs[i], "");
1983
1984
1985   infos = NULL;
1986   g_hash_table_iter_init (&iter, apps);
1987   while (g_hash_table_iter_next (&iter, NULL, &value))
1988     {
1989       if (value)
1990         infos = g_list_prepend (infos, value);
1991     }
1992
1993   g_hash_table_destroy (apps);
1994
1995   return g_list_reverse (infos);
1996 }
1997
1998 /* Cacheing of mimeinfo.cache and defaults.list files */
1999
2000 typedef struct {
2001   char *path;
2002   GHashTable *mime_info_cache_map;
2003   GHashTable *defaults_list_map;
2004   GHashTable *mimeapps_list_added_map;
2005   GHashTable *mimeapps_list_removed_map;
2006   time_t mime_info_cache_timestamp;
2007   time_t defaults_list_timestamp;
2008   time_t mimeapps_list_timestamp;
2009 } MimeInfoCacheDir;
2010
2011 typedef struct {
2012   GList *dirs;                       /* mimeinfo.cache and defaults.list */
2013   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
2014   time_t last_stat_time;
2015   guint should_ping_mime_monitor : 1;
2016 } MimeInfoCache;
2017
2018 static MimeInfoCache *mime_info_cache = NULL;
2019 G_LOCK_DEFINE_STATIC (mime_info_cache);
2020
2021 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2022                                                      const char        *mime_type,
2023                                                      char             **new_desktop_file_ids);
2024
2025 static MimeInfoCache * mime_info_cache_new (void);
2026
2027 static void
2028 destroy_info_cache_value (gpointer  key, 
2029                           GList    *value, 
2030                           gpointer  data)
2031 {
2032   g_list_foreach (value, (GFunc)g_free, NULL);
2033   g_list_free (value);
2034 }
2035
2036 static void
2037 destroy_info_cache_map (GHashTable *info_cache_map)
2038 {
2039   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
2040   g_hash_table_destroy (info_cache_map);
2041 }
2042
2043 static gboolean
2044 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
2045                                  const char       *cache_file,
2046                                  time_t           *timestamp)
2047 {
2048   struct stat buf;
2049   char *filename;
2050   
2051   filename = g_build_filename (dir->path, cache_file, NULL);
2052   
2053   if (g_stat (filename, &buf) < 0)
2054     {
2055       g_free (filename);
2056       return TRUE;
2057     }
2058   g_free (filename);
2059
2060   if (buf.st_mtime != *timestamp) 
2061     return TRUE;
2062   
2063   return FALSE;
2064 }
2065
2066 /* Call with lock held */
2067 static gboolean
2068 remove_all (gpointer  key,
2069             gpointer  value,
2070             gpointer  user_data)
2071 {
2072   return TRUE;
2073 }
2074
2075
2076 static void
2077 mime_info_cache_blow_global_cache (void)
2078 {
2079   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
2080                                remove_all, NULL);
2081 }
2082
2083 static void
2084 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
2085 {
2086   GError *load_error;
2087   GKeyFile *key_file;
2088   gchar *filename, **mime_types;
2089   int i;
2090   struct stat buf;
2091   
2092   load_error = NULL;
2093   mime_types = NULL;
2094   
2095   if (dir->mime_info_cache_map != NULL &&
2096       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
2097                                         &dir->mime_info_cache_timestamp))
2098     return;
2099   
2100   if (dir->mime_info_cache_map != NULL)
2101     destroy_info_cache_map (dir->mime_info_cache_map);
2102   
2103   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2104                                                     (GDestroyNotify) g_free,
2105                                                     NULL);
2106   
2107   key_file = g_key_file_new ();
2108   
2109   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
2110   
2111   if (g_stat (filename, &buf) < 0)
2112     goto error;
2113   
2114   if (dir->mime_info_cache_timestamp > 0) 
2115     mime_info_cache->should_ping_mime_monitor = TRUE;
2116   
2117   dir->mime_info_cache_timestamp = buf.st_mtime;
2118   
2119   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2120   
2121   g_free (filename);
2122   filename = NULL;
2123   
2124   if (load_error != NULL)
2125     goto error;
2126   
2127   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
2128                                     NULL, &load_error);
2129   
2130   if (load_error != NULL)
2131     goto error;
2132   
2133   for (i = 0; mime_types[i] != NULL; i++)
2134     {
2135       gchar **desktop_file_ids;
2136       char *unaliased_type;
2137       desktop_file_ids = g_key_file_get_string_list (key_file,
2138                                                      MIME_CACHE_GROUP,
2139                                                      mime_types[i],
2140                                                      NULL,
2141                                                      NULL);
2142       
2143       if (desktop_file_ids == NULL)
2144         continue;
2145
2146       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2147       mime_info_cache_dir_add_desktop_entries (dir,
2148                                                unaliased_type,
2149                                                desktop_file_ids);
2150       g_free (unaliased_type);
2151     
2152       g_strfreev (desktop_file_ids);
2153     }
2154   
2155   g_strfreev (mime_types);
2156   g_key_file_free (key_file);
2157   
2158   return;
2159  error:
2160   g_free (filename);
2161   g_key_file_free (key_file);
2162   
2163   if (mime_types != NULL)
2164     g_strfreev (mime_types);
2165   
2166   if (load_error)
2167     g_error_free (load_error);
2168 }
2169
2170 static void
2171 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
2172 {
2173   GKeyFile *key_file;
2174   GError *load_error;
2175   gchar *filename, **mime_types;
2176   char *unaliased_type;
2177   char **desktop_file_ids;
2178   int i;
2179   struct stat buf;
2180
2181   load_error = NULL;
2182   mime_types = NULL;
2183
2184   if (dir->defaults_list_map != NULL &&
2185       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
2186                                         &dir->defaults_list_timestamp))
2187     return;
2188   
2189   if (dir->defaults_list_map != NULL)
2190     g_hash_table_destroy (dir->defaults_list_map);
2191   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2192                                                   g_free, (GDestroyNotify)g_strfreev);
2193   
2194
2195   key_file = g_key_file_new ();
2196   
2197   filename = g_build_filename (dir->path, "defaults.list", NULL);
2198   if (g_stat (filename, &buf) < 0)
2199     goto error;
2200
2201   if (dir->defaults_list_timestamp > 0) 
2202     mime_info_cache->should_ping_mime_monitor = TRUE;
2203
2204   dir->defaults_list_timestamp = buf.st_mtime;
2205
2206   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2207   g_free (filename);
2208   filename = NULL;
2209
2210   if (load_error != NULL)
2211     goto error;
2212
2213   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2214                                     NULL, NULL);
2215   if (mime_types != NULL)
2216     {
2217       for (i = 0; mime_types[i] != NULL; i++)
2218         {
2219           desktop_file_ids = g_key_file_get_string_list (key_file,
2220                                                          DEFAULT_APPLICATIONS_GROUP,
2221                                                          mime_types[i],
2222                                                          NULL,
2223                                                          NULL);
2224           if (desktop_file_ids == NULL)
2225             continue;
2226           
2227           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2228           g_hash_table_replace (dir->defaults_list_map,
2229                                 unaliased_type,
2230                                 desktop_file_ids);
2231         }
2232       
2233       g_strfreev (mime_types);
2234     }
2235
2236   g_key_file_free (key_file);
2237   return;
2238   
2239  error:
2240   g_free (filename);
2241   g_key_file_free (key_file);
2242   
2243   if (mime_types != NULL)
2244     g_strfreev (mime_types);
2245   
2246   if (load_error)
2247     g_error_free (load_error);
2248 }
2249
2250 static void
2251 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
2252 {
2253   GKeyFile *key_file;
2254   GError *load_error;
2255   gchar *filename, **mime_types;
2256   char *unaliased_type;
2257   char **desktop_file_ids;
2258   int i;
2259   struct stat buf;
2260
2261   load_error = NULL;
2262   mime_types = NULL;
2263
2264   if (dir->mimeapps_list_added_map != NULL &&
2265       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
2266                                         &dir->mimeapps_list_timestamp))
2267     return;
2268   
2269   if (dir->mimeapps_list_added_map != NULL)
2270     g_hash_table_destroy (dir->mimeapps_list_added_map);
2271   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2272                                                         g_free, (GDestroyNotify)g_strfreev);
2273   
2274   if (dir->mimeapps_list_removed_map != NULL)
2275     g_hash_table_destroy (dir->mimeapps_list_removed_map);
2276   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2277                                                           g_free, (GDestroyNotify)g_strfreev);
2278
2279   key_file = g_key_file_new ();
2280   
2281   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
2282   if (g_stat (filename, &buf) < 0)
2283     goto error;
2284
2285   if (dir->mimeapps_list_timestamp > 0) 
2286     mime_info_cache->should_ping_mime_monitor = TRUE;
2287
2288   dir->mimeapps_list_timestamp = buf.st_mtime;
2289
2290   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2291   g_free (filename);
2292   filename = NULL;
2293
2294   if (load_error != NULL)
2295     goto error;
2296
2297   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
2298                                     NULL, NULL);
2299   if (mime_types != NULL)
2300     {
2301       for (i = 0; mime_types[i] != NULL; i++)
2302         {
2303           desktop_file_ids = g_key_file_get_string_list (key_file,
2304                                                          ADDED_ASSOCIATIONS_GROUP,
2305                                                          mime_types[i],
2306                                                          NULL,
2307                                                          NULL);
2308           if (desktop_file_ids == NULL)
2309             continue;
2310           
2311           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2312           g_hash_table_replace (dir->mimeapps_list_added_map,
2313                                 unaliased_type,
2314                                 desktop_file_ids);
2315         }
2316       
2317       g_strfreev (mime_types);
2318     }
2319
2320   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
2321                                     NULL, NULL);
2322   if (mime_types != NULL)
2323     {
2324       for (i = 0; mime_types[i] != NULL; i++)
2325         {
2326           desktop_file_ids = g_key_file_get_string_list (key_file,
2327                                                          REMOVED_ASSOCIATIONS_GROUP,
2328                                                          mime_types[i],
2329                                                          NULL,
2330                                                          NULL);
2331           if (desktop_file_ids == NULL)
2332             continue;
2333           
2334           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2335           g_hash_table_replace (dir->mimeapps_list_removed_map,
2336                                 unaliased_type,
2337                                 desktop_file_ids);
2338         }
2339       
2340       g_strfreev (mime_types);
2341     }
2342
2343   g_key_file_free (key_file);
2344   return;
2345   
2346  error:
2347   g_free (filename);
2348   g_key_file_free (key_file);
2349   
2350   if (mime_types != NULL)
2351     g_strfreev (mime_types);
2352   
2353   if (load_error)
2354     g_error_free (load_error);
2355 }
2356
2357 static MimeInfoCacheDir *
2358 mime_info_cache_dir_new (const char *path)
2359 {
2360   MimeInfoCacheDir *dir;
2361
2362   dir = g_new0 (MimeInfoCacheDir, 1);
2363   dir->path = g_strdup (path);
2364   
2365   return dir;
2366 }
2367
2368 static void
2369 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
2370 {
2371   if (dir == NULL)
2372     return;
2373   
2374   if (dir->mime_info_cache_map != NULL)
2375     {
2376       destroy_info_cache_map (dir->mime_info_cache_map);
2377       dir->mime_info_cache_map = NULL;
2378       
2379   }
2380   
2381   if (dir->defaults_list_map != NULL)
2382     {
2383       g_hash_table_destroy (dir->defaults_list_map);
2384       dir->defaults_list_map = NULL;
2385     }
2386   
2387   if (dir->mimeapps_list_added_map != NULL)
2388     {
2389       g_hash_table_destroy (dir->mimeapps_list_added_map);
2390       dir->mimeapps_list_added_map = NULL;
2391     }
2392   
2393   if (dir->mimeapps_list_removed_map != NULL)
2394     {
2395       g_hash_table_destroy (dir->mimeapps_list_removed_map);
2396       dir->mimeapps_list_removed_map = NULL;
2397     }
2398   
2399   g_free (dir);
2400 }
2401
2402 static void
2403 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2404                                          const char        *mime_type,
2405                                          char             **new_desktop_file_ids)
2406 {
2407   GList *desktop_file_ids;
2408   int i;
2409   
2410   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2411                                           mime_type);
2412   
2413   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2414     {
2415       if (!g_list_find (desktop_file_ids, new_desktop_file_ids[i]))
2416         desktop_file_ids = g_list_append (desktop_file_ids,
2417                                           g_strdup (new_desktop_file_ids[i]));
2418     }
2419   
2420   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2421 }
2422
2423 static void
2424 mime_info_cache_init_dir_lists (void)
2425 {
2426   const char * const *dirs;
2427   int i;
2428   
2429   mime_info_cache = mime_info_cache_new ();
2430   
2431   dirs = get_applications_search_path ();
2432   
2433   for (i = 0; dirs[i] != NULL; i++)
2434     {
2435       MimeInfoCacheDir *dir;
2436       
2437       dir = mime_info_cache_dir_new (dirs[i]);
2438       
2439       if (dir != NULL)
2440         {
2441           mime_info_cache_dir_init (dir);
2442           mime_info_cache_dir_init_defaults_list (dir);
2443           mime_info_cache_dir_init_mimeapps_list (dir);
2444           
2445           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2446         }
2447     }
2448 }
2449
2450 static void
2451 mime_info_cache_update_dir_lists (void)
2452 {
2453   GList *tmp;
2454   
2455   tmp = mime_info_cache->dirs;
2456   
2457   while (tmp != NULL)
2458     {
2459       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2460
2461       /* No need to do this if we had file monitors... */
2462       mime_info_cache_blow_global_cache ();
2463       mime_info_cache_dir_init (dir);
2464       mime_info_cache_dir_init_defaults_list (dir);
2465       mime_info_cache_dir_init_mimeapps_list (dir);
2466       
2467       tmp = tmp->next;
2468     }
2469 }
2470
2471 static void
2472 mime_info_cache_init (void)
2473 {
2474   G_LOCK (mime_info_cache);
2475   if (mime_info_cache == NULL)
2476     mime_info_cache_init_dir_lists ();
2477   else
2478     {
2479       time_t now;
2480       
2481       time (&now);
2482       if (now >= mime_info_cache->last_stat_time + 10)
2483         {
2484           mime_info_cache_update_dir_lists ();
2485           mime_info_cache->last_stat_time = now;
2486         }
2487     }
2488   
2489   if (mime_info_cache->should_ping_mime_monitor)
2490     {
2491       /* g_idle_add (emit_mime_changed, NULL); */
2492       mime_info_cache->should_ping_mime_monitor = FALSE;
2493     }
2494   
2495   G_UNLOCK (mime_info_cache);
2496 }
2497
2498 static MimeInfoCache *
2499 mime_info_cache_new (void)
2500 {
2501   MimeInfoCache *cache;
2502   
2503   cache = g_new0 (MimeInfoCache, 1);
2504   
2505   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2506                                                         (GDestroyNotify) g_free,
2507                                                         (GDestroyNotify) g_free);
2508   return cache;
2509 }
2510
2511 static void
2512 mime_info_cache_free (MimeInfoCache *cache)
2513 {
2514   if (cache == NULL)
2515     return;
2516   
2517   g_list_foreach (cache->dirs,
2518                   (GFunc) mime_info_cache_dir_free,
2519                   NULL);
2520   g_list_free (cache->dirs);
2521   g_hash_table_destroy (cache->global_defaults_cache);
2522   g_free (cache);
2523 }
2524
2525 /**
2526  * mime_info_cache_reload:
2527  * @dir: directory path which needs reloading.
2528  * 
2529  * Reload the mime information for the @dir.
2530  */
2531 static void
2532 mime_info_cache_reload (const char *dir)
2533 {
2534   /* FIXME: just reload the dir that needs reloading,
2535    * don't blow the whole cache
2536    */
2537   if (mime_info_cache != NULL)
2538     {
2539       G_LOCK (mime_info_cache);
2540       mime_info_cache_free (mime_info_cache);
2541       mime_info_cache = NULL;
2542       G_UNLOCK (mime_info_cache);
2543     }
2544 }
2545
2546 static GList *
2547 append_desktop_entry (GList      *list, 
2548                       const char *desktop_entry,
2549                       GList      *removed_entries)
2550 {
2551   /* Add if not already in list, and valid */
2552   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
2553       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
2554     list = g_list_prepend (list, g_strdup (desktop_entry));
2555   
2556   return list;
2557 }
2558
2559 /**
2560  * get_all_desktop_entries_for_mime_type:
2561  * @mime_type: a mime type.
2562  *
2563  * Returns all the desktop ids for @mime_type. The desktop files
2564  * are listed in an order so that default applications are listed before
2565  * non-default ones, and handlers for inherited mimetypes are listed
2566  * after the base ones.
2567  *
2568  * Return value: a #GList containing the desktop ids which claim
2569  *    to handle @mime_type.
2570  */
2571 static GList *
2572 get_all_desktop_entries_for_mime_type (const char *base_mime_type)
2573 {
2574   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
2575   MimeInfoCacheDir *dir;
2576   char *mime_type;
2577   char **mime_types;
2578   char **default_entries;
2579   char **removed_associations;
2580   int i, j, k;
2581   GPtrArray *array;
2582   char **anc;
2583   
2584   mime_info_cache_init ();
2585
2586   /* collect all ancestors */
2587   mime_types = _g_unix_content_type_get_parents (base_mime_type);
2588   array = g_ptr_array_new ();
2589   for (i = 0; mime_types[i]; i++)
2590     g_ptr_array_add (array, mime_types[i]);
2591   g_free (mime_types);
2592   for (i = 0; i < array->len; i++)
2593     {
2594       anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
2595       for (j = 0; anc[j]; j++)
2596         {
2597           for (k = 0; k < array->len; k++)
2598             {
2599               if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
2600                 break;
2601             }
2602           if (k == array->len) /* not found */
2603             g_ptr_array_add (array, g_strdup (anc[j]));
2604         }
2605       g_strfreev (anc);
2606     }
2607   g_ptr_array_add (array, NULL);
2608   mime_types = (char **)g_ptr_array_free (array, FALSE);
2609
2610   G_LOCK (mime_info_cache);
2611   
2612   removed_entries = NULL;
2613   desktop_entries = NULL;
2614   for (i = 0; mime_types[i] != NULL; i++)
2615     {
2616       mime_type = mime_types[i];
2617
2618       /* Go through all apps listed as defaults */
2619       for (dir_list = mime_info_cache->dirs;
2620            dir_list != NULL;
2621            dir_list = dir_list->next)
2622         {
2623           dir = dir_list->data;
2624
2625           /* First added associations from mimeapps.list */
2626           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
2627           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2628             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
2629
2630           /* Then removed associations from mimeapps.list */
2631           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
2632           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
2633             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
2634
2635           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
2636           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
2637           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2638             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
2639         }
2640
2641       /* Go through all entries that support the mimetype */
2642       for (dir_list = mime_info_cache->dirs;
2643            dir_list != NULL;
2644            dir_list = dir_list->next) 
2645         {
2646           dir = dir_list->data;
2647         
2648           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
2649           for (tmp = list; tmp != NULL; tmp = tmp->next)
2650             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
2651         }
2652     }
2653   
2654   G_UNLOCK (mime_info_cache);
2655
2656   g_strfreev (mime_types);
2657
2658   g_list_free (removed_entries);
2659   
2660   desktop_entries = g_list_reverse (desktop_entries);
2661   
2662   return desktop_entries;
2663 }
2664
2665 /* GDesktopAppInfoLookup interface: */
2666
2667 static void g_desktop_app_info_lookup_base_init (gpointer g_class);
2668 static void g_desktop_app_info_lookup_class_init (gpointer g_class,
2669                                                   gpointer class_data);
2670
2671 GType
2672 g_desktop_app_info_lookup_get_type (void)
2673 {
2674   static volatile gsize g_define_type_id__volatile = 0;
2675
2676   if (g_once_init_enter (&g_define_type_id__volatile))
2677     {
2678       const GTypeInfo desktop_app_info_lookup_info =
2679       {
2680         sizeof (GDesktopAppInfoLookupIface), /* class_size */
2681         g_desktop_app_info_lookup_base_init,   /* base_init */
2682         NULL,           /* base_finalize */
2683         g_desktop_app_info_lookup_class_init,
2684         NULL,           /* class_finalize */
2685         NULL,           /* class_data */
2686         0,
2687         0,              /* n_preallocs */
2688         NULL
2689       };
2690       GType g_define_type_id =
2691         g_type_register_static (G_TYPE_INTERFACE, I_("GDesktopAppInfoLookup"),
2692                                 &desktop_app_info_lookup_info, 0);
2693
2694       g_type_interface_add_prerequisite (g_define_type_id, G_TYPE_OBJECT);
2695
2696       g_once_init_leave (&g_define_type_id__volatile, g_define_type_id);
2697     }
2698
2699   return g_define_type_id__volatile;
2700 }
2701
2702 static void
2703 g_desktop_app_info_lookup_class_init (gpointer g_class,
2704                                       gpointer class_data)
2705 {
2706 }
2707
2708 static void
2709 g_desktop_app_info_lookup_base_init (gpointer g_class)
2710 {
2711 }
2712
2713 /**
2714  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
2715  * @lookup: a #GDesktopAppInfoLookup
2716  * @uri_scheme: a string containing a URI scheme.
2717  *
2718  * Gets the default application for launching applications 
2719  * using this URI scheme for a particular GDesktopAppInfoLookup
2720  * implementation.
2721  *
2722  * The GDesktopAppInfoLookup interface and this function is used
2723  * to implement g_app_info_get_default_for_uri_scheme() backends
2724  * in a GIO module. There is no reason for applications to use it
2725  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
2726  * 
2727  * Returns: #GAppInfo for given @uri_scheme or %NULL on error.
2728  */
2729 GAppInfo *
2730 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
2731                                                       const char            *uri_scheme)
2732 {
2733   GDesktopAppInfoLookupIface *iface;
2734   
2735   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
2736
2737   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
2738
2739   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
2740 }
2741
2742 #define __G_DESKTOP_APP_INFO_C__
2743 #include "gioaliasdef.c"