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