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