Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Linux: "Use system setting" asks the desktop, not winit (#881)

gyurixc93378203956
diff --git a/Cargo.lock b/Cargo.lock
index 3523ac1d4..7c3064e72 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3814,6 +3814,9 @@ dependencies = [
[[package]]
name = "pdfcraft-platform"
version = "0.5.0"
+dependencies = [
+ "zbus",
+]
[[package]]
name = "pdfcraft-preflight"
diff --git a/crates/platform/Cargo.toml b/crates/platform/Cargo.toml
index 54e7030a3..d3644b913 100644
--- a/crates/platform/Cargo.toml
+++ b/crates/platform/Cargo.toml
@@ -9,3 +9,9 @@ license.workspace = true
workspace = true
[dependencies]
+
+[target.'cfg(target_os = "linux")'.dependencies]
+# The desktop's light/dark choice (see `desktop_theme.rs`). Already in the tree, with the features
+# this needs, through accesskit's accessibility bus; pinned to the same version so nothing is
+# built twice.
+zbus = "=5.19.0"
diff --git a/crates/platform/src/desktop_theme.rs b/crates/platform/src/desktop_theme.rs
new file mode 100644
index 000000000..9b88f9efe
--- /dev/null
+++ b/crates/platform/src/desktop_theme.rs
@@ -0,0 +1,136 @@
+//! The desktop's own light/dark choice, for an interface setting that follows it.
+//!
+//! winit reports no system theme on Linux — `ActiveEventLoop::system_theme` is `None` on every
+//! desktop there — so "Use system setting" has to ask the desktop itself. The XDG Desktop Portal's
+//! Settings interface answers on GNOME, KDE and XFCE alike, over X11 and Wayland alike.
+
+use std::sync::mpsc::{Receiver, TryRecvError, channel};
+use std::time::Duration;
+
+/// How often [`DesktopTheme::start`] re-reads the desktop's answer. The portal also publishes a
+/// change signal, but subscribing needs a connection kept alive for the life of every window; one
+/// round trip every few seconds is cheap and reacts soon enough after a theme switch.
+const POLL: Duration = Duration::from_secs(4);
+
+/// Whether the desktop asks applications to draw dark. `None` when it says nothing, and when
+/// there is no session bus or no portal to ask (a bare X server, a container), so the caller
+/// keeps whatever it chose itself.
+pub fn prefers_dark() -> Option<bool> {
+ read()
+}
+
+/// Watches the desktop and reports its choice when it changes. [`prefers_dark`] covers the
+/// answer at start-up; this covers the user switching theme while the app runs.
+#[derive(Default)]
+pub struct DesktopTheme {
+ /// `None` when no watcher thread could be started; the one-shot read still works.
+ changes: Option<Receiver<Option<bool>>>,
+}
+
+impl DesktopTheme {
+ /// Start watching. Nothing runs before this is called, and calling it once is enough. The
+ /// first answer is sent straight away, so the caller does not have to ask for it separately.
+ pub fn start() -> Self {
+ let (tx, rx) = channel();
+ let started = std::thread::Builder::new().name("pdfcraft-desktop-theme".into()).spawn(move || {
+ let mut last = read();
+ if tx.send(last).is_err() {
+ return;
+ }
+ loop {
+ std::thread::sleep(POLL);
+ let now = read();
+ if now != last {
+ last = now;
+ if tx.send(now).is_err() {
+ return;
+ }
+ }
+ }
+ });
+ Self { changes: started.ok().map(|_| rx) }
+ }
+
+ /// The desktop's new answer if it changed since the last call, to be polled once a frame.
+ /// Several changes in one frame collapse to the newest, and a desktop that stops answering
+ /// leaves the last answer in place.
+ pub fn take_change(&mut self) -> Option<bool> {
+ let Some(changes) = &self.changes else { return None };
+ let mut newest = None;
+ loop {
+ match changes.try_recv() {
+ Ok(changed) => newest = changed,
+ Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => return newest,
+ }
+ }
+ }
+}
+
+/// Ask the portal once. D-Bus calls block, so this belongs off the UI thread: the watcher's
+/// thread is its only caller.
+#[cfg(target_os = "linux")]
+fn read() -> Option<bool> {
+ const PORTAL: &str = "org.freedesktop.portal.Desktop";
+ const SETTINGS: &str = "org.freedesktop.portal.Settings";
+ // The colour scheme under its GNOME schema name first: GNOME's portal answers it, and so
+ // does XFCE's, which proxies the GSettings schemas but not the older freedesktop one. KDE
+ // answers only the second.
+ const SCHEMAS: [(&str, &str); 2] = [("org.gnome.desktop.interface", "color-scheme"), ("org.freedesktop.interface.color-scheme", "color-scheme")];
+ let connection = zbus::blocking::Connection::session().ok()?;
+ for (schema, key) in SCHEMAS {
+ let Ok(reply) = connection.call_method(Some(PORTAL), "/org/freedesktop/portal/desktop", Some(SETTINGS), "ReadOne", &(schema, key)) else {
+ continue;
+ };
+ let Ok((answer,)) = reply.body().deserialize::<(zbus::zvariant::OwnedValue,)>() else { continue };
+ // The reply is one variant wrapping a string.
+ if let Ok(scheme) = String::try_from(&*answer) {
+ return parse(&scheme);
+ }
+ }
+ None
+}
+
+/// The portal's `color-scheme` answer. `default` means the desktop states no preference, so
+/// neither does the application.
+#[cfg(target_os = "linux")]
+fn parse(scheme: &str) -> Option<bool> {
+ match scheme {
+ "prefer-dark" => Some(true),
+ "prefer-light" => Some(false),
+ _ => None,
+ }
+}
+
+/// macOS and Windows answer through winit, which the caller already has.
+#[cfg(not(target_os = "linux"))]
+fn read() -> Option<bool> {
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The portal answers with one of three strings; only the two preferences are a choice.
+ #[test]
+ #[cfg(target_os = "linux")]
+ fn the_portal_answer_reads_as_a_choice_or_as_none() {
+ assert_eq!(parse("prefer-dark"), Some(true));
+ assert_eq!(parse("prefer-light"), Some(false));
+ assert_eq!(parse("default"), None);
+ assert_eq!(parse(""), None);
+ }
+
+ /// Off Linux the caller already has winit's answer, so this adds nothing.
+ #[test]
+ #[cfg(not(target_os = "linux"))]
+ fn other_platforms_answer_through_winit() {
+ assert_eq!(prefers_dark(), None);
+ }
+
+ /// A watcher that was never started is inert rather than a panic.
+ #[test]
+ fn a_watcher_without_a_thread_is_inert() {
+ assert_eq!(DesktopTheme::default().take_change(), None);
+ }
+}
diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs
index 799eb5669..684f100d3 100644
--- a/crates/platform/src/lib.rs
+++ b/crates/platform/src/lib.rs
@@ -3,4 +3,5 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
+pub mod desktop_theme;
pub mod staging;
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e2dfca1ff..db2520e7b 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -393,6 +393,10 @@ pub struct PdfCraftApp {
/// Resolved colours, including the current OS theme when following the system.
pub theme: ThemeKind,
pub theme_preference: ThemePreference,
+ /// The desktop's light/dark choice, watched while the app runs (Linux has no winit answer).
+ desktop_theme: pdfcraft_platform::desktop_theme::DesktopTheme,
+ /// The last answer [`desktop_theme`] gave, so a frame that asks costs nothing.
+ desktop_dark: Option<bool>,
/// Interface language preference: `auto` (follow the system) or a code from [`i18n::LANGUAGES`].
pub language: String,
/// Preferences: bake Fill & Sign marks into the page when saving. Off, so a normal save stays editable.
@@ -633,6 +637,12 @@ impl Default for PdfCraftApp {
}
}
+/// What the operating system says about light and dark, as "draw dark". `None` means nobody
+/// answered, not a preference, so the caller keeps what it chose.
+fn system_theme(ctx: &egui::Context, desktop_dark: Option<bool>) -> Option<bool> {
+ ctx.system_theme().map(|theme| theme == egui::Theme::Dark).or(desktop_dark)
+}
+
/// A restored colour: an `[r, g, b]` array of finite numbers, each clamped to 0–1 (restored
/// settings are untrusted). Anything else (a string, a wrong length, a null or a non-finite
/// number) is refused whole, so the caller keeps its default.
@@ -672,6 +682,8 @@ impl PdfCraftApp {
comment_prefs: Default::default(),
theme: ThemeKind::Light,
theme_preference: ThemePreference::Light,
+ desktop_theme: pdfcraft_platform::desktop_theme::DesktopTheme::start(),
+ desktop_dark: None,
language: i18n::AUTO.to_string(),
flatten_fill_sign_on_save: false,
dialog: None,
@@ -1224,7 +1236,9 @@ impl PdfCraftApp {
pub fn set_theme_preference(&mut self, preference: ThemePreference) {
self.theme_preference = preference;
- self.theme = preference.resolve(self.ctx.as_ref().and_then(egui::Context::system_theme), self.theme);
+ // Before the first frame there is no context to ask, so the last choice stands.
+ let system = self.ctx.as_ref().and_then(|ctx| system_theme(ctx, self.desktop_dark));
+ self.theme = preference.resolve(system, self.theme);
if let Some(ctx) = &self.ctx {
theme::apply(ctx, self.theme);
}
@@ -1238,7 +1252,10 @@ impl PdfCraftApp {
}
fn sync_theme(&mut self, ctx: &egui::Context) {
- let kind = self.theme_preference.resolve(ctx.system_theme(), self.theme);
+ if let Some(dark) = self.desktop_theme.take_change() {
+ self.desktop_dark = Some(dark);
+ }
+ let kind = self.theme_preference.resolve(system_theme(ctx, self.desktop_dark), self.theme);
if kind != self.theme {
self.theme = kind;
theme::apply(ctx, kind);
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index 5b74b6422..1691f8328 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -22,13 +22,16 @@ pub enum ThemePreference {
}
impl ThemePreference {
- pub fn resolve(self, system: Option<egui::Theme>, fallback: ThemeKind) -> ThemeKind {
+ /// The colours to draw. `system` is what the operating system says, `None` when it says
+ /// nothing; `fallback` is then what the app last drew, so an unanswering desktop leaves the
+ /// user's choice alone.
+ pub fn resolve(self, system: Option<bool>, fallback: ThemeKind) -> ThemeKind {
match self {
Self::Light => ThemeKind::Light,
Self::Dark => ThemeKind::Dark,
Self::System => match system {
- Some(egui::Theme::Light) => ThemeKind::Light,
- Some(egui::Theme::Dark) => ThemeKind::Dark,
+ Some(true) => ThemeKind::Dark,
+ Some(false) => ThemeKind::Light,
None => fallback,
},
}
@@ -285,6 +288,23 @@ pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
mod tests {
use super::*;
+ /// "Use system setting" draws what the operating system says, dark or light.
+ #[test]
+ fn following_the_system_draws_what_the_system_says() {
+ assert_eq!(ThemePreference::System.resolve(Some(true), ThemeKind::Light), ThemeKind::Dark);
+ assert_eq!(ThemePreference::System.resolve(Some(false), ThemeKind::Dark), ThemeKind::Light);
+ }
+
+ /// An operating system that says nothing leaves the last choice standing, and an explicit
+ /// Light or Dark is never overridden by what the system says.
+ #[test]
+ fn an_answerless_system_leaves_the_choice_and_an_explicit_one_stands() {
+ assert_eq!(ThemePreference::System.resolve(None, ThemeKind::Light), ThemeKind::Light);
+ assert_eq!(ThemePreference::System.resolve(None, ThemeKind::Dark), ThemeKind::Dark);
+ assert_eq!(ThemePreference::Light.resolve(Some(true), ThemeKind::Dark), ThemeKind::Light);
+ assert_eq!(ThemePreference::Dark.resolve(Some(false), ThemeKind::Light), ThemeKind::Dark);
+ }
+
/// WCAG 2 contrast ratio between two opaque colours.
fn contrast(a: Color32, b: Color32) -> f32 {
let lum = |c: Color32| {