Coverage Report

Created: 2026-10-14 08:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/glib-2.88.3/gio/gdesktopappinfo.c
Line
Count
Source
1
/* GIO - GLib Input, Output and Streaming Library
2
 *
3
 * Copyright (C) 2006-2007 Red Hat, Inc.
4
 * Copyright © 2007 Ryan Lortie
5
 *
6
 * SPDX-License-Identifier: LGPL-2.1-or-later
7
 *
8
 * This library is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11
 * version 2.1 of the License, or (at your option) any later version.
12
 *
13
 * This library is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16
 * Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General
19
 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
20
 *
21
 * Author: Alexander Larsson <alexl@redhat.com>
22
 *         Ryan Lortie <desrt@desrt.ca>
23
 */
24
25
/* Prelude {{{1 */
26
27
#include "config.h"
28
29
/* For the #GDesktopAppInfoLookup macros; since macro deprecation is implemented
30
 * in the preprocessor, we need to define this before including glib.h*/
31
#ifndef GLIB_DISABLE_DEPRECATION_WARNINGS
32
#define GLIB_DISABLE_DEPRECATION_WARNINGS
33
#endif
34
35
#include <errno.h>
36
#include <string.h>
37
#include <unistd.h>
38
39
#ifdef HAVE_CRT_EXTERNS_H
40
#include <crt_externs.h>
41
#endif
42
43
#include "gcontenttypeprivate.h"
44
#include "gdesktopappinfo.h"
45
#ifdef G_OS_UNIX
46
#include "glib-unix.h"
47
#endif
48
#include "gfile.h"
49
#include "gioerror.h"
50
#include "gthemedicon.h"
51
#include "gfileicon.h"
52
#include <glib/gstdio.h>
53
#include "glibintl.h"
54
#include "glib-private.h"
55
#include "giomodule-priv.h"
56
#include "gappinfo.h"
57
#include "gappinfoprivate.h"
58
#include "glocalfilemonitor.h"
59
#include "gutilsprivate.h"
60
61
#ifdef G_OS_UNIX
62
#include "gdocumentportal.h"
63
#endif
64
65
/**
66
 * GDesktopAppInfo:
67
 *
68
 * `GDesktopAppInfo` is an implementation of [iface@Gio.AppInfo] based on
69
 * desktop files.
70
 *
71
 * Note that `<gio/gdesktopappinfo.h>` belongs to the UNIX-specific
72
 * GIO interfaces, thus you have to use the `gio-unix-2.0.pc` pkg-config
73
 * file or the `GioUnix-2.0` GIR namespace when using it.
74
 */
75
76
0
#define DEFAULT_APPLICATIONS_GROUP  "Default Applications"
77
0
#define ADDED_ASSOCIATIONS_GROUP    "Added Associations"
78
0
#define REMOVED_ASSOCIATIONS_GROUP  "Removed Associations"
79
0
#define MIME_CACHE_GROUP            "MIME Cache"
80
0
#define GENERIC_NAME_KEY            "GenericName"
81
0
#define FULL_NAME_KEY               "X-GNOME-FullName"
82
0
#define KEYWORDS_KEY                "Keywords"
83
0
#define STARTUP_WM_CLASS_KEY        "StartupWMClass"
84
85
enum {
86
  PROP_0,
87
  PROP_FILENAME
88
};
89
90
static void     g_desktop_app_info_iface_init         (GAppInfoIface    *iface);
91
static gboolean g_desktop_app_info_ensure_saved       (GDesktopAppInfo  *info,
92
                                                       GError          **error);
93
static gboolean g_desktop_app_info_load_file (GDesktopAppInfo *self);
94
95
struct _GDesktopAppInfo
96
{
97
  GObject parent_instance;
98
99
  char *desktop_id;
100
  char *filename;
101
  char *app_id;
102
103
  GKeyFile *keyfile;
104
105
  char *name;
106
  char *generic_name;
107
  char *fullname;
108
  char *comment;
109
  char *icon_name;
110
  GIcon *icon;
111
  char **keywords;
112
  char **only_show_in;
113
  char **not_show_in;
114
  char *try_exec;
115
  char *exec;
116
  char *binary;
117
  char *path;
118
  char *categories;
119
  char *startup_wm_class;
120
  char **mime_types;
121
  char **actions;
122
123
  guint nodisplay       : 1;
124
  guint hidden          : 1;
125
  guint terminal        : 1;
126
  guint startup_notify  : 1;
127
  guint no_fuse         : 1;
128
};
129
130
typedef enum {
131
  UPDATE_MIME_NONE = 1 << 0,
132
  UPDATE_MIME_SET_DEFAULT = 1 << 1,
133
  UPDATE_MIME_SET_NON_DEFAULT = 1 << 2,
134
  UPDATE_MIME_REMOVE = 1 << 3,
135
  UPDATE_MIME_SET_LAST_USED = 1 << 4,
136
} G_GNUC_FLAG_ENUM UpdateMimeFlags;
137
138
0
G_DEFINE_TYPE_WITH_CODE (GDesktopAppInfo, g_desktop_app_info, G_TYPE_OBJECT,
139
0
                         G_IMPLEMENT_INTERFACE (G_TYPE_APP_INFO, g_desktop_app_info_iface_init))
140
0
141
0
/* DesktopFileDir implementation {{{1 */
142
0
143
0
typedef struct
144
0
{
145
0
  gatomicrefcount             ref_count;
146
0
  gchar                      *path;
147
0
  gchar                      *alternatively_watching;
148
0
  gboolean                    is_config;
149
0
  gboolean                    is_setup;
150
0
  GFileMonitor               *monitor;
151
0
  GHashTable                 *app_names;
152
0
  GHashTable                 *mime_tweaks;
153
0
  GHashTable                 *memory_index;
154
0
  GHashTable                 *memory_implementations;
155
0
} DesktopFileDir;
156
0
157
0
static GPtrArray      *desktop_file_dirs = NULL;
158
0
static const gchar    *desktop_file_dirs_config_dir = NULL;
159
0
static DesktopFileDir *desktop_file_dir_user_config = NULL;  /* (owned) */
160
0
static DesktopFileDir *desktop_file_dir_user_data = NULL;  /* (owned) */
161
0
static GMutex          desktop_file_dir_lock;
162
0
static const gchar    *gio_launch_desktop_path = NULL;
163
0
164
0
/* Monitor 'changed' signal handler {{{2 */
165
0
static void desktop_file_dir_reset (DesktopFileDir *dir);
166
0
167
0
static DesktopFileDir *
168
0
desktop_file_dir_ref (DesktopFileDir *dir)
169
0
{
170
0
  g_atomic_ref_count_inc (&dir->ref_count);
171
172
0
  return dir;
173
0
}
174
175
static void
176
desktop_file_dir_unref (DesktopFileDir *dir)
177
0
{
178
0
  if (g_atomic_ref_count_dec (&dir->ref_count))
179
0
    {
180
0
      desktop_file_dir_reset (dir);
181
0
      g_free (dir->path);
182
0
      g_free (dir);
183
0
    }
184
0
}
185
186
/*< internal >
187
 * desktop_file_dir_get_alternative_dir:
188
 * @dir: a #DesktopFileDir
189
 *
190
 * Gets the "alternative" directory to monitor in case the path
191
 * doesn't exist.
192
 *
193
 * If the path exists this will return NULL, otherwise it will return a
194
 * parent directory of the path.
195
 *
196
 * This is used to avoid inotify on a non-existent directory (which
197
 * results in polling).
198
 *
199
 * See https://bugzilla.gnome.org/show_bug.cgi?id=522314 for more info.
200
 */
201
static gchar *
202
desktop_file_dir_get_alternative_dir (DesktopFileDir *dir)
203
0
{
204
0
  gchar *parent;
205
206
  /* If the directory itself exists then we need no alternative. */
207
0
  if (g_access (dir->path, R_OK | X_OK) == 0)
208
0
    return NULL;
209
210
  /* Otherwise, try the parent directories until we find one. */
211
0
  parent = g_path_get_dirname (dir->path);
212
213
0
  while (g_access (parent, R_OK | X_OK) != 0)
214
0
    {
215
0
      gchar *tmp = parent;
216
217
0
      parent = g_path_get_dirname (tmp);
218
219
      /* If somehow we get to '/' or '.' then just stop... */
220
0
      if (g_str_equal (parent, tmp))
221
0
        {
222
0
          g_free (tmp);
223
0
          break;
224
0
        }
225
226
0
      g_free (tmp);
227
0
    }
228
229
0
  return parent;
230
0
}
231
232
static void
233
desktop_file_dir_changed (GFileMonitor      *monitor,
234
                          GFile             *file,
235
                          GFile             *other_file,
236
                          GFileMonitorEvent  event_type,
237
                          gpointer           user_data)
238
0
{
239
0
  DesktopFileDir *dir = user_data;
240
0
  gboolean do_nothing = FALSE;
241
242
  /* We are not interested in receiving notifications forever just
243
   * because someone asked about one desktop file once.
244
   *
245
   * After we receive the first notification, reset the dir, destroying
246
   * the monitor.  We will take this as a hint, next time that we are
247
   * asked, that we need to check if everything is up to date.
248
   *
249
   * If this is a notification for a parent directory (because the
250
   * desktop directory didn't exist) then we shouldn't fire the signal
251
   * unless something actually changed.
252
   */
253
0
  g_mutex_lock (&desktop_file_dir_lock);
254
255
0
  if (dir->alternatively_watching)
256
0
    {
257
0
      gchar *alternative_dir;
258
259
0
      alternative_dir = desktop_file_dir_get_alternative_dir (dir);
260
0
      do_nothing = alternative_dir && g_str_equal (dir->alternatively_watching, alternative_dir);
261
0
      g_free (alternative_dir);
262
0
    }
263
264
0
  if (!do_nothing)
265
0
    desktop_file_dir_reset (dir);
266
267
0
  g_mutex_unlock (&desktop_file_dir_lock);
268
269
  /* Notify anyone else who may be interested */
270
0
  if (!do_nothing)
271
0
    g_app_info_monitor_fire ();
272
0
}
273
274
/* Internal utility functions {{{2 */
275
276
/*< internal >
277
 * desktop_file_dir_app_name_is_masked:
278
 * @dir: a #DesktopFileDir
279
 * @app_name: an application ID
280
 *
281
 * Checks if @app_name is masked for @dir.
282
 *
283
 * An application is masked if a similarly-named desktop file exists in
284
 * a desktop file directory with higher precedence.  Masked desktop
285
 * files should be ignored.
286
 */
287
static gboolean
288
desktop_file_dir_app_name_is_masked (DesktopFileDir *dir,
289
                                     const gchar    *app_name)
290
0
{
291
0
  guint i;
292
293
0
  for (i = 0; i < desktop_file_dirs->len; i++)
294
0
    {
295
0
      DesktopFileDir *i_dir = g_ptr_array_index (desktop_file_dirs, i);
296
297
0
      if (dir == i_dir)
298
0
        return FALSE;
299
0
      if (i_dir->app_names && g_hash_table_contains (i_dir->app_names, app_name))
300
0
        return TRUE;
301
0
    }
302
303
0
  return FALSE;
304
0
}
305
306
/* Not much to go on from https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
307
 * so validate it as a non-empty alphanumeric ASCII string with `-` and `_` allowed.
308
 *
309
 * Validation is important as the desktop IDs are used to construct filenames,
310
 * and may be set by an unprivileged caller if running in a setuid program. */
311
static gboolean
312
validate_xdg_desktop (const gchar *desktop)
313
0
{
314
0
  gsize i;
315
316
0
  for (i = 0; desktop[i] != '\0'; i++)
317
0
    if (desktop[i] != '-' && desktop[i] != '_' &&
318
0
        !g_ascii_isalnum (desktop[i]))
319
0
      return FALSE;
320
321
0
  if (i == 0)
322
0
    return FALSE;
323
324
0
  return TRUE;
325
0
}
326
327
static char **
328
get_valid_current_desktops (const char *value)
329
0
{
330
0
  char **tmp;
331
0
  gsize i;
332
0
  GPtrArray *valid_desktops;
333
334
0
  if (value == NULL)
335
0
    value = g_getenv ("XDG_CURRENT_DESKTOP");
336
0
  if (value == NULL)
337
0
    value = "";
338
339
0
  tmp = g_strsplit (value, G_SEARCHPATH_SEPARATOR_S, 0);
340
0
  valid_desktops = g_ptr_array_new_full (g_strv_length (tmp) + 1, g_free);
341
0
  for (i = 0; tmp[i]; i++)
342
0
    {
343
0
      if (validate_xdg_desktop (tmp[i]))
344
0
        g_ptr_array_add (valid_desktops, tmp[i]);
345
0
      else
346
0
        g_free (tmp[i]);
347
0
    }
348
0
  g_ptr_array_add (valid_desktops, NULL);
349
0
  g_free (tmp);
350
0
  tmp = (char **) g_ptr_array_steal (valid_desktops, NULL);
351
0
  g_ptr_array_unref (valid_desktops);
352
0
  return tmp;
353
0
}
354
355
static const gchar * const *
356
get_lowercase_current_desktops (void)
357
0
{
358
0
  static gchar **result;
359
360
0
  if (g_once_init_enter_pointer (&result))
361
0
    {
362
0
      char **tmp = get_valid_current_desktops (NULL);
363
0
      gsize i, j;
364
365
0
      for (i = 0; tmp[i]; i++)
366
0
        {
367
          /* Convert to lowercase. */
368
0
          for (j = 0; tmp[i][j]; j++)
369
0
            tmp[i][j] = g_ascii_tolower (tmp[i][j]);
370
0
        }
371
372
0
      g_once_init_leave_pointer (&result, tmp);
373
0
    }
374
375
0
  return (const gchar **) result;
376
0
}
377
378
static const gchar * const *
379
get_current_desktops (const gchar *value)
380
0
{
381
0
  static gchar **result;
382
383
0
  if (g_once_init_enter_pointer (&result))
384
0
    {
385
0
      char **tmp = get_valid_current_desktops (value);
386
387
0
      g_once_init_leave_pointer (&result, tmp);
388
0
    }
389
390
0
  return (const gchar **) result;
391
0
}
392
393
/*< internal >
394
 * add_to_table_if_appropriate:
395
 * @apps: a string to GDesktopAppInfo hash table
396
 * @app_name: the name of the application
397
 * @info: a #GDesktopAppInfo, or NULL
398
 *
399
 * If @info is non-%NULL and non-hidden, then add it to @apps, using
400
 * @app_name as a key.
401
 *
402
 * If @info is non-%NULL then this function will consume the passed-in
403
 * reference.
404
 */
405
static void
406
add_to_table_if_appropriate (GHashTable      *apps,
407
                             const gchar     *app_name,
408
                             GDesktopAppInfo *info)
409
0
{
410
0
  if (!info)
411
0
    return;
412
413
0
  if (info->hidden)
414
0
    {
415
0
      g_object_unref (info);
416
0
      return;
417
0
    }
418
419
0
  g_free (info->desktop_id);
420
0
  info->desktop_id = g_strdup (app_name);
421
422
0
  g_hash_table_insert (apps, g_strdup (info->desktop_id), info);
423
0
}
424
425
enum
426
{
427
  DESKTOP_KEY_Exec,
428
  DESKTOP_KEY_GenericName,
429
  DESKTOP_KEY_Keywords,
430
  DESKTOP_KEY_Name,
431
  DESKTOP_KEY_X_GNOME_FullName,
432
433
  N_DESKTOP_KEYS
434
};
435
436
const gchar desktop_key_match_category[N_DESKTOP_KEYS] = {
437
  /* Note: lower numbers are a better match.
438
   *
439
   * In case we want two keys to match at the same level, we can just
440
   * use the same number for the two different keys.
441
   */
442
  [DESKTOP_KEY_Name]             = 1,
443
  [DESKTOP_KEY_Exec]             = 2,
444
  [DESKTOP_KEY_Keywords]         = 3,
445
  [DESKTOP_KEY_GenericName]      = 4,
446
  [DESKTOP_KEY_X_GNOME_FullName] = 5
447
};
448
449
typedef enum {
450
  /* Lower numbers have higher priority.
451
   * Prefix match should put before substring match, independently of
452
   * category relevance, i.e. a prefix match in 'Keyword' category will
453
   * come before a substring match in a more relevant category like 'Name'.
454
   */
455
  MATCH_TYPE_PREFIX = 1,
456
  MATCH_TYPE_SUBSTRING = 2
457
} MatchType;
458
459
/* Common prefix commands to ignore from Exec= lines */
460
const char * const exec_key_match_blocklist[] = {
461
  "bash",
462
  "env",
463
  "flatpak",
464
  "snap",
465
  "gjs",
466
  "pkexec",
467
  "python",
468
  "python2",
469
  "python3",
470
  "sh",
471
  "wine",
472
  "wine64",
473
  NULL
474
};
475
476
static gchar *
477
desktop_key_get_name (guint key_id)
478
0
{
479
0
  switch (key_id)
480
0
    {
481
0
    case DESKTOP_KEY_Exec:
482
0
      return "Exec";
483
0
    case DESKTOP_KEY_GenericName:
484
0
      return GENERIC_NAME_KEY;
485
0
    case DESKTOP_KEY_Keywords:
486
0
      return KEYWORDS_KEY;
487
0
    case DESKTOP_KEY_Name:
488
0
      return "Name";
489
0
    case DESKTOP_KEY_X_GNOME_FullName:
490
0
      return FULL_NAME_KEY;
491
0
    default:
492
0
      g_assert_not_reached ();
493
0
    }
494
0
}
495
496
/* Search global state {{{2
497
 *
498
 * We only ever search under a global lock, so we can use (and reuse)
499
 * some global data to reduce allocations made while searching.
500
 *
501
 * In short, we keep around arrays of results that we expand as needed
502
 * (and never shrink).
503
 *
504
 * static_token_results: this is where we append the results for each
505
 *     token within a given desktop directory, as we handle it (which is
506
 *     a union of all matches for this term)
507
 *
508
 * static_search_results: this is where we build the complete results
509
 *     for a single directory (which is an intersection of the matches
510
 *     found for each term)
511
 *
512
 * static_total_results: this is where we build the complete results
513
 *     across all directories (which is a union of the matches found in
514
 *     each directory)
515
 *
516
 * The app_names that enter these tables are always pointer-unique (in
517
 * the sense that string equality is the same as pointer equality).
518
 * This can be guaranteed for two reasons:
519
 *
520
 *   - we mask appids so that a given appid will only ever appear within
521
 *     the highest-precedence directory that contains it.  We never
522
 *     return search results from a lower-level directory if a desktop
523
 *     file exists in a higher-level one.
524
 *
525
 *   - within a given directory, the string is unique because it's the
526
 *     key in the hashtable of all app_ids for that directory.
527
 *
528
 * We perform a merging of the results in merge_token_results().  This
529
 * works by ordering the two lists and moving through each of them (at
530
 * the same time) looking for common elements, rejecting uncommon ones.
531
 * "Order" here need not mean any particular thing, as long as it is
532
 * some order.  Because of the uniqueness of our strings, we can use
533
 * pointer order.  That's what's going on in compare_results() below.
534
 */
535
struct search_result
536
{
537
  const gchar *app_name;
538
  gint         category;
539
  gint         match_type;
540
  gint         token_pos;
541
};
542
543
static struct search_result *static_token_results;
544
static size_t                static_token_results_size;
545
static size_t                static_token_results_allocated;
546
static struct search_result *static_search_results;
547
static size_t                static_search_results_size;
548
static size_t                static_search_results_allocated;
549
static struct search_result *static_total_results;
550
static size_t                static_total_results_size;
551
static size_t                static_total_results_allocated;
552
553
/* And some functions for performing nice operations against it */
554
static gint
555
compare_results (gconstpointer a,
556
                 gconstpointer b)
557
0
{
558
0
  const struct search_result *ra = a;
559
0
  const struct search_result *rb = b;
560
561
0
  if (ra->app_name < rb->app_name)
562
0
    {
563
0
      return -1;
564
0
    }
565
0
  else if (ra->app_name > rb->app_name)
566
0
    {
567
0
      return 1;
568
0
    }
569
0
  else
570
0
    {
571
      /* We prioritize prefix matches over category relevance e.g. a prefix match in 'Keyword'
572
       * category is better than a substring match in a more relevance category like 'Name'.
573
       */
574
0
      if (ra->match_type != rb->match_type)
575
0
        return ra->match_type - rb->match_type;
576
577
0
      return ra->category - rb->category;
578
0
    }
579
0
}
580
581
static gint
582
compare_categories (gconstpointer a,
583
                    gconstpointer b)
584
0
{
585
0
  const struct search_result *ra = a;
586
0
  const struct search_result *rb = b;
587
588
  /* We prioritize prefix matches over category relevance e.g. a prefix match in 'Keyword'
589
   * category is better than a substring match in a more relevance category like 'Name'.
590
   */
591
0
  if (ra->match_type != rb->match_type)
592
0
    return ra->match_type - rb->match_type;
593
594
0
  if (ra->category != rb->category)
595
0
    return ra->category - rb->category;
596
597
  /* We prefer matches that occur earlier in the string. Eg. this will match 'Calculator'
598
   * before 'LibreOffice Calc' when searching for 'calc'.
599
   */
600
0
  return ra->token_pos - rb->token_pos;
601
0
}
602
603
static void
604
add_token_result (const gchar *app_name,
605
                  guint16      category,
606
                  guint16      match_type,
607
                  guint16      token_pos)
608
0
{
609
0
  if G_UNLIKELY (static_token_results_size == static_token_results_allocated)
610
0
    {
611
0
      static_token_results_allocated = MAX (16, static_token_results_allocated * 2);
612
0
      static_token_results = g_renew (struct search_result, static_token_results, static_token_results_allocated);
613
0
    }
614
615
0
  static_token_results[static_token_results_size].app_name = app_name;
616
0
  static_token_results[static_token_results_size].category = category;
617
0
  static_token_results[static_token_results_size].match_type = match_type;
618
0
  static_token_results[static_token_results_size].token_pos = token_pos;
619
0
  static_token_results_size++;
620
0
}
621
622
static void
623
merge_token_results (gboolean first)
624
0
{
625
0
  if (static_token_results_size != 0)
626
0
    qsort (static_token_results, static_token_results_size, sizeof (struct search_result), compare_results);
627
628
  /* If this is the first token then we are basically merging a list with
629
   * itself -- we only perform de-duplication.
630
   *
631
   * If this is not the first token then we are doing a real merge.
632
   */
633
0
  if (first)
634
0
    {
635
0
      const gchar *last_name = NULL;
636
637
      /* We must de-duplicate, but we do so by taking the best category
638
       * in each case.
639
       *
640
       * The final list can be as large as the input here, so make sure
641
       * we have enough room (even if it's too much room).
642
       */
643
644
0
      if G_UNLIKELY (static_search_results_allocated < static_token_results_size)
645
0
        {
646
0
          static_search_results_allocated = static_token_results_allocated;
647
0
          static_search_results = g_renew (struct search_result,
648
0
                                           static_search_results,
649
0
                                           static_search_results_allocated);
650
0
        }
651
652
0
      for (size_t i = 0; i < static_token_results_size; i++)
653
0
        {
654
          /* The list is sorted so that the best match for a given id
655
           * will be at the front, so once we have copied an id, skip
656
           * the rest of the entries for the same id.
657
           */
658
0
          if (static_token_results[i].app_name == last_name)
659
0
            continue;
660
661
0
          last_name = static_token_results[i].app_name;
662
663
0
          static_search_results[static_search_results_size++] = static_token_results[i];
664
0
        }
665
0
    }
666
0
  else
667
0
    {
668
0
      const gchar *last_name = NULL;
669
0
      size_t j = 0, k = 0;
670
671
      /* We only ever remove items from the results list, so no need to
672
       * resize to ensure that we have enough room.
673
       */
674
0
      for (size_t i = 0; i < static_token_results_size; i++)
675
0
        {
676
0
          if (static_token_results[i].app_name == last_name)
677
0
            continue;
678
679
0
          last_name = static_token_results[i].app_name;
680
681
          /* Now we only want to have a result in static_search_results
682
           * if we already have it there *and* we have it in
683
           * static_token_results as well.  The category will be the
684
           * lesser of the two.
685
           *
686
           * Skip past the results in static_search_results that are not
687
           * going to be matches.
688
           */
689
0
          while (k < static_search_results_size &&
690
0
                 static_search_results[k].app_name < static_token_results[i].app_name)
691
0
            k++;
692
693
0
          if (k < static_search_results_size &&
694
0
              static_search_results[k].app_name == static_token_results[i].app_name)
695
0
            {
696
              /* We have a match.
697
               *
698
               * Category should be the worse of the two (ie:
699
               * numerically larger).
700
               *
701
               * Match type should also be the worse, so if an app has two
702
               * prefix matches it will has higher priority than one prefix
703
               * matches and one substring matches, for example, LibreOffice
704
               * Writer should be higher priority than LibreOffice Draw with
705
               * `lib w`.
706
               *
707
               * We prioritize tokens that occur near the start of the string
708
               * over tokens that appear near the end.
709
               *
710
               * (This ignores the difference between partly prefix matches and
711
               * all substring matches, however most time we just focus on exact
712
               * prefix matches, who cares the 10th-20th search results?)
713
               */
714
0
              static_search_results[j].app_name = static_search_results[k].app_name;
715
0
              static_search_results[j].category = MAX (static_search_results[k].category,
716
0
                                                       static_token_results[i].category);
717
0
              static_search_results[j].match_type = MAX (static_search_results[k].match_type,
718
0
                                                         static_token_results[i].match_type);
719
0
              static_search_results[j].token_pos = MAX (static_search_results[k].token_pos,
720
0
                                                        static_token_results[i].token_pos);
721
0
              j++;
722
0
            }
723
0
        }
724
725
0
      static_search_results_size = j;
726
0
    }
727
728
  /* Clear it out for next time... */
729
0
  static_token_results_size = 0;
730
0
}
731
732
static void
733
reset_total_search_results (void)
734
0
{
735
0
  static_total_results_size = 0;
736
0
}
737
738
static void
739
sort_total_search_results (void)
740
0
{
741
0
  if (static_total_results_size != 0)
742
0
    qsort (static_total_results, static_total_results_size, sizeof (struct search_result), compare_categories);
743
0
}
744
745
static void
746
merge_directory_results (void)
747
0
{
748
0
  if G_UNLIKELY (static_total_results_size + static_search_results_size > static_total_results_allocated)
749
0
    {
750
0
      static_total_results_allocated = MAX (16, static_total_results_allocated);
751
0
      while (static_total_results_allocated < static_total_results_size + static_search_results_size)
752
0
        static_total_results_allocated *= 2;
753
0
      static_total_results = g_renew (struct search_result, static_total_results, static_total_results_allocated);
754
0
    }
755
756
0
  if (static_search_results_size != 0)
757
0
    memcpy (static_total_results + static_total_results_size,
758
0
            static_search_results,
759
0
            static_search_results_size * sizeof (struct search_result));
760
761
0
  static_total_results_size += static_search_results_size;
762
763
  /* Clear it out for next time... */
764
0
  static_search_results_size = 0;
765
0
}
766
767
/* Support for unindexed DesktopFileDirs {{{2 */
768
static void
769
get_apps_from_dir (GHashTable **apps,
770
                   const char  *dirname,
771
                   const char  *prefix)
