File: WidgetUtilsGtk.cpp

package info (click to toggle)
firefox 147.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,683,320 kB
  • sloc: cpp: 7,607,359; javascript: 6,533,295; ansic: 3,775,223; python: 1,415,500; xml: 634,561; asm: 438,949; java: 186,241; sh: 62,752; makefile: 18,079; objc: 13,092; perl: 12,808; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (652 lines) | stat: -rw-r--r-- 20,523 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "WidgetUtilsGtk.h"

#include "MainThreadUtils.h"
#include "mozilla/StaticPrefs_widget.h"
#include "mozilla/UniquePtr.h"
#include "nsReadableUtils.h"
#include "nsString.h"
#include "nsStringFwd.h"
#include "nsWindow.h"
#include "nsIGfxInfo.h"
#include "mozilla/Components.h"
#include "nsCOMPtr.h"
#include "nsIProperties.h"
#include "nsIFile.h"
#include "nsXULAppAPI.h"
#include "nsXPCOMCID.h"
#include "nsDirectoryServiceDefs.h"
#include "nsString.h"
#include "nsGtkKeyUtils.h"
#include "nsGtkUtils.h"

#include <gtk/gtk.h>
#include <dlfcn.h>
#include <glib.h>

#ifdef MOZ_ENABLE_DBUS
#  include "mozilla/ClearOnShutdown.h"
#  include "mozilla/widget/AsyncDBus.h"
#  include "nsAppShell.h"
#endif  // MOZ_ENABLE_DBUS

#ifdef MOZ_WAYLAND
#  include "nsWaylandDisplay.h"
#endif  // MOZ_WAYLAND

#ifdef MOZ_X11
#  include <X11/Xlib.h>
#  include <X11/Xatom.h>
#endif /* MOZ_X11 */

#undef LOGW
#ifdef MOZ_LOGGING
#  include "mozilla/Logging.h"
extern mozilla::LazyLogModule gWidgetLog;
#  define LOGW(...) MOZ_LOG(gWidgetLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
#else
#  define LOGW(...)
#endif /* MOZ_LOGGING */

