desktopappinfo: add Exec to searchable keys
[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, see <http://www.gnu.org/licenses/>.
18  *
19  * Author: Alexander Larsson <alexl@redhat.com>
20  *         Ryan Lortie <desrt@desrt.ca>
21  */
22
23 /* Prelude {{{1 */
24
25 #include "config.h"
26
27 #include <errno.h>
28 #include <string.h>
29 #include <unistd.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 #ifdef G_OS_UNIX
38 #include "glib-unix.h"
39 #endif
40 #include "gfile.h"
41 #include "gioerror.h"
42 #include "gthemedicon.h"
43 #include "gfileicon.h"
44 #include <glib/gstdio.h>
45 #include "glibintl.h"
46 #include "giomodule-priv.h"
47 #include "gappinfo.h"
48 #include "gappinfoprivate.h"
49 #include "glocaldirectorymonitor.h"
50
51
52 /**
53  * SECTION:gdesktopappinfo
54  * @title: GDesktopAppInfo
55  * @short_description: Application information from desktop files
56  * @include: gio/gdesktopappinfo.h
57  *
58  * #GDesktopAppInfo is an implementation of #GAppInfo based on
59  * desktop files.
60  *
61  * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
62  * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
63  * file when using it.
64  */
65
66 #define DEFAULT_APPLICATIONS_GROUP  "Default Applications"
67 #define ADDED_ASSOCIATIONS_GROUP    "Added Associations"
68 #define REMOVED_ASSOCIATIONS_GROUP  "Removed Associations"
69 #define MIME_CACHE_GROUP            "MIME Cache"
70 #define GENERIC_NAME_KEY            "GenericName"
71 #define FULL_NAME_KEY               "X-GNOME-FullName"
72 #define KEYWORDS_KEY                "Keywords"
73 #define STARTUP_WM_CLASS_KEY        "StartupWMClass"
74
75 enum {
76   PROP_0,
77   PROP_FILENAME
78 };
79
80 static void     g_desktop_app_info_iface_init         (GAppInfoIface    *iface);
81 static GList *  get_all_desktop_entries_for_mime_type (const char       *base_mime_type,
82                                                        const char      **except,
83                                                        gboolean          include_fallback,
84                                                        char            **explicit_default);
85 static void     mime_info_cache_reload                (const char       *dir);
86 static gboolean g_desktop_app_info_ensure_saved       (GDesktopAppInfo  *info,
87                                                        GError          **error);
88
89 /**
90  * GDesktopAppInfo:
91  *
92  * Information about an installed application from a desktop file.
93  */
94 struct _GDesktopAppInfo
95 {
96   GObject parent_instance;
97
98   char *desktop_id;
99   char *filename;
100   char *app_id;
101
102   GKeyFile *keyfile;
103
104   char *name;
105   char *generic_name;
106   char *fullname;
107   char *comment;
108   char *icon_name;
109   GIcon *icon;
110   char **keywords;
111   char **only_show_in;
112   char **not_show_in;
113   char *try_exec;
114   char *exec;
115   char *binary;
116   char *path;
117   char *categories;
118   char *startup_wm_class;
119   char **mime_types;
120   char **actions;
121
122   guint nodisplay       : 1;
123   guint hidden          : 1;
124   guint terminal        : 1;
125   guint startup_notify  : 1;
126   guint no_fuse         : 1;
127 };
128
129 typedef enum {
130   UPDATE_MIME_NONE = 1 << 0,
131   UPDATE_MIME_SET_DEFAULT = 1 << 1,
132   UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
133   UPDATE_MIME_REMOVE = 1 << 3,
134   UPDATE_MIME_SET_LAST_USED = 1 << 4,
135 } UpdateMimeFlags;
136
137 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
138                          G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
139
140 G_LOCK_DEFINE_STATIC (g_desktop_env);
141 static gchar *g_desktop_env = NULL;
142
143 /* DesktopFileDir implementation {{{1 */
144
145 typedef struct
146 {
147   gchar                      *path;
148   GLocalDirectoryMonitor     *monitor;
149   GHashTable                 *app_names;
150   gboolean                    is_setup;
151   GHashTable                 *memory_index;
152 } DesktopFileDir;
153
154 static DesktopFileDir *desktop_file_dirs;
155 static guint           n_desktop_file_dirs;
156 static GMutex          desktop_file_dir_lock;
157
158 /* Monitor 'changed' signal handler {{{2 */
159 static void desktop_file_dir_reset (DesktopFileDir *dir);
160
161 static void
162 desktop_file_dir_changed (GFileMonitor      *monitor,
163                           GFile             *file,
164                           GFile             *other_file,
165                           GFileMonitorEvent  event_type,
166                           gpointer           user_data)
167 {
168   DesktopFileDir *dir = user_data;
169
170   /* We are not interested in receiving notifications forever just
171    * because someone asked about one desktop file once.
172    *
173    * After we receive the first notification, reset the dir, destroying
174    * the monitor.  We will take this as a hint, next time that we are
175    * asked, that we need to check if everything is up to date.
176    */
177   g_mutex_lock (&desktop_file_dir_lock);
178
179   desktop_file_dir_reset (dir);
180
181   g_mutex_unlock (&desktop_file_dir_lock);
182
183   /* Notify anyone else who may be interested */
184   g_app_info_monitor_fire ();
185 }
186
187 /* Internal utility functions {{{2 */
188
189 /*< internal >
190  * desktop_file_dir_app_name_is_masked:
191  * @dir: a #DesktopFileDir
192  * @app_name: an application ID
193  *
194  * Checks if @app_name is masked for @dir.
195  *
196  * An application is masked if a similarly-named desktop file exists in
197  * a desktop file directory with higher precedence.  Masked desktop
198  * files should be ignored.
199  */
200 static gboolean
201 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
202                                      const gchar    *app_name)
203 {
204   while (dir > desktop_file_dirs)
205     {
206       dir--;
207
208       if (dir->app_names && g_hash_table_contains (dir->app_names, app_name))
209         return TRUE;
210     }
211
212   return FALSE;
213 }
214
215 /*< internal >
216  * add_to_table_if_appropriate:
217  * @apps: a string to GDesktopAppInfo hash table
218  * @app_name: the name of the application
219  * @info: a #GDesktopAppInfo, or NULL
220  *
221  * If @info is non-%NULL and non-hidden, then add it to @apps, using
222  * @app_name as a key.
223  *
224  * If @info is non-%NULL then this function will consume the passed-in
225  * reference.
226  */
227 static void
228 add_to_table_if_appropriate (GHashTable      *apps,
229                              const gchar     *app_name,
230                              GDesktopAppInfo *info)
231 {
232   if (!info)
233     return;
234
235   if (info->hidden)
236     {
237       g_object_unref (info);
238       return;
239     }
240
241   g_free (info->desktop_id);
242   info->desktop_id = g_strdup (app_name);
243
244   g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
245 }
246
247 enum
248 {
249   DESKTOP_KEY_Comment,
250   DESKTOP_KEY_Exec,
251   DESKTOP_KEY_GenericName,
252   DESKTOP_KEY_Keywords,
253   DESKTOP_KEY_Name,
254   DESKTOP_KEY_X_GNOME_FullName,
255
256   N_DESKTOP_KEYS
257 };
258
259 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
260   /* Note: lower numbers are a better match.
261    *
262    * In case we want two keys to match at the same level, we can just
263    * use the same number for the two different keys.
264    */
265   [DESKTOP_KEY_Name]             = 1,
266   [DESKTOP_KEY_Exec]             = 2,
267   [DESKTOP_KEY_Keywords]         = 3,
268   [DESKTOP_KEY_GenericName]      = 4,
269   [DESKTOP_KEY_X_GNOME_FullName] = 5,
270   [DESKTOP_KEY_Comment]          = 6
271 };
272
273 static gchar *
274 desktop_key_get_name (guint key_id)
275 {
276   switch (key_id)
277     {
278     case DESKTOP_KEY_Comment:
279       return "Comment";
280     case DESKTOP_KEY_Exec:
281       return "Exec";
282     case DESKTOP_KEY_GenericName:
283       return "GenericName";
284     case DESKTOP_KEY_Keywords:
285       return "Keywords";
286     case DESKTOP_KEY_Name:
287       return "Name";
288     case DESKTOP_KEY_X_GNOME_FullName:
289       return "X-GNOME-FullName";
290     default:
291       g_assert_not_reached ();
292     }
293 }
294
295 /* Search global state {{{2
296  *
297  * We only ever search under a global lock, so we can use (and reuse)
298  * some global data to reduce allocations made while searching.
299  *
300  * In short, we keep around arrays of results that we expand as needed
301  * (and never shrink).
302  *
303  * static_token_results: this is where we append the results for each
304  *     token within a given desktop directory, as we handle it (which is
305  *     a union of all matches for this term)
306  *
307  * static_search_results: this is where we build the complete results
308  *     for a single directory (which is an intersection of the matches
309  *     found for each term)
310  *
311  * static_total_results: this is where we build the complete results
312  *     across all directories (which is a union of the matches found in
313  *     each directory)
314  *
315  * The app_names that enter these tables are always pointer-unique (in
316  * the sense that string equality is the same as pointer equality).
317  * This can be guaranteed for two reasons:
318  *
319  *   - we mask appids so that a given appid will only ever appear within
320  *     the highest-precedence directory that contains it.  We never
321  *     return search results from a lower-level directory if a desktop
322  *     file exists in a higher-level one.
323  *
324  *   - within a given directory, the string is unique because it's the
325  *     key in the hashtable of all app_ids for that directory.
326  *
327  * We perform a merging of the results in merge_token_results().  This
328  * works by ordering the two lists and moving through each of them (at
329  * the same time) looking for common elements, rejecting uncommon ones.
330  * "Order" here need not mean any particular thing, as long as it is
331  * some order.  Because of the uniqueness of our strings, we can use
332  * pointer order.  That's what's going on in compare_results() below.
333  */
334 struct search_result
335 {
336   const gchar *app_name;
337   gint         category;
338 };
339
340 static struct search_result *static_token_results;
341 static gint                  static_token_results_size;
342 static gint                  static_token_results_allocated;
343 static struct search_result *static_search_results;
344 static gint                  static_search_results_size;
345 static gint                  static_search_results_allocated;
346 static struct search_result *static_total_results;
347 static gint                  static_total_results_size;
348 static gint                  static_total_results_allocated;
349
350 /* And some functions for performing nice operations against it */
351 static gint
352 compare_results (gconstpointer a,
353                  gconstpointer b)
354 {
355   const struct search_result *ra = a;
356   const struct search_result *rb = b;
357
358   if (ra->app_name < rb->app_name)
359     return -1;
360
361   else if (ra->app_name > rb->app_name)
362     return 1;
363
364   else
365     return ra->category - rb->category;
366 }
367
368 static gint
369 compare_categories (gconstpointer a,
370                     gconstpointer b)
371 {
372   const struct search_result *ra = a;
373   const struct search_result *rb = b;
374
375   return ra->category - rb->category;
376 }
377
378 static void
379 add_token_result (const gchar *app_name,
380                   guint16      category)
381 {
382   if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
383     {
384       static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
385       static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
386     }
387
388   static_token_results[static_token_results_size].app_name = app_name;
389   static_token_results[static_token_results_size].category = category;
390   static_token_results_size++;
391 }
392
393 static void
394 merge_token_results (gboolean first)
395 {
396   qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
397
398   /* If this is the first token then we are basically merging a list with
399    * itself -- we only perform de-duplication.
400    *
401    * If this is not the first token then we are doing a real merge.
402    */
403   if (first)
404     {
405       const gchar *last_name = NULL;
406       gint i;
407
408       /* We must de-duplicate, but we do so by taking the best category
409        * in each case.
410        *
411        * The final list can be as large as the input here, so make sure
412        * we have enough room (even if it's too much room).
413        */
414
415       if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
416         {
417           static_search_results_allocated = static_token_results_allocated;
418           static_search_results = g_renew (struct search_result,
419                                            static_search_results,
420                                            static_search_results_allocated);
421         }
422
423       for (i = 0; i < static_token_results_size; i++)
424         {
425           /* The list is sorted so that the best match for a given id
426            * will be at the front, so once we have copied an id, skip
427            * the rest of the entries for the same id.
428            */
429           if (static_token_results[i].app_name == last_name)
430             continue;
431
432           last_name = static_token_results[i].app_name;
433
434           static_search_results[static_search_results_size++] = static_token_results[i];
435         }
436     }
437   else
438     {
439       const gchar *last_name = NULL;
440       gint i, j = 0;
441       gint k = 0;
442
443       /* We only ever remove items from the results list, so no need to
444        * resize to ensure that we have enough room.
445        */
446       for (i = 0; i < static_token_results_size; i++)
447         {
448           if (static_token_results[i].app_name == last_name)
449             continue;
450
451           last_name = static_token_results[i].app_name;
452
453           /* Now we only want to have a result in static_search_results
454            * if we already have it there *and* we have it in
455            * static_token_results as well.  The category will be the
456            * lesser of the two.
457            *
458            * Skip past the results in static_search_results that are not
459            * going to be matches.
460            */
461           while (k < static_search_results_size &&
462                  static_search_results[k].app_name < static_token_results[i].app_name)
463             k++;
464
465           if (k < static_search_results_size &&
466               static_search_results[k].app_name == static_token_results[i].app_name)
467             {
468               /* We have a match.
469                *
470                * Category should be the worse of the two (ie:
471                * numerically larger).
472                */
473               static_search_results[j].app_name = static_search_results[k].app_name;
474               static_search_results[j].category = MAX (static_search_results[k].category,
475                                                        static_token_results[i].category);
476               j++;
477             }
478         }
479
480       static_search_results_size = j;
481     }
482
483   /* Clear it out for next time... */
484   static_token_results_size = 0;
485 }
486
487 static void
488 reset_total_search_results (void)
489 {
490   static_total_results_size = 0;
491 }
492
493 static void
494 sort_total_search_results (void)
495 {
496   qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
497 }
498
499 static void
500 merge_directory_results (void)
501 {
502   if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
503     {
504       static_total_results_allocated = MAX (16, static_total_results_allocated);
505       while (static_total_results_allocated < static_total_results_size + static_search_results_size)
506         static_total_results_allocated *= 2;
507       static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
508     }
509
510   memcpy (static_total_results + static_total_results_size,
511           static_search_results,
512           static_search_results_size * sizeof (struct search_result));
513
514   static_total_results_size += static_search_results_size;
515
516   /* Clear it out for next time... */
517   static_search_results_size = 0;
518 }
519
520
521 /* Support for unindexed DesktopFileDirs {{{2 */
522 static void
523 get_apps_from_dir (GHashTable **apps,
524                    const char  *dirname,
525                    const char  *prefix)
526 {
527   const char *basename;
528   GDir *dir;
529
530   dir = g_dir_open (dirname, 0, NULL);
531
532   if (dir == NULL)
533     return;
534
535   while ((basename = g_dir_read_name (dir)) != NULL)
536     {
537       gchar *filename;
538
539       filename = g_build_filename (dirname, basename, NULL);
540
541       if (g_str_has_suffix (basename, ".desktop"))
542         {
543           gchar *app_name;
544
545           app_name = g_strconcat (prefix, basename, NULL);
546
547           if (*apps == NULL)
548             *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
549
550           g_hash_table_insert (*apps, app_name, g_strdup (filename));
551         }
552       else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
553         {
554           gchar *subprefix;
555
556           subprefix = g_strconcat (prefix, basename, "-", NULL);
557           get_apps_from_dir (apps, filename, subprefix);
558           g_free (subprefix);
559         }
560
561       g_free (filename);
562     }
563
564   g_dir_close (dir);
565 }
566
567 static void
568 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
569 {
570   get_apps_from_dir (&dir->app_names, dir->path, "");
571 }
572
573 static GDesktopAppInfo *
574 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
575                                     const gchar    *desktop_id)
576 {
577   const gchar *filename;
578
579   filename = g_hash_table_lookup (dir->app_names, desktop_id);
580
581   if (!filename)
582     return NULL;
583
584   return g_desktop_app_info_new_from_filename (filename);
585 }
586
587 static void
588 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
589                                     GHashTable     *apps)
590 {
591   GHashTableIter iter;
592   gpointer app_name;
593   gpointer filename;
594
595   if (dir->app_names == NULL)
596     return;
597
598   g_hash_table_iter_init (&iter, dir->app_names);
599   while (g_hash_table_iter_next (&iter, &app_name, &filename))
600     {
601       if (desktop_file_dir_app_name_is_masked (dir, app_name))
602         continue;
603
604       add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename (filename));
605     }
606 }
607
608 typedef struct _MemoryIndexEntry MemoryIndexEntry;
609 typedef GHashTable MemoryIndex;
610
611 struct _MemoryIndexEntry
612 {
613   const gchar      *app_name; /* pointer to the hashtable key */
614   gint              match_category;
615   MemoryIndexEntry *next;
616 };
617
618 static void
619 memory_index_entry_free (gpointer data)
620 {
621   MemoryIndexEntry *mie = data;
622
623   while (mie)
624     {
625       MemoryIndexEntry *next = mie->next;
626
627       g_slice_free (MemoryIndexEntry, mie);
628       mie = next;
629     }
630 }
631
632 static void
633 memory_index_add_token (MemoryIndex *mi,
634                         const gchar *token,
635                         gint         match_category,
636                         const gchar *app_name)
637 {
638   MemoryIndexEntry *mie, *first;
639
640   mie = g_slice_new (MemoryIndexEntry);
641   mie->app_name = app_name;
642   mie->match_category = match_category;
643
644   first = g_hash_table_lookup (mi, token);
645
646   if (first)
647     {
648       mie->next = first->next;
649       first->next = mie;
650     }
651   else
652     {
653       mie->next = NULL;
654       g_hash_table_insert (mi, g_strdup (token), mie);
655     }
656 }
657
658 static void
659 memory_index_add_string (MemoryIndex *mi,
660                          const gchar *string,
661                          gint         match_category,
662                          const gchar *app_name)
663 {
664   gchar **tokens, **alternates;
665   gint i;
666
667   tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
668
669   for (i = 0; tokens[i]; i++)
670     memory_index_add_token (mi, tokens[i], match_category, app_name);
671
672   for (i = 0; alternates[i]; i++)
673     memory_index_add_token (mi, alternates[i], match_category, app_name);
674
675   g_strfreev (alternates);
676   g_strfreev (tokens);
677 }
678
679 static MemoryIndex *
680 memory_index_new (void)
681 {
682   return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
683 }
684
685 static void
686 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
687 {
688   GHashTableIter iter;
689   gpointer app, path;
690
691   dir->memory_index = memory_index_new ();
692
693   /* Nothing to search? */
694   if (dir->app_names == NULL)
695     return;
696
697   g_hash_table_iter_init (&iter, dir->app_names);
698   while (g_hash_table_iter_next (&iter, &app, &path))
699     {
700       GKeyFile *key_file;
701
702       if (desktop_file_dir_app_name_is_masked (dir, app))
703         continue;
704
705       key_file = g_key_file_new ();
706
707       if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
708           !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
709         {
710           /* Index the interesting keys... */
711           gint i;
712
713           for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
714             {
715               const gchar *value;
716               gchar *raw;
717
718               if (!desktop_key_match_category[i])
719                 continue;
720
721               raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
722               value = raw;
723
724               if (i == DESKTOP_KEY_Exec && raw != NULL)
725                 {
726                   /* Special handling: only match basename of first field */
727                   gchar *space;
728                   gchar *slash;
729
730                   /* Remove extra arguments, if any */
731                   space = raw + strcspn (raw, " \t\n"); /* IFS */
732                   *space = '\0';
733
734                   /* Skip the pathname, if any */
735                   if ((slash = strrchr (raw, '/')))
736                     value = slash + 1;
737                 }
738
739               if (value)
740                 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
741
742               g_free (raw);
743             }
744         }
745
746       g_key_file_free (key_file);
747     }
748 }
749
750 static void
751 desktop_file_dir_unindexed_search (DesktopFileDir  *dir,
752                                    const gchar     *search_token)
753 {
754   GHashTableIter iter;
755   gpointer key, value;
756
757   if (!dir->memory_index)
758     desktop_file_dir_unindexed_setup_search (dir);
759
760   g_hash_table_iter_init (&iter, dir->memory_index);
761   while (g_hash_table_iter_next (&iter, &key, &value))
762     {
763       MemoryIndexEntry *mie = value;
764
765       if (!g_str_has_prefix (key, search_token))
766         continue;
767
768       while (mie)
769         {
770           add_token_result (mie->app_name, mie->match_category);
771           mie = mie->next;
772         }
773     }
774 }
775
776 /* DesktopFileDir "API" {{{2 */
777
778 /*< internal >
779  * desktop_file_dir_create:
780  * @array: the #GArray to add a new item to
781  * @data_dir: an XDG_DATA_DIR
782  *
783  * Creates a #DesktopFileDir for the corresponding @data_dir, adding it
784  * to @array.
785  */
786 static void
787 desktop_file_dir_create (GArray      *array,
788                          const gchar *data_dir)
789 {
790   DesktopFileDir dir = { 0, };
791
792   dir.path = g_build_filename (data_dir, "applications", NULL);
793
794   g_array_append_val (array, dir);
795 }
796
797 /*< internal >
798  * desktop_file_dir_reset:
799  * @dir: a #DesktopFileDir
800  *
801  * Cleans up @dir, releasing most resources that it was using.
802  */
803 static void
804 desktop_file_dir_reset (DesktopFileDir *dir)
805 {
806   if (dir->monitor)
807     {
808       g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
809       g_object_unref (dir->monitor);
810       dir->monitor = NULL;
811     }
812
813   if (dir->app_names)
814     {
815       g_hash_table_unref (dir->app_names);
816       dir->app_names = NULL;
817     }
818
819   if (dir->memory_index)
820     {
821       g_hash_table_unref (dir->memory_index);
822       dir->memory_index = NULL;
823     }
824
825   dir->is_setup = FALSE;
826 }
827
828 /*< internal >
829  * desktop_file_dir_init:
830  * @dir: a #DesktopFileDir
831  *
832  * Does initial setup for @dir
833  *
834  * You should only call this if @dir is not already setup.
835  */
836 static void
837 desktop_file_dir_init (DesktopFileDir *dir)
838 {
839   g_assert (!dir->is_setup);
840
841   g_assert (!dir->monitor);
842   dir->monitor = g_local_directory_monitor_new_in_worker (dir->path, G_FILE_MONITOR_NONE, NULL);
843
844   if (dir->monitor)
845     {
846       g_signal_connect (dir->monitor, "changed", G_CALLBACK (desktop_file_dir_changed), dir);
847       g_local_directory_monitor_start (dir->monitor);
848     }
849
850   desktop_file_dir_unindexed_init (dir);
851
852   dir->is_setup = TRUE;
853 }
854
855 /*< internal >
856  * desktop_file_dir_get_app:
857  * @dir: a DesktopFileDir
858  * @desktop_id: the desktop ID to load
859  *
860  * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
861  * within @dir, even if it is hidden.
862  *
863  * This function does not check if @desktop_id would be masked by a
864  * directory with higher precedence.  The caller must do so.
865  */
866 static GDesktopAppInfo *
867 desktop_file_dir_get_app (DesktopFileDir *dir,
868                           const gchar    *desktop_id)
869 {
870   if (!dir->app_names)
871     return NULL;
872
873   return desktop_file_dir_unindexed_get_app (dir, desktop_id);
874 }
875
876 /*< internal >
877  * desktop_file_dir_get_all:
878  * @dir: a DesktopFileDir
879  * @apps: a #GHashTable<string, GDesktopAppInfo>
880  *
881  * Loads all desktop files in @dir and adds them to @apps, careful to
882  * ensure we don't add any files masked by a similarly-named file in a
883  * higher-precedence directory.
884  */
885 static void
886 desktop_file_dir_get_all (DesktopFileDir *dir,
887                           GHashTable     *apps)
888 {
889   desktop_file_dir_unindexed_get_all (dir, apps);
890 }
891
892 /*< internal >
893  * desktop_file_dir_search:
894  * @dir: a #DesktopFilEDir
895  * @term: a normalised and casefolded search term
896  *
897  * Finds the names of applications in @dir that match @term.
898  */
899 static void
900 desktop_file_dir_search (DesktopFileDir *dir,
901                          const gchar    *search_token)
902 {
903   desktop_file_dir_unindexed_search (dir, search_token);
904 }
905
906 /* Lock/unlock and global setup API {{{2 */
907
908 static void
909 desktop_file_dirs_lock (void)
910 {
911   gint i;
912
913   g_mutex_lock (&desktop_file_dir_lock);
914
915   if (desktop_file_dirs == NULL)
916     {
917       const char * const *data_dirs;
918       GArray *tmp;
919       gint i;
920
921       tmp = g_array_new (FALSE, FALSE, sizeof (DesktopFileDir));
922
923       /* Highest priority: the user's ~/.local/share/applications */
924       desktop_file_dir_create (tmp, g_get_user_data_dir ());
925
926       /* Following that, XDG_DATA_DIRS/applications, in order */
927       data_dirs = g_get_system_data_dirs ();
928       for (i = 0; data_dirs[i]; i++)
929         desktop_file_dir_create (tmp, data_dirs[i]);
930
931       desktop_file_dirs = (DesktopFileDir *) tmp->data;
932       n_desktop_file_dirs = tmp->len;
933
934       g_array_free (tmp, FALSE);
935     }
936
937   for (i = 0; i < n_desktop_file_dirs; i++)
938     if (!desktop_file_dirs[i].is_setup)
939       desktop_file_dir_init (&desktop_file_dirs[i]);
940 }
941
942 static void
943 desktop_file_dirs_unlock (void)
944 {
945   g_mutex_unlock (&desktop_file_dir_lock);
946 }
947
948 static void
949 desktop_file_dirs_refresh (void)
950 {
951   desktop_file_dirs_lock ();
952   desktop_file_dirs_unlock ();
953 }
954
955 static void
956 desktop_file_dirs_invalidate_user (void)
957 {
958   g_mutex_lock (&desktop_file_dir_lock);
959
960   if (n_desktop_file_dirs)
961     desktop_file_dir_reset (&desktop_file_dirs[0]);
962
963   g_mutex_unlock (&desktop_file_dir_lock);
964 }
965
966 /* GDesktopAppInfo implementation {{{1 */
967 /* GObject implementation {{{2 */
968 static void
969 g_desktop_app_info_finalize (GObject *object)
970 {
971   GDesktopAppInfo *info;
972
973   info = G_DESKTOP_APP_INFO (object);
974
975   g_free (info->desktop_id);
976   g_free (info->filename);
977
978   if (info->keyfile)
979     g_key_file_unref (info->keyfile);
980
981   g_free (info->name);
982   g_free (info->generic_name);
983   g_free (info->fullname);
984   g_free (info->comment);
985   g_free (info->icon_name);
986   if (info->icon)
987     g_object_unref (info->icon);
988   g_strfreev (info->keywords);
989   g_strfreev (info->only_show_in);
990   g_strfreev (info->not_show_in);
991   g_free (info->try_exec);
992   g_free (info->exec);
993   g_free (info->binary);
994   g_free (info->path);
995   g_free (info->categories);
996   g_free (info->startup_wm_class);
997   g_strfreev (info->mime_types);
998   g_free (info->app_id);
999   g_strfreev (info->actions);
1000
1001   G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1002 }
1003
1004 static void
1005 g_desktop_app_info_set_property (GObject      *object,
1006                                  guint         prop_id,
1007                                  const GValue *value,
1008                                  GParamSpec   *pspec)
1009 {
1010   GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1011
1012   switch (prop_id)
1013     {
1014     case PROP_FILENAME:
1015       self->filename = g_value_dup_string (value);
1016       break;
1017
1018     default:
1019       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1020       break;
1021     }
1022 }
1023
1024 static void
1025 g_desktop_app_info_get_property (GObject    *object,
1026                                  guint       prop_id,
1027                                  GValue     *value,
1028                                  GParamSpec *pspec)
1029 {
1030   GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1031
1032   switch (prop_id)
1033     {
1034     case PROP_FILENAME:
1035       g_value_set_string (value, self->filename);
1036       break;
1037     default:
1038       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1039       break;
1040     }
1041 }
1042
1043 static void
1044 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1045 {
1046   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1047
1048   gobject_class->get_property = g_desktop_app_info_get_property;
1049   gobject_class->set_property = g_desktop_app_info_set_property;
1050   gobject_class->finalize = g_desktop_app_info_finalize;
1051
1052   /**
1053    * GDesktopAppInfo:filename:
1054    *
1055    * The origin filename of this #GDesktopAppInfo
1056    */
1057   g_object_class_install_property (gobject_class,
1058                                    PROP_FILENAME,
1059                                    g_param_spec_string ("filename", "Filename", "", NULL,
1060                                                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1061 }
1062
1063 static void
1064 g_desktop_app_info_init (GDesktopAppInfo *local)
1065 {
1066 }
1067
1068 /* Construction... {{{2 */
1069
1070 /*< internal >
1071  * binary_from_exec:
1072  * @exec: an exec line
1073  *
1074  * Returns the first word in an exec line (ie: the binary name).
1075  *
1076  * If @exec is "  progname --foo %F" then returns "progname".
1077  */
1078 static char *
1079 binary_from_exec (const char *exec)
1080 {
1081   const char *p, *start;
1082
1083   p = exec;
1084   while (*p == ' ')
1085     p++;
1086   start = p;
1087   while (*p != ' ' && *p != 0)
1088     p++;
1089
1090   return g_strndup (start, p - start);
1091 }
1092
1093 static gboolean
1094 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1095                                       GKeyFile        *key_file)
1096 {
1097   char *start_group;
1098   char *type;
1099   char *try_exec;
1100   char *exec;
1101   gboolean bus_activatable;
1102
1103   start_group = g_key_file_get_start_group (key_file);
1104   if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1105     {
1106       g_free (start_group);
1107       return FALSE;
1108     }
1109   g_free (start_group);
1110
1111   type = g_key_file_get_string (key_file,
1112                                 G_KEY_FILE_DESKTOP_GROUP,
1113                                 G_KEY_FILE_DESKTOP_KEY_TYPE,
1114                                 NULL);
1115   if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1116     {
1117       g_free (type);
1118       return FALSE;
1119     }
1120   g_free (type);
1121
1122   try_exec = g_key_file_get_string (key_file,
1123                                     G_KEY_FILE_DESKTOP_GROUP,
1124                                     G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1125                                     NULL);
1126   if (try_exec && try_exec[0] != '\0')
1127     {
1128       char *t;
1129       t = g_find_program_in_path (try_exec);
1130       if (t == NULL)
1131         {
1132           g_free (try_exec);
1133           return FALSE;
1134         }
1135       g_free (t);
1136     }
1137
1138   exec = g_key_file_get_string (key_file,
1139                                 G_KEY_FILE_DESKTOP_GROUP,
1140                                 G_KEY_FILE_DESKTOP_KEY_EXEC,
1141                                 NULL);
1142   if (exec && exec[0] != '\0')
1143     {
1144       gint argc;
1145       char **argv;
1146       if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1147         {
1148           g_free (exec);
1149           g_free (try_exec);
1150           return FALSE;
1151         }
1152       else
1153         {
1154           char *t;
1155           t = g_find_program_in_path (argv[0]);
1156           g_strfreev (argv);
1157
1158           if (t == NULL)
1159             {
1160               g_free (exec);
1161               g_free (try_exec);
1162               return FALSE;
1163             }
1164           g_free (t);
1165         }
1166     }
1167
1168   info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1169   info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1170   info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1171   info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1172   info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1173   info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1174   info->icon_name =  g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1175   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);
1176   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);
1177   info->try_exec = try_exec;
1178   info->exec = exec;
1179   info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1180   info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1181   info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1182   info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1183   info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1184   info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1185   info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1186   info->mime_types = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL, NULL);
1187   bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1188   info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1189
1190   /* Remove the special-case: no Actions= key just means 0 extra actions */
1191   if (info->actions == NULL)
1192     info->actions = g_new0 (gchar *, 0 + 1);
1193
1194   info->icon = NULL;
1195   if (info->icon_name)
1196     {
1197       if (g_path_is_absolute (info->icon_name))
1198         {
1199           GFile *file;
1200
1201           file = g_file_new_for_path (info->icon_name);
1202           info->icon = g_file_icon_new (file);
1203           g_object_unref (file);
1204         }
1205       else
1206         {
1207           char *p;
1208
1209           /* Work around a common mistake in desktop files */
1210           if ((p = strrchr (info->icon_name, '.')) != NULL &&
1211               (strcmp (p, ".png") == 0 ||
1212                strcmp (p, ".xpm") == 0 ||
1213                strcmp (p, ".svg") == 0))
1214             *p = 0;
1215
1216           info->icon = g_themed_icon_new (info->icon_name);
1217         }
1218     }
1219
1220   if (info->exec)
1221     info->binary = binary_from_exec (info->exec);
1222
1223   if (info->path && info->path[0] == '\0')
1224     {
1225       g_free (info->path);
1226       info->path = NULL;
1227     }
1228
1229   /* Can only be DBusActivatable if we know the filename, which means
1230    * that this won't work for the load-from-keyfile case.
1231    */
1232   if (bus_activatable && info->filename)
1233     {
1234       gchar *basename;
1235       gchar *last_dot;
1236
1237       basename = g_path_get_basename (info->filename);
1238       last_dot = strrchr (basename, '.');
1239
1240       if (last_dot && g_str_equal (last_dot, ".desktop"))
1241         {
1242           *last_dot = '\0';
1243
1244           if (g_dbus_is_interface_name (basename))
1245             info->app_id = g_strdup (basename);
1246         }
1247
1248       g_free (basename);
1249     }
1250
1251   info->keyfile = g_key_file_ref (key_file);
1252
1253   return TRUE;
1254 }
1255
1256 static gboolean
1257 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1258 {
1259   GKeyFile *key_file;
1260   gboolean retval = FALSE;
1261
1262   g_return_val_if_fail (self->filename != NULL, FALSE);
1263
1264   self->desktop_id = g_path_get_basename (self->filename);
1265
1266   key_file = g_key_file_new ();
1267
1268   if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
1269     retval = g_desktop_app_info_load_from_keyfile (self, key_file);
1270
1271   g_key_file_unref (key_file);
1272   return retval;
1273 }
1274
1275 /**
1276  * g_desktop_app_info_new_from_keyfile:
1277  * @key_file: an opened #GKeyFile
1278  *
1279  * Creates a new #GDesktopAppInfo.
1280  *
1281  * Returns: a new #GDesktopAppInfo or %NULL on error.
1282  *
1283  * Since: 2.18
1284  **/
1285 GDesktopAppInfo *
1286 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
1287 {
1288   GDesktopAppInfo *info;
1289
1290   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1291   info->filename = NULL;
1292   if (!g_desktop_app_info_load_from_keyfile (info, key_file))
1293     {
1294       g_object_unref (info);
1295       return NULL;
1296     }
1297   return info;
1298 }
1299
1300 /**
1301  * g_desktop_app_info_new_from_filename:
1302  * @filename: the path of a desktop file, in the GLib filename encoding
1303  *
1304  * Creates a new #GDesktopAppInfo.
1305  *
1306  * Returns: a new #GDesktopAppInfo or %NULL on error.
1307  **/
1308 GDesktopAppInfo *
1309 g_desktop_app_info_new_from_filename (const char *filename)
1310 {
1311   GDesktopAppInfo *info = NULL;
1312
1313   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1314   if (!g_desktop_app_info_load_file (info))
1315     {
1316       g_object_unref (info);
1317       return NULL;
1318     }
1319   return info;
1320 }
1321
1322 /**
1323  * g_desktop_app_info_new:
1324  * @desktop_id: the desktop file id
1325  *
1326  * Creates a new #GDesktopAppInfo based on a desktop file id.
1327  *
1328  * A desktop file id is the basename of the desktop file, including the
1329  * .desktop extension. GIO is looking for a desktop file with this name
1330  * in the `applications` subdirectories of the XDG
1331  * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
1332  * and `XDG_DATA_DIRS` environment variables). GIO also supports the
1333  * prefix-to-subdirectory mapping that is described in the
1334  * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
1335  * (i.e. a desktop id of kde-foo.desktop will match
1336  * `/usr/share/applications/kde/foo.desktop`).
1337  *
1338  * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
1339  */
1340 GDesktopAppInfo *
1341 g_desktop_app_info_new (const char *desktop_id)
1342 {
1343   GDesktopAppInfo *appinfo = NULL;
1344   guint i;
1345
1346   desktop_file_dirs_lock ();
1347
1348   for (i = 0; i < n_desktop_file_dirs; i++)
1349     {
1350       appinfo = desktop_file_dir_get_app (&desktop_file_dirs[i], desktop_id);
1351
1352       if (appinfo)
1353         break;
1354     }
1355
1356   desktop_file_dirs_unlock ();
1357
1358   if (appinfo == NULL)
1359     return NULL;
1360
1361   g_free (appinfo->desktop_id);
1362   appinfo->desktop_id = g_strdup (desktop_id);
1363
1364   if (g_desktop_app_info_get_is_hidden (appinfo))
1365     {
1366       g_object_unref (appinfo);
1367       appinfo = NULL;
1368     }
1369
1370   return appinfo;
1371 }
1372
1373 static GAppInfo *
1374 g_desktop_app_info_dup (GAppInfo *appinfo)
1375 {
1376   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1377   GDesktopAppInfo *new_info;
1378
1379   new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1380
1381   new_info->filename = g_strdup (info->filename);
1382   new_info->desktop_id = g_strdup (info->desktop_id);
1383
1384   if (info->keyfile)
1385     new_info->keyfile = g_key_file_ref (info->keyfile);
1386
1387   new_info->name = g_strdup (info->name);
1388   new_info->generic_name = g_strdup (info->generic_name);
1389   new_info->fullname = g_strdup (info->fullname);
1390   new_info->keywords = g_strdupv (info->keywords);
1391   new_info->comment = g_strdup (info->comment);
1392   new_info->nodisplay = info->nodisplay;
1393   new_info->icon_name = g_strdup (info->icon_name);
1394   if (info->icon)
1395     new_info->icon = g_object_ref (info->icon);
1396   new_info->only_show_in = g_strdupv (info->only_show_in);
1397   new_info->not_show_in = g_strdupv (info->not_show_in);
1398   new_info->try_exec = g_strdup (info->try_exec);
1399   new_info->exec = g_strdup (info->exec);
1400   new_info->binary = g_strdup (info->binary);
1401   new_info->path = g_strdup (info->path);
1402   new_info->app_id = g_strdup (info->app_id);
1403   new_info->hidden = info->hidden;
1404   new_info->terminal = info->terminal;
1405   new_info->startup_notify = info->startup_notify;
1406
1407   return G_APP_INFO (new_info);
1408 }
1409
1410 /* GAppInfo interface implementation functions {{{2 */
1411
1412 static gboolean
1413 g_desktop_app_info_equal (GAppInfo *appinfo1,
1414                           GAppInfo *appinfo2)
1415 {
1416   GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
1417   GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
1418
1419   if (info1->desktop_id == NULL ||
1420       info2->desktop_id == NULL)
1421     return info1 == info2;
1422
1423   return strcmp (info1->desktop_id, info2->desktop_id) == 0;
1424 }
1425
1426 static const char *
1427 g_desktop_app_info_get_id (GAppInfo *appinfo)
1428 {
1429   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1430
1431   return info->desktop_id;
1432 }
1433
1434 static const char *
1435 g_desktop_app_info_get_name (GAppInfo *appinfo)
1436 {
1437   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1438
1439   if (info->name == NULL)
1440     return _("Unnamed");
1441   return info->name;
1442 }
1443
1444 static const char *
1445 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
1446 {
1447   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1448
1449   if (info->fullname == NULL)
1450     return g_desktop_app_info_get_name (appinfo);
1451   return info->fullname;
1452 }
1453
1454 /**
1455  * g_desktop_app_info_get_is_hidden:
1456  * @info: a #GDesktopAppInfo.
1457  *
1458  * A desktop file is hidden if the Hidden key in it is
1459  * set to True.
1460  *
1461  * Returns: %TRUE if hidden, %FALSE otherwise.
1462  **/
1463 gboolean
1464 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
1465 {
1466   return info->hidden;
1467 }
1468
1469 /**
1470  * g_desktop_app_info_get_filename:
1471  * @info: a #GDesktopAppInfo
1472  *
1473  * When @info was created from a known filename, return it.  In some
1474  * situations such as the #GDesktopAppInfo returned from
1475  * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
1476  *
1477  * Returns: The full path to the file for @info, or %NULL if not known.
1478  * Since: 2.24
1479  */
1480 const char *
1481 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
1482 {
1483   return info->filename;
1484 }
1485
1486 static const char *
1487 g_desktop_app_info_get_description (GAppInfo *appinfo)
1488 {
1489   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1490
1491   return info->comment;
1492 }
1493
1494 static const char *
1495 g_desktop_app_info_get_executable (GAppInfo *appinfo)
1496 {
1497   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1498
1499   return info->binary;
1500 }
1501
1502 static const char *
1503 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
1504 {
1505   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1506
1507   return info->exec;
1508 }
1509
1510 static GIcon *
1511 g_desktop_app_info_get_icon (GAppInfo *appinfo)
1512 {
1513   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1514
1515   return info->icon;
1516 }
1517
1518 /**
1519  * g_desktop_app_info_get_categories:
1520  * @info: a #GDesktopAppInfo
1521  *
1522  * Gets the categories from the desktop file.
1523  *
1524  * Returns: The unparsed Categories key from the desktop file;
1525  *     i.e. no attempt is made to split it by ';' or validate it.
1526  */
1527 const char *
1528 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
1529 {
1530   return info->categories;
1531 }
1532
1533 /**
1534  * g_desktop_app_info_get_keywords:
1535  * @info: a #GDesktopAppInfo
1536  *
1537  * Gets the keywords from the desktop file.
1538  *
1539  * Returns: (transfer none): The value of the Keywords key
1540  *
1541  * Since: 2.32
1542  */
1543 const char * const *
1544 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
1545 {
1546   return (const char * const *)info->keywords;
1547 }
1548
1549 /**
1550  * g_desktop_app_info_get_generic_name:
1551  * @info: a #GDesktopAppInfo
1552  *
1553  * Gets the generic name from the destkop file.
1554  *
1555  * Returns: The value of the GenericName key
1556  */
1557 const char *
1558 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
1559 {
1560   return info->generic_name;
1561 }
1562
1563 /**
1564  * g_desktop_app_info_get_nodisplay:
1565  * @info: a #GDesktopAppInfo
1566  *
1567  * Gets the value of the NoDisplay key, which helps determine if the
1568  * application info should be shown in menus. See
1569  * #G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
1570  *
1571  * Returns: The value of the NoDisplay key
1572  *
1573  * Since: 2.30
1574  */
1575 gboolean
1576 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
1577 {
1578   return info->nodisplay;
1579 }
1580
1581 /**
1582  * g_desktop_app_info_get_show_in:
1583  * @info: a #GDesktopAppInfo
1584  * @desktop_env: a string specifying a desktop name
1585  *
1586  * Checks if the application info should be shown in menus that list available
1587  * applications for a specific name of the desktop, based on the
1588  * `OnlyShowIn` and `NotShowIn` keys.
1589  *
1590  * If @desktop_env is %NULL, then the name of the desktop set with
1591  * g_desktop_app_info_set_desktop_env() is used.
1592  *
1593  * Note that g_app_info_should_show() for @info will include this check (with
1594  * %NULL for @desktop_env) as well as additional checks.
1595  *
1596  * Returns: %TRUE if the @info should be shown in @desktop_env according to the
1597  * `OnlyShowIn` and `NotShowIn` keys, %FALSE
1598  * otherwise.
1599  *
1600  * Since: 2.30
1601  */
1602 gboolean
1603 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
1604                                 const gchar     *desktop_env)
1605 {
1606   gboolean found;
1607   int i;
1608
1609   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
1610
1611   if (!desktop_env) {
1612     G_LOCK (g_desktop_env);
1613     desktop_env = g_desktop_env;
1614     G_UNLOCK (g_desktop_env);
1615   }
1616
1617   if (info->only_show_in)
1618     {
1619       if (desktop_env == NULL)
1620         return FALSE;
1621
1622       found = FALSE;
1623       for (i = 0; info->only_show_in[i] != NULL; i++)
1624         {
1625           if (strcmp (info->only_show_in[i], desktop_env) == 0)
1626             {
1627               found = TRUE;
1628               break;
1629             }
1630         }
1631       if (!found)
1632         return FALSE;
1633     }
1634
1635   if (info->not_show_in && desktop_env)
1636     {
1637       for (i = 0; info->not_show_in[i] != NULL; i++)
1638         {
1639           if (strcmp (info->not_show_in[i], desktop_env) == 0)
1640             return FALSE;
1641         }
1642     }
1643
1644   return TRUE;
1645 }
1646
1647 /* Launching... {{{2 */
1648
1649 static char *
1650 expand_macro_single (char macro, char *uri)
1651 {
1652   GFile *file;
1653   char *result = NULL;
1654   char *path = NULL;
1655   char *name;
1656
1657   file = g_file_new_for_uri (uri);
1658
1659   switch (macro)
1660     {
1661     case 'u':
1662     case 'U':
1663       result = g_shell_quote (uri);
1664       break;
1665     case 'f':
1666     case 'F':
1667       path = g_file_get_path (file);
1668       if (path)
1669         result = g_shell_quote (path);
1670       break;
1671     case 'd':
1672     case 'D':
1673       path = g_file_get_path (file);
1674       if (path)
1675         {
1676           name = g_path_get_dirname (path);
1677           result = g_shell_quote (name);
1678           g_free (name);
1679         }
1680       break;
1681     case 'n':
1682     case 'N':
1683       path = g_file_get_path (file);
1684       if (path)
1685         {
1686           name = g_path_get_basename (path);
1687           result = g_shell_quote (name);
1688           g_free (name);
1689         }
1690       break;
1691     }
1692
1693   g_object_unref (file);
1694   g_free (path);
1695
1696   return result;
1697 }
1698
1699 static void
1700 expand_macro (char              macro,
1701               GString          *exec,
1702               GDesktopAppInfo  *info,
1703               GList           **uri_list)
1704 {
1705   GList *uris = *uri_list;
1706   char *expanded;
1707   gboolean force_file_uri;
1708   char force_file_uri_macro;
1709   char *uri;
1710
1711   g_return_if_fail (exec != NULL);
1712
1713   /* On %u and %U, pass POSIX file path pointing to the URI via
1714    * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
1715    * running or the URI doesn't have a POSIX file path via FUSE
1716    * we'll just pass the URI.
1717    */
1718   force_file_uri_macro = macro;
1719   force_file_uri = FALSE;
1720   if (!info->no_fuse)
1721     {
1722       switch (macro)
1723         {
1724         case 'u':
1725           force_file_uri_macro = 'f';
1726           force_file_uri = TRUE;
1727           break;
1728         case 'U':
1729           force_file_uri_macro = 'F';
1730           force_file_uri = TRUE;
1731           break;
1732         default:
1733           break;
1734         }
1735     }
1736
1737   switch (macro)
1738     {
1739     case 'u':
1740     case 'f':
1741     case 'd':
1742     case 'n':
1743       if (uris)
1744         {
1745           uri = uris->data;
1746           if (!force_file_uri ||
1747               /* Pass URI if it contains an anchor */
1748               strchr (uri, '#') != NULL)
1749             {
1750               expanded = expand_macro_single (macro, uri);
1751             }
1752           else
1753             {
1754               expanded = expand_macro_single (force_file_uri_macro, uri);
1755               if (expanded == NULL)
1756                 expanded = expand_macro_single (macro, uri);
1757             }
1758
1759           if (expanded)
1760             {
1761               g_string_append (exec, expanded);
1762               g_free (expanded);
1763             }
1764           uris = uris->next;
1765         }
1766
1767       break;
1768
1769     case 'U':
1770     case 'F':
1771     case 'D':
1772     case 'N':
1773       while (uris)
1774         {
1775           uri = uris->data;
1776
1777           if (!force_file_uri ||
1778               /* Pass URI if it contains an anchor */
1779               strchr (uri, '#') != NULL)
1780             {
1781               expanded = expand_macro_single (macro, uri);
1782             }
1783           else
1784             {
1785               expanded = expand_macro_single (force_file_uri_macro, uri);
1786               if (expanded == NULL)
1787                 expanded = expand_macro_single (macro, uri);
1788             }
1789
1790           if (expanded)
1791             {
1792               g_string_append (exec, expanded);
1793               g_free (expanded);
1794             }
1795
1796           uris = uris->next;
1797
1798           if (uris != NULL && expanded)
1799             g_string_append_c (exec, ' ');
1800         }
1801
1802       break;
1803
1804     case 'i':
1805       if (info->icon_name)
1806         {
1807           g_string_append (exec, "--icon ");
1808           expanded = g_shell_quote (info->icon_name);
1809           g_string_append (exec, expanded);
1810           g_free (expanded);
1811         }
1812       break;
1813
1814     case 'c':
1815       if (info->name)
1816         {
1817           expanded = g_shell_quote (info->name);
1818           g_string_append (exec, expanded);
1819           g_free (expanded);
1820         }
1821       break;
1822
1823     case 'k':
1824       if (info->filename)
1825         {
1826           expanded = g_shell_quote (info->filename);
1827           g_string_append (exec, expanded);
1828           g_free (expanded);
1829         }
1830       break;
1831
1832     case 'm': /* deprecated */
1833       break;
1834
1835     case '%':
1836       g_string_append_c (exec, '%');
1837       break;
1838     }
1839
1840   *uri_list = uris;
1841 }
1842
1843 static gboolean
1844 expand_application_parameters (GDesktopAppInfo   *info,
1845                                const gchar       *exec_line,
1846                                GList            **uris,
1847                                int               *argc,
1848                                char            ***argv,
1849                                GError           **error)
1850 {
1851   GList *uri_list = *uris;
1852   const char *p = exec_line;
1853   GString *expanded_exec;
1854   gboolean res;
1855
1856   if (exec_line == NULL)
1857     {
1858       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1859                            _("Desktop file didn't specify Exec field"));
1860       return FALSE;
1861     }
1862
1863   expanded_exec = g_string_new (NULL);
1864
1865   while (*p)
1866     {
1867       if (p[0] == '%' && p[1] != '\0')
1868         {
1869           expand_macro (p[1], expanded_exec, info, uris);
1870           p++;
1871         }
1872       else
1873         g_string_append_c (expanded_exec, *p);
1874
1875       p++;
1876     }
1877
1878   /* No file substitutions */
1879   if (uri_list == *uris && uri_list != NULL)
1880     {
1881       /* If there is no macro default to %f. This is also what KDE does */
1882       g_string_append_c (expanded_exec, ' ');
1883       expand_macro ('f', expanded_exec, info, uris);
1884     }
1885
1886   res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
1887   g_string_free (expanded_exec, TRUE);
1888   return res;
1889 }
1890
1891 static gboolean
1892 prepend_terminal_to_vector (int    *argc,
1893                             char ***argv)
1894 {
1895 #ifndef G_OS_WIN32
1896   char **real_argv;
1897   int real_argc;
1898   int i, j;
1899   char **term_argv = NULL;
1900   int term_argc = 0;
1901   char *check;
1902   char **the_argv;
1903
1904   g_return_val_if_fail (argc != NULL, FALSE);
1905   g_return_val_if_fail (argv != NULL, FALSE);
1906
1907   /* sanity */
1908   if(*argv == NULL)
1909     *argc = 0;
1910
1911   the_argv = *argv;
1912
1913   /* compute size if not given */
1914   if (*argc < 0)
1915     {
1916       for (i = 0; the_argv[i] != NULL; i++)
1917         ;
1918       *argc = i;
1919     }
1920
1921   term_argc = 2;
1922   term_argv = g_new0 (char *, 3);
1923
1924   check = g_find_program_in_path ("gnome-terminal");
1925   if (check != NULL)
1926     {
1927       term_argv[0] = check;
1928       /* Note that gnome-terminal takes -x and
1929        * as -e in gnome-terminal is broken we use that. */
1930       term_argv[1] = g_strdup ("-x");
1931     }
1932   else
1933     {
1934       if (check == NULL)
1935         check = g_find_program_in_path ("nxterm");
1936       if (check == NULL)
1937         check = g_find_program_in_path ("color-xterm");
1938       if (check == NULL)
1939         check = g_find_program_in_path ("rxvt");
1940       if (check == NULL)
1941         check = g_find_program_in_path ("xterm");
1942       if (check == NULL)
1943         check = g_find_program_in_path ("dtterm");
1944       if (check == NULL)
1945         {
1946           check = g_strdup ("xterm");
1947           g_warning ("couldn't find a terminal, falling back to xterm");
1948         }
1949       term_argv[0] = check;
1950       term_argv[1] = g_strdup ("-e");
1951     }
1952
1953   real_argc = term_argc + *argc;
1954   real_argv = g_new (char *, real_argc + 1);
1955
1956   for (i = 0; i < term_argc; i++)
1957     real_argv[i] = term_argv[i];
1958
1959   for (j = 0; j < *argc; j++, i++)
1960     real_argv[i] = (char *)the_argv[j];
1961
1962   real_argv[i] = NULL;
1963
1964   g_free (*argv);
1965   *argv = real_argv;
1966   *argc = real_argc;
1967
1968   /* we use g_free here as we sucked all the inner strings
1969    * out from it into real_argv */
1970   g_free (term_argv);
1971   return TRUE;
1972 #else
1973   return FALSE;
1974 #endif /* G_OS_WIN32 */
1975 }
1976
1977 static GList *
1978 create_files_for_uris (GList *uris)
1979 {
1980   GList *res;
1981   GList *iter;
1982
1983   res = NULL;
1984
1985   for (iter = uris; iter; iter = iter->next)
1986     {
1987       GFile *file = g_file_new_for_uri ((char *)iter->data);
1988       res = g_list_prepend (res, file);
1989     }
1990
1991   return g_list_reverse (res);
1992 }
1993
1994 typedef struct
1995 {
1996   GSpawnChildSetupFunc user_setup;
1997   gpointer user_setup_data;
1998
1999   char *pid_envvar;
2000 } ChildSetupData;
2001
2002 static void
2003 child_setup (gpointer user_data)
2004 {
2005   ChildSetupData *data = user_data;
2006
2007   if (data->pid_envvar)
2008     {
2009       pid_t pid = getpid ();
2010       char buf[20];
2011       int i;
2012
2013       /* Write the pid into the space already reserved for it in the
2014        * environment array. We can't use sprintf because it might
2015        * malloc, so we do it by hand. It's simplest to write the pid
2016        * out backwards first, then copy it over.
2017        */
2018       for (i = 0; pid; i++, pid /= 10)
2019         buf[i] = (pid % 10) + '0';
2020       for (i--; i >= 0; i--)
2021         *(data->pid_envvar++) = buf[i];
2022       *data->pid_envvar = '\0';
2023     }
2024
2025   if (data->user_setup)
2026     data->user_setup (data->user_setup_data);
2027 }
2028
2029 static void
2030 notify_desktop_launch (GDBusConnection  *session_bus,
2031                        GDesktopAppInfo  *info,
2032                        long              pid,
2033                        const char       *display,
2034                        const char       *sn_id,
2035                        GList            *uris)
2036 {
2037   GDBusMessage *msg;
2038   GVariantBuilder uri_variant;
2039   GVariantBuilder extras_variant;
2040   GList *iter;
2041   const char *desktop_file_id;
2042   const char *gio_desktop_file;
2043
2044   if (session_bus == NULL)
2045     return;
2046
2047   g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2048   for (iter = uris; iter; iter = iter->next)
2049     g_variant_builder_add (&uri_variant, "s", iter->data);
2050
2051   g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2052   if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2053     g_variant_builder_add (&extras_variant, "{sv}",
2054                            "startup-id",
2055                            g_variant_new ("s",
2056                                           sn_id));
2057   gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2058   if (gio_desktop_file != NULL)
2059     g_variant_builder_add (&extras_variant, "{sv}",
2060                            "origin-desktop-file",
2061                            g_variant_new_bytestring (gio_desktop_file));
2062   if (g_get_prgname () != NULL)
2063     g_variant_builder_add (&extras_variant, "{sv}",
2064                            "origin-prgname",
2065                            g_variant_new_bytestring (g_get_prgname ()));
2066   g_variant_builder_add (&extras_variant, "{sv}",
2067                          "origin-pid",
2068                          g_variant_new ("x",
2069                                         (gint64)getpid ()));
2070
2071   if (info->filename)
2072     desktop_file_id = info->filename;
2073   else if (info->desktop_id)
2074     desktop_file_id = info->desktop_id;
2075   else
2076     desktop_file_id = "";
2077
2078   msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2079                                    "org.gtk.gio.DesktopAppInfo",
2080                                    "Launched");
2081   g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2082                                                g_variant_new_bytestring (desktop_file_id),
2083                                                display ? display : "",
2084                                                (gint64)pid,
2085                                                &uri_variant,
2086                                                &extras_variant));
2087   g_dbus_connection_send_message (session_bus,
2088                                   msg, 0,
2089                                   NULL,
2090                                   NULL);
2091   g_object_unref (msg);
2092 }
2093
2094 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2095
2096 static gboolean
2097 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo            *info,
2098                                            GDBusConnection            *session_bus,
2099                                            const gchar                *exec_line,
2100                                            GList                      *uris,
2101                                            GAppLaunchContext          *launch_context,
2102                                            GSpawnFlags                 spawn_flags,
2103                                            GSpawnChildSetupFunc        user_setup,
2104                                            gpointer                    user_setup_data,
2105                                            GDesktopAppLaunchCallback   pid_callback,
2106                                            gpointer                    pid_callback_data,
2107                                            GError                    **error)
2108 {
2109   gboolean completed = FALSE;
2110   GList *old_uris;
2111   char **argv, **envp;
2112   int argc;
2113   ChildSetupData data;
2114
2115   g_return_val_if_fail (info != NULL, FALSE);
2116
2117   argv = NULL;
2118
2119   if (launch_context)
2120     envp = g_app_launch_context_get_environment (launch_context);
2121   else
2122     envp = g_get_environ ();
2123
2124   do
2125     {
2126       GPid pid;
2127       GList *launched_uris;
2128       GList *iter;
2129       char *display, *sn_id;
2130
2131       old_uris = uris;
2132       if (!expand_application_parameters (info, exec_line, &uris, &argc, &argv, error))
2133         goto out;
2134
2135       /* Get the subset of URIs we're launching with this process */
2136       launched_uris = NULL;
2137       for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
2138         launched_uris = g_list_prepend (launched_uris, iter->data);
2139       launched_uris = g_list_reverse (launched_uris);
2140
2141       if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2142         {
2143           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2144                                _("Unable to find terminal required for application"));
2145           goto out;
2146         }
2147
2148       data.user_setup = user_setup;
2149       data.user_setup_data = user_setup_data;
2150
2151       if (info->filename)
2152         {
2153           envp = g_environ_setenv (envp,
2154                                    "GIO_LAUNCHED_DESKTOP_FILE",
2155                                    info->filename,
2156                                    TRUE);
2157           envp = g_environ_setenv (envp,
2158                                    "GIO_LAUNCHED_DESKTOP_FILE_PID",
2159                                    "XXXXXXXXXXXXXXXXXXXX", /* filled in child_setup */
2160                                    TRUE);
2161           data.pid_envvar = (char *)g_environ_getenv (envp, "GIO_LAUNCHED_DESKTOP_FILE_PID");
2162         }
2163       else
2164         {
2165           data.pid_envvar = NULL;
2166         }
2167
2168       display = NULL;
2169       sn_id = NULL;
2170       if (launch_context)
2171         {
2172           GList *launched_files = create_files_for_uris (launched_uris);
2173
2174           display = g_app_launch_context_get_display (launch_context,
2175                                                       G_APP_INFO (info),
2176                                                       launched_files);
2177           if (display)
2178             envp = g_environ_setenv (envp, "DISPLAY", display, TRUE);
2179
2180           if (info->startup_notify)
2181             {
2182               sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2183                                                                   G_APP_INFO (info),
2184                                                                   launched_files);
2185               envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2186             }
2187
2188           g_list_free_full (launched_files, g_object_unref);
2189         }
2190
2191       if (!g_spawn_async (info->path,
2192                           argv,
2193                           envp,
2194                           spawn_flags,
2195                           child_setup,
2196                           &data,
2197                           &pid,
2198                           error))
2199         {
2200           if (sn_id)
2201             g_app_launch_context_launch_failed (launch_context, sn_id);
2202
2203           g_free (display);
2204           g_free (sn_id);
2205           g_list_free (launched_uris);
2206
2207           goto out;
2208         }
2209
2210       if (pid_callback != NULL)
2211         pid_callback (info, pid, pid_callback_data);
2212
2213       if (launch_context != NULL)
2214         {
2215           GVariantBuilder builder;
2216           GVariant *platform_data;
2217
2218           g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2219           g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2220           if (sn_id)
2221             g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2222           platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2223           g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2224           g_variant_unref (platform_data);
2225         }
2226
2227       notify_desktop_launch (session_bus,
2228                              info,
2229                              pid,
2230                              display,
2231                              sn_id,
2232                              launched_uris);
2233
2234       g_free (display);
2235       g_free (sn_id);
2236       g_list_free (launched_uris);
2237
2238       g_strfreev (argv);
2239       argv = NULL;
2240     }
2241   while (uris != NULL);
2242
2243   completed = TRUE;
2244
2245  out:
2246   g_strfreev (argv);
2247   g_strfreev (envp);
2248
2249   return completed;
2250 }
2251
2252 static gchar *
2253 object_path_from_appid (const gchar *app_id)
2254 {
2255   gchar *path;
2256   gint i, n;
2257
2258   n = strlen (app_id);
2259   path = g_malloc (n + 2);
2260
2261   path[0] = '/';
2262
2263   for (i = 0; i < n; i++)
2264     if (app_id[i] != '.')
2265       path[i + 1] = app_id[i];
2266     else
2267       path[i + 1] = '/';
2268
2269   path[i + 1] = '\0';
2270
2271   return path;
2272 }
2273
2274 static GVariant *
2275 g_desktop_app_info_make_platform_data (GDesktopAppInfo   *info,
2276                                        GList             *uris,
2277                                        GAppLaunchContext *launch_context)
2278 {
2279   GVariantBuilder builder;
2280
2281   g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2282
2283   if (launch_context)
2284     {
2285       GList *launched_files = create_files_for_uris (uris);
2286
2287       if (info->startup_notify)
2288         {
2289           gchar *sn_id;
2290
2291           sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2292           g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2293         }
2294
2295       g_list_free_full (launched_files, g_object_unref);
2296     }
2297
2298   return g_variant_builder_end (&builder);
2299 }
2300
2301 static gboolean
2302 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo    *info,
2303                                           GDBusConnection    *session_bus,
2304                                           GList              *uris,
2305                                           GAppLaunchContext  *launch_context)
2306 {
2307   GVariantBuilder builder;
2308   gchar *object_path;
2309
2310   g_return_val_if_fail (info != NULL, FALSE);
2311
2312   g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2313
2314   if (uris)
2315     {
2316       GList *iter;
2317
2318       g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2319       for (iter = uris; iter; iter = iter->next)
2320         g_variant_builder_add (&builder, "s", iter->data);
2321       g_variant_builder_close (&builder);
2322     }
2323
2324   g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2325
2326   /* This is non-blocking API.  Similar to launching via fork()/exec()
2327    * we don't wait around to see if the program crashed during startup.
2328    * This is what startup-notification's job is...
2329    */
2330   object_path = object_path_from_appid (info->app_id);
2331   g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2332                           uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2333                           NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
2334   g_free (object_path);
2335
2336   return TRUE;
2337 }
2338
2339 static gboolean
2340 g_desktop_app_info_launch_uris_internal (GAppInfo                   *appinfo,
2341                                          GList                      *uris,
2342                                          GAppLaunchContext          *launch_context,
2343                                          GSpawnFlags                 spawn_flags,
2344                                          GSpawnChildSetupFunc        user_setup,
2345                                          gpointer                    user_setup_data,
2346                                          GDesktopAppLaunchCallback   pid_callback,
2347                                          gpointer                    pid_callback_data,
2348                                          GError                     **error)
2349 {
2350   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2351   GDBusConnection *session_bus;
2352   gboolean success = TRUE;
2353
2354   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
2355
2356   if (session_bus && info->app_id)
2357     g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context);
2358   else
2359     success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
2360                                                          spawn_flags, user_setup, user_setup_data,
2361                                                          pid_callback, pid_callback_data, error);
2362
2363   if (session_bus != NULL)
2364     {
2365       /* This asynchronous flush holds a reference until it completes,
2366        * which ensures that the following unref won't immediately kill
2367        * the connection if we were the initial owner.
2368        */
2369       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
2370       g_object_unref (session_bus);
2371     }
2372
2373   return success;
2374 }
2375
2376 static gboolean
2377 g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
2378                                 GList              *uris,
2379                                 GAppLaunchContext  *launch_context,
2380                                 GError            **error)
2381 {
2382   return g_desktop_app_info_launch_uris_internal (appinfo, uris,
2383                                                   launch_context,
2384                                                   _SPAWN_FLAGS_DEFAULT,
2385                                                   NULL, NULL, NULL, NULL,
2386                                                   error);
2387 }
2388
2389 static gboolean
2390 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
2391 {
2392   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2393
2394   return info->exec &&
2395     ((strstr (info->exec, "%u") != NULL) ||
2396      (strstr (info->exec, "%U") != NULL));
2397 }
2398
2399 static gboolean
2400 g_desktop_app_info_supports_files (GAppInfo *appinfo)
2401 {
2402   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2403
2404   return info->exec &&
2405     ((strstr (info->exec, "%f") != NULL) ||
2406      (strstr (info->exec, "%F") != NULL));
2407 }
2408
2409 static gboolean
2410 g_desktop_app_info_launch (GAppInfo           *appinfo,
2411                            GList              *files,
2412                            GAppLaunchContext  *launch_context,
2413                            GError            **error)
2414 {
2415   GList *uris;
2416   char *uri;
2417   gboolean res;
2418
2419   uris = NULL;
2420   while (files)
2421     {
2422       uri = g_file_get_uri (files->data);
2423       uris = g_list_prepend (uris, uri);
2424       files = files->next;
2425     }
2426
2427   uris = g_list_reverse (uris);
2428
2429   res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
2430
2431   g_list_free_full (uris, g_free);
2432
2433   return res;
2434 }
2435
2436 /**
2437  * g_desktop_app_info_launch_uris_as_manager:
2438  * @appinfo: a #GDesktopAppInfo
2439  * @uris: (element-type utf8): List of URIs
2440  * @launch_context: (allow-none): a #GAppLaunchContext
2441  * @spawn_flags: #GSpawnFlags, used for each process
2442  * @user_setup: (scope call) (allow-none): a #GSpawnChildSetupFunc, used once
2443  *     for each process.
2444  * @user_setup_data: (closure user_setup) (allow-none): User data for @user_setup
2445  * @pid_callback: (scope call) (allow-none): Callback for child processes
2446  * @pid_callback_data: (closure pid_callback) (allow-none): User data for @callback
2447  * @error: return location for a #GError, or %NULL
2448  *
2449  * This function performs the equivalent of g_app_info_launch_uris(),
2450  * but is intended primarily for operating system components that
2451  * launch applications.  Ordinary applications should use
2452  * g_app_info_launch_uris().
2453  *
2454  * If the application is launched via traditional UNIX fork()/exec()
2455  * then @spawn_flags, @user_setup and @user_setup_data are used for the
2456  * call to g_spawn_async().  Additionally, @pid_callback (with
2457  * @pid_callback_data) will be called to inform about the PID of the
2458  * created process.
2459  *
2460  * If application launching occurs via some other mechanism (eg: D-Bus
2461  * activation) then @spawn_flags, @user_setup, @user_setup_data,
2462  * @pid_callback and @pid_callback_data are ignored.
2463  *
2464  * Returns: %TRUE on successful launch, %FALSE otherwise.
2465  */
2466 gboolean
2467 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo            *appinfo,
2468                                            GList                      *uris,
2469                                            GAppLaunchContext          *launch_context,
2470                                            GSpawnFlags                 spawn_flags,
2471                                            GSpawnChildSetupFunc        user_setup,
2472                                            gpointer                    user_setup_data,
2473                                            GDesktopAppLaunchCallback   pid_callback,
2474                                            gpointer                    pid_callback_data,
2475                                            GError                    **error)
2476 {
2477   return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
2478                                                   uris,
2479                                                   launch_context,
2480                                                   spawn_flags,
2481                                                   user_setup,
2482                                                   user_setup_data,
2483                                                   pid_callback,
2484                                                   pid_callback_data,
2485                                                   error);
2486 }
2487
2488 /* OnlyShowIn API support {{{2 */
2489
2490 /**
2491  * g_desktop_app_info_set_desktop_env:
2492  * @desktop_env: a string specifying what desktop this is
2493  *
2494  * Sets the name of the desktop that the application is running in.
2495  * This is used by g_app_info_should_show() and
2496  * g_desktop_app_info_get_show_in() to evaluate the
2497  * `OnlyShowIn` and `NotShowIn`
2498  * desktop entry fields.
2499  *
2500  * The 
2501  * [Desktop Menu specification](http://standards.freedesktop.org/menu-spec/latest/)
2502  * recognizes the following:
2503  * - GNOME
2504  * - KDE
2505  * - ROX
2506  * - XFCE
2507  * - LXDE
2508  * - Unity
2509  * - Old
2510  *
2511  * Should be called only once; subsequent calls are ignored.
2512  */
2513 void
2514 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
2515 {
2516   G_LOCK (g_desktop_env);
2517   if (!g_desktop_env)
2518     g_desktop_env = g_strdup (desktop_env);
2519   G_UNLOCK (g_desktop_env);
2520 }
2521
2522 static gboolean
2523 g_desktop_app_info_should_show (GAppInfo *appinfo)
2524 {
2525   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2526
2527   if (info->nodisplay)
2528     return FALSE;
2529
2530   return g_desktop_app_info_get_show_in (info, NULL);
2531 }
2532
2533 /* mime types/default apps support {{{2 */
2534
2535 typedef enum {
2536   APP_DIR,
2537   MIMETYPE_DIR
2538 } DirType;
2539
2540 static char *
2541 ensure_dir (DirType   type,
2542             GError  **error)
2543 {
2544   char *path, *display_name;
2545   int errsv;
2546
2547   if (type == APP_DIR)
2548     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
2549   else
2550     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
2551
2552   errno = 0;
2553   if (g_mkdir_with_parents (path, 0700) == 0)
2554     return path;
2555
2556   errsv = errno;
2557   display_name = g_filename_display_name (path);
2558   if (type == APP_DIR)
2559     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2560                  _("Can't create user application configuration folder %s: %s"),
2561                  display_name, g_strerror (errsv));
2562   else
2563     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2564                  _("Can't create user MIME configuration folder %s: %s"),
2565                  display_name, g_strerror (errsv));
2566
2567   g_free (display_name);
2568   g_free (path);
2569
2570   return NULL;
2571 }
2572
2573 static gboolean
2574 update_mimeapps_list (const char  *desktop_id,
2575                       const char  *content_type,
2576                       UpdateMimeFlags flags,
2577                       GError     **error)
2578 {
2579   char *dirname, *filename, *string;
2580   GKeyFile *key_file;
2581   gboolean load_succeeded, res;
2582   char **old_list, **list;
2583   gsize length, data_size;
2584   char *data;
2585   int i, j, k;
2586   char **content_types;
2587
2588   /* Don't add both at start and end */
2589   g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
2590               (flags & UPDATE_MIME_SET_NON_DEFAULT)));
2591
2592   dirname = ensure_dir (APP_DIR, error);
2593   if (!dirname)
2594     return FALSE;
2595
2596   filename = g_build_filename (dirname, "mimeapps.list", NULL);
2597   g_free (dirname);
2598
2599   key_file = g_key_file_new ();
2600   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
2601   if (!load_succeeded ||
2602       (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
2603        !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
2604        !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
2605     {
2606       g_key_file_free (key_file);
2607       key_file = g_key_file_new ();
2608     }
2609
2610   if (content_type)
2611     {
2612       content_types = g_new (char *, 2);
2613       content_types[0] = g_strdup (content_type);
2614       content_types[1] = NULL;
2615     }
2616   else
2617     {
2618       content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
2619     }
2620
2621   for (k = 0; content_types && content_types[k]; k++)
2622     {
2623       /* set as default, if requested so */
2624       string = g_key_file_get_string (key_file,
2625                                       DEFAULT_APPLICATIONS_GROUP,
2626                                       content_types[k],
2627                                       NULL);
2628
2629       if (g_strcmp0 (string, desktop_id) != 0 &&
2630           (flags & UPDATE_MIME_SET_DEFAULT))
2631         {
2632           g_free (string);
2633           string = g_strdup (desktop_id);
2634
2635           /* add in the non-default list too, if it's not already there */
2636           flags |= UPDATE_MIME_SET_NON_DEFAULT;
2637         }
2638
2639       if (string == NULL || desktop_id == NULL)
2640         g_key_file_remove_key (key_file,
2641                                DEFAULT_APPLICATIONS_GROUP,
2642                                content_types[k],
2643                                NULL);
2644       else
2645         g_key_file_set_string (key_file,
2646                                DEFAULT_APPLICATIONS_GROUP,
2647                                content_types[k],
2648                                string);
2649
2650       g_free (string);
2651     }
2652
2653   if (content_type)
2654     {
2655       /* reuse the list from above */
2656     }
2657   else
2658     {
2659       g_strfreev (content_types);
2660       content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
2661     }
2662
2663   for (k = 0; content_types && content_types[k]; k++)
2664     {
2665       /* Add to the right place in the list */
2666
2667       length = 0;
2668       old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
2669                                              content_types[k], &length, NULL);
2670
2671       list = g_new (char *, 1 + length + 1);
2672
2673       i = 0;
2674
2675       /* if we're adding a last-used hint, just put the application in front of the list */
2676       if (flags & UPDATE_MIME_SET_LAST_USED)
2677         {
2678           /* avoid adding this again as non-default later */
2679           if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2680             flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2681
2682           list[i++] = g_strdup (desktop_id);
2683         }
2684
2685       if (old_list)
2686         {
2687           for (j = 0; old_list[j] != NULL; j++)
2688             {
2689               if (g_strcmp0 (old_list[j], desktop_id) != 0)
2690                 {
2691                   /* rewrite other entries if they're different from the new one */
2692                   list[i++] = g_strdup (old_list[j]);
2693                 }
2694               else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2695                 {
2696                   /* we encountered an old entry which is equal to the one we're adding as non-default,
2697                    * don't change its position in the list.
2698                    */
2699                   flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2700                   list[i++] = g_strdup (old_list[j]);
2701                 }
2702             }
2703         }
2704
2705       /* add it at the end of the list */
2706       if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2707         list[i++] = g_strdup (desktop_id);
2708
2709       list[i] = NULL;
2710
2711       g_strfreev (old_list);
2712
2713       if (list[0] == NULL || desktop_id == NULL)
2714         g_key_file_remove_key (key_file,
2715                                ADDED_ASSOCIATIONS_GROUP,
2716                                content_types[k],
2717                                NULL);
2718       else
2719         g_key_file_set_string_list (key_file,
2720                                     ADDED_ASSOCIATIONS_GROUP,
2721                                     content_types[k],
2722                                     (const char * const *)list, i);
2723
2724       g_strfreev (list);
2725     }
2726
2727   if (content_type)
2728     {
2729       /* reuse the list from above */
2730     }
2731   else
2732     {
2733       g_strfreev (content_types);
2734       content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
2735     }
2736
2737   for (k = 0; content_types && content_types[k]; k++)
2738     {
2739       /* Remove from removed associations group (unless remove) */
2740
2741       length = 0;
2742       old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
2743                                              content_types[k], &length, NULL);
2744
2745       list = g_new (char *, 1 + length + 1);
2746
2747       i = 0;
2748       if (flags & UPDATE_MIME_REMOVE)
2749         list[i++] = g_strdup (desktop_id);
2750       if (old_list)
2751         {
2752           for (j = 0; old_list[j] != NULL; j++)
2753             {
2754               if (g_strcmp0 (old_list[j], desktop_id) != 0)
2755                 list[i++] = g_strdup (old_list[j]);
2756             }
2757         }
2758       list[i] = NULL;
2759
2760       g_strfreev (old_list);
2761
2762       if (list[0] == NULL || desktop_id == NULL)
2763         g_key_file_remove_key (key_file,
2764                                REMOVED_ASSOCIATIONS_GROUP,
2765                                content_types[k],
2766                                NULL);
2767       else
2768         g_key_file_set_string_list (key_file,
2769                                     REMOVED_ASSOCIATIONS_GROUP,
2770                                     content_types[k],
2771                                     (const char * const *)list, i);
2772
2773       g_strfreev (list);
2774     }
2775
2776   g_strfreev (content_types);
2777
2778   data = g_key_file_to_data (key_file, &data_size, error);
2779   g_key_file_free (key_file);
2780
2781   res = g_file_set_contents (filename, data, data_size, error);
2782
2783   mime_info_cache_reload (NULL);
2784
2785   g_free (filename);
2786   g_free (data);
2787
2788   return res;
2789 }
2790
2791 static gboolean
2792 g_desktop_app_info_set_as_last_used_for_type (GAppInfo    *appinfo,
2793                                               const char  *content_type,
2794                                               GError     **error)
2795 {
2796   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2797
2798   if (!g_desktop_app_info_ensure_saved (info, error))
2799     return FALSE;
2800
2801   if (!info->desktop_id)
2802     {
2803       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2804                            _("Application information lacks an identifier"));
2805       return FALSE;
2806     }
2807
2808   /* both add support for the content type and set as last used */
2809   return update_mimeapps_list (info->desktop_id, content_type,
2810                                UPDATE_MIME_SET_NON_DEFAULT |
2811                                UPDATE_MIME_SET_LAST_USED,
2812                                error);
2813 }
2814
2815 static gboolean
2816 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
2817                                             const char  *content_type,
2818                                             GError     **error)
2819 {
2820   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2821
2822   if (!g_desktop_app_info_ensure_saved (info, error))
2823     return FALSE;
2824
2825   if (!info->desktop_id)
2826     {
2827       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2828                            _("Application information lacks an identifier"));
2829       return FALSE;
2830     }
2831
2832   return update_mimeapps_list (info->desktop_id, content_type,
2833                                UPDATE_MIME_SET_DEFAULT,
2834                                error);
2835 }
2836
2837 static void
2838 update_program_done (GPid     pid,
2839                      gint     status,
2840                      gpointer data)
2841 {
2842   /* Did the application exit correctly */
2843   if (g_spawn_check_exit_status (status, NULL))
2844     {
2845       /* Here we could clean out any caches in use */
2846     }
2847 }
2848
2849 static void
2850 run_update_command (char *command,
2851                     char *subdir)
2852 {
2853         char *argv[3] = {
2854                 NULL,
2855                 NULL,
2856                 NULL,
2857         };
2858         GPid pid = 0;
2859         GError *error = NULL;
2860
2861         argv[0] = command;
2862         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
2863
2864         if (g_spawn_async ("/", argv,
2865                            NULL,       /* envp */
2866                            G_SPAWN_SEARCH_PATH |
2867                            G_SPAWN_STDOUT_TO_DEV_NULL |
2868                            G_SPAWN_STDERR_TO_DEV_NULL |
2869                            G_SPAWN_DO_NOT_REAP_CHILD,
2870                            NULL, NULL, /* No setup function */
2871                            &pid,
2872                            &error))
2873           g_child_watch_add (pid, update_program_done, NULL);
2874         else
2875           {
2876             /* If we get an error at this point, it's quite likely the user doesn't
2877              * have an installed copy of either 'update-mime-database' or
2878              * 'update-desktop-database'.  I don't think we want to popup an error
2879              * dialog at this point, so we just do a g_warning to give the user a
2880              * chance of debugging it.
2881              */
2882             g_warning ("%s", error->message);
2883           }
2884
2885         g_free (argv[1]);
2886 }
2887
2888 static gboolean
2889 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
2890                                                  const char  *extension,
2891                                                  GError     **error)
2892 {
2893   char *filename, *basename, *mimetype;
2894   char *dirname;
2895   gboolean res;
2896
2897   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
2898     return FALSE;
2899
2900   dirname = ensure_dir (MIMETYPE_DIR, error);
2901   if (!dirname)
2902     return FALSE;
2903
2904   basename = g_strdup_printf ("user-extension-%s.xml", extension);
2905   filename = g_build_filename (dirname, basename, NULL);
2906   g_free (basename);
2907   g_free (dirname);
2908
2909   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
2910
2911   if (!g_file_test (filename, G_FILE_TEST_EXISTS))
2912     {
2913       char *contents;
2914
2915       contents =
2916         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2917                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
2918                          " <mime-type type=\"%s\">\n"
2919                          "  <comment>%s document</comment>\n"
2920                          "  <glob pattern=\"*.%s\"/>\n"
2921                          " </mime-type>\n"
2922                          "</mime-info>\n", mimetype, extension, extension);
2923
2924       g_file_set_contents (filename, contents, -1, NULL);
2925       g_free (contents);
2926
2927       run_update_command ("update-mime-database", "mime");
2928     }
2929   g_free (filename);
2930
2931   res = g_desktop_app_info_set_as_default_for_type (appinfo,
2932                                                     mimetype,
2933                                                     error);
2934
2935   g_free (mimetype);
2936
2937   return res;
2938 }
2939
2940 static gboolean
2941 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
2942                                       const char  *content_type,
2943                                       GError     **error)
2944 {
2945   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2946
2947   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2948     return FALSE;
2949
2950   return update_mimeapps_list (info->desktop_id, content_type,
2951                                UPDATE_MIME_SET_NON_DEFAULT,
2952                                error);
2953 }
2954
2955 static gboolean
2956 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
2957 {
2958   return TRUE;
2959 }
2960
2961 static gboolean
2962 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
2963                                          const char  *content_type,
2964                                          GError     **error)
2965 {
2966   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2967
2968   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2969     return FALSE;
2970
2971   return update_mimeapps_list (info->desktop_id, content_type,
2972                                UPDATE_MIME_REMOVE,
2973                                error);
2974 }
2975
2976 static const char **
2977 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
2978 {
2979   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2980
2981   return (const char**) info->mime_types;
2982 }
2983
2984 /* Saving and deleting {{{2 */
2985
2986 static gboolean
2987 g_desktop_app_info_ensure_saved (GDesktopAppInfo  *info,
2988                                  GError          **error)
2989 {
2990   GKeyFile *key_file;
2991   char *dirname;
2992   char *filename;
2993   char *data, *desktop_id;
2994   gsize data_size;
2995   int fd;
2996   gboolean res;
2997
2998   if (info->filename != NULL)
2999     return TRUE;
3000
3001   /* This is only used for object created with
3002    * g_app_info_create_from_commandline. All other
3003    * object should have a filename
3004    */
3005
3006   dirname = ensure_dir (APP_DIR, error);
3007   if (!dirname)
3008     return FALSE;
3009
3010   key_file = g_key_file_new ();
3011
3012   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3013                          "Encoding", "UTF-8");
3014   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3015                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
3016   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3017                          G_KEY_FILE_DESKTOP_KEY_TYPE,
3018                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3019   if (info->terminal)
3020     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3021                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3022   if (info->nodisplay)
3023     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3024                             G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3025
3026   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3027                          G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3028
3029   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3030                          G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3031
3032   if (info->generic_name != NULL)
3033     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3034                            GENERIC_NAME_KEY, info->generic_name);
3035
3036   if (info->fullname != NULL)
3037     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3038                            FULL_NAME_KEY, info->fullname);
3039
3040   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3041                          G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3042
3043   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3044                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3045
3046   data = g_key_file_to_data (key_file, &data_size, NULL);
3047   g_key_file_free (key_file);
3048
3049   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3050   filename = g_build_filename (dirname, desktop_id, NULL);
3051   g_free (desktop_id);
3052   g_free (dirname);
3053
3054   fd = g_mkstemp (filename);
3055   if (fd == -1)
3056     {
3057       char *display_name;
3058
3059       display_name = g_filename_display_name (filename);
3060       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3061                    _("Can't create user desktop file %s"), display_name);
3062       g_free (display_name);
3063       g_free (filename);
3064       g_free (data);
3065       return FALSE;
3066     }
3067
3068   desktop_id = g_path_get_basename (filename);
3069
3070   /* FIXME - actually handle error */
3071   (void) g_close (fd, NULL);
3072
3073   res = g_file_set_contents (filename, data, data_size, error);
3074   g_free (data);
3075   if (!res)
3076     {
3077       g_free (desktop_id);
3078       g_free (filename);
3079       return FALSE;
3080     }
3081
3082   info->filename = filename;
3083   info->desktop_id = desktop_id;
3084
3085   run_update_command ("update-desktop-database", "applications");
3086
3087   /* We just dropped a file in the user's desktop file directory.  Save
3088    * the monitor the bother of having to notice it and invalidate
3089    * immediately.
3090    *
3091    * This means that calls directly following this will be able to see
3092    * the results immediately.
3093    */
3094   desktop_file_dirs_invalidate_user ();
3095
3096   return TRUE;
3097 }
3098
3099 static gboolean
3100 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3101 {
3102   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3103
3104   if (info->filename)
3105     {
3106       if (strstr (info->filename, "/userapp-"))
3107         return g_access (info->filename, W_OK) == 0;
3108     }
3109
3110   return FALSE;
3111 }
3112
3113 static gboolean
3114 g_desktop_app_info_delete (GAppInfo *appinfo)
3115 {
3116   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3117
3118   if (info->filename)
3119     {
3120       if (g_remove (info->filename) == 0)
3121         {
3122           update_mimeapps_list (info->desktop_id, NULL,
3123                                 UPDATE_MIME_NONE,
3124                                 NULL);
3125
3126           g_free (info->filename);
3127           info->filename = NULL;
3128           g_free (info->desktop_id);
3129           info->desktop_id = NULL;
3130
3131           return TRUE;
3132         }
3133     }
3134
3135   return FALSE;
3136 }
3137
3138 /* Create for commandline {{{2 */
3139 /**
3140  * g_app_info_create_from_commandline:
3141  * @commandline: the commandline to use
3142  * @application_name: (allow-none): the application name, or %NULL to use @commandline
3143  * @flags: flags that can specify details of the created #GAppInfo
3144  * @error: a #GError location to store the error occurring, %NULL to ignore.
3145  *
3146  * Creates a new #GAppInfo from the given information.
3147  *
3148  * Note that for @commandline, the quoting rules of the Exec key of the
3149  * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
3150  * are applied. For example, if the @commandline contains
3151  * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
3152  * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
3153  *
3154  * Returns: (transfer full): new #GAppInfo for given command.
3155  **/
3156 GAppInfo *
3157 g_app_info_create_from_commandline (const char           *commandline,
3158                                     const char           *application_name,
3159                                     GAppInfoCreateFlags   flags,
3160                                     GError              **error)
3161 {
3162   char **split;
3163   char *basename;
3164   GDesktopAppInfo *info;
3165
3166   g_return_val_if_fail (commandline, NULL);
3167
3168   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
3169
3170   info->filename = NULL;
3171   info->desktop_id = NULL;
3172
3173   info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
3174   info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
3175   info->hidden = FALSE;
3176   if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
3177     info->exec = g_strconcat (commandline, " %u", NULL);
3178   else
3179     info->exec = g_strconcat (commandline, " %f", NULL);
3180   info->nodisplay = TRUE;
3181   info->binary = binary_from_exec (info->exec);
3182
3183   if (application_name)
3184     info->name = g_strdup (application_name);
3185   else
3186     {
3187       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
3188       split = g_strsplit (commandline, " ", 2);
3189       basename = split[0] ? g_path_get_basename (split[0]) : NULL;
3190       g_strfreev (split);
3191       info->name = basename;
3192       if (info->name == NULL)
3193         info->name = g_strdup ("custom");
3194     }
3195   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
3196
3197   return G_APP_INFO (info);
3198 }
3199
3200 /* GAppInfo interface init */
3201
3202 static void
3203 g_desktop_app_info_iface_init (GAppInfoIface *iface)
3204 {
3205   iface->dup = g_desktop_app_info_dup;
3206   iface->equal = g_desktop_app_info_equal;
3207   iface->get_id = g_desktop_app_info_get_id;
3208   iface->get_name = g_desktop_app_info_get_name;
3209   iface->get_description = g_desktop_app_info_get_description;
3210   iface->get_executable = g_desktop_app_info_get_executable;
3211   iface->get_icon = g_desktop_app_info_get_icon;
3212   iface->launch = g_desktop_app_info_launch;
3213   iface->supports_uris = g_desktop_app_info_supports_uris;
3214   iface->supports_files = g_desktop_app_info_supports_files;
3215   iface->launch_uris = g_desktop_app_info_launch_uris;
3216   iface->should_show = g_desktop_app_info_should_show;
3217   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
3218   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
3219   iface->add_supports_type = g_desktop_app_info_add_supports_type;
3220   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
3221   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
3222   iface->can_delete = g_desktop_app_info_can_delete;
3223   iface->do_delete = g_desktop_app_info_delete;
3224   iface->get_commandline = g_desktop_app_info_get_commandline;
3225   iface->get_display_name = g_desktop_app_info_get_display_name;
3226   iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
3227   iface->get_supported_types = g_desktop_app_info_get_supported_types;
3228 }
3229
3230 /* Recommended applications {{{2 */
3231
3232 static gboolean
3233 app_info_in_list (GAppInfo *info,
3234                   GList    *list)
3235 {
3236   while (list != NULL)
3237     {
3238       if (g_app_info_equal (info, list->data))
3239         return TRUE;
3240       list = list->next;
3241     }
3242   return FALSE;
3243 }
3244
3245 /**
3246  * g_app_info_get_recommended_for_type:
3247  * @content_type: the content type to find a #GAppInfo for
3248  *
3249  * Gets a list of recommended #GAppInfos for a given content type, i.e.
3250  * those applications which claim to support the given content type exactly,
3251  * and not by MIME type subclassing.
3252  * Note that the first application of the list is the last used one, i.e.
3253  * the last one for which g_app_info_set_as_last_used_for_type() has been
3254  * called.
3255  *
3256  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3257  *     for given @content_type or %NULL on error.
3258  *
3259  * Since: 2.28
3260  **/
3261 GList *
3262 g_app_info_get_recommended_for_type (const gchar *content_type)
3263 {
3264   GList *desktop_entries, *l;
3265   GList *infos;
3266   GDesktopAppInfo *info;
3267
3268   g_return_val_if_fail (content_type != NULL, NULL);
3269
3270   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, FALSE, NULL);
3271
3272   infos = NULL;
3273   for (l = desktop_entries; l != NULL; l = l->next)
3274     {
3275       char *desktop_entry = l->data;
3276
3277       info = g_desktop_app_info_new (desktop_entry);
3278       if (info)
3279         {
3280           if (app_info_in_list (G_APP_INFO (info), infos))
3281             g_object_unref (info);
3282           else
3283             infos = g_list_prepend (infos, info);
3284         }
3285       g_free (desktop_entry);
3286     }
3287
3288   g_list_free (desktop_entries);
3289
3290   return g_list_reverse (infos);
3291 }
3292
3293 /**
3294  * g_app_info_get_fallback_for_type:
3295  * @content_type: the content type to find a #GAppInfo for
3296  *
3297  * Gets a list of fallback #GAppInfos for a given content type, i.e.
3298  * those applications which claim to support the given content type
3299  * by MIME type subclassing and not directly.
3300  *
3301  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3302  *     for given @content_type or %NULL on error.
3303  *
3304  * Since: 2.28
3305  **/
3306 GList *
3307 g_app_info_get_fallback_for_type (const gchar *content_type)
3308 {
3309   GList *desktop_entries, *l;
3310   GList *infos, *recommended_infos;
3311   GDesktopAppInfo *info;
3312
3313   g_return_val_if_fail (content_type != NULL, NULL);
3314
3315   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, NULL);
3316   recommended_infos = g_app_info_get_recommended_for_type (content_type);
3317
3318   infos = NULL;
3319   for (l = desktop_entries; l != NULL; l = l->next)
3320     {
3321       char *desktop_entry = l->data;
3322
3323       info = g_desktop_app_info_new (desktop_entry);
3324       if (info)
3325         {
3326           if (app_info_in_list (G_APP_INFO (info), infos) ||
3327               app_info_in_list (G_APP_INFO (info), recommended_infos))
3328             g_object_unref (info);
3329           else
3330             infos = g_list_prepend (infos, info);
3331         }
3332       g_free (desktop_entry);
3333     }
3334
3335   g_list_free (desktop_entries);
3336   g_list_free_full (recommended_infos, g_object_unref);
3337
3338   return g_list_reverse (infos);
3339 }
3340
3341 /**
3342  * g_app_info_get_all_for_type:
3343  * @content_type: the content type to find a #GAppInfo for
3344  *
3345  * Gets a list of all #GAppInfos for a given content type,
3346  * including the recommended and fallback #GAppInfos. See
3347  * g_app_info_get_recommended_for_type() and
3348  * g_app_info_get_fallback_for_type().
3349  *
3350  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3351  *     for given @content_type or %NULL on error.
3352  **/
3353 GList *
3354 g_app_info_get_all_for_type (const char *content_type)
3355 {
3356   GList *desktop_entries, *l;
3357   GList *infos;
3358   char *user_default = NULL;
3359   GDesktopAppInfo *info;
3360
3361   g_return_val_if_fail (content_type != NULL, NULL);
3362
3363   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3364   infos = NULL;
3365
3366   /* put the user default in front of the list, for compatibility */
3367   if (user_default != NULL)
3368     {
3369       info = g_desktop_app_info_new (user_default);
3370
3371       if (info != NULL)
3372         infos = g_list_prepend (infos, info);
3373     }
3374
3375   g_free (user_default);
3376
3377   for (l = desktop_entries; l != NULL; l = l->next)
3378     {
3379       char *desktop_entry = l->data;
3380
3381       info = g_desktop_app_info_new (desktop_entry);
3382       if (info)
3383         {
3384           if (app_info_in_list (G_APP_INFO (info), infos))
3385             g_object_unref (info);
3386           else
3387             infos = g_list_prepend (infos, info);
3388         }
3389       g_free (desktop_entry);
3390     }
3391
3392   g_list_free (desktop_entries);
3393
3394   return g_list_reverse (infos);
3395 }
3396
3397 /**
3398  * g_app_info_reset_type_associations:
3399  * @content_type: a content type
3400  *
3401  * Removes all changes to the type associations done by
3402  * g_app_info_set_as_default_for_type(),
3403  * g_app_info_set_as_default_for_extension(),
3404  * g_app_info_add_supports_type() or
3405  * g_app_info_remove_supports_type().
3406  *
3407  * Since: 2.20
3408  */
3409 void
3410 g_app_info_reset_type_associations (const char *content_type)
3411 {
3412   update_mimeapps_list (NULL, content_type,
3413                         UPDATE_MIME_NONE,
3414                         NULL);
3415 }
3416
3417 /**
3418  * g_app_info_get_default_for_type:
3419  * @content_type: the content type to find a #GAppInfo for
3420  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
3421  *     support URIs
3422  *
3423  * Gets the default #GAppInfo for a given content type.
3424  *
3425  * Returns: (transfer full): #GAppInfo for given @content_type or
3426  *     %NULL on error.
3427  */
3428 GAppInfo *
3429 g_app_info_get_default_for_type (const char *content_type,
3430                                  gboolean    must_support_uris)
3431 {
3432   GList *desktop_entries, *l;
3433   char *user_default = NULL;
3434   GAppInfo *info;
3435
3436   g_return_val_if_fail (content_type != NULL, NULL);
3437
3438   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3439
3440   info = NULL;
3441
3442   if (user_default != NULL)
3443     {
3444       info = (GAppInfo *) g_desktop_app_info_new (user_default);
3445
3446       if (info)
3447         {
3448           if (must_support_uris && !g_app_info_supports_uris (info))
3449             {
3450               g_object_unref (info);
3451               info = NULL;
3452             }
3453         }
3454     }
3455
3456   g_free (user_default);
3457
3458   if (info != NULL)
3459     {
3460       g_list_free_full (desktop_entries, g_free);
3461       return info;
3462     }
3463
3464   /* pick the first from the other list that matches our URI
3465    * requirements.
3466    */
3467   for (l = desktop_entries; l != NULL; l = l->next)
3468     {
3469       char *desktop_entry = l->data;
3470
3471       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
3472       if (info)
3473         {
3474           if (must_support_uris && !g_app_info_supports_uris (info))
3475             {
3476               g_object_unref (info);
3477               info = NULL;
3478             }
3479           else
3480             break;
3481         }
3482     }
3483
3484   g_list_free_full (desktop_entries, g_free);
3485
3486   return info;
3487 }
3488
3489 /**
3490  * g_app_info_get_default_for_uri_scheme:
3491  * @uri_scheme: a string containing a URI scheme.
3492  *
3493  * Gets the default application for handling URIs with
3494  * the given URI scheme. A URI scheme is the initial part
3495  * of the URI, up to but not including the ':', e.g. "http",
3496  * "ftp" or "sip".
3497  *
3498  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
3499  */
3500 GAppInfo *
3501 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
3502 {
3503   GAppInfo *app_info;
3504   char *content_type, *scheme_down;
3505
3506   scheme_down = g_ascii_strdown (uri_scheme, -1);
3507   content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
3508   g_free (scheme_down);
3509   app_info = g_app_info_get_default_for_type (content_type, FALSE);
3510   g_free (content_type);
3511
3512   return app_info;
3513 }
3514
3515 /* "Get all" API {{{2 */
3516
3517 /**
3518  * g_desktop_app_info_search:
3519  * @search_string: the search string to use
3520  *
3521  * Searches desktop files for ones that match @search_string.
3522  *
3523  * The return value is an array of strvs.  Each strv contains a list of
3524  * applications that matched @search_string with an equal score.  The
3525  * outer list is sorted by score so that the first strv contains the
3526  * best-matching applications, and so on.
3527  * The algorithm for determining matches is undefined and may change at
3528  * any time.
3529  *
3530  * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
3531  *   list of strvs.  Free each item with g_strfreev() and free the outer
3532  *   list with g_free().
3533  */
3534 gchar ***
3535 g_desktop_app_info_search (const gchar *search_string)
3536 {
3537   gchar **search_tokens;
3538   gint last_category = -1;
3539   gchar ***results;
3540   gint n_categories = 0;
3541   gint start_of_category;
3542   gint i, j;
3543
3544   search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
3545
3546   desktop_file_dirs_lock ();
3547
3548   reset_total_search_results ();
3549
3550   for (i = 0; i < n_desktop_file_dirs; i++)
3551     {
3552       for (j = 0; search_tokens[j]; j++)
3553         {
3554           desktop_file_dir_search (&desktop_file_dirs[i], search_tokens[j]);
3555           merge_token_results (j == 0);
3556         }
3557       merge_directory_results ();
3558     }
3559
3560   sort_total_search_results ();
3561
3562   /* Count the total number of unique categories */
3563   for (i = 0; i < static_total_results_size; i++)
3564     if (static_total_results[i].category != last_category)
3565       {
3566         last_category = static_total_results[i].category;
3567         n_categories++;
3568       }
3569
3570   results = g_new (gchar **, n_categories + 1);
3571
3572   /* Start loading into the results list */
3573   start_of_category = 0;
3574   for (i = 0; i < n_categories; i++)
3575     {
3576       gint n_items_in_category = 0;
3577       gint this_category;
3578       gint j;
3579
3580       this_category = static_total_results[start_of_category].category;
3581
3582       while (start_of_category + n_items_in_category < static_total_results_size &&
3583              static_total_results[start_of_category + n_items_in_category].category == this_category)
3584         n_items_in_category++;
3585
3586       results[i] = g_new (gchar *, n_items_in_category + 1);
3587       for (j = 0; j < n_items_in_category; j++)
3588         results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
3589       results[i][j] = NULL;
3590
3591       start_of_category += n_items_in_category;
3592     }
3593   results[i] = NULL;
3594
3595   desktop_file_dirs_unlock ();
3596
3597   g_strfreev (search_tokens);
3598
3599   return results;
3600 }
3601
3602 /**
3603  * g_app_info_get_all:
3604  *
3605  * Gets a list of all of the applications currently registered
3606  * on this system.
3607  *
3608  * For desktop files, this includes applications that have
3609  * `NoDisplay=true` set or are excluded from display by means
3610  * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
3611  * The returned list does not include applications which have
3612  * the `Hidden` key set.
3613  *
3614  * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
3615  **/
3616 GList *
3617 g_app_info_get_all (void)
3618 {
3619   GHashTable *apps;
3620   GHashTableIter iter;
3621   gpointer value;
3622   int i;
3623   GList *infos;
3624
3625   apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
3626
3627   desktop_file_dirs_lock ();
3628
3629   for (i = 0; i < n_desktop_file_dirs; i++)
3630     desktop_file_dir_get_all (&desktop_file_dirs[i], apps);
3631
3632   desktop_file_dirs_unlock ();
3633
3634   infos = NULL;
3635   g_hash_table_iter_init (&iter, apps);
3636   while (g_hash_table_iter_next (&iter, NULL, &value))
3637     {
3638       if (value)
3639         infos = g_list_prepend (infos, value);
3640     }
3641
3642   g_hash_table_destroy (apps);
3643
3644   return infos;
3645 }
3646
3647 /* Caching of mimeinfo.cache and defaults.list files {{{2 */
3648
3649 typedef struct {
3650   char *path;
3651   GHashTable *mime_info_cache_map;
3652   GHashTable *defaults_list_map;
3653   GHashTable *mimeapps_list_added_map;
3654   GHashTable *mimeapps_list_removed_map;
3655   GHashTable *mimeapps_list_defaults_map;
3656   time_t mime_info_cache_timestamp;
3657   time_t defaults_list_timestamp;
3658   time_t mimeapps_list_timestamp;
3659 } MimeInfoCacheDir;
3660
3661 typedef struct {
3662   GList *dirs;                       /* mimeinfo.cache and defaults.list */
3663   time_t last_stat_time;
3664 } MimeInfoCache;
3665
3666 static MimeInfoCache *mime_info_cache = NULL;
3667 G_LOCK_DEFINE_STATIC (mime_info_cache);
3668
3669 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
3670                                                      const char        *mime_type,
3671                                                      char             **new_desktop_file_ids);
3672
3673 static MimeInfoCache * mime_info_cache_new (void);
3674
3675 static void
3676 destroy_info_cache_value (gpointer  key,
3677                           GList    *value,
3678                           gpointer  data)
3679 {
3680   g_list_free_full (value, g_free);
3681 }
3682
3683 static void
3684 destroy_info_cache_map (GHashTable *info_cache_map)
3685 {
3686   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
3687   g_hash_table_destroy (info_cache_map);
3688 }
3689
3690 static gboolean
3691 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
3692                                  const char       *cache_file,
3693                                  time_t           *timestamp)
3694 {
3695   struct stat buf;
3696   char *filename;
3697
3698   filename = g_build_filename (dir->path, cache_file, NULL);
3699
3700   if (g_stat (filename, &buf) < 0)
3701     {
3702       g_free (filename);
3703       return TRUE;
3704     }
3705   g_free (filename);
3706
3707   if (buf.st_mtime != *timestamp)
3708     return TRUE;
3709
3710   return FALSE;
3711 }
3712
3713 /* Call with lock held */
3714 static void
3715 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
3716 {
3717   GError *load_error;
3718   GKeyFile *key_file;
3719   gchar *filename, **mime_types;
3720   int i;
3721   struct stat buf;
3722
3723   load_error = NULL;
3724   mime_types = NULL;
3725
3726   if (dir->mime_info_cache_map != NULL &&
3727       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
3728                                         &dir->mime_info_cache_timestamp))
3729     return;
3730
3731   if (dir->mime_info_cache_map != NULL)
3732     destroy_info_cache_map (dir->mime_info_cache_map);
3733
3734   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3735                                                     (GDestroyNotify) g_free,
3736                                                     NULL);
3737
3738   key_file = g_key_file_new ();
3739
3740   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
3741
3742   if (g_stat (filename, &buf) < 0)
3743     goto error;
3744
3745   dir->mime_info_cache_timestamp = buf.st_mtime;
3746
3747   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3748
3749   g_free (filename);
3750   filename = NULL;
3751
3752   if (load_error != NULL)
3753     goto error;
3754
3755   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
3756                                     NULL, &load_error);
3757
3758   if (load_error != NULL)
3759     goto error;
3760
3761   for (i = 0; mime_types[i] != NULL; i++)
3762     {
3763       gchar **desktop_file_ids;
3764       char *unaliased_type;
3765       desktop_file_ids = g_key_file_get_string_list (key_file,
3766                                                      MIME_CACHE_GROUP,
3767                                                      mime_types[i],
3768                                                      NULL,
3769                                                      NULL);
3770
3771       if (desktop_file_ids == NULL)
3772         continue;
3773
3774       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3775       mime_info_cache_dir_add_desktop_entries (dir,
3776                                                unaliased_type,
3777                                                desktop_file_ids);
3778       g_free (unaliased_type);
3779
3780       g_strfreev (desktop_file_ids);
3781     }
3782
3783   g_strfreev (mime_types);
3784   g_key_file_free (key_file);
3785
3786   return;
3787  error:
3788   g_free (filename);
3789   g_key_file_free (key_file);
3790
3791   if (mime_types != NULL)
3792     g_strfreev (mime_types);
3793
3794   if (load_error)
3795     g_error_free (load_error);
3796 }
3797
3798 static void
3799 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
3800 {
3801   GKeyFile *key_file;
3802   GError *load_error;
3803   gchar *filename, **mime_types;
3804   char *unaliased_type;
3805   char **desktop_file_ids;
3806   int i;
3807   struct stat buf;
3808
3809   load_error = NULL;
3810   mime_types = NULL;
3811
3812   if (dir->defaults_list_map != NULL &&
3813       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
3814                                         &dir->defaults_list_timestamp))
3815     return;
3816
3817   if (dir->defaults_list_map != NULL)
3818     g_hash_table_destroy (dir->defaults_list_map);
3819   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3820                                                   g_free, (GDestroyNotify)g_strfreev);
3821
3822
3823   key_file = g_key_file_new ();
3824
3825   filename = g_build_filename (dir->path, "defaults.list", NULL);
3826   if (g_stat (filename, &buf) < 0)
3827     goto error;
3828
3829   dir->defaults_list_timestamp = buf.st_mtime;
3830
3831   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3832   g_free (filename);
3833   filename = NULL;
3834
3835   if (load_error != NULL)
3836     goto error;
3837
3838   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3839                                     NULL, NULL);
3840   if (mime_types != NULL)
3841     {
3842       for (i = 0; mime_types[i] != NULL; i++)
3843         {
3844           desktop_file_ids = g_key_file_get_string_list (key_file,
3845                                                          DEFAULT_APPLICATIONS_GROUP,
3846                                                          mime_types[i],
3847                                                          NULL,
3848                                                          NULL);
3849           if (desktop_file_ids == NULL)
3850             continue;
3851
3852           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3853           g_hash_table_replace (dir->defaults_list_map,
3854                                 unaliased_type,
3855                                 desktop_file_ids);
3856         }
3857
3858       g_strfreev (mime_types);
3859     }
3860
3861   g_key_file_free (key_file);
3862   return;
3863
3864  error:
3865   g_free (filename);
3866   g_key_file_free (key_file);
3867
3868   if (mime_types != NULL)
3869     g_strfreev (mime_types);
3870
3871   if (load_error)
3872     g_error_free (load_error);
3873 }
3874
3875 static void
3876 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
3877 {
3878   GKeyFile *key_file;
3879   GError *load_error;
3880   gchar *filename, **mime_types;
3881   char *unaliased_type;
3882   char **desktop_file_ids;
3883   char *desktop_id;
3884   int i;
3885   struct stat buf;
3886
3887   load_error = NULL;
3888   mime_types = NULL;
3889
3890   if (dir->mimeapps_list_added_map != NULL &&
3891       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
3892                                         &dir->mimeapps_list_timestamp))
3893     return;
3894
3895   if (dir->mimeapps_list_added_map != NULL)
3896     g_hash_table_destroy (dir->mimeapps_list_added_map);
3897   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3898                                                         g_free, (GDestroyNotify)g_strfreev);
3899
3900   if (dir->mimeapps_list_removed_map != NULL)
3901     g_hash_table_destroy (dir->mimeapps_list_removed_map);
3902   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3903                                                           g_free, (GDestroyNotify)g_strfreev);
3904
3905   if (dir->mimeapps_list_defaults_map != NULL)
3906     g_hash_table_destroy (dir->mimeapps_list_defaults_map);
3907   dir->mimeapps_list_defaults_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3908                                                            g_free, g_free);
3909
3910   key_file = g_key_file_new ();
3911
3912   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
3913   if (g_stat (filename, &buf) < 0)
3914     goto error;
3915
3916   dir->mimeapps_list_timestamp = buf.st_mtime;
3917
3918   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3919   g_free (filename);
3920   filename = NULL;
3921
3922   if (load_error != NULL)
3923     goto error;
3924
3925   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
3926                                     NULL, NULL);
3927   if (mime_types != NULL)
3928     {
3929       for (i = 0; mime_types[i] != NULL; i++)
3930         {
3931           desktop_file_ids = g_key_file_get_string_list (key_file,
3932                                                          ADDED_ASSOCIATIONS_GROUP,
3933                                                          mime_types[i],
3934                                                          NULL,
3935                                                          NULL);
3936           if (desktop_file_ids == NULL)
3937             continue;
3938
3939           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3940           g_hash_table_replace (dir->mimeapps_list_added_map,
3941                                 unaliased_type,
3942                                 desktop_file_ids);
3943         }
3944
3945       g_strfreev (mime_types);
3946     }
3947
3948   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
3949                                     NULL, NULL);
3950   if (mime_types != NULL)
3951     {
3952       for (i = 0; mime_types[i] != NULL; i++)
3953         {
3954           desktop_file_ids = g_key_file_get_string_list (key_file,
3955                                                          REMOVED_ASSOCIATIONS_GROUP,
3956                                                          mime_types[i],
3957                                                          NULL,
3958                                                          NULL);
3959           if (desktop_file_ids == NULL)
3960             continue;
3961
3962           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3963           g_hash_table_replace (dir->mimeapps_list_removed_map,
3964                                 unaliased_type,
3965                                 desktop_file_ids);
3966         }
3967
3968       g_strfreev (mime_types);
3969     }
3970
3971   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3972                                     NULL, NULL);
3973   if (mime_types != NULL)
3974     {
3975       for (i = 0; mime_types[i] != NULL; i++)
3976         {
3977           desktop_id = g_key_file_get_string (key_file,
3978                                               DEFAULT_APPLICATIONS_GROUP,
3979                                               mime_types[i],
3980                                               NULL);
3981           if (desktop_id == NULL)
3982             continue;
3983
3984           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3985           g_hash_table_replace (dir->mimeapps_list_defaults_map,
3986                                 unaliased_type,
3987                                 desktop_id);
3988         }
3989
3990       g_strfreev (mime_types);
3991     }
3992
3993   g_key_file_free (key_file);
3994   return;
3995
3996  error:
3997   g_free (filename);
3998   g_key_file_free (key_file);
3999
4000   if (mime_types != NULL)
4001     g_strfreev (mime_types);
4002
4003   if (load_error)
4004     g_error_free (load_error);
4005 }
4006
4007 static MimeInfoCacheDir *
4008 mime_info_cache_dir_new (const char *path)
4009 {
4010   MimeInfoCacheDir *dir;
4011
4012   dir = g_new0 (MimeInfoCacheDir, 1);
4013   dir->path = g_strdup (path);
4014
4015   return dir;
4016 }
4017
4018 static void
4019 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
4020 {
4021   if (dir == NULL)
4022     return;
4023
4024   if (dir->mime_info_cache_map != NULL)
4025     {
4026       destroy_info_cache_map (dir->mime_info_cache_map);
4027       dir->mime_info_cache_map = NULL;
4028
4029   }
4030
4031   if (dir->defaults_list_map != NULL)
4032     {
4033       g_hash_table_destroy (dir->defaults_list_map);
4034       dir->defaults_list_map = NULL;
4035     }
4036
4037   if (dir->mimeapps_list_added_map != NULL)
4038     {
4039       g_hash_table_destroy (dir->mimeapps_list_added_map);
4040       dir->mimeapps_list_added_map = NULL;
4041     }
4042
4043   if (dir->mimeapps_list_removed_map != NULL)
4044     {
4045       g_hash_table_destroy (dir->mimeapps_list_removed_map);
4046       dir->mimeapps_list_removed_map = NULL;
4047     }
4048
4049   if (dir->mimeapps_list_defaults_map != NULL)
4050     {
4051       g_hash_table_destroy (dir->mimeapps_list_defaults_map);
4052       dir->mimeapps_list_defaults_map = NULL;
4053     }
4054
4055   g_free (dir);
4056 }
4057
4058 static void
4059 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
4060                                          const char        *mime_type,
4061                                          char             **new_desktop_file_ids)
4062 {
4063   GList *desktop_file_ids;
4064   int i;
4065
4066   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
4067                                           mime_type);
4068
4069   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
4070     {
4071       if (!g_list_find_custom (desktop_file_ids, new_desktop_file_ids[i], (GCompareFunc) strcmp))
4072         desktop_file_ids = g_list_append (desktop_file_ids,
4073                                           g_strdup (new_desktop_file_ids[i]));
4074     }
4075
4076   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
4077 }
4078
4079 static void
4080 mime_info_cache_init_dir_lists (void)
4081 {
4082   int i;
4083
4084   mime_info_cache = mime_info_cache_new ();
4085
4086   desktop_file_dirs_refresh ();
4087
4088   for (i = 0; i < n_desktop_file_dirs; i++)
4089     {
4090       MimeInfoCacheDir *dir;
4091
4092       dir = mime_info_cache_dir_new (desktop_file_dirs[i].path);
4093
4094       if (dir != NULL)
4095         {
4096           mime_info_cache_dir_init (dir);
4097           mime_info_cache_dir_init_defaults_list (dir);
4098           mime_info_cache_dir_init_mimeapps_list (dir);
4099
4100           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
4101         }
4102     }
4103 }
4104
4105 static void
4106 mime_info_cache_update_dir_lists (void)
4107 {
4108   GList *tmp;
4109
4110   tmp = mime_info_cache->dirs;
4111
4112   while (tmp != NULL)
4113     {
4114       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
4115
4116       /* No need to do this if we had file monitors... */
4117       mime_info_cache_dir_init (dir);
4118       mime_info_cache_dir_init_defaults_list (dir);
4119       mime_info_cache_dir_init_mimeapps_list (dir);
4120
4121       tmp = tmp->next;
4122     }
4123 }
4124
4125 static void
4126 mime_info_cache_init (void)
4127 {
4128   G_LOCK (mime_info_cache);
4129   if (mime_info_cache == NULL)
4130     mime_info_cache_init_dir_lists ();
4131   else
4132     {
4133       time_t now;
4134
4135       time (&now);
4136       if (now >= mime_info_cache->last_stat_time + 10)
4137         {
4138           mime_info_cache_update_dir_lists ();
4139           mime_info_cache->last_stat_time = now;
4140         }
4141     }
4142
4143   G_UNLOCK (mime_info_cache);
4144 }
4145
4146 static MimeInfoCache *
4147 mime_info_cache_new (void)
4148 {
4149   MimeInfoCache *cache;
4150
4151   cache = g_new0 (MimeInfoCache, 1);
4152
4153   return cache;
4154 }
4155
4156 static void
4157 mime_info_cache_free (MimeInfoCache *cache)
4158 {
4159   if (cache == NULL)
4160     return;
4161
4162   g_list_free_full (cache->dirs, (GDestroyNotify) mime_info_cache_dir_free);
4163   g_free (cache);
4164 }
4165
4166 /**
4167  * mime_info_cache_reload:
4168  * @dir: directory path which needs reloading.
4169  *
4170  * Reload the mime information for the @dir.
4171  */
4172 static void
4173 mime_info_cache_reload (const char *dir)
4174 {
4175   /* FIXME: just reload the dir that needs reloading,
4176    * don't blow the whole cache
4177    */
4178   if (mime_info_cache != NULL)
4179     {
4180       G_LOCK (mime_info_cache);
4181       mime_info_cache_free (mime_info_cache);
4182       mime_info_cache = NULL;
4183       G_UNLOCK (mime_info_cache);
4184     }
4185 }
4186
4187 static GList *
4188 append_desktop_entry (GList      *list,
4189                       const char *desktop_entry,
4190                       GList      *removed_entries)
4191 {
4192   /* Add if not already in list, and valid */
4193   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
4194       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
4195     list = g_list_prepend (list, g_strdup (desktop_entry));
4196
4197   return list;
4198 }
4199
4200 /**
4201  * get_all_desktop_entries_for_mime_type:
4202  * @mime_type: a mime type.
4203  * @except: NULL or a strv list
4204  *
4205  * Returns all the desktop ids for @mime_type. The desktop files
4206  * are listed in an order so that default applications are listed before
4207  * non-default ones, and handlers for inherited mimetypes are listed
4208  * after the base ones.
4209  *
4210  * Optionally doesn't list the desktop ids given in the @except
4211  *
4212  * Returns: a #GList containing the desktop ids which claim
4213  *    to handle @mime_type.
4214  */
4215 static GList *
4216 get_all_desktop_entries_for_mime_type (const char  *base_mime_type,
4217                                        const char **except,
4218                                        gboolean     include_fallback,
4219                                        char       **explicit_default)
4220 {
4221   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
4222   MimeInfoCacheDir *dir;
4223   char *mime_type, *default_entry = NULL;
4224   char *old_default_entry = NULL;
4225   const char *entry;
4226   char **mime_types;
4227   char **default_entries;
4228   char **removed_associations;
4229   gboolean already_found_handler;
4230   int i, j, k;
4231   GPtrArray *array;
4232   char **anc;
4233
4234   mime_info_cache_init ();
4235
4236   if (include_fallback)
4237     {
4238       /* collect all ancestors */
4239       mime_types = _g_unix_content_type_get_parents (base_mime_type);
4240       array = g_ptr_array_new ();
4241       for (i = 0; mime_types[i]; i++)
4242         g_ptr_array_add (array, mime_types[i]);
4243       g_free (mime_types);
4244       for (i = 0; i < array->len; i++)
4245         {
4246           anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4247           for (j = 0; anc[j]; j++)
4248             {
4249               for (k = 0; k < array->len; k++)
4250                 {
4251                   if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
4252                     break;
4253                 }
4254               if (k == array->len) /* not found */
4255                 g_ptr_array_add (array, g_strdup (anc[j]));
4256             }
4257           g_strfreev (anc);
4258         }
4259       g_ptr_array_add (array, NULL);
4260       mime_types = (char **)g_ptr_array_free (array, FALSE);
4261     }
4262   else
4263     {
4264       mime_types = g_malloc0 (2 * sizeof (gchar *));
4265       mime_types[0] = g_strdup (base_mime_type);
4266       mime_types[1] = NULL;
4267     }
4268
4269   G_LOCK (mime_info_cache);
4270
4271   removed_entries = NULL;
4272   desktop_entries = NULL;
4273
4274   for (i = 0; except != NULL && except[i] != NULL; i++)
4275     removed_entries = g_list_prepend (removed_entries, g_strdup (except[i]));
4276
4277   for (i = 0; mime_types[i] != NULL; i++)
4278     {
4279       mime_type = mime_types[i];
4280
4281       /* This is true if we already found a handler for a more specific
4282          mimetype. If its set we ignore any defaults for the less specific
4283          mimetypes. */
4284       already_found_handler = (desktop_entries != NULL);
4285
4286       /* Go through all apps listed in user and system dirs */
4287       for (dir_list = mime_info_cache->dirs;
4288            dir_list != NULL;
4289            dir_list = dir_list->next)
4290         {
4291           dir = dir_list->data;
4292
4293           /* Pick the explicit default application if we got no result earlier
4294            * (ie, for more specific mime types)
4295            */
4296           if (!already_found_handler)
4297             {
4298               entry = g_hash_table_lookup (dir->mimeapps_list_defaults_map, mime_type);
4299
4300               if (entry != NULL)
4301                 {
4302                   /* Save the default entry if it's the first one we encounter */
4303                   if (default_entry == NULL)
4304                     default_entry = g_strdup (entry);
4305                 }
4306             }
4307
4308           /* Then added associations from mimeapps.list */
4309           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
4310           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4311             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4312
4313           /* Then removed associations from mimeapps.list */
4314           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
4315           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
4316             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
4317
4318           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
4319           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
4320           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4321             {
4322               if (default_entry == NULL && old_default_entry == NULL && !already_found_handler)
4323                 old_default_entry = g_strdup (default_entries[j]);
4324
4325               desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4326             }
4327         }
4328
4329       /* Go through all entries that support the mimetype */
4330       for (dir_list = mime_info_cache->dirs;
4331            dir_list != NULL;
4332            dir_list = dir_list->next)
4333         {
4334           dir = dir_list->data;
4335
4336           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
4337           for (tmp = list; tmp != NULL; tmp = tmp->next)
4338             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
4339         }
4340     }
4341
4342   G_UNLOCK (mime_info_cache);
4343
4344   g_strfreev (mime_types);
4345
4346   /* If we have no default from mimeapps.list, take it from
4347    * defaults.list intead.
4348    *
4349    * If we do have a default from mimeapps.list, free any one that came
4350    * from defaults.list.
4351    */
4352   if (default_entry == NULL)
4353     default_entry = old_default_entry;
4354   else
4355     g_free (old_default_entry);
4356
4357   if (explicit_default != NULL)
4358     *explicit_default = default_entry;
4359   else
4360     g_free (default_entry);
4361
4362   g_list_free_full (removed_entries, g_free);
4363
4364   desktop_entries = g_list_reverse (desktop_entries);
4365
4366   return desktop_entries;
4367 }
4368
4369 /* GDesktopAppInfoLookup interface {{{2 */
4370
4371 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4372
4373 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4374 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4375
4376 static void
4377 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4378 {
4379 }
4380
4381 /* "Get for mime type" APIs {{{2 */
4382
4383 /**
4384  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4385  * @lookup: a #GDesktopAppInfoLookup
4386  * @uri_scheme: a string containing a URI scheme.
4387  *
4388  * Gets the default application for launching applications
4389  * using this URI scheme for a particular GDesktopAppInfoLookup
4390  * implementation.
4391  *
4392  * The GDesktopAppInfoLookup interface and this function is used
4393  * to implement g_app_info_get_default_for_uri_scheme() backends
4394  * in a GIO module. There is no reason for applications to use it
4395  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4396  *
4397  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4398  *
4399  * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
4400  */
4401 GAppInfo *
4402 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4403                                                       const char            *uri_scheme)
4404 {
4405   GDesktopAppInfoLookupIface *iface;
4406
4407   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4408
4409   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4410
4411   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4412 }
4413
4414 G_GNUC_END_IGNORE_DEPRECATIONS
4415
4416 /* Misc getter APIs {{{2 */
4417
4418 /**
4419  * g_desktop_app_info_get_startup_wm_class:
4420  * @info: a #GDesktopAppInfo that supports startup notify
4421  *
4422  * Retrieves the StartupWMClass field from @info. This represents the
4423  * WM_CLASS property of the main window of the application, if launched
4424  * through @info.
4425  *
4426  * Returns: (transfer none): the startup WM class, or %NULL if none is set
4427  * in the desktop file.
4428  *
4429  * Since: 2.34
4430  */
4431 const char *
4432 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4433 {
4434   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4435
4436   return info->startup_wm_class;
4437 }
4438
4439 /**
4440  * g_desktop_app_info_get_string:
4441  * @info: a #GDesktopAppInfo
4442  * @key: the key to look up
4443  *
4444  * Looks up a string value in the keyfile backing @info.
4445  *
4446  * The @key is looked up in the "Desktop Entry" group.
4447  *
4448  * Returns: a newly allocated string, or %NULL if the key
4449  *     is not found
4450  *
4451  * Since: 2.36
4452  */
4453 char *
4454 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4455                                const char      *key)
4456 {
4457   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4458
4459   return g_key_file_get_string (info->keyfile,
4460                                 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4461 }
4462
4463 /**
4464  * g_desktop_app_info_get_boolean:
4465  * @info: a #GDesktopAppInfo
4466  * @key: the key to look up
4467  *
4468  * Looks up a boolean value in the keyfile backing @info.
4469  *
4470  * The @key is looked up in the "Desktop Entry" group.
4471  *
4472  * Returns: the boolean value, or %FALSE if the key
4473  *     is not found
4474  *
4475  * Since: 2.36
4476  */
4477 gboolean
4478 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4479                                 const char      *key)
4480 {
4481   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4482
4483   return g_key_file_get_boolean (info->keyfile,
4484                                  G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4485 }
4486
4487 /**
4488  * g_desktop_app_info_has_key:
4489  * @info: a #GDesktopAppInfo
4490  * @key: the key to look up
4491  *
4492  * Returns whether @key exists in the "Desktop Entry" group
4493  * of the keyfile backing @info.
4494  *
4495  * Returns: %TRUE if the @key exists
4496  *
4497  * Since: 2.36
4498  */
4499 gboolean
4500 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4501                             const char      *key)
4502 {
4503   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4504
4505   return g_key_file_has_key (info->keyfile,
4506                              G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4507 }
4508
4509 /* Desktop actions support {{{2 */
4510
4511 /**
4512  * g_desktop_app_info_list_actions:
4513  * @info: a #GDesktopAppInfo
4514  *
4515  * Returns the list of "additional application actions" supported on the
4516  * desktop file, as per the desktop file specification.
4517  *
4518  * As per the specification, this is the list of actions that are
4519  * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4520  *
4521  * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4522  *
4523  * Since: 2.38
4524  **/
4525 const gchar * const *
4526 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4527 {
4528   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4529
4530   return (const gchar **) info->actions;
4531 }
4532
4533 static gboolean
4534 app_info_has_action (GDesktopAppInfo *info,
4535                      const gchar     *action_name)
4536 {
4537   gint i;
4538
4539   for (i = 0; info->actions[i]; i++)
4540     if (g_str_equal (info->actions[i], action_name))
4541       return TRUE;
4542
4543   return FALSE;
4544 }
4545
4546 /**
4547  * g_desktop_app_info_get_action_name:
4548  * @info: a #GDesktopAppInfo
4549  * @action_name: the name of the action as from
4550  *   g_desktop_app_info_list_actions()
4551  *
4552  * Gets the user-visible display name of the "additional application
4553  * action" specified by @action_name.
4554  *
4555  * This corresponds to the "Name" key within the keyfile group for the
4556  * action.
4557  *
4558  * Returns: (transfer full): the locale-specific action name
4559  *
4560  * Since: 2.38
4561  */
4562 gchar *
4563 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4564                                     const gchar     *action_name)
4565 {
4566   gchar *group_name;
4567   gchar *result;
4568
4569   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4570   g_return_val_if_fail (action_name != NULL, NULL);
4571   g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4572
4573   group_name = g_strdup_printf ("Desktop Action %s", action_name);
4574   result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4575   g_free (group_name);
4576
4577   /* The spec says that the Name field must be given.
4578    *
4579    * If it's not, let's follow the behaviour of our get_name()
4580    * implementation above and never return %NULL.
4581    */
4582   if (result == NULL)
4583     result = g_strdup (_("Unnamed"));
4584
4585   return result;
4586 }
4587
4588 /**
4589  * g_desktop_app_info_launch_action:
4590  * @info: a #GDesktopAppInfo
4591  * @action_name: the name of the action as from
4592  *   g_desktop_app_info_list_actions()
4593  * @launch_context: (allow-none): a #GAppLaunchContext
4594  *
4595  * Activates the named application action.
4596  *
4597  * You may only call this function on action names that were
4598  * returned from g_desktop_app_info_list_actions().
4599  *
4600  * Note that if the main entry of the desktop file indicates that the
4601  * application supports startup notification, and @launch_context is
4602  * non-%NULL, then startup notification will be used when activating the
4603  * action (and as such, invocation of the action on the receiving side
4604  * must signal the end of startup notification when it is completed).
4605  * This is the expected behaviour of applications declaring additional
4606  * actions, as per the desktop file specification.
4607  *
4608  * As with g_app_info_launch() there is no way to detect failures that
4609  * occur while using this function.
4610  *
4611  * Since: 2.38
4612  */
4613 void
4614 g_desktop_app_info_launch_action (GDesktopAppInfo   *info,
4615                                   const gchar       *action_name,
4616                                   GAppLaunchContext *launch_context)
4617 {
4618   GDBusConnection *session_bus;
4619
4620   g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4621   g_return_if_fail (action_name != NULL);
4622   g_return_if_fail (app_info_has_action (info, action_name));
4623
4624   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4625
4626   if (session_bus && info->app_id)
4627     {
4628       gchar *object_path;
4629
4630       object_path = object_path_from_appid (info->app_id);
4631       g_dbus_connection_call (session_bus, info->app_id, object_path,
4632                               "org.freedesktop.Application", "ActivateAction",
4633                               g_variant_new ("(sav@a{sv})", action_name, NULL,
4634                                              g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4635                               NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4636       g_free (object_path);
4637     }
4638   else
4639     {
4640       gchar *group_name;
4641       gchar *exec_line;
4642
4643       group_name = g_strdup_printf ("Desktop Action %s", action_name);
4644       exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4645       g_free (group_name);
4646
4647       if (exec_line)
4648         g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4649                                                    _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL, NULL);
4650     }
4651
4652   if (session_bus != NULL)
4653     {
4654       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
4655       g_object_unref (session_bus);
4656     }
4657 }
4658 /* Epilogue {{{1 */
4659
4660 /* vim:set foldmethod=marker: */