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