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