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