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