Documentation updates
[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_launch_uris (GAppInfo           *appinfo,
955                                 GList              *uris,
956                                 GAppLaunchContext  *launch_context,
957                                 GError            **error)
958 {
959   GList *files;
960   GFile *file;
961   gboolean res;
962
963   files = NULL;
964   while (uris)
965     {
966       file = g_file_new_for_uri (uris->data);
967       if (file == NULL)
968         g_warning ("Invalid uri passed to g_desktop_app_info_launch_uris");
969       
970       if (file)
971         files = g_list_prepend (files, file);
972     }
973   
974   files = g_list_reverse (files);
975   
976   res = g_desktop_app_info_launch (appinfo, files, launch_context, error);
977   
978   g_list_foreach  (files, (GFunc)g_object_unref, NULL);
979   g_list_free (files);
980   
981   return res;
982 }
983
984 static gboolean
985 g_desktop_app_info_should_show (GAppInfo   *appinfo,
986                                 const char *desktop_env)
987 {
988   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
989   gboolean found;
990   int i;
991
992   if (info->nodisplay)
993     return FALSE;
994
995   if (info->only_show_in)
996     {
997       if (desktop_env == NULL)
998         return FALSE;
999       
1000       found = FALSE;
1001       for (i = 0; info->only_show_in[i] != NULL; i++)
1002         {
1003           if (strcmp (info->only_show_in[i], desktop_env) == 0)
1004             {
1005               found = TRUE;
1006               break;
1007             }
1008         }
1009       if (!found)
1010         return FALSE;
1011     }
1012
1013   if (info->not_show_in && desktop_env)
1014     {
1015       for (i = 0; info->not_show_in[i] != NULL; i++)
1016         {
1017           if (strcmp (info->not_show_in[i], desktop_env) == 0)
1018             return FALSE;
1019         }
1020     }
1021   
1022   return TRUE;
1023 }
1024
1025 typedef enum {
1026   APP_DIR,
1027   MIMETYPE_DIR
1028 } DirType;
1029
1030 static char *
1031 ensure_dir (DirType   type,
1032             GError  **error)
1033 {
1034   char *path, *display_name;
1035   int err;
1036
1037   if (type == APP_DIR)
1038     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1039   else
1040     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
1041
1042   errno = 0;
1043   if (g_mkdir_with_parents (path, 0700) == 0)
1044     return path;
1045
1046   err = errno;
1047   display_name = g_filename_display_name (path);
1048   if (type == APP_DIR)
1049     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (err),
1050                  _("Can't create user application configuration folder %s: %s"),
1051                  display_name, g_strerror (err));
1052   else
1053     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (err),
1054                  _("Can't create user MIME configuration folder %s: %s"),
1055                  display_name, g_strerror (err));
1056
1057   g_free (display_name);
1058   g_free (path);
1059
1060   return NULL;
1061 }
1062
1063 static gboolean
1064 update_default_list (const char  *desktop_id, 
1065                      const char  *content_type, 
1066                      gboolean     add, 
1067                      GError     **error)
1068 {
1069   char *dirname, *filename;
1070   GKeyFile *key_file;
1071   gboolean load_succeeded, res;
1072   char **old_list;
1073   char **list;
1074   gsize length, data_size;
1075   char *data;
1076   int i, j;
1077
1078   dirname = ensure_dir (APP_DIR, error);
1079   if (!dirname)
1080     return FALSE;
1081
1082   filename = g_build_filename (dirname, "defaults.list", NULL);
1083   g_free (dirname);
1084
1085   key_file = g_key_file_new ();
1086   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
1087   if (!load_succeeded || !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP))
1088     {
1089       g_key_file_free (key_file);
1090       key_file = g_key_file_new ();
1091     }
1092
1093   length = 0;
1094   old_list = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP,
1095                                          content_type, &length, NULL);
1096
1097   list = g_new (char *, 1 + length + 1);
1098
1099   i = 0;
1100   if (add)
1101     list[i++] = g_strdup (desktop_id);
1102   if (old_list)
1103     {
1104       for (j = 0; old_list[j] != NULL; j++)
1105         {
1106           if (strcmp (old_list[j], desktop_id) != 0)
1107             list[i++] = g_strdup (old_list[j]);
1108         }
1109     }
1110   list[i] = NULL;
1111   
1112   g_strfreev (old_list);
1113
1114   g_key_file_set_string_list (key_file,
1115                               DEFAULT_APPLICATIONS_GROUP,
1116                               content_type,
1117                               (const char * const *)list, i);
1118
1119   g_strfreev (list);
1120   
1121   data = g_key_file_to_data (key_file, &data_size, error);
1122   g_key_file_free (key_file);
1123   
1124   res = g_file_set_contents (filename, data, data_size, error);
1125
1126   mime_info_cache_reload (NULL);
1127                           
1128   g_free (filename);
1129   g_free (data);
1130   
1131   return res;
1132 }
1133
1134 static gboolean
1135 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
1136                                             const char  *content_type,
1137                                             GError     **error)
1138 {
1139   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1140
1141   if (!g_app_info_add_supports_type (appinfo, content_type, error))
1142     return FALSE;
1143   
1144   return update_default_list (info->desktop_id, content_type, TRUE, error);
1145 }
1146
1147 static void
1148 update_program_done (GPid     pid,
1149                      gint     status,
1150                      gpointer data)
1151 {
1152   /* Did the application exit correctly */
1153   if (WIFEXITED (status) &&
1154       WEXITSTATUS (status) == 0)
1155     {
1156       /* Here we could clean out any caches in use */
1157     }
1158 }
1159
1160 static void
1161 run_update_command (char *command,
1162                     char *subdir)
1163 {
1164         char *argv[3] = {
1165                 NULL,
1166                 NULL,
1167                 NULL,
1168         };
1169         GPid pid = 0;
1170         GError *error = NULL;
1171
1172         argv[0] = command;
1173         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
1174
1175         if (g_spawn_async ("/", argv,
1176                            NULL,       /* envp */
1177                            G_SPAWN_SEARCH_PATH |
1178                            G_SPAWN_STDOUT_TO_DEV_NULL |
1179                            G_SPAWN_STDERR_TO_DEV_NULL |
1180                            G_SPAWN_DO_NOT_REAP_CHILD,
1181                            NULL, NULL, /* No setup function */
1182                            &pid,
1183                            NULL)) 
1184           g_child_watch_add (pid, update_program_done, NULL);
1185         else
1186           {
1187             /* If we get an error at this point, it's quite likely the user doesn't
1188              * have an installed copy of either 'update-mime-database' or
1189              * 'update-desktop-database'.  I don't think we want to popup an error
1190              * dialog at this point, so we just do a g_warning to give the user a
1191              * chance of debugging it.
1192              */
1193             g_warning ("%s", error->message);
1194           }
1195         
1196         g_free (argv[1]);
1197 }
1198
1199 static gboolean
1200 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
1201                                                  const char  *extension,
1202                                                  GError     **error)
1203 {
1204   char *filename, *basename, *mimetype;
1205   char *dirname;
1206   gboolean res;
1207
1208   dirname = ensure_dir (MIMETYPE_DIR, error);
1209   if (!dirname)
1210     return FALSE;
1211   
1212   basename = g_strdup_printf ("user-extension-%s.xml", extension);
1213   filename = g_build_filename (dirname, basename, NULL);
1214   g_free (basename);
1215   g_free (dirname);
1216
1217   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
1218   
1219   if (!g_file_test (filename, G_FILE_TEST_EXISTS)) 
1220     {
1221       char *contents;
1222
1223       contents =
1224         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1225                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
1226                          " <mime-type type=\"%s\">\n"
1227                          "  <comment>%s document</comment>\n"
1228                          "  <glob pattern=\"*.%s\"/>\n"
1229                          " </mime-type>\n"
1230                          "</mime-info>\n", mimetype, extension, extension);
1231
1232       g_file_set_contents (filename, contents, -1, NULL);
1233       g_free (contents);
1234
1235       run_update_command ("update-mime-database", "mime");
1236     }
1237   g_free (filename);
1238   
1239   res = g_desktop_app_info_set_as_default_for_type (appinfo,
1240                                                     mimetype,
1241                                                     error);
1242
1243   g_free (mimetype);
1244   
1245   return res;
1246 }
1247
1248 static gboolean
1249 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
1250                                       const char  *content_type,
1251                                       GError     **error)
1252 {
1253   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1254   GKeyFile *keyfile;
1255   char *new_mimetypes, *old_mimetypes, *content;
1256   char *dirname;
1257   char *filename;
1258
1259   keyfile = g_key_file_new ();
1260   if (!g_key_file_load_from_file (keyfile, info->filename,
1261                                   G_KEY_FILE_KEEP_COMMENTS |
1262                                   G_KEY_FILE_KEEP_TRANSLATIONS, error))
1263     {
1264       g_key_file_free (keyfile);
1265       return FALSE;
1266     }
1267
1268   old_mimetypes = g_key_file_get_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL);
1269   new_mimetypes = g_strconcat (content_type, ";", old_mimetypes, NULL);
1270   g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, new_mimetypes);
1271   g_free (old_mimetypes);
1272   g_free (new_mimetypes);
1273
1274   content = g_key_file_to_data (keyfile, NULL, NULL);
1275   g_key_file_free (keyfile);
1276
1277   dirname = ensure_dir (APP_DIR, error);
1278   if (!dirname)
1279     {
1280       g_free (content);
1281       return FALSE;
1282     }
1283   
1284   filename = g_build_filename (dirname, info->desktop_id, NULL);
1285   g_free (dirname);
1286   
1287   if (!g_file_set_contents (filename, content, -1, error))
1288     {
1289       g_free (filename);
1290       g_free (content);
1291       return FALSE;
1292     }
1293   g_free (filename);
1294   g_free (content);
1295
1296   run_update_command ("update-desktop-database", "applications");
1297   return TRUE;
1298 }
1299
1300 static gboolean
1301 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
1302 {
1303   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1304   char *user_dirname;
1305   
1306   user_dirname = g_build_filename (g_get_user_data_dir (), "applications", NULL);
1307   return g_str_has_prefix (info->filename, user_dirname);
1308 }
1309
1310 static gboolean
1311 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
1312                                          const char  *content_type,
1313                                          GError     **error)
1314 {
1315   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1316   GKeyFile *keyfile;
1317   char *new_mimetypes, *old_mimetypes, *content;
1318   char *found;
1319   char *filename;
1320   char *dirname;
1321
1322   keyfile = g_key_file_new ();
1323   if (!g_key_file_load_from_file (keyfile, info->filename,
1324                                   G_KEY_FILE_KEEP_COMMENTS |
1325                                   G_KEY_FILE_KEEP_TRANSLATIONS, error))
1326     {
1327       g_key_file_free (keyfile);
1328       return FALSE;
1329     }
1330
1331   old_mimetypes = g_key_file_get_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL);
1332   new_mimetypes = g_strdup (old_mimetypes);
1333   found = NULL;
1334   if (new_mimetypes)
1335     found = strstr (new_mimetypes, content_type);
1336   if (found && *(found + strlen (content_type)) == ';')
1337     {
1338       char *rest = found + strlen (content_type) + 1;
1339       memmove (found, rest, strlen (rest) + 1);
1340     }
1341   g_key_file_set_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, new_mimetypes);
1342   g_free (old_mimetypes);
1343   g_free (new_mimetypes);
1344
1345   content = g_key_file_to_data (keyfile, NULL, NULL);
1346   g_key_file_free (keyfile);
1347
1348   dirname = ensure_dir (APP_DIR, error);
1349   if (!dirname)
1350     {
1351       g_free (content);
1352       return FALSE;
1353     }
1354   
1355   filename = g_build_filename (dirname, info->desktop_id, NULL);
1356   g_free (dirname);
1357   if (!g_file_set_contents (filename, content, -1, error))
1358     {
1359       g_free (filename);
1360       g_free (content);
1361       return FALSE;
1362     }
1363   g_free (filename);
1364   g_free (content);
1365
1366   run_update_command ("update-desktop-database", "applications");
1367
1368   return update_default_list (info->desktop_id, content_type, FALSE, error);
1369 }
1370
1371 /**
1372  * g_app_info_create_from_commandline:
1373  * @commandline: the commandline to use
1374  * @application_name: the application name, or %NULL to use @commandline
1375  * @flags: flags that can specify details of the created #GAppInfo
1376  * @error: a #GError location to store the error occuring, %NULL to ignore.
1377  *
1378  * Creates a new #GAppInfo from the given information.
1379  *
1380  * Returns: new #GAppInfo for given command.
1381  **/
1382 GAppInfo *
1383 g_app_info_create_from_commandline (const char           *commandline,
1384                                     const char           *application_name,
1385                                     GAppInfoCreateFlags   flags,
1386                                     GError              **error)
1387 {
1388   GKeyFile *key_file;
1389   char *dirname;
1390   char **split;
1391   char *basename, *exec, *filename, *comment;
1392   char *data, *desktop_id;
1393   gsize data_size;
1394   int fd;
1395   GDesktopAppInfo *info;
1396   gboolean res;
1397
1398   dirname = ensure_dir (APP_DIR, error);
1399   if (!dirname)
1400     return NULL;
1401   
1402   key_file = g_key_file_new ();
1403
1404   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1405                          "Encoding", "UTF-8");
1406   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1407                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
1408   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1409                          G_KEY_FILE_DESKTOP_KEY_TYPE,
1410                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
1411   if (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) 
1412     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1413                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
1414
1415   exec = g_strconcat (commandline, " %f", NULL);
1416   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1417                          G_KEY_FILE_DESKTOP_KEY_EXEC, exec);
1418   g_free (exec);
1419
1420   /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
1421   split = g_strsplit (commandline, " ", 2);
1422   basename = g_path_get_basename (split[0]);
1423   g_strfreev (split);
1424   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1425                          G_KEY_FILE_DESKTOP_KEY_NAME, application_name?application_name:basename);
1426
1427   comment = g_strdup_printf (_("Custom definition for %s"), basename);
1428   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
1429                          G_KEY_FILE_DESKTOP_KEY_COMMENT, comment);
1430   g_free (comment);
1431   
1432   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
1433                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
1434
1435   data = g_key_file_to_data (key_file, &data_size, NULL);
1436   g_key_file_free (key_file);
1437
1438   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", basename);
1439   g_free (basename);
1440   filename = g_build_filename (dirname, desktop_id, NULL);
1441   g_free (desktop_id);
1442   g_free (dirname);
1443   
1444   fd = g_mkstemp (filename);
1445   if (fd == -1)
1446     {
1447       char *display_name;
1448
1449       display_name = g_filename_display_name (filename);
1450       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1451                    _("Can't create user desktop file %s"), display_name);
1452       g_free (display_name);
1453       g_free (filename);
1454       g_free (data);
1455       return NULL;
1456     }
1457
1458   desktop_id = g_path_get_basename (filename);
1459
1460   close (fd);
1461   
1462   res = g_file_set_contents (filename, data, data_size, error);
1463   if (!res)
1464     {
1465       g_free (desktop_id);
1466       g_free (filename);
1467       return NULL;
1468     }
1469
1470   run_update_command ("update-desktop-database", "applications");
1471   
1472   info = g_desktop_app_info_new_from_filename (filename);
1473   g_free (filename);
1474   if (info == NULL) 
1475     g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1476                  _("Can't load just created desktop file"));
1477   else
1478     info->desktop_id = g_strdup (desktop_id);
1479     
1480   g_free (desktop_id);
1481   
1482   return G_APP_INFO (info);
1483 }
1484
1485
1486 static void
1487 g_desktop_app_info_iface_init (GAppInfoIface *iface)
1488 {
1489   iface->dup = g_desktop_app_info_dup;
1490   iface->equal = g_desktop_app_info_equal;
1491   iface->get_id = g_desktop_app_info_get_id;
1492   iface->get_name = g_desktop_app_info_get_name;
1493   iface->get_description = g_desktop_app_info_get_description;
1494   iface->get_executable = g_desktop_app_info_get_executable;
1495   iface->get_icon = g_desktop_app_info_get_icon;
1496   iface->launch = g_desktop_app_info_launch;
1497   iface->supports_uris = g_desktop_app_info_supports_uris;
1498   iface->launch_uris = g_desktop_app_info_launch_uris;
1499   iface->should_show = g_desktop_app_info_should_show;
1500   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
1501   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
1502   iface->add_supports_type = g_desktop_app_info_add_supports_type;
1503   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
1504   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
1505 }
1506
1507 static gboolean
1508 app_info_in_list (GAppInfo *info, 
1509                   GList    *list)
1510 {
1511   while (list != NULL)
1512     {
1513       if (g_app_info_equal (info, list->data))
1514         return TRUE;
1515       list = list->next;
1516     }
1517   return FALSE;
1518 }
1519
1520
1521 /**
1522  * g_app_info_get_all_for_type:
1523  * @content_type: the content type to find a #GAppInfo for
1524  * 
1525  * Gets a list of all #GAppInfo s for a given content type.
1526  *
1527  * Returns: #GList of #GAppInfo s for given @content_type.
1528  **/
1529 GList *
1530 g_app_info_get_all_for_type (const char *content_type)
1531 {
1532   GList *desktop_entries, *l;
1533   GList *infos;
1534   GDesktopAppInfo *info;
1535   
1536   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1537
1538   infos = NULL;
1539   for (l = desktop_entries; l != NULL; l = l->next)
1540     {
1541       char *desktop_entry = l->data;
1542
1543       info = g_desktop_app_info_new (desktop_entry);
1544       if (info)
1545         {
1546           if (app_info_in_list (G_APP_INFO (info), infos))
1547             g_object_unref (info);
1548           else
1549             infos = g_list_prepend (infos, info);
1550         }
1551       g_free (desktop_entry);
1552     }
1553
1554   g_list_free (desktop_entries);
1555   
1556   return g_list_reverse (infos);
1557 }
1558
1559
1560 /**
1561  * g_app_info_get_default_for_type:
1562  * @content_type: the content type to find a #GAppInfo for
1563  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
1564  *     support URIs
1565  * 
1566  * Gets the #GAppInfo that correspond to a given content type.
1567  *
1568  * Returns: #GAppInfo for given @content_type.
1569  **/
1570 GAppInfo *
1571 g_app_info_get_default_for_type (const char *content_type,
1572                                  gboolean    must_support_uris)
1573 {
1574   GList *desktop_entries, *l;
1575   GAppInfo *info;
1576   
1577   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1578
1579   info = NULL;
1580   for (l = desktop_entries; l != NULL; l = l->next)
1581     {
1582       char *desktop_entry = l->data;
1583
1584       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
1585       if (info)
1586         {
1587           if (must_support_uris && !g_app_info_supports_uris (info))
1588             {
1589               g_object_unref (info);
1590               info = NULL;
1591             }
1592           else
1593             break;
1594         }
1595     }
1596   
1597   g_list_foreach  (desktop_entries, (GFunc)g_free, NULL);
1598   g_list_free (desktop_entries);
1599   
1600   return info;
1601 }
1602
1603
1604 /**
1605  * g_app_info_get_default_for_uri_scheme:
1606  * @uri_scheme: a string containing a URI scheme.
1607  *
1608  * Gets the default application for launching applications 
1609  * using this URI scheme.
1610  *
1611  * TODO: This is currently unimplemented.
1612  * 
1613  * Returns: %NULL.
1614  **/
1615 GAppInfo *
1616 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
1617 {
1618   /* TODO: Implement this using giomodules, reading the gconf settings
1619    * in /desktop/gnome/url-handlers
1620    */
1621   return NULL;
1622 }
1623
1624
1625 static void
1626 get_apps_from_dir (GHashTable *apps, 
1627                    const char *dirname, 
1628                    const char *prefix)
1629 {
1630   GDir *dir;
1631   const char *basename;
1632   char *filename, *subprefix, *desktop_id;
1633   gboolean hidden;
1634   GDesktopAppInfo *appinfo;
1635   
1636   dir = g_dir_open (dirname, 0, NULL);
1637   if (dir)
1638     {
1639       while ((basename = g_dir_read_name (dir)) != NULL)
1640         {
1641           filename = g_build_filename (dirname, basename, NULL);
1642           if (g_str_has_suffix (basename, ".desktop"))
1643             {
1644               desktop_id = g_strconcat (prefix, basename, NULL);
1645
1646               /* Use _extended so we catch NULLs too (hidden) */
1647               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
1648                 {
1649                   appinfo = g_desktop_app_info_new_from_filename (filename);
1650
1651                   /* Don't return apps that don't take arguments */
1652                   if (appinfo &&
1653                       (g_desktop_app_info_get_is_hidden (appinfo) ||
1654                        (appinfo->exec && 
1655                         strstr (appinfo->exec,"%U") == NULL &&
1656                         strstr (appinfo->exec,"%u") == NULL &&
1657                         strstr (appinfo->exec,"%f") == NULL &&
1658                         strstr (appinfo->exec,"%F") == NULL)))
1659                     {
1660                       g_object_unref (appinfo);
1661                       appinfo = NULL;
1662                       hidden = TRUE;
1663                     }
1664                                       
1665                   if (appinfo != NULL || hidden)
1666                     {
1667                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
1668
1669                       if (appinfo)
1670                         {
1671                           /* Reuse instead of strdup here */
1672                           appinfo->desktop_id = desktop_id;
1673                           desktop_id = NULL;
1674                         }
1675                     }
1676                 }
1677               g_free (desktop_id);
1678             }
1679           else
1680             {
1681               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
1682                 {
1683                   subprefix = g_strconcat (prefix, basename, "-", NULL);
1684                   get_apps_from_dir (apps, filename, subprefix);
1685                   g_free (subprefix);
1686                 }
1687             }
1688           g_free (filename);
1689         }
1690       g_dir_close (dir);
1691     }
1692 }
1693
1694
1695 /**
1696  * g_app_info_get_all:
1697  *
1698  * Gets a list of all of the applications currently registered on this system.
1699  * 
1700  * Returns: a newly allocated #GList of references to #GAppInfo<!---->s.
1701  **/
1702 GList *
1703 g_app_info_get_all (void)
1704 {
1705   const char * const *dirs;
1706   GHashTable *apps;
1707   GHashTableIter iter;
1708   gpointer value;
1709   int i;
1710   GList *infos;
1711
1712   dirs = get_applications_search_path ();
1713
1714   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
1715                                 g_free, NULL);
1716
1717   
1718   for (i = 0; dirs[i] != NULL; i++)
1719     get_apps_from_dir (apps, dirs[i], "");
1720
1721
1722   infos = NULL;
1723   g_hash_table_iter_init (&iter, apps);
1724   while (g_hash_table_iter_next (&iter, NULL, &value))
1725     infos = g_list_prepend (infos, value);
1726
1727   g_hash_table_destroy (apps);
1728
1729   return g_list_reverse (infos);
1730 }
1731
1732 /* Cacheing of mimeinfo.cache and defaults.list files */
1733
1734 typedef struct {
1735   char *path;
1736   GHashTable *mime_info_cache_map;
1737   GHashTable *defaults_list_map;
1738   time_t mime_info_cache_timestamp;
1739   time_t defaults_list_timestamp;
1740 } MimeInfoCacheDir;
1741
1742 typedef struct {
1743   GList *dirs;                       /* mimeinfo.cache and defaults.list */
1744   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
1745   time_t last_stat_time;
1746   guint should_ping_mime_monitor : 1;
1747 } MimeInfoCache;
1748
1749 static MimeInfoCache *mime_info_cache = NULL;
1750 G_LOCK_DEFINE_STATIC (mime_info_cache);
1751
1752 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
1753                                                      const char        *mime_type,
1754                                                      char             **new_desktop_file_ids);
1755
1756 static MimeInfoCache * mime_info_cache_new (void);
1757
1758 static void
1759 destroy_info_cache_value (gpointer  key, 
1760                           GList    *value, 
1761                           gpointer  data)
1762 {
1763   g_list_foreach (value, (GFunc)g_free, NULL);
1764   g_list_free (value);
1765 }
1766
1767 static void
1768 destroy_info_cache_map (GHashTable *info_cache_map)
1769 {
1770   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
1771   g_hash_table_destroy (info_cache_map);
1772 }
1773
1774 static gboolean
1775 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
1776                                  const char       *cache_file,
1777                                  time_t           *timestamp)
1778 {
1779   struct stat buf;
1780   char *filename;
1781   
1782   filename = g_build_filename (dir->path, cache_file, NULL);
1783   
1784   if (g_stat (filename, &buf) < 0)
1785     {
1786       g_free (filename);
1787       return TRUE;
1788     }
1789   g_free (filename);
1790
1791   if (buf.st_mtime != *timestamp) 
1792     return TRUE;
1793   
1794   return FALSE;
1795 }
1796
1797 /* Call with lock held */
1798 static gboolean
1799 remove_all (gpointer  key,
1800             gpointer  value,
1801             gpointer  user_data)
1802 {
1803   return TRUE;
1804 }
1805
1806
1807 static void
1808 mime_info_cache_blow_global_cache (void)
1809 {
1810   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
1811                                remove_all, NULL);
1812 }
1813
1814 static void
1815 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
1816 {
1817   GError *load_error;
1818   GKeyFile *key_file;
1819   gchar *filename, **mime_types;
1820   int i;
1821   struct stat buf;
1822   
1823   load_error = NULL;
1824   mime_types = NULL;
1825   
1826   if (dir->mime_info_cache_map != NULL &&
1827       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
1828                                         &dir->mime_info_cache_timestamp))
1829     return;
1830   
1831   if (dir->mime_info_cache_map != NULL)
1832     destroy_info_cache_map (dir->mime_info_cache_map);
1833   
1834   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1835                                                     (GDestroyNotify) g_free,
1836                                                     NULL);
1837   
1838   key_file = g_key_file_new ();
1839   
1840   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
1841   
1842   if (g_stat (filename, &buf) < 0)
1843     goto error;
1844   
1845   if (dir->mime_info_cache_timestamp > 0) 
1846     mime_info_cache->should_ping_mime_monitor = TRUE;
1847   
1848   dir->mime_info_cache_timestamp = buf.st_mtime;
1849   
1850   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1851   
1852   g_free (filename);
1853   filename = NULL;
1854   
1855   if (load_error != NULL)
1856     goto error;
1857   
1858   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
1859                                     NULL, &load_error);
1860   
1861   if (load_error != NULL)
1862     goto error;
1863   
1864   for (i = 0; mime_types[i] != NULL; i++)
1865     {
1866       gchar **desktop_file_ids;
1867       char *unaliased_type;
1868       desktop_file_ids = g_key_file_get_string_list (key_file,
1869                                                      MIME_CACHE_GROUP,
1870                                                      mime_types[i],
1871                                                      NULL,
1872                                                      NULL);
1873       
1874       if (desktop_file_ids == NULL)
1875         continue;
1876
1877       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1878       mime_info_cache_dir_add_desktop_entries (dir,
1879                                                unaliased_type,
1880                                                desktop_file_ids);
1881       g_free (unaliased_type);
1882     
1883       g_strfreev (desktop_file_ids);
1884     }
1885   
1886   g_strfreev (mime_types);
1887   g_key_file_free (key_file);
1888   
1889   return;
1890  error:
1891   g_free (filename);
1892   g_key_file_free (key_file);
1893   
1894   if (mime_types != NULL)
1895     g_strfreev (mime_types);
1896   
1897   if (load_error)
1898     g_error_free (load_error);
1899 }
1900
1901 static void
1902 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
1903 {
1904   GKeyFile *key_file;
1905   GError *load_error;
1906   gchar *filename, **mime_types;
1907   char *unaliased_type;
1908   char **desktop_file_ids;
1909   int i;
1910   struct stat buf;
1911
1912   load_error = NULL;
1913   mime_types = NULL;
1914
1915   if (dir->defaults_list_map != NULL &&
1916       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
1917                                         &dir->defaults_list_timestamp))
1918     return;
1919   
1920   if (dir->defaults_list_map != NULL)
1921     g_hash_table_destroy (dir->defaults_list_map);
1922
1923   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1924                                                   g_free, (GDestroyNotify)g_strfreev);
1925
1926   key_file = g_key_file_new ();
1927   
1928   filename = g_build_filename (dir->path, "defaults.list", NULL);
1929   if (g_stat (filename, &buf) < 0)
1930     goto error;
1931
1932   if (dir->defaults_list_timestamp > 0) 
1933     mime_info_cache->should_ping_mime_monitor = TRUE;
1934
1935   dir->defaults_list_timestamp = buf.st_mtime;
1936
1937   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1938   g_free (filename);
1939   filename = NULL;
1940
1941   if (load_error != NULL)
1942     goto error;
1943
1944   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
1945                                     NULL, &load_error);
1946
1947   if (load_error != NULL)
1948     goto error;
1949
1950   for (i = 0; mime_types[i] != NULL; i++)
1951     {
1952       desktop_file_ids = g_key_file_get_string_list (key_file,
1953                                                      DEFAULT_APPLICATIONS_GROUP,
1954                                                      mime_types[i],
1955                                                      NULL,
1956                                                      NULL);
1957       if (desktop_file_ids == NULL)
1958         continue;
1959
1960       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1961       g_hash_table_replace (dir->defaults_list_map,
1962                             unaliased_type,
1963                             desktop_file_ids);
1964     }
1965
1966   g_strfreev (mime_types);
1967   g_key_file_free (key_file);
1968   
1969   return;
1970  error:
1971   g_free (filename);
1972   g_key_file_free (key_file);
1973   
1974   if (mime_types != NULL)
1975     g_strfreev (mime_types);
1976   
1977   if (load_error)
1978     g_error_free (load_error);
1979 }
1980
1981 static MimeInfoCacheDir *
1982 mime_info_cache_dir_new (const char *path)
1983 {
1984   MimeInfoCacheDir *dir;
1985
1986   dir = g_new0 (MimeInfoCacheDir, 1);
1987   dir->path = g_strdup (path);
1988   
1989   return dir;
1990 }
1991
1992 static void
1993 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
1994 {
1995   if (dir == NULL)
1996     return;
1997   
1998   if (dir->mime_info_cache_map != NULL)
1999     {
2000       destroy_info_cache_map (dir->mime_info_cache_map);
2001       dir->mime_info_cache_map = NULL;
2002       
2003   }
2004   
2005   if (dir->defaults_list_map != NULL)
2006     {
2007       g_hash_table_destroy (dir->defaults_list_map);
2008       dir->defaults_list_map = NULL;
2009     }
2010   
2011   g_free (dir);
2012 }
2013
2014 static void
2015 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2016                                          const char        *mime_type,
2017                                          char             **new_desktop_file_ids)
2018 {
2019   GList *desktop_file_ids;
2020   int i;
2021   
2022   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2023                                           mime_type);
2024   
2025   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2026     {
2027       if (!g_list_find (desktop_file_ids, new_desktop_file_ids[i]))
2028         desktop_file_ids = g_list_append (desktop_file_ids,
2029                                           g_strdup (new_desktop_file_ids[i]));
2030     }
2031   
2032   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2033 }
2034
2035 static void
2036 mime_info_cache_init_dir_lists (void)
2037 {
2038   const char * const *dirs;
2039   int i;
2040   
2041   mime_info_cache = mime_info_cache_new ();
2042   
2043   dirs = get_applications_search_path ();
2044   
2045   for (i = 0; dirs[i] != NULL; i++)
2046     {
2047       MimeInfoCacheDir *dir;
2048       
2049       dir = mime_info_cache_dir_new (dirs[i]);
2050       
2051       if (dir != NULL)
2052         {
2053           mime_info_cache_dir_init (dir);
2054           mime_info_cache_dir_init_defaults_list (dir);
2055           
2056           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2057         }
2058     }
2059 }
2060
2061 static void
2062 mime_info_cache_update_dir_lists (void)
2063 {
2064   GList *tmp;
2065   
2066   tmp = mime_info_cache->dirs;
2067   
2068   while (tmp != NULL)
2069     {
2070       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2071
2072       /* No need to do this if we had file monitors... */
2073       mime_info_cache_blow_global_cache ();
2074       mime_info_cache_dir_init (dir);
2075       mime_info_cache_dir_init_defaults_list (dir);
2076       
2077       tmp = tmp->next;
2078     }
2079 }
2080
2081 static void
2082 mime_info_cache_init (void)
2083 {
2084         G_LOCK (mime_info_cache);
2085         if (mime_info_cache == NULL)
2086           mime_info_cache_init_dir_lists ();
2087         else
2088           {
2089             time_t now;
2090             
2091             time (&now);
2092             if (now >= mime_info_cache->last_stat_time + 10)
2093               {
2094                 mime_info_cache_update_dir_lists ();
2095                 mime_info_cache->last_stat_time = now;
2096               }
2097           }
2098
2099         if (mime_info_cache->should_ping_mime_monitor)
2100           {
2101             /* g_idle_add (emit_mime_changed, NULL); */
2102             mime_info_cache->should_ping_mime_monitor = FALSE;
2103           }
2104         
2105         G_UNLOCK (mime_info_cache);
2106 }
2107
2108 static MimeInfoCache *
2109 mime_info_cache_new (void)
2110 {
2111   MimeInfoCache *cache;
2112   
2113   cache = g_new0 (MimeInfoCache, 1);
2114   
2115   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2116                                                         (GDestroyNotify) g_free,
2117                                                         (GDestroyNotify) g_free);
2118   return cache;
2119 }
2120
2121 static void
2122 mime_info_cache_free (MimeInfoCache *cache)
2123 {
2124   if (cache == NULL)
2125     return;
2126   
2127   g_list_foreach (cache->dirs,
2128                   (GFunc) mime_info_cache_dir_free,
2129                   NULL);
2130   g_list_free (cache->dirs);
2131   g_hash_table_destroy (cache->global_defaults_cache);
2132   g_free (cache);
2133 }
2134
2135 /**
2136  * mime_info_cache_reload:
2137  * @dir: directory path which needs reloading.
2138  * 
2139  * Reload the mime information for the @dir.
2140  */
2141 static void
2142 mime_info_cache_reload (const char *dir)
2143 {
2144   /* FIXME: just reload the dir that needs reloading,
2145    * don't blow the whole cache
2146    */
2147   if (mime_info_cache != NULL)
2148     {
2149       G_LOCK (mime_info_cache);
2150       mime_info_cache_free (mime_info_cache);
2151       mime_info_cache = NULL;
2152       G_UNLOCK (mime_info_cache);
2153     }
2154 }
2155
2156 static GList *
2157 append_desktop_entry (GList      *list, 
2158                       const char *desktop_entry)
2159 {
2160   /* Add if not already in list, and valid */
2161   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp))
2162     list = g_list_prepend (list, g_strdup (desktop_entry));
2163   
2164   return list;
2165 }
2166
2167 /**
2168  * get_all_desktop_entries_for_mime_type:
2169  * @mime_type: a mime type.
2170  *
2171  * Returns all the desktop ids for @mime_type. The desktop files
2172  * are listed in an order so that default applications are listed before
2173  * non-default ones, and handlers for inherited mimetypes are listed
2174  * after the base ones.
2175  *
2176  * Return value: a #GList containing the desktop ids which claim
2177  *    to handle @mime_type.
2178  */
2179 static GList *
2180 get_all_desktop_entries_for_mime_type (const char *base_mime_type)
2181 {
2182   GList *desktop_entries, *list, *dir_list, *tmp;
2183   MimeInfoCacheDir *dir;
2184   char *mime_type;
2185   char **mime_types;
2186   char **default_entries;
2187   int i,j;
2188   
2189   mime_info_cache_init ();
2190
2191   mime_types = _g_unix_content_type_get_parents (base_mime_type);
2192   G_LOCK (mime_info_cache);
2193   
2194   desktop_entries = NULL;
2195   for (i = 0; mime_types[i] != NULL; i++)
2196     {
2197       mime_type = mime_types[i];
2198
2199       /* Go through all apps listed as defaults */
2200       for (dir_list = mime_info_cache->dirs;
2201            dir_list != NULL;
2202            dir_list = dir_list->next)
2203         {
2204           dir = dir_list->data;
2205           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
2206           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2207             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j]);
2208         }
2209
2210       /* Go through all entries that support the mimetype */
2211       for (dir_list = mime_info_cache->dirs;
2212            dir_list != NULL;
2213            dir_list = dir_list->next) 
2214         {
2215           dir = dir_list->data;
2216         
2217           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
2218           for (tmp = list; tmp != NULL; tmp = tmp->next)
2219             desktop_entries = append_desktop_entry (desktop_entries, tmp->data);
2220         }
2221     }
2222   
2223   G_UNLOCK (mime_info_cache);
2224
2225   g_strfreev (mime_types);
2226   
2227   desktop_entries = g_list_reverse (desktop_entries);
2228   
2229   return desktop_entries;
2230 }
2231
2232 #define __G_DESKTOP_APP_INFO_C__
2233 #include "gioaliasdef.c"