Coverage Report

Created: 2025-06-13 06:55

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