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