From 6070f29fda1612c42b0e4551c99c02db03bffc02 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sat, 28 Nov 2026 22:57:56 +0100 Subject: [PATCH 1/6] test(ui): run the UI tests on one shell on every machine; in-window menus follow the shell (#8630) On a Mac runner, 49 ui-egui tests and one perf test failed that pass on Linux: - The test runtime took the build machine's shell (ShellInfo::default), so a Mac runner had macOS's key table and chords, and ctx.set_os only changed egui's OS. support::install_runtime (and perf.rs's copy) now pin the shell to Linux with craft's testing set_os. A test of another platform still sets it as before. - The in-window menu bar and the palette laid their menus out for Target::current() (the build's OS) instead of the shell's. They now use Target::of_shell, which craft-menu documents for a shell on another OS than the build's. Production is unchanged: there the shell is the build's. - wheel_frames_build_only_the_pages_in_view scrolls three lines per event (one wheel notch), since a line is 40 points on macOS and 100 elsewhere. Refs #8630 --- crates/ui-egui/src/chrome/mode_bar.rs | 3 +-- crates/ui-egui/src/menus.rs | 12 ++++++++++-- crates/ui-egui/tests/it/support/mod.rs | 10 ++++++++++ crates/ui-egui/tests/perf.rs | 6 +++++- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/chrome/mode_bar.rs b/crates/ui-egui/src/chrome/mode_bar.rs index 49c6d4e294..b663668482 100644 --- a/crates/ui-egui/src/chrome/mode_bar.rs +++ b/crates/ui-egui/src/chrome/mode_bar.rs @@ -4,7 +4,6 @@ use std::borrow::Cow; use craft::behavior::{DisplayOrder, IconId, ItemSource, SelectionChange}; use craft::keymap::CommandRef; -use craft::menu::Target; use craft::ui::bars::{Bar, BarKind}; use craft::ui::buttons::{CommandSearch, IconButton}; use craft::ui::contract::{Bind, CollectionEvent, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; @@ -105,7 +104,7 @@ pub(super) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { /// What the palette searches: the menus' commands, each ready tool group, and the catalogue items /// that are not commands of their own. fn palette_entries(app: &PdfCraftApp, ctx: &egui::Context) -> Vec { - let mut entries = app.menu_bar(ctx).help_entries(Target::current(), &crate::menus::layout_options()); + let mut entries = app.menu_bar(ctx).help_entries(crate::menus::shell_target(ctx), &crate::menus::layout_options()); for group in TOOL_GROUPS { if group.availability == Availability::Ready { // PLAN: assumed `tool.group` reads a `group` parameter (pdf-chrome-w9) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2ef9274894..9e28ebb8c8 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -297,6 +297,13 @@ pub(crate) fn layout_options() -> LayoutOptions<'static> { LayoutOptions::new(APP_NAME).label(&translate) } +/// The platform the window's shell runs on, for the menus drawn in the window: the build's own in +/// production, and the operating system a test or a browser sets, so the in-window menus, their +/// chords and the key table agree. +pub(crate) fn shell_target(ctx: &egui::Context) -> Target { + Target::of_shell(&craft::ui::runtime::windows::WindowHost::of(ctx).shell()) +} + /// Whether a dialog, a prompt or the command palette holds the window: the one gate over commands /// and the menus. pub(crate) fn gated(app: &PdfCraftApp) -> bool { @@ -519,12 +526,13 @@ impl PdfCraftApp { /// couldn't be installed), where the top bar starts. A chosen command fires through the board. pub(crate) fn menu_bar_ui(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); - let bar = craft::menu::layout(&self.menu_bar(&ctx), Target::current(), &layout_options()).bar; + let target = shell_target(&ctx); + let bar = craft::menu::layout(&self.menu_bar(&ctx), target, &layout_options()).bar; let modal = gated(self); if *self.window_menu_bar != bar { *self.window_menu_bar = bar; } - craft::menu::MenuBarUi::new(&self.window_menu_bar).target(Target::current()).keyboard(!modal).icons(false).compact(true).show(ui); + craft::menu::MenuBarUi::new(&self.window_menu_bar).target(target).keyboard(!modal).icons(false).compact(true).show(ui); } /// Install the native menu bar (macOS), once, from the eframe app creator. `false` when diff --git a/crates/ui-egui/tests/it/support/mod.rs b/crates/ui-egui/tests/it/support/mod.rs index dbb9ad0a32..14d5c3a27f 100644 --- a/crates/ui-egui/tests/it/support/mod.rs +++ b/crates/ui-egui/tests/it/support/mod.rs @@ -147,6 +147,16 @@ pub fn app_with_clipboard(clipboard: RecordingClipboard) -> PdfCraftApp { pub fn install_runtime(ctx: &egui::Context) { let spec = InstallSpec::new(ShellInfo::default(), Arc::new(NoWindows)); embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(i18n::Lang::EN)).expect("the runtime installs on a fresh context"); + pin_shell_os(ctx); +} + +/// Runs every test on the same shell whatever machine runs it: Linux's key table, chords, menu layout +/// and capabilities. Without it a macOS runner gave the tests its own shell (⌘ chords, the macOS +/// menu layout), so tests written for the in-window menu bar and Ctrl failed there and passed on +/// Linux and Windows. A test of another platform's behaviour sets it with +/// `craft::ui::testing::windows::set_os` (the shell) or `ctx.set_os` (egui's OS only), as before. +pub fn pin_shell_os(ctx: &egui::Context) { + craft::ui::testing::windows::set_os(ctx, craft::host::target::Os::Linux); } /// A clipboard backend the tests share: what the app writes is read back through the clone the test keeps. diff --git a/crates/ui-egui/tests/perf.rs b/crates/ui-egui/tests/perf.rs index acdc4926d6..0ddf43766c 100644 --- a/crates/ui-egui/tests/perf.rs +++ b/crates/ui-egui/tests/perf.rs @@ -163,7 +163,9 @@ fn wheel_frames_build_only_the_pages_in_view() { if frame % 3 == 0 { h.event(egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Line, - delta: egui::vec2(0.0, -1.0), + // Three lines, as one wheel notch: a line is 100 points on Linux and Windows but 40 on + // macOS (`scroll_speed`), and twenty single lines there don't leave the first page at 200%. + delta: egui::vec2(0.0, -3.0), phase: egui::TouchPhase::Move, modifiers: egui::Modifiers::NONE, source: egui::MouseWheelSource::Unknown, @@ -221,4 +223,6 @@ fn install_runtime(ctx: &egui::Context) { let spec = craft::ui::InstallSpec::new(craft::host::target::ShellInfo::default(), std::sync::Arc::new(craft::window::system::NoWindows)); craft::ui::shell::embed::install(ctx, spec, &pdfcraft_ui_egui::fonts::ui_fonts(pdfcraft_ui_egui::i18n::Lang::EN)) .expect("the runtime installs on a fresh context"); + // The same shell on every machine, as `tests/it/support`'s `pin_shell_os`. + craft::ui::testing::windows::set_os(ctx, craft::host::target::Os::Linux); } From 34fdd242ad833271d12fabc3a114883d4829ac51 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 03:13:12 +0100 Subject: [PATCH 2/6] Keep macOS validation gestures and shortcuts on the test shell --- crates/ui-egui/src/dialogs/shortcuts.rs | 2 +- crates/ui-egui/src/menus.rs | 1336 +++++++++++----------- crates/ui-egui/tests/it/control.rs | 6 +- crates/ui-egui/tests/it/organize_drag.rs | 4 +- 4 files changed, 675 insertions(+), 673 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shortcuts.rs b/crates/ui-egui/src/dialogs/shortcuts.rs index be8b2900cc..69b3d4de28 100644 --- a/crates/ui-egui/src/dialogs/shortcuts.rs +++ b/crates/ui-egui/src/dialogs/shortcuts.rs @@ -26,7 +26,7 @@ fn keymap(ctx: &egui::Context) -> Keymap { let defs = crate::commands::catalog::shared_catalog(crate::commands::mac_shortcuts(ctx)) .map(|c| c.defs().iter().map(localized).collect()) .unwrap_or_default(); - Keymap::new(defs, Scopes::new(), Platform::current()) + Keymap::new(defs, Scopes::new(), Platform::of_egui(ctx.os())) } /// `def` as the window shows it: labelled as the menus label it, under its menu bar path. diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2ea447c819..835bbc37a0 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,668 +1,668 @@ -//! The menus: one definition ([`PdfCraftApp::menu_bar`]) for the native macOS menu bar and the -//! in-window bar on Windows, Linux and the web, laid out for each platform by craft-menu. -//! -//! Items run registry commands (`pdfcraft_engine::commands`) by id, with the registry's label and -//! shortcut, so a menu click and its shortcut run the same command. A few items have menu-only -//! ids: the zoom keys the document view handles itself, the side panel choices, the clipboard -//! keys, the recent files and the open documents. Each is a command of the app's catalog -//! (`commands::catalog`), fired once per click, whichever bar it came from. - -use craft::keymap::{Key, Mods}; -use craft::menu::{Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Layout, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target}; -use craft::ui::runtime::commands::{FireSource, fire, resolve}; -use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS}; -use pdfcraft_engine::commands::{self, Shortcut}; - -use crate::{PdfCraftApp, RightPanel}; - -pub(super) mod tab_context; - -/// The app's name in the menus the layouts write (About, Hide, Quit). -pub(crate) const APP_NAME: &str = "PdfCraft"; - -/// Menu-only commands. The registry's commands keep their own ids. -pub(crate) const CUT: &str = "edit.cut"; -pub(crate) const PASTE: &str = "edit.paste"; -pub(crate) const DELETE: &str = "edit.delete"; -pub(crate) const SELECT_ALL: &str = "edit.select_all"; -pub(crate) const QUIT: &str = "app.quit"; -pub(crate) const NO_RECENT: &str = "file.no_recent"; -/// An open document in the Window menu, `{"index": n}` in the tab strip. -pub(crate) const DOCUMENT: &str = "window.document"; -/// A side panel, `{"panel": name}` ([`PANELS`]). -pub(crate) const PANEL: &str = "view.panel"; -const ACTUAL_SIZE: &str = "view.zoom.actual_size"; -const PAGE_LEVEL: &str = "view.zoom.page_level"; -const FIT_WIDTH: &str = "view.zoom.fit_width"; -const FIT_HEIGHT: &str = "view.zoom.fit_height"; -const ZOOM_IN: &str = "view.zoom.in"; -const ZOOM_OUT: &str = "view.zoom.out"; -const ROTATE_CW: &str = "view.rotate.cw"; -const ROTATE_CCW: &str = "view.rotate.ccw"; - -/// The menu-only items: id, English label and the shortcut shown (the keys stay with the view). The -/// zoom and rotate ids are registry commands; only Fit to height has no registry row. -pub(crate) const EXTRA: &[(&str, &str, Option)] = &[ - (QUIT, "Quit", Some(Shortcut::cmd("Q"))), - (CUT, "Cut", Some(Shortcut::cmd("X"))), - (PASTE, "Paste", Some(Shortcut::cmd("V"))), - (DELETE, "Delete", Some(Shortcut { command: false, shift: false, mac_ctrl: false, key: "Delete" })), - (SELECT_ALL, "Select all", Some(crate::commands::SELECT_ALL)), - (NO_RECENT, "No recent files", None), - (FIT_HEIGHT, "Fit to height", None), -]; - -/// View ▸ Side panels: the panel, its id in [`PANEL`] commands and its English label. -pub(crate) const PANELS: &[(RightPanel, &str, &str)] = &[ - (RightPanel::Comments, "comments", "Comments"), - (RightPanel::Bookmarks, "bookmarks", "Bookmarks"), - (RightPanel::Pages, "pages", "Pages"), - (RightPanel::Fields, "fields", "Fields"), - (RightPanel::Layers, "layers", "Layers"), - (RightPanel::Attachments, "attachments", "Attachments"), - (RightPanel::Signatures, "signatures", "Signatures"), - (RightPanel::Accessibility, "accessibility", "Accessibility Checker"), - (RightPanel::Tags, "tags", "Tags"), - (RightPanel::Search, "search", "Search"), - (RightPanel::Compare, "compare", "Compare"), -]; - -/// The English titles of the menus and submenus, for the bar's mnemonics in languages whose -/// labels have no ASCII letter. -const TITLES: &[&str] = &[ - "File", - "Edit", - "View", - "Pages", - "Sign", - "Window", - "Help", - "Open Recent", - "Create", - "Export", - "Protect", - "Zoom", - "Rotate view", - "Page navigation", - "Page display", - "Side panels", - "Display theme", - "Tools", - "Fill & Sign", -]; - -/// Separator. -const SEP: &str = "---"; - -const FILE: &[&str] = &[ - "create.blank", - "file.open", - "file.open_recent", - "file.pin_folder", - SEP, - "page.combine", - SEP, - "file.save", - "file.save_as", - "file.revert", - SEP, - "file.close", - "file.close_all", - SEP, - "optimize.reduce", - "optimize.advanced", - SEP, - "file.properties", - "file.word_count", - SEP, - "print.dialog", - QUIT, -]; -const CREATE: &[&str] = &["create.file", "create.multiple", "create.multiple_separate", "create.images", "create.clipboard"]; -const EXPORT: &[&str] = &["export.docx", "export.pptx", "export.rtf", "export.html", "export.text", SEP, "export.image", "export.all_images"]; -const PROTECT: &[&str] = &["protect.password", "protect.remove", "protect.unlock", SEP, "protect.properties"]; -const EDIT: &[&str] = &[ - "edit.undo", - "edit.redo", - SEP, - CUT, - "edit.copy", - PASTE, - DELETE, - SEP, - "comment.copy", - "comment.paste", - SEP, - SELECT_ALL, - SEP, - "edit.find", - "edit.replace", - "edit.advanced_search", - SEP, - "edit.column_select", - "edit.snapshot", - SEP, - "edit.attach", - "form.clear", - SEP, - "app.preferences", -]; -const ZOOM: &[&str] = &[ACTUAL_SIZE, PAGE_LEVEL, FIT_WIDTH, FIT_HEIGHT, "view.fit_visible", SEP, ZOOM_IN, ZOOM_OUT, SEP, "view.marquee_zoom"]; -const NAVIGATION: &[&str] = &["view.focus_page_input", SEP, "view.previous_view", "view.next_view"]; -const DISPLAY: &[&str] = &[ - "view.layout.single", - "view.layout.two_up", - SEP, - "view.continuous", - "view.page_gaps", - "view.layout.cover", - SEP, - "view.fit_width_scrolling", - "view.fit_one_page", -]; -const THEMES: &[&str] = &["view.theme.system", "view.theme.light", "view.theme.dark"]; -const PANES: &[&str] = &["view.side_panel", "view.tools_pane", "view.split"]; -const PANE_COMMANDS: &[&str] = &["comment.list", "form.fields", "ui.dock.reset"]; -const MODES: &[&str] = &["view.full_screen", "view.read_mode", crate::viewer_prefs::TOGGLE]; -const PAGES: &[&str] = &[ - "page.organize", - SEP, - "page.insert_blank", - "page.insert", - "page.replace", - "page.extract", - "page.split", - "page.duplicate", - "page.delete", - SEP, - "page.rotate", - "page.rotate_ccw", - "page.rotate_dialog", - "page.reverse", - SEP, - "page.crop", - "page.boxes", - "page.number", - "page.properties", - SEP, - "bookmark.add", - "bookmark.from_structure", - "bookmark.from_text_styles", -]; -/// Sign ▸ Fill & Sign, with the short labels of the Fill & Sign toolbar. -const FILL: &[(&str, &str)] = &[ - ("sign.fill.text", "Add text"), - ("sign.fill.check", "Checkmark"), - ("sign.fill.cross", "Cross"), - ("sign.fill.dot", "Dot"), - ("sign.fill.line", "Line"), - ("sign.fill.date", "Date"), - ("sign.fill.signature", "Signature"), - ("sign.fill.initials", "Initials"), -]; -const SIGN: &[&str] = &[ - SEP, - "sign.fill.signature.change", - "sign.fill.initials.change", - "sign.fill.signature.remove", - "sign.fill.initials.remove", - SEP, - "sign.digital", - "sign.certify", - "sign.certify_invisible", - "form.add.signature", - SEP, - "sign.validate", - "sign.panel", -]; -const WINDOW: &[&str] = &["view.next_tab", "view.previous_tab"]; -const HELP: &[&str] = - &["help.shortcuts", SEP, "help.app_page", "help.github", "help.website", "help.discord", SEP, "help.check_updates", SEP, "help.about"]; - -/// Where the menu bar lists command `id`: the English titles of its menu and submenu, top menu first, -/// as [`MenuBar`] builds them. The shortcuts window groups its rows by them. `None` for a command -/// the bar lists by something other than its id (tools, documents, side panels) or not at all. -pub(crate) fn menu_path(id: &str) -> Option<&'static [&'static str]> { - const PLACES: &[(&[&str], &[&str])] = &[ - (FILE, &["File"]), - (CREATE, &["File", "Create"]), - (EXPORT, &["File", "Export"]), - (PROTECT, &["File", "Protect"]), - (EDIT, &["Edit"]), - (PAGES, &["Edit", "Pages"]), - (SIGN, &["Sign"]), - (WINDOW, &["Window"]), - (HELP, &["Help"]), - (ZOOM, &["View", "Zoom"]), - (&[ROTATE_CW, ROTATE_CCW], &["View", "Rotate view"]), - (NAVIGATION, &["View", "Page navigation"]), - (DISPLAY, &["View", "Page display"]), - (PANES, &["View"]), - (PANE_COMMANDS, &["View"]), - (MODES, &["View"]), - (THEMES, &["View", "Display theme"]), - (&["view.palette"], &["View"]), - ]; - if id == SEP { - return None; - } - if FILL.iter().any(|(fill, _)| *fill == id) { - return Some(&["Sign", "Fill & Sign"]); - } - PLACES.iter().find(|(ids, _)| ids.contains(&id)).map(|(_, path)| *path) -} - -/// A registry shortcut as a craft-keymap chord: `command` is ⌘ (Ctrl elsewhere) and `mac_ctrl` -/// the Control key on macOS. `None` for a key craft-keymap doesn't name. -pub(crate) fn chord(s: Shortcut) -> Option { - let key = Key::parse(s.key)?; - Some(Chord::new(Mods { cmd: s.command, ctrl: s.mac_ctrl, alt: false, shift: s.shift }, key)) -} - -fn extra(id: &str) -> Option<&'static (&'static str, &'static str, Option)> { - EXTRA.iter().find(|(e, ..)| *e == id) -} - -/// The English label of an item's command, for the bar's mnemonics. -fn english_label(command: &CommandRef) -> Option { - if let Some(spec) = commands::command(&command.id) { - return Some(spec.label.to_owned()); - } - if let Some((_, label, _)) = extra(&command.id) { - return Some((*label).to_owned()); - } - FILL.iter().find(|(id, _)| *id == command.id).map(|(_, label)| (*label).to_owned()) -} - -/// Puts the English names on the menu model, for the bar's mnemonics and the Help search. -fn name_in_english(nodes: &mut [Node]) { - for node in nodes { - match node { - Node::Item(item) => item.english = english_label(&item.command), - Node::Submenu { label, english, children, .. } => { - *english = TITLES.iter().find(|t| tl!(t) == label.as_str()).map(|t| (*t).to_owned()); - name_in_english(children); - } - _ => {} - } - } -} - -fn translate(english: &'static str) -> String { - tl!(english).to_owned() -} - -/// The layouts' own labels (About, Quit, Window…) through the app's translations. -pub(crate) fn layout_options() -> LayoutOptions<'static> { - LayoutOptions::new(APP_NAME).label(&translate) -} - -/// The platform the window's shell runs on, for menus drawn in the window. -pub(crate) fn shell_target(ctx: &egui::Context) -> Target { - Target::of_shell(&craft::ui::runtime::windows::WindowHost::of(ctx).shell()) -} - -/// Whether a dialog, a prompt or the command palette holds the window: the gate over the menu bar's -/// keys and the native menu. The command gate (`commands::catalog::command_input`) leaves the -/// palette out, so the palette lists and runs the commands as the window under it has them. -pub(crate) fn gated(app: &PdfCraftApp) -> bool { - app.modal_open() || app.palette_open -} - -/// Whether a text field has the keyboard: the one signal behind the Edit rows' state and the native -/// menu's gate. A text field only, as production's `text_edit_focused`: egui's keyboard focus alone is -/// also on an open menu's rows or a button, which would hand Edit ▸ Copy and Paste to them. -pub(crate) fn text_editing(ctx: &egui::Context) -> bool { - craft::ui::runtime::windows::WindowHost::of(ctx).typing() -} - -impl PdfCraftApp { - /// The app's menus for this frame, before the platform layout: every item's label, shortcut, - /// enabled and checked state follow the item's command (`commands::catalog::command_input`). A - /// modal dialog doesn't grey anything here; the command gate there does. - pub fn menu_bar(&self, ctx: &egui::Context) -> MenuBar { - let mac = crate::commands::mac_shortcuts(ctx); - let mut used: Vec<&str> = Vec::new(); - let list = |ids: &[&'static str], used: &mut Vec<&'static str>| -> Vec { - ids.iter() - .map(|&id| { - if id == SEP { - return Node::Separator; - } - used.push(id); - self.menu_item(id, None, mac) - }) - .collect() - }; - let mut file = { - let mut nodes = Vec::new(); - for node in list(FILE, &mut used) { - // Open Recent is the live recent list; Create, Export and Protect follow Combine, - // Optimize and Close. - let recent = matches!(&node, Node::Item(it) if it.command.id == "file.open_recent"); - if recent { - nodes.push(self.recent_menu(mac)); - continue; - } - let after = match &node { - Node::Item(it) => it.command.id.clone(), - _ => String::new(), - }; - nodes.push(node); - match after.as_str() { - "page.combine" => nodes.push(Node::submenu(tl!("Create"), list(CREATE, &mut used))), - "optimize.advanced" => { - nodes.push(Node::submenu(tl!("Export"), list(EXPORT, &mut used))); - nodes.push(Node::Separator); - nodes.push(Node::submenu(tl!("Protect"), list(PROTECT, &mut used))); - } - _ => {} - } - } - nodes - }; - // Edit ▸ Pages follows Select All. - let mut edit = Vec::new(); - for node in list(EDIT, &mut used) { - let select_all = matches!(&node, Node::Item(it) if it.command.id == SELECT_ALL); - edit.push(node); - if select_all { - edit.push(Node::submenu(tl!("Pages"), list(PAGES, &mut used))); - } - } - let mut sign = vec![Node::submenu( - tl!("Fill & Sign"), - FILL.iter() - .map(|&(id, label)| { - used.push(id); - self.menu_item(id, Some(tl!(label)), mac) - }) - .collect(), - )]; - sign.extend(list(SIGN, &mut used)); - let window = list(WINDOW, &mut used); - let mut help = list(HELP, &mut used); - let mut view = vec![ - Node::submenu(tl!("Zoom"), list(ZOOM, &mut used)), - Node::submenu(tl!("Rotate view"), list(&[ROTATE_CW, ROTATE_CCW], &mut used)), - Node::submenu(tl!("Page navigation"), list(NAVIGATION, &mut used)), - Node::submenu(tl!("Page display"), list(DISPLAY, &mut used)), - Node::Separator, - ]; - view.extend(list(PANES, &mut used)); - view.push(Node::submenu( - tl!("Side panels"), - PANELS - .iter() - .map(|(_, name, label)| { - Item::new(CommandRef::with_params(PANEL, serde_json::json!({ "panel": name })), tl!(label)).radio(false).into() - }) - .collect(), - )); - view.extend(list(PANE_COMMANDS, &mut used)); - view.push(Node::Separator); - view.extend(list(MODES, &mut used)); - view.push(Node::submenu(tl!("Display theme"), list(THEMES, &mut used))); - view.push(Node::Separator); - view.push(Node::submenu(tl!("Tools"), self.tools_menu(&used, mac))); - view.extend(list(&["view.palette"], &mut used)); - for nodes in [&mut file, &mut edit, &mut view, &mut sign, &mut help] { - craft::menu::tidy(nodes); - } - let mut bar = MenuBar::new(vec![ - Menu::new(tl!("File"), file).role(MenuRole::File), - Menu::new(tl!("Edit"), edit).role(MenuRole::Edit), - Menu::new(tl!("View"), view).role(MenuRole::View), - Menu::new(tl!("Sign"), sign), - Menu::new(tl!("Window"), window).role(MenuRole::Window), - Menu::new(tl!("Help"), help).role(MenuRole::Help), - ]) - .documents(self.menu_documents()); - for menu in &mut bar.menus { - menu.english = TITLES.iter().find(|t| tl!(t) == menu.title.as_str()).map(|t| (*t).to_owned()); - name_in_english(&mut menu.children); - } - bar.tag_item(&CommandRef::new("help.about"), ItemRole::About); - bar.tag_item(&CommandRef::new("app.preferences"), ItemRole::Settings); - bar.tag_item(&CommandRef::new(QUIT), ItemRole::Quit); - bar - } - - /// One item: a registry command with its live label (Undo names the edit) and shortcut, or a - /// menu-only one. Radio items get their kind here, their state from the command. - fn menu_item(&self, id: &'static str, label: Option<&str>, mac: bool) -> Node { - let (english, shortcut) = match commands::command(id) { - Some(spec) => { - let current = commands::current_label(spec, &self.session, self.active_ids().map(|(_, doc)| doc)); - (crate::i18n::menu_label(id, ¤t), spec.shortcut_for(mac).or((id == "edit.copy").then_some(crate::commands::COPY))) - } - None => match extra(id) { - Some((_, label, shortcut)) => (tl!(label).to_owned(), *shortcut), - None => (id.to_owned(), None), - }, - }; - let mut item = Item::new(id, label.map_or(english, str::to_owned)); - if let Some(c) = shortcut.and_then(chord) { - item = item.shortcut(c); - } - if matches!(id, "view.layout.single" | "view.layout.two_up") || THEMES.contains(&id) { - item = item.radio(false); - } - item.into() - } - - /// File ▸ Open Recent: the recent files, newest first, then Clear Recent Files. - fn recent_menu(&self, mac: bool) -> Node { - let mut items: Vec = self - .recent - .iter() - .enumerate() - .map(|(index, r)| Item::new(CommandRef::with_params("file.open_recent", serde_json::json!({ "index": index })), r.name.clone()).into()) - .collect(); - if items.is_empty() { - items.push(self.menu_item(NO_RECENT, None, mac)); - } else { - items.push(Node::Separator); - items.push(self.menu_item("file.clear_recent", Some(tl!("Clear Recent Files")), mac)); - } - let label = commands::command("file.open_recent").map_or("Open Recent", |c| c.label); - Node::submenu(crate::i18n::menu_label("file.open_recent", label), items).enabled(!self.recent.is_empty()) - } - - /// View ▸ Tools: the All tools groups, each a submenu of its ready tools that no other menu - /// lists, sections apart. - fn tools_menu(&self, used: &[&str], mac: bool) -> Vec { - TOOL_GROUPS - .iter() - .filter(|g| g.availability == Availability::Ready) - .map(|group| { - let mut nodes = Vec::new(); - let mut seen: Vec<&str> = Vec::new(); - for section in group.sections { - nodes.push(Node::Separator); - for tool in section.items.iter().filter(|t| t.availability == Availability::Ready) { - let actions: &[&'static str] = if tool.actions.is_empty() { std::slice::from_ref(&tool.command) } else { tool.actions }; - for &id in actions { - if commands::command(id).is_none() || used.contains(&id) || seen.contains(&id) { - continue; - } - seen.push(id); - let label = if tool.actions.is_empty() { Some(tl!(tool.label)) } else { None }; - nodes.push(self.menu_item(id, label, mac)); - } - } - } - Node::submenu(tl!(group.label), nodes) - }) - .collect() - } - - /// The open documents, in tab order, for the Window menu. - fn menu_documents(&self) -> Vec { - (0..self.views.len()) - .filter_map(|index| { - let name = crate::canvas::tab_label(self, index)?; - Some(Document::new(CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": index })), name).active(self.active == Some(index))) - }) - .collect() - } - - /// The native macOS bar's layout with the state AppKit shows: each item's enabled and checked - /// state is its command's, read from the board. The one reader of command state for the native - /// bar. - pub(crate) fn native_bar(&self, ctx: &egui::Context) -> Layout { - let mut layout = craft::menu::mac_layout(&self.menu_bar(ctx), &layout_options()); - let mut bar = craft::ui::contract::Tracked::new(std::mem::take(&mut layout.bar)); - craft::menu::apply_state(&mut bar, |command| { - let resolved = resolve(ctx, command.clone()); - ItemState::default().enabled(resolved.enabled).checked(resolved.checked) - }); - layout.bar = bar.into_inner(); - layout - } - - /// The menu bar drawn in the window (Windows, Linux, the web, and macOS when the native one - /// couldn't be installed), where the top bar starts. A chosen command fires through the board. - pub(crate) fn menu_bar_ui(&mut self, ui: &mut egui::Ui) { - let ctx = ui.ctx().clone(); - let target = shell_target(&ctx); - let bar = craft::menu::layout(&self.menu_bar(&ctx), target, &layout_options()).bar; - let modal = gated(self); - if *self.window_menu_bar != bar { - *self.window_menu_bar = bar; - } - craft::menu::MenuBarUi::new(&self.window_menu_bar).target(target).keyboard(!modal).icons(false).compact(true).show(ui); - } - - /// Install the native menu bar (macOS), once, from the eframe app creator. `false` when - /// AppKit refused it: the in-window bar stays. - #[cfg(target_os = "macos")] - pub fn install_native_menu(&mut self, ctx: &egui::Context) -> bool { - crate::i18n::set_current(crate::i18n::Lang::from_pref(&self.language)); - let bar = self.native_bar(ctx).bar; - // The Window menu lists the open documents itself, so AppKit's window list stays off. - self.native_menu = craft::menu::mac::install_with(ctx, &bar, craft::menu::mac::MacOptions::default().window_list(false)); - self.native_menu.is_some() - } -} - -/// The native menu's per-frame turn: its gate, its clicks fired as commands, then its bar brought in -/// step with the app, last, after this frame's changes. -pub(crate) fn frame(app: &mut PdfCraftApp, ctx: &egui::Context) { - if app.native_menu.is_none() { - return; - } - let gate = Gate::default().modal(gated(app)).text_editing(text_editing(ctx)); - let clicks = app.native_menu.as_mut().map(|native| { - // The menu events since the last frame, before the gate as craft-menu asks: clicks wait - // for `take_clicks`, key equivalents become the key presses they were. - native.poll(ctx); - native.set_gate(gate); - native.take_clicks(ctx) - }); - for command in clicks.unwrap_or_default() { - fire(ctx, command, FireSource::Menu); - } - // The layout is built every frame from the commands' state; keyed on its bar, the native menus are laid out - // again only when that changed (or a menu event flipped an item). - let layout = app.native_bar(ctx); - let key = layout.bar.clone(); - if let Some(native) = app.native_menu.as_mut() { - for clash in native.sync_with(&key, move || layout) { - log::info!("menu shortcut {:?} kept by {} over {} ({})", clash.shortcut, clash.command.id, clash.system, clash.resolution); - } - } -} - -/// A command's `{"index": n}` parameter. -pub(crate) fn param_index(command: &CommandRef) -> Option { - command.params.get("index").and_then(serde_json::Value::as_u64).and_then(|i| usize::try_from(i).ok()) -} - -/// The side panel a [`PANEL`] command names. -pub(crate) fn panel(command: &CommandRef) -> Option { - let name = command.params.get("panel").and_then(serde_json::Value::as_str)?; - PANELS.iter().find(|(_, n, _)| *n == name).map(|(p, ..)| *p) -} - -#[cfg(test)] -mod tests { - use craft::menu::Builtin; - - use super::*; - - const PDF: &[u8] = include_bytes!("../tests/data/form.pdf"); - - fn app(docs: &[&str]) -> (PdfCraftApp, egui::Context) { - let mut app = PdfCraftApp::for_unit_tests(); - app.set_option(&egui::Context::default(), "language", "en").unwrap(); - for name in docs { - app.open_bytes(&egui::Context::default(), name, None, PDF.to_vec()).unwrap(); - } - (app, egui::Context::default()) - } - - fn linux(app: &PdfCraftApp, ctx: &egui::Context) -> MenuBar { - craft::menu::layout(&app.menu_bar(ctx), Target::Linux, &layout_options()).bar - } - - fn item<'b>(bar: &'b MenuBar, command: &CommandRef) -> &'b Item { - bar.find(command).unwrap_or_else(|| panic!("{} is in the menus", command.key())) - } - - #[test] - fn every_menu_command_is_listed_once_with_its_shortcut() { - let (app, ctx) = app(&["a.pdf"]); - let bar = linux(&app, &ctx); - let items = bar.items(); - let mut keys: Vec = items.iter().map(|it| it.command.key()).collect(); - keys.sort(); - let count = keys.len(); - keys.dedup(); - assert_eq!(keys.len(), count, "no command is listed twice"); - for spec in commands::COMMANDS.iter().filter(|s| s.menu.is_some()) { - if spec.id == "file.open_recent" { - continue; // A submenu of the recent files. - } - let it = item(&bar, &CommandRef::new(spec.id)); - let shortcut = spec.shortcut_for(crate::commands::mac_shortcuts(&ctx)).or((spec.id == "edit.copy").then_some(crate::commands::COPY)); - assert_eq!(it.shortcut, shortcut.and_then(chord), "{} has its registry shortcut", spec.id); - } - // Every item runs a registry command or one of the menu's own. - for it in items { - let id = it.command.id.as_str(); - assert!( - commands::command(id).is_some() || extra(id).is_some() || [PANEL, DOCUMENT].contains(&id) || Builtin::of(&it.command).is_some(), - "{id} runs something" - ); - } - } - - #[test] - fn recent_files_and_open_documents_are_listed_once_each() { - let (mut app, ctx) = app(&["a.pdf", "b.pdf"]); - app.recent = ["one.pdf", "two.pdf"].map(|n| crate::RecentFile { name: n.into(), path: format!("/nowhere/{n}"), pages: 1, size: 0 }).into(); - let bar = linux(&app, &ctx); - for (i, name) in ["one.pdf", "two.pdf"].into_iter().enumerate() { - assert_eq!(item(&bar, &CommandRef::with_params("file.open_recent", serde_json::json!({ "index": i }))).label, name); - } - let window = bar.menu(MenuRole::Window).unwrap(); - let documents: Vec<&str> = window - .children - .iter() - .filter_map(|n| match n { - Node::Item(it) if it.command.id == DOCUMENT => Some(it.label.as_str()), - _ => None, - }) - .collect(); - assert_eq!(documents, ["a.pdf", "b.pdf"], "each open document once, in tab order"); - // The macOS layout lists them once too. - let mac = craft::menu::mac_layout(&app.menu_bar(&ctx), &layout_options()).bar; - let listed = mac.items().iter().filter(|it| it.command.id == DOCUMENT).count(); - assert_eq!(listed, 2); - app.recent.clear(); - let bar = linux(&app, &ctx); - assert!(bar.find(&CommandRef::new(NO_RECENT)).is_some(), "an empty list shows a placeholder"); - assert!(bar.find(&CommandRef::new("file.clear_recent")).is_none()); - } -} +//! The menus: one definition ([`PdfCraftApp::menu_bar`]) for the native macOS menu bar and the +//! in-window bar on Windows, Linux and the web, laid out for each platform by craft-menu. +//! +//! Items run registry commands (`pdfcraft_engine::commands`) by id, with the registry's label and +//! shortcut, so a menu click and its shortcut run the same command. A few items have menu-only +//! ids: the zoom keys the document view handles itself, the side panel choices, the clipboard +//! keys, the recent files and the open documents. Each is a command of the app's catalog +//! (`commands::catalog`), fired once per click, whichever bar it came from. + +use craft::keymap::{Key, Mods}; +use craft::menu::{Chord, CommandRef, Document, Gate, Item, ItemRole, ItemState, Layout, LayoutOptions, Menu, MenuBar, MenuRole, Node, Target}; +use craft::ui::runtime::commands::{FireSource, fire, resolve}; +use pdfcraft_engine::catalog::{Availability, TOOL_GROUPS}; +use pdfcraft_engine::commands::{self, Shortcut}; + +use crate::{PdfCraftApp, RightPanel}; + +pub(super) mod tab_context; + +/// The app's name in the menus the layouts write (About, Hide, Quit). +pub(crate) const APP_NAME: &str = "PdfCraft"; + +/// Menu-only commands. The registry's commands keep their own ids. +pub(crate) const CUT: &str = "edit.cut"; +pub(crate) const PASTE: &str = "edit.paste"; +pub(crate) const DELETE: &str = "edit.delete"; +pub(crate) const SELECT_ALL: &str = "edit.select_all"; +pub(crate) const QUIT: &str = "app.quit"; +pub(crate) const NO_RECENT: &str = "file.no_recent"; +/// An open document in the Window menu, `{"index": n}` in the tab strip. +pub(crate) const DOCUMENT: &str = "window.document"; +/// A side panel, `{"panel": name}` ([`PANELS`]). +pub(crate) const PANEL: &str = "view.panel"; +const ACTUAL_SIZE: &str = "view.zoom.actual_size"; +const PAGE_LEVEL: &str = "view.zoom.page_level"; +const FIT_WIDTH: &str = "view.zoom.fit_width"; +const FIT_HEIGHT: &str = "view.zoom.fit_height"; +const ZOOM_IN: &str = "view.zoom.in"; +const ZOOM_OUT: &str = "view.zoom.out"; +const ROTATE_CW: &str = "view.rotate.cw"; +const ROTATE_CCW: &str = "view.rotate.ccw"; + +/// The menu-only items: id, English label and the shortcut shown (the keys stay with the view). The +/// zoom and rotate ids are registry commands; only Fit to height has no registry row. +pub(crate) const EXTRA: &[(&str, &str, Option)] = &[ + (QUIT, "Quit", Some(Shortcut::cmd("Q"))), + (CUT, "Cut", Some(Shortcut::cmd("X"))), + (PASTE, "Paste", Some(Shortcut::cmd("V"))), + (DELETE, "Delete", Some(Shortcut { command: false, shift: false, mac_ctrl: false, key: "Delete" })), + (SELECT_ALL, "Select all", Some(crate::commands::SELECT_ALL)), + (NO_RECENT, "No recent files", None), + (FIT_HEIGHT, "Fit to height", None), +]; + +/// View ▸ Side panels: the panel, its id in [`PANEL`] commands and its English label. +pub(crate) const PANELS: &[(RightPanel, &str, &str)] = &[ + (RightPanel::Comments, "comments", "Comments"), + (RightPanel::Bookmarks, "bookmarks", "Bookmarks"), + (RightPanel::Pages, "pages", "Pages"), + (RightPanel::Fields, "fields", "Fields"), + (RightPanel::Layers, "layers", "Layers"), + (RightPanel::Attachments, "attachments", "Attachments"), + (RightPanel::Signatures, "signatures", "Signatures"), + (RightPanel::Accessibility, "accessibility", "Accessibility Checker"), + (RightPanel::Tags, "tags", "Tags"), + (RightPanel::Search, "search", "Search"), + (RightPanel::Compare, "compare", "Compare"), +]; + +/// The English titles of the menus and submenus, for the bar's mnemonics in languages whose +/// labels have no ASCII letter. +const TITLES: &[&str] = &[ + "File", + "Edit", + "View", + "Pages", + "Sign", + "Window", + "Help", + "Open Recent", + "Create", + "Export", + "Protect", + "Zoom", + "Rotate view", + "Page navigation", + "Page display", + "Side panels", + "Display theme", + "Tools", + "Fill & Sign", +]; + +/// Separator. +const SEP: &str = "---"; + +const FILE: &[&str] = &[ + "create.blank", + "file.open", + "file.open_recent", + "file.pin_folder", + SEP, + "page.combine", + SEP, + "file.save", + "file.save_as", + "file.revert", + SEP, + "file.close", + "file.close_all", + SEP, + "optimize.reduce", + "optimize.advanced", + SEP, + "file.properties", + "file.word_count", + SEP, + "print.dialog", + QUIT, +]; +const CREATE: &[&str] = &["create.file", "create.multiple", "create.multiple_separate", "create.images", "create.clipboard"]; +const EXPORT: &[&str] = &["export.docx", "export.pptx", "export.rtf", "export.html", "export.text", SEP, "export.image", "export.all_images"]; +const PROTECT: &[&str] = &["protect.password", "protect.remove", "protect.unlock", SEP, "protect.properties"]; +const EDIT: &[&str] = &[ + "edit.undo", + "edit.redo", + SEP, + CUT, + "edit.copy", + PASTE, + DELETE, + SEP, + "comment.copy", + "comment.paste", + SEP, + SELECT_ALL, + SEP, + "edit.find", + "edit.replace", + "edit.advanced_search", + SEP, + "edit.column_select", + "edit.snapshot", + SEP, + "edit.attach", + "form.clear", + SEP, + "app.preferences", +]; +const ZOOM: &[&str] = &[ACTUAL_SIZE, PAGE_LEVEL, FIT_WIDTH, FIT_HEIGHT, "view.fit_visible", SEP, ZOOM_IN, ZOOM_OUT, SEP, "view.marquee_zoom"]; +const NAVIGATION: &[&str] = &["view.focus_page_input", SEP, "view.previous_view", "view.next_view"]; +const DISPLAY: &[&str] = &[ + "view.layout.single", + "view.layout.two_up", + SEP, + "view.continuous", + "view.page_gaps", + "view.layout.cover", + SEP, + "view.fit_width_scrolling", + "view.fit_one_page", +]; +const THEMES: &[&str] = &["view.theme.system", "view.theme.light", "view.theme.dark"]; +const PANES: &[&str] = &["view.side_panel", "view.tools_pane", "view.split"]; +const PANE_COMMANDS: &[&str] = &["comment.list", "form.fields", "ui.dock.reset"]; +const MODES: &[&str] = &["view.full_screen", "view.read_mode", crate::viewer_prefs::TOGGLE]; +const PAGES: &[&str] = &[ + "page.organize", + SEP, + "page.insert_blank", + "page.insert", + "page.replace", + "page.extract", + "page.split", + "page.duplicate", + "page.delete", + SEP, + "page.rotate", + "page.rotate_ccw", + "page.rotate_dialog", + "page.reverse", + SEP, + "page.crop", + "page.boxes", + "page.number", + "page.properties", + SEP, + "bookmark.add", + "bookmark.from_structure", + "bookmark.from_text_styles", +]; +/// Sign ▸ Fill & Sign, with the short labels of the Fill & Sign toolbar. +const FILL: &[(&str, &str)] = &[ + ("sign.fill.text", "Add text"), + ("sign.fill.check", "Checkmark"), + ("sign.fill.cross", "Cross"), + ("sign.fill.dot", "Dot"), + ("sign.fill.line", "Line"), + ("sign.fill.date", "Date"), + ("sign.fill.signature", "Signature"), + ("sign.fill.initials", "Initials"), +]; +const SIGN: &[&str] = &[ + SEP, + "sign.fill.signature.change", + "sign.fill.initials.change", + "sign.fill.signature.remove", + "sign.fill.initials.remove", + SEP, + "sign.digital", + "sign.certify", + "sign.certify_invisible", + "form.add.signature", + SEP, + "sign.validate", + "sign.panel", +]; +const WINDOW: &[&str] = &["view.next_tab", "view.previous_tab"]; +const HELP: &[&str] = + &["help.shortcuts", SEP, "help.app_page", "help.github", "help.website", "help.discord", SEP, "help.check_updates", SEP, "help.about"]; + +/// Where the menu bar lists command `id`: the English titles of its menu and submenu, top menu first, +/// as [`MenuBar`] builds them. The shortcuts window groups its rows by them. `None` for a command +/// the bar lists by something other than its id (tools, documents, side panels) or not at all. +pub(crate) fn menu_path(id: &str) -> Option<&'static [&'static str]> { + const PLACES: &[(&[&str], &[&str])] = &[ + (FILE, &["File"]), + (CREATE, &["File", "Create"]), + (EXPORT, &["File", "Export"]), + (PROTECT, &["File", "Protect"]), + (EDIT, &["Edit"]), + (PAGES, &["Edit", "Pages"]), + (SIGN, &["Sign"]), + (WINDOW, &["Window"]), + (HELP, &["Help"]), + (ZOOM, &["View", "Zoom"]), + (&[ROTATE_CW, ROTATE_CCW], &["View", "Rotate view"]), + (NAVIGATION, &["View", "Page navigation"]), + (DISPLAY, &["View", "Page display"]), + (PANES, &["View"]), + (PANE_COMMANDS, &["View"]), + (MODES, &["View"]), + (THEMES, &["View", "Display theme"]), + (&["view.palette"], &["View"]), + ]; + if id == SEP { + return None; + } + if FILL.iter().any(|(fill, _)| *fill == id) { + return Some(&["Sign", "Fill & Sign"]); + } + PLACES.iter().find(|(ids, _)| ids.contains(&id)).map(|(_, path)| *path) +} + +/// A registry shortcut as a craft-keymap chord: `command` is ⌘ (Ctrl elsewhere) and `mac_ctrl` +/// the Control key on macOS. `None` for a key craft-keymap doesn't name. +pub(crate) fn chord(s: Shortcut) -> Option { + let key = Key::parse(s.key)?; + Some(Chord::new(Mods { cmd: s.command, ctrl: s.mac_ctrl, alt: false, shift: s.shift }, key)) +} + +fn extra(id: &str) -> Option<&'static (&'static str, &'static str, Option)> { + EXTRA.iter().find(|(e, ..)| *e == id) +} + +/// The English label of an item's command, for the bar's mnemonics. +fn english_label(command: &CommandRef) -> Option { + if let Some(spec) = commands::command(&command.id) { + return Some(spec.label.to_owned()); + } + if let Some((_, label, _)) = extra(&command.id) { + return Some((*label).to_owned()); + } + FILL.iter().find(|(id, _)| *id == command.id).map(|(_, label)| (*label).to_owned()) +} + +/// Puts the English names on the menu model, for the bar's mnemonics and the Help search. +fn name_in_english(nodes: &mut [Node]) { + for node in nodes { + match node { + Node::Item(item) => item.english = english_label(&item.command), + Node::Submenu { label, english, children, .. } => { + *english = TITLES.iter().find(|t| tl!(t) == label.as_str()).map(|t| (*t).to_owned()); + name_in_english(children); + } + _ => {} + } + } +} + +fn translate(english: &'static str) -> String { + tl!(english).to_owned() +} + +/// The layouts' own labels (About, Quit, Window…) through the app's translations. +pub(crate) fn layout_options() -> LayoutOptions<'static> { + LayoutOptions::new(APP_NAME).label(&translate) +} + +/// The platform the window's shell runs on, for menus drawn in the window. +pub(crate) fn shell_target(ctx: &egui::Context) -> Target { + Target::of_shell(&craft::ui::runtime::windows::WindowHost::of(ctx).shell()) +} + +/// Whether a dialog, a prompt or the command palette holds the window: the gate over the menu bar's +/// keys and the native menu. The command gate (`commands::catalog::command_input`) leaves the +/// palette out, so the palette lists and runs the commands as the window under it has them. +pub(crate) fn gated(app: &PdfCraftApp) -> bool { + app.modal_open() || app.palette_open +} + +/// Whether a text field has the keyboard: the one signal behind the Edit rows' state and the native +/// menu's gate. A text field only, as production's `text_edit_focused`: egui's keyboard focus alone is +/// also on an open menu's rows or a button, which would hand Edit ▸ Copy and Paste to them. +pub(crate) fn text_editing(ctx: &egui::Context) -> bool { + craft::ui::runtime::windows::WindowHost::of(ctx).typing() +} + +impl PdfCraftApp { + /// The app's menus for this frame, before the platform layout: every item's label, shortcut, + /// enabled and checked state follow the item's command (`commands::catalog::command_input`). A + /// modal dialog doesn't grey anything here; the command gate there does. + pub fn menu_bar(&self, ctx: &egui::Context) -> MenuBar { + let mac = crate::commands::mac_shortcuts(ctx); + let mut used: Vec<&str> = Vec::new(); + let list = |ids: &[&'static str], used: &mut Vec<&'static str>| -> Vec { + ids.iter() + .map(|&id| { + if id == SEP { + return Node::Separator; + } + used.push(id); + self.menu_item(id, None, mac) + }) + .collect() + }; + let mut file = { + let mut nodes = Vec::new(); + for node in list(FILE, &mut used) { + // Open Recent is the live recent list; Create, Export and Protect follow Combine, + // Optimize and Close. + let recent = matches!(&node, Node::Item(it) if it.command.id == "file.open_recent"); + if recent { + nodes.push(self.recent_menu(mac)); + continue; + } + let after = match &node { + Node::Item(it) => it.command.id.clone(), + _ => String::new(), + }; + nodes.push(node); + match after.as_str() { + "page.combine" => nodes.push(Node::submenu(tl!("Create"), list(CREATE, &mut used))), + "optimize.advanced" => { + nodes.push(Node::submenu(tl!("Export"), list(EXPORT, &mut used))); + nodes.push(Node::Separator); + nodes.push(Node::submenu(tl!("Protect"), list(PROTECT, &mut used))); + } + _ => {} + } + } + nodes + }; + // Edit ▸ Pages follows Select All. + let mut edit = Vec::new(); + for node in list(EDIT, &mut used) { + let select_all = matches!(&node, Node::Item(it) if it.command.id == SELECT_ALL); + edit.push(node); + if select_all { + edit.push(Node::submenu(tl!("Pages"), list(PAGES, &mut used))); + } + } + let mut sign = vec![Node::submenu( + tl!("Fill & Sign"), + FILL.iter() + .map(|&(id, label)| { + used.push(id); + self.menu_item(id, Some(tl!(label)), mac) + }) + .collect(), + )]; + sign.extend(list(SIGN, &mut used)); + let window = list(WINDOW, &mut used); + let mut help = list(HELP, &mut used); + let mut view = vec![ + Node::submenu(tl!("Zoom"), list(ZOOM, &mut used)), + Node::submenu(tl!("Rotate view"), list(&[ROTATE_CW, ROTATE_CCW], &mut used)), + Node::submenu(tl!("Page navigation"), list(NAVIGATION, &mut used)), + Node::submenu(tl!("Page display"), list(DISPLAY, &mut used)), + Node::Separator, + ]; + view.extend(list(PANES, &mut used)); + view.push(Node::submenu( + tl!("Side panels"), + PANELS + .iter() + .map(|(_, name, label)| { + Item::new(CommandRef::with_params(PANEL, serde_json::json!({ "panel": name })), tl!(label)).radio(false).into() + }) + .collect(), + )); + view.extend(list(PANE_COMMANDS, &mut used)); + view.push(Node::Separator); + view.extend(list(MODES, &mut used)); + view.push(Node::submenu(tl!("Display theme"), list(THEMES, &mut used))); + view.push(Node::Separator); + view.push(Node::submenu(tl!("Tools"), self.tools_menu(&used, mac))); + view.extend(list(&["view.palette"], &mut used)); + for nodes in [&mut file, &mut edit, &mut view, &mut sign, &mut help] { + craft::menu::tidy(nodes); + } + let mut bar = MenuBar::new(vec![ + Menu::new(tl!("File"), file).role(MenuRole::File), + Menu::new(tl!("Edit"), edit).role(MenuRole::Edit), + Menu::new(tl!("View"), view).role(MenuRole::View), + Menu::new(tl!("Sign"), sign), + Menu::new(tl!("Window"), window).role(MenuRole::Window), + Menu::new(tl!("Help"), help).role(MenuRole::Help), + ]) + .documents(self.menu_documents()); + for menu in &mut bar.menus { + menu.english = TITLES.iter().find(|t| tl!(t) == menu.title.as_str()).map(|t| (*t).to_owned()); + name_in_english(&mut menu.children); + } + bar.tag_item(&CommandRef::new("help.about"), ItemRole::About); + bar.tag_item(&CommandRef::new("app.preferences"), ItemRole::Settings); + bar.tag_item(&CommandRef::new(QUIT), ItemRole::Quit); + bar + } + + /// One item: a registry command with its live label (Undo names the edit) and shortcut, or a + /// menu-only one. Radio items get their kind here, their state from the command. + fn menu_item(&self, id: &'static str, label: Option<&str>, mac: bool) -> Node { + let (english, shortcut) = match commands::command(id) { + Some(spec) => { + let current = commands::current_label(spec, &self.session, self.active_ids().map(|(_, doc)| doc)); + (crate::i18n::menu_label(id, ¤t), spec.shortcut_for(mac).or((id == "edit.copy").then_some(crate::commands::COPY))) + } + None => match extra(id) { + Some((_, label, shortcut)) => (tl!(label).to_owned(), *shortcut), + None => (id.to_owned(), None), + }, + }; + let mut item = Item::new(id, label.map_or(english, str::to_owned)); + if let Some(c) = shortcut.and_then(chord) { + item = item.shortcut(c); + } + if matches!(id, "view.layout.single" | "view.layout.two_up") || THEMES.contains(&id) { + item = item.radio(false); + } + item.into() + } + + /// File ▸ Open Recent: the recent files, newest first, then Clear Recent Files. + fn recent_menu(&self, mac: bool) -> Node { + let mut items: Vec = self + .recent + .iter() + .enumerate() + .map(|(index, r)| Item::new(CommandRef::with_params("file.open_recent", serde_json::json!({ "index": index })), r.name.clone()).into()) + .collect(); + if items.is_empty() { + items.push(self.menu_item(NO_RECENT, None, mac)); + } else { + items.push(Node::Separator); + items.push(self.menu_item("file.clear_recent", Some(tl!("Clear Recent Files")), mac)); + } + let label = commands::command("file.open_recent").map_or("Open Recent", |c| c.label); + Node::submenu(crate::i18n::menu_label("file.open_recent", label), items).enabled(!self.recent.is_empty()) + } + + /// View ▸ Tools: the All tools groups, each a submenu of its ready tools that no other menu + /// lists, sections apart. + fn tools_menu(&self, used: &[&str], mac: bool) -> Vec { + TOOL_GROUPS + .iter() + .filter(|g| g.availability == Availability::Ready) + .map(|group| { + let mut nodes = Vec::new(); + let mut seen: Vec<&str> = Vec::new(); + for section in group.sections { + nodes.push(Node::Separator); + for tool in section.items.iter().filter(|t| t.availability == Availability::Ready) { + let actions: &[&'static str] = if tool.actions.is_empty() { std::slice::from_ref(&tool.command) } else { tool.actions }; + for &id in actions { + if commands::command(id).is_none() || used.contains(&id) || seen.contains(&id) { + continue; + } + seen.push(id); + let label = if tool.actions.is_empty() { Some(tl!(tool.label)) } else { None }; + nodes.push(self.menu_item(id, label, mac)); + } + } + } + Node::submenu(tl!(group.label), nodes) + }) + .collect() + } + + /// The open documents, in tab order, for the Window menu. + fn menu_documents(&self) -> Vec { + (0..self.views.len()) + .filter_map(|index| { + let name = crate::canvas::tab_label(self, index)?; + Some(Document::new(CommandRef::with_params(DOCUMENT, serde_json::json!({ "index": index })), name).active(self.active == Some(index))) + }) + .collect() + } + + /// The native macOS bar's layout with the state AppKit shows: each item's enabled and checked + /// state is its command's, read from the board. The one reader of command state for the native + /// bar. + pub(crate) fn native_bar(&self, ctx: &egui::Context) -> Layout { + let mut layout = craft::menu::mac_layout(&self.menu_bar(ctx), &layout_options()); + let mut bar = craft::ui::contract::Tracked::new(std::mem::take(&mut layout.bar)); + craft::menu::apply_state(&mut bar, |command| { + let resolved = resolve(ctx, command.clone()); + ItemState::default().enabled(resolved.enabled).checked(resolved.checked) + }); + layout.bar = bar.into_inner(); + layout + } + + /// The menu bar drawn in the window (Windows, Linux, the web, and macOS when the native one + /// couldn't be installed), where the top bar starts. A chosen command fires through the board. + pub(crate) fn menu_bar_ui(&mut self, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); + let target = shell_target(&ctx); + let bar = craft::menu::layout(&self.menu_bar(&ctx), target, &layout_options()).bar; + let modal = gated(self); + if *self.window_menu_bar != bar { + *self.window_menu_bar = bar; + } + craft::menu::MenuBarUi::new(&self.window_menu_bar).target(target).keyboard(!modal).icons(false).compact(true).show(ui); + } + + /// Install the native menu bar (macOS), once, from the eframe app creator. `false` when + /// AppKit refused it: the in-window bar stays. + #[cfg(target_os = "macos")] + pub fn install_native_menu(&mut self, ctx: &egui::Context) -> bool { + crate::i18n::set_current(crate::i18n::Lang::from_pref(&self.language)); + let bar = self.native_bar(ctx).bar; + // The Window menu lists the open documents itself, so AppKit's window list stays off. + self.native_menu = craft::menu::mac::install_with(ctx, &bar, craft::menu::mac::MacOptions::default().window_list(false)); + self.native_menu.is_some() + } +} + +/// The native menu's per-frame turn: its gate, its clicks fired as commands, then its bar brought in +/// step with the app, last, after this frame's changes. +pub(crate) fn frame(app: &mut PdfCraftApp, ctx: &egui::Context) { + if app.native_menu.is_none() { + return; + } + let gate = Gate::default().modal(gated(app)).text_editing(text_editing(ctx)); + let clicks = app.native_menu.as_mut().map(|native| { + // The menu events since the last frame, before the gate as craft-menu asks: clicks wait + // for `take_clicks`, key equivalents become the key presses they were. + native.poll(ctx); + native.set_gate(gate); + native.take_clicks(ctx) + }); + for command in clicks.unwrap_or_default() { + fire(ctx, command, FireSource::Menu); + } + // The layout is built every frame from the commands' state; keyed on its bar, the native menus are laid out + // again only when that changed (or a menu event flipped an item). + let layout = app.native_bar(ctx); + let key = layout.bar.clone(); + if let Some(native) = app.native_menu.as_mut() { + for clash in native.sync_with(&key, move || layout) { + log::info!("menu shortcut {:?} kept by {} over {} ({})", clash.shortcut, clash.command.id, clash.system, clash.resolution); + } + } +} + +/// A command's `{"index": n}` parameter. +pub(crate) fn param_index(command: &CommandRef) -> Option { + command.params.get("index").and_then(serde_json::Value::as_u64).and_then(|i| usize::try_from(i).ok()) +} + +/// The side panel a [`PANEL`] command names. +pub(crate) fn panel(command: &CommandRef) -> Option { + let name = command.params.get("panel").and_then(serde_json::Value::as_str)?; + PANELS.iter().find(|(_, n, _)| *n == name).map(|(p, ..)| *p) +} + +#[cfg(test)] +mod tests { + use craft::menu::Builtin; + + use super::*; + + const PDF: &[u8] = include_bytes!("../tests/data/form.pdf"); + + fn app(docs: &[&str]) -> (PdfCraftApp, egui::Context) { + let mut app = PdfCraftApp::for_unit_tests(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + for name in docs { + app.open_bytes(&egui::Context::default(), name, None, PDF.to_vec()).unwrap(); + } + (app, egui::Context::default()) + } + + fn linux(app: &PdfCraftApp, ctx: &egui::Context) -> MenuBar { + craft::menu::layout(&app.menu_bar(ctx), Target::Linux, &layout_options()).bar + } + + fn item<'b>(bar: &'b MenuBar, command: &CommandRef) -> &'b Item { + bar.find(command).unwrap_or_else(|| panic!("{} is in the menus", command.key())) + } + + #[test] + fn every_menu_command_is_listed_once_with_its_shortcut() { + let (app, ctx) = app(&["a.pdf"]); + let bar = linux(&app, &ctx); + let items = bar.items(); + let mut keys: Vec = items.iter().map(|it| it.command.key()).collect(); + keys.sort(); + let count = keys.len(); + keys.dedup(); + assert_eq!(keys.len(), count, "no command is listed twice"); + for spec in commands::COMMANDS.iter().filter(|s| s.menu.is_some()) { + if spec.id == "file.open_recent" { + continue; // A submenu of the recent files. + } + let it = item(&bar, &CommandRef::new(spec.id)); + let shortcut = spec.shortcut_for(crate::commands::mac_shortcuts(&ctx)).or((spec.id == "edit.copy").then_some(crate::commands::COPY)); + assert_eq!(it.shortcut, shortcut.and_then(chord), "{} has its registry shortcut", spec.id); + } + // Every item runs a registry command or one of the menu's own. + for it in items { + let id = it.command.id.as_str(); + assert!( + commands::command(id).is_some() || extra(id).is_some() || [PANEL, DOCUMENT].contains(&id) || Builtin::of(&it.command).is_some(), + "{id} runs something" + ); + } + } + + #[test] + fn recent_files_and_open_documents_are_listed_once_each() { + let (mut app, ctx) = app(&["a.pdf", "b.pdf"]); + app.recent = ["one.pdf", "two.pdf"].map(|n| crate::RecentFile { name: n.into(), path: format!("/nowhere/{n}"), pages: 1, size: 0 }).into(); + let bar = linux(&app, &ctx); + for (i, name) in ["one.pdf", "two.pdf"].into_iter().enumerate() { + assert_eq!(item(&bar, &CommandRef::with_params("file.open_recent", serde_json::json!({ "index": i }))).label, name); + } + let window = bar.menu(MenuRole::Window).unwrap(); + let documents: Vec<&str> = window + .children + .iter() + .filter_map(|n| match n { + Node::Item(it) if it.command.id == DOCUMENT => Some(it.label.as_str()), + _ => None, + }) + .collect(); + assert_eq!(documents, ["a.pdf", "b.pdf"], "each open document once, in tab order"); + // The macOS layout lists them once too. + let mac = craft::menu::mac_layout(&app.menu_bar(&ctx), &layout_options()).bar; + let listed = mac.items().iter().filter(|it| it.command.id == DOCUMENT).count(); + assert_eq!(listed, 2); + app.recent.clear(); + let bar = linux(&app, &ctx); + assert!(bar.find(&CommandRef::new(NO_RECENT)).is_some(), "an empty list shows a placeholder"); + assert!(bar.find(&CommandRef::new("file.clear_recent")).is_none()); + } +} diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 2ba24ba2f6..1c8455c21b 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1069,10 +1069,10 @@ fn preferences_menu_and_shortcut_allow_switching_interface_languages() { let (mut h, c) = harness(); ok(&mut h, &c, "ui.set", json!({ "key": "language", "value": "ja" })); // The menu bar's Edit menu holds Preferences on Windows and Linux. On macOS the in-window bar - // takes the Mac layout (`Target::current()`), which moves it to the app menu as Settings…. + // takes the shell layout (`Target::of_shell`), which moves it to the app menu as Settings…. // Titles and rows carry their mnemonic ("編集(E)", "環境設定(P)…"), so match by the start of // the label. - let (menu, preferences) = if cfg!(target_os = "macos") { + let (menu, preferences) = if h.ctx.os() == egui::os::OperatingSystem::Mac { let ja = pdfcraft_ui_egui::i18n::Lang::from_code("ja").unwrap(); ("PdfCraft", pdfcraft_ui_egui::i18n::tr(ja, "Settings…").trim_end_matches('…')) } else { @@ -1148,6 +1148,8 @@ fn japanese_dialogs_errors_and_custom_action_names() { ("sign", "署名用のデジタル ID を設定"), ] { ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": dialog})); + // Hosted dialogs publish their access tree on a subsequent frame. + settle(&mut h); let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); assert!(found["count"].as_u64().unwrap() > 0, "{dialog}: {found}"); } diff --git a/crates/ui-egui/tests/it/organize_drag.rs b/crates/ui-egui/tests/it/organize_drag.rs index fd71c033d0..5e22eae290 100644 --- a/crates/ui-egui/tests/it/organize_drag.rs +++ b/crates/ui-egui/tests/it/organize_drag.rs @@ -87,8 +87,8 @@ fn page_texts(app: &PdfCraftApp) -> Vec { } /// Organize copies pages as a file manager copies files: Option on macOS, Ctrl elsewhere. -fn copy_modifier(_h: &Harness<'static, PdfCraftApp>, copying: bool) -> Modifiers { - match (copying, cfg!(target_os = "macos")) { +fn copy_modifier(h: &Harness<'static, PdfCraftApp>, copying: bool) -> Modifiers { + match (copying, h.ctx.os() == egui::os::OperatingSystem::Mac) { (false, _) => Modifiers::NONE, (true, true) => Modifiers::ALT, // Ctrl as a keyboard sends it off macOS: the command key too. From e437e20eaf24c80c0d8e27475bdbd37525bb500b Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 03:43:15 +0100 Subject: [PATCH 3/6] Align control input OS and isolate translated dialog checks --- crates/ui-egui/tests/it/control.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 1c8455c21b..5aabeb2791 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1147,6 +1147,10 @@ fn japanese_dialogs_errors_and_custom_action_names() { ("compare-files", "ファイルを比較"), ("sign", "署名用のデジタル ID を設定"), ] { + // Close the previous modal before opening another; a hosted dialog must not be + // inspected through the JavaScript console or another modal's access boundary. + ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": "none"})); + settle(&mut h); ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": dialog})); // Hosted dialogs publish their access tree on a subsequent frame. settle(&mut h); @@ -1266,6 +1270,16 @@ fn commands_keys_and_typing() { #[test] fn ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page() { let (mut h, c) = harness_pages(3); + // The control protocol normalizes modifier flags for the host OS. Exercise that same + // OS in the shell rather than pairing macOS protocol input with the Linux test shell. + let os = if cfg!(target_os = "macos") { + egui::os::OperatingSystem::Mac + } else if cfg!(target_os = "windows") { + egui::os::OperatingSystem::Windows + } else { + egui::os::OperatingSystem::Nix + }; + craft::ui::testing::windows::set_os(&h.ctx, os); ok(&mut h, &c, "ui.set", json!({ "key": "tool", "value": "organize" })); h.run_steps(3); // The grid cell of a page: the node labelled exactly "Page N" (the checkbox says "Select page N"). From 0d4597ec5c71a4c14fcb21dc9a54cb771cb6994c Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 05:06:45 +0100 Subject: [PATCH 4/6] test: pass the host OS type to shell fixture --- crates/ui-egui/tests/it/control.rs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 5aabeb2791..1c7c616cfa 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1272,14 +1272,7 @@ fn ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page() { let (mut h, c) = harness_pages(3); // The control protocol normalizes modifier flags for the host OS. Exercise that same // OS in the shell rather than pairing macOS protocol input with the Linux test shell. - let os = if cfg!(target_os = "macos") { - egui::os::OperatingSystem::Mac - } else if cfg!(target_os = "windows") { - egui::os::OperatingSystem::Windows - } else { - egui::os::OperatingSystem::Nix - }; - craft::ui::testing::windows::set_os(&h.ctx, os); + craft::ui::testing::windows::set_os(&h.ctx, craft::host::target::Os::current()); ok(&mut h, &c, "ui.set", json!({ "key": "tool", "value": "organize" })); h.run_steps(3); // The grid cell of a page: the node labelled exactly "Page N" (the checkbox says "Select page N"). From 9ddaae3fae79ad63f53050569db41c789384ac32 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 06:01:27 +0100 Subject: [PATCH 5/6] test(ui): share the default app fixture across harnesses --- crates/ui-egui/tests/page_shadows.rs | 20 ++------------------ crates/ui-egui/tests/perf.rs | 20 ++------------------ crates/ui-egui/tests/play.rs | 20 ++------------------ crates/ui-egui/tests/support/mod.rs | 18 ++++++++++++++++++ 4 files changed, 24 insertions(+), 54 deletions(-) create mode 100644 crates/ui-egui/tests/support/mod.rs diff --git a/crates/ui-egui/tests/page_shadows.rs b/crates/ui-egui/tests/page_shadows.rs index b80b84ad56..0e419d2631 100644 --- a/crates/ui-egui/tests/page_shadows.rs +++ b/crates/ui-egui/tests/page_shadows.rs @@ -218,24 +218,8 @@ fn page_shadow_preference_round_trips_and_ignores_invalid_settings() { assert_eq!(enabled(&app), Some(true)); } -/// An app on the default host with test services: no wake-ups, no autosave folder, the GitHub update -/// source, a fresh intake and an inline watch (as `tests/it/control.rs`' `new_app`). -fn new_app() -> pdfcraft_ui_egui::PdfCraftApp { - use craft::host::{AppInfo, Host, Wake}; - use craft::platform::clipboard::{Clipboard, SystemClipboard}; - use craft::platform::open::FileIntake; - use craft::platform::watch::FileWatch; - let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" }).build(); - let services = pdfcraft_ui_egui::AppServices::new( - Wake::none(), - Clipboard::new(SystemClipboard::new()), - None, - None, - FileIntake::new(Wake::none()).0, - FileWatch::new(Wake::none()).inline(), - ); - pdfcraft_ui_egui::PdfCraftApp::with_host(std::sync::Arc::new(host), services) -} +mod support; +use support::new_app; /// The app's command and option entry points with the harness's own context (L-208). trait AppHarness { diff --git a/crates/ui-egui/tests/perf.rs b/crates/ui-egui/tests/perf.rs index 0ddf43766c..1c2089d807 100644 --- a/crates/ui-egui/tests/perf.rs +++ b/crates/ui-egui/tests/perf.rs @@ -199,24 +199,8 @@ fn panels_build_only_the_rows_in_view() { } } -/// An app on the default host with test services: no wake-ups, no autosave folder, the GitHub update -/// source, a fresh intake and an inline watch (as `tests/it/control.rs`' `new_app`). -fn new_app() -> pdfcraft_ui_egui::PdfCraftApp { - use craft::host::{AppInfo, Host, Wake}; - use craft::platform::clipboard::{Clipboard, SystemClipboard}; - use craft::platform::open::FileIntake; - use craft::platform::watch::FileWatch; - let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" }).build(); - let services = pdfcraft_ui_egui::AppServices::new( - Wake::none(), - Clipboard::new(SystemClipboard::new()), - None, - None, - FileIntake::new(Wake::none()).0, - FileWatch::new(Wake::none()).inline(), - ); - pdfcraft_ui_egui::PdfCraftApp::with_host(std::sync::Arc::new(host), services) -} +mod support; +use support::new_app; /// Installs the framework runtime on a harness context, as `tests/it/support`'s `install_runtime` (L-227). fn install_runtime(ctx: &egui::Context) { diff --git a/crates/ui-egui/tests/play.rs b/crates/ui-egui/tests/play.rs index 3fcc00284a..332126907b 100644 --- a/crates/ui-egui/tests/play.rs +++ b/crates/ui-egui/tests/play.rs @@ -374,24 +374,8 @@ fn letter_pdf(content: &str) -> Vec { out } -/// An app on the default host with test services: no wake-ups, no autosave folder, the GitHub update -/// source, a fresh intake and an inline watch (as `tests/it/control.rs`' `new_app`). -fn new_app() -> pdfcraft_ui_egui::PdfCraftApp { - use craft::host::{AppInfo, Host, Wake}; - use craft::platform::clipboard::{Clipboard, SystemClipboard}; - use craft::platform::open::FileIntake; - use craft::platform::watch::FileWatch; - let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" }).build(); - let services = pdfcraft_ui_egui::AppServices::new( - Wake::none(), - Clipboard::new(SystemClipboard::new()), - None, - None, - FileIntake::new(Wake::none()).0, - FileWatch::new(Wake::none()).inline(), - ); - pdfcraft_ui_egui::PdfCraftApp::with_host(std::sync::Arc::new(host), services) -} +mod support; +use support::new_app; /// The app's command and option entry points with the harness's own context (L-208). trait AppHarness { diff --git a/crates/ui-egui/tests/support/mod.rs b/crates/ui-egui/tests/support/mod.rs new file mode 100644 index 0000000000..19f24354aa --- /dev/null +++ b/crates/ui-egui/tests/support/mod.rs @@ -0,0 +1,18 @@ +/// An app on the default host with test services: no wake-ups, no autosave folder, the GitHub update +/// source, a fresh intake and an inline watch (as `tests/it/control.rs`' `new_app`). +pub fn new_app() -> pdfcraft_ui_egui::PdfCraftApp { + use craft::host::{AppInfo, Host, Wake}; + use craft::platform::clipboard::{Clipboard, SystemClipboard}; + use craft::platform::open::FileIntake; + use craft::platform::watch::FileWatch; + let host = Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" }).build(); + let services = pdfcraft_ui_egui::AppServices::new( + Wake::none(), + Clipboard::new(SystemClipboard::new()), + None, + None, + FileIntake::new(Wake::none()).0, + FileWatch::new(Wake::none()).inline(), + ); + pdfcraft_ui_egui::PdfCraftApp::with_host(std::sync::Arc::new(host), services) +} From b7ac143e7c3651bd63b48a912769252a987fcb84 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 08:44:19 +0100 Subject: [PATCH 6/6] test(control): close the inline console before inspecting compare --- crates/ui-egui/tests/it/control.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 1c7c616cfa..06ca77e77e 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1156,6 +1156,14 @@ fn japanese_dialogs_errors_and_custom_action_names() { settle(&mut h); let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); assert!(found["count"].as_u64().unwrap() > 0, "{dialog}: {found}"); + if dialog == "js-console" { + // The console is an inline window outside the hosted dialog stack. Close it + // through its translated button before inspecting the next hosted dialog. + ok(&mut h, &c, "ui.click", json!({"label": "閉じる"})); + settle(&mut h); + let closed = ok(&mut h, &c, "ui.inspect", json!({"query": label})); + assert_eq!(closed["count"], 0, "the console must close before the next dialog: {closed}"); + } } ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": "none"})); let ctx_h = h.ctx.clone();