772
0
{
773
0
  const char *basename;
774
0
  GDir *dir;
775
776
0
  dir = g_dir_open (dirname, 0, NULL);
777
778
0
  if (dir == NULL)
779
0
    return;
780
781
0
  while ((basename = g_dir_read_name (dir)) != NULL)
782
0
    {
783
0
      gchar *filename;
784
785
0
      filename = g_build_filename (dirname, basename, NULL);
786
787
0
      if (g_str_has_suffix (basename, ".desktop"))
788
0
        {
789
0
          gchar *app_name;
790
791
0
          app_name = g_strconcat (prefix, basename, NULL);
792
793
0
          if (*apps == NULL)
794
0
            *apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
795
796
0
          g_hash_table_insert (*apps, app_name, g_strdup (filename));
797
0
        }
798
0
      else if (g_file_test (filename, G_FILE_TEST_IS_DIR))
799
0
        {
800
0
          gchar *subprefix;
801
802
0
          subprefix = g_strconcat (prefix, basename, "-", NULL);
803
0
          get_apps_from_dir (apps, filename, subprefix);
804
0
          g_free (subprefix);
805
0
        }
806
807
0
      g_free (filename);
808
0
    }
809
810
0
  g_dir_close (dir);
811
0
}
812
813
typedef struct
814
{
815
  gchar **additions;
816
  gchar **removals;
817
  gchar **defaults;
818
} UnindexedMimeTweaks;
819
820
static void
821
free_mime_tweaks (gpointer data)
822
0
{
823
0
  UnindexedMimeTweaks *tweaks = data;
824
825
0
  g_strfreev (tweaks->additions);
826
0
  g_strfreev (tweaks->removals);
827
0
  g_strfreev (tweaks->defaults);
828
829
0
  g_slice_free (UnindexedMimeTweaks, tweaks);
830
0
}
831
832
static UnindexedMimeTweaks *
833
desktop_file_dir_unindexed_get_tweaks (DesktopFileDir *dir,
834
                                       const gchar    *mime_type)
835
0
{
836
0
  UnindexedMimeTweaks *tweaks;
837
0
  gchar *unaliased_type;
838
839
0
  unaliased_type = _g_unix_content_type_unalias (mime_type);
840
0
  tweaks = g_hash_table_lookup (dir->mime_tweaks, unaliased_type);
841
842
0
  if (tweaks == NULL)
843
0
    {
844
0
      tweaks = g_slice_new0 (UnindexedMimeTweaks);
845
0
      g_hash_table_insert (dir->mime_tweaks, unaliased_type, tweaks);
846
0
    }
847
0
  else
848
0
    g_free (unaliased_type);
849
850
0
  return tweaks;
851
0
}
852
853
/* consumes 'to_add' */
854
static void
855
expand_strv (gchar         ***strv_ptr,
856
             gchar          **to_add,
857
             gchar * const   *blocklist)
858
0
{
859
0
  guint strv_len, add_len;
860
0
  gchar **strv;
861
0
  guint i, j;
862
863
0
  if (!*strv_ptr)
864
0
    {
865
0
      *strv_ptr = to_add;
866
0
      return;
867
0
    }
868
869
0
  strv = *strv_ptr;
870
0
  strv_len = g_strv_length (strv);
871
0
  add_len = g_strv_length (to_add);
872
0
  strv = g_renew (gchar *, strv, strv_len + add_len + 1);
873
874
0
  for (i = 0; to_add[i]; i++)
875
0
    {
876
      /* Don't add blocklisted strings */
877
0
      if (blocklist)
878
0
        for (j = 0; blocklist[j]; j++)
879
0
          if (g_str_equal (to_add[i], blocklist[j]))
880
0
            goto no_add;
881
882
      /* Don't add duplicates already in the list */
883
0
      for (j = 0; j < strv_len; j++)
884
0
        if (g_str_equal (to_add[i], strv[j]))
885
0
          goto no_add;
886
887
0
      strv[strv_len++] = to_add[i];
888
0
      continue;
889
890
0
no_add:
891
0
      g_free (to_add[i]);
892
0
    }
893
894
0
  strv[strv_len] = NULL;
895
0
  *strv_ptr = strv;
896
897
0
  g_free (to_add);
898
0
}
899
900
static void
901
desktop_file_dir_unindexed_read_mimeapps_list (DesktopFileDir *dir,
902
                                               const gchar    *filename,
903
                                               const gchar    *added_group,
904
                                               gboolean        tweaks_permitted)
905
0
{
906
0
  UnindexedMimeTweaks *tweaks;
907
0
  char **desktop_file_ids;
908
0
  GKeyFile *key_file;
909
0
  gchar **mime_types;
910
0
  int i;
911
912
0
  key_file = g_key_file_new ();
913
0
  if (!g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL))
914
0
    {
915
0
      g_key_file_free (key_file);
916
0
      return;
917
0
    }
918
919
0
  mime_types = g_key_file_get_keys (key_file, added_group, NULL, NULL);
920
921
0
  if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
922
0
    {
923
0
      g_warning ("%s contains a [%s] group, but it is not permitted here.  Only the non-desktop-specific "
924
0
                 "mimeapps.list file may add or remove associations.", filename, added_group);
925
0
      g_strfreev (mime_types);
926
0
      mime_types = NULL;
927
0
    }
928
929
0
  if (mime_types != NULL)
930
0
    {
931
0
      for (i = 0; mime_types[i] != NULL; i++)
932
0
        {
933
0
          desktop_file_ids = g_key_file_get_string_list (key_file, added_group, mime_types[i], NULL, NULL);
934
935
0
          if (desktop_file_ids)
936
0
            {
937
0
              tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
938
0
              expand_strv (&tweaks->additions, desktop_file_ids, tweaks->removals);
939
0
            }
940
0
        }
941
942
0
      g_strfreev (mime_types);
943
0
    }
944
945
0
  mime_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
946
947
0
  if G_UNLIKELY (mime_types != NULL && !tweaks_permitted)
948
0
    {
949
0
      g_warning ("%s contains a [%s] group, but it is not permitted here.  Only the non-desktop-specific "
950
0
                 "mimeapps.list file may add or remove associations.", filename, REMOVED_ASSOCIATIONS_GROUP);
951
0
      g_strfreev (mime_types);
952
0
      mime_types = NULL;
953
0
    }
954
955
0
  if (mime_types != NULL)
956
0
    {
957
0
      for (i = 0; mime_types[i] != NULL; i++)
958
0
        {
959
0
          desktop_file_ids = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP, mime_types[i], NULL, NULL);
960
961
0
          if (desktop_file_ids)
962
0
            {
963
0
              tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
964
0
              expand_strv (&tweaks->removals, desktop_file_ids, tweaks->additions);
965
0
            }
966
0
        }
967
968
0
      g_strfreev (mime_types);
969
0
    }
970
971
0
  mime_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
972
973
0
  if (mime_types != NULL)
974
0
    {
975
0
      for (i = 0; mime_types[i] != NULL; i++)
976
0
        {
977
0
          desktop_file_ids = g_key_file_get_string_list (key_file, DEFAULT_APPLICATIONS_GROUP, mime_types[i], NULL, NULL);
978
979
0
          if (desktop_file_ids)
980
0
            {
981
0
              tweaks = desktop_file_dir_unindexed_get_tweaks (dir, mime_types[i]);
982
0
              expand_strv (&tweaks->defaults, desktop_file_ids, NULL);
983
0
            }
984
0
        }
985
986
0
      g_strfreev (mime_types);
987
0
    }
988
989
0
  g_key_file_free (key_file);
990
0
}
991
992
static void
993
desktop_file_dir_unindexed_read_mimeapps_lists (DesktopFileDir *dir)
994
0
{
995
0
  const gchar * const *desktops;
996
0
  gchar *filename;
997
0
  gint i;
998
999
0
  dir->mime_tweaks = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, free_mime_tweaks);
1000
1001
  /* We process in order of precedence, using a blocklisting approach to
1002
   * avoid recording later instructions that conflict with ones we found
1003
   * earlier.
1004
   *
1005
   * We first start with the XDG_CURRENT_DESKTOP files, in precedence
1006
   * order.
1007
   */
1008
0
  desktops = get_lowercase_current_desktops ();
1009
0
  for (i = 0; desktops[i]; i++)
1010
0
    {
1011
0
      filename = g_strdup_printf ("%s/%s-mimeapps.list", dir->path, desktops[i]);
1012
0
      desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
1013
0
      g_free (filename);
1014
0
    }
1015
1016
  /* Next, the non-desktop-specific mimeapps.list */
1017
0
  filename = g_strdup_printf ("%s/mimeapps.list", dir->path);
1018
0
  desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, TRUE);
1019
0
  g_free (filename);
1020
1021
  /* The remaining files are only checked for in directories that might
1022
   * contain desktop files (ie: not the config dirs).
1023
   */
1024
0
  if (dir->is_config)
1025
0
    return;
1026
1027
  /* We have 'defaults.list' which was only ever understood by GLib.  It
1028
   * exists widely, but it has never been part of any spec and it should
1029
   * be treated as deprecated.  This will be removed in a future
1030
   * version.
1031
   */
1032
0
  filename = g_strdup_printf ("%s/defaults.list", dir->path);
1033
0
  desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, ADDED_ASSOCIATIONS_GROUP, FALSE);
1034
0
  g_free (filename);
1035
1036
  /* Finally, the mimeinfo.cache, which is just a cached copy of what we
1037
   * would find in the MimeTypes= lines of all of the desktop files.
1038
   */
1039
0
  filename = g_strdup_printf ("%s/mimeinfo.cache", dir->path);
1040
0
  desktop_file_dir_unindexed_read_mimeapps_list (dir, filename, MIME_CACHE_GROUP, TRUE);
1041
0
  g_free (filename);
1042
0
}
1043
1044
static void
1045
desktop_file_dir_unindexed_init (DesktopFileDir *dir)
1046
0
{
1047
0
  if (!dir->is_config)
1048
0
    get_apps_from_dir (&dir->app_names, dir->path, "");
1049
1050
0
  desktop_file_dir_unindexed_read_mimeapps_lists (dir);
1051
0
}
1052
1053
static GDesktopAppInfo *
1054
g_desktop_app_info_new_from_filename_unlocked (const char *filename)
1055
0
{
1056
0
  GDesktopAppInfo *info = NULL;
1057
1058
0
  info = g_object_new (G_TYPE_DESKTOP_APP_INFO, "filename", filename, NULL);
1059
1060
0
  if (!g_desktop_app_info_load_file (info))
1061
0
    g_clear_object (&info);
1062
1063
0
  return info;
1064
0
}
1065
1066
static GDesktopAppInfo *
1067
desktop_file_dir_unindexed_get_app (DesktopFileDir *dir,
1068
                                    const gchar    *desktop_id)
1069
0
{
1070
0
  const gchar *filename;
1071
1072
0
  filename = g_hash_table_lookup (dir->app_names, desktop_id);
1073
1074
0
  if (!filename)
1075
0
    return NULL;
1076
1077
0
  return g_desktop_app_info_new_from_filename_unlocked (filename);
1078
0
}
1079
1080
static void
1081
desktop_file_dir_unindexed_get_all (DesktopFileDir *dir,
1082
                                    GHashTable     *apps)
1083
0
{
1084
0
  GHashTableIter iter;
1085
0
  gpointer app_name;
1086
0
  gpointer filename;
1087
1088
0
  if (dir->app_names == NULL)
1089
0
    return;
1090
1091
0
  g_hash_table_iter_init (&iter, dir->app_names);
1092
0
  while (g_hash_table_iter_next (&iter, &app_name, &filename))
1093
0
    {
1094
0
      if (desktop_file_dir_app_name_is_masked (dir, app_name))
1095
0
        continue;
1096
1097
0
      add_to_table_if_appropriate (apps, app_name, g_desktop_app_info_new_from_filename_unlocked (filename));
1098
0
    }
1099
0
}
1100
1101
typedef struct _MemoryIndexEntry MemoryIndexEntry;
1102
typedef GHashTable MemoryIndex;
1103
1104
struct _MemoryIndexEntry
1105
{
1106
  const gchar      *app_name; /* pointer to the hashtable key */
1107
  gint              match_category; /* the entry key (Name, Exec, ...) */
1108
  gint              token_pos; /* the position of the token in the field */
1109
  MemoryIndexEntry *next;
1110
};
1111
1112
static void
1113
memory_index_entry_free (gpointer data)
1114
0
{
1115
0
  MemoryIndexEntry *mie = data;
1116
1117
0
  while (mie)
1118
0
    {
1119
0
      MemoryIndexEntry *next = mie->next;
1120
1121
0
      g_slice_free (MemoryIndexEntry, mie);
1122
0
      mie = next;
1123
0
    }
1124
0
}
1125
1126
static void
1127
memory_index_add_token (MemoryIndex *mi,
1128
                        const gchar *token,
1129
                        gint         match_category,
1130
                        gint         token_pos,
1131
                        const gchar *app_name)
1132
0
{
1133
0
  MemoryIndexEntry *mie, *first;
1134
1135
0
  mie = g_slice_new (MemoryIndexEntry);
1136
0
  mie->app_name = app_name;
1137
0
  mie->match_category = match_category;
1138
0
  mie->token_pos = token_pos;
1139
1140
0
  first = g_hash_table_lookup (mi, token);
1141
1142
0
  if (first)
1143
0
    {
1144
0
      mie->next = first->next;
1145
0
      first->next = mie;
1146
0
    }
1147
0
  else
1148
0
    {
1149
0
      mie->next = NULL;
1150
0
      g_hash_table_insert (mi, g_strdup (token), mie);
1151
0
    }
1152
0
}
1153
1154
static void
1155
memory_index_add_string (MemoryIndex *mi,
1156
                         const gchar *string,
1157
                         gint         match_category,
1158
                         const gchar *app_name)
1159
0
{
1160
0
  gchar **tokens, **alternates;
1161
0
  gint i, n;
1162
1163
0
  tokens = g_str_tokenize_and_fold (string, NULL, &alternates);
1164
1165
0
  for (i = 0; tokens[i]; i++)
1166
0
    memory_index_add_token (mi, tokens[i], match_category, i, app_name);
1167
1168
0
  n = i;
1169
0
  for (i = 0; alternates[i]; i++)
1170
0
    memory_index_add_token (mi, alternates[i], match_category, n + i, app_name);
1171
1172
0
  g_strfreev (alternates);
1173
0
  g_strfreev (tokens);
1174
0
}
1175
1176
static MemoryIndex *
1177
memory_index_new (void)
1178
0
{
1179
0
  return g_hash_table_new_full (g_str_hash, g_str_equal, g_free, memory_index_entry_free);
1180
0
}
1181
1182
static void
1183
desktop_file_dir_unindexed_setup_search (DesktopFileDir *dir)
1184
0
{
1185
0
  GHashTableIter iter;
1186
0
  gpointer app, path;
1187
1188
0
  dir->memory_index = memory_index_new ();
1189
0
  dir->memory_implementations = memory_index_new ();
1190
1191
  /* Nothing to search? */
1192
0
  if (dir->app_names == NULL)
1193
0
    return;
1194
1195
0
  g_hash_table_iter_init (&iter, dir->app_names);
1196
0
  while (g_hash_table_iter_next (&iter, &app, &path))
1197
0
    {
1198
0
      GKeyFile *key_file;
1199
1200
0
      if (desktop_file_dir_app_name_is_masked (dir, app))
1201
0
        continue;
1202
1203
0
      key_file = g_key_file_new ();
1204
1205
0
      if (g_key_file_load_from_file (key_file, path, G_KEY_FILE_NONE, NULL) &&
1206
0
          !g_key_file_get_boolean (key_file, "Desktop Entry", "Hidden", NULL))
1207
0
        {
1208
          /* Index the interesting keys... */
1209
0
          gchar **implements;
1210
0
          gsize i;
1211
1212
0
          for (i = 0; i < G_N_ELEMENTS (desktop_key_match_category); i++)
1213
0
            {
1214
0
              const gchar *value;
1215
0
              gchar *raw;
1216
1217
0
              if (!desktop_key_match_category[i])
1218
0
                continue;
1219
1220
0
              raw = g_key_file_get_locale_string (key_file, "Desktop Entry", desktop_key_get_name (i), NULL, NULL);
1221
0
              value = raw;
1222
1223
0
              if (i == DESKTOP_KEY_Exec && raw != NULL)
1224
0
                {
1225
                  /* Special handling: only match basename of first field */
1226
0
                  gchar *space;
1227
0
                  gchar *slash;
1228
1229
                  /* Remove extra arguments, if any */
1230
0
                  space = raw + strcspn (raw, " \t\n"); /* IFS */
1231
0
                  *space = '\0';
1232
1233
                  /* Skip the pathname, if any */
1234
0
                  if ((slash = strrchr (raw, '/')))
1235
0
                    value = slash + 1;
1236
1237
                  /* Don't match on blocklisted binaries like interpreters */
1238
0
                  if (g_strv_contains (exec_key_match_blocklist, value))
1239
0
        value = NULL;
1240
0
                }
1241
1242
0
              if (value)
1243
0
                memory_index_add_string (dir->memory_index, value, desktop_key_match_category[i], app);
1244
1245
0
              g_free (raw);
1246
0
            }
1247
1248
          /* Make note of the Implements= line */
1249
0
          implements = g_key_file_get_string_list (key_file, "Desktop Entry", "Implements", NULL, NULL);
1250
0
          for (i = 0; implements && implements[i]; i++)
1251
0
            memory_index_add_token (dir->memory_implementations, implements[i], i, 0, app);
1252
0
          g_strfreev (implements);
1253
0
        }
1254
1255
0
      g_key_file_free (key_file);
1256
0
    }
1257
0
}
1258
1259
static void
1260
desktop_file_dir_unindexed_search (DesktopFileDir  *dir,
1261
                                   const gchar     *search_token)
1262
0
{
1263
0
  GHashTableIter iter;
1264
0
  gpointer key, value;
1265
1266
0
  g_assert (search_token != NULL);
1267
1268
0
  if (!dir->memory_index)
1269
0
    desktop_file_dir_unindexed_setup_search (dir);
1270
1271
0
  g_hash_table_iter_init (&iter, dir->memory_index);
1272
0
  while (g_hash_table_iter_next (&iter, &key, &value))
1273
0
    {
1274
0
      MemoryIndexEntry *mie = value;
1275
0
      const char *p;
1276
0
      MatchType match_type;
1277
1278
      /* strstr(haystack, needle) returns haystack if needle is empty, so if
1279
       * needle is not empty and return value equals to haystack means a prefix
1280
       * match.
1281
       */
1282
0
      p = strstr (key, search_token);
1283
0
      if (p == NULL)
1284
0
        continue;
1285
0
      else if (p == key && *search_token != '\0')
1286
0
        match_type = MATCH_TYPE_PREFIX;
1287
0
      else
1288
0
        match_type = MATCH_TYPE_SUBSTRING;
1289
1290
0
      while (mie)
1291
0
        {
1292
0
          add_token_result (mie->app_name, mie->match_category, match_type, mie->token_pos);
1293
0
          mie = mie->next;
1294
0
        }
1295
0
    }
1296
0
}
1297
1298
static gboolean
1299
array_contains (GPtrArray *array,
1300
                const gchar *str)
1301
0
{
1302
0
  guint i;
1303
1304
0
  for (i = 0; i < array->len; i++)
1305
0
    if (g_str_equal (array->pdata[i], str))
1306
0
      return TRUE;
1307
1308
0
  return FALSE;
1309
0
}
1310
1311
static void
1312
desktop_file_dir_unindexed_mime_lookup (DesktopFileDir *dir,
1313
                                        const gchar    *mime_type,
1314
                                        GPtrArray      *hits,
1315
                                        GPtrArray      *blocklist)
1316
0
{
1317
0
  UnindexedMimeTweaks *tweaks;
1318
0
  gint i;
1319
1320
0
  tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1321
1322
0
  if (!tweaks)
1323
0
    return;
1324
1325
0
  if (tweaks->additions)
1326
0
    {
1327
0
      for (i = 0; tweaks->additions[i]; i++)
1328
0
        {
1329
0
          gchar *app_name = tweaks->additions[i];
1330
1331
0
          if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1332
0
              !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1333
0
            g_ptr_array_add (hits, app_name);
1334
0
        }
1335
0
    }
1336
1337
0
  if (tweaks->removals)
1338
0
    {
1339
0
      for (i = 0; tweaks->removals[i]; i++)
1340
0
        {
1341
0
          gchar *app_name = tweaks->removals[i];
1342
1343
0
          if (!desktop_file_dir_app_name_is_masked (dir, app_name) &&
1344
0
              !array_contains (blocklist, app_name) && !array_contains (hits, app_name))
1345
0
            g_ptr_array_add (blocklist, app_name);
1346
0
        }
1347
0
    }
1348
0
}
1349
1350
static void
1351
desktop_file_dir_unindexed_default_lookup (DesktopFileDir *dir,
1352
                                           const gchar    *mime_type,
1353
                                           GPtrArray      *results)
1354
0
{
1355
0
  UnindexedMimeTweaks *tweaks;
1356
0
  gint i;
1357
1358
0
  tweaks = g_hash_table_lookup (dir->mime_tweaks, mime_type);
1359
1360
0
  if (!tweaks || !tweaks->defaults)
1361
0
    return;
1362
1363
0
  for (i = 0; tweaks->defaults[i]; i++)
1364
0
    {
1365
0
      gchar *app_name = tweaks->defaults[i];
1366
1367
0
      if (!array_contains (results, app_name))
1368
0
        g_ptr_array_add (results, app_name);
1369
0
    }
1370
0
}
1371
1372
static void
1373
desktop_file_dir_unindexed_get_implementations (DesktopFileDir  *dir,
1374
                                                GList          **results,
1375
                                                const gchar     *interface)
1376
0
{
1377
0
  MemoryIndexEntry *mie;
1378
1379
0
  if (!dir->memory_index)
1380
0
    desktop_file_dir_unindexed_setup_search (dir);
1381
1382
0
  for (mie = g_hash_table_lookup (dir->memory_implementations, interface); mie; mie = mie->next)
1383
0
    *results = g_list_prepend (*results, g_strdup (mie->app_name));
1384
0
}
1385
1386
/* DesktopFileDir "API" {{{2 */
1387
1388
/*< internal >
1389
 * desktop_file_dir_new:
1390
 * @data_dir: an XDG_DATA_DIR
1391
 *
1392
 * Creates a #DesktopFileDir for the corresponding @data_dir.
1393
 */
1394
static DesktopFileDir *
1395
desktop_file_dir_new (const gchar *data_dir)
1396
0
{
1397
0
  DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1398
1399
0
  g_atomic_ref_count_init (&dir->ref_count);
1400
0
  dir->path = g_build_filename (data_dir, "applications", NULL);
1401
1402
0
  return g_steal_pointer (&dir);
1403
0
}
1404
1405
/*< internal >
1406
 * desktop_file_dir_new_for_config:
1407
 * @config_dir: an XDG_CONFIG_DIR
1408
 *
1409
 * Just the same as desktop_file_dir_new() except that it does not
1410
 * add the "applications" directory.  It also marks the directory as
1411
 * config-only, which prevents us from attempting to find desktop files
1412
 * here.
1413
 */
