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