diff --git a/Cargo.lock b/Cargo.lock index 59a753b..d3356e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -209,7 +209,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "wl-clipboard-rs", "x11rb", ] @@ -599,7 +599,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.61.2", + "windows-sys 0.60.2", "winx", ] @@ -795,15 +795,28 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-dialogs" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "block2 0.6.2", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "raw-window-handle", + "rfd", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "fixed_decimal", "icu_decimal", @@ -823,10 +836,44 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-keymap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "egui", + "serde", + "serde_json", +] + +[[package]] +name = "craft-menu" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "craft-keymap", + "craft-quit", + "egui", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + +[[package]] +name = "craft-quit" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "dispatch2", + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f8f8829cc7be65d466d687dae381d1ca60e31242#f8f8829cc7be65d466d687dae381d1ca60e31242" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -870,6 +917,17 @@ dependencies = [ "zip 9.5.0", ] +[[package]] +name = "craft-window" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +dependencies = [ + "egui", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "wayland-client", +] + [[package]] name = "crc32fast" version = "1.5.3" @@ -879,6 +937,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-deque" version = "0.8.8" @@ -1325,7 +1392,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2346,6 +2413,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyboard-types" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d" +dependencies = [ + "bitflags 2.13.2", + "serde", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -2483,7 +2560,9 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" name = "materialcraft" version = "0.1.3" dependencies = [ + "craft-menu", "craft-update", + "craft-window", "eframe", "egui", "image", @@ -2626,8 +2705,12 @@ name = "materialcraft-ui-egui" version = "0.1.3" dependencies = [ "base64 0.22.1", + "craft-dialogs", + "craft-keymap", + "craft-quit", "craft-ui", "craft-update", + "craft-window", "eframe", "egui", "egui-phosphor", @@ -2741,6 +2824,24 @@ dependencies = [ "pxfm", ] +[[package]] +name = "muda" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4340e89c178916e62879c5c36b7f699019369be413e496178a6983ce91b8bc03" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "png", + "thiserror 2.0.21", + "windows-sys 0.60.2", +] + [[package]] name = "naga" version = "30.0.1" @@ -3253,7 +3354,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3928,7 +4029,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3995,7 +4096,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -4335,7 +4436,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4455,7 +4556,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -4773,7 +4874,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -5373,7 +5474,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 1f5470e..b8065fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,9 +83,18 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"] cap-std = "4" getrandom = "0.3" # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, -# MIT OR Apache-2.0, pinned to one rev (the one TextureCraft pins). +# MIT OR Apache-2.0, every craft-libs crate pinned to one rev. egui_kittest = "0.37" -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "f8f8829cc7be65d466d687dae381d1ca60e31242", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } +# Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0. +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +# Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0. +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +# The platform quit and the macOS Quit menu item: storytold/craft-libs, MIT OR Apache-2.0. +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +# Who draws the window frame, and an app-drawn strip as the title bar: storytold/craft-libs, MIT OR Apache-2.0. +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } # Release checks and self-updates for the desktop app: storytold/craft-libs, MIT OR Apache-2.0. craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index 7017800..3815c01 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -22,9 +22,16 @@ log = { workspace = true } # A start that never opens a window says why in an error dialog (src/start_failure.rs). rfd = { workspace = true } +# The window frame's choice applies before the window exists. +craft-window = { workspace = true, features = ["egui"] } + # The Windows update helper is a copy of this program started with `--finish-update`. [target.'cfg(windows)'.dependencies] craft-update = { workspace = true } +# The macOS app menu whose Quit asks before unsaved work is lost. +[target.'cfg(target_os = "macos")'.dependencies] +craft-menu = { workspace = true } + [build-dependencies] winresource = "0.1" diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 10a4184..672c499 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -10,6 +10,11 @@ mod start_failure; use materialcraft_engine::Session; use materialcraft_ui_egui::MaterialCraftApp; +/// The window's size when it opens, in points. +const DEFAULT_SIZE: [f32; 2] = [1600.0, 960.0]; +/// The smallest size the window can be resized to, in points. +const MIN_SIZE: [f32; 2] = [960.0, 600.0]; + const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.materialcraft.png"); fn version() -> String { @@ -97,7 +102,11 @@ fn main() { prev(info); })); let session = initial_session(&args); - let mut viewport = egui::ViewportBuilder::default().with_title("MaterialCraft").with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); + let window_frame = craft_window::Choice::probe(craft_window::Prefix::new("MATERIALCRAFT")).into_frame(); + let mut viewport = craft_window::decorate( + egui::ViewportBuilder::default().with_title("MaterialCraft").with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE), + &window_frame, + ); if let Some(i) = icon() { viewport = viewport.with_icon(i); } @@ -112,6 +121,12 @@ fn main() { options, Box::new(move |cc| { let mut app = MaterialCraftApp::new(cc, session); + app.window_layout = window_frame.layout().cloned(); + // Called from the creator: winit installs its default menu before this runs. On error winit's menu stays, whose Quit does not ask + #[cfg(target_os = "macos")] + if let Err(error) = craft_menu::mac::install_app_menu(&cc.egui_ctx, "MaterialCraft") { + log::warn!("could not install the app menu: {error}"); + } app.set_startup_update_check(startup_update_check); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 7bf2aab..71ab2a3 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -14,6 +14,7 @@ materialcraft-render = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } +craft-keymap = { workspace = true, features = ["egui"] } egui-phosphor = { version = "0.14", features = ["regular"] } serde = { workspace = true } serde_json = { workspace = true } @@ -24,8 +25,10 @@ zip = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] sys-locale = "0.3" -rfd = { workspace = true } craft-update = { workspace = true } +craft-dialogs = { workspace = true } +craft-quit = { workspace = true, features = ["egui"] } +craft-window = { workspace = true, features = ["egui"] } # Floating panels open as OS windows. craft-ui = { workspace = true, features = ["native-windows"] } @@ -41,4 +44,4 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] eframe = { workspace = true, features = ["x11"] } # Offscreen renders of the real UI (tests/snapshot.rs). -egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] } +egui_kittest = { workspace = true, features = ["wgpu", "snapshot", "eframe"] } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 7cd2bf7..4febae5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -119,7 +119,8 @@ fn modifiers(v: &Value) -> Modifiers { for k in v.get("modifiers").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { match k.to_ascii_lowercase().as_str() { "ctrl" | "control" => { - m.ctrl = true; + // A shortcut's Ctrl is Command on macOS, where the real Control key is a different chord + m.ctrl = !cfg!(target_os = "macos"); m.command = true; } "shift" => m.shift = true, diff --git a/crates/ui-egui/src/graph/edit_menu.rs b/crates/ui-egui/src/graph/edit_menu.rs index b419bc8..8738c9a 100644 --- a/crates/ui-egui/src/graph/edit_menu.rs +++ b/crates/ui-egui/src/graph/edit_menu.rs @@ -3,7 +3,7 @@ use egui::Ui; pub(crate) fn button(ui: &mut Ui, label: &str, command: &str, enabled: bool) -> bool { let mut button = egui::Button::new(tr(label)); - if let Some(shortcut) = menus::shortcut_of(command) { + if let Some(shortcut) = menus::shortcut_of(command).map(|text| menus::shortcut_label(ui.ctx(), text)) { button = button.shortcut_text(shortcut); } let clicked = ui.add_enabled(enabled, button).clicked(); diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index 8588328..65ce447 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -155,7 +155,7 @@ fn embedded_graphs_open_with_control_e_but_not_double_click() { assert_eq!(frames.app.session.selection, vec![node]); assert_eq!(frames.app.session.view2d.node, Some(node)); - let control = Modifiers::CTRL | Modifiers::COMMAND; + let control = Modifiers::COMMAND; for pressed in [true, false] { frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed, repeat: false, modifiers: control }], control); } @@ -181,7 +181,7 @@ fn selected_pattern_subgraph_opens_with_control_e() { let original = frames.app.session.pkg.clone(); let history = frames.app.session.history(); - let control = Modifiers::CTRL | Modifiers::COMMAND; + let control = Modifiers::COMMAND; frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed: true, repeat: false, modifiers: control }], control); frames.run(vec![Event::Key { key: egui::Key::E, physical_key: Some(egui::Key::E), pressed: false, repeat: false, modifiers: control }], control); assert_eq!(frames.app.pattern_editor.as_ref().map(|editor| editor.node), Some(node)); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a4370b0..aa933f6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -33,12 +33,16 @@ pub mod widgets; pub mod windows; mod material_craft_app; +#[cfg(not(target_arch = "wasm32"))] +mod native_dialogs; pub mod pattern; mod toast; #[cfg(not(target_arch = "wasm32"))] pub mod updates_ui; mod user_directory; mod value_editor; +#[cfg(not(target_arch = "wasm32"))] +mod window_controls; /// This app as the updater knows it: its release repository, and the icon and accent color the /// update prompt shows diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 1998304..d7010c6 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -43,6 +43,18 @@ pub struct MaterialCraftApp { /// Release checks and the update prompt (desktop only) #[cfg(not(target_arch = "wasm32"))] pub(crate) updates_rt: crate::updates_ui::Runtime, + /// Native file dialogs (desktop only) + #[cfg(not(target_arch = "wasm32"))] + pub(crate) dialogs: crate::native_dialogs::Dialogs, + /// The held action waiting for the Save dialog the unsaved-changes prompt opened + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) awaiting_save: Option, + /// The window buttons to draw when the app draws the window frame; `None` while the desktop draws it (desktop only) + #[cfg(not(target_arch = "wasm32"))] + pub window_layout: Option, + /// Keyboard shortcuts and their dispatch + pub(crate) keymap: craft_keymap::Keymap, + pub(crate) dispatcher: craft_keymap::egui::Dispatcher, /// Fallback fonts for Arabic pub fonts: fonts::UiFonts, /// The icon font is installed (it takes effect on the frame after `set_fonts`) @@ -58,6 +70,10 @@ impl MaterialCraftApp { i18n::set_language(&app.ui.prefs.language); app.fonts_ready = true; app.ui.windows.home = app.ui.prefs.show_home; + #[cfg(not(target_arch = "wasm32"))] + { + app.dialogs = crate::native_dialogs::attached(&cc.egui_ctx); + } app } @@ -93,6 +109,14 @@ impl MaterialCraftApp { styled: None, #[cfg(not(target_arch = "wasm32"))] updates_rt: crate::updates_ui::Runtime::default(), + #[cfg(not(target_arch = "wasm32"))] + dialogs: crate::native_dialogs::unattached(), + awaiting_save: None, + #[cfg(not(target_arch = "wasm32"))] + window_layout: None, + keymap: menus::keymap(craft_keymap::Platform::current()), + // The web build sends a key press with each clipboard event, and the option lets that press run its command + dispatcher: craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(cfg!(target_arch = "wasm32")), fonts: fonts::UiFonts::default(), fonts_ready: false, ui_gesture_active: false, @@ -265,15 +289,29 @@ impl eframe::App for MaterialCraftApp { } fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + #[cfg(not(target_arch = "wasm32"))] + self.step_then(ctx, craft_quit::on_close_request); + #[cfg(target_arch = "wasm32")] self.step(ctx); } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.draw(ui); + #[cfg(not(target_arch = "wasm32"))] + self.dialogs.show_pending(Some(&*frame)); + #[cfg(target_arch = "wasm32")] + let _ = frame; } } impl MaterialCraftApp { + /// [`Self::step`], then the platform's close handling, which sees a close `step` canceled + #[cfg(not(target_arch = "wasm32"))] + fn step_then(&mut self, ctx: &egui::Context, close: impl FnOnce(&egui::Context) -> bool) { + self.step(ctx); + close(ctx); + } + /// Per-frame logic before drawing: styles, the control channel, cooking, shortcuts pub fn step(&mut self, ctx: &egui::Context) { if !self.fonts_ready { @@ -304,6 +342,8 @@ impl MaterialCraftApp { crate::unsaved::handle_close(self, ctx); control::poll(self, ctx); web_files::poll(self); + #[cfg(not(target_arch = "wasm32"))] + crate::native_dialogs::poll(self); for f in ctx.input(|i| i.raw.dropped_files.clone()) { web_files::dropped(self, ctx, &f); } @@ -336,6 +376,10 @@ impl MaterialCraftApp { toolbar::status_bar(self, ui); egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui)); windows::show(self, &ctx); + #[cfg(not(target_arch = "wasm32"))] + if self.window_layout.is_some() { + crate::window_controls::resize_zones(ui); + } let gesture_active = ctx.input(|input| input.pointer.any_down()) || ctx.egui_wants_keyboard_input(); if !gesture_active && (self.ui_gesture_active || ctx.input(|input| input.pointer.any_released())) { self.session.finish_edit(); diff --git a/crates/ui-egui/src/material_craft_app.test.rs b/crates/ui-egui/src/material_craft_app.test.rs index 853f133..4aaf0da 100644 --- a/crates/ui-egui/src/material_craft_app.test.rs +++ b/crates/ui-egui/src/material_craft_app.test.rs @@ -14,6 +14,41 @@ mod lib_tests { } } +#[cfg(all(test, not(target_arch = "wasm32")))] +mod close_order_tests { + use crate::MaterialCraftApp; + use crate::state::UiState; + + fn close_frame(app: &mut MaterialCraftApp) -> bool { + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut canceled = false; + ctx.run_ui(input, |ui| { + app.step_then(ui.ctx(), |ctx| { + canceled = ctx.viewport(|viewport| viewport.commands.contains(&egui::ViewportCommand::CancelClose)); + false + }); + }) + .textures_delta + .clear(); + canceled + } + + #[test] + fn the_quit_hook_runs_after_the_close_guard() { + let mut held = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + held.fonts_ready = true; + held.session.modified = true; + assert!(close_frame(&mut held), "the guard canceled the close before the hook runs"); + + let mut clean = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + clean.fonts_ready = true; + clean.session.modified = false; + assert!(!close_frame(&mut clean), "nothing to hold: the hook sees a close to take over"); + } +} + #[cfg(test)] mod unsaved_state_tests { use crate::unsaved::{Choice, Guarded, Step, answer, guard}; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 34fcdcd..d0e76d7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1,6 +1,6 @@ //! Menu actions and shortcuts share stable command ids -use egui::{Key, KeyboardShortcut, Modifiers}; +use craft_keymap::{Active, Bindable, Binding, Chord, Keymap, Platform, Scope, Scopes}; use serde_json::Value; use crate::MaterialCraftApp; @@ -199,19 +199,38 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) { } } -/// Parse "Ctrl+Shift+E" style shortcuts -pub fn parse_shortcut(s: &str) -> Option { - let mut mods = Modifiers::NONE; - let mut key = None; - for part in s.split('+') { - match part { - "Ctrl" | "Cmd" => mods |= Modifiers::COMMAND, - "Shift" => mods |= Modifiers::SHIFT, - "Alt" => mods |= Modifiers::ALT, - k => key = Key::from_name(k), +/// Parse "Ctrl+Shift+E" style shortcuts; `Ctrl` in these texts is Command on macOS +pub fn parse_shortcut(s: &str) -> Option { + Chord::parse(&s.replace("Ctrl", "Cmd")).ok() +} + +/// The text a shortcut shows on this platform: "Cmd+Shift+E" on macOS, where the interface fonts lack the ⇧ and ⌘ glyphs, and "Ctrl+Shift+E" elsewhere +pub fn shortcut_label(ctx: &egui::Context, text: &str) -> String { + let platform = craft_keymap::egui::platform(ctx); + parse_shortcut(text).map_or_else(|| text.to_string(), |chord| if platform.is_mac() { chord.to_string() } else { chord.display(platform) }) +} + +/// Every shortcut in effect: the catalog's, then the engine commands' not listed there +pub(crate) fn shortcut_table() -> Vec<(&'static str, &'static str)> { + let mut table: Vec<(&'static str, &'static str)> = CATALOG.iter().filter_map(|i| Some((i.id, i.shortcut?))).collect(); + for c in materialcraft_engine::command_specs() { + if table.iter().any(|(id, _)| *id == c.id) { + continue; + } + if let Some(shortcut) = c.shortcut { + table.push((c.id, shortcut)); } } - key.map(|k| KeyboardShortcut::new(mods, k)) + table +} + +/// The keymap the table's shortcuts dispatch through +pub(crate) fn keymap(platform: Platform) -> Keymap { + let catalog = shortcut_table() + .into_iter() + .filter_map(|(id, text)| Some(Bindable::new(id, id, Scope::app()).with_default(Binding::new(parse_shortcut(text)?)))) + .collect(); + Keymap::new(catalog, Scopes::new(), platform) } /// The shortcut text shown for `id` (the catalog's, else the engine command's) @@ -222,8 +241,18 @@ pub fn shortcut_of(id: &str) -> Option<&'static str> { pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { let tk = Tokens::get(ui.ctx()); egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| { + #[cfg(not(target_arch = "wasm32"))] + let window_layout = app.window_layout.clone(); + #[cfg(not(target_arch = "wasm32"))] + if window_layout.is_some() { + craft_window::title_bar::empty_area(ui, ui.max_rect()); + } egui::MenuBar::new().ui(ui, |ui| { let ctx = ui.ctx().clone(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(layout) = &window_layout { + crate::window_controls::buttons(ui, &ctx, &layout.left); + } for top in TOP { ui.menu_button(tr(top), |ui| { ui.set_min_width(220.0); @@ -250,6 +279,14 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) { } }); } + #[cfg(not(target_arch = "wasm32"))] + if let Some(layout) = window_layout.as_ref().filter(|layout| !layout.right.is_empty()) { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut right = layout.right.clone(); + right.reverse(); + crate::window_controls::buttons(ui, &ctx, &right); + }); + } }); }); } @@ -258,7 +295,7 @@ fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, let on = enabled(app, item.id); let mut b = egui::Button::new(tr(item.label)); if let Some(sc) = item.shortcut { - b = b.shortcut_text(sc); + b = b.shortcut_text(shortcut_label(ctx, sc)); } let checked = match item.id { "ui.view.graph" => Some(true), @@ -309,33 +346,26 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { crate::graph::wire_actions::shortcuts(app, ctx); - let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect(); - for c in materialcraft_engine::command_specs() { - if table.iter().any(|(id, _)| *id == c.id) { - continue; - } - if let Some(sc) = c.shortcut.and_then(parse_shortcut) { - table.push((c.id, sc)); - } + let platform = craft_keymap::egui::platform(ctx); + if app.keymap.platform() != platform { + app.keymap = keymap(platform); } - - // Longer chords take priority - table.sort_by_key(|(_, sc)| std::cmp::Reverse(sc.modifiers.ctrl as u8 + sc.modifiers.shift as u8 + sc.modifiers.alt as u8 + sc.modifiers.command as u8)); - let mut fire: Vec<&str> = Vec::new(); - ctx.input_mut(|i| { - for (id, sc) in &table { - if i.consume_shortcut(sc) { - fire.push(*id); - } - } + // Selected label text copies through egui's Copy and Cut events, which a hit would remove + let label_selected = label_text_selected(ctx); + let hits = ctx.input_mut(|i| { + app.dispatcher.dispatch_filtered(i, &app.keymap, &Active::NONE, |hit| !(label_selected && matches!(hit.command.id.as_str(), "edit.copy" | "edit.cut"))) }); - for id in fire { - if crate::graph::editor_actions::shortcut_enabled(app, id) { - invoke(app, ctx, id); + for hit in hits { + if crate::graph::editor_actions::shortcut_enabled(app, &hit.command.id) { + invoke(app, ctx, &hit.command.id); } } } +fn label_text_selected(ctx: &egui::Context) -> bool { + ctx.with_plugin::(|state| state.has_selection()).unwrap_or(false) +} + /// Menu items for `ui.menu.list` pub fn list(app: &MaterialCraftApp) -> Value { Value::Array( @@ -367,4 +397,199 @@ mod tests { let live = CATALOG.iter().filter(|i| i.label != "-" && implemented(i.id)).count(); assert!(live + 1 >= CATALOG.iter().filter(|i| i.label != "-").count()); } + + #[test] + fn every_shortcut_is_a_chord_and_the_catalog_wins_a_shared_chord() { + for platform in [Platform::Mac, Platform::Windows, Platform::Linux] { + let map = keymap(platform); + let mut owners = std::collections::BTreeMap::new(); + for (id, text) in shortcut_table() { + let chord = parse_shortcut(text).unwrap_or_else(|| panic!("{id}: {text}")); + owners.entry(chord.to_string()).or_insert((id, chord)); + } + for (id, chord) in owners.into_values() { + assert_eq!(map.lookup(&chord, false, &Active::NONE), craft_keymap::Lookup::Run(id.into()), "{chord}"); + } + } + } + + #[test] + fn ctrl_in_a_shortcut_text_is_command_on_macos() { + let chord = parse_shortcut("Ctrl+Shift+E").unwrap(); + assert_eq!(chord.display(Platform::Mac), "⇧⌘E"); + assert_eq!(chord.display(Platform::Windows), "Ctrl+Shift+E"); + } + + fn dispatched(key: egui::Key, modifiers: egui::Modifiers, app: &mut MaterialCraftApp) { + let ctx = egui::Context::default(); + let input = + egui::RawInput { events: vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], ..Default::default() }; + ctx.run_ui(input, |ui| shortcuts(app, ui.ctx())).textures_delta.clear(); + } + + fn app() -> MaterialCraftApp { + MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()) + } + + #[test] + fn a_shortcut_needs_exactly_its_modifiers() { + let mut exact = app(); + dispatched(egui::Key::N, egui::Modifiers::COMMAND, &mut exact); + assert!(exact.ui.windows.new_graph, "Ctrl+N is bound to New graph"); + + let mut extra = app(); + dispatched(egui::Key::N, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, &mut extra); + assert!(!extra.ui.windows.new_graph, "Ctrl+Shift+N is not bound"); + } + + #[test] + fn a_longer_chord_runs_its_own_command() { + let mut app = app(); + dispatched(egui::Key::E, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, &mut app); + assert!(app.ui.windows.export, "Ctrl+Shift+E opens Export outputs"); + } + + #[test] + fn a_scripted_ctrl_key_runs_its_shortcut() { + let mut app = app(); + let ctx = egui::Context::default(); + let frames = crate::control::parse_events(&[serde_json::json!({"type": "key", "key": "N", "modifiers": ["ctrl"]})]).unwrap(); + for frame in frames { + let input = egui::RawInput { events: frame.events, ..Default::default() }; + ctx.run_ui(input, |ui| shortcuts(&mut app, ui.ctx())).textures_delta.clear(); + } + assert!(app.ui.windows.new_graph); + } + + #[test] + fn a_held_key_repeats_its_shortcut() { + let mut app = app(); + let ctx = egui::Context::default(); + // egui marks the second press of a key that was never released as a repeat + for _ in 0..2 { + app.ui.windows.new_graph = false; + let input = egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::N, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }], + ..Default::default() + }; + ctx.run_ui(input, |ui| shortcuts(&mut app, ui.ctx())).textures_delta.clear(); + assert!(app.ui.windows.new_graph, "a held key runs the shortcut again"); + } + } + + #[test] + fn shortcuts_wait_while_a_text_field_has_the_keyboard() { + let mut app = app(); + let ctx = egui::Context::default(); + let field = egui::Id::unique("field"); + ctx.run_ui(egui::RawInput::default(), |ui| ui.memory_mut(|m| m.request_focus(field))).textures_delta.clear(); + let input = egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::N, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }], + ..Default::default() + }; + ctx.run_ui(input, |ui| { + let mut text = String::new(); + ui.add(egui::TextEdit::singleline(&mut text).id(field)); + shortcuts(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(!app.ui.windows.new_graph); + } + + fn press_c(events_after: Vec) -> egui::RawInput { + let mut events = vec![ + egui::Event::ModifiersChanged(egui::Modifiers::COMMAND), + egui::Event::Key { key: egui::Key::C, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }, + ]; + events.extend(events_after); + egui::RawInput { events, ..Default::default() } + } + + /// Run a frame with `input` around a selectable label, and report whether egui's Copy event is still there after `shortcuts` + fn copy_event_kept(app: &mut MaterialCraftApp, ctx: &egui::Context, input: egui::RawInput) -> bool { + let mut kept = false; + ctx.run_ui(input, |ui| { + shortcuts(app, ui.ctx()); + kept = ui.input(|i| i.events.contains(&egui::Event::Copy)); + ui.label("selectable text"); + }) + .textures_delta + .clear(); + kept + } + + fn select_label_text(ctx: &egui::Context) { + let frame = |events: Vec| { + let mut rect = egui::Rect::NOTHING; + ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| rect = ui.label("selectable text").rect).textures_delta.clear(); + rect + }; + let rect = frame(Vec::new()); + let (from, to) = (rect.left_center() + egui::vec2(1.0, 0.0), rect.right_center() - egui::vec2(1.0, 0.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(vec![egui::Event::PointerMoved(from)]); + frame(vec![button(from, true)]); + frame(vec![egui::Event::PointerMoved(to)]); + frame(vec![button(to, false)]); + frame(Vec::new()); + } + + #[test] + fn the_desktops_copy_event_stays_with_egui() { + let mut app = app(); + app.run("edit.selectAll", serde_json::json!({})); + let ctx = egui::Context::default(); + let kept = copy_event_kept(&mut app, &ctx, egui::RawInput { events: vec![egui::Event::Copy], ..Default::default() }); + assert!(kept, "selected label text copies through this event"); + assert!(app.session.clipboard.is_none(), "the desktop's Copy event does not run edit.copy"); + } + + #[test] + fn a_web_copy_press_runs_edit_copy() { + let mut app = app(); + app.dispatcher = craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true); + app.run("edit.selectAll", serde_json::json!({})); + let ctx = egui::Context::default(); + copy_event_kept(&mut app, &ctx, press_c(vec![egui::Event::Copy])); + assert!(app.session.clipboard.is_some(), "the web build's press runs edit.copy"); + } + + #[test] + fn selected_label_text_keeps_its_copy_on_the_web() { + let mut app = app(); + app.dispatcher = craft_keymap::egui::Dispatcher::new().with_repeat(true).with_clipboard_events(true); + app.run("edit.selectAll", serde_json::json!({})); + let ctx = egui::Context::default(); + select_label_text(&ctx); + assert!(label_text_selected(&ctx)); + assert!(copy_event_kept(&mut app, &ctx, press_c(vec![egui::Event::Copy])), "egui copies the label's text from this event"); + assert!(app.session.clipboard.is_none(), "the press does not also copy the selected nodes"); + } + + #[test] + fn the_interface_fonts_draw_every_shortcut_label() { + for os in [egui::os::OperatingSystem::Mac, egui::os::OperatingSystem::Windows, egui::os::OperatingSystem::Nix] { + let ctx = egui::Context::default(); + ctx.set_os(os); + crate::theme::install(&ctx); + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + for (id, text) in shortcut_table() { + let label = shortcut_label(&ctx, text); + for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] { + let font = egui::FontId::new(13.0, family.clone()); + assert!(ctx.fonts_mut(|fonts| fonts.has_glyphs(&font, &label)), "{id}: {label} in {family:?}"); + } + } + } + } + + #[test] + fn macos_labels_name_the_command_key() { + let ctx = egui::Context::default(); + ctx.set_os(egui::os::OperatingSystem::Mac); + assert_eq!(shortcut_label(&ctx, "Ctrl+Shift+E"), "Cmd+Shift+E"); + ctx.set_os(egui::os::OperatingSystem::Windows); + assert_eq!(shortcut_label(&ctx, "Ctrl+Shift+E"), "Ctrl+Shift+E"); + } } diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs new file mode 100644 index 0000000..6c4ac5f --- /dev/null +++ b/crates/ui-egui/src/native_dialogs.rs @@ -0,0 +1,193 @@ +//! The desktop's file dialogs: queued on [`craft_dialogs::Dialogs`], shown at the end of a frame and answered on a later one + +use craft_dialogs::{Answer, FileDialog}; +use materialcraft_engine::formats::material::MATERIAL_EXT; +use materialcraft_engine::image::Image; +use serde_json::{Value, json}; + +use crate::MaterialCraftApp; +use crate::i18n::tr; + +pub(crate) type Dialogs = craft_dialogs::Dialogs; + +/// What the app does with an answered dialog +pub(crate) enum Then { + OpenPackage, + /// `document` is the package the request was for; `before_action` finishes a Save in the unsaved-changes prompt + SavePackage { + document: u64, + copy: bool, + before_action: bool, + }, + ExportMaterial(GraphRef), + ImportBitmap(GraphRef), + ExportFolder, + LoadMesh { + document: u64, + }, + SaveImage(Box), + /// The parameters `graph.input.bind` runs with, before the path + BindInput(Value, GraphRef), +} + +/// The active graph when a dialog was requested. Its index can pass to another graph when one is deleted, so its folder-qualified path is part of the identity +#[derive(Clone, PartialEq)] +pub(crate) struct GraphRef { + document: u64, + graph: usize, + path: String, +} + +impl GraphRef { + pub(crate) fn active(app: &MaterialCraftApp) -> GraphRef { + GraphRef { document: app.session.document_id, graph: app.session.graph, path: app.session.graph().map(|g| g.sbs_path()).unwrap_or_default() } + } +} + +/// A queue for an app that has no window to wake yet (offscreen snapshots and tests) +pub(crate) fn unattached() -> Dialogs { + craft_dialogs::Dialogs::new(std::sync::Arc::new(|| {})) +} + +/// A queue whose answers wake the window +pub(crate) fn attached(ctx: &egui::Context) -> Dialogs { + let ctx = ctx.clone(); + craft_dialogs::Dialogs::new(std::sync::Arc::new(move || ctx.request_repaint())) +} + +/// Queue a dialog unless one is already open or waiting, in which case the open one comes forward +pub(crate) fn ask(app: &mut MaterialCraftApp, dialog: FileDialog, then: Then) { + if app.dialogs.is_open() || app.dialogs.queued() > 0 { + app.dialogs.raise(); + } else { + app.dialogs.ask(dialog, then); + } +} + +fn save_dialog(app: &MaterialCraftApp) -> FileDialog { + FileDialog::save().file_name(format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name))).filter("SBS package", &["sbs"]) +} + +/// File ▸ Save as and Save a copy as: choose where to write the active package +pub(crate) fn save_package(app: &mut MaterialCraftApp, copy: bool) { + let then = Then::SavePackage { document: app.session.document_id, copy, before_action: false }; + let dialog = save_dialog(app); + ask(app, dialog, then); +} + +/// Save in the unsaved-changes prompt, for a package without a path: waits behind any open dialog +pub(crate) fn save_before_action(app: &mut MaterialCraftApp) { + let then = Then::SavePackage { document: app.session.document_id, copy: false, before_action: true }; + let dialog = save_dialog(app); + app.dialogs.ask(dialog, then); +} + +/// File ▸ Export material: choose where to write the active graph's material +pub(crate) fn export_material(app: &mut MaterialCraftApp) { + let name = format!("{}.{MATERIAL_EXT}", materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default())); + let then = Then::ExportMaterial(GraphRef::active(app)); + ask(app, FileDialog::save().file_name(name).filter("MaterialCraft material", &[MATERIAL_EXT]), then); +} + +/// Apply the answers that arrived since the last frame. Call once per frame +pub(crate) fn poll(app: &mut MaterialCraftApp) { + for (then, answer) in app.dialogs.take_answers() { + match answer { + Answer::Paths(paths) => match paths.into_iter().next() { + Some(path) => chosen(app, then, &path), + None => cancelled(app, then), + }, + Answer::Cancelled | Answer::Message(_) => cancelled(app, then), + Answer::Unavailable(why) => { + app.toast(format!("{}: {why}", tr("The file dialog could not be shown")), true); + cancelled(app, then); + } + } + } +} + +fn cancelled(app: &mut MaterialCraftApp, then: Then) { + if matches!(then, Then::SavePackage { before_action: true, .. }) { + crate::unsaved::finish_save_dialog(app, false); + } +} + +fn chosen(app: &mut MaterialCraftApp, then: Then, path: &std::path::Path) { + let picked = path.display().to_string(); + match then { + Then::OpenPackage => crate::windows::open_path(app, &picked), + Then::SavePackage { document, copy, before_action } => { + let saved = save_to(app, document, copy, &picked); + if before_action { + crate::unsaved::finish_save_dialog(app, saved); + } + } + Then::ExportMaterial(target) => { + if GraphRef::active(app) != target { + not_applied(app); + } else if let Some(r) = app.run("file.exportMaterial", json!({"path": picked})) { + app.toast(format!("{} {}", tr("Exported"), r["path"].as_str().unwrap_or_default()), false); + } + } + Then::ImportBitmap(target) => { + if GraphRef::active(app) == target { + crate::graph::import_bitmap_file(app, &picked); + } else { + not_applied(app); + } + } + Then::ExportFolder => app.ui.export_dir = picked, + Then::LoadMesh { document } => { + if app.session.document_id == document { + app.run("view.3d.loadMesh", json!({"path": picked})); + } else { + not_applied(app); + } + } + Then::SaveImage(image) => save_image(app, &image, path), + Then::BindInput(mut parameters, target) => { + if GraphRef::active(app) != target { + not_applied(app); + return; + } + parameters["path"] = json!(picked); + app.run("graph.input.bind", parameters); + } + } +} + +/// The commands behind these dialogs act on the active graph, so an answer for a graph that is no longer active, or was renamed or moved, is reported instead of applied +fn not_applied(app: &mut MaterialCraftApp) { + app.toast(tr("Not applied: the active graph or package changed while the file dialog was open"), true); +} + +/// Save `document` to the chosen path, activating it first when another package became active meanwhile +fn save_to(app: &mut MaterialCraftApp, document: u64, copy: bool, picked: &str) -> bool { + if app.session.document_id != document && app.run("package.activate", json!({"document": document})).is_none() { + return false; + } + let path = materialcraft_engine::file_cmds::package_path(picked); + if app.run(if copy { "file.saveCopyAs" } else { "file.save" }, json!({"path": path})).is_none() { + return false; + } + if !copy { + app.ui.add_recent(&path); + } + app.toast(format!("{} {path}", tr("Saved")), false); + true +} + +fn save_image(app: &mut MaterialCraftApp, image: &Image, path: &std::path::Path) { + let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("png").to_ascii_lowercase(); + let depth = if ext == "exr" { materialcraft_engine::formats::Depth::F32 } else { materialcraft_engine::formats::Depth::U16 }; + let result = + materialcraft_engine::formats::encode(image, &ext, depth, !image.is_gray()).and_then(|b| materialcraft_engine::formats::write_atomic(path, &b)); + match result { + Ok(()) => app.toast(format!("{} {}", tr("Saved"), path.display()), false), + Err(e) => app.toast(e.to_string(), true), + } +} + +#[cfg(test)] +#[path = "native_dialogs.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/native_dialogs.test.rs b/crates/ui-egui/src/native_dialogs.test.rs new file mode 100644 index 0000000..797dcfe --- /dev/null +++ b/crates/ui-egui/src/native_dialogs.test.rs @@ -0,0 +1,388 @@ +use super::*; +use crate::UiState; +use crate::unsaved::Guarded; +use craft_dialogs::Request; + +fn app() -> MaterialCraftApp { + MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()) +} + +/// Answer every queued dialog with `answer` and collect what was asked +fn answer_all(app: &mut MaterialCraftApp, answer: impl Fn() -> Answer + 'static) -> Vec { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let log = asked.clone(); + app.dialogs.set_override(Some(Box::new(move |request: &Request| { + log.borrow_mut().push(request.clone()); + answer() + }))); + app.dialogs.show_pending(None::<&eframe::Frame>); + poll(app); + asked.take() +} + +fn temp(name: &str) -> std::path::PathBuf { + std::env::temp_dir().join(format!("mc-dialogs-{}-{name}", std::process::id())) +} + +#[test] +fn save_as_writes_the_package_and_adds_it_to_recent() { + let mut app = app(); + let path = temp("saved.sbs"); + assert!(crate::windows::file_action(&mut app, &egui::Context::default(), "file.saveAs")); + let target = path.clone(); + let asked = answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + let Some(Request::File(dialog)) = asked.first() else { panic!("{asked:?}") }; + assert!(matches!(dialog.kind, craft_dialogs::Kind::Save)); + assert_eq!(dialog.file_name.as_deref(), Some(format!("{}.sbs", app.session.pkg.name).as_str())); + assert!(path.exists()); + assert!(!app.ui.recent.is_empty()); + assert_eq!(app.session.path.as_deref().map(std::path::PathBuf::from), std::fs::canonicalize(&path).ok()); + std::fs::remove_file(path).ok(); +} + +#[test] +fn a_canceled_dialog_changes_nothing() { + let mut app = app(); + let before = app.session.pkg.clone(); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.saveAs"); + let asked = answer_all(&mut app, || Answer::Cancelled); + assert_eq!(asked.len(), 1); + assert_eq!(app.session.pkg, before); + assert!(app.toasts.is_empty()); +} + +#[test] +fn an_unavailable_dialog_reports_why() { + let mut app = app(); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.saveAs"); + answer_all(&mut app, || Answer::Unavailable("no display".into())); + assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains("no display")), "{:?}", app.toasts.len()); +} + +#[test] +fn a_second_request_while_a_dialog_is_waiting_is_not_queued() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::windows::file_action(&mut app, &ctx, "file.open"); + crate::windows::file_action(&mut app, &ctx, "file.open"); + assert_eq!(app.dialogs.queued(), 1); +} + +#[test] +fn save_goes_straight_to_a_path_the_package_has() { + let mut app = app(); + let path = temp("direct.sbs"); + app.session.path = Some(path.display().to_string()); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.save"); + assert_eq!(app.dialogs.queued(), 0, "no dialog for a package with a path"); + assert!(path.exists()); + std::fs::remove_file(path).ok(); +} + +fn modified_app_asking_to_quit() -> MaterialCraftApp { + let mut app = app(); + app.session.modified = true; + app.session.path = None; + crate::unsaved::guard(&mut app, Guarded::Quit); + assert_eq!(app.ui.windows.unsaved, Some(Guarded::Quit)); + app +} + +fn answer_prompt_with_save(app: &mut MaterialCraftApp) { + let step = crate::unsaved::answer(&mut app.ui.windows.unsaved, crate::unsaved::Choice::Save); + let crate::unsaved::Step::Save(action) = step else { panic!("{step:?}") }; + crate::unsaved::save_then(app, &egui::Context::default(), action); +} + +#[test] +fn the_prompts_save_with_a_path_saves_and_runs_the_action_at_once() { + let mut app = modified_app_asking_to_quit(); + let path = temp("prompt-direct.sbs"); + app.session.path = Some(path.display().to_string()); + answer_prompt_with_save(&mut app); + assert_eq!(app.dialogs.queued(), 0, "no dialog for a package with a path"); + assert!(path.exists()); + assert!(app.quit_confirmed); + assert!(app.awaiting_save.is_none()); + std::fs::remove_file(path).ok(); +} + +#[test] +fn the_app_shows_a_requested_dialog_and_applies_its_answer() { + let mut harness = egui_kittest::Harness::builder().build_eframe(|_| app()); + harness.step(); + harness.step(); + let path = temp("frames.sbs"); + let target = path.clone(); + let ctx = harness.ctx.clone(); + let state = harness.state_mut(); + state.dialogs.set_override(Some(Box::new(move |_: &Request| Answer::Paths(vec![target.clone()])))); + crate::windows::file_action(state, &ctx, "file.saveAs"); + assert_eq!(state.dialogs.queued(), 1); + harness.step(); + assert_eq!(harness.state().dialogs.queued(), 0, "the frame shows the dialog"); + assert!(!path.exists(), "the answer is applied on the next frame"); + harness.step(); + assert!(path.exists(), "the frame applies the answer"); + std::fs::remove_file(path).ok(); +} + +#[test] +fn a_picked_package_opens() { + let mut first = app(); + let path = temp("opened.sbs"); + let document = first.session.document_id; + assert!(save_to(&mut first, document, false, &path.display().to_string())); + + let mut app = app(); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.open"); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert_eq!(app.session.path.as_deref().map(std::path::PathBuf::from), std::fs::canonicalize(&path).ok()); + assert!(app.toasts.iter().any(|toast| !toast.error && toast.text.starts_with("Opened")), "{}", app.toasts.len()); + std::fs::remove_file(path).ok(); +} + +#[test] +fn an_exported_material_is_written_for_the_active_graph() { + let mut app = app(); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.exportMaterial"); + let path = temp("exported.mcmat"); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert!(path.exists()); + assert!(app.toasts.iter().all(|toast| !toast.error), "{}", app.toasts.len()); + std::fs::remove_file(path).ok(); +} + +fn png(name: &str) -> std::path::PathBuf { + use materialcraft_engine::formats::{Depth, encode}; + let image = Image::filled(4, 4, materialcraft_engine::image::Kind::Gray, [0.7; 4]); + let path = temp(name); + std::fs::write(&path, encode(&image, "png", Depth::U16, false).unwrap()).unwrap(); + path +} + +#[test] +fn an_imported_bitmap_joins_the_active_package() { + let mut app = app(); + let before = app.session.pkg.resources.len(); + crate::windows::file_action(&mut app, &egui::Context::default(), "file.importBitmap"); + let path = png("imported.png"); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert_eq!(app.session.pkg.resources.len(), before + 1); + std::fs::remove_file(path).ok(); +} + +#[test] +fn a_picked_mesh_shows_in_the_3d_view() { + let mut app = app(); + crate::web_files::load_mesh(&mut app, &egui::Context::default()); + let path = temp("mesh.obj"); + std::fs::write(&path, "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n").unwrap(); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert!(app.session.custom_mesh.is_some()); + assert_eq!(app.session.view3d.scene, "custom"); + std::fs::remove_file(path).ok(); +} + +#[test] +fn the_2d_views_image_is_written_to_the_picked_file() { + for ext in ["png", "exr"] { + let mut app = app(); + app.session.cook(); + crate::view2d::save_image(&mut app); + let path = temp(&format!("view.{ext}")); + let target = path.clone(); + let asked = answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + let Some(Request::File(dialog)) = asked.first() else { panic!("{asked:?}") }; + assert!(dialog.file_name.as_deref().is_some_and(|name| name.ends_with(".png"))); + assert!(materialcraft_engine::formats::decode(&std::fs::read(&path).unwrap(), false).is_ok(), "{ext}"); + std::fs::remove_file(path).ok(); + } +} + +#[test] +fn a_picked_input_image_is_bound_on_the_active_graph() { + let mut app = app(); + app.run("graph.node.add", json!({"def": "input_grayscale", "params": {"identifier": "curvature"}})); + let path = png("input.png"); + app.dialogs.ask(FileDialog::open(), Then::BindInput(json!({"identifier": "curvature"}), GraphRef::active(&app))); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert!(app.session.graph().unwrap().input_images.contains_key("curvature")); + std::fs::remove_file(path).ok(); +} + +#[test] +fn the_prompts_save_waits_for_its_dialog_and_then_quits() { + let mut app = modified_app_asking_to_quit(); + answer_prompt_with_save(&mut app); + + // While the dialog is up, another close asks nothing and the app is not quitting + assert!(!app.quit_confirmed); + crate::unsaved::guard(&mut app, Guarded::Quit); + assert_eq!(app.ui.windows.unsaved, None, "no second prompt while the Save dialog is open"); + + let path = temp("quit.sbs"); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert!(path.exists()); + assert!(!app.session.modified); + assert!(app.quit_confirmed, "the held quit runs once the package is saved"); + assert!(app.awaiting_save.is_none()); + std::fs::remove_file(path).ok(); +} + +#[test] +fn canceling_the_prompts_save_dialog_keeps_the_app_open() { + let mut app = modified_app_asking_to_quit(); + app.pending_load = Some(("waiting.sbs".into(), vec![1, 2, 3])); + answer_prompt_with_save(&mut app); + answer_all(&mut app, || Answer::Cancelled); + assert!(!app.quit_confirmed); + assert!(app.awaiting_save.is_none()); + assert!(app.pending_load.is_none(), "the held load is dropped"); + assert!(app.session.modified); +} + +#[test] +fn a_held_close_waits_for_the_save_dialog() { + let mut app = modified_app_asking_to_quit(); + answer_prompt_with_save(&mut app); + app.session.modified = false; + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close); + let mut output = ctx.run_ui(input, |ui| crate::unsaved::handle_close(&mut app, ui.ctx())); + output.textures_delta.clear(); + let commands = output.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default(); + assert!(commands.contains(&egui::ViewportCommand::CancelClose)); +} + +#[test] +fn a_held_close_restores_a_minimized_window() { + for (minimized, restored) in [(Some(true), true), (Some(false), false), (None, false)] { + let mut app = modified_app_asking_to_quit(); + app.ui.windows.unsaved = None; + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + let root = input.viewports.entry(egui::ViewportId::ROOT).or_default(); + root.minimized = minimized; + root.events.push(egui::ViewportEvent::Close); + let mut output = ctx.run_ui(input, |ui| crate::unsaved::handle_close(&mut app, ui.ctx())); + output.textures_delta.clear(); + let commands = output.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default(); + assert_eq!(commands.contains(&egui::ViewportCommand::Minimized(false)), restored, "{minimized:?}"); + } +} + +#[test] +fn a_saved_package_goes_to_the_document_that_asked() { + let mut app = app(); + let first = app.session.document_id; + app.run("file.newPackage", serde_json::json!({})); + let second = app.session.document_id; + assert_ne!(first, second, "a second package is open"); + + let path = temp("first.sbs"); + let saved = save_to(&mut app, first, false, &path.display().to_string()); + assert!(saved); + assert_eq!(app.session.document_id, first, "the asking package is active again"); + assert_eq!(app.session.path.as_deref().map(std::path::PathBuf::from), std::fs::canonicalize(&path).ok()); + std::fs::remove_file(path).ok(); +} + +#[test] +fn saving_a_package_that_closed_meanwhile_does_not_write() { + let mut app = app(); + let path = temp("gone.sbs"); + assert!(!save_to(&mut app, u64::MAX, false, &path.display().to_string())); + assert!(!path.exists()); + assert!(!app.toasts.is_empty(), "the error is reported"); +} + +#[test] +fn the_export_folder_dialog_fills_the_field() { + let mut app = app(); + app.dialogs.ask(FileDialog::folder(), Then::ExportFolder); + let dir = std::env::temp_dir(); + let target = dir.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert_eq!(app.ui.export_dir, dir.display().to_string()); +} + +#[test] +fn a_picked_input_image_is_not_applied_to_another_graph() { + let mut app = app(); + let target = GraphRef { path: "another graph".into(), ..GraphRef::active(&app) }; + app.dialogs.ask(FileDialog::open(), Then::BindInput(json!({"identifier": "curvature"}), target)); + let before = app.session.history().len(); + answer_all(&mut app, || Answer::Paths(vec!["image.png".into()])); + assert_eq!(app.session.history().len(), before); + assert!(app.toasts.iter().any(|toast| toast.error && toast.text.starts_with("Not applied")), "{}", app.toasts.len()); +} + +#[test] +fn an_imported_bitmap_is_not_added_to_another_graph() { + let mut app = app(); + let target = GraphRef { path: "another graph".into(), ..GraphRef::active(&app) }; + app.dialogs.ask(FileDialog::open(), Then::ImportBitmap(target)); + let before = app.session.history().len(); + answer_all(&mut app, || Answer::Paths(vec!["does-not-exist.png".into()])); + assert_eq!(app.session.history().len(), before); + assert!(app.toasts.iter().any(|toast| toast.text.starts_with("Not applied")), "{}", app.toasts.len()); +} + +#[test] +fn a_graph_that_took_over_the_index_is_a_different_graph() { + let mut app = app(); + app.run("graph.duplicate", json!({})); + app.run("graph.open", json!({"graph": 0})); + let target = GraphRef::active(&app); + app.run("graph.delete", json!({"graph": 0})); + assert_eq!(app.session.graph, 0, "another graph holds the index now"); + assert!(GraphRef::active(&app) != target); +} + +#[test] +fn a_pick_for_a_renamed_graph_says_the_graph_changed() { + let mut app = app(); + let target = GraphRef::active(&app); + app.session.graph_mut().unwrap().name = "renamed".into(); + app.dialogs.ask(FileDialog::open(), Then::ImportBitmap(target)); + answer_all(&mut app, || Answer::Paths(vec!["does-not-exist.png".into()])); + assert!(app.toasts.iter().any(|toast| toast.text.contains("graph or package changed")), "{}", app.toasts.len()); +} + +#[test] +fn a_graph_of_the_same_name_in_another_folder_is_a_different_graph() { + let mut app = app(); + app.session.graph_mut().unwrap().folder = "first".into(); + let target = GraphRef::active(&app); + app.session.graph_mut().unwrap().folder = "second".into(); + assert!(GraphRef::active(&app) != target); +} + +#[test] +fn a_mesh_picked_for_another_package_is_not_loaded() { + let mut app = app(); + let document = app.session.document_id + 1; + app.dialogs.ask(FileDialog::open(), Then::LoadMesh { document }); + answer_all(&mut app, || Answer::Paths(vec!["does-not-exist.obj".into()])); + assert!(app.toasts.iter().any(|toast| toast.text.starts_with("Not applied")), "{}", app.toasts.len()); +} + +#[test] +fn an_exported_material_is_not_written_after_the_graph_changed() { + let mut app = app(); + let target = GraphRef { graph: app.session.graph + 1, ..GraphRef::active(&app) }; + app.dialogs.ask(FileDialog::save(), Then::ExportMaterial(target)); + let path = temp("gone.mcmat"); + let target = path.clone(); + answer_all(&mut app, move || Answer::Paths(vec![target.clone()])); + assert!(!path.exists()); + assert!(app.toasts.iter().any(|toast| toast.error), "{}", app.toasts.len()); +} diff --git a/crates/ui-egui/src/property/graph.rs b/crates/ui-egui/src/property/graph.rs index 89685a8..a417baf 100644 --- a/crates/ui-egui/src/property/graph.rs +++ b/crates/ui-egui/src/property/graph.rs @@ -107,10 +107,22 @@ fn show_target(app: &mut MaterialCraftApp, ui: &mut Ui, target: materialcraft_en }); for (id, parameters) in commands { - app.run(id, parameters); + run_or_pick(app, id, parameters); } } +/// Run a panel command. On the desktop, `ui.pickInputImage` asks for the file first and binds it when the dialog answers +fn run_or_pick(app: &mut MaterialCraftApp, id: &str, parameters: JsonValue) { + #[cfg(not(target_arch = "wasm32"))] + if id == "ui.pickInputImage" { + let dialog = craft_dialogs::FileDialog::open().filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS); + let then = crate::native_dialogs::Then::BindInput(parameters, crate::native_dialogs::GraphRef::active(app)); + crate::native_dialogs::ask(app, dialog, then); + return; + } + app.run(id, parameters); +} + /// Preview images of the graph's input nodes: a bitmap resource, or (desktop) an image file such as a mesh map baked in TextureCraft fn input_previews(ui: &mut Ui, graph: &Graph, resources: &[Resource], emit: &mut impl FnMut(&'static str, JsonValue)) { let inputs = materialcraft_engine::material_cmds::image_inputs(graph); @@ -134,10 +146,8 @@ fn input_previews(ui: &mut Ui, graph: &Graph, resources: &[Resource], emit: &mut } }); #[cfg(not(target_arch = "wasm32"))] - if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() - && let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() - { - emit("graph.input.bind", json!({"identifier": id, "path": path.display().to_string()})); + if crate::widgets::icon_button(ui, icon::FOLDER_OPEN, tr("Pick an image file (a mesh map baked in TextureCraft)"), false, 18.0).clicked() { + emit("ui.pickInputImage", json!({"identifier": id})); } }); } @@ -171,3 +181,19 @@ fn presets_bar(ui: &mut Ui, graph: &Graph, emit: &mut impl FnMut(&'static str, J }); ui.data_mut(|data| data.insert_temp(name_id, name)); } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + #[test] + fn picking_an_input_image_asks_for_the_file_and_other_commands_run() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + let nodes = app.session.graph().unwrap().nodes.len(); + run_or_pick(&mut app, "ui.pickInputImage", json!({"identifier": "curvature"})); + assert_eq!(app.dialogs.queued(), 1); + run_or_pick(&mut app, "graph.node.add", json!({"def": "input_grayscale"})); + assert_eq!(app.dialogs.queued(), 1, "a command does not ask for a file"); + assert_eq!(app.session.graph().unwrap().nodes.len(), nodes + 1); + } +} diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs index b4d2a81..487220c 100644 --- a/crates/ui-egui/src/unsaved.rs +++ b/crates/ui-egui/src/unsaved.rs @@ -60,7 +60,7 @@ pub fn holds_close(modified: bool, confirmed: bool) -> bool { /// Run `action`, asking first when the package has unsaved changes pub fn guard(app: &mut MaterialCraftApp, action: Guarded) { - if app.ui.windows.unsaved.is_some() { + if app.ui.windows.unsaved.is_some() || app.awaiting_save.is_some() { return; } @@ -123,8 +123,14 @@ pub fn handle_close(app: &mut MaterialCraftApp, ctx: &Context) { if ctx.input(|i| i.viewport().close_requested()) && !app.quit_confirmed { // Focused text is still a draft when the OS asks to close the window crate::properties::GraphPropertyDraft::commit(app); - if holds_close(needs_confirmation(&app.session), app.quit_confirmed) { + // While the Save dialog of a held action is open, the close waits for its answer + if app.awaiting_save.is_some() || holds_close(needs_confirmation(&app.session), app.quit_confirmed) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + // The prompt is drawn only while the window is visible + if ctx.input(|i| i.viewport().minimized) == Some(true) { + ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false)); + ctx.send_viewport_cmd(egui::ViewportCommand::Focus); + } guard(app, Guarded::Quit); } } @@ -174,17 +180,42 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &Context) { let Some(choice) = choice else { return }; match answer(&mut app.ui.windows.unsaved, choice) { Step::Run(a) => perform(app, a), - Step::Save(a) => { - crate::windows::file_action(app, ctx, "file.save"); - match after_save(app.session.modified, a) { - Some(a) => perform(app, a), - None => app.pending_load = None, - } - } + Step::Save(a) => save_then(app, ctx, a), Step::Stop => app.pending_load = None, } } +/// Save first, then run `action` if the package is no longer modified. Without a path to save to, +/// the action waits for the Save dialog's answer ([`finish_save_dialog`]) on the desktop +pub(crate) fn save_then(app: &mut MaterialCraftApp, ctx: &Context, action: Guarded) { + #[cfg(not(target_arch = "wasm32"))] + if !crate::windows::has_local_path(app) { + app.awaiting_save = Some(action); + crate::native_dialogs::save_before_action(app); + return; + } + crate::windows::file_action(app, ctx, "file.save"); + run_if_saved(app, action); +} + +fn run_if_saved(app: &mut MaterialCraftApp, action: Guarded) { + match after_save(app.session.modified, action) { + Some(action) => perform(app, action), + None => app.pending_load = None, + } +} + +/// The Save dialog of a held action has answered: run the action when `saved`, otherwise drop it +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn finish_save_dialog(app: &mut MaterialCraftApp, saved: bool) { + let Some(action) = app.awaiting_save.take() else { return }; + if saved { + run_if_saved(app, action); + } else { + app.pending_load = None; + } +} + #[cfg(test)] #[path = "unsaved.test.rs"] mod tests; diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 70bb3ac..0831094 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -234,25 +234,11 @@ fn draw_histogram(st: &mut View2dState, p: &egui::Painter, rect: Rect, key: u64, } #[cfg(not(target_arch = "wasm32"))] -fn save_image(app: &mut MaterialCraftApp) { +pub(crate) fn save_image(app: &mut MaterialCraftApp) { let Some((id, img)) = app.session.view2d_image().map(|(id, i)| (id, i.clone())) else { return }; let name = app.session.graph().ok().and_then(|g| g.node(id).ok().map(crate::graph::node_label)).unwrap_or_else(|| "image".into()); - let Some(path) = rfd::FileDialog::new() - .set_file_name(format!("{name}.png")) - .add_filter("PNG", &["png"]) - .add_filter("OpenEXR", &["exr"]) - .add_filter("TGA", &["tga"]) - .save_file() - else { - return; - }; - let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("png").to_ascii_lowercase(); - let depth = if ext == "exr" { materialcraft_engine::formats::Depth::F32 } else { materialcraft_engine::formats::Depth::U16 }; - let result = materialcraft_engine::formats::encode(&img, &ext, depth, !img.is_gray()).and_then(|b| materialcraft_engine::formats::write_atomic(&path, &b)); - match result { - Ok(()) => app.toast(format!("{} {}", tr("Saved"), path.display()), false), - Err(e) => app.toast(e.to_string(), true), - } + let dialog = craft_dialogs::FileDialog::save().file_name(format!("{name}.png")).filter("PNG", &["png"]).filter("OpenEXR", &["exr"]).filter("TGA", &["tga"]); + crate::native_dialogs::ask(app, dialog, crate::native_dialogs::Then::SaveImage(Box::new(img))); } #[cfg(test)] diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index d8ff750..442c4bc 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -40,9 +40,9 @@ pub fn load_mesh(app: &mut MaterialCraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { let _ = ctx; - if let Some(p) = rfd::FileDialog::new().add_filter("Meshes", materialcraft_engine::formats::mesh::MESH_EXTENSIONS).pick_file() { - app.run("view.3d.loadMesh", serde_json::json!({"path": p.display().to_string()})); - } + let dialog = craft_dialogs::FileDialog::open().filter("Meshes", materialcraft_engine::formats::mesh::MESH_EXTENSIONS); + let then = crate::native_dialogs::Then::LoadMesh { document: app.session.document_id }; + crate::native_dialogs::ask(app, dialog, then); } #[cfg(target_arch = "wasm32")] { diff --git a/crates/ui-egui/src/window_controls.rs b/crates/ui-egui/src/window_controls.rs new file mode 100644 index 0000000..cb0bd4a --- /dev/null +++ b/crates/ui-egui/src/window_controls.rs @@ -0,0 +1,87 @@ +//! The menu bar as the title bar, where the desktop leaves the window frame to the app (GNOME on Wayland) + +use craft_window::Button; +use egui::viewport::ResizeDirection; +use egui::{Context, CursorIcon, Id, LayerId, Order, PointerButton, Rect, Sense, Ui, ViewportCommand, pos2, vec2}; +use egui_phosphor::regular as icon; + +use crate::i18n::tr; + +fn label(button: Button) -> &'static str { + match button { + Button::Minimize => "Minimize", + Button::Maximize => "Maximize", + Button::Close => "Close", + } +} + +fn glyph(button: Button) -> &'static str { + match button { + Button::Minimize => icon::MINUS, + Button::Maximize => icon::SQUARE, + Button::Close => icon::X, + } +} + +fn command(button: Button, maximized: bool) -> ViewportCommand { + match button { + Button::Minimize => ViewportCommand::Minimized(true), + Button::Maximize => ViewportCommand::Maximized(!maximized), + Button::Close => ViewportCommand::Close, + } +} + +const EDGE: f32 = 5.0; +const CORNER: f32 = 12.0; + +/// The edge and corner zones of a window with content rect `w`; corners come last and win where they overlap the edges +fn zones(w: Rect) -> [(Rect, ResizeDirection, CursorIcon); 8] { + use ResizeDirection::*; + [ + (Rect::from_min_max(w.left_top(), pos2(w.right(), w.top() + EDGE)), North, CursorIcon::ResizeVertical), + (Rect::from_min_max(pos2(w.left(), w.bottom() - EDGE), w.right_bottom()), South, CursorIcon::ResizeVertical), + (Rect::from_min_max(w.left_top(), pos2(w.left() + EDGE, w.bottom())), West, CursorIcon::ResizeHorizontal), + (Rect::from_min_max(pos2(w.right() - EDGE, w.top()), w.right_bottom()), East, CursorIcon::ResizeHorizontal), + (Rect::from_min_size(w.left_top(), vec2(CORNER, CORNER)), NorthWest, CursorIcon::ResizeNwSe), + (Rect::from_min_size(w.right_top() - vec2(CORNER, 0.0), vec2(CORNER, CORNER)), NorthEast, CursorIcon::ResizeNeSw), + (Rect::from_min_size(w.left_bottom() - vec2(0.0, CORNER), vec2(CORNER, CORNER)), SouthWest, CursorIcon::ResizeNeSw), + (Rect::from_min_size(w.right_bottom() - vec2(CORNER, CORNER), vec2(CORNER, CORNER)), SouthEast, CursorIcon::ResizeNwSe), + ] +} + +/// Invisible resize zones along the window's edges, above everything else; none while the window is maximized or full screen +pub(crate) fn resize_zones(ui: &mut Ui) { + let ctx = ui.ctx().clone(); + let (maximized, fullscreen) = ctx.input(|input| (input.viewport().maximized.unwrap_or(false), input.viewport().fullscreen.unwrap_or(false))); + if maximized || fullscreen { + return; + } + let window = ctx.content_rect(); + let layer = LayerId::new(Order::Foreground, Id::unique("window-resize-zones")); + let zones_ui = ui.new_child(egui::UiBuilder::new().layer_id(layer).max_rect(window)); + for (index, (rect, direction, cursor)) in zones(window).into_iter().enumerate() { + let response = zones_ui.interact(rect, Id::unique(("window-resize-zone", index)), Sense::DRAG).on_hover_cursor(cursor); + if response.drag_started_by(PointerButton::Primary) { + ctx.send_viewport_cmd(ViewportCommand::BeginResize(direction)); + // The window manager takes the pointer and on some desktops its release as well + ctx.stop_dragging(); + ctx.input_mut(|input| input.pointer = Default::default()); + } + } +} + +/// Draw `buttons` in the given left-to-right order +pub(crate) fn buttons(ui: &mut Ui, ctx: &Context, buttons: &[Button]) { + for &button in buttons { + let response = crate::widgets::icon_button(ui, glyph(button), tr(label(button)), false, 18.0); + crate::widgets::name(&response, egui::Role::Button, label(button)); + if response.clicked() { + let maximized = ctx.input(|input| input.viewport().maximized).unwrap_or(false); + ctx.send_viewport_cmd(command(button, maximized)); + } + } +} + +#[cfg(test)] +#[path = "window_controls.test.rs"] +mod tests; diff --git a/crates/ui-egui/src/window_controls.test.rs b/crates/ui-egui/src/window_controls.test.rs new file mode 100644 index 0000000..e73504e --- /dev/null +++ b/crates/ui-egui/src/window_controls.test.rs @@ -0,0 +1,70 @@ +use super::*; + +#[test] +fn each_button_sends_its_viewport_command() { + assert_eq!(command(Button::Minimize, false), ViewportCommand::Minimized(true)); + assert_eq!(command(Button::Maximize, false), ViewportCommand::Maximized(true)); + assert_eq!(command(Button::Maximize, true), ViewportCommand::Maximized(false)); + assert_eq!(command(Button::Close, false), ViewportCommand::Close); +} + +fn commands_after_press_at(pos: egui::Pos2) -> Vec { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut output = Vec::new(); + for events in [ + vec![egui::Event::PointerMoved(pos)], + vec![egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }], + vec![egui::Event::PointerMoved(pos + egui::vec2(3.0, 3.0))], + vec![egui::Event::PointerMoved(pos + egui::vec2(9.0, 9.0))], + ] { + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut frame = ctx.run_ui(input, resize_zones); + frame.textures_delta.clear(); + output.extend(frame.viewport_output.remove(&egui::ViewportId::ROOT).map(|root| root.commands).unwrap_or_default()); + } + output +} + +#[test] +fn a_press_on_a_window_edge_starts_a_resize() { + use egui::viewport::ResizeDirection::{East, North, SouthEast, West}; + for (pos, direction) in + [(egui::pos2(400.0, 1.0), North), (egui::pos2(1.0, 300.0), West), (egui::pos2(799.0, 300.0), East), (egui::pos2(799.0, 599.0), SouthEast)] + { + let commands = commands_after_press_at(pos); + assert!(commands.contains(&ViewportCommand::BeginResize(direction)), "{pos:?}: {commands:?}"); + } +} + +#[test] +fn a_press_inside_the_window_does_not_resize() { + let commands = commands_after_press_at(egui::pos2(400.0, 300.0)); + assert!(!commands.iter().any(|command| matches!(command, ViewportCommand::BeginResize(_))), "{commands:?}"); +} + +#[test] +fn the_menu_bar_shows_window_buttons_only_when_the_app_draws_the_frame() { + let mut app = crate::MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default()); + let mut labels_drawn = |layout: Option| { + app.window_layout = layout; + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| crate::menus::menu_bar(&mut app, ui)); + output.textures_delta.clear(); + let nodes = output.platform_output.accesskit_update.map(|update| update.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label().map(str::to_owned)).collect::>() + }; + + let desktop = labels_drawn(None); + assert!(!desktop.iter().any(|label| label == "Close"), "{desktop:?}"); + + let drawn = labels_drawn(Some(craft_window::Layout::default())); + for button in ["Minimize", "Maximize", "Close"] { + assert!(drawn.iter().any(|label| label == button), "{button} in {drawn:?}"); + } + + let left = labels_drawn(Some(craft_window::Layout { left: vec![Button::Close], right: Vec::new() })); + assert!(left.iter().any(|label| label == "Close"), "{left:?}"); + assert!(!left.iter().any(|label| label == "Minimize"), "{left:?}"); +} diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 353a1fc..f422e85 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -182,10 +182,8 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) { let r = ui.add(egui::TextEdit::singleline(&mut app.ui.export_dir).desired_width(280.0)); crate::widgets::name(&r, egui::Role::TextInput, "Folder"); #[cfg(not(target_arch = "wasm32"))] - if ui.button(icon::FOLDER_OPEN).clicked() - && let Some(d) = rfd::FileDialog::new().pick_folder() - { - app.ui.export_dir = d.display().to_string(); + if ui.button(icon::FOLDER_OPEN).clicked() { + crate::native_dialogs::ask(app, craft_dialogs::FileDialog::folder(), crate::native_dialogs::Then::ExportFolder); } }); crate::widgets::combo(ui, tr("Format"), app.ui.export_format.to_uppercase(), |ui| { @@ -331,7 +329,7 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { egui::Grid::new("sc").striped(true).show(ui, |ui| { for i in crate::menus::CATALOG.iter().filter(|i| i.shortcut.is_some()) { ui.label(tr(i.label)); - ui.label(RichText::new(i.shortcut.unwrap_or_default()).monospace()); + ui.label(RichText::new(crate::menus::shortcut_label(ctx, i.shortcut.unwrap_or_default())).monospace()); ui.end_row(); } for (k, what) in [ @@ -529,14 +527,14 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> let _ = ctx; #[cfg(not(target_arch = "wasm32"))] { + use crate::native_dialogs::{self, Then}; + use craft_dialogs::FileDialog; match id { "file.open" => { - if let Some(p) = rfd::FileDialog::new().add_filter("SBS or MaterialCraft package, or material", OPEN_EXTS).pick_file() { - open_path(app, &p.display().to_string()); - } + native_dialogs::ask(app, FileDialog::open().filter("SBS or MaterialCraft package, or material", OPEN_EXTS), Then::OpenPackage); true } - "file.save" if app.session.path.as_ref().is_some_and(|path| !path.contains("://")) => { + "file.save" if has_local_path(app) => { if let Some(r) = app.run("file.save", json!({})) { let path = r["path"].as_str().unwrap_or_default().to_string(); app.ui.add_recent(&path); @@ -545,28 +543,11 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> true } "file.save" | "file.saveAs" | "file.saveCopyAs" => { - let name = format!("{}.sbs", materialcraft_engine::formats::safe_file_name(&app.session.pkg.name)); - if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("SBS package", &["sbs"]).save_file() { - let path = materialcraft_engine::file_cmds::package_path(&p.display().to_string()); - if app.run(if id == "file.saveCopyAs" { id } else { "file.save" }, json!({"path": path})).is_some() { - if id != "file.saveCopyAs" { - app.ui.add_recent(&path); - } - app.toast(format!("{} {path}", tr("Saved")), false); - } - } + native_dialogs::save_package(app, id == "file.saveCopyAs"); true } "file.exportMaterial" => { - let name = format!( - "{}.{MATERIAL_EXT}", - materialcraft_engine::formats::safe_file_name(&app.session.graph().map(|g| g.name.clone()).unwrap_or_default()) - ); - if let Some(p) = rfd::FileDialog::new().set_file_name(name).add_filter("MaterialCraft material", &[MATERIAL_EXT]).save_file() - && let Some(r) = app.run("file.exportMaterial", json!({"path": p.display().to_string()})) - { - app.toast(format!("{} {}", tr("Exported"), r["path"].as_str().unwrap_or_default()), false); - } + native_dialogs::export_material(app); true } "file.sendToTextureCraft" => { @@ -576,9 +557,8 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> true } "file.importBitmap" => { - if let Some(path) = rfd::FileDialog::new().add_filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS).pick_file() { - crate::graph::import_bitmap_file(app, &path.display().to_string()); - } + let then = Then::ImportBitmap(native_dialogs::GraphRef::active(app)); + native_dialogs::ask(app, FileDialog::open().filter("Images", materialcraft_engine::formats::IMAGE_EXTENSIONS), then); true } _ => false, @@ -598,6 +578,12 @@ pub fn file_action(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) -> } } +/// Whether File ▸ Save writes straight to the package's path (a package opened from a URL has none to write to) +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn has_local_path(app: &MaterialCraftApp) -> bool { + app.session.path.as_ref().is_some_and(|path| !path.contains("://")) +} + /// Open a package from a path (recent list, command line) #[cfg(not(target_arch = "wasm32"))] pub fn open_path(app: &mut MaterialCraftApp, path: &str) {