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