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