namespace mozilla::widget {

#ifdef MOZ_ENABLE_DBUS
constexpr char sXdpServiceName[] = "org.freedesktop.portal.Desktop";
constexpr char sXdpDBusPath[] = "/org/freedesktop/portal/desktop";
constexpr char sXdpRegistryInterfaceName[] =
    "org.freedesktop.host.portal.Registry";
#endif

int32_t WidgetUtilsGTK::IsTouchDeviceSupportPresent() {
  int32_t result = 0;
  GdkDisplay* display = gdk_display_get_default();
  if (!display) {
    return 0;
  }

  GdkDeviceManager* manager = gdk_display_get_device_manager(display);
  if (!manager) {
    return 0;
  }

  GList* devices =
      gdk_device_manager_list_devices(manager, GDK_DEVICE_TYPE_SLAVE);
  GList* list = devices;

  while (devices) {
    GdkDevice* device = static_cast<GdkDevice*>(devices->data);
    if (gdk_device_get_source(device) == GDK_SOURCE_TOUCHSCREEN) {
      result = 1;
      break;
    }
    devices = devices->next;
  }

  if (list) {
    g_list_free(list);
  }

  return result;
}

bool IsMainWindowTransparent() {
  return nsWindow::IsToplevelWindowTransparent();
}

// We avoid linking gdk_*_display_get_type directly in order to avoid a runtime
// dependency on GTK built with both backends. Other X11- and Wayland-specific
// functions get stubbed out by libmozgtk and crash when called, but those
// should only be called when the matching backend is already in use.

bool GdkIsWaylandDisplay(GdkDisplay* display) {
  static auto sGdkWaylandDisplayGetType =
      (GType (*)())dlsym(RTLD_DEFAULT, "gdk_wayland_display_get_type");
  return sGdkWaylandDisplayGetType &&
         G_TYPE_CHECK_INSTANCE_TYPE(display, sGdkWaylandDisplayGetType());
}

bool GdkIsX11Display(GdkDisplay* display) {
  static auto sGdkX11DisplayGetType =
      (GType (*)())dlsym(RTLD_DEFAULT, "gdk_x11_display_get_type");
  return sGdkX11DisplayGetType &&
         G_TYPE_CHECK_INSTANCE_TYPE(display, sGdkX11DisplayGetType());
}

bool IsXWaylandProtocol() {
  static bool isXwayland = [] {
    return !GdkIsWaylandDisplay() && !!getenv("WAYLAND_DISPLAY");
  }();
  return isXwayland;
}

bool GdkIsWaylandDisplay() {
  static bool isWaylandDisplay = gdk_display_get_default() &&
                                 GdkIsWaylandDisplay(gdk_display_get_default());
  return isWaylandDisplay;
}

bool GdkIsX11Display() {
  static bool isX11Display = gdk_display_get_default()
                                 ? GdkIsX11Display(gdk_display_get_default())
                                 : false;
  return isX11Display;
}

GdkDevice* GdkGetPointer() {
  GdkDisplay* display = gdk_display_get_default();
  GdkDeviceManager* deviceManager = gdk_display_get_device_manager(display);
  return gdk_device_manager_get_client_pointer(deviceManager);
}

static GdkEvent* sLastPointerDownEvent = nullptr;
GdkEvent* GetLastPointerDownEvent() { return sLastPointerDownEvent; }

void SetLastPointerDownEvent(GdkEvent* aEvent) {
  if (sLastPointerDownEvent) {
    GUniquePtr<GdkEvent> event(sLastPointerDownEvent);
    sLastPointerDownEvent = nullptr;
  }
  if (!aEvent) {
    return;
  }
  GUniquePtr<GdkEvent> event(gdk_event_copy(aEvent));
  sLastPointerDownEvent = event.release();
}

bool IsRunningUnderSnap() { return !!GetSnapInstanceName(); }

bool IsRunningUnderFlatpak() {
  // https://gitlab.gnome.org/GNOME/gtk/-/blob/4300a5c609306ce77cbc8a3580c19201dccd8d13/gdk/gdk.c#L472
  static bool sRunning = [] {
    return g_file_test("/.flatpak-info", G_FILE_TEST_EXISTS);
  }();
  return sRunning;
}

#ifdef MOZ_ENABLE_DBUS
static void DoRegisterHostApp() {
  GUniquePtr<GError> error;

  nsAppShell::DBusConnectionCheck();
  RefPtr<GDBusProxy> proxy = dont_AddRef(g_dbus_proxy_new_for_bus_sync(
      G_BUS_TYPE_SESSION, G_DBUS_PROXY_FLAGS_NONE, nullptr, sXdpServiceName,
      sXdpDBusPath, sXdpRegistryInterfaceName, nullptr /* cancellable */,
      getter_Transfers(error)));
  if (error) {
    NS_WARNING(
        nsPrintfCString("Failed to create DBus proxy : %s\n", error->message)
            .get());
    return;
  }

  GVariantBuilder builder;
  g_variant_builder_init(&builder, G_VARIANT_TYPE("(sa{sv})"));
  g_variant_builder_add(&builder, "s", "org.mozilla.firefox");
  GVariantBuilder dict_builder;
  g_variant_builder_init(&dict_builder, G_VARIANT_TYPE("a{sv}"));
  g_variant_builder_add_value(&builder, g_variant_builder_end(&dict_builder));

  RefPtr<GVariant> args =
      dont_AddRef(g_variant_ref_sink(g_variant_builder_end(&builder)));

  DBusProxyCall(proxy, "Register", args, G_DBUS_CALL_FLAGS_NONE, -1,
                /* cancellable */ nullptr)
      ->Then(GetCurrentSerialEventTarget(), __func__,
             [](const DBusCallPromise::ResolveOrRejectValue& aValue) {
               if (aValue.IsReject()) {
                 NS_WARNING(
                     "Failed to register host application for "
                     "portals\n");
               }
             });
}

void RegisterHostApp() {
  static bool sInitialized = false;

  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(XRE_IsParentProcess());
  MOZ_ASSERT(!sInitialized);

  // Register unsandboxed application with an application ID that will be used
  // in portals. It has to be called before any other portal call, which
  // happens with gtk_init or in our LookAndFeel code. We also need to
  // re-register again when the portal is restarted. Documentation:
  // https://github.com/flatpak/xdg-desktop-portal/blob/main/data/org.freedesktop.host.portal.Registry.xml
  if (sInitialized || IsRunningUnderFlatpakOrSnap() ||
      g_getenv("XPCSHELL_TEST")) {
    return;
  }

  sInitialized = true;

  uint32_t DBusID = g_bus_watch_name(
      G_BUS_TYPE_SESSION, sXdpServiceName, G_BUS_NAME_WATCHER_FLAGS_AUTO_START,
      [](GDBusConnection*, const gchar*, const gchar*, gpointer data) -> void {
        DoRegisterHostApp();
      },
      nullptr, nullptr, nullptr);

  if (DBusID) {
    RunOnShutdown([DBusID] { g_bus_unwatch_name(DBusID); });
  }
}
#endif

bool IsPackagedAppFileExists() {
  static bool sRunning = [] {
    nsresult rv;
    nsCString path;
    nsCOMPtr<nsIFile> file;
    nsCOMPtr<nsIProperties> directoryService;

    directoryService = do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
    NS_ENSURE_TRUE(directoryService, FALSE);

    rv = directoryService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile),
                               getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, FALSE);

