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