Skip to content

Commit e1d85af

Browse files
eboyeclaudemaria-rcks
authored
fix(desktop): follow live system light/dark changes on Linux (#24193)
Co-authored-by: eboye <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent c924644 commit e1d85af

4 files changed

Lines changed: 334 additions & 21 deletions

File tree

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import { assert, describe, it } from "@effect/vitest";
2+
import * as Effect from "effect/Effect";
3+
import { vi } from "vite-plus/test";
4+
5+
import type { LinuxColorScheme } from "./LinuxColorScheme.ts";
6+
7+
const { nativeTheme } = vi.hoisted(() => ({
8+
nativeTheme: { themeSource: "system" as "system" | "light" | "dark" },
9+
}));
10+
11+
vi.mock("electron", () => ({ nativeTheme }));
12+
13+
import * as ElectronTheme from "./ElectronTheme.ts";
14+
15+
function setup() {
16+
nativeTheme.themeSource = "system";
17+
const portal: { report: (scheme: LinuxColorScheme) => void; stopped: boolean } = {
18+
report: () => undefined,
19+
stopped: false,
20+
};
21+
const watch = (onChange: (scheme: LinuxColorScheme) => void) => {
22+
portal.report = onChange;
23+
return {
24+
stop: () => {
25+
portal.stopped = true;
26+
},
27+
};
28+
};
29+
return { portal, watch };
30+
}
31+
32+
describe("ElectronTheme", () => {
33+
it.effect("resolves the system appearance from the desktop color scheme as it changes", () =>
34+
Effect.gen(function* () {
35+
const { portal, watch } = setup();
36+
const theme = yield* ElectronTheme.makeWith(watch);
37+
yield* theme.setSource("system");
38+
39+
portal.report("dark");
40+
assert.equal(nativeTheme.themeSource, "dark");
41+
portal.report("light");
42+
assert.equal(nativeTheme.themeSource, "light");
43+
portal.report(null);
44+
assert.equal(nativeTheme.themeSource, "system");
45+
}).pipe(Effect.scoped),
46+
);
47+
48+
it.effect("keeps an explicit appearance over the desktop color scheme", () =>
49+
Effect.gen(function* () {
50+
const { portal, watch } = setup();
51+
const theme = yield* ElectronTheme.makeWith(watch);
52+
portal.report("dark");
53+
54+
yield* theme.setSource("light");
55+
portal.report("dark");
56+
assert.equal(nativeTheme.themeSource, "light");
57+
58+
yield* theme.setSource("system");
59+
assert.equal(nativeTheme.themeSource, "dark");
60+
}).pipe(Effect.scoped),
61+
);
62+
63+
it.effect("stops following the desktop when the layer is released", () =>
64+
Effect.gen(function* () {
65+
const { portal, watch } = setup();
66+
yield* ElectronTheme.makeWith(watch).pipe(Effect.scoped);
67+
assert.isTrue(portal.stopped);
68+
}),
69+
);
70+
71+
it.effect("leaves the system appearance to Electron when the portal is unavailable", () =>
72+
Effect.gen(function* () {
73+
setup();
74+
const theme = yield* ElectronTheme.makeWith(() => {
75+
throw new Error("no session bus");
76+
});
77+
yield* theme.setSource("system");
78+
assert.equal(nativeTheme.themeSource, "system");
79+
}).pipe(Effect.scoped),
80+
);
81+
});
Lines changed: 62 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { DesktopThemeSchema, type DesktopTheme } from "@t3tools/contracts";
2+
import * as HostProcess from "@t3tools/shared/HostProcess";
23
import * as Context from "effect/Context";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
@@ -7,6 +8,8 @@ import * as Scope from "effect/Scope";
78

89
import * as Electron from "electron";
910

11+
import { watchLinuxColorScheme, type LinuxColorScheme } from "./LinuxColorScheme.ts";
12+
1013
export class ElectronThemeSetSourceError extends Schema.TaggedError<ElectronThemeSetSourceError>()(
1114
"ElectronThemeSetSourceError",
1215
{
@@ -28,30 +31,68 @@ export class ElectronTheme extends Context.Service<
2831
}
2932
>()("@t3tools/desktop/electron/ElectronTheme") {}
3033

31-
/** @public */
32-
export const make = ElectronTheme.of({
33-
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
34-
setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {
35-
return Effect.try({
36-
try: () => {
37-
Electron.nativeTheme.themeSource = theme;
38-
},
39-
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
40-
});
41-
}),
42-
onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {
43-
return Effect.acquireRelease(
44-
Effect.suspend(() => {
45-
Electron.nativeTheme.on("updated", listener);
46-
return Effect.void;
34+
type WatchSystemColorScheme = (onChange: (scheme: LinuxColorScheme) => void) => {
35+
readonly stop: () => void;
36+
};
37+
38+
export const makeWith = Effect.fn("ElectronTheme.make")(function* (
39+
watchSystemColorScheme: WatchSystemColorScheme | undefined,
40+
) {
41+
let source: DesktopTheme = Electron.nativeTheme.themeSource;
42+
let systemScheme: LinuxColorScheme = null;
43+
// On Linux, Electron reads the desktop color scheme once and then ignores the settings
44+
// portal (electron/electron#48736), so "system" is resolved from the portal directly.
45+
const apply = () => {
46+
Electron.nativeTheme.themeSource = source === "system" ? (systemScheme ?? source) : source;
47+
};
48+
49+
if (watchSystemColorScheme) {
50+
yield* Effect.acquireRelease(
51+
Effect.sync(() => {
52+
try {
53+
return watchSystemColorScheme((scheme) => {
54+
systemScheme = scheme;
55+
apply();
56+
});
57+
} catch {
58+
return undefined;
59+
}
4760
}),
48-
() =>
61+
(watcher) => Effect.sync(() => watcher?.stop()),
62+
);
63+
}
64+
65+
return ElectronTheme.of({
66+
shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors),
67+
setSource: Effect.fn("ElectronTheme.setSource")(function (theme) {
68+
return Effect.try({
69+
try: () => {
70+
source = theme;
71+
apply();
72+
},
73+
catch: (cause) => new ElectronThemeSetSourceError({ source: theme, cause }),
74+
});
75+
}),
76+
onUpdated: Effect.fn("ElectronTheme.onUpdated")(function (listener) {
77+
return Effect.acquireRelease(
4978
Effect.suspend(() => {
50-
Electron.nativeTheme.removeListener("updated", listener);
79+
Electron.nativeTheme.on("updated", listener);
5180
return Effect.void;
5281
}),
53-
);
54-
}),
82+
() =>
83+
Effect.suspend(() => {
84+
Electron.nativeTheme.removeListener("updated", listener);
85+
return Effect.void;
86+
}),
87+
);
88+
}),
89+
});
90+
});
91+
92+
/** @public */
93+
export const make = Effect.gen(function* () {
94+
const platform = yield* HostProcess.Platform;
95+
return yield* makeWith(platform === "linux" ? watchLinuxColorScheme : undefined);
5596
});
5697

57-
export const layer = Layer.succeed(ElectronTheme, make);
98+
export const layer = Layer.effect(ElectronTheme, make);
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// @effect-diagnostics nodeBuiltinImport:off -- Event-driven fake of the portal transport.
2+
import * as NodeEvents from "node:events";
3+
import { DBusError, Message, MessageType, Variant, type MessageBus } from "dbus-next";
4+
import { expect, it, vi } from "vite-plus/test";
5+
6+
import { watchLinuxColorScheme, type LinuxColorScheme } from "./LinuxColorScheme.ts";
7+
8+
const PATH = "/org/freedesktop/portal/desktop";
9+
const SETTINGS = "org.freedesktop.portal.Settings";
10+
11+
class FakeBus extends NodeEvents.EventEmitter {
12+
calls: Message[] = [];
13+
disconnect = vi.fn();
14+
readonly settings: { readOne?: unknown; read?: unknown };
15+
constructor(settings: { readOne?: unknown; read?: unknown }) {
16+
super();
17+
this.settings = settings;
18+
}
19+
20+
readonly readOneCalled = Promise.withResolvers<void>();
21+
22+
async call(message: Message) {
23+
this.calls.push(message);
24+
if (message.member === "AddMatch")
25+
return new Message({ type: MessageType.METHOD_RETURN, replySerial: "1" });
26+
if (message.member === "ReadOne") this.readOneCalled.resolve();
27+
const value = await (message.member === "ReadOne" ? this.settings.readOne : this.settings.read);
28+
if (value === undefined) throw new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "");
29+
return new Message({
30+
type: MessageType.METHOD_RETURN,
31+
replySerial: "1",
32+
signature: "v",
33+
body: [value],
34+
});
35+
}
36+
37+
changed(namespace: string, key: string, value: number) {
38+
this.emit(
39+
"message",
40+
new Message({
41+
type: MessageType.SIGNAL,
42+
path: PATH,
43+
interface: SETTINGS,
44+
member: "SettingChanged",
45+
body: [namespace, key, new Variant("u", value)],
46+
}),
47+
);
48+
}
49+
}
50+
51+
function watch(bus: FakeBus) {
52+
const schemes: LinuxColorScheme[] = [];
53+
const { ready, stop } = watchLinuxColorScheme(
54+
(scheme) => schemes.push(scheme),
55+
bus as unknown as MessageBus,
56+
);
57+
return { schemes, ready, stop };
58+
}
59+
60+
it("reads the current color scheme and follows portal changes", async () => {
61+
const bus = new FakeBus({ readOne: new Variant("u", 1) });
62+
const { schemes, ready, stop } = watch(bus);
63+
await ready;
64+
65+
bus.changed("org.freedesktop.appearance", "color-scheme", 2);
66+
bus.changed("org.freedesktop.appearance", "accent-color", 1);
67+
bus.changed("org.gnome.desktop.interface", "color-scheme", 1);
68+
bus.changed("org.freedesktop.appearance", "color-scheme", 1);
69+
// GNOME's light mode reports "no preference".
70+
bus.changed("org.freedesktop.appearance", "color-scheme", 0);
71+
bus.changed("org.freedesktop.appearance", "color-scheme", 3);
72+
expect(schemes).toEqual(["dark", "light", "dark", "light", null]);
73+
74+
stop();
75+
bus.changed("org.freedesktop.appearance", "color-scheme", 1);
76+
expect(schemes).toEqual(["dark", "light", "dark", "light", null]);
77+
expect(bus.disconnect).toHaveBeenCalledOnce();
78+
});
79+
80+
it("falls back to the nested Read reply on portals without ReadOne", async () => {
81+
const bus = new FakeBus({ read: new Variant("v", new Variant("u", 2)) });
82+
const { schemes, ready } = watch(bus);
83+
await ready;
84+
85+
expect(schemes).toEqual(["light"]);
86+
expect(bus.calls.map((call) => call.member)).toEqual(["AddMatch", "ReadOne", "Read"]);
87+
});
88+
89+
it("keeps a change that arrives while the initial read is pending", async () => {
90+
const reply = Promise.withResolvers<Variant>();
91+
const bus = new FakeBus({ readOne: reply.promise });
92+
const { schemes, ready } = watch(bus);
93+
94+
await bus.readOneCalled.promise;
95+
bus.changed("org.freedesktop.appearance", "color-scheme", 1);
96+
reply.resolve(new Variant("u", 0));
97+
await ready;
98+
99+
expect(schemes).toEqual(["dark"]);
100+
});
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { Message, MessageType, Variant, sessionBus, type MessageBus } from "dbus-next";
2+
3+
const PORTAL = "org.freedesktop.portal.Desktop";
4+
const PATH = "/org/freedesktop/portal/desktop";
5+
const SETTINGS = "org.freedesktop.portal.Settings";
6+
const DBUS = "org.freedesktop.DBus";
7+
const NAMESPACE = "org.freedesktop.appearance";
8+
const KEY = "color-scheme";
9+
10+
export type LinuxColorScheme = "dark" | "light" | null;
11+
12+
// The portal reports 1 for prefer-dark, 2 for prefer-light and 0 for no preference. GNOME's
13+
// light mode is 0, and the spec asks apps to use their default then, so only 1 is dark.
14+
// The deprecated Read method nests the value in a second variant.
15+
function decodeColorScheme(value: unknown): LinuxColorScheme {
16+
let scheme = value;
17+
while (scheme instanceof Variant) scheme = scheme.value;
18+
return scheme === 1 ? "dark" : scheme === 0 || scheme === 2 ? "light" : null;
19+
}
20+
21+
const settingsCall = (member: "ReadOne" | "Read") =>
22+
new Message({
23+
destination: PORTAL,
24+
path: PATH,
25+
interface: SETTINGS,
26+
member,
27+
signature: "ss",
28+
body: [NAMESPACE, KEY],
29+
});
30+
31+
/**
32+
* Follows the desktop color scheme through the XDG settings portal. Without a session bus or
33+
* portal it reports nothing, so Chromium's own resolution stays in charge.
34+
*/
35+
export function watchLinuxColorScheme(
36+
onChange: (scheme: LinuxColorScheme) => void,
37+
bus: MessageBus = sessionBus(),
38+
) {
39+
let closed = false;
40+
let changed = false;
41+
const report = (value: unknown) => {
42+
if (!closed) onChange(decodeColorScheme(value));
43+
};
44+
const onMessage = (message: Message) => {
45+
if (
46+
message.type !== MessageType.SIGNAL ||
47+
message.path !== PATH ||
48+
message.interface !== SETTINGS ||
49+
message.member !== "SettingChanged"
50+
)
51+
return;
52+
const [namespace, key, value] = message.body;
53+
if (namespace !== NAMESPACE || key !== KEY) return;
54+
changed = true;
55+
report(value);
56+
};
57+
const ignore = () => undefined;
58+
59+
bus.on("error", ignore);
60+
bus.on("message", onMessage);
61+
const ready = (async () => {
62+
await bus.call(
63+
new Message({
64+
destination: DBUS,
65+
path: "/org/freedesktop/DBus",
66+
interface: DBUS,
67+
member: "AddMatch",
68+
signature: "s",
69+
body: [
70+
`type='signal',interface='${SETTINGS}',member='SettingChanged',path='${PATH}',arg0='${NAMESPACE}',arg1='${KEY}'`,
71+
],
72+
}),
73+
);
74+
// ReadOne needs Settings portal version 2; older portals only offer Read.
75+
const reply = await bus
76+
.call(settingsCall("ReadOne"))
77+
.catch(() => bus.call(settingsCall("Read")));
78+
// The portal answers reads through its backend asynchronously, so a change signal can
79+
// overtake this reply; the reply then carries the older value.
80+
if (reply && !changed) report(reply.body[0]);
81+
})().catch(ignore);
82+
83+
return {
84+
ready,
85+
stop: () => {
86+
closed = true;
87+
bus.removeListener("message", onMessage);
88+
bus.disconnect();
89+
},
90+
};
91+
}

0 commit comments

Comments
 (0)