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