1414
static DesktopFileDir *
1415
desktop_file_dir_new_for_config (const gchar *config_dir)
1416
0
{
1417
0
  DesktopFileDir *dir = g_new0 (DesktopFileDir, 1);
1418
1419
0
  g_atomic_ref_count_init (&dir->ref_count);
1420
0
  dir->path = g_strdup (config_dir);
1421
0
  dir->is_config = TRUE;
1422
1423
0
  return g_steal_pointer (&dir);
1424
0
}
1425
1426
/*< internal >
1427
 * desktop_file_dir_reset:
1428
 * @dir: a #DesktopFileDir
1429
 *
1430
 * Cleans up @dir, releasing most resources that it was using.
1431
 */
1432
static void
1433
desktop_file_dir_reset (DesktopFileDir *dir)
1434
0
{
1435
0
  if (dir->alternatively_watching)
1436
0
    {
1437
0
      g_free (dir->alternatively_watching);
1438
0
      dir->alternatively_watching = NULL;
1439
0
    }
1440
1441
0
  if (dir->monitor)
1442
0
    {
1443
0
      g_signal_handlers_disconnect_by_func (dir->monitor, desktop_file_dir_changed, dir);
1444
0
      g_file_monitor_cancel (dir->monitor);
1445
0
      g_object_unref (dir->monitor);
1446
0
      dir->monitor = NULL;
1447
0
    }
1448
1449
0
  if (dir->app_names)
1450
0
    {
1451
0
      g_hash_table_unref (dir->app_names);
1452
0
      dir->app_names = NULL;
1453
0
    }
1454
1455
0
  if (dir->memory_index)
1456
0
    {
1457
0
      g_hash_table_unref (dir->memory_index);
1458
0
      dir->memory_index = NULL;
1459
0
    }
1460
1461
0
  if (dir->mime_tweaks)
1462
0
    {
1463
0
      g_hash_table_unref (dir->mime_tweaks);
1464
0
      dir->mime_tweaks = NULL;
1465
0
    }
1466
1467
0
  if (dir->memory_implementations)
1468
0
    {
1469
0
      g_hash_table_unref (dir->memory_implementations);
1470
0
      dir->memory_implementations = NULL;
1471
0
    }
1472
1473
0
  dir->is_setup = FALSE;
1474
0
}
1475
1476
static void
1477
closure_notify_cb (gpointer  data,
1478
                   GClosure *closure)
1479
0
{
1480
0
  DesktopFileDir *dir = data;
1481
0
  desktop_file_dir_unref (dir);
1482
0
}
1483
1484
/*< internal >
1485
 * desktop_file_dir_init:
1486
 * @dir: a #DesktopFileDir
1487
 *
1488
 * Does initial setup for @dir
1489
 *
1490
 * You should only call this if @dir is not already setup.
1491
 */
1492
static void
1493
desktop_file_dir_init (DesktopFileDir *dir)
1494
0
{
1495
0
  const gchar *watch_dir;
1496
1497
0
  g_assert (!dir->is_setup);
1498
1499
0
  g_assert (!dir->alternatively_watching);
1500
0
  g_assert (!dir->monitor);
1501
1502
0
  dir->alternatively_watching = desktop_file_dir_get_alternative_dir (dir);
1503
0
  watch_dir = dir->alternatively_watching ? dir->alternatively_watching : dir->path;
1504
1505
  /* There is a very thin race here if the watch_dir has been _removed_
1506
   * between when we checked for it and when we establish the watch.
1507
   * Removes probably don't happen in usual operation, and even if it
1508
   * does (and we catch the unlikely race), the only degradation is that
1509
   * we will fall back to polling.
1510
   */
1511
0
  dir->monitor = g_local_file_monitor_new_in_worker (watch_dir, TRUE, G_FILE_MONITOR_NONE,
1512
0
                                                     desktop_file_dir_changed,
1513
0
                                                     desktop_file_dir_ref (dir),
1514
0
                                                     closure_notify_cb, NULL);
1515
1516
0
  desktop_file_dir_unindexed_init (dir);
1517
1518
0
  dir->is_setup = TRUE;
1519
0
}
1520
1521
/*< internal >
1522
 * desktop_file_dir_get_app:
1523
 * @dir: a DesktopFileDir
1524
 * @desktop_id: the desktop ID to load
1525
 *
1526
 * Creates the #GDesktopAppInfo for the given @desktop_id if it exists
1527
 * within @dir, even if it is hidden.
1528
 *
1529
 * This function does not check if @desktop_id would be masked by a
1530
 * directory with higher precedence.  The caller must do so.
1531
 */
1532
static GDesktopAppInfo *
1533
desktop_file_dir_get_app (DesktopFileDir *dir,
1534
                          const gchar    *desktop_id)
1535
0
{
1536
0
  if (!dir->app_names)
1537
0
    return NULL;
1538
1539
0
  return desktop_file_dir_unindexed_get_app (dir, desktop_id);
1540
0
}
1541
1542
/*< internal >
1543
 * desktop_file_dir_get_all:
1544
 * @dir: a DesktopFileDir
1545
 * @apps: a #GHashTable<string, GDesktopAppInfo>
1546
 *
1547
 * Loads all desktop files in @dir and adds them to @apps, careful to
1548
 * ensure we don't add any files masked by a similarly-named file in a
1549
 * higher-precedence directory.
1550
 */
1551
static void
1552
desktop_file_dir_get_all (DesktopFileDir *dir,
1553
                          GHashTable     *apps)
1554
0
{
1555
0
  desktop_file_dir_unindexed_get_all (dir, apps);
1556
0
}
1557
1558
/*< internal >
1559
 * desktop_file_dir_mime_lookup:
1560
 * @dir: a #DesktopFileDir
1561
 * @mime_type: the mime type to look up
1562
 * @hits: the array to store the hits
1563
 * @blocklist: the array to store the blocklist
1564
 *
1565
 * Does a lookup of a mimetype against one desktop file directory,
1566
 * recording any hits and blocklisting and "Removed" associations (so
1567
 * later directories don't record them as hits).
1568
 *
1569
 * The items added to @hits are duplicated, but the ones in @blocklist
1570
 * are weak pointers.  This facilitates simply freeing the blocklist
1571
 * (which is only used for internal bookkeeping) but using the pdata of
1572
 * @hits as the result of the operation.
1573
 */
1574
static void
1575
desktop_file_dir_mime_lookup (DesktopFileDir *dir,
1576
                              const gchar    *mime_type,
1577
                              GPtrArray      *hits,
1578
                              GPtrArray      *blocklist)
1579
0
{
1580
0
  desktop_file_dir_unindexed_mime_lookup (dir, mime_type, hits, blocklist);
1581
0
}
1582
1583
/*< internal >
1584
 * desktop_file_dir_default_lookup:
1585
 * @dir: a #DesktopFileDir
1586
 * @mime_type: the mime type to look up
1587
 * @results: an array to store the results in
1588
 *
1589
 * Collects the "default" applications for a given mime type from @dir.
1590
 */
1591
static void
1592
desktop_file_dir_default_lookup (DesktopFileDir *dir,
1593
                                 const gchar    *mime_type,
1594
                                 GPtrArray      *results)
1595
0
{
1596
0
  desktop_file_dir_unindexed_default_lookup (dir, mime_type, results);
1597
0
}
1598
1599
/*< internal >
1600
 * desktop_file_dir_search:
1601
 * @dir: a #DesktopFileDir
1602
 * @term: a normalised and casefolded search term
1603
 *
1604
 * Finds the names of applications in @dir that match @term.
1605
 */
1606
static void
1607
desktop_file_dir_search (DesktopFileDir *dir,
1608
                         const gchar    *search_token)
1609
0
{
1610
0
  desktop_file_dir_unindexed_search (dir, search_token);
1611
0
}
1612
1613
static void
1614
desktop_file_dir_get_implementations (DesktopFileDir  *dir,
1615
                                      GList          **results,
1616
                                      const gchar     *interface)
1617
0
{
1618
0
  desktop_file_dir_unindexed_get_implementations (dir, results, interface);
1619
0
}
1620
1621
/* Lock/unlock and global setup API {{{2 */
1622
1623
static void
1624
desktop_file_dirs_lock (void)
1625
0
{
1626
0
  guint i;
1627
0
  const gchar *user_config_dir = g_get_user_config_dir ();
1628
1629
0
  g_mutex_lock (&desktop_file_dir_lock);
1630
1631
  /* If the XDG dirs configuration has changed (expected only during tests),
1632
   * clear and reload the state. */
1633
0
  if (desktop_file_dirs_config_dir != NULL &&
1634
0
      g_strcmp0 (desktop_file_dirs_config_dir, user_config_dir) != 0)
1635
0
    {
1636
0
      g_debug ("%s: Resetting desktop app info dirs from %s to %s",
1637
0
               G_STRFUNC, desktop_file_dirs_config_dir, user_config_dir);
1638
1639
0
      g_ptr_array_set_size (desktop_file_dirs, 0);
1640
0
      g_clear_pointer (&desktop_file_dir_user_config, desktop_file_dir_unref);
1641
0
      g_clear_pointer (&desktop_file_dir_user_data, desktop_file_dir_unref);
1642
0
    }
1643
1644
0
  if (desktop_file_dirs == NULL || desktop_file_dirs->len == 0)
1645
0
    {
1646
0
      const char * const *dirs;
1647
0
      gint i;
1648
1649
0
      if (desktop_file_dirs == NULL)
1650
0
        desktop_file_dirs = g_ptr_array_new_with_free_func ((GDestroyNotify) desktop_file_dir_unref);
1651
1652
      /* First, the configs.  Highest priority: the user's ~/.config */
1653
0
      desktop_file_dir_user_config = desktop_file_dir_new_for_config (user_config_dir);
1654
0
      g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_config));
1655
1656
      /* Next, the system configs (/etc/xdg, and so on). */
1657
0
      dirs = g_get_system_config_dirs ();
1658
0
      for (i = 0; dirs[i]; i++)
1659
0
        g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new_for_config (dirs[i]));
1660
1661
      /* Now the data.  Highest priority: the user's ~/.local/share/applications */
1662
0
      desktop_file_dir_user_data = desktop_file_dir_new (g_get_user_data_dir ());
1663
0
      g_ptr_array_add (desktop_file_dirs, desktop_file_dir_ref (desktop_file_dir_user_data));
1664
1665
      /* Following that, XDG_DATA_DIRS/applications, in order */
1666
0
      dirs = g_get_system_data_dirs ();
1667
0
      for (i = 0; dirs[i]; i++)
1668
0
        g_ptr_array_add (desktop_file_dirs, desktop_file_dir_new (dirs[i]));
1669
1670
      /* The list of directories will never change after this, unless
1671
       * g_get_user_config_dir() changes due to %G_TEST_OPTION_ISOLATE_DIRS. */
1672
0
      desktop_file_dirs_config_dir = user_config_dir;
1673
0
    }
1674
1675
0
  for (i = 0; i < desktop_file_dirs->len; i++)
1676
0
    if (!((DesktopFileDir *) g_ptr_array_index (desktop_file_dirs, i))->is_setup)
1677
0
      desktop_file_dir_init (g_ptr_array_index (desktop_file_dirs, i));
1678
0
}
1679
1680
static void
1681
desktop_file_dirs_unlock (void)
1682
0
{
1683
0
  g_mutex_unlock (&desktop_file_dir_lock);
1684
0
}
1685
1686
static void
1687
desktop_file_dirs_invalidate_user_config (void)
1688
0
{
1689
0
  g_mutex_lock (&desktop_file_dir_lock);
1690
1691
0
  if (desktop_file_dir_user_config != NULL)
1692
0
    desktop_file_dir_reset (desktop_file_dir_user_config);
1693
1694
0
  g_mutex_unlock (&desktop_file_dir_lock);
1695
0
}
1696
1697
static void
1698
desktop_file_dirs_invalidate_user_data (void)
1699
0
{
1700
0
  g_mutex_lock (&desktop_file_dir_lock);
1701
1702
0
  if (desktop_file_dir_user_data != NULL)
1703
0
    desktop_file_dir_reset (desktop_file_dir_user_data);
1704
1705
0
  g_mutex_unlock (&desktop_file_dir_lock);
1706
0
}
1707
1708
/* GDesktopAppInfo implementation {{{1 */
1709
/* GObject implementation {{{2 */
1710
static void
1711
g_desktop_app_info_finalize (GObject *object)
1712
0
{
1713
0
  GDesktopAppInfo *info;
1714
1715
0
  info = G_DESKTOP_APP_INFO (object);
1716
1717
0
  g_free (info->desktop_id);
1718
0
  g_free (info->filename);
1719
1720
0
  if (info->keyfile)
1721
0
    g_key_file_unref (info->keyfile);
1722
1723
0
  g_free (info->name);
1724
0
  g_free (info->generic_name);
1725
0
  g_free (info->fullname);
1726
0
  g_free (info->comment);
1727
0
  g_free (info->icon_name);
1728
0
  if (info->icon)
1729
0
    g_object_unref (info->icon);
1730
0
  g_strfreev (info->keywords);
1731
0
  g_strfreev (info->only_show_in);
1732
0
  g_strfreev (info->not_show_in);
1733
0
  g_free (info->try_exec);
1734
0
  g_free (info->exec);
1735
0
  g_free (info->binary);
1736
0
  g_free (info->path);
1737
0
  g_free (info->categories);
1738
0
  g_free (info->startup_wm_class);
1739
0
  g_strfreev (info->mime_types);
1740
0
  g_free (info->app_id);
1741
0
  g_strfreev (info->actions);
1742
1743
0
  G_OBJECT_CLASS (g_desktop_app_info_parent_class)->finalize (object);
1744
0
}
1745
1746
static void
1747
g_desktop_app_info_set_property (GObject      *object,
1748
                                 guint         prop_id,
1749
                                 const GValue *value,
1750
                                 GParamSpec   *pspec)
1751
0
{
1752
0
  GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1753
1754
0
  switch (prop_id)
1755
0
    {
1756
0
    case PROP_FILENAME:
1757
0
      self->filename = g_value_dup_string (value);
1758
0
      break;
1759
1760
0
    default:
1761
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1762
0
      break;
1763
0
    }
1764
0
}
1765
1766
static void
1767
g_desktop_app_info_get_property (GObject    *object,
1768
                                 guint       prop_id,
1769
                                 GValue     *value,
1770
                                 GParamSpec *pspec)
1771
0
{
1772
0
  GDesktopAppInfo *self = G_DESKTOP_APP_INFO (object);
1773
1774
0
  switch (prop_id)
1775
0
    {
1776
0
    case PROP_FILENAME:
1777
0
      g_value_set_string (value, self->filename);
1778
0
      break;
1779
0
    default:
1780
0
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1781
0
      break;
1782
0
    }
1783
0
}
1784
1785
static void
1786
g_desktop_app_info_class_init (GDesktopAppInfoClass *klass)
1787
0
{
1788
0
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1789
1790
0
  gobject_class->get_property = g_desktop_app_info_get_property;
1791
0
  gobject_class->set_property = g_desktop_app_info_set_property;
1792
0
  gobject_class->finalize = g_desktop_app_info_finalize;
1793
1794
  /**
1795
   * GDesktopAppInfo:filename:
1796
   *
1797
   * The origin filename of this [class@GioUnix.DesktopAppInfo]
1798
   */
1799
0
  g_object_class_install_property (gobject_class,
1800
0
                                   PROP_FILENAME,
1801
0
                                   g_param_spec_string ("filename", NULL, NULL, NULL,
1802
0
                                                        G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
1803
0
}
1804
1805
static void
1806
g_desktop_app_info_init (GDesktopAppInfo *local)
1807
0
{
1808
0
}
1809
1810
/* Construction... {{{2 */
1811
1812
/*< internal >
1813
 * binary_from_exec:
1814
 * @exec: an exec line
1815
 *
1816
 * Returns the first word in an exec line (ie: the binary name).
1817
 *
1818
 * If @exec is "  progname --foo %F" then returns "progname".
1819
 */
1820
static char *
1821
binary_from_exec (const char *exec)
1822
0
{
1823
0
  const char *p, *start;
1824
1825
0
  p = exec;
1826
0
  while (*p == ' ')
1827
0
    p++;
1828
0
  start = p;
1829
0
  while (*p != ' ' && *p != 0)
1830
0
    p++;
1831
1832
0
  return g_strndup (start, (size_t) (p - start));
1833
0
}
1834
1835
/*< internal >
1836
 * g_desktop_app_info_get_desktop_id_for_filename
1837
 * @self: #GDesktopAppInfo to get desktop id of
1838
 *
1839
 * Tries to find the desktop ID for a particular `.desktop` filename, as per the
1840
 * [Desktop Entry Specification](https://specifications.freedesktop.org/desktop-
1841
 * entry-spec/desktop-entry-spec-latest.html#desktop-file-id).
1842
 *
1843
 * Returns: desktop id or basename if filename is unknown.
1844
 */
1845
static char *
1846
g_desktop_app_info_get_desktop_id_for_filename (GDesktopAppInfo *self)
1847
0
{
1848
0
  guint i;
1849
0
  gchar *desktop_id = NULL;
1850
1851
0
  g_return_val_if_fail (self->filename != NULL, NULL);
1852
1853
0
  for (i = 0; i < desktop_file_dirs->len; i++)
1854
0
    {
1855
0
      DesktopFileDir *dir = g_ptr_array_index (desktop_file_dirs, i);
1856
0
      GHashTable *app_names;
1857
0
      GHashTableIter iter;
1858
0
      gpointer key, value;
1859
1860
0
      app_names = dir->app_names;
1861
1862
0
      if (!app_names)
1863
0
        continue;
1864
1865
0
      g_hash_table_iter_init (&iter, app_names);
1866
0
      while (g_hash_table_iter_next (&iter, &key, &value))
1867
0
        {
1868
0
          if (!strcmp (value, self->filename))
1869
0
            {
1870
0
              desktop_id = g_strdup (key);
1871
0
              break;
1872
0
            }
1873
0
        }
1874
1875
0
      if (desktop_id)
1876
0
        break;
1877
0
    }
1878
1879
0
  if (!desktop_id)
1880
0
    desktop_id = g_path_get_basename (self->filename);
1881
1882
0
  return g_steal_pointer (&desktop_id);
1883
0
}
1884
1885
static gboolean
1886
is_invalid_key_error (const GError *error)
1887
0
{
1888
0
  return (error != NULL &&
1889
0
          !g_error_matches (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_GROUP_NOT_FOUND) &&
1890
0
          !g_error_matches (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND));
1891
0
}
1892
1893
static gboolean
1894
g_desktop_app_info_load_from_keyfile (GDesktopAppInfo *info,
1895
                                      GKeyFile        *key_file)
1896
0
{
1897
0
  char *start_group;
1898
0
  char *type;
1899
0
  char *try_exec;
1900
0
  char *exec;
1901
0
  char *path;
1902
0
  gboolean bus_activatable;
1903
0
  GError *local_error = NULL;
1904
1905
0
  start_group = g_key_file_get_start_group (key_file);
1906
0
  if (start_group == NULL || strcmp (start_group, G_KEY_FILE_DESKTOP_GROUP) != 0)
1907
0
    {
1908
0
      g_free (start_group);
1909
0
      return FALSE;
1910
0
    }
1911
0
  g_free (start_group);
1912
1913
0
  type = g_key_file_get_string (key_file,
1914
0
                                G_KEY_FILE_DESKTOP_GROUP,
1915
0
                                G_KEY_FILE_DESKTOP_KEY_TYPE,
1916
0
                                NULL);
1917
0
  if (type == NULL || strcmp (type, G_KEY_FILE_DESKTOP_TYPE_APPLICATION) != 0)
1918
0
    {
1919
0
      g_free (type);
1920
0
      return FALSE;
1921
0
    }
1922
0
  g_free (type);
1923
1924
0
  path = g_key_file_get_string (key_file,
1925
0
                                G_KEY_FILE_DESKTOP_GROUP,
1926
0
                                G_KEY_FILE_DESKTOP_KEY_PATH,
1927
0
                                &local_error);
1928
0
  if (is_invalid_key_error (local_error))
1929
0
    {
1930
0
      g_error_free (local_error);
1931
0
      return FALSE;
1932
0
    }
1933
0
  g_clear_error (&local_error);
1934
1935
0
  try_exec = g_key_file_get_string (key_file,
1936
0
                                    G_KEY_FILE_DESKTOP_GROUP,
1937
0
                                    G_KEY_FILE_DESKTOP_KEY_TRY_EXEC,
1938
0
                                    &local_error);
1939
0
  if (is_invalid_key_error (local_error))
1940
0
    {
1941
0
      g_free (path);
1942
0
      g_error_free (local_error);
1943
0
      return FALSE;
1944
0
    }
1945
0
  g_clear_error (&local_error);
1946
1947
0
  if (try_exec && try_exec[0] != '\0')
1948
0
    {
1949
0
      char *t;
1950
      /* Use the desktop file path (if any) as working dir to search program */
1951
0
      t = GLIB_PRIVATE_CALL (g_find_program_for_path) (try_exec, NULL, path);
1952
0
      if (t == NULL)
1953
0
        {
1954
0
          g_free (path);
1955
0
          g_free (try_exec);
1956
0
          return FALSE;
1957
0
        }
1958
0
      g_free (t);
1959
0
    }
1960
1961
0
  exec = g_key_file_get_string (key_file,
1962
0
                                G_KEY_FILE_DESKTOP_GROUP,
1963
0
                                G_KEY_FILE_DESKTOP_KEY_EXEC,
1964
0
                                &local_error);
1965
0
  if (is_invalid_key_error (local_error))
1966
0
    {
1967
0
      g_free (path);
1968
0
      g_free (try_exec);
1969
0
      g_error_free (local_error);
1970
0
      return FALSE;
1971
0
    }
1972
0
  g_clear_error (&local_error);
1973
1974
0
  if (exec && exec[0] != '\0')
1975
0
    {
1976
0
      gint argc;
1977
0
      char **argv;
1978
0
      if (!g_shell_parse_argv (exec, &argc, &argv, NULL))
1979
0
        {
1980
0
          g_free (path);
1981
0
          g_free (exec);
1982
0
          g_free (try_exec);
1983
0
          return FALSE;
1984
0
        }
1985
0
      else
1986
0
        {
1987
0
          char *t;
1988
1989
          /* Since @exec is not an empty string, there must be at least one
1990
           * argument, so dereferencing argv[0] should return non-NULL. */
1991
0
          g_assert (argc > 0);
1992
          /* Use the desktop file path (if any) as working dir to search program */
1993
0
          t = GLIB_PRIVATE_CALL (g_find_program_for_path) (argv[0], NULL, path);
1994
0
          g_strfreev (argv);
1995
1996
0
          if (t == NULL)
1997
0
            {
1998
0
              g_free (path);
1999
0
              g_free (exec);
2000
0
              g_free (try_exec);
2001
0
              return FALSE;
2002
0
            }
2003
0
          g_free (t);
2004
0
        }
2005
0
    }
2006
2007
0
  info->name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
2008
0
  info->generic_name = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, GENERIC_NAME_KEY, NULL, NULL);
2009
0
  info->fullname = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, FULL_NAME_KEY, NULL, NULL);
2010
0
  info->keywords = g_key_file_get_locale_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, KEYWORDS_KEY, NULL, NULL, NULL);
2011
0
  info->comment = g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_COMMENT, NULL, NULL);
2012
0
  info->nodisplay = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, NULL) != FALSE;
2013
0
  info->icon_name =  g_key_file_get_locale_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL, NULL);
2014
0
  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);
2015
0
  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);
2016
0
  info->try_exec = try_exec;
2017
0
  info->exec = exec;
2018
0
  info->path = g_steal_pointer (&path);
2019
0
  info->terminal = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_TERMINAL, NULL) != FALSE;
2020
0
  info->startup_notify = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY, NULL) != FALSE;
2021
0
  info->no_fuse = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, "X-GIO-NoFuse", NULL) != FALSE;
2022
0
  info->hidden = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_HIDDEN, NULL) != FALSE;
2023
0
  info->categories = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_CATEGORIES, NULL);
2024
0
  info->startup_wm_class = g_key_file_get_string (key_file, G_KEY_FILE_DESKTOP_GROUP, STARTUP_WM_CLASS_KEY, NULL);
2025
0
  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);
2026
0
  bus_activatable = g_key_file_get_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_DBUS_ACTIVATABLE, NULL);
2027
0
  info->actions = g_key_file_get_string_list (key_file, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ACTIONS, NULL, NULL);
2028
2029
  /* Remove the special-case: no Actions= key just means 0 extra actions */
2030
0
  if (info->actions == NULL)
2031
0
    info->actions = g_new0 (gchar *, 0 + 1);
2032
2033
0
  info->icon = NULL;
2034
0
  if (info->icon_name)
2035
0
    {
2036
0
      if (g_path_is_absolute (info->icon_name))
2037
0
        {
2038
0
          GFile *file;
2039
2040
0
          file = g_file_new_for_path (info->icon_name);
2041
0
          info->icon = g_file_icon_new (file);
2042
0
          g_object_unref (file);
2043
0
        }
2044
0
      else
2045
0
        {
2046
0
          char *p;
2047
2048
          /* Work around a common mistake in desktop files */
2049
0
          if ((p = strrchr (info->icon_name, '.')) != NULL &&
2050
0
              (strcmp (p, ".png") == 0 ||
2051
0
               strcmp (p, ".xpm") == 0 ||
2052
0
               strcmp (p, ".svg") == 0))
2053
0
            *p = 0;
2054
2055
0
          info->icon = g_themed_icon_new (info->icon_name);
2056
0
        }
2057
0
    }
