Chrome follows the Dark mode switch: Chandra serves the portal's color-scheme
CI / test (push) Failing after 17s

Chrome (and Firefox, Electron, GTK 4, Qt 6) read dark/light from xdg-desktop-portal's Settings
interface. With XDG_CURRENT_DESKTOP=chandra and no chandra-portals.conf, xdg-desktop-portal found
no Settings backend (gtk/gnome are UseIn=gnome, kde is UseIn=KDE) and exported no Settings
interface at all, so the gsettings color-scheme a790901 sets never reached Chrome.

- compositor/portal: the compositor is an org.freedesktop.impl.portal.Settings backend
  (org.freedesktop.impl.portal.desktop.chandra on the session bus): Read/ReadAll of
  org.freedesktop.appearance color-scheme (1 dark, 2 light), SettingChanged when the switch flips,
  version property, introspection. Login session only; the main loop wakes on its socket.
- compositor/network/dbus.mbt: serve calls (on_call, reply, reply_error), emit and receive
  signals, sender field, session bus address.
- session/chandra.portal + chandra-portals.conf, installed to /usr/share/xdg-desktop-portal by
  install.py: Settings from chandra first, then gtk/kde/gnome; other portals from gtk/kde/gnome.
- chandra-session restarts a running xdg-desktop-portal so it reads the config for this desktop.
- scripts/test-portal-dbus.sh: end to end behind the real xdg-desktop-portal on a private bus
  (ReadOne gives 1, flipping gives SettingChanged 2). docs/dark-mode.md: how to check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhkztRQM7vcSuHX4bB
This commit is contained in:
Claude committed 2026-11-25 20:30:30 +00:00
1 parent c7a6c8376e
commit 005e11e7bf
14 files changed
+739 -5

No files matched your search