    rv = file->AppendNative("is-packaged-app"_ns);
    NS_ENSURE_SUCCESS(rv, FALSE);

    rv = file->GetNativePath(path);
    NS_ENSURE_SUCCESS(rv, FALSE);

    return g_file_test(path.get(), G_FILE_TEST_EXISTS);
  }();
  return sRunning;
}

const char* GetSnapInstanceName() {
  static const char* sInstanceName = []() -> const char* {
    const char* snapName = g_getenv("SNAP_NAME");
    if (!snapName) {
      return nullptr;
    }
    if (g_strcmp0(snapName, MOZ_APP_NAME) &&
        g_strcmp0(snapName, MOZ_APP_NAME "-devel")) {
      return nullptr;
    }
    // Intentionally leaked, as keeping a pointer to the environment forever
    // is a bit suspicious.
    if (const char* instanceName = g_getenv("SNAP_INSTANCE_NAME")) {
      return g_strdup(instanceName);
    }
    // Instance name didn't exist for snapd <= 2.35:
    return g_strdup(snapName);
  }();
  return sInstanceName;
}

bool ShouldUsePortal(PortalKind aPortalKind) {
  static bool sPortalEnv = [] {
    if (IsRunningUnderFlatpakOrSnap()) {
      return true;
    }
    const char* portalEnvString = g_getenv("GTK_USE_PORTAL");
    return portalEnvString && atoi(portalEnvString) != 0;
  }();

  bool autoBehavior = sPortalEnv;
  const int32_t pref = [&] {
    switch (aPortalKind) {
      case PortalKind::FilePicker:
#ifdef EARLY_BETA_OR_EARLIER
        autoBehavior = true;
#endif
        return StaticPrefs::widget_use_xdg_desktop_portal_file_picker();
      case PortalKind::MimeHandler:
        // Mime portal breaks default browser handling, see bug 1516290.
        autoBehavior = IsRunningUnderFlatpakOrSnap();
        return StaticPrefs::widget_use_xdg_desktop_portal_mime_handler();
      case PortalKind::NativeMessaging:
        return StaticPrefs::widget_use_xdg_desktop_portal_native_messaging();
      case PortalKind::Settings:
        autoBehavior = true;
        return StaticPrefs::widget_use_xdg_desktop_portal_settings();
      case PortalKind::Location:
        return StaticPrefs::widget_use_xdg_desktop_portal_location();
      case PortalKind::OpenUri:
        return StaticPrefs::widget_use_xdg_desktop_portal_open_uri();
    }
    return 2;
  }();

  switch (pref) {
    case 0:
      return false;
    case 1:
      return true;
    default:
      return autoBehavior;
  }
}