2058
2059
0
  if (info->exec)
2060
0
    info->binary = binary_from_exec (info->exec);
2061
2062
0
  if (info->path && info->path[0] == '\0')
2063
0
    {
2064
0
      g_free (info->path);
2065
0
      info->path = NULL;
2066
0
    }
2067
2068
  /* Can only be DBusActivatable if we know the filename, which means
2069
   * that this won't work for the load-from-keyfile case.
2070
   */
2071
0
  if (bus_activatable && info->filename)
2072
0
    {
2073
0
      gchar *basename;
2074
0
      gchar *last_dot;
2075
2076
0
      basename = g_path_get_basename (info->filename);
2077
0
      last_dot = strrchr (basename, '.');
2078
2079
0
      if (last_dot && g_str_equal (last_dot, ".desktop"))
2080
0
        {
2081
0
          *last_dot = '\0';
2082
2083
0
          if (g_dbus_is_name (basename) && basename[0] != ':')
2084
0
            info->app_id = g_strdup (basename);
2085
0
        }
2086
2087
0
      g_free (basename);
2088
0
    }
2089
2090
0
  if (info->filename)
2091
0
    info->desktop_id = g_desktop_app_info_get_desktop_id_for_filename (info);
2092
2093
0
  info->keyfile = g_key_file_ref (key_file);
2094
2095
0
  return TRUE;
2096
0
}
2097
2098
static gboolean
2099
g_desktop_app_info_load_file (GDesktopAppInfo *self)
2100
0
{
2101
0
  GKeyFile *key_file;
2102
0
  gboolean retval = FALSE;
2103
2104
0
  g_return_val_if_fail (self->filename != NULL, FALSE);
2105
2106
0
  key_file = g_key_file_new ();
2107
2108
0
  if (g_key_file_load_from_file (key_file, self->filename, G_KEY_FILE_NONE, NULL))
2109
0
    retval = g_desktop_app_info_load_from_keyfile (self, key_file);
2110
2111
0
  g_key_file_unref (key_file);
2112
0
  return retval;
2113
0
}
2114
2115
/**
2116
 * g_desktop_app_info_new_from_keyfile:
2117
 * @key_file: an opened [type@GLib.KeyFile]
2118
 *
2119
 * Creates a new [class@GioUnix.DesktopAppInfo].
2120
 *
2121
 * Returns: (nullable): a new [class@GioUnix.DesktopAppInfo] or `NULL` on error.
2122
 *
2123
 * Since: 2.18
2124
 **/
2125
GDesktopAppInfo *
2126
g_desktop_app_info_new_from_keyfile (GKeyFile *key_file)
2127
0
{
2128
0
  GDesktopAppInfo *info;
2129
2130
0
  info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2131
0
  info->filename = NULL;
2132
2133
0
  desktop_file_dirs_lock ();
2134
2135
0
  if (!g_desktop_app_info_load_from_keyfile (info, key_file))
2136
0
    g_clear_object (&info);
2137
2138
0
  desktop_file_dirs_unlock ();
2139
2140
0
  return info;
2141
0
}
2142
2143
/**
2144
 * g_desktop_app_info_new_from_filename:
2145
 * @filename: (type filename): the path of a desktop file, in the GLib
2146
 *      filename encoding
2147
 *
2148
 * Creates a new [class@GioUnix.DesktopAppInfo].
2149
 *
2150
 * Returns: (nullable): a new [class@GioUnix.DesktopAppInfo] or `NULL` on error.
2151
 **/
2152
GDesktopAppInfo *
2153
g_desktop_app_info_new_from_filename (const char *filename)
2154
0
{
2155
0
  GDesktopAppInfo *info = NULL;
2156
2157
0
  desktop_file_dirs_lock ();
2158
2159
0
  info = g_desktop_app_info_new_from_filename_unlocked (filename);
2160
2161
0
  desktop_file_dirs_unlock ();
2162
2163
0
  return info;
2164
0
}
2165
2166
/**
2167
 * g_desktop_app_info_new:
2168
 * @desktop_id: the desktop file ID
2169
 *
2170
 * Creates a new [class@GioUnix.DesktopAppInfo] based on a desktop file ID.
2171
 *
2172
 * A desktop file ID is the basename of the desktop file, including the
2173
 * `.desktop` extension. GIO is looking for a desktop file with this name
2174
 * in the `applications` subdirectories of the XDG
2175
 * data directories (i.e. the directories specified in the `XDG_DATA_HOME`
2176
 * and `XDG_DATA_DIRS` environment variables). GIO also supports the
2177
 * prefix-to-subdirectory mapping that is described in the
2178
 * [Menu Spec](http://standards.freedesktop.org/menu-spec/latest/)
2179
 * (i.e. a desktop ID of `kde-foo.desktop` will match
2180
 * `/usr/share/applications/kde/foo.desktop`).
2181
 *
2182
 * Returns: (nullable): a new [class@GioUnix.DesktopAppInfo], or `NULL` if no
2183
 *    desktop file with that ID exists.
2184
 */
2185
GDesktopAppInfo *
2186
g_desktop_app_info_new (const char *desktop_id)
2187
0
{
2188
0
  GDesktopAppInfo *appinfo = NULL;
2189
0
  guint i;
2190
2191
0
  desktop_file_dirs_lock ();
2192
2193
0
  for (i = 0; i < desktop_file_dirs->len; i++)
2194
0
    {
2195
0
      appinfo = desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, i), desktop_id);
2196
2197
0
      if (appinfo)
2198
0
        break;
2199
0
    }
2200
2201
0
  desktop_file_dirs_unlock ();
2202
2203
0
  if (appinfo == NULL)
2204
0
    return NULL;
2205
2206
0
  g_free (appinfo->desktop_id);
2207
0
  appinfo->desktop_id = g_strdup (desktop_id);
2208
2209
0
  if (g_desktop_app_info_get_is_hidden (appinfo))
2210
0
    {
2211
0
      g_object_unref (appinfo);
2212
0
      appinfo = NULL;
2213
0
    }
2214
2215
0
  return appinfo;
2216
0
}
2217
2218
static GAppInfo *
2219
g_desktop_app_info_dup (GAppInfo *appinfo)
2220
0
{
2221
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2222
0
  GDesktopAppInfo *new_info;
2223
2224
0
  new_info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
2225
2226
0
  new_info->filename = g_strdup (info->filename);
2227
0
  new_info->desktop_id = g_strdup (info->desktop_id);
2228
2229
0
  if (info->keyfile)
2230
0
    new_info->keyfile = g_key_file_ref (info->keyfile);
2231
2232
0
  new_info->name = g_strdup (info->name);
2233
0
  new_info->generic_name = g_strdup (info->generic_name);
2234
0
  new_info->fullname = g_strdup (info->fullname);
2235
0
  new_info->keywords = g_strdupv (info->keywords);
2236
0
  new_info->comment = g_strdup (info->comment);
2237
0
  new_info->nodisplay = info->nodisplay;
2238
0
  new_info->icon_name = g_strdup (info->icon_name);
2239
0
  if (info->icon)
2240
0
    new_info->icon = g_object_ref (info->icon);
2241
0
  new_info->only_show_in = g_strdupv (info->only_show_in);
2242
0
  new_info->not_show_in = g_strdupv (info->not_show_in);
2243
0
  new_info->try_exec = g_strdup (info->try_exec);
2244
0
  new_info->exec = g_strdup (info->exec);
2245
0
  new_info->binary = g_strdup (info->binary);
2246
0
  new_info->path = g_strdup (info->path);
2247
0
  new_info->app_id = g_strdup (info->app_id);
2248
0
  new_info->hidden = info->hidden;
2249
0
  new_info->terminal = info->terminal;
2250
0
  new_info->startup_notify = info->startup_notify;
2251
2252
0
  return G_APP_INFO (new_info);
2253
0
}
2254
2255
/* GAppInfo interface implementation functions {{{2 */
2256
2257
static gboolean
2258
g_desktop_app_info_equal (GAppInfo *appinfo1,
2259
                          GAppInfo *appinfo2)
2260
0
{
2261
0
  GDesktopAppInfo *info1 = G_DESKTOP_APP_INFO (appinfo1);
2262
0
  GDesktopAppInfo *info2 = G_DESKTOP_APP_INFO (appinfo2);
2263
2264
0
  if (info1->desktop_id == NULL ||
2265
0
      info2->desktop_id == NULL)
2266
0
    return info1 == info2;
2267
2268
0
  return strcmp (info1->desktop_id, info2->desktop_id) == 0;
2269
0
}
2270
2271
static const char *
2272
g_desktop_app_info_get_id (GAppInfo *appinfo)
2273
0
{
2274
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2275
2276
0
  return info->desktop_id;
2277
0
}
2278
2279
static const char *
2280
g_desktop_app_info_get_name (GAppInfo *appinfo)
2281
0
{
2282
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2283
2284
0
  if (info->name == NULL)
2285
0
    return _("Unnamed");
2286
0
  return info->name;
2287
0
}
2288
2289
static const char *
2290
g_desktop_app_info_get_display_name (GAppInfo *appinfo)
2291
0
{
2292
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2293
2294
0
  if (info->fullname == NULL)
2295
0
    return g_desktop_app_info_get_name (appinfo);
2296
0
  return info->fullname;
2297
0
}
2298
2299
/**
2300
 * g_desktop_app_info_get_is_hidden:
2301
 * @info: a [class@GioUnix.DesktopAppInfo].
2302
 *
2303
 * A desktop file is hidden if the
2304
 * [`Hidden` key](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-hidden)
2305
 * in it is set to `True`.
2306
 *
2307
 * Returns: `TRUE` if hidden, `FALSE` otherwise.
2308
 **/
2309
gboolean
2310
g_desktop_app_info_get_is_hidden (GDesktopAppInfo *info)
2311
0
{
2312
0
  return info->hidden;
2313
0
}
2314
2315
/**
2316
 * g_desktop_app_info_get_filename:
2317
 * @info: a [class@GioUnix.DesktopAppInfo]
2318
 *
2319
 * When @info was created from a known filename, return it.
2320
 *
2321
 * In some situations such as a [class@GioUnix.DesktopAppInfo] returned
2322
 * from [ctor@GioUnix.DesktopAppInfo.new_from_keyfile], this function
2323
 * will return `NULL`.
2324
 *
2325
 * Returns: (nullable) (type filename): The full path to the file for @info,
2326
 *   or `NULL` if not known.
2327
 * Since: 2.24
2328
 */
2329
const char *
2330
g_desktop_app_info_get_filename (GDesktopAppInfo *info)
2331
0
{
2332
0
  return info->filename;
2333
0
}
2334
2335
static const char *
2336
g_desktop_app_info_get_description (GAppInfo *appinfo)
2337
0
{
2338
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2339
2340
0
  return info->comment;
2341
0
}
2342
2343
static const char *
2344
g_desktop_app_info_get_executable (GAppInfo *appinfo)
2345
0
{
2346
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2347
2348
0
  return info->binary;
2349
0
}
2350
2351
static const char *
2352
g_desktop_app_info_get_commandline (GAppInfo *appinfo)
2353
0
{
2354
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2355
2356
0
  return info->exec;
2357
0
}
2358
2359
static GIcon *
2360
g_desktop_app_info_get_icon (GAppInfo *appinfo)
2361
0
{
2362
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
2363
2364
0
  return info->icon;
2365
0
}
2366
2367
/**
2368
 * g_desktop_app_info_get_categories:
2369
 * @info: a [class@GioUnix.DesktopAppInfo]
2370
 *
2371
 * Gets the categories from the desktop file.
2372
 *
2373
 * Returns: (nullable): The unparsed
2374
 *   [`Categories` key](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-categories)
2375
 *   from the desktop file;
2376
 *   i.e. no attempt is made to split it by `;` or validate it.
2377
 */
2378
const char *
2379
g_desktop_app_info_get_categories (GDesktopAppInfo *info)
2380
0
{
2381
0
  return info->categories;
2382
0
}
2383
2384
/**
2385
 * g_desktop_app_info_get_keywords:
2386
 * @info: a [class@GioUnix.DesktopAppInfo]
2387
 *
2388
 * Gets the keywords from the desktop file.
2389
 *
2390
 * Returns: (nullable) (array zero-terminated=1) (transfer none): The value of the
2391
 *   [`Keywords` key](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-keywords)
2392
 *
2393
 * Since: 2.32
2394
 */
2395
const char * const *
2396
g_desktop_app_info_get_keywords (GDesktopAppInfo *info)
2397
0
{
2398
0
  return (const char * const *)info->keywords;
2399
0
}
2400
2401
/**
2402
 * g_desktop_app_info_get_generic_name:
2403
 * @info: a [class@GioUnix.DesktopAppInfo]
2404
 *
2405
 * Gets the generic name from the desktop file.
2406
 *
2407
 * Returns: (nullable): The value of the
2408
 *   [`GenericName` key](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-genericname)
2409
 */
2410
const char *
2411
g_desktop_app_info_get_generic_name (GDesktopAppInfo *info)
2412
0
{
2413
0
  return info->generic_name;
2414
0
}
2415
2416
/**
2417
 * g_desktop_app_info_get_nodisplay:
2418
 * @info: a [class@GioUnix.DesktopAppInfo]
2419
 *
2420
 * Gets the value of the
2421
 * [`NoDisplay` key](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-nodisplay)
2422
 *  which helps determine if the application info should be shown in menus. See
2423
 * `G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY` and [method@Gio.AppInfo.should_show].
2424
 *
2425
 * Returns: The value of the `NoDisplay` key
2426
 *
2427
 * Since: 2.30
2428
 */
2429
gboolean
2430
g_desktop_app_info_get_nodisplay (GDesktopAppInfo *info)
2431
0
{
2432
0
  return info->nodisplay;
2433
0
}
2434
2435
/**
2436
 * g_desktop_app_info_get_show_in:
2437
 * @info: a [class@GioUnix.DesktopAppInfo]
2438
 * @desktop_env: (nullable): a string specifying a desktop name
2439
 *
2440
 * Checks if the application info should be shown in menus that list available
2441
 * applications for a specific name of the desktop, based on the
2442
 * [`OnlyShowIn`](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-onlyshowin)
2443
 * and [`NotShowIn`](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-notshowin)
2444
 * keys.
2445
 *
2446
 * @desktop_env should typically be given as `NULL`, in which case the
2447
 * `XDG_CURRENT_DESKTOP` environment variable is consulted.  If you want
2448
 * to override the default mechanism then you may specify @desktop_env,
2449
 * but this is not recommended.
2450
 *
2451
 * Note that [method@Gio.AppInfo.should_show] for @info will include this check
2452
 * (with `NULL` for @desktop_env) as well as additional checks.
2453
 *
2454
 * Returns: `TRUE` if the @info should be shown in @desktop_env according to the
2455
 * `OnlyShowIn` and `NotShowIn` keys, `FALSE` otherwise.
2456
 *
2457
 * Since: 2.30
2458
 */
2459
gboolean
2460
g_desktop_app_info_get_show_in (GDesktopAppInfo *info,
2461
                                const gchar     *desktop_env)
2462
0
{
2463
0
  const gchar *specified_envs[] = { desktop_env, NULL };
2464
0
  const gchar * const *envs;
2465
0
  gint i;
2466
2467
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
2468
2469
0
  if (desktop_env)
2470
0
    envs = specified_envs;
2471
0
  else
2472
0
    envs = get_current_desktops (NULL);
2473
2474
0
  for (i = 0; envs[i]; i++)
2475
0
    {
2476
0
      gint j;
2477
2478
0
      if (info->only_show_in)
2479
0
        for (j = 0; info->only_show_in[j]; j++)
2480
0
          if (g_str_equal (info->only_show_in[j], envs[i]))
2481
0
            return TRUE;
2482
2483
0
      if (info->not_show_in)
2484
0
        for (j = 0; info->not_show_in[j]; j++)
2485
0
          if (g_str_equal (info->not_show_in[j], envs[i]))
2486
0
            return FALSE;
2487
0
    }
2488
2489
0
  return info->only_show_in == NULL;
2490
0
}
2491
2492
/* Launching... {{{2 */
2493
2494
static char *
2495
expand_macro_single (char macro, const char *uri)
2496
0
{
2497
0
  GFile *file;
2498
0
  char *result = NULL;
2499
0
  char *path = NULL;
2500
0
  char *name;
2501
2502
0
  file = g_file_new_for_uri (uri);
2503
2504
0
  switch (macro)
2505
0
    {
2506
0
    case 'u':
2507
0
    case 'U':
2508
0
      result = g_shell_quote (uri);
2509
0
      break;
2510
0
    case 'f':
2511
0
    case 'F':
2512
0
      path = g_file_get_path (file);
2513
0
      if (path)
2514
0
        result = g_shell_quote (path);
2515
0
      break;
2516
0
    case 'd':
2517
0
    case 'D':
2518
0
      path = g_file_get_path (file);
2519
0
      if (path)
2520
0
        {
2521
0
          name = g_path_get_dirname (path);
2522
0
          result = g_shell_quote (name);
2523
0
          g_free (name);
2524
0
        }
2525
0
      break;
2526
0
    case 'n':
2527
0
    case 'N':
2528
0
      path = g_file_get_path (file);
2529
0
      if (path)
2530
0
        {
2531
0
          name = g_path_get_basename (path);
2532
0
          result = g_shell_quote (name);
2533
0
          g_free (name);
2534
0
        }
2535
0
      break;
2536
0
    }
2537
2538
0
  g_object_unref (file);
2539
0
  g_free (path);
2540
2541
0
  return result;
2542
0
}
2543
2544
static char *
2545
expand_macro_uri (char macro, const char *uri, gboolean force_file_uri, char force_file_uri_macro)
2546
0
{
2547
0
  char *expanded = NULL;
2548
2549
0
  g_return_val_if_fail (uri != NULL, NULL);
2550
2551
0
  if (!force_file_uri ||
2552
      /* Pass URI if it contains an anchor */
2553
0
      strchr (uri, '#') != NULL)
2554
0
    {
2555
0
      expanded = expand_macro_single (macro, uri);
2556
0
    }
2557
0
  else
2558
0
    {
2559
0
      expanded = expand_macro_single (force_file_uri_macro, uri);
2560
0
      if (expanded == NULL)
2561
0
        expanded = expand_macro_single (macro, uri);
2562
0
    }
2563
2564
0
  return expanded;
2565
0
}
2566
2567
static void
2568
expand_macro (char              macro,
2569
              GString          *exec,
2570
              GDesktopAppInfo  *info,
2571
              GList           **uri_list)
2572
0
{
2573
0
  GList *uris = *uri_list;
2574
0
  char *expanded = NULL;
2575
0
  gboolean force_file_uri;
2576
0
  char force_file_uri_macro;
2577
0
  const char *uri;
2578
2579
0
  g_return_if_fail (exec != NULL);
2580
2581
  /* On %u and %U, pass POSIX file path pointing to the URI via
2582
   * the FUSE mount in ~/.gvfs. Note that if the FUSE daemon isn't
2583
   * running or the URI doesn't have a POSIX file path via FUSE
2584
   * we'll just pass the URI.
2585
   */
2586
0
  force_file_uri_macro = macro;
2587
0
  force_file_uri = FALSE;
2588
0
  if (!info->no_fuse)
2589
0
    {
2590
0
      switch (macro)
2591
0
        {
2592
0
        case 'u':
2593
0
          force_file_uri_macro = 'f';
2594
0
          force_file_uri = TRUE;
2595
0
          break;
2596
0
        case 'U':
2597
0
          force_file_uri_macro = 'F';
2598
0
          force_file_uri = TRUE;
2599
0
          break;
2600
0
        default:
2601
0
          break;
2602
0
        }
2603
0
    }
2604
2605
0
  switch (macro)
2606
0
    {
2607
0
    case 'u':
2608
0
    case 'f':
2609
0
    case 'd':
2610
0
    case 'n':
2611
0
      if (uris)
2612
0
        {
2613
0
          uri = uris->data;
2614
0
          expanded = expand_macro_uri (macro, uri,
2615
0
                                       force_file_uri, force_file_uri_macro);
2616
0
          if (expanded)
2617
0
            {
2618
0
              g_string_append (exec, expanded);
2619
0
              g_free (expanded);
2620
0
            }
2621
0
          uris = uris->next;
2622
0
        }
2623
2624
0
      break;
2625
2626
0
    case 'U':
2627
0
    case 'F':
2628
0
    case 'D':
2629
0
    case 'N':
2630
0
      while (uris)
2631
0
        {
2632
0
          uri = uris->data;
2633
0
          expanded = expand_macro_uri (macro, uri,
2634
0
                                       force_file_uri, force_file_uri_macro);
2635
0
          if (expanded)
2636
0
            {
2637
0
              g_string_append (exec, expanded);
2638
0
              g_free (expanded);
2639
0
            }
2640
2641
0
          uris = uris->next;
2642
2643
0
          if (uris != NULL && expanded)
2644
0
            g_string_append_c (exec, ' ');
2645
0
        }
2646
2647
0
      break;
2648
2649
0
    case 'i':
2650
0
      if (info->icon_name)
2651
0
        {
2652
0
          g_string_append (exec, "--icon ");
2653
0
          expanded = g_shell_quote (info->icon_name);
2654
0
          g_string_append (exec, expanded);
2655
0
          g_free (expanded);
2656
0
        }
2657
0
      break;
2658
2659
0
    case 'c':
2660
0
      if (info->name)
2661
0
        {
2662
0
          expanded = g_shell_quote (info->name);
2663
0
          g_string_append (exec, expanded);
2664
0
          g_free (expanded);
2665
0
        }
2666
0
      break;
2667
2668
0
    case 'k':
2669
0
      if (info->filename)
2670
0
        {
2671
0
          expanded = g_shell_quote (info->filename);
2672
0
          g_string_append (exec, expanded);
2673
0
          g_free (expanded);
2674
0
        }
2675
0
      break;
2676
2677
0
    case 'm': /* deprecated */
2678
0
      break;
2679
2680
0
    case '%':
2681
0
      g_string_append_c (exec, '%');
2682
0
      break;
2683
0
    }
2684
2685
0
  *uri_list = uris;
2686
0
}
2687
2688
static gboolean
2689
expand_application_parameters (GDesktopAppInfo   *info,
2690
                               const gchar       *exec_line,
2691
                               GList            **uris,
2692
                               int               *argc,
2693
                               char            ***argv,
2694
                               GError           **error)
2695
0
{
2696
0
  GList *uri_list = *uris;
2697
0
  const char *p = exec_line;
2698
0
  GString *expanded_exec;
2699
0
  gboolean res;
2700
2701
0
  if (exec_line == NULL)
2702
0
    {
2703
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
2704
0
                           _("Desktop file didn’t specify Exec field"));
2705
0
      return FALSE;
2706
0
    }
2707
2708
0
  expanded_exec = g_string_new (NULL);
2709
2710
0
  while (*p)
2711
0
    {
2712
0
      if (p[0] == '%' && p[1] != '\0')
2713
0
        {
2714
0
          expand_macro (p[1], expanded_exec, info, uris);
2715
0
          p++;
2716
0
        }
2717
0
      else
2718
0
        g_string_append_c (expanded_exec, *p);
2719
2720
0
      p++;
2721
0
    }
2722
2723
  /* No file substitutions */
2724
0
  if (uri_list == *uris && uri_list != NULL)
2725
0
    {
2726
      /* If there is no macro default to %f. This is also what KDE does */
2727
0
      g_string_append_c (expanded_exec, ' ');
2728
0
      expand_macro ('f', expanded_exec, info, uris);
2729
0
    }
2730
2731
0
  res = g_shell_parse_argv (expanded_exec->str, argc, argv, error);
2732
0
  g_string_free (expanded_exec, TRUE);
2733
0
  return res;
2734
0
}
2735
2736
static gboolean
2737
prepend_terminal_to_vector (int          *argc,
2738
                            char       ***argv,
2739
                            const char   *path,
2740
                            const char   *working_dir)
