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