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