nsTArray<nsCString> ParseTextURIList(const nsACString& aData) {
  UniquePtr<char[]> data(ToNewCString(aData));
  gchar** uris = g_uri_list_extract_uris(data.get());

  nsTArray<nsCString> result;
  for (size_t i = 0; i < g_strv_length(uris); i++) {
    result.AppendElement(nsCString(uris[i]));
  }

  g_strfreev(uris);
  return result;
}

#ifdef MOZ_WAYLAND
static gboolean token_failed(gpointer aData);

class XDGTokenRequest {
 public:
  void SetTokenID(const char* aTokenID) {
    LOGW("RequestWaylandFocusPromise() SetTokenID %s", aTokenID);
    mTransferPromise->Resolve(aTokenID, __func__);
  }
  void Cancel() {
    LOGW("RequestWaylandFocusPromise() canceled");
    mTransferPromise->Reject(false, __func__);
    mActivationTimeoutID = 0;
  }

  XDGTokenRequest(xdg_activation_token_v1* aXdgToken,
                  RefPtr<FocusRequestPromise::Private> aTransferPromise)
      : mXdgToken(aXdgToken), mTransferPromise(std::move(aTransferPromise)) {
    mActivationTimeoutID =
        g_timeout_add(sActivationTimeout, token_failed, this);
  }
  ~XDGTokenRequest() {
    MozClearPointer(mXdgToken, xdg_activation_token_v1_destroy);
    if (mActivationTimeoutID) {
      g_source_remove(mActivationTimeoutID);
    }
  }

 private:
  xdg_activation_token_v1* mXdgToken;
  RefPtr<FocusRequestPromise::Private> mTransferPromise;
  guint mActivationTimeoutID;
  // Reject FocusRequestPromise if we don't get XDG token in 0.5 sec.
  static constexpr int sActivationTimeout = 500;
};

// Failed to get token in time
static gboolean token_failed(gpointer data) {
  UniquePtr<XDGTokenRequest> request(static_cast<XDGTokenRequest*>(data));
  request->Cancel();
  return false;
}

// We've got activation token from Wayland compositor so it's time to use it.
static void token_done(gpointer data, struct xdg_activation_token_v1* provider,
                       const char* tokenID) {
  UniquePtr<XDGTokenRequest> request(static_cast<XDGTokenRequest*>(data));
  request->SetTokenID(tokenID);
}

static const struct xdg_activation_token_v1_listener token_listener = {
    token_done,
};
#endif

RefPtr<FocusRequestPromise> RequestWaylandFocusPromise() {
#ifdef MOZ_WAYLAND
  if (!GdkIsWaylandDisplay() || !WaylandDisplayGet()->GetSeat()) {
    LOGW("RequestWaylandFocusPromise() failed.");
    return nullptr;
  }

  RefPtr<nsWindow> sourceWindow = nsWindow::GetFocusedWindow();
  if (!sourceWindow || sourceWindow->IsDestroyed()) {
    LOGW("RequestWaylandFocusPromise() missing source window");
    return nullptr;
  }

  xdg_activation_v1* xdg_activation = WaylandDisplayGet()->GetXdgActivation();
  if (!xdg_activation) {
    LOGW("RequestWaylandFocusPromise() missing xdg_activation");
    return nullptr;
  }

  GdkWindow* gdkWindow = sourceWindow->GetToplevelGdkWindow();
  if (!gdkWindow) {
    return nullptr;
  }
  wl_surface* surface = gdk_wayland_window_get_wl_surface(gdkWindow);

  RefPtr<FocusRequestPromise::Private> transferPromise =
      new FocusRequestPromise::Private(__func__);

  xdg_activation_token_v1* aXdgToken =
      xdg_activation_v1_get_activation_token(xdg_activation);
  xdg_activation_token_v1_add_listener(
      aXdgToken, &token_listener,
      new XDGTokenRequest(aXdgToken, transferPromise));
  xdg_activation_token_v1_set_serial(aXdgToken,
                                     nsWaylandDisplay::GetLastEventSerial(),
                                     WaylandDisplayGet()->GetSeat());
  xdg_activation_token_v1_set_surface(aXdgToken, surface);
  xdg_activation_token_v1_commit(aXdgToken);

  LOGW("RequestWaylandFocusPromise() XDG Token sent");

  return transferPromise.forget();
#else  // !defined(MOZ_WAYLAND)
  return nullptr;
#endif
}

