Skip to content

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

Fix theme controls with shared System, Light and Dark preferences (#212)

才倾梦华V42078a8365f8
diff --git a/ROADMAP.md b/ROADMAP.md
index 8da005d56..79e5eadc9 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -92,7 +92,7 @@ Hours are for a single agent (low–high). "Done" is the estimated fraction of t
| M0 | Skeleton: workspace, xtask gates, CI | 15–30 | 92% | 2–4 | GitHub workflow, `deny.toml` (licence audit of every dependency), parity checklist (826 features, `xtask parity`) done. Missing: remaining crate stubs, testkit/oracle crates |
| M1 | COS: filters, crypt, parser, xref, writer | 120–200 | 78% | 25–45 | Done:<br>- filters and crypt: every standard-security revision R2–R6 (RC4, AES-128/256), SASLprep, permissions, creating encryption;<br>- cos: parse and repair (including invalid xref object-number ranges), decrypt on load, re-encrypt on save, incremental and full writing.<br>Corpus: open/edit/save passes on 958 files, and all 7 password-protected files open.<br>Full saves now pack objects into compressed object streams. Fuzzing runs nightly (`xtask fuzz`). Missing: ≥ 250 tests, own image codecs |
| M2 | Model, render, text | 200–350 | 15% | 170–300 | hayro bootstrap renderer (vendored patches). Text extraction reaches word-F1 0.98 against pdftotext. Missing: model crate, fonts, DisplayList, renderer independent of hayro |
-| M3 | Viewer app (native + web) | 80–150 | 88% | 10–19 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling, covered by headless UI regressions. |
+| M3 | Viewer app (native + web) | 80–150 | 88% | 10–19 | Acrobat-style shell, find, select, panels, tiles, web build, UI control channel for agents (opt-in). Missing: 60 fps test on a 500-page document, snapshot tests of every panel Done since: fit visible, document title in the window; Linux middle-button scrolling; shared three-state theme preferences in the toolbar, View menu and control channel. |
| M4 | Engine, history, save, organize | 100–180 | 95% | 9–17 | Done:<br>- command registry (menus, shortcuts and palette all use it);<br>- undo/redo; incremental, atomic and encrypted saves;<br>- autosave and crash recovery;<br>- organize, combine, extract, split and insert-from-file, with identical fonts and images stored once;<br>- CLI `edit/combine/extract/split`.<br>Done since: bookmark editing, page labels (Number pages), CLI `run`, Set Page Boxes, Crop tool, Duplicate pages, Ctrl+A / Cmd+A to select all pages in Organize. Missing: Replace pages, page transitions, recovery on the web |
| M5 | Comments (all annotation types, XFDF) | 120–200 | 88% | 15–25 | Done: notes, highlight/underline/strikeout/squiggly, text boxes, ink, lines, arrows, rectangles, ovals, stamps (dynamic, Sign Here, Standard Business), with appearance streams; replies, status, checkmarks, locking, move/resize/restyle/delete; properties dialog; panel filter and sort; hide all; summaries (comments only); XFDF/FDF import and export; flatten; Fill & Sign; agent tools. Done since: polygons, connected lines, clouds, callouts, inserted text, colour and checkmark filters. Missing: custom stamps, replace-text proposals, summary layouts with the page |
| M6 | Forms + JavaScript | 160–320 | 45% | 95–185 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done. Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA |
@@ -129,6 +129,8 @@ Newest first. One line per session: the date, what moved, and the new overall pe
- **2026-10-08 (M14, Windows Chinese Auto):** Auto now reads the Windows display language after locale environment overrides, selecting Simplified or Traditional Chinese through the existing locale mapping. Added Chinese region/script and Windows query regressions. Chinese font delivery remains incomplete. Localization remains partial; overall ≈ 30–35% (unchanged).
+- **2026-10-08 (M3, themes):** Toolbar and Display theme now share System, Light and Dark preferences, one command path and persistent settings; the duplicate View toggle is removed. Effective colours track the OS only in System mode, with egui popup styles kept in sync. Overall estimate unchanged (about 30–35%).
+
- **2026-10-08 (M14, Simplified Chinese):** Added 208 translations, bringing the catalog from 1,625 to 1,833 entries. PhotoCraft-style coverage checks protect registered commands, All tools labels and UI `tl!` literals; generated history and diagnostic regressions preserve user values. Chinese font delivery remains incomplete: the release-pinned craft-fonts input has no Hans face and the web build only embeds the Japanese UI face (see #112 and #140). Localization remains partial; overall ≈ 30–35% (unchanged).
- **2026-10-07 (community, #208):** Measure: distance, perimeter and area annotations (standard LineDimension/PolyLineDimension/PolygonDimension with rectilinear /Measure), persistent viewport scales with two-point calibration, vector snapping (endpoints, midpoints, intersections, paths) through nested forms, live readings, CSV export, and eight `measure_*` agent tools. Hardened on landing: snap extraction caps segments and snap targets page-wide and skips undecodable streams and over-deep `q` instead of failing; unsupported imported measurements (compound ft-in, fractional, invalid geometry) are listed as unsupported rather than failing the list; non-ASCII units ("m²") are allowed and rendered in WinAnsi; a closing duplicate polygon vertex counts as closed. Distance and scale are partial (single-unit decimal formats only; Acrobat interop untested). 51.0% shipped; ≈ 30–35% effort.
diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs
index 4105c4ae9..ff746770e 100644
--- a/apps/pdfcraft/src/main.rs
+++ b/apps/pdfcraft/src/main.rs
@@ -5,7 +5,7 @@
//!
//! View options (applied after the files open; also the seed of the UI control channel):
//! `--page N --zoom 150 --layout continuous|two-up|single --panel comments|bookmarks|pages|fields|layers|attachments|none
-//! --theme light|dark --language auto|<code> --mode all|read|edit|convert|sign --tool <catalogue id> --left open|closed
+//! --theme light|dark|system --language auto|<code> --mode all|read|edit|convert|sign --tool <catalogue id> --left open|closed
//! --organize on --fields on --dialog properties|shortcuts|about --palette <query> --home on`
//!
//! `--control <file>` enables the UI control channel (off by default): the app listens on a random
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 442fe9e4b..23ca8bf1f 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -178,7 +178,10 @@ pub const COMMANDS: &[CommandSpec] = &[
c("edit.snapshot", "Take a snapshot", EDIT, None, Document, "camera"),
c("view.full_screen", "Full screen mode", VIEW, Some(Shortcut::cmd("L")), Document, "maximize"),
c("view.read_mode", "Read mode", VIEW, Some(Shortcut { command: true, shift: false, mac_ctrl: true, key: "H" }), Document, "book-open"),
- c("view.theme", "Switch light / dark theme", VIEW, None, Nothing, "moon"),
+ c("view.theme", "Switch light / dark theme", None, None, Nothing, "moon"),
+ c("view.theme.system", "Use system setting", None, None, Nothing, "settings"),
+ c("view.theme.light", "Light gray", None, None, Nothing, "sun"),
+ c("view.theme.dark", "Dark gray", None, None, Nothing, "moon"),
c("comment.list", "Comments panel", VIEW, None, Document, "message-square-text"),
c("comment.note", "Add a sticky note", None, None, Annotate, "sticky-note"),
c("comment.freetext", "Add a text box", None, None, Annotate, "type"),
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index 64aaa41ad..465dae905 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -3,7 +3,7 @@
use egui::{Align, Align2, Color32, CornerRadius, Layout, Rect, Sense, Stroke, vec2};
use crate::canvas::{Fit, PageLayout};
-use crate::theme::{self, ThemeKind, Tokens};
+use crate::theme::{self, ThemePreference, Tokens};
use crate::{Dialog, Mode, PdfCraftApp, PropsTab, RightPanel, icons, widgets};
pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
@@ -43,14 +43,14 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
app.open_dialog();
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
- let (icon, next, tip) = match app.theme {
- ThemeKind::Light => ("moon", ThemeKind::Dark, tl!("Dark gray theme")),
- ThemeKind::Dark => ("sun", ThemeKind::Light, tl!("Light theme")),
+ let (icon, label) = match app.theme_preference {
+ ThemePreference::System => ("settings", tl!("Use system setting")),
+ ThemePreference::Light => ("sun", tl!("Light gray")),
+ ThemePreference::Dark => ("moon", tl!("Dark gray")),
};
- if icons::button(ui, icon, 28.0, false, tl!(tip)).clicked() {
- let ctx = ui.ctx().clone();
- app.set_theme(&ctx, next);
- }
+ let tip = format!("{}: {label}", tl!("Display theme"));
+ let response = icons::button(ui, icon, 28.0, false, &tip);
+ egui::Popup::menu(&response).show(|ui| theme_menu(app, ui));
if icons::button(ui, "circle-help", 28.0, false, tl!("Keyboard shortcuts")).clicked() {
app.dialog = Some(Dialog::Shortcuts);
}
@@ -63,6 +63,20 @@ pub fn tab_strip(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
});
}
+/// Both theme entry points use the same choices and command path.
+fn theme_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
+ for (preference, command, label) in [
+ (ThemePreference::System, "view.theme.system", "Use system setting"),
+ (ThemePreference::Light, "view.theme.light", "Light gray"),
+ (ThemePreference::Dark, "view.theme.dark", "Dark gray"),
+ ] {
+ if ui.radio(app.theme_preference == preference, tl!(label)).clicked() {
+ app.execute(command);
+ ui.close();
+ }
+ }
+}
+
fn tab(ui: &mut egui::Ui, t: &Tokens, name: &str, dirty: bool, active: bool, close: &mut Option<usize>, index: usize) -> egui::Response {
let font = theme::regular(13.0);
let label: String = if name.chars().count() > 28 { format!("{}…", name.chars().take(27).collect::<String>()) } else { name.to_string() };
@@ -212,20 +226,7 @@ fn main_menu(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
ui.separator();
}
crate::commands::registry_menu(app, ui, "View");
- ui.menu_button(tl!("Display theme"), |ui| {
- let ctx = ui.ctx().clone();
- if ui.radio(app.follow_system_theme, tl!("Use system setting")).clicked() {
- app.follow_system_theme = true;
- }
- if ui.radio(!app.follow_system_theme && app.theme == ThemeKind::Light, tl!("Light gray")).clicked() {
- app.follow_system_theme = false;
- app.set_theme(&ctx, ThemeKind::Light);
- }
- if ui.radio(!app.follow_system_theme && app.theme == ThemeKind::Dark, tl!("Dark gray")).clicked() {
- app.follow_system_theme = false;
- app.set_theme(&ctx, ThemeKind::Dark);
- }
- });
+ ui.menu_button(tl!("Display theme"), |ui| theme_menu(app, ui));
ui.menu_button(tl!("Side panels"), |ui| {
for (p, label) in [
(RightPanel::Comments, tl!("Comments")),
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index 4edcd81a7..db033bd6f 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -7,7 +7,11 @@
use pdfcraft_engine::Edit;
use pdfcraft_engine::commands::{self, COMMANDS, CommandSpec};
-use crate::{Dialog, Mode, PdfCraftApp, PropsTab, RightPanel, SaveTarget, theme::ThemeKind, widgets};
+use crate::{
+ Dialog, Mode, PdfCraftApp, PropsTab, RightPanel, SaveTarget,
+ theme::{ThemeKind, ThemePreference},
+ widgets,
+};
impl PdfCraftApp {
pub(crate) fn command_enabled(&self, spec: &CommandSpec) -> bool {
@@ -125,13 +129,13 @@ impl PdfCraftApp {
}
"view.read_mode" => self.mode = if self.mode == Mode::Read { Mode::AllTools } else { Mode::Read },
"view.theme" => {
- let next = if self.theme == ThemeKind::Light { ThemeKind::Dark } else { ThemeKind::Light };
- match self.ctx.clone() {
- Some(ctx) => self.set_theme(&ctx, next),
- None => self.theme = next,
- }
+ let next = if self.theme == ThemeKind::Light { ThemePreference::Dark } else { ThemePreference::Light };
+ self.set_theme_preference(next);
}
command if command.starts_with("measure.") => crate::measure_ui::command(self, command),
+ "view.theme.system" => self.set_theme_preference(ThemePreference::System),
+ "view.theme.light" => self.set_theme_preference(ThemePreference::Light),
+ "view.theme.dark" => self.set_theme_preference(ThemePreference::Dark),
"comment.list" => self.right = Some(RightPanel::Comments),
tool if crate::comments::CommentTool::from_command(tool).is_some() => {
let Some(tool) = crate::comments::CommentTool::from_command(tool) else { return false };
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 1ab32f0e9..be3855a24 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -26,6 +26,8 @@
//! - `ui.set {key, value}`: view options (`--page`, `--zoom`, …), plus persistent preferences.
//! `default-mode=all|read|edit|convert|sign` applies to future PDF opens; `mode` overrides it
//! for this session without changing the saved preference. `ui.state.default_mode` reports it.
+//! `theme=light|dark|system` changes the saved theme preference; `ui.state.theme_preference`
+//! reports the choice and `ui.state.theme` reports the resolved light/dark colours.
//! - `ui.open {path}`: open a file.
//! - `ui.screenshot {region?}`: PNG of the window (base64), optionally cropped to a rect.
@@ -587,6 +589,7 @@ impl Host for crate::PdfCraftApp {
"dialog": self.dialog.map(|d| format!("{d:?}")),
"palette_open": self.palette_open,
"theme": format!("{:?}", self.theme),
+ "theme_preference": self.theme_preference,
"language": self.language,
"notice": self.toast.as_ref().map(|t| t.0.clone()),
"password_prompt": self.password_prompt.is_some(),
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index e8fe02d65..826244b68 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -84,7 +84,7 @@ pub use canvas::DocView;
pub use editing::{CloseRequest, SaveTarget};
pub use files::{ExtractDraft, FilePurpose, RotateDraft, SplitDraft, SplitMode, SplitPlan};
pub use recovery::{AUTOSAVE_SECS, RecoveryMeta, RecoveryStore};
-use theme::ThemeKind;
+use theme::{ThemeKind, ThemePreference};
/// Top-level workspace modes (Acrobat's mode bar).
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -326,11 +326,11 @@ pub struct PdfCraftApp {
pub quick_tool: QuickTool,
/// Comment author, per-tool colours and widths, pin.
pub comment_prefs: comments::CommentPrefs,
+ /// Resolved colours, including the current OS theme when following the system.
pub theme: ThemeKind,
+ pub theme_preference: ThemePreference,
/// Interface language preference: `auto` (follow the system) or a code from [`i18n::LANGUAGES`].
pub language: String,
- /// Follow the operating system's light/dark setting.
- pub follow_system_theme: bool,
pub dialog: Option<Dialog>,
/// How to ask for the latest release (the desktop app sets it; see `updates`).
pub update_source: Option<updates::UpdateSource>,
@@ -439,7 +439,6 @@ pub struct PdfCraftApp {
allow_quit: bool,
/// The egui context, for commands that change window or theme state.
ctx: Option<egui::Context>,
- pending_theme: Option<ThemeKind>,
styled: bool,
fonts_ready: bool,
/// The installed fonts put the Simplified Chinese faces first (see `theme::font_definitions_for`).
@@ -547,8 +546,8 @@ impl PdfCraftApp {
quick_tool: QuickTool::Select,
comment_prefs: Default::default(),
theme: ThemeKind::Light,
+ theme_preference: ThemePreference::Light,
language: i18n::AUTO.to_string(),
- follow_system_theme: false,
dialog: None,
update_source: None,
updates: updates::Updates::default(),
@@ -618,7 +617,6 @@ impl PdfCraftApp {
pending_recovered: None,
allow_quit: false,
ctx: None,
- pending_theme: None,
styled: false,
fonts_ready: false,
fonts_hans: false,
@@ -952,9 +950,20 @@ impl PdfCraftApp {
self.notify(i18n::fmt(tl!(template), args));
}
- pub fn set_theme(&mut self, ctx: &egui::Context, kind: ThemeKind) {
- self.theme = kind;
- theme::apply(ctx, kind);
+ 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);
+ if let Some(ctx) = &self.ctx {
+ theme::apply(ctx, self.theme);
+ }
+ }
+
+ fn sync_theme(&mut self, ctx: &egui::Context) {
+ let kind = self.theme_preference.resolve(ctx.system_theme(), self.theme);
+ if kind != self.theme {
+ self.theme = kind;
+ theme::apply(ctx, kind);
+ }
}
/// Run a catalogue command. Commands that aren't implemented yet say which milestone ships them.
@@ -994,7 +1003,7 @@ impl PdfCraftApp {
let trusted: Vec<String> = self.session.trusted_certificates().iter().map(pdfcraft_engine::sign::x509::to_pem).collect();
serde_json::json!({
"recent": self.recent,
- "theme": self.theme,
+ "theme": self.theme_preference,
"default_mode": self.default_mode,
"language": self.language,
"author": self.comment_prefs.author,
@@ -1021,8 +1030,8 @@ impl PdfCraftApp {
let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();
self.recent = r;
}
- if let Ok(t) = serde_json::from_value::<ThemeKind>(v["theme"].clone()) {
- self.theme = t;
+ if let Ok(preference) = serde_json::from_value::<ThemePreference>(v["theme"].clone()) {
+ self.set_theme_preference(preference);
}
if let Ok(mode) = serde_json::from_value::<Mode>(v["default_mode"].clone()) {
self.default_mode = mode;
@@ -1079,8 +1088,13 @@ impl PdfCraftApp {
self.language = language.to_string();
}
("theme", _) => {
- self.follow_system_theme = value == "system";
- self.pending_theme = Some(if value == "dark" { ThemeKind::Dark } else { ThemeKind::Light });
+ let preference = match value {
+ "system" => ThemePreference::System,
+ "light" => ThemePreference::Light,
+ "dark" => ThemePreference::Dark,
+ _ => return Err("theme must be light, dark, or system".into()),
+ };
+ self.set_theme_preference(preference);
}
("panel", _) => {
self.right = match value {
@@ -1324,17 +1338,7 @@ impl eframe::App for PdfCraftApp {
self.fonts_hans = hans;
}
}
- if let Some(k) = self.pending_theme.take() {
- self.set_theme(ctx, k);
- }
- if self.follow_system_theme
- && let Some(sys) = ctx.system_theme()
- {
- let want = if sys == egui::Theme::Dark { ThemeKind::Dark } else { ThemeKind::Light };
- if want != self.theme {
- self.set_theme(ctx, want);
- }
- }
+ self.sync_theme(ctx);
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
for f in dropped {
self.open_dropped(f, ctx);
diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs
index efb130670..cb8734009 100644
--- a/crates/ui-egui/src/theme.rs
+++ b/crates/ui-egui/src/theme.rs
@@ -12,6 +12,29 @@ pub enum ThemeKind {
Dark,
}
+/// The saved user choice, independent of the light/dark colours currently displayed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
+pub enum ThemePreference {
+ System,
+ #[default]
+ Light,
+ Dark,
+}
+
+impl ThemePreference {
+ pub fn resolve(self, system: Option<egui::Theme>, 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,
+ None => fallback,
+ },
+ }
+ }
+}
+
#[derive(Clone, Copy, Debug)]
pub struct Tokens {
pub kind: ThemeKind,
@@ -168,6 +191,8 @@ pub fn semibold(size: f32) -> FontId {
}
pub fn apply(ctx: &egui::Context, kind: ThemeKind) {
+ // egui must use the same theme for popup/menu styles as our custom chrome.
+ ctx.set_theme(if kind == ThemeKind::Dark { egui::Theme::Dark } else { egui::Theme::Light });
let t = Tokens::for_kind(kind);
ctx.data_mut(|d| d.insert_temp(egui::Id::new("pdfcraft-theme"), t));
let mut v = if t.dark() { Visuals::dark() } else { Visuals::light() };
diff --git a/crates/ui-egui/tests/control.rs b/crates/ui-egui/tests/control.rs
index 323c91552..ff5bcd459 100644
--- a/crates/ui-egui/tests/control.rs
+++ b/crates/ui-egui/tests/control.rs
@@ -68,6 +68,29 @@ fn ok(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, pa
call(h, c, method, params).unwrap_or_else(|e| panic!("{method}: {e}"))
}
+#[test]
+fn theme_commands_and_options_report_preference_and_effective_colours() {
+ let (mut h, c) = harness();
+ h.input_mut().system_theme = Some(egui::Theme::Dark);
+ h.run_steps(2);
+ for (id, preference, effective) in
+ [("view.theme.system", "System", "Dark"), ("view.theme.light", "Light", "Light"), ("view.theme.dark", "Dark", "Dark")]
+ {
+ ok(&mut h, &c, "ui.command", json!({ "id": id }));
+ let state = ok(&mut h, &c, "ui.state", json!({}));
+ assert_eq!(state["theme_preference"], preference);
+ assert_eq!(state["theme"], effective);
+ }
+ ok(&mut h, &c, "ui.set", json!({ "key": "theme", "value": "system" }));
+ h.input_mut().system_theme = Some(egui::Theme::Light);
+ h.run_steps(2);
+ let state = ok(&mut h, &c, "ui.state", json!({}));
+ assert_eq!(state["theme_preference"], "System");
+ assert_eq!(state["theme"], "Light");
+ assert!(call(&mut h, &c, "ui.set", json!({ "key": "theme", "value": "purple" })).is_err());
+ assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["theme_preference"], "System");
+}
+
/// Switching the interface language changes labels only: documents, their dirty state and the
/// command ids agents drive stay exactly the same.
#[test]
diff --git a/crates/ui-egui/tests/theme.rs b/crates/ui-egui/tests/theme.rs
new file mode 100644
index 000000000..9a90181f3
--- /dev/null
+++ b/crates/ui-egui/tests/theme.rs
@@ -0,0 +1,124 @@
+//! Theme preferences stay in sync across both menus, OS changes and saved settings.
+
+use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
+use pdfcraft_ui_egui::PdfCraftApp;
+use pdfcraft_ui_egui::theme::{ThemeKind, ThemePreference, Tokens};
+
+fn harness() -> Harness<'static, PdfCraftApp> {
+ let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app
+ });
+ h.input_mut().system_theme = Some(egui::Theme::Dark);
+ h.run_steps(4);
+ h
+}
+
+fn assert_theme(h: &Harness<'static, PdfCraftApp>, preference: ThemePreference, kind: ThemeKind) {
+ assert_eq!(h.state().theme_preference, preference);
+ assert_eq!(h.state().theme, kind);
+ assert_eq!(Tokens::get(&h.ctx).kind, kind);
+ assert_eq!(h.ctx.global_style().visuals.dark_mode, kind == ThemeKind::Dark);
+ assert_eq!(h.ctx.theme(), if kind == ThemeKind::Dark { egui::Theme::Dark } else { egui::Theme::Light });
+}
+
+fn open_toolbar(h: &mut Harness<'static, PdfCraftApp>, label: &str) {
+ h.get_by_label(&format!("Display theme: {label}")).click();
+ h.run_steps(3);
+ for choice in ["Use system setting", "Light gray", "Dark gray"] {
+ h.get_by_label(choice);
+ }
+}
+
+fn open_view_menu(h: &mut Harness<'static, PdfCraftApp>) {
+ h.get_by_label("Menu").click();
+ h.run_steps(2);
+ h.get_by_label("View ⏵").hover();
+ h.run_steps(3);
+ assert!(h.query_by_label("Switch light / dark theme").is_none());
+ h.get_by_label("Display theme ⏵").hover();
+ h.run_steps(3);
+ for choice in ["Use system setting", "Light gray", "Dark gray"] {
+ h.get_by_label(choice);
+ }
+}
+
+#[test]
+fn toolbar_and_view_menu_share_three_state_preferences() {
+ let mut h = harness();
+ // Explicit light wins even on a dark desktop, including egui's popup style.
+ assert_theme(&h, ThemePreference::Light, ThemeKind::Light);
+ open_toolbar(&mut h, "Light gray");
+ h.get_by_label("Use system setting").click();
+ h.run_steps(3);
+ assert_theme(&h, ThemePreference::System, ThemeKind::Dark);
+
+ open_view_menu(&mut h);
+ h.get_by_label("Light gray").click();
+ h.run_steps(3);
+ assert_theme(&h, ThemePreference::Light, ThemeKind::Light);
+ open_toolbar(&mut h, "Light gray");
+ h.get_by_label("Dark gray").click();
+ h.run_steps(3);
+ assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark);
+
+ open_view_menu(&mut h);
+ h.get_by_label("Use system setting").click();
+ h.run_steps(3);
+ assert_theme(&h, ThemePreference::System, ThemeKind::Dark);
+ h.input_mut().system_theme = Some(egui::Theme::Light);
+ h.run_steps(3);
+ assert_theme(&h, ThemePreference::System, ThemeKind::Light);
+ open_toolbar(&mut h, "Use system setting");
+ h.get_by_label("Dark gray").click();
+ h.run_steps(3);
+ // A manual choice exits system mode and survives subsequent OS changes.
+ h.input_mut().system_theme = Some(egui::Theme::Dark);
+ h.run_steps(2);
+ h.input_mut().system_theme = Some(egui::Theme::Light);
+ h.run_steps(2);
+ assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark);
+}
+
+#[test]
+fn saved_preferences_restore_with_legacy_light_dark_settings() {
+ for (value, preference) in [("light", ThemePreference::Light), ("dark", ThemePreference::Dark), ("system", ThemePreference::System)] {
+ let mut app = PdfCraftApp::new();
+ app.set_option("theme", value).unwrap();
+ let saved = app.persist();
+ let mut restored = PdfCraftApp::new();
+ restored.restore(&saved);
+ assert_eq!(restored.theme_preference, preference);
+ }
+ let mut app = PdfCraftApp::new();
+ app.restore(r#"{"theme":"Dark"}"#);
+ assert_eq!(app.theme_preference, ThemePreference::Dark);
+ assert_eq!(app.theme, ThemeKind::Dark);
+ app.restore(r#"{"theme":"Light"}"#);
+ assert_eq!(app.theme_preference, ThemePreference::Light);
+ assert_eq!(app.theme, ThemeKind::Light);
+ app.restore(r#"{"theme":"System"}"#);
+ app.restore(r#"{"theme":"Purple"}"#);
+ assert_eq!(app.theme_preference, ThemePreference::System);
+}
+
+#[test]
+fn commands_and_options_apply_before_the_first_frame() {
+ let mut app = PdfCraftApp::new();
+ app.run_command("view.theme.dark");
+ assert_eq!(app.theme_preference, ThemePreference::Dark);
+ assert_eq!(app.theme, ThemeKind::Dark);
+ app.run_command("view.theme.system");
+ assert_eq!(app.theme_preference, ThemePreference::System);
+ // The existing palette/control toggle also goes through the preference setter.
+ app.run_command("view.theme");
+ assert_eq!(app.theme_preference, ThemePreference::Light);
+ assert_eq!(app.theme, ThemeKind::Light);
+ app.run_command("view.theme.light");
+ app.set_option("theme", "dark").unwrap();
+ assert!(app.set_option("theme", "purple").unwrap_err().contains("light, dark, or system"));
+ assert_eq!(app.theme_preference, ThemePreference::Dark);
+ assert_eq!(app.theme, ThemeKind::Dark);
+}
diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs
index 3ee9dc5fd..23d8de888 100644
--- a/crates/ui-egui/tests/ui.rs
+++ b/crates/ui-egui/tests/ui.rs
@@ -158,7 +158,7 @@ fn drag_selects_text_and_copy_returns_it() {
#[test]
fn persistence_round_trips_and_tolerates_garbage() {
let mut a = PdfCraftApp::new();
- a.theme = pdfcraft_ui_egui::theme::ThemeKind::Dark;
+ a.set_option("theme", "dark").unwrap();
let json = a.persist();
let mut b = PdfCraftApp::new();
b.restore(&json);
diff --git a/crates/ui-egui/tests/viewer.rs b/crates/ui-egui/tests/viewer.rs
index c3217a46e..3f915bdfd 100644
--- a/crates/ui-egui/tests/viewer.rs
+++ b/crates/ui-egui/tests/viewer.rs
@@ -174,7 +174,7 @@ fn layouts_fit_height_labels_and_system_theme() {
assert!(!h.state_mut().views[0].go_to_typed("xx", &labels));
// Follow the system theme.
h.state_mut().set_option("theme", "system").unwrap();
- assert!(h.state().follow_system_theme);
+ assert_eq!(h.state().theme_preference, pdfcraft_ui_egui::theme::ThemePreference::System);
}
#[test]
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 835d0b10c..e4f7c9ae3 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -1584,10 +1584,10 @@ area = "B"
tier = "P1"
milestone = "M3"
status = "shipped"
-commands = ["view.theme"]
+commands = ["view.theme", "view.theme.light", "view.theme.dark"]
tools = []
-evidence = ["crates/ui-egui/tests/ui.rs::theme_and_view_options_apply", "crates/ui-egui/src/theme.rs::text_is_readable_on_every_surface"]
-notes = "every text colour meets WCAG AA (4.5:1) on every surface in both themes; glyphs are pixel-aligned for sharper text at 100–150 % scaling"
+evidence = ["crates/ui-egui/tests/theme.rs::toolbar_and_view_menu_share_three_state_preferences", "crates/ui-egui/src/theme.rs::text_is_readable_on_every_surface"]
+notes = "Toolbar and Display theme share three choices and a preference setter; manual choices exit system mode. Every text colour meets WCAG AA (4.5:1) on every surface in both themes; glyphs are pixel-aligned for sharper text at 100–150 % scaling."
[[feature]]
id = "view.theme-system"
@@ -1596,10 +1596,10 @@ area = "B"
tier = "P1"
milestone = "M3"
status = "shipped"
-commands = ["view.theme"]
+commands = ["view.theme.system"]
tools = []
-evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
-notes = "Display theme ▸ Use system setting (and --theme system)"
+evidence = ["crates/ui-egui/tests/theme.rs::toolbar_and_view_menu_share_three_state_preferences", "crates/ui-egui/tests/theme.rs::saved_preferences_restore_with_legacy_light_dark_settings", "crates/ui-egui/tests/control.rs::theme_commands_and_options_report_preference_and_effective_colours"]
+notes = "Toolbar, Display theme and --theme system share a persisted System preference that follows OS changes without losing the selected mode; ui.state reports preference and resolved colours separately."
[[feature]]
id = "view.home-view"