+4
View File
@@ -265,6 +265,10 @@ pub fn run(args : Array[String]) -> Int {
// Idle: sleep until a client, the seat or the clock has something.
let fds = comp.server.wait_fds()
fds.append(k.wait_fds())
let pfd = comp.portal_fd() // apps asking the dark/light preference
if pfd >= 0 {
fds.push(pfd)
}
ignore(@sys.wait_readable(fds, idle.timeout()))
} else {
// Sleep out what is left of the frame budget (8 ms), not a fixed 8 ms on top of the work.
+9
View File
@@ -44,6 +44,9 @@ pub(all) struct ChandraCompositor {
/// Also set the system-wide dark/light preference for apps (system_theme.mbt). The login
/// session turns it on; nested windows and tests leave it off.
mut sync_system_theme : Bool
/// The xdg-desktop-portal Settings backend apps read the dark/light preference from
/// (compositor/portal), started with the first `sync_system_theme_pref`.
mut settings_portal : @portal.SettingsPortal?
/// Running as the login session (--drm): power actions act on the machine (power.mbt).
mut login_session : Bool
/// Power (power.mbt): when input last came (monotonic ms), whether the screen is off for being
@@ -162,6 +165,7 @@ pub fn ChandraCompositor::new(
theme,
dark_theme: theme,
sync_system_theme: false,
settings_portal: None,
login_session: false,
last_input_ms: @sys.monotonic_ms(),
screen_off: false,
@@ -267,6 +271,10 @@ pub fn ChandraCompositor::close(self : ChandraCompositor) -> Unit {
release_snapshot(win.surface)
}
self.shell.shutdown()
match self.settings_portal {
Some(p) => p.close()
None => ()
}
self.server.close()
}
@@ -367,6 +375,7 @@ fn ChandraCompositor::flush_configures(self : ChandraCompositor) -> Unit {
///|
pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
self.flush_configures()
self.portal_tick()
let events = self.server.poll_events()
for ev in events {
match ev {
+1
View File
@@ -12,6 +12,7 @@ import {
"chandra/desktop/compositor/wayland" @wayland,
"chandra/desktop/compositor/gfx" @gfx,
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/portal" @portal,
}
supported_targets = "+native+wasm"
+26 -1
View File
@@ -73,11 +73,36 @@ pub fn system_theme_command(dark : Bool) -> String {
s
}
///| Tell the system the desktop is dark or light (see above). A no-op unless
///| Tell the system the desktop is dark or light (see above), and apps through our own portal
/// backend (compositor/portal), which xdg-desktop-portal relays to them live. A no-op unless
/// `sync_system_theme` is on.
fn ChandraCompositor::sync_system_theme_pref(self : ChandraCompositor, dark : Bool) -> Unit {
if self.sync_system_theme {
ignore(@sys.spawn(system_theme_command(dark), self.shell.display))
match self.settings_portal {
Some(p) => p.set_dark(dark)
None => {
let p = @portal.SettingsPortal::new(dark)
self.settings_portal = Some(p)
p.tick(@sys.monotonic_ms())
}
}
}
}
///| Serve calls to the portal backend (each main-loop pass).
fn ChandraCompositor::portal_tick(self : ChandraCompositor) -> Unit {
match self.settings_portal {
Some(p) => p.tick(@sys.monotonic_ms())
None => ()
}
}
///| The portal backend's bus socket, for the main loop to wake on (-1 when there is none).
pub fn ChandraCompositor::portal_fd(self : ChandraCompositor) -> Int {
match self.settings_portal {
Some(p) => p.fd()
None => -1
}
}
+130 -4
View File
@@ -223,6 +223,8 @@ pub(all) struct DMessage {
meth : String
error_name : String
dest : String
/// The unique name of who sent it (set by the bus on what we receive).
sender : String
sig : String
body : Array[DValue]
} derive(Debug)
@@ -248,6 +250,7 @@ pub fn DMessage::call(
meth,
error_name: "",
dest,
sender: "",
sig: sb.to_string(),
body: args,
}
@@ -538,6 +541,7 @@ pub fn decode(data : Array[Byte]) -> DMessage? {
let mut error_name = ""
let mut reply_serial = 0
let mut dest = ""
let mut sender = ""
let mut sig = ""
if fields is Arr(_, items) {
for f in items {
@@ -550,6 +554,7 @@ pub fn decode(data : Array[Byte]) -> DMessage? {
(4, Str(s)) => error_name = s
(5, U32(n)) => reply_serial = n.reinterpret_as_int()
(6, Str(s)) => dest = s
(7, Str(s)) => sender = s
(8, Sig(s)) => sig = s
_ => ()
}
@@ -562,7 +567,19 @@ pub fn decode(data : Array[Byte]) -> DMessage? {
if r.bad {
return None
}
Some({ mtype, serial, reply_serial, path, iface, meth, error_name, dest, sig, body })
Some({
mtype,
serial,
reply_serial,
path,
iface,
meth,
error_name,
dest,
sender,
sig,
body,
})
}
// ---- the connection ----
@@ -574,6 +591,41 @@ pub struct DBus {
mut serial : Int
pending : Map[Int, (DMessage) -> Unit]
mut alive : Bool
/// Runs (from `pump`) for each method call made to us; it should answer with `reply` or
/// `reply_error`. Unset, calls to us are dropped.
mut on_call : ((DMessage) -> Unit)?
/// Runs (from `pump`) for each signal that reaches us (see AddMatch). Unset, they are dropped.
mut on_signal : ((DMessage) -> Unit)?
}
///| The socket path of a unix:path= bus address ("" for anything else, such as unix:abstract=).
/// An address may list several, separated by ';': the first unix:path= one is used.
pub fn bus_address_path(addr : String) -> String {
let pre = "unix:path="
for a in addr.split(";") {
let a = a.to_string()
if a.has_prefix(pre) {
let rest = a[pre.length():].to_string()
return match rest.find(",") {
Some(i) => rest[:i].to_string()
None => rest
}
}
}
""
}
///| The session bus socket: $DBUS_SESSION_BUS_ADDRESS when it is a unix:path= address, else
/// $XDG_RUNTIME_DIR/bus (systemd's per-user bus), else "".
pub fn session_bus_path() -> String {
let p = bus_address_path(@sys.getenv("DBUS_SESSION_BUS_ADDRESS"))
if p != "" {
return p
}
match @sys.getenv("XDG_RUNTIME_DIR") {
"" => ""
rt => rt + "/bus"
}
}
///| The system bus socket: $DBUS_SYSTEM_BUS_ADDRESS when it is a unix:path= address, else the
@@ -693,7 +745,7 @@ pub fn DBus::open(path : String) -> DBus? {
if !ok || !send_text(fd, "BEGIN\r\n") {
return fail()
}
let bus = { fd, inbuf, serial: 0, pending: {}, alive: true }
let bus = { fd, inbuf, serial: 0, pending: {}, alive: true, on_call: None, on_signal: None }
let hello = bus.call_sync(
DMessage::call(
"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "Hello", [],
@@ -737,8 +789,8 @@ pub fn DBus::call(self : DBus, m : DMessage, on_reply? : (DMessage) -> Unit) ->
s
}
///| Read whatever has arrived (waiting up to `timeout_ms`) and run reply handlers. Signals and
/// calls to us are dropped.
///| Read whatever has arrived (waiting up to `timeout_ms`) and run reply handlers, `on_call` for
/// calls to us and `on_signal` for signals.
pub fn DBus::pump(self : DBus, timeout_ms? : Int = 0) -> Unit {
if !self.alive {
return
@@ -785,6 +837,16 @@ fn DBus::dispatch(self : DBus) -> Unit {
}
None => ()
}
Some(m) if m.mtype == method_call =>
match self.on_call {
Some(f) => f(m)
None => ()
}
Some(m) if m.mtype == signal_msg =>
match self.on_signal {
Some(f) => f(m)
None => ()
}
_ => ()
}
}
@@ -816,3 +878,67 @@ pub fn DMessage::error_text(self : DMessage) -> String {
_ => self.error_name
}
}
///| The socket, for waiting until something arrives (-1 once closed).
pub fn DBus::fd(self : DBus) -> Int {
if self.alive {
self.fd
} else {
-1
}
}
///| Send `m` without waiting for anything back (replies, signals).
fn DBus::send(self : DBus, m : DMessage) -> Bool {
if !self.alive {
return false
}
self.serial = self.serial + 1
let b = m.encode(self.serial)
if @sys.sendmsg_fd(self.fd, b, -1) != b.length() {
self.close()
return false
}
true
}
///| Answer the method call `call` with `args`.
pub fn DBus::reply(self : DBus, call : DMessage, args : Array[DValue]) -> Unit {
let m = DMessage::call(call.sender, "", "", "", args)
ignore(self.send({ ..m, mtype: method_return, reply_serial: call.serial }))
}
///| Answer the method call `call` with the error `name` (say
/// "org.freedesktop.DBus.Error.UnknownMethod") and message `text`.
pub fn DBus::reply_error(
self : DBus,
call : DMessage,
name : String,
text : String,
) -> Unit {
let m = DMessage::call(call.sender, "", "", "", [Str(text)])
ignore(
self.send({ ..m, mtype: error_reply, reply_serial: call.serial, error_name: name }),
)
}
///| Broadcast the signal `iface`.`member` from object `path`.
pub fn DBus::emit(
self : DBus,
path : String,
iface : String,
member : String,
args : Array[DValue],
) -> Unit {
ignore(self.send({ ..DMessage::call("", path, iface, member, args), mtype: signal_msg }))
}
///| Answer method calls to us with `f` (see `on_call`).
pub fn DBus::set_on_call(self : DBus, f : (DMessage) -> Unit) -> Unit {
self.on_call = Some(f)
}
///| Run `f` for each signal that reaches us (subscribe with the bus's AddMatch).
pub fn DBus::set_on_signal(self : DBus, f : (DMessage) -> Unit) -> Unit {
self.on_signal = Some(f)
}
+15
View File
@@ -0,0 +1,15 @@
import {
"moonbitlang/core/builtin",
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/sys" @sys,
}
supported_targets = "+native+wasm"
warnings = "-44"
import {
"chandra/desktop/compositor/portal" @portal,
"chandra/desktop/compositor/network" @network,
"chandra/desktop/compositor/sys" @sys,
} for "test"
+266
View File
@@ -0,0 +1,266 @@
///| Chandra's own xdg-desktop-portal Settings backend, so apps follow the Dark mode switch live.
///
/// Chrome/Chromium, Electron, Firefox, GTK 4 / libadwaita and Qt 6.5+ ask xdg-desktop-portal for
/// `org.freedesktop.appearance color-scheme` (0 no preference, 1 dark, 2 light) and listen for its
/// SettingChanged signal. xdg-desktop-portal gets the answer from a backend: it picks backends by
/// `$XDG_CURRENT_DESKTOP-portals.conf` (here chandra-portals.conf), else `UseIn=` in the backends'
/// .portal files. With XDG_CURRENT_DESKTOP=chandra neither matched (GTK's and GNOME's backends say
/// UseIn=gnome, KDE's UseIn=KDE), so xdg-desktop-portal (1.18) exported no Settings interface at
/// all and apps never saw the preference gsettings held.
///
/// So the compositor is the backend itself: it owns `org.freedesktop.impl.portal.desktop.chandra`
/// on the session bus and serves `org.freedesktop.impl.portal.Settings` at
/// /org/freedesktop/portal/desktop. session/chandra.portal and session/chandra-portals.conf
/// (installed by session/install.py) point xdg-desktop-portal at it. Only the login session does
/// this, like the gsettings sync in compositor/host/system_theme.mbt.
///|
pub let bus_name : String = "org.freedesktop.impl.portal.desktop.chandra"
///|
pub let object_path : String = "/org/freedesktop/portal/desktop"
///|
pub let settings_iface : String = "org.freedesktop.impl.portal.Settings"
///|
pub let appearance : String = "org.freedesktop.appearance"
///| How long to wait before trying the bus again after it went away or refused the name.
let retry_ms : UInt64 = 30000UL
///| The portal backend. `tick` serves calls; `set_dark` changes the answer and tells apps.
pub struct SettingsPortal {
mut bus : @network.DBus?
mut dark : Bool
mut next_try : UInt64
/// The session bus socket to use; "" finds it from the environment.
bus_path : String
}
///| A backend that is not connected yet: the first `tick` connects.
pub fn SettingsPortal::new(dark : Bool, bus_path? : String = "") -> SettingsPortal {
{ bus: None, dark, next_try: 0UL, bus_path }
}
///| The color-scheme value: 1 prefer dark, 2 prefer light.
pub fn color_scheme(dark : Bool) -> UInt {
if dark {
1
} else {
2
}
}
///| Whether `ns` is asked for by `patterns` (ReadAll's argument): empty asks for everything, and
/// a pattern ending in ".*" (or "*") matches by prefix.
pub fn namespace_matches(patterns : Array[String], ns : String) -> Bool {
if patterns.length() == 0 {
return true
}
for p in patterns {
if p == "" || p == "*" || p == ns {
return true
}
if p.has_suffix("*") && ns.has_prefix(p[:p.length() - 1].to_string()) {
return true
}
}
false
}
///| The settings we know, as (namespace, key, value).
fn SettingsPortal::settings(self : SettingsPortal) -> Array[(String, String, @network.DValue)] {
[(appearance, "color-scheme", U32(color_scheme(self.dark)))]
}
///|
let introspection : String =
#|<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
#| "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
#|<node>
#| <interface name="org.freedesktop.impl.portal.Settings">
#| <method name="ReadAll"><arg type="as" name="namespaces" direction="in"/><arg type="a{sa{sv}}" name="value" direction="out"/></method>
#| <method name="Read"><arg type="s" name="namespace" direction="in"/><arg type="s" name="key" direction="in"/><arg type="v" name="value" direction="out"/></method>
#| <signal name="SettingChanged"><arg type="s" name="namespace"/><arg type="s" name="key"/><arg type="v" name="value"/></signal>
#| <property name="version" type="u" access="read"/>
#| </interface>
#| <interface name="org.freedesktop.DBus.Properties">
#| <method name="Get"><arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/></method>
#| <method name="GetAll"><arg type="s" direction="in"/><arg type="a{sv}" direction="out"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Introspectable">
#| <method name="Introspect"><arg type="s" direction="out"/></method>
#| </interface>
#| <interface name="org.freedesktop.DBus.Peer">
#| <method name="Ping"/>
#| </interface>
#|</node>
///|
let err_unknown_method : String = "org.freedesktop.DBus.Error.UnknownMethod"
///|
let err_not_found : String = "org.freedesktop.portal.Error.NotFound"
///| What to answer the method call `m`: Ok(reply values) or Err((error name, message)).
pub fn SettingsPortal::answer(
self : SettingsPortal,
m : @network.DMessage,
) -> Result[Array[@network.DValue], (String, String)] {
match (m.iface, m.meth, m.body) {
("org.freedesktop.DBus.Peer", "Ping", _) => Ok([])
("org.freedesktop.DBus.Peer", "GetMachineId", _) =>
Err((err_unknown_method, "no machine id here"))
("org.freedesktop.DBus.Introspectable", "Introspect", _) =>
Ok([Str(if m.path == object_path { introspection } else { "<node/>" })])
_ if m.path != object_path =>
Err(("org.freedesktop.DBus.Error.UnknownObject", "no object " + m.path))
("org.freedesktop.DBus.Properties", "GetAll", [Str(i)]) =>
Ok([
@network.dict(
"v",
if i == settings_iface || i == "" {
[("version", Variant(U32(2)))]
} else {
[]
},
),
])
("org.freedesktop.DBus.Properties", "Get", [Str(i), Str("version")]) if i ==
settings_iface || i == "" => Ok([Variant(U32(2))])
("org.freedesktop.DBus.Properties", _, _) =>
Err(("org.freedesktop.DBus.Error.UnknownProperty", "no such property"))
(i, "ReadAll", [Arr(_, pats)]) if i == settings_iface || i == "" => {
let patterns = pats.filter_map(p => if p is Str(s) { Some(s) } else { None })
let namespaces : Array[String] = []
let values : Map[String, Array[(String, @network.DValue)]] = {}
for s in self.settings() {
if namespace_matches(patterns, s.0) {
match values.get(s.0) {
Some(kv) => kv.push((s.1, Variant(s.2)))
None => {
namespaces.push(s.0)
values.set(s.0, [(s.1, Variant(s.2))])
}
}
}
}
let entries = namespaces.map(ns => @network.DValue::Entry(
Str(ns),
@network.dict("v", values.get(ns).unwrap_or([])),
))
Ok([Arr("{sa{sv}}", entries)])
}
(i, "Read", [Str(ns), Str(key)]) if i == settings_iface || i == "" => {
for s in self.settings() {
if s.0 == ns && s.1 == key {
return Ok([Variant(s.2)])
}
}
Err((err_not_found, "Requested setting not found"))
}
_ => Err((err_unknown_method, "unknown method " + m.iface + "." + m.meth))
}
}
///| Connect to the session bus and take the backend's name. False when there is no bus or the
/// name is someone else's (another Chandra session of this user).
fn SettingsPortal::connect(self : SettingsPortal) -> Bool {
let path = if self.bus_path != "" {
self.bus_path
} else {
@network.session_bus_path()
}
if path == "" {
return false
}
let bus = match @network.DBus::open(path) {
Some(b) => b
None => return false
}
// Flags: 0x4 DO_NOT_QUEUE. Reply 1 = we are the primary owner, 4 = we already were.
let r = bus.call_sync(
@network.DMessage::call(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"RequestName",
[Str(bus_name), U32(4)],
),
1000,
)
match r {
Some({ body: [U32(1U) | U32(4U)], .. }) => ()
_ => {
@sys.log("settings portal: could not own " + bus_name + " on the session bus")
bus.close()
return false
}
}
bus.set_on_call(fn(m) {
match self.answer(m) {
Ok(args) => bus.reply(m, args)
Err((name, text)) => bus.reply_error(m, name, text)
}
})
self.bus = Some(bus)
true
}
///| Serve whatever calls have arrived; (re)connects when not connected, at most every 30 s.
pub fn SettingsPortal::tick(self : SettingsPortal, now : UInt64) -> Unit {
match self.bus {
Some(b) => {
b.pump()
if !b.alive {
self.bus = None
self.next_try = now + retry_ms
}
}
None =>
if now >= self.next_try {
self.next_try = now + retry_ms
ignore(self.connect())
}
}
}
///| Prefer dark (`dark`) or light, telling apps listening through xdg-desktop-portal.
pub fn SettingsPortal::set_dark(self : SettingsPortal, dark : Bool) -> Unit {
if dark == self.dark {
return
}
self.dark = dark
match self.bus {
Some(b) =>
b.emit(object_path, settings_iface, "SettingChanged", [
Str(appearance),
Str("color-scheme"),
Variant(U32(color_scheme(dark))),
])
None => ()
}
}
///| The bus socket to wait on for calls (-1 when not connected).
pub fn SettingsPortal::fd(self : SettingsPortal) -> Int {
match self.bus {
Some(b) => b.fd()
None => -1
}
}
///| Whether the backend is on the bus with its name.
pub fn SettingsPortal::connected(self : SettingsPortal) -> Bool {
self.bus is Some(_)
}
///| Leave the bus (the name goes with the connection).
pub fn SettingsPortal::close(self : SettingsPortal) -> Unit {
match self.bus {
Some(b) => b.close()
None => ()
}
self.bus = None
}
+179
View File
@@ -0,0 +1,179 @@
///|
fn call(iface : String, meth : String, args : Array[@network.DValue]) -> @network.DMessage {
@network.DMessage::call(
@portal.bus_name,
@portal.object_path,
iface,
meth,
args,
)
}
///|
test "Read answers color-scheme: 1 when dark, 2 when light" {
let p = @portal.SettingsPortal::new(true)
let read = call(@portal.settings_iface, "Read", [
Str("org.freedesktop.appearance"),
Str("color-scheme"),
])
assert_eq(p.answer(read), Ok([Variant(U32(1))]))
p.set_dark(false)
assert_eq(p.answer(read), Ok([Variant(U32(2))]))
}
///|
test "Read of an unknown setting is NotFound (so xdg-desktop-portal asks the next backend)" {
let p = @portal.SettingsPortal::new(true)
let r = p.answer(
call(@portal.settings_iface, "Read", [Str("org.gnome.desktop.interface"), Str("gtk-theme")]),
)
match r {
Err((name, _)) => assert_eq(name, "org.freedesktop.portal.Error.NotFound")
Ok(_) => fail("expected an error")
}
}
///|
test "ReadAll filters namespaces, with globs" {
let p = @portal.SettingsPortal::new(true)
let want : Array[@network.DValue] = [
Arr("{sa{sv}}", [
Entry(
Str("org.freedesktop.appearance"),
@network.dict("v", [("color-scheme", Variant(U32(1)))]),
),
]),
]
let all = fn(pats : Array[String]) {
p.answer(
call(@portal.settings_iface, "ReadAll", [Arr("s", pats.map(s => @network.DValue::Str(s)))]),
)
}
assert_eq(all([]), Ok(want))
assert_eq(all(["org.freedesktop.*"]), Ok(want))
assert_eq(all(["org.freedesktop.appearance"]), Ok(want))
assert_eq(all(["org.gnome.*"]), Ok([Arr("{sa{sv}}", [])]))
}
///|
test "the version property, introspection and unknown methods" {
let p = @portal.SettingsPortal::new(false)
assert_eq(
p.answer(call("org.freedesktop.DBus.Properties", "Get", [Str(@portal.settings_iface), Str("version")])),
Ok([Variant(U32(2))]),
)
assert_eq(
p.answer(call("org.freedesktop.DBus.Properties", "GetAll", [Str(@portal.settings_iface)])),
Ok([@network.dict("v", [("version", Variant(U32(2)))])]),
)
match p.answer(call("org.freedesktop.DBus.Introspectable", "Introspect", [])) {
Ok([Str(xml)]) => assert_true(xml.contains("SettingChanged"))
_ => fail("no introspection")
}
assert_true(p.answer(call(@portal.settings_iface, "Frobnicate", [])) is Err(_))
}
///|
test "namespace patterns" {
assert_true(@portal.namespace_matches([], "org.freedesktop.appearance"))
assert_true(@portal.namespace_matches(["org.freedesktop.*"], "org.freedesktop.appearance"))
assert_false(@portal.namespace_matches(["org.kde.*"], "org.freedesktop.appearance"))
}
///|
test "no session bus: the backend stays off without errors" {
let p = @portal.SettingsPortal::new(true, bus_path="/nonexistent/bus")
p.tick(0UL)
assert_false(p.connected())
assert_eq(p.fd(), -1)
p.set_dark(false) // nothing to tell, no crash
}
///| Run `p`'s backend and `client` until `done` or `ms` pass.
fn spin(
p : @portal.SettingsPortal,
client : @network.DBus,
ms : Int,
done : () -> Bool,
) -> Bool {
let deadline = @sys.monotonic_ms() + ms.to_uint64()
while @sys.monotonic_ms() < deadline {
p.tick(@sys.monotonic_ms())
client.pump(timeout_ms=10)
if done() {
return true
}
}
false
}
///| Against a real session bus and the real xdg-desktop-portal with session/chandra.portal and
/// session/chandra-portals.conf, as apps see it: org.freedesktop.portal.Settings ReadOne gives our
/// color-scheme, and flipping the switch reaches apps as SettingChanged. Skipped unless
/// CHANDRA_PORTAL_E2E=1 (scripts/test-portal-dbus.sh sets it up).
test "apps read the color-scheme through xdg-desktop-portal, and see it change" {
if @sys.getenv("CHANDRA_PORTAL_E2E") != "1" {
return
}
let p = @portal.SettingsPortal::new(true)
p.tick(@sys.monotonic_ms())
assert_true(p.connected())
let client = @network.DBus::open(@network.session_bus_path()).unwrap()
// Listen like Chrome does.
let changed : Array[@network.DMessage] = []
client.set_on_signal(fn(m) {
if m.meth == "SettingChanged" {
changed.push(m)
}
})
let add_match = @network.DMessage::call(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"AddMatch",
[
Str(
"type='signal',interface='org.freedesktop.portal.Settings',member='SettingChanged'",
),
],
)
ignore(client.call(add_match))
let read_one = fn() -> @network.DMessage? {
let got : Ref[@network.DMessage?] = { val: None }
ignore(
client.call(
@network.DMessage::call(
"org.freedesktop.portal.Desktop",
"/org/freedesktop/portal/desktop",
"org.freedesktop.portal.Settings",
"ReadOne",
[Str("org.freedesktop.appearance"), Str("color-scheme")],
),
on_reply=r => got.val = Some(r),
),
)
// The first call starts xdg-desktop-portal (D-Bus activation), which then asks us.
ignore(spin(p, client, 15000, () => got.val is Some(_)))
got.val
}
match read_one() {
Some(m) => {
assert_eq(m.error_name, "")
assert_eq(m.body, [Variant(U32(1))])
}
None => fail("no answer from xdg-desktop-portal")
}
p.set_dark(false)
assert_true(spin(p, client, 5000, () => changed.length() > 0))
assert_eq(changed[0].body, [
Str("org.freedesktop.appearance"),
Str("color-scheme"),
Variant(U32(2)),
])
match read_one() {
Some(m) => assert_eq(m.body, [Variant(U32(2))])
None => fail("no second answer")
}
p.close()
client.close()
}
+42
View File
@@ -0,0 +1,42 @@
# Dark mode for apps
The Settings module's **Dark mode** switch restyles Chandra itself and, in the login session
(`chandra-session`, `--drm`), tells apps:
- **xdg-desktop-portal Settings** (Chrome/Chromium, Electron, Firefox, GTK 4 / libadwaita,
Qt 6.5+): the compositor is a portal backend itself (`compositor/portal`). It owns
`org.freedesktop.impl.portal.desktop.chandra` on the session bus and answers
`org.freedesktop.appearance color-scheme` (1 dark, 2 light), emitting `SettingChanged` when the
switch flips, so open apps follow live.
`session/chandra.portal` and `session/chandra-portals.conf` (installed to
`/usr/share/xdg-desktop-portal/` by `session/install.py`) point xdg-desktop-portal at it.
- gsettings `color-scheme` / `gtk-theme`, GTK 3/4 `settings.ini`, KDE color scheme and qt5ct/qt6ct
(`compositor/host/system_theme.mbt`), for apps that read those instead.
## Why Chrome ignored the switch before
xdg-desktop-portal chooses backends from `$XDG_CURRENT_DESKTOP-portals.conf`, then the backends'
`UseIn=` keys. The session sets `XDG_CURRENT_DESKTOP=chandra` and there was no
`chandra-portals.conf`; GTK's and GNOME's backends say `UseIn=gnome`, KDE's `UseIn=KDE`. So
xdg-desktop-portal (1.18, as in Ubuntu 24.04) exported no Settings interface at all, and Chrome,
which asks the portal, never saw the preference that gsettings held.
## Checking it on your machine
After reinstalling (`just install-session`) and logging in to Chandra again:
```sh
# 1 = dark, 2 = light; flip the switch and run it again
gdbus call --session -d org.freedesktop.portal.Desktop -o /org/freedesktop/portal/desktop \
-m org.freedesktop.portal.Settings.ReadOne org.freedesktop.appearance color-scheme
# the backend itself
busctl --user status org.freedesktop.impl.portal.desktop.chandra
```
- xdg-desktop-portal must be installed (`xdg-desktop-portal` package). It reads its config only
when it starts: `chandra-session` restarts it at login, or run
`systemctl --user restart xdg-desktop-portal`.
- In Chrome, Settings > Appearance > Mode must be **Device** (a fixed Light or Dark there wins).
Pages follow through `prefers-color-scheme`; Chrome's own UI follows too.
- `scripts/test-portal-dbus.sh` runs the backend behind the real xdg-desktop-portal on a private
bus (what CI-less checks can do without a desktop).
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
# Run the portal package's end-to-end test: Chandra's Settings portal backend behind the real
# xdg-desktop-portal on a private session bus, configured by session/chandra.portal and
# session/chandra-portals.conf exactly as session/install.py installs them (apt: dbus
# xdg-desktop-portal). It checks what Chrome, Firefox, GTK 4 and Qt 6 see: ReadOne of
# org.freedesktop.appearance color-scheme, and SettingChanged when the Dark mode switch flips.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"; cd "$ROOT"
XDP=""
for x in /usr/libexec/xdg-desktop-portal /usr/lib/xdg-desktop-portal; do
[ -x "$x" ] && XDP="$x" && break
done
[ -n "$XDP" ] || { echo "xdg-desktop-portal not found (apt install xdg-desktop-portal)" >&2; exit 1; }
tmp=$(mktemp -d)
mkdir -p "$tmp/portals" "$tmp/config" "$tmp/run"
cp session/chandra.portal "$tmp/portals/"
# The distro's backends too, as on a real system (chandra-portals.conf lists them after chandra).
cp /usr/share/xdg-desktop-portal/portals/*.portal "$tmp/portals/" 2>/dev/null || true
# With XDG_DESKTOP_PORTAL_DIR set, xdg-desktop-portal reads its config from there too.
cp session/chandra-portals.conf "$tmp/portals/"
export XDG_DESKTOP_PORTAL_DIR="$tmp/portals" XDG_CONFIG_HOME="$tmp/config" \
XDG_RUNTIME_DIR="$tmp/run" XDG_CURRENT_DESKTOP=chandra
addr_pid=$(dbus-daemon --session --fork --print-address=1 --print-pid=1)
export DBUS_SESSION_BUS_ADDRESS=$(echo "$addr_pid" | sed -n 1p)
DPID=$(echo "$addr_pid" | sed -n 2p)
trap 'kill ${XPID:-} "$DPID" 2>/dev/null || true; rm -rf "$tmp"' EXIT
dbus-update-activation-environment XDG_DESKTOP_PORTAL_DIR XDG_CONFIG_HOME XDG_RUNTIME_DIR \
XDG_CURRENT_DESKTOP
# Start xdg-desktop-portal before the backend is on the bus (the harder order: it must still find
# it once it appears); its log is printed if the test fails.
"$XDP" -v >"$tmp/xdp.log" 2>&1 &
XPID=$!
sleep 1
CHANDRA_PORTAL_E2E=1 moon test --target native --warn-list -a compositor/portal "$@" || { cat "$tmp/xdp.log"; exit 1; }
+10
View File
@@ -0,0 +1,10 @@
# xdg-desktop-portal backends for the Chandra session (XDG_CURRENT_DESKTOP=chandra), installed to
# /usr/share/xdg-desktop-portal/ by session/install.py. See portals.conf(5).
#
# Settings (dark/light color-scheme and the rest): Chandra's compositor first (it serves
# org.freedesktop.appearance color-scheme from the Dark mode switch, live), then whatever the
# installed GTK / KDE / GNOME backends add (fonts, accent colors...).
# Everything else (file chooser, open-with, notifications...): the first of these installed.
[preferred]
default=gtk;kde;gnome
org.freedesktop.impl.portal.Settings=chandra;gtk;kde;gnome
+9
View File
@@ -78,6 +78,15 @@ if command -v dbus-update-activation-environment >/dev/null 2>&1; then
XDG_SESSION_DESKTOP >>"$log" 2>&1 || true
fi
# xdg-desktop-portal picks its backends once, at start, from $XDG_CURRENT_DESKTOP (here
# chandra-portals.conf: the compositor answers apps' dark/light question). One still running from
# an earlier session (systemd keeps the user's services between logins) would keep another
# desktop's choice, so Chrome and Firefox would not follow the Dark mode switch: restart it if it
# is running. Apps start it on demand otherwise.
if command -v systemctl >/dev/null 2>&1; then
systemctl --user try-restart xdg-desktop-portal.service >>"$log" 2>&1 || true
fi
# Hand the PAM-started keyring daemon (already unlocked by the login password) its session
# components, so it owns org.freedesktop.secrets on our bus. Harmless if it isn't installed,
# already running under systemd's socket units, or not unlocked by PAM (it then prompts once).
+4
View File
@@ -0,0 +1,4 @@
[portal]
DBusName=org.freedesktop.impl.portal.desktop.chandra
Interfaces=org.freedesktop.impl.portal.Settings;
UseIn=chandra
+10
View File
@@ -24,6 +24,8 @@ Installs:
/usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime
/usr/local/share/chandra/modules/*.wasm the panel's wasm modules (build them first: just modules)
/usr/share/wayland-sessions/chandra.desktop display-manager entry
/usr/share/xdg-desktop-portal/portals/chandra.portal xdg-desktop-portal backend: the compositor
/usr/share/xdg-desktop-portal/chandra-portals.conf serves Settings (apps' dark/light preference)
"""
import os, shutil, sys
@@ -44,6 +46,8 @@ targets = [
"/usr/local/bin/chandra-session",
"/usr/local/bin/chandra-root",
"/usr/share/wayland-sessions/chandra.desktop",
"/usr/share/xdg-desktop-portal/portals/chandra.portal",
"/usr/share/xdg-desktop-portal/chandra-portals.conf",
]
if os.geteuid() != 0:
@@ -104,6 +108,12 @@ install(os.path.join(root, "session/chandra-session"), "/usr/local/bin/chandra-s
install(os.path.join(root, "session/chandra-root"), "/usr/local/bin/chandra-root")
# The display-manager entry stays a real file: some managers don't follow symlinks there.
put(os.path.join(root, "session/chandra.desktop"), "/usr/share/wayland-sessions/chandra.desktop", 0o644)
# xdg-desktop-portal reads backends only from /usr/share (or $XDG_DESKTOP_PORTAL_DIR), not
# /usr/local. With XDG_CURRENT_DESKTOP=chandra and no chandra-portals.conf it offered apps no
# Settings portal at all, so Chrome, Firefox, GTK 4 and Qt 6 never saw the Dark mode switch; the
# compositor serves it (compositor/portal) and this config picks it, then the installed backends.
put(os.path.join(root, "session/chandra.portal"), "/usr/share/xdg-desktop-portal/portals/chandra.portal", 0o644)
put(os.path.join(root, "session/chandra-portals.conf"), "/usr/share/xdg-desktop-portal/chandra-portals.conf", 0o644)
# Read at runtime relative to the working directory (the launcher cd's here): the Interface Explorer
# shows wit/, the theme comes from config/, and assets/fonts holds the Allo font.
for d in ("config", "wit", "assets"):