f7208d3ec6e69943914fd8e12fb66ac4bfd2c64d
[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 = NULL;
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               if (sn_id)
2186                 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2187             }
2188
2189           g_list_free_full (launched_files, g_object_unref);
2190         }
2191
2192       if (!g_spawn_async (info->path,
2193                           argv,
2194                           envp,
2195                           spawn_flags,
2196                           child_setup,
2197                           &data,
2198                           &pid,
2199                           error))
2200         {
2201           if (sn_id)
2202             g_app_launch_context_launch_failed (launch_context, sn_id);
2203
2204           g_free (display);
2205           g_free (sn_id);
2206           g_list_free (launched_uris);
2207
2208           goto out;
2209         }
2210
2211       if (pid_callback != NULL)
2212         pid_callback (info, pid, pid_callback_data);
2213
2214       if (launch_context != NULL)
2215         {
2216           GVariantBuilder builder;
2217           GVariant *platform_data;
2218
2219           g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2220           g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2221           if (sn_id)
2222             g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2223           platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2224           g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2225           g_variant_unref (platform_data);
2226         }
2227
2228       notify_desktop_launch (session_bus,
2229                              info,
2230                              pid,
2231                              display,
2232                              sn_id,
2233                              launched_uris);
2234
2235       g_free (display);
2236       g_free (sn_id);
2237       g_list_free (launched_uris);
2238
2239       g_strfreev (argv);
2240       argv = NULL;
2241     }
2242   while (uris != NULL);
2243
2244   completed = TRUE;
2245
2246  out:
2247   g_strfreev (argv);
2248   g_strfreev (envp);
2249
2250   return completed;
2251 }
2252
2253 static gchar *
2254 object_path_from_appid (const gchar *app_id)
2255 {
2256   gchar *path;
2257   gint i, n;
2258
2259   n = strlen (app_id);
2260   path = g_malloc (n + 2);
2261
2262   path[0] = '/';
2263
2264   for (i = 0; i < n; i++)
2265     if (app_id[i] != '.')
2266       path[i + 1] = app_id[i];
2267     else
2268       path[i + 1] = '/';
2269
2270   path[i + 1] = '\0';
2271
2272   return path;
2273 }
2274
2275 static GVariant *
2276 g_desktop_app_info_make_platform_data (GDesktopAppInfo   *info,
2277                                        GList             *uris,
2278                                        GAppLaunchContext *launch_context)
2279 {
2280   GVariantBuilder builder;
2281
2282   g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2283
2284   if (launch_context)
2285     {
2286       GList *launched_files = create_files_for_uris (uris);
2287
2288       if (info->startup_notify)
2289         {
2290           gchar *sn_id;
2291
2292           sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2293           if (sn_id)
2294             g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2295         }
2296
2297       g_list_free_full (launched_files, g_object_unref);
2298     }
2299
2300   return g_variant_builder_end (&builder);
2301 }
2302
2303 static gboolean
2304 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo    *info,
2305                                           GDBusConnection    *session_bus,
2306                                           GList              *uris,
2307                                           GAppLaunchContext  *launch_context)
2308 {
2309   GVariantBuilder builder;
2310   gchar *object_path;
2311
2312   g_return_val_if_fail (info != NULL, FALSE);
2313
2314   g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2315
2316   if (uris)
2317     {
2318       GList *iter;
2319
2320       g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2321       for (iter = uris; iter; iter = iter->next)
2322         g_variant_builder_add (&builder, "s", iter->data);
2323       g_variant_builder_close (&builder);
2324     }
2325
2326   g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2327
2328   /* This is non-blocking API.  Similar to launching via fork()/exec()
2329    * we don't wait around to see if the program crashed during startup.
2330    * This is what startup-notification's job is...
2331    */
2332   object_path = object_path_from_appid (info->app_id);
2333   g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2334                           uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2335                           NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
2336   g_free (object_path);
2337
2338   return TRUE;
2339 }
2340
2341 static gboolean
2342 g_desktop_app_info_launch_uris_internal (GAppInfo                   *appinfo,
2343                                          GList                      *uris,
2344                                          GAppLaunchContext          *launch_context,
2345                                          GSpawnFlags                 spawn_flags,
2346                                          GSpawnChildSetupFunc        user_setup,
2347                                          gpointer                    user_setup_data,
2348                                          GDesktopAppLaunchCallback   pid_callback,
2349                                          gpointer                    pid_callback_data,
2350                                          GError                     **error)
2351 {
2352   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2353   GDBusConnection *session_bus;
2354   gboolean success = TRUE;
2355
2356   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
2357
2358   if (session_bus && info->app_id)
2359     g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context);
2360   else
2361     success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
2362                                                          spawn_flags, user_setup, user_setup_data,
2363                                                          pid_callback, pid_callback_data, error);
2364
2365   if (session_bus != NULL)
2366     {
2367       /* This asynchronous flush holds a reference until it completes,
2368        * which ensures that the following unref won't immediately kill
2369        * the connection if we were the initial owner.
2370        */
2371       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
2372       g_object_unref (session_bus);
2373     }
2374
2375   return success;
2376 }
2377
2378 static gboolean
2379 g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
2380                                 GList              *uris,
2381                                 GAppLaunchContext  *launch_context,
2382                                 GError            **error)
2383 {
2384   return g_desktop_app_info_launch_uris_internal (appinfo, uris,
2385                                                   launch_context,
2386                                                   _SPAWN_FLAGS_DEFAULT,
2387                                                   NULL, NULL, NULL, NULL,
2388                                                   error);
2389 }
2390
2391 static gboolean
2392 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
2393 {
2394   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2395
2396   return info->exec &&
2397     ((strstr (info->exec, "%u") != NULL) ||
2398      (strstr (info->exec, "%U") != NULL));
2399 }
2400
2401 static gboolean
2402 g_desktop_app_info_supports_files (GAppInfo *appinfo)
2403 {
2404   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2405
2406   return info->exec &&
2407     ((strstr (info->exec, "%f") != NULL) ||
2408      (strstr (info->exec, "%F") != NULL));
2409 }
2410
2411 static gboolean
2412 g_desktop_app_info_launch (GAppInfo           *appinfo,
2413                            GList              *files,
2414                            GAppLaunchContext  *launch_context,
2415                            GError            **error)
2416 {
2417   GList *uris;
2418   char *uri;
2419   gboolean res;
2420
2421   uris = NULL;
2422   while (files)
2423     {
2424       uri = g_file_get_uri (files->data);
2425       uris = g_list_prepend (uris, uri);
2426       files = files->next;
2427     }
2428
2429   uris = g_list_reverse (uris);
2430
2431   res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
2432
2433   g_list_free_full (uris, g_free);
2434
2435   return res;
2436 }
2437
2438 /**
2439  * g_desktop_app_info_launch_uris_as_manager:
2440  * @appinfo: a #GDesktopAppInfo
2441  * @uris: (element-type utf8): List of URIs
2442  * @launch_context: (allow-none): a #GAppLaunchContext
2443  * @spawn_flags: #GSpawnFlags, used for each process
2444  * @user_setup: (scope call) (allow-none): a #GSpawnChildSetupFunc, used once
2445  *     for each process.
2446  * @user_setup_data: (closure user_setup) (allow-none): User data for @user_setup
2447  * @pid_callback: (scope call) (allow-none): Callback for child processes
2448  * @pid_callback_data: (closure pid_callback) (allow-none): User data for @callback
2449  * @error: return location for a #GError, or %NULL
2450  *
2451  * This function performs the equivalent of g_app_info_launch_uris(),
2452  * but is intended primarily for operating system components that
2453  * launch applications.  Ordinary applications should use
2454  * g_app_info_launch_uris().
2455  *
2456  * If the application is launched via traditional UNIX fork()/exec()
2457  * then @spawn_flags, @user_setup and @user_setup_data are used for the
2458  * call to g_spawn_async().  Additionally, @pid_callback (with
2459  * @pid_callback_data) will be called to inform about the PID of the
2460  * created process.
2461  *
2462  * If application launching occurs via some other mechanism (eg: D-Bus
2463  * activation) then @spawn_flags, @user_setup, @user_setup_data,
2464  * @pid_callback and @pid_callback_data are ignored.
2465  *
2466  * Returns: %TRUE on successful launch, %FALSE otherwise.
2467  */
2468 gboolean
2469 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo            *appinfo,
2470                                            GList                      *uris,
2471                                            GAppLaunchContext          *launch_context,
2472                                            GSpawnFlags                 spawn_flags,
2473                                            GSpawnChildSetupFunc        user_setup,
2474                                            gpointer                    user_setup_data,
2475                                            GDesktopAppLaunchCallback   pid_callback,
2476                                            gpointer                    pid_callback_data,
2477                                            GError                    **error)
2478 {
2479   return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
2480                                                   uris,
2481                                                   launch_context,
2482                                                   spawn_flags,
2483                                                   user_setup,
2484                                                   user_setup_data,
2485                                                   pid_callback,
2486                                                   pid_callback_data,
2487                                                   error);
2488 }
2489
2490 /* OnlyShowIn API support {{{2 */
2491
2492 /**
2493  * g_desktop_app_info_set_desktop_env:
2494  * @desktop_env: a string specifying what desktop this is
2495  *
2496  * Sets the name of the desktop that the application is running in.
2497  * This is used by g_app_info_should_show() and
2498  * g_desktop_app_info_get_show_in() to evaluate the
2499  * `OnlyShowIn` and `NotShowIn`
2500  * desktop entry fields.
2501  *
2502  * The 
2503  * [Desktop Menu specification](http://standards.freedesktop.org/menu-spec/latest/)
2504  * recognizes the following:
2505  * - GNOME
2506  * - KDE
2507  * - ROX
2508  * - XFCE
2509  * - LXDE
2510  * - Unity
2511  * - Old
2512  *
2513  * Should be called only once; subsequent calls are ignored.
2514  */
2515 void
2516 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
2517 {
2518   G_LOCK (g_desktop_env);
2519   if (!g_desktop_env)
2520     g_desktop_env = g_strdup (desktop_env);
2521   G_UNLOCK (g_desktop_env);
2522 }
2523
2524 static gboolean
2525 g_desktop_app_info_should_show (GAppInfo *appinfo)
2526 {
2527   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2528
2529   if (info->nodisplay)
2530     return FALSE;
2531
2532   return g_desktop_app_info_get_show_in (info, NULL);
2533 }
2534
2535 /* mime types/default apps support {{{2 */
2536
2537 typedef enum {
2538   APP_DIR,
2539   MIMETYPE_DIR
2540 } DirType;
2541
2542 static char *
2543 ensure_dir (DirType   type,
2544             GError  **error)
2545 {
2546   char *path, *display_name;
2547   int errsv;
2548
2549   if (type == APP_DIR)
2550     path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
2551   else
2552     path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
2553
2554   errno = 0;
2555   if (g_mkdir_with_parents (path, 0700) == 0)
2556     return path;
2557
2558   errsv = errno;
2559   display_name = g_filename_display_name (path);
2560   if (type == APP_DIR)
2561     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2562                  _("Can't create user application configuration folder %s: %s"),
2563                  display_name, g_strerror (errsv));
2564   else
2565     g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2566                  _("Can't create user MIME configuration folder %s: %s"),
2567                  display_name, g_strerror (errsv));
2568
2569   g_free (display_name);
2570   g_free (path);
2571
2572   return NULL;
2573 }
2574
2575 static gboolean
2576 update_mimeapps_list (const char  *desktop_id,
2577                       const char  *content_type,
2578                       UpdateMimeFlags flags,
2579                       GError     **error)
2580 {
2581   char *dirname, *filename, *string;
2582   GKeyFile *key_file;
2583   gboolean load_succeeded, res;
2584   char **old_list, **list;
2585   gsize length, data_size;
2586   char *data;
2587   int i, j, k;
2588   char **content_types;
2589
2590   /* Don't add both at start and end */
2591   g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
2592               (flags & UPDATE_MIME_SET_NON_DEFAULT)));
2593
2594   dirname = ensure_dir (APP_DIR, error);
2595   if (!dirname)
2596     return FALSE;
2597
2598   filename = g_build_filename (dirname, "mimeapps.list", NULL);
2599   g_free (dirname);
2600
2601   key_file = g_key_file_new ();
2602   load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
2603   if (!load_succeeded ||
2604       (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
2605        !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
2606        !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
2607     {
2608       g_key_file_free (key_file);
2609       key_file = g_key_file_new ();
2610     }
2611
2612   if (content_type)
2613     {
2614       content_types = g_new (char *, 2);
2615       content_types[0] = g_strdup (content_type);
2616       content_types[1] = NULL;
2617     }
2618   else
2619     {
2620       content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
2621     }
2622
2623   for (k = 0; content_types && content_types[k]; k++)
2624     {
2625       /* set as default, if requested so */
2626       string = g_key_file_get_string (key_file,
2627                                       DEFAULT_APPLICATIONS_GROUP,
2628                                       content_types[k],
2629                                       NULL);
2630
2631       if (g_strcmp0 (string, desktop_id) != 0 &&
2632           (flags & UPDATE_MIME_SET_DEFAULT))
2633         {
2634           g_free (string);
2635           string = g_strdup (desktop_id);
2636
2637           /* add in the non-default list too, if it's not already there */
2638           flags |= UPDATE_MIME_SET_NON_DEFAULT;
2639         }
2640
2641       if (string == NULL || desktop_id == NULL)
2642         g_key_file_remove_key (key_file,
2643                                DEFAULT_APPLICATIONS_GROUP,
2644                                content_types[k],
2645                                NULL);
2646       else
2647         g_key_file_set_string (key_file,
2648                                DEFAULT_APPLICATIONS_GROUP,
2649                                content_types[k],
2650                                string);
2651
2652       g_free (string);
2653     }
2654
2655   if (content_type)
2656     {
2657       /* reuse the list from above */
2658     }
2659   else
2660     {
2661       g_strfreev (content_types);
2662       content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
2663     }
2664
2665   for (k = 0; content_types && content_types[k]; k++)
2666     {
2667       /* Add to the right place in the list */
2668
2669       length = 0;
2670       old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
2671                                              content_types[k], &length, NULL);
2672
2673       list = g_new (char *, 1 + length + 1);
2674
2675       i = 0;
2676
2677       /* if we're adding a last-used hint, just put the application in front of the list */
2678       if (flags & UPDATE_MIME_SET_LAST_USED)
2679         {
2680           /* avoid adding this again as non-default later */
2681           if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2682             flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2683
2684           list[i++] = g_strdup (desktop_id);
2685         }
2686
2687       if (old_list)
2688         {
2689           for (j = 0; old_list[j] != NULL; j++)
2690             {
2691               if (g_strcmp0 (old_list[j], desktop_id) != 0)
2692                 {
2693                   /* rewrite other entries if they're different from the new one */
2694                   list[i++] = g_strdup (old_list[j]);
2695                 }
2696               else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2697                 {
2698                   /* we encountered an old entry which is equal to the one we're adding as non-default,
2699                    * don't change its position in the list.
2700                    */
2701                   flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2702                   list[i++] = g_strdup (old_list[j]);
2703                 }
2704             }
2705         }
2706
2707       /* add it at the end of the list */
2708       if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2709         list[i++] = g_strdup (desktop_id);
2710
2711       list[i] = NULL;
2712
2713       g_strfreev (old_list);
2714
2715       if (list[0] == NULL || desktop_id == NULL)
2716         g_key_file_remove_key (key_file,
2717                                ADDED_ASSOCIATIONS_GROUP,
2718                                content_types[k],
2719                                NULL);
2720       else
2721         g_key_file_set_string_list (key_file,
2722                                     ADDED_ASSOCIATIONS_GROUP,
2723                                     content_types[k],
2724                                     (const char * const *)list, i);
2725
2726       g_strfreev (list);
2727     }
2728
2729   if (content_type)
2730     {
2731       /* reuse the list from above */
2732     }
2733   else
2734     {
2735       g_strfreev (content_types);
2736       content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
2737     }
2738
2739   for (k = 0; content_types && content_types[k]; k++)
2740     {
2741       /* Remove from removed associations group (unless remove) */
2742
2743       length = 0;
2744       old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
2745                                              content_types[k], &length, NULL);
2746
2747       list = g_new (char *, 1 + length + 1);
2748
2749       i = 0;
2750       if (flags & UPDATE_MIME_REMOVE)
2751         list[i++] = g_strdup (desktop_id);
2752       if (old_list)
2753         {
2754           for (j = 0; old_list[j] != NULL; j++)
2755             {
2756               if (g_strcmp0 (old_list[j], desktop_id) != 0)
2757                 list[i++] = g_strdup (old_list[j]);
2758             }
2759         }
2760       list[i] = NULL;
2761
2762       g_strfreev (old_list);
2763
2764       if (list[0] == NULL || desktop_id == NULL)
2765         g_key_file_remove_key (key_file,
2766                                REMOVED_ASSOCIATIONS_GROUP,
2767                                content_types[k],
2768                                NULL);
2769       else
2770         g_key_file_set_string_list (key_file,
2771                                     REMOVED_ASSOCIATIONS_GROUP,
2772                                     content_types[k],
2773                                     (const char * const *)list, i);
2774
2775       g_strfreev (list);
2776     }
2777
2778   g_strfreev (content_types);
2779
2780   data = g_key_file_to_data (key_file, &data_size, error);
2781   g_key_file_free (key_file);
2782
2783   res = g_file_set_contents (filename, data, data_size, error);
2784
2785   mime_info_cache_reload (NULL);
2786
2787   g_free (filename);
2788   g_free (data);
2789
2790   return res;
2791 }
2792
2793 static gboolean
2794 g_desktop_app_info_set_as_last_used_for_type (GAppInfo    *appinfo,
2795                                               const char  *content_type,
2796                                               GError     **error)
2797 {
2798   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2799
2800   if (!g_desktop_app_info_ensure_saved (info, error))
2801     return FALSE;
2802
2803   if (!info->desktop_id)
2804     {
2805       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2806                            _("Application information lacks an identifier"));
2807       return FALSE;
2808     }
2809
2810   /* both add support for the content type and set as last used */
2811   return update_mimeapps_list (info->desktop_id, content_type,
2812                                UPDATE_MIME_SET_NON_DEFAULT |
2813                                UPDATE_MIME_SET_LAST_USED,
2814                                error);
2815 }
2816
2817 static gboolean
2818 g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
2819                                             const char  *content_type,
2820                                             GError     **error)
2821 {
2822   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2823
2824   if (!g_desktop_app_info_ensure_saved (info, error))
2825     return FALSE;
2826
2827   if (!info->desktop_id)
2828     {
2829       g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2830                            _("Application information lacks an identifier"));
2831       return FALSE;
2832     }
2833
2834   return update_mimeapps_list (info->desktop_id, content_type,
2835                                UPDATE_MIME_SET_DEFAULT,
2836                                error);
2837 }
2838
2839 static void
2840 update_program_done (GPid     pid,
2841                      gint     status,
2842                      gpointer data)
2843 {
2844   /* Did the application exit correctly */
2845   if (g_spawn_check_exit_status (status, NULL))
2846     {
2847       /* Here we could clean out any caches in use */
2848     }
2849 }
2850
2851 static void
2852 run_update_command (char *command,
2853                     char *subdir)
2854 {
2855         char *argv[3] = {
2856                 NULL,
2857                 NULL,
2858                 NULL,
2859         };
2860         GPid pid = 0;
2861         GError *error = NULL;
2862
2863         argv[0] = command;
2864         argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
2865
2866         if (g_spawn_async ("/", argv,
2867                            NULL,       /* envp */
2868                            G_SPAWN_SEARCH_PATH |
2869                            G_SPAWN_STDOUT_TO_DEV_NULL |
2870                            G_SPAWN_STDERR_TO_DEV_NULL |
2871                            G_SPAWN_DO_NOT_REAP_CHILD,
2872                            NULL, NULL, /* No setup function */
2873                            &pid,
2874                            &error))
2875           g_child_watch_add (pid, update_program_done, NULL);
2876         else
2877           {
2878             /* If we get an error at this point, it's quite likely the user doesn't
2879              * have an installed copy of either 'update-mime-database' or
2880              * 'update-desktop-database'.  I don't think we want to popup an error
2881              * dialog at this point, so we just do a g_warning to give the user a
2882              * chance of debugging it.
2883              */
2884             g_warning ("%s", error->message);
2885           }
2886
2887         g_free (argv[1]);
2888 }
2889
2890 static gboolean
2891 g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
2892                                                  const char  *extension,
2893                                                  GError     **error)
2894 {
2895   char *filename, *basename, *mimetype;
2896   char *dirname;
2897   gboolean res;
2898
2899   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
2900     return FALSE;
2901
2902   dirname = ensure_dir (MIMETYPE_DIR, error);
2903   if (!dirname)
2904     return FALSE;
2905
2906   basename = g_strdup_printf ("user-extension-%s.xml", extension);
2907   filename = g_build_filename (dirname, basename, NULL);
2908   g_free (basename);
2909   g_free (dirname);
2910
2911   mimetype = g_strdup_printf ("application/x-extension-%s", extension);
2912
2913   if (!g_file_test (filename, G_FILE_TEST_EXISTS))
2914     {
2915       char *contents;
2916
2917       contents =
2918         g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2919                          "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
2920                          " <mime-type type=\"%s\">\n"
2921                          "  <comment>%s document</comment>\n"
2922                          "  <glob pattern=\"*.%s\"/>\n"
2923                          " </mime-type>\n"
2924                          "</mime-info>\n", mimetype, extension, extension);
2925
2926       g_file_set_contents (filename, contents, -1, NULL);
2927       g_free (contents);
2928
2929       run_update_command ("update-mime-database", "mime");
2930     }
2931   g_free (filename);
2932
2933   res = g_desktop_app_info_set_as_default_for_type (appinfo,
2934                                                     mimetype,
2935                                                     error);
2936
2937   g_free (mimetype);
2938
2939   return res;
2940 }
2941
2942 static gboolean
2943 g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
2944                                       const char  *content_type,
2945                                       GError     **error)
2946 {
2947   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2948
2949   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2950     return FALSE;
2951
2952   return update_mimeapps_list (info->desktop_id, content_type,
2953                                UPDATE_MIME_SET_NON_DEFAULT,
2954                                error);
2955 }
2956
2957 static gboolean
2958 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
2959 {
2960   return TRUE;
2961 }
2962
2963 static gboolean
2964 g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
2965                                          const char  *content_type,
2966                                          GError     **error)
2967 {
2968   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2969
2970   if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2971     return FALSE;
2972
2973   return update_mimeapps_list (info->desktop_id, content_type,
2974                                UPDATE_MIME_REMOVE,
2975                                error);
2976 }
2977
2978 static const char **
2979 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
2980 {
2981   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2982
2983   return (const char**) info->mime_types;
2984 }
2985
2986 /* Saving and deleting {{{2 */
2987
2988 static gboolean
2989 g_desktop_app_info_ensure_saved (GDesktopAppInfo  *info,
2990                                  GError          **error)
2991 {
2992   GKeyFile *key_file;
2993   char *dirname;
2994   char *filename;
2995   char *data, *desktop_id;
2996   gsize data_size;
2997   int fd;
2998   gboolean res;
2999
3000   if (info->filename != NULL)
3001     return TRUE;
3002
3003   /* This is only used for object created with
3004    * g_app_info_create_from_commandline. All other
3005    * object should have a filename
3006    */
3007
3008   dirname = ensure_dir (APP_DIR, error);
3009   if (!dirname)
3010     return FALSE;
3011
3012   key_file = g_key_file_new ();
3013
3014   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3015                          "Encoding", "UTF-8");
3016   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3017                          G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
3018   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3019                          G_KEY_FILE_DESKTOP_KEY_TYPE,
3020                          G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3021   if (info->terminal)
3022     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3023                             G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3024   if (info->nodisplay)
3025     g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3026                             G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3027
3028   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3029                          G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3030
3031   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3032                          G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3033
3034   if (info->generic_name != NULL)
3035     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3036                            GENERIC_NAME_KEY, info->generic_name);
3037
3038   if (info->fullname != NULL)
3039     g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3040                            FULL_NAME_KEY, info->fullname);
3041
3042   g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3043                          G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3044
3045   g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3046                           G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3047
3048   data = g_key_file_to_data (key_file, &data_size, NULL);
3049   g_key_file_free (key_file);
3050
3051   desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3052   filename = g_build_filename (dirname, desktop_id, NULL);
3053   g_free (desktop_id);
3054   g_free (dirname);
3055
3056   fd = g_mkstemp (filename);
3057   if (fd == -1)
3058     {
3059       char *display_name;
3060
3061       display_name = g_filename_display_name (filename);
3062       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3063                    _("Can't create user desktop file %s"), display_name);
3064       g_free (display_name);
3065       g_free (filename);
3066       g_free (data);
3067       return FALSE;
3068     }
3069
3070   desktop_id = g_path_get_basename (filename);
3071
3072   /* FIXME - actually handle error */
3073   (void) g_close (fd, NULL);
3074
3075   res = g_file_set_contents (filename, data, data_size, error);
3076   g_free (data);
3077   if (!res)
3078     {
3079       g_free (desktop_id);
3080       g_free (filename);
3081       return FALSE;
3082     }
3083
3084   info->filename = filename;
3085   info->desktop_id = desktop_id;
3086
3087   run_update_command ("update-desktop-database", "applications");
3088
3089   /* We just dropped a file in the user's desktop file directory.  Save
3090    * the monitor the bother of having to notice it and invalidate
3091    * immediately.
3092    *
3093    * This means that calls directly following this will be able to see
3094    * the results immediately.
3095    */
3096   desktop_file_dirs_invalidate_user ();
3097
3098   return TRUE;
3099 }
3100
3101 static gboolean
3102 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3103 {
3104   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3105
3106   if (info->filename)
3107     {
3108       if (strstr (info->filename, "/userapp-"))
3109         return g_access (info->filename, W_OK) == 0;
3110     }
3111
3112   return FALSE;
3113 }
3114
3115 static gboolean
3116 g_desktop_app_info_delete (GAppInfo *appinfo)
3117 {
3118   GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3119
3120   if (info->filename)
3121     {
3122       if (g_remove (info->filename) == 0)
3123         {
3124           update_mimeapps_list (info->desktop_id, NULL,
3125                                 UPDATE_MIME_NONE,
3126                                 NULL);
3127
3128           g_free (info->filename);
3129           info->filename = NULL;
3130           g_free (info->desktop_id);
3131           info->desktop_id = NULL;
3132
3133           return TRUE;
3134         }
3135     }
3136
3137   return FALSE;
3138 }
3139
3140 /* Create for commandline {{{2 */
3141 /**
3142  * g_app_info_create_from_commandline:
3143  * @commandline: the commandline to use
3144  * @application_name: (allow-none): the application name, or %NULL to use @commandline
3145  * @flags: flags that can specify details of the created #GAppInfo
3146  * @error: a #GError location to store the error occurring, %NULL to ignore.
3147  *
3148  * Creates a new #GAppInfo from the given information.
3149  *
3150  * Note that for @commandline, the quoting rules of the Exec key of the
3151  * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
3152  * are applied. For example, if the @commandline contains
3153  * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
3154  * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
3155  *
3156  * Returns: (transfer full): new #GAppInfo for given command.
3157  **/
3158 GAppInfo *
3159 g_app_info_create_from_commandline (const char           *commandline,
3160                                     const char           *application_name,
3161                                     GAppInfoCreateFlags   flags,
3162                                     GError              **error)
3163 {
3164   char **split;
3165   char *basename;
3166   GDesktopAppInfo *info;
3167
3168   g_return_val_if_fail (commandline, NULL);
3169
3170   info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
3171
3172   info->filename = NULL;
3173   info->desktop_id = NULL;
3174
3175   info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
3176   info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
3177   info->hidden = FALSE;
3178   if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
3179     info->exec = g_strconcat (commandline, " %u", NULL);
3180   else
3181     info->exec = g_strconcat (commandline, " %f", NULL);
3182   info->nodisplay = TRUE;
3183   info->binary = binary_from_exec (info->exec);
3184
3185   if (application_name)
3186     info->name = g_strdup (application_name);
3187   else
3188     {
3189       /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
3190       split = g_strsplit (commandline, " ", 2);
3191       basename = split[0] ? g_path_get_basename (split[0]) : NULL;
3192       g_strfreev (split);
3193       info->name = basename;
3194       if (info->name == NULL)
3195         info->name = g_strdup ("custom");
3196     }
3197   info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
3198
3199   return G_APP_INFO (info);
3200 }
3201
3202 /* GAppInfo interface init */
3203
3204 static void
3205 g_desktop_app_info_iface_init (GAppInfoIface *iface)
3206 {
3207   iface->dup = g_desktop_app_info_dup;
3208   iface->equal = g_desktop_app_info_equal;
3209   iface->get_id = g_desktop_app_info_get_id;
3210   iface->get_name = g_desktop_app_info_get_name;
3211   iface->get_description = g_desktop_app_info_get_description;
3212   iface->get_executable = g_desktop_app_info_get_executable;
3213   iface->get_icon = g_desktop_app_info_get_icon;
3214   iface->launch = g_desktop_app_info_launch;
3215   iface->supports_uris = g_desktop_app_info_supports_uris;
3216   iface->supports_files = g_desktop_app_info_supports_files;
3217   iface->launch_uris = g_desktop_app_info_launch_uris;
3218   iface->should_show = g_desktop_app_info_should_show;
3219   iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
3220   iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
3221   iface->add_supports_type = g_desktop_app_info_add_supports_type;
3222   iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
3223   iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
3224   iface->can_delete = g_desktop_app_info_can_delete;
3225   iface->do_delete = g_desktop_app_info_delete;
3226   iface->get_commandline = g_desktop_app_info_get_commandline;
3227   iface->get_display_name = g_desktop_app_info_get_display_name;
3228   iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
3229   iface->get_supported_types = g_desktop_app_info_get_supported_types;
3230 }
3231
3232 /* Recommended applications {{{2 */
3233
3234 static gboolean
3235 app_info_in_list (GAppInfo *info,
3236                   GList    *list)
3237 {
3238   while (list != NULL)
3239     {
3240       if (g_app_info_equal (info, list->data))
3241         return TRUE;
3242       list = list->next;
3243     }
3244   return FALSE;
3245 }
3246
3247 /**
3248  * g_app_info_get_recommended_for_type:
3249  * @content_type: the content type to find a #GAppInfo for
3250  *
3251  * Gets a list of recommended #GAppInfos for a given content type, i.e.
3252  * those applications which claim to support the given content type exactly,
3253  * and not by MIME type subclassing.
3254  * Note that the first application of the list is the last used one, i.e.
3255  * the last one for which g_app_info_set_as_last_used_for_type() has been
3256  * called.
3257  *
3258  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3259  *     for given @content_type or %NULL on error.
3260  *
3261  * Since: 2.28
3262  **/
3263 GList *
3264 g_app_info_get_recommended_for_type (const gchar *content_type)
3265 {
3266   GList *desktop_entries, *l;
3267   GList *infos;
3268   GDesktopAppInfo *info;
3269
3270   g_return_val_if_fail (content_type != NULL, NULL);
3271
3272   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, FALSE, NULL);
3273
3274   infos = NULL;
3275   for (l = desktop_entries; l != NULL; l = l->next)
3276     {
3277       char *desktop_entry = l->data;
3278
3279       info = g_desktop_app_info_new (desktop_entry);
3280       if (info)
3281         {
3282           if (app_info_in_list (G_APP_INFO (info), infos))
3283             g_object_unref (info);
3284           else
3285             infos = g_list_prepend (infos, info);
3286         }
3287       g_free (desktop_entry);
3288     }
3289
3290   g_list_free (desktop_entries);
3291
3292   return g_list_reverse (infos);
3293 }
3294
3295 /**
3296  * g_app_info_get_fallback_for_type:
3297  * @content_type: the content type to find a #GAppInfo for
3298  *
3299  * Gets a list of fallback #GAppInfos for a given content type, i.e.
3300  * those applications which claim to support the given content type
3301  * by MIME type subclassing and not directly.
3302  *
3303  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3304  *     for given @content_type or %NULL on error.
3305  *
3306  * Since: 2.28
3307  **/
3308 GList *
3309 g_app_info_get_fallback_for_type (const gchar *content_type)
3310 {
3311   GList *desktop_entries, *l;
3312   GList *infos, *recommended_infos;
3313   GDesktopAppInfo *info;
3314
3315   g_return_val_if_fail (content_type != NULL, NULL);
3316
3317   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, NULL);
3318   recommended_infos = g_app_info_get_recommended_for_type (content_type);
3319
3320   infos = NULL;
3321   for (l = desktop_entries; l != NULL; l = l->next)
3322     {
3323       char *desktop_entry = l->data;
3324
3325       info = g_desktop_app_info_new (desktop_entry);
3326       if (info)
3327         {
3328           if (app_info_in_list (G_APP_INFO (info), infos) ||
3329               app_info_in_list (G_APP_INFO (info), recommended_infos))
3330             g_object_unref (info);
3331           else
3332             infos = g_list_prepend (infos, info);
3333         }
3334       g_free (desktop_entry);
3335     }
3336
3337   g_list_free (desktop_entries);
3338   g_list_free_full (recommended_infos, g_object_unref);
3339
3340   return g_list_reverse (infos);
3341 }
3342
3343 /**
3344  * g_app_info_get_all_for_type:
3345  * @content_type: the content type to find a #GAppInfo for
3346  *
3347  * Gets a list of all #GAppInfos for a given content type,
3348  * including the recommended and fallback #GAppInfos. See
3349  * g_app_info_get_recommended_for_type() and
3350  * g_app_info_get_fallback_for_type().
3351  *
3352  * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3353  *     for given @content_type or %NULL on error.
3354  **/
3355 GList *
3356 g_app_info_get_all_for_type (const char *content_type)
3357 {
3358   GList *desktop_entries, *l;
3359   GList *infos;
3360   char *user_default = NULL;
3361   GDesktopAppInfo *info;
3362
3363   g_return_val_if_fail (content_type != NULL, NULL);
3364
3365   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3366   infos = NULL;
3367
3368   /* put the user default in front of the list, for compatibility */
3369   if (user_default != NULL)
3370     {
3371       info = g_desktop_app_info_new (user_default);
3372
3373       if (info != NULL)
3374         infos = g_list_prepend (infos, info);
3375     }
3376
3377   g_free (user_default);
3378
3379   for (l = desktop_entries; l != NULL; l = l->next)
3380     {
3381       char *desktop_entry = l->data;
3382
3383       info = g_desktop_app_info_new (desktop_entry);
3384       if (info)
3385         {
3386           if (app_info_in_list (G_APP_INFO (info), infos))
3387             g_object_unref (info);
3388           else
3389             infos = g_list_prepend (infos, info);
3390         }
3391       g_free (desktop_entry);
3392     }
3393
3394   g_list_free (desktop_entries);
3395
3396   return g_list_reverse (infos);
3397 }
3398
3399 /**
3400  * g_app_info_reset_type_associations:
3401  * @content_type: a content type
3402  *
3403  * Removes all changes to the type associations done by
3404  * g_app_info_set_as_default_for_type(),
3405  * g_app_info_set_as_default_for_extension(),
3406  * g_app_info_add_supports_type() or
3407  * g_app_info_remove_supports_type().
3408  *
3409  * Since: 2.20
3410  */
3411 void
3412 g_app_info_reset_type_associations (const char *content_type)
3413 {
3414   update_mimeapps_list (NULL, content_type,
3415                         UPDATE_MIME_NONE,
3416                         NULL);
3417 }
3418
3419 /**
3420  * g_app_info_get_default_for_type:
3421  * @content_type: the content type to find a #GAppInfo for
3422  * @must_support_uris: if %TRUE, the #GAppInfo is expected to
3423  *     support URIs
3424  *
3425  * Gets the default #GAppInfo for a given content type.
3426  *
3427  * Returns: (transfer full): #GAppInfo for given @content_type or
3428  *     %NULL on error.
3429  */
3430 GAppInfo *
3431 g_app_info_get_default_for_type (const char *content_type,
3432                                  gboolean    must_support_uris)
3433 {
3434   GList *desktop_entries, *l;
3435   char *user_default = NULL;
3436   GAppInfo *info;
3437
3438   g_return_val_if_fail (content_type != NULL, NULL);
3439
3440   desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3441
3442   info = NULL;
3443
3444   if (user_default != NULL)
3445     {
3446       info = (GAppInfo *) g_desktop_app_info_new (user_default);
3447
3448       if (info)
3449         {
3450           if (must_support_uris && !g_app_info_supports_uris (info))
3451             {
3452               g_object_unref (info);
3453               info = NULL;
3454             }
3455         }
3456     }
3457
3458   g_free (user_default);
3459
3460   if (info != NULL)
3461     {
3462       g_list_free_full (desktop_entries, g_free);
3463       return info;
3464     }
3465
3466   /* pick the first from the other list that matches our URI
3467    * requirements.
3468    */
3469   for (l = desktop_entries; l != NULL; l = l->next)
3470     {
3471       char *desktop_entry = l->data;
3472
3473       info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
3474       if (info)
3475         {
3476           if (must_support_uris && !g_app_info_supports_uris (info))
3477             {
3478               g_object_unref (info);
3479               info = NULL;
3480             }
3481           else
3482             break;
3483         }
3484     }
3485
3486   g_list_free_full (desktop_entries, g_free);
3487
3488   return info;
3489 }
3490
3491 /**
3492  * g_app_info_get_default_for_uri_scheme:
3493  * @uri_scheme: a string containing a URI scheme.
3494  *
3495  * Gets the default application for handling URIs with
3496  * the given URI scheme. A URI scheme is the initial part
3497  * of the URI, up to but not including the ':', e.g. "http",
3498  * "ftp" or "sip".
3499  *
3500  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
3501  */
3502 GAppInfo *
3503 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
3504 {
3505   GAppInfo *app_info;
3506   char *content_type, *scheme_down;
3507
3508   scheme_down = g_ascii_strdown (uri_scheme, -1);
3509   content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
3510   g_free (scheme_down);
3511   app_info = g_app_info_get_default_for_type (content_type, FALSE);
3512   g_free (content_type);
3513
3514   return app_info;
3515 }
3516
3517 /* "Get all" API {{{2 */
3518
3519 /**
3520  * g_desktop_app_info_search:
3521  * @search_string: the search string to use
3522  *
3523  * Searches desktop files for ones that match @search_string.
3524  *
3525  * The return value is an array of strvs.  Each strv contains a list of
3526  * applications that matched @search_string with an equal score.  The
3527  * outer list is sorted by score so that the first strv contains the
3528  * best-matching applications, and so on.
3529  * The algorithm for determining matches is undefined and may change at
3530  * any time.
3531  *
3532  * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
3533  *   list of strvs.  Free each item with g_strfreev() and free the outer
3534  *   list with g_free().
3535  */
3536 gchar ***
3537 g_desktop_app_info_search (const gchar *search_string)
3538 {
3539   gchar **search_tokens;
3540   gint last_category = -1;
3541   gchar ***results;
3542   gint n_categories = 0;
3543   gint start_of_category;
3544   gint i, j;
3545
3546   search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
3547
3548   desktop_file_dirs_lock ();
3549
3550   reset_total_search_results ();
3551
3552   for (i = 0; i < n_desktop_file_dirs; i++)
3553     {
3554       for (j = 0; search_tokens[j]; j++)
3555         {
3556           desktop_file_dir_search (&desktop_file_dirs[i], search_tokens[j]);
3557           merge_token_results (j == 0);
3558         }
3559       merge_directory_results ();
3560     }
3561
3562   sort_total_search_results ();
3563
3564   /* Count the total number of unique categories */
3565   for (i = 0; i < static_total_results_size; i++)
3566     if (static_total_results[i].category != last_category)
3567       {
3568         last_category = static_total_results[i].category;
3569         n_categories++;
3570       }
3571
3572   results = g_new (gchar **, n_categories + 1);
3573
3574   /* Start loading into the results list */
3575   start_of_category = 0;
3576   for (i = 0; i < n_categories; i++)
3577     {
3578       gint n_items_in_category = 0;
3579       gint this_category;
3580       gint j;
3581
3582       this_category = static_total_results[start_of_category].category;
3583
3584       while (start_of_category + n_items_in_category < static_total_results_size &&
3585              static_total_results[start_of_category + n_items_in_category].category == this_category)
3586         n_items_in_category++;
3587
3588       results[i] = g_new (gchar *, n_items_in_category + 1);
3589       for (j = 0; j < n_items_in_category; j++)
3590         results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
3591       results[i][j] = NULL;
3592
3593       start_of_category += n_items_in_category;
3594     }
3595   results[i] = NULL;
3596
3597   desktop_file_dirs_unlock ();
3598
3599   g_strfreev (search_tokens);
3600
3601   return results;
3602 }
3603
3604 /**
3605  * g_app_info_get_all:
3606  *
3607  * Gets a list of all of the applications currently registered
3608  * on this system.
3609  *
3610  * For desktop files, this includes applications that have
3611  * `NoDisplay=true` set or are excluded from display by means
3612  * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
3613  * The returned list does not include applications which have
3614  * the `Hidden` key set.
3615  *
3616  * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
3617  **/
3618 GList *
3619 g_app_info_get_all (void)
3620 {
3621   GHashTable *apps;
3622   GHashTableIter iter;
3623   gpointer value;
3624   int i;
3625   GList *infos;
3626
3627   apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
3628
3629   desktop_file_dirs_lock ();
3630
3631   for (i = 0; i < n_desktop_file_dirs; i++)
3632     desktop_file_dir_get_all (&desktop_file_dirs[i], apps);
3633
3634   desktop_file_dirs_unlock ();
3635
3636   infos = NULL;
3637   g_hash_table_iter_init (&iter, apps);
3638   while (g_hash_table_iter_next (&iter, NULL, &value))
3639     {
3640       if (value)
3641         infos = g_list_prepend (infos, value);
3642     }
3643
3644   g_hash_table_destroy (apps);
3645
3646   return infos;
3647 }
3648
3649 /* Caching of mimeinfo.cache and defaults.list files {{{2 */
3650
3651 typedef struct {
3652   char *path;
3653   GHashTable *mime_info_cache_map;
3654   GHashTable *defaults_list_map;
3655   GHashTable *mimeapps_list_added_map;
3656   GHashTable *mimeapps_list_removed_map;
3657   GHashTable *mimeapps_list_defaults_map;
3658   time_t mime_info_cache_timestamp;
3659   time_t defaults_list_timestamp;
3660   time_t mimeapps_list_timestamp;
3661 } MimeInfoCacheDir;
3662
3663 typedef struct {
3664   GList *dirs;                       /* mimeinfo.cache and defaults.list */
3665   time_t last_stat_time;
3666 } MimeInfoCache;
3667
3668 static MimeInfoCache *mime_info_cache = NULL;
3669 G_LOCK_DEFINE_STATIC (mime_info_cache);
3670
3671 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
3672                                                      const char        *mime_type,
3673                                                      char             **new_desktop_file_ids);
3674
3675 static MimeInfoCache * mime_info_cache_new (void);
3676
3677 static void
3678 destroy_info_cache_value (gpointer  key,
3679                           GList    *value,
3680                           gpointer  data)
3681 {
3682   g_list_free_full (value, g_free);
3683 }
3684
3685 static void
3686 destroy_info_cache_map (GHashTable *info_cache_map)
3687 {
3688   g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
3689   g_hash_table_destroy (info_cache_map);
3690 }
3691
3692 static gboolean
3693 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
3694                                  const char       *cache_file,
3695                                  time_t           *timestamp)
3696 {
3697   struct stat buf;
3698   char *filename;
3699
3700   filename = g_build_filename (dir->path, cache_file, NULL);
3701
3702   if (g_stat (filename, &buf) < 0)
3703     {
3704       g_free (filename);
3705       return TRUE;
3706     }
3707   g_free (filename);
3708
3709   if (buf.st_mtime != *timestamp)
3710     return TRUE;
3711
3712   return FALSE;
3713 }
3714
3715 /* Call with lock held */
3716 static void
3717 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
3718 {
3719   GError *load_error;
3720   GKeyFile *key_file;
3721   gchar *filename, **mime_types;
3722   int i;
3723   struct stat buf;
3724
3725   load_error = NULL;
3726   mime_types = NULL;
3727
3728   if (dir->mime_info_cache_map != NULL &&
3729       !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
3730                                         &dir->mime_info_cache_timestamp))
3731     return;
3732
3733   if (dir->mime_info_cache_map != NULL)
3734     destroy_info_cache_map (dir->mime_info_cache_map);
3735
3736   dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3737                                                     (GDestroyNotify) g_free,
3738                                                     NULL);
3739
3740   key_file = g_key_file_new ();
3741
3742   filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
3743
3744   if (g_stat (filename, &buf) < 0)
3745     goto error;
3746
3747   dir->mime_info_cache_timestamp = buf.st_mtime;
3748
3749   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3750
3751   g_free (filename);
3752   filename = NULL;
3753
3754   if (load_error != NULL)
3755     goto error;
3756
3757   mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
3758                                     NULL, &load_error);
3759
3760   if (load_error != NULL)
3761     goto error;
3762
3763   for (i = 0; mime_types[i] != NULL; i++)
3764     {
3765       gchar **desktop_file_ids;
3766       char *unaliased_type;
3767       desktop_file_ids = g_key_file_get_string_list (key_file,
3768                                                      MIME_CACHE_GROUP,
3769                                                      mime_types[i],
3770                                                      NULL,
3771                                                      NULL);
3772
3773       if (desktop_file_ids == NULL)
3774         continue;
3775
3776       unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3777       mime_info_cache_dir_add_desktop_entries (dir,
3778                                                unaliased_type,
3779                                                desktop_file_ids);
3780       g_free (unaliased_type);
3781
3782       g_strfreev (desktop_file_ids);
3783     }
3784
3785   g_strfreev (mime_types);
3786   g_key_file_free (key_file);
3787
3788   return;
3789  error:
3790   g_free (filename);
3791   g_key_file_free (key_file);
3792
3793   if (mime_types != NULL)
3794     g_strfreev (mime_types);
3795
3796   if (load_error)
3797     g_error_free (load_error);
3798 }
3799
3800 static void
3801 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
3802 {
3803   GKeyFile *key_file;
3804   GError *load_error;
3805   gchar *filename, **mime_types;
3806   char *unaliased_type;
3807   char **desktop_file_ids;
3808   int i;
3809   struct stat buf;
3810
3811   load_error = NULL;
3812   mime_types = NULL;
3813
3814   if (dir->defaults_list_map != NULL &&
3815       !mime_info_cache_dir_out_of_date (dir, "defaults.list",
3816                                         &dir->defaults_list_timestamp))
3817     return;
3818
3819   if (dir->defaults_list_map != NULL)
3820     g_hash_table_destroy (dir->defaults_list_map);
3821   dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3822                                                   g_free, (GDestroyNotify)g_strfreev);
3823
3824
3825   key_file = g_key_file_new ();
3826
3827   filename = g_build_filename (dir->path, "defaults.list", NULL);
3828   if (g_stat (filename, &buf) < 0)
3829     goto error;
3830
3831   dir->defaults_list_timestamp = buf.st_mtime;
3832
3833   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3834   g_free (filename);
3835   filename = NULL;
3836
3837   if (load_error != NULL)
3838     goto error;
3839
3840   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3841                                     NULL, NULL);
3842   if (mime_types != NULL)
3843     {
3844       for (i = 0; mime_types[i] != NULL; i++)
3845         {
3846           desktop_file_ids = g_key_file_get_string_list (key_file,
3847                                                          DEFAULT_APPLICATIONS_GROUP,
3848                                                          mime_types[i],
3849                                                          NULL,
3850                                                          NULL);
3851           if (desktop_file_ids == NULL)
3852             continue;
3853
3854           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3855           g_hash_table_replace (dir->defaults_list_map,
3856                                 unaliased_type,
3857                                 desktop_file_ids);
3858         }
3859
3860       g_strfreev (mime_types);
3861     }
3862
3863   g_key_file_free (key_file);
3864   return;
3865
3866  error:
3867   g_free (filename);
3868   g_key_file_free (key_file);
3869
3870   if (mime_types != NULL)
3871     g_strfreev (mime_types);
3872
3873   if (load_error)
3874     g_error_free (load_error);
3875 }
3876
3877 static void
3878 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
3879 {
3880   GKeyFile *key_file;
3881   GError *load_error;
3882   gchar *filename, **mime_types;
3883   char *unaliased_type;
3884   char **desktop_file_ids;
3885   char *desktop_id;
3886   int i;
3887   struct stat buf;
3888
3889   load_error = NULL;
3890   mime_types = NULL;
3891
3892   if (dir->mimeapps_list_added_map != NULL &&
3893       !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
3894                                         &dir->mimeapps_list_timestamp))
3895     return;
3896
3897   if (dir->mimeapps_list_added_map != NULL)
3898     g_hash_table_destroy (dir->mimeapps_list_added_map);
3899   dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3900                                                         g_free, (GDestroyNotify)g_strfreev);
3901
3902   if (dir->mimeapps_list_removed_map != NULL)
3903     g_hash_table_destroy (dir->mimeapps_list_removed_map);
3904   dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3905                                                           g_free, (GDestroyNotify)g_strfreev);
3906
3907   if (dir->mimeapps_list_defaults_map != NULL)
3908     g_hash_table_destroy (dir->mimeapps_list_defaults_map);
3909   dir->mimeapps_list_defaults_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3910                                                            g_free, g_free);
3911
3912   key_file = g_key_file_new ();
3913
3914   filename = g_build_filename (dir->path, "mimeapps.list", NULL);
3915   if (g_stat (filename, &buf) < 0)
3916     goto error;
3917
3918   dir->mimeapps_list_timestamp = buf.st_mtime;
3919
3920   g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3921   g_free (filename);
3922   filename = NULL;
3923
3924   if (load_error != NULL)
3925     goto error;
3926
3927   mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
3928                                     NULL, NULL);
3929   if (mime_types != NULL)
3930     {
3931       for (i = 0; mime_types[i] != NULL; i++)
3932         {
3933           desktop_file_ids = g_key_file_get_string_list (key_file,
3934                                                          ADDED_ASSOCIATIONS_GROUP,
3935                                                          mime_types[i],
3936                                                          NULL,
3937                                                          NULL);
3938           if (desktop_file_ids == NULL)
3939             continue;
3940
3941           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3942           g_hash_table_replace (dir->mimeapps_list_added_map,
3943                                 unaliased_type,
3944                                 desktop_file_ids);
3945         }
3946
3947       g_strfreev (mime_types);
3948     }
3949
3950   mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
3951                                     NULL, NULL);
3952   if (mime_types != NULL)
3953     {
3954       for (i = 0; mime_types[i] != NULL; i++)
3955         {
3956           desktop_file_ids = g_key_file_get_string_list (key_file,
3957                                                          REMOVED_ASSOCIATIONS_GROUP,
3958                                                          mime_types[i],
3959                                                          NULL,
3960                                                          NULL);
3961           if (desktop_file_ids == NULL)
3962             continue;
3963
3964           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3965           g_hash_table_replace (dir->mimeapps_list_removed_map,
3966                                 unaliased_type,
3967                                 desktop_file_ids);
3968         }
3969
3970       g_strfreev (mime_types);
3971     }
3972
3973   mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3974                                     NULL, NULL);
3975   if (mime_types != NULL)
3976     {
3977       for (i = 0; mime_types[i] != NULL; i++)
3978         {
3979           desktop_id = g_key_file_get_string (key_file,
3980                                               DEFAULT_APPLICATIONS_GROUP,
3981                                               mime_types[i],
3982                                               NULL);
3983           if (desktop_id == NULL)
3984             continue;
3985
3986           unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3987           g_hash_table_replace (dir->mimeapps_list_defaults_map,
3988                                 unaliased_type,
3989                                 desktop_id);
3990         }
3991
3992       g_strfreev (mime_types);
3993     }
3994
3995   g_key_file_free (key_file);
3996   return;
3997
3998  error:
3999   g_free (filename);
4000   g_key_file_free (key_file);
4001
4002   if (mime_types != NULL)
4003     g_strfreev (mime_types);
4004
4005   if (load_error)
4006     g_error_free (load_error);
4007 }
4008
4009 static MimeInfoCacheDir *
4010 mime_info_cache_dir_new (const char *path)
4011 {
4012   MimeInfoCacheDir *dir;
4013
4014   dir = g_new0 (MimeInfoCacheDir, 1);
4015   dir->path = g_strdup (path);
4016
4017   return dir;
4018 }
4019
4020 static void
4021 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
4022 {
4023   if (dir == NULL)
4024     return;
4025
4026   if (dir->mime_info_cache_map != NULL)
4027     {
4028       destroy_info_cache_map (dir->mime_info_cache_map);
4029       dir->mime_info_cache_map = NULL;
4030
4031   }
4032
4033   if (dir->defaults_list_map != NULL)
4034     {
4035       g_hash_table_destroy (dir->defaults_list_map);
4036       dir->defaults_list_map = NULL;
4037     }
4038
4039   if (dir->mimeapps_list_added_map != NULL)
4040     {
4041       g_hash_table_destroy (dir->mimeapps_list_added_map);
4042       dir->mimeapps_list_added_map = NULL;
4043     }
4044
4045   if (dir->mimeapps_list_removed_map != NULL)
4046     {
4047       g_hash_table_destroy (dir->mimeapps_list_removed_map);
4048       dir->mimeapps_list_removed_map = NULL;
4049     }
4050
4051   if (dir->mimeapps_list_defaults_map != NULL)
4052     {
4053       g_hash_table_destroy (dir->mimeapps_list_defaults_map);
4054       dir->mimeapps_list_defaults_map = NULL;
4055     }
4056
4057   g_free (dir);
4058 }
4059
4060 static void
4061 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir  *dir,
4062                                          const char        *mime_type,
4063                                          char             **new_desktop_file_ids)
4064 {
4065   GList *desktop_file_ids;
4066   int i;
4067
4068   desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
4069                                           mime_type);
4070
4071   for (i = 0; new_desktop_file_ids[i] != NULL; i++)
4072     {
4073       if (!g_list_find_custom (desktop_file_ids, new_desktop_file_ids[i], (GCompareFunc) strcmp))
4074         desktop_file_ids = g_list_append (desktop_file_ids,
4075                                           g_strdup (new_desktop_file_ids[i]));
4076     }
4077
4078   g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
4079 }
4080
4081 static void
4082 mime_info_cache_init_dir_lists (void)
4083 {
4084   int i;
4085
4086   mime_info_cache = mime_info_cache_new ();
4087
4088   desktop_file_dirs_refresh ();
4089
4090   for (i = 0; i < n_desktop_file_dirs; i++)
4091     {
4092       MimeInfoCacheDir *dir;
4093
4094       dir = mime_info_cache_dir_new (desktop_file_dirs[i].path);
4095
4096       if (dir != NULL)
4097         {
4098           mime_info_cache_dir_init (dir);
4099           mime_info_cache_dir_init_defaults_list (dir);
4100           mime_info_cache_dir_init_mimeapps_list (dir);
4101
4102           mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
4103         }
4104     }
4105 }
4106
4107 static void
4108 mime_info_cache_update_dir_lists (void)
4109 {
4110   GList *tmp;
4111
4112   tmp = mime_info_cache->dirs;
4113
4114   while (tmp != NULL)
4115     {
4116       MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
4117
4118       /* No need to do this if we had file monitors... */
4119       mime_info_cache_dir_init (dir);
4120       mime_info_cache_dir_init_defaults_list (dir);
4121       mime_info_cache_dir_init_mimeapps_list (dir);
4122
4123       tmp = tmp->next;
4124     }
4125 }
4126
4127 static void
4128 mime_info_cache_init (void)
4129 {
4130   G_LOCK (mime_info_cache);
4131   if (mime_info_cache == NULL)
4132     mime_info_cache_init_dir_lists ();
4133   else
4134     {
4135       time_t now;
4136
4137       time (&now);
4138       if (now >= mime_info_cache->last_stat_time + 10)
4139         {
4140           mime_info_cache_update_dir_lists ();
4141           mime_info_cache->last_stat_time = now;
4142         }
4143     }
4144
4145   G_UNLOCK (mime_info_cache);
4146 }
4147
4148 static MimeInfoCache *
4149 mime_info_cache_new (void)
4150 {
4151   MimeInfoCache *cache;
4152
4153   cache = g_new0 (MimeInfoCache, 1);
4154
4155   return cache;
4156 }
4157
4158 static void
4159 mime_info_cache_free (MimeInfoCache *cache)
4160 {
4161   if (cache == NULL)
4162     return;
4163
4164   g_list_free_full (cache->dirs, (GDestroyNotify) mime_info_cache_dir_free);
4165   g_free (cache);
4166 }
4167
4168 /**
4169  * mime_info_cache_reload:
4170  * @dir: directory path which needs reloading.
4171  *
4172  * Reload the mime information for the @dir.
4173  */
4174 static void
4175 mime_info_cache_reload (const char *dir)
4176 {
4177   /* FIXME: just reload the dir that needs reloading,
4178    * don't blow the whole cache
4179    */
4180   if (mime_info_cache != NULL)
4181     {
4182       G_LOCK (mime_info_cache);
4183       mime_info_cache_free (mime_info_cache);
4184       mime_info_cache = NULL;
4185       G_UNLOCK (mime_info_cache);
4186     }
4187 }
4188
4189 static GList *
4190 append_desktop_entry (GList      *list,
4191                       const char *desktop_entry,
4192                       GList      *removed_entries)
4193 {
4194   /* Add if not already in list, and valid */
4195   if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
4196       !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
4197     list = g_list_prepend (list, g_strdup (desktop_entry));
4198
4199   return list;
4200 }
4201
4202 /**
4203  * get_all_desktop_entries_for_mime_type:
4204  * @mime_type: a mime type.
4205  * @except: NULL or a strv list
4206  *
4207  * Returns all the desktop ids for @mime_type. The desktop files
4208  * are listed in an order so that default applications are listed before
4209  * non-default ones, and handlers for inherited mimetypes are listed
4210  * after the base ones.
4211  *
4212  * Optionally doesn't list the desktop ids given in the @except
4213  *
4214  * Returns: a #GList containing the desktop ids which claim
4215  *    to handle @mime_type.
4216  */
4217 static GList *
4218 get_all_desktop_entries_for_mime_type (const char  *base_mime_type,
4219                                        const char **except,
4220                                        gboolean     include_fallback,
4221                                        char       **explicit_default)
4222 {
4223   GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
4224   MimeInfoCacheDir *dir;
4225   char *mime_type, *default_entry = NULL;
4226   char *old_default_entry = NULL;
4227   const char *entry;
4228   char **mime_types;
4229   char **default_entries;
4230   char **removed_associations;
4231   gboolean already_found_handler;
4232   int i, j, k;
4233   GPtrArray *array;
4234   char **anc;
4235
4236   mime_info_cache_init ();
4237
4238   if (include_fallback)
4239     {
4240       /* collect all ancestors */
4241       mime_types = _g_unix_content_type_get_parents (base_mime_type);
4242       array = g_ptr_array_new ();
4243       for (i = 0; mime_types[i]; i++)
4244         g_ptr_array_add (array, mime_types[i]);
4245       g_free (mime_types);
4246       for (i = 0; i < array->len; i++)
4247         {
4248           anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4249           for (j = 0; anc[j]; j++)
4250             {
4251               for (k = 0; k < array->len; k++)
4252                 {
4253                   if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
4254                     break;
4255                 }
4256               if (k == array->len) /* not found */
4257                 g_ptr_array_add (array, g_strdup (anc[j]));
4258             }
4259           g_strfreev (anc);
4260         }
4261       g_ptr_array_add (array, NULL);
4262       mime_types = (char **)g_ptr_array_free (array, FALSE);
4263     }
4264   else
4265     {
4266       mime_types = g_malloc0 (2 * sizeof (gchar *));
4267       mime_types[0] = g_strdup (base_mime_type);
4268       mime_types[1] = NULL;
4269     }
4270
4271   G_LOCK (mime_info_cache);
4272
4273   removed_entries = NULL;
4274   desktop_entries = NULL;
4275
4276   for (i = 0; except != NULL && except[i] != NULL; i++)
4277     removed_entries = g_list_prepend (removed_entries, g_strdup (except[i]));
4278
4279   for (i = 0; mime_types[i] != NULL; i++)
4280     {
4281       mime_type = mime_types[i];
4282
4283       /* This is true if we already found a handler for a more specific
4284          mimetype. If its set we ignore any defaults for the less specific
4285          mimetypes. */
4286       already_found_handler = (desktop_entries != NULL);
4287
4288       /* Go through all apps listed in user and system dirs */
4289       for (dir_list = mime_info_cache->dirs;
4290            dir_list != NULL;
4291            dir_list = dir_list->next)
4292         {
4293           dir = dir_list->data;
4294
4295           /* Pick the explicit default application if we got no result earlier
4296            * (ie, for more specific mime types)
4297            */
4298           if (!already_found_handler)
4299             {
4300               entry = g_hash_table_lookup (dir->mimeapps_list_defaults_map, mime_type);
4301
4302               if (entry != NULL)
4303                 {
4304                   /* Save the default entry if it's the first one we encounter */
4305                   if (default_entry == NULL)
4306                     default_entry = g_strdup (entry);
4307                 }
4308             }
4309
4310           /* Then added associations from mimeapps.list */
4311           default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
4312           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4313             desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4314
4315           /* Then removed associations from mimeapps.list */
4316           removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
4317           for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
4318             removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
4319
4320           /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
4321           default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
4322           for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4323             {
4324               if (default_entry == NULL && old_default_entry == NULL && !already_found_handler)
4325                 old_default_entry = g_strdup (default_entries[j]);
4326
4327               desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4328             }
4329         }
4330
4331       /* Go through all entries that support the mimetype */
4332       for (dir_list = mime_info_cache->dirs;
4333            dir_list != NULL;
4334            dir_list = dir_list->next)
4335         {
4336           dir = dir_list->data;
4337
4338           list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
4339           for (tmp = list; tmp != NULL; tmp = tmp->next)
4340             desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
4341         }
4342     }
4343
4344   G_UNLOCK (mime_info_cache);
4345
4346   g_strfreev (mime_types);
4347
4348   /* If we have no default from mimeapps.list, take it from
4349    * defaults.list intead.
4350    *
4351    * If we do have a default from mimeapps.list, free any one that came
4352    * from defaults.list.
4353    */
4354   if (default_entry == NULL)
4355     default_entry = old_default_entry;
4356   else
4357     g_free (old_default_entry);
4358
4359   if (explicit_default != NULL)
4360     *explicit_default = default_entry;
4361   else
4362     g_free (default_entry);
4363
4364   g_list_free_full (removed_entries, g_free);
4365
4366   desktop_entries = g_list_reverse (desktop_entries);
4367
4368   return desktop_entries;
4369 }
4370
4371 /* GDesktopAppInfoLookup interface {{{2 */
4372
4373 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4374
4375 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4376 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4377
4378 static void
4379 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4380 {
4381 }
4382
4383 /* "Get for mime type" APIs {{{2 */
4384
4385 /**
4386  * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4387  * @lookup: a #GDesktopAppInfoLookup
4388  * @uri_scheme: a string containing a URI scheme.
4389  *
4390  * Gets the default application for launching applications
4391  * using this URI scheme for a particular GDesktopAppInfoLookup
4392  * implementation.
4393  *
4394  * The GDesktopAppInfoLookup interface and this function is used
4395  * to implement g_app_info_get_default_for_uri_scheme() backends
4396  * in a GIO module. There is no reason for applications to use it
4397  * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4398  *
4399  * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4400  *
4401  * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
4402  */
4403 GAppInfo *
4404 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4405                                                       const char            *uri_scheme)
4406 {
4407   GDesktopAppInfoLookupIface *iface;
4408
4409   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4410
4411   iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4412
4413   return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4414 }
4415
4416 G_GNUC_END_IGNORE_DEPRECATIONS
4417
4418 /* Misc getter APIs {{{2 */
4419
4420 /**
4421  * g_desktop_app_info_get_startup_wm_class:
4422  * @info: a #GDesktopAppInfo that supports startup notify
4423  *
4424  * Retrieves the StartupWMClass field from @info. This represents the
4425  * WM_CLASS property of the main window of the application, if launched
4426  * through @info.
4427  *
4428  * Returns: (transfer none): the startup WM class, or %NULL if none is set
4429  * in the desktop file.
4430  *
4431  * Since: 2.34
4432  */
4433 const char *
4434 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4435 {
4436   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4437
4438   return info->startup_wm_class;
4439 }
4440
4441 /**
4442  * g_desktop_app_info_get_string:
4443  * @info: a #GDesktopAppInfo
4444  * @key: the key to look up
4445  *
4446  * Looks up a string value in the keyfile backing @info.
4447  *
4448  * The @key is looked up in the "Desktop Entry" group.
4449  *
4450  * Returns: a newly allocated string, or %NULL if the key
4451  *     is not found
4452  *
4453  * Since: 2.36
4454  */
4455 char *
4456 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4457                                const char      *key)
4458 {
4459   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4460
4461   return g_key_file_get_string (info->keyfile,
4462                                 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4463 }
4464
4465 /**
4466  * g_desktop_app_info_get_boolean:
4467  * @info: a #GDesktopAppInfo
4468  * @key: the key to look up
4469  *
4470  * Looks up a boolean value in the keyfile backing @info.
4471  *
4472  * The @key is looked up in the "Desktop Entry" group.
4473  *
4474  * Returns: the boolean value, or %FALSE if the key
4475  *     is not found
4476  *
4477  * Since: 2.36
4478  */
4479 gboolean
4480 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4481                                 const char      *key)
4482 {
4483   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4484
4485   return g_key_file_get_boolean (info->keyfile,
4486                                  G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4487 }
4488
4489 /**
4490  * g_desktop_app_info_has_key:
4491  * @info: a #GDesktopAppInfo
4492  * @key: the key to look up
4493  *
4494  * Returns whether @key exists in the "Desktop Entry" group
4495  * of the keyfile backing @info.
4496  *
4497  * Returns: %TRUE if the @key exists
4498  *
4499  * Since: 2.36
4500  */
4501 gboolean
4502 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4503                             const char      *key)
4504 {
4505   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4506
4507   return g_key_file_has_key (info->keyfile,
4508                              G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4509 }
4510
4511 /* Desktop actions support {{{2 */
4512
4513 /**
4514  * g_desktop_app_info_list_actions:
4515  * @info: a #GDesktopAppInfo
4516  *
4517  * Returns the list of "additional application actions" supported on the
4518  * desktop file, as per the desktop file specification.
4519  *
4520  * As per the specification, this is the list of actions that are
4521  * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4522  *
4523  * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4524  *
4525  * Since: 2.38
4526  **/
4527 const gchar * const *
4528 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4529 {
4530   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4531
4532   return (const gchar **) info->actions;
4533 }
4534
4535 static gboolean
4536 app_info_has_action (GDesktopAppInfo *info,
4537                      const gchar     *action_name)
4538 {
4539   gint i;
4540
4541   for (i = 0; info->actions[i]; i++)
4542     if (g_str_equal (info->actions[i], action_name))
4543       return TRUE;
4544
4545   return FALSE;
4546 }
4547
4548 /**
4549  * g_desktop_app_info_get_action_name:
4550  * @info: a #GDesktopAppInfo
4551  * @action_name: the name of the action as from
4552  *   g_desktop_app_info_list_actions()
4553  *
4554  * Gets the user-visible display name of the "additional application
4555  * action" specified by @action_name.
4556  *
4557  * This corresponds to the "Name" key within the keyfile group for the
4558  * action.
4559  *
4560  * Returns: (transfer full): the locale-specific action name
4561  *
4562  * Since: 2.38
4563  */
4564 gchar *
4565 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4566                                     const gchar     *action_name)
4567 {
4568   gchar *group_name;
4569   gchar *result;
4570
4571   g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4572   g_return_val_if_fail (action_name != NULL, NULL);
4573   g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4574
4575   group_name = g_strdup_printf ("Desktop Action %s", action_name);
4576   result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4577   g_free (group_name);
4578
4579   /* The spec says that the Name field must be given.
4580    *
4581    * If it's not, let's follow the behaviour of our get_name()
4582    * implementation above and never return %NULL.
4583    */
4584   if (result == NULL)
4585     result = g_strdup (_("Unnamed"));
4586
4587   return result;
4588 }
4589
4590 /**
4591  * g_desktop_app_info_launch_action:
4592  * @info: a #GDesktopAppInfo
4593  * @action_name: the name of the action as from
4594  *   g_desktop_app_info_list_actions()
4595  * @launch_context: (allow-none): a #GAppLaunchContext
4596  *
4597  * Activates the named application action.
4598  *
4599  * You may only call this function on action names that were
4600  * returned from g_desktop_app_info_list_actions().
4601  *
4602  * Note that if the main entry of the desktop file indicates that the
4603  * application supports startup notification, and @launch_context is
4604  * non-%NULL, then startup notification will be used when activating the
4605  * action (and as such, invocation of the action on the receiving side
4606  * must signal the end of startup notification when it is completed).
4607  * This is the expected behaviour of applications declaring additional
4608  * actions, as per the desktop file specification.
4609  *
4610  * As with g_app_info_launch() there is no way to detect failures that
4611  * occur while using this function.
4612  *
4613  * Since: 2.38
4614  */
4615 void
4616 g_desktop_app_info_launch_action (GDesktopAppInfo   *info,
4617                                   const gchar       *action_name,
4618                                   GAppLaunchContext *launch_context)
4619 {
4620   GDBusConnection *session_bus;
4621
4622   g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4623   g_return_if_fail (action_name != NULL);
4624   g_return_if_fail (app_info_has_action (info, action_name));
4625
4626   session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4627
4628   if (session_bus && info->app_id)
4629     {
4630       gchar *object_path;
4631
4632       object_path = object_path_from_appid (info->app_id);
4633       g_dbus_connection_call (session_bus, info->app_id, object_path,
4634                               "org.freedesktop.Application", "ActivateAction",
4635                               g_variant_new ("(sav@a{sv})", action_name, NULL,
4636                                              g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4637                               NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4638       g_free (object_path);
4639     }
4640   else
4641     {
4642       gchar *group_name;
4643       gchar *exec_line;
4644
4645       group_name = g_strdup_printf ("Desktop Action %s", action_name);
4646       exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4647       g_free (group_name);
4648
4649       if (exec_line)
4650         g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4651                                                    _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL, NULL);
4652     }
4653
4654   if (session_bus != NULL)
4655     {
4656       g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
4657       g_object_unref (session_bus);
4658     }
4659 }
4660 /* Epilogue {{{1 */
4661
4662 /* vim:set foldmethod=marker: */