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