2741
0
{
2742
0
#ifndef G_OS_WIN32
2743
0
  char **real_argv;
2744
0
  size_t real_argc;
2745
0
  size_t i;
2746
0
  size_t term_argc;
2747
0
  char *found_terminal;
2748
0
  char **the_argv;
2749
0
  const char *term_arg = NULL;
2750
0
  static const struct {
2751
0
    const char *exec;
2752
0
    const char *exec_arg;
2753
0
  } known_terminals[] = {
2754
0
    { "xdg-terminal-exec", NULL },
2755
0
    { "kgx", "-e" },
2756
0
    { "gnome-terminal", "--" },
2757
0
    { "mate-terminal", "-x" },
2758
0
    { "xfce4-terminal", "-x" },
2759
0
    { "tilix", "-e" },
2760
0
    { "konsole", "-e" },
2761
0
    { "nxterm", "-e" },
2762
0
    { "color-xterm", "-e" },
2763
0
    { "rxvt", "-e" },
2764
0
    { "dtterm", "-e" },
2765
0
    { "xterm", "-e" }
2766
0
  };
2767
2768
0
  g_return_val_if_fail (argc != NULL, FALSE);
2769
0
  g_return_val_if_fail (argv != NULL, FALSE);
2770
2771
  /* sanity */
2772
0
  if(*argv == NULL)
2773
0
    *argc = 0;
2774
2775
0
  the_argv = *argv;
2776
2777
  /* compute size if not given */
2778
0
  if (*argc < 0)
2779
0
    {
2780
0
      for ((*argc) = 0; the_argv[*argc] != NULL; (*argc)++)
2781
0
        ;
2782
0
    }
2783
0
  g_assert (*argc >= 0);
2784
2785
0
  for (i = 0, found_terminal = NULL; i < G_N_ELEMENTS (known_terminals); i++)
2786
0
    {
2787
0
      found_terminal = GLIB_PRIVATE_CALL (g_find_program_for_path) (known_terminals[i].exec,
2788
0
                                                                    path, working_dir);
2789
0
      if (found_terminal != NULL)
2790
0
        {
2791
0
          term_arg = known_terminals[i].exec_arg;
2792
0
          break;
2793
0
        }
2794
0
    }
2795
2796
0
  if (found_terminal == NULL)
2797
0
    {
2798
0
      g_debug ("Couldn’t find a known terminal");
2799
0
      return FALSE;
2800
0
    }
2801
2802
  /* check if the terminal require an option */
2803
0
  term_argc = term_arg ? 2 : 1;
2804
2805
0
  real_argc = term_argc + (size_t) *argc;
2806
0
  real_argv = g_new (char *, real_argc + 1);
2807
2808
0
  i = 0;
2809
0
  real_argv[i++] = found_terminal;
2810
2811
0
  if (term_arg)
2812
0
    real_argv[i++] = g_strdup (term_arg);
2813
2814
0
  g_assert (i == term_argc);
2815
0
  for (int j = 0; j < *argc; j++)
2816
0
    real_argv[i++] = the_argv[j];
2817
2818
0
  real_argv[i] = NULL;
2819
2820
0
  g_free (*argv);
2821
0
  *argv = real_argv;
2822
0
  *argc = real_argc;
2823
2824
0
  return TRUE;
2825
#else
2826
  return FALSE;
2827
#endif /* G_OS_WIN32 */
2828
0
}
2829
2830
static GList *
2831
create_files_for_uris (GList *uris)
2832
0
{
2833
0
  GList *res;
2834
0
  GList *iter;
2835
2836
0
  res = NULL;
2837
2838
0
  for (iter = uris; iter; iter = iter->next)
2839
0
    {
2840
0
      GFile *file = g_file_new_for_uri ((char *)iter->data);
2841
0
      res = g_list_prepend (res, file);
2842
0
    }
2843
2844
0
  return g_list_reverse (res);
2845
0
}
2846
2847
static void
2848
notify_desktop_launch (GDBusConnection  *session_bus,
2849
                       GDesktopAppInfo  *info,
2850
                       long              pid,
2851
                       const char       *display,
2852
                       const char       *sn_id,
2853
                       GList            *uris)
2854
0
{
2855
0
  GDBusMessage *msg;
2856
0
  GVariantBuilder uri_variant;
2857
0
  GVariantBuilder extras_variant;
2858
0
  GList *iter;
2859
0
  const char *desktop_file_id;
2860
0
  const char *gio_desktop_file;
2861
2862
0
  if (session_bus == NULL)
2863
0
    return;
2864
2865
0
  g_variant_builder_init_static (&uri_variant, G_VARIANT_TYPE ("as"));
2866
0
  for (iter = uris; iter; iter = iter->next)
2867
0
    g_variant_builder_add (&uri_variant, "s", iter->data);
2868
2869
0
  g_variant_builder_init_static (&extras_variant, G_VARIANT_TYPE ("a{sv}"));
2870
0
  if (sn_id != NULL && g_utf8_validate (sn_id, -1, NULL))
2871
0
    g_variant_builder_add (&extras_variant, "{sv}",
2872
0
                           "startup-id",
2873
0
                           g_variant_new ("s",
2874
0
                                          sn_id));
2875
0
  gio_desktop_file = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
2876
0
  if (gio_desktop_file != NULL)
2877
0
    g_variant_builder_add (&extras_variant, "{sv}",
2878
0
                           "origin-desktop-file",
2879
0
                           g_variant_new_bytestring (gio_desktop_file));
2880
0
  if (g_get_prgname () != NULL)
2881
0
    g_variant_builder_add (&extras_variant, "{sv}",
2882
0
                           "origin-prgname",
2883
0
                           g_variant_new_bytestring (g_get_prgname ()));
2884
0
  g_variant_builder_add (&extras_variant, "{sv}",
2885
0
                         "origin-pid",
2886
0
                         g_variant_new ("x",
2887
0
                                        (gint64)getpid ()));
2888
2889
0
  if (info->filename)
2890
0
    desktop_file_id = info->filename;
2891
0
  else if (info->desktop_id)
2892
0
    desktop_file_id = info->desktop_id;
2893
0
  else
2894
0
    desktop_file_id = "";
2895
2896
0
  msg = g_dbus_message_new_signal ("/org/gtk/gio/DesktopAppInfo",
2897
0
                                   "org.gtk.gio.DesktopAppInfo",
2898
0
                                   "Launched");
2899
0
  g_dbus_message_set_body (msg, g_variant_new ("(@aysxasa{sv})",
2900
0
                                               g_variant_new_bytestring (desktop_file_id),
2901
0
                                               display ? display : "",
2902
0
                                               (gint64)pid,
2903
0
                                               &uri_variant,
2904
0
                                               &extras_variant));
2905
0
  g_dbus_connection_send_message (session_bus,
2906
0
                                  msg, 0,
2907
0
                                  NULL,
2908
0
                                  NULL);
2909
0
  g_object_unref (msg);
2910
0
}
2911
2912
static void
2913
emit_launch_started (GAppLaunchContext *context,
2914
                     GDesktopAppInfo   *info,
2915
                     const gchar       *startup_id)
2916
0
{
2917
0
  GVariantBuilder builder;
2918
0
  GVariant *platform_data = NULL;
2919
2920
0
  if (startup_id)
2921
0
    {
2922
0
      g_variant_builder_init_static (&builder, G_VARIANT_TYPE_ARRAY);
2923
0
      g_variant_builder_add (&builder, "{sv}",
2924
0
                             "startup-notification-id",
2925
0
                             g_variant_new_string (startup_id));
2926
0
      platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
2927
0
    }
2928
0
  g_signal_emit_by_name (context, "launch-started", info, platform_data);
2929
0
  g_clear_pointer (&platform_data, g_variant_unref);
2930
0
}
2931
2932
0
#define _SPAWN_FLAGS_DEFAULT (G_SPAWN_SEARCH_PATH)
2933
2934
static gboolean
2935
g_desktop_app_info_launch_uris_with_spawn (GDesktopAppInfo            *info,
2936
                                           GDBusConnection            *session_bus,
2937
                                           const gchar                *exec_line,
2938
                                           GList                      *uris,
2939
                                           GAppLaunchContext          *launch_context,
2940
                                           GSpawnFlags                 spawn_flags,
2941
                                           GSpawnChildSetupFunc        user_setup,
2942
                                           gpointer                    user_setup_data,
2943
                                           GDesktopAppLaunchCallback   pid_callback,
2944
                                           gpointer                    pid_callback_data,
2945
                                           gint                        stdin_fd,
2946
                                           gint                        stdout_fd,
2947
                                           gint                        stderr_fd,
2948
                                           GError                    **error)
2949
0
{
2950
0
  gboolean completed = FALSE;
2951
0
  GList *old_uris;
2952
0
  GList *dup_uris;
2953
0
  GList *ruris = NULL;
2954
2955
0
  char **argv, **envp;
2956
0
  int argc;
2957
2958
0
  g_return_val_if_fail (info != NULL, FALSE);
2959
2960
0
  argv = NULL;
2961
2962
0
  if (launch_context)
2963
0
    envp = g_app_launch_context_get_environment (launch_context);
2964
0
  else
2965
0
    envp = g_get_environ ();
2966
2967
0
#ifdef G_OS_UNIX
2968
0
  if (uris && info->keyfile)
2969
0
    {
2970
0
      char *snap_instance;
2971
0
      char *app_id = NULL;
2972
2973
0
      snap_instance = g_desktop_app_info_get_string (info, "X-SnapInstanceName");
2974
2975
0
      if (snap_instance && *snap_instance)
2976
0
        app_id = g_strconcat ("snap.", snap_instance, NULL);
2977
2978
0
      g_free (snap_instance);
2979
2980
0
      if (app_id)
2981
0
        {
2982
0
          ruris = g_document_portal_add_documents (uris, app_id, NULL);
2983
0
          if (ruris != NULL)
2984
0
            uris = ruris;
2985
0
        }
2986
2987
0
      g_clear_pointer (&app_id, g_free);
2988
0
    }
2989
0
#endif
2990
2991
  /* The GList* passed to expand_application_parameters() will be modified
2992
   * internally by expand_macro(), so we need to pass a copy of it instead,
2993
   * and also use that copy to control the exit condition of the loop below.
2994
   */
2995
0
  dup_uris = uris;
2996
0
  do
2997
0
    {
2998
0
      GPid pid;
2999
0
      GList *launched_uris;
3000
0
      GList *iter;
3001
0
      char *sn_id = NULL;
3002
0
      char **wrapped_argv;
3003
0
      size_t i;
3004
3005
0
      old_uris = dup_uris;
3006
0
      if (!expand_application_parameters (info, exec_line, &dup_uris, &argc, &argv, error))
3007
0
        goto out;
3008
3009
      /* Get the subset of URIs we're launching with this process */
3010
0
      launched_uris = NULL;
3011
0
      for (iter = old_uris; iter != NULL && iter != dup_uris; iter = iter->next)
3012
0
        launched_uris = g_list_prepend (launched_uris, iter->data);
3013
0
      launched_uris = g_list_reverse (launched_uris);
3014
3015
0
      if (info->terminal && !prepend_terminal_to_vector (&argc, &argv,
3016
0
                                                         g_environ_getenv (envp, "PATH"),
3017
0
                                                         info->path))
3018
0
        {
3019
0
          g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
3020
0
                               _("Unable to find terminal required for application"));
3021
0
          goto out;
3022
0
        }
3023
3024
0
      if (info->filename)
3025
0
        envp = g_environ_setenv (envp,
3026
0
                                 "GIO_LAUNCHED_DESKTOP_FILE",
3027
0
                                 info->filename,
3028
0
                                 TRUE);
3029
3030
0
      sn_id = NULL;
3031
0
      if (launch_context)
3032
0
        {
3033
0
          GList *launched_files = create_files_for_uris (launched_uris);
3034
3035
0
          if (info->startup_notify)
3036
0
            {
3037
0
              sn_id = g_app_launch_context_get_startup_notify_id (launch_context,
3038
0
                                                                  G_APP_INFO (info),
3039
0
                                                                  launched_files);
3040
0
              if (sn_id)
3041
0
                {
3042
0
                  envp = g_environ_setenv (envp, "DESKTOP_STARTUP_ID", sn_id, TRUE);
3043
0
                  envp = g_environ_setenv (envp, "XDG_ACTIVATION_TOKEN", sn_id, TRUE);
3044
0
                }
3045
0
            }
3046
3047
0
          g_list_free_full (launched_files, g_object_unref);
3048
3049
0
          emit_launch_started (launch_context, info, sn_id);
3050
0
        }
3051
3052
0
      g_assert (argc > 0);
3053
3054
0
      if (!g_path_is_absolute (argv[0]) ||
3055
0
          !g_file_test (argv[0], G_FILE_TEST_IS_EXECUTABLE) ||
3056
0
          g_file_test (argv[0], G_FILE_TEST_IS_DIR))
3057
0
        {
3058
0
          char *program = g_strdup (argv[0]);
3059
0
          char *program_path = NULL;
3060
3061
0
          if (!g_path_is_absolute (program))
3062
0
            {
3063
0
              const char *env_path = g_environ_getenv (envp, "PATH");
3064
3065
0
              program_path = GLIB_PRIVATE_CALL (g_find_program_for_path) (program,
3066
0
                                                                          env_path,
3067
0
                                                                          info->path);
3068
0
            }
3069
3070
0
          if (program_path)
3071
0
            {
3072
0
              g_free (argv[0]);
3073
0
              argv[0] = g_steal_pointer (&program_path);
3074
0
            }
3075
0
          else
3076
0
            {
3077
0
              if (sn_id)
3078
0
                g_app_launch_context_launch_failed (launch_context, sn_id);
3079
3080
0
              g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT,
3081
0
                           _("Program ‘%s’ not found in $PATH"),
3082
0
                           program);
3083
3084
0
              g_free (program);
3085
0
              g_clear_pointer (&sn_id, g_free);
3086
0
              g_clear_list (&launched_uris, NULL);
3087
0
              goto out;
3088
0
            }
3089
3090
0
          g_free (program);
3091
0
        }
3092
3093
0
      if (g_once_init_enter_pointer (&gio_launch_desktop_path))
3094
0
        {
3095
0
          const gchar *tmp = NULL;
3096
0
          gboolean is_setuid = GLIB_PRIVATE_CALL (g_check_setuid) ();
3097
3098
          /* Allow test suite to specify path to gio-launch-desktop */
3099
0
          if (!is_setuid)
3100
0
            tmp = g_getenv ("GIO_LAUNCH_DESKTOP");
3101
3102
          /* Allow build system to specify path to gio-launch-desktop */
3103
0
          if (tmp == NULL && g_file_test (GIO_LAUNCH_DESKTOP, G_FILE_TEST_IS_EXECUTABLE))
3104
0
            tmp = GIO_LAUNCH_DESKTOP;
3105
3106
          /* Fall back on usual searching in $PATH */
3107
0
          if (tmp == NULL)
3108
0
            tmp = "gio-launch-desktop";
3109
0
          g_once_init_leave_pointer (&gio_launch_desktop_path, tmp);
3110
0
        }
3111
3112
0
      wrapped_argv = g_new (char *, (size_t) argc + 2);
3113
0
      wrapped_argv[0] = g_strdup (gio_launch_desktop_path);
3114
3115
0
      for (i = 0; i < (size_t) argc; i++)
3116
0
        wrapped_argv[i + 1] = g_steal_pointer (&argv[i]);
3117
3118
0
      wrapped_argv[i + 1] = NULL;
3119
0
      g_free (argv);
3120
0
      argv = NULL;
3121
3122
0
      if (!g_spawn_async_with_fds (info->path,
3123
0
                                   wrapped_argv,
3124
0
                                   envp,
3125
0
                                   spawn_flags,
3126
0
                                   user_setup,
3127
0
                                   user_setup_data,
3128
0
                                   &pid,
3129
0
                                   stdin_fd,
3130
0
                                   stdout_fd,
3131
0
                                   stderr_fd,
3132
0
                                   error))
3133
0
        {
3134
0
          if (sn_id)
3135
0
            g_app_launch_context_launch_failed (launch_context, sn_id);
3136
3137
0
          g_free (sn_id);
3138
0
          g_list_free (launched_uris);
3139
0
          g_clear_pointer (&wrapped_argv, g_strfreev);
3140
3141
0
          goto out;
3142
0
        }
3143
3144
0
      if (pid_callback != NULL)
3145
0
        pid_callback (info, pid, pid_callback_data);
3146
3147
0
      if (launch_context != NULL)
3148
0
        {
3149
0
          GVariantBuilder builder;
3150
0
          GVariant *platform_data;
3151
3152
0
          g_variant_builder_init_static (&builder, G_VARIANT_TYPE_ARRAY);
3153
0
          g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (pid));
3154
0
          if (sn_id)
3155
0
            g_variant_builder_add (&builder, "{sv}", "startup-notification-id", g_variant_new_string (sn_id));
3156
0
          platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
3157
0
          g_signal_emit_by_name (launch_context, "launched", info, platform_data);
3158
0
          g_variant_unref (platform_data);
3159
0
        }
3160
3161
0
      notify_desktop_launch (session_bus,
3162
0
                             info,
3163
0
                             pid,
3164
0
                             NULL,
3165
0
                             sn_id,
3166
0
                             launched_uris);
3167
3168
0
      g_free (sn_id);
3169
0
      g_list_free (launched_uris);
3170
3171
0
      g_strfreev (wrapped_argv);
3172
0
      wrapped_argv = NULL;
3173
0
    }
3174
0
  while (dup_uris != NULL);
3175
3176
0
  completed = TRUE;
3177
3178
0
 out:
3179
0
  g_strfreev (argv);
3180
0
  g_strfreev (envp);
3181
0
  g_list_free_full (ruris, g_free);
3182
3183
0
  return completed;
3184
0
}
3185
3186
static gchar *
3187
object_path_from_appid (const gchar *appid)
3188
0
{
3189
0
  gchar *appid_path, *iter;
3190
3191
0
  appid_path = g_strconcat ("/", appid, NULL);
3192
0
  for (iter = appid_path; *iter; iter++)
3193
0
    {
3194
0
      if (*iter == '.')
3195
0
        *iter = '/';
3196
3197
0
      if (*iter == '-')
3198
0
        *iter = '_';
3199
0
    }
3200
3201
0
  return appid_path;
3202
0
}
3203
3204
static GVariant *
3205
g_desktop_app_info_make_platform_data (GDesktopAppInfo   *info,
3206
                                       GList             *uris,
3207
                                       GAppLaunchContext *launch_context)
3208
0
{
3209
0
  GVariantBuilder builder;
3210
3211
0
  g_variant_builder_init_static (&builder, G_VARIANT_TYPE_VARDICT);
3212
3213
0
  if (launch_context)
3214
0
    {
3215
0
      GList *launched_files = create_files_for_uris (uris);
3216
3217
0
      if (info->startup_notify)
3218
0
        {
3219
0
          gchar *sn_id;
3220
3221
0
          sn_id = g_app_launch_context_get_startup_notify_id (launch_context, G_APP_INFO (info), launched_files);
3222
0
          if (sn_id)
3223
0
            {
3224
0
              g_variant_builder_add (&builder, "{sv}", "desktop-startup-id", g_variant_new_string (sn_id));
3225
0
              g_variant_builder_add (&builder, "{sv}", "activation-token", g_variant_new_take_string (g_steal_pointer (&sn_id)));
3226
0
            }
3227
0
        }
3228
3229
0
      g_list_free_full (launched_files, g_object_unref);
3230
0
    }
3231
3232
0
  return g_variant_builder_end (&builder);
3233
0
}
3234
3235
typedef struct
3236
{
3237
  GDesktopAppInfo     *info; /* (owned) */
3238
  GAppLaunchContext   *launch_context; /* (owned) (nullable) */
3239
  GAsyncReadyCallback  callback;
3240
  gchar               *startup_id; /* (owned) (nullable) */
3241
  gpointer             user_data;
3242
} LaunchUrisWithDBusData;
3243
3244
static void
3245
launch_uris_with_dbus_data_free (LaunchUrisWithDBusData *data)
3246
0
{
3247
0
  g_clear_object (&data->info);
3248
0
  g_clear_object (&data->launch_context);
3249
0
  g_free (data->startup_id);
3250
3251
0
  g_free (data);
3252
0
}
3253
3254
static void
3255
launch_uris_with_dbus_signal_cb (GObject      *object,
3256
                                 GAsyncResult *result,
3257
                                 gpointer      user_data)
3258
0
{
3259
0
  LaunchUrisWithDBusData *data = user_data;
3260
0
  GVariantBuilder builder;
3261
3262
0
  if (data->launch_context)
3263
0
    {
3264
0
      if (g_task_had_error (G_TASK (result)))
3265
0
        {
3266
0
          if (data->startup_id != NULL)
3267
0
            g_app_launch_context_launch_failed (data->launch_context, data->startup_id);
3268
0
        }
3269
0
      else
3270
0
        {
3271
0
          GVariant *platform_data;
3272
3273
0
          g_variant_builder_init_static (&builder, G_VARIANT_TYPE_ARRAY);
3274
          /* the docs guarantee `pid` will be set, but we can’t
3275
           * easily know it for a D-Bus process, so set it to zero */
3276
0
          g_variant_builder_add (&builder, "{sv}", "pid", g_variant_new_int32 (0));
3277
0
          if (data->startup_id)
3278
0
            g_variant_builder_add (&builder, "{sv}",
3279
0
                                   "startup-notification-id",
3280
0
                                   g_variant_new_string (data->startup_id));
3281
0
          platform_data = g_variant_ref_sink (g_variant_builder_end (&builder));
3282
0
          g_signal_emit_by_name (data->launch_context,
3283
0
                                 "launched",
3284
0
                                 data->info,
3285
0
                                 platform_data);
3286
0
          g_variant_unref (platform_data);
3287
0
        }
3288
0
    }
3289
3290
0
  if (data->callback)
3291
0
    data->callback (object, result, data->user_data);
3292
0
  else if (!g_task_had_error (G_TASK (result)))
3293
0
    g_variant_unref (g_dbus_connection_call_finish (G_DBUS_CONNECTION (object),
3294
0
                                                    result, NULL));
3295
3296
0
  launch_uris_with_dbus_data_free (data);
3297
0
}
3298
3299
static void
3300
launch_uris_with_dbus (GDesktopAppInfo    *info,
3301
                       GDBusConnection    *session_bus,
3302
                       GList              *uris,
3303
                       GAppLaunchContext  *launch_context,
3304
                       GCancellable       *cancellable,
3305
                       GAsyncReadyCallback callback,
3306
                       gpointer            user_data)
3307
0
{
3308
0
  GVariant *platform_data;
3309
0
  GVariantBuilder builder;
3310
0
  GVariantDict dict;
3311
0
  gchar *object_path;
3312
0
  LaunchUrisWithDBusData *data;
3313
3314
0
  g_variant_builder_init_static (&builder, G_VARIANT_TYPE_TUPLE);
3315
3316
0
  if (uris)
3317
0
    {
3318
0
      GList *iter;
3319
3320
0
      g_variant_builder_open (&builder, G_VARIANT_TYPE_STRING_ARRAY);
3321
0
      for (iter = uris; iter; iter = iter->next)
3322
0
        g_variant_builder_add (&builder, "s", iter->data);
3323
0
      g_variant_builder_close (&builder);
3324
0
    }
3325
3326
0
  platform_data = g_desktop_app_info_make_platform_data (info, uris, launch_context);
3327
3328
0
  g_variant_builder_add_value (&builder, platform_data);
3329
0
  object_path = object_path_from_appid (info->app_id);
3330
3331
0
  data = g_new0 (LaunchUrisWithDBusData, 1);
3332
0
  data->info = g_object_ref (info);
3333
0
  data->callback = callback;
3334
0
  data->user_data = user_data;
3335
0
  data->launch_context = launch_context ? g_object_ref (launch_context) : NULL;
3336
0
  g_variant_dict_init (&dict, platform_data);
3337
0
  g_variant_dict_lookup (&dict, "desktop-startup-id", "s", &data->startup_id);
3338
3339
0
  if (launch_context)
3340
0
    emit_launch_started (launch_context, info, data->startup_id);
3341
3342
0
  g_dbus_connection_call (session_bus, info->app_id, object_path, "org.freedesktop.Application",
3343
0
                          uris ? "Open" : "Activate", g_variant_builder_end (&builder),
3344
0
                          NULL, G_DBUS_CALL_FLAGS_NONE, -1,
3345
0
                          cancellable, launch_uris_with_dbus_signal_cb, g_steal_pointer (&data));
3346
0
  g_free (object_path);
3347
3348
0
  g_variant_dict_clear (&dict);
3349
0
}
3350
3351
static gboolean
3352
g_desktop_app_info_launch_uris_with_dbus (GDesktopAppInfo    *info,
3353
                                          GDBusConnection    *session_bus,
3354
                                          GList              *uris,
3355
                                          GAppLaunchContext  *launch_context,
3356
                                          GCancellable       *cancellable,
3357
                                          GAsyncReadyCallback callback,
3358
                                          gpointer            user_data)
3359
0
{
3360
0
  GList *ruris = uris;
3361
0
  char *app_id = NULL;
3362
3363
0
  g_return_val_if_fail (info != NULL, FALSE);
3364
3365
0
#ifdef G_OS_UNIX
3366
0
  app_id = g_desktop_app_info_get_string (info, "X-Flatpak");
3367
3368
0
  if (!app_id)
3369
0
    {
3370
0
      char *snap_instance;
3371
3372
0
      snap_instance = g_desktop_app_info_get_string (info, "X-SnapInstanceName");
3373
3374
0
      if (snap_instance && *snap_instance)
3375
0
        app_id = g_strconcat ("snap.", snap_instance, NULL);
3376
3377
0
      g_free (snap_instance);
3378
0
    }
3379
3380
0
  if (app_id && *app_id)
3381
0
    {
3382
0
      ruris = g_document_portal_add_documents (uris, app_id, NULL);
3383
0
      if (ruris == NULL)
3384
0
        ruris = uris;
3385
0
    }
3386
3387
0
  g_clear_pointer (&app_id, g_free);
3388
0
#endif
3389
3390
0
  launch_uris_with_dbus (info, session_bus, ruris, launch_context,
3391
0
                         cancellable, callback, user_data);
3392
3393
0
  if (ruris != uris)
3394
0
    g_list_free_full (ruris, g_free);
3395
3396
0
  return TRUE;
3397
0
}
3398
3399
static gboolean
3400
g_desktop_app_info_launch_uris_internal (GAppInfo                   *appinfo,
3401
                                         GList                      *uris,
3402
                                         GAppLaunchContext          *launch_context,
3403
                                         GSpawnFlags                 spawn_flags,
3404
                                         GSpawnChildSetupFunc        user_setup,
3405
                                         gpointer                    user_setup_data,
3406
                                         GDesktopAppLaunchCallback   pid_callback,
3407
                                         gpointer                    pid_callback_data,
3408
                                         gint                        stdin_fd,
3409
                                         gint                        stdout_fd,
3410
                                         gint                        stderr_fd,
3411
                                         GError                     **error)
