TypeScript
fix(desktop): follow live system light/dark changes on Linux (#24193)
Vasilj Miloševiće1d85af8a3fc
diff --git a/apps/desktop/src/electron/ElectronTheme.test.ts b/apps/desktop/src/electron/ElectronTheme.test.tsnew file mode 100644index 00000000000..4239bfe4c5b--- /dev/null+++ b/apps/desktop/src/electron/ElectronTheme.test.ts@@ -0,0 +1,81 @@+import { assert, describe, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import { vi } from "vite-plus/test";++import type { LinuxColorScheme } from "./LinuxColorScheme.ts";++const { nativeTheme } = vi.hoisted(() => ({+ nativeTheme: { themeSource: "system" as "system" | "light" | "dark" },+}));++vi.mock("electron", () => ({ nativeTheme }));++import * as ElectronTheme from "./ElectronTheme.ts";++function setup() {+ nativeTheme.themeSource = "system";+ const portal: { report: (scheme: LinuxColorScheme) => void; stopped: boolean } = {+ report: () => undefined,+ stopped: false,+ };+ const watch = (onChange: (scheme: LinuxColorScheme) => void) => {+ portal.report = onChange;+ return {+ stop: () => {+ portal.stopped = true;+ },+ };+ };+ return { portal, watch };+}++describe("ElectronTheme", () => {+ it.effect("resolves the system appearance from the desktop color scheme as it changes", () =>+ Effect.gen(function* () {+ const { portal, watch } = setup();+ const theme = yield* ElectronTheme.makeWith(watch);+ yield* theme.setSource("system");++ portal.report("dark");+ assert.equal(nativeTheme.themeSource, "dark");+ portal.report("light");+ assert.equal(nativeTheme.themeSource, "light");+ portal.report(null);+ assert.equal(nativeTheme.themeSource, "system");+ }).pipe(Effect.scoped),+ );++ it.effect("keeps an explicit appearance over the desktop color scheme", () =>+ Effect.gen(function* () {+ const { portal, watch } = setup();+ const theme = yield* ElectronTheme.makeWith(watch);+ portal.report("dark");++ yield* theme.setSource("light");+ portal.report("dark");+ assert.equal(nativeTheme.themeSource, "light");++ yield* theme.setSource("system");+ assert.equal(nativeTheme.themeSource, "dark");+ }).pipe(Effect.scoped),+ );++ it.effect("stops following the desktop when the layer is released", () =>+ Effect.gen(function* () {+ const { portal, watch } = setup();+ yield* ElectronTheme.makeWith(watch).pipe(Effect.scoped);+ assert.isTrue(portal.stopped);+ }),+ );++ it.effect("leaves the system appearance to Electron when the portal is unavailable", () =>+ Effect.gen(function* () {+ setup();+ const theme = yield* ElectronTheme.makeWith(() => {+ throw new Error("no session bus");+ });+ yield* theme.setSource("system");+ assert.equal(nativeTheme.themeSource, "system");+ }).pipe(Effect.scoped),+ );+});diff --git a/apps/desktop/src/electron/ElectronTheme.ts b/apps/desktop/src/electron/ElectronTheme.tsindex ab0673b817a..d31939ba761 100644--- a/apps/desktop/src/electron/ElectronTheme.ts+++ b/apps/desktop/src/electron/ElectronTheme.ts@@ -1,4 +1,5 @@import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";+import * as HostProcess from "@t3tools/shared/HostProcess";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -7,6 +8,8 @@ import * as Scope from "effect/Scope";import * as Electron from "electron";+import { watchLinuxColorScheme, type LinuxColorScheme } from "./LinuxColorScheme.ts";+export class ElectronThemeSetSourceError extends Schema.TaggedError<ElectronThemeSetSourceError>()("ElectronThemeSetSourceError",{@@ -28,30 +31,68 @@ export class ElectronTheme extends Context.Service<}>()("@t3tools/desktop/electron/ElectronTheme") {}-/** @public */-export const make = ElectronTheme.of({- shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),- setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {- return Effect.try({- try: () => {- Electron.nativeTheme.themeSource = theme;- },- catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),- });- }),- onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {- return Effect.acquireRelease(- Effect.suspend(() => {- Electron.nativeTheme.on("updated", listener);- return Effect.void;+type WatchSystemColorScheme = (onChange: (scheme: LinuxColorScheme) => void) => {+ readonly stop: () => void;+};++export const makeWith = Effect.fn("ElectronTheme.make")(function* (+ watchSystemColorScheme: WatchSystemColorScheme | undefined,+) {+ let source: DesktopTheme = Electron.nativeTheme.themeSource;+ let systemScheme: LinuxColorScheme = null;+ // On Linux, Electron reads the desktop color scheme once and then ignores the settings+ // portal (electron/electron#48736), so "system" is resolved from the portal directly.+ const apply = () => {+ Electron.nativeTheme.themeSource = source === "system" ? (systemScheme ?? source) : source;+ };++ if (watchSystemColorScheme) {+ yield* Effect.acquireRelease(+ Effect.sync(() => {+ try {+ return watchSystemColorScheme((scheme) => {+ systemScheme = scheme;+ apply();+ });+ } catch {+ return undefined;+ }}),- () =>+ (watcher) => Effect.sync(() => watcher?.stop()),+ );+ }++ return ElectronTheme.of({+ shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),+ setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {+ return Effect.try({+ try: () => {+ source = theme;+ apply();+ },+ catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),+ });+ }),+ onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {+ return Effect.acquireRelease(Effect.suspend(() => {- Electron.nativeTheme.removeListener("updated", listener);+ Electron.nativeTheme.on("updated", listener);return Effect.void;}),- );- }),+ () =>+ Effect.suspend(() => {+ Electron.nativeTheme.removeListener("updated", listener);+ return Effect.void;+ }),+ );+ }),+ });+});++/** @public */+export const make = Effect.gen(function* () {+ const platform = yield* HostProcess.Platform;+ return yield* makeWith(platform === "linux" ? watchLinuxColorScheme : undefined);});-export const layer = Layer.succeed(ElectronTheme, make);+export const layer = Layer.effect(ElectronTheme, make);diff --git a/apps/desktop/src/electron/LinuxColorScheme.test.ts b/apps/desktop/src/electron/LinuxColorScheme.test.tsnew file mode 100644index 00000000000..47225f0611b--- /dev/null+++ b/apps/desktop/src/electron/LinuxColorScheme.test.ts@@ -0,0 +1,100 @@+// @effect-diagnostics nodeBuiltinImport:off -- Event-driven fake of the portal transport.+import * as NodeEvents from "node:events";+import { DBusError, Message, MessageType, Variant, type MessageBus } from "dbus-next";+import { expect, it, vi } from "vite-plus/test";++import { watchLinuxColorScheme, type LinuxColorScheme } from "./LinuxColorScheme.ts";++const PATH = "/org/freedesktop/portal/desktop";+const SETTINGS = "org.freedesktop.portal.Settings";++class FakeBus extends NodeEvents.EventEmitter {+ calls: Message[] = [];+ disconnect = vi.fn();+ readonly settings: { readOne?: unknown; read?: unknown };+ constructor(settings: { readOne?: unknown; read?: unknown }) {+ super();+ this.settings = settings;+ }++ readonly readOneCalled = Promise.withResolvers<void>();++ async call(message: Message) {+ this.calls.push(message);+ if (message.member === "AddMatch")+ return new Message({ type: MessageType.METHOD_RETURN, replySerial: "1" });+ if (message.member === "ReadOne") this.readOneCalled.resolve();+ const value = await (message.member === "ReadOne" ? this.settings.readOne : this.settings.read);+ if (value === undefined) throw new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "");+ return new Message({+ type: MessageType.METHOD_RETURN,+ replySerial: "1",+ signature: "v",+ body: [value],+ });+ }++ changed(namespace: string, key: string, value: number) {+ this.emit(+ "message",+ new Message({+ type: MessageType.SIGNAL,+ path: PATH,+ interface: SETTINGS,+ member: "SettingChanged",+ body: [namespace, key, new Variant("u", value)],+ }),+ );+ }+}++function watch(bus: FakeBus) {+ const schemes: LinuxColorScheme[] = [];+ const { ready, stop } = watchLinuxColorScheme(+ (scheme) => schemes.push(scheme),+ bus as unknown as MessageBus,+ );+ return { schemes, ready, stop };+}++it("reads the current color scheme and follows portal changes", async () => {+ const bus = new FakeBus({ readOne: new Variant("u", 1) });+ const { schemes, ready, stop } = watch(bus);+ await ready;++ bus.changed("org.freedesktop.appearance", "color-scheme", 2);+ bus.changed("org.freedesktop.appearance", "accent-color", 1);+ bus.changed("org.gnome.desktop.interface", "color-scheme", 1);+ bus.changed("org.freedesktop.appearance", "color-scheme", 1);+ // GNOME's light mode reports "no preference".+ bus.changed("org.freedesktop.appearance", "color-scheme", 0);+ bus.changed("org.freedesktop.appearance", "color-scheme", 3);+ expect(schemes).toEqual(["dark", "light", "dark", "light", null]);++ stop();+ bus.changed("org.freedesktop.appearance", "color-scheme", 1);+ expect(schemes).toEqual(["dark", "light", "dark", "light", null]);+ expect(bus.disconnect).toHaveBeenCalledOnce();+});++it("falls back to the nested Read reply on portals without ReadOne", async () => {+ const bus = new FakeBus({ read: new Variant("v", new Variant("u", 2)) });+ const { schemes, ready } = watch(bus);+ await ready;++ expect(schemes).toEqual(["light"]);+ expect(bus.calls.map((call) => call.member)).toEqual(["AddMatch", "ReadOne", "Read"]);+});++it("keeps a change that arrives while the initial read is pending", async () => {+ const reply = Promise.withResolvers<Variant>();+ const bus = new FakeBus({ readOne: reply.promise });+ const { schemes, ready } = watch(bus);++ await bus.readOneCalled.promise;+ bus.changed("org.freedesktop.appearance", "color-scheme", 1);+ reply.resolve(new Variant("u", 0));+ await ready;++ expect(schemes).toEqual(["dark"]);+});diff --git a/apps/desktop/src/electron/LinuxColorScheme.ts b/apps/desktop/src/electron/LinuxColorScheme.tsnew file mode 100644index 00000000000..8b88fd5655a--- /dev/null+++ b/apps/desktop/src/electron/LinuxColorScheme.ts@@ -0,0 +1,91 @@+import { Message, MessageType, Variant, sessionBus, type MessageBus } from "dbus-next";++const PORTAL = "org.freedesktop.portal.Desktop";+const PATH = "/org/freedesktop/portal/desktop";+const SETTINGS = "org.freedesktop.portal.Settings";+const DBUS = "org.freedesktop.DBus";+const NAMESPACE = "org.freedesktop.appearance";+const KEY = "color-scheme";++export type LinuxColorScheme = "dark" | "light" | null;++// The portal reports 1 for prefer-dark, 2 for prefer-light and 0 for no preference. GNOME's+// light mode is 0, and the spec asks apps to use their default then, so only 1 is dark.+// The deprecated Read method nests the value in a second variant.+function decodeColorScheme(value: unknown): LinuxColorScheme {+ let scheme = value;+ while (scheme instanceof Variant) scheme = scheme.value;+ return scheme === 1 ? "dark" : scheme === 0 || scheme === 2 ? "light" : null;+}++const settingsCall = (member: "ReadOne" | "Read") =>+ new Message({+ destination: PORTAL,+ path: PATH,+ interface: SETTINGS,+ member,+ signature: "ss",+ body: [NAMESPACE, KEY],+ });++/**+ * Follows the desktop color scheme through the XDG settings portal. Without a session bus or+ * portal it reports nothing, so Chromium's own resolution stays in charge.+ */+export function watchLinuxColorScheme(+ onChange: (scheme: LinuxColorScheme) => void,+ bus: MessageBus = sessionBus(),+) {+ let closed = false;+ let changed = false;+ const report = (value: unknown) => {+ if (!closed) onChange(decodeColorScheme(value));+ };+ const onMessage = (message: Message) => {+ if (+ message.type !== MessageType.SIGNAL ||+ message.path !== PATH ||+ message.interface !== SETTINGS ||+ message.member !== "SettingChanged"+ )+ return;+ const [namespace, key, value] = message.body;+ if (namespace !== NAMESPACE || key !== KEY) return;+ changed = true;+ report(value);+ };+ const ignore = () => undefined;++ bus.on("error", ignore);+ bus.on("message", onMessage);+ const ready = (async () => {+ await bus.call(+ new Message({+ destination: DBUS,+ path: "/org/freedesktop/DBus",+ interface: DBUS,+ member: "AddMatch",+ signature: "s",+ body: [+ `type='signal',interface='${SETTINGS}',member='SettingChanged',path='${PATH}',arg0='${NAMESPACE}',arg1='${KEY}'`,+ ],+ }),+ );+ // ReadOne needs Settings portal version 2; older portals only offer Read.+ const reply = await bus+ .call(settingsCall("ReadOne"))+ .catch(() => bus.call(settingsCall("Read")));+ // The portal answers reads through its backend asynchronously, so a change signal can+ // overtake this reply; the reply then carries the older value.+ if (reply && !changed) report(reply.body[0]);+ })().catch(ignore);++ return {+ ready,+ stop: () => {+ closed = true;+ bus.removeListener("message", onMessage);+ bus.disconnect();+ },+ };+}