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