3412
0
{
3413
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3414
0
  GDBusConnection *session_bus;
3415
0
  gboolean success = TRUE;
3416
3417
0
  session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
3418
3419
0
  if (session_bus && info->app_id)
3420
    /* This is non-blocking API. Similar to launching via fork()/exec()
3421
     * we don't wait around to see if the program crashed during startup.
3422
     * This is what startup-notification's job is...
3423
     */
3424
0
    g_desktop_app_info_launch_uris_with_dbus (info, session_bus, uris, launch_context,
3425
0
                                              NULL, NULL, NULL);
3426
0
  else
3427
0
    success = g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec, uris, launch_context,
3428
0
                                                         spawn_flags, user_setup, user_setup_data,
3429
0
                                                         pid_callback, pid_callback_data,
3430
0
                                                         stdin_fd, stdout_fd, stderr_fd, error);
3431
3432
0
  if (session_bus != NULL)
3433
0
    {
3434
      /* This asynchronous flush holds a reference until it completes,
3435
       * which ensures that the following unref won't immediately kill
3436
       * the connection if we were the initial owner.
3437
       */
3438
0
      g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
3439
0
      g_object_unref (session_bus);
3440
0
    }
3441
3442
0
  return success;
3443
0
}
3444
3445
static gboolean
3446
g_desktop_app_info_launch_uris (GAppInfo           *appinfo,
3447
                                GList              *uris,
3448
                                GAppLaunchContext  *launch_context,
3449
                                GError            **error)
3450
0
{
3451
0
  return g_desktop_app_info_launch_uris_internal (appinfo, uris,
3452
0
                                                  launch_context,
3453
0
                                                  _SPAWN_FLAGS_DEFAULT,
3454
0
                                                  NULL, NULL, NULL, NULL,
3455
0
                                                  -1, -1, -1,
3456
0
                                                  error);
3457
0
}
3458
3459
typedef struct
3460
{
3461
  GList *uris;  /* (element-type utf8) (owned) (nullable) */
3462
  GAppLaunchContext *context;  /* (owned) (nullable) */
3463
} LaunchUrisData;
3464
3465
static void
3466
launch_uris_data_free (LaunchUrisData *data)
3467
0
{
3468
0
  g_clear_object (&data->context);
3469
0
  g_list_free_full (data->uris, g_free);
3470
0
  g_free (data);
3471
0
}
3472
3473
static void
3474
launch_uris_with_dbus_cb (GObject      *object,
3475
                          GAsyncResult *result,
3476
                          gpointer      user_data)
3477
0
{
3478
0
  GTask *task = G_TASK (user_data);
3479
0
  GError *local_error = NULL;
3480
0
  GVariant *ret;
3481
3482
0
  ret = g_dbus_connection_call_finish (G_DBUS_CONNECTION (object), result, &local_error);
3483
0
  if (local_error != NULL)
3484
0
    {
3485
0
      g_dbus_error_strip_remote_error (local_error);
3486
0
      g_task_return_error (task, g_steal_pointer (&local_error));
3487
0
    }
3488
0
  else
3489
0
    {
3490
0
      g_task_return_boolean (task, TRUE);
3491
0
      g_variant_unref (ret);
3492
0
    }
3493
3494
0
  g_object_unref (task);
3495
0
}
3496
3497
static void
3498
launch_uris_flush_cb (GObject      *object,
3499
                      GAsyncResult *result,
3500
                      gpointer      user_data)
3501
0
{
3502
0
  GTask *task = G_TASK (user_data);
3503
3504
0
  g_dbus_connection_flush_finish (G_DBUS_CONNECTION (object), result, NULL);
3505
0
  g_task_return_boolean (task, TRUE);
3506
0
  g_object_unref (task);
3507
0
}
3508
3509
static void
3510
launch_uris_bus_get_cb (GObject      *object,
3511
                        GAsyncResult *result,
3512
                        gpointer      user_data)
3513
0
{
3514
0
  GTask *task = G_TASK (user_data);
3515
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (g_task_get_source_object (task));
3516
0
  LaunchUrisData *data = g_task_get_task_data (task);
3517
0
  GCancellable *cancellable = g_task_get_cancellable (task);
3518
0
  GDBusConnection *session_bus;
3519
0
  GError *local_error = NULL;
3520
3521
0
  session_bus = g_bus_get_finish (result, NULL);
3522
3523
0
  if (session_bus && info->app_id)
3524
0
    {
3525
      /* FIXME: The g_document_portal_add_documents() function, which is called
3526
       * from the g_desktop_app_info_launch_uris_with_dbus() function, still
3527
       * uses blocking calls.
3528
       */
3529
0
      g_desktop_app_info_launch_uris_with_dbus (info, session_bus,
3530
0
                                                data->uris, data->context,
3531
0
                                                cancellable,
3532
0
                                                launch_uris_with_dbus_cb,
3533
0
                                                g_steal_pointer (&task));
3534
0
    }
3535
0
  else
3536
0
    {
3537
      /* FIXME: The D-Bus message from the notify_desktop_launch() function
3538
       * can be still lost even if flush is called later. See:
3539
       * https://gitlab.freedesktop.org/dbus/dbus/issues/72
3540
       */
3541
0
      g_desktop_app_info_launch_uris_with_spawn (info, session_bus, info->exec,
3542
0
                                                 data->uris, data->context,
3543
0
                                                 _SPAWN_FLAGS_DEFAULT, NULL,
3544
0
                                                 NULL, NULL, NULL, -1, -1, -1,
3545
0
                                                 &local_error);
3546
0
      if (local_error != NULL)
3547
0
        {
3548
0
          g_task_return_error (task, g_steal_pointer (&local_error));
3549
0
          g_object_unref (task);
3550
0
        }
3551
0
      else if (session_bus)
3552
0
        g_dbus_connection_flush (session_bus,
3553
0
                                 cancellable,
3554
0
                                 launch_uris_flush_cb,
3555
0
                                 g_steal_pointer (&task));
3556
0
      else
3557
0
        {
3558
0
          g_task_return_boolean (task, TRUE);
3559
0
          g_clear_object (&task);
3560
0
        }
3561
0
    }
3562
3563
0
  g_clear_object (&session_bus);
3564
0
}
3565
3566
static void
3567
g_desktop_app_info_launch_uris_async (GAppInfo           *appinfo,
3568
                                      GList              *uris,
3569
                                      GAppLaunchContext  *context,
3570
                                      GCancellable       *cancellable,
3571
                                      GAsyncReadyCallback callback,
3572
                                      gpointer            user_data)
3573
0
{
3574
0
  GTask *task;
3575
0
  LaunchUrisData *data;
3576
3577
0
  task = g_task_new (appinfo, cancellable, callback, user_data);
3578
0
  g_task_set_source_tag (task, g_desktop_app_info_launch_uris_async);
3579
3580
0
  data = g_new0 (LaunchUrisData, 1);
3581
0
  data->uris = g_list_copy_deep (uris, (GCopyFunc) g_strdup, NULL);
3582
0
  g_set_object (&data->context, context);
3583
0
  g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) launch_uris_data_free);
3584
3585
0
  g_bus_get (G_BUS_TYPE_SESSION, cancellable, launch_uris_bus_get_cb, task);
3586
0
}
3587
3588
static gboolean
3589
g_desktop_app_info_launch_uris_finish (GAppInfo     *appinfo,
3590
                                       GAsyncResult *result,
3591
                                       GError      **error)
3592
0
{
3593
0
  g_return_val_if_fail (g_task_is_valid (result, appinfo), FALSE);
3594
3595
0
  return g_task_propagate_boolean (G_TASK (result), error);
3596
0
}
3597
3598
static gboolean
3599
g_desktop_app_info_supports_uris (GAppInfo *appinfo)
3600
0
{
3601
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3602
3603
0
  return info->exec &&
3604
0
    ((strstr (info->exec, "%u") != NULL) ||
3605
0
     (strstr (info->exec, "%U") != NULL));
3606
0
}
3607
3608
static gboolean
3609
g_desktop_app_info_supports_files (GAppInfo *appinfo)
3610
0
{
3611
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3612
3613
0
  return info->exec &&
3614
0
    ((strstr (info->exec, "%f") != NULL) ||
3615
0
     (strstr (info->exec, "%F") != NULL));
3616
0
}
3617
3618
static gboolean
3619
g_desktop_app_info_launch (GAppInfo           *appinfo,
3620
                           GList              *files,
3621
                           GAppLaunchContext  *launch_context,
3622
                           GError            **error)
3623
0
{
3624
0
  GList *uris;
3625
0
  char *uri;
3626
0
  gboolean res;
3627
3628
0
  uris = NULL;
3629
0
  while (files)
3630
0
    {
3631
0
      uri = g_file_get_uri (files->data);
3632
0
      uris = g_list_prepend (uris, uri);
3633
0
      files = files->next;
3634
0
    }
3635
3636
0
  uris = g_list_reverse (uris);
3637
3638
0
  res = g_desktop_app_info_launch_uris (appinfo, uris, launch_context, error);
3639
3640
0
  g_list_free_full (uris, g_free);
3641
3642
0
  return res;
3643
0
}
3644
3645
/**
3646
 * g_desktop_app_info_launch_uris_as_manager_with_fds:
3647
 * @appinfo: a [class@GioUnix.DesktopAppInfo]
3648
 * @uris: (element-type utf8): List of URIs
3649
 * @launch_context: (nullable): a [class@Gio.AppLaunchContext]
3650
 * @spawn_flags: [flags@GLib.SpawnFlags], used for each process
3651
 * @user_setup: (scope async) (nullable) (closure user_setup_data): a
3652
 *   [callback@GLib.SpawnChildSetupFunc], used once for each process.
3653
 * @user_setup_data: User data for @user_setup
3654
 * @pid_callback: (scope call) (nullable) (closure pid_callback_data): Callback for child processes
3655
 * @pid_callback_data: User data for @callback
3656
 * @stdin_fd: file descriptor to use for child’s stdin, or `-1`
3657
 * @stdout_fd: file descriptor to use for child’s stdout, or `-1`
3658
 * @stderr_fd: file descriptor to use for child’s stderr, or `-1`
3659
 * @error: return location for a #GError, or `NULL`
3660
 *
3661
 * Equivalent to [method@GioUnix.DesktopAppInfo.launch_uris_as_manager] but
3662
 * allows you to pass in file descriptors for the stdin, stdout and stderr
3663
 * streams of the launched process.
3664
 *
3665
 * If application launching occurs via some non-spawn mechanism (e.g. D-Bus
3666
 * activation) then @stdin_fd, @stdout_fd and @stderr_fd are ignored.
3667
 *
3668
 * Returns: `TRUE` on successful launch, `FALSE` otherwise.
3669
 *
3670
 * Since: 2.58
3671
 */
3672
gboolean
3673
g_desktop_app_info_launch_uris_as_manager_with_fds (GDesktopAppInfo            *appinfo,
3674
                                                    GList                      *uris,
3675
                                                    GAppLaunchContext          *launch_context,
3676
                                                    GSpawnFlags                 spawn_flags,
3677
                                                    GSpawnChildSetupFunc        user_setup,
3678
                                                    gpointer                    user_setup_data,
3679
                                                    GDesktopAppLaunchCallback   pid_callback,
3680
                                                    gpointer                    pid_callback_data,
3681
                                                    gint                        stdin_fd,
3682
                                                    gint                        stdout_fd,
3683
                                                    gint                        stderr_fd,
3684
                                                    GError                    **error)
3685
0
{
3686
0
  return g_desktop_app_info_launch_uris_internal ((GAppInfo*)appinfo,
3687
0
                                                  uris,
3688
0
                                                  launch_context,
3689
0
                                                  spawn_flags,
3690
0
                                                  user_setup,
3691
0
                                                  user_setup_data,
3692
0
                                                  pid_callback,
3693
0
                                                  pid_callback_data,
3694
0
                                                  stdin_fd,
3695
0
                                                  stdout_fd,
3696
0
                                                  stderr_fd,
3697
0
                                                  error);
3698
0
}
3699
3700
/**
3701
 * g_desktop_app_info_launch_uris_as_manager:
3702
 * @appinfo: a [class@GioUnix.DesktopAppInfo]
3703
 * @uris: (element-type utf8): List of URIs
3704
 * @launch_context: (nullable): a [class@Gio.AppLaunchContext]
3705
 * @spawn_flags: [flags@GLib.SpawnFlags], used for each process
3706
 * @user_setup: (scope async) (nullable): a [callback@GLib.SpawnChildSetupFunc],
3707
 *   used once  for each process.
3708
 * @user_setup_data: (closure user_setup) (nullable): User data for @user_setup
3709
 * @pid_callback: (scope call) (nullable): Callback for child processes
3710
 * @pid_callback_data: (closure pid_callback) (nullable): User data for @callback
3711
 * @error: return location for a #GError, or `NULL`
3712
 *
3713
 * This function performs the equivalent of [method@Gio.AppInfo.launch_uris],
3714
 * but is intended primarily for operating system components that
3715
 * launch applications.  Ordinary applications should use
3716
 * [method@Gio.AppInfo.launch_uris].
3717
 *
3718
 * If the application is launched via GSpawn, then @spawn_flags, @user_setup
3719
 * and @user_setup_data are used for the call to [func@GLib.spawn_async].
3720
 * Additionally, @pid_callback (with @pid_callback_data) will be called to
3721
 * inform about the PID of the created process. See
3722
 * [func@GLib.spawn_async_with_pipes] for information on certain parameter
3723
 * conditions that can enable an optimized [`posix_spawn()`](man:posix_spawn(3))
3724
 * code path to be used.
3725
 *
3726
 * If application launching occurs via some other mechanism (for example, D-Bus
3727
 * activation) then @spawn_flags, @user_setup, @user_setup_data,
3728
 * @pid_callback and @pid_callback_data are ignored.
3729
 *
3730
 * Returns: `TRUE` on successful launch, `FALSE` otherwise.
3731
 */
3732
gboolean
3733
g_desktop_app_info_launch_uris_as_manager (GDesktopAppInfo            *appinfo,
3734
                                           GList                      *uris,
3735
                                           GAppLaunchContext          *launch_context,
3736
                                           GSpawnFlags                 spawn_flags,
3737
                                           GSpawnChildSetupFunc        user_setup,
3738
                                           gpointer                    user_setup_data,
3739
                                           GDesktopAppLaunchCallback   pid_callback,
3740
                                           gpointer                    pid_callback_data,
3741
                                           GError                    **error)
3742
0
{
3743
0
  return g_desktop_app_info_launch_uris_as_manager_with_fds (appinfo,
3744
0
                                                             uris,
3745
0
                                                             launch_context,
3746
0
                                                             spawn_flags,
3747
0
                                                             user_setup,
3748
0
                                                             user_setup_data,
3749
0
                                                             pid_callback,
3750
0
                                                             pid_callback_data,
3751
0
                                                             -1, -1, -1,
3752
0
                                                             error);
3753
0
}
3754
3755
/* OnlyShowIn API support {{{2 */
3756
3757
/**
3758
 * g_desktop_app_info_set_desktop_env:
3759
 * @desktop_env: a string specifying what desktop this is
3760
 *
3761
 * Sets the name of the desktop that the application is running in.
3762
 *
3763
 * This is used by [method@Gio.AppInfo.should_show] and
3764
 * [method@GioUnix.DesktopAppInfo.get_show_in] to evaluate the
3765
 * [`OnlyShowIn`](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-onlyshowin)
3766
 * and [`NotShowIn`](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s06.html#key-notshowin)
3767
 * keys.
3768
 *
3769
 * Should be called only once; subsequent calls are ignored.
3770
 *
3771
 * Deprecated:2.42:do not use this API.  Since 2.42 the value of the
3772
 *   `XDG_CURRENT_DESKTOP` environment variable will be used.
3773
 */
3774
void
3775
g_desktop_app_info_set_desktop_env (const gchar *desktop_env)
3776
0
{
3777
0
  get_current_desktops (desktop_env);
3778
0
}
3779
3780
static gboolean
3781
g_desktop_app_info_should_show (GAppInfo *appinfo)
3782
0
{
3783
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
3784
3785
0
  if (info->nodisplay)
3786
0
    return FALSE;
3787
3788
0
  return g_desktop_app_info_get_show_in (info, NULL);
3789
0
}
3790
3791
/* mime types/default apps support {{{2 */
3792
3793
typedef enum {
3794
  CONF_DIR,
3795
  APP_DIR,
3796
  MIMETYPE_DIR
3797
} DirType;
3798
3799
static char *
3800
ensure_dir (DirType   type,
3801
            GError  **error)
3802
0
{
3803
0
  char *path, *display_name;
3804
0
  int errsv;
3805
3806
0
  switch (type)
3807
0
    {
3808
0
    case CONF_DIR:
3809
0
      path = g_build_filename (g_get_user_config_dir (), NULL);
3810
0
      break;
3811
3812
0
    case APP_DIR:
3813
0
      path = g_build_filename (g_get_user_data_dir (), "applications", NULL);
3814
0
      break;
3815
3816
0
    case MIMETYPE_DIR:
3817
0
      path = g_build_filename (g_get_user_data_dir (), "mime", "packages", NULL);
3818
0
      break;
3819
3820
0
    default:
3821
0
      g_assert_not_reached ();
3822
0
    }
3823
3824
0
  g_debug ("%s: Ensuring %s", G_STRFUNC, path);
3825
3826
0
  errno = 0;
3827
0
  if (g_mkdir_with_parents (path, 0700) == 0)
3828
0
    return path;
3829
3830
0
  errsv = errno;
3831
0
  display_name = g_filename_display_name (path);
3832
0
  if (type == APP_DIR)
3833
0
    g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3834
0
                 _("Can’t create user application configuration folder %s: %s"),
3835
0
                 display_name, g_strerror (errsv));
3836
0
  else
3837
0
    g_set_error (error, G_IO_ERROR, g_io_error_from_errno (errsv),
3838
0
                 _("Can’t create user MIME configuration folder %s: %s"),
3839
0
                 display_name, g_strerror (errsv));
3840
3841
0
  g_free (display_name);
3842
0
  g_free (path);
3843
3844
0
  return NULL;
3845
0
}
3846
3847
static gboolean
3848
update_mimeapps_list (const char  *desktop_id,
3849
                      const char  *content_type,
3850
                      UpdateMimeFlags flags,
3851
                      GError     **error)
3852
0
{
3853
0
  char *dirname, *old_filename, *filename, *string;
3854
0
  GKeyFile *key_file;
3855
0
  gboolean load_succeeded, res;
3856
0
  char **old_list, **list;
3857
0
  gsize length, data_size;
3858
0
  char *data;
3859
0
  char **content_types;
3860
3861
  /* Don't add both at start and end */
3862
0
  g_assert (!((flags & UPDATE_MIME_SET_DEFAULT) &&
3863
0
              (flags & UPDATE_MIME_SET_NON_DEFAULT)));
3864
3865
0
  dirname = ensure_dir (CONF_DIR, error);
3866
0
  if (!dirname)
3867
0
    return FALSE;
3868
3869
0
  filename = g_build_filename (dirname, "mimeapps.list", NULL);
3870
3871
0
  while (g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
3872
0
    {
3873
0
      old_filename = filename;
3874
0
      filename = g_file_read_link (old_filename, error);
3875
0
      g_free (old_filename);
3876
0
      if (filename == NULL)
3877
0
        return FALSE;
3878
0
    }
3879
3880
0
  g_free (dirname);
3881
3882
0
  key_file = g_key_file_new ();
3883
0
  load_succeeded = g_key_file_load_from_file (key_file, filename, G_KEY_FILE_NONE, NULL);
3884
0
  if (!load_succeeded ||
3885
0
      (!g_key_file_has_group (key_file, ADDED_ASSOCIATIONS_GROUP) &&
3886
0
       !g_key_file_has_group (key_file, REMOVED_ASSOCIATIONS_GROUP) &&
3887
0
       !g_key_file_has_group (key_file, DEFAULT_APPLICATIONS_GROUP)))
3888
0
    {
3889
0
      g_key_file_free (key_file);
3890
0
      key_file = g_key_file_new ();
3891
0
    }
3892
3893
0
  if (content_type)
3894
0
    {
3895
0
      content_types = g_new (char *, 2);
3896
0
      content_types[0] = g_strdup (content_type);
3897
0
      content_types[1] = NULL;
3898
0
    }
3899
0
  else
3900
0
    {
3901
0
      content_types = g_key_file_get_keys (key_file, DEFAULT_APPLICATIONS_GROUP, NULL, NULL);
3902
0
    }
3903
3904
0
  for (size_t k = 0; content_types && content_types[k]; k++)
3905
0
    {
3906
      /* set as default, if requested so */
3907
0
      string = g_key_file_get_string (key_file,
3908
0
                                      DEFAULT_APPLICATIONS_GROUP,
3909
0
                                      content_types[k],
3910
0
                                      NULL);
3911
3912
0
      if (g_strcmp0 (string, desktop_id) != 0 &&
3913
0
          (flags & UPDATE_MIME_SET_DEFAULT))
3914
0
        {
3915
0
          g_free (string);
3916
0
          string = g_strdup (desktop_id);
3917
3918
          /* add in the non-default list too, if it's not already there */
3919
0
          flags |= UPDATE_MIME_SET_NON_DEFAULT;
3920
0
        }
3921
3922
0
      if (string == NULL || desktop_id == NULL)
3923
0
        g_key_file_remove_key (key_file,
3924
0
                               DEFAULT_APPLICATIONS_GROUP,
3925
0
                               content_types[k],
3926
0
                               NULL);
3927
0
      else
3928
0
        g_key_file_set_string (key_file,
3929
0
                               DEFAULT_APPLICATIONS_GROUP,
3930
0
                               content_types[k],
3931
0
                               string);
3932
3933
0
      g_free (string);
3934
0
    }
3935
3936
0
  if (content_type)
3937
0
    {
3938
      /* reuse the list from above */
3939
0
    }
3940
0
  else
3941
0
    {
3942
0
      g_strfreev (content_types);
3943
0
      content_types = g_key_file_get_keys (key_file, ADDED_ASSOCIATIONS_GROUP, NULL, NULL);
3944
0
    }
3945
3946
0
  for (size_t k = 0; content_types && content_types[k]; k++)
3947
0
    {
3948
0
      size_t i = 0;
3949
3950
      /* Add to the right place in the list */
3951
3952
0
      length = 0;
3953
0
      old_list = g_key_file_get_string_list (key_file, ADDED_ASSOCIATIONS_GROUP,
3954
0
                                             content_types[k], &length, NULL);
3955
3956
0
      list = g_new (char *, 1 + length + 1);
3957
3958
      /* if we're adding a last-used hint, just put the application in front of the list */
3959
0
      if (flags & UPDATE_MIME_SET_LAST_USED)
3960
0
        {
3961
          /* avoid adding this again as non-default later */
3962
0
          if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3963
0
            flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3964
3965
0
          list[i++] = g_strdup (desktop_id);
3966
0
        }
3967
3968
0
      if (old_list)
3969
0
        {
3970
0
          for (size_t j = 0; old_list[j] != NULL; j++)
3971
0
            {
3972
0
              if (g_strcmp0 (old_list[j], desktop_id) != 0)
3973
0
                {
3974
                  /* rewrite other entries if they're different from the new one */
3975
0
                  list[i++] = g_strdup (old_list[j]);
3976
0
                }
3977
0
              else if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3978
0
                {
3979
                  /* we encountered an old entry which is equal to the one we're adding as non-default,
3980
                   * don't change its position in the list.
3981
                   */
3982
0
                  flags ^= UPDATE_MIME_SET_NON_DEFAULT;
3983
0
                  list[i++] = g_strdup (old_list[j]);
3984
0
                }
3985
0
            }
3986
0
        }
3987
3988
      /* add it at the end of the list */
3989
0
      if (flags & UPDATE_MIME_SET_NON_DEFAULT)
3990
0
        list[i++] = g_strdup (desktop_id);
3991
3992
0
      list[i] = NULL;
3993
3994
0
      g_strfreev (old_list);
3995
3996
0
      if (list[0] == NULL || desktop_id == NULL)
3997
0
        g_key_file_remove_key (key_file,
3998
0
                               ADDED_ASSOCIATIONS_GROUP,
3999
0
                               content_types[k],
4000
0
                               NULL);
4001
0
      else
4002
0
        g_key_file_set_string_list (key_file,
4003
0
                                    ADDED_ASSOCIATIONS_GROUP,
4004
0
                                    content_types[k],
4005
0
                                    (const char * const *)list, i);
4006
4007
0
      g_strfreev (list);
4008
0
    }
4009
4010
0
  if (content_type)
4011
0
    {
4012
      /* reuse the list from above */
4013
0
    }
4014
0
  else
4015
0
    {
4016
0
      g_strfreev (content_types);
4017
0
      content_types = g_key_file_get_keys (key_file, REMOVED_ASSOCIATIONS_GROUP, NULL, NULL);
4018
0
    }
4019
4020
0
  for (size_t k = 0; content_types && content_types[k]; k++)
4021
0
    {
4022
0
      size_t i = 0;
4023
4024
      /* Remove from removed associations group (unless remove) */
4025
4026
0
      length = 0;
4027
0
      old_list = g_key_file_get_string_list (key_file, REMOVED_ASSOCIATIONS_GROUP,
4028
0
                                             content_types[k], &length, NULL);
4029
4030
0
      list = g_new (char *, 1 + length + 1);
4031
4032
0
      if (flags & UPDATE_MIME_REMOVE)
4033
0
        list[i++] = g_strdup (desktop_id);
4034
0
      if (old_list)
4035
0
        {
4036
0
          for (size_t j = 0; old_list[j] != NULL; j++)
4037
0
            {
4038
0
              if (g_strcmp0 (old_list[j], desktop_id) != 0)
4039
0
                list[i++] = g_strdup (old_list[j]);
4040
0
            }
4041
0
        }
4042
0
      list[i] = NULL;
4043
4044
0
      g_strfreev (old_list);
4045
4046
0
      if (list[0] == NULL || desktop_id == NULL)
4047
0
        g_key_file_remove_key (key_file,
4048
0
                               REMOVED_ASSOCIATIONS_GROUP,
4049
0
                               content_types[k],
4050
0
                               NULL);
4051
0
      else
4052
0
        g_key_file_set_string_list (key_file,
4053
0
                                    REMOVED_ASSOCIATIONS_GROUP,
4054
0
                                    content_types[k],
4055
0
                                    (const char * const *)list, i);
4056
4057
0
      g_strfreev (list);
4058
0
    }
4059
4060
0
  g_strfreev (content_types);
4061
4062
0
  data = g_key_file_to_data (key_file, &data_size, error);
4063
0
  g_key_file_free (key_file);
4064
4065
0
  if (data_size > G_MAXSSIZE)
4066
0
    {
4067
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
4068
0
                           _("MIME apps information is too long"));
4069
0
      g_free (filename);
4070
0
      g_free (data);
4071
0
      return FALSE;
4072
0
    }
4073
4074
0
  res = g_file_set_contents_full (filename, data, (gssize) data_size,
4075
0
                                  G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
4076
0
                                  0600, error);
4077
4078
0
  desktop_file_dirs_invalidate_user_config ();
4079
4080
0
  g_free (filename);
4081
0
  g_free (data);
4082
4083
0
  return res;
4084
0
}
4085
4086
static gboolean
4087
g_desktop_app_info_set_as_last_used_for_type (GAppInfo    *appinfo,
4088
                                              const char  *content_type,
4089
                                              GError     **error)
