Documentation additions
[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  **/
1577 GList *
1578 g_app_info_get_all_for_type (const char *content_type)
1579 {
1580   GList *desktop_entries, *l;
1581   GList *infos;
1582   GDesktopAppInfo *info;
1583   
1584   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1585
1586   infos = NULL;
1587   for (l = desktop_entries; l != NULL; l = l->next)
1588     {
1589       char *desktop_entry = l->data;
1590
1591       info = g_desktop_app_info_new (desktop_entry);
1592       if (info)
1593         {
1594           if (app_info_in_list (G_APP_INFO (info), infos))
1595             g_object_unref (info);
1596           else
1597             infos = g_list_prepend (infos, info);
1598         }
1599       g_free (desktop_entry);
1600     }
1601
1602   g_list_free (desktop_entries);
1603   
1604   return g_list_reverse (infos);
1605 }
1606
1607
1608 /**
1609  * g_app_info_get_default_for_type:
1610  * @content_type: the content type to find a #GAppInfo for
1611  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
1612  *     support URIs
1613  * 
1614  * Gets the #GAppInfo that correspond to a given content type.
1615  *
1616  * Returns: #GAppInfo for given @content_type.
1617  **/
1618 GAppInfo *
1619 g_app_info_get_default_for_type (const char *content_type,
1620                                  gboolean    must_support_uris)
1621 {
1622   GList *desktop_entries, *l;
1623   GAppInfo *info;
1624   
1625   desktop_entries = get_all_desktop_entries_for_mime_type (content_type);
1626
1627   info = NULL;
1628   for (l = desktop_entries; l != NULL; l = l->next)
1629     {
1630       char *desktop_entry = l->data;
1631
1632       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
1633       if (info)
1634         {
1635           if (must_support_uris && !g_app_info_supports_uris (info))
1636             {
1637               g_object_unref (info);
1638               info = NULL;
1639             }
1640           else
1641             break;
1642         }
1643     }
1644   
1645   g_list_foreach  (desktop_entries, (GFunc)g_free, NULL);
1646   g_list_free (desktop_entries);
1647   
1648   return info;
1649 }
1650
1651
1652 /**
1653  * g_app_info_get_default_for_uri_scheme:
1654  * @uri_scheme: a string containing a URI scheme.
1655  *
1656  * Gets the default application for launching applications 
1657  * using this URI scheme.
1658  *
1659  * TODO: This is currently unimplemented.
1660  * 
1661  * Returns: %NULL.
1662  **/
1663 GAppInfo *
1664 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
1665 {
1666   /* TODO: Implement this using giomodules, reading the gconf settings
1667    * in /desktop/gnome/url-handlers
1668    */
1669   return NULL;
1670 }
1671
1672
1673 static void
1674 get_apps_from_dir (GHashTable *apps, 
1675                    const char *dirname, 
1676                    const char *prefix)
1677 {
1678   GDir *dir;
1679   const char *basename;
1680   char *filename, *subprefix, *desktop_id;
1681   gboolean hidden;
1682   GDesktopAppInfo *appinfo;
1683   
1684   dir = g_dir_open (dirname, 0, NULL);
1685   if (dir)
1686     {
1687       while ((basename = g_dir_read_name (dir)) != NULL)
1688         {
1689           filename = g_build_filename (dirname, basename, NULL);
1690           if (g_str_has_suffix (basename, ".desktop"))
1691             {
1692               desktop_id = g_strconcat (prefix, basename, NULL);
1693
1694               /* Use _extended so we catch NULLs too (hidden) */
1695               if (!g_hash_table_lookup_extended (apps, desktop_id, NULL, NULL))
1696                 {
1697                   appinfo = g_desktop_app_info_new_from_filename (filename);
1698
1699                   if (appinfo && g_desktop_app_info_get_is_hidden (appinfo))
1700                     {
1701                       g_object_unref (appinfo);
1702                       appinfo = NULL;
1703                       hidden = TRUE;
1704                     }
1705                                       
1706                   if (appinfo || hidden)
1707                     {
1708                       g_hash_table_insert (apps, g_strdup (desktop_id), appinfo);
1709
1710                       if (appinfo)
1711                         {
1712                           /* Reuse instead of strdup here */
1713                           appinfo->desktop_id = desktop_id;
1714                           desktop_id = NULL;
1715                         }
1716                     }
1717                 }
1718               g_free (desktop_id);
1719             }
1720           else
1721             {
1722               if (g_file_test (filename, G_FILE_TEST_IS_DIR))
1723                 {
1724                   subprefix = g_strconcat (prefix, basename, "-", NULL);
1725                   get_apps_from_dir (apps, filename, subprefix);
1726                   g_free (subprefix);
1727                 }
1728             }
1729           g_free (filename);
1730         }
1731       g_dir_close (dir);
1732     }
1733 }
1734
1735
1736 /**
1737  * g_app_info_get_all:
1738  *
1739  * Gets a list of all of the applications currently registered 
1740  * on this system.
1741  * 
1742  * For desktop files, this includes applications that have 
1743  * <literal>NoDisplay=true</literal> set or are excluded from 
1744  * display by means of <literal>OnlyShowIn</literal> or
1745  * <literal>NotShowIn</literal>. See g_app_info_should_show().
1746  * The returned list does not include applications which have
1747  * the <literal>Hidden</literal> key set. 
1748  * 
1749  * Returns: a newly allocated #GList of references to #GAppInfo<!---->s.
1750  **/
1751 GList *
1752 g_app_info_get_all (void)
1753 {
1754   const char * const *dirs;
1755   GHashTable *apps;
1756   GHashTableIter iter;
1757   gpointer value;
1758   int i;
1759   GList *infos;
1760
1761   dirs = get_applications_search_path ();
1762
1763   apps = g_hash_table_new_full (g_str_hash, g_str_equal,
1764                                 g_free, NULL);
1765
1766   
1767   for (i = 0; dirs[i] != NULL; i++)
1768     get_apps_from_dir (apps, dirs[i], "");
1769
1770
1771   infos = NULL;
1772   g_hash_table_iter_init (&iter, apps);
1773   while (g_hash_table_iter_next (&iter, NULL, &value))
1774     {
1775       if (value)
1776         infos = g_list_prepend (infos, value);
1777     }
1778
1779   g_hash_table_destroy (apps);
1780
1781   return g_list_reverse (infos);
1782 }
1783
1784 /* Cacheing of mimeinfo.cache and defaults.list files */
1785
1786 typedef struct {
1787   char *path;
1788   GHashTable *mime_info_cache_map;
1789   GHashTable *defaults_list_map;
1790   time_t mime_info_cache_timestamp;
1791   time_t defaults_list_timestamp;
1792 } MimeInfoCacheDir;
1793
1794 typedef struct {
1795   GList *dirs;                       /* mimeinfo.cache and defaults.list */
1796   GHashTable *global_defaults_cache; /* global results of defaults.list lookup and validation */
1797   time_t last_stat_time;
1798   guint should_ping_mime_monitor : 1;
1799 } MimeInfoCache;
1800
1801 static MimeInfoCache *mime_info_cache = NULL;
1802 G_LOCK_DEFINE_STATIC (mime_info_cache);
1803
1804 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
1805                                                      const char        *mime_type,
1806                                                      char             **new_desktop_file_ids);
1807
1808 static MimeInfoCache * mime_info_cache_new (void);
1809
1810 static void
1811 destroy_info_cache_value (gpointer  key, 
1812                           GList    *value, 
1813                           gpointer  data)
1814 {
1815   g_list_foreach (value, (GFunc)g_free, NULL);
1816   g_list_free (value);
1817 }
1818
1819 static void
1820 destroy_info_cache_map (GHashTable *info_cache_map)
1821 {
1822   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
1823   g_hash_table_destroy (info_cache_map);
1824 }
1825
1826 static gboolean
1827 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
1828                                  const char       *cache_file,
1829                                  time_t           *timestamp)
1830 {
1831   struct stat buf;
1832   char *filename;
1833   
1834   filename = g_build_filename (dir->path, cache_file, NULL);
1835   
1836   if (g_stat (filename, &buf) < 0)
1837     {
1838       g_free (filename);
1839       return TRUE;
1840     }
1841   g_free (filename);
1842
1843   if (buf.st_mtime != *timestamp) 
1844     return TRUE;
1845   
1846   return FALSE;
1847 }
1848
1849 /* Call with lock held */
1850 static gboolean
1851 remove_all (gpointer  key,
1852             gpointer  value,
1853             gpointer  user_data)
1854 {
1855   return TRUE;
1856 }
1857
1858
1859 static void
1860 mime_info_cache_blow_global_cache (void)
1861 {
1862   g_hash_table_foreach_remove (mime_info_cache->global_defaults_cache,
1863                                remove_all, NULL);
1864 }
1865
1866 static void
1867 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
1868 {
1869   GError *load_error;
1870   GKeyFile *key_file;
1871   gchar *filename, **mime_types;
1872   int i;
1873   struct stat buf;
1874   
1875   load_error = NULL;
1876   mime_types = NULL;
1877   
1878   if (dir->mime_info_cache_map != NULL &&
1879       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
1880                                         &dir->mime_info_cache_timestamp))
1881     return;
1882   
1883   if (dir->mime_info_cache_map != NULL)
1884     destroy_info_cache_map (dir->mime_info_cache_map);
1885   
1886   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1887                                                     (GDestroyNotify) g_free,
1888                                                     NULL);
1889   
1890   key_file = g_key_file_new ();
1891   
1892   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
1893   
1894   if (g_stat (filename, &buf) < 0)
1895     goto error;
1896   
1897   if (dir->mime_info_cache_timestamp > 0) 
1898     mime_info_cache->should_ping_mime_monitor = TRUE;
1899   
1900   dir->mime_info_cache_timestamp = buf.st_mtime;
1901   
1902   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1903   
1904   g_free (filename);
1905   filename = NULL;
1906   
1907   if (load_error != NULL)
1908     goto error;
1909   
1910   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
1911                                     NULL, &load_error);
1912   
1913   if (load_error != NULL)
1914     goto error;
1915   
1916   for (i = 0; mime_types[i] != NULL; i++)
1917     {
1918       gchar **desktop_file_ids;
1919       char *unaliased_type;
1920       desktop_file_ids = g_key_file_get_string_list (key_file,
1921                                                      MIME_CACHE_GROUP,
1922                                                      mime_types[i],
1923                                                      NULL,
1924                                                      NULL);
1925       
1926       if (desktop_file_ids == NULL)
1927         continue;
1928
1929       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
1930       mime_info_cache_dir_add_desktop_entries (dir,
1931                                                unaliased_type,
1932                                                desktop_file_ids);
1933       g_free (unaliased_type);
1934     
1935       g_strfreev (desktop_file_ids);
1936     }
1937   
1938   g_strfreev (mime_types);
1939   g_key_file_free (key_file);
1940   
1941   return;
1942  error:
1943   g_free (filename);
1944   g_key_file_free (key_file);
1945   
1946   if (mime_types != NULL)
1947     g_strfreev (mime_types);
1948   
1949   if (load_error)
1950     g_error_free (load_error);
1951 }
1952
1953 static void
1954 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
1955 {
1956   GKeyFile *key_file;
1957   GError *load_error;
1958   gchar *filename, **mime_types;
1959   char *unaliased_type;
1960   char **desktop_file_ids;
1961   int i;
1962   struct stat buf;
1963
1964   load_error = NULL;
1965   mime_types = NULL;
1966
1967   if (dir->defaults_list_map != NULL &&
1968       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
1969                                         &dir->defaults_list_timestamp))
1970     return;
1971   
1972   if (dir->defaults_list_map != NULL)
1973     g_hash_table_destroy (dir->defaults_list_map);
1974
1975   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
1976                                                   g_free, (GDestroyNotify)g_strfreev);
1977
1978   key_file = g_key_file_new ();
1979   
1980   filename = g_build_filename (dir->path, "defaults.list", NULL);
1981   if (g_stat (filename, &buf) < 0)
1982     goto error;
1983
1984   if (dir->defaults_list_timestamp > 0) 
1985     mime_info_cache->should_ping_mime_monitor = TRUE;
1986
1987   dir->defaults_list_timestamp = buf.st_mtime;
1988
1989   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
1990   g_free (filename);
1991   filename = NULL;
1992
1993   if (load_error != NULL)
1994     goto error;
1995
1996   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
1997                                     NULL, &load_error);
1998
1999   if (load_error != NULL)
2000     goto error;
2001
2002   for (i = 0; mime_types[i] != NULL; i++)
2003     {
2004       desktop_file_ids = g_key_file_get_string_list (key_file,
2005                                                      DEFAULT_APPLICATIONS_GROUP,
2006                                                      mime_types[i],
2007                                                      NULL,
2008                                                      NULL);
2009       if (desktop_file_ids == NULL)
2010         continue;
2011
2012       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
2013       g_hash_table_replace (dir->defaults_list_map,
2014                             unaliased_type,
2015                             desktop_file_ids);
2016     }
2017
2018   g_strfreev (mime_types);
2019   g_key_file_free (key_file);
2020   
2021   return;
2022  error:
2023   g_free (filename);
2024   g_key_file_free (key_file);
2025   
2026   if (mime_types != NULL)
2027     g_strfreev (mime_types);
2028   
2029   if (load_error)
2030     g_error_free (load_error);
2031 }
2032
2033 static MimeInfoCacheDir *
2034 mime_info_cache_dir_new (const char *path)
2035 {
2036   MimeInfoCacheDir *dir;
2037
2038   dir = g_new0 (MimeInfoCacheDir, 1);
2039   dir->path = g_strdup (path);
2040   
2041   return dir;
2042 }
2043
2044 static void
2045 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
2046 {
2047   if (dir == NULL)
2048     return;
2049   
2050   if (dir->mime_info_cache_map != NULL)
2051     {
2052       destroy_info_cache_map (dir->mime_info_cache_map);
2053       dir->mime_info_cache_map = NULL;
2054       
2055   }
2056   
2057   if (dir->defaults_list_map != NULL)
2058     {
2059       g_hash_table_destroy (dir->defaults_list_map);
2060       dir->defaults_list_map = NULL;
2061     }
2062   
2063   g_free (dir);
2064 }
2065
2066 static void
2067 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
2068                                          const char        *mime_type,
2069                                          char             **new_desktop_file_ids)
2070 {
2071   GList *desktop_file_ids;
2072   int i;
2073   
2074   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
2075                                           mime_type);
2076   
2077   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
2078     {
2079       if (!g_list_find (desktop_file_ids, new_desktop_file_ids[i]))
2080         desktop_file_ids = g_list_append (desktop_file_ids,
2081                                           g_strdup (new_desktop_file_ids[i]));
2082     }
2083   
2084   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
2085 }
2086
2087 static void
2088 mime_info_cache_init_dir_lists (void)
2089 {
2090   const char * const *dirs;
2091   int i;
2092   
2093   mime_info_cache = mime_info_cache_new ();
2094   
2095   dirs = get_applications_search_path ();
2096   
2097   for (i = 0; dirs[i] != NULL; i++)
2098     {
2099       MimeInfoCacheDir *dir;
2100       
2101       dir = mime_info_cache_dir_new (dirs[i]);
2102       
2103       if (dir != NULL)
2104         {
2105           mime_info_cache_dir_init (dir);
2106           mime_info_cache_dir_init_defaults_list (dir);
2107           
2108           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
2109         }
2110     }
2111 }
2112
2113 static void
2114 mime_info_cache_update_dir_lists (void)
2115 {
2116   GList *tmp;
2117   
2118   tmp = mime_info_cache->dirs;
2119   
2120   while (tmp != NULL)
2121     {
2122       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
2123
2124       /* No need to do this if we had file monitors... */
2125       mime_info_cache_blow_global_cache ();
2126       mime_info_cache_dir_init (dir);
2127       mime_info_cache_dir_init_defaults_list (dir);
2128       
2129       tmp = tmp->next;
2130     }
2131 }
2132
2133 static void
2134 mime_info_cache_init (void)
2135 {
2136         G_LOCK (mime_info_cache);
2137         if (mime_info_cache == NULL)
2138           mime_info_cache_init_dir_lists ();
2139         else
2140           {
2141             time_t now;
2142             
2143             time (&now);
2144             if (now >= mime_info_cache->last_stat_time + 10)
2145               {
2146                 mime_info_cache_update_dir_lists ();
2147                 mime_info_cache->last_stat_time = now;
2148               }
2149           }
2150
2151         if (mime_info_cache->should_ping_mime_monitor)
2152           {
2153             /* g_idle_add (emit_mime_changed, NULL); */
2154             mime_info_cache->should_ping_mime_monitor = FALSE;
2155           }
2156         
2157         G_UNLOCK (mime_info_cache);
2158 }
2159
2160 static MimeInfoCache *
2161 mime_info_cache_new (void)
2162 {
2163   MimeInfoCache *cache;
2164   
2165   cache = g_new0 (MimeInfoCache, 1);
2166   
2167   cache->global_defaults_cache = g_hash_table_new_full (g_str_hash, g_str_equal,
2168                                                         (GDestroyNotify) g_free,
2169                                                         (GDestroyNotify) g_free);
2170   return cache;
2171 }
2172
2173 static void
2174 mime_info_cache_free (MimeInfoCache *cache)
2175 {
2176   if (cache == NULL)
2177     return;
2178   
2179   g_list_foreach (cache->dirs,
2180                   (GFunc) mime_info_cache_dir_free,
2181                   NULL);
2182   g_list_free (cache->dirs);
2183   g_hash_table_destroy (cache->global_defaults_cache);
2184   g_free (cache);
2185 }
2186
2187 /**
2188  * mime_info_cache_reload:
2189  * @dir: directory path which needs reloading.
2190  * 
2191  * Reload the mime information for the @dir.
2192  */
2193 static void
2194 mime_info_cache_reload (const char *dir)
2195 {
2196   /* FIXME: just reload the dir that needs reloading,
2197    * don't blow the whole cache
2198    */
2199   if (mime_info_cache != NULL)
2200     {
2201       G_LOCK (mime_info_cache);
2202       mime_info_cache_free (mime_info_cache);
2203       mime_info_cache = NULL;
2204       G_UNLOCK (mime_info_cache);
2205     }
2206 }
2207
2208 static GList *
2209 append_desktop_entry (GList      *list, 
2210                       const char *desktop_entry)
2211 {
2212   /* Add if not already in list, and valid */
2213   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp))
2214     list = g_list_prepend (list, g_strdup (desktop_entry));
2215   
2216   return list;
2217 }
2218
2219 /**
2220  * get_all_desktop_entries_for_mime_type:
2221  * @mime_type: a mime type.
2222  *
2223  * Returns all the desktop ids for @mime_type. The desktop files
2224  * are listed in an order so that default applications are listed before
2225  * non-default ones, and handlers for inherited mimetypes are listed
2226  * after the base ones.
2227  *
2228  * Return value: a #GList containing the desktop ids which claim
2229  *    to handle @mime_type.
2230  */
2231 static GList *
2232 get_all_desktop_entries_for_mime_type (const char *base_mime_type)
2233 {
2234   GList *desktop_entries, *list, *dir_list, *tmp;
2235   MimeInfoCacheDir *dir;
2236   char *mime_type;
2237   char **mime_types;
2238   char **default_entries;
2239   int i,j;
2240   
2241   mime_info_cache_init ();
2242
2243   mime_types = _g_unix_content_type_get_parents (base_mime_type);
2244   G_LOCK (mime_info_cache);
2245   
2246   desktop_entries = NULL;
2247   for (i = 0; mime_types[i] != NULL; i++)
2248     {
2249       mime_type = mime_types[i];
2250
2251       /* Go through all apps listed as defaults */
2252       for (dir_list = mime_info_cache->dirs;
2253            dir_list != NULL;
2254            dir_list = dir_list->next)
2255         {
2256           dir = dir_list->data;
2257           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
2258           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
2259             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j]);
2260         }
2261
2262       /* Go through all entries that support the mimetype */
2263       for (dir_list = mime_info_cache->dirs;
2264            dir_list != NULL;
2265            dir_list = dir_list->next) 
2266         {
2267           dir = dir_list->data;
2268         
2269           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
2270           for (tmp = list; tmp != NULL; tmp = tmp->next)
2271             desktop_entries = append_desktop_entry (desktop_entries, tmp->data);
2272         }
2273     }
2274   
2275   G_UNLOCK (mime_info_cache);
2276
2277   g_strfreev (mime_types);
2278   
2279   desktop_entries = g_list_reverse (desktop_entries);
2280   
2281   return desktop_entries;
2282 }
2283
2284 #define __G_DESKTOP_APP_INFO_C__
2285 #include "gioaliasdef.c"