// https://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html
static nsCString GetWindowManagerName() {
  if (!GdkIsX11Display()) {
    return {};
  }

#ifdef MOZ_X11
  Display* xdisplay = gdk_x11_get_default_xdisplay();
  Window root_win =
      GDK_WINDOW_XID(gdk_screen_get_root_window(gdk_screen_get_default()));

  int actual_format_return;
  Atom actual_type_return;
  unsigned long nitems_return;
  unsigned long bytes_after_return;
  unsigned char* prop_return = nullptr;
  auto releaseXProperty = MakeScopeExit([&] {
    if (prop_return) {
      XFree(prop_return);
    }
  });

  Atom property = XInternAtom(xdisplay, "_NET_SUPPORTING_WM_CHECK", true);
  Atom req_type = XInternAtom(xdisplay, "WINDOW", true);
  if (!property || !req_type) {
    return {};
  }
  int result =
      XGetWindowProperty(xdisplay, root_win, property,
                         0L,                  // offset
                         sizeof(Window) / 4,  // length
                         false,               // delete
                         req_type, &actual_type_return, &actual_format_return,
                         &nitems_return, &bytes_after_return, &prop_return);

  if (result != Success || bytes_after_return != 0 || nitems_return != 1) {
    return {};
  }

  Window wmWindow = reinterpret_cast<Window*>(prop_return)[0];
  if (!wmWindow) {
    return {};
  }

  XFree(prop_return);
  prop_return = nullptr;

  property = XInternAtom(xdisplay, "_NET_WM_NAME", true);
  req_type = XInternAtom(xdisplay, "UTF8_STRING", true);
  if (!property || !req_type) {
    return {};
  }
  result =
      XGetWindowProperty(xdisplay, wmWindow, property,
                         0L,         // offset
                         INT32_MAX,  // length
                         false,      // delete
                         req_type, &actual_type_return, &actual_format_return,
                         &nitems_return, &bytes_after_return, &prop_return);
  if (result != Success || bytes_after_return != 0) {
    return {};
  }

  return nsCString(reinterpret_cast<const char*>(prop_return));
#else
  return {};
#endif
}

// Getting a reliable identifier is quite tricky. We try to use the standard
// XDG_CURRENT_DESKTOP environment first, _NET_WM_NAME later, and a set of
// legacy / non-standard environment variables otherwise.
//
// Documentation for some of those can be found in:
//
// https://wiki.archlinux.org/title/Environment_variables#Examples
// https://wiki.archlinux.org/title/Xdg-utils#Environment_variables
const nsCString& GetDesktopEnvironmentIdentifier() {
  static const nsDependentCString sIdentifier = [] {
    nsCString ident = [] {
      auto Env = [](const char* aKey) -> const char* {
        const char* v = getenv(aKey);
        return v && *v ? v : nullptr;
      };
      if (const char* currentDesktop = Env("XDG_CURRENT_DESKTOP")) {
        return nsCString(currentDesktop);
      }
      if (auto wm = GetWindowManagerName(); !wm.IsEmpty()) {
        return wm;
      }
      if (const char* sessionDesktop = Env("XDG_SESSION_DESKTOP")) {
        // This is not really standardized in freedesktop.org, but it is
        // documented here, and should be set in systemd systems.
        // https://www.freedesktop.org/software/systemd/man/pam_systemd.html#%24XDG_SESSION_DESKTOP
        return nsCString(sessionDesktop);
      }
      // We try first the DE-specific variables, then SESSION_DESKTOP, to match
      // the documented order in:
      // https://wiki.archlinux.org/title/Xdg-utils#Environment_variables
      if (getenv("GNOME_DESKTOP_SESSION_ID")) {
        return nsCString("gnome"_ns);
      }
      if (getenv("KDE_FULL_SESSION")) {
        return nsCString("kde"_ns);
      }
      if (getenv("MATE_DESKTOP_SESSION_ID")) {
        return nsCString("mate"_ns);
      }
      if (getenv("LXQT_SESSION_CONFIG")) {
        return nsCString("lxqt"_ns);
      }
      if (const char* desktopSession = Env("DESKTOP_SESSION")) {
        // Try the legacy DESKTOP_SESSION as a last resort.
        return nsCString(desktopSession);
      }
      return nsCString();
    }();
    ToLowerCase(ident);
    // Intentionally put into a ToNewCString copy, rather than just making a
    // static nsCString to avoid leakchecking errors, since we really want to
    // leak this string.
    return nsDependentCString(ToNewCString(ident), ident.Length());
  }();
  return sIdentifier;
}

