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