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