Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/ui-egui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }

[target.'cfg(target_os = "linux")'.dependencies]
zbus = { version = "5", default-features = false, features = ["async-io", "blocking-api"] }

[dev-dependencies]
skrifa = { workspace = true }
# kittest's own dev-dependencies do not propagate; tests need both font features explicitly.
Expand Down
9 changes: 7 additions & 2 deletions crates/ui-egui/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use super::state::{FilePlace, FilePurpose, ImeDescriptorKey, ImeDestination, Ime
use super::updates_ui;
use super::{
AnimPreview, ControlRequest, FileTarget, HashMap, ImeCancelled, ImeComposition, ImeResetPhase, ImeTerminalPending, InputTarget, Mods,
PendingFile, Perf, Receiver, Session, SlideApp, Target, UI_COMMANDS, UiRequest, Value, backstage, canvas, capture, dialogs, doc_window,
eyedropper, json, media, menus, notes, panes, preview, qat, ribbon, selpane, show, sorter, status, textures, theme, thumbs, toast, uifonts,
PendingFile, Perf, Receiver, Session, SlideApp, Target, UI_COMMANDS, UiRequest, Value, backstage, canvas, capture, desktop_theme, dialogs,
doc_window, eyedropper, json, media, menus, notes, panes, preview, qat, ribbon, selpane, show, sorter, status, textures, theme, thumbs, toast,
uifonts,
};

mod clipboard;
Expand Down Expand Up @@ -89,6 +90,10 @@ impl SlideApp {
capture: capture::Capture::default(),
styled: false,
restyle: true,
desktop_theme: desktop_theme::DesktopTheme::start(),
desktop_dark: None,
last_system_dark: None,
shown_brightness: theme::Brightness::Light,
fonts_ready: false,
last_time: 0.0,
last_recovery: 0.0,
Expand Down
15 changes: 13 additions & 2 deletions crates/ui-egui/src/app/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,21 @@ impl SlideApp {
}
"view.collapseRibbon" => self.ui.ribbon_collapsed = !self.ui.ribbon_collapsed,
"view.dark" => {
let on = self.flag(p, self.ui.brightness == theme::Brightness::Dark);
self.ui.brightness = if on { theme::Brightness::Dark } else { theme::Brightness::Light };
let on = self.flag(p, self.shown_brightness == theme::Brightness::Dark);
self.ui.brightness = Some(if on { theme::Brightness::Dark } else { theme::Brightness::Light });
self.restyle = true;
}
"view.theme" => {
if let Some(value) = p.get("value").and_then(Value::as_str) {
self.ui.brightness = match value {
"system" => None,
"light" => Some(theme::Brightness::Light),
"dark" => Some(theme::Brightness::Dark),
other => return Err(format!("unknown theme `{other}`; use system, light or dark")),
};
self.restyle = true;
}
}
"view.grayscale" => self.ui.grayscale = self.flag(p, self.ui.grayscale),
"view.newWindow" => return doc_window::command(self, p),
"show.start" => {
Expand Down
16 changes: 15 additions & 1 deletion crates/ui-egui/src/app/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,22 @@ impl SlideApp {
ctx.request_discard("install interface fonts before layout");
return false;
}
if let Some(answer) = self.desktop_theme.take_change() {
self.desktop_dark = Some(answer);
if self.ui.brightness.is_none() {
self.restyle = true;
}
}
let system_dark = ctx.system_theme().map(|theme| theme == egui::Theme::Dark).or(self.desktop_dark);
if self.last_system_dark != system_dark {
self.last_system_dark = system_dark;
if self.ui.brightness.is_none() {
self.restyle = true;
}
}
if self.restyle {
theme::apply(ctx, &theme::Tokens::for_brightness(self.ui.brightness));
self.shown_brightness = theme::resolve_brightness(self.ui.brightness, system_dark, self.shown_brightness);
theme::apply(ctx, &theme::Tokens::for_brightness(self.shown_brightness));
self.restyle = false;
}
self.fonts_ready = true;
Expand Down
2 changes: 1 addition & 1 deletion crates/ui-egui/src/backstage/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ pub(super) fn about(app: &mut SlideApp, ui: &mut Ui) {
ui.vertical(|ui| {
ui.set_width(340.0);
heading(ui, "Appearance");
let dark = app.ui.brightness == theme::Brightness::Dark;
let dark = app.shown_brightness == theme::Brightness::Dark;
craft_ui::ComboBox::from_id_salt("backstage_appearance")
.width(260.0)
.selected_text(if dark { "Dark" } else { "Light" })
Expand Down
163 changes: 163 additions & 0 deletions crates/ui-egui/src/desktop_theme.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
//! 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.

#[cfg(not(test))]
use std::sync::mpsc::channel;
use std::sync::mpsc::{Receiver, TryRecvError};
#[cfg(not(test))]
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.
#[cfg(not(test))]
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.
/// Tests get an inert watcher, so they never depend on the host desktop's theme.
#[cfg(test)]
pub fn start() -> Self {
Self::default()
}

/// 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.
#[cfg(not(test))]
pub fn start() -> Self {
let (tx, rx) = channel();
let started = std::thread::Builder::new().name("deckcraft-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.appearance", "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 };
if let Ok(scheme) = String::try_from(&*answer) {
return parse_string(&scheme);
}
if let Ok(scheme) = u32::try_from(&*answer) {
return parse_number(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_string(scheme: &str) -> Option<bool> {
match scheme {
"prefer-dark" => Some(true),
"prefer-light" => Some(false),
_ => None,
}
}

#[cfg(target_os = "linux")]
fn parse_number(scheme: u32) -> Option<bool> {
match scheme {
1 => Some(true),
2 => 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_string("prefer-dark"), Some(true));
assert_eq!(parse_string("prefer-light"), Some(false));
assert_eq!(parse_string("default"), None);
assert_eq!(parse_string(""), None);
assert_eq!(parse_number(1), Some(true));
assert_eq!(parse_number(2), Some(false));
assert_eq!(parse_number(0), 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);
}
}
29 changes: 25 additions & 4 deletions crates/ui-egui/src/dialogs/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1341,10 +1341,31 @@ fn dlg_preferences(app: &mut SlideApp, ui: &mut Ui, d: &mut Dialog) -> bool {
d.params = json!({ "before": preferences_snapshot(app) });
}
ui.label(egui::RichText::new("General").font(theme::bold(13.0)));
let mut dark = app.ui.brightness == theme::Brightness::Dark;
if ui.checkbox(&mut dark, "Dark appearance").changed() {
let _ = app.run("view.dark", json!({"on": dark}));
}
ui.horizontal(|ui| {
ui.label("Display theme");
let selected = match app.ui.brightness {
None => "Use system setting",
Some(theme::Brightness::Light) => "Light",
Some(theme::Brightness::Dark) => "Dark",
};
egui::ComboBox::from_id_salt("display_theme")
.selected_text(selected)
.width(180.0)
.show_ui(ui, |ui| {
for (value, label) in [("system", "Use system setting"), ("light", "Light"), ("dark", "Dark")] {
let chosen = match value {
"system" => app.ui.brightness.is_none(),
"light" => app.ui.brightness == Some(theme::Brightness::Light),
_ => app.ui.brightness == Some(theme::Brightness::Dark),
};
if ui.selectable_label(chosen, label).clicked() {
let _ = app.run("view.theme", json!({"value": value}));
}
}
})
.response
.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, "Display theme"));
});
// While the pointer holds the slider its value only waits in the dialog: applying it
// would rescale the slider under the pointer and run it to an end (#767). It applies
// on release, and at once from the keyboard.
Expand Down
28 changes: 25 additions & 3 deletions crates/ui-egui/src/dialogs/preferences.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@ use super::{Dialog, SlideApp, Value, json, theme};
/// What the Preferences dialog can change, as it was when the dialog opened.
pub(super) fn preferences_snapshot(app: &SlideApp) -> Value {
json!({
"dark": app.ui.brightness == theme::Brightness::Dark,
"theme": match app.ui.brightness {
None => "system",
Some(theme::Brightness::Light) => "light",
Some(theme::Brightness::Dark) => "dark",
},
// What was on screen, for a system setting the desktop gives no answer for.
"dark": app.shown_brightness == theme::Brightness::Dark,
"uiScale": app.ui.ui_scale,
"prefs": serde_json::to_value(&app.session.prefs).unwrap_or(Value::Null),
})
Expand All @@ -12,11 +18,27 @@ pub(super) fn preferences_snapshot(app: &SlideApp) -> Value {
/// Puts back the settings the Preferences dialog opened with (Cancel, Esc, the close button).
pub(super) fn restore_preferences(app: &mut SlideApp, d: &Dialog) {
let Some(before) = d.params.get("before") else { return };
if let Some(dark) = before.get("dark").and_then(Value::as_bool)
&& dark != (app.ui.brightness == theme::Brightness::Dark)
if let Some(value) = before.get("theme").and_then(Value::as_str) {
if Some(value)
!= match app.ui.brightness {
None => Some("system"),
Some(theme::Brightness::Light) => Some("light"),
Some(theme::Brightness::Dark) => Some("dark"),
}
{
let _ = app.run("view.theme", json!({ "value": value }));
}
} else if let Some(dark) = before.get("dark").and_then(Value::as_bool)
&& dark != (app.shown_brightness == theme::Brightness::Dark)
{
let _ = app.run("view.dark", json!({ "on": dark }));
}
if let Some(dark) = before.get("dark").and_then(Value::as_bool) {
// With no system answer the restyle keeps what was drawn, so put that back explicitly:
// Cancel must not leave the dark choice the user tried.
app.shown_brightness = if dark { theme::Brightness::Dark } else { theme::Brightness::Light };
app.restyle = true;
}
if let Some(scale) = before.get("uiScale").and_then(Value::as_f64) {
app.ui.ui_scale = scale as f32;
}
Expand Down
11 changes: 8 additions & 3 deletions crates/ui-egui/src/dialogs/preferences_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ fn open_options(h: &mut Harness<'_, SlideApp>) {
}

fn dark(app: &SlideApp) -> bool {
app.ui.brightness == Brightness::Dark
app.shown_brightness == Brightness::Dark
}

/// A checkbox applies as it is toggled and Cancel puts the old value back.
Expand Down Expand Up @@ -99,9 +99,14 @@ fn options_cancel_puts_the_appearance_and_scale_back() {
let (dark_before, scale_before) = (dark(h.state()), h.state().ui.ui_scale);
open_options(&mut h);

h.query_by_label("Dark appearance").expect("the checkbox is there").click();
let next_theme = if dark(h.state()) { "light" } else { "dark" };
h.state_mut().run("view.theme", json!({"value": next_theme})).expect("change display theme");
h.run_steps(2);
assert!(dark(h.state()), "the appearance applies as it is toggled");
assert_eq!(
h.state().ui.brightness,
Some(if next_theme == "dark" { Brightness::Dark } else { Brightness::Light }),
"the appearance choice applies immediately"
);

// Clicking the slider's middle sets it near the middle of its range, away from the default.
interface_size(&h).click();
Expand Down
6 changes: 6 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod backstage;
pub mod canvas;
pub mod capture;
pub mod control;
pub mod desktop_theme;
pub mod dialogs;
pub mod doc_window;
pub mod eyedropper;
Expand Down Expand Up @@ -116,6 +117,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("view.tab", "Ribbon Tab", None, "{tab}"),
("view.collapseRibbon", "Collapse the Ribbon", Some("Cmd+F1"), "{}"),
("view.dark", "Dark Mode", None, "{on?: bool}"),
("view.theme", "Display theme", None, "{value?: system|light|dark}"),
("view.grayscale", "Grayscale", None, "{on?: bool}"),
("view.newWindow", "New Window", None, "{on?: bool, slide?: index, delta?: int}"),
("show.start", "Slide Show", Some("F5"), "{from?: index, custom?: name}"),
Expand Down Expand Up @@ -303,6 +305,10 @@ pub struct SlideApp {
capture: capture::Capture,
styled: bool,
restyle: bool,
desktop_theme: desktop_theme::DesktopTheme,
desktop_dark: Option<bool>,
last_system_dark: Option<bool>,
pub(crate) shown_brightness: theme::Brightness,
fonts_ready: bool,
last_time: f64,
/// When AutoRecover data was last written (monotonic seconds, not wall time).
Expand Down
Loading
Loading