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