Add some more cases to the app-id unit tests
[glib.git] / gio / gdesktopappinfo.c
blob81dff27c9cd7a4827c645d2f1a77cf79ea3b4b36
1 /* GIO - GLib Input, Output and Streaming Library
3 * Copyright (C) 2006-2007 Red Hat, Inc.
4 * Copyright © 2007 Ryan Lortie
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General
17 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19 * Author: Alexander Larsson <alexl@redhat.com>
20 * Ryan Lortie <desrt@desrt.ca>
23 /* Prelude {{{1 */
25 #include "config.h"
27 #include <errno.h>
28 #include <string.h>
29 #include <unistd.h>
31 #ifdef HAVE_CRT_EXTERNS_H
32 #include <crt_externs.h>
33 #endif
35 #include "gcontenttypeprivate.h"
36 #include "gdesktopappinfo.h"
37 #ifdef G_OS_UNIX
38 #include "glib-unix.h"
39 #endif
40 #include "gfile.h"
41 #include "gioerror.h"
42 #include "gthemedicon.h"
43 #include "gfileicon.h"
44 #include <glib/gstdio.h>
45 #include "glibintl.h"
46 #include "giomodule-priv.h"
47 #include "gappinfo.h"
48 #include "gappinfoprivate.h"
49 #include "glocalfilemonitor.h"
51 /**
52 * SECTION:gdesktopappinfo
53 * @title: GDesktopAppInfo
54 * @short_description: Application information from desktop files
55 * @include: gio/gdesktopappinfo.h
57 * #GDesktopAppInfo is an implementation of #GAppInfo based on
58 * desktop files.
60 * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
61 * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
62 * file when using it.
65 #define DEFAULT_APPLICATIONS_GROUP "Default Applications"
66 #define ADDED_ASSOCIATIONS_GROUP "Added Associations"
67 #define REMOVED_ASSOCIATIONS_GROUP "Removed Associations"
68 #define MIME_CACHE_GROUP "MIME Cache"
69 #define GENERIC_NAME_KEY "GenericName"
70 #define FULL_NAME_KEY "X-GNOME-FullName"
71 #define KEYWORDS_KEY "Keywords"
72 #define STARTUP_WM_CLASS_KEY "StartupWMClass"
74 enum {
75 PROP_0,
76 PROP_FILENAME
79 static void g_desktop_app_info_iface_init (GAppInfoIface *iface);
80 static gboolean g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
81 GError **error);
83 /**
84 * GDesktopAppInfo:
86 * Information about an installed application from a desktop file.
88 struct _GDesktopAppInfo
90 GObject parent_instance;
92 char *desktop_id;
93 char *filename;
94 char *app_id;
96 GKeyFile *keyfile;
98 char *name;
99 char *generic_name;
100 char *fullname;
101 char *comment;
102 char *icon_name;
103 GIcon *icon;
104 char **keywords;
105 char **only_show_in;
106 char **not_show_in;
107 char *try_exec;
108 char *exec;
109 char *binary;
110 char *path;
111 char *categories;
112 char *startup_wm_class;
113 char **mime_types;
114 char **actions;
116 guint nodisplay : 1;
117 guint hidden : 1;
118 guint terminal : 1;
119 guint startup_notify : 1;
120 guint no_fuse : 1;
123 typedef enum {
124 UPDATE_MIME_NONE = 1 << 0,
125 UPDATE_MIME_SET_DEFAULT = 1 << 1,
126 UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
127 UPDATE_MIME_REMOVE = 1 << 3,
128 UPDATE_MIME_SET_LAST_USED = 1 << 4,
129 } UpdateMimeFlags;
131 G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
132 G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
134 /* DesktopFileDir implementation {{{1 */
136 typedef struct
138 gchar *path;
139 gchar *alternatively_watching;
140 gboolean is_config;
141 gboolean is_setup;
142 GFileMonitor *monitor;
143 GHashTable *app_names;
144 GHashTable *mime_tweaks;
145 GHashTable *memory_index;
146 GHashTable *memory_implementations;
147 } DesktopFileDir;
149 static DesktopFileDir *desktop_file_dirs;
150 static guint n_desktop_file_dirs;
151 static const guint desktop_file_dir_user_config_index = 0;
152 static guint desktop_file_dir_user_data_index;
153 static GMutex desktop_file_dir_lock;
155 /* Monitor 'changed' signal handler {{{2 */
156 static void desktop_file_dir_reset (DesktopFileDir *dir);
158 /*< internal >
159 * desktop_file_dir_get_alternative_dir:
160 * @dir: a #DesktopFileDir
162 * Gets the "alternative" directory to monitor in case the path
163 * doesn't exist.
165 * If the path exists this will return NULL, otherwise it will return a
166 * parent directory of the path.
168 * This is used to avoid inotify on a non-existent directory (which
169 * results in polling).
171 * See https://bugzilla.gnome.org/show_bug.cgi?id=522314 for more info.
173 static gchar *
174 desktop_file_dir_get_alternative_dir (DesktopFileDir *dir)
176 gchar *parent;
178 /* If the directory itself exists then we need no alternative. */
179 if (g_access (dir->path, R_OK | X_OK) == 0)
180 return NULL;
182 /* Otherwise, try the parent directories until we find one. */
183 parent = g_path_get_dirname (dir->path);
185 while (g_access (parent, R_OK | X_OK) != 0)
187 gchar *tmp = parent;
189 parent = g_path_get_dirname (tmp);
191 /* If somehow we get to '/' or '.' then just stop... */
192 if (g_str_equal (parent, tmp))
194 g_free (tmp);
195 break;
198 g_free (tmp);
201 return parent;
204 static void
205 desktop_file_dir_changed (GFileMonitor *monitor,
206 GFile *file,
207 GFile *other_file,
208 GFileMonitorEvent event_type,
209 gpointer user_data)
211 DesktopFileDir *dir = user_data;
212 gboolean do_nothing = FALSE;
214 /* We are not interested in receiving notifications forever just
215 * because someone asked about one desktop file once.
217 * After we receive the first notification, reset the dir, destroying
218 * the monitor. We will take this as a hint, next time that we are
219 * asked, that we need to check if everything is up to date.
221 * If this is a notification for a parent directory (because the
222 * desktop directory didn't exist) then we shouldn't fire the signal
223 * unless something actually changed.
225 g_mutex_lock (&desktop_file_dir_lock);
227 if (dir->alternatively_watching)
229 gchar *alternative_dir;
231 alternative_dir = desktop_file_dir_get_alternative_dir (dir);
232 do_nothing = alternative_dir && g_str_equal (dir->alternatively_watching, alternative_dir);
233 g_free (alternative_dir);
236 if (!do_nothing)
237 desktop_file_dir_reset (dir);
239 g_mutex_unlock (&desktop_file_dir_lock);
241 /* Notify anyone else who may be interested */
242 if (!do_nothing)
243 g_app_info_monitor_fire ();
246 /* Internal utility functions {{{2 */
248 /*< internal >
249 * desktop_file_dir_app_name_is_masked:
250 * @dir: a #DesktopFileDir
251 * @app_name: an application ID
253 * Checks if @app_name is masked for @dir.
255 * An application is masked if a similarly-named desktop file exists in
256 * a desktop file directory with higher precedence. Masked desktop
257 * files should be ignored.
259 static gboolean
260 desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
261 const gchar *app_name)
263 while (dir > desktop_file_dirs)
265 dir--;
267 if (dir->app_names && g_hash_table_contains (dir->app_names, app_name))
268 return TRUE;
271 return FALSE;
274 static const gchar * const *
275 get_lowercase_current_desktops (void)
277 static gchar **result;
279 if (g_once_init_enter (&result))
281 const gchar *envvar;
282 gchar **tmp;
284 envvar = g_getenv ("XDG_CURRENT_DESKTOP");
286 if (envvar)
288 gint i, j;
290 tmp = g_strsplit (envvar, G_SEARCHPATH_SEPARATOR_S, 0);
292 for (i = 0; tmp[i]; i++)
293 for (j = 0; tmp[i][j]; j++)
294 tmp[i][j] = g_ascii_tolower (tmp[i][j]);
296 else
297 tmp = g_new0 (gchar *, 0 + 1);
299 g_once_init_leave (&result, tmp);
302 return (const gchar **) result;
305 static const gchar * const *
306 get_current_desktops (const gchar *value)
308 static gchar **result;
310 if (g_once_init_enter (&result))
312 gchar **tmp;
314 if (!value)
315 value = g_getenv ("XDG_CURRENT_DESKTOP");
317 if (!value)
318 value = "";
320 tmp = g_strsplit (value, ":", 0);
322 g_once_init_leave (&result, tmp);
325 return (const gchar **) result;
328 /*< internal >
329 * add_to_table_if_appropriate:
330 * @apps: a string to GDesktopAppInfo hash table
331 * @app_name: the name of the application
332 * @info: a #GDesktopAppInfo, or NULL
334 * If @info is non-%NULL and non-hidden, then add it to @apps, using
335 * @app_name as a key.
337 * If @info is non-%NULL then this function will consume the passed-in
338 * reference.
340 static void
341 add_to_table_if_appropriate (GHashTable *apps,
342 const gchar *app_name,
343 GDesktopAppInfo *info)
345 if (!info)
346 return;
348 if (info->hidden)
350 g_object_unref (info);
351 return;
354 g_free (info->desktop_id);
355 info->desktop_id = g_strdup (app_name);
357 g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
360 enum
362 DESKTOP_KEY_Comment,
363 DESKTOP_KEY_Exec,
364 DESKTOP_KEY_GenericName,
365 DESKTOP_KEY_Keywords,
366 DESKTOP_KEY_Name,
367 DESKTOP_KEY_X_GNOME_FullName,
369 N_DESKTOP_KEYS
372 const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
373 /* Note: lower numbers are a better match.
375 * In case we want two keys to match at the same level, we can just
376 * use the same number for the two different keys.
378 [DESKTOP_KEY_Name] = 1,
379 [DESKTOP_KEY_Exec] = 2,
380 [DESKTOP_KEY_Keywords] = 3,
381 [DESKTOP_KEY_GenericName] = 4,
382 [DESKTOP_KEY_X_GNOME_FullName] = 5,
383 [DESKTOP_KEY_Comment] = 6
386 static gchar *
387 desktop_key_get_name (guint key_id)
389 switch (key_id)
391 case DESKTOP_KEY_Comment:
392 return "Comment";
393 case DESKTOP_KEY_Exec:
394 return "Exec";
395 case DESKTOP_KEY_GenericName:
396 return GENERIC_NAME_KEY;
397 case DESKTOP_KEY_Keywords:
398 return KEYWORDS_KEY;
399 case DESKTOP_KEY_Name:
400 return "Name";
401 case DESKTOP_KEY_X_GNOME_FullName:
402 return FULL_NAME_KEY;
403 default:
404 g_assert_not_reached ();
408 /* Search global state {{{2
410 * We only ever search under a global lock, so we can use (and reuse)
411 * some global data to reduce allocations made while searching.
413 * In short, we keep around arrays of results that we expand as needed
414 * (and never shrink).
416 * static_token_results: this is where we append the results for each
417 * token within a given desktop directory, as we handle it (which is
418 * a union of all matches for this term)
420 * static_search_results: this is where we build the complete results
421 * for a single directory (which is an intersection of the matches
422 * found for each term)
424 * static_total_results: this is where we build the complete results
425 * across all directories (which is a union of the matches found in
426 * each directory)
428 * The app_names that enter these tables are always pointer-unique (in
429 * the sense that string equality is the same as pointer equality).
430 * This can be guaranteed for two reasons:
432 * - we mask appids so that a given appid will only ever appear within
433 * the highest-precedence directory that contains it. We never
434 * return search results from a lower-level directory if a desktop
435 * file exists in a higher-level one.
437 * - within a given directory, the string is unique because it's the
438 * key in the hashtable of all app_ids for that directory.
440 * We perform a merging of the results in merge_token_results(). This
441 * works by ordering the two lists and moving through each of them (at
442 * the same time) looking for common elements, rejecting uncommon ones.
443 * "Order" here need not mean any particular thing, as long as it is
444 * some order. Because of the uniqueness of our strings, we can use
445 * pointer order. That's what's going on in compare_results() below.
447 struct search_result
449 const gchar *app_name;
450 gint category;
453 static struct search_result *static_token_results;
454 static gint static_token_results_size;
455 static gint static_token_results_allocated;
456 static struct search_result *static_search_results;
457 static gint static_search_results_size;
458 static gint static_search_results_allocated;
459 static struct search_result *static_total_results;
460 static gint static_total_results_size;
461 static gint static_total_results_allocated;
463 /* And some functions for performing nice operations against it */
464 static gint
465 compare_results (gconstpointer a,
466 gconstpointer b)
468 const struct search_result *ra = a;
469 const struct search_result *rb = b;
471 if (ra->app_name < rb->app_name)
472 return -1;
474 else if (ra->app_name > rb->app_name)
475 return 1;
477 else
478 return ra->category - rb->category;
481 static gint
482 compare_categories (gconstpointer a,
483 gconstpointer b)
485 const struct search_result *ra = a;
486 const struct search_result *rb = b;
488 return ra->category - rb->category;
491 static void
492 add_token_result (const gchar *app_name,
493 guint16 category)
495 if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
497 static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
498 static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
501 static_token_results[static_token_results_size].app_name = app_name;
502 static_token_results[static_token_results_size].category = category;
503 static_token_results_size++;
506 static void
507 merge_token_results (gboolean first)
509 if (static_token_results_size != 0)
510 qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
512 /* If this is the first token then we are basically merging a list with
513 * itself -- we only perform de-duplication.
515 * If this is not the first token then we are doing a real merge.
517 if (first)
519 const gchar *last_name = NULL;
520 gint i;
522 /* We must de-duplicate, but we do so by taking the best category
523 * in each case.
525 * The final list can be as large as the input here, so make sure
526 * we have enough room (even if it's too much room).
529 if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
531 static_search_results_allocated = static_token_results_allocated;
532 static_search_results = g_renew (struct search_result,
533 static_search_results,
534 static_search_results_allocated);
537 for (i = 0; i < static_token_results_size; i++)
539 /* The list is sorted so that the best match for a given id
540 * will be at the front, so once we have copied an id, skip
541 * the rest of the entries for the same id.
543 if (static_token_results[i].app_name == last_name)
544 continue;
546 last_name = static_token_results[i].app_name;
548 static_search_results[static_search_results_size++] = static_token_results[i];
551 else
553 const gchar *last_name = NULL;
554 gint i, j = 0;
555 gint k = 0;
557 /* We only ever remove items from the results list, so no need to
558 * resize to ensure that we have enough room.
560 for (i = 0; i < static_token_results_size; i++)
562 if (static_token_results[i].app_name == last_name)
563 continue;
565 last_name = static_token_results[i].app_name;
567 /* Now we only want to have a result in static_search_results
568 * if we already have it there *and* we have it in
569 * static_token_results as well. The category will be the
570 * lesser of the two.
572 * Skip past the results in static_search_results that are not
573 * going to be matches.
575 while (k < static_search_results_size &&
576 static_search_results[k].app_name < static_token_results[i].app_name)
577 k++;
579 if (k < static_search_results_size &&
580 static_search_results[k].app_name == static_token_results[i].app_name)
582 /* We have a match.
584 * Category should be the worse of the two (ie:
585 * numerically larger).
587 static_search_results[j].app_name = static_search_results[k].app_name;
588 static_search_results[j].category = MAX (static_search_results[k].category,
589 static_token_results[i].category);
590 j++;
594 static_search_results_size = j;
597 /* Clear it out for next time... */
598 static_token_results_size = 0;
601 static void
602 reset_total_search_results (void)
604 static_total_results_size = 0;
607 static void
608 sort_total_search_results (void)
610 if (static_total_results_size != 0)
611 qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
614 static void
615 merge_directory_results (void)
617 if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
619 static_total_results_allocated = MAX (16, static_total_results_allocated);
620 while (static_total_results_allocated < static_total_results_size + static_search_results_size)
621 static_total_results_allocated *= 2;
622 static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
625 if (static_total_results + static_total_results_size != 0)
626 memcpy (static_total_results + static_total_results_size,
627 static_search_results,
628 static_search_results_size * sizeof (struct search_result));
630 static_total_results_size += static_search_results_size;
632 /* Clear it out for next time... */
633 static_search_results_size = 0;
636 /* Support for unindexed DesktopFileDirs {{{2 */
637 static void
638 get_apps_from_dir (GHashTable **apps,
639 const char *dirname,
640 const char *prefix)
642 const char *basename;
643 GDir *dir;
645 dir = g_dir_open (dirname, 0, NULL);
647 if (dir == NULL)
648 return;
650 while ((basename = g_dir_read_name (dir)) != NULL)
652 gchar *filename;
654 filename = g_build_filename (dirname, basename, NULL);
656 if (g_str_has_suffix (basename, ".desktop"))
658 gchar *app_name;
660 app_name = g_strconcat (prefix, basename, NULL);
662 if (*apps == NULL)
663 *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
665 g_hash_table_insert (*apps, app_name, g_strdup (filename));
667 else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
669 gchar *subprefix;
671 subprefix = g_strconcat (prefix, basename, "-", NULL);
672 get_apps_from_dir (apps, filename, subprefix);
673 g_free (subprefix);
676 g_free (filename);
679 g_dir_close (dir);
682 typedef struct
684 gchar **additions;
685 gchar **removals;
686 gchar **defaults;
687 } UnindexedMimeTweaks;
689 static void
690 free_mime_tweaks (gpointer data)
692 UnindexedMimeTweaks *tweaks = data;
694 g_strfreev (tweaks->additions);
695 g_strfreev (tweaks->removals);
696 g_strfreev (tweaks->defaults);
698 g_slice_free (UnindexedMimeTweaks, tweaks);
701 static UnindexedMimeTweaks *
702 desktop_file_dir_unindexed_get_tweaks (DesktopFileDir *dir,
703 const gchar *mime_type)
705 UnindexedMimeTweaks *tweaks;
706 gchar *unaliased_type;
708 unaliased_type = _g_unix_content_type_unalias (mime_type);
709 tweaks = g_hash_table_lookup (dir->mime_tweaks, unaliased_type);
711 if (tweaks == NULL)
713 tweaks = g_slice_new0 (UnindexedMimeTweaks);
714 g_hash_table_insert (dir->mime_tweaks, unaliased_type, tweaks);
716 else
717 g_free (unaliased_type);
719 return tweaks;
722 /* consumes 'to_add' */
723 static void
724 expand_strv (gchar ***strv_ptr,
725 gchar **to_add,
726 gchar * const *blacklist)
728 guint strv_len, add_len;
729 gchar **strv;
730 guint i, j;
732 if (!*strv_ptr)
734 *strv_ptr = to_add;
735 return;
738 strv = *strv_ptr;
739 strv_len = g_strv_length (strv);
740 add_len = g_strv_length (to_add);
741 strv = g_renew (gchar *, strv, strv_len + add_len + 1);
743 for (i = 0; to_add[i]; i++)
745 /* Don't add blacklisted strings */
746 if (blacklist)
747 for (j = 0; blacklist[j]; j++)
748 if (g_str_equal (to_add[i], blacklist[j]))
749 goto no_add;
751 /* Don't add duplicates already in the list */
752 for (j = 0; j < strv_len; j++)
753 if (g_str_equal (to_add[i], strv[j]))
754 goto no_add;
756 strv[strv_len++] = to_add[i];
757 continue;
759 no_add:
760 g_free (to_add[i]);
763 strv[strv_len] = NULL;
764 *strv_ptr = strv;
766 g_free (to_add);
769 static void
770 desktop_file_dir_unindexed_read_mimeapps_list (DesktopFileDir *dir,
771 const gchar *filename,
772 const gchar *added_group,
773 gboolean tweaks_permitted)
775 UnindexedMimeTweaks *tweaks;
776 char **desktop_file_ids;
777 GKeyFile *key_file;
778 gchar **mime_types;
779 int i;
781 key_file = g_key_file_new ();
782 if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL))
784 g_key_file_free (key_file);
785 return;
788 mime_types = g_key_file_get_keys (key_file, added_group, NULL, NULL);
790 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
792 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
793 "mimeapps.list file may add or remove associations.", filename, added_group);
794 g_strfreev (mime_types);
795 mime_types = NULL;
798 if (mime_types != NULL)
800 for (i = 0; mime_types[i] != NULL; i++)
802 desktop_file_ids = g_key_file_get_string_list (key_file, added_group, mime_types[i], NULL, NULL);
804 if (desktop_file_ids)
806 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
807 expand_strv (&tweaks->additions, desktop_file_ids, tweaks->removals);
811 g_strfreev (mime_types);
814 mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
816 if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
818 g_warning ("%s contains a [%s] group, but it is not permitted here. Only the non-desktop-specific "
819 "mimeapps.list file may add or remove associations.", filename, REMOVED_ASSOCIATIONS_GROUP);
820 g_strfreev (mime_types);
821 mime_types = NULL;
824 if (mime_types != NULL)
826 for (i = 0; mime_types[i] != NULL; i++)
828 desktop_file_ids = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP, mime_types[i], NULL, NULL);
830 if (desktop_file_ids)
832 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
833 expand_strv (&tweaks->removals, desktop_file_ids, tweaks->additions);
837 g_strfreev (mime_types);
840 mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
842 if (mime_types != NULL)
844 for (i = 0; mime_types[i] != NULL; i++)
846 desktop_file_ids = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP, mime_types[i], NULL, NULL);
848 if (desktop_file_ids)
850 tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
851 expand_strv (&tweaks->defaults, desktop_file_ids, NULL);
855 g_strfreev (mime_types);
858 g_key_file_free (key_file);
861 static void
862 desktop_file_dir_unindexed_read_mimeapps_lists (DesktopFileDir *dir)
864 const gchar * const *desktops;
865 gchar *filename;
866 gint i;
868 dir->mime_tweaks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_mime_tweaks);
870 /* We process in order of precedence, using a blacklisting approach to
871 * avoid recording later instructions that conflict with ones we found
872 * earlier.
874 * We first start with the XDG_CURRENT_DESKTOP files, in precedence
875 * order.
877 desktops = get_lowercase_current_desktops ();
878 for (i = 0; desktops[i]; i++)
880 filename = g_strdup_printf ("%s/%s-mimeapps.list", dir->path, desktops[i]);
881 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
882 g_free (filename);
885 /* Next, the non-desktop-specific mimeapps.list */
886 filename = g_strdup_printf ("%s/mimeapps.list", dir->path);
887 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, TRUE);
888 g_free (filename);
890 /* The remaining files are only checked for in directories that might
891 * contain desktop files (ie: not the config dirs).
893 if (dir->is_config)
894 return;
896 /* We have 'defaults.list' which was only ever understood by GLib. It
897 * exists widely, but it has never been part of any spec and it should
898 * be treated as deprecated. This will be removed in a future
899 * version.
901 filename = g_strdup_printf ("%s/defaults.list", dir->path);
902 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
903 g_free (filename);
905 /* Finally, the mimeinfo.cache, which is just a cached copy of what we
906 * would find in the MimeTypes= lines of all of the desktop files.
908 filename = g_strdup_printf ("%s/mimeinfo.cache", dir->path);
909 desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, MIME_CACHE_GROUP, TRUE);
910 g_free (filename);
913 static void
914 desktop_file_dir_unindexed_init (DesktopFileDir *dir)
916 if (!dir->is_config)
917 get_apps_from_dir (&dir->app_names, dir->path, "");
919 desktop_file_dir_unindexed_read_mimeapps_lists (dir);
922 static GDesktopAppInfo *
923 desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
924 const gchar *desktop_id)
926 const gchar *filename;
928 filename = g_hash_table_lookup (dir->app_names, desktop_id);
930 if (!filename)
931 return NULL;
933 return g_desktop_app_info_new_from_filename (filename);
936 static void
937 desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
938 GHashTable *apps)
940 GHashTableIter iter;
941 gpointer app_name;
942 gpointer filename;
944 if (dir->app_names == NULL)
945 return;
947 g_hash_table_iter_init (&iter, dir->app_names);
948 while (g_hash_table_iter_next (&iter, &app_name, &filename))
950 if (desktop_file_dir_app_name_is_masked (dir, app_name))
951 continue;
953 add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename (filename));
957 typedef struct _MemoryIndexEntry MemoryIndexEntry;
958 typedef GHashTable MemoryIndex;
960 struct _MemoryIndexEntry
962 const gchar *app_name; /* pointer to the hashtable key */
963 gint match_category;
964 MemoryIndexEntry *next;
967 static void
968 memory_index_entry_free (gpointer data)
970 MemoryIndexEntry *mie = data;
972 while (mie)
974 MemoryIndexEntry *next = mie->next;
976 g_slice_free (MemoryIndexEntry, mie);
977 mie = next;
981 static void
982 memory_index_add_token (MemoryIndex *mi,
983 const gchar *token,
984 gint match_category,
985 const gchar *app_name)
987 MemoryIndexEntry *mie, *first;
989 mie = g_slice_new (MemoryIndexEntry);
990 mie->app_name = app_name;
991 mie->match_category = match_category;
993 first = g_hash_table_lookup (mi, token);
995 if (first)
997 mie->next = first->next;
998 first->next = mie;
1000 else
1002 mie->next = NULL;
1003 g_hash_table_insert (mi, g_strdup (token), mie);
1007 static void
1008 memory_index_add_string (MemoryIndex *mi,
1009 const gchar *string,
1010 gint match_category,
1011 const gchar *app_name)
1013 gchar **tokens, **alternates;
1014 gint i;
1016 tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
1018 for (i = 0; tokens[i]; i++)
1019 memory_index_add_token (mi, tokens[i], match_category, app_name);
1021 for (i = 0; alternates[i]; i++)
1022 memory_index_add_token (mi, alternates[i], match_category, app_name);
1024 g_strfreev (alternates);
1025 g_strfreev (tokens);
1028 static MemoryIndex *
1029 memory_index_new (void)
1031 return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
1034 static void
1035 desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
1037 GHashTableIter iter;
1038 gpointer app, path;
1040 dir->memory_index = memory_index_new ();
1041 dir->memory_implementations = memory_index_new ();
1043 /* Nothing to search? */
1044 if (dir->app_names == NULL)
1045 return;
1047 g_hash_table_iter_init (&iter, dir->app_names);
1048 while (g_hash_table_iter_next (&iter, &app, &path))
1050 GKeyFile *key_file;
1052 if (desktop_file_dir_app_name_is_masked (dir, app))
1053 continue;
1055 key_file = g_key_file_new ();
1057 if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
1058 !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
1060 /* Index the interesting keys... */
1061 gchar **implements;
1062 gint i;
1064 for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
1066 const gchar *value;
1067 gchar *raw;
1069 if (!desktop_key_match_category[i])
1070 continue;
1072 raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
1073 value = raw;
1075 if (i == DESKTOP_KEY_Exec && raw != NULL)
1077 /* Special handling: only match basename of first field */
1078 gchar *space;
1079 gchar *slash;
1081 /* Remove extra arguments, if any */
1082 space = raw + strcspn (raw, " \t\n"); /* IFS */
1083 *space = '\0';
1085 /* Skip the pathname, if any */
1086 if ((slash = strrchr (raw, '/')))
1087 value = slash + 1;
1090 if (value)
1091 memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
1093 g_free (raw);
1096 /* Make note of the Implements= line */
1097 implements = g_key_file_get_string_list (key_file, "Desktop Entry", "Implements", NULL, NULL);
1098 for (i = 0; implements && implements[i]; i++)
1099 memory_index_add_token (dir->memory_implementations, implements[i], 0, app);
1100 g_strfreev (implements);
1103 g_key_file_free (key_file);
1107 static void
1108 desktop_file_dir_unindexed_search (DesktopFileDir *dir,
1109 const gchar *search_token)
1111 GHashTableIter iter;
1112 gpointer key, value;
1114 if (!dir->memory_index)
1115 desktop_file_dir_unindexed_setup_search (dir);
1117 g_hash_table_iter_init (&iter, dir->memory_index);
1118 while (g_hash_table_iter_next (&iter, &key, &value))
1120 MemoryIndexEntry *mie = value;
1122 if (!g_str_has_prefix (key, search_token))
1123 continue;
1125 while (mie)
1127 add_token_result (mie->app_name, mie->match_category);
1128 mie = mie->next;
1133 static gboolean
1134 array_contains (GPtrArray *array,
1135 const gchar *str)
1137 gint i;
1139 for (i = 0; i < array->len; i++)
1140 if (g_str_equal (array->pdata[i], str))
1141 return TRUE;
1143 return FALSE;
1146 static void
1147 desktop_file_dir_unindexed_mime_lookup (DesktopFileDir *dir,
1148 const gchar *mime_type,
1149 GPtrArray *hits,
1150 GPtrArray *blacklist)
1152 UnindexedMimeTweaks *tweaks;
1153 gint i;
1155 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1157 if (!tweaks)
1158 return;
1160 if (tweaks->additions)
1162 for (i = 0; tweaks->additions[i]; i++)
1164 gchar *app_name = tweaks->additions[i];
1166 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1167 !array_contains (blacklist, app_name) && !array_contains (hits, app_name))
1168 g_ptr_array_add (hits, app_name);
1172 if (tweaks->removals)
1174 for (i = 0; tweaks->removals[i]; i++)
1176 gchar *app_name = tweaks->removals[i];
1178 if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1179 !array_contains (blacklist, app_name) && !array_contains (hits, app_name))
1180 g_ptr_array_add (blacklist, app_name);
1185 static void
1186 desktop_file_dir_unindexed_default_lookup (DesktopFileDir *dir,
1187 const gchar *mime_type,
1188 GPtrArray *results)
1190 UnindexedMimeTweaks *tweaks;
1191 gint i;
1193 tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1195 if (!tweaks || !tweaks->defaults)
1196 return;
1198 for (i = 0; tweaks->defaults[i]; i++)
1200 gchar *app_name = tweaks->defaults[i];
1202 if (!array_contains (results, app_name))
1203 g_ptr_array_add (results, app_name);
1207 static void
1208 desktop_file_dir_unindexed_get_implementations (DesktopFileDir *dir,
1209 GList **results,
1210 const gchar *interface)
1212 MemoryIndexEntry *mie;
1214 if (!dir->memory_index)
1215 desktop_file_dir_unindexed_setup_search (dir);
1217 for (mie = g_hash_table_lookup (dir->memory_implementations, interface); mie; mie = mie->next)
1218 *results = g_list_prepend (*results, g_strdup (mie->app_name));
1221 /* DesktopFileDir "API" {{{2 */
1223 /*< internal >
1224 * desktop_file_dir_create:
1225 * @array: the #GArray to add a new item to
1226 * @data_dir: an XDG_DATA_DIR
1228 * Creates a #DesktopFileDir for the corresponding @data_dir, adding it
1229 * to @array.
1231 static void
1232 desktop_file_dir_create (GArray *array,
1233 const gchar *data_dir)
1235 DesktopFileDir dir = { 0, };
1237 dir.path = g_build_filename (data_dir, "applications", NULL);
1239 g_array_append_val (array, dir);
1242 /*< internal >
1243 * desktop_file_dir_create:
1244 * @array: the #GArray to add a new item to
1245 * @config_dir: an XDG_CONFIG_DIR
1247 * Just the same as desktop_file_dir_create() except that it does not
1248 * add the "applications" directory. It also marks the directory as
1249 * config-only, which prevents us from attempting to find desktop files
1250 * here.
1252 static void
1253 desktop_file_dir_create_for_config (GArray *array,
1254 const gchar *config_dir)
1256 DesktopFileDir dir = { 0, };
1258 dir.path = g_strdup (config_dir);
1259 dir.is_config = TRUE;
1261 g_array_append_val (array, dir);
1264 /*< internal >
1265 * desktop_file_dir_reset:
1266 * @dir: a #DesktopFileDir
1268 * Cleans up @dir, releasing most resources that it was using.
1270 static void
1271 desktop_file_dir_reset (DesktopFileDir *dir)
1273 if (dir->alternatively_watching)
1275 g_free (dir->alternatively_watching);
1276 dir->alternatively_watching = NULL;
1279 if (dir->monitor)
1281 g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
1282 g_object_unref (dir->monitor);
1283 dir->monitor = NULL;
1286 if (dir->app_names)
1288 g_hash_table_unref (dir->app_names);
1289 dir->app_names = NULL;
1292 if (dir->memory_index)
1294 g_hash_table_unref (dir->memory_index);
1295 dir->memory_index = NULL;
1298 if (dir->mime_tweaks)
1300 g_hash_table_unref (dir->mime_tweaks);
1301 dir->mime_tweaks = NULL;
1304 if (dir->memory_implementations)
1306 g_hash_table_unref (dir->memory_implementations);
1307 dir->memory_implementations = NULL;
1310 dir->is_setup = FALSE;
1313 /*< internal >
1314 * desktop_file_dir_init:
1315 * @dir: a #DesktopFileDir
1317 * Does initial setup for @dir
1319 * You should only call this if @dir is not already setup.
1321 static void
1322 desktop_file_dir_init (DesktopFileDir *dir)
1324 const gchar *watch_dir;
1326 g_assert (!dir->is_setup);
1328 g_assert (!dir->alternatively_watching);
1329 g_assert (!dir->monitor);
1331 dir->alternatively_watching = desktop_file_dir_get_alternative_dir (dir);
1332 watch_dir = dir->alternatively_watching ? dir->alternatively_watching : dir->path;
1334 /* There is a very thin race here if the watch_dir has been _removed_
1335 * between when we checked for it and when we establish the watch.
1336 * Removes probably don't happen in usual operation, and even if it
1337 * does (and we catch the unlikely race), the only degradation is that
1338 * we will fall back to polling.
1340 dir->monitor = g_local_file_monitor_new_in_worker (watch_dir, TRUE, G_FILE_MONITOR_NONE,
1341 desktop_file_dir_changed, dir, NULL);
1343 desktop_file_dir_unindexed_init (dir);
1345 dir->is_setup = TRUE;
1348 /*< internal >
1349 * desktop_file_dir_get_app:
1350 * @dir: a DesktopFileDir
1351 * @desktop_id: the desktop ID to load
1353 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
1354 * within @dir, even if it is hidden.
1356 * This function does not check if @desktop_id would be masked by a
1357 * directory with higher precedence. The caller must do so.
1359 static GDesktopAppInfo *
1360 desktop_file_dir_get_app (DesktopFileDir *dir,
1361 const gchar *desktop_id)
1363 if (!dir->app_names)
1364 return NULL;
1366 return desktop_file_dir_unindexed_get_app (dir, desktop_id);
1369 /*< internal >
1370 * desktop_file_dir_get_all:
1371 * @dir: a DesktopFileDir
1372 * @apps: a #GHashTable<string, GDesktopAppInfo>
1374 * Loads all desktop files in @dir and adds them to @apps, careful to
1375 * ensure we don't add any files masked by a similarly-named file in a
1376 * higher-precedence directory.
1378 static void
1379 desktop_file_dir_get_all (DesktopFileDir *dir,
1380 GHashTable *apps)
1382 desktop_file_dir_unindexed_get_all (dir, apps);
1385 /*< internal >
1386 * desktop_file_dir_mime_lookup:
1387 * @dir: a #DesktopFileDir
1388 * @mime_type: the mime type to look up
1389 * @hits: the array to store the hits
1390 * @blacklist: the array to store the blacklist
1392 * Does a lookup of a mimetype against one desktop file directory,
1393 * recording any hits and blacklisting and "Removed" associations (so
1394 * later directories don't record them as hits).
1396 * The items added to @hits are duplicated, but the ones in @blacklist
1397 * are weak pointers. This facilitates simply freeing the blacklist
1398 * (which is only used for internal bookkeeping) but using the pdata of
1399 * @hits as the result of the operation.
1401 static void
1402 desktop_file_dir_mime_lookup (DesktopFileDir *dir,
1403 const gchar *mime_type,
1404 GPtrArray *hits,
1405 GPtrArray *blacklist)
1407 desktop_file_dir_unindexed_mime_lookup (dir, mime_type, hits, blacklist);
1410 /*< internal >
1411 * desktop_file_dir_default_lookup:
1412 * @dir: a #DesktopFileDir
1413 * @mime_type: the mime type to look up
1414 * @results: an array to store the results in
1416 * Collects the "default" applications for a given mime type from @dir.
1418 static void
1419 desktop_file_dir_default_lookup (DesktopFileDir *dir,
1420 const gchar *mime_type,
1421 GPtrArray *results)
1423 desktop_file_dir_unindexed_default_lookup (dir, mime_type, results);
1426 /*< internal >
1427 * desktop_file_dir_search:
1428 * @dir: a #DesktopFileDir
1429 * @term: a normalised and casefolded search term
1431 * Finds the names of applications in @dir that match @term.
1433 static void
1434 desktop_file_dir_search (DesktopFileDir *dir,
1435 const gchar *search_token)
1437 desktop_file_dir_unindexed_search (dir, search_token);
1440 static void
1441 desktop_file_dir_get_implementations (DesktopFileDir *dir,
1442 GList **results,
1443 const gchar *interface)
1445 desktop_file_dir_unindexed_get_implementations (dir, results, interface);
1448 /* Lock/unlock and global setup API {{{2 */
1450 static void
1451 desktop_file_dirs_lock (void)
1453 gint i;
1455 g_mutex_lock (&desktop_file_dir_lock);
1457 if (desktop_file_dirs == NULL)
1459 const char * const *dirs;
1460 GArray *tmp;
1461 gint i;
1463 tmp = g_array_new (FALSE, FALSE, sizeof (DesktopFileDir));
1465 /* First, the configs. Highest priority: the user's ~/.config */
1466 desktop_file_dir_create_for_config (tmp, g_get_user_config_dir ());
1468 /* Next, the system configs (/etc/xdg, and so on). */
1469 dirs = g_get_system_config_dirs ();
1470 for (i = 0; dirs[i]; i++)
1471 desktop_file_dir_create_for_config (tmp, dirs[i]);
1473 /* Now the data. Highest priority: the user's ~/.local/share/applications */
1474 desktop_file_dir_user_data_index = tmp->len;
1475 desktop_file_dir_create (tmp, g_get_user_data_dir ());
1477 /* Following that, XDG_DATA_DIRS/applications, in order */
1478 dirs = g_get_system_data_dirs ();
1479 for (i = 0; dirs[i]; i++)
1480 desktop_file_dir_create (tmp, dirs[i]);
1482 /* The list of directories will never change after this. */
1483 desktop_file_dirs = (DesktopFileDir *) tmp->data;
1484 n_desktop_file_dirs = tmp->len;
1486 g_array_free (tmp, FALSE);
1489 for (i = 0; i < n_desktop_file_dirs; i++)
1490 if (!desktop_file_dirs[i].is_setup)
1491 desktop_file_dir_init (&desktop_file_dirs[i]);
1494 static void
1495 desktop_file_dirs_unlock (void)
1497 g_mutex_unlock (&desktop_file_dir_lock);
1500 static void
1501 desktop_file_dirs_invalidate_user_config (void)
1503 g_mutex_lock (&desktop_file_dir_lock);
1505 if (n_desktop_file_dirs)
1506 desktop_file_dir_reset (&desktop_file_dirs[desktop_file_dir_user_config_index]);
1508 g_mutex_unlock (&desktop_file_dir_lock);
1511 static void
1512 desktop_file_dirs_invalidate_user_data (void)
1514 g_mutex_lock (&desktop_file_dir_lock);
1516 if (n_desktop_file_dirs)
1517 desktop_file_dir_reset (&desktop_file_dirs[desktop_file_dir_user_data_index]);
1519 g_mutex_unlock (&desktop_file_dir_lock);
1522 /* GDesktopAppInfo implementation {{{1 */
1523 /* GObject implementation {{{2 */
1524 static void
1525 g_desktop_app_info_finalize (GObject *object)
1527 GDesktopAppInfo *info;
1529 info = G_DESKTOP_APP_INFO (object);
1531 g_free (info->desktop_id);
1532 g_free (info->filename);
1534 if (info->keyfile)
1535 g_key_file_unref (info->keyfile);
1537 g_free (info->name);
1538 g_free (info->generic_name);
1539 g_free (info->fullname);
1540 g_free (info->comment);
1541 g_free (info->icon_name);
1542 if (info->icon)
1543 g_object_unref (info->icon);
1544 g_strfreev (info->keywords);
1545 g_strfreev (info->only_show_in);
1546 g_strfreev (info->not_show_in);
1547 g_free (info->try_exec);
1548 g_free (info->exec);
1549 g_free (info->binary);
1550 g_free (info->path);
1551 g_free (info->categories);
1552 g_free (info->startup_wm_class);
1553 g_strfreev (info->mime_types);
1554 g_free (info->app_id);
1555 g_strfreev (info->actions);
1557 G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1560 static void
1561 g_desktop_app_info_set_property (GObject *object,
1562 guint prop_id,
1563 const GValue *value,
1564 GParamSpec *pspec)
1566 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1568 switch (prop_id)
1570 case PROP_FILENAME:
1571 self->filename = g_value_dup_string (value);
1572 break;
1574 default:
1575 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1576 break;
1580 static void
1581 g_desktop_app_info_get_property (GObject *object,
1582 guint prop_id,
1583 GValue *value,
1584 GParamSpec *pspec)
1586 GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1588 switch (prop_id)
1590 case PROP_FILENAME:
1591 g_value_set_string (value, self->filename);
1592 break;
1593 default:
1594 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1595 break;
1599 static void
1600 g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1602 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1604 gobject_class->get_property = g_desktop_app_info_get_property;
1605 gobject_class->set_property = g_desktop_app_info_set_property;
1606 gobject_class->finalize = g_desktop_app_info_finalize;
1609 * GDesktopAppInfo:filename:
1611 * The origin filename of this #GDesktopAppInfo
1613 g_object_class_install_property (gobject_class,
1614 PROP_FILENAME,
1615 g_param_spec_string ("filename", "Filename", "", NULL,
1616 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1619 static void
1620 g_desktop_app_info_init (GDesktopAppInfo *local)
1624 /* Construction... {{{2 */
1626 /*< internal >
1627 * binary_from_exec:
1628 * @exec: an exec line
1630 * Returns the first word in an exec line (ie: the binary name).
1632 * If @exec is " progname --foo %F" then returns "progname".
1634 static char *
1635 binary_from_exec (const char *exec)
1637 const char *p, *start;
1639 p = exec;
1640 while (*p == ' ')
1641 p++;
1642 start = p;
1643 while (*p != ' ' && *p != 0)
1644 p++;
1646 return g_strndup (start, p - start);
1649 static gboolean
1650 g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1651 GKeyFile *key_file)
1653 char *start_group;
1654 char *type;
1655 char *try_exec;
1656 char *exec;
1657 gboolean bus_activatable;
1659 start_group = g_key_file_get_start_group (key_file);
1660 if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1662 g_free (start_group);
1663 return FALSE;
1665 g_free (start_group);
1667 type = g_key_file_get_string (key_file,
1668 G_KEY_FILE_DESKTOP_GROUP,
1669 G_KEY_FILE_DESKTOP_KEY_TYPE,
1670 NULL);
1671 if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1673 g_free (type);
1674 return FALSE;
1676 g_free (type);
1678 try_exec = g_key_file_get_string (key_file,
1679 G_KEY_FILE_DESKTOP_GROUP,
1680 G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1681 NULL);
1682 if (try_exec && try_exec[0] != '\0')
1684 char *t;
1685 t = g_find_program_in_path (try_exec);
1686 if (t == NULL)
1688 g_free (try_exec);
1689 return FALSE;
1691 g_free (t);
1694 exec = g_key_file_get_string (key_file,
1695 G_KEY_FILE_DESKTOP_GROUP,
1696 G_KEY_FILE_DESKTOP_KEY_EXEC,
1697 NULL);
1698 if (exec && exec[0] != '\0')
1700 gint argc;
1701 char **argv;
1702 if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1704 g_free (exec);
1705 g_free (try_exec);
1706 return FALSE;
1708 else
1710 char *t;
1711 t = g_find_program_in_path (argv[0]);
1712 g_strfreev (argv);
1714 if (t == NULL)
1716 g_free (exec);
1717 g_free (try_exec);
1718 return FALSE;
1720 g_free (t);
1724 info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
1725 info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
1726 info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
1727 info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
1728 info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
1729 info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
1730 info->icon_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
1731 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);
1732 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);
1733 info->try_exec = try_exec;
1734 info->exec = exec;
1735 info->path = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_PATH, NULL);
1736 info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
1737 info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
1738 info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
1739 info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
1740 info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
1741 info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
1742 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);
1743 bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
1744 info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
1746 /* Remove the special-case: no Actions= key just means 0 extra actions */
1747 if (info->actions == NULL)
1748 info->actions = g_new0 (gchar *, 0 + 1);
1750 info->icon = NULL;
1751 if (info->icon_name)
1753 if (g_path_is_absolute (info->icon_name))
1755 GFile *file;
1757 file = g_file_new_for_path (info->icon_name);
1758 info->icon = g_file_icon_new (file);
1759 g_object_unref (file);
1761 else
1763 char *p;
1765 /* Work around a common mistake in desktop files */
1766 if ((p = strrchr (info->icon_name, '.')) != NULL &&
1767 (strcmp (p, ".png") == 0 ||
1768 strcmp (p, ".xpm") == 0 ||
1769 strcmp (p, ".svg") == 0))
1770 *p = 0;
1772 info->icon = g_themed_icon_new (info->icon_name);
1776 if (info->exec)
1777 info->binary = binary_from_exec (info->exec);
1779 if (info->path && info->path[0] == '\0')
1781 g_free (info->path);
1782 info->path = NULL;
1785 /* Can only be DBusActivatable if we know the filename, which means
1786 * that this won't work for the load-from-keyfile case.
1788 if (bus_activatable && info->filename)
1790 gchar *basename;
1791 gchar *last_dot;
1793 basename = g_path_get_basename (info->filename);
1794 last_dot = strrchr (basename, '.');
1796 if (last_dot && g_str_equal (last_dot, ".desktop"))
1798 *last_dot = '\0';
1800 if (g_dbus_is_name (basename) && basename[0] != ':')
1801 info->app_id = g_strdup (basename);
1804 g_free (basename);
1807 info->keyfile = g_key_file_ref (key_file);
1809 return TRUE;
1812 static gboolean
1813 g_desktop_app_info_load_file (GDesktopAppInfo *self)
1815 GKeyFile *key_file;
1816 gboolean retval = FALSE;
1818 g_return_val_if_fail (self->filename != NULL, FALSE);
1820 self->desktop_id = g_path_get_basename (self->filename);
1822 key_file = g_key_file_new ();
1824 if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
1825 retval = g_desktop_app_info_load_from_keyfile (self, key_file);
1827 g_key_file_unref (key_file);
1828 return retval;
1832 * g_desktop_app_info_new_from_keyfile:
1833 * @key_file: an opened #GKeyFile
1835 * Creates a new #GDesktopAppInfo.
1837 * Returns: a new #GDesktopAppInfo or %NULL on error.
1839 * Since: 2.18
1841 GDesktopAppInfo *
1842 g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
1844 GDesktopAppInfo *info;
1846 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1847 info->filename = NULL;
1848 if (!g_desktop_app_info_load_from_keyfile (info, key_file))
1850 g_object_unref (info);
1851 return NULL;
1853 return info;
1857 * g_desktop_app_info_new_from_filename:
1858 * @filename: (type filename): the path of a desktop file, in the GLib
1859 * filename encoding
1861 * Creates a new #GDesktopAppInfo.
1863 * Returns: a new #GDesktopAppInfo or %NULL on error.
1865 GDesktopAppInfo *
1866 g_desktop_app_info_new_from_filename (const char *filename)
1868 GDesktopAppInfo *info = NULL;
1870 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1871 if (!g_desktop_app_info_load_file (info))
1873 g_object_unref (info);
1874 return NULL;
1876 return info;
1880 * g_desktop_app_info_new:
1881 * @desktop_id: the desktop file id
1883 * Creates a new #GDesktopAppInfo based on a desktop file id.
1885 * A desktop file id is the basename of the desktop file, including the
1886 * .desktop extension. GIO is looking for a desktop file with this name
1887 * in the `applications` subdirectories of the XDG
1888 * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
1889 * and `XDG_DATA_DIRS` environment variables). GIO also supports the
1890 * prefix-to-subdirectory mapping that is described in the
1891 * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
1892 * (i.e. a desktop id of kde-foo.desktop will match
1893 * `/usr/share/applications/kde/foo.desktop`).
1895 * Returns: a new #GDesktopAppInfo, or %NULL if no desktop file with that id
1897 GDesktopAppInfo *
1898 g_desktop_app_info_new (const char *desktop_id)
1900 GDesktopAppInfo *appinfo = NULL;
1901 guint i;
1903 desktop_file_dirs_lock ();
1905 for (i = 0; i < n_desktop_file_dirs; i++)
1907 appinfo = desktop_file_dir_get_app (&desktop_file_dirs[i], desktop_id);
1909 if (appinfo)
1910 break;
1913 desktop_file_dirs_unlock ();
1915 if (appinfo == NULL)
1916 return NULL;
1918 g_free (appinfo->desktop_id);
1919 appinfo->desktop_id = g_strdup (desktop_id);
1921 if (g_desktop_app_info_get_is_hidden (appinfo))
1923 g_object_unref (appinfo);
1924 appinfo = NULL;
1927 return appinfo;
1930 static GAppInfo *
1931 g_desktop_app_info_dup (GAppInfo *appinfo)
1933 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1934 GDesktopAppInfo *new_info;
1936 new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
1938 new_info->filename = g_strdup (info->filename);
1939 new_info->desktop_id = g_strdup (info->desktop_id);
1941 if (info->keyfile)
1942 new_info->keyfile = g_key_file_ref (info->keyfile);
1944 new_info->name = g_strdup (info->name);
1945 new_info->generic_name = g_strdup (info->generic_name);
1946 new_info->fullname = g_strdup (info->fullname);
1947 new_info->keywords = g_strdupv (info->keywords);
1948 new_info->comment = g_strdup (info->comment);
1949 new_info->nodisplay = info->nodisplay;
1950 new_info->icon_name = g_strdup (info->icon_name);
1951 if (info->icon)
1952 new_info->icon = g_object_ref (info->icon);
1953 new_info->only_show_in = g_strdupv (info->only_show_in);
1954 new_info->not_show_in = g_strdupv (info->not_show_in);
1955 new_info->try_exec = g_strdup (info->try_exec);
1956 new_info->exec = g_strdup (info->exec);
1957 new_info->binary = g_strdup (info->binary);
1958 new_info->path = g_strdup (info->path);
1959 new_info->app_id = g_strdup (info->app_id);
1960 new_info->hidden = info->hidden;
1961 new_info->terminal = info->terminal;
1962 new_info->startup_notify = info->startup_notify;
1964 return G_APP_INFO (new_info);
1967 /* GAppInfo interface implementation functions {{{2 */
1969 static gboolean
1970 g_desktop_app_info_equal (GAppInfo *appinfo1,
1971 GAppInfo *appinfo2)
1973 GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
1974 GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
1976 if (info1->desktop_id == NULL ||
1977 info2->desktop_id == NULL)
1978 return info1 == info2;
1980 return strcmp (info1->desktop_id, info2->desktop_id) == 0;
1983 static const char *
1984 g_desktop_app_info_get_id (GAppInfo *appinfo)
1986 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1988 return info->desktop_id;
1991 static const char *
1992 g_desktop_app_info_get_name (GAppInfo *appinfo)
1994 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
1996 if (info->name == NULL)
1997 return _("Unnamed");
1998 return info->name;
2001 static const char *
2002 g_desktop_app_info_get_display_name (GAppInfo *appinfo)
2004 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2006 if (info->fullname == NULL)
2007 return g_desktop_app_info_get_name (appinfo);
2008 return info->fullname;
2012 * g_desktop_app_info_get_is_hidden:
2013 * @info: a #GDesktopAppInfo.
2015 * A desktop file is hidden if the Hidden key in it is
2016 * set to True.
2018 * Returns: %TRUE if hidden, %FALSE otherwise.
2020 gboolean
2021 g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
2023 return info->hidden;
2027 * g_desktop_app_info_get_filename:
2028 * @info: a #GDesktopAppInfo
2030 * When @info was created from a known filename, return it. In some
2031 * situations such as the #GDesktopAppInfo returned from
2032 * g_desktop_app_info_new_from_keyfile(), this function will return %NULL.
2034 * Returns: (type filename): The full path to the file for @info,
2035 * or %NULL if not known.
2036 * Since: 2.24
2038 const char *
2039 g_desktop_app_info_get_filename (GDesktopAppInfo *info)
2041 return info->filename;
2044 static const char *
2045 g_desktop_app_info_get_description (GAppInfo *appinfo)
2047 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2049 return info->comment;
2052 static const char *
2053 g_desktop_app_info_get_executable (GAppInfo *appinfo)
2055 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2057 return info->binary;
2060 static const char *
2061 g_desktop_app_info_get_commandline (GAppInfo *appinfo)
2063 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2065 return info->exec;
2068 static GIcon *
2069 g_desktop_app_info_get_icon (GAppInfo *appinfo)
2071 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2073 return info->icon;
2077 * g_desktop_app_info_get_categories:
2078 * @info: a #GDesktopAppInfo
2080 * Gets the categories from the desktop file.
2082 * Returns: The unparsed Categories key from the desktop file;
2083 * i.e. no attempt is made to split it by ';' or validate it.
2085 const char *
2086 g_desktop_app_info_get_categories (GDesktopAppInfo *info)
2088 return info->categories;
2092 * g_desktop_app_info_get_keywords:
2093 * @info: a #GDesktopAppInfo
2095 * Gets the keywords from the desktop file.
2097 * Returns: (transfer none): The value of the Keywords key
2099 * Since: 2.32
2101 const char * const *
2102 g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
2104 return (const char * const *)info->keywords;
2108 * g_desktop_app_info_get_generic_name:
2109 * @info: a #GDesktopAppInfo
2111 * Gets the generic name from the destkop file.
2113 * Returns: The value of the GenericName key
2115 const char *
2116 g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
2118 return info->generic_name;
2122 * g_desktop_app_info_get_nodisplay:
2123 * @info: a #GDesktopAppInfo
2125 * Gets the value of the NoDisplay key, which helps determine if the
2126 * application info should be shown in menus. See
2127 * #G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY and g_app_info_should_show().
2129 * Returns: The value of the NoDisplay key
2131 * Since: 2.30
2133 gboolean
2134 g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
2136 return info->nodisplay;
2140 * g_desktop_app_info_get_show_in:
2141 * @info: a #GDesktopAppInfo
2142 * @desktop_env: (nullable): a string specifying a desktop name
2144 * Checks if the application info should be shown in menus that list available
2145 * applications for a specific name of the desktop, based on the
2146 * `OnlyShowIn` and `NotShowIn` keys.
2148 * @desktop_env should typically be given as %NULL, in which case the
2149 * `XDG_CURRENT_DESKTOP` environment variable is consulted. If you want
2150 * to override the default mechanism then you may specify @desktop_env,
2151 * but this is not recommended.
2153 * Note that g_app_info_should_show() for @info will include this check (with
2154 * %NULL for @desktop_env) as well as additional checks.
2156 * Returns: %TRUE if the @info should be shown in @desktop_env according to the
2157 * `OnlyShowIn` and `NotShowIn` keys, %FALSE
2158 * otherwise.
2160 * Since: 2.30
2162 gboolean
2163 g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
2164 const gchar *desktop_env)
2166 const gchar *specified_envs[] = { desktop_env, NULL };
2167 const gchar * const *envs;
2168 gint i;
2170 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
2172 if (desktop_env)
2173 envs = specified_envs;
2174 else
2175 envs = get_current_desktops (NULL);
2177 for (i = 0; envs[i]; i++)
2179 gint j;
2181 if (info->only_show_in)
2182 for (j = 0; info->only_show_in[j]; j++)
2183 if (g_str_equal (info->only_show_in[j], envs[i]))
2184 return TRUE;
2186 if (info->not_show_in)
2187 for (j = 0; info->not_show_in[j]; j++)
2188 if (g_str_equal (info->not_show_in[j], envs[i]))
2189 return FALSE;
2192 return info->only_show_in == NULL;
2195 /* Launching... {{{2 */
2197 static char *
2198 expand_macro_single (char macro, char *uri)
2200 GFile *file;
2201 char *result = NULL;
2202 char *path = NULL;
2203 char *name;
2205 file = g_file_new_for_uri (uri);
2207 switch (macro)
2209 case 'u':
2210 case 'U':
2211 result = g_shell_quote (uri);
2212 break;
2213 case 'f':
2214 case 'F':
2215 path = g_file_get_path (file);
2216 if (path)
2217 result = g_shell_quote (path);
2218 break;
2219 case 'd':
2220 case 'D':
2221 path = g_file_get_path (file);
2222 if (path)
2224 name = g_path_get_dirname (path);
2225 result = g_shell_quote (name);
2226 g_free (name);
2228 break;
2229 case 'n':
2230 case 'N':
2231 path = g_file_get_path (file);
2232 if (path)
2234 name = g_path_get_basename (path);
2235 result = g_shell_quote (name);
2236 g_free (name);
2238 break;
2241 g_object_unref (file);
2242 g_free (path);
2244 return result;
2247 static void
2248 expand_macro (char macro,
2249 GString *exec,
2250 GDesktopAppInfo *info,
2251 GList **uri_list)
2253 GList *uris = *uri_list;
2254 char *expanded;
2255 gboolean force_file_uri;
2256 char force_file_uri_macro;
2257 char *uri;
2259 g_return_if_fail (exec != NULL);
2261 /* On %u and %U, pass POSIX file path pointing to the URI via
2262 * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
2263 * running or the URI doesn't have a POSIX file path via FUSE
2264 * we'll just pass the URI.
2266 force_file_uri_macro = macro;
2267 force_file_uri = FALSE;
2268 if (!info->no_fuse)
2270 switch (macro)
2272 case 'u':
2273 force_file_uri_macro = 'f';
2274 force_file_uri = TRUE;
2275 break;
2276 case 'U':
2277 force_file_uri_macro = 'F';
2278 force_file_uri = TRUE;
2279 break;
2280 default:
2281 break;
2285 switch (macro)
2287 case 'u':
2288 case 'f':
2289 case 'd':
2290 case 'n':
2291 if (uris)
2293 uri = uris->data;
2294 if (!force_file_uri ||
2295 /* Pass URI if it contains an anchor */
2296 strchr (uri, '#') != NULL)
2298 expanded = expand_macro_single (macro, uri);
2300 else
2302 expanded = expand_macro_single (force_file_uri_macro, uri);
2303 if (expanded == NULL)
2304 expanded = expand_macro_single (macro, uri);
2307 if (expanded)
2309 g_string_append (exec, expanded);
2310 g_free (expanded);
2312 uris = uris->next;
2315 break;
2317 case 'U':
2318 case 'F':
2319 case 'D':
2320 case 'N':
2321 while (uris)
2323 uri = uris->data;
2325 if (!force_file_uri ||
2326 /* Pass URI if it contains an anchor */
2327 strchr (uri, '#') != NULL)
2329 expanded = expand_macro_single (macro, uri);
2331 else
2333 expanded = expand_macro_single (force_file_uri_macro, uri);
2334 if (expanded == NULL)
2335 expanded = expand_macro_single (macro, uri);
2338 if (expanded)
2340 g_string_append (exec, expanded);
2341 g_free (expanded);
2344 uris = uris->next;
2346 if (uris != NULL && expanded)
2347 g_string_append_c (exec, ' ');
2350 break;
2352 case 'i':
2353 if (info->icon_name)
2355 g_string_append (exec, "--icon ");
2356 expanded = g_shell_quote (info->icon_name);
2357 g_string_append (exec, expanded);
2358 g_free (expanded);
2360 break;
2362 case 'c':
2363 if (info->name)
2365 expanded = g_shell_quote (info->name);
2366 g_string_append (exec, expanded);
2367 g_free (expanded);
2369 break;
2371 case 'k':
2372 if (info->filename)
2374 expanded = g_shell_quote (info->filename);
2375 g_string_append (exec, expanded);
2376 g_free (expanded);
2378 break;
2380 case 'm': /* deprecated */
2381 break;
2383 case '%':
2384 g_string_append_c (exec, '%');
2385 break;
2388 *uri_list = uris;
2391 static gboolean
2392 expand_application_parameters (GDesktopAppInfo *info,
2393 const gchar *exec_line,
2394 GList **uris,
2395 int *argc,
2396 char ***argv,
2397 GError **error)
2399 GList *uri_list = *uris;
2400 const char *p = exec_line;
2401 GString *expanded_exec;
2402 gboolean res;
2404 if (exec_line == NULL)
2406 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2407 _("Desktop file didn’t specify Exec field"));
2408 return FALSE;
2411 expanded_exec = g_string_new (NULL);
2413 while (*p)
2415 if (p[0] == '%' && p[1] != '\0')
2417 expand_macro (p[1], expanded_exec, info, uris);
2418 p++;
2420 else
2421 g_string_append_c (expanded_exec, *p);
2423 p++;
2426 /* No file substitutions */
2427 if (uri_list == *uris && uri_list != NULL)
2429 /* If there is no macro default to %f. This is also what KDE does */
2430 g_string_append_c (expanded_exec, ' ');
2431 expand_macro ('f', expanded_exec, info, uris);
2434 res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
2435 g_string_free (expanded_exec, TRUE);
2436 return res;
2439 static gboolean
2440 prepend_terminal_to_vector (int *argc,
2441 char ***argv)
2443 #ifndef G_OS_WIN32
2444 char **real_argv;
2445 int real_argc;
2446 int i, j;
2447 char **term_argv = NULL;
2448 int term_argc = 0;
2449 char *check;
2450 char **the_argv;
2452 g_return_val_if_fail (argc != NULL, FALSE);
2453 g_return_val_if_fail (argv != NULL, FALSE);
2455 /* sanity */
2456 if(*argv == NULL)
2457 *argc = 0;
2459 the_argv = *argv;
2461 /* compute size if not given */
2462 if (*argc < 0)
2464 for (i = 0; the_argv[i] != NULL; i++)
2466 *argc = i;
2469 term_argc = 2;
2470 term_argv = g_new0 (char *, 3);
2472 check = g_find_program_in_path ("gnome-terminal");
2473 if (check != NULL)
2475 term_argv[0] = check;
2476 /* Note that gnome-terminal takes -x and
2477 * as -e in gnome-terminal is broken we use that. */
2478 term_argv[1] = g_strdup ("-x");
2480 else
2482 if (check == NULL)
2483 check = g_find_program_in_path ("nxterm");
2484 if (check == NULL)
2485 check = g_find_program_in_path ("color-xterm");
2486 if (check == NULL)
2487 check = g_find_program_in_path ("rxvt");
2488 if (check == NULL)
2489 check = g_find_program_in_path ("xterm");
2490 if (check == NULL)
2491 check = g_find_program_in_path ("dtterm");
2492 if (check == NULL)
2494 check = g_strdup ("xterm");
2495 g_warning ("couldn't find a terminal, falling back to xterm");
2497 term_argv[0] = check;
2498 term_argv[1] = g_strdup ("-e");
2501 real_argc = term_argc + *argc;
2502 real_argv = g_new (char *, real_argc + 1);
2504 for (i = 0; i < term_argc; i++)
2505 real_argv[i] = term_argv[i];
2507 for (j = 0; j < *argc; j++, i++)
2508 real_argv[i] = (char *)the_argv[j];
2510 real_argv[i] = NULL;
2512 g_free (*argv);
2513 *argv = real_argv;
2514 *argc = real_argc;
2516 /* we use g_free here as we sucked all the inner strings
2517 * out from it into real_argv */
2518 g_free (term_argv);
2519 return TRUE;
2520 #else
2521 return FALSE;
2522 #endif /* G_OS_WIN32 */
2525 static GList *
2526 create_files_for_uris (GList *uris)
2528 GList *res;
2529 GList *iter;
2531 res = NULL;
2533 for (iter = uris; iter; iter = iter->next)
2535 GFile *file = g_file_new_for_uri ((char *)iter->data);
2536 res = g_list_prepend (res, file);
2539 return g_list_reverse (res);
2542 typedef struct
2544 GSpawnChildSetupFunc user_setup;
2545 gpointer user_setup_data;
2547 char *pid_envvar;
2548 } ChildSetupData;
2550 static void
2551 child_setup (gpointer user_data)
2553 ChildSetupData *data = user_data;
2555 if (data->pid_envvar)
2557 pid_t pid = getpid ();
2558 char buf[20];
2559 int i;
2561 /* Write the pid into the space already reserved for it in the
2562 * environment array. We can't use sprintf because it might
2563 * malloc, so we do it by hand. It's simplest to write the pid
2564 * out backwards first, then copy it over.
2566 for (i = 0; pid; i++, pid /= 10)
2567 buf[i] = (pid % 10) + '0';
2568 for (i--; i >= 0; i--)
2569 *(data->pid_envvar++) = buf[i];
2570 *data->pid_envvar = '\0';
2573 if (data->user_setup)
2574 data->user_setup (data->user_setup_data);
2577 static void
2578 notify_desktop_launch (GDBusConnection *session_bus,
2579 GDesktopAppInfo *info,
2580 long pid,
2581 const char *display,
2582 const char *sn_id,
2583 GList *uris)
2585 GDBusMessage *msg;
2586 GVariantBuilder uri_variant;
2587 GVariantBuilder extras_variant;
2588 GList *iter;
2589 const char *desktop_file_id;
2590 const char *gio_desktop_file;
2592 if (session_bus == NULL)
2593 return;
2595 g_variant_builder_init (&uri_variant, G_VARIANT_TYPE ("as"));
2596 for (iter = uris; iter; iter = iter->next)
2597 g_variant_builder_add (&uri_variant, "s", iter->data);
2599 g_variant_builder_init (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2600 if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2601 g_variant_builder_add (&extras_variant, "{sv}",
2602 "startup-id",
2603 g_variant_new ("s",
2604 sn_id));
2605 gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2606 if (gio_desktop_file != NULL)
2607 g_variant_builder_add (&extras_variant, "{sv}",
2608 "origin-desktop-file",
2609 g_variant_new_bytestring (gio_desktop_file));
2610 if (g_get_prgname () != NULL)
2611 g_variant_builder_add (&extras_variant, "{sv}",
2612 "origin-prgname",
2613 g_variant_new_bytestring (g_get_prgname ()));
2614 g_variant_builder_add (&extras_variant, "{sv}",
2615 "origin-pid",
2616 g_variant_new ("x",
2617 (gint64)getpid ()));
2619 if (info->filename)
2620 desktop_file_id = info->filename;
2621 else if (info->desktop_id)
2622 desktop_file_id = info->desktop_id;
2623 else
2624 desktop_file_id = "";
2626 msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2627 "org.gtk.gio.DesktopAppInfo",
2628 "Launched");
2629 g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2630 g_variant_new_bytestring (desktop_file_id),
2631 display ? display : "",
2632 (gint64)pid,
2633 &uri_variant,
2634 &extras_variant));
2635 g_dbus_connection_send_message (session_bus,
2636 msg, 0,
2637 NULL,
2638 NULL);
2639 g_object_unref (msg);
2642 #define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2644 static gboolean
2645 g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo *info,
2646 GDBusConnection *session_bus,
2647 const gchar *exec_line,
2648 GList *uris,
2649 GAppLaunchContext *launch_context,
2650 GSpawnFlags spawn_flags,
2651 GSpawnChildSetupFunc user_setup,
2652 gpointer user_setup_data,
2653 GDesktopAppLaunchCallback pid_callback,
2654 gpointer pid_callback_data,
2655 GError **error)
2657 gboolean completed = FALSE;
2658 GList *old_uris;
2659 char **argv, **envp;
2660 int argc;
2661 ChildSetupData data;
2663 g_return_val_if_fail (info != NULL, FALSE);
2665 argv = NULL;
2667 if (launch_context)
2668 envp = g_app_launch_context_get_environment (launch_context);
2669 else
2670 envp = g_get_environ ();
2674 GPid pid;
2675 GList *launched_uris;
2676 GList *iter;
2677 char *sn_id = NULL;
2679 old_uris = uris;
2680 if (!expand_application_parameters (info, exec_line, &uris, &argc, &argv, error))
2681 goto out;
2683 /* Get the subset of URIs we're launching with this process */
2684 launched_uris = NULL;
2685 for (iter = old_uris; iter != NULL && iter != uris; iter = iter->next)
2686 launched_uris = g_list_prepend (launched_uris, iter->data);
2687 launched_uris = g_list_reverse (launched_uris);
2689 if (info->terminal && !prepend_terminal_to_vector (&argc, &argv))
2691 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2692 _("Unable to find terminal required for application"));
2693 goto out;
2696 data.user_setup = user_setup;
2697 data.user_setup_data = user_setup_data;
2699 if (info->filename)
2701 envp = g_environ_setenv (envp,
2702 "GIO_LAUNCHED_DESKTOP_FILE",
2703 info->filename,
2704 TRUE);
2705 envp = g_environ_setenv (envp,
2706 "GIO_LAUNCHED_DESKTOP_FILE_PID",
2707 "XXXXXXXXXXXXXXXXXXXX", /* filled in child_setup */
2708 TRUE);
2709 data.pid_envvar = (char *)g_environ_getenv (envp, "GIO_LAUNCHED_DESKTOP_FILE_PID");
2711 else
2713 data.pid_envvar = NULL;
2716 sn_id = NULL;
2717 if (launch_context)
2719 GList *launched_files = create_files_for_uris (launched_uris);
2721 if (info->startup_notify)
2723 sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
2724 G_APP_INFO (info),
2725 launched_files);
2726 if (sn_id)
2727 envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
2730 g_list_free_full (launched_files, g_object_unref);
2733 if (!g_spawn_async (info->path,
2734 argv,
2735 envp,
2736 spawn_flags,
2737 child_setup,
2738 &data,
2739 &pid,
2740 error))
2742 if (sn_id)
2743 g_app_launch_context_launch_failed (launch_context, sn_id);
2745 g_free (sn_id);
2746 g_list_free (launched_uris);
2748 goto out;
2751 if (pid_callback != NULL)
2752 pid_callback (info, pid, pid_callback_data);
2754 if (launch_context != NULL)
2756 GVariantBuilder builder;
2757 GVariant *platform_data;
2759 g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
2760 g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
2761 if (sn_id)
2762 g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
2763 platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2764 g_signal_emit_by_name (launch_context, "launched", info, platform_data);
2765 g_variant_unref (platform_data);
2768 notify_desktop_launch (session_bus,
2769 info,
2770 pid,
2771 NULL,
2772 sn_id,
2773 launched_uris);
2775 g_free (sn_id);
2776 g_list_free (launched_uris);
2778 g_strfreev (argv);
2779 argv = NULL;
2781 while (uris != NULL);
2783 completed = TRUE;
2785 out:
2786 g_strfreev (argv);
2787 g_strfreev (envp);
2789 return completed;
2792 static gchar *
2793 object_path_from_appid (const gchar *appid)
2795 gchar *appid_path, *iter;
2797 appid_path = g_strconcat ("/", appid, NULL);
2798 for (iter = appid_path; *iter; iter++)
2800 if (*iter == '.')
2801 *iter = '/';
2803 if (*iter == '-')
2804 *iter = '_';
2807 return appid_path;
2810 static GVariant *
2811 g_desktop_app_info_make_platform_data (GDesktopAppInfo *info,
2812 GList *uris,
2813 GAppLaunchContext *launch_context)
2815 GVariantBuilder builder;
2817 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
2819 if (launch_context)
2821 GList *launched_files = create_files_for_uris (uris);
2823 if (info->startup_notify)
2825 gchar *sn_id;
2827 sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
2828 if (sn_id)
2829 g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_take_string (sn_id));
2832 g_list_free_full (launched_files, g_object_unref);
2835 return g_variant_builder_end (&builder);
2838 static gboolean
2839 g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo *info,
2840 GDBusConnection *session_bus,
2841 GList *uris,
2842 GAppLaunchContext *launch_context)
2844 GVariantBuilder builder;
2845 gchar *object_path;
2847 g_return_val_if_fail (info != NULL, FALSE);
2849 g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
2851 if (uris)
2853 GList *iter;
2855 g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
2856 for (iter = uris; iter; iter = iter->next)
2857 g_variant_builder_add (&builder, "s", iter->data);
2858 g_variant_builder_close (&builder);
2861 g_variant_builder_add_value (&builder, g_desktop_app_info_make_platform_data (info, uris, launch_context));
2863 /* This is non-blocking API. Similar to launching via fork()/exec()
2864 * we don't wait around to see if the program crashed during startup.
2865 * This is what startup-notification's job is...
2867 object_path = object_path_from_appid (info->app_id);
2868 g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
2869 uris ? "Open" : "Activate", g_variant_builder_end (&builder),
2870 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
2871 g_free (object_path);
2873 return TRUE;
2876 static gboolean
2877 g_desktop_app_info_launch_uris_internal (GAppInfo *appinfo,
2878 GList *uris,
2879 GAppLaunchContext *launch_context,
2880 GSpawnFlags spawn_flags,
2881 GSpawnChildSetupFunc user_setup,
2882 gpointer user_setup_data,
2883 GDesktopAppLaunchCallback pid_callback,
2884 gpointer pid_callback_data,
2885 GError **error)
2887 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2888 GDBusConnection *session_bus;
2889 gboolean success = TRUE;
2891 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
2893 if (session_bus && info->app_id)
2894 g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context);
2895 else
2896 success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
2897 spawn_flags, user_setup, user_setup_data,
2898 pid_callback, pid_callback_data, error);
2900 if (session_bus != NULL)
2902 /* This asynchronous flush holds a reference until it completes,
2903 * which ensures that the following unref won't immediately kill
2904 * the connection if we were the initial owner.
2906 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
2907 g_object_unref (session_bus);
2910 return success;
2913 static gboolean
2914 g_desktop_app_info_launch_uris (GAppInfo *appinfo,
2915 GList *uris,
2916 GAppLaunchContext *launch_context,
2917 GError **error)
2919 return g_desktop_app_info_launch_uris_internal (appinfo, uris,
2920 launch_context,
2921 _SPAWN_FLAGS_DEFAULT,
2922 NULL, NULL, NULL, NULL,
2923 error);
2926 static gboolean
2927 g_desktop_app_info_supports_uris (GAppInfo *appinfo)
2929 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2931 return info->exec &&
2932 ((strstr (info->exec, "%u") != NULL) ||
2933 (strstr (info->exec, "%U") != NULL));
2936 static gboolean
2937 g_desktop_app_info_supports_files (GAppInfo *appinfo)
2939 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2941 return info->exec &&
2942 ((strstr (info->exec, "%f") != NULL) ||
2943 (strstr (info->exec, "%F") != NULL));
2946 static gboolean
2947 g_desktop_app_info_launch (GAppInfo *appinfo,
2948 GList *files,
2949 GAppLaunchContext *launch_context,
2950 GError **error)
2952 GList *uris;
2953 char *uri;
2954 gboolean res;
2956 uris = NULL;
2957 while (files)
2959 uri = g_file_get_uri (files->data);
2960 uris = g_list_prepend (uris, uri);
2961 files = files->next;
2964 uris = g_list_reverse (uris);
2966 res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
2968 g_list_free_full (uris, g_free);
2970 return res;
2974 * g_desktop_app_info_launch_uris_as_manager:
2975 * @appinfo: a #GDesktopAppInfo
2976 * @uris: (element-type utf8): List of URIs
2977 * @launch_context: (nullable): a #GAppLaunchContext
2978 * @spawn_flags: #GSpawnFlags, used for each process
2979 * @user_setup: (scope call) (nullable): a #GSpawnChildSetupFunc, used once
2980 * for each process.
2981 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
2982 * @pid_callback: (scope call) (nullable): Callback for child processes
2983 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
2984 * @error: return location for a #GError, or %NULL
2986 * This function performs the equivalent of g_app_info_launch_uris(),
2987 * but is intended primarily for operating system components that
2988 * launch applications. Ordinary applications should use
2989 * g_app_info_launch_uris().
2991 * If the application is launched via traditional UNIX fork()/exec()
2992 * then @spawn_flags, @user_setup and @user_setup_data are used for the
2993 * call to g_spawn_async(). Additionally, @pid_callback (with
2994 * @pid_callback_data) will be called to inform about the PID of the
2995 * created process.
2997 * If application launching occurs via some other mechanism (eg: D-Bus
2998 * activation) then @spawn_flags, @user_setup, @user_setup_data,
2999 * @pid_callback and @pid_callback_data are ignored.
3001 * Returns: %TRUE on successful launch, %FALSE otherwise.
3003 gboolean
3004 g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo *appinfo,
3005 GList *uris,
3006 GAppLaunchContext *launch_context,
3007 GSpawnFlags spawn_flags,
3008 GSpawnChildSetupFunc user_setup,
3009 gpointer user_setup_data,
3010 GDesktopAppLaunchCallback pid_callback,
3011 gpointer pid_callback_data,
3012 GError **error)
3014 return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
3015 uris,
3016 launch_context,
3017 spawn_flags,
3018 user_setup,
3019 user_setup_data,
3020 pid_callback,
3021 pid_callback_data,
3022 error);
3025 /* OnlyShowIn API support {{{2 */
3028 * g_desktop_app_info_set_desktop_env:
3029 * @desktop_env: a string specifying what desktop this is
3031 * Sets the name of the desktop that the application is running in.
3032 * This is used by g_app_info_should_show() and
3033 * g_desktop_app_info_get_show_in() to evaluate the
3034 * `OnlyShowIn` and `NotShowIn`
3035 * desktop entry fields.
3037 * Should be called only once; subsequent calls are ignored.
3039 * Deprecated:2.42:do not use this API. Since 2.42 the value of the
3040 * `XDG_CURRENT_DESKTOP` environment variable will be used.
3042 void
3043 g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
3045 get_current_desktops (desktop_env);
3048 static gboolean
3049 g_desktop_app_info_should_show (GAppInfo *appinfo)
3051 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3053 if (info->nodisplay)
3054 return FALSE;
3056 return g_desktop_app_info_get_show_in (info, NULL);
3059 /* mime types/default apps support {{{2 */
3061 typedef enum {
3062 CONF_DIR,
3063 APP_DIR,
3064 MIMETYPE_DIR
3065 } DirType;
3067 static char *
3068 ensure_dir (DirType type,
3069 GError **error)
3071 char *path, *display_name;
3072 int errsv;
3074 switch (type)
3076 case CONF_DIR:
3077 path = g_build_filename (g_get_user_config_dir (), NULL);
3078 break;
3080 case APP_DIR:
3081 path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
3082 break;
3084 case MIMETYPE_DIR:
3085 path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
3086 break;
3088 default:
3089 g_assert_not_reached ();
3092 errno = 0;
3093 if (g_mkdir_with_parents (path, 0700) == 0)
3094 return path;
3096 errsv = errno;
3097 display_name = g_filename_display_name (path);
3098 if (type == APP_DIR)
3099 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3100 _("Can’t create user application configuration folder %s: %s"),
3101 display_name, g_strerror (errsv));
3102 else
3103 g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3104 _("Can’t create user MIME configuration folder %s: %s"),
3105 display_name, g_strerror (errsv));
3107 g_free (display_name);
3108 g_free (path);
3110 return NULL;
3113 static gboolean
3114 update_mimeapps_list (const char *desktop_id,
3115 const char *content_type,
3116 UpdateMimeFlags flags,
3117 GError **error)
3119 char *dirname, *filename, *string;
3120 GKeyFile *key_file;
3121 gboolean load_succeeded, res;
3122 char **old_list, **list;
3123 gsize length, data_size;
3124 char *data;
3125 int i, j, k;
3126 char **content_types;
3128 /* Don't add both at start and end */
3129 g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
3130 (flags & UPDATE_MIME_SET_NON_DEFAULT)));
3132 dirname = ensure_dir (CONF_DIR, error);
3133 if (!dirname)
3134 return FALSE;
3136 filename = g_build_filename (dirname, "mimeapps.list", NULL);
3137 g_free (dirname);
3139 key_file = g_key_file_new ();
3140 load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
3141 if (!load_succeeded ||
3142 (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
3143 !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
3144 !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
3146 g_key_file_free (key_file);
3147 key_file = g_key_file_new ();
3150 if (content_type)
3152 content_types = g_new (char *, 2);
3153 content_types[0] = g_strdup (content_type);
3154 content_types[1] = NULL;
3156 else
3158 content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
3161 for (k = 0; content_types && content_types[k]; k++)
3163 /* set as default, if requested so */
3164 string = g_key_file_get_string (key_file,
3165 DEFAULT_APPLICATIONS_GROUP,
3166 content_types[k],
3167 NULL);
3169 if (g_strcmp0 (string, desktop_id) != 0 &&
3170 (flags & UPDATE_MIME_SET_DEFAULT))
3172 g_free (string);
3173 string = g_strdup (desktop_id);
3175 /* add in the non-default list too, if it's not already there */
3176 flags |= UPDATE_MIME_SET_NON_DEFAULT;
3179 if (string == NULL || desktop_id == NULL)
3180 g_key_file_remove_key (key_file,
3181 DEFAULT_APPLICATIONS_GROUP,
3182 content_types[k],
3183 NULL);
3184 else
3185 g_key_file_set_string (key_file,
3186 DEFAULT_APPLICATIONS_GROUP,
3187 content_types[k],
3188 string);
3190 g_free (string);
3193 if (content_type)
3195 /* reuse the list from above */
3197 else
3199 g_strfreev (content_types);
3200 content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
3203 for (k = 0; content_types && content_types[k]; k++)
3205 /* Add to the right place in the list */
3207 length = 0;
3208 old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
3209 content_types[k], &length, NULL);
3211 list = g_new (char *, 1 + length + 1);
3213 i = 0;
3215 /* if we're adding a last-used hint, just put the application in front of the list */
3216 if (flags & UPDATE_MIME_SET_LAST_USED)
3218 /* avoid adding this again as non-default later */
3219 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3220 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3222 list[i++] = g_strdup (desktop_id);
3225 if (old_list)
3227 for (j = 0; old_list[j] != NULL; j++)
3229 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3231 /* rewrite other entries if they're different from the new one */
3232 list[i++] = g_strdup (old_list[j]);
3234 else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3236 /* we encountered an old entry which is equal to the one we're adding as non-default,
3237 * don't change its position in the list.
3239 flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3240 list[i++] = g_strdup (old_list[j]);
3245 /* add it at the end of the list */
3246 if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3247 list[i++] = g_strdup (desktop_id);
3249 list[i] = NULL;
3251 g_strfreev (old_list);
3253 if (list[0] == NULL || desktop_id == NULL)
3254 g_key_file_remove_key (key_file,
3255 ADDED_ASSOCIATIONS_GROUP,
3256 content_types[k],
3257 NULL);
3258 else
3259 g_key_file_set_string_list (key_file,
3260 ADDED_ASSOCIATIONS_GROUP,
3261 content_types[k],
3262 (const char * const *)list, i);
3264 g_strfreev (list);
3267 if (content_type)
3269 /* reuse the list from above */
3271 else
3273 g_strfreev (content_types);
3274 content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
3277 for (k = 0; content_types && content_types[k]; k++)
3279 /* Remove from removed associations group (unless remove) */
3281 length = 0;
3282 old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
3283 content_types[k], &length, NULL);
3285 list = g_new (char *, 1 + length + 1);
3287 i = 0;
3288 if (flags & UPDATE_MIME_REMOVE)
3289 list[i++] = g_strdup (desktop_id);
3290 if (old_list)
3292 for (j = 0; old_list[j] != NULL; j++)
3294 if (g_strcmp0 (old_list[j], desktop_id) != 0)
3295 list[i++] = g_strdup (old_list[j]);
3298 list[i] = NULL;
3300 g_strfreev (old_list);
3302 if (list[0] == NULL || desktop_id == NULL)
3303 g_key_file_remove_key (key_file,
3304 REMOVED_ASSOCIATIONS_GROUP,
3305 content_types[k],
3306 NULL);
3307 else
3308 g_key_file_set_string_list (key_file,
3309 REMOVED_ASSOCIATIONS_GROUP,
3310 content_types[k],
3311 (const char * const *)list, i);
3313 g_strfreev (list);
3316 g_strfreev (content_types);
3318 data = g_key_file_to_data (key_file, &data_size, error);
3319 g_key_file_free (key_file);
3321 res = g_file_set_contents (filename, data, data_size, error);
3323 desktop_file_dirs_invalidate_user_config ();
3325 g_free (filename);
3326 g_free (data);
3328 return res;
3331 static gboolean
3332 g_desktop_app_info_set_as_last_used_for_type (GAppInfo *appinfo,
3333 const char *content_type,
3334 GError **error)
3336 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3338 if (!g_desktop_app_info_ensure_saved (info, error))
3339 return FALSE;
3341 if (!info->desktop_id)
3343 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3344 _("Application information lacks an identifier"));
3345 return FALSE;
3348 /* both add support for the content type and set as last used */
3349 return update_mimeapps_list (info->desktop_id, content_type,
3350 UPDATE_MIME_SET_NON_DEFAULT |
3351 UPDATE_MIME_SET_LAST_USED,
3352 error);
3355 static gboolean
3356 g_desktop_app_info_set_as_default_for_type (GAppInfo *appinfo,
3357 const char *content_type,
3358 GError **error)
3360 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3362 if (!g_desktop_app_info_ensure_saved (info, error))
3363 return FALSE;
3365 if (!info->desktop_id)
3367 g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3368 _("Application information lacks an identifier"));
3369 return FALSE;
3372 return update_mimeapps_list (info->desktop_id, content_type,
3373 UPDATE_MIME_SET_DEFAULT,
3374 error);
3377 static void
3378 update_program_done (GPid pid,
3379 gint status,
3380 gpointer data)
3382 /* Did the application exit correctly */
3383 if (g_spawn_check_exit_status (status, NULL))
3385 /* Here we could clean out any caches in use */
3389 static void
3390 run_update_command (char *command,
3391 char *subdir)
3393 char *argv[3] = {
3394 NULL,
3395 NULL,
3396 NULL,
3398 GPid pid = 0;
3399 GError *error = NULL;
3401 argv[0] = command;
3402 argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
3404 if (g_spawn_async ("/", argv,
3405 NULL, /* envp */
3406 G_SPAWN_SEARCH_PATH |
3407 G_SPAWN_STDOUT_TO_DEV_NULL |
3408 G_SPAWN_STDERR_TO_DEV_NULL |
3409 G_SPAWN_DO_NOT_REAP_CHILD,
3410 NULL, NULL, /* No setup function */
3411 &pid,
3412 &error))
3413 g_child_watch_add (pid, update_program_done, NULL);
3414 else
3416 /* If we get an error at this point, it's quite likely the user doesn't
3417 * have an installed copy of either 'update-mime-database' or
3418 * 'update-desktop-database'. I don't think we want to popup an error
3419 * dialog at this point, so we just do a g_warning to give the user a
3420 * chance of debugging it.
3422 g_warning ("%s", error->message);
3423 g_error_free (error);
3426 g_free (argv[1]);
3429 static gboolean
3430 g_desktop_app_info_set_as_default_for_extension (GAppInfo *appinfo,
3431 const char *extension,
3432 GError **error)
3434 char *filename, *basename, *mimetype;
3435 char *dirname;
3436 gboolean res;
3438 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
3439 return FALSE;
3441 dirname = ensure_dir (MIMETYPE_DIR, error);
3442 if (!dirname)
3443 return FALSE;
3445 basename = g_strdup_printf ("user-extension-%s.xml", extension);
3446 filename = g_build_filename (dirname, basename, NULL);
3447 g_free (basename);
3448 g_free (dirname);
3450 mimetype = g_strdup_printf ("application/x-extension-%s", extension);
3452 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
3454 char *contents;
3456 contents =
3457 g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
3458 "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
3459 " <mime-type type=\"%s\">\n"
3460 " <comment>%s document</comment>\n"
3461 " <glob pattern=\"*.%s\"/>\n"
3462 " </mime-type>\n"
3463 "</mime-info>\n", mimetype, extension, extension);
3465 g_file_set_contents (filename, contents, -1, NULL);
3466 g_free (contents);
3468 run_update_command ("update-mime-database", "mime");
3470 g_free (filename);
3472 res = g_desktop_app_info_set_as_default_for_type (appinfo,
3473 mimetype,
3474 error);
3476 g_free (mimetype);
3478 return res;
3481 static gboolean
3482 g_desktop_app_info_add_supports_type (GAppInfo *appinfo,
3483 const char *content_type,
3484 GError **error)
3486 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3488 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3489 return FALSE;
3491 return update_mimeapps_list (info->desktop_id, content_type,
3492 UPDATE_MIME_SET_NON_DEFAULT,
3493 error);
3496 static gboolean
3497 g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
3499 return TRUE;
3502 static gboolean
3503 g_desktop_app_info_remove_supports_type (GAppInfo *appinfo,
3504 const char *content_type,
3505 GError **error)
3507 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3509 if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
3510 return FALSE;
3512 return update_mimeapps_list (info->desktop_id, content_type,
3513 UPDATE_MIME_REMOVE,
3514 error);
3517 static const char **
3518 g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
3520 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3522 return (const char**) info->mime_types;
3525 /* Saving and deleting {{{2 */
3527 static gboolean
3528 g_desktop_app_info_ensure_saved (GDesktopAppInfo *info,
3529 GError **error)
3531 GKeyFile *key_file;
3532 char *dirname;
3533 char *filename;
3534 char *data, *desktop_id;
3535 gsize data_size;
3536 int fd;
3537 gboolean res;
3539 if (info->filename != NULL)
3540 return TRUE;
3542 /* This is only used for object created with
3543 * g_app_info_create_from_commandline. All other
3544 * object should have a filename
3547 dirname = ensure_dir (APP_DIR, error);
3548 if (!dirname)
3549 return FALSE;
3551 key_file = g_key_file_new ();
3553 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3554 "Encoding", "UTF-8");
3555 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3556 G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
3557 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3558 G_KEY_FILE_DESKTOP_KEY_TYPE,
3559 G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
3560 if (info->terminal)
3561 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3562 G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
3563 if (info->nodisplay)
3564 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3565 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3567 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3568 G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
3570 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3571 G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
3573 if (info->generic_name != NULL)
3574 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3575 GENERIC_NAME_KEY, info->generic_name);
3577 if (info->fullname != NULL)
3578 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3579 FULL_NAME_KEY, info->fullname);
3581 g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
3582 G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
3584 g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
3585 G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
3587 data = g_key_file_to_data (key_file, &data_size, NULL);
3588 g_key_file_free (key_file);
3590 desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
3591 filename = g_build_filename (dirname, desktop_id, NULL);
3592 g_free (desktop_id);
3593 g_free (dirname);
3595 fd = g_mkstemp (filename);
3596 if (fd == -1)
3598 char *display_name;
3600 display_name = g_filename_display_name (filename);
3601 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3602 _("Can’t create user desktop file %s"), display_name);
3603 g_free (display_name);
3604 g_free (filename);
3605 g_free (data);
3606 return FALSE;
3609 desktop_id = g_path_get_basename (filename);
3611 /* FIXME - actually handle error */
3612 (void) g_close (fd, NULL);
3614 res = g_file_set_contents (filename, data, data_size, error);
3615 g_free (data);
3616 if (!res)
3618 g_free (desktop_id);
3619 g_free (filename);
3620 return FALSE;
3623 info->filename = filename;
3624 info->desktop_id = desktop_id;
3626 run_update_command ("update-desktop-database", "applications");
3628 /* We just dropped a file in the user's desktop file directory. Save
3629 * the monitor the bother of having to notice it and invalidate
3630 * immediately.
3632 * This means that calls directly following this will be able to see
3633 * the results immediately.
3635 desktop_file_dirs_invalidate_user_data ();
3637 return TRUE;
3640 static gboolean
3641 g_desktop_app_info_can_delete (GAppInfo *appinfo)
3643 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3645 if (info->filename)
3647 if (strstr (info->filename, "/userapp-"))
3648 return g_access (info->filename, W_OK) == 0;
3651 return FALSE;
3654 static gboolean
3655 g_desktop_app_info_delete (GAppInfo *appinfo)
3657 GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3659 if (info->filename)
3661 if (g_remove (info->filename) == 0)
3663 update_mimeapps_list (info->desktop_id, NULL,
3664 UPDATE_MIME_NONE,
3665 NULL);
3667 g_free (info->filename);
3668 info->filename = NULL;
3669 g_free (info->desktop_id);
3670 info->desktop_id = NULL;
3672 return TRUE;
3676 return FALSE;
3679 /* Create for commandline {{{2 */
3681 * g_app_info_create_from_commandline:
3682 * @commandline: the commandline to use
3683 * @application_name: (nullable): the application name, or %NULL to use @commandline
3684 * @flags: flags that can specify details of the created #GAppInfo
3685 * @error: a #GError location to store the error occurring, %NULL to ignore.
3687 * Creates a new #GAppInfo from the given information.
3689 * Note that for @commandline, the quoting rules of the Exec key of the
3690 * [freedesktop.org Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
3691 * are applied. For example, if the @commandline contains
3692 * percent-encoded URIs, the percent-character must be doubled in order to prevent it from
3693 * being swallowed by Exec key unquoting. See the specification for exact quoting rules.
3695 * Returns: (transfer full): new #GAppInfo for given command.
3697 GAppInfo *
3698 g_app_info_create_from_commandline (const char *commandline,
3699 const char *application_name,
3700 GAppInfoCreateFlags flags,
3701 GError **error)
3703 char **split;
3704 char *basename;
3705 GDesktopAppInfo *info;
3707 g_return_val_if_fail (commandline, NULL);
3709 info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
3711 info->filename = NULL;
3712 info->desktop_id = NULL;
3714 info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
3715 info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
3716 info->hidden = FALSE;
3717 if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
3718 info->exec = g_strconcat (commandline, " %u", NULL);
3719 else
3720 info->exec = g_strconcat (commandline, " %f", NULL);
3721 info->nodisplay = TRUE;
3722 info->binary = binary_from_exec (info->exec);
3724 if (application_name)
3725 info->name = g_strdup (application_name);
3726 else
3728 /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
3729 split = g_strsplit (commandline, " ", 2);
3730 basename = split[0] ? g_path_get_basename (split[0]) : NULL;
3731 g_strfreev (split);
3732 info->name = basename;
3733 if (info->name == NULL)
3734 info->name = g_strdup ("custom");
3736 info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
3738 return G_APP_INFO (info);
3741 /* GAppInfo interface init */
3743 static void
3744 g_desktop_app_info_iface_init (GAppInfoIface *iface)
3746 iface->dup = g_desktop_app_info_dup;
3747 iface->equal = g_desktop_app_info_equal;
3748 iface->get_id = g_desktop_app_info_get_id;
3749 iface->get_name = g_desktop_app_info_get_name;
3750 iface->get_description = g_desktop_app_info_get_description;
3751 iface->get_executable = g_desktop_app_info_get_executable;
3752 iface->get_icon = g_desktop_app_info_get_icon;
3753 iface->launch = g_desktop_app_info_launch;
3754 iface->supports_uris = g_desktop_app_info_supports_uris;
3755 iface->supports_files = g_desktop_app_info_supports_files;
3756 iface->launch_uris = g_desktop_app_info_launch_uris;
3757 iface->should_show = g_desktop_app_info_should_show;
3758 iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
3759 iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
3760 iface->add_supports_type = g_desktop_app_info_add_supports_type;
3761 iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
3762 iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
3763 iface->can_delete = g_desktop_app_info_can_delete;
3764 iface->do_delete = g_desktop_app_info_delete;
3765 iface->get_commandline = g_desktop_app_info_get_commandline;
3766 iface->get_display_name = g_desktop_app_info_get_display_name;
3767 iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
3768 iface->get_supported_types = g_desktop_app_info_get_supported_types;
3771 /* Recommended applications {{{2 */
3773 /* Converts content_type into a list of itself with all of its parent
3774 * types (if include_fallback is enabled) or just returns a single-item
3775 * list with the unaliased content type.
3777 static gchar **
3778 get_list_of_mimetypes (const gchar *content_type,
3779 gboolean include_fallback)
3781 gchar *unaliased;
3782 GPtrArray *array;
3784 array = g_ptr_array_new ();
3785 unaliased = _g_unix_content_type_unalias (content_type);
3786 g_ptr_array_add (array, unaliased);
3788 if (include_fallback)
3790 gint i;
3792 /* Iterate the array as we grow it, until we have nothing more to add */
3793 for (i = 0; i < array->len; i++)
3795 gchar **parents = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
3796 gint j;
3798 for (j = 0; parents[j]; j++)
3799 /* Don't add duplicates */
3800 if (!array_contains (array, parents[j]))
3801 g_ptr_array_add (array, parents[j]);
3802 else
3803 g_free (parents[j]);
3805 /* We already stole or freed each element. Free the container. */
3806 g_free (parents);
3810 g_ptr_array_add (array, NULL);
3812 return (gchar **) g_ptr_array_free (array, FALSE);
3815 static gchar **
3816 g_desktop_app_info_get_desktop_ids_for_content_type (const gchar *content_type,
3817 gboolean include_fallback)
3819 GPtrArray *hits, *blacklist;
3820 gchar **types;
3821 gint i, j;
3823 hits = g_ptr_array_new ();
3824 blacklist = g_ptr_array_new ();
3826 types = get_list_of_mimetypes (content_type, include_fallback);
3828 desktop_file_dirs_lock ();
3830 for (i = 0; types[i]; i++)
3831 for (j = 0; j < n_desktop_file_dirs; j++)
3832 desktop_file_dir_mime_lookup (&desktop_file_dirs[j], types[i], hits, blacklist);
3834 /* We will keep the hits past unlocking, so we must dup them */
3835 for (i = 0; i < hits->len; i++)
3836 hits->pdata[i] = g_strdup (hits->pdata[i]);
3838 desktop_file_dirs_unlock ();
3840 g_ptr_array_add (hits, NULL);
3842 g_ptr_array_free (blacklist, TRUE);
3843 g_strfreev (types);
3845 return (gchar **) g_ptr_array_free (hits, FALSE);
3849 * g_app_info_get_recommended_for_type:
3850 * @content_type: the content type to find a #GAppInfo for
3852 * Gets a list of recommended #GAppInfos for a given content type, i.e.
3853 * those applications which claim to support the given content type exactly,
3854 * and not by MIME type subclassing.
3855 * Note that the first application of the list is the last used one, i.e.
3856 * the last one for which g_app_info_set_as_last_used_for_type() has been
3857 * called.
3859 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3860 * for given @content_type or %NULL on error.
3862 * Since: 2.28
3864 GList *
3865 g_app_info_get_recommended_for_type (const gchar *content_type)
3867 gchar **desktop_ids;
3868 GList *infos;
3869 gint i;
3871 g_return_val_if_fail (content_type != NULL, NULL);
3873 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
3875 infos = NULL;
3876 for (i = 0; desktop_ids[i]; i++)
3878 GDesktopAppInfo *info;
3880 info = g_desktop_app_info_new (desktop_ids[i]);
3881 if (info)
3882 infos = g_list_prepend (infos, info);
3885 g_strfreev (desktop_ids);
3887 return g_list_reverse (infos);
3891 * g_app_info_get_fallback_for_type:
3892 * @content_type: the content type to find a #GAppInfo for
3894 * Gets a list of fallback #GAppInfos for a given content type, i.e.
3895 * those applications which claim to support the given content type
3896 * by MIME type subclassing and not directly.
3898 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3899 * for given @content_type or %NULL on error.
3901 * Since: 2.28
3903 GList *
3904 g_app_info_get_fallback_for_type (const gchar *content_type)
3906 gchar **recommended_ids;
3907 gchar **all_ids;
3908 GList *infos;
3909 gint i;
3911 g_return_val_if_fail (content_type != NULL, NULL);
3913 recommended_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
3914 all_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
3916 infos = NULL;
3917 for (i = 0; all_ids[i]; i++)
3919 GDesktopAppInfo *info;
3920 gint j;
3922 /* Don't return the ones on the recommended list */
3923 for (j = 0; recommended_ids[j]; j++)
3924 if (g_str_equal (all_ids[i], recommended_ids[j]))
3925 break;
3927 if (recommended_ids[j])
3928 continue;
3930 info = g_desktop_app_info_new (all_ids[i]);
3932 if (info)
3933 infos = g_list_prepend (infos, info);
3936 g_strfreev (recommended_ids);
3937 g_strfreev (all_ids);
3939 return g_list_reverse (infos);
3943 * g_app_info_get_all_for_type:
3944 * @content_type: the content type to find a #GAppInfo for
3946 * Gets a list of all #GAppInfos for a given content type,
3947 * including the recommended and fallback #GAppInfos. See
3948 * g_app_info_get_recommended_for_type() and
3949 * g_app_info_get_fallback_for_type().
3951 * Returns: (element-type GAppInfo) (transfer full): #GList of #GAppInfos
3952 * for given @content_type or %NULL on error.
3954 GList *
3955 g_app_info_get_all_for_type (const char *content_type)
3957 gchar **desktop_ids;
3958 GList *infos;
3959 gint i;
3961 g_return_val_if_fail (content_type != NULL, NULL);
3963 desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
3965 infos = NULL;
3966 for (i = 0; desktop_ids[i]; i++)
3968 GDesktopAppInfo *info;
3970 info = g_desktop_app_info_new (desktop_ids[i]);
3971 if (info)
3972 infos = g_list_prepend (infos, info);
3975 g_strfreev (desktop_ids);
3977 return g_list_reverse (infos);
3981 * g_app_info_reset_type_associations:
3982 * @content_type: a content type
3984 * Removes all changes to the type associations done by
3985 * g_app_info_set_as_default_for_type(),
3986 * g_app_info_set_as_default_for_extension(),
3987 * g_app_info_add_supports_type() or
3988 * g_app_info_remove_supports_type().
3990 * Since: 2.20
3992 void
3993 g_app_info_reset_type_associations (const char *content_type)
3995 update_mimeapps_list (NULL, content_type,
3996 UPDATE_MIME_NONE,
3997 NULL);
4001 * g_app_info_get_default_for_type:
4002 * @content_type: the content type to find a #GAppInfo for
4003 * @must_support_uris: if %TRUE, the #GAppInfo is expected to
4004 * support URIs
4006 * Gets the default #GAppInfo for a given content type.
4008 * Returns: (transfer full): #GAppInfo for given @content_type or
4009 * %NULL on error.
4011 GAppInfo *
4012 g_app_info_get_default_for_type (const char *content_type,
4013 gboolean must_support_uris)
4015 GPtrArray *blacklist;
4016 GPtrArray *results;
4017 GAppInfo *info;
4018 gchar **types;
4019 gint i, j, k;
4021 g_return_val_if_fail (content_type != NULL, NULL);
4023 types = get_list_of_mimetypes (content_type, TRUE);
4025 blacklist = g_ptr_array_new ();
4026 results = g_ptr_array_new ();
4027 info = NULL;
4029 desktop_file_dirs_lock ();
4031 for (i = 0; types[i]; i++)
4033 /* Collect all the default apps for this type */
4034 for (j = 0; j < n_desktop_file_dirs; j++)
4035 desktop_file_dir_default_lookup (&desktop_file_dirs[j], types[i], results);
4037 /* Consider the associations as well... */
4038 for (j = 0; j < n_desktop_file_dirs; j++)
4039 desktop_file_dir_mime_lookup (&desktop_file_dirs[j], types[i], results, blacklist);
4041 /* (If any), see if one of those apps is installed... */
4042 for (j = 0; j < results->len; j++)
4044 const gchar *desktop_id = g_ptr_array_index (results, j);
4046 for (k = 0; k < n_desktop_file_dirs; k++)
4048 info = (GAppInfo *) desktop_file_dir_get_app (&desktop_file_dirs[k], desktop_id);
4050 if (info)
4052 if (!must_support_uris || g_app_info_supports_uris (info))
4053 goto out;
4055 g_clear_object (&info);
4060 /* Reset the list, ready to try again with the next (parent)
4061 * mimetype, but keep the blacklist in place.
4063 g_ptr_array_set_size (results, 0);
4066 out:
4067 desktop_file_dirs_unlock ();
4069 g_ptr_array_unref (blacklist);
4070 g_ptr_array_unref (results);
4071 g_strfreev (types);
4073 return info;
4077 * g_app_info_get_default_for_uri_scheme:
4078 * @uri_scheme: a string containing a URI scheme.
4080 * Gets the default application for handling URIs with
4081 * the given URI scheme. A URI scheme is the initial part
4082 * of the URI, up to but not including the ':', e.g. "http",
4083 * "ftp" or "sip".
4085 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4087 GAppInfo *
4088 g_app_info_get_default_for_uri_scheme (const char *uri_scheme)
4090 GAppInfo *app_info;
4091 char *content_type, *scheme_down;
4093 scheme_down = g_ascii_strdown (uri_scheme, -1);
4094 content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
4095 g_free (scheme_down);
4096 app_info = g_app_info_get_default_for_type (content_type, FALSE);
4097 g_free (content_type);
4099 return app_info;
4102 /* "Get all" API {{{2 */
4105 * g_desktop_app_info_get_implementations:
4106 * @interface: the name of the interface
4108 * Gets all applications that implement @interface.
4110 * An application implements an interface if that interface is listed in
4111 * the Implements= line of the desktop file of the application.
4113 * Returns: (element-type GDesktopAppInfo) (transfer full): a list of #GDesktopAppInfo
4114 * objects.
4116 * Since: 2.42
4118 GList *
4119 g_desktop_app_info_get_implementations (const gchar *interface)
4121 GList *result = NULL;
4122 GList **ptr;
4123 gint i;
4125 desktop_file_dirs_lock ();
4127 for (i = 0; i < n_desktop_file_dirs; i++)
4128 desktop_file_dir_get_implementations (&desktop_file_dirs[i], &result, interface);
4130 desktop_file_dirs_unlock ();
4132 ptr = &result;
4133 while (*ptr)
4135 gchar *name = (*ptr)->data;
4136 GDesktopAppInfo *app;
4138 app = g_desktop_app_info_new (name);
4139 g_free (name);
4141 if (app)
4143 (*ptr)->data = app;
4144 ptr = &(*ptr)->next;
4146 else
4147 *ptr = g_list_delete_link (*ptr, *ptr);
4150 return result;
4154 * g_desktop_app_info_search:
4155 * @search_string: the search string to use
4157 * Searches desktop files for ones that match @search_string.
4159 * The return value is an array of strvs. Each strv contains a list of
4160 * applications that matched @search_string with an equal score. The
4161 * outer list is sorted by score so that the first strv contains the
4162 * best-matching applications, and so on.
4163 * The algorithm for determining matches is undefined and may change at
4164 * any time.
4166 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
4167 * list of strvs. Free each item with g_strfreev() and free the outer
4168 * list with g_free().
4170 gchar ***
4171 g_desktop_app_info_search (const gchar *search_string)
4173 gchar **search_tokens;
4174 gint last_category = -1;
4175 gchar ***results;
4176 gint n_categories = 0;
4177 gint start_of_category;
4178 gint i, j;
4180 search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
4182 desktop_file_dirs_lock ();
4184 reset_total_search_results ();
4186 for (i = 0; i < n_desktop_file_dirs; i++)
4188 for (j = 0; search_tokens[j]; j++)
4190 desktop_file_dir_search (&desktop_file_dirs[i], search_tokens[j]);
4191 merge_token_results (j == 0);
4193 merge_directory_results ();
4196 sort_total_search_results ();
4198 /* Count the total number of unique categories */
4199 for (i = 0; i < static_total_results_size; i++)
4200 if (static_total_results[i].category != last_category)
4202 last_category = static_total_results[i].category;
4203 n_categories++;
4206 results = g_new (gchar **, n_categories + 1);
4208 /* Start loading into the results list */
4209 start_of_category = 0;
4210 for (i = 0; i < n_categories; i++)
4212 gint n_items_in_category = 0;
4213 gint this_category;
4214 gint j;
4216 this_category = static_total_results[start_of_category].category;
4218 while (start_of_category + n_items_in_category < static_total_results_size &&
4219 static_total_results[start_of_category + n_items_in_category].category == this_category)
4220 n_items_in_category++;
4222 results[i] = g_new (gchar *, n_items_in_category + 1);
4223 for (j = 0; j < n_items_in_category; j++)
4224 results[i][j] = g_strdup (static_total_results[start_of_category + j].app_name);
4225 results[i][j] = NULL;
4227 start_of_category += n_items_in_category;
4229 results[i] = NULL;
4231 desktop_file_dirs_unlock ();
4233 g_strfreev (search_tokens);
4235 return results;
4239 * g_app_info_get_all:
4241 * Gets a list of all of the applications currently registered
4242 * on this system.
4244 * For desktop files, this includes applications that have
4245 * `NoDisplay=true` set or are excluded from display by means
4246 * of `OnlyShowIn` or `NotShowIn`. See g_app_info_should_show().
4247 * The returned list does not include applications which have
4248 * the `Hidden` key set.
4250 * Returns: (element-type GAppInfo) (transfer full): a newly allocated #GList of references to #GAppInfos.
4252 GList *
4253 g_app_info_get_all (void)
4255 GHashTable *apps;
4256 GHashTableIter iter;
4257 gpointer value;
4258 int i;
4259 GList *infos;
4261 apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4263 desktop_file_dirs_lock ();
4265 for (i = 0; i < n_desktop_file_dirs; i++)
4266 desktop_file_dir_get_all (&desktop_file_dirs[i], apps);
4268 desktop_file_dirs_unlock ();
4270 infos = NULL;
4271 g_hash_table_iter_init (&iter, apps);
4272 while (g_hash_table_iter_next (&iter, NULL, &value))
4274 if (value)
4275 infos = g_list_prepend (infos, value);
4278 g_hash_table_destroy (apps);
4280 return infos;
4283 /* GDesktopAppInfoLookup interface {{{2 */
4286 * GDesktopAppInfoLookup:
4288 * #GDesktopAppInfoLookup is an opaque data structure and can only be accessed
4289 * using the following functions.
4292 G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4294 typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4295 G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4297 static void
4298 g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4302 /* "Get for mime type" APIs {{{2 */
4305 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4306 * @lookup: a #GDesktopAppInfoLookup
4307 * @uri_scheme: a string containing a URI scheme.
4309 * Gets the default application for launching applications
4310 * using this URI scheme for a particular GDesktopAppInfoLookup
4311 * implementation.
4313 * The GDesktopAppInfoLookup interface and this function is used
4314 * to implement g_app_info_get_default_for_uri_scheme() backends
4315 * in a GIO module. There is no reason for applications to use it
4316 * directly. Applications should use g_app_info_get_default_for_uri_scheme().
4318 * Returns: (transfer full): #GAppInfo for given @uri_scheme or %NULL on error.
4320 * Deprecated: The #GDesktopAppInfoLookup interface is deprecated and unused by gio.
4322 GAppInfo *
4323 g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
4324 const char *uri_scheme)
4326 GDesktopAppInfoLookupIface *iface;
4328 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
4330 iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
4332 return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
4335 G_GNUC_END_IGNORE_DEPRECATIONS
4337 /* Misc getter APIs {{{2 */
4340 * g_desktop_app_info_get_startup_wm_class:
4341 * @info: a #GDesktopAppInfo that supports startup notify
4343 * Retrieves the StartupWMClass field from @info. This represents the
4344 * WM_CLASS property of the main window of the application, if launched
4345 * through @info.
4347 * Returns: (transfer none): the startup WM class, or %NULL if none is set
4348 * in the desktop file.
4350 * Since: 2.34
4352 const char *
4353 g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
4355 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4357 return info->startup_wm_class;
4361 * g_desktop_app_info_get_string:
4362 * @info: a #GDesktopAppInfo
4363 * @key: the key to look up
4365 * Looks up a string value in the keyfile backing @info.
4367 * The @key is looked up in the "Desktop Entry" group.
4369 * Returns: a newly allocated string, or %NULL if the key
4370 * is not found
4372 * Since: 2.36
4374 char *
4375 g_desktop_app_info_get_string (GDesktopAppInfo *info,
4376 const char *key)
4378 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4380 return g_key_file_get_string (info->keyfile,
4381 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4385 * g_desktop_app_info_get_boolean:
4386 * @info: a #GDesktopAppInfo
4387 * @key: the key to look up
4389 * Looks up a boolean value in the keyfile backing @info.
4391 * The @key is looked up in the "Desktop Entry" group.
4393 * Returns: the boolean value, or %FALSE if the key
4394 * is not found
4396 * Since: 2.36
4398 gboolean
4399 g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
4400 const char *key)
4402 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4404 return g_key_file_get_boolean (info->keyfile,
4405 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4409 * g_desktop_app_info_has_key:
4410 * @info: a #GDesktopAppInfo
4411 * @key: the key to look up
4413 * Returns whether @key exists in the "Desktop Entry" group
4414 * of the keyfile backing @info.
4416 * Returns: %TRUE if the @key exists
4418 * Since: 2.36
4420 gboolean
4421 g_desktop_app_info_has_key (GDesktopAppInfo *info,
4422 const char *key)
4424 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
4426 return g_key_file_has_key (info->keyfile,
4427 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
4430 /* Desktop actions support {{{2 */
4433 * g_desktop_app_info_list_actions:
4434 * @info: a #GDesktopAppInfo
4436 * Returns the list of "additional application actions" supported on the
4437 * desktop file, as per the desktop file specification.
4439 * As per the specification, this is the list of actions that are
4440 * explicitly listed in the "Actions" key of the [Desktop Entry] group.
4442 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a list of strings, always non-%NULL
4444 * Since: 2.38
4446 const gchar * const *
4447 g_desktop_app_info_list_actions (GDesktopAppInfo *info)
4449 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4451 return (const gchar **) info->actions;
4454 static gboolean
4455 app_info_has_action (GDesktopAppInfo *info,
4456 const gchar *action_name)
4458 gint i;
4460 for (i = 0; info->actions[i]; i++)
4461 if (g_str_equal (info->actions[i], action_name))
4462 return TRUE;
4464 return FALSE;
4468 * g_desktop_app_info_get_action_name:
4469 * @info: a #GDesktopAppInfo
4470 * @action_name: the name of the action as from
4471 * g_desktop_app_info_list_actions()
4473 * Gets the user-visible display name of the "additional application
4474 * action" specified by @action_name.
4476 * This corresponds to the "Name" key within the keyfile group for the
4477 * action.
4479 * Returns: (transfer full): the locale-specific action name
4481 * Since: 2.38
4483 gchar *
4484 g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
4485 const gchar *action_name)
4487 gchar *group_name;
4488 gchar *result;
4490 g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
4491 g_return_val_if_fail (action_name != NULL, NULL);
4492 g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
4494 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4495 result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
4496 g_free (group_name);
4498 /* The spec says that the Name field must be given.
4500 * If it's not, let's follow the behaviour of our get_name()
4501 * implementation above and never return %NULL.
4503 if (result == NULL)
4504 result = g_strdup (_("Unnamed"));
4506 return result;
4510 * g_desktop_app_info_launch_action:
4511 * @info: a #GDesktopAppInfo
4512 * @action_name: the name of the action as from
4513 * g_desktop_app_info_list_actions()
4514 * @launch_context: (nullable): a #GAppLaunchContext
4516 * Activates the named application action.
4518 * You may only call this function on action names that were
4519 * returned from g_desktop_app_info_list_actions().
4521 * Note that if the main entry of the desktop file indicates that the
4522 * application supports startup notification, and @launch_context is
4523 * non-%NULL, then startup notification will be used when activating the
4524 * action (and as such, invocation of the action on the receiving side
4525 * must signal the end of startup notification when it is completed).
4526 * This is the expected behaviour of applications declaring additional
4527 * actions, as per the desktop file specification.
4529 * As with g_app_info_launch() there is no way to detect failures that
4530 * occur while using this function.
4532 * Since: 2.38
4534 void
4535 g_desktop_app_info_launch_action (GDesktopAppInfo *info,
4536 const gchar *action_name,
4537 GAppLaunchContext *launch_context)
4539 GDBusConnection *session_bus;
4541 g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
4542 g_return_if_fail (action_name != NULL);
4543 g_return_if_fail (app_info_has_action (info, action_name));
4545 session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
4547 if (session_bus && info->app_id)
4549 gchar *object_path;
4551 object_path = object_path_from_appid (info->app_id);
4552 g_dbus_connection_call (session_bus, info->app_id, object_path,
4553 "org.freedesktop.Application", "ActivateAction",
4554 g_variant_new ("(sav@a{sv})", action_name, NULL,
4555 g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
4556 NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
4557 g_free (object_path);
4559 else
4561 gchar *group_name;
4562 gchar *exec_line;
4564 group_name = g_strdup_printf ("Desktop Action %s", action_name);
4565 exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
4566 g_free (group_name);
4568 if (exec_line)
4569 g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
4570 _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL, NULL);
4573 if (session_bus != NULL)
4575 g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
4576 g_object_unref (session_bus);
4579 /* Epilogue {{{1 */
4581 /* vim:set foldmethod=marker: */