4090
0
{
4091
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4092
4093
0
  if (!g_desktop_app_info_ensure_saved (info, error))
4094
0
    return FALSE;
4095
4096
0
  if (!info->desktop_id)
4097
0
    {
4098
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
4099
0
                           _("Application information lacks an identifier"));
4100
0
      return FALSE;
4101
0
    }
4102
4103
  /* both add support for the content type and set as last used */
4104
0
  return update_mimeapps_list (info->desktop_id, content_type,
4105
0
                               UPDATE_MIME_SET_NON_DEFAULT |
4106
0
                               UPDATE_MIME_SET_LAST_USED,
4107
0
                               error);
4108
0
}
4109
4110
static gboolean
4111
g_desktop_app_info_set_as_default_for_type (GAppInfo    *appinfo,
4112
                                            const char  *content_type,
4113
                                            GError     **error)
4114
0
{
4115
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4116
4117
0
  if (!g_desktop_app_info_ensure_saved (info, error))
4118
0
    return FALSE;
4119
4120
0
  if (!info->desktop_id)
4121
0
    {
4122
0
      g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
4123
0
                           _("Application information lacks an identifier"));
4124
0
      return FALSE;
4125
0
    }
4126
4127
0
  return update_mimeapps_list (info->desktop_id, content_type,
4128
0
                               UPDATE_MIME_SET_DEFAULT,
4129
0
                               error);
4130
0
}
4131
4132
static void
4133
update_program_done (GPid     pid,
4134
                     gint     status,
4135
                     gpointer data)
4136
0
{
4137
  /* Did the application exit correctly */
4138
0
  if (g_spawn_check_wait_status (status, NULL))
4139
0
    {
4140
      /* Here we could clean out any caches in use */
4141
0
    }
4142
0
}
4143
4144
static void
4145
run_update_command (char *command,
4146
                    char *subdir)
4147
0
{
4148
0
  char *argv[3] = {
4149
0
          NULL,
4150
0
          NULL,
4151
0
          NULL,
4152
0
  };
4153
0
  GPid pid = 0;
4154
0
  GError *local_error = NULL;
4155
4156
0
  argv[0] = command;
4157
0
  argv[1] = g_build_filename (g_get_user_data_dir (), subdir, NULL);
4158
4159
0
  if (g_spawn_async ("/", argv,
4160
0
                     NULL,       /* envp */
4161
0
                     G_SPAWN_SEARCH_PATH |
4162
0
                     G_SPAWN_STDOUT_TO_DEV_NULL |
4163
0
                     G_SPAWN_STDERR_TO_DEV_NULL |
4164
0
                     G_SPAWN_DO_NOT_REAP_CHILD,
4165
0
                     NULL, NULL, /* No setup function */
4166
0
                     &pid,
4167
0
                     &local_error))
4168
0
    g_child_watch_add (pid, update_program_done, NULL);
4169
0
  else
4170
0
    {
4171
      /* If we get an error at this point, it's quite likely the user doesn't
4172
       * have an installed copy of either 'update-mime-database' or
4173
       * 'update-desktop-database'.  I don't think we want to popup an error
4174
       * dialog at this point, so we just do a g_warning to give the user a
4175
       * chance of debugging it.
4176
       */
4177
0
      g_warning ("%s", local_error->message);
4178
0
      g_error_free (local_error);
4179
0
    }
4180
4181
0
  g_free (argv[1]);
4182
0
}
4183
4184
static gboolean
4185
g_desktop_app_info_set_as_default_for_extension (GAppInfo    *appinfo,
4186
                                                 const char  *extension,
4187
                                                 GError     **error)
4188
0
{
4189
0
  char *filename, *basename, *mimetype;
4190
0
  char *dirname;
4191
0
  gboolean res;
4192
4193
0
  if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (appinfo), error))
4194
0
    return FALSE;
4195
4196
0
  dirname = ensure_dir (MIMETYPE_DIR, error);
4197
0
  if (!dirname)
4198
0
    return FALSE;
4199
4200
0
  basename = g_strdup_printf ("user-extension-%s.xml", extension);
4201
0
  filename = g_build_filename (dirname, basename, NULL);
4202
0
  g_free (basename);
4203
0
  g_free (dirname);
4204
4205
0
  mimetype = g_strdup_printf ("application/x-extension-%s", extension);
4206
4207
0
  if (!g_file_test (filename, G_FILE_TEST_EXISTS))
4208
0
    {
4209
0
      char *contents;
4210
4211
0
      contents =
4212
0
        g_strdup_printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
4213
0
                         "<mime-info xmlns=\"http://www.freedesktop.org/standards/shared-mime-info\">\n"
4214
0
                         " <mime-type type=\"%s\">\n"
4215
0
                         "  <comment>%s document</comment>\n"
4216
0
                         "  <glob pattern=\"*.%s\"/>\n"
4217
0
                         " </mime-type>\n"
4218
0
                         "</mime-info>\n", mimetype, extension, extension);
4219
4220
0
      g_file_set_contents_full (filename, contents, -1,
4221
0
                                G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
4222
0
                                0600, NULL);
4223
0
      g_free (contents);
4224
4225
0
      run_update_command ("update-mime-database", "mime");
4226
0
    }
4227
0
  g_free (filename);
4228
4229
0
  res = g_desktop_app_info_set_as_default_for_type (appinfo,
4230
0
                                                    mimetype,
4231
0
                                                    error);
4232
4233
0
  g_free (mimetype);
4234
4235
0
  return res;
4236
0
}
4237
4238
static gboolean
4239
g_desktop_app_info_add_supports_type (GAppInfo    *appinfo,
4240
                                      const char  *content_type,
4241
                                      GError     **error)
4242
0
{
4243
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4244
4245
0
  if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
4246
0
    return FALSE;
4247
4248
0
  return update_mimeapps_list (info->desktop_id, content_type,
4249
0
                               UPDATE_MIME_SET_NON_DEFAULT,
4250
0
                               error);
4251
0
}
4252
4253
static gboolean
4254
g_desktop_app_info_can_remove_supports_type (GAppInfo *appinfo)
4255
0
{
4256
0
  return TRUE;
4257
0
}
4258
4259
static gboolean
4260
g_desktop_app_info_remove_supports_type (GAppInfo    *appinfo,
4261
                                         const char  *content_type,
4262
                                         GError     **error)
4263
0
{
4264
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4265
4266
0
  if (!g_desktop_app_info_ensure_saved (G_DESKTOP_APP_INFO (info), error))
4267
0
    return FALSE;
4268
4269
0
  return update_mimeapps_list (info->desktop_id, content_type,
4270
0
                               UPDATE_MIME_REMOVE,
4271
0
                               error);
4272
0
}
4273
4274
static const char **
4275
g_desktop_app_info_get_supported_types (GAppInfo *appinfo)
4276
0
{
4277
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4278
4279
0
  return (const char**) info->mime_types;
4280
0
}
4281
4282
/* Saving and deleting {{{2 */
4283
4284
static gboolean
4285
g_desktop_app_info_ensure_saved (GDesktopAppInfo  *info,
4286
                                 GError          **error)
4287
0
{
4288
0
  GKeyFile *key_file;
4289
0
  char *dirname;
4290
0
  char *filename;
4291
0
  char *data, *desktop_id;
4292
0
  gsize data_size;
4293
0
  int fd;
4294
0
  gboolean res;
4295
4296
0
  if (info->filename != NULL)
4297
0
    return TRUE;
4298
4299
  /* This is only used for object created with
4300
   * g_app_info_create_from_commandline. All other
4301
   * object should have a filename
4302
   */
4303
4304
0
  dirname = ensure_dir (APP_DIR, error);
4305
0
  if (!dirname)
4306
0
    return FALSE;
4307
4308
0
  key_file = g_key_file_new ();
4309
4310
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4311
0
                         "Encoding", "UTF-8");
4312
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4313
0
                         G_KEY_FILE_DESKTOP_KEY_VERSION, "1.0");
4314
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4315
0
                         G_KEY_FILE_DESKTOP_KEY_TYPE,
4316
0
                         G_KEY_FILE_DESKTOP_TYPE_APPLICATION);
4317
0
  if (info->terminal)
4318
0
    g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4319
0
                            G_KEY_FILE_DESKTOP_KEY_TERMINAL, TRUE);
4320
0
  if (info->nodisplay)
4321
0
    g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4322
0
                            G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
4323
4324
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4325
0
                         G_KEY_FILE_DESKTOP_KEY_EXEC, info->exec);
4326
4327
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4328
0
                         G_KEY_FILE_DESKTOP_KEY_NAME, info->name);
4329
4330
0
  if (info->generic_name != NULL)
4331
0
    g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4332
0
                           GENERIC_NAME_KEY, info->generic_name);
4333
4334
0
  if (info->fullname != NULL)
4335
0
    g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4336
0
                           FULL_NAME_KEY, info->fullname);
4337
4338
0
  g_key_file_set_string (key_file, G_KEY_FILE_DESKTOP_GROUP,
4339
0
                         G_KEY_FILE_DESKTOP_KEY_COMMENT, info->comment);
4340
4341
0
  g_key_file_set_boolean (key_file, G_KEY_FILE_DESKTOP_GROUP,
4342
0
                          G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY, TRUE);
4343
4344
0
  data = g_key_file_to_data (key_file, &data_size, NULL);
4345
0
  g_key_file_free (key_file);
4346
4347
0
  desktop_id = g_strdup_printf ("userapp-%s-XXXXXX.desktop", info->name);
4348
0
  filename = g_build_filename (dirname, desktop_id, NULL);
4349
0
  g_free (desktop_id);
4350
0
  g_free (dirname);
4351
4352
0
  fd = g_mkstemp (filename);
4353
0
  if (fd == -1)
4354
0
    {
4355
0
      char *display_name;
4356
4357
0
      display_name = g_filename_display_name (filename);
4358
0
      g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
4359
0
                   _("Can’t create user desktop file %s"), display_name);
4360
0
      g_free (display_name);
4361
0
      g_free (filename);
4362
0
      g_free (data);
4363
0
      return FALSE;
4364
0
    }
4365
4366
0
  desktop_id = g_path_get_basename (filename);
4367
4368
  /* FIXME - actually handle error */
4369
0
  (void) g_close (fd, NULL);
4370
4371
0
  res = g_file_set_contents_full (filename, data, data_size,
4372
0
                                  G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING,
4373
0
                                  0600, error);
4374
0
  g_free (data);
4375
0
  if (!res)
4376
0
    {
4377
0
      g_free (desktop_id);
4378
0
      g_free (filename);
4379
0
      return FALSE;
4380
0
    }
4381
4382
0
  info->filename = filename;
4383
0
  info->desktop_id = desktop_id;
4384
4385
0
  run_update_command ("update-desktop-database", "applications");
4386
4387
  /* We just dropped a file in the user's desktop file directory.  Save
4388
   * the monitor the bother of having to notice it and invalidate
4389
   * immediately.
4390
   *
4391
   * This means that calls directly following this will be able to see
4392
   * the results immediately.
4393
   */
4394
0
  desktop_file_dirs_invalidate_user_data ();
4395
4396
0
  return TRUE;
4397
0
}
4398
4399
static gboolean
4400
g_desktop_app_info_can_delete (GAppInfo *appinfo)
4401
0
{
4402
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4403
4404
0
  if (info->filename)
4405
0
    {
4406
0
      if (strstr (info->filename, "/userapp-"))
4407
0
        return g_access (info->filename, W_OK) == 0;
4408
0
    }
4409
4410
0
  return FALSE;
4411
0
}
4412
4413
static gboolean
4414
g_desktop_app_info_delete (GAppInfo *appinfo)
4415
0
{
4416
0
  GDesktopAppInfo *info = G_DESKTOP_APP_INFO (appinfo);
4417
4418
0
  if (info->filename)
4419
0
    {
4420
0
      if (g_remove (info->filename) == 0)
4421
0
        {
4422
0
          update_mimeapps_list (info->desktop_id, NULL,
4423
0
                                UPDATE_MIME_NONE,
4424
0
                                NULL);
4425
4426
0
          g_free (info->filename);
4427
0
          info->filename = NULL;
4428
0
          g_free (info->desktop_id);
4429
0
          info->desktop_id = NULL;
4430
4431
0
          return TRUE;
4432
0
        }
4433
0
    }
4434
4435
0
  return FALSE;
4436
0
}
4437
4438
/* Create for commandline {{{2 */
4439
4440
GAppInfo *
4441
g_app_info_create_from_commandline_impl (const char           *commandline,
4442
                                         const char           *application_name,
4443
                                         GAppInfoCreateFlags   flags,
4444
                                         GError              **error)
4445
0
{
4446
0
  char **split;
4447
0
  char *basename;
4448
0
  GDesktopAppInfo *info;
4449
4450
0
  g_return_val_if_fail (commandline, NULL);
4451
4452
0
  info = g_object_new (G_TYPE_DESKTOP_APP_INFO, NULL);
4453
4454
0
  info->filename = NULL;
4455
0
  info->desktop_id = NULL;
4456
4457
0
  info->terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0;
4458
0
  info->startup_notify = (flags & G_APP_INFO_CREATE_SUPPORTS_STARTUP_NOTIFICATION) != 0;
4459
0
  info->hidden = FALSE;
4460
0
  if ((flags & G_APP_INFO_CREATE_SUPPORTS_URIS) != 0)
4461
0
    info->exec = g_strconcat (commandline, " %u", NULL);
4462
0
  else
4463
0
    info->exec = g_strconcat (commandline, " %f", NULL);
4464
0
  info->nodisplay = TRUE;
4465
0
  info->binary = binary_from_exec (info->exec);
4466
4467
0
  if (application_name)
4468
0
    info->name = g_strdup (application_name);
4469
0
  else
4470
0
    {
4471
      /* FIXME: this should be more robust. Maybe g_shell_parse_argv and use argv[0] */
4472
0
      split = g_strsplit (commandline, " ", 2);
4473
0
      basename = split[0] ? g_path_get_basename (split[0]) : NULL;
4474
0
      g_strfreev (split);
4475
0
      info->name = basename;
4476
0
      if (info->name == NULL)
4477
0
        info->name = g_strdup ("custom");
4478
0
    }
4479
0
  info->comment = g_strdup_printf (_("Custom definition for %s"), info->name);
4480
4481
0
  return G_APP_INFO (info);
4482
0
}
4483
4484
/* GAppInfo interface init */
4485
4486
static void
4487
g_desktop_app_info_iface_init (GAppInfoIface *iface)
4488
0
{
4489
0
  iface->dup = g_desktop_app_info_dup;
4490
0
  iface->equal = g_desktop_app_info_equal;
4491
0
  iface->get_id = g_desktop_app_info_get_id;
4492
0
  iface->get_name = g_desktop_app_info_get_name;
4493
0
  iface->get_description = g_desktop_app_info_get_description;
4494
0
  iface->get_executable = g_desktop_app_info_get_executable;
4495
0
  iface->get_icon = g_desktop_app_info_get_icon;
4496
0
  iface->launch = g_desktop_app_info_launch;
4497
0
  iface->supports_uris = g_desktop_app_info_supports_uris;
4498
0
  iface->supports_files = g_desktop_app_info_supports_files;
4499
0
  iface->launch_uris = g_desktop_app_info_launch_uris;
4500
0
  iface->launch_uris_async = g_desktop_app_info_launch_uris_async;
4501
0
  iface->launch_uris_finish = g_desktop_app_info_launch_uris_finish;
4502
0
  iface->should_show = g_desktop_app_info_should_show;
4503
0
  iface->set_as_default_for_type = g_desktop_app_info_set_as_default_for_type;
4504
0
  iface->set_as_default_for_extension = g_desktop_app_info_set_as_default_for_extension;
4505
0
  iface->add_supports_type = g_desktop_app_info_add_supports_type;
4506
0
  iface->can_remove_supports_type = g_desktop_app_info_can_remove_supports_type;
4507
0
  iface->remove_supports_type = g_desktop_app_info_remove_supports_type;
4508
0
  iface->can_delete = g_desktop_app_info_can_delete;
4509
0
  iface->do_delete = g_desktop_app_info_delete;
4510
0
  iface->get_commandline = g_desktop_app_info_get_commandline;
4511
0
  iface->get_display_name = g_desktop_app_info_get_display_name;
4512
0
  iface->set_as_last_used_for_type = g_desktop_app_info_set_as_last_used_for_type;
4513
0
  iface->get_supported_types = g_desktop_app_info_get_supported_types;
4514
0
}
4515
4516
/* Recommended applications {{{2 */
4517
4518
/* Converts content_type into a list of itself with all of its parent
4519
 * types (if include_fallback is enabled) or just returns a single-item
4520
 * list with the unaliased content type.
4521
 */
4522
static gchar **
4523
get_list_of_mimetypes (const gchar *content_type,
4524
                       gboolean     include_fallback)
4525
0
{
4526
0
  gchar *unaliased;
4527
0
  GPtrArray *array;
4528
4529
0
  array = g_ptr_array_new ();
4530
0
  unaliased = _g_unix_content_type_unalias (content_type);
4531
0
  g_ptr_array_add (array, unaliased);
4532
4533
0
  if (include_fallback)
4534
0
    {
4535
0
      guint i;
4536
4537
      /* Iterate the array as we grow it, until we have nothing more to add */
4538
0
      for (i = 0; i < array->len; i++)
4539
0
        {
4540
0
          gchar **parents = _g_unix_content_type_get_parents (g_ptr_array_index (array, i));
4541
0
          gint j;
4542
4543
0
          for (j = 0; parents[j]; j++)
4544
            /* Don't add duplicates */
4545
0
            if (!array_contains (array, parents[j]))
4546
0
              g_ptr_array_add (array, parents[j]);
4547
0
            else
4548
0
              g_free (parents[j]);
4549
4550
          /* We already stole or freed each element.  Free the container. */
4551
0
          g_free (parents);
4552
0
        }
4553
0
    }
4554
4555
0
  g_ptr_array_add (array, NULL);
4556
4557
0
  return (gchar **) g_ptr_array_free (array, FALSE);
4558
0
}
4559
4560
static gchar **
4561
g_desktop_app_info_get_desktop_ids_for_content_type (const gchar *content_type,
4562
                                                     gboolean     include_fallback)
4563
0
{
4564
0
  GPtrArray *hits, *blocklist;
4565
0
  gchar **types;
4566
0
  guint i, j;
4567
4568
0
  hits = g_ptr_array_new ();
4569
0
  blocklist = g_ptr_array_new ();
4570
4571
0
  types = get_list_of_mimetypes (content_type, include_fallback);
4572
4573
0
  desktop_file_dirs_lock ();
4574
4575
0
  for (i = 0; types[i]; i++)
4576
0
    for (j = 0; j < desktop_file_dirs->len; j++)
4577
0
      desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], hits, blocklist);
4578
4579
  /* We will keep the hits past unlocking, so we must dup them */
4580
0
  for (i = 0; i < hits->len; i++)
4581
0
    hits->pdata[i] = g_strdup (hits->pdata[i]);
4582
4583
0
  desktop_file_dirs_unlock ();
4584
4585
0
  g_ptr_array_add (hits, NULL);
4586
4587
0
  g_ptr_array_free (blocklist, TRUE);
4588
0
  g_strfreev (types);
4589
4590
0
  return (gchar **) g_ptr_array_free (hits, FALSE);
4591
0
}
4592
4593
GList *
4594
g_app_info_get_recommended_for_type_impl (const gchar *content_type)
4595
0
{
4596
0
  gchar **desktop_ids;
4597
0
  GList *infos;
4598
0
  gint i;
4599
4600
0
  g_return_val_if_fail (content_type != NULL, NULL);
4601
4602
0
  desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4603
4604
0
  infos = NULL;
4605
0
  for (i = 0; desktop_ids[i]; i++)
4606
0
    {
4607
0
      GDesktopAppInfo *info;
4608
4609
0
      info = g_desktop_app_info_new (desktop_ids[i]);
4610
0
      if (info)
4611
0
        infos = g_list_prepend (infos, info);
4612
0
    }
4613
4614
0
  g_strfreev (desktop_ids);
4615
4616
0
  return g_list_reverse (infos);
4617
0
}
4618
4619
GList *
4620
g_app_info_get_fallback_for_type_impl (const gchar *content_type)
4621
0
{
4622
0
  gchar **recommended_ids;
4623
0
  gchar **all_ids;
4624
0
  GList *infos;
4625
0
  gint i;
4626
4627
0
  g_return_val_if_fail (content_type != NULL, NULL);
4628
4629
0
  recommended_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, FALSE);
4630
0
  all_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4631
4632
0
  infos = NULL;
4633
0
  for (i = 0; all_ids[i]; i++)
4634
0
    {
4635
0
      GDesktopAppInfo *info;
4636
0
      gint j;
4637
4638
      /* Don't return the ones on the recommended list */
4639
0
      for (j = 0; recommended_ids[j]; j++)
4640
0
        if (g_str_equal (all_ids[i], recommended_ids[j]))
4641
0
          break;
4642
4643
0
      if (recommended_ids[j])
4644
0
        continue;
4645
4646
0
      info = g_desktop_app_info_new (all_ids[i]);
4647
4648
0
      if (info)
4649
0
        infos = g_list_prepend (infos, info);
4650
0
    }
4651
4652
0
  g_strfreev (recommended_ids);
4653
0
  g_strfreev (all_ids);
4654
4655
0
  return g_list_reverse (infos);
4656
0
}
4657
4658
GList *
4659
g_app_info_get_all_for_type_impl (const char *content_type)
4660
0
{
4661
0
  gchar **desktop_ids;
4662
0
  GList *infos;
4663
0
  gint i;
4664
4665
0
  g_return_val_if_fail (content_type != NULL, NULL);
4666
4667
0
  desktop_ids = g_desktop_app_info_get_desktop_ids_for_content_type (content_type, TRUE);
4668
4669
0
  infos = NULL;
4670
0
  for (i = 0; desktop_ids[i]; i++)
4671
0
    {
4672
0
      GDesktopAppInfo *info;
4673
4674
0
      info = g_desktop_app_info_new (desktop_ids[i]);
4675
0
      if (info)
4676
0
        infos = g_list_prepend (infos, info);
4677
0
    }
4678
4679
0
  g_strfreev (desktop_ids);
4680
4681
0
  return g_list_reverse (infos);
4682
0
}
4683
4684
void
4685
g_app_info_reset_type_associations_impl (const char *content_type)
4686
0
{
4687
0
  update_mimeapps_list (NULL, content_type,
4688
0
                        UPDATE_MIME_NONE,
4689
0
                        NULL);
4690
0
}
4691
4692
GAppInfo *
4693
g_app_info_get_default_for_type_impl (const char *content_type,
4694
                                      gboolean    must_support_uris)
