glib/tests: Fix non-debug build of slice test
[glib.git] / gio / gdesktopappinfo.c
blobf97ad6debd2b94f80b7debb77c0b4f5977b320a1
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
4 * Copyright © 2007 Ryan Lortie
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.
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.
16 * You should have received a copy of the GNU Lesser General
17 * Public License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19 * Boston, MA 02111-1307, USA.
21 * Author: Alexander Larsson <alexl@redhat.com>
22 * Ryan Lortie <desrt@desrt.ca>
25 /* Prelude {{{1 */
27 #include "config.h"
29 #include <errno.h>
30 #include <string.h>
31 #include <unistd.h>
33 #ifdef HAVE_CRT_EXTERNS_H
34 #include <crt_externs.h>
35 #endif
37 #include "gcontenttypeprivate.h"
38 #include "gdesktopappinfo.h"
39 #ifdef G_OS_UNIX
40 #include "glib-unix.h"
41 #endif
42 #include "gfile.h"
43 #include "gioerror.h"
44 #include "gthemedicon.h"
45 #include "gfileicon.h"
46 #include <glib/gstdio.h>
47 #include "glibintl.h"
48 #include "giomodule-priv.h"
49 #include "gappinfo.h"
50 #include "gappinfoprivate.h"
51 #include "glocaldirectorymonitor.h"
54 /**
55 * SECTION:gdesktopappinfo
56 * @title: GDesktopAppInfo
57 * @short_description: Application information from desktop files
58 * @include: gio/gdesktopappinfo.h
60 * #GDesktopAppInfo is an implementation of #GAppInfo based on
61 * desktop files.
63 * Note that <filename>&lt;gio/gdesktopappinfo.h&gt;</filename> belongs to
64 * the UNIX-specific GIO interfaces, thus you have to use the
65 * <filename>gio-unix-2.0.pc</filename> pkg-config file when using it.
68 #define DEFAULT_APPLICATIONS_GROUP "Default Applications"
69 #define ADDED_ASSOCIATIONS_GROUP "Added Associations"
70 #define REMOVED_ASSOCIATIONS_GROUP "Removed Associations"
71 #define MIME_CACHE_GROUP "MIME Cache"
72 #define GENERIC_NAME_KEY "GenericName"
73 #define FULL_NAME_KEY "X-GNOME-FullName"
74 #define KEYWORDS_KEY "Keywords"
75 #define STARTUP_WM_CLASS_KEY "StartupWMClass"
77 enum {
78 PROP_0,
79 PROP_FILENAME
82 static void g_desktop_app_info_iface_init (GAppInfoIface *iface);
83 static GList * get_all_desktop_entries_for_mime_type (const char *base_mime_type,
84 const char **except,
85 gboolean include_fallback,
86 char **explicit_default);
87 static void mime_info_cache_reload (const char *dir);
88 static gboolean g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
89 GError **error);
91 /**
92 * GDesktopAppInfo:
94 * Information about an installed application from a desktop file.
96 struct _GDesktopAppInfo
98 GObject parent_instance;
100 char *desktop_id;
101 char *filename;
102 char *app_id;
104 GKeyFile *keyfile;
106 char *name;
107 char *generic_name;
108 char *fullname;
109 char *comment;
110 char *icon_name;
111 GIcon *icon;
112 char **keywords;
113 char **only_show_in;
114 char **not_show_in;
115 char *try_exec;
116 char *exec;
117 char *binary;
118 char *path;
119 char *categories;
120 char *startup_wm_class;
121 char **mime_types;
122 char **actions;
124 guint nodisplay : 1;
125 guint hidden : 1;
126 guint terminal : 1;
127 guint startup_notify : 1;
128 guint no_fuse : 1;
131 typedef enum {
132 UPDATE_MIME_NONE = 1 << 0,
133 UPDATE_MIME_SET_DEFAULT = 1 << 1,
134 UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
135 UPDATE_MIME_REMOVE = 1 << 3,
136 UPDATE_MIME_SET_LAST_USED = 1 << 4,
137 } UpdateMimeFlags;
139 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
140 G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
142 G_LOCK_DEFINE_STATIC (g_desktop_env);
143 static gchar *g_desktop_env = NULL;
145 /* DesktopFileDir implementation {{{1 */
147 typedef struct
149 gchar *path;
150 GLocalDirectoryMonitor *monitor;
151 GHashTable *app_names;
152 gboolean is_setup;
153 GHashTable *memory_index;
154 } DesktopFileDir;
156 static DesktopFileDir *desktop_file_dirs;
157 static guint n_desktop_file_dirs;
158 static GMutex desktop_file_dir_lock;
160 /* Monitor 'changed' signal handler {{{2 */
161 static void desktop_file_dir_reset (DesktopFileDir *dir);
163 static void
164 desktop_file_dir_changed (GFileMonitor *monitor,
165 GFile *file,
166 GFile *other_file,
167 GFileMonitorEvent event_type,
168 gpointer user_data)
170 DesktopFileDir *dir = user_data;
172 /* We are not interested in receiving notifications forever just
173 * because someone asked about one desktop file once.
175 * After we receive the first notification, reset the dir, destroying
176 * the monitor. We will take this as a hint, next time that we are
177 * asked, that we need to check if everything is up to date.
179 g_mutex_lock (&desktop_file_dir_lock);
181 desktop_file_dir_reset (dir);
183 g_mutex_unlock (&desktop_file_dir_lock);
185 /* Notify anyone else who may be interested */
186 g_app_info_monitor_fire ();
189 /* Internal utility functions {{{2 */
191 /*< internal >
192 * desktop_file_dir_app_name_is_masked:
193 * @dir: a #DesktopFileDir
194 * @app_name: an application ID
196 * Checks if @app_name is masked for @dir.
198 * An application is masked if a similarly-named desktop file exists in
199 * a desktop file directory with higher precedence. Masked desktop
200 * files should be ignored.
202 static gboolean
203 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
204 const gchar *app_name)
206 while (dir > desktop_file_dirs)
208 dir--;
210 if (dir->app_names && g_hash_table_contains (dir->app_names, app_name))
211 return TRUE;
214 return FALSE;
217 /*< internal >
218 * add_to_table_if_appropriate:
219 * @apps: a string to GDesktopAppInfo hash table
220 * @app_name: the name of the application
221 * @info: a #GDesktopAppInfo, or NULL
223 * If @info is non-%NULL and non-hidden, then add it to @apps, using
224 * @app_name as a key.
226 * If @info is non-%NULL then this function will consume the passed-in
227 * reference.
229 static void
230 add_to_table_if_appropriate (GHashTable *apps,
231 const gchar *app_name,
232 GDesktopAppInfo *info)
234 if (!info)
235 return;
237 if (info->hidden)
239 g_object_unref (info);
240 return;
243 g_free (info->desktop_id);
244 info->desktop_id = g_strdup (app_name);
246 g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
249 enum
251 DESKTOP_KEY_Comment,
252 DESKTOP_KEY_GenericName,
253 DESKTOP_KEY_Keywords,
254 DESKTOP_KEY_Name,
255 DESKTOP_KEY_X_GNOME_FullName,
257 N_DESKTOP_KEYS
260 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
261 /* Note: lower numbers are a better match.
263 * In case we want two keys to match at the same level, we can just
264 * use the same number for the two different keys.
266 [DESKTOP_KEY_Name] = 1,
267 [DESKTOP_KEY_Keywords] = 2,
268 [DESKTOP_KEY_GenericName] = 3,
269 [DESKTOP_KEY_X_GNOME_FullName] = 4,
270 [DESKTOP_KEY_Comment] = 5
273 static gchar *
274 desktop_key_get_name (guint key_id)
276 switch (key_id)
278 case DESKTOP_KEY_Comment:
279 return "Comment";
280 case DESKTOP_KEY_GenericName:
281 return "GenericName";
282 case DESKTOP_KEY_Keywords:
283 return "Keywords";
284 case DESKTOP_KEY_Name:
285 return "Name";
286 case DESKTOP_KEY_X_GNOME_FullName:
287 return "X-GNOME-FullName";
288 default:
289 g_assert_not_reached ();
293 /* Search global state {{{2
295 * We only ever search under a global lock, so we can use (and reuse)
296 * some global data to reduce allocations made while searching.
298 * In short, we keep around arrays of results that we expand as needed
299 * (and never shrink).
301 * static_token_results: this is where we append the results for each
302 * token within a given desktop directory, as we handle it (which is
303 * a union of all matches for this term)
305 * static_search_results: this is where we build the complete results
306 * for a single directory (which is an intersection of the matches
307 * found for each term)
309 * static_total_results: this is where we build the complete results
310 * across all directories (which is a union of the matches found in
311 * each directory)
313 * The app_names that enter these tables are always pointer-unique (in
314 * the sense that string equality is the same as pointer equality).
315 * This can be guaranteed for two reasons:
317 * - we mask appids so that a given appid will only ever appear within
318 * the highest-precedence directory that contains it. We never
319 * return search results from a lower-level directory if a desktop
320 * file exists in a higher-level one.
322 * - within a given directory, the string is unique because it's the
323 * key in the hashtable of all app_ids for that directory.
325 * We perform a merging of the results in merge_token_results(). This
326 * works by ordering the two lists and moving through each of them (at
327 * the same time) looking for common elements, rejecting uncommon ones.
328 * "Order" here need not mean any particular thing, as long as it is
329 * some order. Because of the uniqueness of our strings, we can use
330 * pointer order. That's what's going on in compare_results() below.
332 struct search_result
334 const gchar *app_name;
335 gint category;
338 static struct search_result *static_token_results;
339 static gint static_token_results_size;
340 static gint static_token_results_allocated;
341 static struct search_result *static_search_results;
342 static gint static_search_results_size;
343 static gint static_search_results_allocated;
344 static struct search_result *static_total_results;
345 static gint static_total_results_size;
346 static gint static_total_results_allocated;
348 /* And some functions for performing nice operations against it */
349 static gint
350 compare_results (gconstpointer a,
351 gconstpointer b)
353 const struct search_result *ra = a;
354 const struct search_result *rb = b;
356 if (ra->app_name < rb->app_name)
357 return -1;
359 else if (ra->app_name > rb->app_name)
360 return 1;
362 else
363 return ra->category - rb->category;
366 static gint
367 compare_categories (gconstpointer a,
368 gconstpointer b)
370 const struct search_result *ra = a;
371 const struct search_result *rb = b;
373 return ra->category - rb->category;
376 static void
377 add_token_result (const gchar *app_name,
378 guint16 category)
380 if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
382 static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
383 static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
386 static_token_results[static_token_results_size].app_name = app_name;
387 static_token_results[static_token_results_size].category = category;
388 static_token_results_size++;
391 static void
392 merge_token_results (gboolean first)
394 qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
396 /* If this is the first token then we are basically merging a list with
397 * itself -- we only perform de-duplication.
399 * If this is not the first token then we are doing a real merge.
401 if (first)
403 const gchar *last_name = NULL;
404 gint i;
406 /* We must de-duplicate, but we do so by taking the best category
407 * in each case.
409 * The final list can be as large as the input here, so make sure
410 * we have enough room (even if it's too much room).
413 if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
415 static_search_results_allocated = static_token_results_allocated;
416 static_search_results = g_renew (struct search_result,
417 static_search_results,
418 static_search_results_allocated);
421 for (i = 0; i < static_token_results_size; i++)
423 /* The list is sorted so that the best match for a given id
424 * will be at the front, so once we have copied an id, skip
425 * the rest of the entries for the same id.
427 if (static_token_results[i].app_name == last_name)
428 continue;
430 last_name = static_token_results[i].app_name;
432 static_search_results[static_search_results_size++] = static_token_results[i];
435 else
437 const gchar *last_name = NULL;
438 gint i, j = 0;
439 gint k = 0;
441 /* We only ever remove items from the results list, so no need to
442 * resize to ensure that we have enough room.
444 for (i = 0; i < static_token_results_size; i++)
446 if (static_token_results[i].app_name == last_name)
447 continue;
449 last_name = static_token_results[i].app_name;
451 /* Now we only want to have a result in static_search_results
452 * if we already have it there *and* we have it in
453 * static_token_results as well. The category will be the
454 * lesser of the two.
456 * Skip past the results in static_search_results that are not
457 * going to be matches.
459 while (k < static_search_results_size &&
460 static_search_results[k].app_name < static_token_results[i].app_name)
461 k++;
463 if (k < static_search_results_size &&
464 static_search_results[k].app_name == static_token_results[i].app_name)
466 /* We have a match.
468 * Category should be the worse of the two (ie:
469 * numerically larger).
471 static_search_results[j].app_name = static_search_results[k].app_name;
472 static_search_results[j].category = MAX (static_search_results[k].category,
473 static_token_results[i].category);
474 j++;
478 static_search_results_size = j;
481 /* Clear it out for next time... */
482 static_token_results_size = 0;
485 static void
486 reset_total_search_results (void)
488 static_total_results_size = 0;
491 static void
492 sort_total_search_results (void)
494 qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
497 static void
498 merge_directory_results (void)
500 if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
502 static_total_results_allocated = MAX (16, static_total_results_allocated);
503 while (static_total_results_allocated < static_total_results_size + static_search_results_size)
504 static_total_results_allocated *= 2;
505 static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
508 memcpy (static_total_results + static_total_results_size,
509 static_search_results,
510 static_search_results_size * sizeof (struct search_result));
512 static_total_results_size += static_search_results_size;
514 /* Clear it out for next time... */
515 static_search_results_size = 0;
519 /* Support for unindexed DesktopFileDirs {{{2 */
520 static void
521 get_apps_from_dir (GHashTable **apps,
522 const char *dirname,
523 const char *prefix)
525 const char *basename;
526 GDir *dir;
528 dir = g_dir_open (dirname, 0, NULL);
530 if (dir == NULL)
531 return;
533 while ((basename = g_dir_read_name (dir)) != NULL)
535 gchar *filename;
537 filename = g_build_filename (dirname, basename, NULL);
539 if (g_str_has_suffix (basename, ".desktop"))
541 gchar *app_name;
543 app_name = g_strconcat (prefix, basename, NULL);
545 if (*apps == NULL)
546 *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
548 g_hash_table_insert (*apps, app_name, g_strdup (filename));
550 else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
552 gchar *subprefix;
554 subprefix = g_strconcat (prefix, basename, "-", NULL);
555 get_apps_from_dir (apps, filename, subprefix);
556 g_free (subprefix);
559 g_free (filename);
562 g_dir_close (dir);
565 static void
566 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
568 get_apps_from_dir (&dir->app_names, dir->path, "");
571 static GDesktopAppInfo *
572 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
573 const gchar *desktop_id)
575 const gchar *filename;
577 filename = g_hash_table_lookup (dir->app_names, desktop_id);
579 if (!filename)
580 return NULL;
582 return g_desktop_app_info_new_from_filename (filename);
585 static void
586 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
587 GHashTable *apps)
589 GHashTableIter iter;
590 gpointer app_name;
591 gpointer filename;
593 if (dir->app_names == NULL)
594 return;
596 g_hash_table_iter_init (&iter, dir->app_names);
597 while (g_hash_table_iter_next (&iter, &app_name, &filename))
599 if (desktop_file_dir_app_name_is_masked (dir, app_name))
600 continue;
602 add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename (filename));
606 typedef struct _MemoryIndexEntry MemoryIndexEntry;
607 typedef GHashTable MemoryIndex;
609 struct _MemoryIndexEntry
611 const gchar *app_name; /* pointer to the hashtable key */
612 gint match_category;
613 MemoryIndexEntry *next;
616 static void
617 memory_index_entry_free (gpointer data)
619 MemoryIndexEntry *mie = data;
621 while (mie)
623 MemoryIndexEntry *next = mie->next;
625 g_slice_free (MemoryIndexEntry, mie);
626 mie = next;
630 static void
631 memory_index_add_token (MemoryIndex *mi,
632 const gchar *token,
633 gint match_category,
634 const gchar *app_name)
636 MemoryIndexEntry *mie, *first;
638 mie = g_slice_new (MemoryIndexEntry);
639 mie->app_name = app_name;
640 mie->match_category = match_category;
642 first = g_hash_table_lookup (mi, token);
644 if (first)
646 mie->next = first->next;
647 first->next = mie;
649 else
651 mie->next = NULL;
652 g_hash_table_insert (mi, g_strdup (token), mie);
656 static void
657 memory_index_add_string (MemoryIndex *mi,
658 const gchar *string,
659 gint match_category,
660 const gchar *app_name)
662 gchar **tokens, **alternates;
663 gint i;
665 tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
667 for (i = 0; tokens[i]; i++)
668 memory_index_add_token (mi, tokens[i], match_category, app_name);
670 for (i = 0; alternates[i]; i++)
671 memory_index_add_token (mi, alternates[i], match_category, app_name);
673 g_strfreev (alternates);
674 g_strfreev (tokens);
677 static MemoryIndex *
678 memory_index_new (void)
680 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
683 static void
684 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
686 GHashTableIter iter;
687 gpointer app, path;
689 dir->memory_index = memory_index_new ();
691 /* Nothing to search? */
692 if (dir->app_names == NULL)
693 return;
695 g_hash_table_iter_init (&iter, dir->app_names);
696 while (g_hash_table_iter_next (&iter, &app, &path))
698 GKeyFile *key_file;
700 if (desktop_file_dir_app_name_is_masked (dir, app))
701 continue;
703 key_file = g_key_file_new ();
705 if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
706 !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
708 /* Index the interesting keys... */
709 gint i;
711 for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
713 gchar *value;
715 if (!desktop_key_match_category[i])
716 continue;
718 value = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
720 if (value)
721 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
723 g_free (value);
727 g_key_file_free (key_file);
731 static void
732 desktop_file_dir_unindexed_search (DesktopFileDir *dir,
733 const gchar *search_token)
735 GHashTableIter iter;
736 gpointer key, value;
738 if (!dir->memory_index)
739 desktop_file_dir_unindexed_setup_search (dir);
741 g_hash_table_iter_init (&iter, dir->memory_index);
742 while (g_hash_table_iter_next (&iter, &key, &value))
744 MemoryIndexEntry *mie = value;
746 if (!g_str_has_prefix (key, search_token))
747 continue;
749 while (mie)
751 add_token_result (mie->app_name, mie->match_category);
752 mie = mie->next;
757 /* DesktopFileDir "API" {{{2 */
759 /*< internal >
760 * desktop_file_dir_create:
761 * @array: the #GArray to add a new item to
762 * @data_dir: an XDG_DATA_DIR
764 * Creates a #DesktopFileDir for the corresponding @data_dir, adding it
765 * to @array.
767 static void
768 desktop_file_dir_create (GArray *array,
769 const gchar *data_dir)
771 DesktopFileDir dir = { 0, };
773 dir.path = g_build_filename (data_dir, "applications", NULL);
775 g_array_append_val (array, dir);
778 /*< internal >
779 * desktop_file_dir_reset:
780 * @dir: a #DesktopFileDir
782 * Cleans up @dir, releasing most resources that it was using.
784 static void
785 desktop_file_dir_reset (DesktopFileDir *dir)
787 if (dir->monitor)
789 g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
790 g_object_unref (dir->monitor);
791 dir->monitor = NULL;
794 if (dir->app_names)
796 g_hash_table_unref (dir->app_names);
797 dir->app_names = NULL;
800 if (dir->memory_index)
802 g_hash_table_unref (dir->memory_index);
803 dir->memory_index = NULL;
806 dir->is_setup = FALSE;
809 /*< internal >
810 * desktop_file_dir_init:
811 * @dir: a #DesktopFileDir
813 * Does initial setup for @dir
815 * You should only call this if @dir is not already setup.
817 static void
818 desktop_file_dir_init (DesktopFileDir *dir)
820 g_assert (!dir->is_setup);
822 g_assert (!dir->monitor);
823 dir->monitor = g_local_directory_monitor_new_in_worker (dir->path, G_FILE_MONITOR_NONE, NULL);
825 if (dir->monitor)
827 g_signal_connect (dir->monitor, "changed", G_CALLBACK (desktop_file_dir_changed), dir);
828 g_local_directory_monitor_start (dir->monitor);
831 desktop_file_dir_unindexed_init (dir);
833 dir->is_setup = TRUE;
836 /*< internal >
837 * desktop_file_dir_get_app:
838 * @dir: a DesktopFileDir
839 * @desktop_id: the desktop ID to load
841 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
842 * within @dir, even if it is hidden.
844 * This function does not check if @desktop_id would be masked by a
845 * directory with higher precedence. The caller must do so.
847 static GDesktopAppInfo *
848 desktop_file_dir_get_app (DesktopFileDir *dir,
849 const gchar *desktop_id)
851 if (!dir->app_names)
852 return NULL;
854 return desktop_file_dir_unindexed_get_app (dir, desktop_id);
857 /*< internal >
858 * desktop_file_dir_get_all:
859 * @dir: a DesktopFileDir
860 * @apps: a #GHashTable<string, GDesktopAppInfo>
862 * Loads all desktop files in @dir and adds them to @apps, careful to
863 * ensure we don't add any files masked by a similarly-named file in a
864 * higher-precedence directory.
866 static void
867 desktop_file_dir_get_all (DesktopFileDir *dir,
868 GHashTable *apps)
870 desktop_file_dir_unindexed_get_all (dir, apps);
873 /*< internal >
874 * desktop_file_dir_search:
875 * @dir: a #DesktopFilEDir
876 * @term: a normalised and casefolded search term
878 * Finds the names of applications in @dir that match @term.
880 static void
881 desktop_file_dir_search (DesktopFileDir *dir,
882 const gchar *search_token)
884 desktop_file_dir_unindexed_search (dir, search_token);
887 /* Lock/unlock and global setup API {{{2 */
889 static void
890 desktop_file_dirs_lock (void)
892 gint i;
894 g_mutex_lock (&desktop_file_dir_lock);
896 if (desktop_file_dirs == NULL)
898 const char * const *data_dirs;
899 GArray *tmp;
900 gint i;
902 tmp = g_array_new (FALSE, FALSE, sizeof (DesktopFileDir));
904 /* Highest priority: the user's ~/.local/share/applications */
905 desktop_file_dir_create (tmp, g_get_user_data_dir ());
907 /* Following that, XDG_DATA_DIRS/applications, in order */
908 data_dirs = g_get_system_data_dirs ();
909 for (i = 0; data_dirs[i]; i++)
910 desktop_file_dir_create (tmp, data_dirs[i]);
912 desktop_file_dirs = (DesktopFileDir *) tmp->data;
913 n_desktop_file_dirs = tmp->len;
915 g_array_free (tmp, FALSE);
918 for (i = 0; i < n_desktop_file_dirs; i++)
919 if (!desktop_file_dirs[i].is_setup)
920 desktop_file_dir_init (&desktop_file_dirs[i]);
923 static void
924 desktop_file_dirs_unlock (void)
926 g_mutex_unlock (&desktop_file_dir_lock);
929 static void
930 desktop_file_dirs_refresh (void)
932 desktop_file_dirs_lock ();
933 desktop_file_dirs_unlock ();
936 static void
937 desktop_file_dirs_invalidate_user (void)
939 g_mutex_lock (&desktop_file_dir_lock);
941 if (n_desktop_file_dirs)
942 desktop_file_dir_reset (&desktop_file_dirs[0]);
944 g_mutex_unlock (&desktop_file_dir_lock);
947 /* GDesktopAppInfo implementation {{{1 */
948 /* GObject implementation {{{2 */
949 static void
950 g_desktop_app_info_finalize (GObject *object)
952 GDesktopAppInfo *info;
954 info = G_DESKTOP_APP_INFO (object);
956 g_free (info->desktop_id);
957 g_free (info->filename);
959 if (info->keyfile)
960 g_key_file_unref (info->keyfile);
962 g_free (info->name);
963 g_free (info->generic_name);
964 g_free (info->fullname);
965 g_free (info->comment);
966 g_free (info->icon_name);
967 if (info->icon)
968 g_object_unref (info->icon);
969 g_strfreev (info->keywords);
970 g_strfreev (info->only_show_in);
971 g_strfreev (info->not_show_in);
972 g_free (info->try_exec);
973 g_free (info->exec);
974 g_free (info->binary);
975 g_free (info->path);
976 g_free (info->categories);
977 g_free (info->startup_wm_class);
978 g_strfreev (info->mime_types);
979 g_free (info->app_id);
980 g_strfreev (info->actions);
982 G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
985 static void
986 g_desktop_app_info_set_property (GObject *object,
987 guint prop_id,
988 const GValue *value,
989 GParamSpec *pspec)
991 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
993 switch (prop_id)
995 case PROP_FILENAME:
996 self->filename = g_value_dup_string (value);
997 break;
999 default:
1000 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1001 break;
1005 static void
1006 g_desktop_app_info_get_property (GObject *object,
1007 guint prop_id,
1008 GValue *value,
1009 GParamSpec *pspec)
1011 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1013 switch (prop_id)
1015 case PROP_FILENAME:
1016 g_value_set_string (value, self->filename);
1017 break;
1018 default:
1019 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1020 break;
1024 static void
1025 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1027 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1029 gobject_class->get_property = g_desktop_app_info_get_property;
1030 gobject_class->set_property = g_desktop_app_info_set_property;
1031 gobject_class->finalize = g_desktop_app_info_finalize;
1034 * GDesktopAppInfo:filename:
1036 * The origin filename of this #GDesktopAppInfo
1038 g_object_class_install_property (gobject_class,
1039 PROP_FILENAME,
1040 g_param_spec_string ("filename", "Filename", "", NULL,
1041 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1044 static void
1045 g_desktop_app_info_init (GDesktopAppInfo *local)
1049 /* Construction... {{{2 */
1051 /*< internal >
1052 * binary_from_exec:
1053 * @exec: an exec line
1055 * Returns the first word in an exec line (ie: the binary name).
1057 * If @exec is " progname --foo %F" then returns "progname".
1059 static char *
1060 binary_from_exec (const char *exec)
1062 const char *p, *start;
1064 p = exec;
1065 while (*p == ' ')
1066 p++;
1067 start = p;
1068 while (*p != ' ' && *p != 0)
1069 p++;
1071 return g_strndup (start, p - start);
1074 static gboolean
1075 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1076 GKeyFile *key_file)
1078 char *start_group;
1079 char *type;
1080 char *try_exec;
1081 char *exec;
1082 gboolean bus_activatable;
1084 start_group = g_key_file_get_start_group (key_file);
1085 if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1087 g_free (start_group);
1088 return FALSE;
1090 g_free (start_group);
1092 type = g_key_file_get_string (key_file,
1093 G_KEY_FILE_DESKTOP_GROUP,
1094 G_KEY_FILE_DESKTOP_KEY_TYPE,
1095 NULL);
1096 if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1098 g_free (type);
1099 return FALSE;
1101 g_free (type);
1103 try_exec = g_key_file_get_string (key_file,
1104 G_KEY_FILE_DESKTOP_GROUP,
1105 G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1106 NULL);
1107 if (try_exec && try_exec[0] != '\0')
1109 char *t;
1110 t = g_find_program_in_path (try_exec);
1111 if (t == NULL)
1113 g_free (try_exec);
1114 return FALSE;
1116 g_free (t);
1119 exec = g_key_file_get_string (key_file,
1120 G_KEY_FILE_DESKTOP_GROUP,
1121 G_KEY_FILE_DESKTOP_KEY_EXEC,
1122 NULL);
1123 if (exec && exec[0] != '\0')
1125 gint argc;
1126 char **argv;
1127 if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1129 g_free (exec);
1130 g_free (try_exec);
1131 return FALSE;
1133 else
1135 char *t;
1136 t = g_find_program_in_path (argv[0]);
1137 g_strfreev (argv);
1139 if (t == NULL)
1141 g_free (exec);
1142 g_free (try_exec);
1143 return FALSE;
1145 g_free (t);
1149 info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1150 info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1151 info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1152 info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1153 info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1154 info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1155 info->icon_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1156 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);
1157 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);
1158 info->try_exec = try_exec;
1159 info->exec = exec;
1160 info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1161 info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1162 info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1163 info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1164 info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1165 info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1166 info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1167 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);
1168 bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1169 info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1171 /* Remove the special-case: no Actions= key just means 0 extra actions */
1172 if (info->actions == NULL)
1173 info->actions = g_new0 (gchar *, 0 + 1);
1175 info->icon = NULL;
1176 if (info->icon_name)
1178 if (g_path_is_absolute (info->icon_name))
1180 GFile *file;
1182 file = g_file_new_for_path (info->icon_name);
1183 info->icon = g_file_icon_new (file);
1184 g_object_unref (file);
1186 else
1188 char *p;
1190 /* Work around a common mistake in desktop files */
1191 if ((p = strrchr (info->icon_name, '.')) != NULL &&
1192 (strcmp (p, ".png") == 0 ||
1193 strcmp (p, ".xpm") == 0 ||
1194 strcmp (p, ".svg") == 0))
1195 *p = 0;
1197 info->icon = g_themed_icon_new (info->icon_name);
1201 if (info->exec)
1202 info->binary = binary_from_exec (info->exec);
1204 if (info->path && info->path[0] == '\0')
1206 g_free (info->path);
1207 info->path = NULL;
1210 /* Can only be DBusActivatable if we know the filename, which means
1211 * that this won't work for the load-from-keyfile case.
1213 if (bus_activatable && info->filename)
1215 gchar *basename;
1216 gchar *last_dot;
1218 basename = g_path_get_basename (info->filename);
1219 last_dot = strrchr (basename, '.');
1221 if (last_dot && g_str_equal (last_dot, ".desktop"))
1223 *last_dot = '\0';
1225 if (g_dbus_is_interface_name (basename))
1226 info->app_id = g_strdup (basename);
1229 g_free (basename);
1232 info->keyfile = g_key_file_ref (key_file);
1234 return TRUE;
1237 static gboolean
1238 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1240 GKeyFile *key_file;
1241 gboolean retval = FALSE;
1243 g_return_val_if_fail (self->filename != NULL, FALSE);
1245 self->desktop_id = g_path_get_basename (self->filename);
1247 key_file = g_key_file_new ();
1249 if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
1250 retval = g_desktop_app_info_load_from_keyfile (self, key_file);
1252 g_key_file_unref (key_file);
1253 return retval;
1257 * g_desktop_app_info_new_from_keyfile:
1258 * @key_file: an opened #GKeyFile
1260 * Creates a new #GDesktopAppInfo.
1262 * Returns: a new #GDesktopAppInfo or %NULL on error.
1264 * Since: 2.18
1266 GDesktopAppInfo *
1267 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
1269 GDesktopAppInfo *info;
1271 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1272 info->filename = NULL;
1273 if (!g_desktop_app_info_load_from_keyfile (info, key_file))
1275 g_object_unref (info);
1276 return NULL;
1278 return info;
1282 * g_desktop_app_info_new_from_filename:
1283 * @filename: the path of a desktop file, in the GLib filename encoding
1285 * Creates a new #GDesktopAppInfo.
1287 * Returns: a new #GDesktopAppInfo or %NULL on error.
1289 GDesktopAppInfo *
1290 g_desktop_app_info_new_from_filename (const char *filename)
1292 GDesktopAppInfo *info = NULL;
1294 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1295 if (!g_desktop_app_info_load_file (info))
1297 g_object_unref (info);
1298 return NULL;
1300 return info;
1304 * g_desktop_app_info_new:
1305 * @desktop_id: the desktop file id
1307 * Creates a new #GDesktopAppInfo based on a desktop file id.
1309 * A desktop file id is the basename of the desktop file, including the
1310 * .desktop extension. GIO is looking for a desktop file with this name
1311 * in the <filename>applications</filename> subdirectories of the XDG data
1312 * directories (i.e. the directories specified in the
1313 * <envar>XDG_DATA_HOME</envar> and <envar>XDG_DATA_DIRS</envar> environment
1314 * variables). GIO also supports the prefix-to-subdirectory mapping that is
1315 * described in the <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Menu Spec</ulink>
1316 * (i.e. a desktop id of kde-foo.desktop will match
1317 * <filename>/usr/share/applications/kde/foo.desktop</filename>).
1319 * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
1321 GDesktopAppInfo *
1322 g_desktop_app_info_new (const char *desktop_id)
1324 GDesktopAppInfo *appinfo = NULL;
1325 guint i;
1327 desktop_file_dirs_lock ();
1329 for (i = 0; i < n_desktop_file_dirs; i++)
1331 appinfo = desktop_file_dir_get_app (&desktop_file_dirs[i], desktop_id);
1333 if (appinfo)
1334 break;
1337 desktop_file_dirs_unlock ();
1339 if (appinfo == NULL)
1340 return NULL;
1342 g_free (appinfo->desktop_id);
1343 appinfo->desktop_id = g_strdup (desktop_id);
1345 if (g_desktop_app_info_get_is_hidden (appinfo))
1347 g_object_unref (appinfo);
1348 appinfo = NULL;
1351 return appinfo;
1354 static GAppInfo *
1355 g_desktop_app_info_dup (GAppInfo *appinfo)
1357 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1358 GDesktopAppInfo *new_info;
1360 new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1362 new_info->filename = g_strdup (info->filename);
1363 new_info->desktop_id = g_strdup (info->desktop_id);
1365 if (info->keyfile)
1366 new_info->keyfile = g_key_file_ref (info->keyfile);
1368 new_info->name = g_strdup (info->name);
1369 new_info->generic_name = g_strdup (info->generic_name);
1370 new_info->fullname = g_strdup (info->fullname);
1371 new_info->keywords = g_strdupv (info->keywords);
1372 new_info->comment = g_strdup (info->comment);
1373 new_info->nodisplay = info->nodisplay;
1374 new_info->icon_name = g_strdup (info->icon_name);
1375 if (info->icon)
1376 new_info->icon = g_object_ref (info->icon);
1377 new_info->only_show_in = g_strdupv (info->only_show_in);
1378 new_info->not_show_in = g_strdupv (info->not_show_in);
1379 new_info->try_exec = g_strdup (info->try_exec);
1380 new_info->exec = g_strdup (info->exec);
1381 new_info->binary = g_strdup (info->binary);
1382 new_info->path = g_strdup (info->path);
1383 new_info->app_id = g_strdup (info->app_id);
1384 new_info->hidden = info->hidden;
1385 new_info->terminal = info->terminal;
1386 new_info->startup_notify = info->startup_notify;
1388 return G_APP_INFO (new_info);
1391 /* GAppInfo interface implementation functions {{{2 */
1393 static gboolean
1394 g_desktop_app_info_equal (GAppInfo *appinfo1,
1395 GAppInfo *appinfo2)
1397 GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
1398 GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
1400 if (info1->desktop_id == NULL ||
1401 info2->desktop_id == NULL)
1402 return info1 == info2;
1404 return strcmp (info1->desktop_id, info2->desktop_id) == 0;
1407 static const char *
1408 g_desktop_app_info_get_id (GAppInfo *appinfo)
1410 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1412 return info->desktop_id;
1415 static const char *
1416 g_desktop_app_info_get_name (GAppInfo *appinfo)
1418 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1420 if (info->name == NULL)
1421 return _("Unnamed");
1422 return info->name;
1425 static const char *
1426 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
1428 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1430 if (info->fullname == NULL)
1431 return g_desktop_app_info_get_name (appinfo);
1432 return info->fullname;
1436 * g_desktop_app_info_get_is_hidden:
1437 * @info: a #GDesktopAppInfo.
1439 * A desktop file is hidden if the Hidden key in it is
1440 * set to True.
1442 * Returns: %TRUE if hidden, %FALSE otherwise.
1444 gboolean
1445 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
1447 return info->hidden;
1451 * g_desktop_app_info_get_filename:
1452 * @info: a #GDesktopAppInfo
1454 * When @info was created from a known filename, return it. In some
1455 * situations such as the #GDesktopAppInfo returned from
1456 * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
1458 * Returns: The full path to the file for @info, or %NULL if not known.
1459 * Since: 2.24
1461 const char *
1462 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
1464 return info->filename;
1467 static const char *
1468 g_desktop_app_info_get_description (GAppInfo *appinfo)
1470 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1472 return info->comment;
1475 static const char *
1476 g_desktop_app_info_get_executable (GAppInfo *appinfo)
1478 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1480 return info->binary;
1483 static const char *
1484 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
1486 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1488 return info->exec;
1491 static GIcon *
1492 g_desktop_app_info_get_icon (GAppInfo *appinfo)
1494 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1496 return info->icon;
1500 * g_desktop_app_info_get_categories:
1501 * @info: a #GDesktopAppInfo
1503 * Gets the categories from the desktop file.
1505 * Returns: The unparsed Categories key from the desktop file;
1506 * i.e. no attempt is made to split it by ';' or validate it.
1508 const char *
1509 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
1511 return info->categories;
1515 * g_desktop_app_info_get_keywords:
1516 * @info: a #GDesktopAppInfo
1518 * Gets the keywords from the desktop file.
1520 * Returns: (transfer none): The value of the Keywords key
1522 * Since: 2.32
1524 const char * const *
1525 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
1527 return (const char * const *)info->keywords;
1531 * g_desktop_app_info_get_generic_name:
1532 * @info: a #GDesktopAppInfo
1534 * Gets the generic name from the destkop file.
1536 * Returns: The value of the GenericName key
1538 const char *
1539 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
1541 return info->generic_name;
1545 * g_desktop_app_info_get_nodisplay:
1546 * @info: a #GDesktopAppInfo
1548 * Gets the value of the NoDisplay key, which helps determine if the
1549 * application info should be shown in menus. See
1550 * #G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
1552 * Returns: The value of the NoDisplay key
1554 * Since: 2.30
1556 gboolean
1557 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
1559 return info->nodisplay;
1563 * g_desktop_app_info_get_show_in:
1564 * @info: a #GDesktopAppInfo
1565 * @desktop_env: a string specifying a desktop name
1567 * Checks if the application info should be shown in menus that list available
1568 * applications for a specific name of the desktop, based on the
1569 * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal> keys.
1571 * If @desktop_env is %NULL, then the name of the desktop set with
1572 * g_desktop_app_info_set_desktop_env() is used.
1574 * Note that g_app_info_should_show() for @info will include this check (with
1575 * %NULL for @desktop_env) as well as additional checks.
1577 * Returns: %TRUE if the @info should be shown in @desktop_env according to the
1578 * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal> keys, %FALSE
1579 * otherwise.
1581 * Since: 2.30
1583 gboolean
1584 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
1585 const gchar *desktop_env)
1587 gboolean found;
1588 int i;
1590 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
1592 if (!desktop_env) {
1593 G_LOCK (g_desktop_env);
1594 desktop_env = g_desktop_env;
1595 G_UNLOCK (g_desktop_env);
1598 if (info->only_show_in)
1600 if (desktop_env == NULL)
1601 return FALSE;
1603 found = FALSE;
1604 for (i = 0; info->only_show_in[i] != NULL; i++)
1606 if (strcmp (info->only_show_in[i], desktop_env) == 0)
1608 found = TRUE;
1609 break;
1612 if (!found)
1613 return FALSE;
1616 if (info->not_show_in && desktop_env)
1618 for (i = 0; info->not_show_in[i] != NULL; i++)
1620 if (strcmp (info->not_show_in[i], desktop_env) == 0)
1621 return FALSE;
1625 return TRUE;
1628 /* Launching... {{{2 */
1630 static char *
1631 expand_macro_single (char macro, char *uri)
1633 GFile *file;
1634 char *result = NULL;
1635 char *path = NULL;
1636 char *name;
1638 file = g_file_new_for_uri (uri);
1640 switch (macro)
1642 case 'u':
1643 case 'U':
1644 result = g_shell_quote (uri);
1645 break;
1646 case 'f':
1647 case 'F':
1648 path = g_file_get_path (file);
1649 if (path)
1650 result = g_shell_quote (path);
1651 break;
1652 case 'd':
1653 case 'D':
1654 path = g_file_get_path (file);
1655 if (path)
1657 name = g_path_get_dirname (path);
1658 result = g_shell_quote (name);
1659 g_free (name);
1661 break;
1662 case 'n':
1663 case 'N':
1664 path = g_file_get_path (file);
1665 if (path)
1667 name = g_path_get_basename (path);
1668 result = g_shell_quote (name);
1669 g_free (name);
1671 break;
1674 g_object_unref (file);
1675 g_free (path);
1677 return result;
1680 static void
1681 expand_macro (char macro,
1682 GString *exec,
1683 GDesktopAppInfo *info,
1684 GList **uri_list)
1686 GList *uris = *uri_list;
1687 char *expanded;
1688 gboolean force_file_uri;
1689 char force_file_uri_macro;
1690 char *uri;
1692 g_return_if_fail (exec != NULL);
1694 /* On %u and %U, pass POSIX file path pointing to the URI via
1695 * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
1696 * running or the URI doesn't have a POSIX file path via FUSE
1697 * we'll just pass the URI.
1699 force_file_uri_macro = macro;
1700 force_file_uri = FALSE;
1701 if (!info->no_fuse)
1703 switch (macro)
1705 case 'u':
1706 force_file_uri_macro = 'f';
1707 force_file_uri = TRUE;
1708 break;
1709 case 'U':
1710 force_file_uri_macro = 'F';
1711 force_file_uri = TRUE;
1712 break;
1713 default:
1714 break;
1718 switch (macro)
1720 case 'u':
1721 case 'f':
1722 case 'd':
1723 case 'n':
1724 if (uris)
1726 uri = uris->data;
1727 if (!force_file_uri ||
1728 /* Pass URI if it contains an anchor */
1729 strchr (uri, '#') != NULL)
1731 expanded = expand_macro_single (macro, uri);
1733 else
1735 expanded = expand_macro_single (force_file_uri_macro, uri);
1736 if (expanded == NULL)
1737 expanded = expand_macro_single (macro, uri);
1740 if (expanded)
1742 g_string_append (exec, expanded);
1743 g_free (expanded);
1745 uris = uris->next;
1748 break;
1750 case 'U':
1751 case 'F':
1752 case 'D':
1753 case 'N':
1754 while (uris)
1756 uri = uris->data;
1758 if (!force_file_uri ||
1759 /* Pass URI if it contains an anchor */
1760 strchr (uri, '#') != NULL)
1762 expanded = expand_macro_single (macro, uri);
1764 else
1766 expanded = expand_macro_single (force_file_uri_macro, uri);
1767 if (expanded == NULL)
1768 expanded = expand_macro_single (macro, uri);
1771 if (expanded)
1773 g_string_append (exec, expanded);
1774 g_free (expanded);
1777 uris = uris->next;
1779 if (uris != NULL && expanded)
1780 g_string_append_c (exec, ' ');
1783 break;
1785 case 'i':
1786 if (info->icon_name)
1788 g_string_append (exec, "--icon ");
1789 expanded = g_shell_quote (info->icon_name);
1790 g_string_append (exec, expanded);
1791 g_free (expanded);
1793 break;
1795 case 'c':
1796 if (info->name)
1798 expanded = g_shell_quote (info->name);
1799 g_string_append (exec, expanded);
1800 g_free (expanded);
1802 break;
1804 case 'k':
1805 if (info->filename)
1807 expanded = g_shell_quote (info->filename);
1808 g_string_append (exec, expanded);
1809 g_free (expanded);
1811 break;
1813 case 'm': /* deprecated */
1814 break;
1816 case '%':
1817 g_string_append_c (exec, '%');
1818 break;
1821 *uri_list = uris;
1824 static gboolean
1825 expand_application_parameters (GDesktopAppInfo *info,
1826 const gchar *exec_line,
1827 GList **uris,
1828 int *argc,
1829 char ***argv,
1830 GError **error)
1832 GList *uri_list = *uris;
1833 const char *p = exec_line;
1834 GString *expanded_exec;
1835 gboolean res;
1837 if (exec_line == NULL)
1839 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1840 _("Desktop file didn't specify Exec field"));
1841 return FALSE;
1844 expanded_exec = g_string_new (NULL);
1846 while (*p)
1848 if (p[0] == '%' && p[1] != '\0')
1850 expand_macro (p[1], expanded_exec, info, uris);
1851 p++;
1853 else
1854 g_string_append_c (expanded_exec, *p);
1856 p++;
1859 /* No file substitutions */
1860 if (uri_list == *uris && uri_list != NULL)
1862 /* If there is no macro default to %f. This is also what KDE does */
1863 g_string_append_c (expanded_exec, ' ');
1864 expand_macro ('f', expanded_exec, info, uris);
1867 res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
1868 g_string_free (expanded_exec, TRUE);
1869 return res;
1872 static gboolean
1873 prepend_terminal_to_vector (int *argc,
1874 char ***argv)
1876 #ifndef G_OS_WIN32
1877 char **real_argv;
1878 int real_argc;
1879 int i, j;
1880 char **term_argv = NULL;
1881 int term_argc = 0;
1882 char *check;
1883 char **the_argv;
1885 g_return_val_if_fail (argc != NULL, FALSE);
1886 g_return_val_if_fail (argv != NULL, FALSE);
1888 /* sanity */
1889 if(*argv == NULL)
1890 *argc = 0;
1892 the_argv = *argv;
1894 /* compute size if not given */
1895 if (*argc < 0)
1897 for (i = 0; the_argv[i] != NULL; i++)
1899 *argc = i;
1902 term_argc = 2;
1903 term_argv = g_new0 (char *, 3);
1905 check = g_find_program_in_path ("gnome-terminal");
1906 if (check != NULL)
1908 term_argv[0] = check;
1909 /* Note that gnome-terminal takes -x and
1910 * as -e in gnome-terminal is broken we use that. */
1911 term_argv[1] = g_strdup ("-x");
1913 else
1915 if (check == NULL)
1916 check = g_find_program_in_path ("nxterm");
1917 if (check == NULL)
1918 check = g_find_program_in_path ("color-xterm");
1919 if (check == NULL)
1920 check = g_find_program_in_path ("rxvt");
1921 if (check == NULL)
1922 check = g_find_program_in_path ("xterm");
1923 if (check == NULL)
1924 check = g_find_program_in_path ("dtterm");
1925 if (check == NULL)
1927 check = g_strdup ("xterm");
1928 g_warning ("couldn't find a terminal, falling back to xterm");
1930 term_argv[0] = check;
1931 term_argv[1] = g_strdup ("-e");
1934 real_argc = term_argc + *argc;
1935 real_argv = g_new (char *, real_argc + 1);
1937 for (i = 0; i < term_argc; i++)
1938 real_argv[i] = term_argv[i];
1940 for (j = 0; j < *argc; j++, i++)
1941 real_argv[i] = (char *)the_argv[j];
1943 real_argv[i] = NULL;
1945 g_free (*argv);
1946 *argv = real_argv;
1947 *argc = real_argc;
1949 /* we use g_free here as we sucked all the inner strings
1950 * out from it into real_argv */
1951 g_free (term_argv);
1952 return TRUE;
1953 #else
1954 return FALSE;
1955 #endif /* G_OS_WIN32 */
1958 static GList *
1959 create_files_for_uris (GList *uris)
1961 GList *res;
1962 GList *iter;
1964 res = NULL;
1966 for (iter = uris; iter; iter = iter->next)
1968 GFile *file = g_file_new_for_uri ((char *)iter->data);
1969 res = g_list_prepend (res, file);
1972 return g_list_reverse (res);
1975 typedef struct
1977 GSpawnChildSetupFunc user_setup;
1978 gpointer user_setup_data;
1980 char *pid_envvar;
1981 } ChildSetupData;
1983 static void
1984 child_setup (gpointer user_data)
1986 ChildSetupData *data = user_data;
1988 if (data->pid_envvar)
1990 pid_t pid = getpid ();
1991 char buf[20];
1992 int i;
1994 /* Write the pid into the space already reserved for it in the
1995 * environment array. We can't use sprintf because it might
1996 * malloc, so we do it by hand. It's simplest to write the pid
1997 * out backwards first, then copy it over.
1999 for (i = 0; pid; i++, pid /= 10)
2000 buf[i] = (pid % 10) + '0';
2001 for (i--; i >= 0; i--)
2002 *(data->pid_envvar++) = buf[i];
2003 *data->pid_envvar = '\0';
2006 if (data->user_setup)
2007 data->user_setup (data->user_setup_data);
2010 static void
2011 notify_desktop_launch (GDBusConnection *session_bus,
2012 GDesktopAppInfo *info,
2013 long pid,
2014 const char *display,
2015 const char *sn_id,
2016 GList *uris)
2018 GDBusMessage *msg;
2019 GVariantBuilder uri_variant;
2020 GVariantBuilder extras_variant;
2021 GList *iter;
2022 const char *desktop_file_id;
2023 const char *gio_desktop_file;
2025 if (session_bus == NULL)
2026 return;
2028 g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2029 for (iter = uris; iter; iter = iter->next)
2030 g_variant_builder_add (&uri_variant, "s", iter->data);
2032 g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2033 if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2034 g_variant_builder_add (&extras_variant, "{sv}",
2035 "startup-id",
2036 g_variant_new ("s",
2037 sn_id));
2038 gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2039 if (gio_desktop_file != NULL)
2040 g_variant_builder_add (&extras_variant, "{sv}",
2041 "origin-desktop-file",
2042 g_variant_new_bytestring (gio_desktop_file));
2043 if (g_get_prgname () != NULL)
2044 g_variant_builder_add (&extras_variant, "{sv}",
2045 "origin-prgname",
2046 g_variant_new_bytestring (g_get_prgname ()));
2047 g_variant_builder_add (&extras_variant, "{sv}",
2048 "origin-pid",
2049 g_variant_new ("x",
2050 (gint64)getpid ()));
2052 if (info->filename)
2053 desktop_file_id = info->filename;
2054 else if (info->desktop_id)
2055 desktop_file_id = info->desktop_id;
2056 else
2057 desktop_file_id = "";
2059 msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2060 "org.gtk.gio.DesktopAppInfo",
2061 "Launched");
2062 g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2063 g_variant_new_bytestring (desktop_file_id),
2064 display ? display : "",
2065 (gint64)pid,
2066 &uri_variant,
2067 &extras_variant));
2068 g_dbus_connection_send_message (session_bus,
2069 msg, 0,
2070 NULL,
2071 NULL);
2072 g_object_unref (msg);
2075 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2077 static gboolean
2078 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo *info,
2079 GDBusConnection *session_bus,
2080 const gchar *exec_line,
2081 GList *uris,
2082 GAppLaunchContext *launch_context,
2083 GSpawnFlags spawn_flags,
2084 GSpawnChildSetupFunc user_setup,
2085 gpointer user_setup_data,
2086 GDesktopAppLaunchCallback pid_callback,
2087 gpointer pid_callback_data,
2088 GError **error)
2090 gboolean completed = FALSE;
2091 GList *old_uris;
2092 char **argv, **envp;
2093 int argc;
2094 ChildSetupData data;
2096 g_return_val_if_fail (info != NULL, FALSE);
2098 argv = NULL;
2100 if (launch_context)
2101 envp = g_app_launch_context_get_environment (launch_context);
2102 else
2103 envp = g_get_environ ();
2107 GPid pid;
2108 GList *launched_uris;
2109 GList *iter;
2110 char *display, *sn_id;
2112 old_uris = uris;
2113 if (!expand_application_parameters (info, exec_line, &uris, &argc, &argv, error))
2114 goto out;
2116 /* Get the subset of URIs we're launching with this process */
2117 launched_uris = NULL;
2118 for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
2119 launched_uris = g_list_prepend (launched_uris, iter->data);
2120 launched_uris = g_list_reverse (launched_uris);
2122 if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2124 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2125 _("Unable to find terminal required for application"));
2126 goto out;
2129 data.user_setup = user_setup;
2130 data.user_setup_data = user_setup_data;
2132 if (info->filename)
2134 envp = g_environ_setenv (envp,
2135 "GIO_LAUNCHED_DESKTOP_FILE",
2136 info->filename,
2137 TRUE);
2138 envp = g_environ_setenv (envp,
2139 "GIO_LAUNCHED_DESKTOP_FILE_PID",
2140 "XXXXXXXXXXXXXXXXXXXX", /* filled in child_setup */
2141 TRUE);
2142 data.pid_envvar = (char *)g_environ_getenv (envp, "GIO_LAUNCHED_DESKTOP_FILE_PID");
2144 else
2146 data.pid_envvar = NULL;
2149 display = NULL;
2150 sn_id = NULL;
2151 if (launch_context)
2153 GList *launched_files = create_files_for_uris (launched_uris);
2155 display = g_app_launch_context_get_display (launch_context,
2156 G_APP_INFO (info),
2157 launched_files);
2158 if (display)
2159 envp = g_environ_setenv (envp, "DISPLAY", display, TRUE);
2161 if (info->startup_notify)
2163 sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2164 G_APP_INFO (info),
2165 launched_files);
2166 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2169 g_list_free_full (launched_files, g_object_unref);
2172 if (!g_spawn_async (info->path,
2173 argv,
2174 envp,
2175 spawn_flags,
2176 child_setup,
2177 &data,
2178 &pid,
2179 error))
2181 if (sn_id)
2182 g_app_launch_context_launch_failed (launch_context, sn_id);
2184 g_free (display);
2185 g_free (sn_id);
2186 g_list_free (launched_uris);
2188 goto out;
2191 if (pid_callback != NULL)
2192 pid_callback (info, pid, pid_callback_data);
2194 if (launch_context != NULL)
2196 GVariantBuilder builder;
2197 GVariant *platform_data;
2199 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2200 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2201 if (sn_id)
2202 g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2203 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2204 g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2205 g_variant_unref (platform_data);
2208 notify_desktop_launch (session_bus,
2209 info,
2210 pid,
2211 display,
2212 sn_id,
2213 launched_uris);
2215 g_free (display);
2216 g_free (sn_id);
2217 g_list_free (launched_uris);
2219 g_strfreev (argv);
2220 argv = NULL;
2222 while (uris != NULL);
2224 completed = TRUE;
2226 out:
2227 g_strfreev (argv);
2228 g_strfreev (envp);
2230 return completed;
2233 static gchar *
2234 object_path_from_appid (const gchar *app_id)
2236 gchar *path;
2237 gint i, n;
2239 n = strlen (app_id);
2240 path = g_malloc (n + 2);
2242 path[0] = '/';
2244 for (i = 0; i < n; i++)
2245 if (app_id[i] != '.')
2246 path[i + 1] = app_id[i];
2247 else
2248 path[i + 1] = '/';
2250 path[i + 1] = '\0';
2252 return path;
2255 static GVariant *
2256 g_desktop_app_info_make_platform_data (GDesktopAppInfo *info,
2257 GList *uris,
2258 GAppLaunchContext *launch_context)
2260 GVariantBuilder builder;
2262 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2264 if (launch_context)
2266 GList *launched_files = create_files_for_uris (uris);
2268 if (info->startup_notify)
2270 gchar *sn_id;
2272 sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2273 g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2276 g_list_free_full (launched_files, g_object_unref);
2279 return g_variant_builder_end (&builder);
2282 static gboolean
2283 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo *info,
2284 GDBusConnection *session_bus,
2285 GList *uris,
2286 GAppLaunchContext *launch_context)
2288 GVariantBuilder builder;
2289 gchar *object_path;
2291 g_return_val_if_fail (info != NULL, FALSE);
2293 g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2295 if (uris)
2297 GList *iter;
2299 g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2300 for (iter = uris; iter; iter = iter->next)
2301 g_variant_builder_add (&builder, "s", iter->data);
2302 g_variant_builder_close (&builder);
2305 g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2307 /* This is non-blocking API. Similar to launching via fork()/exec()
2308 * we don't wait around to see if the program crashed during startup.
2309 * This is what startup-notification's job is...
2311 object_path = object_path_from_appid (info->app_id);
2312 g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2313 uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2314 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
2315 g_free (object_path);
2317 return TRUE;
2320 static gboolean
2321 g_desktop_app_info_launch_uris_internal (GAppInfo *appinfo,
2322 GList *uris,
2323 GAppLaunchContext *launch_context,
2324 GSpawnFlags spawn_flags,
2325 GSpawnChildSetupFunc user_setup,
2326 gpointer user_setup_data,
2327 GDesktopAppLaunchCallback pid_callback,
2328 gpointer pid_callback_data,
2329 GError **error)
2331 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2332 GDBusConnection *session_bus;
2333 gboolean success = TRUE;
2335 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
2337 if (session_bus && info->app_id)
2338 g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context);
2339 else
2340 success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
2341 spawn_flags, user_setup, user_setup_data,
2342 pid_callback, pid_callback_data, error);
2344 if (session_bus != NULL)
2346 /* This asynchronous flush holds a reference until it completes,
2347 * which ensures that the following unref won't immediately kill
2348 * the connection if we were the initial owner.
2350 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
2351 g_object_unref (session_bus);
2354 return success;
2357 static gboolean
2358 g_desktop_app_info_launch_uris (GAppInfo *appinfo,
2359 GList *uris,
2360 GAppLaunchContext *launch_context,
2361 GError **error)
2363 return g_desktop_app_info_launch_uris_internal (appinfo, uris,
2364 launch_context,
2365 _SPAWN_FLAGS_DEFAULT,
2366 NULL, NULL, NULL, NULL,
2367 error);
2370 static gboolean
2371 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
2373 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2375 return info->exec &&
2376 ((strstr (info->exec, "%u") != NULL) ||
2377 (strstr (info->exec, "%U") != NULL));
2380 static gboolean
2381 g_desktop_app_info_supports_files (GAppInfo *appinfo)
2383 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2385 return info->exec &&
2386 ((strstr (info->exec, "%f") != NULL) ||
2387 (strstr (info->exec, "%F") != NULL));
2390 static gboolean
2391 g_desktop_app_info_launch (GAppInfo *appinfo,
2392 GList *files,
2393 GAppLaunchContext *launch_context,
2394 GError **error)
2396 GList *uris;
2397 char *uri;
2398 gboolean res;
2400 uris = NULL;
2401 while (files)
2403 uri = g_file_get_uri (files->data);
2404 uris = g_list_prepend (uris, uri);
2405 files = files->next;
2408 uris = g_list_reverse (uris);
2410 res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
2412 g_list_free_full (uris, g_free);
2414 return res;
2418 * g_desktop_app_info_launch_uris_as_manager:
2419 * @appinfo: a #GDesktopAppInfo
2420 * @uris: (element-type utf8): List of URIs
2421 * @launch_context: (allow-none): a #GAppLaunchContext
2422 * @spawn_flags: #GSpawnFlags, used for each process
2423 * @user_setup: (scope call) (allow-none): a #GSpawnChildSetupFunc, used once
2424 * for each process.
2425 * @user_setup_data: (closure user_setup) (allow-none): User data for @user_setup
2426 * @pid_callback: (scope call) (allow-none): Callback for child processes
2427 * @pid_callback_data: (closure pid_callback) (allow-none): User data for @callback
2428 * @error: return location for a #GError, or %NULL
2430 * This function performs the equivalent of g_app_info_launch_uris(),
2431 * but is intended primarily for operating system components that
2432 * launch applications. Ordinary applications should use
2433 * g_app_info_launch_uris().
2435 * If the application is launched via traditional UNIX fork()/exec()
2436 * then @spawn_flags, @user_setup and @user_setup_data are used for the
2437 * call to g_spawn_async(). Additionally, @pid_callback (with
2438 * @pid_callback_data) will be called to inform about the PID of the
2439 * created process.
2441 * If application launching occurs via some other mechanism (eg: D-Bus
2442 * activation) then @spawn_flags, @user_setup, @user_setup_data,
2443 * @pid_callback and @pid_callback_data are ignored.
2445 * Returns: %TRUE on successful launch, %FALSE otherwise.
2447 gboolean
2448 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo *appinfo,
2449 GList *uris,
2450 GAppLaunchContext *launch_context,
2451 GSpawnFlags spawn_flags,
2452 GSpawnChildSetupFunc user_setup,
2453 gpointer user_setup_data,
2454 GDesktopAppLaunchCallback pid_callback,
2455 gpointer pid_callback_data,
2456 GError **error)
2458 return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
2459 uris,
2460 launch_context,
2461 spawn_flags,
2462 user_setup,
2463 user_setup_data,
2464 pid_callback,
2465 pid_callback_data,
2466 error);
2469 /* OnlyShowIn API support {{{2 */
2472 * g_desktop_app_info_set_desktop_env:
2473 * @desktop_env: a string specifying what desktop this is
2475 * Sets the name of the desktop that the application is running in.
2476 * This is used by g_app_info_should_show() and
2477 * g_desktop_app_info_get_show_in() to evaluate the
2478 * <literal>OnlyShowIn</literal> and <literal>NotShowIn</literal>
2479 * desktop entry fields.
2481 * The <ulink url="http://standards.freedesktop.org/menu-spec/latest/">Desktop
2482 * Menu specification</ulink> recognizes the following:
2483 * <simplelist>
2484 * <member>GNOME</member>
2485 * <member>KDE</member>
2486 * <member>ROX</member>
2487 * <member>XFCE</member>
2488 * <member>LXDE</member>
2489 * <member>Unity</member>
2490 * <member>Old</member>
2491 * </simplelist>
2493 * Should be called only once; subsequent calls are ignored.
2495 void
2496 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
2498 G_LOCK (g_desktop_env);
2499 if (!g_desktop_env)
2500 g_desktop_env = g_strdup (desktop_env);
2501 G_UNLOCK (g_desktop_env);
2504 static gboolean
2505 g_desktop_app_info_should_show (GAppInfo *appinfo)
2507 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2509 if (info->nodisplay)
2510 return FALSE;
2512 return g_desktop_app_info_get_show_in (info, NULL);
2515 /* mime types/default apps support {{{2 */
2517 typedef enum {
2518 APP_DIR,
2519 MIMETYPE_DIR
2520 } DirType;
2522 static char *
2523 ensure_dir (DirType type,
2524 GError **error)
2526 char *path, *display_name;
2527 int errsv;
2529 if (type == APP_DIR)
2530 path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
2531 else
2532 path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
2534 errno = 0;
2535 if (g_mkdir_with_parents (path, 0700) == 0)
2536 return path;
2538 errsv = errno;
2539 display_name = g_filename_display_name (path);
2540 if (type == APP_DIR)
2541 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2542 _("Can't create user application configuration folder %s: %s"),
2543 display_name, g_strerror (errsv));
2544 else
2545 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
2546 _("Can't create user MIME configuration folder %s: %s"),
2547 display_name, g_strerror (errsv));
2549 g_free (display_name);
2550 g_free (path);
2552 return NULL;
2555 static gboolean
2556 update_mimeapps_list (const char *desktop_id,
2557 const char *content_type,
2558 UpdateMimeFlags flags,
2559 GError **error)
2561 char *dirname, *filename, *string;
2562 GKeyFile *key_file;
2563 gboolean load_succeeded, res;
2564 char **old_list, **list;
2565 gsize length, data_size;
2566 char *data;
2567 int i, j, k;
2568 char **content_types;
2570 /* Don't add both at start and end */
2571 g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
2572 (flags & UPDATE_MIME_SET_NON_DEFAULT)));
2574 dirname = ensure_dir (APP_DIR, error);
2575 if (!dirname)
2576 return FALSE;
2578 filename = g_build_filename (dirname, "mimeapps.list", NULL);
2579 g_free (dirname);
2581 key_file = g_key_file_new ();
2582 load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
2583 if (!load_succeeded ||
2584 (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
2585 !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
2586 !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
2588 g_key_file_free (key_file);
2589 key_file = g_key_file_new ();
2592 if (content_type)
2594 content_types = g_new (char *, 2);
2595 content_types[0] = g_strdup (content_type);
2596 content_types[1] = NULL;
2598 else
2600 content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
2603 for (k = 0; content_types && content_types[k]; k++)
2605 /* set as default, if requested so */
2606 string = g_key_file_get_string (key_file,
2607 DEFAULT_APPLICATIONS_GROUP,
2608 content_types[k],
2609 NULL);
2611 if (g_strcmp0 (string, desktop_id) != 0 &&
2612 (flags & UPDATE_MIME_SET_DEFAULT))
2614 g_free (string);
2615 string = g_strdup (desktop_id);
2617 /* add in the non-default list too, if it's not already there */
2618 flags |= UPDATE_MIME_SET_NON_DEFAULT;
2621 if (string == NULL || desktop_id == NULL)
2622 g_key_file_remove_key (key_file,
2623 DEFAULT_APPLICATIONS_GROUP,
2624 content_types[k],
2625 NULL);
2626 else
2627 g_key_file_set_string (key_file,
2628 DEFAULT_APPLICATIONS_GROUP,
2629 content_types[k],
2630 string);
2632 g_free (string);
2635 if (content_type)
2637 /* reuse the list from above */
2639 else
2641 g_strfreev (content_types);
2642 content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
2645 for (k = 0; content_types && content_types[k]; k++)
2647 /* Add to the right place in the list */
2649 length = 0;
2650 old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
2651 content_types[k], &length, NULL);
2653 list = g_new (char *, 1 + length + 1);
2655 i = 0;
2657 /* if we're adding a last-used hint, just put the application in front of the list */
2658 if (flags & UPDATE_MIME_SET_LAST_USED)
2660 /* avoid adding this again as non-default later */
2661 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2662 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2664 list[i++] = g_strdup (desktop_id);
2667 if (old_list)
2669 for (j = 0; old_list[j] != NULL; j++)
2671 if (g_strcmp0 (old_list[j], desktop_id) != 0)
2673 /* rewrite other entries if they're different from the new one */
2674 list[i++] = g_strdup (old_list[j]);
2676 else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2678 /* we encountered an old entry which is equal to the one we're adding as non-default,
2679 * don't change its position in the list.
2681 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
2682 list[i++] = g_strdup (old_list[j]);
2687 /* add it at the end of the list */
2688 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
2689 list[i++] = g_strdup (desktop_id);
2691 list[i] = NULL;
2693 g_strfreev (old_list);
2695 if (list[0] == NULL || desktop_id == NULL)
2696 g_key_file_remove_key (key_file,
2697 ADDED_ASSOCIATIONS_GROUP,
2698 content_types[k],
2699 NULL);
2700 else
2701 g_key_file_set_string_list (key_file,
2702 ADDED_ASSOCIATIONS_GROUP,
2703 content_types[k],
2704 (const char * const *)list, i);
2706 g_strfreev (list);
2709 if (content_type)
2711 /* reuse the list from above */
2713 else
2715 g_strfreev (content_types);
2716 content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
2719 for (k = 0; content_types && content_types[k]; k++)
2721 /* Remove from removed associations group (unless remove) */
2723 length = 0;
2724 old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
2725 content_types[k], &length, NULL);
2727 list = g_new (char *, 1 + length + 1);
2729 i = 0;
2730 if (flags & UPDATE_MIME_REMOVE)
2731 list[i++] = g_strdup (desktop_id);
2732 if (old_list)
2734 for (j = 0; old_list[j] != NULL; j++)
2736 if (g_strcmp0 (old_list[j], desktop_id) != 0)
2737 list[i++] = g_strdup (old_list[j]);
2740 list[i] = NULL;
2742 g_strfreev (old_list);
2744 if (list[0] == NULL || desktop_id == NULL)
2745 g_key_file_remove_key (key_file,
2746 REMOVED_ASSOCIATIONS_GROUP,
2747 content_types[k],
2748 NULL);
2749 else
2750 g_key_file_set_string_list (key_file,
2751 REMOVED_ASSOCIATIONS_GROUP,
2752 content_types[k],
2753 (const char * const *)list, i);
2755 g_strfreev (list);
2758 g_strfreev (content_types);
2760 data = g_key_file_to_data (key_file, &data_size, error);
2761 g_key_file_free (key_file);
2763 res = g_file_set_contents (filename, data, data_size, error);
2765 mime_info_cache_reload (NULL);
2767 g_free (filename);
2768 g_free (data);
2770 return res;
2773 static gboolean
2774 g_desktop_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
2775 const char *content_type,
2776 GError **error)
2778 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2780 if (!g_desktop_app_info_ensure_saved (info, error))
2781 return FALSE;
2783 if (!info->desktop_id)
2785 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2786 _("Application information lacks an identifier"));
2787 return FALSE;
2790 /* both add support for the content type and set as last used */
2791 return update_mimeapps_list (info->desktop_id, content_type,
2792 UPDATE_MIME_SET_NON_DEFAULT |
2793 UPDATE_MIME_SET_LAST_USED,
2794 error);
2797 static gboolean
2798 g_desktop_app_info_set_as_default_for_type (GAppInfo *appinfo,
2799 const char *content_type,
2800 GError **error)
2802 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2804 if (!g_desktop_app_info_ensure_saved (info, error))
2805 return FALSE;
2807 if (!info->desktop_id)
2809 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2810 _("Application information lacks an identifier"));
2811 return FALSE;
2814 return update_mimeapps_list (info->desktop_id, content_type,
2815 UPDATE_MIME_SET_DEFAULT,
2816 error);
2819 static void
2820 update_program_done (GPid pid,
2821 gint status,
2822 gpointer data)
2824 /* Did the application exit correctly */
2825 if (g_spawn_check_exit_status (status, NULL))
2827 /* Here we could clean out any caches in use */
2831 static void
2832 run_update_command (char *command,
2833 char *subdir)
2835 char *argv[3] = {
2836 NULL,
2837 NULL,
2838 NULL,
2840 GPid pid = 0;
2841 GError *error = NULL;
2843 argv[0] = command;
2844 argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
2846 if (g_spawn_async ("/", argv,
2847 NULL, /* envp */
2848 G_SPAWN_SEARCH_PATH |
2849 G_SPAWN_STDOUT_TO_DEV_NULL |
2850 G_SPAWN_STDERR_TO_DEV_NULL |
2851 G_SPAWN_DO_NOT_REAP_CHILD,
2852 NULL, NULL, /* No setup function */
2853 &pid,
2854 &error))
2855 g_child_watch_add (pid, update_program_done, NULL);
2856 else
2858 /* If we get an error at this point, it's quite likely the user doesn't
2859 * have an installed copy of either 'update-mime-database' or
2860 * 'update-desktop-database'. I don't think we want to popup an error
2861 * dialog at this point, so we just do a g_warning to give the user a
2862 * chance of debugging it.
2864 g_warning ("%s", error->message);
2867 g_free (argv[1]);
2870 static gboolean
2871 g_desktop_app_info_set_as_default_for_extension (GAppInfo *appinfo,
2872 const char *extension,
2873 GError **error)
2875 char *filename, *basename, *mimetype;
2876 char *dirname;
2877 gboolean res;
2879 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
2880 return FALSE;
2882 dirname = ensure_dir (MIMETYPE_DIR, error);
2883 if (!dirname)
2884 return FALSE;
2886 basename = g_strdup_printf ("user-extension-%s.xml", extension);
2887 filename = g_build_filename (dirname, basename, NULL);
2888 g_free (basename);
2889 g_free (dirname);
2891 mimetype = g_strdup_printf ("application/x-extension-%s", extension);
2893 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
2895 char *contents;
2897 contents =
2898 g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2899 "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
2900 " <mime-type type=\"%s\">\n"
2901 " <comment>%s document</comment>\n"
2902 " <glob pattern=\"*.%s\"/>\n"
2903 " </mime-type>\n"
2904 "</mime-info>\n", mimetype, extension, extension);
2906 g_file_set_contents (filename, contents, -1, NULL);
2907 g_free (contents);
2909 run_update_command ("update-mime-database", "mime");
2911 g_free (filename);
2913 res = g_desktop_app_info_set_as_default_for_type (appinfo,
2914 mimetype,
2915 error);
2917 g_free (mimetype);
2919 return res;
2922 static gboolean
2923 g_desktop_app_info_add_supports_type (GAppInfo *appinfo,
2924 const char *content_type,
2925 GError **error)
2927 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2929 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2930 return FALSE;
2932 return update_mimeapps_list (info->desktop_id, content_type,
2933 UPDATE_MIME_SET_NON_DEFAULT,
2934 error);
2937 static gboolean
2938 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
2940 return TRUE;
2943 static gboolean
2944 g_desktop_app_info_remove_supports_type (GAppInfo *appinfo,
2945 const char *content_type,
2946 GError **error)
2948 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2950 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
2951 return FALSE;
2953 return update_mimeapps_list (info->desktop_id, content_type,
2954 UPDATE_MIME_REMOVE,
2955 error);
2958 static const char **
2959 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
2961 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2963 return (const char**) info->mime_types;
2966 /* Saving and deleting {{{2 */
2968 static gboolean
2969 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
2970 GError **error)
2972 GKeyFile *key_file;
2973 char *dirname;
2974 char *filename;
2975 char *data, *desktop_id;
2976 gsize data_size;
2977 int fd;
2978 gboolean res;
2980 if (info->filename != NULL)
2981 return TRUE;
2983 /* This is only used for object created with
2984 * g_app_info_create_from_commandline. All other
2985 * object should have a filename
2988 dirname = ensure_dir (APP_DIR, error);
2989 if (!dirname)
2990 return FALSE;
2992 key_file = g_key_file_new ();
2994 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
2995 "Encoding", "UTF-8");
2996 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
2997 G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
2998 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
2999 G_KEY_FILE_DESKTOP_KEY_TYPE,
3000 G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3001 if (info->terminal)
3002 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3003 G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3004 if (info->nodisplay)
3005 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3006 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3008 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3009 G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3011 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3012 G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3014 if (info->generic_name != NULL)
3015 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3016 GENERIC_NAME_KEY, info->generic_name);
3018 if (info->fullname != NULL)
3019 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3020 FULL_NAME_KEY, info->fullname);
3022 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3023 G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3025 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3026 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3028 data = g_key_file_to_data (key_file, &data_size, NULL);
3029 g_key_file_free (key_file);
3031 desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3032 filename = g_build_filename (dirname, desktop_id, NULL);
3033 g_free (desktop_id);
3034 g_free (dirname);
3036 fd = g_mkstemp (filename);
3037 if (fd == -1)
3039 char *display_name;
3041 display_name = g_filename_display_name (filename);
3042 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3043 _("Can't create user desktop file %s"), display_name);
3044 g_free (display_name);
3045 g_free (filename);
3046 g_free (data);
3047 return FALSE;
3050 desktop_id = g_path_get_basename (filename);
3052 /* FIXME - actually handle error */
3053 (void) g_close (fd, NULL);
3055 res = g_file_set_contents (filename, data, data_size, error);
3056 g_free (data);
3057 if (!res)
3059 g_free (desktop_id);
3060 g_free (filename);
3061 return FALSE;
3064 info->filename = filename;
3065 info->desktop_id = desktop_id;
3067 run_update_command ("update-desktop-database", "applications");
3069 /* We just dropped a file in the user's desktop file directory. Save
3070 * the monitor the bother of having to notice it and invalidate
3071 * immediately.
3073 * This means that calls directly following this will be able to see
3074 * the results immediately.
3076 desktop_file_dirs_invalidate_user ();
3078 return TRUE;
3081 static gboolean
3082 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3084 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3086 if (info->filename)
3088 if (strstr (info->filename, "/userapp-"))
3089 return g_access (info->filename, W_OK) == 0;
3092 return FALSE;
3095 static gboolean
3096 g_desktop_app_info_delete (GAppInfo *appinfo)
3098 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3100 if (info->filename)
3102 if (g_remove (info->filename) == 0)
3104 update_mimeapps_list (info->desktop_id, NULL,
3105 UPDATE_MIME_NONE,
3106 NULL);
3108 g_free (info->filename);
3109 info->filename = NULL;
3110 g_free (info->desktop_id);
3111 info->desktop_id = NULL;
3113 return TRUE;
3117 return FALSE;
3120 /* Create for commandline {{{2 */
3122 * g_app_info_create_from_commandline:
3123 * @commandline: the commandline to use
3124 * @application_name: (allow-none): the application name, or %NULL to use @commandline
3125 * @flags: flags that can specify details of the created #GAppInfo
3126 * @error: a #GError location to store the error occurring, %NULL to ignore.
3128 * Creates a new #GAppInfo from the given information.
3130 * Note that for @commandline, the quoting rules of the Exec key of the
3131 * <ulink url="http://freedesktop.org/Standards/desktop-entry-spec">freedesktop.org Desktop
3132 * Entry Specification</ulink> are applied. For example, if the @commandline contains
3133 * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
3134 * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
3136 * Returns: (transfer full): new #GAppInfo for given command.
3138 GAppInfo *
3139 g_app_info_create_from_commandline (const char *commandline,
3140 const char *application_name,
3141 GAppInfoCreateFlags flags,
3142 GError **error)
3144 char **split;
3145 char *basename;
3146 GDesktopAppInfo *info;
3148 g_return_val_if_fail (commandline, NULL);
3150 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
3152 info->filename = NULL;
3153 info->desktop_id = NULL;
3155 info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
3156 info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
3157 info->hidden = FALSE;
3158 if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
3159 info->exec = g_strconcat (commandline, " %u", NULL);
3160 else
3161 info->exec = g_strconcat (commandline, " %f", NULL);
3162 info->nodisplay = TRUE;
3163 info->binary = binary_from_exec (info->exec);
3165 if (application_name)
3166 info->name = g_strdup (application_name);
3167 else
3169 /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
3170 split = g_strsplit (commandline, " ", 2);
3171 basename = split[0] ? g_path_get_basename (split[0]) : NULL;
3172 g_strfreev (split);
3173 info->name = basename;
3174 if (info->name == NULL)
3175 info->name = g_strdup ("custom");
3177 info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
3179 return G_APP_INFO (info);
3182 /* GAppInfo interface init */
3184 static void
3185 g_desktop_app_info_iface_init (GAppInfoIface *iface)
3187 iface->dup = g_desktop_app_info_dup;
3188 iface->equal = g_desktop_app_info_equal;
3189 iface->get_id = g_desktop_app_info_get_id;
3190 iface->get_name = g_desktop_app_info_get_name;
3191 iface->get_description = g_desktop_app_info_get_description;
3192 iface->get_executable = g_desktop_app_info_get_executable;
3193 iface->get_icon = g_desktop_app_info_get_icon;
3194 iface->launch = g_desktop_app_info_launch;
3195 iface->supports_uris = g_desktop_app_info_supports_uris;
3196 iface->supports_files = g_desktop_app_info_supports_files;
3197 iface->launch_uris = g_desktop_app_info_launch_uris;
3198 iface->should_show = g_desktop_app_info_should_show;
3199 iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
3200 iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
3201 iface->add_supports_type = g_desktop_app_info_add_supports_type;
3202 iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
3203 iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
3204 iface->can_delete = g_desktop_app_info_can_delete;
3205 iface->do_delete = g_desktop_app_info_delete;
3206 iface->get_commandline = g_desktop_app_info_get_commandline;
3207 iface->get_display_name = g_desktop_app_info_get_display_name;
3208 iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
3209 iface->get_supported_types = g_desktop_app_info_get_supported_types;
3212 /* Recommended applications {{{2 */
3214 static gboolean
3215 app_info_in_list (GAppInfo *info,
3216 GList *list)
3218 while (list != NULL)
3220 if (g_app_info_equal (info, list->data))
3221 return TRUE;
3222 list = list->next;
3224 return FALSE;
3228 * g_app_info_get_recommended_for_type:
3229 * @content_type: the content type to find a #GAppInfo for
3231 * Gets a list of recommended #GAppInfos for a given content type, i.e.
3232 * those applications which claim to support the given content type exactly,
3233 * and not by MIME type subclassing.
3234 * Note that the first application of the list is the last used one, i.e.
3235 * the last one for which g_app_info_set_as_last_used_for_type() has been
3236 * called.
3238 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3239 * for given @content_type or %NULL on error.
3241 * Since: 2.28
3243 GList *
3244 g_app_info_get_recommended_for_type (const gchar *content_type)
3246 GList *desktop_entries, *l;
3247 GList *infos;
3248 GDesktopAppInfo *info;
3250 g_return_val_if_fail (content_type != NULL, NULL);
3252 desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, FALSE, NULL);
3254 infos = NULL;
3255 for (l = desktop_entries; l != NULL; l = l->next)
3257 char *desktop_entry = l->data;
3259 info = g_desktop_app_info_new (desktop_entry);
3260 if (info)
3262 if (app_info_in_list (G_APP_INFO (info), infos))
3263 g_object_unref (info);
3264 else
3265 infos = g_list_prepend (infos, info);
3267 g_free (desktop_entry);
3270 g_list_free (desktop_entries);
3272 return g_list_reverse (infos);
3276 * g_app_info_get_fallback_for_type:
3277 * @content_type: the content type to find a #GAppInfo for
3279 * Gets a list of fallback #GAppInfos for a given content type, i.e.
3280 * those applications which claim to support the given content type
3281 * by MIME type subclassing and not directly.
3283 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3284 * for given @content_type or %NULL on error.
3286 * Since: 2.28
3288 GList *
3289 g_app_info_get_fallback_for_type (const gchar *content_type)
3291 GList *desktop_entries, *l;
3292 GList *infos, *recommended_infos;
3293 GDesktopAppInfo *info;
3295 g_return_val_if_fail (content_type != NULL, NULL);
3297 desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, NULL);
3298 recommended_infos = g_app_info_get_recommended_for_type (content_type);
3300 infos = NULL;
3301 for (l = desktop_entries; l != NULL; l = l->next)
3303 char *desktop_entry = l->data;
3305 info = g_desktop_app_info_new (desktop_entry);
3306 if (info)
3308 if (app_info_in_list (G_APP_INFO (info), infos) ||
3309 app_info_in_list (G_APP_INFO (info), recommended_infos))
3310 g_object_unref (info);
3311 else
3312 infos = g_list_prepend (infos, info);
3314 g_free (desktop_entry);
3317 g_list_free (desktop_entries);
3318 g_list_free_full (recommended_infos, g_object_unref);
3320 return g_list_reverse (infos);
3324 * g_app_info_get_all_for_type:
3325 * @content_type: the content type to find a #GAppInfo for
3327 * Gets a list of all #GAppInfos for a given content type,
3328 * including the recommended and fallback #GAppInfos. See
3329 * g_app_info_get_recommended_for_type() and
3330 * g_app_info_get_fallback_for_type().
3332 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3333 * for given @content_type or %NULL on error.
3335 GList *
3336 g_app_info_get_all_for_type (const char *content_type)
3338 GList *desktop_entries, *l;
3339 GList *infos;
3340 char *user_default = NULL;
3341 GDesktopAppInfo *info;
3343 g_return_val_if_fail (content_type != NULL, NULL);
3345 desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3346 infos = NULL;
3348 /* put the user default in front of the list, for compatibility */
3349 if (user_default != NULL)
3351 info = g_desktop_app_info_new (user_default);
3353 if (info != NULL)
3354 infos = g_list_prepend (infos, info);
3357 g_free (user_default);
3359 for (l = desktop_entries; l != NULL; l = l->next)
3361 char *desktop_entry = l->data;
3363 info = g_desktop_app_info_new (desktop_entry);
3364 if (info)
3366 if (app_info_in_list (G_APP_INFO (info), infos))
3367 g_object_unref (info);
3368 else
3369 infos = g_list_prepend (infos, info);
3371 g_free (desktop_entry);
3374 g_list_free (desktop_entries);
3376 return g_list_reverse (infos);
3380 * g_app_info_reset_type_associations:
3381 * @content_type: a content type
3383 * Removes all changes to the type associations done by
3384 * g_app_info_set_as_default_for_type(),
3385 * g_app_info_set_as_default_for_extension(),
3386 * g_app_info_add_supports_type() or
3387 * g_app_info_remove_supports_type().
3389 * Since: 2.20
3391 void
3392 g_app_info_reset_type_associations (const char *content_type)
3394 update_mimeapps_list (NULL, content_type,
3395 UPDATE_MIME_NONE,
3396 NULL);
3400 * g_app_info_get_default_for_type:
3401 * @content_type: the content type to find a #GAppInfo for
3402 * @must_support_uris: if %TRUE, the #GAppInfo is expected to
3403 * support URIs
3405 * Gets the default #GAppInfo for a given content type.
3407 * Returns: (transfer full): #GAppInfo for given @content_type or
3408 * %NULL on error.
3410 GAppInfo *
3411 g_app_info_get_default_for_type (const char *content_type,
3412 gboolean must_support_uris)
3414 GList *desktop_entries, *l;
3415 char *user_default = NULL;
3416 GAppInfo *info;
3418 g_return_val_if_fail (content_type != NULL, NULL);
3420 desktop_entries = get_all_desktop_entries_for_mime_type (content_type, NULL, TRUE, &user_default);
3422 info = NULL;
3424 if (user_default != NULL)
3426 info = (GAppInfo *) g_desktop_app_info_new (user_default);
3428 if (info)
3430 if (must_support_uris && !g_app_info_supports_uris (info))
3432 g_object_unref (info);
3433 info = NULL;
3438 g_free (user_default);
3440 if (info != NULL)
3442 g_list_free_full (desktop_entries, g_free);
3443 return info;
3446 /* pick the first from the other list that matches our URI
3447 * requirements.
3449 for (l = desktop_entries; l != NULL; l = l->next)
3451 char *desktop_entry = l->data;
3453 info = (GAppInfo *)g_desktop_app_info_new (desktop_entry);
3454 if (info)
3456 if (must_support_uris && !g_app_info_supports_uris (info))
3458 g_object_unref (info);
3459 info = NULL;
3461 else
3462 break;
3466 g_list_free_full (desktop_entries, g_free);
3468 return info;
3472 * g_app_info_get_default_for_uri_scheme:
3473 * @uri_scheme: a string containing a URI scheme.
3475 * Gets the default application for handling URIs with
3476 * the given URI scheme. A URI scheme is the initial part
3477 * of the URI, up to but not including the ':', e.g. "http",
3478 * "ftp" or "sip".
3480 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
3482 GAppInfo *
3483 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
3485 GAppInfo *app_info;
3486 char *content_type, *scheme_down;
3488 scheme_down = g_ascii_strdown (uri_scheme, -1);
3489 content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
3490 g_free (scheme_down);
3491 app_info = g_app_info_get_default_for_type (content_type, FALSE);
3492 g_free (content_type);
3494 return app_info;
3497 /* "Get all" API {{{2 */
3500 * g_desktop_app_info_search:
3501 * @search_string: the search string to use
3503 * Searches desktop files for ones that match @search_string.
3505 * The return value is an array of strvs. Each strv contains a list of
3506 * applications that matched @search_string with an equal score. The
3507 * outer list is sorted by score so that the first strv contains the
3508 * best-matching applications, and so on.
3509 * The algorithm for determining matches is undefined and may change at
3510 * any time.
3512 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
3513 * list of strvs. Free each item with g_strfreev() and free the outer
3514 * list with g_free().
3516 gchar ***
3517 g_desktop_app_info_search (const gchar *search_string)
3519 gchar **search_tokens;
3520 gint last_category = -1;
3521 gchar ***results;
3522 gint n_categories = 0;
3523 gint start_of_category;
3524 gint i, j;
3526 search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
3528 desktop_file_dirs_lock ();
3530 reset_total_search_results ();
3532 for (i = 0; i < n_desktop_file_dirs; i++)
3534 for (j = 0; search_tokens[j]; j++)
3536 desktop_file_dir_search (&desktop_file_dirs[i], search_tokens[j]);
3537 merge_token_results (j == 0);
3539 merge_directory_results ();
3542 sort_total_search_results ();
3544 /* Count the total number of unique categories */
3545 for (i = 0; i < static_total_results_size; i++)
3546 if (static_total_results[i].category != last_category)
3548 last_category = static_total_results[i].category;
3549 n_categories++;
3552 results = g_new (gchar **, n_categories + 1);
3554 /* Start loading into the results list */
3555 start_of_category = 0;
3556 for (i = 0; i < n_categories; i++)
3558 gint n_items_in_category = 0;
3559 gint this_category;
3560 gint j;
3562 this_category = static_total_results[start_of_category].category;
3564 while (start_of_category + n_items_in_category < static_total_results_size &&
3565 static_total_results[start_of_category + n_items_in_category].category == this_category)
3566 n_items_in_category++;
3568 results[i] = g_new (gchar *, n_items_in_category + 1);
3569 for (j = 0; j < n_items_in_category; j++)
3570 results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
3571 results[i][j] = NULL;
3573 start_of_category += n_items_in_category;
3575 results[i] = NULL;
3577 desktop_file_dirs_unlock ();
3579 g_strfreev (search_tokens);
3581 return results;
3585 * g_app_info_get_all:
3587 * Gets a list of all of the applications currently registered
3588 * on this system.
3590 * For desktop files, this includes applications that have
3591 * <literal>NoDisplay=true</literal> set or are excluded from
3592 * display by means of <literal>OnlyShowIn</literal> or
3593 * <literal>NotShowIn</literal>. See g_app_info_should_show().
3594 * The returned list does not include applications which have
3595 * the <literal>Hidden</literal> key set.
3597 * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfo<!---->s.
3599 GList *
3600 g_app_info_get_all (void)
3602 GHashTable *apps;
3603 GHashTableIter iter;
3604 gpointer value;
3605 int i;
3606 GList *infos;
3608 apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
3610 desktop_file_dirs_lock ();
3612 for (i = 0; i < n_desktop_file_dirs; i++)
3613 desktop_file_dir_get_all (&desktop_file_dirs[i], apps);
3615 desktop_file_dirs_unlock ();
3617 infos = NULL;
3618 g_hash_table_iter_init (&iter, apps);
3619 while (g_hash_table_iter_next (&iter, NULL, &value))
3621 if (value)
3622 infos = g_list_prepend (infos, value);
3625 g_hash_table_destroy (apps);
3627 return infos;
3630 /* Caching of mimeinfo.cache and defaults.list files {{{2 */
3632 typedef struct {
3633 char *path;
3634 GHashTable *mime_info_cache_map;
3635 GHashTable *defaults_list_map;
3636 GHashTable *mimeapps_list_added_map;
3637 GHashTable *mimeapps_list_removed_map;
3638 GHashTable *mimeapps_list_defaults_map;
3639 time_t mime_info_cache_timestamp;
3640 time_t defaults_list_timestamp;
3641 time_t mimeapps_list_timestamp;
3642 } MimeInfoCacheDir;
3644 typedef struct {
3645 GList *dirs; /* mimeinfo.cache and defaults.list */
3646 time_t last_stat_time;
3647 } MimeInfoCache;
3649 static MimeInfoCache *mime_info_cache = NULL;
3650 G_LOCK_DEFINE_STATIC (mime_info_cache);
3652 static void mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir *dir,
3653 const char *mime_type,
3654 char **new_desktop_file_ids);
3656 static MimeInfoCache * mime_info_cache_new (void);
3658 static void
3659 destroy_info_cache_value (gpointer key,
3660 GList *value,
3661 gpointer data)
3663 g_list_free_full (value, g_free);
3666 static void
3667 destroy_info_cache_map (GHashTable *info_cache_map)
3669 g_hash_table_foreach (info_cache_map, (GHFunc)destroy_info_cache_value, NULL);
3670 g_hash_table_destroy (info_cache_map);
3673 static gboolean
3674 mime_info_cache_dir_out_of_date (MimeInfoCacheDir *dir,
3675 const char *cache_file,
3676 time_t *timestamp)
3678 struct stat buf;
3679 char *filename;
3681 filename = g_build_filename (dir->path, cache_file, NULL);
3683 if (g_stat (filename, &buf) < 0)
3685 g_free (filename);
3686 return TRUE;
3688 g_free (filename);
3690 if (buf.st_mtime != *timestamp)
3691 return TRUE;
3693 return FALSE;
3696 /* Call with lock held */
3697 static void
3698 mime_info_cache_dir_init (MimeInfoCacheDir *dir)
3700 GError *load_error;
3701 GKeyFile *key_file;
3702 gchar *filename, **mime_types;
3703 int i;
3704 struct stat buf;
3706 load_error = NULL;
3707 mime_types = NULL;
3709 if (dir->mime_info_cache_map != NULL &&
3710 !mime_info_cache_dir_out_of_date (dir, "mimeinfo.cache",
3711 &dir->mime_info_cache_timestamp))
3712 return;
3714 if (dir->mime_info_cache_map != NULL)
3715 destroy_info_cache_map (dir->mime_info_cache_map);
3717 dir->mime_info_cache_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3718 (GDestroyNotify) g_free,
3719 NULL);
3721 key_file = g_key_file_new ();
3723 filename = g_build_filename (dir->path, "mimeinfo.cache", NULL);
3725 if (g_stat (filename, &buf) < 0)
3726 goto error;
3728 dir->mime_info_cache_timestamp = buf.st_mtime;
3730 g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3732 g_free (filename);
3733 filename = NULL;
3735 if (load_error != NULL)
3736 goto error;
3738 mime_types = g_key_file_get_keys (key_file, MIME_CACHE_GROUP,
3739 NULL, &load_error);
3741 if (load_error != NULL)
3742 goto error;
3744 for (i = 0; mime_types[i] != NULL; i++)
3746 gchar **desktop_file_ids;
3747 char *unaliased_type;
3748 desktop_file_ids = g_key_file_get_string_list (key_file,
3749 MIME_CACHE_GROUP,
3750 mime_types[i],
3751 NULL,
3752 NULL);
3754 if (desktop_file_ids == NULL)
3755 continue;
3757 unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3758 mime_info_cache_dir_add_desktop_entries (dir,
3759 unaliased_type,
3760 desktop_file_ids);
3761 g_free (unaliased_type);
3763 g_strfreev (desktop_file_ids);
3766 g_strfreev (mime_types);
3767 g_key_file_free (key_file);
3769 return;
3770 error:
3771 g_free (filename);
3772 g_key_file_free (key_file);
3774 if (mime_types != NULL)
3775 g_strfreev (mime_types);
3777 if (load_error)
3778 g_error_free (load_error);
3781 static void
3782 mime_info_cache_dir_init_defaults_list (MimeInfoCacheDir *dir)
3784 GKeyFile *key_file;
3785 GError *load_error;
3786 gchar *filename, **mime_types;
3787 char *unaliased_type;
3788 char **desktop_file_ids;
3789 int i;
3790 struct stat buf;
3792 load_error = NULL;
3793 mime_types = NULL;
3795 if (dir->defaults_list_map != NULL &&
3796 !mime_info_cache_dir_out_of_date (dir, "defaults.list",
3797 &dir->defaults_list_timestamp))
3798 return;
3800 if (dir->defaults_list_map != NULL)
3801 g_hash_table_destroy (dir->defaults_list_map);
3802 dir->defaults_list_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3803 g_free, (GDestroyNotify)g_strfreev);
3806 key_file = g_key_file_new ();
3808 filename = g_build_filename (dir->path, "defaults.list", NULL);
3809 if (g_stat (filename, &buf) < 0)
3810 goto error;
3812 dir->defaults_list_timestamp = buf.st_mtime;
3814 g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3815 g_free (filename);
3816 filename = NULL;
3818 if (load_error != NULL)
3819 goto error;
3821 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3822 NULL, NULL);
3823 if (mime_types != NULL)
3825 for (i = 0; mime_types[i] != NULL; i++)
3827 desktop_file_ids = g_key_file_get_string_list (key_file,
3828 DEFAULT_APPLICATIONS_GROUP,
3829 mime_types[i],
3830 NULL,
3831 NULL);
3832 if (desktop_file_ids == NULL)
3833 continue;
3835 unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3836 g_hash_table_replace (dir->defaults_list_map,
3837 unaliased_type,
3838 desktop_file_ids);
3841 g_strfreev (mime_types);
3844 g_key_file_free (key_file);
3845 return;
3847 error:
3848 g_free (filename);
3849 g_key_file_free (key_file);
3851 if (mime_types != NULL)
3852 g_strfreev (mime_types);
3854 if (load_error)
3855 g_error_free (load_error);
3858 static void
3859 mime_info_cache_dir_init_mimeapps_list (MimeInfoCacheDir *dir)
3861 GKeyFile *key_file;
3862 GError *load_error;
3863 gchar *filename, **mime_types;
3864 char *unaliased_type;
3865 char **desktop_file_ids;
3866 char *desktop_id;
3867 int i;
3868 struct stat buf;
3870 load_error = NULL;
3871 mime_types = NULL;
3873 if (dir->mimeapps_list_added_map != NULL &&
3874 !mime_info_cache_dir_out_of_date (dir, "mimeapps.list",
3875 &dir->mimeapps_list_timestamp))
3876 return;
3878 if (dir->mimeapps_list_added_map != NULL)
3879 g_hash_table_destroy (dir->mimeapps_list_added_map);
3880 dir->mimeapps_list_added_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3881 g_free, (GDestroyNotify)g_strfreev);
3883 if (dir->mimeapps_list_removed_map != NULL)
3884 g_hash_table_destroy (dir->mimeapps_list_removed_map);
3885 dir->mimeapps_list_removed_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3886 g_free, (GDestroyNotify)g_strfreev);
3888 if (dir->mimeapps_list_defaults_map != NULL)
3889 g_hash_table_destroy (dir->mimeapps_list_defaults_map);
3890 dir->mimeapps_list_defaults_map = g_hash_table_new_full (g_str_hash, g_str_equal,
3891 g_free, g_free);
3893 key_file = g_key_file_new ();
3895 filename = g_build_filename (dir->path, "mimeapps.list", NULL);
3896 if (g_stat (filename, &buf) < 0)
3897 goto error;
3899 dir->mimeapps_list_timestamp = buf.st_mtime;
3901 g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, &load_error);
3902 g_free (filename);
3903 filename = NULL;
3905 if (load_error != NULL)
3906 goto error;
3908 mime_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP,
3909 NULL, NULL);
3910 if (mime_types != NULL)
3912 for (i = 0; mime_types[i] != NULL; i++)
3914 desktop_file_ids = g_key_file_get_string_list (key_file,
3915 ADDED_ASSOCIATIONS_GROUP,
3916 mime_types[i],
3917 NULL,
3918 NULL);
3919 if (desktop_file_ids == NULL)
3920 continue;
3922 unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3923 g_hash_table_replace (dir->mimeapps_list_added_map,
3924 unaliased_type,
3925 desktop_file_ids);
3928 g_strfreev (mime_types);
3931 mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP,
3932 NULL, NULL);
3933 if (mime_types != NULL)
3935 for (i = 0; mime_types[i] != NULL; i++)
3937 desktop_file_ids = g_key_file_get_string_list (key_file,
3938 REMOVED_ASSOCIATIONS_GROUP,
3939 mime_types[i],
3940 NULL,
3941 NULL);
3942 if (desktop_file_ids == NULL)
3943 continue;
3945 unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3946 g_hash_table_replace (dir->mimeapps_list_removed_map,
3947 unaliased_type,
3948 desktop_file_ids);
3951 g_strfreev (mime_types);
3954 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP,
3955 NULL, NULL);
3956 if (mime_types != NULL)
3958 for (i = 0; mime_types[i] != NULL; i++)
3960 desktop_id = g_key_file_get_string (key_file,
3961 DEFAULT_APPLICATIONS_GROUP,
3962 mime_types[i],
3963 NULL);
3964 if (desktop_id == NULL)
3965 continue;
3967 unaliased_type = _g_unix_content_type_unalias (mime_types[i]);
3968 g_hash_table_replace (dir->mimeapps_list_defaults_map,
3969 unaliased_type,
3970 desktop_id);
3973 g_strfreev (mime_types);
3976 g_key_file_free (key_file);
3977 return;
3979 error:
3980 g_free (filename);
3981 g_key_file_free (key_file);
3983 if (mime_types != NULL)
3984 g_strfreev (mime_types);
3986 if (load_error)
3987 g_error_free (load_error);
3990 static MimeInfoCacheDir *
3991 mime_info_cache_dir_new (const char *path)
3993 MimeInfoCacheDir *dir;
3995 dir = g_new0 (MimeInfoCacheDir, 1);
3996 dir->path = g_strdup (path);
3998 return dir;
4001 static void
4002 mime_info_cache_dir_free (MimeInfoCacheDir *dir)
4004 if (dir == NULL)
4005 return;
4007 if (dir->mime_info_cache_map != NULL)
4009 destroy_info_cache_map (dir->mime_info_cache_map);
4010 dir->mime_info_cache_map = NULL;
4014 if (dir->defaults_list_map != NULL)
4016 g_hash_table_destroy (dir->defaults_list_map);
4017 dir->defaults_list_map = NULL;
4020 if (dir->mimeapps_list_added_map != NULL)
4022 g_hash_table_destroy (dir->mimeapps_list_added_map);
4023 dir->mimeapps_list_added_map = NULL;
4026 if (dir->mimeapps_list_removed_map != NULL)
4028 g_hash_table_destroy (dir->mimeapps_list_removed_map);
4029 dir->mimeapps_list_removed_map = NULL;
4032 if (dir->mimeapps_list_defaults_map != NULL)
4034 g_hash_table_destroy (dir->mimeapps_list_defaults_map);
4035 dir->mimeapps_list_defaults_map = NULL;
4038 g_free (dir);
4041 static void
4042 mime_info_cache_dir_add_desktop_entries (MimeInfoCacheDir *dir,
4043 const char *mime_type,
4044 char **new_desktop_file_ids)
4046 GList *desktop_file_ids;
4047 int i;
4049 desktop_file_ids = g_hash_table_lookup (dir->mime_info_cache_map,
4050 mime_type);
4052 for (i = 0; new_desktop_file_ids[i] != NULL; i++)
4054 if (!g_list_find_custom (desktop_file_ids, new_desktop_file_ids[i], (GCompareFunc) strcmp))
4055 desktop_file_ids = g_list_append (desktop_file_ids,
4056 g_strdup (new_desktop_file_ids[i]));
4059 g_hash_table_insert (dir->mime_info_cache_map, g_strdup (mime_type), desktop_file_ids);
4062 static void
4063 mime_info_cache_init_dir_lists (void)
4065 int i;
4067 mime_info_cache = mime_info_cache_new ();
4069 desktop_file_dirs_refresh ();
4071 for (i = 0; i < n_desktop_file_dirs; i++)
4073 MimeInfoCacheDir *dir;
4075 dir = mime_info_cache_dir_new (desktop_file_dirs[i].path);
4077 if (dir != NULL)
4079 mime_info_cache_dir_init (dir);
4080 mime_info_cache_dir_init_defaults_list (dir);
4081 mime_info_cache_dir_init_mimeapps_list (dir);
4083 mime_info_cache->dirs = g_list_append (mime_info_cache->dirs, dir);
4088 static void
4089 mime_info_cache_update_dir_lists (void)
4091 GList *tmp;
4093 tmp = mime_info_cache->dirs;
4095 while (tmp != NULL)
4097 MimeInfoCacheDir *dir = (MimeInfoCacheDir *) tmp->data;
4099 /* No need to do this if we had file monitors... */
4100 mime_info_cache_dir_init (dir);
4101 mime_info_cache_dir_init_defaults_list (dir);
4102 mime_info_cache_dir_init_mimeapps_list (dir);
4104 tmp = tmp->next;
4108 static void
4109 mime_info_cache_init (void)
4111 G_LOCK (mime_info_cache);
4112 if (mime_info_cache == NULL)
4113 mime_info_cache_init_dir_lists ();
4114 else
4116 time_t now;
4118 time (&now);
4119 if (now >= mime_info_cache->last_stat_time + 10)
4121 mime_info_cache_update_dir_lists ();
4122 mime_info_cache->last_stat_time = now;
4126 G_UNLOCK (mime_info_cache);
4129 static MimeInfoCache *
4130 mime_info_cache_new (void)
4132 MimeInfoCache *cache;
4134 cache = g_new0 (MimeInfoCache, 1);
4136 return cache;
4139 static void
4140 mime_info_cache_free (MimeInfoCache *cache)
4142 if (cache == NULL)
4143 return;
4145 g_list_free_full (cache->dirs, (GDestroyNotify) mime_info_cache_dir_free);
4146 g_free (cache);
4150 * mime_info_cache_reload:
4151 * @dir: directory path which needs reloading.
4153 * Reload the mime information for the @dir.
4155 static void
4156 mime_info_cache_reload (const char *dir)
4158 /* FIXME: just reload the dir that needs reloading,
4159 * don't blow the whole cache
4161 if (mime_info_cache != NULL)
4163 G_LOCK (mime_info_cache);
4164 mime_info_cache_free (mime_info_cache);
4165 mime_info_cache = NULL;
4166 G_UNLOCK (mime_info_cache);
4170 static GList *
4171 append_desktop_entry (GList *list,
4172 const char *desktop_entry,
4173 GList *removed_entries)
4175 /* Add if not already in list, and valid */
4176 if (!g_list_find_custom (list, desktop_entry, (GCompareFunc) strcmp) &&
4177 !g_list_find_custom (removed_entries, desktop_entry, (GCompareFunc) strcmp))
4178 list = g_list_prepend (list, g_strdup (desktop_entry));
4180 return list;
4184 * get_all_desktop_entries_for_mime_type:
4185 * @mime_type: a mime type.
4186 * @except: NULL or a strv list
4188 * Returns all the desktop ids for @mime_type. The desktop files
4189 * are listed in an order so that default applications are listed before
4190 * non-default ones, and handlers for inherited mimetypes are listed
4191 * after the base ones.
4193 * Optionally doesn't list the desktop ids given in the @except
4195 * Return value: a #GList containing the desktop ids which claim
4196 * to handle @mime_type.
4198 static GList *
4199 get_all_desktop_entries_for_mime_type (const char *base_mime_type,
4200 const char **except,
4201 gboolean include_fallback,
4202 char **explicit_default)
4204 GList *desktop_entries, *removed_entries, *list, *dir_list, *tmp;
4205 MimeInfoCacheDir *dir;
4206 char *mime_type, *default_entry = NULL;
4207 char *old_default_entry = NULL;
4208 const char *entry;
4209 char **mime_types;
4210 char **default_entries;
4211 char **removed_associations;
4212 gboolean already_found_handler;
4213 int i, j, k;
4214 GPtrArray *array;
4215 char **anc;
4217 mime_info_cache_init ();
4219 if (include_fallback)
4221 /* collect all ancestors */
4222 mime_types = _g_unix_content_type_get_parents (base_mime_type);
4223 array = g_ptr_array_new ();
4224 for (i = 0; mime_types[i]; i++)
4225 g_ptr_array_add (array, mime_types[i]);
4226 g_free (mime_types);
4227 for (i = 0; i < array->len; i++)
4229 anc = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4230 for (j = 0; anc[j]; j++)
4232 for (k = 0; k < array->len; k++)
4234 if (strcmp (anc[j], g_ptr_array_index (array, k)) == 0)
4235 break;
4237 if (k == array->len) /* not found */
4238 g_ptr_array_add (array, g_strdup (anc[j]));
4240 g_strfreev (anc);
4242 g_ptr_array_add (array, NULL);
4243 mime_types = (char **)g_ptr_array_free (array, FALSE);
4245 else
4247 mime_types = g_malloc0 (2 * sizeof (gchar *));
4248 mime_types[0] = g_strdup (base_mime_type);
4249 mime_types[1] = NULL;
4252 G_LOCK (mime_info_cache);
4254 removed_entries = NULL;
4255 desktop_entries = NULL;
4257 for (i = 0; except != NULL && except[i] != NULL; i++)
4258 removed_entries = g_list_prepend (removed_entries, g_strdup (except[i]));
4260 for (i = 0; mime_types[i] != NULL; i++)
4262 mime_type = mime_types[i];
4264 /* This is true if we already found a handler for a more specific
4265 mimetype. If its set we ignore any defaults for the less specific
4266 mimetypes. */
4267 already_found_handler = (desktop_entries != NULL);
4269 /* Go through all apps listed in user and system dirs */
4270 for (dir_list = mime_info_cache->dirs;
4271 dir_list != NULL;
4272 dir_list = dir_list->next)
4274 dir = dir_list->data;
4276 /* Pick the explicit default application if we got no result earlier
4277 * (ie, for more specific mime types)
4279 if (!already_found_handler)
4281 entry = g_hash_table_lookup (dir->mimeapps_list_defaults_map, mime_type);
4283 if (entry != NULL)
4285 /* Save the default entry if it's the first one we encounter */
4286 if (default_entry == NULL)
4287 default_entry = g_strdup (entry);
4291 /* Then added associations from mimeapps.list */
4292 default_entries = g_hash_table_lookup (dir->mimeapps_list_added_map, mime_type);
4293 for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4294 desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4296 /* Then removed associations from mimeapps.list */
4297 removed_associations = g_hash_table_lookup (dir->mimeapps_list_removed_map, mime_type);
4298 for (j = 0; removed_associations != NULL && removed_associations[j] != NULL; j++)
4299 removed_entries = append_desktop_entry (removed_entries, removed_associations[j], NULL);
4301 /* Then system defaults (or old per-user config) (using removed associations from this dir or earlier) */
4302 default_entries = g_hash_table_lookup (dir->defaults_list_map, mime_type);
4303 for (j = 0; default_entries != NULL && default_entries[j] != NULL; j++)
4305 if (default_entry == NULL && old_default_entry == NULL && !already_found_handler)
4306 old_default_entry = g_strdup (default_entries[j]);
4308 desktop_entries = append_desktop_entry (desktop_entries, default_entries[j], removed_entries);
4312 /* Go through all entries that support the mimetype */
4313 for (dir_list = mime_info_cache->dirs;
4314 dir_list != NULL;
4315 dir_list = dir_list->next)
4317 dir = dir_list->data;
4319 list = g_hash_table_lookup (dir->mime_info_cache_map, mime_type);
4320 for (tmp = list; tmp != NULL; tmp = tmp->next)
4321 desktop_entries = append_desktop_entry (desktop_entries, tmp->data, removed_entries);
4325 G_UNLOCK (mime_info_cache);
4327 g_strfreev (mime_types);
4329 /* If we have no default from mimeapps.list, take it from
4330 * defaults.list intead.
4332 * If we do have a default from mimeapps.list, free any one that came
4333 * from defaults.list.
4335 if (default_entry == NULL)
4336 default_entry = old_default_entry;
4337 else
4338 g_free (old_default_entry);
4340 if (explicit_default != NULL)
4341 *explicit_default = default_entry;
4342 else
4343 g_free (default_entry);
4345 g_list_free_full (removed_entries, g_free);
4347 desktop_entries = g_list_reverse (desktop_entries);
4349 return desktop_entries;
4352 /* GDesktopAppInfoLookup interface {{{2 */
4354 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4356 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4357 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4359 static void
4360 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4364 /* "Get for mime type" APIs {{{2 */
4367 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4368 * @lookup: a #GDesktopAppInfoLookup
4369 * @uri_scheme: a string containing a URI scheme.
4371 * Gets the default application for launching applications
4372 * using this URI scheme for a particular GDesktopAppInfoLookup
4373 * implementation.
4375 * The GDesktopAppInfoLookup interface and this function is used
4376 * to implement g_app_info_get_default_for_uri_scheme() backends
4377 * in a GIO module. There is no reason for applications to use it
4378 * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4380 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4382 * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
4384 GAppInfo *
4385 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4386 const char *uri_scheme)
4388 GDesktopAppInfoLookupIface *iface;
4390 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4392 iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4394 return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4397 G_GNUC_END_IGNORE_DEPRECATIONS
4399 /* Misc getter APIs {{{2 */
4402 * g_desktop_app_info_get_startup_wm_class:
4403 * @info: a #GDesktopAppInfo that supports startup notify
4405 * Retrieves the StartupWMClass field from @info. This represents the
4406 * WM_CLASS property of the main window of the application, if launched
4407 * through @info.
4409 * Returns: (transfer none): the startup WM class, or %NULL if none is set
4410 * in the desktop file.
4412 * Since: 2.34
4414 const char *
4415 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4417 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4419 return info->startup_wm_class;
4423 * g_desktop_app_info_get_string:
4424 * @info: a #GDesktopAppInfo
4425 * @key: the key to look up
4427 * Looks up a string value in the keyfile backing @info.
4429 * The @key is looked up in the "Desktop Entry" group.
4431 * Returns: a newly allocated string, or %NULL if the key
4432 * is not found
4434 * Since: 2.36
4436 char *
4437 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4438 const char *key)
4440 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4442 return g_key_file_get_string (info->keyfile,
4443 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4447 * g_desktop_app_info_get_boolean:
4448 * @info: a #GDesktopAppInfo
4449 * @key: the key to look up
4451 * Looks up a boolean value in the keyfile backing @info.
4453 * The @key is looked up in the "Desktop Entry" group.
4455 * Returns: the boolean value, or %FALSE if the key
4456 * is not found
4458 * Since: 2.36
4460 gboolean
4461 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4462 const char *key)
4464 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4466 return g_key_file_get_boolean (info->keyfile,
4467 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4471 * g_desktop_app_info_has_key:
4472 * @info: a #GDesktopAppInfo
4473 * @key: the key to look up
4475 * Returns whether @key exists in the "Desktop Entry" group
4476 * of the keyfile backing @info.
4478 * Returns: %TRUE if the @key exists
4480 * Since: 2.26
4482 gboolean
4483 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4484 const char *key)
4486 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4488 return g_key_file_has_key (info->keyfile,
4489 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4492 /* Desktop actions support {{{2 */
4495 * g_desktop_app_info_list_actions:
4496 * @info: a #GDesktopAppInfo
4498 * Returns the list of "additional application actions" supported on the
4499 * desktop file, as per the desktop file specification.
4501 * As per the specification, this is the list of actions that are
4502 * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4504 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4506 * Since: 2.38
4508 const gchar * const *
4509 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4511 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4513 return (const gchar **) info->actions;
4516 static gboolean
4517 app_info_has_action (GDesktopAppInfo *info,
4518 const gchar *action_name)
4520 gint i;
4522 for (i = 0; info->actions[i]; i++)
4523 if (g_str_equal (info->actions[i], action_name))
4524 return TRUE;
4526 return FALSE;
4530 * g_desktop_app_info_get_action_name:
4531 * @info: a #GDesktopAppInfo
4532 * @action_name: the name of the action as from
4533 * g_desktop_app_info_list_actions()
4535 * Gets the user-visible display name of the "additional application
4536 * action" specified by @action_name.
4538 * This corresponds to the "Name" key within the keyfile group for the
4539 * action.
4541 * Returns: (transfer full): the locale-specific action name
4543 * Since: 2.38
4545 gchar *
4546 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4547 const gchar *action_name)
4549 gchar *group_name;
4550 gchar *result;
4552 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4553 g_return_val_if_fail (action_name != NULL, NULL);
4554 g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4556 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4557 result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4558 g_free (group_name);
4560 /* The spec says that the Name field must be given.
4562 * If it's not, let's follow the behaviour of our get_name()
4563 * implementation above and never return %NULL.
4565 if (result == NULL)
4566 result = g_strdup (_("Unnamed"));
4568 return result;
4572 * g_desktop_app_info_launch_action:
4573 * @info: a #GDesktopAppInfo
4574 * @action_name: the name of the action as from
4575 * g_desktop_app_info_list_actions()
4576 * @launch_context: (allow-none): a #GAppLaunchContext
4578 * Activates the named application action.
4580 * You may only call this function on action names that were
4581 * returned from g_desktop_app_info_list_actions().
4583 * Note that if the main entry of the desktop file indicates that the
4584 * application supports startup notification, and @launch_context is
4585 * non-%NULL, then startup notification will be used when activating the
4586 * action (and as such, invocation of the action on the receiving side
4587 * must signal the end of startup notification when it is completed).
4588 * This is the expected behaviour of applications declaring additional
4589 * actions, as per the desktop file specification.
4591 * As with g_app_info_launch() there is no way to detect failures that
4592 * occur while using this function.
4594 * Since: 2.38
4596 void
4597 g_desktop_app_info_launch_action (GDesktopAppInfo *info,
4598 const gchar *action_name,
4599 GAppLaunchContext *launch_context)
4601 GDBusConnection *session_bus;
4603 g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4604 g_return_if_fail (action_name != NULL);
4605 g_return_if_fail (app_info_has_action (info, action_name));
4607 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4609 if (session_bus && info->app_id)
4611 gchar *object_path;
4613 object_path = object_path_from_appid (info->app_id);
4614 g_dbus_connection_call (session_bus, info->app_id, object_path,
4615 "org.freedesktop.Application", "ActivateAction",
4616 g_variant_new ("(sav@a{sv})", action_name, NULL,
4617 g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4618 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4619 g_free (object_path);
4621 else
4623 gchar *group_name;
4624 gchar *exec_line;
4626 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4627 exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4628 g_free (group_name);
4630 if (exec_line)
4631 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4632 _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL, NULL);
4635 if (session_bus != NULL)
4637 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
4638 g_object_unref (session_bus);
4641 /* Epilogue {{{1 */
4643 /* vim:set foldmethod=marker: */