Open History to see the last commit
1import { Message, MessageType, Variant, sessionBus, type MessageBus } from "dbus-next";
2
3const PORTAL = "org.freedesktop.portal.Desktop";
4const PATH = "/org/freedesktop/portal/desktop";
5const SETTINGS = "org.freedesktop.portal.Settings";
6const DBUS = "org.freedesktop.DBus";
7const NAMESPACE = "org.freedesktop.appearance";
8const KEY = "color-scheme";
9
10export 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.
15function 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
21const 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 */
35export 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}