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