Coding style fixups
[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     char *contents;
1189
1190     contents =
1191       g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1192                        "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
1193                        " <mime-type type=\"%s\">\n"
1194                        "  <comment>%s document</comment>\n"
1195                        "  <glob pattern=\"*.%s\"/>\n"
1196                        " </mime-type>\n"
1197                        "</mime-info>\n", mimetype, extension, extension);
1198
1199     g_file_set_contents (filename, contents, -1, NULL);
1200     g_free (contents);
1201
1202     run_update_command ("update-mime-database", "mime");
1203   }
1204   g_free (filename);
1205   
1206   res = g_desktop_app_info_set_as_default_for_type (appinfo,
1207                                                     mimetype,
1208                                                     error);
1209
1210   g_free (mimetype);
1211   
1212   return res;
1213 }
1214
1215 static gboolean
1216 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
1217                                       const char  *content_type,
1218                                       GError     **error)
1219 {
1220   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1221   GKeyFile *keyfile;
1222   char *new_mimetypes, *old_mimetypes, *content;
1223   char *dirname;
1224   char *filename;
1225
1226   keyfile = g_key_file_new ();
1227   if (!g_key_file_load_from_file (keyfile, info->filename,
1228                                   G_KEY_FILE_KEEP_COMMENTS |
1229                                   G_KEY_FILE_KEEP_TRANSLATIONS, error))
1230     {
1231       g_key_file_free (keyfile);
1232       return FALSE;
1233     }
1234
1235   old_mimetypes = g_key_file_get_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL);
1236   new_mimetypes = g_strconcat (content_type, ";", old_mimetypes, NULL);
1237   g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, new_mimetypes);
1238   g_free (old_mimetypes);
1239   g_free (new_mimetypes);
1240
1241   content = g_key_file_to_data (keyfile, NULL, NULL);
1242   g_key_file_free (keyfile);
1243
1244   dirname = ensure_dir (APP_DIR, error);
1245   if (!dirname)
1246     {
1247       g_free (content);
1248       return FALSE;
1249     }
1250   
1251   filename = g_build_filename (dirname, info->desktop_id, NULL);
1252   g_free (dirname);
1253   
1254   if (!g_file_set_contents (filename, content, -1, error))
1255     {
1256       g_free (filename);
1257       g_free (content);
1258       return FALSE;
1259     }
1260   g_free (filename);
1261   g_free (content);
1262
1263   run_update_command ("update-desktop-database", "applications");
1264   return TRUE;
1265 }
1266
1267 static gboolean
1268 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
1269 {
1270   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1271   char *user_dirname;
1272   
1273   user_dirname = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1274   return g_str_has_prefix (info->filename, user_dirname);
1275 }
1276
1277 static gboolean
1278 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
1279                                          const char  *content_type,
1280                                          GError     **error)
1281 {
1282   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1283   GKeyFile *keyfile;
1284   char *new_mimetypes, *old_mimetypes, *content;
1285   char *found;
1286   char *filename;
1287   char *dirname;
1288
1289   keyfile = g_key_file_new ();
1290   if (!g_key_file_load_from_file (keyfile, info->filename,
1291                                   G_KEY_FILE_KEEP_COMMENTS |
1292                                   G_KEY_FILE_KEEP_TRANSLATIONS, error))
1293     {
1294       g_key_file_free (keyfile);
1295       return FALSE;
1296     }
1297
1298   old_mimetypes = g_key_file_get_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL);
1299   new_mimetypes = g_strdup (old_mimetypes);
1300   found = NULL;
1301   if (new_mimetypes)
1302     found = strstr (new_mimetypes, content_type);
1303   if (found && *(found + strlen (content_type)) == ';')
1304     {
1305       char *rest = found + strlen (content_type) + 1;
1306       memmove (found, rest, strlen (rest) + 1);
1307     }
1308   g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, new_mimetypes);
1309   g_free (old_mimetypes);
1310   g_free (new_mimetypes);
1311
1312   content = g_key_file_to_data (keyfile, NULL, NULL);
1313   g_key_file_free (keyfile);
1314
1315   dirname = ensure_dir (APP_DIR, error);
1316   if (!dirname)
1317     {
1318       g_free (content);
1319       return FALSE;
1320     }
1321   
1322   filename = g_build_filename (dirname, info->desktop_id, NULL);
1323   g_free (dirname);
1324   if (!g_file_set_contents (filename, content, -1, error))
1325     {
1326       g_free (filename);
1327       g_free (content);
1328       return FALSE;
1329     }
1330   g_free (filename);
1331   g_free (content);
1332
1333   run_update_command ("update-desktop-database", "applications");
1334
1335   return update_default_list (info->desktop_id, content_type, FALSE, error);
1336 }
1337
1338 /**
1339  * g_app_info_create_from_commandline:
1340  * @commandline: the commandline to use
1341  * @application_name: the application name, or %NULL to use @commandline
1342  * @flags: flags that can specify details of the created #GAppInfo
1343  * @error: a #GError location to store the error occuring, %NULL to ignore.
1344  *
1345  * Creates a new #GAppInfo from the given information.
1346  *
1347  * Returns: new #GAppInfo for given command.
1348  **/
1349 GAppInfo *
1350 g_app_info_create_from_commandline (const char           *commandline,
1351                                     const char           *application_name,
1352                                     GAppInfoCreateFlags   flags,
1353                                     GError              **error)
1354 {
1355   GKeyFile *key_file;
1356   char *dirname;
1357   char **split;
1358   char *basename, *exec, *filename, *comment;
1359   char *data, *desktop_id;
1360   gsize data_size;
1361   int fd;
1362   GDesktopAppInfo *info;
1363   gboolean res;
1364
1365   dirname = ensure_dir (APP_DIR, error);
1366   if (!dirname)
1367     return NULL;
1368   
1369   key_file = g_key_file_new ();
1370
1371   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1372                          "Encoding", "UTF-8");
1373   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1374                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
1375   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1376                          G_KEY_FILE_DESKTOP_KEY_TYPE,
1377                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
1378   if (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) 
1379     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1380                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
1381
1382   exec = g_strconcat (commandline, " %f", NULL);
1383   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1384                          G_KEY_FILE_DESKTOP_KEY_EXEC, exec);
1385   g_free (exec);
1386
1387   /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
1388   split = g_strsplit (commandline, " ", 2);
1389   basename = g_path_get_basename (split[0]);
1390   g_strfreev (split);
1391   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1392                          G_KEY_FILE_DESKTOP_KEY_NAME, application_name?application_name:basename);
1393
1394   comment = g_strdup_printf (_("Custom definition for %s"), basename);
1395   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1396                          G_KEY_FILE_DESKTOP_KEY_COMMENT, comment);
1397   g_free (comment);
1398   
1399   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1400                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
1401
1402   data = g_key_file_to_data (key_file, &data_size, NULL);
1403   g_key_file_free (key_file);
1404
1405   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", basename);
1406   g_free (basename);
1407   filename = g_build_filename (dirname, desktop_id, NULL);
1408   g_free (desktop_id);
1409   g_free (dirname);
1410   
1411   fd = g_mkstemp (filename);
1412   if (fd == -1)
1413     {
1414       char *display_name;
1415
1416       display_name = g_filename_display_name (filename);
1417       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1418                    _("Can't create user desktop file %s"), display_name);
1419       g_free (display_name);
1420       g_free (filename);
1421       g_free (data);
1422       return NULL;
1423     }
1424
1425   desktop_id = g_path_get_basename (filename);
1426
1427   close (fd);
1428   
1429   res = g_file_set_contents (filename, data, data_size, error);
1430   if (!res)
1431     {
1432       g_free (desktop_id);
1433       g_free (filename);
1434       return NULL;
1435     }
1436
1437   run_update_command ("update-desktop-database", "applications");
1438   
1439   info = _g_desktop_app_info_new_from_filename (filename);
1440   g_free (filename);
1441   if (info == NULL) 
1442     g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1443                  _("Can't load just created desktop file"));
1444   else
1445     info->desktop_id = g_strdup (desktop_id);
1446     
1447   g_free (desktop_id);
1448   
1449   return G_APP_INFO (info);
1450 }
1451
1452
1453 static void
1454 g_desktop_app_info_iface_init (GAppInfoIface *iface)
1455 {
1456   iface->dup = g_desktop_app_info_dup;
1457   iface->equal = g_desktop_app_info_equal;
1458   iface->get_id = g_desktop_app_info_get_id;
1459   iface->get_name = g_desktop_app_info_get_name;
1460   iface->get_description = g_desktop_app_info_get_description;
1461   iface->get_executable = g_desktop_app_info_get_executable;
1462   iface->get_icon = g_desktop_app_info_get_icon;
1463   iface->launch = g_desktop_app_info_launch;
1464   iface->supports_uris = g_desktop_app_info_supports_uris;
1465   iface->supports_xdg_startup_notify = g_desktop_app_info_supports_xdg_startup_notify;
1466   iface->launch_uris = g_desktop_app_info_launch_uris;
1467   iface->should_show = g_desktop_app_info_should_show;
1468   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
1469   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
1470   iface->add_supports_type = g_desktop_app_info_add_supports_type;
1471   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
1472   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
1473 }
1474
1475 static gboolean
1476 app_info_in_list (GAppInfo *info, 
1477                   GList    *list)
1478 {
1479   while (list != NULL)
1480     {
1481       if (g_app_info_equal (info, list->data))
1482         return TRUE;
1483       list = list->next;
1484     }
1485   return FALSE;
1486 }
1487
1488
1489 /**
1490  * g_app_info_get_all_for_type:
1491  * @content_type: the content type to find a #GAppInfo for
1492  * 
1493  * Gets a list of all #GAppInfo s for a given content type.
1494  *
1495  * Returns: #GList of #GAppInfo s for given @content_type.
1496  **/
1497 GList *
1498 g_app_info_get_all_for_type (const char *content_type)
1499 {
1500   GList *desktop_entries, *l;
1501   GList *infos;
1502   GDesktopAppInfo *info;
1503   
1504   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1505
1506   infos = NULL;
1507   for (l = desktop_entries; l != NULL; l = l->next)
1508     {
1509       char *desktop_entry = l->data;
1510
1511       info = _g_desktop_app_info_new (desktop_entry);
1512       if (info)
1513         {
1514           if (app_info_in_list (G_APP_INFO (info), infos))
1515             g_object_unref (info);
1516           else
1517             infos = g_list_prepend (infos, info);
1518         }
1519       g_free (desktop_entry);
1520     }
1521
1522   g_list_free (desktop_entries);
1523   
1524   return g_list_reverse (infos);
1525 }
1526
1527
1528 /**
1529  * g_app_info_get_default_for_type:
1530  * @content_type: the content type to find a #GAppInfo for
1531  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
1532  *     support URIs
1533  * 
1534  * Gets the #GAppInfo that correspond to a given content type.
1535  *
1536  * Returns: #GAppInfo for given @content_type.
1537  **/
1538 GAppInfo *
1539 g_app_info_get_default_for_type (const char *content_type,
1540                                  gboolean    must_support_uris)
1541 {
1542   GList *desktop_entries, *l;
1543   GAppInfo *info;
1544   
1545   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1546
1547   info = NULL;
1548   for (l = desktop_entries; l != NULL; l = l->next)
1549     {
1550       char *desktop_entry = l->data;
1551
1552       info = (GAppInfo *)_g_desktop_app_info_new (desktop_entry);
1553       if (info)
1554         {
1555           if (must_support_uris && !g_app_info_supports_uris (info))
1556             {
1557               g_object_unref (info);
1558               info = NULL;
1559             }
1560           else
1561             break;
1562         }
1563     }
1564   
1565   g_list_foreach  (desktop_entries, (GFunc)g_free, NULL);
1566   g_list_free (desktop_entries);
1567   
1568   return info;
1569 }
1570
1571
1572 /**
1573  * g_app_info_get_default_for_uri_scheme:
1574  * @uri_scheme:
1575  * 
1576  * Returns: #GAppInfo
1577  **/
1578 GAppInfo *
1579 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
1580 {
1581   /* TODO: Implement this using giomodules, reading the gconf settings
1582    * in /desktop/gnome/url-handlers
1583    */
1584   return NULL;
1585 }
1586
1587
1588 static void
1589 get_apps_from_dir (GHashTable *apps, 
1590                    const char *dirname, 
1591                    const char *prefix)
1592 {
1593   GDir *dir;
1594   const char *basename;
1595   char *filename, *subprefix, *desktop_id;
1596   gboolean hidden;
1597   GDesktopAppInfo *appinfo;
1598   
1599   dir = g_dir_open (dirname, 0, NULL);
1600   if (dir)
1601     {
1602       while ((basename = g_dir_read_name (dir)) != NULL)
1603         {
1604           filename = g_build_filename (dirname, basename, NULL);
1605           if (g_str_has_suffix (basename, ".desktop"))
1606             {
1607               desktop_id = g_strconcat (prefix, basename, NULL);
1608
1609               /* Use _extended so we catch NULLs too (hidden) */
1610               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
1611                 {
1612                   appinfo = _g_desktop_app_info_new_from_filename (filename);
1613
1614                   /* Don't return apps that don't take arguments */
1615                   if (appinfo &&
1616                       _g_desktop_app_info_get_is_hidden (appinfo) &&
1617                       strstr (appinfo->exec,"%U") == NULL &&
1618                       strstr (appinfo->exec,"%u") == NULL &&
1619                       strstr (appinfo->exec,"%f") == NULL &&
1620                       strstr (appinfo->exec,"%F") == NULL)
1621                     {
1622                       g_object_unref (appinfo);
1623                       appinfo = NULL;
1624                       hidden = TRUE;
1625                     }
1626                                       
1627                   if (appinfo != NULL || hidden)
1628                     {
1629                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
1630
1631                       if (appinfo)
1632                         {
1633                           /* Reuse instead of strdup here */
1634                           appinfo->desktop_id = desktop_id;
1635                           desktop_id = NULL;
1636                         }
1637                     }
1638                 }
1639               g_free (desktop_id);
1640             }
1641           else
1642             {
1643               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
1644                 {
1645                   subprefix = g_strconcat (prefix, basename, "-", NULL);
1646                   get_apps_from_dir (apps, filename, subprefix);
1647                   g_free (subprefix);
1648                 }
1649             }
1650           g_free (filename);
1651         }
1652       g_dir_close (dir);
1653     }
1654 }
1655
1656 static void
1657 collect_apps (gpointer key,
1658               gpointer value,
1659               gpointer user_data)
1660 {
1661   GList **infos = user_data;
1662
1663   if (value)
1664     *infos = g_list_prepend (*infos, value);
1665 }
1666
1667
1668 /**
1669  * g_app_info_get_all:
1670  * 
1671  * Returns: a newly allocated #GList of references to #GAppInfo s.
1672  **/
1673 GList *
1674 g_app_info_get_all (void)
1675 {
1676   const char * const *dirs;
1677   GHashTable *apps;
1678   int i;
1679   GList *infos;
1680
1681   dirs = get_applications_search_path ();
1682
1683   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
1684                                 g_free, NULL);
1685
1686   
1687   for (i = 0; dirs[i] != NULL; i++)
1688     get_apps_from_dir (apps, dirs[i], "");
1689
1690
1691   infos = NULL;
1692   g_hash_table_foreach (apps,
1693                         collect_apps,
1694                         &infos);
1695
1696   g_hash_table_destroy (apps);
1697
1698   return g_list_reverse (infos);
1699 }
1700
1701 /* Cacheing of mimeinfo.cache and defaults.list files */
1702
1703 typedef struct {
1704   char *path;
1705   GHashTable *mime_info_cache_map;
1706   GHashTable *defaults_list_map;
1707   time_t mime_info_cache_timestamp;
1708   time_t defaults_list_timestamp;
1709 } MimeInfoCacheDir;
1710
1711 typedef struct {
1712   GList *dirs;                       /* mimeinfo.cache and defaults.list */
1713   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
1714   time_t last_stat_time;
1715   guint should_ping_mime_monitor : 1;
1716 } MimeInfoCache;
1717
1718 static MimeInfoCache *mime_info_cache = NULL;
1719 G_LOCK_DEFINE_STATIC (mime_info_cache);
1720
1721 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
1722                                                      const char        *mime_type,
1723                                                      char             **new_desktop_file_ids);
1724
1725 static MimeInfoCache * mime_info_cache_new (void);
1726
1727 static void
1728 destroy_info_cache_value (gpointer  key, 
1729                           GList    *value, 
1730                           gpointer  data)
1731 {
1732   g_list_foreach (value, (GFunc)g_free, NULL);
1733   g_list_free (value);
1734 }
1735
1736 static void
1737 destroy_info_cache_map (GHashTable *info_cache_map)
1738 {
1739   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
1740   g_hash_table_destroy (info_cache_map);
1741 }
1742
1743 static gboolean
1744 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
1745                                  const char       *cache_file,
1746                                  time_t           *timestamp)
1747 {
1748   struct stat buf;
1749   char *filename;
1750   
1751   filename = g_build_filename (dir->path, cache_file, NULL);
1752   
1753   if (g_stat (filename, &buf) < 0)
1754     {
1755       g_free (filename);
1756       return TRUE;
1757     }
1758   g_free (filename);
1759
1760   if (buf.st_mtime != *timestamp) 
1761     return TRUE;
1762   
1763   return FALSE;
1764 }
1765
1766 /* Call with lock held */
1767 static gboolean
1768 remove_all (gpointer  key,
1769             gpointer  value,
1770             gpointer  user_data)
1771 {
1772   return TRUE;
1773 }
1774
1775
1776 static void
1777 mime_info_cache_blow_global_cache (void)
1778 {
1779   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
1780                                remove_all, NULL);
1781 }
1782
1783 static void
1784 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
1785 {
1786   GError *load_error;
1787   GKeyFile *key_file;
1788   gchar *filename, **mime_types;
1789   int i;
1790   struct stat buf;
1791   
1792   load_error = NULL;
1793   mime_types = NULL;
1794   
1795   if (dir->mime_info_cache_map != NULL &&
1796       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
1797                                         &dir->mime_info_cache_timestamp))
1798     return;
1799   
1800   if (dir->mime_info_cache_map != NULL)
1801     destroy_info_cache_map (dir->mime_info_cache_map);
1802   
1803   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1804                                                     (GDestroyNotify) g_free,
1805                                                     NULL);
1806   
1807   key_file = g_key_file_new ();
1808   
1809   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
1810   
1811   if (g_stat (filename, &buf) < 0)
1812     goto error;
1813   
1814   if (dir->mime_info_cache_timestamp > 0) 
1815     mime_info_cache->should_ping_mime_monitor = TRUE;
1816   
1817   dir->mime_info_cache_timestamp = buf.st_mtime;
1818   
1819   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1820   
1821   g_free (filename);
1822   filename = NULL;
1823   
1824   if (load_error != NULL)
1825     goto error;
1826   
1827   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
1828                                     NULL, &load_error);
1829   
1830   if (load_error != NULL)
1831     goto error;
1832   
1833   for (i = 0; mime_types[i] != NULL; i++)
1834     {
1835       gchar **desktop_file_ids;
1836       char *unaliased_type;
1837       desktop_file_ids = g_key_file_get_string_list (key_file,
1838                                                      MIME_CACHE_GROUP,
1839                                                      mime_types[i],
1840                                                      NULL,
1841                                                      NULL);
1842       
1843       if (desktop_file_ids == NULL)
1844         continue;
1845
1846       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1847       mime_info_cache_dir_add_desktop_entries (dir,
1848                                                unaliased_type,
1849                                                desktop_file_ids);
1850       g_free (unaliased_type);
1851     
1852       g_strfreev (desktop_file_ids);
1853     }
1854   
1855   g_strfreev (mime_types);
1856   g_key_file_free (key_file);
1857   
1858   return;
1859  error:
1860   g_free (filename);
1861   g_key_file_free (key_file);
1862   
1863   if (mime_types != NULL)
1864     g_strfreev (mime_types);
1865   
1866   if (load_error)
1867     g_error_free (load_error);
1868 }
1869
1870 static void
1871 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
1872 {
1873   GKeyFile *key_file;
1874   GError *load_error;
1875   gchar *filename, **mime_types;
1876   char *unaliased_type;
1877   char **desktop_file_ids;
1878   int i;
1879   struct stat buf;
1880
1881   load_error = NULL;
1882   mime_types = NULL;
1883
1884   if (dir->defaults_list_map != NULL &&
1885       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
1886                                         &dir->defaults_list_timestamp))
1887     return;
1888   
1889   if (dir->defaults_list_map != NULL)
1890     g_hash_table_destroy (dir->defaults_list_map);
1891
1892   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1893                                                   g_free, (GDestroyNotify)g_strfreev);
1894
1895   key_file = g_key_file_new ();
1896   
1897   filename = g_build_filename (dir->path, "defaults.list", NULL);
1898   if (g_stat (filename, &buf) < 0)
1899     goto error;
1900
1901   if (dir->defaults_list_timestamp > 0) 
1902     mime_info_cache->should_ping_mime_monitor = TRUE;
1903
1904   dir->defaults_list_timestamp = buf.st_mtime;
1905
1906   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1907   g_free (filename);
1908   filename = NULL;
1909
1910   if (load_error != NULL)
1911     goto error;
1912
1913   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
1914                                     NULL, &load_error);
1915
1916   if (load_error != NULL)
1917     goto error;
1918
1919   for (i = 0; mime_types[i] != NULL; i++)
1920     {
1921       desktop_file_ids = g_key_file_get_string_list (key_file,
1922                                                      DEFAULT_APPLICATIONS_GROUP,
1923                                                      mime_types[i],
1924                                                      NULL,
1925                                                      NULL);
1926       if (desktop_file_ids == NULL)
1927         continue;
1928
1929       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1930       g_hash_table_replace (dir->defaults_list_map,
1931                             unaliased_type,
1932                             desktop_file_ids);
1933     }
1934
1935   g_strfreev (mime_types);
1936   g_key_file_free (key_file);
1937   
1938   return;
1939  error:
1940   g_free (filename);
1941   g_key_file_free (key_file);
1942   
1943   if (mime_types != NULL)
1944     g_strfreev (mime_types);
1945   
1946   if (load_error)
1947     g_error_free (load_error);
1948 }
1949
1950 static MimeInfoCacheDir *
1951 mime_info_cache_dir_new (const char *path)
1952 {
1953   MimeInfoCacheDir *dir;
1954
1955   dir = g_new0 (MimeInfoCacheDir, 1);
1956   dir->path = g_strdup (path);
1957   
1958   return dir;
1959 }
1960
1961 static void
1962 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
1963 {
1964   if (dir == NULL)
1965     return;
1966   
1967   if (dir->mime_info_cache_map != NULL)
1968     {
1969       destroy_info_cache_map (dir->mime_info_cache_map);
1970       dir->mime_info_cache_map = NULL;
1971       
1972   }
1973   
1974   if (dir->defaults_list_map != NULL)
1975     {
1976       g_hash_table_destroy (dir->defaults_list_map);
1977       dir->defaults_list_map = NULL;
1978     }
1979   
1980   g_free (dir);
1981 }
1982
1983 static void
1984 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
1985                                          const char        *mime_type,
1986                                          char             **new_desktop_file_ids)
1987 {
1988   GList *desktop_file_ids;
1989   int i;
1990   
1991   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
1992                                           mime_type);
1993   
1994   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
1995     {
1996       if (!g_list_find (desktop_file_ids, new_desktop_file_ids[i]))
1997         desktop_file_ids = g_list_append (desktop_file_ids,
1998                                           g_strdup (new_desktop_file_ids[i]));
1999     }
2000   
2001   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2002 }
2003
2004 static void
2005 mime_info_cache_init_dir_lists (void)
2006 {
2007   const char * const *dirs;
2008   int i;
2009   
2010   mime_info_cache = mime_info_cache_new ();
2011   
2012   dirs = get_applications_search_path ();
2013   
2014   for (i = 0; dirs[i] != NULL; i++)
2015     {
2016       MimeInfoCacheDir *dir;
2017       
2018       dir = mime_info_cache_dir_new (dirs[i]);
2019       
2020       if (dir != NULL)
2021         {
2022           mime_info_cache_dir_init (dir);
2023           mime_info_cache_dir_init_defaults_list (dir);
2024           
2025           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2026         }
2027     }
2028 }
2029
2030 static void
2031 mime_info_cache_update_dir_lists (void)
2032 {
2033   GList *tmp;
2034   
2035   tmp = mime_info_cache->dirs;
2036   
2037   while (tmp != NULL)
2038     {
2039       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2040
2041       /* No need to do this if we had file monitors... */
2042       mime_info_cache_blow_global_cache ();
2043       mime_info_cache_dir_init (dir);
2044       mime_info_cache_dir_init_defaults_list (dir);
2045       
2046       tmp = tmp->next;
2047     }
2048 }
2049
2050 static void
2051 mime_info_cache_init (void)
2052 {
2053         G_LOCK (mime_info_cache);
2054         if (mime_info_cache == NULL)
2055           mime_info_cache_init_dir_lists ();
2056         else
2057           {
2058             time_t now;
2059             
2060             time (&now);
2061             if (now >= mime_info_cache->last_stat_time + 10)
2062               {
2063                 mime_info_cache_update_dir_lists ();
2064                 mime_info_cache->last_stat_time = now;
2065               }
2066           }
2067
2068         if (mime_info_cache->should_ping_mime_monitor)
2069           {
2070             /* g_idle_add (emit_mime_changed, NULL); */
2071             mime_info_cache->should_ping_mime_monitor = FALSE;
2072           }
2073         
2074         G_UNLOCK (mime_info_cache);
2075 }
2076
2077 static MimeInfoCache *
2078 mime_info_cache_new (void)
2079 {
2080   MimeInfoCache *cache;
2081   
2082   cache = g_new0 (MimeInfoCache, 1);
2083   
2084   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2085                                                         (GDestroyNotify) g_free,
2086                                                         (GDestroyNotify) g_free);
2087   return cache;
2088 }
2089
2090 static void
2091 mime_info_cache_free (MimeInfoCache *cache)
2092 {
2093   if (cache == NULL)
2094     return;
2095   
2096   g_list_foreach (cache->dirs,
2097                   (GFunc) mime_info_cache_dir_free,
2098                   NULL);
2099   g_list_free (cache->dirs);
2100   g_hash_table_destroy (cache->global_defaults_cache);
2101   g_free (cache);
2102 }
2103
2104 /**
2105  * mime_info_cache_reload:
2106  * @dir: directory path which needs reloading.
2107  * 
2108  * Reload the mime information for the @dir.
2109  */
2110 static void
2111 mime_info_cache_reload (const char *dir)
2112 {
2113   /* FIXME: just reload the dir that needs reloading,
2114    * don't blow the whole cache
2115    */
2116   if (mime_info_cache != NULL)
2117     {
2118       G_LOCK (mime_info_cache);
2119       mime_info_cache_free (mime_info_cache);
2120       mime_info_cache = NULL;
2121       G_UNLOCK (mime_info_cache);
2122     }
2123 }
2124
2125 static GList *
2126 append_desktop_entry (GList      *list, 
2127                       const char *desktop_entry)
2128 {
2129   /* Add if not already in list, and valid */
2130   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp))
2131     list = g_list_prepend (list, g_strdup (desktop_entry));
2132   
2133   return list;
2134 }
2135
2136 /**
2137  * get_all_desktop_entries_for_mime_type:
2138  * @mime_type: a mime type.
2139  *
2140  * Returns all the desktop filenames for @mime_type. The desktop files
2141  * are listed in an order so that default applications are listed before
2142  * non-default ones, and handlers for inherited mimetypes are listed
2143  * after the base ones.
2144  *
2145  * Return value: a #GList containing the desktop filenames containing the
2146  * @mime_type.
2147  */
2148 static GList *
2149 get_all_desktop_entries_for_mime_type (const char *base_mime_type)
2150 {
2151   GList *desktop_entries, *list, *dir_list, *tmp;
2152   MimeInfoCacheDir *dir;
2153   char *mime_type;
2154   char **mime_types;
2155   char **default_entries;
2156   int i,j;
2157   
2158   mime_info_cache_init ();
2159
2160   mime_types = _g_unix_content_type_get_parents (base_mime_type);
2161   G_LOCK (mime_info_cache);
2162   
2163   desktop_entries = NULL;
2164   for (i = 0; mime_types[i] != NULL; i++)
2165     {
2166       mime_type = mime_types[i];
2167
2168       /* Go through all apps listed as defaults */
2169       for (dir_list = mime_info_cache->dirs;
2170            dir_list != NULL;
2171            dir_list = dir_list->next)
2172         {
2173           dir = dir_list->data;
2174           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
2175           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2176             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j]);
2177         }
2178
2179       /* Go through all entries that support the mimetype */
2180       for (dir_list = mime_info_cache->dirs;
2181            dir_list != NULL;
2182            dir_list = dir_list->next) {
2183         dir = dir_list->data;
2184         
2185         list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
2186         for (tmp = list; tmp != NULL; tmp = tmp->next) {
2187           desktop_entries = append_desktop_entry (desktop_entries, tmp->data);
2188         }
2189       }
2190     }
2191   
2192   G_UNLOCK (mime_info_cache);
2193
2194   g_strfreev (mime_types);
2195   
2196   desktop_entries = g_list_reverse (desktop_entries);
2197   
2198   return desktop_entries;
2199 }
2200
2201 #define __G_DESKTOP_APP_INFO_C__
2202 #include "gioaliasdef.c"