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