Files
chandra/compositor/portal/settings.mbt
Claude f0c39757d7
CI / test (push) Successful in 12m52s
GTK 3 windows get Chandra's frame: org_kde_kwin_server_decoration
GTK 3 has no xdg-decoration support, so every GTK 3 window without its own
header bar (Webby, Nemo-style apps) drew GTK's fallback title bar: a centered
title, only a close button, and a dark border inside Chandra's CSD box.
GTK 3 asks for server-side decoration through KWin's
org_kde_kwin_server_decoration instead. Chandra now advertises it with
default mode Server; request_mode(Client) (GTK 3 apps with a header bar)
keeps their own frame.

The Settings portal also answers org.gnome.desktop.wm.preferences
button-layout "appmenu:minimize,maximize,close", so apps that still draw
their own title bar show the same three buttons as Chandra's frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hghaEWWsCBgEq6iZHj
2026-11-26 02:37:48 +00:00

278 lines
9.5 KiB
MoonBit

///| 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))),
// Title bar buttons of apps that draw their own (GTK header bars, GTK 3's fallback title
// bar): the same three as Chandra's frame. GNOME's default is "appmenu:close".
(wm_preferences, "button-layout", Str(button_layout)),
]
}
///|
pub let wm_preferences : String = "org.gnome.desktop.wm.preferences"
///|
pub let button_layout : String = "appmenu:minimize,maximize,close"
///|
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
}