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