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