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.1 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>
27 /* For the #GDesktopAppInfoLookup macros; since macro deprecation is implemented
28 * in the preprocessor, we need to define this before including glib.h*/
29 #ifndef GLIB_DISABLE_DEPRECATION_WARNINGS
30 #define GLIB_DISABLE_DEPRECATION_WARNINGS
37 #ifdef HAVE_CRT_EXTERNS_H
38 #include <crt_externs.h>
41 #include "gcontenttypeprivate.h"
42 #include "gdesktopappinfo.h"
44 #include "glib-unix.h"
48 #include "gthemedicon.h"
49 #include "gfileicon.h"
50 #include <glib/gstdio.h>
52 #include "giomodule-priv.h"
54 #include "gappinfoprivate.h"
55 #include "glocalfilemonitor.h"
58 #include "gdocumentportal.h"
62 * SECTION:gdesktopappinfo
63 * @title: GDesktopAppInfo
64 * @short_description: Application information from desktop files
65 * @include: gio/gdesktopappinfo.h
67 * #GDesktopAppInfo is an implementation of #GAppInfo based on
70 * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
71 * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
75 #define DEFAULT_APPLICATIONS_GROUP "Default Applications"
76 #define ADDED_ASSOCIATIONS_GROUP "Added Associations"
77 #define REMOVED_ASSOCIATIONS_GROUP "Removed Associations"
78 #define MIME_CACHE_GROUP "MIME Cache"
79 #define GENERIC_NAME_KEY "GenericName"
80 #define FULL_NAME_KEY "X-GNOME-FullName"
81 #define KEYWORDS_KEY "Keywords"
82 #define STARTUP_WM_CLASS_KEY "StartupWMClass"
89 static void g_desktop_app_info_iface_init (GAppInfoIface *iface);
90 static gboolean g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
96 * Information about an installed application from a desktop file.
98 struct _GDesktopAppInfo
100 GObject parent_instance;
122 char *startup_wm_class;
129 guint startup_notify : 1;
134 UPDATE_MIME_NONE = 1 << 0,
135 UPDATE_MIME_SET_DEFAULT = 1 << 1,
136 UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
137 UPDATE_MIME_REMOVE = 1 << 3,
138 UPDATE_MIME_SET_LAST_USED = 1 << 4,
141 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
142 G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
144 /* DesktopFileDir implementation {{{1 */
148 gatomicrefcount ref_count;
150 gchar *alternatively_watching;
153 GFileMonitor *monitor;
154 GHashTable *app_names;
155 GHashTable *mime_tweaks;
156 GHashTable *memory_index;
157 GHashTable *memory_implementations;
160 static GPtrArray *desktop_file_dirs = NULL;
161 static const gchar *desktop_file_dirs_config_dir = NULL;
162 static DesktopFileDir *desktop_file_dir_user_config = NULL; /* (owned) */
163 static DesktopFileDir *desktop_file_dir_user_data = NULL; /* (owned) */
164 static GMutex desktop_file_dir_lock;
166 /* Monitor 'changed' signal handler {{{2 */
167 static void desktop_file_dir_reset (DesktopFileDir *dir);
169 static DesktopFileDir *
170 desktop_file_dir_ref (DesktopFileDir *dir)
172 g_atomic_ref_count_inc (&dir->ref_count);
178 desktop_file_dir_unref (DesktopFileDir *dir)
180 if (g_atomic_ref_count_dec (&dir->ref_count))
182 desktop_file_dir_reset (dir);
189 * desktop_file_dir_get_alternative_dir:
190 * @dir: a #DesktopFileDir
192 * Gets the "alternative" directory to monitor in case the path
195 * If the path exists this will return NULL, otherwise it will return a
196 * parent directory of the path.
198 * This is used to avoid inotify on a non-existent directory (which
199 * results in polling).
201 * See https://bugzilla.gnome.org/show_bug.cgi?id=522314 for more info.
204 desktop_file_dir_get_alternative_dir (DesktopFileDir *dir)
208 /* If the directory itself exists then we need no alternative. */
209 if (g_access (dir->path, R_OK | X_OK) == 0)
212 /* Otherwise, try the parent directories until we find one. */
213 parent = g_path_get_dirname (dir->path);
215 while (g_access (parent, R_OK | X_OK) != 0)
219 parent = g_path_get_dirname (tmp);
221 /* If somehow we get to '/' or '.' then just stop... */
222 if (g_str_equal (parent, tmp))
235 desktop_file_dir_changed (GFileMonitor *monitor,
238 GFileMonitorEvent event_type,
241 DesktopFileDir *dir = user_data;
242 gboolean do_nothing = FALSE;
244 /* We are not interested in receiving notifications forever just
245 * because someone asked about one desktop file once.
247 * After we receive the first notification, reset the dir, destroying
248 * the monitor. We will take this as a hint, next time that we are
249 * asked, that we need to check if everything is up to date.
251 * If this is a notification for a parent directory (because the
252 * desktop directory didn't exist) then we shouldn't fire the signal
253 * unless something actually changed.
255 g_mutex_lock (&desktop_file_dir_lock);
257 if (dir->alternatively_watching)
259 gchar *alternative_dir;
261 alternative_dir = desktop_file_dir_get_alternative_dir (dir);
262 do_nothing = alternative_dir && g_str_equal (dir->alternatively_watching, alternative_dir);
263 g_free (alternative_dir);
267 desktop_file_dir_reset (dir);
269 g_mutex_unlock (&desktop_file_dir_lock);
271 /* Notify anyone else who may be interested */
273 g_app_info_monitor_fire ();
276 /* Internal utility functions {{{2 */
279 * desktop_file_dir_app_name_is_masked:
280 * @dir: a #DesktopFileDir
281 * @app_name: an application ID
283 * Checks if @app_name is masked for @dir.
285 * An application is masked if a similarly-named desktop file exists in
286 * a desktop file directory with higher precedence. Masked desktop
287 * files should be ignored.
290 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
291 const gchar *app_name)
295 for (i = 0; i < desktop_file_dirs->len; i++)
297 DesktopFileDir *i_dir = g_ptr_array_index (desktop_file_dirs, i);
301 if (i_dir->app_names && g_hash_table_contains (i_dir->app_names, app_name))
308 /* Not much to go on from https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
309 * so validate it as a non-empty alphanumeric ASCII string with `-` and `_` allowed.
311 * Validation is important as the desktop IDs are used to construct filenames,
312 * and may be set by an unprivileged caller if running in a setuid program. */
314 validate_xdg_desktop (const gchar *desktop)
318 for (i = 0; desktop[i] != '\0'; i++)
319 if (desktop[i] != '-' && desktop[i] != '_' &&
320 !g_ascii_isalnum (desktop[i]))
330 get_valid_current_desktops (const char *value)
334 GPtrArray *valid_desktops;
337 value = g_getenv ("XDG_CURRENT_DESKTOP");
341 tmp = g_strsplit (value, G_SEARCHPATH_SEPARATOR_S, 0);
342 valid_desktops = g_ptr_array_new_full (g_strv_length (tmp) + 1, g_free);
343 for (i = 0; tmp[i]; i++)
345 if (validate_xdg_desktop (tmp[i]))
346 g_ptr_array_add (valid_desktops, tmp[i]);
350 g_ptr_array_add (valid_desktops, NULL);
352 tmp = (char **) g_ptr_array_steal (valid_desktops, NULL);
353 g_ptr_array_unref (valid_desktops);
357 static const gchar * const *
358 get_lowercase_current_desktops (void)
360 static gchar **result;
362 if (g_once_init_enter (&result))
364 char **tmp = get_valid_current_desktops (NULL);
367 for (i = 0; tmp[i]; i++)
369 /* Convert to lowercase. */
370 for (j = 0; tmp[i][j]; j++)
371 tmp[i][j] = g_ascii_tolower (tmp[i][j]);
374 g_once_init_leave (&result, tmp);
377 return (const gchar **) result;
380 static const gchar * const *
381 get_current_desktops (const gchar *value)
383 static gchar **result;
385 if (g_once_init_enter (&result))
387 char **tmp = get_valid_current_desktops (value);
389 g_once_init_leave (&result, tmp);
392 return (const gchar **) result;
396 * add_to_table_if_appropriate:
397 * @apps: a string to GDesktopAppInfo hash table
398 * @app_name: the name of the application
399 * @info: a #GDesktopAppInfo, or NULL
401 * If @info is non-%NULL and non-hidden, then add it to @apps, using
402 * @app_name as a key.
404 * If @info is non-%NULL then this function will consume the passed-in
408 add_to_table_if_appropriate (GHashTable *apps,
409 const gchar *app_name,
410 GDesktopAppInfo *info)
417 g_object_unref (info);
421 g_free (info->desktop_id);
422 info->desktop_id = g_strdup (app_name);
424 g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
431 DESKTOP_KEY_GenericName,
432 DESKTOP_KEY_Keywords,
434 DESKTOP_KEY_X_GNOME_FullName,
439 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
440 /* Note: lower numbers are a better match.
442 * In case we want two keys to match at the same level, we can just
443 * use the same number for the two different keys.
445 [DESKTOP_KEY_Name] = 1,
446 [DESKTOP_KEY_Exec] = 2,
447 [DESKTOP_KEY_Keywords] = 3,
448 [DESKTOP_KEY_GenericName] = 4,
449 [DESKTOP_KEY_X_GNOME_FullName] = 5,
450 [DESKTOP_KEY_Comment] = 6
453 /* Common prefix commands to ignore from Exec= lines */
454 const char * const exec_key_match_blocklist[] = {
470 desktop_key_get_name (guint key_id)
474 case DESKTOP_KEY_Comment:
476 case DESKTOP_KEY_Exec:
478 case DESKTOP_KEY_GenericName:
479 return GENERIC_NAME_KEY;
480 case DESKTOP_KEY_Keywords:
482 case DESKTOP_KEY_Name:
484 case DESKTOP_KEY_X_GNOME_FullName:
485 return FULL_NAME_KEY;
487 g_assert_not_reached ();
491 /* Search global state {{{2
493 * We only ever search under a global lock, so we can use (and reuse)
494 * some global data to reduce allocations made while searching.
496 * In short, we keep around arrays of results that we expand as needed
497 * (and never shrink).
499 * static_token_results: this is where we append the results for each
500 * token within a given desktop directory, as we handle it (which is
501 * a union of all matches for this term)
503 * static_search_results: this is where we build the complete results
504 * for a single directory (which is an intersection of the matches
505 * found for each term)
507 * static_total_results: this is where we build the complete results
508 * across all directories (which is a union of the matches found in
511 * The app_names that enter these tables are always pointer-unique (in
512 * the sense that string equality is the same as pointer equality).
513 * This can be guaranteed for two reasons:
515 * - we mask appids so that a given appid will only ever appear within
516 * the highest-precedence directory that contains it. We never
517 * return search results from a lower-level directory if a desktop
518 * file exists in a higher-level one.
520 * - within a given directory, the string is unique because it's the
521 * key in the hashtable of all app_ids for that directory.
523 * We perform a merging of the results in merge_token_results(). This
524 * works by ordering the two lists and moving through each of them (at
525 * the same time) looking for common elements, rejecting uncommon ones.
526 * "Order" here need not mean any particular thing, as long as it is
527 * some order. Because of the uniqueness of our strings, we can use
528 * pointer order. That's what's going on in compare_results() below.
532 const gchar *app_name;
536 static struct search_result *static_token_results;
537 static gint static_token_results_size;
538 static gint static_token_results_allocated;
539 static struct search_result *static_search_results;
540 static gint static_search_results_size;
541 static gint static_search_results_allocated;
542 static struct search_result *static_total_results;
543 static gint static_total_results_size;
544 static gint static_total_results_allocated;
546 /* And some functions for performing nice operations against it */
548 compare_results (gconstpointer a,
551 const struct search_result *ra = a;
552 const struct search_result *rb = b;
554 if (ra->app_name < rb->app_name)
557 else if (ra->app_name > rb->app_name)
561 return ra->category - rb->category;
565 compare_categories (gconstpointer a,
568 const struct search_result *ra = a;
569 const struct search_result *rb = b;
571 return ra->category - rb->category;
575 add_token_result (const gchar *app_name,
578 if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
580 static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
581 static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
584 static_token_results[static_token_results_size].app_name = app_name;
585 static_token_results[static_token_results_size].category = category;
586 static_token_results_size++;
590 merge_token_results (gboolean first)
592 if (static_token_results_size != 0)
593 qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
595 /* If this is the first token then we are basically merging a list with
596 * itself -- we only perform de-duplication.
598 * If this is not the first token then we are doing a real merge.
602 const gchar *last_name = NULL;
605 /* We must de-duplicate, but we do so by taking the best category
608 * The final list can be as large as the input here, so make sure
609 * we have enough room (even if it's too much room).
612 if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
614 static_search_results_allocated = static_token_results_allocated;
615 static_search_results = g_renew (struct search_result,
616 static_search_results,
617 static_search_results_allocated);
620 for (i = 0; i < static_token_results_size; i++)
622 /* The list is sorted so that the best match for a given id
623 * will be at the front, so once we have copied an id, skip
624 * the rest of the entries for the same id.
626 if (static_token_results[i].app_name == last_name)
629 last_name = static_token_results[i].app_name;
631 static_search_results[static_search_results_size++] = static_token_results[i];
636 const gchar *last_name = NULL;
640 /* We only ever remove items from the results list, so no need to
641 * resize to ensure that we have enough room.
643 for (i = 0; i < static_token_results_size; i++)
645 if (static_token_results[i].app_name == last_name)
648 last_name = static_token_results[i].app_name;
650 /* Now we only want to have a result in static_search_results
651 * if we already have it there *and* we have it in
652 * static_token_results as well. The category will be the
655 * Skip past the results in static_search_results that are not
656 * going to be matches.
658 while (k < static_search_results_size &&
659 static_search_results[k].app_name < static_token_results[i].app_name)
662 if (k < static_search_results_size &&
663 static_search_results[k].app_name == static_token_results[i].app_name)
667 * Category should be the worse of the two (ie:
668 * numerically larger).
670 static_search_results[j].app_name = static_search_results[k].app_name;
671 static_search_results[j].category = MAX (static_search_results[k].category,
672 static_token_results[i].category);
677 static_search_results_size = j;
680 /* Clear it out for next time... */
681 static_token_results_size = 0;
685 reset_total_search_results (void)
687 static_total_results_size = 0;
691 sort_total_search_results (void)
693 if (static_total_results_size != 0)
694 qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
698 merge_directory_results (void)
700 if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
702 static_total_results_allocated = MAX (16, static_total_results_allocated);
703 while (static_total_results_allocated < static_total_results_size + static_search_results_size)
704 static_total_results_allocated *= 2;
705 static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
708 if (static_total_results + static_total_results_size != 0)
709 memcpy (static_total_results + static_total_results_size,
710 static_search_results,
711 static_search_results_size * sizeof (struct search_result));
713 static_total_results_size += static_search_results_size;
715 /* Clear it out for next time... */
716 static_search_results_size = 0;
719 /* Support for unindexed DesktopFileDirs {{{2 */
721 get_apps_from_dir (GHashTable **apps,
725 const char *basename;
728 dir = g_dir_open (dirname, 0, NULL);
733 while ((basename = g_dir_read_name (dir)) != NULL)
737 filename = g_build_filename (dirname, basename, NULL);
739 if (g_str_has_suffix (basename, ".desktop"))
743 app_name = g_strconcat (prefix, basename, NULL);
746 *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
748 g_hash_table_insert (*apps, app_name, g_strdup (filename));
750 else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
754 subprefix = g_strconcat (prefix, basename, "-", NULL);
755 get_apps_from_dir (apps, filename, subprefix);
770 } UnindexedMimeTweaks;
773 free_mime_tweaks (gpointer data)
775 UnindexedMimeTweaks *tweaks = data;
777 g_strfreev (tweaks->additions);
778 g_strfreev (tweaks->removals);
779 g_strfreev (tweaks->defaults);
781 g_slice_free (UnindexedMimeTweaks, tweaks);
784 static UnindexedMimeTweaks *
785 desktop_file_dir_unindexed_get_tweaks (DesktopFileDir *dir,
786 const gchar *mime_type)
788 UnindexedMimeTweaks *tweaks;
789 gchar *unaliased_type;
791 unaliased_type = _g_unix_content_type_unalias (mime_type);
792 tweaks = g_hash_table_lookup (dir->mime_tweaks, unaliased_type);
796 tweaks = g_slice_new0 (UnindexedMimeTweaks);
797 g_hash_table_insert (dir->mime_tweaks, unaliased_type, tweaks);
800 g_free (unaliased_type);
805 /* consumes 'to_add' */
807 expand_strv (gchar ***strv_ptr,
809 gchar * const *blocklist)
811 guint strv_len, add_len;
822 strv_len = g_strv_length (strv);
823 add_len = g_strv_length (to_add);
824 strv = g_renew (gchar *, strv, strv_len + add_len + 1);
826 for (i = 0; to_add[i]; i++)
828 /* Don't add blocklisted strings */
830 for (j = 0; blocklist[j]; j++)
831 if (g_str_equal (to_add[i], blocklist[j]))
834 /* Don't add duplicates already in the list */
835 for (j = 0; j < strv_len; j++)
836 if (g_str_equal (to_add[i], strv[j]))
839 strv[strv_len++] = to_add[i];
846 strv[strv_len] = NULL;
853 desktop_file_dir_unindexed_read_mimeapps_list (DesktopFileDir *dir,
854 const gchar *filename,
855 const gchar *added_group,
856 gboolean tweaks_permitted)
858 UnindexedMimeTweaks *tweaks;
859 char **desktop_file_ids;
864 key_file = g_key_file_new ();
865 if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL))
867 g_key_file_free (key_file);
871 mime_types = g_key_file_get_keys (key_file, added_group, NULL, NULL);
873 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
875 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
876 "mimeapps.list file may add or remove associations.", filename, added_group);
877 g_strfreev (mime_types);
881 if (mime_types != NULL)
883 for (i = 0; mime_types[i] != NULL; i++)
885 desktop_file_ids = g_key_file_get_string_list (key_file, added_group, mime_types[i], NULL, NULL);
887 if (desktop_file_ids)
889 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
890 expand_strv (&tweaks->additions, desktop_file_ids, tweaks->removals);
894 g_strfreev (mime_types);
897 mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
899 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
901 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
902 "mimeapps.list file may add or remove associations.", filename, REMOVED_ASSOCIATIONS_GROUP);
903 g_strfreev (mime_types);
907 if (mime_types != NULL)
909 for (i = 0; mime_types[i] != NULL; i++)
911 desktop_file_ids = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP, mime_types[i], NULL, NULL);
913 if (desktop_file_ids)
915 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
916 expand_strv (&tweaks->removals, desktop_file_ids, tweaks->additions);
920 g_strfreev (mime_types);
923 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
925 if (mime_types != NULL)
927 for (i = 0; mime_types[i] != NULL; i++)
929 desktop_file_ids = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP, mime_types[i], NULL, NULL);
931 if (desktop_file_ids)
933 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
934 expand_strv (&tweaks->defaults, desktop_file_ids, NULL);
938 g_strfreev (mime_types);
941 g_key_file_free (key_file);
945 desktop_file_dir_unindexed_read_mimeapps_lists (DesktopFileDir *dir)
947 const gchar * const *desktops;
951 dir->mime_tweaks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_mime_tweaks);
953 /* We process in order of precedence, using a blocklisting approach to
954 * avoid recording later instructions that conflict with ones we found
957 * We first start with the XDG_CURRENT_DESKTOP files, in precedence
960 desktops = get_lowercase_current_desktops ();
961 for (i = 0; desktops[i]; i++)
963 filename = g_strdup_printf ("%s/%s-mimeapps.list", dir->path, desktops[i]);
964 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
968 /* Next, the non-desktop-specific mimeapps.list */
969 filename = g_strdup_printf ("%s/mimeapps.list", dir->path);
970 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, TRUE);
973 /* The remaining files are only checked for in directories that might
974 * contain desktop files (ie: not the config dirs).
979 /* We have 'defaults.list' which was only ever understood by GLib. It
980 * exists widely, but it has never been part of any spec and it should
981 * be treated as deprecated. This will be removed in a future
984 filename = g_strdup_printf ("%s/defaults.list", dir->path);
985 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
988 /* Finally, the mimeinfo.cache, which is just a cached copy of what we
989 * would find in the MimeTypes= lines of all of the desktop files.
991 filename = g_strdup_printf ("%s/mimeinfo.cache", dir->path);
992 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, MIME_CACHE_GROUP, TRUE);
997 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
1000 get_apps_from_dir (&dir->app_names, dir->path, "");
1002 desktop_file_dir_unindexed_read_mimeapps_lists (dir);
1005 static GDesktopAppInfo *
1006 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
1007 const gchar *desktop_id)
1009 const gchar *filename;
1011 filename = g_hash_table_lookup (dir->app_names, desktop_id);
1016 return g_desktop_app_info_new_from_filename (filename);
1020 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
1023 GHashTableIter iter;
1027 if (dir->app_names == NULL)
1030 g_hash_table_iter_init (&iter, dir->app_names);
1031 while (g_hash_table_iter_next (&iter, &app_name, &filename))
1033 if (desktop_file_dir_app_name_is_masked (dir, app_name))
1036 add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename (filename));
1040 typedef struct _MemoryIndexEntry MemoryIndexEntry;
1041 typedef GHashTable MemoryIndex;
1043 struct _MemoryIndexEntry
1045 const gchar *app_name; /* pointer to the hashtable key */
1046 gint match_category;
1047 MemoryIndexEntry *next;
1051 memory_index_entry_free (gpointer data)
1053 MemoryIndexEntry *mie = data;
1057 MemoryIndexEntry *next = mie->next;
1059 g_slice_free (MemoryIndexEntry, mie);
1065 memory_index_add_token (MemoryIndex *mi,
1067 gint match_category,
1068 const gchar *app_name)
1070 MemoryIndexEntry *mie, *first;
1072 mie = g_slice_new (MemoryIndexEntry);
1073 mie->app_name = app_name;
1074 mie->match_category = match_category;
1076 first = g_hash_table_lookup (mi, token);
1080 mie->next = first->next;
1086 g_hash_table_insert (mi, g_strdup (token), mie);
1091 memory_index_add_string (MemoryIndex *mi,
1092 const gchar *string,
1093 gint match_category,
1094 const gchar *app_name)
1096 gchar **tokens, **alternates;
1099 tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
1101 for (i = 0; tokens[i]; i++)
1102 memory_index_add_token (mi, tokens[i], match_category, app_name);
1104 for (i = 0; alternates[i]; i++)
1105 memory_index_add_token (mi, alternates[i], match_category, app_name);
1107 g_strfreev (alternates);
1108 g_strfreev (tokens);
1111 static MemoryIndex *
1112 memory_index_new (void)
1114 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
1118 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
1120 GHashTableIter iter;
1123 dir->memory_index = memory_index_new ();
1124 dir->memory_implementations = memory_index_new ();
1126 /* Nothing to search? */
1127 if (dir->app_names == NULL)
1130 g_hash_table_iter_init (&iter, dir->app_names);
1131 while (g_hash_table_iter_next (&iter, &app, &path))
1135 if (desktop_file_dir_app_name_is_masked (dir, app))
1138 key_file = g_key_file_new ();
1140 if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
1141 !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
1143 /* Index the interesting keys... */
1147 for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
1152 if (!desktop_key_match_category[i])
1155 raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
1158 if (i == DESKTOP_KEY_Exec && raw != NULL)
1160 /* Special handling: only match basename of first field */
1164 /* Remove extra arguments, if any */
1165 space = raw + strcspn (raw, " \t\n"); /* IFS */
1168 /* Skip the pathname, if any */
1169 if ((slash = strrchr (raw, '/')))
1172 /* Don't match on blocklisted binaries like interpreters */
1173 if (g_strv_contains (exec_key_match_blocklist, value))
1178 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
1183 /* Make note of the Implements= line */
1184 implements = g_key_file_get_string_list (key_file, "Desktop Entry", "Implements", NULL, NULL);
1185 for (i = 0; implements && implements[i]; i++)
1186 memory_index_add_token (dir->memory_implementations, implements[i], 0, app);
1187 g_strfreev (implements);
1190 g_key_file_free (key_file);
1195 desktop_file_dir_unindexed_search (DesktopFileDir *dir,
1196 const gchar *search_token)
1198 GHashTableIter iter;
1199 gpointer key, value;
1201 if (!dir->memory_index)
1202 desktop_file_dir_unindexed_setup_search (dir);
1204 g_hash_table_iter_init (&iter, dir->memory_index);
1205 while (g_hash_table_iter_next (&iter, &key, &value))
1207 MemoryIndexEntry *mie = value;
1209 if (!g_str_has_prefix (key, search_token))
1214 add_token_result (mie->app_name, mie->match_category);
1221 array_contains (GPtrArray *array,
1226 for (i = 0; i < array->len; i++)
1227 if (g_str_equal (array->pdata[i], str))
1234 desktop_file_dir_unindexed_mime_lookup (DesktopFileDir *dir,
1235 const gchar *mime_type,
1237 GPtrArray *blocklist)
1239 UnindexedMimeTweaks *tweaks;
1242 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1247 if (tweaks->additions)
1249 for (i = 0; tweaks->additions[i]; i++)
1251 gchar *app_name = tweaks->additions[i];
1253 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1254 !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1255 g_ptr_array_add (hits, app_name);
1259 if (tweaks->removals)
1261 for (i = 0; tweaks->removals[i]; i++)
1263 gchar *app_name = tweaks->removals[i];
1265 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1266 !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1267 g_ptr_array_add (blocklist, app_name);
1273 desktop_file_dir_unindexed_default_lookup (DesktopFileDir *dir,
1274 const gchar *mime_type,
1277 UnindexedMimeTweaks *tweaks;
1280 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1282 if (!tweaks || !tweaks->defaults)
1285 for (i = 0; tweaks->defaults[i]; i++)
1287 gchar *app_name = tweaks->defaults[i];
1289 if (!array_contains (results, app_name))
1290 g_ptr_array_add (results, app_name);
1295 desktop_file_dir_unindexed_get_implementations (DesktopFileDir *dir,
1297 const gchar *interface)
1299 MemoryIndexEntry *mie;
1301 if (!dir->memory_index)
1302 desktop_file_dir_unindexed_setup_search (dir);
1304 for (mie = g_hash_table_lookup (dir->memory_implementations, interface); mie; mie = mie->next)
1305 *results = g_list_prepend (*results, g_strdup (mie->app_name));
1308 /* DesktopFileDir "API" {{{2 */
1311 * desktop_file_dir_new:
1312 * @data_dir: an XDG_DATA_DIR
1314 * Creates a #DesktopFileDir for the corresponding @data_dir.
1316 static DesktopFileDir *
1317 desktop_file_dir_new (const gchar *data_dir)
1319 DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1321 g_atomic_ref_count_init (&dir->ref_count);
1322 dir->path = g_build_filename (data_dir, "applications", NULL);
1324 return g_steal_pointer (&dir);
1328 * desktop_file_dir_new_for_config:
1329 * @config_dir: an XDG_CONFIG_DIR
1331 * Just the same as desktop_file_dir_new() except that it does not
1332 * add the "applications" directory. It also marks the directory as
1333 * config-only, which prevents us from attempting to find desktop files
1336 static DesktopFileDir *
1337 desktop_file_dir_new_for_config (const gchar *config_dir)
1339 DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1341 g_atomic_ref_count_init (&dir->ref_count);
1342 dir->path = g_strdup (config_dir);
1343 dir->is_config = TRUE;
1345 return g_steal_pointer (&dir);
1349 * desktop_file_dir_reset:
1350 * @dir: a #DesktopFileDir
1352 * Cleans up @dir, releasing most resources that it was using.
1355 desktop_file_dir_reset (DesktopFileDir *dir)
1357 if (dir->alternatively_watching)
1359 g_free (dir->alternatively_watching);
1360 dir->alternatively_watching = NULL;
1365 g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
1366 g_file_monitor_cancel (dir->monitor);
1367 g_object_unref (dir->monitor);
1368 dir->monitor = NULL;
1373 g_hash_table_unref (dir->app_names);
1374 dir->app_names = NULL;
1377 if (dir->memory_index)
1379 g_hash_table_unref (dir->memory_index);
1380 dir->memory_index = NULL;
1383 if (dir->mime_tweaks)
1385 g_hash_table_unref (dir->mime_tweaks);
1386 dir->mime_tweaks = NULL;
1389 if (dir->memory_implementations)
1391 g_hash_table_unref (dir->memory_implementations);
1392 dir->memory_implementations = NULL;
1395 dir->is_setup = FALSE;
1399 closure_notify_cb (gpointer data,
1402 DesktopFileDir *dir = data;
1403 desktop_file_dir_unref (dir);
1407 * desktop_file_dir_init:
1408 * @dir: a #DesktopFileDir
1410 * Does initial setup for @dir
1412 * You should only call this if @dir is not already setup.
1415 desktop_file_dir_init (DesktopFileDir *dir)
1417 const gchar *watch_dir;
1419 g_assert (!dir->is_setup);
1421 g_assert (!dir->alternatively_watching);
1422 g_assert (!dir->monitor);
1424 dir->alternatively_watching = desktop_file_dir_get_alternative_dir (dir);
1425 watch_dir = dir->alternatively_watching ? dir->alternatively_watching : dir->path;
1427 /* There is a very thin race here if the watch_dir has been _removed_
1428 * between when we checked for it and when we establish the watch.
1429 * Removes probably don't happen in usual operation, and even if it
1430 * does (and we catch the unlikely race), the only degradation is that
1431 * we will fall back to polling.
1433 dir->monitor = g_local_file_monitor_new_in_worker (watch_dir, TRUE, G_FILE_MONITOR_NONE,
1434 desktop_file_dir_changed,
1435 desktop_file_dir_ref (dir),
1436 closure_notify_cb, NULL);
1438 desktop_file_dir_unindexed_init (dir);
1440 dir->is_setup = TRUE;
1444 * desktop_file_dir_get_app:
1445 * @dir: a DesktopFileDir
1446 * @desktop_id: the desktop ID to load
1448 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
1449 * within @dir, even if it is hidden.
1451 * This function does not check if @desktop_id would be masked by a
1452 * directory with higher precedence. The caller must do so.
1454 static GDesktopAppInfo *
1455 desktop_file_dir_get_app (DesktopFileDir *dir,
1456 const gchar *desktop_id)
1458 if (!dir->app_names)
1461 return desktop_file_dir_unindexed_get_app (dir, desktop_id);
1465 * desktop_file_dir_get_all:
1466 * @dir: a DesktopFileDir
1467 * @apps: a #GHashTable<string, GDesktopAppInfo>
1469 * Loads all desktop files in @dir and adds them to @apps, careful to
1470 * ensure we don't add any files masked by a similarly-named file in a
1471 * higher-precedence directory.
1474 desktop_file_dir_get_all (DesktopFileDir *dir,
1477 desktop_file_dir_unindexed_get_all (dir, apps);
1481 * desktop_file_dir_mime_lookup:
1482 * @dir: a #DesktopFileDir
1483 * @mime_type: the mime type to look up
1484 * @hits: the array to store the hits
1485 * @blocklist: the array to store the blocklist
1487 * Does a lookup of a mimetype against one desktop file directory,
1488 * recording any hits and blocklisting and "Removed" associations (so
1489 * later directories don't record them as hits).
1491 * The items added to @hits are duplicated, but the ones in @blocklist
1492 * are weak pointers. This facilitates simply freeing the blocklist
1493 * (which is only used for internal bookkeeping) but using the pdata of
1494 * @hits as the result of the operation.
1497 desktop_file_dir_mime_lookup (DesktopFileDir *dir,
1498 const gchar *mime_type,
1500 GPtrArray *blocklist)
1502 desktop_file_dir_unindexed_mime_lookup (dir, mime_type, hits, blocklist);
1506 * desktop_file_dir_default_lookup:
1507 * @dir: a #DesktopFileDir
1508 * @mime_type: the mime type to look up
1509 * @results: an array to store the results in
1511 * Collects the "default" applications for a given mime type from @dir.
1514 desktop_file_dir_default_lookup (DesktopFileDir *dir,
1515 const gchar *mime_type,
1518 desktop_file_dir_unindexed_default_lookup (dir, mime_type, results);
1522 * desktop_file_dir_search:
1523 * @dir: a #DesktopFileDir
1524 * @term: a normalised and casefolded search term
1526 * Finds the names of applications in @dir that match @term.
1529 desktop_file_dir_search (DesktopFileDir *dir,
1530 const gchar *search_token)
1532 desktop_file_dir_unindexed_search (dir, search_token);
1536 desktop_file_dir_get_implementations (DesktopFileDir *dir,
1538 const gchar *interface)
1540 desktop_file_dir_unindexed_get_implementations (dir, results, interface);
1543 /* Lock/unlock and global setup API {{{2 */
1546 desktop_file_dirs_lock (void)
1549 const gchar *user_config_dir = g_get_user_config_dir ();
1551 g_mutex_lock (&desktop_file_dir_lock);
1553 /* If the XDG dirs configuration has changed (expected only during tests),
1554 * clear and reload the state. */
1555 if (desktop_file_dirs_config_dir != NULL &&
1556 g_strcmp0 (desktop_file_dirs_config_dir, user_config_dir) != 0)
1558 g_debug ("%s: Resetting desktop app info dirs from %s to %s",
1559 G_STRFUNC, desktop_file_dirs_config_dir, user_config_dir);
1561 g_ptr_array_set_size (desktop_file_dirs, 0);
1562 g_clear_pointer (&desktop_file_dir_user_config, desktop_file_dir_unref);
1563 g_clear_pointer (&desktop_file_dir_user_data, desktop_file_dir_unref);
1566 if (desktop_file_dirs == NULL || desktop_file_dirs->len == 0)
1568 const char * const *dirs;
1571 if (desktop_file_dirs == NULL)
1572 desktop_file_dirs = g_ptr_array_new_with_free_func ((GDestroyNotify) desktop_file_dir_unref);
1574 /* First, the configs. Highest priority: the user's ~/.config */
1575 desktop_file_dir_user_config = desktop_file_dir_new_for_config (user_config_dir);
1576 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_config));
1578 /* Next, the system configs (/etc/xdg, and so on). */
1579 dirs = g_get_system_config_dirs ();
1580 for (i = 0; dirs[i]; i++)
1581 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new_for_config (dirs[i]));
1583 /* Now the data. Highest priority: the user's ~/.local/share/applications */
1584 desktop_file_dir_user_data = desktop_file_dir_new (g_get_user_data_dir ());
1585 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_data));
1587 /* Following that, XDG_DATA_DIRS/applications, in order */
1588 dirs = g_get_system_data_dirs ();
1589 for (i = 0; dirs[i]; i++)
1590 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new (dirs[i]));
1592 /* The list of directories will never change after this, unless
1593 * g_get_user_config_dir() changes due to %G_TEST_OPTION_ISOLATE_DIRS. */
1594 desktop_file_dirs_config_dir = user_config_dir;
1597 for (i = 0; i < desktop_file_dirs->len; i++)
1598 if (!((DesktopFileDir *) g_ptr_array_index (desktop_file_dirs, i))->is_setup)
1599 desktop_file_dir_init (g_ptr_array_index (desktop_file_dirs, i));
1603 desktop_file_dirs_unlock (void)
1605 g_mutex_unlock (&desktop_file_dir_lock);
1609 desktop_file_dirs_invalidate_user_config (void)
1611 g_mutex_lock (&desktop_file_dir_lock);
1613 if (desktop_file_dir_user_config != NULL)
1614 desktop_file_dir_reset (desktop_file_dir_user_config);
1616 g_mutex_unlock (&desktop_file_dir_lock);
1620 desktop_file_dirs_invalidate_user_data (void)
1622 g_mutex_lock (&desktop_file_dir_lock);
1624 if (desktop_file_dir_user_data != NULL)
1625 desktop_file_dir_reset (desktop_file_dir_user_data);
1627 g_mutex_unlock (&desktop_file_dir_lock);
1630 /* GDesktopAppInfo implementation {{{1 */
1631 /* GObject implementation {{{2 */
1633 g_desktop_app_info_finalize (GObject *object)
1635 GDesktopAppInfo *info;
1637 info = G_DESKTOP_APP_INFO (object);
1639 g_free (info->desktop_id);
1640 g_free (info->filename);
1643 g_key_file_unref (info->keyfile);
1645 g_free (info->name);
1646 g_free (info->generic_name);
1647 g_free (info->fullname);
1648 g_free (info->comment);
1649 g_free (info->icon_name);
1651 g_object_unref (info->icon);
1652 g_strfreev (info->keywords);
1653 g_strfreev (info->only_show_in);
1654 g_strfreev (info->not_show_in);
1655 g_free (info->try_exec);
1656 g_free (info->exec);
1657 g_free (info->binary);
1658 g_free (info->path);
1659 g_free (info->categories);
1660 g_free (info->startup_wm_class);
1661 g_strfreev (info->mime_types);
1662 g_free (info->app_id);
1663 g_strfreev (info->actions);
1665 G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1669 g_desktop_app_info_set_property (GObject *object,
1671 const GValue *value,
1674 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1679 self->filename = g_value_dup_string (value);
1683 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1689 g_desktop_app_info_get_property (GObject *object,
1694 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1699 g_value_set_string (value, self->filename);
1702 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1708 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1710 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1712 gobject_class->get_property = g_desktop_app_info_get_property;
1713 gobject_class->set_property = g_desktop_app_info_set_property;
1714 gobject_class->finalize = g_desktop_app_info_finalize;
1717 * GDesktopAppInfo:filename:
1719 * The origin filename of this #GDesktopAppInfo
1721 g_object_class_install_property (gobject_class,
1723 g_param_spec_string ("filename", "Filename", "", NULL,
1724 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1728 g_desktop_app_info_init (GDesktopAppInfo *local)
1732 /* Construction... {{{2 */
1736 * @exec: an exec line
1738 * Returns the first word in an exec line (ie: the binary name).
1740 * If @exec is " progname --foo %F" then returns "progname".
1743 binary_from_exec (const char *exec)
1745 const char *p, *start;
1751 while (*p != ' ' && *p != 0)
1754 return g_strndup (start, p - start);
1758 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1765 gboolean bus_activatable;
1767 start_group = g_key_file_get_start_group (key_file);
1768 if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1770 g_free (start_group);
1773 g_free (start_group);
1775 type = g_key_file_get_string (key_file,
1776 G_KEY_FILE_DESKTOP_GROUP,
1777 G_KEY_FILE_DESKTOP_KEY_TYPE,
1779 if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1786 try_exec = g_key_file_get_string (key_file,
1787 G_KEY_FILE_DESKTOP_GROUP,
1788 G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1790 if (try_exec && try_exec[0] != '\0')
1793 t = g_find_program_in_path (try_exec);
1802 exec = g_key_file_get_string (key_file,
1803 G_KEY_FILE_DESKTOP_GROUP,
1804 G_KEY_FILE_DESKTOP_KEY_EXEC,
1806 if (exec && exec[0] != '\0')
1810 if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1819 t = g_find_program_in_path (argv[0]);
1832 info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1833 info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1834 info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1835 info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1836 info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1837 info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1838 info->icon_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1839 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);
1840 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);
1841 info->try_exec = try_exec;
1843 info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1844 info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1845 info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1846 info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1847 info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1848 info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1849 info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1850 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);
1851 bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1852 info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1854 /* Remove the special-case: no Actions= key just means 0 extra actions */
1855 if (info->actions == NULL)
1856 info->actions = g_new0 (gchar *, 0 + 1);
1859 if (info->icon_name)
1861 if (g_path_is_absolute (info->icon_name))
1865 file = g_file_new_for_path (info->icon_name);
1866 info->icon = g_file_icon_new (file);
1867 g_object_unref (file);
1873 /* Work around a common mistake in desktop files */
1874 if ((p = strrchr (info->icon_name, '.')) != NULL &&
1875 (strcmp (p, ".png") == 0 ||
1876 strcmp (p, ".xpm") == 0 ||
1877 strcmp (p, ".svg") == 0))
1880 info->icon = g_themed_icon_new (info->icon_name);
1885 info->binary = binary_from_exec (info->exec);
1887 if (info->path && info->path[0] == '\0')
1889 g_free (info->path);
1893 /* Can only be DBusActivatable if we know the filename, which means
1894 * that this won't work for the load-from-keyfile case.
1896 if (bus_activatable && info->filename)
1901 basename = g_path_get_basename (info->filename);
1902 last_dot = strrchr (basename, '.');
1904 if (last_dot && g_str_equal (last_dot, ".desktop"))
1908 if (g_dbus_is_name (basename) && basename[0] != ':')
1909 info->app_id = g_strdup (basename);
1915 info->keyfile = g_key_file_ref (key_file);
1921 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1924 gboolean retval = FALSE;
1926 g_return_val_if_fail (self->filename != NULL, FALSE);
1928 self->desktop_id = g_path_get_basename (self->filename);
1930 key_file = g_key_file_new ();
1932 if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
1933 retval = g_desktop_app_info_load_from_keyfile (self, key_file);
1935 g_key_file_unref (key_file);
1940 * g_desktop_app_info_new_from_keyfile:
1941 * @key_file: an opened #GKeyFile
1943 * Creates a new #GDesktopAppInfo.
1945 * Returns: (nullable): a new #GDesktopAppInfo or %NULL on error.
1950 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
1952 GDesktopAppInfo *info;
1954 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1955 info->filename = NULL;
1956 if (!g_desktop_app_info_load_from_keyfile (info, key_file))
1958 g_object_unref (info);
1965 * g_desktop_app_info_new_from_filename:
1966 * @filename: (type filename): the path of a desktop file, in the GLib
1969 * Creates a new #GDesktopAppInfo.
1971 * Returns: (nullable): a new #GDesktopAppInfo or %NULL on error.
1974 g_desktop_app_info_new_from_filename (const char *filename)
1976 GDesktopAppInfo *info = NULL;
1978 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1979 if (!g_desktop_app_info_load_file (info))
1981 g_object_unref (info);
1988 * g_desktop_app_info_new:
1989 * @desktop_id: the desktop file id
1991 * Creates a new #GDesktopAppInfo based on a desktop file id.
1993 * A desktop file id is the basename of the desktop file, including the
1994 * .desktop extension. GIO is looking for a desktop file with this name
1995 * in the `applications` subdirectories of the XDG
1996 * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
1997 * and `XDG_DATA_DIRS` environment variables). GIO also supports the
1998 * prefix-to-subdirectory mapping that is described in the
1999 * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
2000 * (i.e. a desktop id of kde-foo.desktop will match
2001 * `/usr/share/applications/kde/foo.desktop`).
2003 * Returns: (nullable): a new #GDesktopAppInfo, or %NULL if no desktop
2004 * file with that id exists.
2007 g_desktop_app_info_new (const char *desktop_id)
2009 GDesktopAppInfo *appinfo = NULL;
2012 desktop_file_dirs_lock ();
2014 for (i = 0; i < desktop_file_dirs->len; i++)
2016 appinfo = desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, i), desktop_id);
2022 desktop_file_dirs_unlock ();
2024 if (appinfo == NULL)
2027 g_free (appinfo->desktop_id);
2028 appinfo->desktop_id = g_strdup (desktop_id);
2030 if (g_desktop_app_info_get_is_hidden (appinfo))
2032 g_object_unref (appinfo);
2040 g_desktop_app_info_dup (GAppInfo *appinfo)
2042 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2043 GDesktopAppInfo *new_info;
2045 new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2047 new_info->filename = g_strdup (info->filename);
2048 new_info->desktop_id = g_strdup (info->desktop_id);
2051 new_info->keyfile = g_key_file_ref (info->keyfile);
2053 new_info->name = g_strdup (info->name);
2054 new_info->generic_name = g_strdup (info->generic_name);
2055 new_info->fullname = g_strdup (info->fullname);
2056 new_info->keywords = g_strdupv (info->keywords);
2057 new_info->comment = g_strdup (info->comment);
2058 new_info->nodisplay = info->nodisplay;
2059 new_info->icon_name = g_strdup (info->icon_name);
2061 new_info->icon = g_object_ref (info->icon);
2062 new_info->only_show_in = g_strdupv (info->only_show_in);
2063 new_info->not_show_in = g_strdupv (info->not_show_in);
2064 new_info->try_exec = g_strdup (info->try_exec);
2065 new_info->exec = g_strdup (info->exec);
2066 new_info->binary = g_strdup (info->binary);
2067 new_info->path = g_strdup (info->path);
2068 new_info->app_id = g_strdup (info->app_id);
2069 new_info->hidden = info->hidden;
2070 new_info->terminal = info->terminal;
2071 new_info->startup_notify = info->startup_notify;
2073 return G_APP_INFO (new_info);
2076 /* GAppInfo interface implementation functions {{{2 */
2079 g_desktop_app_info_equal (GAppInfo *appinfo1,
2082 GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
2083 GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
2085 if (info1->desktop_id == NULL ||
2086 info2->desktop_id == NULL)
2087 return info1 == info2;
2089 return strcmp (info1->desktop_id, info2->desktop_id) == 0;
2093 g_desktop_app_info_get_id (GAppInfo *appinfo)
2095 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2097 return info->desktop_id;
2101 g_desktop_app_info_get_name (GAppInfo *appinfo)
2103 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2105 if (info->name == NULL)
2106 return _("Unnamed");
2111 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
2113 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2115 if (info->fullname == NULL)
2116 return g_desktop_app_info_get_name (appinfo);
2117 return info->fullname;
2121 * g_desktop_app_info_get_is_hidden:
2122 * @info: a #GDesktopAppInfo.
2124 * A desktop file is hidden if the Hidden key in it is
2127 * Returns: %TRUE if hidden, %FALSE otherwise.
2130 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
2132 return info->hidden;
2136 * g_desktop_app_info_get_filename:
2137 * @info: a #GDesktopAppInfo
2139 * When @info was created from a known filename, return it. In some
2140 * situations such as the #GDesktopAppInfo returned from
2141 * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
2143 * Returns: (type filename): The full path to the file for @info,
2144 * or %NULL if not known.
2148 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
2150 return info->filename;
2154 g_desktop_app_info_get_description (GAppInfo *appinfo)
2156 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2158 return info->comment;
2162 g_desktop_app_info_get_executable (GAppInfo *appinfo)
2164 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2166 return info->binary;
2170 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
2172 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2178 g_desktop_app_info_get_icon (GAppInfo *appinfo)
2180 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2186 * g_desktop_app_info_get_categories:
2187 * @info: a #GDesktopAppInfo
2189 * Gets the categories from the desktop file.
2191 * Returns: The unparsed Categories key from the desktop file;
2192 * i.e. no attempt is made to split it by ';' or validate it.
2195 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
2197 return info->categories;
2201 * g_desktop_app_info_get_keywords:
2202 * @info: a #GDesktopAppInfo
2204 * Gets the keywords from the desktop file.
2206 * Returns: (transfer none): The value of the Keywords key
2210 const char * const *
2211 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
2213 return (const char * const *)info->keywords;
2217 * g_desktop_app_info_get_generic_name:
2218 * @info: a #GDesktopAppInfo
2220 * Gets the generic name from the destkop file.
2222 * Returns: The value of the GenericName key
2225 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
2227 return info->generic_name;
2231 * g_desktop_app_info_get_nodisplay:
2232 * @info: a #GDesktopAppInfo
2234 * Gets the value of the NoDisplay key, which helps determine if the
2235 * application info should be shown in menus. See
2236 * #G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
2238 * Returns: The value of the NoDisplay key
2243 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
2245 return info->nodisplay;
2249 * g_desktop_app_info_get_show_in:
2250 * @info: a #GDesktopAppInfo
2251 * @desktop_env: (nullable): a string specifying a desktop name
2253 * Checks if the application info should be shown in menus that list available
2254 * applications for a specific name of the desktop, based on the
2255 * `OnlyShowIn` and `NotShowIn` keys.
2257 * @desktop_env should typically be given as %NULL, in which case the
2258 * `XDG_CURRENT_DESKTOP` environment variable is consulted. If you want
2259 * to override the default mechanism then you may specify @desktop_env,
2260 * but this is not recommended.
2262 * Note that g_app_info_should_show() for @info will include this check (with
2263 * %NULL for @desktop_env) as well as additional checks.
2265 * Returns: %TRUE if the @info should be shown in @desktop_env according to the
2266 * `OnlyShowIn` and `NotShowIn` keys, %FALSE
2272 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
2273 const gchar *desktop_env)
2275 const gchar *specified_envs[] = { desktop_env, NULL };
2276 const gchar * const *envs;
2279 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
2282 envs = specified_envs;
2284 envs = get_current_desktops (NULL);
2286 for (i = 0; envs[i]; i++)
2290 if (info->only_show_in)
2291 for (j = 0; info->only_show_in[j]; j++)
2292 if (g_str_equal (info->only_show_in[j], envs[i]))
2295 if (info->not_show_in)
2296 for (j = 0; info->not_show_in[j]; j++)
2297 if (g_str_equal (info->not_show_in[j], envs[i]))
2301 return info->only_show_in == NULL;
2304 /* Launching... {{{2 */
2307 expand_macro_single (char macro, const char *uri)
2310 char *result = NULL;
2314 file = g_file_new_for_uri (uri);
2320 result = g_shell_quote (uri);
2324 path = g_file_get_path (file);
2326 result = g_shell_quote (path);
2330 path = g_file_get_path (file);
2333 name = g_path_get_dirname (path);
2334 result = g_shell_quote (name);
2340 path = g_file_get_path (file);
2343 name = g_path_get_basename (path);
2344 result = g_shell_quote (name);
2350 g_object_unref (file);
2357 expand_macro_uri (char macro, const char *uri, gboolean force_file_uri, char force_file_uri_macro)
2359 char *expanded = NULL;
2361 g_return_val_if_fail (uri != NULL, NULL);
2363 if (!force_file_uri ||
2364 /* Pass URI if it contains an anchor */
2365 strchr (uri, '#') != NULL)
2367 expanded = expand_macro_single (macro, uri);
2371 expanded = expand_macro_single (force_file_uri_macro, uri);
2372 if (expanded == NULL)
2373 expanded = expand_macro_single (macro, uri);
2380 expand_macro (char macro,
2382 GDesktopAppInfo *info,
2385 GList *uris = *uri_list;
2386 char *expanded = NULL;
2387 gboolean force_file_uri;
2388 char force_file_uri_macro;
2391 g_return_if_fail (exec != NULL);
2393 /* On %u and %U, pass POSIX file path pointing to the URI via
2394 * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
2395 * running or the URI doesn't have a POSIX file path via FUSE
2396 * we'll just pass the URI.
2398 force_file_uri_macro = macro;
2399 force_file_uri = FALSE;
2405 force_file_uri_macro = 'f';
2406 force_file_uri = TRUE;
2409 force_file_uri_macro = 'F';
2410 force_file_uri = TRUE;
2426 expanded = expand_macro_uri (macro, uri,
2427 force_file_uri, force_file_uri_macro);
2430 g_string_append (exec, expanded);
2445 expanded = expand_macro_uri (macro, uri,
2446 force_file_uri, force_file_uri_macro);
2449 g_string_append (exec, expanded);
2455 if (uris != NULL && expanded)
2456 g_string_append_c (exec, ' ');
2462 if (info->icon_name)
2464 g_string_append (exec, "--icon ");
2465 expanded = g_shell_quote (info->icon_name);
2466 g_string_append (exec, expanded);
2474 expanded = g_shell_quote (info->name);
2475 g_string_append (exec, expanded);
2483 expanded = g_shell_quote (info->filename);
2484 g_string_append (exec, expanded);
2489 case 'm': /* deprecated */
2493 g_string_append_c (exec, '%');
2501 expand_application_parameters (GDesktopAppInfo *info,
2502 const gchar *exec_line,
2508 GList *uri_list = *uris;
2509 const char *p = exec_line;
2510 GString *expanded_exec;
2513 if (exec_line == NULL)
2515 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2516 _("Desktop file didn’t specify Exec field"));
2520 expanded_exec = g_string_new (NULL);
2524 if (p[0] == '%' && p[1] != '\0')
2526 expand_macro (p[1], expanded_exec, info, uris);
2530 g_string_append_c (expanded_exec, *p);
2535 /* No file substitutions */
2536 if (uri_list == *uris && uri_list != NULL)
2538 /* If there is no macro default to %f. This is also what KDE does */
2539 g_string_append_c (expanded_exec, ' ');
2540 expand_macro ('f', expanded_exec, info, uris);
2543 res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
2544 g_string_free (expanded_exec, TRUE);
2549 prepend_terminal_to_vector (int *argc,
2556 char **term_argv = NULL;
2561 g_return_val_if_fail (argc != NULL, FALSE);
2562 g_return_val_if_fail (argv != NULL, FALSE);
2570 /* compute size if not given */
2573 for (i = 0; the_argv[i] != NULL; i++)
2579 term_argv = g_new0 (char *, 3);
2581 check = g_find_program_in_path ("gnome-terminal");
2584 term_argv[0] = check;
2585 /* Since 2017, gnome-terminal has preferred `--` over `-x` or `-e`. */
2586 term_argv[1] = g_strdup ("--");
2591 check = g_find_program_in_path ("mate-terminal");
2593 check = g_find_program_in_path ("xfce4-terminal");
2596 term_argv[0] = check;
2597 /* Note that gnome-terminal takes -x and
2598 * as -e in gnome-terminal is broken we use that. */
2599 term_argv[1] = g_strdup ("-x");
2604 check = g_find_program_in_path ("nxterm");
2606 check = g_find_program_in_path ("color-xterm");
2608 check = g_find_program_in_path ("rxvt");
2610 check = g_find_program_in_path ("dtterm");
2613 check = g_strdup ("xterm");
2614 g_debug ("Couldn’t find a terminal: falling back to xterm");
2616 term_argv[0] = check;
2617 term_argv[1] = g_strdup ("-e");
2621 real_argc = term_argc + *argc;
2622 real_argv = g_new (char *, real_argc + 1);
2624 for (i = 0; i < term_argc; i++)
2625 real_argv[i] = term_argv[i];
2627 for (j = 0; j < *argc; j++, i++)
2628 real_argv[i] = (char *)the_argv[j];
2630 real_argv[i] = NULL;
2636 /* we use g_free here as we sucked all the inner strings
2637 * out from it into real_argv */
2642 #endif /* G_OS_WIN32 */
2646 create_files_for_uris (GList *uris)
2653 for (iter = uris; iter; iter = iter->next)
2655 GFile *file = g_file_new_for_uri ((char *)iter->data);
2656 res = g_list_prepend (res, file);
2659 return g_list_reverse (res);
2663 notify_desktop_launch (GDBusConnection *session_bus,
2664 GDesktopAppInfo *info,
2666 const char *display,
2671 GVariantBuilder uri_variant;
2672 GVariantBuilder extras_variant;
2674 const char *desktop_file_id;
2675 const char *gio_desktop_file;
2677 if (session_bus == NULL)
2680 g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2681 for (iter = uris; iter; iter = iter->next)
2682 g_variant_builder_add (&uri_variant, "s", iter->data);
2684 g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2685 if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2686 g_variant_builder_add (&extras_variant, "{sv}",
2690 gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2691 if (gio_desktop_file != NULL)
2692 g_variant_builder_add (&extras_variant, "{sv}",
2693 "origin-desktop-file",
2694 g_variant_new_bytestring (gio_desktop_file));
2695 if (g_get_prgname () != NULL)
2696 g_variant_builder_add (&extras_variant, "{sv}",
2698 g_variant_new_bytestring (g_get_prgname ()));
2699 g_variant_builder_add (&extras_variant, "{sv}",
2702 (gint64)getpid ()));
2705 desktop_file_id = info->filename;
2706 else if (info->desktop_id)
2707 desktop_file_id = info->desktop_id;
2709 desktop_file_id = "";
2711 msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2712 "org.gtk.gio.DesktopAppInfo",
2714 g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2715 g_variant_new_bytestring (desktop_file_id),
2716 display ? display : "",
2720 g_dbus_connection_send_message (session_bus,
2724 g_object_unref (msg);
2727 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2730 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo *info,
2731 GDBusConnection *session_bus,
2732 const gchar *exec_line,
2734 GAppLaunchContext *launch_context,
2735 GSpawnFlags spawn_flags,
2736 GSpawnChildSetupFunc user_setup,
2737 gpointer user_setup_data,
2738 GDesktopAppLaunchCallback pid_callback,
2739 gpointer pid_callback_data,
2745 gboolean completed = FALSE;
2749 char **argv, **envp;
2752 g_return_val_if_fail (info != NULL, FALSE);
2757 envp = g_app_launch_context_get_environment (launch_context);
2759 envp = g_get_environ ();
2761 /* The GList* passed to expand_application_parameters() will be modified
2762 * internally by expand_macro(), so we need to pass a copy of it instead,
2763 * and also use that copy to control the exit condition of the loop below.
2769 GList *launched_uris;
2772 char **wrapped_argv;
2774 const gchar * const wrapper_argv[] =
2779 "-c", "export GIO_LAUNCHED_DESKTOP_FILE_PID=$$; exec \"$@\"",
2780 "sh", /* argv[0] for sh */
2783 old_uris = dup_uris;
2784 if (!expand_application_parameters (info, exec_line, &dup_uris, &argc, &argv, error))
2787 /* Get the subset of URIs we're launching with this process */
2788 launched_uris = NULL;
2789 for (iter = old_uris; iter != NULL && iter != dup_uris; iter = iter->next)
2790 launched_uris = g_list_prepend (launched_uris, iter->data);
2791 launched_uris = g_list_reverse (launched_uris);
2793 if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2795 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2796 _("Unable to find terminal required for application"));
2801 envp = g_environ_setenv (envp,
2802 "GIO_LAUNCHED_DESKTOP_FILE",
2809 GList *launched_files = create_files_for_uris (launched_uris);
2811 if (info->startup_notify)
2813 sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2817 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2820 g_list_free_full (launched_files, g_object_unref);
2823 /* Wrap the @argv in a command which will set the
2824 * `GIO_LAUNCHED_DESKTOP_FILE_PID` environment variable. We can’t set this
2825 * in @envp along with `GIO_LAUNCHED_DESKTOP_FILE` because we need to know
2826 * the PID of the new forked process. We can’t use setenv() between fork()
2827 * and exec() because we’d rather use posix_spawn() for speed.
2829 * `sh` should be available on all the platforms that `GDesktopAppInfo`
2830 * currently supports (since they are all POSIX). If additional platforms
2831 * need to be supported in future, it will probably have to be replaced
2832 * with a wrapper program (grep the GLib git history for
2833 * `gio-launch-desktop` for an example of this which could be
2835 wrapped_argv = g_new (char *, argc + G_N_ELEMENTS (wrapper_argv) + 1);
2837 for (i = 0; i < G_N_ELEMENTS (wrapper_argv); i++)
2838 wrapped_argv[i] = g_strdup (wrapper_argv[i]);
2839 for (i = 0; i < argc; i++)
2840 wrapped_argv[i + G_N_ELEMENTS (wrapper_argv)] = g_steal_pointer (&argv[i]);
2842 wrapped_argv[i + G_N_ELEMENTS (wrapper_argv)] = NULL;
2846 if (!g_spawn_async_with_fds (info->path,
2859 g_app_launch_context_launch_failed (launch_context, sn_id);
2862 g_list_free (launched_uris);
2867 if (pid_callback != NULL)
2868 pid_callback (info, pid, pid_callback_data);
2870 if (launch_context != NULL)
2872 GVariantBuilder builder;
2873 GVariant *platform_data;
2875 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2876 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2878 g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2879 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2880 g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2881 g_variant_unref (platform_data);
2884 notify_desktop_launch (session_bus,
2892 g_list_free (launched_uris);
2894 g_strfreev (wrapped_argv);
2895 wrapped_argv = NULL;
2897 while (dup_uris != NULL);
2909 object_path_from_appid (const gchar *appid)
2911 gchar *appid_path, *iter;
2913 appid_path = g_strconcat ("/", appid, NULL);
2914 for (iter = appid_path; *iter; iter++)
2927 g_desktop_app_info_make_platform_data (GDesktopAppInfo *info,
2929 GAppLaunchContext *launch_context)
2931 GVariantBuilder builder;
2933 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2937 GList *launched_files = create_files_for_uris (uris);
2939 if (info->startup_notify)
2943 sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2945 g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2948 g_list_free_full (launched_files, g_object_unref);
2951 return g_variant_builder_end (&builder);
2955 launch_uris_with_dbus (GDesktopAppInfo *info,
2956 GDBusConnection *session_bus,
2958 GAppLaunchContext *launch_context,
2959 GCancellable *cancellable,
2960 GAsyncReadyCallback callback,
2963 GVariantBuilder builder;
2966 g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2972 g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2973 for (iter = uris; iter; iter = iter->next)
2974 g_variant_builder_add (&builder, "s", iter->data);
2975 g_variant_builder_close (&builder);
2978 g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2980 object_path = object_path_from_appid (info->app_id);
2981 g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2982 uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2983 NULL, G_DBUS_CALL_FLAGS_NONE, -1,
2984 cancellable, callback, user_data);
2985 g_free (object_path);
2989 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo *info,
2990 GDBusConnection *session_bus,
2992 GAppLaunchContext *launch_context,
2993 GCancellable *cancellable,
2994 GAsyncReadyCallback callback,
2997 GList *ruris = uris;
2998 char *app_id = NULL;
3000 g_return_val_if_fail (info != NULL, FALSE);
3003 app_id = g_desktop_app_info_get_string (info, "X-Flatpak");
3004 if (app_id && *app_id)
3006 ruris = g_document_portal_add_documents (uris, app_id, NULL);
3012 launch_uris_with_dbus (info, session_bus, ruris, launch_context,
3013 cancellable, callback, user_data);
3016 g_list_free_full (ruris, g_free);
3024 g_desktop_app_info_launch_uris_internal (GAppInfo *appinfo,
3026 GAppLaunchContext *launch_context,
3027 GSpawnFlags spawn_flags,
3028 GSpawnChildSetupFunc user_setup,
3029 gpointer user_setup_data,
3030 GDesktopAppLaunchCallback pid_callback,
3031 gpointer pid_callback_data,
3037 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3038 GDBusConnection *session_bus;
3039 gboolean success = TRUE;
3041 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
3043 if (session_bus && info->app_id)
3044 /* This is non-blocking API. Similar to launching via fork()/exec()
3045 * we don't wait around to see if the program crashed during startup.
3046 * This is what startup-notification's job is...
3048 g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context,
3051 success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
3052 spawn_flags, user_setup, user_setup_data,
3053 pid_callback, pid_callback_data,
3054 stdin_fd, stdout_fd, stderr_fd, error);
3056 if (session_bus != NULL)
3058 /* This asynchronous flush holds a reference until it completes,
3059 * which ensures that the following unref won't immediately kill
3060 * the connection if we were the initial owner.
3062 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
3063 g_object_unref (session_bus);
3070 g_desktop_app_info_launch_uris (GAppInfo *appinfo,
3072 GAppLaunchContext *launch_context,
3075 return g_desktop_app_info_launch_uris_internal (appinfo, uris,
3077 _SPAWN_FLAGS_DEFAULT,
3078 NULL, NULL, NULL, NULL,
3087 GAppLaunchContext *context;
3091 launch_uris_data_free (LaunchUrisData *data)
3093 g_clear_object (&data->context);
3094 g_list_free_full (data->uris, g_free);
3099 launch_uris_with_dbus_cb (GObject *object,
3100 GAsyncResult *result,
3103 GTask *task = G_TASK (user_data);
3104 GError *error = NULL;
3106 g_dbus_connection_call_finish (G_DBUS_CONNECTION (object), result, &error);
3109 g_dbus_error_strip_remote_error (error);
3110 g_task_return_error (task, g_steal_pointer (&error));
3113 g_task_return_boolean (task, TRUE);
3115 g_object_unref (task);
3119 launch_uris_flush_cb (GObject *object,
3120 GAsyncResult *result,
3123 GTask *task = G_TASK (user_data);
3125 g_dbus_connection_flush_finish (G_DBUS_CONNECTION (object), result, NULL);
3126 g_task_return_boolean (task, TRUE);
3127 g_object_unref (task);
3131 launch_uris_bus_get_cb (GObject *object,
3132 GAsyncResult *result,
3135 GTask *task = G_TASK (user_data);
3136 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (g_task_get_source_object (task));
3137 LaunchUrisData *data = g_task_get_task_data (task);
3138 GCancellable *cancellable = g_task_get_cancellable (task);
3139 GDBusConnection *session_bus;
3140 GError *error = NULL;
3142 session_bus = g_bus_get_finish (result, NULL);
3144 if (session_bus && info->app_id)
3146 /* FIXME: The g_document_portal_add_documents() function, which is called
3147 * from the g_desktop_app_info_launch_uris_with_dbus() function, still
3148 * uses blocking calls.
3150 g_desktop_app_info_launch_uris_with_dbus (info, session_bus,
3151 data->uris, data->context,
3153 launch_uris_with_dbus_cb,
3154 g_steal_pointer (&task));
3158 /* FIXME: The D-Bus message from the notify_desktop_launch() function
3159 * can be still lost even if flush is called later. See:
3160 * https://gitlab.freedesktop.org/dbus/dbus/issues/72
3162 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec,
3163 data->uris, data->context,
3164 _SPAWN_FLAGS_DEFAULT, NULL,
3165 NULL, NULL, NULL, -1, -1, -1,
3169 g_task_return_error (task, g_steal_pointer (&error));
3170 g_object_unref (task);
3173 g_dbus_connection_flush (session_bus,
3175 launch_uris_flush_cb,
3176 g_steal_pointer (&task));
3179 g_clear_object (&session_bus);
3183 g_desktop_app_info_launch_uris_async (GAppInfo *appinfo,
3185 GAppLaunchContext *context,
3186 GCancellable *cancellable,
3187 GAsyncReadyCallback callback,
3191 LaunchUrisData *data;
3193 task = g_task_new (appinfo, cancellable, callback, user_data);
3194 g_task_set_source_tag (task, g_desktop_app_info_launch_uris_async);
3196 data = g_new0 (LaunchUrisData, 1);
3197 data->uris = g_list_copy_deep (uris, (GCopyFunc) g_strdup, NULL);
3198 data->context = (context != NULL) ? g_object_ref (context) : NULL;
3199 g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) launch_uris_data_free);
3201 g_bus_get (G_BUS_TYPE_SESSION, cancellable, launch_uris_bus_get_cb, task);
3205 g_desktop_app_info_launch_uris_finish (GAppInfo *appinfo,
3206 GAsyncResult *result,
3209 g_return_val_if_fail (g_task_is_valid (result, appinfo), FALSE);
3211 return g_task_propagate_boolean (G_TASK (result), error);
3215 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
3217 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3219 return info->exec &&
3220 ((strstr (info->exec, "%u") != NULL) ||
3221 (strstr (info->exec, "%U") != NULL));
3225 g_desktop_app_info_supports_files (GAppInfo *appinfo)
3227 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3229 return info->exec &&
3230 ((strstr (info->exec, "%f") != NULL) ||
3231 (strstr (info->exec, "%F") != NULL));
3235 g_desktop_app_info_launch (GAppInfo *appinfo,
3237 GAppLaunchContext *launch_context,
3247 uri = g_file_get_uri (files->data);
3248 uris = g_list_prepend (uris, uri);
3249 files = files->next;
3252 uris = g_list_reverse (uris);
3254 res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
3256 g_list_free_full (uris, g_free);
3262 * g_desktop_app_info_launch_uris_as_manager_with_fds:
3263 * @appinfo: a #GDesktopAppInfo
3264 * @uris: (element-type utf8): List of URIs
3265 * @launch_context: (nullable): a #GAppLaunchContext
3266 * @spawn_flags: #GSpawnFlags, used for each process
3267 * @user_setup: (scope async) (nullable): a #GSpawnChildSetupFunc, used once
3269 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
3270 * @pid_callback: (scope call) (nullable): Callback for child processes
3271 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
3272 * @stdin_fd: file descriptor to use for child's stdin, or -1
3273 * @stdout_fd: file descriptor to use for child's stdout, or -1
3274 * @stderr_fd: file descriptor to use for child's stderr, or -1
3275 * @error: return location for a #GError, or %NULL
3277 * Equivalent to g_desktop_app_info_launch_uris_as_manager() but allows
3278 * you to pass in file descriptors for the stdin, stdout and stderr streams
3279 * of the launched process.
3281 * If application launching occurs via some non-spawn mechanism (e.g. D-Bus
3282 * activation) then @stdin_fd, @stdout_fd and @stderr_fd are ignored.
3284 * Returns: %TRUE on successful launch, %FALSE otherwise.
3289 g_desktop_app_info_launch_uris_as_manager_with_fds (GDesktopAppInfo *appinfo,
3291 GAppLaunchContext *launch_context,
3292 GSpawnFlags spawn_flags,
3293 GSpawnChildSetupFunc user_setup,
3294 gpointer user_setup_data,
3295 GDesktopAppLaunchCallback pid_callback,
3296 gpointer pid_callback_data,
3302 return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
3317 * g_desktop_app_info_launch_uris_as_manager:
3318 * @appinfo: a #GDesktopAppInfo
3319 * @uris: (element-type utf8): List of URIs
3320 * @launch_context: (nullable): a #GAppLaunchContext
3321 * @spawn_flags: #GSpawnFlags, used for each process
3322 * @user_setup: (scope async) (nullable): a #GSpawnChildSetupFunc, used once
3324 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
3325 * @pid_callback: (scope call) (nullable): Callback for child processes
3326 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
3327 * @error: return location for a #GError, or %NULL
3329 * This function performs the equivalent of g_app_info_launch_uris(),
3330 * but is intended primarily for operating system components that
3331 * launch applications. Ordinary applications should use
3332 * g_app_info_launch_uris().
3334 * If the application is launched via GSpawn, then @spawn_flags, @user_setup
3335 * and @user_setup_data are used for the call to g_spawn_async().
3336 * Additionally, @pid_callback (with @pid_callback_data) will be called to
3337 * inform about the PID of the created process. See g_spawn_async_with_pipes()
3338 * for information on certain parameter conditions that can enable an
3339 * optimized posix_spawn() codepath to be used.
3341 * If application launching occurs via some other mechanism (eg: D-Bus
3342 * activation) then @spawn_flags, @user_setup, @user_setup_data,
3343 * @pid_callback and @pid_callback_data are ignored.
3345 * Returns: %TRUE on successful launch, %FALSE otherwise.
3348 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo *appinfo,
3350 GAppLaunchContext *launch_context,
3351 GSpawnFlags spawn_flags,
3352 GSpawnChildSetupFunc user_setup,
3353 gpointer user_setup_data,
3354 GDesktopAppLaunchCallback pid_callback,
3355 gpointer pid_callback_data,
3358 return g_desktop_app_info_launch_uris_as_manager_with_fds (appinfo,
3370 /* OnlyShowIn API support {{{2 */
3373 * g_desktop_app_info_set_desktop_env:
3374 * @desktop_env: a string specifying what desktop this is
3376 * Sets the name of the desktop that the application is running in.
3377 * This is used by g_app_info_should_show() and
3378 * g_desktop_app_info_get_show_in() to evaluate the
3379 * `OnlyShowIn` and `NotShowIn`
3380 * desktop entry fields.
3382 * Should be called only once; subsequent calls are ignored.
3384 * Deprecated:2.42:do not use this API. Since 2.42 the value of the
3385 * `XDG_CURRENT_DESKTOP` environment variable will be used.
3388 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
3390 get_current_desktops (desktop_env);
3394 g_desktop_app_info_should_show (GAppInfo *appinfo)
3396 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3398 if (info->nodisplay)
3401 return g_desktop_app_info_get_show_in (info, NULL);
3404 /* mime types/default apps support {{{2 */
3413 ensure_dir (DirType type,
3416 char *path, *display_name;
3422 path = g_build_filename (g_get_user_config_dir (), NULL);
3426 path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
3430 path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
3434 g_assert_not_reached ();
3437 g_debug ("%s: Ensuring %s", G_STRFUNC, path);
3440 if (g_mkdir_with_parents (path, 0700) == 0)
3444 display_name = g_filename_display_name (path);
3445 if (type == APP_DIR)
3446 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3447 _("Can’t create user application configuration folder %s: %s"),
3448 display_name, g_strerror (errsv));
3450 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3451 _("Can’t create user MIME configuration folder %s: %s"),
3452 display_name, g_strerror (errsv));
3454 g_free (display_name);
3461 update_mimeapps_list (const char *desktop_id,
3462 const char *content_type,
3463 UpdateMimeFlags flags,
3466 char *dirname, *filename, *string;
3468 gboolean load_succeeded, res;
3469 char **old_list, **list;
3470 gsize length, data_size;
3473 char **content_types;
3475 /* Don't add both at start and end */
3476 g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
3477 (flags & UPDATE_MIME_SET_NON_DEFAULT)));
3479 dirname = ensure_dir (CONF_DIR, error);
3483 filename = g_build_filename (dirname, "mimeapps.list", NULL);
3486 key_file = g_key_file_new ();
3487 load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
3488 if (!load_succeeded ||
3489 (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
3490 !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
3491 !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
3493 g_key_file_free (key_file);
3494 key_file = g_key_file_new ();
3499 content_types = g_new (char *, 2);
3500 content_types[0] = g_strdup (content_type);
3501 content_types[1] = NULL;
3505 content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
3508 for (k = 0; content_types && content_types[k]; k++)
3510 /* set as default, if requested so */
3511 string = g_key_file_get_string (key_file,
3512 DEFAULT_APPLICATIONS_GROUP,
3516 if (g_strcmp0 (string, desktop_id) != 0 &&
3517 (flags & UPDATE_MIME_SET_DEFAULT))
3520 string = g_strdup (desktop_id);
3522 /* add in the non-default list too, if it's not already there */
3523 flags |= UPDATE_MIME_SET_NON_DEFAULT;
3526 if (string == NULL || desktop_id == NULL)
3527 g_key_file_remove_key (key_file,
3528 DEFAULT_APPLICATIONS_GROUP,
3532 g_key_file_set_string (key_file,
3533 DEFAULT_APPLICATIONS_GROUP,
3542 /* reuse the list from above */
3546 g_strfreev (content_types);
3547 content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
3550 for (k = 0; content_types && content_types[k]; k++)
3552 /* Add to the right place in the list */
3555 old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
3556 content_types[k], &length, NULL);
3558 list = g_new (char *, 1 + length + 1);
3562 /* if we're adding a last-used hint, just put the application in front of the list */
3563 if (flags & UPDATE_MIME_SET_LAST_USED)
3565 /* avoid adding this again as non-default later */
3566 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3567 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3569 list[i++] = g_strdup (desktop_id);
3574 for (j = 0; old_list[j] != NULL; j++)
3576 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3578 /* rewrite other entries if they're different from the new one */
3579 list[i++] = g_strdup (old_list[j]);
3581 else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3583 /* we encountered an old entry which is equal to the one we're adding as non-default,
3584 * don't change its position in the list.
3586 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3587 list[i++] = g_strdup (old_list[j]);
3592 /* add it at the end of the list */
3593 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3594 list[i++] = g_strdup (desktop_id);
3598 g_strfreev (old_list);
3600 if (list[0] == NULL || desktop_id == NULL)
3601 g_key_file_remove_key (key_file,
3602 ADDED_ASSOCIATIONS_GROUP,
3606 g_key_file_set_string_list (key_file,
3607 ADDED_ASSOCIATIONS_GROUP,
3609 (const char * const *)list, i);
3616 /* reuse the list from above */
3620 g_strfreev (content_types);
3621 content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
3624 for (k = 0; content_types && content_types[k]; k++)
3626 /* Remove from removed associations group (unless remove) */
3629 old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
3630 content_types[k], &length, NULL);
3632 list = g_new (char *, 1 + length + 1);
3635 if (flags & UPDATE_MIME_REMOVE)
3636 list[i++] = g_strdup (desktop_id);
3639 for (j = 0; old_list[j] != NULL; j++)
3641 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3642 list[i++] = g_strdup (old_list[j]);
3647 g_strfreev (old_list);
3649 if (list[0] == NULL || desktop_id == NULL)
3650 g_key_file_remove_key (key_file,
3651 REMOVED_ASSOCIATIONS_GROUP,
3655 g_key_file_set_string_list (key_file,
3656 REMOVED_ASSOCIATIONS_GROUP,
3658 (const char * const *)list, i);
3663 g_strfreev (content_types);
3665 data = g_key_file_to_data (key_file, &data_size, error);
3666 g_key_file_free (key_file);
3668 res = g_file_set_contents_full (filename, data, data_size,
3669 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
3672 desktop_file_dirs_invalidate_user_config ();
3681 g_desktop_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
3682 const char *content_type,
3685 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3687 if (!g_desktop_app_info_ensure_saved (info, error))
3690 if (!info->desktop_id)
3692 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3693 _("Application information lacks an identifier"));
3697 /* both add support for the content type and set as last used */
3698 return update_mimeapps_list (info->desktop_id, content_type,
3699 UPDATE_MIME_SET_NON_DEFAULT |
3700 UPDATE_MIME_SET_LAST_USED,
3705 g_desktop_app_info_set_as_default_for_type (GAppInfo *appinfo,
3706 const char *content_type,
3709 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3711 if (!g_desktop_app_info_ensure_saved (info, error))
3714 if (!info->desktop_id)
3716 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3717 _("Application information lacks an identifier"));
3721 return update_mimeapps_list (info->desktop_id, content_type,
3722 UPDATE_MIME_SET_DEFAULT,
3727 update_program_done (GPid pid,
3731 /* Did the application exit correctly */
3732 if (g_spawn_check_exit_status (status, NULL))
3734 /* Here we could clean out any caches in use */
3739 run_update_command (char *command,
3748 GError *error = NULL;
3751 argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
3753 if (g_spawn_async ("/", argv,
3755 G_SPAWN_SEARCH_PATH |
3756 G_SPAWN_STDOUT_TO_DEV_NULL |
3757 G_SPAWN_STDERR_TO_DEV_NULL |
3758 G_SPAWN_DO_NOT_REAP_CHILD,
3759 NULL, NULL, /* No setup function */
3762 g_child_watch_add (pid, update_program_done, NULL);
3765 /* If we get an error at this point, it's quite likely the user doesn't
3766 * have an installed copy of either 'update-mime-database' or
3767 * 'update-desktop-database'. I don't think we want to popup an error
3768 * dialog at this point, so we just do a g_warning to give the user a
3769 * chance of debugging it.
3771 g_warning ("%s", error->message);
3772 g_error_free (error);
3779 g_desktop_app_info_set_as_default_for_extension (GAppInfo *appinfo,
3780 const char *extension,
3783 char *filename, *basename, *mimetype;
3787 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
3790 dirname = ensure_dir (MIMETYPE_DIR, error);
3794 basename = g_strdup_printf ("user-extension-%s.xml", extension);
3795 filename = g_build_filename (dirname, basename, NULL);
3799 mimetype = g_strdup_printf ("application/x-extension-%s", extension);
3801 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
3806 g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
3807 "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
3808 " <mime-type type=\"%s\">\n"
3809 " <comment>%s document</comment>\n"
3810 " <glob pattern=\"*.%s\"/>\n"
3812 "</mime-info>\n", mimetype, extension, extension);
3814 g_file_set_contents_full (filename, contents, -1,
3815 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
3819 run_update_command ("update-mime-database", "mime");
3823 res = g_desktop_app_info_set_as_default_for_type (appinfo,
3833 g_desktop_app_info_add_supports_type (GAppInfo *appinfo,
3834 const char *content_type,
3837 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3839 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3842 return update_mimeapps_list (info->desktop_id, content_type,
3843 UPDATE_MIME_SET_NON_DEFAULT,
3848 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
3854 g_desktop_app_info_remove_supports_type (GAppInfo *appinfo,
3855 const char *content_type,
3858 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3860 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3863 return update_mimeapps_list (info->desktop_id, content_type,
3868 static const char **
3869 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
3871 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3873 return (const char**) info->mime_types;
3876 /* Saving and deleting {{{2 */
3879 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
3885 char *data, *desktop_id;
3890 if (info->filename != NULL)
3893 /* This is only used for object created with
3894 * g_app_info_create_from_commandline. All other
3895 * object should have a filename
3898 dirname = ensure_dir (APP_DIR, error);
3902 key_file = g_key_file_new ();
3904 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3905 "Encoding", "UTF-8");
3906 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3907 G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
3908 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3909 G_KEY_FILE_DESKTOP_KEY_TYPE,
3910 G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3912 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3913 G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3914 if (info->nodisplay)
3915 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3916 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3918 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3919 G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3921 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3922 G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3924 if (info->generic_name != NULL)
3925 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3926 GENERIC_NAME_KEY, info->generic_name);
3928 if (info->fullname != NULL)
3929 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3930 FULL_NAME_KEY, info->fullname);
3932 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3933 G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3935 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3936 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3938 data = g_key_file_to_data (key_file, &data_size, NULL);
3939 g_key_file_free (key_file);
3941 desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3942 filename = g_build_filename (dirname, desktop_id, NULL);
3943 g_free (desktop_id);
3946 fd = g_mkstemp (filename);
3951 display_name = g_filename_display_name (filename);
3952 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3953 _("Can’t create user desktop file %s"), display_name);
3954 g_free (display_name);
3960 desktop_id = g_path_get_basename (filename);
3962 /* FIXME - actually handle error */
3963 (void) g_close (fd, NULL);
3965 res = g_file_set_contents_full (filename, data, data_size,
3966 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
3971 g_free (desktop_id);
3976 info->filename = filename;
3977 info->desktop_id = desktop_id;
3979 run_update_command ("update-desktop-database", "applications");
3981 /* We just dropped a file in the user's desktop file directory. Save
3982 * the monitor the bother of having to notice it and invalidate
3985 * This means that calls directly following this will be able to see
3986 * the results immediately.
3988 desktop_file_dirs_invalidate_user_data ();
3994 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3996 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4000 if (strstr (info->filename, "/userapp-"))
4001 return g_access (info->filename, W_OK) == 0;
4008 g_desktop_app_info_delete (GAppInfo *appinfo)
4010 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4014 if (g_remove (info->filename) == 0)
4016 update_mimeapps_list (info->desktop_id, NULL,
4020 g_free (info->filename);
4021 info->filename = NULL;
4022 g_free (info->desktop_id);
4023 info->desktop_id = NULL;
4032 /* Create for commandline {{{2 */
4034 * g_app_info_create_from_commandline:
4035 * @commandline: (type filename): the commandline to use
4036 * @application_name: (nullable): the application name, or %NULL to use @commandline
4037 * @flags: flags that can specify details of the created #GAppInfo
4038 * @error: a #GError location to store the error occurring, %NULL to ignore.
4040 * Creates a new #GAppInfo from the given information.
4042 * Note that for @commandline, the quoting rules of the Exec key of the
4043 * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
4044 * are applied. For example, if the @commandline contains
4045 * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
4046 * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
4048 * Returns: (transfer full): new #GAppInfo for given command.
4051 g_app_info_create_from_commandline (const char *commandline,
4052 const char *application_name,
4053 GAppInfoCreateFlags flags,
4058 GDesktopAppInfo *info;
4060 g_return_val_if_fail (commandline, NULL);
4062 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
4064 info->filename = NULL;
4065 info->desktop_id = NULL;
4067 info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
4068 info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
4069 info->hidden = FALSE;
4070 if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
4071 info->exec = g_strconcat (commandline, " %u", NULL);
4073 info->exec = g_strconcat (commandline, " %f", NULL);
4074 info->nodisplay = TRUE;
4075 info->binary = binary_from_exec (info->exec);
4077 if (application_name)
4078 info->name = g_strdup (application_name);
4081 /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
4082 split = g_strsplit (commandline, " ", 2);
4083 basename = split[0] ? g_path_get_basename (split[0]) : NULL;
4085 info->name = basename;
4086 if (info->name == NULL)
4087 info->name = g_strdup ("custom");
4089 info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
4091 return G_APP_INFO (info);
4094 /* GAppInfo interface init */
4097 g_desktop_app_info_iface_init (GAppInfoIface *iface)
4099 iface->dup = g_desktop_app_info_dup;
4100 iface->equal = g_desktop_app_info_equal;
4101 iface->get_id = g_desktop_app_info_get_id;
4102 iface->get_name = g_desktop_app_info_get_name;
4103 iface->get_description = g_desktop_app_info_get_description;
4104 iface->get_executable = g_desktop_app_info_get_executable;
4105 iface->get_icon = g_desktop_app_info_get_icon;
4106 iface->launch = g_desktop_app_info_launch;
4107 iface->supports_uris = g_desktop_app_info_supports_uris;
4108 iface->supports_files = g_desktop_app_info_supports_files;
4109 iface->launch_uris = g_desktop_app_info_launch_uris;
4110 iface->launch_uris_async = g_desktop_app_info_launch_uris_async;
4111 iface->launch_uris_finish = g_desktop_app_info_launch_uris_finish;
4112 iface->should_show = g_desktop_app_info_should_show;
4113 iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
4114 iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
4115 iface->add_supports_type = g_desktop_app_info_add_supports_type;
4116 iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
4117 iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
4118 iface->can_delete = g_desktop_app_info_can_delete;
4119 iface->do_delete = g_desktop_app_info_delete;
4120 iface->get_commandline = g_desktop_app_info_get_commandline;
4121 iface->get_display_name = g_desktop_app_info_get_display_name;
4122 iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
4123 iface->get_supported_types = g_desktop_app_info_get_supported_types;
4126 /* Recommended applications {{{2 */
4128 /* Converts content_type into a list of itself with all of its parent
4129 * types (if include_fallback is enabled) or just returns a single-item
4130 * list with the unaliased content type.
4133 get_list_of_mimetypes (const gchar *content_type,
4134 gboolean include_fallback)
4139 array = g_ptr_array_new ();
4140 unaliased = _g_unix_content_type_unalias (content_type);
4141 g_ptr_array_add (array, unaliased);
4143 if (include_fallback)
4147 /* Iterate the array as we grow it, until we have nothing more to add */
4148 for (i = 0; i < array->len; i++)
4150 gchar **parents = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4153 for (j = 0; parents[j]; j++)
4154 /* Don't add duplicates */
4155 if (!array_contains (array, parents[j]))
4156 g_ptr_array_add (array, parents[j]);
4158 g_free (parents[j]);
4160 /* We already stole or freed each element. Free the container. */
4165 g_ptr_array_add (array, NULL);
4167 return (gchar **) g_ptr_array_free (array, FALSE);
4171 g_desktop_app_info_get_desktop_ids_for_content_type (const gchar *content_type,
4172 gboolean include_fallback)
4174 GPtrArray *hits, *blocklist;
4178 hits = g_ptr_array_new ();
4179 blocklist = g_ptr_array_new ();
4181 types = get_list_of_mimetypes (content_type, include_fallback);
4183 desktop_file_dirs_lock ();
4185 for (i = 0; types[i]; i++)
4186 for (j = 0; j < desktop_file_dirs->len; j++)
4187 desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], hits, blocklist);
4189 /* We will keep the hits past unlocking, so we must dup them */
4190 for (i = 0; i < hits->len; i++)
4191 hits->pdata[i] = g_strdup (hits->pdata[i]);
4193 desktop_file_dirs_unlock ();
4195 g_ptr_array_add (hits, NULL);
4197 g_ptr_array_free (blocklist, TRUE);
4200 return (gchar **) g_ptr_array_free (hits, FALSE);
4204 * g_app_info_get_recommended_for_type:
4205 * @content_type: the content type to find a #GAppInfo for
4207 * Gets a list of recommended #GAppInfos for a given content type, i.e.
4208 * those applications which claim to support the given content type exactly,
4209 * and not by MIME type subclassing.
4210 * Note that the first application of the list is the last used one, i.e.
4211 * the last one for which g_app_info_set_as_last_used_for_type() has been
4214 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4215 * for given @content_type or %NULL on error.
4220 g_app_info_get_recommended_for_type (const gchar *content_type)
4222 gchar **desktop_ids;
4226 g_return_val_if_fail (content_type != NULL, NULL);
4228 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4231 for (i = 0; desktop_ids[i]; i++)
4233 GDesktopAppInfo *info;
4235 info = g_desktop_app_info_new (desktop_ids[i]);
4237 infos = g_list_prepend (infos, info);
4240 g_strfreev (desktop_ids);
4242 return g_list_reverse (infos);
4246 * g_app_info_get_fallback_for_type:
4247 * @content_type: the content type to find a #GAppInfo for
4249 * Gets a list of fallback #GAppInfos for a given content type, i.e.
4250 * those applications which claim to support the given content type
4251 * by MIME type subclassing and not directly.
4253 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4254 * for given @content_type or %NULL on error.
4259 g_app_info_get_fallback_for_type (const gchar *content_type)
4261 gchar **recommended_ids;
4266 g_return_val_if_fail (content_type != NULL, NULL);
4268 recommended_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4269 all_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4272 for (i = 0; all_ids[i]; i++)
4274 GDesktopAppInfo *info;
4277 /* Don't return the ones on the recommended list */
4278 for (j = 0; recommended_ids[j]; j++)
4279 if (g_str_equal (all_ids[i], recommended_ids[j]))
4282 if (recommended_ids[j])
4285 info = g_desktop_app_info_new (all_ids[i]);
4288 infos = g_list_prepend (infos, info);
4291 g_strfreev (recommended_ids);
4292 g_strfreev (all_ids);
4294 return g_list_reverse (infos);
4298 * g_app_info_get_all_for_type:
4299 * @content_type: the content type to find a #GAppInfo for
4301 * Gets a list of all #GAppInfos for a given content type,
4302 * including the recommended and fallback #GAppInfos. See
4303 * g_app_info_get_recommended_for_type() and
4304 * g_app_info_get_fallback_for_type().
4306 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4307 * for given @content_type or %NULL on error.
4310 g_app_info_get_all_for_type (const char *content_type)
4312 gchar **desktop_ids;
4316 g_return_val_if_fail (content_type != NULL, NULL);
4318 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4321 for (i = 0; desktop_ids[i]; i++)
4323 GDesktopAppInfo *info;
4325 info = g_desktop_app_info_new (desktop_ids[i]);
4327 infos = g_list_prepend (infos, info);
4330 g_strfreev (desktop_ids);
4332 return g_list_reverse (infos);
4336 * g_app_info_reset_type_associations:
4337 * @content_type: a content type
4339 * Removes all changes to the type associations done by
4340 * g_app_info_set_as_default_for_type(),
4341 * g_app_info_set_as_default_for_extension(),
4342 * g_app_info_add_supports_type() or
4343 * g_app_info_remove_supports_type().
4348 g_app_info_reset_type_associations (const char *content_type)
4350 update_mimeapps_list (NULL, content_type,
4356 * g_app_info_get_default_for_type:
4357 * @content_type: the content type to find a #GAppInfo for
4358 * @must_support_uris: if %TRUE, the #GAppInfo is expected to
4361 * Gets the default #GAppInfo for a given content type.
4363 * Returns: (transfer full) (nullable): #GAppInfo for given @content_type or
4367 g_app_info_get_default_for_type (const char *content_type,
4368 gboolean must_support_uris)
4370 GPtrArray *blocklist;
4376 g_return_val_if_fail (content_type != NULL, NULL);
4378 types = get_list_of_mimetypes (content_type, TRUE);
4380 blocklist = g_ptr_array_new ();
4381 results = g_ptr_array_new ();
4384 desktop_file_dirs_lock ();
4386 for (i = 0; types[i]; i++)
4388 /* Collect all the default apps for this type */
4389 for (j = 0; j < desktop_file_dirs->len; j++)
4390 desktop_file_dir_default_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results);
4392 /* Consider the associations as well... */
4393 for (j = 0; j < desktop_file_dirs->len; j++)
4394 desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results, blocklist);
4396 /* (If any), see if one of those apps is installed... */
4397 for (j = 0; j < results->len; j++)
4399 const gchar *desktop_id = g_ptr_array_index (results, j);
4401 for (k = 0; k < desktop_file_dirs->len; k++)
4403 info = (GAppInfo *) desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, k), desktop_id);
4407 if (!must_support_uris || g_app_info_supports_uris (info))
4410 g_clear_object (&info);
4415 /* Reset the list, ready to try again with the next (parent)
4416 * mimetype, but keep the blocklist in place.
4418 g_ptr_array_set_size (results, 0);
4422 desktop_file_dirs_unlock ();
4424 g_ptr_array_unref (blocklist);
4425 g_ptr_array_unref (results);
4432 * g_app_info_get_default_for_uri_scheme:
4433 * @uri_scheme: a string containing a URI scheme.
4435 * Gets the default application for handling URIs with
4436 * the given URI scheme. A URI scheme is the initial part
4437 * of the URI, up to but not including the ':', e.g. "http",
4440 * Returns: (transfer full) (nullable): #GAppInfo for given @uri_scheme or
4444 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
4447 char *content_type, *scheme_down;
4449 scheme_down = g_ascii_strdown (uri_scheme, -1);
4450 content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
4451 g_free (scheme_down);
4452 app_info = g_app_info_get_default_for_type (content_type, FALSE);
4453 g_free (content_type);
4458 /* "Get all" API {{{2 */
4461 * g_desktop_app_info_get_implementations:
4462 * @interface: the name of the interface
4464 * Gets all applications that implement @interface.
4466 * An application implements an interface if that interface is listed in
4467 * the Implements= line of the desktop file of the application.
4469 * Returns: (element-type GDesktopAppInfo) (transfer full): a list of #GDesktopAppInfo
4475 g_desktop_app_info_get_implementations (const gchar *interface)
4477 GList *result = NULL;
4481 desktop_file_dirs_lock ();
4483 for (i = 0; i < desktop_file_dirs->len; i++)
4484 desktop_file_dir_get_implementations (g_ptr_array_index (desktop_file_dirs, i), &result, interface);
4486 desktop_file_dirs_unlock ();
4491 gchar *name = (*ptr)->data;
4492 GDesktopAppInfo *app;
4494 app = g_desktop_app_info_new (name);
4500 ptr = &(*ptr)->next;
4503 *ptr = g_list_delete_link (*ptr, *ptr);
4510 * g_desktop_app_info_search:
4511 * @search_string: the search string to use
4513 * Searches desktop files for ones that match @search_string.
4515 * The return value is an array of strvs. Each strv contains a list of
4516 * applications that matched @search_string with an equal score. The
4517 * outer list is sorted by score so that the first strv contains the
4518 * best-matching applications, and so on.
4519 * The algorithm for determining matches is undefined and may change at
4522 * None of the search results are subjected to the normal validation
4523 * checks performed by g_desktop_app_info_new() (for example, checking that
4524 * the executable referenced by a result exists), and so it is possible for
4525 * g_desktop_app_info_new() to return %NULL when passed an app ID returned by
4526 * this function. It is expected that calling code will do this when
4527 * subsequently creating a #GDesktopAppInfo for each result.
4529 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
4530 * list of strvs. Free each item with g_strfreev() and free the outer
4531 * list with g_free().
4534 g_desktop_app_info_search (const gchar *search_string)
4536 gchar **search_tokens;
4537 gint last_category = -1;
4539 gint n_categories = 0;
4540 gint start_of_category;
4543 search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
4545 desktop_file_dirs_lock ();
4547 reset_total_search_results ();
4549 for (i = 0; i < desktop_file_dirs->len; i++)
4551 for (j = 0; search_tokens[j]; j++)
4553 desktop_file_dir_search (g_ptr_array_index (desktop_file_dirs, i), search_tokens[j]);
4554 merge_token_results (j == 0);
4556 merge_directory_results ();
4559 sort_total_search_results ();
4561 /* Count the total number of unique categories */
4562 for (i = 0; i < static_total_results_size; i++)
4563 if (static_total_results[i].category != last_category)
4565 last_category = static_total_results[i].category;
4569 results = g_new (gchar **, n_categories + 1);
4571 /* Start loading into the results list */
4572 start_of_category = 0;
4573 for (i = 0; i < n_categories; i++)
4575 gint n_items_in_category = 0;
4579 this_category = static_total_results[start_of_category].category;
4581 while (start_of_category + n_items_in_category < static_total_results_size &&
4582 static_total_results[start_of_category + n_items_in_category].category == this_category)
4583 n_items_in_category++;
4585 results[i] = g_new (gchar *, n_items_in_category + 1);
4586 for (j = 0; j < n_items_in_category; j++)
4587 results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
4588 results[i][j] = NULL;
4590 start_of_category += n_items_in_category;
4594 desktop_file_dirs_unlock ();
4596 g_strfreev (search_tokens);
4602 * g_app_info_get_all:
4604 * Gets a list of all of the applications currently registered
4607 * For desktop files, this includes applications that have
4608 * `NoDisplay=true` set or are excluded from display by means
4609 * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
4610 * The returned list does not include applications which have
4611 * the `Hidden` key set.
4613 * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
4616 g_app_info_get_all (void)
4619 GHashTableIter iter;
4624 apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4626 desktop_file_dirs_lock ();
4628 for (i = 0; i < desktop_file_dirs->len; i++)
4629 desktop_file_dir_get_all (g_ptr_array_index (desktop_file_dirs, i), apps);
4631 desktop_file_dirs_unlock ();
4634 g_hash_table_iter_init (&iter, apps);
4635 while (g_hash_table_iter_next (&iter, NULL, &value))
4638 infos = g_list_prepend (infos, value);
4641 g_hash_table_destroy (apps);
4646 /* GDesktopAppInfoLookup interface {{{2 */
4649 * GDesktopAppInfoLookup:
4651 * #GDesktopAppInfoLookup is an opaque data structure and can only be accessed
4652 * using the following functions.
4654 * Deprecated: 2.28: The #GDesktopAppInfoLookup interface is deprecated and
4658 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4660 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4661 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4664 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4668 /* "Get for mime type" APIs {{{2 */
4671 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4672 * @lookup: a #GDesktopAppInfoLookup
4673 * @uri_scheme: a string containing a URI scheme.
4675 * Gets the default application for launching applications
4676 * using this URI scheme for a particular #GDesktopAppInfoLookup
4679 * The #GDesktopAppInfoLookup interface and this function is used
4680 * to implement g_app_info_get_default_for_uri_scheme() backends
4681 * in a GIO module. There is no reason for applications to use it
4682 * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4684 * Returns: (transfer full) (nullable): #GAppInfo for given @uri_scheme or
4687 * Deprecated: 2.28: The #GDesktopAppInfoLookup interface is deprecated and
4691 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4692 const char *uri_scheme)
4694 GDesktopAppInfoLookupIface *iface;
4696 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4698 iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4700 return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4703 G_GNUC_END_IGNORE_DEPRECATIONS
4705 /* Misc getter APIs {{{2 */
4708 * g_desktop_app_info_get_startup_wm_class:
4709 * @info: a #GDesktopAppInfo that supports startup notify
4711 * Retrieves the StartupWMClass field from @info. This represents the
4712 * WM_CLASS property of the main window of the application, if launched
4715 * Returns: (transfer none): the startup WM class, or %NULL if none is set
4716 * in the desktop file.
4721 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4723 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4725 return info->startup_wm_class;
4729 * g_desktop_app_info_get_string:
4730 * @info: a #GDesktopAppInfo
4731 * @key: the key to look up
4733 * Looks up a string value in the keyfile backing @info.
4735 * The @key is looked up in the "Desktop Entry" group.
4737 * Returns: a newly allocated string, or %NULL if the key
4743 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4746 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4748 return g_key_file_get_string (info->keyfile,
4749 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4753 * g_desktop_app_info_get_locale_string:
4754 * @info: a #GDesktopAppInfo
4755 * @key: the key to look up
4757 * Looks up a localized string value in the keyfile backing @info
4758 * translated to the current locale.
4760 * The @key is looked up in the "Desktop Entry" group.
4762 * Returns: (nullable): a newly allocated string, or %NULL if the key
4768 g_desktop_app_info_get_locale_string (GDesktopAppInfo *info,
4771 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4772 g_return_val_if_fail (key != NULL && *key != '\0', NULL);
4774 return g_key_file_get_locale_string (info->keyfile,
4775 G_KEY_FILE_DESKTOP_GROUP,
4780 * g_desktop_app_info_get_boolean:
4781 * @info: a #GDesktopAppInfo
4782 * @key: the key to look up
4784 * Looks up a boolean value in the keyfile backing @info.
4786 * The @key is looked up in the "Desktop Entry" group.
4788 * Returns: the boolean value, or %FALSE if the key
4794 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4797 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4799 return g_key_file_get_boolean (info->keyfile,
4800 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4804 * g_desktop_app_info_get_string_list:
4805 * @info: a #GDesktopAppInfo
4806 * @key: the key to look up
4807 * @length: (out) (optional): return location for the number of returned strings, or %NULL
4809 * Looks up a string list value in the keyfile backing @info.
4811 * The @key is looked up in the "Desktop Entry" group.
4813 * Returns: (array zero-terminated=1 length=length) (element-type utf8) (transfer full):
4814 * a %NULL-terminated string array or %NULL if the specified
4815 * key cannot be found. The array should be freed with g_strfreev().
4820 g_desktop_app_info_get_string_list (GDesktopAppInfo *info,
4824 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4826 return g_key_file_get_string_list (info->keyfile,
4827 G_KEY_FILE_DESKTOP_GROUP, key, length, NULL);
4831 * g_desktop_app_info_has_key:
4832 * @info: a #GDesktopAppInfo
4833 * @key: the key to look up
4835 * Returns whether @key exists in the "Desktop Entry" group
4836 * of the keyfile backing @info.
4838 * Returns: %TRUE if the @key exists
4843 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4846 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4848 return g_key_file_has_key (info->keyfile,
4849 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4852 /* Desktop actions support {{{2 */
4855 * g_desktop_app_info_list_actions:
4856 * @info: a #GDesktopAppInfo
4858 * Returns the list of "additional application actions" supported on the
4859 * desktop file, as per the desktop file specification.
4861 * As per the specification, this is the list of actions that are
4862 * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4864 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4868 const gchar * const *
4869 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4871 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4873 return (const gchar **) info->actions;
4877 app_info_has_action (GDesktopAppInfo *info,
4878 const gchar *action_name)
4882 for (i = 0; info->actions[i]; i++)
4883 if (g_str_equal (info->actions[i], action_name))
4890 * g_desktop_app_info_get_action_name:
4891 * @info: a #GDesktopAppInfo
4892 * @action_name: the name of the action as from
4893 * g_desktop_app_info_list_actions()
4895 * Gets the user-visible display name of the "additional application
4896 * action" specified by @action_name.
4898 * This corresponds to the "Name" key within the keyfile group for the
4901 * Returns: (transfer full): the locale-specific action name
4906 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4907 const gchar *action_name)
4912 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4913 g_return_val_if_fail (action_name != NULL, NULL);
4914 g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4916 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4917 result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4918 g_free (group_name);
4920 /* The spec says that the Name field must be given.
4922 * If it's not, let's follow the behaviour of our get_name()
4923 * implementation above and never return %NULL.
4926 result = g_strdup (_("Unnamed"));
4932 * g_desktop_app_info_launch_action:
4933 * @info: a #GDesktopAppInfo
4934 * @action_name: the name of the action as from
4935 * g_desktop_app_info_list_actions()
4936 * @launch_context: (nullable): a #GAppLaunchContext
4938 * Activates the named application action.
4940 * You may only call this function on action names that were
4941 * returned from g_desktop_app_info_list_actions().
4943 * Note that if the main entry of the desktop file indicates that the
4944 * application supports startup notification, and @launch_context is
4945 * non-%NULL, then startup notification will be used when activating the
4946 * action (and as such, invocation of the action on the receiving side
4947 * must signal the end of startup notification when it is completed).
4948 * This is the expected behaviour of applications declaring additional
4949 * actions, as per the desktop file specification.
4951 * As with g_app_info_launch() there is no way to detect failures that
4952 * occur while using this function.
4957 g_desktop_app_info_launch_action (GDesktopAppInfo *info,
4958 const gchar *action_name,
4959 GAppLaunchContext *launch_context)
4961 GDBusConnection *session_bus;
4963 g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4964 g_return_if_fail (action_name != NULL);
4965 g_return_if_fail (app_info_has_action (info, action_name));
4967 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4969 if (session_bus && info->app_id)
4973 object_path = object_path_from_appid (info->app_id);
4974 g_dbus_connection_call (session_bus, info->app_id, object_path,
4975 "org.freedesktop.Application", "ActivateAction",
4976 g_variant_new ("(sav@a{sv})", action_name, NULL,
4977 g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4978 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4979 g_free (object_path);
4986 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4987 exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4988 g_free (group_name);
4991 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4992 _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL,
4998 if (session_bus != NULL)
5000 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
5001 g_object_unref (session_bus);
5006 /* vim:set foldmethod=marker: */