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