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