bool IsGnomeDesktopEnvironment() {
  static bool sIsGnome =
      !!FindInReadable("gnome"_ns, GetDesktopEnvironmentIdentifier());
  return sIsGnome;
}

bool IsKdeDesktopEnvironment() {
  static bool sIsKde = GetDesktopEnvironmentIdentifier().EqualsLiteral("kde");
  return sIsKde;
}

bool IsCancelledGError(GError* aGError) {
  return g_error_matches(aGError, G_IO_ERROR, G_IO_ERROR_CANCELLED);
}

#if defined(MOZ_X11)
static unsigned long GetWindowUserTime(GdkDisplay* aDisplay,
                                       uintptr_t aWindow) {
  Atom actualType;
  int actualFormat;
  unsigned long numberOfItems;
  unsigned long bytesAfter;
  unsigned char* property = nullptr;
  unsigned long userTime = 0;

  Display* xDisplay = GDK_DISPLAY_XDISPLAY(aDisplay);
  Atom atom =
      gdk_x11_get_xatom_by_name_for_display(aDisplay, "_NET_WM_USER_TIME");

  if (XGetWindowProperty(xDisplay, aWindow, atom, 0, 1, false, XA_CARDINAL,
                         &actualType, &actualFormat, &numberOfItems,
                         &bytesAfter, &property) == Success &&
      property) {
    if (numberOfItems == 1) {
      userTime = *((unsigned long*)property);
    }
    XFree(property);
  }

  return userTime;
}

void FindLatestUserTime(GdkDisplay* aDisplay, uintptr_t aWindow,
                        unsigned long* aLatestTime) {
  Window rootReturn;
  Window parentReturn;
  Window* children;
  unsigned int numberOfChildren;
  unsigned long userTime;

  Display* xDisplay = GDK_DISPLAY_XDISPLAY(aDisplay);

  if (XQueryTree(xDisplay, aWindow, &rootReturn, &parentReturn, &children,
                 &numberOfChildren)) {
    for (unsigned int i = 0; i < numberOfChildren; i++) {
      userTime = GetWindowUserTime(aDisplay, children[i]);
      if (userTime > *aLatestTime) {
        *aLatestTime = userTime;
      }
      FindLatestUserTime(aDisplay, children[i], aLatestTime);
    }

    XFree(children);
  }
}

// Assume we're started from user interaction and infer user time if its missing
nsCString SynthesizeStartupToken() {
  unsigned long latestUserTime = 0;
  FindLatestUserTime(gdk_display_get_default(),
                     GDK_WINDOW_XID(gdk_get_default_root_window()),
                     &latestUserTime);

  if (latestUserTime == 0) {
    return nsCString();
  }

  return nsPrintfCString("%s_TIME%lu", g_get_host_name(), latestUserTime);
}
#endif

}  // namespace mozilla::widget