4695
0
{
4696
0
  GPtrArray *blocklist;
4697
0
  GPtrArray *results;
4698
0
  GAppInfo *info;
4699
0
  gchar **types;
4700
0
  guint i, j, k;
4701
4702
0
  g_return_val_if_fail (content_type != NULL, NULL);
4703
4704
0
  types = get_list_of_mimetypes (content_type, TRUE);
4705
4706
0
  blocklist = g_ptr_array_new ();
4707
0
  results = g_ptr_array_new ();
4708
0
  info = NULL;
4709
4710
0
  desktop_file_dirs_lock ();
4711
4712
0
  for (i = 0; types[i]; i++)
4713
0
    {
4714
      /* Collect all the default apps for this type */
4715
0
      for (j = 0; j < desktop_file_dirs->len; j++)
4716
0
        desktop_file_dir_default_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results);
4717
4718
      /* Consider the associations as well... */
4719
0
      for (j = 0; j < desktop_file_dirs->len; j++)
4720
0
        desktop_file_dir_mime_lookup (g_ptr_array_index (desktop_file_dirs, j), types[i], results, blocklist);
4721
4722
      /* (If any), see if one of those apps is installed... */
4723
0
      for (j = 0; j < results->len; j++)
4724
0
        {
4725
0
          const gchar *desktop_id = g_ptr_array_index (results, j);
4726
4727
0
          for (k = 0; k < desktop_file_dirs->len; k++)
4728
0
            {
4729
0
              info = (GAppInfo *) desktop_file_dir_get_app (g_ptr_array_index (desktop_file_dirs, k), desktop_id);
4730
4731
0
              if (info)
4732
0
                {
4733
0
                  if (!must_support_uris || g_app_info_supports_uris (info))
4734
0
                    goto out;
4735
4736
0
                  g_clear_object (&info);
4737
0
                }
4738
0
            }
4739
0
        }
4740
4741
      /* Reset the list, ready to try again with the next (parent)
4742
       * mimetype, but keep the blocklist in place.
4743
       */
4744
0
      g_ptr_array_set_size (results, 0);
4745
0
    }
4746
4747
0
out:
4748
0
  desktop_file_dirs_unlock ();
4749
4750
0
  g_ptr_array_unref (blocklist);
4751
0
  g_ptr_array_unref (results);
4752
0
  g_strfreev (types);
4753
4754
0
  return info;
4755
0
}
4756
4757
GAppInfo *
4758
g_app_info_get_default_for_uri_scheme_impl (const char *uri_scheme)
4759
0
{
4760
0
  GAppInfo *app_info;
4761
0
  char *content_type, *scheme_down;
4762
4763
0
  g_return_val_if_fail (uri_scheme != NULL && *uri_scheme != '\0', NULL);
4764
4765
0
  scheme_down = g_ascii_strdown (uri_scheme, -1);
4766
0
  content_type = g_strdup_printf ("x-scheme-handler/%s", scheme_down);
4767
0
  g_free (scheme_down);
4768
0
  app_info = g_app_info_get_default_for_type (content_type, FALSE);
4769
0
  g_free (content_type);
4770
4771
0
  return app_info;
4772
0
}
4773
4774
/* "Get all" API {{{2 */
4775
4776
/**
4777
 * g_desktop_app_info_get_implementations:
4778
 * @interface: the name of the interface
4779
 *
4780
 * Gets all applications that implement @interface.
4781
 *
4782
 * An application implements an interface if that interface is listed in
4783
 * the `Implements` line of the desktop file of the application.
4784
 *
4785
 * Returns: (element-type GDesktopAppInfo) (transfer full): a list of
4786
 *   [class@GioUnix.DesktopAppInfo] objects.
4787
 *
4788
 * Since: 2.42
4789
 **/
4790
GList *
4791
g_desktop_app_info_get_implementations (const gchar *interface)
4792
0
{
4793
0
  GList *result = NULL;
4794
0
  GList **ptr;
4795
0
  guint i;
4796
4797
0
  desktop_file_dirs_lock ();
4798
4799
0
  for (i = 0; i < desktop_file_dirs->len; i++)
4800
0
    desktop_file_dir_get_implementations (g_ptr_array_index (desktop_file_dirs, i), &result, interface);
4801
4802
0
  desktop_file_dirs_unlock ();
4803
4804
0
  ptr = &result;
4805
0
  while (*ptr)
4806
0
    {
4807
0
      gchar *name = (*ptr)->data;
4808
0
      GDesktopAppInfo *app;
4809
4810
0
      app = g_desktop_app_info_new (name);
4811
0
      g_free (name);
4812
4813
0
      if (app)
4814
0
        {
4815
0
          (*ptr)->data = app;
4816
0
          ptr = &(*ptr)->next;
4817
0
        }
4818
0
      else
4819
0
        *ptr = g_list_delete_link (*ptr, *ptr);
4820
0
    }
4821
4822
0
  return result;
4823
0
}
4824
4825
/**
4826
 * g_desktop_app_info_search:
4827
 * @search_string: the search string to use
4828
 *
4829
 * Searches desktop files for ones that match @search_string.
4830
 *
4831
 * The return value is an array of strvs.  Each strv contains a list of
4832
 * applications that matched @search_string with an equal score.  The
4833
 * outer list is sorted by score so that the first strv contains the
4834
 * best-matching applications, and so on.
4835
 * The algorithm for determining matches is undefined and may change at
4836
 * any time.
4837
 *
4838
 * None of the search results are subjected to the normal validation
4839
 * checks performed by [ctor@GioUnix.DesktopAppInfo.new] (for example,
4840
 * checking that the executable referenced by a result exists), and so it is
4841
 * possible for [ctor@GioUnix.DesktopAppInfo.new] to return `NULL` when passed
4842
 * an app ID returned by this function. It is expected that calling code will
4843
 * do this when subsequently creating a [class@GioUnix.DesktopAppInfo] for
4844
 * each result.
4845
 *
4846
 * Returns: (array zero-terminated=1) (element-type GStrv) (transfer full): a
4847
 *   list of strvs.  Free each item with [func@GLib.strfreev] and free the outer
4848
 *   list with [func@GLib.free].
4849
 */
4850
gchar ***
4851
g_desktop_app_info_search (const gchar *search_string)
4852
0
{
4853
0
  gchar **search_tokens;
4854
0
  gint last_category = -1;
4855
0
  gint last_match_type = -1;
4856
0
  gint last_token_pos = -1;
4857
0
  gchar ***results;
4858
0
  size_t n_groups = 0;
4859
0
  size_t start_of_group;
4860
0
  size_t i;
4861
0
  guint k;
4862
4863
0
  search_tokens = g_str_tokenize_and_fold (search_string, NULL, NULL);
4864
4865
0
  desktop_file_dirs_lock ();
4866
4867
0
  reset_total_search_results ();
4868
4869
0
  for (k = 0; k < desktop_file_dirs->len; k++)
4870
0
    {
4871
0
      for (size_t j = 0; search_tokens[j]; j++)
4872
0
        {
4873
0
          desktop_file_dir_search (g_ptr_array_index (desktop_file_dirs, k), search_tokens[j]);
4874
0
          merge_token_results (j == 0);
4875
0
        }
4876
0
      merge_directory_results ();
4877
0
    }
4878
4879
0
  sort_total_search_results ();
4880
4881
  /* Count the total number of unique categories and match types */
4882
0
  for (i = 0; i < static_total_results_size; i++)
4883
0
    if (static_total_results[i].category != last_category ||
4884
0
        static_total_results[i].match_type != last_match_type ||
4885
0
        static_total_results[i].token_pos != last_token_pos)
4886
0
      {
4887
0
        last_category = static_total_results[i].category;
4888
0
        last_match_type = static_total_results[i].match_type;
4889
0
        last_token_pos = static_total_results[i].token_pos;
4890
0
        n_groups++;
4891
0
      }
4892
4893
0
  results = g_new (gchar **, n_groups + 1);
4894
4895
  /* Start loading into the results list */
4896
0
  start_of_group = 0;
4897
0
  for (i = 0; i < n_groups; i++)
4898
0
    {
4899
0
      size_t n_items_in_group = 0;
4900
0
      gint this_category;
4901
0
      gint this_match_type;
4902
0
      gint this_token_pos;
4903
0
      size_t j;
4904
4905
0
      this_category = static_total_results[start_of_group].category;
4906
0
      this_match_type = static_total_results[start_of_group].match_type;
4907
0
      this_token_pos = static_total_results[start_of_group].token_pos;
4908
4909
0
      while (start_of_group + n_items_in_group < static_total_results_size &&
4910
0
             static_total_results[start_of_group + n_items_in_group].category == this_category &&
4911
0
             static_total_results[start_of_group + n_items_in_group].match_type == this_match_type &&
4912
0
             static_total_results[start_of_group + n_items_in_group].token_pos == this_token_pos)
4913
0
        n_items_in_group++;
4914
4915
0
      results[i] = g_new (gchar *, n_items_in_group + 1);
4916
0
      for (j = 0; j < n_items_in_group; j++)
4917
0
        results[i][j] = g_strdup (static_total_results[start_of_group + j].app_name);
4918
0
      results[i][j] = NULL;
4919
4920
0
      start_of_group += n_items_in_group;
4921
0
    }
4922
0
  results[i] = NULL;
4923
4924
0
  desktop_file_dirs_unlock ();
4925
4926
0
  g_strfreev (search_tokens);
4927
4928
0
  return results;
4929
0
}
4930
4931
GList *
4932
g_app_info_get_all_impl (void)
4933
0
{
4934
0
  GHashTable *apps;
4935
0
  GHashTableIter iter;
4936
0
  gpointer value;
4937
0
  guint i;
4938
0
  GList *infos;
4939
4940
0
  apps = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4941
4942
0
  desktop_file_dirs_lock ();
4943
4944
0
  for (i = 0; i < desktop_file_dirs->len; i++)
4945
0
    desktop_file_dir_get_all (g_ptr_array_index (desktop_file_dirs, i), apps);
4946
4947
0
  desktop_file_dirs_unlock ();
4948
4949
0
  infos = NULL;
4950
0
  g_hash_table_iter_init (&iter, apps);
4951
0
  while (g_hash_table_iter_next (&iter, NULL, &value))
4952
0
    {
4953
0
      if (value)
4954
0
        infos = g_list_prepend (infos, value);
4955
0
    }
4956
4957
0
  g_hash_table_destroy (apps);
4958
4959
0
  return infos;
4960
0
}
4961
4962
/* GDesktopAppInfoLookup interface {{{2 */
4963
4964
/**
4965
 * GDesktopAppInfoLookup:
4966
 *
4967
 * #GDesktopAppInfoLookup is an opaque data structure and can only be accessed
4968
 * using the following functions.
4969
 *
4970
 * Deprecated: 2.28: The [iface@GioUnix.DesktopAppInfoLookup] interface is
4971
 *   deprecated and unused by GIO.
4972
 **/
4973
4974
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
4975
4976
typedef GDesktopAppInfoLookupIface GDesktopAppInfoLookupInterface;
4977
0
G_DEFINE_INTERFACE (GDesktopAppInfoLookup, g_desktop_app_info_lookup, G_TYPE_OBJECT)
4978
0
4979
0
static void
4980
0
g_desktop_app_info_lookup_default_init (GDesktopAppInfoLookupInterface *iface)
4981
0
{
4982
0
}
4983
4984
/* "Get for mime type" APIs {{{2 */
4985
4986
/**
4987
 * g_desktop_app_info_lookup_get_default_for_uri_scheme:
4988
 * @lookup: a [iface@GioUnix.DesktopAppInfoLookup]
4989
 * @uri_scheme: a string containing a URI scheme.
4990
 *
4991
 * Gets the default application for launching applications
4992
 * using this URI scheme for a particular [iface@GioUnix.DesktopAppInfoLookup]
4993
 * implementation.
4994
 *
4995
 * The [iface@GioUnix.DesktopAppInfoLookup] interface and this function is used
4996
 * to implement [func@Gio.AppInfo.get_default_for_uri_scheme] backends
4997
 * in a GIO module. There is no reason for applications to use it
4998
 * directly. Applications should use
4999
 * [func@Gio.AppInfo.get_default_for_uri_scheme].
5000
 *
5001
 * Returns: (transfer full) (nullable): [iface@Gio.AppInfo] for given
5002
 *   @uri_scheme or `NULL` on error.
5003
 *
5004
 * Deprecated: 2.28: The [iface@GioUnix.DesktopAppInfoLookup] interface is
5005
 *   deprecated and unused by GIO.
5006
 */
5007
GAppInfo *
5008
g_desktop_app_info_lookup_get_default_for_uri_scheme (GDesktopAppInfoLookup *lookup,
5009
                                                      const char            *uri_scheme)
5010
0
{
5011
0
  GDesktopAppInfoLookupIface *iface;
5012
5013
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO_LOOKUP (lookup), NULL);
5014
5015
0
  iface = G_DESKTOP_APP_INFO_LOOKUP_GET_IFACE (lookup);
5016
5017
0
  return (* iface->get_default_for_uri_scheme) (lookup, uri_scheme);
5018
0
}
5019
5020
G_GNUC_END_IGNORE_DEPRECATIONS
5021
5022
/* Misc getter APIs {{{2 */
5023
5024
/**
5025
 * g_desktop_app_info_get_startup_wm_class:
5026
 * @info: a [class@GioUnix.DesktopAppInfo] that supports startup notify
5027
 *
5028
 * Retrieves the `StartupWMClass` field from @info. This represents the
5029
 * `WM_CLASS` property of the main window of the application, if launched
5030
 * through @info.
5031
 *
5032
 * Returns: (nullable) (transfer none): the startup WM class, or `NULL` if none
5033
 *   is set in the desktop file.
5034
 *
5035
 * Since: 2.34
5036
 */
5037
const char *
5038
g_desktop_app_info_get_startup_wm_class (GDesktopAppInfo *info)
5039
0
{
5040
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5041
5042
0
  return info->startup_wm_class;
5043
0
}
5044
5045
/**
5046
 * g_desktop_app_info_get_string:
5047
 * @info: a [class@GioUnix.DesktopAppInfo]
5048
 * @key: the key to look up
5049
 *
5050
 * Looks up a string value in the keyfile backing @info.
5051
 *
5052
 * The @key is looked up in the `Desktop Entry` group.
5053
 *
5054
 * Returns: (nullable): a newly allocated string, or `NULL` if the key is not
5055
 *   found
5056
 *
5057
 * Since: 2.36
5058
 */
5059
char *
5060
g_desktop_app_info_get_string (GDesktopAppInfo *info,
5061
                               const char      *key)
5062
0
{
5063
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5064
5065
0
  return g_key_file_get_string (info->keyfile,
5066
0
                                G_KEY_FILE_DESKTOP_GROUP, key, NULL);
5067
0
}
5068
5069
/**
5070
 * g_desktop_app_info_get_locale_string:
5071
 * @info: a [class@GioUnix.DesktopAppInfo]
5072
 * @key: the key to look up
5073
 *
5074
 * Looks up a localized string value in the keyfile backing @info
5075
 * translated to the current locale.
5076
 *
5077
 * The @key is looked up in the `Desktop Entry` group.
5078
 *
5079
 * Returns: (nullable): a newly allocated string, or `NULL` if the key is not
5080
 *   found
5081
 *
5082
 * Since: 2.56
5083
 */
5084
char *
5085
g_desktop_app_info_get_locale_string (GDesktopAppInfo *info,
5086
                                      const char      *key)
5087
0
{
5088
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5089
0
  g_return_val_if_fail (key != NULL && *key != '\0', NULL);
5090
5091
0
  return g_key_file_get_locale_string (info->keyfile,
5092
0
                                       G_KEY_FILE_DESKTOP_GROUP,
5093
0
                                       key, NULL, NULL);
5094
0
}
5095
5096
/**
5097
 * g_desktop_app_info_get_boolean:
5098
 * @info: a [class@GioUnix.DesktopAppInfo]
5099
 * @key: the key to look up
5100
 *
5101
 * Looks up a boolean value in the keyfile backing @info.
5102
 *
5103
 * The @key is looked up in the `Desktop Entry` group.
5104
 *
5105
 * Returns: the boolean value, or `FALSE` if the key is not found
5106
 *
5107
 * Since: 2.36
5108
 */
5109
gboolean
5110
g_desktop_app_info_get_boolean (GDesktopAppInfo *info,
5111
                                const char      *key)
5112
0
{
5113
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
5114
5115
0
  return g_key_file_get_boolean (info->keyfile,
5116
0
                                 G_KEY_FILE_DESKTOP_GROUP, key, NULL);
5117
0
}
5118
5119
/**
5120
 * g_desktop_app_info_get_string_list:
5121
 * @info: a [class@GioUnix.DesktopAppInfo]
5122
 * @key: the key to look up
5123
 * @length: (out) (optional): return location for the number of returned
5124
 *   strings, or `NULL`
5125
 *
5126
 * Looks up a string list value in the keyfile backing @info.
5127
 *
5128
 * The @key is looked up in the `Desktop Entry` group.
5129
 *
5130
 * Returns: (nullable) (array zero-terminated=1 length=length) (element-type utf8) (transfer full):
5131
 *   a `NULL`-terminated string array or `NULL` if the specified
5132
 *   key cannot be found. The array should be freed with [func@GLib.strfreev].
5133
 *
5134
 * Since: 2.60
5135
 */
5136
gchar **
5137
g_desktop_app_info_get_string_list (GDesktopAppInfo *info,
5138
                                    const char      *key,
5139
                                    gsize           *length)
5140
0
{
5141
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5142
5143
0
  return g_key_file_get_string_list (info->keyfile,
5144
0
                                     G_KEY_FILE_DESKTOP_GROUP, key, length, NULL);
5145
0
}
5146
5147
/**
5148
 * g_desktop_app_info_has_key:
5149
 * @info: a [class@GioUnix.DesktopAppInfo]
5150
 * @key: the key to look up
5151
 *
5152
 * Returns whether @key exists in the `Desktop Entry` group
5153
 * of the keyfile backing @info.
5154
 *
5155
 * Returns: `TRUE` if the @key exists
5156
 *
5157
 * Since: 2.36
5158
 */
5159
gboolean
5160
g_desktop_app_info_has_key (GDesktopAppInfo *info,
5161
                            const char      *key)
5162
0
{
5163
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), FALSE);
5164
5165
0
  return g_key_file_has_key (info->keyfile,
5166
0
                             G_KEY_FILE_DESKTOP_GROUP, key, NULL);
5167
0
}
5168
5169
/* Desktop actions support {{{2 */
5170
5171
/**
5172
 * g_desktop_app_info_list_actions:
5173
 * @info: a [class@GioUnix.DesktopAppInfo]
5174
 *
5175
 * Returns the list of
5176
 * [‘additional application actions’](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s11.html)
5177
 * supported on the desktop file, as per the desktop file specification.
5178
 *
5179
 * As per the specification, this is the list of actions that are
5180
 * explicitly listed in the `Actions` key of the `Desktop Entry` group.
5181
 *
5182
 * Returns: (array zero-terminated=1) (element-type utf8) (transfer none): a
5183
 *   list of strings, always non-`NULL`
5184
 *
5185
 * Since: 2.38
5186
 **/
5187
const gchar * const *
5188
g_desktop_app_info_list_actions (GDesktopAppInfo *info)
5189
0
{
5190
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5191
5192
0
  return (const gchar **) info->actions;
5193
0
}
5194
5195
static gboolean
5196
app_info_has_action (GDesktopAppInfo *info,
5197
                     const gchar     *action_name)
5198
0
{
5199
0
  gint i;
5200
5201
0
  for (i = 0; info->actions[i]; i++)
5202
0
    if (g_str_equal (info->actions[i], action_name))
5203
0
      return TRUE;
5204
5205
0
  return FALSE;
5206
0
}
5207
5208
/**
5209
 * g_desktop_app_info_get_action_name:
5210
 * @info: a [class@GioUnix.DesktopAppInfo]
5211
 * @action_name: the name of the action as from
5212
 *   [method@GioUnix.DesktopAppInfo.list_actions]
5213
 *
5214
 * Gets the user-visible display name of the
5215
 * [‘additional application actions’](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s11.html)
5216
 * specified by @action_name.
5217
 *
5218
 * This corresponds to the `Name` key within the keyfile group for the
5219
 * action.
5220
 *
5221
 * Returns: (transfer full): the locale-specific action name
5222
 *
5223
 * Since: 2.38
5224
 */
5225
gchar *
5226
g_desktop_app_info_get_action_name (GDesktopAppInfo *info,
5227
                                    const gchar     *action_name)
5228
0
{
5229
0
  gchar *group_name;
5230
0
  gchar *result;
5231
5232
0
  g_return_val_if_fail (G_IS_DESKTOP_APP_INFO (info), NULL);
5233
0
  g_return_val_if_fail (action_name != NULL, NULL);
5234
0
  g_return_val_if_fail (app_info_has_action (info, action_name), NULL);
5235
5236
0
  group_name = g_strdup_printf ("Desktop Action %s", action_name);
5237
0
  result = g_key_file_get_locale_string (info->keyfile, group_name, "Name", NULL, NULL);
5238
0
  g_free (group_name);
5239
5240
  /* The spec says that the Name field must be given.
5241
   *
5242
   * If it's not, let's follow the behaviour of our get_name()
5243
   * implementation above and never return %NULL.
5244
   */
5245
0
  if (result == NULL)
5246
0
    result = g_strdup (_("Unnamed"));
5247
5248
0
  return result;
5249
0
}
5250
5251
/**
5252
 * g_desktop_app_info_launch_action:
5253
 * @info: a [class@GioUnix.DesktopAppInfo]
5254
 * @action_name: the name of the action as from
5255
 *   [method@GioUnix.DesktopAppInfo.list_actions]
5256
 * @launch_context: (nullable): a [class@Gio.AppLaunchContext]
5257
 *
5258
 * Activates the named application action.
5259
 *
5260
 * You may only call this function on action names that were
5261
 * returned from [method@GioUnix.DesktopAppInfo.list_actions].
5262
 *
5263
 * Note that if the main entry of the desktop file indicates that the
5264
 * application supports startup notification, and @launch_context is
5265
 * non-`NULL`, then startup notification will be used when activating the
5266
 * action (and as such, invocation of the action on the receiving side
5267
 * must signal the end of startup notification when it is completed).
5268
 * This is the expected behaviour of applications declaring additional
5269
 * actions, as per the
5270
 * [desktop file specification](https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s11.html).
5271
 *
5272
 * As with [method@Gio.AppInfo.launch] there is no way to detect failures that
5273
 * occur while using this function.
5274
 *
5275
 * Since: 2.38
5276
 */
5277
void
5278
g_desktop_app_info_launch_action (GDesktopAppInfo   *info,
5279
                                  const gchar       *action_name,
5280
                                  GAppLaunchContext *launch_context)
5281
0
{
5282
0
  GDBusConnection *session_bus;
5283
5284
0
  g_return_if_fail (G_IS_DESKTOP_APP_INFO (info));
5285
0
  g_return_if_fail (action_name != NULL);
5286
0
  g_return_if_fail (app_info_has_action (info, action_name));
5287
5288
0
  session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
5289
5290
0
  if (session_bus && info->app_id)
5291
0
    {
5292
0
      gchar *object_path;
5293
5294
0
      object_path = object_path_from_appid (info->app_id);
5295
0
      g_dbus_connection_call (session_bus, info->app_id, object_path,
5296
0
                              "org.freedesktop.Application", "ActivateAction",
5297
0
                              g_variant_new ("(sav@a{sv})", action_name, NULL,
5298
0
                                             g_desktop_app_info_make_platform_data (info, NULL, launch_context)),
5299
0
                              NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL);
5300
0
      g_free (object_path);
5301
0
    }
5302
0
  else
5303
0
    {
5304
0
      gchar *group_name;
5305
0
      gchar *exec_line;
5306
5307
0
      group_name = g_strdup_printf ("Desktop Action %s", action_name);
5308
0
      exec_line = g_key_file_get_string (info->keyfile, group_name, "Exec", NULL);
5309
0
      g_free (group_name);
5310
5311
0
      if (exec_line)
5312
0
        g_desktop_app_info_launch_uris_with_spawn (info, session_bus, exec_line, NULL, launch_context,
5313
0
                                                   _SPAWN_FLAGS_DEFAULT, NULL, NULL, NULL, NULL,
5314
0
                                                   -1, -1, -1, NULL);
5315
5316
0
      g_free (exec_line);
5317
0
    }
5318
5319
0
  if (session_bus != NULL)
5320
0
    {
5321
0
      g_dbus_connection_flush (session_bus, NULL, NULL, NULL);
5322
0
      g_object_unref (session_bus);
5323
0
    }
5324
0
}
5325
/* Epilogue {{{1 */
5326
5327
/* vim:set foldmethod=marker: */