Use g_set_error_literal where appropriate. Patch from bug #535947.
[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 && try_exec[0] != '\0')
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_literal (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_literal (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->nodisplay = TRUE;
1518   info->binary = binary_from_exec (info->exec);
1519   
1520   if (application_name)
1521     info->name = g_strdup (application_name);
1522   else
1523     {
1524       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
1525       split = g_strsplit (commandline, " ", 2);
1526       basename = g_path_get_basename (split[0]);
1527       g_strfreev (split);
1528       info->name = basename;
1529       if (info->name == NULL)
1530         info->name = g_strdup ("custom");
1531     }
1532   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
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. A URI scheme is the initial part 
1666  * of the URI, up to but not including the ':', e.g. "http", 
1667  * "ftp" or "sip".
1668  * 
1669  * Returns: #GAppInfo for given @uri_scheme or %NULL on error.
1670  **/
1671 GAppInfo *
1672 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
1673 {
1674   static gsize lookup = 0;
1675   
1676   if (g_once_init_enter (&lookup))
1677     {
1678       gsize setup_value = 1;
1679       GDesktopAppInfoLookup *lookup_instance;
1680       const char *use_this;
1681       GIOExtensionPoint *ep;
1682       GIOExtension *extension;
1683       GList *l;
1684
1685       use_this = g_getenv ("GIO_USE_URI_ASSOCIATION");
1686       
1687       /* Ensure vfs in modules loaded */
1688       _g_io_modules_ensure_loaded ();
1689       
1690       ep = g_io_extension_point_lookup (G_DESKTOP_APP_INFO_LOOKUP_EXTENSION_POINT_NAME);
1691
1692       lookup_instance = NULL;
1693       if (use_this)
1694         {
1695           extension = g_io_extension_point_get_extension_by_name (ep, use_this);
1696           if (extension)
1697             lookup_instance = g_object_new (g_io_extension_get_type (extension), NULL);
1698         }
1699       
1700       if (lookup_instance == NULL)
1701         {
1702           for (l = g_io_extension_point_get_extensions (ep); l != NULL; l = l->next)
1703             {
1704               extension = l->data;
1705               lookup_instance = g_object_new (g_io_extension_get_type (extension), NULL);
1706               if (lookup_instance != NULL)
1707                 break;
1708             }
1709         }
1710
1711       if (lookup_instance != NULL)
1712         setup_value = (gsize)lookup_instance;
1713       
1714       g_once_init_leave (&lookup, setup_value);
1715     }
1716
1717   if (lookup == 1)
1718     return NULL;
1719
1720   return g_desktop_app_info_lookup_get_default_for_uri_scheme (G_DESKTOP_APP_INFO_LOOKUP (lookup),
1721                                                                uri_scheme);
1722 }
1723
1724
1725 static void
1726 get_apps_from_dir (GHashTable *apps, 
1727                    const char *dirname, 
1728                    const char *prefix)
1729 {
1730   GDir *dir;
1731   const char *basename;
1732   char *filename, *subprefix, *desktop_id;
1733   gboolean hidden;
1734   GDesktopAppInfo *appinfo;
1735   
1736   dir = g_dir_open (dirname, 0, NULL);
1737   if (dir)
1738     {
1739       while ((basename = g_dir_read_name (dir)) != NULL)
1740         {
1741           filename = g_build_filename (dirname, basename, NULL);
1742           if (g_str_has_suffix (basename, ".desktop"))
1743             {
1744               desktop_id = g_strconcat (prefix, basename, NULL);
1745
1746               /* Use _extended so we catch NULLs too (hidden) */
1747               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
1748                 {
1749                   appinfo = g_desktop_app_info_new_from_filename (filename);
1750
1751                   if (appinfo && g_desktop_app_info_get_is_hidden (appinfo))
1752                     {
1753                       g_object_unref (appinfo);
1754                       appinfo = NULL;
1755                       hidden = TRUE;
1756                     }
1757                                       
1758                   if (appinfo || hidden)
1759                     {
1760                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
1761
1762                       if (appinfo)
1763                         {
1764                           /* Reuse instead of strdup here */
1765                           appinfo->desktop_id = desktop_id;
1766                           desktop_id = NULL;
1767                         }
1768                     }
1769                 }
1770               g_free (desktop_id);
1771             }
1772           else
1773             {
1774               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
1775                 {
1776                   subprefix = g_strconcat (prefix, basename, "-", NULL);
1777                   get_apps_from_dir (apps, filename, subprefix);
1778                   g_free (subprefix);
1779                 }
1780             }
1781           g_free (filename);
1782         }
1783       g_dir_close (dir);
1784     }
1785 }
1786
1787
1788 /**
1789  * g_app_info_get_all:
1790  *
1791  * Gets a list of all of the applications currently registered 
1792  * on this system.
1793  * 
1794  * For desktop files, this includes applications that have 
1795  * <literal>NoDisplay=true</literal> set or are excluded from 
1796  * display by means of <literal>OnlyShowIn</literal> or
1797  * <literal>NotShowIn</literal>. See g_app_info_should_show().
1798  * The returned list does not include applications which have
1799  * the <literal>Hidden</literal> key set. 
1800  * 
1801  * Returns: a newly allocated #GList of references to #GAppInfo<!---->s.
1802  **/
1803 GList *
1804 g_app_info_get_all (void)
1805 {
1806   const char * const *dirs;
1807   GHashTable *apps;
1808   GHashTableIter iter;
1809   gpointer value;
1810   int i;
1811   GList *infos;
1812
1813   dirs = get_applications_search_path ();
1814
1815   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
1816                                 g_free, NULL);
1817
1818   
1819   for (i = 0; dirs[i] != NULL; i++)
1820     get_apps_from_dir (apps, dirs[i], "");
1821
1822
1823   infos = NULL;
1824   g_hash_table_iter_init (&iter, apps);
1825   while (g_hash_table_iter_next (&iter, NULL, &value))
1826     {
1827       if (value)
1828         infos = g_list_prepend (infos, value);
1829     }
1830
1831   g_hash_table_destroy (apps);
1832
1833   return g_list_reverse (infos);
1834 }
1835
1836 /* Cacheing of mimeinfo.cache and defaults.list files */
1837
1838 typedef struct {
1839   char *path;
1840   GHashTable *mime_info_cache_map;
1841   GHashTable *defaults_list_map;
1842   GHashTable *mimeapps_list_added_map;
1843   GHashTable *mimeapps_list_removed_map;
1844   time_t mime_info_cache_timestamp;
1845   time_t defaults_list_timestamp;
1846   time_t mimeapps_list_timestamp;
1847 } MimeInfoCacheDir;
1848
1849 typedef struct {
1850   GList *dirs;                       /* mimeinfo.cache and defaults.list */
1851   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
1852   time_t last_stat_time;
1853   guint should_ping_mime_monitor : 1;
1854 } MimeInfoCache;
1855
1856 static MimeInfoCache *mime_info_cache = NULL;
1857 G_LOCK_DEFINE_STATIC (mime_info_cache);
1858
1859 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
1860                                                      const char        *mime_type,
1861                                                      char             **new_desktop_file_ids);
1862
1863 static MimeInfoCache * mime_info_cache_new (void);
1864
1865 static void
1866 destroy_info_cache_value (gpointer  key, 
1867                           GList    *value, 
1868                           gpointer  data)
1869 {
1870   g_list_foreach (value, (GFunc)g_free, NULL);
1871   g_list_free (value);
1872 }
1873
1874 static void
1875 destroy_info_cache_map (GHashTable *info_cache_map)
1876 {
1877   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
1878   g_hash_table_destroy (info_cache_map);
1879 }
1880
1881 static gboolean
1882 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
1883                                  const char       *cache_file,
1884                                  time_t           *timestamp)
1885 {
1886   struct stat buf;
1887   char *filename;
1888   
1889   filename = g_build_filename (dir->path, cache_file, NULL);
1890   
1891   if (g_stat (filename, &buf) < 0)
1892     {
1893       g_free (filename);
1894       return TRUE;
1895     }
1896   g_free (filename);
1897
1898   if (buf.st_mtime != *timestamp) 
1899     return TRUE;
1900   
1901   return FALSE;
1902 }
1903
1904 /* Call with lock held */
1905 static gboolean
1906 remove_all (gpointer  key,
1907             gpointer  value,
1908             gpointer  user_data)
1909 {
1910   return TRUE;
1911 }
1912
1913
1914 static void
1915 mime_info_cache_blow_global_cache (void)
1916 {
1917   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
1918                                remove_all, NULL);
1919 }
1920
1921 static void
1922 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
1923 {
1924   GError *load_error;
1925   GKeyFile *key_file;
1926   gchar *filename, **mime_types;
1927   int i;
1928   struct stat buf;
1929   
1930   load_error = NULL;
1931   mime_types = NULL;
1932   
1933   if (dir->mime_info_cache_map != NULL &&
1934       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
1935                                         &dir->mime_info_cache_timestamp))
1936     return;
1937   
1938   if (dir->mime_info_cache_map != NULL)
1939     destroy_info_cache_map (dir->mime_info_cache_map);
1940   
1941   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1942                                                     (GDestroyNotify) g_free,
1943                                                     NULL);
1944   
1945   key_file = g_key_file_new ();
1946   
1947   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
1948   
1949   if (g_stat (filename, &buf) < 0)
1950     goto error;
1951   
1952   if (dir->mime_info_cache_timestamp > 0) 
1953     mime_info_cache->should_ping_mime_monitor = TRUE;
1954   
1955   dir->mime_info_cache_timestamp = buf.st_mtime;
1956   
1957   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1958   
1959   g_free (filename);
1960   filename = NULL;
1961   
1962   if (load_error != NULL)
1963     goto error;
1964   
1965   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
1966                                     NULL, &load_error);
1967   
1968   if (load_error != NULL)
1969     goto error;
1970   
1971   for (i = 0; mime_types[i] != NULL; i++)
1972     {
1973       gchar **desktop_file_ids;
1974       char *unaliased_type;
1975       desktop_file_ids = g_key_file_get_string_list (key_file,
1976                                                      MIME_CACHE_GROUP,
1977                                                      mime_types[i],
1978                                                      NULL,
1979                                                      NULL);
1980       
1981       if (desktop_file_ids == NULL)
1982         continue;
1983
1984       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1985       mime_info_cache_dir_add_desktop_entries (dir,
1986                                                unaliased_type,
1987                                                desktop_file_ids);
1988       g_free (unaliased_type);
1989     
1990       g_strfreev (desktop_file_ids);
1991     }
1992   
1993   g_strfreev (mime_types);
1994   g_key_file_free (key_file);
1995   
1996   return;
1997  error:
1998   g_free (filename);
1999   g_key_file_free (key_file);
2000   
2001   if (mime_types != NULL)
2002     g_strfreev (mime_types);
2003   
2004   if (load_error)
2005     g_error_free (load_error);
2006 }
2007
2008 static void
2009 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
2010 {
2011   GKeyFile *key_file;
2012   GError *load_error;
2013   gchar *filename, **mime_types;
2014   char *unaliased_type;
2015   char **desktop_file_ids;
2016   int i;
2017   struct stat buf;
2018
2019   load_error = NULL;
2020   mime_types = NULL;
2021
2022   if (dir->defaults_list_map != NULL &&
2023       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
2024                                         &dir->defaults_list_timestamp))
2025     return;
2026   
2027   if (dir->defaults_list_map != NULL)
2028     g_hash_table_destroy (dir->defaults_list_map);
2029   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2030                                                   g_free, (GDestroyNotify)g_strfreev);
2031   
2032
2033   key_file = g_key_file_new ();
2034   
2035   filename = g_build_filename (dir->path, "defaults.list", NULL);
2036   if (g_stat (filename, &buf) < 0)
2037     goto error;
2038
2039   if (dir->defaults_list_timestamp > 0) 
2040     mime_info_cache->should_ping_mime_monitor = TRUE;
2041
2042   dir->defaults_list_timestamp = buf.st_mtime;
2043
2044   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2045   g_free (filename);
2046   filename = NULL;
2047
2048   if (load_error != NULL)
2049     goto error;
2050
2051   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
2052                                     NULL, NULL);
2053   if (mime_types != NULL)
2054     {
2055       for (i = 0; mime_types[i] != NULL; i++)
2056         {
2057           desktop_file_ids = g_key_file_get_string_list (key_file,
2058                                                          DEFAULT_APPLICATIONS_GROUP,
2059                                                          mime_types[i],
2060                                                          NULL,
2061                                                          NULL);
2062           if (desktop_file_ids == NULL)
2063             continue;
2064           
2065           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2066           g_hash_table_replace (dir->defaults_list_map,
2067                                 unaliased_type,
2068                                 desktop_file_ids);
2069         }
2070       
2071       g_strfreev (mime_types);
2072     }
2073
2074   g_key_file_free (key_file);
2075   return;
2076   
2077  error:
2078   g_free (filename);
2079   g_key_file_free (key_file);
2080   
2081   if (mime_types != NULL)
2082     g_strfreev (mime_types);
2083   
2084   if (load_error)
2085     g_error_free (load_error);
2086 }
2087
2088 static void
2089 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
2090 {
2091   GKeyFile *key_file;
2092   GError *load_error;
2093   gchar *filename, **mime_types;
2094   char *unaliased_type;
2095   char **desktop_file_ids;
2096   int i;
2097   struct stat buf;
2098
2099   load_error = NULL;
2100   mime_types = NULL;
2101
2102   if (dir->mimeapps_list_added_map != NULL &&
2103       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
2104                                         &dir->mimeapps_list_timestamp))
2105     return;
2106   
2107   if (dir->mimeapps_list_added_map != NULL)
2108     g_hash_table_destroy (dir->mimeapps_list_added_map);
2109   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2110                                                         g_free, (GDestroyNotify)g_strfreev);
2111   
2112   if (dir->mimeapps_list_removed_map != NULL)
2113     g_hash_table_destroy (dir->mimeapps_list_removed_map);
2114   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
2115                                                           g_free, (GDestroyNotify)g_strfreev);
2116
2117   key_file = g_key_file_new ();
2118   
2119   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
2120   if (g_stat (filename, &buf) < 0)
2121     goto error;
2122
2123   if (dir->mimeapps_list_timestamp > 0) 
2124     mime_info_cache->should_ping_mime_monitor = TRUE;
2125
2126   dir->mimeapps_list_timestamp = buf.st_mtime;
2127
2128   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
2129   g_free (filename);
2130   filename = NULL;
2131
2132   if (load_error != NULL)
2133     goto error;
2134
2135   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
2136                                     NULL, NULL);
2137   if (mime_types != NULL)
2138     {
2139       for (i = 0; mime_types[i] != NULL; i++)
2140         {
2141           desktop_file_ids = g_key_file_get_string_list (key_file,
2142                                                          ADDED_ASSOCIATIONS_GROUP,
2143                                                          mime_types[i],
2144                                                          NULL,
2145                                                          NULL);
2146           if (desktop_file_ids == NULL)
2147             continue;
2148           
2149           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2150           g_hash_table_replace (dir->mimeapps_list_added_map,
2151                                 unaliased_type,
2152                                 desktop_file_ids);
2153         }
2154       
2155       g_strfreev (mime_types);
2156     }
2157
2158   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
2159                                     NULL, NULL);
2160   if (mime_types != NULL)
2161     {
2162       for (i = 0; mime_types[i] != NULL; i++)
2163         {
2164           desktop_file_ids = g_key_file_get_string_list (key_file,
2165                                                          REMOVED_ASSOCIATIONS_GROUP,
2166                                                          mime_types[i],
2167                                                          NULL,
2168                                                          NULL);
2169           if (desktop_file_ids == NULL)
2170             continue;
2171           
2172           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2173           g_hash_table_replace (dir->mimeapps_list_removed_map,
2174                                 unaliased_type,
2175                                 desktop_file_ids);
2176         }
2177       
2178       g_strfreev (mime_types);
2179     }
2180
2181   g_key_file_free (key_file);
2182   return;
2183   
2184  error:
2185   g_free (filename);
2186   g_key_file_free (key_file);
2187   
2188   if (mime_types != NULL)
2189     g_strfreev (mime_types);
2190   
2191   if (load_error)
2192     g_error_free (load_error);
2193 }
2194
2195 static MimeInfoCacheDir *
2196 mime_info_cache_dir_new (const char *path)
2197 {
2198   MimeInfoCacheDir *dir;
2199
2200   dir = g_new0 (MimeInfoCacheDir, 1);
2201   dir->path = g_strdup (path);
2202   
2203   return dir;
2204 }
2205
2206 static void
2207 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
2208 {
2209   if (dir == NULL)
2210     return;
2211   
2212   if (dir->mime_info_cache_map != NULL)
2213     {
2214       destroy_info_cache_map (dir->mime_info_cache_map);
2215       dir->mime_info_cache_map = NULL;
2216       
2217   }
2218   
2219   if (dir->defaults_list_map != NULL)
2220     {
2221       g_hash_table_destroy (dir->defaults_list_map);
2222       dir->defaults_list_map = NULL;
2223     }
2224   
2225   if (dir->mimeapps_list_added_map != NULL)
2226     {
2227       g_hash_table_destroy (dir->mimeapps_list_added_map);
2228       dir->mimeapps_list_added_map = NULL;
2229     }
2230   
2231   if (dir->mimeapps_list_removed_map != NULL)
2232     {
2233       g_hash_table_destroy (dir->mimeapps_list_removed_map);
2234       dir->mimeapps_list_removed_map = NULL;
2235     }
2236   
2237   g_free (dir);
2238 }
2239
2240 static void
2241 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2242                                          const char        *mime_type,
2243                                          char             **new_desktop_file_ids)
2244 {
2245   GList *desktop_file_ids;
2246   int i;
2247   
2248   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2249                                           mime_type);
2250   
2251   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2252     {
2253       if (!g_list_find (desktop_file_ids, new_desktop_file_ids[i]))
2254         desktop_file_ids = g_list_append (desktop_file_ids,
2255                                           g_strdup (new_desktop_file_ids[i]));
2256     }
2257   
2258   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2259 }
2260
2261 static void
2262 mime_info_cache_init_dir_lists (void)
2263 {
2264   const char * const *dirs;
2265   int i;
2266   
2267   mime_info_cache = mime_info_cache_new ();
2268   
2269   dirs = get_applications_search_path ();
2270   
2271   for (i = 0; dirs[i] != NULL; i++)
2272     {
2273       MimeInfoCacheDir *dir;
2274       
2275       dir = mime_info_cache_dir_new (dirs[i]);
2276       
2277       if (dir != NULL)
2278         {
2279           mime_info_cache_dir_init (dir);
2280           mime_info_cache_dir_init_defaults_list (dir);
2281           mime_info_cache_dir_init_mimeapps_list (dir);
2282           
2283           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2284         }
2285     }
2286 }
2287
2288 static void
2289 mime_info_cache_update_dir_lists (void)
2290 {
2291   GList *tmp;
2292   
2293   tmp = mime_info_cache->dirs;
2294   
2295   while (tmp != NULL)
2296     {
2297       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2298
2299       /* No need to do this if we had file monitors... */
2300       mime_info_cache_blow_global_cache ();
2301       mime_info_cache_dir_init (dir);
2302       mime_info_cache_dir_init_defaults_list (dir);
2303       mime_info_cache_dir_init_mimeapps_list (dir);
2304       
2305       tmp = tmp->next;
2306     }
2307 }
2308
2309 static void
2310 mime_info_cache_init (void)
2311 {
2312   G_LOCK (mime_info_cache);
2313   if (mime_info_cache == NULL)
2314     mime_info_cache_init_dir_lists ();
2315   else
2316     {
2317       time_t now;
2318       
2319       time (&now);
2320       if (now >= mime_info_cache->last_stat_time + 10)
2321         {
2322           mime_info_cache_update_dir_lists ();
2323           mime_info_cache->last_stat_time = now;
2324         }
2325     }
2326   
2327   if (mime_info_cache->should_ping_mime_monitor)
2328     {
2329       /* g_idle_add (emit_mime_changed, NULL); */
2330       mime_info_cache->should_ping_mime_monitor = FALSE;
2331     }
2332   
2333   G_UNLOCK (mime_info_cache);
2334 }
2335
2336 static MimeInfoCache *
2337 mime_info_cache_new (void)
2338 {
2339   MimeInfoCache *cache;
2340   
2341   cache = g_new0 (MimeInfoCache, 1);
2342   
2343   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2344                                                         (GDestroyNotify) g_free,
2345                                                         (GDestroyNotify) g_free);
2346   return cache;
2347 }
2348
2349 static void
2350 mime_info_cache_free (MimeInfoCache *cache)
2351 {
2352   if (cache == NULL)
2353     return;
2354   
2355   g_list_foreach (cache->dirs,
2356                   (GFunc) mime_info_cache_dir_free,
2357                   NULL);
2358   g_list_free (cache->dirs);
2359   g_hash_table_destroy (cache->global_defaults_cache);
2360   g_free (cache);
2361 }
2362
2363 /**
2364  * mime_info_cache_reload:
2365  * @dir: directory path which needs reloading.
2366  * 
2367  * Reload the mime information for the @dir.
2368  */
2369 static void
2370 mime_info_cache_reload (const char *dir)
2371 {
2372   /* FIXME: just reload the dir that needs reloading,
2373    * don't blow the whole cache
2374    */
2375   if (mime_info_cache != NULL)
2376     {
2377       G_LOCK (mime_info_cache);
2378       mime_info_cache_free (mime_info_cache);
2379       mime_info_cache = NULL;
2380       G_UNLOCK (mime_info_cache);
2381     }
2382 }
2383
2384 static GList *
2385 append_desktop_entry (GList      *list, 
2386                       const char *desktop_entry,
2387                       GList      *removed_entries)
2388 {
2389   /* Add if not already in list, and valid */
2390   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
2391       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
2392     list = g_list_prepend (list, g_strdup (desktop_entry));
2393   
2394   return list;
2395 }
2396
2397 /**
2398  * get_all_desktop_entries_for_mime_type:
2399  * @mime_type: a mime type.
2400  *
2401  * Returns all the desktop ids for @mime_type. The desktop files
2402  * are listed in an order so that default applications are listed before
2403  * non-default ones, and handlers for inherited mimetypes are listed
2404  * after the base ones.
2405  *
2406  * Return value: a #GList containing the desktop ids which claim
2407  *    to handle @mime_type.
2408  */
2409 static GList *
2410 get_all_desktop_entries_for_mime_type (const char *base_mime_type)
2411 {
2412   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
2413   MimeInfoCacheDir *dir;
2414   char *mime_type;
2415   char **mime_types;
2416   char **default_entries;
2417   char **removed_associations;
2418   int i,j;
2419   
2420   mime_info_cache_init ();
2421
2422   mime_types = _g_unix_content_type_get_parents (base_mime_type);
2423   G_LOCK (mime_info_cache);
2424   
2425   removed_entries = NULL;
2426   desktop_entries = NULL;
2427   for (i = 0; mime_types[i] != NULL; i++)
2428     {
2429       mime_type = mime_types[i];
2430
2431       /* Go through all apps listed as defaults */
2432       for (dir_list = mime_info_cache->dirs;
2433            dir_list != NULL;
2434            dir_list = dir_list->next)
2435         {
2436           dir = dir_list->data;
2437
2438           /* First added associations from mimeapps.list */
2439           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
2440           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2441             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
2442
2443           /* Then removed assiciations from mimeapps.list */
2444           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
2445           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
2446             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
2447
2448           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
2449           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
2450           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2451             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
2452         }
2453
2454       /* Go through all entries that support the mimetype */
2455       for (dir_list = mime_info_cache->dirs;
2456            dir_list != NULL;
2457            dir_list = dir_list->next) 
2458         {
2459           dir = dir_list->data;
2460         
2461           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
2462           for (tmp = list; tmp != NULL; tmp = tmp->next)
2463             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
2464         }
2465     }
2466   
2467   G_UNLOCK (mime_info_cache);
2468
2469   g_strfreev (mime_types);
2470
2471   g_list_free (removed_entries);
2472   
2473   desktop_entries = g_list_reverse (desktop_entries);
2474   
2475   return desktop_entries;
2476 }
2477
2478 /* GDesktopAppInfoLookup interface: */
2479
2480 static void g_desktop_app_info_lookup_base_init (gpointer g_class);
2481 static void g_desktop_app_info_lookup_class_init (gpointer g_class,
2482                                                   gpointer class_data);
2483
2484 GType
2485 g_desktop_app_info_lookup_get_type (void)
2486 {
2487   static GType desktop_app_info_lookup_type = 0;
2488
2489   if (! desktop_app_info_lookup_type)
2490     {
2491       static const GTypeInfo desktop_app_info_lookup_info =
2492       {
2493         sizeof (GDesktopAppInfoLookupIface), /* class_size */
2494         g_desktop_app_info_lookup_base_init,   /* base_init */
2495         NULL,           /* base_finalize */
2496         g_desktop_app_info_lookup_class_init,
2497         NULL,           /* class_finalize */
2498         NULL,           /* class_data */
2499         0,
2500         0,              /* n_preallocs */
2501         NULL
2502       };
2503
2504       desktop_app_info_lookup_type =
2505         g_type_register_static (G_TYPE_INTERFACE, I_("GDesktopAppInfoLookup"),
2506                                 &desktop_app_info_lookup_info, 0);
2507
2508       g_type_interface_add_prerequisite (desktop_app_info_lookup_type, G_TYPE_OBJECT);
2509     }
2510
2511   return desktop_app_info_lookup_type;
2512 }
2513
2514 static void
2515 g_desktop_app_info_lookup_class_init (gpointer g_class,
2516                                       gpointer class_data)
2517 {
2518 }
2519
2520 static void
2521 g_desktop_app_info_lookup_base_init (gpointer g_class)
2522 {
2523 }
2524
2525 /**
2526  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
2527  * @lookup: a #GDesktopAppInfoLookup
2528  * @uri_scheme: a string containing a URI scheme.
2529  *
2530  * Gets the default application for launching applications 
2531  * using this URI scheme for a particular GDesktopAppInfoLookup
2532  * implementation.
2533  *
2534  * The GDesktopAppInfoLookup interface and this function is used
2535  * to implement g_app_info_get_default_for_uri_scheme() backends
2536  * in a GIO module. There is no reason for applications to use it
2537  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
2538  * 
2539  * Returns: #GAppInfo for given @uri_scheme or %NULL on error.
2540  */
2541 GAppInfo *
2542 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
2543                                                       const char            *uri_scheme)
2544 {
2545   GDesktopAppInfoLookupIface *iface;
2546   
2547   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
2548
2549   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
2550
2551   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
2552 }
2553
2554 #define __G_DESKTOP_APP_INFO_C__
2555 #include "gioaliasdef.c"