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