1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
4 * Copyright © 2007 Ryan Lortie
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General
19 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Author: Alexander Larsson <alexl@redhat.com>
22 * Ryan Lortie <desrt@desrt.ca>
29 /* For the #GDesktopAppInfoLookup macros; since macro deprecation is implemented
30 * in the preprocessor, we need to define this before including glib.h*/
31 #ifndef GLIB_DISABLE_DEPRECATION_WARNINGS
32 #define GLIB_DISABLE_DEPRECATION_WARNINGS
39 #ifdef HAVE_CRT_EXTERNS_H
40 #include <crt_externs.h>
43 #include "gcontenttypeprivate.h"
44 #include "gdesktopappinfo.h"
46 #include "glib-unix.h"
50 #include "gthemedicon.h"
51 #include "gfileicon.h"
52 #include <glib/gstdio.h>
54 #include "glib-private.h"
55 #include "giomodule-priv.h"
57 #include "gappinfoprivate.h"
58 #include "glocalfilemonitor.h"
61 #include "gdocumentportal.h"
65 * SECTION:gdesktopappinfo
66 * @title: GDesktopAppInfo
67 * @short_description: Application information from desktop files
68 * @include: gio/gdesktopappinfo.h
70 * #GDesktopAppInfo is an implementation of #GAppInfo based on
73 * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
74 * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
78 #define DEFAULT_APPLICATIONS_GROUP "Default Applications"
79 #define ADDED_ASSOCIATIONS_GROUP "Added Associations"
80 #define REMOVED_ASSOCIATIONS_GROUP "Removed Associations"
81 #define MIME_CACHE_GROUP "MIME Cache"
82 #define GENERIC_NAME_KEY "GenericName"
83 #define FULL_NAME_KEY "X-GNOME-FullName"
84 #define KEYWORDS_KEY "Keywords"
85 #define STARTUP_WM_CLASS_KEY "StartupWMClass"
92 static void g_desktop_app_info_iface_init (GAppInfoIface *iface);
93 static gboolean g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
95 static gboolean g_desktop_app_info_load_file (GDesktopAppInfo *self);
100 * Information about an installed application from a desktop file.
102 struct _GDesktopAppInfo
104 GObject parent_instance;
126 char *startup_wm_class;
133 guint startup_notify : 1;
138 UPDATE_MIME_NONE = 1 << 0,
139 UPDATE_MIME_SET_DEFAULT = 1 << 1,
140 UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
141 UPDATE_MIME_REMOVE = 1 << 3,
142 UPDATE_MIME_SET_LAST_USED = 1 << 4,
145 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
146 G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
148 /* DesktopFileDir implementation {{{1 */
152 gatomicrefcount ref_count;
154 gchar *alternatively_watching;
157 GFileMonitor *monitor;
158 GHashTable *app_names;
159 GHashTable *mime_tweaks;
160 GHashTable *memory_index;
161 GHashTable *memory_implementations;
164 static GPtrArray *desktop_file_dirs = NULL;
165 static const gchar *desktop_file_dirs_config_dir = NULL;
166 static DesktopFileDir *desktop_file_dir_user_config = NULL; /* (owned) */
167 static DesktopFileDir *desktop_file_dir_user_data = NULL; /* (owned) */
168 static GMutex desktop_file_dir_lock;
169 static const gchar *gio_launch_desktop_path = NULL;
171 /* Monitor 'changed' signal handler {{{2 */
172 static void desktop_file_dir_reset (DesktopFileDir *dir);
174 static DesktopFileDir *
175 desktop_file_dir_ref (DesktopFileDir *dir)
177 g_atomic_ref_count_inc (&dir->ref_count);
183 desktop_file_dir_unref (DesktopFileDir *dir)
185 if (g_atomic_ref_count_dec (&dir->ref_count))
187 desktop_file_dir_reset (dir);
194 * desktop_file_dir_get_alternative_dir:
195 * @dir: a #DesktopFileDir
197 * Gets the "alternative" directory to monitor in case the path
200 * If the path exists this will return NULL, otherwise it will return a
201 * parent directory of the path.
203 * This is used to avoid inotify on a non-existent directory (which
204 * results in polling).
206 * See https://bugzilla.gnome.org/show_bug.cgi?id=522314 for more info.
209 desktop_file_dir_get_alternative_dir (DesktopFileDir *dir)
213 /* If the directory itself exists then we need no alternative. */
214 if (g_access (dir->path, R_OK | X_OK) == 0)
217 /* Otherwise, try the parent directories until we find one. */
218 parent = g_path_get_dirname (dir->path);
220 while (g_access (parent, R_OK | X_OK) != 0)
224 parent = g_path_get_dirname (tmp);
226 /* If somehow we get to '/' or '.' then just stop... */
227 if (g_str_equal (parent, tmp))
240 desktop_file_dir_changed (GFileMonitor *monitor,
243 GFileMonitorEvent event_type,
246 DesktopFileDir *dir = user_data;
247 gboolean do_nothing = FALSE;
249 /* We are not interested in receiving notifications forever just
250 * because someone asked about one desktop file once.
252 * After we receive the first notification, reset the dir, destroying
253 * the monitor. We will take this as a hint, next time that we are
254 * asked, that we need to check if everything is up to date.
256 * If this is a notification for a parent directory (because the
257 * desktop directory didn't exist) then we shouldn't fire the signal
258 * unless something actually changed.
260 g_mutex_lock (&desktop_file_dir_lock);
262 if (dir->alternatively_watching)
264 gchar *alternative_dir;
266 alternative_dir = desktop_file_dir_get_alternative_dir (dir);
267 do_nothing = alternative_dir && g_str_equal (dir->alternatively_watching, alternative_dir);
268 g_free (alternative_dir);
272 desktop_file_dir_reset (dir);
274 g_mutex_unlock (&desktop_file_dir_lock);
276 /* Notify anyone else who may be interested */
278 g_app_info_monitor_fire ();
281 /* Internal utility functions {{{2 */
284 * desktop_file_dir_app_name_is_masked:
285 * @dir: a #DesktopFileDir
286 * @app_name: an application ID
288 * Checks if @app_name is masked for @dir.
290 * An application is masked if a similarly-named desktop file exists in
291 * a desktop file directory with higher precedence. Masked desktop
292 * files should be ignored.
295 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
296 const gchar *app_name)
300 for (i = 0; i < desktop_file_dirs->len; i++)
302 DesktopFileDir *i_dir = g_ptr_array_index (desktop_file_dirs, i);
306 if (i_dir->app_names && g_hash_table_contains (i_dir->app_names, app_name))
313 /* Not much to go on from https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
314 * so validate it as a non-empty alphanumeric ASCII string with `-` and `_` allowed.
316 * Validation is important as the desktop IDs are used to construct filenames,
317 * and may be set by an unprivileged caller if running in a setuid program. */
319 validate_xdg_desktop (const gchar *desktop)
323 for (i = 0; desktop[i] != '\0'; i++)
324 if (desktop[i] != '-' && desktop[i] != '_' &&
325 !g_ascii_isalnum (desktop[i]))
335 get_valid_current_desktops (const char *value)
339 GPtrArray *valid_desktops;
342 value = g_getenv ("XDG_CURRENT_DESKTOP");
346 tmp = g_strsplit (value, G_SEARCHPATH_SEPARATOR_S, 0);
347 valid_desktops = g_ptr_array_new_full (g_strv_length (tmp) + 1, g_free);
348 for (i = 0; tmp[i]; i++)
350 if (validate_xdg_desktop (tmp[i]))
351 g_ptr_array_add (valid_desktops, tmp[i]);
355 g_ptr_array_add (valid_desktops, NULL);
357 tmp = (char **) g_ptr_array_steal (valid_desktops, NULL);
358 g_ptr_array_unref (valid_desktops);
362 static const gchar * const *
363 get_lowercase_current_desktops (void)
365 static gchar **result;
367 if (g_once_init_enter (&result))
369 char **tmp = get_valid_current_desktops (NULL);
372 for (i = 0; tmp[i]; i++)
374 /* Convert to lowercase. */
375 for (j = 0; tmp[i][j]; j++)
376 tmp[i][j] = g_ascii_tolower (tmp[i][j]);
379 g_once_init_leave (&result, tmp);
382 return (const gchar **) result;
385 static const gchar * const *
386 get_current_desktops (const gchar *value)
388 static gchar **result;
390 if (g_once_init_enter (&result))
392 char **tmp = get_valid_current_desktops (value);
394 g_once_init_leave (&result, tmp);
397 return (const gchar **) result;
401 * add_to_table_if_appropriate:
402 * @apps: a string to GDesktopAppInfo hash table
403 * @app_name: the name of the application
404 * @info: a #GDesktopAppInfo, or NULL
406 * If @info is non-%NULL and non-hidden, then add it to @apps, using
407 * @app_name as a key.
409 * If @info is non-%NULL then this function will consume the passed-in
413 add_to_table_if_appropriate (GHashTable *apps,
414 const gchar *app_name,
415 GDesktopAppInfo *info)
422 g_object_unref (info);
426 g_free (info->desktop_id);
427 info->desktop_id = g_strdup (app_name);
429 g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
436 DESKTOP_KEY_GenericName,
437 DESKTOP_KEY_Keywords,
439 DESKTOP_KEY_X_GNOME_FullName,
444 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
445 /* Note: lower numbers are a better match.
447 * In case we want two keys to match at the same level, we can just
448 * use the same number for the two different keys.
450 [DESKTOP_KEY_Name] = 1,
451 [DESKTOP_KEY_Exec] = 2,
452 [DESKTOP_KEY_Keywords] = 3,
453 [DESKTOP_KEY_GenericName] = 4,
454 [DESKTOP_KEY_X_GNOME_FullName] = 5,
455 [DESKTOP_KEY_Comment] = 6
458 /* Common prefix commands to ignore from Exec= lines */
459 const char * const exec_key_match_blocklist[] = {
475 desktop_key_get_name (guint key_id)
479 case DESKTOP_KEY_Comment:
481 case DESKTOP_KEY_Exec:
483 case DESKTOP_KEY_GenericName:
484 return GENERIC_NAME_KEY;
485 case DESKTOP_KEY_Keywords:
487 case DESKTOP_KEY_Name:
489 case DESKTOP_KEY_X_GNOME_FullName:
490 return FULL_NAME_KEY;
492 g_assert_not_reached ();
496 /* Search global state {{{2
498 * We only ever search under a global lock, so we can use (and reuse)
499 * some global data to reduce allocations made while searching.
501 * In short, we keep around arrays of results that we expand as needed
502 * (and never shrink).
504 * static_token_results: this is where we append the results for each
505 * token within a given desktop directory, as we handle it (which is
506 * a union of all matches for this term)
508 * static_search_results: this is where we build the complete results
509 * for a single directory (which is an intersection of the matches
510 * found for each term)
512 * static_total_results: this is where we build the complete results
513 * across all directories (which is a union of the matches found in
516 * The app_names that enter these tables are always pointer-unique (in
517 * the sense that string equality is the same as pointer equality).
518 * This can be guaranteed for two reasons:
520 * - we mask appids so that a given appid will only ever appear within
521 * the highest-precedence directory that contains it. We never
522 * return search results from a lower-level directory if a desktop
523 * file exists in a higher-level one.
525 * - within a given directory, the string is unique because it's the
526 * key in the hashtable of all app_ids for that directory.
528 * We perform a merging of the results in merge_token_results(). This
529 * works by ordering the two lists and moving through each of them (at
530 * the same time) looking for common elements, rejecting uncommon ones.
531 * "Order" here need not mean any particular thing, as long as it is
532 * some order. Because of the uniqueness of our strings, we can use
533 * pointer order. That's what's going on in compare_results() below.
537 const gchar *app_name;
541 static struct search_result *static_token_results;
542 static gint static_token_results_size;
543 static gint static_token_results_allocated;
544 static struct search_result *static_search_results;
545 static gint static_search_results_size;
546 static gint static_search_results_allocated;
547 static struct search_result *static_total_results;
548 static gint static_total_results_size;
549 static gint static_total_results_allocated;
551 /* And some functions for performing nice operations against it */
553 compare_results (gconstpointer a,
556 const struct search_result *ra = a;
557 const struct search_result *rb = b;
559 if (ra->app_name < rb->app_name)
562 else if (ra->app_name > rb->app_name)
566 return ra->category - rb->category;
570 compare_categories (gconstpointer a,
573 const struct search_result *ra = a;
574 const struct search_result *rb = b;
576 return ra->category - rb->category;
580 add_token_result (const gchar *app_name,
583 if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
585 static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
586 static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
589 static_token_results[static_token_results_size].app_name = app_name;
590 static_token_results[static_token_results_size].category = category;
591 static_token_results_size++;
595 merge_token_results (gboolean first)
597 if (static_token_results_size != 0)
598 qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
600 /* If this is the first token then we are basically merging a list with
601 * itself -- we only perform de-duplication.
603 * If this is not the first token then we are doing a real merge.
607 const gchar *last_name = NULL;
610 /* We must de-duplicate, but we do so by taking the best category
613 * The final list can be as large as the input here, so make sure
614 * we have enough room (even if it's too much room).
617 if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
619 static_search_results_allocated = static_token_results_allocated;
620 static_search_results = g_renew (struct search_result,
621 static_search_results,
622 static_search_results_allocated);
625 for (i = 0; i < static_token_results_size; i++)
627 /* The list is sorted so that the best match for a given id
628 * will be at the front, so once we have copied an id, skip
629 * the rest of the entries for the same id.
631 if (static_token_results[i].app_name == last_name)
634 last_name = static_token_results[i].app_name;
636 static_search_results[static_search_results_size++] = static_token_results[i];
641 const gchar *last_name = NULL;
645 /* We only ever remove items from the results list, so no need to
646 * resize to ensure that we have enough room.
648 for (i = 0; i < static_token_results_size; i++)
650 if (static_token_results[i].app_name == last_name)
653 last_name = static_token_results[i].app_name;
655 /* Now we only want to have a result in static_search_results
656 * if we already have it there *and* we have it in
657 * static_token_results as well. The category will be the
660 * Skip past the results in static_search_results that are not
661 * going to be matches.
663 while (k < static_search_results_size &&
664 static_search_results[k].app_name < static_token_results[i].app_name)
667 if (k < static_search_results_size &&
668 static_search_results[k].app_name == static_token_results[i].app_name)
672 * Category should be the worse of the two (ie:
673 * numerically larger).
675 static_search_results[j].app_name = static_search_results[k].app_name;
676 static_search_results[j].category = MAX (static_search_results[k].category,
677 static_token_results[i].category);
682 static_search_results_size = j;
685 /* Clear it out for next time... */
686 static_token_results_size = 0;
690 reset_total_search_results (void)
692 static_total_results_size = 0;
696 sort_total_search_results (void)
698 if (static_total_results_size != 0)
699 qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
703 merge_directory_results (void)
705 if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
707 static_total_results_allocated = MAX (16, static_total_results_allocated);
708 while (static_total_results_allocated < static_total_results_size + static_search_results_size)
709 static_total_results_allocated *= 2;
710 static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
713 if (static_total_results + static_total_results_size != 0)
714 memcpy (static_total_results + static_total_results_size,
715 static_search_results,
716 static_search_results_size * sizeof (struct search_result));
718 static_total_results_size += static_search_results_size;
720 /* Clear it out for next time... */
721 static_search_results_size = 0;
724 /* Support for unindexed DesktopFileDirs {{{2 */
726 get_apps_from_dir (GHashTable **apps,
730 const char *basename;
733 dir = g_dir_open (dirname, 0, NULL);
738 while ((basename = g_dir_read_name (dir)) != NULL)
742 filename = g_build_filename (dirname, basename, NULL);
744 if (g_str_has_suffix (basename, ".desktop"))
748 app_name = g_strconcat (prefix, basename, NULL);
751 *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
753 g_hash_table_insert (*apps, app_name, g_strdup (filename));
755 else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
759 subprefix = g_strconcat (prefix, basename, "-", NULL);
760 get_apps_from_dir (apps, filename, subprefix);
775 } UnindexedMimeTweaks;
778 free_mime_tweaks (gpointer data)
780 UnindexedMimeTweaks *tweaks = data;
782 g_strfreev (tweaks->additions);
783 g_strfreev (tweaks->removals);
784 g_strfreev (tweaks->defaults);
786 g_slice_free (UnindexedMimeTweaks, tweaks);
789 static UnindexedMimeTweaks *
790 desktop_file_dir_unindexed_get_tweaks (DesktopFileDir *dir,
791 const gchar *mime_type)
793 UnindexedMimeTweaks *tweaks;
794 gchar *unaliased_type;
796 unaliased_type = _g_unix_content_type_unalias (mime_type);
797 tweaks = g_hash_table_lookup (dir->mime_tweaks, unaliased_type);
801 tweaks = g_slice_new0 (UnindexedMimeTweaks);
802 g_hash_table_insert (dir->mime_tweaks, unaliased_type, tweaks);
805 g_free (unaliased_type);
810 /* consumes 'to_add' */
812 expand_strv (gchar ***strv_ptr,
814 gchar * const *blocklist)
816 guint strv_len, add_len;
827 strv_len = g_strv_length (strv);
828 add_len = g_strv_length (to_add);
829 strv = g_renew (gchar *, strv, strv_len + add_len + 1);
831 for (i = 0; to_add[i]; i++)
833 /* Don't add blocklisted strings */
835 for (j = 0; blocklist[j]; j++)
836 if (g_str_equal (to_add[i], blocklist[j]))
839 /* Don't add duplicates already in the list */
840 for (j = 0; j < strv_len; j++)
841 if (g_str_equal (to_add[i], strv[j]))
844 strv[strv_len++] = to_add[i];
851 strv[strv_len] = NULL;
858 desktop_file_dir_unindexed_read_mimeapps_list (DesktopFileDir *dir,
859 const gchar *filename,
860 const gchar *added_group,
861 gboolean tweaks_permitted)
863 UnindexedMimeTweaks *tweaks;
864 char **desktop_file_ids;
869 key_file = g_key_file_new ();
870 if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL))
872 g_key_file_free (key_file);
876 mime_types = g_key_file_get_keys (key_file, added_group, NULL, NULL);
878 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
880 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
881 "mimeapps.list file may add or remove associations.", filename, added_group);
882 g_strfreev (mime_types);
886 if (mime_types != NULL)
888 for (i = 0; mime_types[i] != NULL; i++)
890 desktop_file_ids = g_key_file_get_string_list (key_file, added_group, mime_types[i], NULL, NULL);
892 if (desktop_file_ids)
894 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
895 expand_strv (&tweaks->additions, desktop_file_ids, tweaks->removals);
899 g_strfreev (mime_types);
902 mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
904 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
906 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
907 "mimeapps.list file may add or remove associations.", filename, REMOVED_ASSOCIATIONS_GROUP);
908 g_strfreev (mime_types);
912 if (mime_types != NULL)
914 for (i = 0; mime_types[i] != NULL; i++)
916 desktop_file_ids = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP, mime_types[i], NULL, NULL);
918 if (desktop_file_ids)
920 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
921 expand_strv (&tweaks->removals, desktop_file_ids, tweaks->additions);
925 g_strfreev (mime_types);
928 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
930 if (mime_types != NULL)
932 for (i = 0; mime_types[i] != NULL; i++)
934 desktop_file_ids = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP, mime_types[i], NULL, NULL);
936 if (desktop_file_ids)
938 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
939 expand_strv (&tweaks->defaults, desktop_file_ids, NULL);
943 g_strfreev (mime_types);
946 g_key_file_free (key_file);
950 desktop_file_dir_unindexed_read_mimeapps_lists (DesktopFileDir *dir)
952 const gchar * const *desktops;
956 dir->mime_tweaks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_mime_tweaks);
958 /* We process in order of precedence, using a blocklisting approach to
959 * avoid recording later instructions that conflict with ones we found
962 * We first start with the XDG_CURRENT_DESKTOP files, in precedence
965 desktops = get_lowercase_current_desktops ();
966 for (i = 0; desktops[i]; i++)
968 filename = g_strdup_printf ("%s/%s-mimeapps.list", dir->path, desktops[i]);
969 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
973 /* Next, the non-desktop-specific mimeapps.list */
974 filename = g_strdup_printf ("%s/mimeapps.list", dir->path);
975 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, TRUE);
978 /* The remaining files are only checked for in directories that might
979 * contain desktop files (ie: not the config dirs).
984 /* We have 'defaults.list' which was only ever understood by GLib. It
985 * exists widely, but it has never been part of any spec and it should
986 * be treated as deprecated. This will be removed in a future
989 filename = g_strdup_printf ("%s/defaults.list", dir->path);
990 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
993 /* Finally, the mimeinfo.cache, which is just a cached copy of what we
994 * would find in the MimeTypes= lines of all of the desktop files.
996 filename = g_strdup_printf ("%s/mimeinfo.cache", dir->path);
997 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, MIME_CACHE_GROUP, TRUE);
1002 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
1004 if (!dir->is_config)
1005 get_apps_from_dir (&dir->app_names, dir->path, "");
1007 desktop_file_dir_unindexed_read_mimeapps_lists (dir);
1010 static GDesktopAppInfo *
1011 g_desktop_app_info_new_from_filename_unlocked (const char *filename)
1013 GDesktopAppInfo *info = NULL;
1015 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1017 if (!g_desktop_app_info_load_file (info))
1018 g_clear_object (&info);
1023 static GDesktopAppInfo *
1024 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
1025 const gchar *desktop_id)
1027 const gchar *filename;
1029 filename = g_hash_table_lookup (dir->app_names, desktop_id);
1034 return g_desktop_app_info_new_from_filename_unlocked (filename);
1038 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
1041 GHashTableIter iter;
1045 if (dir->app_names == NULL)
1048 g_hash_table_iter_init (&iter, dir->app_names);
1049 while (g_hash_table_iter_next (&iter, &app_name, &filename))
1051 if (desktop_file_dir_app_name_is_masked (dir, app_name))
1054 add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename_unlocked (filename));
1058 typedef struct _MemoryIndexEntry MemoryIndexEntry;
1059 typedef GHashTable MemoryIndex;
1061 struct _MemoryIndexEntry
1063 const gchar *app_name; /* pointer to the hashtable key */
1064 gint match_category;
1065 MemoryIndexEntry *next;
1069 memory_index_entry_free (gpointer data)
1071 MemoryIndexEntry *mie = data;
1075 MemoryIndexEntry *next = mie->next;
1077 g_slice_free (MemoryIndexEntry, mie);
1083 memory_index_add_token (MemoryIndex *mi,
1085 gint match_category,
1086 const gchar *app_name)
1088 MemoryIndexEntry *mie, *first;
1090 mie = g_slice_new (MemoryIndexEntry);
1091 mie->app_name = app_name;
1092 mie->match_category = match_category;
1094 first = g_hash_table_lookup (mi, token);
1098 mie->next = first->next;
1104 g_hash_table_insert (mi, g_strdup (token), mie);
1109 memory_index_add_string (MemoryIndex *mi,
1110 const gchar *string,
1111 gint match_category,
1112 const gchar *app_name)
1114 gchar **tokens, **alternates;
1117 tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
1119 for (i = 0; tokens[i]; i++)
1120 memory_index_add_token (mi, tokens[i], match_category, app_name);
1122 for (i = 0; alternates[i]; i++)
1123 memory_index_add_token (mi, alternates[i], match_category, app_name);
1125 g_strfreev (alternates);
1126 g_strfreev (tokens);
1129 static MemoryIndex *
1130 memory_index_new (void)
1132 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
1136 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
1138 GHashTableIter iter;
1141 dir->memory_index = memory_index_new ();
1142 dir->memory_implementations = memory_index_new ();
1144 /* Nothing to search? */
1145 if (dir->app_names == NULL)
1148 g_hash_table_iter_init (&iter, dir->app_names);
1149 while (g_hash_table_iter_next (&iter, &app, &path))
1153 if (desktop_file_dir_app_name_is_masked (dir, app))
1156 key_file = g_key_file_new ();
1158 if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
1159 !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
1161 /* Index the interesting keys... */
1165 for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
1170 if (!desktop_key_match_category[i])
1173 raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
1176 if (i == DESKTOP_KEY_Exec && raw != NULL)
1178 /* Special handling: only match basename of first field */
1182 /* Remove extra arguments, if any */
1183 space = raw + strcspn (raw, " \t\n"); /* IFS */
1186 /* Skip the pathname, if any */
1187 if ((slash = strrchr (raw, '/')))
1190 /* Don't match on blocklisted binaries like interpreters */
1191 if (g_strv_contains (exec_key_match_blocklist, value))
1196 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
1201 /* Make note of the Implements= line */
1202 implements = g_key_file_get_string_list (key_file, "Desktop Entry", "Implements", NULL, NULL);
1203 for (i = 0; implements && implements[i]; i++)
1204 memory_index_add_token (dir->memory_implementations, implements[i], 0, app);
1205 g_strfreev (implements);
1208 g_key_file_free (key_file);
1213 desktop_file_dir_unindexed_search (DesktopFileDir *dir,
1214 const gchar *search_token)
1216 GHashTableIter iter;
1217 gpointer key, value;
1219 if (!dir->memory_index)
1220 desktop_file_dir_unindexed_setup_search (dir);
1222 g_hash_table_iter_init (&iter, dir->memory_index);
1223 while (g_hash_table_iter_next (&iter, &key, &value))
1225 MemoryIndexEntry *mie = value;
1227 if (!g_str_has_prefix (key, search_token))
1232 add_token_result (mie->app_name, mie->match_category);
1239 array_contains (GPtrArray *array,
1244 for (i = 0; i < array->len; i++)
1245 if (g_str_equal (array->pdata[i], str))
1252 desktop_file_dir_unindexed_mime_lookup (DesktopFileDir *dir,
1253 const gchar *mime_type,
1255 GPtrArray *blocklist)
1257 UnindexedMimeTweaks *tweaks;
1260 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1265 if (tweaks->additions)
1267 for (i = 0; tweaks->additions[i]; i++)
1269 gchar *app_name = tweaks->additions[i];
1271 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1272 !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1273 g_ptr_array_add (hits, app_name);
1277 if (tweaks->removals)
1279 for (i = 0; tweaks->removals[i]; i++)
1281 gchar *app_name = tweaks->removals[i];
1283 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1284 !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1285 g_ptr_array_add (blocklist, app_name);
1291 desktop_file_dir_unindexed_default_lookup (DesktopFileDir *dir,
1292 const gchar *mime_type,
1295 UnindexedMimeTweaks *tweaks;
1298 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1300 if (!tweaks || !tweaks->defaults)
1303 for (i = 0; tweaks->defaults[i]; i++)
1305 gchar *app_name = tweaks->defaults[i];
1307 if (!array_contains (results, app_name))
1308 g_ptr_array_add (results, app_name);
1313 desktop_file_dir_unindexed_get_implementations (DesktopFileDir *dir,
1315 const gchar *interface)
1317 MemoryIndexEntry *mie;
1319 if (!dir->memory_index)
1320 desktop_file_dir_unindexed_setup_search (dir);
1322 for (mie = g_hash_table_lookup (dir->memory_implementations, interface); mie; mie = mie->next)
1323 *results = g_list_prepend (*results, g_strdup (mie->app_name));
1326 /* DesktopFileDir "API" {{{2 */
1329 * desktop_file_dir_new:
1330 * @data_dir: an XDG_DATA_DIR
1332 * Creates a #DesktopFileDir for the corresponding @data_dir.
1334 static DesktopFileDir *
1335 desktop_file_dir_new (const gchar *data_dir)
1337 DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1339 g_atomic_ref_count_init (&dir->ref_count);
1340 dir->path = g_build_filename (data_dir, "applications", NULL);
1342 return g_steal_pointer (&dir);
1346 * desktop_file_dir_new_for_config:
1347 * @config_dir: an XDG_CONFIG_DIR
1349 * Just the same as desktop_file_dir_new() except that it does not
1350 * add the "applications" directory. It also marks the directory as
1351 * config-only, which prevents us from attempting to find desktop files
1354 static DesktopFileDir *
1355 desktop_file_dir_new_for_config (const gchar *config_dir)
1357 DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1359 g_atomic_ref_count_init (&dir->ref_count);
1360 dir->path = g_strdup (config_dir);
1361 dir->is_config = TRUE;
1363 return g_steal_pointer (&dir);
1367 * desktop_file_dir_reset:
1368 * @dir: a #DesktopFileDir
1370 * Cleans up @dir, releasing most resources that it was using.
1373 desktop_file_dir_reset (DesktopFileDir *dir)
1375 if (dir->alternatively_watching)
1377 g_free (dir->alternatively_watching);
1378 dir->alternatively_watching = NULL;
1383 g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
1384 g_file_monitor_cancel (dir->monitor);
1385 g_object_unref (dir->monitor);
1386 dir->monitor = NULL;
1391 g_hash_table_unref (dir->app_names);
1392 dir->app_names = NULL;
1395 if (dir->memory_index)
1397 g_hash_table_unref (dir->memory_index);
1398 dir->memory_index = NULL;
1401 if (dir->mime_tweaks)
1403 g_hash_table_unref (dir->mime_tweaks);
1404 dir->mime_tweaks = NULL;
1407 if (dir->memory_implementations)
1409 g_hash_table_unref (dir->memory_implementations);
1410 dir->memory_implementations = NULL;
1413 dir->is_setup = FALSE;
1417 closure_notify_cb (gpointer data,
1420 DesktopFileDir *dir = data;
1421 desktop_file_dir_unref (dir);
1425 * desktop_file_dir_init:
1426 * @dir: a #DesktopFileDir
1428 * Does initial setup for @dir
1430 * You should only call this if @dir is not already setup.
1433 desktop_file_dir_init (DesktopFileDir *dir)
1435 const gchar *watch_dir;
1437 g_assert (!dir->is_setup);
1439 g_assert (!dir->alternatively_watching);
1440 g_assert (!dir->monitor);
1442 dir->alternatively_watching = desktop_file_dir_get_alternative_dir (dir);
1443 watch_dir = dir->alternatively_watching ? dir->alternatively_watching : dir->path;
1445 /* There is a very thin race here if the watch_dir has been _removed_
1446 * between when we checked for it and when we establish the watch.
1447 * Removes probably don't happen in usual operation, and even if it
1448 * does (and we catch the unlikely race), the only degradation is that
1449 * we will fall back to polling.
1451 dir->monitor = g_local_file_monitor_new_in_worker (watch_dir, TRUE, G_FILE_MONITOR_NONE,
1452 desktop_file_dir_changed,
1453 desktop_file_dir_ref (dir),
1454 closure_notify_cb, NULL);
1456 desktop_file_dir_unindexed_init (dir);
1458 dir->is_setup = TRUE;
1462 * desktop_file_dir_get_app:
1463 * @dir: a DesktopFileDir
1464 * @desktop_id: the desktop ID to load
1466 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
1467 * within @dir, even if it is hidden.
1469 * This function does not check if @desktop_id would be masked by a
1470 * directory with higher precedence. The caller must do so.
1472 static GDesktopAppInfo *
1473 desktop_file_dir_get_app (DesktopFileDir *dir,
1474 const gchar *desktop_id)
1476 if (!dir->app_names)
1479 return desktop_file_dir_unindexed_get_app (dir, desktop_id);
1483 * desktop_file_dir_get_all:
1484 * @dir: a DesktopFileDir
1485 * @apps: a #GHashTable<string, GDesktopAppInfo>
1487 * Loads all desktop files in @dir and adds them to @apps, careful to
1488 * ensure we don't add any files masked by a similarly-named file in a
1489 * higher-precedence directory.
1492 desktop_file_dir_get_all (DesktopFileDir *dir,
1495 desktop_file_dir_unindexed_get_all (dir, apps);
1499 * desktop_file_dir_mime_lookup:
1500 * @dir: a #DesktopFileDir
1501 * @mime_type: the mime type to look up
1502 * @hits: the array to store the hits
1503 * @blocklist: the array to store the blocklist
1505 * Does a lookup of a mimetype against one desktop file directory,
1506 * recording any hits and blocklisting and "Removed" associations (so
1507 * later directories don't record them as hits).
1509 * The items added to @hits are duplicated, but the ones in @blocklist
1510 * are weak pointers. This facilitates simply freeing the blocklist
1511 * (which is only used for internal bookkeeping) but using the pdata of
1512 * @hits as the result of the operation.
1515 desktop_file_dir_mime_lookup (DesktopFileDir *dir,
1516 const gchar *mime_type,
1518 GPtrArray *blocklist)
1520 desktop_file_dir_unindexed_mime_lookup (dir, mime_type, hits, blocklist);
1524 * desktop_file_dir_default_lookup:
1525 * @dir: a #DesktopFileDir
1526 * @mime_type: the mime type to look up
1527 * @results: an array to store the results in
1529 * Collects the "default" applications for a given mime type from @dir.
1532 desktop_file_dir_default_lookup (DesktopFileDir *dir,
1533 const gchar *mime_type,
1536 desktop_file_dir_unindexed_default_lookup (dir, mime_type, results);
1540 * desktop_file_dir_search:
1541 * @dir: a #DesktopFileDir
1542 * @term: a normalised and casefolded search term
1544 * Finds the names of applications in @dir that match @term.
1547 desktop_file_dir_search (DesktopFileDir *dir,
1548 const gchar *search_token)
1550 desktop_file_dir_unindexed_search (dir, search_token);
1554 desktop_file_dir_get_implementations (DesktopFileDir *dir,
1556 const gchar *interface)
1558 desktop_file_dir_unindexed_get_implementations (dir, results, interface);
1561 /* Lock/unlock and global setup API {{{2 */
1564 desktop_file_dirs_lock (void)
1567 const gchar *user_config_dir = g_get_user_config_dir ();
1569 g_mutex_lock (&desktop_file_dir_lock);
1571 /* If the XDG dirs configuration has changed (expected only during tests),
1572 * clear and reload the state. */
1573 if (desktop_file_dirs_config_dir != NULL &&
1574 g_strcmp0 (desktop_file_dirs_config_dir, user_config_dir) != 0)
1576 g_debug ("%s: Resetting desktop app info dirs from %s to %s",
1577 G_STRFUNC, desktop_file_dirs_config_dir, user_config_dir);
1579 g_ptr_array_set_size (desktop_file_dirs, 0);
1580 g_clear_pointer (&desktop_file_dir_user_config, desktop_file_dir_unref);
1581 g_clear_pointer (&desktop_file_dir_user_data, desktop_file_dir_unref);
1584 if (desktop_file_dirs == NULL || desktop_file_dirs->len == 0)
1586 const char * const *dirs;
1589 if (desktop_file_dirs == NULL)
1590 desktop_file_dirs = g_ptr_array_new_with_free_func ((GDestroyNotify) desktop_file_dir_unref);
1592 /* First, the configs. Highest priority: the user's ~/.config */
1593 desktop_file_dir_user_config = desktop_file_dir_new_for_config (user_config_dir);
1594 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_config));
1596 /* Next, the system configs (/etc/xdg, and so on). */
1597 dirs = g_get_system_config_dirs ();
1598 for (i = 0; dirs[i]; i++)
1599 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new_for_config (dirs[i]));
1601 /* Now the data. Highest priority: the user's ~/.local/share/applications */
1602 desktop_file_dir_user_data = desktop_file_dir_new (g_get_user_data_dir ());
1603 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_data));
1605 /* Following that, XDG_DATA_DIRS/applications, in order */
1606 dirs = g_get_system_data_dirs ();
1607 for (i = 0; dirs[i]; i++)
1608 g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new (dirs[i]));
1610 /* The list of directories will never change after this, unless
1611 * g_get_user_config_dir() changes due to %G_TEST_OPTION_ISOLATE_DIRS. */
1612 desktop_file_dirs_config_dir = user_config_dir;
1615 for (i = 0; i < desktop_file_dirs->len; i++)
1616 if (!((DesktopFileDir *) g_ptr_array_index (desktop_file_dirs, i))->is_setup)
1617 desktop_file_dir_init (g_ptr_array_index (desktop_file_dirs, i));
1621 desktop_file_dirs_unlock (void)
1623 g_mutex_unlock (&desktop_file_dir_lock);
1627 desktop_file_dirs_invalidate_user_config (void)
1629 g_mutex_lock (&desktop_file_dir_lock);
1631 if (desktop_file_dir_user_config != NULL)
1632 desktop_file_dir_reset (desktop_file_dir_user_config);
1634 g_mutex_unlock (&desktop_file_dir_lock);
1638 desktop_file_dirs_invalidate_user_data (void)
1640 g_mutex_lock (&desktop_file_dir_lock);
1642 if (desktop_file_dir_user_data != NULL)
1643 desktop_file_dir_reset (desktop_file_dir_user_data);
1645 g_mutex_unlock (&desktop_file_dir_lock);
1648 /* GDesktopAppInfo implementation {{{1 */
1649 /* GObject implementation {{{2 */
1651 g_desktop_app_info_finalize (GObject *object)
1653 GDesktopAppInfo *info;
1655 info = G_DESKTOP_APP_INFO (object);
1657 g_free (info->desktop_id);
1658 g_free (info->filename);
1661 g_key_file_unref (info->keyfile);
1663 g_free (info->name);
1664 g_free (info->generic_name);
1665 g_free (info->fullname);
1666 g_free (info->comment);
1667 g_free (info->icon_name);
1669 g_object_unref (info->icon);
1670 g_strfreev (info->keywords);
1671 g_strfreev (info->only_show_in);
1672 g_strfreev (info->not_show_in);
1673 g_free (info->try_exec);
1674 g_free (info->exec);
1675 g_free (info->binary);
1676 g_free (info->path);
1677 g_free (info->categories);
1678 g_free (info->startup_wm_class);
1679 g_strfreev (info->mime_types);
1680 g_free (info->app_id);
1681 g_strfreev (info->actions);
1683 G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1687 g_desktop_app_info_set_property (GObject *object,
1689 const GValue *value,
1692 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1697 self->filename = g_value_dup_string (value);
1701 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1707 g_desktop_app_info_get_property (GObject *object,
1712 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1717 g_value_set_string (value, self->filename);
1720 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1726 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1728 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1730 gobject_class->get_property = g_desktop_app_info_get_property;
1731 gobject_class->set_property = g_desktop_app_info_set_property;
1732 gobject_class->finalize = g_desktop_app_info_finalize;
1735 * GDesktopAppInfo:filename:
1737 * The origin filename of this #GDesktopAppInfo
1739 g_object_class_install_property (gobject_class,
1741 g_param_spec_string ("filename", "Filename", "", NULL,
1742 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1746 g_desktop_app_info_init (GDesktopAppInfo *local)
1750 /* Construction... {{{2 */
1754 * @exec: an exec line
1756 * Returns the first word in an exec line (ie: the binary name).
1758 * If @exec is " progname --foo %F" then returns "progname".
1761 binary_from_exec (const char *exec)
1763 const char *p, *start;
1769 while (*p != ' ' && *p != 0)
1772 return g_strndup (start, p - start);
1776 * g_desktop_app_info_get_desktop_id_for_filename
1777 * @self: #GDesktopAppInfo to get desktop id of
1779 * Tries to find the desktop ID for a particular `.desktop` filename, as per the
1780 * [Desktop Entry Specification](https://specifications.freedesktop.org/desktop-
1781 * entry-spec/desktop-entry-spec-latest.html#desktop-file-id).
1783 * Returns: desktop id or basename if filename is unknown.
1786 g_desktop_app_info_get_desktop_id_for_filename (GDesktopAppInfo *self)
1789 gchar *desktop_id = NULL;
1791 g_return_val_if_fail (self->filename != NULL, NULL);
1793 for (i = 0; i < desktop_file_dirs->len; i++)
1795 DesktopFileDir *dir = g_ptr_array_index (desktop_file_dirs, i);
1796 GHashTable *app_names;
1797 GHashTableIter iter;
1798 gpointer key, value;
1800 app_names = dir->app_names;
1805 g_hash_table_iter_init (&iter, app_names);
1806 while (g_hash_table_iter_next (&iter, &key, &value))
1808 if (!strcmp (value, self->filename))
1810 desktop_id = g_strdup (key);
1820 desktop_id = g_path_get_basename (self->filename);
1822 return g_steal_pointer (&desktop_id);
1826 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1833 gboolean bus_activatable;
1835 start_group = g_key_file_get_start_group (key_file);
1836 if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1838 g_free (start_group);
1841 g_free (start_group);
1843 type = g_key_file_get_string (key_file,
1844 G_KEY_FILE_DESKTOP_GROUP,
1845 G_KEY_FILE_DESKTOP_KEY_TYPE,
1847 if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1854 try_exec = g_key_file_get_string (key_file,
1855 G_KEY_FILE_DESKTOP_GROUP,
1856 G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1858 if (try_exec && try_exec[0] != '\0')
1861 t = g_find_program_in_path (try_exec);
1870 exec = g_key_file_get_string (key_file,
1871 G_KEY_FILE_DESKTOP_GROUP,
1872 G_KEY_FILE_DESKTOP_KEY_EXEC,
1874 if (exec && exec[0] != '\0')
1878 if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1888 /* Since @exec is not an empty string, there must be at least one
1889 * argument, so dereferencing argv[0] should return non-NULL. */
1890 g_assert (argc > 0);
1891 t = g_find_program_in_path (argv[0]);
1904 info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1905 info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1906 info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1907 info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1908 info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1909 info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1910 info->icon_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1911 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);
1912 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);
1913 info->try_exec = try_exec;
1915 info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1916 info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1917 info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1918 info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1919 info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1920 info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1921 info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1922 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);
1923 bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1924 info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1926 /* Remove the special-case: no Actions= key just means 0 extra actions */
1927 if (info->actions == NULL)
1928 info->actions = g_new0 (gchar *, 0 + 1);
1931 if (info->icon_name)
1933 if (g_path_is_absolute (info->icon_name))
1937 file = g_file_new_for_path (info->icon_name);
1938 info->icon = g_file_icon_new (file);
1939 g_object_unref (file);
1945 /* Work around a common mistake in desktop files */
1946 if ((p = strrchr (info->icon_name, '.')) != NULL &&
1947 (strcmp (p, ".png") == 0 ||
1948 strcmp (p, ".xpm") == 0 ||
1949 strcmp (p, ".svg") == 0))
1952 info->icon = g_themed_icon_new (info->icon_name);
1957 info->binary = binary_from_exec (info->exec);
1959 if (info->path && info->path[0] == '\0')
1961 g_free (info->path);
1965 /* Can only be DBusActivatable if we know the filename, which means
1966 * that this won't work for the load-from-keyfile case.
1968 if (bus_activatable && info->filename)
1973 basename = g_path_get_basename (info->filename);
1974 last_dot = strrchr (basename, '.');
1976 if (last_dot && g_str_equal (last_dot, ".desktop"))
1980 if (g_dbus_is_name (basename) && basename[0] != ':')
1981 info->app_id = g_strdup (basename);
1988 info->desktop_id = g_desktop_app_info_get_desktop_id_for_filename (info);
1990 info->keyfile = g_key_file_ref (key_file);
1996 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1999 gboolean retval = FALSE;
2001 g_return_val_if_fail (self->filename != NULL, FALSE);
2003 key_file = g_key_file_new ();
2005 if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
2006 retval = g_desktop_app_info_load_from_keyfile (self, key_file);
2008 g_key_file_unref (key_file);
2013 * g_desktop_app_info_new_from_keyfile:
2014 * @key_file: an opened #GKeyFile
2016 * Creates a new #GDesktopAppInfo.
2018 * Returns: (nullable): a new #GDesktopAppInfo or %NULL on error.
2023 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
2025 GDesktopAppInfo *info;
2027 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2028 info->filename = NULL;
2030 desktop_file_dirs_lock ();
2032 if (!g_desktop_app_info_load_from_keyfile (info, key_file))
2033 g_clear_object (&info);
2035 desktop_file_dirs_unlock ();
2041 * g_desktop_app_info_new_from_filename:
2042 * @filename: (type filename): the path of a desktop file, in the GLib
2045 * Creates a new #GDesktopAppInfo.
2047 * Returns: (nullable): a new #GDesktopAppInfo or %NULL on error.
2050 g_desktop_app_info_new_from_filename (const char *filename)
2052 GDesktopAppInfo *info = NULL;
2054 desktop_file_dirs_lock ();
2056 info = g_desktop_app_info_new_from_filename_unlocked (filename);
2058 desktop_file_dirs_unlock ();
2064 * g_desktop_app_info_new:
2065 * @desktop_id: the desktop file id
2067 * Creates a new #GDesktopAppInfo based on a desktop file id.
2069 * A desktop file id is the basename of the desktop file, including the
2070 * .desktop extension. GIO is looking for a desktop file with this name
2071 * in the `applications` subdirectories of the XDG
2072 * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
2073 * and `XDG_DATA_DIRS` environment variables). GIO also supports the
2074 * prefix-to-subdirectory mapping that is described in the
2075 * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
2076 * (i.e. a desktop id of kde-foo.desktop will match
2077 * `/usr/share/applications/kde/foo.desktop`).
2079 * Returns: (nullable): a new #GDesktopAppInfo, or %NULL if no desktop
2080 * file with that id exists.
2083 g_desktop_app_info_new (const char *desktop_id)
2085 GDesktopAppInfo *appinfo = NULL;
2088 desktop_file_dirs_lock ();
2090 for (i = 0; i < desktop_file_dirs->len; i++)
2092 appinfo = desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, i), desktop_id);
2098 desktop_file_dirs_unlock ();
2100 if (appinfo == NULL)
2103 g_free (appinfo->desktop_id);
2104 appinfo->desktop_id = g_strdup (desktop_id);
2106 if (g_desktop_app_info_get_is_hidden (appinfo))
2108 g_object_unref (appinfo);
2116 g_desktop_app_info_dup (GAppInfo *appinfo)
2118 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2119 GDesktopAppInfo *new_info;
2121 new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2123 new_info->filename = g_strdup (info->filename);
2124 new_info->desktop_id = g_strdup (info->desktop_id);
2127 new_info->keyfile = g_key_file_ref (info->keyfile);
2129 new_info->name = g_strdup (info->name);
2130 new_info->generic_name = g_strdup (info->generic_name);
2131 new_info->fullname = g_strdup (info->fullname);
2132 new_info->keywords = g_strdupv (info->keywords);
2133 new_info->comment = g_strdup (info->comment);
2134 new_info->nodisplay = info->nodisplay;
2135 new_info->icon_name = g_strdup (info->icon_name);
2137 new_info->icon = g_object_ref (info->icon);
2138 new_info->only_show_in = g_strdupv (info->only_show_in);
2139 new_info->not_show_in = g_strdupv (info->not_show_in);
2140 new_info->try_exec = g_strdup (info->try_exec);
2141 new_info->exec = g_strdup (info->exec);
2142 new_info->binary = g_strdup (info->binary);
2143 new_info->path = g_strdup (info->path);
2144 new_info->app_id = g_strdup (info->app_id);
2145 new_info->hidden = info->hidden;
2146 new_info->terminal = info->terminal;
2147 new_info->startup_notify = info->startup_notify;
2149 return G_APP_INFO (new_info);
2152 /* GAppInfo interface implementation functions {{{2 */
2155 g_desktop_app_info_equal (GAppInfo *appinfo1,
2158 GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
2159 GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
2161 if (info1->desktop_id == NULL ||
2162 info2->desktop_id == NULL)
2163 return info1 == info2;
2165 return strcmp (info1->desktop_id, info2->desktop_id) == 0;
2169 g_desktop_app_info_get_id (GAppInfo *appinfo)
2171 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2173 return info->desktop_id;
2177 g_desktop_app_info_get_name (GAppInfo *appinfo)
2179 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2181 if (info->name == NULL)
2182 return _("Unnamed");
2187 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
2189 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2191 if (info->fullname == NULL)
2192 return g_desktop_app_info_get_name (appinfo);
2193 return info->fullname;
2197 * g_desktop_app_info_get_is_hidden:
2198 * @info: a #GDesktopAppInfo.
2200 * A desktop file is hidden if the Hidden key in it is
2203 * Returns: %TRUE if hidden, %FALSE otherwise.
2206 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
2208 return info->hidden;
2212 * g_desktop_app_info_get_filename:
2213 * @info: a #GDesktopAppInfo
2215 * When @info was created from a known filename, return it. In some
2216 * situations such as the #GDesktopAppInfo returned from
2217 * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
2219 * Returns: (nullable) (type filename): The full path to the file for @info,
2220 * or %NULL if not known.
2224 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
2226 return info->filename;
2230 g_desktop_app_info_get_description (GAppInfo *appinfo)
2232 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2234 return info->comment;
2238 g_desktop_app_info_get_executable (GAppInfo *appinfo)
2240 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2242 return info->binary;
2246 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
2248 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2254 g_desktop_app_info_get_icon (GAppInfo *appinfo)
2256 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2262 * g_desktop_app_info_get_categories:
2263 * @info: a #GDesktopAppInfo
2265 * Gets the categories from the desktop file.
2267 * Returns: (nullable): The unparsed Categories key from the desktop file;
2268 * i.e. no attempt is made to split it by ';' or validate it.
2271 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
2273 return info->categories;
2277 * g_desktop_app_info_get_keywords:
2278 * @info: a #GDesktopAppInfo
2280 * Gets the keywords from the desktop file.
2282 * Returns: (transfer none): The value of the Keywords key
2286 const char * const *
2287 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
2289 return (const char * const *)info->keywords;
2293 * g_desktop_app_info_get_generic_name:
2294 * @info: a #GDesktopAppInfo
2296 * Gets the generic name from the desktop file.
2298 * Returns: (nullable): The value of the GenericName key
2301 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
2303 return info->generic_name;
2307 * g_desktop_app_info_get_nodisplay:
2308 * @info: a #GDesktopAppInfo
2310 * Gets the value of the NoDisplay key, which helps determine if the
2311 * application info should be shown in menus. See
2312 * %G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
2314 * Returns: The value of the NoDisplay key
2319 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
2321 return info->nodisplay;
2325 * g_desktop_app_info_get_show_in:
2326 * @info: a #GDesktopAppInfo
2327 * @desktop_env: (nullable): a string specifying a desktop name
2329 * Checks if the application info should be shown in menus that list available
2330 * applications for a specific name of the desktop, based on the
2331 * `OnlyShowIn` and `NotShowIn` keys.
2333 * @desktop_env should typically be given as %NULL, in which case the
2334 * `XDG_CURRENT_DESKTOP` environment variable is consulted. If you want
2335 * to override the default mechanism then you may specify @desktop_env,
2336 * but this is not recommended.
2338 * Note that g_app_info_should_show() for @info will include this check (with
2339 * %NULL for @desktop_env) as well as additional checks.
2341 * Returns: %TRUE if the @info should be shown in @desktop_env according to the
2342 * `OnlyShowIn` and `NotShowIn` keys, %FALSE
2348 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
2349 const gchar *desktop_env)
2351 const gchar *specified_envs[] = { desktop_env, NULL };
2352 const gchar * const *envs;
2355 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
2358 envs = specified_envs;
2360 envs = get_current_desktops (NULL);
2362 for (i = 0; envs[i]; i++)
2366 if (info->only_show_in)
2367 for (j = 0; info->only_show_in[j]; j++)
2368 if (g_str_equal (info->only_show_in[j], envs[i]))
2371 if (info->not_show_in)
2372 for (j = 0; info->not_show_in[j]; j++)
2373 if (g_str_equal (info->not_show_in[j], envs[i]))
2377 return info->only_show_in == NULL;
2380 /* Launching... {{{2 */
2383 expand_macro_single (char macro, const char *uri)
2386 char *result = NULL;
2390 file = g_file_new_for_uri (uri);
2396 result = g_shell_quote (uri);
2400 path = g_file_get_path (file);
2402 result = g_shell_quote (path);
2406 path = g_file_get_path (file);
2409 name = g_path_get_dirname (path);
2410 result = g_shell_quote (name);
2416 path = g_file_get_path (file);
2419 name = g_path_get_basename (path);
2420 result = g_shell_quote (name);
2426 g_object_unref (file);
2433 expand_macro_uri (char macro, const char *uri, gboolean force_file_uri, char force_file_uri_macro)
2435 char *expanded = NULL;
2437 g_return_val_if_fail (uri != NULL, NULL);
2439 if (!force_file_uri ||
2440 /* Pass URI if it contains an anchor */
2441 strchr (uri, '#') != NULL)
2443 expanded = expand_macro_single (macro, uri);
2447 expanded = expand_macro_single (force_file_uri_macro, uri);
2448 if (expanded == NULL)
2449 expanded = expand_macro_single (macro, uri);
2456 expand_macro (char macro,
2458 GDesktopAppInfo *info,
2461 GList *uris = *uri_list;
2462 char *expanded = NULL;
2463 gboolean force_file_uri;
2464 char force_file_uri_macro;
2467 g_return_if_fail (exec != NULL);
2469 /* On %u and %U, pass POSIX file path pointing to the URI via
2470 * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
2471 * running or the URI doesn't have a POSIX file path via FUSE
2472 * we'll just pass the URI.
2474 force_file_uri_macro = macro;
2475 force_file_uri = FALSE;
2481 force_file_uri_macro = 'f';
2482 force_file_uri = TRUE;
2485 force_file_uri_macro = 'F';
2486 force_file_uri = TRUE;
2502 expanded = expand_macro_uri (macro, uri,
2503 force_file_uri, force_file_uri_macro);
2506 g_string_append (exec, expanded);
2521 expanded = expand_macro_uri (macro, uri,
2522 force_file_uri, force_file_uri_macro);
2525 g_string_append (exec, expanded);
2531 if (uris != NULL && expanded)
2532 g_string_append_c (exec, ' ');
2538 if (info->icon_name)
2540 g_string_append (exec, "--icon ");
2541 expanded = g_shell_quote (info->icon_name);
2542 g_string_append (exec, expanded);
2550 expanded = g_shell_quote (info->name);
2551 g_string_append (exec, expanded);
2559 expanded = g_shell_quote (info->filename);
2560 g_string_append (exec, expanded);
2565 case 'm': /* deprecated */
2569 g_string_append_c (exec, '%');
2577 expand_application_parameters (GDesktopAppInfo *info,
2578 const gchar *exec_line,
2584 GList *uri_list = *uris;
2585 const char *p = exec_line;
2586 GString *expanded_exec;
2589 if (exec_line == NULL)
2591 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2592 _("Desktop file didn’t specify Exec field"));
2596 expanded_exec = g_string_new (NULL);
2600 if (p[0] == '%' && p[1] != '\0')
2602 expand_macro (p[1], expanded_exec, info, uris);
2606 g_string_append_c (expanded_exec, *p);
2611 /* No file substitutions */
2612 if (uri_list == *uris && uri_list != NULL)
2614 /* If there is no macro default to %f. This is also what KDE does */
2615 g_string_append_c (expanded_exec, ' ');
2616 expand_macro ('f', expanded_exec, info, uris);
2619 res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
2620 g_string_free (expanded_exec, TRUE);
2625 prepend_terminal_to_vector (int *argc,
2632 char **term_argv = NULL;
2637 g_return_val_if_fail (argc != NULL, FALSE);
2638 g_return_val_if_fail (argv != NULL, FALSE);
2646 /* compute size if not given */
2649 for (i = 0; the_argv[i] != NULL; i++)
2655 term_argv = g_new0 (char *, 3);
2657 check = g_find_program_in_path ("gnome-terminal");
2660 term_argv[0] = check;
2661 /* Since 2017, gnome-terminal has preferred `--` over `-x` or `-e`. */
2662 term_argv[1] = g_strdup ("--");
2667 check = g_find_program_in_path ("mate-terminal");
2669 check = g_find_program_in_path ("xfce4-terminal");
2672 term_argv[0] = check;
2673 /* Note that gnome-terminal takes -x and
2674 * as -e in gnome-terminal is broken we use that. */
2675 term_argv[1] = g_strdup ("-x");
2680 check = g_find_program_in_path ("tilix");
2682 check = g_find_program_in_path ("konsole");
2684 check = g_find_program_in_path ("nxterm");
2686 check = g_find_program_in_path ("color-xterm");
2688 check = g_find_program_in_path ("rxvt");
2690 check = g_find_program_in_path ("dtterm");
2692 check = g_find_program_in_path ("xterm");
2695 g_debug ("Couldn’t find a known terminal");
2699 term_argv[0] = check;
2700 term_argv[1] = g_strdup ("-e");
2704 real_argc = term_argc + *argc;
2705 real_argv = g_new (char *, real_argc + 1);
2707 for (i = 0; i < term_argc; i++)
2708 real_argv[i] = term_argv[i];
2710 for (j = 0; j < *argc; j++, i++)
2711 real_argv[i] = (char *)the_argv[j];
2713 real_argv[i] = NULL;
2719 /* we use g_free here as we sucked all the inner strings
2720 * out from it into real_argv */
2725 #endif /* G_OS_WIN32 */
2729 create_files_for_uris (GList *uris)
2736 for (iter = uris; iter; iter = iter->next)
2738 GFile *file = g_file_new_for_uri ((char *)iter->data);
2739 res = g_list_prepend (res, file);
2742 return g_list_reverse (res);
2746 notify_desktop_launch (GDBusConnection *session_bus,
2747 GDesktopAppInfo *info,
2749 const char *display,
2754 GVariantBuilder uri_variant;
2755 GVariantBuilder extras_variant;
2757 const char *desktop_file_id;
2758 const char *gio_desktop_file;
2760 if (session_bus == NULL)
2763 g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2764 for (iter = uris; iter; iter = iter->next)
2765 g_variant_builder_add (&uri_variant, "s", iter->data);
2767 g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2768 if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2769 g_variant_builder_add (&extras_variant, "{sv}",
2773 gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2774 if (gio_desktop_file != NULL)
2775 g_variant_builder_add (&extras_variant, "{sv}",
2776 "origin-desktop-file",
2777 g_variant_new_bytestring (gio_desktop_file));
2778 if (g_get_prgname () != NULL)
2779 g_variant_builder_add (&extras_variant, "{sv}",
2781 g_variant_new_bytestring (g_get_prgname ()));
2782 g_variant_builder_add (&extras_variant, "{sv}",
2785 (gint64)getpid ()));
2788 desktop_file_id = info->filename;
2789 else if (info->desktop_id)
2790 desktop_file_id = info->desktop_id;
2792 desktop_file_id = "";
2794 msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2795 "org.gtk.gio.DesktopAppInfo",
2797 g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2798 g_variant_new_bytestring (desktop_file_id),
2799 display ? display : "",
2803 g_dbus_connection_send_message (session_bus,
2807 g_object_unref (msg);
2811 emit_launch_started (GAppLaunchContext *context,
2812 GDesktopAppInfo *info,
2813 const gchar *startup_id)
2815 GVariantBuilder builder;
2816 GVariant *platform_data = NULL;
2820 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2821 g_variant_builder_add (&builder, "{sv}",
2822 "startup-notification-id",
2823 g_variant_new_string (startup_id));
2824 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2826 g_signal_emit_by_name (context, "launch-started", info, platform_data);
2827 g_clear_pointer (&platform_data, g_variant_unref);
2830 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2833 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo *info,
2834 GDBusConnection *session_bus,
2835 const gchar *exec_line,
2837 GAppLaunchContext *launch_context,
2838 GSpawnFlags spawn_flags,
2839 GSpawnChildSetupFunc user_setup,
2840 gpointer user_setup_data,
2841 GDesktopAppLaunchCallback pid_callback,
2842 gpointer pid_callback_data,
2848 gboolean completed = FALSE;
2852 char **argv, **envp;
2855 g_return_val_if_fail (info != NULL, FALSE);
2860 envp = g_app_launch_context_get_environment (launch_context);
2862 envp = g_get_environ ();
2864 /* The GList* passed to expand_application_parameters() will be modified
2865 * internally by expand_macro(), so we need to pass a copy of it instead,
2866 * and also use that copy to control the exit condition of the loop below.
2872 GList *launched_uris;
2875 char **wrapped_argv;
2878 old_uris = dup_uris;
2879 if (!expand_application_parameters (info, exec_line, &dup_uris, &argc, &argv, error))
2882 /* Get the subset of URIs we're launching with this process */
2883 launched_uris = NULL;
2884 for (iter = old_uris; iter != NULL && iter != dup_uris; iter = iter->next)
2885 launched_uris = g_list_prepend (launched_uris, iter->data);
2886 launched_uris = g_list_reverse (launched_uris);
2888 if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2890 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2891 _("Unable to find terminal required for application"));
2896 envp = g_environ_setenv (envp,
2897 "GIO_LAUNCHED_DESKTOP_FILE",
2904 GList *launched_files = create_files_for_uris (launched_uris);
2906 if (info->startup_notify)
2908 sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2912 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2915 g_list_free_full (launched_files, g_object_unref);
2917 emit_launch_started (launch_context, info, sn_id);
2920 if (g_once_init_enter (&gio_launch_desktop_path))
2922 const gchar *tmp = NULL;
2923 gboolean is_setuid = GLIB_PRIVATE_CALL (g_check_setuid) ();
2925 /* Allow test suite to specify path to gio-launch-desktop */
2927 tmp = g_getenv ("GIO_LAUNCH_DESKTOP");
2929 /* Allow build system to specify path to gio-launch-desktop */
2930 if (tmp == NULL && g_file_test (GIO_LAUNCH_DESKTOP, G_FILE_TEST_IS_EXECUTABLE))
2931 tmp = GIO_LAUNCH_DESKTOP;
2933 /* Fall back on usual searching in $PATH */
2935 tmp = "gio-launch-desktop";
2936 g_once_init_leave (&gio_launch_desktop_path, tmp);
2939 wrapped_argv = g_new (char *, argc + 2);
2940 wrapped_argv[0] = g_strdup (gio_launch_desktop_path);
2942 for (i = 0; i < argc; i++)
2943 wrapped_argv[i + 1] = g_steal_pointer (&argv[i]);
2945 wrapped_argv[i + 1] = NULL;
2949 if (!g_spawn_async_with_fds (info->path,
2962 g_app_launch_context_launch_failed (launch_context, sn_id);
2965 g_list_free (launched_uris);
2970 if (pid_callback != NULL)
2971 pid_callback (info, pid, pid_callback_data);
2973 if (launch_context != NULL)
2975 GVariantBuilder builder;
2976 GVariant *platform_data;
2978 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2979 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2981 g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2982 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2983 g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2984 g_variant_unref (platform_data);
2987 notify_desktop_launch (session_bus,
2995 g_list_free (launched_uris);
2997 g_strfreev (wrapped_argv);
2998 wrapped_argv = NULL;
3000 while (dup_uris != NULL);
3012 object_path_from_appid (const gchar *appid)
3014 gchar *appid_path, *iter;
3016 appid_path = g_strconcat ("/", appid, NULL);
3017 for (iter = appid_path; *iter; iter++)
3030 g_desktop_app_info_make_platform_data (GDesktopAppInfo *info,
3032 GAppLaunchContext *launch_context)
3034 GVariantBuilder builder;
3036 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
3040 GList *launched_files = create_files_for_uris (uris);
3042 if (info->startup_notify)
3046 sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
3048 g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
3051 g_list_free_full (launched_files, g_object_unref);
3054 return g_variant_builder_end (&builder);
3059 GDesktopAppInfo *info; /* (owned) */
3060 GAppLaunchContext *launch_context; /* (owned) (nullable) */
3061 GAsyncReadyCallback callback;
3062 gchar *startup_id; /* (owned) */
3064 } LaunchUrisWithDBusData;
3067 launch_uris_with_dbus_data_free (LaunchUrisWithDBusData *data)
3069 g_clear_object (&data->info);
3070 g_clear_object (&data->launch_context);
3071 g_free (data->startup_id);
3077 launch_uris_with_dbus_signal_cb (GObject *object,
3078 GAsyncResult *result,
3081 LaunchUrisWithDBusData *data = user_data;
3082 GVariantBuilder builder;
3084 if (data->launch_context)
3086 if (g_task_had_error (G_TASK (result)))
3087 g_app_launch_context_launch_failed (data->launch_context, data->startup_id);
3090 GVariant *platform_data;
3092 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
3093 /* the docs guarantee `pid` will be set, but we can’t
3094 * easily know it for a D-Bus process, so set it to zero */
3095 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (0));
3096 if (data->startup_id)
3097 g_variant_builder_add (&builder, "{sv}",
3098 "startup-notification-id",
3099 g_variant_new_string (data->startup_id));
3100 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
3101 g_signal_emit_by_name (data->launch_context,
3105 g_variant_unref (platform_data);
3110 data->callback (object, result, data->user_data);
3112 launch_uris_with_dbus_data_free (data);
3116 launch_uris_with_dbus (GDesktopAppInfo *info,
3117 GDBusConnection *session_bus,
3119 GAppLaunchContext *launch_context,
3120 GCancellable *cancellable,
3121 GAsyncReadyCallback callback,
3124 GVariant *platform_data;
3125 GVariantBuilder builder;
3128 LaunchUrisWithDBusData *data;
3130 g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
3136 g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
3137 for (iter = uris; iter; iter = iter->next)
3138 g_variant_builder_add (&builder, "s", iter->data);
3139 g_variant_builder_close (&builder);
3142 platform_data = g_desktop_app_info_make_platform_data (info, uris, launch_context);
3144 g_variant_builder_add_value (&builder, platform_data);
3145 object_path = object_path_from_appid (info->app_id);
3147 data = g_new0 (LaunchUrisWithDBusData, 1);
3148 data->info = g_object_ref (info);
3149 data->callback = callback;
3150 data->user_data = user_data;
3151 data->launch_context = launch_context ? g_object_ref (launch_context) : NULL;
3152 g_variant_dict_init (&dict, platform_data);
3153 g_variant_dict_lookup (&dict, "desktop-startup-id", "s", &data->startup_id);
3156 emit_launch_started (launch_context, info, data->startup_id);
3158 g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
3159 uris ? "Open" : "Activate", g_variant_builder_end (&builder),
3160 NULL, G_DBUS_CALL_FLAGS_NONE, -1,
3161 cancellable, launch_uris_with_dbus_signal_cb, g_steal_pointer (&data));
3162 g_free (object_path);
3164 g_variant_dict_clear (&dict);
3168 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo *info,
3169 GDBusConnection *session_bus,
3171 GAppLaunchContext *launch_context,
3172 GCancellable *cancellable,
3173 GAsyncReadyCallback callback,
3176 GList *ruris = uris;
3177 char *app_id = NULL;
3179 g_return_val_if_fail (info != NULL, FALSE);
3182 app_id = g_desktop_app_info_get_string (info, "X-Flatpak");
3183 if (app_id && *app_id)
3185 ruris = g_document_portal_add_documents (uris, app_id, NULL);
3191 launch_uris_with_dbus (info, session_bus, ruris, launch_context,
3192 cancellable, callback, user_data);
3195 g_list_free_full (ruris, g_free);
3203 g_desktop_app_info_launch_uris_internal (GAppInfo *appinfo,
3205 GAppLaunchContext *launch_context,
3206 GSpawnFlags spawn_flags,
3207 GSpawnChildSetupFunc user_setup,
3208 gpointer user_setup_data,
3209 GDesktopAppLaunchCallback pid_callback,
3210 gpointer pid_callback_data,
3216 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3217 GDBusConnection *session_bus;
3218 gboolean success = TRUE;
3220 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
3222 if (session_bus && info->app_id)
3223 /* This is non-blocking API. Similar to launching via fork()/exec()
3224 * we don't wait around to see if the program crashed during startup.
3225 * This is what startup-notification's job is...
3227 g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context,
3230 success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
3231 spawn_flags, user_setup, user_setup_data,
3232 pid_callback, pid_callback_data,
3233 stdin_fd, stdout_fd, stderr_fd, error);
3235 if (session_bus != NULL)
3237 /* This asynchronous flush holds a reference until it completes,
3238 * which ensures that the following unref won't immediately kill
3239 * the connection if we were the initial owner.
3241 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
3242 g_object_unref (session_bus);
3249 g_desktop_app_info_launch_uris (GAppInfo *appinfo,
3251 GAppLaunchContext *launch_context,
3254 return g_desktop_app_info_launch_uris_internal (appinfo, uris,
3256 _SPAWN_FLAGS_DEFAULT,
3257 NULL, NULL, NULL, NULL,
3266 GAppLaunchContext *context;
3270 launch_uris_data_free (LaunchUrisData *data)
3272 g_clear_object (&data->context);
3273 g_list_free_full (data->uris, g_free);
3278 launch_uris_with_dbus_cb (GObject *object,
3279 GAsyncResult *result,
3282 GTask *task = G_TASK (user_data);
3283 GError *error = NULL;
3285 g_dbus_connection_call_finish (G_DBUS_CONNECTION (object), result, &error);
3288 g_dbus_error_strip_remote_error (error);
3289 g_task_return_error (task, g_steal_pointer (&error));
3292 g_task_return_boolean (task, TRUE);
3294 g_object_unref (task);
3298 launch_uris_flush_cb (GObject *object,
3299 GAsyncResult *result,
3302 GTask *task = G_TASK (user_data);
3304 g_dbus_connection_flush_finish (G_DBUS_CONNECTION (object), result, NULL);
3305 g_task_return_boolean (task, TRUE);
3306 g_object_unref (task);
3310 launch_uris_bus_get_cb (GObject *object,
3311 GAsyncResult *result,
3314 GTask *task = G_TASK (user_data);
3315 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (g_task_get_source_object (task));
3316 LaunchUrisData *data = g_task_get_task_data (task);
3317 GCancellable *cancellable = g_task_get_cancellable (task);
3318 GDBusConnection *session_bus;
3319 GError *error = NULL;
3321 session_bus = g_bus_get_finish (result, NULL);
3323 if (session_bus && info->app_id)
3325 /* FIXME: The g_document_portal_add_documents() function, which is called
3326 * from the g_desktop_app_info_launch_uris_with_dbus() function, still
3327 * uses blocking calls.
3329 g_desktop_app_info_launch_uris_with_dbus (info, session_bus,
3330 data->uris, data->context,
3332 launch_uris_with_dbus_cb,
3333 g_steal_pointer (&task));
3337 /* FIXME: The D-Bus message from the notify_desktop_launch() function
3338 * can be still lost even if flush is called later. See:
3339 * https://gitlab.freedesktop.org/dbus/dbus/issues/72
3341 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec,
3342 data->uris, data->context,
3343 _SPAWN_FLAGS_DEFAULT, NULL,
3344 NULL, NULL, NULL, -1, -1, -1,
3348 g_task_return_error (task, g_steal_pointer (&error));
3349 g_object_unref (task);
3351 else if (session_bus)
3352 g_dbus_connection_flush (session_bus,
3354 launch_uris_flush_cb,
3355 g_steal_pointer (&task));
3358 g_task_return_boolean (task, TRUE);
3359 g_clear_object (&task);
3363 g_clear_object (&session_bus);
3367 g_desktop_app_info_launch_uris_async (GAppInfo *appinfo,
3369 GAppLaunchContext *context,
3370 GCancellable *cancellable,
3371 GAsyncReadyCallback callback,
3375 LaunchUrisData *data;
3377 task = g_task_new (appinfo, cancellable, callback, user_data);
3378 g_task_set_source_tag (task, g_desktop_app_info_launch_uris_async);
3380 data = g_new0 (LaunchUrisData, 1);
3381 data->uris = g_list_copy_deep (uris, (GCopyFunc) g_strdup, NULL);
3382 data->context = (context != NULL) ? g_object_ref (context) : NULL;
3383 g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) launch_uris_data_free);
3385 g_bus_get (G_BUS_TYPE_SESSION, cancellable, launch_uris_bus_get_cb, task);
3389 g_desktop_app_info_launch_uris_finish (GAppInfo *appinfo,
3390 GAsyncResult *result,
3393 g_return_val_if_fail (g_task_is_valid (result, appinfo), FALSE);
3395 return g_task_propagate_boolean (G_TASK (result), error);
3399 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
3401 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3403 return info->exec &&
3404 ((strstr (info->exec, "%u") != NULL) ||
3405 (strstr (info->exec, "%U") != NULL));
3409 g_desktop_app_info_supports_files (GAppInfo *appinfo)
3411 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3413 return info->exec &&
3414 ((strstr (info->exec, "%f") != NULL) ||
3415 (strstr (info->exec, "%F") != NULL));
3419 g_desktop_app_info_launch (GAppInfo *appinfo,
3421 GAppLaunchContext *launch_context,
3431 uri = g_file_get_uri (files->data);
3432 uris = g_list_prepend (uris, uri);
3433 files = files->next;
3436 uris = g_list_reverse (uris);
3438 res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
3440 g_list_free_full (uris, g_free);
3446 * g_desktop_app_info_launch_uris_as_manager_with_fds:
3447 * @appinfo: a #GDesktopAppInfo
3448 * @uris: (element-type utf8): List of URIs
3449 * @launch_context: (nullable): a #GAppLaunchContext
3450 * @spawn_flags: #GSpawnFlags, used for each process
3451 * @user_setup: (scope async) (nullable): a #GSpawnChildSetupFunc, used once
3453 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
3454 * @pid_callback: (scope call) (nullable): Callback for child processes
3455 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
3456 * @stdin_fd: file descriptor to use for child's stdin, or -1
3457 * @stdout_fd: file descriptor to use for child's stdout, or -1
3458 * @stderr_fd: file descriptor to use for child's stderr, or -1
3459 * @error: return location for a #GError, or %NULL
3461 * Equivalent to g_desktop_app_info_launch_uris_as_manager() but allows
3462 * you to pass in file descriptors for the stdin, stdout and stderr streams
3463 * of the launched process.
3465 * If application launching occurs via some non-spawn mechanism (e.g. D-Bus
3466 * activation) then @stdin_fd, @stdout_fd and @stderr_fd are ignored.
3468 * Returns: %TRUE on successful launch, %FALSE otherwise.
3473 g_desktop_app_info_launch_uris_as_manager_with_fds (GDesktopAppInfo *appinfo,
3475 GAppLaunchContext *launch_context,
3476 GSpawnFlags spawn_flags,
3477 GSpawnChildSetupFunc user_setup,
3478 gpointer user_setup_data,
3479 GDesktopAppLaunchCallback pid_callback,
3480 gpointer pid_callback_data,
3486 return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
3501 * g_desktop_app_info_launch_uris_as_manager:
3502 * @appinfo: a #GDesktopAppInfo
3503 * @uris: (element-type utf8): List of URIs
3504 * @launch_context: (nullable): a #GAppLaunchContext
3505 * @spawn_flags: #GSpawnFlags, used for each process
3506 * @user_setup: (scope async) (nullable): a #GSpawnChildSetupFunc, used once
3508 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
3509 * @pid_callback: (scope call) (nullable): Callback for child processes
3510 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
3511 * @error: return location for a #GError, or %NULL
3513 * This function performs the equivalent of g_app_info_launch_uris(),
3514 * but is intended primarily for operating system components that
3515 * launch applications. Ordinary applications should use
3516 * g_app_info_launch_uris().
3518 * If the application is launched via GSpawn, then @spawn_flags, @user_setup
3519 * and @user_setup_data are used for the call to g_spawn_async().
3520 * Additionally, @pid_callback (with @pid_callback_data) will be called to
3521 * inform about the PID of the created process. See g_spawn_async_with_pipes()
3522 * for information on certain parameter conditions that can enable an
3523 * optimized posix_spawn() codepath to be used.
3525 * If application launching occurs via some other mechanism (eg: D-Bus
3526 * activation) then @spawn_flags, @user_setup, @user_setup_data,
3527 * @pid_callback and @pid_callback_data are ignored.
3529 * Returns: %TRUE on successful launch, %FALSE otherwise.
3532 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo *appinfo,
3534 GAppLaunchContext *launch_context,
3535 GSpawnFlags spawn_flags,
3536 GSpawnChildSetupFunc user_setup,
3537 gpointer user_setup_data,
3538 GDesktopAppLaunchCallback pid_callback,
3539 gpointer pid_callback_data,
3542 return g_desktop_app_info_launch_uris_as_manager_with_fds (appinfo,
3554 /* OnlyShowIn API support {{{2 */
3557 * g_desktop_app_info_set_desktop_env:
3558 * @desktop_env: a string specifying what desktop this is
3560 * Sets the name of the desktop that the application is running in.
3561 * This is used by g_app_info_should_show() and
3562 * g_desktop_app_info_get_show_in() to evaluate the
3563 * `OnlyShowIn` and `NotShowIn`
3564 * desktop entry fields.
3566 * Should be called only once; subsequent calls are ignored.
3568 * Deprecated:2.42:do not use this API. Since 2.42 the value of the
3569 * `XDG_CURRENT_DESKTOP` environment variable will be used.
3572 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
3574 get_current_desktops (desktop_env);
3578 g_desktop_app_info_should_show (GAppInfo *appinfo)
3580 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3582 if (info->nodisplay)
3585 return g_desktop_app_info_get_show_in (info, NULL);
3588 /* mime types/default apps support {{{2 */
3597 ensure_dir (DirType type,
3600 char *path, *display_name;
3606 path = g_build_filename (g_get_user_config_dir (), NULL);
3610 path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
3614 path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
3618 g_assert_not_reached ();
3621 g_debug ("%s: Ensuring %s", G_STRFUNC, path);
3624 if (g_mkdir_with_parents (path, 0700) == 0)
3628 display_name = g_filename_display_name (path);
3629 if (type == APP_DIR)
3630 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3631 _("Can’t create user application configuration folder %s: %s"),
3632 display_name, g_strerror (errsv));
3634 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3635 _("Can’t create user MIME configuration folder %s: %s"),
3636 display_name, g_strerror (errsv));
3638 g_free (display_name);
3645 update_mimeapps_list (const char *desktop_id,
3646 const char *content_type,
3647 UpdateMimeFlags flags,
3650 char *dirname, *filename, *string;
3652 gboolean load_succeeded, res;
3653 char **old_list, **list;
3654 gsize length, data_size;
3657 char **content_types;
3659 /* Don't add both at start and end */
3660 g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
3661 (flags & UPDATE_MIME_SET_NON_DEFAULT)));
3663 dirname = ensure_dir (CONF_DIR, error);
3667 filename = g_build_filename (dirname, "mimeapps.list", NULL);
3670 key_file = g_key_file_new ();
3671 load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
3672 if (!load_succeeded ||
3673 (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
3674 !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
3675 !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
3677 g_key_file_free (key_file);
3678 key_file = g_key_file_new ();
3683 content_types = g_new (char *, 2);
3684 content_types[0] = g_strdup (content_type);
3685 content_types[1] = NULL;
3689 content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
3692 for (k = 0; content_types && content_types[k]; k++)
3694 /* set as default, if requested so */
3695 string = g_key_file_get_string (key_file,
3696 DEFAULT_APPLICATIONS_GROUP,
3700 if (g_strcmp0 (string, desktop_id) != 0 &&
3701 (flags & UPDATE_MIME_SET_DEFAULT))
3704 string = g_strdup (desktop_id);
3706 /* add in the non-default list too, if it's not already there */
3707 flags |= UPDATE_MIME_SET_NON_DEFAULT;
3710 if (string == NULL || desktop_id == NULL)
3711 g_key_file_remove_key (key_file,
3712 DEFAULT_APPLICATIONS_GROUP,
3716 g_key_file_set_string (key_file,
3717 DEFAULT_APPLICATIONS_GROUP,
3726 /* reuse the list from above */
3730 g_strfreev (content_types);
3731 content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
3734 for (k = 0; content_types && content_types[k]; k++)
3736 /* Add to the right place in the list */
3739 old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
3740 content_types[k], &length, NULL);
3742 list = g_new (char *, 1 + length + 1);
3746 /* if we're adding a last-used hint, just put the application in front of the list */
3747 if (flags & UPDATE_MIME_SET_LAST_USED)
3749 /* avoid adding this again as non-default later */
3750 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3751 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3753 list[i++] = g_strdup (desktop_id);
3758 for (j = 0; old_list[j] != NULL; j++)
3760 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3762 /* rewrite other entries if they're different from the new one */
3763 list[i++] = g_strdup (old_list[j]);
3765 else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3767 /* we encountered an old entry which is equal to the one we're adding as non-default,
3768 * don't change its position in the list.
3770 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3771 list[i++] = g_strdup (old_list[j]);
3776 /* add it at the end of the list */
3777 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3778 list[i++] = g_strdup (desktop_id);
3782 g_strfreev (old_list);
3784 if (list[0] == NULL || desktop_id == NULL)
3785 g_key_file_remove_key (key_file,
3786 ADDED_ASSOCIATIONS_GROUP,
3790 g_key_file_set_string_list (key_file,
3791 ADDED_ASSOCIATIONS_GROUP,
3793 (const char * const *)list, i);
3800 /* reuse the list from above */
3804 g_strfreev (content_types);
3805 content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
3808 for (k = 0; content_types && content_types[k]; k++)
3810 /* Remove from removed associations group (unless remove) */
3813 old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
3814 content_types[k], &length, NULL);
3816 list = g_new (char *, 1 + length + 1);
3819 if (flags & UPDATE_MIME_REMOVE)
3820 list[i++] = g_strdup (desktop_id);
3823 for (j = 0; old_list[j] != NULL; j++)
3825 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3826 list[i++] = g_strdup (old_list[j]);
3831 g_strfreev (old_list);
3833 if (list[0] == NULL || desktop_id == NULL)
3834 g_key_file_remove_key (key_file,
3835 REMOVED_ASSOCIATIONS_GROUP,
3839 g_key_file_set_string_list (key_file,
3840 REMOVED_ASSOCIATIONS_GROUP,
3842 (const char * const *)list, i);
3847 g_strfreev (content_types);
3849 data = g_key_file_to_data (key_file, &data_size, error);
3850 g_key_file_free (key_file);
3852 res = g_file_set_contents_full (filename, data, data_size,
3853 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
3856 desktop_file_dirs_invalidate_user_config ();
3865 g_desktop_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
3866 const char *content_type,
3869 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3871 if (!g_desktop_app_info_ensure_saved (info, error))
3874 if (!info->desktop_id)
3876 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3877 _("Application information lacks an identifier"));
3881 /* both add support for the content type and set as last used */
3882 return update_mimeapps_list (info->desktop_id, content_type,
3883 UPDATE_MIME_SET_NON_DEFAULT |
3884 UPDATE_MIME_SET_LAST_USED,
3889 g_desktop_app_info_set_as_default_for_type (GAppInfo *appinfo,
3890 const char *content_type,
3893 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3895 if (!g_desktop_app_info_ensure_saved (info, error))
3898 if (!info->desktop_id)
3900 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3901 _("Application information lacks an identifier"));
3905 return update_mimeapps_list (info->desktop_id, content_type,
3906 UPDATE_MIME_SET_DEFAULT,
3911 update_program_done (GPid pid,
3915 /* Did the application exit correctly */
3916 if (g_spawn_check_wait_status (status, NULL))
3918 /* Here we could clean out any caches in use */
3923 run_update_command (char *command,
3932 GError *error = NULL;
3935 argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
3937 if (g_spawn_async ("/", argv,
3939 G_SPAWN_SEARCH_PATH |
3940 G_SPAWN_STDOUT_TO_DEV_NULL |
3941 G_SPAWN_STDERR_TO_DEV_NULL |
3942 G_SPAWN_DO_NOT_REAP_CHILD,
3943 NULL, NULL, /* No setup function */
3946 g_child_watch_add (pid, update_program_done, NULL);
3949 /* If we get an error at this point, it's quite likely the user doesn't
3950 * have an installed copy of either 'update-mime-database' or
3951 * 'update-desktop-database'. I don't think we want to popup an error
3952 * dialog at this point, so we just do a g_warning to give the user a
3953 * chance of debugging it.
3955 g_warning ("%s", error->message);
3956 g_error_free (error);
3963 g_desktop_app_info_set_as_default_for_extension (GAppInfo *appinfo,
3964 const char *extension,
3967 char *filename, *basename, *mimetype;
3971 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
3974 dirname = ensure_dir (MIMETYPE_DIR, error);
3978 basename = g_strdup_printf ("user-extension-%s.xml", extension);
3979 filename = g_build_filename (dirname, basename, NULL);
3983 mimetype = g_strdup_printf ("application/x-extension-%s", extension);
3985 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
3990 g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
3991 "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
3992 " <mime-type type=\"%s\">\n"
3993 " <comment>%s document</comment>\n"
3994 " <glob pattern=\"*.%s\"/>\n"
3996 "</mime-info>\n", mimetype, extension, extension);
3998 g_file_set_contents_full (filename, contents, -1,
3999 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
4003 run_update_command ("update-mime-database", "mime");
4007 res = g_desktop_app_info_set_as_default_for_type (appinfo,
4017 g_desktop_app_info_add_supports_type (GAppInfo *appinfo,
4018 const char *content_type,
4021 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4023 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
4026 return update_mimeapps_list (info->desktop_id, content_type,
4027 UPDATE_MIME_SET_NON_DEFAULT,
4032 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
4038 g_desktop_app_info_remove_supports_type (GAppInfo *appinfo,
4039 const char *content_type,
4042 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4044 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
4047 return update_mimeapps_list (info->desktop_id, content_type,
4052 static const char **
4053 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
4055 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4057 return (const char**) info->mime_types;
4060 /* Saving and deleting {{{2 */
4063 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
4069 char *data, *desktop_id;
4074 if (info->filename != NULL)
4077 /* This is only used for object created with
4078 * g_app_info_create_from_commandline. All other
4079 * object should have a filename
4082 dirname = ensure_dir (APP_DIR, error);
4086 key_file = g_key_file_new ();
4088 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4089 "Encoding", "UTF-8");
4090 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4091 G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
4092 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4093 G_KEY_FILE_DESKTOP_KEY_TYPE,
4094 G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
4096 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4097 G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
4098 if (info->nodisplay)
4099 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4100 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
4102 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4103 G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
4105 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4106 G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
4108 if (info->generic_name != NULL)
4109 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4110 GENERIC_NAME_KEY, info->generic_name);
4112 if (info->fullname != NULL)
4113 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4114 FULL_NAME_KEY, info->fullname);
4116 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4117 G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
4119 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4120 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
4122 data = g_key_file_to_data (key_file, &data_size, NULL);
4123 g_key_file_free (key_file);
4125 desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
4126 filename = g_build_filename (dirname, desktop_id, NULL);
4127 g_free (desktop_id);
4130 fd = g_mkstemp (filename);
4135 display_name = g_filename_display_name (filename);
4136 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
4137 _("Can’t create user desktop file %s"), display_name);
4138 g_free (display_name);
4144 desktop_id = g_path_get_basename (filename);
4146 /* FIXME - actually handle error */
4147 (void) g_close (fd, NULL);
4149 res = g_file_set_contents_full (filename, data, data_size,
4150 G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
4155 g_free (desktop_id);
4160 info->filename = filename;
4161 info->desktop_id = desktop_id;
4163 run_update_command ("update-desktop-database", "applications");
4165 /* We just dropped a file in the user's desktop file directory. Save
4166 * the monitor the bother of having to notice it and invalidate
4169 * This means that calls directly following this will be able to see
4170 * the results immediately.
4172 desktop_file_dirs_invalidate_user_data ();
4178 g_desktop_app_info_can_delete (GAppInfo *appinfo)
4180 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4184 if (strstr (info->filename, "/userapp-"))
4185 return g_access (info->filename, W_OK) == 0;
4192 g_desktop_app_info_delete (GAppInfo *appinfo)
4194 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4198 if (g_remove (info->filename) == 0)
4200 update_mimeapps_list (info->desktop_id, NULL,
4204 g_free (info->filename);
4205 info->filename = NULL;
4206 g_free (info->desktop_id);
4207 info->desktop_id = NULL;
4216 /* Create for commandline {{{2 */
4218 * g_app_info_create_from_commandline:
4219 * @commandline: (type filename): the commandline to use
4220 * @application_name: (nullable): the application name, or %NULL to use @commandline
4221 * @flags: flags that can specify details of the created #GAppInfo
4222 * @error: a #GError location to store the error occurring, %NULL to ignore.
4224 * Creates a new #GAppInfo from the given information.
4226 * Note that for @commandline, the quoting rules of the Exec key of the
4227 * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
4228 * are applied. For example, if the @commandline contains
4229 * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
4230 * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
4232 * Returns: (transfer full): new #GAppInfo for given command.
4235 g_app_info_create_from_commandline (const char *commandline,
4236 const char *application_name,
4237 GAppInfoCreateFlags flags,
4242 GDesktopAppInfo *info;
4244 g_return_val_if_fail (commandline, NULL);
4246 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
4248 info->filename = NULL;
4249 info->desktop_id = NULL;
4251 info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
4252 info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
4253 info->hidden = FALSE;
4254 if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
4255 info->exec = g_strconcat (commandline, " %u", NULL);
4257 info->exec = g_strconcat (commandline, " %f", NULL);
4258 info->nodisplay = TRUE;
4259 info->binary = binary_from_exec (info->exec);
4261 if (application_name)
4262 info->name = g_strdup (application_name);
4265 /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
4266 split = g_strsplit (commandline, " ", 2);
4267 basename = split[0] ? g_path_get_basename (split[0]) : NULL;
4269 info->name = basename;
4270 if (info->name == NULL)
4271 info->name = g_strdup ("custom");
4273 info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
4275 return G_APP_INFO (info);
4278 /* GAppInfo interface init */
4281 g_desktop_app_info_iface_init (GAppInfoIface *iface)
4283 iface->dup = g_desktop_app_info_dup;
4284 iface->equal = g_desktop_app_info_equal;
4285 iface->get_id = g_desktop_app_info_get_id;
4286 iface->get_name = g_desktop_app_info_get_name;
4287 iface->get_description = g_desktop_app_info_get_description;
4288 iface->get_executable = g_desktop_app_info_get_executable;
4289 iface->get_icon = g_desktop_app_info_get_icon;
4290 iface->launch = g_desktop_app_info_launch;
4291 iface->supports_uris = g_desktop_app_info_supports_uris;
4292 iface->supports_files = g_desktop_app_info_supports_files;
4293 iface->launch_uris = g_desktop_app_info_launch_uris;
4294 iface->launch_uris_async = g_desktop_app_info_launch_uris_async;
4295 iface->launch_uris_finish = g_desktop_app_info_launch_uris_finish;
4296 iface->should_show = g_desktop_app_info_should_show;
4297 iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
4298 iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
4299 iface->add_supports_type = g_desktop_app_info_add_supports_type;
4300 iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
4301 iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
4302 iface->can_delete = g_desktop_app_info_can_delete;
4303 iface->do_delete = g_desktop_app_info_delete;
4304 iface->get_commandline = g_desktop_app_info_get_commandline;
4305 iface->get_display_name = g_desktop_app_info_get_display_name;
4306 iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
4307 iface->get_supported_types = g_desktop_app_info_get_supported_types;
4310 /* Recommended applications {{{2 */
4312 /* Converts content_type into a list of itself with all of its parent
4313 * types (if include_fallback is enabled) or just returns a single-item
4314 * list with the unaliased content type.
4317 get_list_of_mimetypes (const gchar *content_type,
4318 gboolean include_fallback)
4323 array = g_ptr_array_new ();
4324 unaliased = _g_unix_content_type_unalias (content_type);
4325 g_ptr_array_add (array, unaliased);
4327 if (include_fallback)
4331 /* Iterate the array as we grow it, until we have nothing more to add */
4332 for (i = 0; i < array->len; i++)
4334 gchar **parents = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4337 for (j = 0; parents[j]; j++)
4338 /* Don't add duplicates */
4339 if (!array_contains (array, parents[j]))
4340 g_ptr_array_add (array, parents[j]);
4342 g_free (parents[j]);
4344 /* We already stole or freed each element. Free the container. */
4349 g_ptr_array_add (array, NULL);
4351 return (gchar **) g_ptr_array_free (array, FALSE);
4355 g_desktop_app_info_get_desktop_ids_for_content_type (const gchar *content_type,
4356 gboolean include_fallback)
4358 GPtrArray *hits, *blocklist;
4362 hits = g_ptr_array_new ();
4363 blocklist = g_ptr_array_new ();
4365 types = get_list_of_mimetypes (content_type, include_fallback);
4367 desktop_file_dirs_lock ();
4369 for (i = 0; types[i]; i++)
4370 for (j = 0; j < desktop_file_dirs->len; j++)
4371 desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], hits, blocklist);
4373 /* We will keep the hits past unlocking, so we must dup them */
4374 for (i = 0; i < hits->len; i++)
4375 hits->pdata[i] = g_strdup (hits->pdata[i]);
4377 desktop_file_dirs_unlock ();
4379 g_ptr_array_add (hits, NULL);
4381 g_ptr_array_free (blocklist, TRUE);
4384 return (gchar **) g_ptr_array_free (hits, FALSE);
4388 * g_app_info_get_recommended_for_type:
4389 * @content_type: the content type to find a #GAppInfo for
4391 * Gets a list of recommended #GAppInfos for a given content type, i.e.
4392 * those applications which claim to support the given content type exactly,
4393 * and not by MIME type subclassing.
4394 * Note that the first application of the list is the last used one, i.e.
4395 * the last one for which g_app_info_set_as_last_used_for_type() has been
4398 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4399 * for given @content_type or %NULL on error.
4404 g_app_info_get_recommended_for_type (const gchar *content_type)
4406 gchar **desktop_ids;
4410 g_return_val_if_fail (content_type != NULL, NULL);
4412 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4415 for (i = 0; desktop_ids[i]; i++)
4417 GDesktopAppInfo *info;
4419 info = g_desktop_app_info_new (desktop_ids[i]);
4421 infos = g_list_prepend (infos, info);
4424 g_strfreev (desktop_ids);
4426 return g_list_reverse (infos);
4430 * g_app_info_get_fallback_for_type:
4431 * @content_type: the content type to find a #GAppInfo for
4433 * Gets a list of fallback #GAppInfos for a given content type, i.e.
4434 * those applications which claim to support the given content type
4435 * by MIME type subclassing and not directly.
4437 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4438 * for given @content_type or %NULL on error.
4443 g_app_info_get_fallback_for_type (const gchar *content_type)
4445 gchar **recommended_ids;
4450 g_return_val_if_fail (content_type != NULL, NULL);
4452 recommended_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4453 all_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4456 for (i = 0; all_ids[i]; i++)
4458 GDesktopAppInfo *info;
4461 /* Don't return the ones on the recommended list */
4462 for (j = 0; recommended_ids[j]; j++)
4463 if (g_str_equal (all_ids[i], recommended_ids[j]))
4466 if (recommended_ids[j])
4469 info = g_desktop_app_info_new (all_ids[i]);
4472 infos = g_list_prepend (infos, info);
4475 g_strfreev (recommended_ids);
4476 g_strfreev (all_ids);
4478 return g_list_reverse (infos);
4482 * g_app_info_get_all_for_type:
4483 * @content_type: the content type to find a #GAppInfo for
4485 * Gets a list of all #GAppInfos for a given content type,
4486 * including the recommended and fallback #GAppInfos. See
4487 * g_app_info_get_recommended_for_type() and
4488 * g_app_info_get_fallback_for_type().
4490 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
4491 * for given @content_type or %NULL on error.
4494 g_app_info_get_all_for_type (const char *content_type)
4496 gchar **desktop_ids;
4500 g_return_val_if_fail (content_type != NULL, NULL);
4502 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4505 for (i = 0; desktop_ids[i]; i++)
4507 GDesktopAppInfo *info;
4509 info = g_desktop_app_info_new (desktop_ids[i]);
4511 infos = g_list_prepend (infos, info);
4514 g_strfreev (desktop_ids);
4516 return g_list_reverse (infos);
4520 * g_app_info_reset_type_associations:
4521 * @content_type: a content type
4523 * Removes all changes to the type associations done by
4524 * g_app_info_set_as_default_for_type(),
4525 * g_app_info_set_as_default_for_extension(),
4526 * g_app_info_add_supports_type() or
4527 * g_app_info_remove_supports_type().
4532 g_app_info_reset_type_associations (const char *content_type)
4534 update_mimeapps_list (NULL, content_type,
4540 * g_app_info_get_default_for_type:
4541 * @content_type: the content type to find a #GAppInfo for
4542 * @must_support_uris: if %TRUE, the #GAppInfo is expected to
4545 * Gets the default #GAppInfo for a given content type.
4547 * Returns: (transfer full) (nullable): #GAppInfo for given @content_type or
4551 g_app_info_get_default_for_type (const char *content_type,
4552 gboolean must_support_uris)
4554 GPtrArray *blocklist;
4560 g_return_val_if_fail (content_type != NULL, NULL);
4562 types = get_list_of_mimetypes (content_type, TRUE);
4564 blocklist = g_ptr_array_new ();
4565 results = g_ptr_array_new ();
4568 desktop_file_dirs_lock ();
4570 for (i = 0; types[i]; i++)
4572 /* Collect all the default apps for this type */
4573 for (j = 0; j < desktop_file_dirs->len; j++)
4574 desktop_file_dir_default_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results);
4576 /* Consider the associations as well... */
4577 for (j = 0; j < desktop_file_dirs->len; j++)
4578 desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results, blocklist);
4580 /* (If any), see if one of those apps is installed... */
4581 for (j = 0; j < results->len; j++)
4583 const gchar *desktop_id = g_ptr_array_index (results, j);
4585 for (k = 0; k < desktop_file_dirs->len; k++)
4587 info = (GAppInfo *) desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, k), desktop_id);
4591 if (!must_support_uris || g_app_info_supports_uris (info))
4594 g_clear_object (&info);
4599 /* Reset the list, ready to try again with the next (parent)
4600 * mimetype, but keep the blocklist in place.
4602 g_ptr_array_set_size (results, 0);
4606 desktop_file_dirs_unlock ();
4608 g_ptr_array_unref (blocklist);
4609 g_ptr_array_unref (results);
4616 * g_app_info_get_default_for_uri_scheme:
4617 * @uri_scheme: a string containing a URI scheme.
4619 * Gets the default application for handling URIs with
4620 * the given URI scheme. A URI scheme is the initial part
4621 * of the URI, up to but not including the ':', e.g. "http",
4624 * Returns: (transfer full) (nullable): #GAppInfo for given @uri_scheme or
4628 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
4631 char *content_type, *scheme_down;
4633 g_return_val_if_fail (uri_scheme != NULL && *uri_scheme != '\0', NULL);
4635 scheme_down = g_ascii_strdown (uri_scheme, -1);
4636 content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
4637 g_free (scheme_down);
4638 app_info = g_app_info_get_default_for_type (content_type, FALSE);
4639 g_free (content_type);
4644 /* "Get all" API {{{2 */
4647 * g_desktop_app_info_get_implementations:
4648 * @interface: the name of the interface
4650 * Gets all applications that implement @interface.
4652 * An application implements an interface if that interface is listed in
4653 * the Implements= line of the desktop file of the application.
4655 * Returns: (element-type GDesktopAppInfo) (transfer full): a list of #GDesktopAppInfo
4661 g_desktop_app_info_get_implementations (const gchar *interface)
4663 GList *result = NULL;
4667 desktop_file_dirs_lock ();
4669 for (i = 0; i < desktop_file_dirs->len; i++)
4670 desktop_file_dir_get_implementations (g_ptr_array_index (desktop_file_dirs, i), &result, interface);
4672 desktop_file_dirs_unlock ();
4677 gchar *name = (*ptr)->data;
4678 GDesktopAppInfo *app;
4680 app = g_desktop_app_info_new (name);
4686 ptr = &(*ptr)->next;
4689 *ptr = g_list_delete_link (*ptr, *ptr);
4696 * g_desktop_app_info_search:
4697 * @search_string: the search string to use
4699 * Searches desktop files for ones that match @search_string.
4701 * The return value is an array of strvs. Each strv contains a list of
4702 * applications that matched @search_string with an equal score. The
4703 * outer list is sorted by score so that the first strv contains the
4704 * best-matching applications, and so on.
4705 * The algorithm for determining matches is undefined and may change at
4708 * None of the search results are subjected to the normal validation
4709 * checks performed by g_desktop_app_info_new() (for example, checking that
4710 * the executable referenced by a result exists), and so it is possible for
4711 * g_desktop_app_info_new() to return %NULL when passed an app ID returned by
4712 * this function. It is expected that calling code will do this when
4713 * subsequently creating a #GDesktopAppInfo for each result.
4715 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
4716 * list of strvs. Free each item with g_strfreev() and free the outer
4717 * list with g_free().
4720 g_desktop_app_info_search (const gchar *search_string)
4722 gchar **search_tokens;
4723 gint last_category = -1;
4725 gint n_categories = 0;
4726 gint start_of_category;
4730 search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
4732 desktop_file_dirs_lock ();
4734 reset_total_search_results ();
4736 for (k = 0; k < desktop_file_dirs->len; k++)
4738 for (j = 0; search_tokens[j]; j++)
4740 desktop_file_dir_search (g_ptr_array_index (desktop_file_dirs, k), search_tokens[j]);
4741 merge_token_results (j == 0);
4743 merge_directory_results ();
4746 sort_total_search_results ();
4748 /* Count the total number of unique categories */
4749 for (i = 0; i < static_total_results_size; i++)
4750 if (static_total_results[i].category != last_category)
4752 last_category = static_total_results[i].category;
4756 results = g_new (gchar **, n_categories + 1);
4758 /* Start loading into the results list */
4759 start_of_category = 0;
4760 for (i = 0; i < n_categories; i++)
4762 gint n_items_in_category = 0;
4766 this_category = static_total_results[start_of_category].category;
4768 while (start_of_category + n_items_in_category < static_total_results_size &&
4769 static_total_results[start_of_category + n_items_in_category].category == this_category)
4770 n_items_in_category++;
4772 results[i] = g_new (gchar *, n_items_in_category + 1);
4773 for (j = 0; j < n_items_in_category; j++)
4774 results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
4775 results[i][j] = NULL;
4777 start_of_category += n_items_in_category;
4781 desktop_file_dirs_unlock ();
4783 g_strfreev (search_tokens);
4789 * g_app_info_get_all:
4791 * Gets a list of all of the applications currently registered
4794 * For desktop files, this includes applications that have
4795 * `NoDisplay=true` set or are excluded from display by means
4796 * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
4797 * The returned list does not include applications which have
4798 * the `Hidden` key set.
4800 * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
4803 g_app_info_get_all (void)
4806 GHashTableIter iter;
4811 apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4813 desktop_file_dirs_lock ();
4815 for (i = 0; i < desktop_file_dirs->len; i++)
4816 desktop_file_dir_get_all (g_ptr_array_index (desktop_file_dirs, i), apps);
4818 desktop_file_dirs_unlock ();
4821 g_hash_table_iter_init (&iter, apps);
4822 while (g_hash_table_iter_next (&iter, NULL, &value))
4825 infos = g_list_prepend (infos, value);
4828 g_hash_table_destroy (apps);
4833 /* GDesktopAppInfoLookup interface {{{2 */
4836 * GDesktopAppInfoLookup:
4838 * #GDesktopAppInfoLookup is an opaque data structure and can only be accessed
4839 * using the following functions.
4841 * Deprecated: 2.28: The #GDesktopAppInfoLookup interface is deprecated and
4845 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4847 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4848 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4851 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4855 /* "Get for mime type" APIs {{{2 */
4858 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4859 * @lookup: a #GDesktopAppInfoLookup
4860 * @uri_scheme: a string containing a URI scheme.
4862 * Gets the default application for launching applications
4863 * using this URI scheme for a particular #GDesktopAppInfoLookup
4866 * The #GDesktopAppInfoLookup interface and this function is used
4867 * to implement g_app_info_get_default_for_uri_scheme() backends
4868 * in a GIO module. There is no reason for applications to use it
4869 * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4871 * Returns: (transfer full) (nullable): #GAppInfo for given @uri_scheme or
4874 * Deprecated: 2.28: The #GDesktopAppInfoLookup interface is deprecated and
4878 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4879 const char *uri_scheme)
4881 GDesktopAppInfoLookupIface *iface;
4883 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4885 iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4887 return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4890 G_GNUC_END_IGNORE_DEPRECATIONS
4892 /* Misc getter APIs {{{2 */
4895 * g_desktop_app_info_get_startup_wm_class:
4896 * @info: a #GDesktopAppInfo that supports startup notify
4898 * Retrieves the StartupWMClass field from @info. This represents the
4899 * WM_CLASS property of the main window of the application, if launched
4902 * Returns: (nullable) (transfer none): the startup WM class, or %NULL if none is set
4903 * in the desktop file.
4908 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4910 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4912 return info->startup_wm_class;
4916 * g_desktop_app_info_get_string:
4917 * @info: a #GDesktopAppInfo
4918 * @key: the key to look up
4920 * Looks up a string value in the keyfile backing @info.
4922 * The @key is looked up in the "Desktop Entry" group.
4924 * Returns: (nullable): a newly allocated string, or %NULL if the key
4930 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4933 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4935 return g_key_file_get_string (info->keyfile,
4936 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4940 * g_desktop_app_info_get_locale_string:
4941 * @info: a #GDesktopAppInfo
4942 * @key: the key to look up
4944 * Looks up a localized string value in the keyfile backing @info
4945 * translated to the current locale.
4947 * The @key is looked up in the "Desktop Entry" group.
4949 * Returns: (nullable): a newly allocated string, or %NULL if the key
4955 g_desktop_app_info_get_locale_string (GDesktopAppInfo *info,
4958 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4959 g_return_val_if_fail (key != NULL && *key != '\0', NULL);
4961 return g_key_file_get_locale_string (info->keyfile,
4962 G_KEY_FILE_DESKTOP_GROUP,
4967 * g_desktop_app_info_get_boolean:
4968 * @info: a #GDesktopAppInfo
4969 * @key: the key to look up
4971 * Looks up a boolean value in the keyfile backing @info.
4973 * The @key is looked up in the "Desktop Entry" group.
4975 * Returns: the boolean value, or %FALSE if the key
4981 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4984 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4986 return g_key_file_get_boolean (info->keyfile,
4987 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4991 * g_desktop_app_info_get_string_list:
4992 * @info: a #GDesktopAppInfo
4993 * @key: the key to look up
4994 * @length: (out) (optional): return location for the number of returned strings, or %NULL
4996 * Looks up a string list value in the keyfile backing @info.
4998 * The @key is looked up in the "Desktop Entry" group.
5000 * Returns: (array zero-terminated=1 length=length) (element-type utf8) (transfer full):
5001 * a %NULL-terminated string array or %NULL if the specified
5002 * key cannot be found. The array should be freed with g_strfreev().
5007 g_desktop_app_info_get_string_list (GDesktopAppInfo *info,
5011 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5013 return g_key_file_get_string_list (info->keyfile,
5014 G_KEY_FILE_DESKTOP_GROUP, key, length, NULL);
5018 * g_desktop_app_info_has_key:
5019 * @info: a #GDesktopAppInfo
5020 * @key: the key to look up
5022 * Returns whether @key exists in the "Desktop Entry" group
5023 * of the keyfile backing @info.
5025 * Returns: %TRUE if the @key exists
5030 g_desktop_app_info_has_key (GDesktopAppInfo *info,
5033 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
5035 return g_key_file_has_key (info->keyfile,
5036 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
5039 /* Desktop actions support {{{2 */
5042 * g_desktop_app_info_list_actions:
5043 * @info: a #GDesktopAppInfo
5045 * Returns the list of "additional application actions" supported on the
5046 * desktop file, as per the desktop file specification.
5048 * As per the specification, this is the list of actions that are
5049 * explicitly listed in the "Actions" key of the [Desktop Entry] group.
5051 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
5055 const gchar * const *
5056 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
5058 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5060 return (const gchar **) info->actions;
5064 app_info_has_action (GDesktopAppInfo *info,
5065 const gchar *action_name)
5069 for (i = 0; info->actions[i]; i++)
5070 if (g_str_equal (info->actions[i], action_name))
5077 * g_desktop_app_info_get_action_name:
5078 * @info: a #GDesktopAppInfo
5079 * @action_name: the name of the action as from
5080 * g_desktop_app_info_list_actions()
5082 * Gets the user-visible display name of the "additional application
5083 * action" specified by @action_name.
5085 * This corresponds to the "Name" key within the keyfile group for the
5088 * Returns: (transfer full): the locale-specific action name
5093 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
5094 const gchar *action_name)
5099 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5100 g_return_val_if_fail (action_name != NULL, NULL);
5101 g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
5103 group_name = g_strdup_printf ("Desktop Action %s", action_name);
5104 result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
5105 g_free (group_name);
5107 /* The spec says that the Name field must be given.
5109 * If it's not, let's follow the behaviour of our get_name()
5110 * implementation above and never return %NULL.
5113 result = g_strdup (_("Unnamed"));
5119 * g_desktop_app_info_launch_action:
5120 * @info: a #GDesktopAppInfo
5121 * @action_name: the name of the action as from
5122 * g_desktop_app_info_list_actions()
5123 * @launch_context: (nullable): a #GAppLaunchContext
5125 * Activates the named application action.
5127 * You may only call this function on action names that were
5128 * returned from g_desktop_app_info_list_actions().
5130 * Note that if the main entry of the desktop file indicates that the
5131 * application supports startup notification, and @launch_context is
5132 * non-%NULL, then startup notification will be used when activating the
5133 * action (and as such, invocation of the action on the receiving side
5134 * must signal the end of startup notification when it is completed).
5135 * This is the expected behaviour of applications declaring additional
5136 * actions, as per the desktop file specification.
5138 * As with g_app_info_launch() there is no way to detect failures that
5139 * occur while using this function.
5144 g_desktop_app_info_launch_action (GDesktopAppInfo *info,
5145 const gchar *action_name,
5146 GAppLaunchContext *launch_context)
5148 GDBusConnection *session_bus;
5150 g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
5151 g_return_if_fail (action_name != NULL);
5152 g_return_if_fail (app_info_has_action (info, action_name));
5154 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
5156 if (session_bus && info->app_id)
5160 object_path = object_path_from_appid (info->app_id);
5161 g_dbus_connection_call (session_bus, info->app_id, object_path,
5162 "org.freedesktop.Application", "ActivateAction",
5163 g_variant_new ("(sav@a{sv})", action_name, NULL,
5164 g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
5165 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
5166 g_free (object_path);
5173 group_name = g_strdup_printf ("Desktop Action %s", action_name);
5174 exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
5175 g_free (group_name);
5178 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
5179 _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL,
5185 if (session_bus != NULL)
5187 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
5188 g_object_unref (session_bus);
5193 /* vim:set foldmethod=marker: */