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, see <http://www.gnu.org/licenses/>.
19 * Author: Alexander Larsson <alexl@redhat.com>
20 * Ryan Lortie <desrt@desrt.ca>
31 #ifdef HAVE_CRT_EXTERNS_H
32 #include <crt_externs.h>
35 #include "gcontenttypeprivate.h"
36 #include "gdesktopappinfo.h"
38 #include "glib-unix.h"
42 #include "gthemedicon.h"
43 #include "gfileicon.h"
44 #include <glib/gstdio.h>
46 #include "giomodule-priv.h"
48 #include "gappinfoprivate.h"
49 #include "glocalfilemonitor.h"
52 * SECTION:gdesktopappinfo
53 * @title: GDesktopAppInfo
54 * @short_description: Application information from desktop files
55 * @include: gio/gdesktopappinfo.h
57 * #GDesktopAppInfo is an implementation of #GAppInfo based on
60 * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
61 * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
65 #define DEFAULT_APPLICATIONS_GROUP "Default Applications"
66 #define ADDED_ASSOCIATIONS_GROUP "Added Associations"
67 #define REMOVED_ASSOCIATIONS_GROUP "Removed Associations"
68 #define MIME_CACHE_GROUP "MIME Cache"
69 #define GENERIC_NAME_KEY "GenericName"
70 #define FULL_NAME_KEY "X-GNOME-FullName"
71 #define KEYWORDS_KEY "Keywords"
72 #define STARTUP_WM_CLASS_KEY "StartupWMClass"
79 static void g_desktop_app_info_iface_init (GAppInfoIface *iface);
80 static gboolean g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
86 * Information about an installed application from a desktop file.
88 struct _GDesktopAppInfo
90 GObject parent_instance;
112 char *startup_wm_class;
119 guint startup_notify : 1;
124 UPDATE_MIME_NONE = 1 << 0,
125 UPDATE_MIME_SET_DEFAULT = 1 << 1,
126 UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
127 UPDATE_MIME_REMOVE = 1 << 3,
128 UPDATE_MIME_SET_LAST_USED = 1 << 4,
131 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
132 G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
134 /* DesktopFileDir implementation {{{1 */
139 gchar *alternatively_watching;
142 GFileMonitor *monitor;
143 GHashTable *app_names;
144 GHashTable *mime_tweaks;
145 GHashTable *memory_index;
146 GHashTable *memory_implementations;
149 static DesktopFileDir *desktop_file_dirs;
150 static guint n_desktop_file_dirs;
151 static const guint desktop_file_dir_user_config_index = 0;
152 static guint desktop_file_dir_user_data_index;
153 static GMutex desktop_file_dir_lock;
155 /* Monitor 'changed' signal handler {{{2 */
156 static void desktop_file_dir_reset (DesktopFileDir *dir);
159 * desktop_file_dir_get_alternative_dir:
160 * @dir: a #DesktopFileDir
162 * Gets the "alternative" directory to monitor in case the path
165 * If the path exists this will return NULL, otherwise it will return a
166 * parent directory of the path.
168 * This is used to avoid inotify on a non-existent directory (which
169 * results in polling).
171 * See https://bugzilla.gnome.org/show_bug.cgi?id=522314 for more info.
174 desktop_file_dir_get_alternative_dir (DesktopFileDir *dir)
178 /* If the directory itself exists then we need no alternative. */
179 if (g_access (dir->path, R_OK | X_OK) == 0)
182 /* Otherwise, try the parent directories until we find one. */
183 parent = g_path_get_dirname (dir->path);
185 while (g_access (parent, R_OK | X_OK) != 0)
189 parent = g_path_get_dirname (tmp);
191 /* If somehow we get to '/' or '.' then just stop... */
192 if (g_str_equal (parent, tmp))
205 desktop_file_dir_changed (GFileMonitor *monitor,
208 GFileMonitorEvent event_type,
211 DesktopFileDir *dir = user_data;
212 gboolean do_nothing = FALSE;
214 /* We are not interested in receiving notifications forever just
215 * because someone asked about one desktop file once.
217 * After we receive the first notification, reset the dir, destroying
218 * the monitor. We will take this as a hint, next time that we are
219 * asked, that we need to check if everything is up to date.
221 * If this is a notification for a parent directory (because the
222 * desktop directory didn't exist) then we shouldn't fire the signal
223 * unless something actually changed.
225 g_mutex_lock (&desktop_file_dir_lock);
227 if (dir->alternatively_watching)
229 gchar *alternative_dir;
231 alternative_dir = desktop_file_dir_get_alternative_dir (dir);
232 do_nothing = alternative_dir && g_str_equal (dir->alternatively_watching, alternative_dir);
233 g_free (alternative_dir);
237 desktop_file_dir_reset (dir);
239 g_mutex_unlock (&desktop_file_dir_lock);
241 /* Notify anyone else who may be interested */
243 g_app_info_monitor_fire ();
246 /* Internal utility functions {{{2 */
249 * desktop_file_dir_app_name_is_masked:
250 * @dir: a #DesktopFileDir
251 * @app_name: an application ID
253 * Checks if @app_name is masked for @dir.
255 * An application is masked if a similarly-named desktop file exists in
256 * a desktop file directory with higher precedence. Masked desktop
257 * files should be ignored.
260 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
261 const gchar *app_name)
263 while (dir > desktop_file_dirs)
267 if (dir->app_names && g_hash_table_contains (dir->app_names, app_name))
274 static const gchar * const *
275 get_lowercase_current_desktops (void)
277 static gchar **result;
279 if (g_once_init_enter (&result))
284 envvar = g_getenv ("XDG_CURRENT_DESKTOP");
290 tmp = g_strsplit (envvar, G_SEARCHPATH_SEPARATOR_S, 0);
292 for (i = 0; tmp[i]; i++)
293 for (j = 0; tmp[i][j]; j++)
294 tmp[i][j] = g_ascii_tolower (tmp[i][j]);
297 tmp = g_new0 (gchar *, 0 + 1);
299 g_once_init_leave (&result, tmp);
302 return (const gchar **) result;
305 static const gchar * const *
306 get_current_desktops (const gchar *value)
308 static gchar **result;
310 if (g_once_init_enter (&result))
315 value = g_getenv ("XDG_CURRENT_DESKTOP");
320 tmp = g_strsplit (value, ":", 0);
322 g_once_init_leave (&result, tmp);
325 return (const gchar **) result;
329 * add_to_table_if_appropriate:
330 * @apps: a string to GDesktopAppInfo hash table
331 * @app_name: the name of the application
332 * @info: a #GDesktopAppInfo, or NULL
334 * If @info is non-%NULL and non-hidden, then add it to @apps, using
335 * @app_name as a key.
337 * If @info is non-%NULL then this function will consume the passed-in
341 add_to_table_if_appropriate (GHashTable *apps,
342 const gchar *app_name,
343 GDesktopAppInfo *info)
350 g_object_unref (info);
354 g_free (info->desktop_id);
355 info->desktop_id = g_strdup (app_name);
357 g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
364 DESKTOP_KEY_GenericName,
365 DESKTOP_KEY_Keywords,
367 DESKTOP_KEY_X_GNOME_FullName,
372 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
373 /* Note: lower numbers are a better match.
375 * In case we want two keys to match at the same level, we can just
376 * use the same number for the two different keys.
378 [DESKTOP_KEY_Name] = 1,
379 [DESKTOP_KEY_Exec] = 2,
380 [DESKTOP_KEY_Keywords] = 3,
381 [DESKTOP_KEY_GenericName] = 4,
382 [DESKTOP_KEY_X_GNOME_FullName] = 5,
383 [DESKTOP_KEY_Comment] = 6
387 desktop_key_get_name (guint key_id)
391 case DESKTOP_KEY_Comment:
393 case DESKTOP_KEY_Exec:
395 case DESKTOP_KEY_GenericName:
396 return GENERIC_NAME_KEY;
397 case DESKTOP_KEY_Keywords:
399 case DESKTOP_KEY_Name:
401 case DESKTOP_KEY_X_GNOME_FullName:
402 return FULL_NAME_KEY;
404 g_assert_not_reached ();
408 /* Search global state {{{2
410 * We only ever search under a global lock, so we can use (and reuse)
411 * some global data to reduce allocations made while searching.
413 * In short, we keep around arrays of results that we expand as needed
414 * (and never shrink).
416 * static_token_results: this is where we append the results for each
417 * token within a given desktop directory, as we handle it (which is
418 * a union of all matches for this term)
420 * static_search_results: this is where we build the complete results
421 * for a single directory (which is an intersection of the matches
422 * found for each term)
424 * static_total_results: this is where we build the complete results
425 * across all directories (which is a union of the matches found in
428 * The app_names that enter these tables are always pointer-unique (in
429 * the sense that string equality is the same as pointer equality).
430 * This can be guaranteed for two reasons:
432 * - we mask appids so that a given appid will only ever appear within
433 * the highest-precedence directory that contains it. We never
434 * return search results from a lower-level directory if a desktop
435 * file exists in a higher-level one.
437 * - within a given directory, the string is unique because it's the
438 * key in the hashtable of all app_ids for that directory.
440 * We perform a merging of the results in merge_token_results(). This
441 * works by ordering the two lists and moving through each of them (at
442 * the same time) looking for common elements, rejecting uncommon ones.
443 * "Order" here need not mean any particular thing, as long as it is
444 * some order. Because of the uniqueness of our strings, we can use
445 * pointer order. That's what's going on in compare_results() below.
449 const gchar *app_name;
453 static struct search_result *static_token_results;
454 static gint static_token_results_size;
455 static gint static_token_results_allocated;
456 static struct search_result *static_search_results;
457 static gint static_search_results_size;
458 static gint static_search_results_allocated;
459 static struct search_result *static_total_results;
460 static gint static_total_results_size;
461 static gint static_total_results_allocated;
463 /* And some functions for performing nice operations against it */
465 compare_results (gconstpointer a,
468 const struct search_result *ra = a;
469 const struct search_result *rb = b;
471 if (ra->app_name < rb->app_name)
474 else if (ra->app_name > rb->app_name)
478 return ra->category - rb->category;
482 compare_categories (gconstpointer a,
485 const struct search_result *ra = a;
486 const struct search_result *rb = b;
488 return ra->category - rb->category;
492 add_token_result (const gchar *app_name,
495 if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
497 static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
498 static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
501 static_token_results[static_token_results_size].app_name = app_name;
502 static_token_results[static_token_results_size].category = category;
503 static_token_results_size++;
507 merge_token_results (gboolean first)
509 qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
511 /* If this is the first token then we are basically merging a list with
512 * itself -- we only perform de-duplication.
514 * If this is not the first token then we are doing a real merge.
518 const gchar *last_name = NULL;
521 /* We must de-duplicate, but we do so by taking the best category
524 * The final list can be as large as the input here, so make sure
525 * we have enough room (even if it's too much room).
528 if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
530 static_search_results_allocated = static_token_results_allocated;
531 static_search_results = g_renew (struct search_result,
532 static_search_results,
533 static_search_results_allocated);
536 for (i = 0; i < static_token_results_size; i++)
538 /* The list is sorted so that the best match for a given id
539 * will be at the front, so once we have copied an id, skip
540 * the rest of the entries for the same id.
542 if (static_token_results[i].app_name == last_name)
545 last_name = static_token_results[i].app_name;
547 static_search_results[static_search_results_size++] = static_token_results[i];
552 const gchar *last_name = NULL;
556 /* We only ever remove items from the results list, so no need to
557 * resize to ensure that we have enough room.
559 for (i = 0; i < static_token_results_size; i++)
561 if (static_token_results[i].app_name == last_name)
564 last_name = static_token_results[i].app_name;
566 /* Now we only want to have a result in static_search_results
567 * if we already have it there *and* we have it in
568 * static_token_results as well. The category will be the
571 * Skip past the results in static_search_results that are not
572 * going to be matches.
574 while (k < static_search_results_size &&
575 static_search_results[k].app_name < static_token_results[i].app_name)
578 if (k < static_search_results_size &&
579 static_search_results[k].app_name == static_token_results[i].app_name)
583 * Category should be the worse of the two (ie:
584 * numerically larger).
586 static_search_results[j].app_name = static_search_results[k].app_name;
587 static_search_results[j].category = MAX (static_search_results[k].category,
588 static_token_results[i].category);
593 static_search_results_size = j;
596 /* Clear it out for next time... */
597 static_token_results_size = 0;
601 reset_total_search_results (void)
603 static_total_results_size = 0;
607 sort_total_search_results (void)
609 qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
613 merge_directory_results (void)
615 if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
617 static_total_results_allocated = MAX (16, static_total_results_allocated);
618 while (static_total_results_allocated < static_total_results_size + static_search_results_size)
619 static_total_results_allocated *= 2;
620 static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
623 memcpy (static_total_results + static_total_results_size,
624 static_search_results,
625 static_search_results_size * sizeof (struct search_result));
627 static_total_results_size += static_search_results_size;
629 /* Clear it out for next time... */
630 static_search_results_size = 0;
633 /* Support for unindexed DesktopFileDirs {{{2 */
635 get_apps_from_dir (GHashTable **apps,
639 const char *basename;
642 dir = g_dir_open (dirname, 0, NULL);
647 while ((basename = g_dir_read_name (dir)) != NULL)
651 filename = g_build_filename (dirname, basename, NULL);
653 if (g_str_has_suffix (basename, ".desktop"))
657 app_name = g_strconcat (prefix, basename, NULL);
660 *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
662 g_hash_table_insert (*apps, app_name, g_strdup (filename));
664 else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
668 subprefix = g_strconcat (prefix, basename, "-", NULL);
669 get_apps_from_dir (apps, filename, subprefix);
684 } UnindexedMimeTweaks;
687 free_mime_tweaks (gpointer data)
689 UnindexedMimeTweaks *tweaks = data;
691 g_strfreev (tweaks->additions);
692 g_strfreev (tweaks->removals);
693 g_strfreev (tweaks->defaults);
695 g_slice_free (UnindexedMimeTweaks, tweaks);
698 static UnindexedMimeTweaks *
699 desktop_file_dir_unindexed_get_tweaks (DesktopFileDir *dir,
700 const gchar *mime_type)
702 UnindexedMimeTweaks *tweaks;
703 gchar *unaliased_type;
705 unaliased_type = _g_unix_content_type_unalias (mime_type);
706 tweaks = g_hash_table_lookup (dir->mime_tweaks, unaliased_type);
710 tweaks = g_slice_new0 (UnindexedMimeTweaks);
711 g_hash_table_insert (dir->mime_tweaks, unaliased_type, tweaks);
714 g_free (unaliased_type);
719 /* consumes 'to_add' */
721 expand_strv (gchar ***strv_ptr,
723 gchar * const *blacklist)
725 guint strv_len, add_len;
736 strv_len = g_strv_length (strv);
737 add_len = g_strv_length (to_add);
738 strv = g_renew (gchar *, strv, strv_len + add_len + 1);
740 for (i = 0; to_add[i]; i++)
742 /* Don't add blacklisted strings */
744 for (j = 0; blacklist[j]; j++)
745 if (g_str_equal (to_add[i], blacklist[j]))
748 /* Don't add duplicates already in the list */
749 for (j = 0; j < strv_len; j++)
750 if (g_str_equal (to_add[i], strv[j]))
753 strv[strv_len++] = to_add[i];
760 strv[strv_len] = NULL;
767 desktop_file_dir_unindexed_read_mimeapps_list (DesktopFileDir *dir,
768 const gchar *filename,
769 const gchar *added_group,
770 gboolean tweaks_permitted)
772 UnindexedMimeTweaks *tweaks;
773 char **desktop_file_ids;
778 key_file = g_key_file_new ();
779 if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL))
781 g_key_file_free (key_file);
785 mime_types = g_key_file_get_keys (key_file, added_group, NULL, NULL);
787 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
789 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
790 "mimeapps.list file may add or remove associations.", filename, added_group);
791 g_strfreev (mime_types);
795 if (mime_types != NULL)
797 for (i = 0; mime_types[i] != NULL; i++)
799 desktop_file_ids = g_key_file_get_string_list (key_file, added_group, mime_types[i], NULL, NULL);
801 if (desktop_file_ids)
803 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
804 expand_strv (&tweaks->additions, desktop_file_ids, tweaks->removals);
808 g_strfreev (mime_types);
811 mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
813 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
815 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
816 "mimeapps.list file may add or remove associations.", filename, REMOVED_ASSOCIATIONS_GROUP);
817 g_strfreev (mime_types);
821 if (mime_types != NULL)
823 for (i = 0; mime_types[i] != NULL; i++)
825 desktop_file_ids = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP, mime_types[i], NULL, NULL);
827 if (desktop_file_ids)
829 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
830 expand_strv (&tweaks->removals, desktop_file_ids, tweaks->additions);
834 g_strfreev (mime_types);
837 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
839 if (mime_types != NULL)
841 for (i = 0; mime_types[i] != NULL; i++)
843 desktop_file_ids = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP, mime_types[i], NULL, NULL);
845 if (desktop_file_ids)
847 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
848 expand_strv (&tweaks->defaults, desktop_file_ids, NULL);
852 g_strfreev (mime_types);
855 g_key_file_free (key_file);
859 desktop_file_dir_unindexed_read_mimeapps_lists (DesktopFileDir *dir)
861 const gchar * const *desktops;
865 dir->mime_tweaks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_mime_tweaks);
867 /* We process in order of precedence, using a blacklisting approach to
868 * avoid recording later instructions that conflict with ones we found
871 * We first start with the XDG_CURRENT_DESKTOP files, in precedence
874 desktops = get_lowercase_current_desktops ();
875 for (i = 0; desktops[i]; i++)
877 filename = g_strdup_printf ("%s/%s-mimeapps.list", dir->path, desktops[i]);
878 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
882 /* Next, the non-desktop-specific mimeapps.list */
883 filename = g_strdup_printf ("%s/mimeapps.list", dir->path);
884 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, TRUE);
887 /* The remaining files are only checked for in directories that might
888 * contain desktop files (ie: not the config dirs).
893 /* We have 'defaults.list' which was only ever understood by GLib. It
894 * exists widely, but it has never been part of any spec and it should
895 * be treated as deprecated. This will be removed in a future
898 filename = g_strdup_printf ("%s/defaults.list", dir->path);
899 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
902 /* Finally, the mimeinfo.cache, which is just a cached copy of what we
903 * would find in the MimeTypes= lines of all of the desktop files.
905 filename = g_strdup_printf ("%s/mimeinfo.cache", dir->path);
906 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, MIME_CACHE_GROUP, TRUE);
911 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
914 get_apps_from_dir (&dir->app_names, dir->path, "");
916 desktop_file_dir_unindexed_read_mimeapps_lists (dir);
919 static GDesktopAppInfo *
920 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
921 const gchar *desktop_id)
923 const gchar *filename;
925 filename = g_hash_table_lookup (dir->app_names, desktop_id);
930 return g_desktop_app_info_new_from_filename (filename);
934 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
941 if (dir->app_names == NULL)
944 g_hash_table_iter_init (&iter, dir->app_names);
945 while (g_hash_table_iter_next (&iter, &app_name, &filename))
947 if (desktop_file_dir_app_name_is_masked (dir, app_name))
950 add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename (filename));
954 typedef struct _MemoryIndexEntry MemoryIndexEntry;
955 typedef GHashTable MemoryIndex;
957 struct _MemoryIndexEntry
959 const gchar *app_name; /* pointer to the hashtable key */
961 MemoryIndexEntry *next;
965 memory_index_entry_free (gpointer data)
967 MemoryIndexEntry *mie = data;
971 MemoryIndexEntry *next = mie->next;
973 g_slice_free (MemoryIndexEntry, mie);
979 memory_index_add_token (MemoryIndex *mi,
982 const gchar *app_name)
984 MemoryIndexEntry *mie, *first;
986 mie = g_slice_new (MemoryIndexEntry);
987 mie->app_name = app_name;
988 mie->match_category = match_category;
990 first = g_hash_table_lookup (mi, token);
994 mie->next = first->next;
1000 g_hash_table_insert (mi, g_strdup (token), mie);
1005 memory_index_add_string (MemoryIndex *mi,
1006 const gchar *string,
1007 gint match_category,
1008 const gchar *app_name)
1010 gchar **tokens, **alternates;
1013 tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
1015 for (i = 0; tokens[i]; i++)
1016 memory_index_add_token (mi, tokens[i], match_category, app_name);
1018 for (i = 0; alternates[i]; i++)
1019 memory_index_add_token (mi, alternates[i], match_category, app_name);
1021 g_strfreev (alternates);
1022 g_strfreev (tokens);
1025 static MemoryIndex *
1026 memory_index_new (void)
1028 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
1032 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
1034 GHashTableIter iter;
1037 dir->memory_index = memory_index_new ();
1038 dir->memory_implementations = memory_index_new ();
1040 /* Nothing to search? */
1041 if (dir->app_names == NULL)
1044 g_hash_table_iter_init (&iter, dir->app_names);
1045 while (g_hash_table_iter_next (&iter, &app, &path))
1049 if (desktop_file_dir_app_name_is_masked (dir, app))
1052 key_file = g_key_file_new ();
1054 if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
1055 !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
1057 /* Index the interesting keys... */
1061 for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
1066 if (!desktop_key_match_category[i])
1069 raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
1072 if (i == DESKTOP_KEY_Exec && raw != NULL)
1074 /* Special handling: only match basename of first field */
1078 /* Remove extra arguments, if any */
1079 space = raw + strcspn (raw, " \t\n"); /* IFS */
1082 /* Skip the pathname, if any */
1083 if ((slash = strrchr (raw, '/')))
1088 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
1093 /* Make note of the Implements= line */
1094 implements = g_key_file_get_string_list (key_file, "Desktop Entry", "Implements", NULL, NULL);
1095 for (i = 0; implements && implements[i]; i++)
1096 memory_index_add_token (dir->memory_implementations, implements[i], 0, app);
1097 g_strfreev (implements);
1100 g_key_file_free (key_file);
1105 desktop_file_dir_unindexed_search (DesktopFileDir *dir,
1106 const gchar *search_token)
1108 GHashTableIter iter;
1109 gpointer key, value;
1111 if (!dir->memory_index)
1112 desktop_file_dir_unindexed_setup_search (dir);
1114 g_hash_table_iter_init (&iter, dir->memory_index);
1115 while (g_hash_table_iter_next (&iter, &key, &value))
1117 MemoryIndexEntry *mie = value;
1119 if (!g_str_has_prefix (key, search_token))
1124 add_token_result (mie->app_name, mie->match_category);
1131 array_contains (GPtrArray *array,
1136 for (i = 0; i < array->len; i++)
1137 if (g_str_equal (array->pdata[i], str))
1144 desktop_file_dir_unindexed_mime_lookup (DesktopFileDir *dir,
1145 const gchar *mime_type,
1147 GPtrArray *blacklist)
1149 UnindexedMimeTweaks *tweaks;
1152 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1157 if (tweaks->additions)
1159 for (i = 0; tweaks->additions[i]; i++)
1161 gchar *app_name = tweaks->additions[i];
1163 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1164 !array_contains (blacklist, app_name) && !array_contains (hits, app_name))
1165 g_ptr_array_add (hits, app_name);
1169 if (tweaks->removals)
1171 for (i = 0; tweaks->removals[i]; i++)
1173 gchar *app_name = tweaks->removals[i];
1175 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1176 !array_contains (blacklist, app_name) && !array_contains (hits, app_name))
1177 g_ptr_array_add (blacklist, app_name);
1183 desktop_file_dir_unindexed_default_lookup (DesktopFileDir *dir,
1184 const gchar *mime_type,
1187 UnindexedMimeTweaks *tweaks;
1190 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1192 if (!tweaks || !tweaks->defaults)
1195 for (i = 0; tweaks->defaults[i]; i++)
1197 gchar *app_name = tweaks->defaults[i];
1199 if (!array_contains (results, app_name))
1200 g_ptr_array_add (results, app_name);
1205 desktop_file_dir_unindexed_get_implementations (DesktopFileDir *dir,
1207 const gchar *interface)
1209 MemoryIndexEntry *mie;
1211 if (!dir->memory_index)
1212 desktop_file_dir_unindexed_setup_search (dir);
1214 for (mie = g_hash_table_lookup (dir->memory_implementations, interface); mie; mie = mie->next)
1215 *results = g_list_prepend (*results, g_strdup (mie->app_name));
1218 /* DesktopFileDir "API" {{{2 */
1221 * desktop_file_dir_create:
1222 * @array: the #GArray to add a new item to
1223 * @data_dir: an XDG_DATA_DIR
1225 * Creates a #DesktopFileDir for the corresponding @data_dir, adding it
1229 desktop_file_dir_create (GArray *array,
1230 const gchar *data_dir)
1232 DesktopFileDir dir = { 0, };
1234 dir.path = g_build_filename (data_dir, "applications", NULL);
1236 g_array_append_val (array, dir);
1240 * desktop_file_dir_create:
1241 * @array: the #GArray to add a new item to
1242 * @config_dir: an XDG_CONFIG_DIR
1244 * Just the same as desktop_file_dir_create() except that it does not
1245 * add the "applications" directory. It also marks the directory as
1246 * config-only, which prevents us from attempting to find desktop files
1250 desktop_file_dir_create_for_config (GArray *array,
1251 const gchar *config_dir)
1253 DesktopFileDir dir = { 0, };
1255 dir.path = g_strdup (config_dir);
1256 dir.is_config = TRUE;
1258 g_array_append_val (array, dir);
1262 * desktop_file_dir_reset:
1263 * @dir: a #DesktopFileDir
1265 * Cleans up @dir, releasing most resources that it was using.
1268 desktop_file_dir_reset (DesktopFileDir *dir)
1270 if (dir->alternatively_watching)
1272 g_free (dir->alternatively_watching);
1273 dir->alternatively_watching = NULL;
1278 g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
1279 g_object_unref (dir->monitor);
1280 dir->monitor = NULL;
1285 g_hash_table_unref (dir->app_names);
1286 dir->app_names = NULL;
1289 if (dir->memory_index)
1291 g_hash_table_unref (dir->memory_index);
1292 dir->memory_index = NULL;
1295 if (dir->mime_tweaks)
1297 g_hash_table_unref (dir->mime_tweaks);
1298 dir->mime_tweaks = NULL;
1301 if (dir->memory_implementations)
1303 g_hash_table_unref (dir->memory_implementations);
1304 dir->memory_implementations = NULL;
1307 dir->is_setup = FALSE;
1311 * desktop_file_dir_init:
1312 * @dir: a #DesktopFileDir
1314 * Does initial setup for @dir
1316 * You should only call this if @dir is not already setup.
1319 desktop_file_dir_init (DesktopFileDir *dir)
1321 const gchar *watch_dir;
1323 g_assert (!dir->is_setup);
1325 g_assert (!dir->alternatively_watching);
1326 g_assert (!dir->monitor);
1328 dir->alternatively_watching = desktop_file_dir_get_alternative_dir (dir);
1329 watch_dir = dir->alternatively_watching ? dir->alternatively_watching : dir->path;
1331 /* There is a very thin race here if the watch_dir has been _removed_
1332 * between when we checked for it and when we establish the watch.
1333 * Removes probably don't happen in usual operation, and even if it
1334 * does (and we catch the unlikely race), the only degradation is that
1335 * we will fall back to polling.
1337 dir->monitor = g_local_file_monitor_new_in_worker (watch_dir, TRUE, G_FILE_MONITOR_NONE,
1338 desktop_file_dir_changed, dir, NULL);
1340 desktop_file_dir_unindexed_init (dir);
1342 dir->is_setup = TRUE;
1346 * desktop_file_dir_get_app:
1347 * @dir: a DesktopFileDir
1348 * @desktop_id: the desktop ID to load
1350 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
1351 * within @dir, even if it is hidden.
1353 * This function does not check if @desktop_id would be masked by a
1354 * directory with higher precedence. The caller must do so.
1356 static GDesktopAppInfo *
1357 desktop_file_dir_get_app (DesktopFileDir *dir,
1358 const gchar *desktop_id)
1360 if (!dir->app_names)
1363 return desktop_file_dir_unindexed_get_app (dir, desktop_id);
1367 * desktop_file_dir_get_all:
1368 * @dir: a DesktopFileDir
1369 * @apps: a #GHashTable<string, GDesktopAppInfo>
1371 * Loads all desktop files in @dir and adds them to @apps, careful to
1372 * ensure we don't add any files masked by a similarly-named file in a
1373 * higher-precedence directory.
1376 desktop_file_dir_get_all (DesktopFileDir *dir,
1379 desktop_file_dir_unindexed_get_all (dir, apps);
1383 * desktop_file_dir_mime_lookup:
1384 * @dir: a #DesktopFileDir
1385 * @mime_type: the mime type to look up
1386 * @hits: the array to store the hits
1387 * @blacklist: the array to store the blacklist
1389 * Does a lookup of a mimetype against one desktop file directory,
1390 * recording any hits and blacklisting and "Removed" associations (so
1391 * later directories don't record them as hits).
1393 * The items added to @hits are duplicated, but the ones in @blacklist
1394 * are weak pointers. This facilitates simply freeing the blacklist
1395 * (which is only used for internal bookkeeping) but using the pdata of
1396 * @hits as the result of the operation.
1399 desktop_file_dir_mime_lookup (DesktopFileDir *dir,
1400 const gchar *mime_type,
1402 GPtrArray *blacklist)
1404 desktop_file_dir_unindexed_mime_lookup (dir, mime_type, hits, blacklist);
1408 * desktop_file_dir_default_lookup:
1409 * @dir: a #DesktopFileDir
1410 * @mime_type: the mime type to look up
1411 * @results: an array to store the results in
1413 * Collects the "default" applications for a given mime type from @dir.
1416 desktop_file_dir_default_lookup (DesktopFileDir *dir,
1417 const gchar *mime_type,
1420 desktop_file_dir_unindexed_default_lookup (dir, mime_type, results);
1424 * desktop_file_dir_search:
1425 * @dir: a #DesktopFileDir
1426 * @term: a normalised and casefolded search term
1428 * Finds the names of applications in @dir that match @term.
1431 desktop_file_dir_search (DesktopFileDir *dir,
1432 const gchar *search_token)
1434 desktop_file_dir_unindexed_search (dir, search_token);
1438 desktop_file_dir_get_implementations (DesktopFileDir *dir,
1440 const gchar *interface)
1442 desktop_file_dir_unindexed_get_implementations (dir, results, interface);
1445 /* Lock/unlock and global setup API {{{2 */
1448 desktop_file_dirs_lock (void)
1452 g_mutex_lock (&desktop_file_dir_lock);
1454 if (desktop_file_dirs == NULL)
1456 const char * const *dirs;
1460 tmp = g_array_new (FALSE, FALSE, sizeof (DesktopFileDir));
1462 /* First, the configs. Highest priority: the user's ~/.config */
1463 desktop_file_dir_create_for_config (tmp, g_get_user_config_dir ());
1465 /* Next, the system configs (/etc/xdg, and so on). */
1466 dirs = g_get_system_config_dirs ();
1467 for (i = 0; dirs[i]; i++)
1468 desktop_file_dir_create_for_config (tmp, dirs[i]);
1470 /* Now the data. Highest priority: the user's ~/.local/share/applications */
1471 desktop_file_dir_user_data_index = tmp->len;
1472 desktop_file_dir_create (tmp, g_get_user_data_dir ());
1474 /* Following that, XDG_DATA_DIRS/applications, in order */
1475 dirs = g_get_system_data_dirs ();
1476 for (i = 0; dirs[i]; i++)
1477 desktop_file_dir_create (tmp, dirs[i]);
1479 /* The list of directories will never change after this. */
1480 desktop_file_dirs = (DesktopFileDir *) tmp->data;
1481 n_desktop_file_dirs = tmp->len;
1483 g_array_free (tmp, FALSE);
1486 for (i = 0; i < n_desktop_file_dirs; i++)
1487 if (!desktop_file_dirs[i].is_setup)
1488 desktop_file_dir_init (&desktop_file_dirs[i]);
1492 desktop_file_dirs_unlock (void)
1494 g_mutex_unlock (&desktop_file_dir_lock);
1498 desktop_file_dirs_invalidate_user_config (void)
1500 g_mutex_lock (&desktop_file_dir_lock);
1502 if (n_desktop_file_dirs)
1503 desktop_file_dir_reset (&desktop_file_dirs[desktop_file_dir_user_config_index]);
1505 g_mutex_unlock (&desktop_file_dir_lock);
1509 desktop_file_dirs_invalidate_user_data (void)
1511 g_mutex_lock (&desktop_file_dir_lock);
1513 if (n_desktop_file_dirs)
1514 desktop_file_dir_reset (&desktop_file_dirs[desktop_file_dir_user_data_index]);
1516 g_mutex_unlock (&desktop_file_dir_lock);
1519 /* GDesktopAppInfo implementation {{{1 */
1520 /* GObject implementation {{{2 */
1522 g_desktop_app_info_finalize (GObject *object)
1524 GDesktopAppInfo *info;
1526 info = G_DESKTOP_APP_INFO (object);
1528 g_free (info->desktop_id);
1529 g_free (info->filename);
1532 g_key_file_unref (info->keyfile);
1534 g_free (info->name);
1535 g_free (info->generic_name);
1536 g_free (info->fullname);
1537 g_free (info->comment);
1538 g_free (info->icon_name);
1540 g_object_unref (info->icon);
1541 g_strfreev (info->keywords);
1542 g_strfreev (info->only_show_in);
1543 g_strfreev (info->not_show_in);
1544 g_free (info->try_exec);
1545 g_free (info->exec);
1546 g_free (info->binary);
1547 g_free (info->path);
1548 g_free (info->categories);
1549 g_free (info->startup_wm_class);
1550 g_strfreev (info->mime_types);
1551 g_free (info->app_id);
1552 g_strfreev (info->actions);
1554 G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1558 g_desktop_app_info_set_property (GObject *object,
1560 const GValue *value,
1563 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1568 self->filename = g_value_dup_string (value);
1572 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1578 g_desktop_app_info_get_property (GObject *object,
1583 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1588 g_value_set_string (value, self->filename);
1591 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1597 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1599 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1601 gobject_class->get_property = g_desktop_app_info_get_property;
1602 gobject_class->set_property = g_desktop_app_info_set_property;
1603 gobject_class->finalize = g_desktop_app_info_finalize;
1606 * GDesktopAppInfo:filename:
1608 * The origin filename of this #GDesktopAppInfo
1610 g_object_class_install_property (gobject_class,
1612 g_param_spec_string ("filename", "Filename", "", NULL,
1613 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1617 g_desktop_app_info_init (GDesktopAppInfo *local)
1621 /* Construction... {{{2 */
1625 * @exec: an exec line
1627 * Returns the first word in an exec line (ie: the binary name).
1629 * If @exec is " progname --foo %F" then returns "progname".
1632 binary_from_exec (const char *exec)
1634 const char *p, *start;
1640 while (*p != ' ' && *p != 0)
1643 return g_strndup (start, p - start);
1647 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1654 gboolean bus_activatable;
1656 start_group = g_key_file_get_start_group (key_file);
1657 if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1659 g_free (start_group);
1662 g_free (start_group);
1664 type = g_key_file_get_string (key_file,
1665 G_KEY_FILE_DESKTOP_GROUP,
1666 G_KEY_FILE_DESKTOP_KEY_TYPE,
1668 if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1675 try_exec = g_key_file_get_string (key_file,
1676 G_KEY_FILE_DESKTOP_GROUP,
1677 G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1679 if (try_exec && try_exec[0] != '\0')
1682 t = g_find_program_in_path (try_exec);
1691 exec = g_key_file_get_string (key_file,
1692 G_KEY_FILE_DESKTOP_GROUP,
1693 G_KEY_FILE_DESKTOP_KEY_EXEC,
1695 if (exec && exec[0] != '\0')
1699 if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1708 t = g_find_program_in_path (argv[0]);
1721 info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1722 info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1723 info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1724 info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1725 info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1726 info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1727 info->icon_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1728 info->only_show_in = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN, NULL, NULL);
1729 info->not_show_in = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN, NULL, NULL);
1730 info->try_exec = try_exec;
1732 info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1733 info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1734 info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1735 info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1736 info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1737 info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1738 info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1739 info->mime_types = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_MIME_TYPE, NULL, NULL);
1740 bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1741 info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1743 /* Remove the special-case: no Actions= key just means 0 extra actions */
1744 if (info->actions == NULL)
1745 info->actions = g_new0 (gchar *, 0 + 1);
1748 if (info->icon_name)
1750 if (g_path_is_absolute (info->icon_name))
1754 file = g_file_new_for_path (info->icon_name);
1755 info->icon = g_file_icon_new (file);
1756 g_object_unref (file);
1762 /* Work around a common mistake in desktop files */
1763 if ((p = strrchr (info->icon_name, '.')) != NULL &&
1764 (strcmp (p, ".png") == 0 ||
1765 strcmp (p, ".xpm") == 0 ||
1766 strcmp (p, ".svg") == 0))
1769 info->icon = g_themed_icon_new (info->icon_name);
1774 info->binary = binary_from_exec (info->exec);
1776 if (info->path && info->path[0] == '\0')
1778 g_free (info->path);
1782 /* Can only be DBusActivatable if we know the filename, which means
1783 * that this won't work for the load-from-keyfile case.
1785 if (bus_activatable && info->filename)
1790 basename = g_path_get_basename (info->filename);
1791 last_dot = strrchr (basename, '.');
1793 if (last_dot && g_str_equal (last_dot, ".desktop"))
1797 if (g_dbus_is_interface_name (basename))
1798 info->app_id = g_strdup (basename);
1804 info->keyfile = g_key_file_ref (key_file);
1810 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1813 gboolean retval = FALSE;
1815 g_return_val_if_fail (self->filename != NULL, FALSE);
1817 self->desktop_id = g_path_get_basename (self->filename);
1819 key_file = g_key_file_new ();
1821 if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
1822 retval = g_desktop_app_info_load_from_keyfile (self, key_file);
1824 g_key_file_unref (key_file);
1829 * g_desktop_app_info_new_from_keyfile:
1830 * @key_file: an opened #GKeyFile
1832 * Creates a new #GDesktopAppInfo.
1834 * Returns: a new #GDesktopAppInfo or %NULL on error.
1839 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
1841 GDesktopAppInfo *info;
1843 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1844 info->filename = NULL;
1845 if (!g_desktop_app_info_load_from_keyfile (info, key_file))
1847 g_object_unref (info);
1854 * g_desktop_app_info_new_from_filename:
1855 * @filename: the path of a desktop file, in the GLib filename encoding
1857 * Creates a new #GDesktopAppInfo.
1859 * Returns: a new #GDesktopAppInfo or %NULL on error.
1862 g_desktop_app_info_new_from_filename (const char *filename)
1864 GDesktopAppInfo *info = NULL;
1866 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1867 if (!g_desktop_app_info_load_file (info))
1869 g_object_unref (info);
1876 * g_desktop_app_info_new:
1877 * @desktop_id: the desktop file id
1879 * Creates a new #GDesktopAppInfo based on a desktop file id.
1881 * A desktop file id is the basename of the desktop file, including the
1882 * .desktop extension. GIO is looking for a desktop file with this name
1883 * in the `applications` subdirectories of the XDG
1884 * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
1885 * and `XDG_DATA_DIRS` environment variables). GIO also supports the
1886 * prefix-to-subdirectory mapping that is described in the
1887 * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
1888 * (i.e. a desktop id of kde-foo.desktop will match
1889 * `/usr/share/applications/kde/foo.desktop`).
1891 * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
1894 g_desktop_app_info_new (const char *desktop_id)
1896 GDesktopAppInfo *appinfo = NULL;
1899 desktop_file_dirs_lock ();
1901 for (i = 0; i < n_desktop_file_dirs; i++)
1903 appinfo = desktop_file_dir_get_app (&desktop_file_dirs[i], desktop_id);
1909 desktop_file_dirs_unlock ();
1911 if (appinfo == NULL)
1914 g_free (appinfo->desktop_id);
1915 appinfo->desktop_id = g_strdup (desktop_id);
1917 if (g_desktop_app_info_get_is_hidden (appinfo))
1919 g_object_unref (appinfo);
1927 g_desktop_app_info_dup (GAppInfo *appinfo)
1929 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1930 GDesktopAppInfo *new_info;
1932 new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1934 new_info->filename = g_strdup (info->filename);
1935 new_info->desktop_id = g_strdup (info->desktop_id);
1938 new_info->keyfile = g_key_file_ref (info->keyfile);
1940 new_info->name = g_strdup (info->name);
1941 new_info->generic_name = g_strdup (info->generic_name);
1942 new_info->fullname = g_strdup (info->fullname);
1943 new_info->keywords = g_strdupv (info->keywords);
1944 new_info->comment = g_strdup (info->comment);
1945 new_info->nodisplay = info->nodisplay;
1946 new_info->icon_name = g_strdup (info->icon_name);
1948 new_info->icon = g_object_ref (info->icon);
1949 new_info->only_show_in = g_strdupv (info->only_show_in);
1950 new_info->not_show_in = g_strdupv (info->not_show_in);
1951 new_info->try_exec = g_strdup (info->try_exec);
1952 new_info->exec = g_strdup (info->exec);
1953 new_info->binary = g_strdup (info->binary);
1954 new_info->path = g_strdup (info->path);
1955 new_info->app_id = g_strdup (info->app_id);
1956 new_info->hidden = info->hidden;
1957 new_info->terminal = info->terminal;
1958 new_info->startup_notify = info->startup_notify;
1960 return G_APP_INFO (new_info);
1963 /* GAppInfo interface implementation functions {{{2 */
1966 g_desktop_app_info_equal (GAppInfo *appinfo1,
1969 GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
1970 GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
1972 if (info1->desktop_id == NULL ||
1973 info2->desktop_id == NULL)
1974 return info1 == info2;
1976 return strcmp (info1->desktop_id, info2->desktop_id) == 0;
1980 g_desktop_app_info_get_id (GAppInfo *appinfo)
1982 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1984 return info->desktop_id;
1988 g_desktop_app_info_get_name (GAppInfo *appinfo)
1990 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1992 if (info->name == NULL)
1993 return _("Unnamed");
1998 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
2000 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2002 if (info->fullname == NULL)
2003 return g_desktop_app_info_get_name (appinfo);
2004 return info->fullname;
2008 * g_desktop_app_info_get_is_hidden:
2009 * @info: a #GDesktopAppInfo.
2011 * A desktop file is hidden if the Hidden key in it is
2014 * Returns: %TRUE if hidden, %FALSE otherwise.
2017 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
2019 return info->hidden;
2023 * g_desktop_app_info_get_filename:
2024 * @info: a #GDesktopAppInfo
2026 * When @info was created from a known filename, return it. In some
2027 * situations such as the #GDesktopAppInfo returned from
2028 * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
2030 * Returns: The full path to the file for @info, or %NULL if not known.
2034 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
2036 return info->filename;
2040 g_desktop_app_info_get_description (GAppInfo *appinfo)
2042 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2044 return info->comment;
2048 g_desktop_app_info_get_executable (GAppInfo *appinfo)
2050 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2052 return info->binary;
2056 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
2058 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2064 g_desktop_app_info_get_icon (GAppInfo *appinfo)
2066 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2072 * g_desktop_app_info_get_categories:
2073 * @info: a #GDesktopAppInfo
2075 * Gets the categories from the desktop file.
2077 * Returns: The unparsed Categories key from the desktop file;
2078 * i.e. no attempt is made to split it by ';' or validate it.
2081 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
2083 return info->categories;
2087 * g_desktop_app_info_get_keywords:
2088 * @info: a #GDesktopAppInfo
2090 * Gets the keywords from the desktop file.
2092 * Returns: (transfer none): The value of the Keywords key
2096 const char * const *
2097 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
2099 return (const char * const *)info->keywords;
2103 * g_desktop_app_info_get_generic_name:
2104 * @info: a #GDesktopAppInfo
2106 * Gets the generic name from the destkop file.
2108 * Returns: The value of the GenericName key
2111 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
2113 return info->generic_name;
2117 * g_desktop_app_info_get_nodisplay:
2118 * @info: a #GDesktopAppInfo
2120 * Gets the value of the NoDisplay key, which helps determine if the
2121 * application info should be shown in menus. See
2122 * #G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
2124 * Returns: The value of the NoDisplay key
2129 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
2131 return info->nodisplay;
2135 * g_desktop_app_info_get_show_in:
2136 * @info: a #GDesktopAppInfo
2137 * @desktop_env: (nullable): a string specifying a desktop name
2139 * Checks if the application info should be shown in menus that list available
2140 * applications for a specific name of the desktop, based on the
2141 * `OnlyShowIn` and `NotShowIn` keys.
2143 * @desktop_env should typically be given as %NULL, in which case the
2144 * `XDG_CURRENT_DESKTOP` environment variable is consulted. If you want
2145 * to override the default mechanism then you may specify @desktop_env,
2146 * but this is not recommended.
2148 * Note that g_app_info_should_show() for @info will include this check (with
2149 * %NULL for @desktop_env) as well as additional checks.
2151 * Returns: %TRUE if the @info should be shown in @desktop_env according to the
2152 * `OnlyShowIn` and `NotShowIn` keys, %FALSE
2158 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
2159 const gchar *desktop_env)
2161 const gchar *specified_envs[] = { desktop_env, NULL };
2162 const gchar * const *envs;
2165 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
2168 envs = specified_envs;
2170 envs = get_current_desktops (NULL);
2172 for (i = 0; envs[i]; i++)
2176 if (info->only_show_in)
2177 for (j = 0; info->only_show_in[j]; j++)
2178 if (g_str_equal (info->only_show_in[j], envs[i]))
2181 if (info->not_show_in)
2182 for (j = 0; info->not_show_in[j]; j++)
2183 if (g_str_equal (info->not_show_in[j], envs[i]))
2187 return info->only_show_in == NULL;
2190 /* Launching... {{{2 */
2193 expand_macro_single (char macro, char *uri)
2196 char *result = NULL;
2200 file = g_file_new_for_uri (uri);
2206 result = g_shell_quote (uri);
2210 path = g_file_get_path (file);
2212 result = g_shell_quote (path);
2216 path = g_file_get_path (file);
2219 name = g_path_get_dirname (path);
2220 result = g_shell_quote (name);
2226 path = g_file_get_path (file);
2229 name = g_path_get_basename (path);
2230 result = g_shell_quote (name);
2236 g_object_unref (file);
2243 expand_macro (char macro,
2245 GDesktopAppInfo *info,
2248 GList *uris = *uri_list;
2250 gboolean force_file_uri;
2251 char force_file_uri_macro;
2254 g_return_if_fail (exec != NULL);
2256 /* On %u and %U, pass POSIX file path pointing to the URI via
2257 * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
2258 * running or the URI doesn't have a POSIX file path via FUSE
2259 * we'll just pass the URI.
2261 force_file_uri_macro = macro;
2262 force_file_uri = FALSE;
2268 force_file_uri_macro = 'f';
2269 force_file_uri = TRUE;
2272 force_file_uri_macro = 'F';
2273 force_file_uri = TRUE;
2289 if (!force_file_uri ||
2290 /* Pass URI if it contains an anchor */
2291 strchr (uri, '#') != NULL)
2293 expanded = expand_macro_single (macro, uri);
2297 expanded = expand_macro_single (force_file_uri_macro, uri);
2298 if (expanded == NULL)
2299 expanded = expand_macro_single (macro, uri);
2304 g_string_append (exec, expanded);
2320 if (!force_file_uri ||
2321 /* Pass URI if it contains an anchor */
2322 strchr (uri, '#') != NULL)
2324 expanded = expand_macro_single (macro, uri);
2328 expanded = expand_macro_single (force_file_uri_macro, uri);
2329 if (expanded == NULL)
2330 expanded = expand_macro_single (macro, uri);
2335 g_string_append (exec, expanded);
2341 if (uris != NULL && expanded)
2342 g_string_append_c (exec, ' ');
2348 if (info->icon_name)
2350 g_string_append (exec, "--icon ");
2351 expanded = g_shell_quote (info->icon_name);
2352 g_string_append (exec, expanded);
2360 expanded = g_shell_quote (info->name);
2361 g_string_append (exec, expanded);
2369 expanded = g_shell_quote (info->filename);
2370 g_string_append (exec, expanded);
2375 case 'm': /* deprecated */
2379 g_string_append_c (exec, '%');
2387 expand_application_parameters (GDesktopAppInfo *info,
2388 const gchar *exec_line,
2394 GList *uri_list = *uris;
2395 const char *p = exec_line;
2396 GString *expanded_exec;
2399 if (exec_line == NULL)
2401 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2402 _("Desktop file didn't specify Exec field"));
2406 expanded_exec = g_string_new (NULL);
2410 if (p[0] == '%' && p[1] != '\0')
2412 expand_macro (p[1], expanded_exec, info, uris);
2416 g_string_append_c (expanded_exec, *p);
2421 /* No file substitutions */
2422 if (uri_list == *uris && uri_list != NULL)
2424 /* If there is no macro default to %f. This is also what KDE does */
2425 g_string_append_c (expanded_exec, ' ');
2426 expand_macro ('f', expanded_exec, info, uris);
2429 res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
2430 g_string_free (expanded_exec, TRUE);
2435 prepend_terminal_to_vector (int *argc,
2442 char **term_argv = NULL;
2447 g_return_val_if_fail (argc != NULL, FALSE);
2448 g_return_val_if_fail (argv != NULL, FALSE);
2456 /* compute size if not given */
2459 for (i = 0; the_argv[i] != NULL; i++)
2465 term_argv = g_new0 (char *, 3);
2467 check = g_find_program_in_path ("gnome-terminal");
2470 term_argv[0] = check;
2471 /* Note that gnome-terminal takes -x and
2472 * as -e in gnome-terminal is broken we use that. */
2473 term_argv[1] = g_strdup ("-x");
2478 check = g_find_program_in_path ("nxterm");
2480 check = g_find_program_in_path ("color-xterm");
2482 check = g_find_program_in_path ("rxvt");
2484 check = g_find_program_in_path ("xterm");
2486 check = g_find_program_in_path ("dtterm");
2489 check = g_strdup ("xterm");
2490 g_warning ("couldn't find a terminal, falling back to xterm");
2492 term_argv[0] = check;
2493 term_argv[1] = g_strdup ("-e");
2496 real_argc = term_argc + *argc;
2497 real_argv = g_new (char *, real_argc + 1);
2499 for (i = 0; i < term_argc; i++)
2500 real_argv[i] = term_argv[i];
2502 for (j = 0; j < *argc; j++, i++)
2503 real_argv[i] = (char *)the_argv[j];
2505 real_argv[i] = NULL;
2511 /* we use g_free here as we sucked all the inner strings
2512 * out from it into real_argv */
2517 #endif /* G_OS_WIN32 */
2521 create_files_for_uris (GList *uris)
2528 for (iter = uris; iter; iter = iter->next)
2530 GFile *file = g_file_new_for_uri ((char *)iter->data);
2531 res = g_list_prepend (res, file);
2534 return g_list_reverse (res);
2539 GSpawnChildSetupFunc user_setup;
2540 gpointer user_setup_data;
2546 child_setup (gpointer user_data)
2548 ChildSetupData *data = user_data;
2550 if (data->pid_envvar)
2552 pid_t pid = getpid ();
2556 /* Write the pid into the space already reserved for it in the
2557 * environment array. We can't use sprintf because it might
2558 * malloc, so we do it by hand. It's simplest to write the pid
2559 * out backwards first, then copy it over.
2561 for (i = 0; pid; i++, pid /= 10)
2562 buf[i] = (pid % 10) + '0';
2563 for (i--; i >= 0; i--)
2564 *(data->pid_envvar++) = buf[i];
2565 *data->pid_envvar = '\0';
2568 if (data->user_setup)
2569 data->user_setup (data->user_setup_data);
2573 notify_desktop_launch (GDBusConnection *session_bus,
2574 GDesktopAppInfo *info,
2576 const char *display,
2581 GVariantBuilder uri_variant;
2582 GVariantBuilder extras_variant;
2584 const char *desktop_file_id;
2585 const char *gio_desktop_file;
2587 if (session_bus == NULL)
2590 g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2591 for (iter = uris; iter; iter = iter->next)
2592 g_variant_builder_add (&uri_variant, "s", iter->data);
2594 g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2595 if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2596 g_variant_builder_add (&extras_variant, "{sv}",
2600 gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2601 if (gio_desktop_file != NULL)
2602 g_variant_builder_add (&extras_variant, "{sv}",
2603 "origin-desktop-file",
2604 g_variant_new_bytestring (gio_desktop_file));
2605 if (g_get_prgname () != NULL)
2606 g_variant_builder_add (&extras_variant, "{sv}",
2608 g_variant_new_bytestring (g_get_prgname ()));
2609 g_variant_builder_add (&extras_variant, "{sv}",
2612 (gint64)getpid ()));
2615 desktop_file_id = info->filename;
2616 else if (info->desktop_id)
2617 desktop_file_id = info->desktop_id;
2619 desktop_file_id = "";
2621 msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2622 "org.gtk.gio.DesktopAppInfo",
2624 g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2625 g_variant_new_bytestring (desktop_file_id),
2626 display ? display : "",
2630 g_dbus_connection_send_message (session_bus,
2634 g_object_unref (msg);
2637 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2640 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo *info,
2641 GDBusConnection *session_bus,
2642 const gchar *exec_line,
2644 GAppLaunchContext *launch_context,
2645 GSpawnFlags spawn_flags,
2646 GSpawnChildSetupFunc user_setup,
2647 gpointer user_setup_data,
2648 GDesktopAppLaunchCallback pid_callback,
2649 gpointer pid_callback_data,
2652 gboolean completed = FALSE;
2654 char **argv, **envp;
2656 ChildSetupData data;
2658 g_return_val_if_fail (info != NULL, FALSE);
2663 envp = g_app_launch_context_get_environment (launch_context);
2665 envp = g_get_environ ();
2670 GList *launched_uris;
2675 if (!expand_application_parameters (info, exec_line, &uris, &argc, &argv, error))
2678 /* Get the subset of URIs we're launching with this process */
2679 launched_uris = NULL;
2680 for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
2681 launched_uris = g_list_prepend (launched_uris, iter->data);
2682 launched_uris = g_list_reverse (launched_uris);
2684 if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2686 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2687 _("Unable to find terminal required for application"));
2691 data.user_setup = user_setup;
2692 data.user_setup_data = user_setup_data;
2696 envp = g_environ_setenv (envp,
2697 "GIO_LAUNCHED_DESKTOP_FILE",
2700 envp = g_environ_setenv (envp,
2701 "GIO_LAUNCHED_DESKTOP_FILE_PID",
2702 "XXXXXXXXXXXXXXXXXXXX", /* filled in child_setup */
2704 data.pid_envvar = (char *)g_environ_getenv (envp, "GIO_LAUNCHED_DESKTOP_FILE_PID");
2708 data.pid_envvar = NULL;
2714 GList *launched_files = create_files_for_uris (launched_uris);
2716 if (info->startup_notify)
2718 sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2722 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2725 g_list_free_full (launched_files, g_object_unref);
2728 if (!g_spawn_async (info->path,
2738 g_app_launch_context_launch_failed (launch_context, sn_id);
2741 g_list_free (launched_uris);
2746 if (pid_callback != NULL)
2747 pid_callback (info, pid, pid_callback_data);
2749 if (launch_context != NULL)
2751 GVariantBuilder builder;
2752 GVariant *platform_data;
2754 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2755 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2757 g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2758 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2759 g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2760 g_variant_unref (platform_data);
2763 notify_desktop_launch (session_bus,
2771 g_list_free (launched_uris);
2776 while (uris != NULL);
2788 object_path_from_appid (const gchar *app_id)
2793 n = strlen (app_id);
2794 path = g_malloc (n + 2);
2798 for (i = 0; i < n; i++)
2799 if (app_id[i] != '.')
2800 path[i + 1] = app_id[i];
2810 g_desktop_app_info_make_platform_data (GDesktopAppInfo *info,
2812 GAppLaunchContext *launch_context)
2814 GVariantBuilder builder;
2816 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2820 GList *launched_files = create_files_for_uris (uris);
2822 if (info->startup_notify)
2826 sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2828 g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2831 g_list_free_full (launched_files, g_object_unref);
2834 return g_variant_builder_end (&builder);
2838 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo *info,
2839 GDBusConnection *session_bus,
2841 GAppLaunchContext *launch_context)
2843 GVariantBuilder builder;
2846 g_return_val_if_fail (info != NULL, FALSE);
2848 g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2854 g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2855 for (iter = uris; iter; iter = iter->next)
2856 g_variant_builder_add (&builder, "s", iter->data);
2857 g_variant_builder_close (&builder);
2860 g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2862 /* This is non-blocking API. Similar to launching via fork()/exec()
2863 * we don't wait around to see if the program crashed during startup.
2864 * This is what startup-notification's job is...
2866 object_path = object_path_from_appid (info->app_id);
2867 g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2868 uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2869 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
2870 g_free (object_path);
2876 g_desktop_app_info_launch_uris_internal (GAppInfo *appinfo,
2878 GAppLaunchContext *launch_context,
2879 GSpawnFlags spawn_flags,
2880 GSpawnChildSetupFunc user_setup,
2881 gpointer user_setup_data,
2882 GDesktopAppLaunchCallback pid_callback,
2883 gpointer pid_callback_data,
2886 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2887 GDBusConnection *session_bus;
2888 gboolean success = TRUE;
2890 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
2892 if (session_bus && info->app_id)
2893 g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context);
2895 success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
2896 spawn_flags, user_setup, user_setup_data,
2897 pid_callback, pid_callback_data, error);
2899 if (session_bus != NULL)
2901 /* This asynchronous flush holds a reference until it completes,
2902 * which ensures that the following unref won't immediately kill
2903 * the connection if we were the initial owner.
2905 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
2906 g_object_unref (session_bus);
2913 g_desktop_app_info_launch_uris (GAppInfo *appinfo,
2915 GAppLaunchContext *launch_context,
2918 return g_desktop_app_info_launch_uris_internal (appinfo, uris,
2920 _SPAWN_FLAGS_DEFAULT,
2921 NULL, NULL, NULL, NULL,
2926 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
2928 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2930 return info->exec &&
2931 ((strstr (info->exec, "%u") != NULL) ||
2932 (strstr (info->exec, "%U") != NULL));
2936 g_desktop_app_info_supports_files (GAppInfo *appinfo)
2938 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2940 return info->exec &&
2941 ((strstr (info->exec, "%f") != NULL) ||
2942 (strstr (info->exec, "%F") != NULL));
2946 g_desktop_app_info_launch (GAppInfo *appinfo,
2948 GAppLaunchContext *launch_context,
2958 uri = g_file_get_uri (files->data);
2959 uris = g_list_prepend (uris, uri);
2960 files = files->next;
2963 uris = g_list_reverse (uris);
2965 res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
2967 g_list_free_full (uris, g_free);
2973 * g_desktop_app_info_launch_uris_as_manager:
2974 * @appinfo: a #GDesktopAppInfo
2975 * @uris: (element-type utf8): List of URIs
2976 * @launch_context: (allow-none): a #GAppLaunchContext
2977 * @spawn_flags: #GSpawnFlags, used for each process
2978 * @user_setup: (scope call) (allow-none): a #GSpawnChildSetupFunc, used once
2980 * @user_setup_data: (closure user_setup) (allow-none): User data for @user_setup
2981 * @pid_callback: (scope call) (allow-none): Callback for child processes
2982 * @pid_callback_data: (closure pid_callback) (allow-none): User data for @callback
2983 * @error: return location for a #GError, or %NULL
2985 * This function performs the equivalent of g_app_info_launch_uris(),
2986 * but is intended primarily for operating system components that
2987 * launch applications. Ordinary applications should use
2988 * g_app_info_launch_uris().
2990 * If the application is launched via traditional UNIX fork()/exec()
2991 * then @spawn_flags, @user_setup and @user_setup_data are used for the
2992 * call to g_spawn_async(). Additionally, @pid_callback (with
2993 * @pid_callback_data) will be called to inform about the PID of the
2996 * If application launching occurs via some other mechanism (eg: D-Bus
2997 * activation) then @spawn_flags, @user_setup, @user_setup_data,
2998 * @pid_callback and @pid_callback_data are ignored.
3000 * Returns: %TRUE on successful launch, %FALSE otherwise.
3003 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo *appinfo,
3005 GAppLaunchContext *launch_context,
3006 GSpawnFlags spawn_flags,
3007 GSpawnChildSetupFunc user_setup,
3008 gpointer user_setup_data,
3009 GDesktopAppLaunchCallback pid_callback,
3010 gpointer pid_callback_data,
3013 return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
3024 /* OnlyShowIn API support {{{2 */
3027 * g_desktop_app_info_set_desktop_env:
3028 * @desktop_env: a string specifying what desktop this is
3030 * Sets the name of the desktop that the application is running in.
3031 * This is used by g_app_info_should_show() and
3032 * g_desktop_app_info_get_show_in() to evaluate the
3033 * `OnlyShowIn` and `NotShowIn`
3034 * desktop entry fields.
3036 * Should be called only once; subsequent calls are ignored.
3038 * Deprecated:2.42:do not use this API. Since 2.42 the value of the
3039 * `XDG_CURRENT_DESKTOP` environment variable will be used.
3042 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
3044 get_current_desktops (desktop_env);
3048 g_desktop_app_info_should_show (GAppInfo *appinfo)
3050 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3052 if (info->nodisplay)
3055 return g_desktop_app_info_get_show_in (info, NULL);
3058 /* mime types/default apps support {{{2 */
3067 ensure_dir (DirType type,
3070 char *path, *display_name;
3076 path = g_build_filename (g_get_user_config_dir (), NULL);
3080 path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
3084 path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
3088 g_assert_not_reached ();
3092 if (g_mkdir_with_parents (path, 0700) == 0)
3096 display_name = g_filename_display_name (path);
3097 if (type == APP_DIR)
3098 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3099 _("Can't create user application configuration folder %s: %s"),
3100 display_name, g_strerror (errsv));
3102 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3103 _("Can't create user MIME configuration folder %s: %s"),
3104 display_name, g_strerror (errsv));
3106 g_free (display_name);
3113 update_mimeapps_list (const char *desktop_id,
3114 const char *content_type,
3115 UpdateMimeFlags flags,
3118 char *dirname, *filename, *string;
3120 gboolean load_succeeded, res;
3121 char **old_list, **list;
3122 gsize length, data_size;
3125 char **content_types;
3127 /* Don't add both at start and end */
3128 g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
3129 (flags & UPDATE_MIME_SET_NON_DEFAULT)));
3131 dirname = ensure_dir (CONF_DIR, error);
3135 filename = g_build_filename (dirname, "mimeapps.list", NULL);
3138 key_file = g_key_file_new ();
3139 load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
3140 if (!load_succeeded ||
3141 (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
3142 !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
3143 !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
3145 g_key_file_free (key_file);
3146 key_file = g_key_file_new ();
3151 content_types = g_new (char *, 2);
3152 content_types[0] = g_strdup (content_type);
3153 content_types[1] = NULL;
3157 content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
3160 for (k = 0; content_types && content_types[k]; k++)
3162 /* set as default, if requested so */
3163 string = g_key_file_get_string (key_file,
3164 DEFAULT_APPLICATIONS_GROUP,
3168 if (g_strcmp0 (string, desktop_id) != 0 &&
3169 (flags & UPDATE_MIME_SET_DEFAULT))
3172 string = g_strdup (desktop_id);
3174 /* add in the non-default list too, if it's not already there */
3175 flags |= UPDATE_MIME_SET_NON_DEFAULT;
3178 if (string == NULL || desktop_id == NULL)
3179 g_key_file_remove_key (key_file,
3180 DEFAULT_APPLICATIONS_GROUP,
3184 g_key_file_set_string (key_file,
3185 DEFAULT_APPLICATIONS_GROUP,
3194 /* reuse the list from above */
3198 g_strfreev (content_types);
3199 content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
3202 for (k = 0; content_types && content_types[k]; k++)
3204 /* Add to the right place in the list */
3207 old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
3208 content_types[k], &length, NULL);
3210 list = g_new (char *, 1 + length + 1);
3214 /* if we're adding a last-used hint, just put the application in front of the list */
3215 if (flags & UPDATE_MIME_SET_LAST_USED)
3217 /* avoid adding this again as non-default later */
3218 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3219 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3221 list[i++] = g_strdup (desktop_id);
3226 for (j = 0; old_list[j] != NULL; j++)
3228 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3230 /* rewrite other entries if they're different from the new one */
3231 list[i++] = g_strdup (old_list[j]);
3233 else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3235 /* we encountered an old entry which is equal to the one we're adding as non-default,
3236 * don't change its position in the list.
3238 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3239 list[i++] = g_strdup (old_list[j]);
3244 /* add it at the end of the list */
3245 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3246 list[i++] = g_strdup (desktop_id);
3250 g_strfreev (old_list);
3252 if (list[0] == NULL || desktop_id == NULL)
3253 g_key_file_remove_key (key_file,
3254 ADDED_ASSOCIATIONS_GROUP,
3258 g_key_file_set_string_list (key_file,
3259 ADDED_ASSOCIATIONS_GROUP,
3261 (const char * const *)list, i);
3268 /* reuse the list from above */
3272 g_strfreev (content_types);
3273 content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
3276 for (k = 0; content_types && content_types[k]; k++)
3278 /* Remove from removed associations group (unless remove) */
3281 old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
3282 content_types[k], &length, NULL);
3284 list = g_new (char *, 1 + length + 1);
3287 if (flags & UPDATE_MIME_REMOVE)
3288 list[i++] = g_strdup (desktop_id);
3291 for (j = 0; old_list[j] != NULL; j++)
3293 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3294 list[i++] = g_strdup (old_list[j]);
3299 g_strfreev (old_list);
3301 if (list[0] == NULL || desktop_id == NULL)
3302 g_key_file_remove_key (key_file,
3303 REMOVED_ASSOCIATIONS_GROUP,
3307 g_key_file_set_string_list (key_file,
3308 REMOVED_ASSOCIATIONS_GROUP,
3310 (const char * const *)list, i);
3315 g_strfreev (content_types);
3317 data = g_key_file_to_data (key_file, &data_size, error);
3318 g_key_file_free (key_file);
3320 res = g_file_set_contents (filename, data, data_size, error);
3322 desktop_file_dirs_invalidate_user_config ();
3331 g_desktop_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
3332 const char *content_type,
3335 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3337 if (!g_desktop_app_info_ensure_saved (info, error))
3340 if (!info->desktop_id)
3342 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3343 _("Application information lacks an identifier"));
3347 /* both add support for the content type and set as last used */
3348 return update_mimeapps_list (info->desktop_id, content_type,
3349 UPDATE_MIME_SET_NON_DEFAULT |
3350 UPDATE_MIME_SET_LAST_USED,
3355 g_desktop_app_info_set_as_default_for_type (GAppInfo *appinfo,
3356 const char *content_type,
3359 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3361 if (!g_desktop_app_info_ensure_saved (info, error))
3364 if (!info->desktop_id)
3366 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3367 _("Application information lacks an identifier"));
3371 return update_mimeapps_list (info->desktop_id, content_type,
3372 UPDATE_MIME_SET_DEFAULT,
3377 update_program_done (GPid pid,
3381 /* Did the application exit correctly */
3382 if (g_spawn_check_exit_status (status, NULL))
3384 /* Here we could clean out any caches in use */
3389 run_update_command (char *command,
3398 GError *error = NULL;
3401 argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
3403 if (g_spawn_async ("/", argv,
3405 G_SPAWN_SEARCH_PATH |
3406 G_SPAWN_STDOUT_TO_DEV_NULL |
3407 G_SPAWN_STDERR_TO_DEV_NULL |
3408 G_SPAWN_DO_NOT_REAP_CHILD,
3409 NULL, NULL, /* No setup function */
3412 g_child_watch_add (pid, update_program_done, NULL);
3415 /* If we get an error at this point, it's quite likely the user doesn't
3416 * have an installed copy of either 'update-mime-database' or
3417 * 'update-desktop-database'. I don't think we want to popup an error
3418 * dialog at this point, so we just do a g_warning to give the user a
3419 * chance of debugging it.
3421 g_warning ("%s", error->message);
3422 g_error_free (error);
3429 g_desktop_app_info_set_as_default_for_extension (GAppInfo *appinfo,
3430 const char *extension,
3433 char *filename, *basename, *mimetype;
3437 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
3440 dirname = ensure_dir (MIMETYPE_DIR, error);
3444 basename = g_strdup_printf ("user-extension-%s.xml", extension);
3445 filename = g_build_filename (dirname, basename, NULL);
3449 mimetype = g_strdup_printf ("application/x-extension-%s", extension);
3451 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
3456 g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
3457 "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
3458 " <mime-type type=\"%s\">\n"
3459 " <comment>%s document</comment>\n"
3460 " <glob pattern=\"*.%s\"/>\n"
3462 "</mime-info>\n", mimetype, extension, extension);
3464 g_file_set_contents (filename, contents, -1, NULL);
3467 run_update_command ("update-mime-database", "mime");
3471 res = g_desktop_app_info_set_as_default_for_type (appinfo,
3481 g_desktop_app_info_add_supports_type (GAppInfo *appinfo,
3482 const char *content_type,
3485 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3487 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3490 return update_mimeapps_list (info->desktop_id, content_type,
3491 UPDATE_MIME_SET_NON_DEFAULT,
3496 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
3502 g_desktop_app_info_remove_supports_type (GAppInfo *appinfo,
3503 const char *content_type,
3506 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3508 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3511 return update_mimeapps_list (info->desktop_id, content_type,
3516 static const char **
3517 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
3519 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3521 return (const char**) info->mime_types;
3524 /* Saving and deleting {{{2 */
3527 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
3533 char *data, *desktop_id;
3538 if (info->filename != NULL)
3541 /* This is only used for object created with
3542 * g_app_info_create_from_commandline. All other
3543 * object should have a filename
3546 dirname = ensure_dir (APP_DIR, error);
3550 key_file = g_key_file_new ();
3552 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3553 "Encoding", "UTF-8");
3554 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3555 G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
3556 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3557 G_KEY_FILE_DESKTOP_KEY_TYPE,
3558 G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3560 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3561 G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3562 if (info->nodisplay)
3563 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3564 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3566 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3567 G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3569 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3570 G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3572 if (info->generic_name != NULL)
3573 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3574 GENERIC_NAME_KEY, info->generic_name);
3576 if (info->fullname != NULL)
3577 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3578 FULL_NAME_KEY, info->fullname);
3580 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3581 G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3583 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3584 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3586 data = g_key_file_to_data (key_file, &data_size, NULL);
3587 g_key_file_free (key_file);
3589 desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3590 filename = g_build_filename (dirname, desktop_id, NULL);
3591 g_free (desktop_id);
3594 fd = g_mkstemp (filename);
3599 display_name = g_filename_display_name (filename);
3600 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3601 _("Can't create user desktop file %s"), display_name);
3602 g_free (display_name);
3608 desktop_id = g_path_get_basename (filename);
3610 /* FIXME - actually handle error */
3611 (void) g_close (fd, NULL);
3613 res = g_file_set_contents (filename, data, data_size, error);
3617 g_free (desktop_id);
3622 info->filename = filename;
3623 info->desktop_id = desktop_id;
3625 run_update_command ("update-desktop-database", "applications");
3627 /* We just dropped a file in the user's desktop file directory. Save
3628 * the monitor the bother of having to notice it and invalidate
3631 * This means that calls directly following this will be able to see
3632 * the results immediately.
3634 desktop_file_dirs_invalidate_user_data ();
3640 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3642 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3646 if (strstr (info->filename, "/userapp-"))
3647 return g_access (info->filename, W_OK) == 0;
3654 g_desktop_app_info_delete (GAppInfo *appinfo)
3656 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3660 if (g_remove (info->filename) == 0)
3662 update_mimeapps_list (info->desktop_id, NULL,
3666 g_free (info->filename);
3667 info->filename = NULL;
3668 g_free (info->desktop_id);
3669 info->desktop_id = NULL;
3678 /* Create for commandline {{{2 */
3680 * g_app_info_create_from_commandline:
3681 * @commandline: the commandline to use
3682 * @application_name: (allow-none): the application name, or %NULL to use @commandline
3683 * @flags: flags that can specify details of the created #GAppInfo
3684 * @error: a #GError location to store the error occurring, %NULL to ignore.
3686 * Creates a new #GAppInfo from the given information.
3688 * Note that for @commandline, the quoting rules of the Exec key of the
3689 * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
3690 * are applied. For example, if the @commandline contains
3691 * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
3692 * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
3694 * Returns: (transfer full): new #GAppInfo for given command.
3697 g_app_info_create_from_commandline (const char *commandline,
3698 const char *application_name,
3699 GAppInfoCreateFlags flags,
3704 GDesktopAppInfo *info;
3706 g_return_val_if_fail (commandline, NULL);
3708 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
3710 info->filename = NULL;
3711 info->desktop_id = NULL;
3713 info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
3714 info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
3715 info->hidden = FALSE;
3716 if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
3717 info->exec = g_strconcat (commandline, " %u", NULL);
3719 info->exec = g_strconcat (commandline, " %f", NULL);
3720 info->nodisplay = TRUE;
3721 info->binary = binary_from_exec (info->exec);
3723 if (application_name)
3724 info->name = g_strdup (application_name);
3727 /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
3728 split = g_strsplit (commandline, " ", 2);
3729 basename = split[0] ? g_path_get_basename (split[0]) : NULL;
3731 info->name = basename;
3732 if (info->name == NULL)
3733 info->name = g_strdup ("custom");
3735 info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
3737 return G_APP_INFO (info);
3740 /* GAppInfo interface init */
3743 g_desktop_app_info_iface_init (GAppInfoIface *iface)
3745 iface->dup = g_desktop_app_info_dup;
3746 iface->equal = g_desktop_app_info_equal;
3747 iface->get_id = g_desktop_app_info_get_id;
3748 iface->get_name = g_desktop_app_info_get_name;
3749 iface->get_description = g_desktop_app_info_get_description;
3750 iface->get_executable = g_desktop_app_info_get_executable;
3751 iface->get_icon = g_desktop_app_info_get_icon;
3752 iface->launch = g_desktop_app_info_launch;
3753 iface->supports_uris = g_desktop_app_info_supports_uris;
3754 iface->supports_files = g_desktop_app_info_supports_files;
3755 iface->launch_uris = g_desktop_app_info_launch_uris;
3756 iface->should_show = g_desktop_app_info_should_show;
3757 iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
3758 iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
3759 iface->add_supports_type = g_desktop_app_info_add_supports_type;
3760 iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
3761 iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
3762 iface->can_delete = g_desktop_app_info_can_delete;
3763 iface->do_delete = g_desktop_app_info_delete;
3764 iface->get_commandline = g_desktop_app_info_get_commandline;
3765 iface->get_display_name = g_desktop_app_info_get_display_name;
3766 iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
3767 iface->get_supported_types = g_desktop_app_info_get_supported_types;
3770 /* Recommended applications {{{2 */
3772 /* Converts content_type into a list of itself with all of its parent
3773 * types (if include_fallback is enabled) or just returns a single-item
3774 * list with the unaliased content type.
3777 get_list_of_mimetypes (const gchar *content_type,
3778 gboolean include_fallback)
3783 array = g_ptr_array_new ();
3784 unaliased = _g_unix_content_type_unalias (content_type);
3785 g_ptr_array_add (array, unaliased);
3787 if (include_fallback)
3791 /* Iterate the array as we grow it, until we have nothing more to add */
3792 for (i = 0; i < array->len; i++)
3794 gchar **parents = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
3797 for (j = 0; parents[j]; j++)
3798 /* Don't add duplicates */
3799 if (!array_contains (array, parents[j]))
3800 g_ptr_array_add (array, parents[j]);
3802 g_free (parents[j]);
3804 /* We already stole or freed each element. Free the container. */
3809 g_ptr_array_add (array, NULL);
3811 return (gchar **) g_ptr_array_free (array, FALSE);
3815 g_desktop_app_info_get_desktop_ids_for_content_type (const gchar *content_type,
3816 gboolean include_fallback)
3818 GPtrArray *hits, *blacklist;
3822 hits = g_ptr_array_new ();
3823 blacklist = g_ptr_array_new ();
3825 types = get_list_of_mimetypes (content_type, include_fallback);
3827 desktop_file_dirs_lock ();
3829 for (i = 0; types[i]; i++)
3830 for (j = 0; j < n_desktop_file_dirs; j++)
3831 desktop_file_dir_mime_lookup (&desktop_file_dirs[j], types[i], hits, blacklist);
3833 /* We will keep the hits past unlocking, so we must dup them */
3834 for (i = 0; i < hits->len; i++)
3835 hits->pdata[i] = g_strdup (hits->pdata[i]);
3837 desktop_file_dirs_unlock ();
3839 g_ptr_array_add (hits, NULL);
3841 g_ptr_array_free (blacklist, TRUE);
3844 return (gchar **) g_ptr_array_free (hits, FALSE);
3848 * g_app_info_get_recommended_for_type:
3849 * @content_type: the content type to find a #GAppInfo for
3851 * Gets a list of recommended #GAppInfos for a given content type, i.e.
3852 * those applications which claim to support the given content type exactly,
3853 * and not by MIME type subclassing.
3854 * Note that the first application of the list is the last used one, i.e.
3855 * the last one for which g_app_info_set_as_last_used_for_type() has been
3858 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3859 * for given @content_type or %NULL on error.
3864 g_app_info_get_recommended_for_type (const gchar *content_type)
3866 gchar **desktop_ids;
3870 g_return_val_if_fail (content_type != NULL, NULL);
3872 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
3875 for (i = 0; desktop_ids[i]; i++)
3877 GDesktopAppInfo *info;
3879 info = g_desktop_app_info_new (desktop_ids[i]);
3881 infos = g_list_prepend (infos, info);
3884 g_strfreev (desktop_ids);
3886 return g_list_reverse (infos);
3890 * g_app_info_get_fallback_for_type:
3891 * @content_type: the content type to find a #GAppInfo for
3893 * Gets a list of fallback #GAppInfos for a given content type, i.e.
3894 * those applications which claim to support the given content type
3895 * by MIME type subclassing and not directly.
3897 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3898 * for given @content_type or %NULL on error.
3903 g_app_info_get_fallback_for_type (const gchar *content_type)
3905 gchar **recommended_ids;
3910 g_return_val_if_fail (content_type != NULL, NULL);
3912 recommended_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
3913 all_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
3916 for (i = 0; all_ids[i]; i++)
3918 GDesktopAppInfo *info;
3921 /* Don't return the ones on the recommended list */
3922 for (j = 0; recommended_ids[j]; j++)
3923 if (g_str_equal (all_ids[i], recommended_ids[j]))
3926 if (recommended_ids[j])
3929 info = g_desktop_app_info_new (all_ids[i]);
3932 infos = g_list_prepend (infos, info);
3935 g_strfreev (recommended_ids);
3936 g_strfreev (all_ids);
3938 return g_list_reverse (infos);
3942 * g_app_info_get_all_for_type:
3943 * @content_type: the content type to find a #GAppInfo for
3945 * Gets a list of all #GAppInfos for a given content type,
3946 * including the recommended and fallback #GAppInfos. See
3947 * g_app_info_get_recommended_for_type() and
3948 * g_app_info_get_fallback_for_type().
3950 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3951 * for given @content_type or %NULL on error.
3954 g_app_info_get_all_for_type (const char *content_type)
3956 gchar **desktop_ids;
3960 g_return_val_if_fail (content_type != NULL, NULL);
3962 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
3965 for (i = 0; desktop_ids[i]; i++)
3967 GDesktopAppInfo *info;
3969 info = g_desktop_app_info_new (desktop_ids[i]);
3971 infos = g_list_prepend (infos, info);
3974 g_strfreev (desktop_ids);
3976 return g_list_reverse (infos);
3980 * g_app_info_reset_type_associations:
3981 * @content_type: a content type
3983 * Removes all changes to the type associations done by
3984 * g_app_info_set_as_default_for_type(),
3985 * g_app_info_set_as_default_for_extension(),
3986 * g_app_info_add_supports_type() or
3987 * g_app_info_remove_supports_type().
3992 g_app_info_reset_type_associations (const char *content_type)
3994 update_mimeapps_list (NULL, content_type,
4000 * g_app_info_get_default_for_type:
4001 * @content_type: the content type to find a #GAppInfo for
4002 * @must_support_uris: if %TRUE, the #GAppInfo is expected to
4005 * Gets the default #GAppInfo for a given content type.
4007 * Returns: (transfer full): #GAppInfo for given @content_type or
4011 g_app_info_get_default_for_type (const char *content_type,
4012 gboolean must_support_uris)
4014 GPtrArray *blacklist;
4020 g_return_val_if_fail (content_type != NULL, NULL);
4022 types = get_list_of_mimetypes (content_type, TRUE);
4024 blacklist = g_ptr_array_new ();
4025 results = g_ptr_array_new ();
4028 desktop_file_dirs_lock ();
4030 for (i = 0; types[i]; i++)
4032 /* Collect all the default apps for this type */
4033 for (j = 0; j < n_desktop_file_dirs; j++)
4034 desktop_file_dir_default_lookup (&desktop_file_dirs[j], types[i], results);
4036 /* Consider the associations as well... */
4037 for (j = 0; j < n_desktop_file_dirs; j++)
4038 desktop_file_dir_mime_lookup (&desktop_file_dirs[j], types[i], results, blacklist);
4040 /* (If any), see if one of those apps is installed... */
4041 for (j = 0; j < results->len; j++)
4043 const gchar *desktop_id = g_ptr_array_index (results, j);
4045 for (k = 0; k < n_desktop_file_dirs; k++)
4047 info = (GAppInfo *) desktop_file_dir_get_app (&desktop_file_dirs[k], desktop_id);
4051 if (!must_support_uris || g_app_info_supports_uris (info))
4054 g_clear_object (&info);
4059 /* Reset the list, ready to try again with the next (parent)
4060 * mimetype, but keep the blacklist in place.
4062 g_ptr_array_set_size (results, 0);
4066 desktop_file_dirs_unlock ();
4068 g_ptr_array_unref (blacklist);
4069 g_ptr_array_unref (results);
4076 * g_app_info_get_default_for_uri_scheme:
4077 * @uri_scheme: a string containing a URI scheme.
4079 * Gets the default application for handling URIs with
4080 * the given URI scheme. A URI scheme is the initial part
4081 * of the URI, up to but not including the ':', e.g. "http",
4084 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4087 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
4090 char *content_type, *scheme_down;
4092 scheme_down = g_ascii_strdown (uri_scheme, -1);
4093 content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
4094 g_free (scheme_down);
4095 app_info = g_app_info_get_default_for_type (content_type, FALSE);
4096 g_free (content_type);
4101 /* "Get all" API {{{2 */
4104 * g_desktop_app_info_get_implementations:
4105 * @interface: the name of the interface
4107 * Gets all applications that implement @interface.
4109 * An application implements an interface if that interface is listed in
4110 * the Implements= line of the desktop file of the application.
4112 * Returns: (element-type GDesktopAppInfo) (transfer full): a list of #GDesktopAppInfo
4118 g_desktop_app_info_get_implementations (const gchar *interface)
4120 GList *result = NULL;
4124 desktop_file_dirs_lock ();
4126 for (i = 0; i < n_desktop_file_dirs; i++)
4127 desktop_file_dir_get_implementations (&desktop_file_dirs[i], &result, interface);
4129 desktop_file_dirs_unlock ();
4134 gchar *name = (*ptr)->data;
4135 GDesktopAppInfo *app;
4137 app = g_desktop_app_info_new (name);
4143 ptr = &(*ptr)->next;
4146 *ptr = g_list_delete_link (*ptr, *ptr);
4153 * g_desktop_app_info_search:
4154 * @search_string: the search string to use
4156 * Searches desktop files for ones that match @search_string.
4158 * The return value is an array of strvs. Each strv contains a list of
4159 * applications that matched @search_string with an equal score. The
4160 * outer list is sorted by score so that the first strv contains the
4161 * best-matching applications, and so on.
4162 * The algorithm for determining matches is undefined and may change at
4165 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
4166 * list of strvs. Free each item with g_strfreev() and free the outer
4167 * list with g_free().
4170 g_desktop_app_info_search (const gchar *search_string)
4172 gchar **search_tokens;
4173 gint last_category = -1;
4175 gint n_categories = 0;
4176 gint start_of_category;
4179 search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
4181 desktop_file_dirs_lock ();
4183 reset_total_search_results ();
4185 for (i = 0; i < n_desktop_file_dirs; i++)
4187 for (j = 0; search_tokens[j]; j++)
4189 desktop_file_dir_search (&desktop_file_dirs[i], search_tokens[j]);
4190 merge_token_results (j == 0);
4192 merge_directory_results ();
4195 sort_total_search_results ();
4197 /* Count the total number of unique categories */
4198 for (i = 0; i < static_total_results_size; i++)
4199 if (static_total_results[i].category != last_category)
4201 last_category = static_total_results[i].category;
4205 results = g_new (gchar **, n_categories + 1);
4207 /* Start loading into the results list */
4208 start_of_category = 0;
4209 for (i = 0; i < n_categories; i++)
4211 gint n_items_in_category = 0;
4215 this_category = static_total_results[start_of_category].category;
4217 while (start_of_category + n_items_in_category < static_total_results_size &&
4218 static_total_results[start_of_category + n_items_in_category].category == this_category)
4219 n_items_in_category++;
4221 results[i] = g_new (gchar *, n_items_in_category + 1);
4222 for (j = 0; j < n_items_in_category; j++)
4223 results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
4224 results[i][j] = NULL;
4226 start_of_category += n_items_in_category;
4230 desktop_file_dirs_unlock ();
4232 g_strfreev (search_tokens);
4238 * g_app_info_get_all:
4240 * Gets a list of all of the applications currently registered
4243 * For desktop files, this includes applications that have
4244 * `NoDisplay=true` set or are excluded from display by means
4245 * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
4246 * The returned list does not include applications which have
4247 * the `Hidden` key set.
4249 * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
4252 g_app_info_get_all (void)
4255 GHashTableIter iter;
4260 apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4262 desktop_file_dirs_lock ();
4264 for (i = 0; i < n_desktop_file_dirs; i++)
4265 desktop_file_dir_get_all (&desktop_file_dirs[i], apps);
4267 desktop_file_dirs_unlock ();
4270 g_hash_table_iter_init (&iter, apps);
4271 while (g_hash_table_iter_next (&iter, NULL, &value))
4274 infos = g_list_prepend (infos, value);
4277 g_hash_table_destroy (apps);
4282 /* GDesktopAppInfoLookup interface {{{2 */
4285 * GDesktopAppInfoLookup:
4287 * #GDesktopAppInfoLookup is an opaque data structure and can only be accessed
4288 * using the following functions.
4291 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4293 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4294 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4297 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4301 /* "Get for mime type" APIs {{{2 */
4304 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4305 * @lookup: a #GDesktopAppInfoLookup
4306 * @uri_scheme: a string containing a URI scheme.
4308 * Gets the default application for launching applications
4309 * using this URI scheme for a particular GDesktopAppInfoLookup
4312 * The GDesktopAppInfoLookup interface and this function is used
4313 * to implement g_app_info_get_default_for_uri_scheme() backends
4314 * in a GIO module. There is no reason for applications to use it
4315 * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4317 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4319 * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
4322 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4323 const char *uri_scheme)
4325 GDesktopAppInfoLookupIface *iface;
4327 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4329 iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4331 return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4334 G_GNUC_END_IGNORE_DEPRECATIONS
4336 /* Misc getter APIs {{{2 */
4339 * g_desktop_app_info_get_startup_wm_class:
4340 * @info: a #GDesktopAppInfo that supports startup notify
4342 * Retrieves the StartupWMClass field from @info. This represents the
4343 * WM_CLASS property of the main window of the application, if launched
4346 * Returns: (transfer none): the startup WM class, or %NULL if none is set
4347 * in the desktop file.
4352 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4354 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4356 return info->startup_wm_class;
4360 * g_desktop_app_info_get_string:
4361 * @info: a #GDesktopAppInfo
4362 * @key: the key to look up
4364 * Looks up a string value in the keyfile backing @info.
4366 * The @key is looked up in the "Desktop Entry" group.
4368 * Returns: a newly allocated string, or %NULL if the key
4374 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4377 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4379 return g_key_file_get_string (info->keyfile,
4380 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4384 * g_desktop_app_info_get_boolean:
4385 * @info: a #GDesktopAppInfo
4386 * @key: the key to look up
4388 * Looks up a boolean value in the keyfile backing @info.
4390 * The @key is looked up in the "Desktop Entry" group.
4392 * Returns: the boolean value, or %FALSE if the key
4398 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4401 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4403 return g_key_file_get_boolean (info->keyfile,
4404 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4408 * g_desktop_app_info_has_key:
4409 * @info: a #GDesktopAppInfo
4410 * @key: the key to look up
4412 * Returns whether @key exists in the "Desktop Entry" group
4413 * of the keyfile backing @info.
4415 * Returns: %TRUE if the @key exists
4420 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4423 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4425 return g_key_file_has_key (info->keyfile,
4426 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4429 /* Desktop actions support {{{2 */
4432 * g_desktop_app_info_list_actions:
4433 * @info: a #GDesktopAppInfo
4435 * Returns the list of "additional application actions" supported on the
4436 * desktop file, as per the desktop file specification.
4438 * As per the specification, this is the list of actions that are
4439 * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4441 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4445 const gchar * const *
4446 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4448 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4450 return (const gchar **) info->actions;
4454 app_info_has_action (GDesktopAppInfo *info,
4455 const gchar *action_name)
4459 for (i = 0; info->actions[i]; i++)
4460 if (g_str_equal (info->actions[i], action_name))
4467 * g_desktop_app_info_get_action_name:
4468 * @info: a #GDesktopAppInfo
4469 * @action_name: the name of the action as from
4470 * g_desktop_app_info_list_actions()
4472 * Gets the user-visible display name of the "additional application
4473 * action" specified by @action_name.
4475 * This corresponds to the "Name" key within the keyfile group for the
4478 * Returns: (transfer full): the locale-specific action name
4483 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4484 const gchar *action_name)
4489 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4490 g_return_val_if_fail (action_name != NULL, NULL);
4491 g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4493 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4494 result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4495 g_free (group_name);
4497 /* The spec says that the Name field must be given.
4499 * If it's not, let's follow the behaviour of our get_name()
4500 * implementation above and never return %NULL.
4503 result = g_strdup (_("Unnamed"));
4509 * g_desktop_app_info_launch_action:
4510 * @info: a #GDesktopAppInfo
4511 * @action_name: the name of the action as from
4512 * g_desktop_app_info_list_actions()
4513 * @launch_context: (allow-none): a #GAppLaunchContext
4515 * Activates the named application action.
4517 * You may only call this function on action names that were
4518 * returned from g_desktop_app_info_list_actions().
4520 * Note that if the main entry of the desktop file indicates that the
4521 * application supports startup notification, and @launch_context is
4522 * non-%NULL, then startup notification will be used when activating the
4523 * action (and as such, invocation of the action on the receiving side
4524 * must signal the end of startup notification when it is completed).
4525 * This is the expected behaviour of applications declaring additional
4526 * actions, as per the desktop file specification.
4528 * As with g_app_info_launch() there is no way to detect failures that
4529 * occur while using this function.
4534 g_desktop_app_info_launch_action (GDesktopAppInfo *info,
4535 const gchar *action_name,
4536 GAppLaunchContext *launch_context)
4538 GDBusConnection *session_bus;
4540 g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4541 g_return_if_fail (action_name != NULL);
4542 g_return_if_fail (app_info_has_action (info, action_name));
4544 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4546 if (session_bus && info->app_id)
4550 object_path = object_path_from_appid (info->app_id);
4551 g_dbus_connection_call (session_bus, info->app_id, object_path,
4552 "org.freedesktop.Application", "ActivateAction",
4553 g_variant_new ("(sav@a{sv})", action_name, NULL,
4554 g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4555 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4556 g_free (object_path);
4563 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4564 exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4565 g_free (group_name);
4568 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4569 _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL, NULL);
4572 if (session_bus != NULL)
4574 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
4575 g_object_unref (session_bus);
4580 /* vim:set foldmethod=marker: */