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