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