Bus, Ui, main: the system's appearance, dark or light and its accent

The desktop portal's org.freedesktop.appearance settings on the session
bus say whether the system prefers dark (color-scheme 1) and which
accent colour it uses, and a flatpak may read them. Bus:Appearance
subscribes to SettingChanged and reads the namespace in one ReadAll
call, which every portal version has, so a start waits for one answer at
most, 2 s; a portal that gave no colour scheme by then — still starting,
or not on the bus yet — is asked again when its name has an owner,
without waiting, and its answer comes as a change. The canvas gained a
dark palette and takes the accent for the avatars, badges, buttons and
outgoing bubbles, with the text on it dark or light by the accent's
brightness. The app applies the theme to the window at once and keeps it
for the next one; --theme dark|light or IMSD_MESSAGES_THEME (the same
two values: another is refused on the command line and ignored in the
environment) overrides the portal's colour scheme, for benches and
desktops without a portal.
This commit is contained in:
Jorijn van der Graaf 2026-10-18 03:08:03 +02:00
commit 9332094333
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
7 changed files with 222 additions and 7 deletions

View file

@ -28,7 +28,7 @@ and §7.9 (Messaging) and §8.1 (the frozen one).
|---|---|
| `project.cpp` | The build description for Crafter.Build: four products (below) and the tests. |
| `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, gestures, the message field's editing, the store, the sync logic. |
| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name. |
| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name, the desktop portal's appearance settings. |
| `interfaces/ImsdMessages.Ui*.cppm` | `imsd-messages-ui`: the window on Crafter.Graphics, driven from the GLib main loop. |
| `implementations/main.cpp` | The executable `imsd-messages`. |
| `tests/<Name>/main.cpp` | One test per directory, declared in `project.cpp`. |

View file

@ -55,6 +55,7 @@ struct Options {
bool openNew = false; // the bench opens the new-conversation screen
std::optional<std::string> benchSheet; // "conversation" or "message": the bench's long press
std::string country;
std::optional<std::string> theme; // "dark" or "light": instead of the portal's answer
std::string error;
};
@ -99,6 +100,7 @@ Options Parse(std::span<const char* const> args) {
else if (a == "--new") o.openNew = true;
else if (a == "--bench-sheet" && i + 1 < args.size()) o.benchSheet = args[++i];
else if (a == "--country" && i + 1 < args.size()) o.country = args[++i];
else if (a == "--theme" && i + 1 < args.size()) o.theme = args[++i];
else if (IsSmsUri(a)) o.uri = std::string(a);
else o.error = std::format("unknown argument: {}", a);
}
@ -114,6 +116,7 @@ Options Parse(std::span<const char* const> args) {
// and CountryCodeOf gives it back from a number that begins with it): a
// completed key is made of it as it is, and read by that rule.
if (!o.country.empty() && (o.country.front() == '0' || CountryCodeOf(std::format("+{}0000000", o.country)) != o.country)) o.error = "--country: not a country code (one to three digits, without its +)";
if (o.theme && *o.theme != "dark" && *o.theme != "light") o.error = "--theme: dark or light";
if (o.hideEvery && *o.hideEvery * 1000 < 1) o.error = "--hide-every: a millisecond at least";
if (o.benchSheet && *o.benchSheet != "conversation" && *o.benchSheet != "message") o.error = "--bench-sheet: conversation or message";
if (o.send && o.quit) o.error = "--send and --quit do not go together";
@ -281,7 +284,7 @@ int main(int argc, char** argv) {
return 0;
}
if (o.help) {
std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [--screenshot FILE.png] [--screenshot-after SECONDS] [--quit-after SECONDS] [--hide-after SECONDS] [--hide-every SECONDS] [--prefill TEXT] [--send-draft] [--new] [--bench-sheet conversation|message] [sms:NUMBER] [--version]");
std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [--theme dark|light] [--screenshot FILE.png] [--screenshot-after SECONDS] [--quit-after SECONDS] [--hide-after SECONDS] [--hide-every SECONDS] [--prefill TEXT] [--send-draft] [--new] [--bench-sheet conversation|message] [sms:NUMBER] [--version]");
return 0;
}
@ -395,6 +398,21 @@ int main(int argc, char** argv) {
if (o.screenshot) app->exitCode = 1; // an asked-for screenshot is a failure until the PNG is written: a run that ends first says so
app->closeQuits = session == nullptr;
app->appId = std::string(Bus::appId);
// The theme: --theme or IMSD_MESSAGES_THEME wins, else the portal's
// appearance settings, else light.
Bus::AppearanceWatch appearance(session);
std::optional<std::string> themeOverride = o.theme;
if (!themeOverride) {
// The flag's two values and no other: anything else leaves the theme to the system.
if (const char* env = std::getenv("IMSD_MESSAGES_THEME"); env && (std::string_view(env) == "dark" || std::string_view(env) == "light")) themeOverride = env;
}
const auto applyTheme = [&app, themeOverride](const Bus::Appearance& a) {
const bool dark = themeOverride ? *themeOverride == "dark" : a.dark;
app->SetTheme(dark, a.accent);
};
applyTheme(appearance.Current());
appearance.onChanged = applyTheme;
Log(std::format("theme: {} ({}){}", themeOverride ? (*themeOverride == "dark" ? "dark" : "light") : appearance.Current().dark ? "dark" : "light", themeOverride ? "override" : appearance.Current().known ? "the system" : "no colour scheme from a portal, the default", appearance.Current().accent ? " with the system's accent" : ""));
app->sync = &sync;
app->onQuit = [loop] { g_main_loop_quit(loop); };
app->onConversationOpened = [&notifier](const std::string& conversation) { notifier.Close(conversation); };

View file

@ -0,0 +1,156 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// lint-disable-file no-char-pointer
/*
ImsdMessages.Bus:Appearance — the system's appearance from the desktop
portal's org.freedesktop.appearance settings on the session bus: the colour
scheme (dark or light) and the accent colour, read at start and followed
through SettingChanged; a flatpak may read them. Without a portal the
appearance stays unknown and the UI keeps its light default; a portal that
gave no colour scheme at the start is asked again when its name has an
owner, and answers as a change.
*/
module;
#include <gio/gio.h>
export module ImsdMessages.Bus:Appearance;
import std;
namespace ImsdMessages::Bus {
constexpr const char* portalName = "org.freedesktop.portal.Desktop";
constexpr const char* portalPath = "/org/freedesktop/portal/desktop";
constexpr const char* settingsIface = "org.freedesktop.portal.Settings";
constexpr const char* appearanceNs = "org.freedesktop.appearance";
}
export namespace ImsdMessages::Bus {
struct Appearance {
bool known = false; // the portal gave a colour scheme
bool dark = false; // color-scheme 1 (prefer dark); 0 and 2 are light
std::optional<std::array<float, 3>> accent;
};
class AppearanceWatch {
public:
explicit AppearanceWatch(GDBusConnection* session) : conn(session) {
if (!conn) return;
// The subscription first, so a change between the read and it is
// not lost.
sub = g_dbus_connection_signal_subscribe(conn, portalName, settingsIface, "SettingChanged", portalPath, appearanceNs, G_DBUS_SIGNAL_FLAGS_NONE, OnChanged, this, nullptr);
ReadAll();
// A portal that gave no colour scheme in the start's two seconds
// — still starting (a start at login races it), or not on the
// bus yet — is asked again when its name has an owner, as the
// client watches imsd's.
watch = g_bus_watch_name_on_connection(conn, portalName, G_BUS_NAME_WATCHER_FLAGS_NONE, OnAppeared, nullptr, this, nullptr);
}
~AppearanceWatch() {
if (watch) g_bus_unwatch_name(watch);
if (conn && sub) g_dbus_connection_signal_unsubscribe(conn, sub);
}
AppearanceWatch(const AppearanceWatch&) = delete;
AppearanceWatch& operator=(const AppearanceWatch&) = delete;
std::function<void(const Appearance&)> onChanged;
const Appearance& Current() const noexcept { return current; }
private:
// One call for the whole namespace: ReadAll is in every portal version
// (ReadOne came with version 2, and Read, deprecated, wraps its value
// in one more variant), and one 2 s timeout is the most a start waits.
void ReadAll() {
GError* err = nullptr;
GVariant* reply = g_dbus_connection_call_sync(conn, portalName, portalPath, settingsIface, "ReadAll", Namespaces(), G_VARIANT_TYPE("(a{sa{sv}})"), G_DBUS_CALL_FLAGS_NONE, 2000, nullptr, &err);
if (!reply) {
g_clear_error(&err);
return;
}
Take(reply);
}
// The portal's name has an owner — at the start when it had one
// already, later when it comes: without a colour scheme so far, the
// settings are asked for without a wait, and the answer comes as a
// change.
static void OnAppeared(GDBusConnection*, const gchar*, const gchar*, gpointer data) {
AppearanceWatch& self = *static_cast<AppearanceWatch*>(data);
if (self.current.known) return;
g_dbus_connection_call(self.conn, portalName, portalPath, settingsIface, "ReadAll", Namespaces(), G_VARIANT_TYPE("(a{sa{sv}})"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, OnLateAnswer, &self);
}
static GVariant* Namespaces() {
GVariantBuilder namespaces;
g_variant_builder_init(&namespaces, G_VARIANT_TYPE("as"));
g_variant_builder_add(&namespaces, "s", appearanceNs);
return g_variant_new("(as)", &namespaces);
}
static void OnLateAnswer(GObject* source, GAsyncResult* result, gpointer data) {
GVariant* reply = g_dbus_connection_call_finish(G_DBUS_CONNECTION(source), result, nullptr);
if (!reply) return;
AppearanceWatch& self = *static_cast<AppearanceWatch*>(data);
self.Take(reply);
if (self.onChanged) self.onChanged(self.current);
}
// ReadAll's answer: the namespace's settings, each applied.
void Take(GVariant* reply) {
GVariant* all = g_variant_get_child_value(reply, 0);
if (GVariant* dict = g_variant_lookup_value(all, appearanceNs, G_VARIANT_TYPE("a{sv}"))) {
GVariantIter it;
g_variant_iter_init(&it, dict);
const gchar* key = nullptr;
GVariant* value = nullptr;
while (g_variant_iter_loop(&it, "{&sv}", &key, &value)) Apply(key, Unwrapped(value));
g_variant_unref(dict);
}
g_variant_unref(all);
g_variant_unref(reply);
}
// The value inside any variant layers (the portal's are single; the
// deprecated Read's were double).
static GVariant* Unwrapped(GVariant* value) {
while (g_variant_is_of_type(value, G_VARIANT_TYPE_VARIANT)) value = g_variant_get_child_value(value, 0);
return value;
}
void Apply(std::string_view key, GVariant* value) {
if (key == "color-scheme" && g_variant_is_of_type(value, G_VARIANT_TYPE_UINT32)) {
current.known = true;
current.dark = g_variant_get_uint32(value) == 1;
} else if (key == "accent-color" && g_variant_is_of_type(value, G_VARIANT_TYPE("(ddd)"))) {
double r = 0, g = 0, b = 0;
g_variant_get(value, "(ddd)", &r, &g, &b);
// Out of range means "no accent set" by the portal's definition.
const bool valid = r >= 0 && r <= 1 && g >= 0 && g <= 1 && b >= 0 && b <= 1;
current.accent = valid ? std::optional<std::array<float, 3>>({ static_cast<float>(r), static_cast<float>(g), static_cast<float>(b) }) : std::nullopt;
}
}
static void OnChanged(GDBusConnection*, const gchar*, const gchar*, const gchar*, const gchar*, GVariant* params, gpointer data) {
AppearanceWatch& self = *static_cast<AppearanceWatch*>(data);
const gchar* ns = nullptr;
const gchar* key = nullptr;
GVariant* value = nullptr;
g_variant_get(params, "(&s&sv)", &ns, &key, &value);
if (ns && key && std::string_view(ns) == appearanceNs) {
GVariant* inner = value;
while (g_variant_is_of_type(inner, G_VARIANT_TYPE_VARIANT)) {
GVariant* next = g_variant_get_variant(inner);
g_variant_unref(inner);
inner = next;
}
self.Apply(key, inner);
value = inner;
if (self.onChanged) self.onChanged(self.current);
}
if (value) g_variant_unref(value);
}
GDBusConnection* conn = nullptr;
guint sub = 0;
guint watch = 0;
Appearance current;
};
}

View file

@ -5,11 +5,13 @@
ImsdMessages.Bus — the GLib side of imsd-messages: the GDBus client of
imsd's /net/catcrafts/IMS1 on the system bus (the Messaging interface, and
the frozen interface's registration signal), the decoding of its
dictionaries, the desktop notifications, and the app's own session-bus name.
No window: the executable wires this to the UI.
dictionaries, the desktop notifications, the app's own session-bus name and
the desktop portal's appearance settings. No window: the executable wires
this to the UI.
*/
export module ImsdMessages.Bus;
export import :Variant;
export import :Client;
export import :Notifier;
export import :Instance;
export import :Appearance;

View file

@ -123,6 +123,15 @@ export namespace ImsdMessages::Ui {
bool Visible() const noexcept { return canvas.has_value(); }
// The system's appearance: dark or light, and its accent colour.
// Applied to the window at once and kept for the next one.
void SetTheme(bool dark, std::optional<std::array<float, 3>> accent) {
theme = dark ? Theme::Dark() : Theme::Light();
if (accent) theme.Accent(*accent);
if (canvas) canvas->theme = theme;
Dirty();
}
// Cancels a close's deferred Hide: a Show or an Open before it runs
// keeps the window. True when there was one.
bool KeepWindow() {
@ -157,6 +166,7 @@ export namespace ImsdMessages::Ui {
Log(std::format("no window: {}", e.what()));
return;
}
canvas->theme = theme;
if (!source) {
source.emplace(Crafter::Device::display);
source->onLost = [this] {
@ -936,6 +946,7 @@ export namespace ImsdMessages::Ui {
std::filesystem::path assetDir;
std::filesystem::path cacheDir;
AppStatus status;
Theme theme;
std::vector<Conversation> convs;
std::optional<Canvas> canvas;
std::vector<std::string> hitKeys; // the conversation each row region named, as drawn

View file

@ -34,6 +34,32 @@ export namespace ImsdMessages::Ui {
Color divider = { 0.88f, 0.88f, 0.89f, 1.0f };
Color danger = { 0.80f, 0.16f, 0.16f, 1.0f };
Color scrim = { 0.0f, 0.0f, 0.0f, 0.35f };
static Theme Light() { return Theme{}; }
static Theme Dark() {
Theme t;
t.bg = { 0.07f, 0.07f, 0.08f, 1.0f };
t.surface = { 0.12f, 0.12f, 0.13f, 1.0f };
t.text = { 0.93f, 0.93f, 0.94f, 1.0f };
t.muted = { 0.62f, 0.62f, 0.65f, 1.0f };
t.bubbleIn = { 0.18f, 0.18f, 0.20f, 1.0f };
t.banner = { 0.30f, 0.26f, 0.10f, 1.0f };
t.bannerText = { 0.98f, 0.88f, 0.55f, 1.0f };
t.divider = { 0.20f, 0.20f, 0.22f, 1.0f };
t.danger = { 0.90f, 0.30f, 0.30f, 1.0f };
t.scrim = { 0.0f, 0.0f, 0.0f, 0.55f };
return t;
}
// The system's accent colour, with text on it dark or light as its
// brightness asks.
void Accent(std::array<float, 3> rgb) {
accent = { rgb[0], rgb[1], rgb[2], 1.0f };
bubbleOut = accent;
const float luminance = 0.2126f * rgb[0] + 0.7152f * rgb[1] + 0.0722f * rgb[2];
onAccent = luminance > 0.6f ? Color{ 0.08f, 0.08f, 0.09f, 1.0f } : Color{ 1.0f, 1.0f, 1.0f, 1.0f };
}
};
// One compositing layer: its own item buffers, one fused dispatch.

View file

@ -111,8 +111,9 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
}
// imsd-messages-bus — the GLib side: imsd's dictionaries, the GDBus client
// of net.catcrafts.IMS1.Messaging, the desktop notifications and the app's
// own session-bus name. No window.
// of net.catcrafts.IMS1.Messaging, the desktop notifications, the app's
// own session-bus name and the desktop portal's appearance settings. No
// window.
static auto Bus = std::make_unique<Configuration>();
Bus->path = "./";
Bus->name = "imsd-messages-bus";
@ -121,11 +122,12 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
Bus->type = ConfigurationType::LibraryStatic;
Bus->dependencies = { Core.get() };
{
std::array<fs::path, 5> ifaces = {
std::array<fs::path, 6> ifaces = {
"interfaces/ImsdMessages.Bus",
"interfaces/ImsdMessages.Bus-Variant",
"interfaces/ImsdMessages.Bus-Client",
"interfaces/ImsdMessages.Bus-Notifier",
"interfaces/ImsdMessages.Bus-Appearance",
"interfaces/ImsdMessages.Bus-Instance",
};
std::array<fs::path, 0> impls = {};