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