diff --git a/Cargo.toml b/Cargo.toml index 4206a1042..19ecc1197 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,9 +41,8 @@ figcraft-plugin = { path = "crates/plugin" } # Which paths stored in a document may be followed (craft-libs). craft-docpath = { version = "0.1.0", git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } # Who draws the window frame on Linux — the compositor or the app — so every Craft app shows the -# same native titlebar per desktop (craft-libs). FigCraft only reads the probe result and maps it -# to its own `TitleBar`, so it does not enable craft-window's optional `egui` helpers (which would -# pull a second egui family version). +# same native titlebar per desktop (craft-libs). FigCraft reads the probe result and maps it to its +# own `TitleBar`; the UI runtime takes its window system from here too. craft-window = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } # craft-update: app-specific pretend versions apply to startup and manual checks. craft-update = { git = "https://github.com/aiongg/craft-libs", version = "=0.1.0", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c", features = ["ui"] } @@ -51,8 +50,14 @@ craft-update = { git = "https://github.com/aiongg/craft-libs", version = "=0.1.0 # indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs). craft-font-store = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } craft-font-catalog = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } -# Shared dropdown menus: a combo box whose menu grows back after shrinking (craft-libs). +# The UI runtime FigCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`) and the +# framework dialogs on it (craft-libs): who the app is to those dialogs, the runtime's key +# bindings, the theme mode and the interface direction. craft-ui = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } +craft-host = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } +craft-keymap = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } +craft-theme = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } +craft-i18n = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } # The macOS app menu whose Quit (⌘Q) asks the app before quitting, like the window's close button # (craft-libs; the menu it replaces quits straight through `terminate:` and loses unsaved work). craft-menu = { git = "https://github.com/aiongg/craft-libs", rev = "86ac6ac5f0f6d6cecb813298debadac7fc6cd79c" } diff --git a/apps/figcraft-web/src/web.rs b/apps/figcraft-web/src/web.rs index 81bd91d64..186833bc4 100644 --- a/apps/figcraft-web/src/web.rs +++ b/apps/figcraft-web/src/web.rs @@ -54,6 +54,8 @@ pub fn start() { canvas, options, Box::new(move |cc| { + // The UI runtime FigCraft's egui UI is hosted by; the page owns the canvas, so it has no window system. + figcraft_ui_egui::framework::install_headless(&cc.egui_ctx); if let Some(rs) = &cc.wgpu_render_state { log::info!("figcraft-web: wgpu backend {:?}", rs.adapter.get_info().backend); } @@ -210,6 +212,7 @@ impl eframe::App for WebShell { if let Some(bridge) = &self.host { bridge.set_dirty(self.fig.session.docs.iter().any(|d| d.is_dirty())); } + self.fig.close_path(ctx); } fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { @@ -217,6 +220,7 @@ impl eframe::App for WebShell { // to draw: the batch is applied by this frame and acknowledged once it is presented, as on // the desktop (`apps/figcraft/src/main.rs`). Without this hook the batch sat in its queue // and its promise never settled. + self.fig.before_input(ctx); let events = figcraft_ui_egui::windows::take_input(&mut self.fig, raw_input.viewport_id); raw_input.events.extend(events); crate::pasted::begin_frame(&mut self.fig, raw_input, ctx); diff --git a/apps/figcraft/src/main.rs b/apps/figcraft/src/main.rs index 1d24e511b..c2087abfd 100644 --- a/apps/figcraft/src/main.rs +++ b/apps/figcraft/src/main.rs @@ -89,9 +89,6 @@ impl eframe::App for App { figcraft_ui_egui::windows::guard(fig, ctx, |fig| fig.background_tick(ctx)); #[cfg(target_os = "macos")] apple_events::poll(&self.apple_events, fig, ctx); - // Closing the window asks about unsaved changes (and keeps the app running while other - // windows are open). - figcraft_ui_egui::windows::on_close_request(fig, ctx); fig.title() }); // Window title follows the document. @@ -111,21 +108,28 @@ impl eframe::App for App { { ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } + // Last: closing the main window asks about unsaved changes (and keeps the app running + // while other windows are open), through the runtime's close path. + with_app(|fig| fig.close_path(ctx)); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) { + fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) { // winit gives an undecorated window its caption back when it changes the window's flags // (maximize, restore, ...): take it off again before the frame is laid out (#1343). self.window_frame.run(); // Pointer and key events sent over the control channel (`ui.input`), for the window // about to draw. - if let Some(events) = with_app(|fig| figcraft_ui_egui::windows::take_input(fig, raw_input.viewport_id)) { + if let Some(events) = with_app(|fig| { + fig.before_input(ctx); + figcraft_ui_egui::windows::take_input(fig, raw_input.viewport_id) + }) { raw_input.events.extend(events); } } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); + figcraft_ui_egui::framework::before_ui(&ctx, &*frame); services::parented(frame, || with_app(|fig| figcraft_ui_egui::windows::guard(fig, &ctx, |fig| fig.ui(ui)))); } @@ -293,6 +297,8 @@ fn main() -> eframe::Result { "FigCraft", options, Box::new(|cc| { + // The UI runtime FigCraft's egui UI is hosted by, before the first pass. + figcraft_ui_egui::framework::install(&cc.egui_ctx)?; if let Some(state) = &cc.wgpu_render_state { graphics.opened(&state.adapter.get_info()); } diff --git a/clippy.toml b/clippy.toml index 305f94bdd..76224ee3b 100644 --- a/clippy.toml +++ b/clippy.toml @@ -4,7 +4,4 @@ allow-unwrap-in-tests = true allow-expect-in-tests = true allow-panic-in-tests = true too-many-arguments-threshold = 10 -disallowed-types = [ - { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, -] cognitive-complexity-threshold = 30 diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 78447d7b2..f86da1023 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -9,7 +9,14 @@ description = "FigCraft egui frontend (the Figma-style UI: canvas, toolbar, laye workspace = true [dependencies] +# The UI runtime that hosts this egui UI (`src/framework.rs`) and the framework dialogs, from the +# one craft-libs revision every craft-libs dependency uses (see the root Cargo.toml). craft-ui = { workspace = true } +craft-host = { workspace = true } +craft-i18n = { workspace = true } +craft-keymap = { workspace = true } +craft-theme = { workspace = true } +craft-window = { workspace = true } figcraft-geom = { workspace = true } figcraft-color = { workspace = true } figcraft-doc = { workspace = true } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 10a82ed5c..451a40d16 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -63,6 +63,8 @@ impl FigApp { ui_frame_stamp: None, ime: egui::ime_context::ImeContextTracker::new(), updates_rt: updates_ui::Runtime::default(), + framework_dialogs: craft_ui::dialog::DialogHost::new(), + framework_host: crate::framework::host(), #[cfg(test)] ime_observations: 0, } @@ -95,17 +97,12 @@ impl FigApp { // Screen-reader and bidi language of the UI (fork E17). ctx.set_language(i18n::current().map(|l| l.code.to_string())); if !self.fonts_installed { - // Cmd/Ctrl+= / - / 0 zoom the canvas (view.zoomIn, view.zoomOut, view.zoom100): egui's - // own keyboard zoom would scale the whole interface on the same keys. - ctx.options_mut(|o| o.zoom_with_keyboard = false); // A double-click's window is the platform's (0.5 s, Windows' default), not egui's // stricter 0.3 s: a double-click the OS takes must enter a shape's points too. ctx.memory_mut(|m| m.options.input_options.max_double_click_delay = 0.5); theme::install_fonts(ctx, false, 0); + // The runtime lays this frame out again with them (`craft_ui::fonts::load`). self.fonts_installed = true; - // Installed fonts apply from the next frame; a child window draws on here, so ask for - // that frame (the root draws nothing on the frame it installs them). - ctx.request_repaint(); } else if figcraft_text::system_fonts_scanned() { // Once the system fonts are indexed: faces for names in scripts the UI fonts lack, and // for each CJK script once something shows it. @@ -120,15 +117,13 @@ impl FigApp { } // egui's zoom is for the whole app and multiplies each window's own system scale, so the // size is the same relative to every screen; the main window, whose size can hold a size - // back, sets it. The browser keeps its own zoom. Every window records its own plan (the - // Preferences warning and `ui.inspect` read it), from its own size. + // back, sets it: the runtime applies the main window's plan as the interface scale + // (`FigApp::before_input`). The browser keeps its own zoom. Every window records its own + // plan (the Preferences warning and `ui.inspect` read it), from its own size. { let window_px = ctx.content_rect().size() * ctx.pixels_per_point(); let size = if cfg!(target_arch = "wasm32") { 1.0 } else { self.session.prefs.ui_scale }; let plan = ui_scale::plan(size, ctx.native_pixels_per_point(), Some((window_px.x, window_px.y))); - if ctx.viewport_id() == egui::ViewportId::ROOT { - ctx.set_zoom_factor(plan.zoom); - } // A size that just changed (a key, Preferences, a command) draws at the new size from // the next frame: ask for it rather than wait for the next input. if plan != self.ui.ui_scale { @@ -168,27 +163,11 @@ impl FigApp { } // Setup once per frame (pass 0), not once per pass and never on a logic-only tick. let stamp = (ctx.viewport_id(), ctx.cumulative_frame_nr()); - let first = !self.fonts_installed; if ctx.current_pass_index() == 0 && self.ui_frame_stamp != Some(stamp) { self.ui_frame_stamp = Some(stamp); self.frame_stats.record(&ctx); self.ui_setup(&ctx); } - if first && self.fonts_installed { - // New fonts apply from the next frame; draw nothing until then. Anything taken into - // this frame's (undrawn) input waits for the first drawn frame. - ctx.request_repaint(); - if let Some(events) = self.applied_input.take() { - self.push_control_input(events); - } - self.input_acks.append(&mut self.applied_acks); - self.applied_frame = None; - self.control_synthetic = false; - // The next (drawn) frame ticks for itself in a direct harness. - self.logic_ticked = false; - self.observe_ime(&ctx, false); - return; - } windows::begin(self, &ctx); let (files, prefs) = (self.session.docs.len(), self.session.prefs.clone()); self.frame(ui); @@ -222,6 +201,9 @@ impl FigApp { /// One frame of the window drawing now. pub(crate) fn frame(&mut self, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); + // Before anything reads the keys: the window's Escape, which the runtime routes to no + // component while nothing has the keyboard, reaches FigCraft's handlers through egui. + crate::framework::return_window_escape(&ctx); // Bind this input batch before controls or pointer input can replace its composing // target/caret. Outgoing IME receipts run after mutation and cannot authorize it. let ime_input = shortcuts::ImeInputBaseline::capture(self); @@ -263,7 +245,7 @@ impl FigApp { dialogs::keys(self, &ctx); present::show(self, ui); dialogs::show(self, &ctx); - updates_ui::show(self, &ctx); + updates_ui::show(self, ui); // What went wrong while presenting (a widget's plugin failing) shows over it. self.toast_ui(&ctx); windows::requests(self, &ctx); @@ -284,7 +266,7 @@ impl FigApp { } dialogs::keys(self, &ctx); dialogs::show(self, &ctx); - updates_ui::show(self, &ctx); + updates_ui::show(self, ui); self.toast_ui(&ctx); windows::requests(self, &ctx); shortcuts::clear_field_save_marker(&ctx); @@ -431,7 +413,7 @@ impl FigApp { self.end_unwanted_text_preview(&ctx); self.end_pen_outside_design(); dialogs::show(self, &ctx); - updates_ui::show(self, &ctx); + updates_ui::show(self, ui); // A scrub that changed speed (the pointer moved up or down) says so at the bottom. if let Some(notice) = ctx.data_mut(|d| d.remove_temp::<&'static str>(widgets::scrub_notice_id())) { self.toast(i18n::tr(notice)); diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 3d3f05082..db3efcfdc 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -252,6 +252,8 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) { let ctx = ui.ctx().clone(); let ppp = ctx.pixels_per_point(); let resp = ui.interact(rect, ui.scope_id().with("canvas"), Sense::click_and_drag()); + // The window's document canvas: with nothing focused its keys stay in egui for the shortcuts. + crate::framework::host_canvas(&ctx, resp.id); let key_box = app.ui.key_box; crate::a11y::canvas(&mut app.ui.nav, &resp, || key_box.map_or_else(|| describe(&app.session), describe_box)); if let Ok(ds) = app.session.ds_mut() { diff --git a/crates/ui-egui/src/combo_menu.rs b/crates/ui-egui/src/combo_menu.rs new file mode 100644 index 000000000..62eb014b6 --- /dev/null +++ b/crates/ui-egui/src/combo_menu.rs @@ -0,0 +1,155 @@ +//! The searchable drop-down menus under a field FigCraft draws itself (the font family picker, the +//! component swap menu): a menu that offers its contents the full height on every pass, so a list +//! that shrank while it was open (a search with no matches) grows back (egui#5225), with a header +//! (the search field) that stays in place above the scrolled list. + +use std::ops::Range; + +use egui::accesskit::Role; +use egui::style::StyleModifier; +use egui::{Align, Context, Frame, Popup, PopupCloseBehavior, Rect, RectAlign, Response, ScrollArea, TextWrapMode, Ui}; + +/// A menu under a field. It opens below the field, or above it when there is more room there, and +/// stays on that side while it is open. It is never taller than the room on that side: a long list +/// scrolls. +#[must_use = "You should call .show*"] +pub(crate) struct Menu<'a> { + popup: Popup<'a>, + ctx: Context, + field: Rect, + height: f32, + style: StyleModifier, + close_behavior: PopupCloseBehavior, +} + +impl<'a> Menu<'a> { + /// The menu under `field`, a widget in `ui`. + pub(crate) fn new(ui: &Ui, field: &Response) -> Self { + // Below the field or above it, never beside it. + let flipped: &'static [RectAlign] = if ui.ctx().global_style().right_to_left { &[RectAlign::TOP_END] } else { &[RectAlign::TOP_START] }; + Self { + popup: Popup::menu(field).align_alternatives(flipped), + ctx: field.ctx.clone(), + field: field.rect, + height: ui.spacing().combo_height, + style: StyleModifier::from(egui::containers::menu::menu_style), + close_behavior: PopupCloseBehavior::CloseOnClick, + } + } + + /// The maximum height of the menu's contents, inside its frame, kept to the room on its side + /// of the field. + pub(crate) fn height(mut self, height: f32) -> Self { + self.height = height; + self + } + + /// When the menu closes. + pub(crate) fn close_behavior(mut self, close_behavior: PopupCloseBehavior) -> Self { + self.close_behavior = close_behavior; + self + } + + /// The menu's style. + pub(crate) fn style(mut self, style: impl Into) -> Self { + self.style = style.into(); + self + } + + /// Shows `header` at the top of the menu and `list` under it while the menu is open, and + /// returns what `list` returned. `list` gets what `header` returned, such as the rows a search + /// field's text matches. Only `list` scrolls; the header stays in place. `list` lays out in a + /// vertical scroll area: give it rows, not a scroll area of its own. + pub(crate) fn show_ui_with_header(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(&mut Ui, H) -> R) -> Option { + self.show(header, |scroll, ui, h| scroll.show(ui, |ui| list(ui, h)).inner) + } + + /// Like [`Self::show_ui_with_header`], with a list of `total_rows(&header's)` rows, each + /// `row_height` tall without the item spacing, that only lays out the rows in view: `rows` + /// gets the range to add, as in [`ScrollArea::show_rows`], and what `header` returned. + pub(crate) fn show_rows_with_header( + self, + header: impl FnOnce(&mut Ui) -> H, + row_height: f32, + total_rows: impl FnOnce(&H) -> usize, + rows: impl FnOnce(&mut Ui, Range, H) -> R, + ) -> Option { + self.show(header, move |scroll, ui, h| { + let total = total_rows(&h); + scroll.show_rows(ui, row_height, total, |ui, range| rows(ui, range, h)).inner + }) + } + + fn show(self, header: impl FnOnce(&mut Ui) -> H, list: impl FnOnce(ScrollArea, &mut Ui, H) -> R) -> Option { + let Self { popup, ctx, field, height, style, close_behavior } = self; + let id = popup.get_id(); + let (align, settled) = side(&popup); + // Until the side is settled, the menu is measured against the whole screen. + let room = match popup.get_anchor_rect() { + Some(anchor) if settled => room(align, anchor, ctx.content_rect()), + _ => ctx.content_rect().height(), + }; + let mut popup_style = (*ctx.global_style()).clone(); + style.apply(&mut popup_style); + let frame = Frame::popup(&popup_style).total_margin().sum().y; + let height = height.min(room - frame).max(0.0); + let inner = popup + .align(align) + .align_alternatives(&[]) + .width(field.width()) + .style(style) + .close_behavior(close_behavior) + .show(|ui| { + ui.set_min_width(ui.available_width()); + // The popup offers last pass's height. Offer the full height instead: the scroll + // area takes what the header leaves of it, then shrinks to the list. + ui.set_max_height(height); + let header = header(ui); + // Labels widen a narrow menu rather than wrap early, as in egui's combo box. A + // list left with no room keeps ScrollArea's minimum scrolled height. + ui.style_mut().wrap_mode = Some(TextWrapMode::Extend); + list(ScrollArea::vertical().max_height(ui.available_height().max(0.0)), ui, header) + }) + .map(|r| r.inner); + if inner.is_some() { + ctx.accesskit_node_builder(id, |node| node.set_role(Role::ListBox)); + } + inner + } +} + +/// The side of its field `popup` shows on, and whether it is settled. The side is settled on the +/// first pass after the menu was shown and measured: the side egui picks when the menu fits there, +/// else the one with more room. It is kept while the menu stays open, so a menu that shrinks or +/// grows while open doesn't jump to the other side. +fn side(popup: &Popup<'_>) -> (RectAlign, bool) { + let ctx = popup.ctx(); + let key = popup.get_id().with("figcraft-menu-side"); + if !popup.is_open() || ctx.read_response(popup.get_id()).is_none() { + ctx.data_mut(|d| d.remove::(key)); + return (popup.get_best_align(), false); + } + if let Some(align) = ctx.data(|d| d.get_temp::(key)) { + return (align, true); + } + // Outside the data lock: these read the popup's state from memory. + let mut align = popup.get_best_align(); + if let (Some(size), Some(anchor)) = (popup.get_expected_size(), popup.get_anchor_rect()) { + let screen = ctx.content_rect(); + let flipped = align.flipped_y(); + if room(align, anchor, screen) < size.y && room(flipped, anchor, screen) > room(align, anchor, screen) { + align = flipped; + } + } + ctx.data_mut(|d| d.insert_temp(key, align)); + (align, true) +} + +/// The height a menu on the `align` side of `anchor` has inside `screen`. +fn room(align: RectAlign, anchor: Rect, screen: Rect) -> f32 { + match (align.parent.y(), align.child.y()) { + (Align::Max, Align::Min) => screen.bottom() - anchor.bottom(), + (Align::Min, Align::Max) => anchor.top() - screen.top(), + _ => screen.height(), + } +} diff --git a/crates/ui-egui/src/dialogs/updates_ui.rs b/crates/ui-egui/src/dialogs/updates_ui.rs index 0cd8dab79..251c22bc8 100644 --- a/crates/ui-egui/src/dialogs/updates_ui.rs +++ b/crates/ui-egui/src/dialogs/updates_ui.rs @@ -1,13 +1,17 @@ -//! Software updates, background check at startup, and startup prompt modal. +//! Software updates, background check at startup, and startup prompt modal. The flow itself is +//! `craft_update::updater::Updater`; its dialogs run on the app's +//! [`DialogHost`](craft_ui::dialog::DialogHost) ([`FigApp::framework_dialogs`]). use crate::FigApp; #[cfg(target_arch = "wasm32")] use crate::i18n::tr; #[cfg(not(target_arch = "wasm32"))] -use craft_update::updater::{Action, Status, Updater}; +use craft_ui::dialog::DialogResult; #[cfg(not(target_arch = "wasm32"))] -use craft_update::{CheckResultDialog, CheckResultResponse}; +use craft_update::stack_dialogs::{CheckChoice, UpdateCheckDialog}; +#[cfg(not(target_arch = "wasm32"))] +use craft_update::updater::{Action, Status, Updater}; pub(crate) struct Runtime { #[cfg(not(target_arch = "wasm32"))] @@ -83,9 +87,9 @@ pub(crate) fn tick(app: &mut FigApp, ctx: &egui::Context) { let rt = &mut app.updates_rt; rt.repaint = Some(ctx.clone()); if std::mem::take(&mut rt.check_requested) { - rt.updater.check_now(ctx); + rt.updater.check_now(); } else if rt.startup_check { - rt.updater.check_at_start(ctx); + rt.updater.check_at_start(); } rt.updater.tick(ctx); } @@ -101,27 +105,52 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { !prompt_open && !matches!(status, Status::Idle) } -pub(crate) fn show(app: &mut FigApp, ctx: &egui::Context) { +/// One frame of the update flow, in the main window only: answers the result dialog closed in the +/// last pass, drives the startup prompt, keeps the result dialog open and current while the updater +/// has something to report, then runs the dialog host. +pub(crate) fn show(app: &mut FigApp, ui: &mut egui::Ui) { + let ctx = ui.ctx().clone(); #[cfg(not(target_arch = "wasm32"))] { + if ctx.viewport_id() != egui::ViewportId::ROOT { + return; + } // The updater asks to close only when no document has unsaved changes; the install starts when the app exits. let clean = !app.session.docs.iter().any(|d| d.is_dirty()); - match app.updates_rt.updater.show_if(ctx, clean) { + // Answered before the dialog is kept open below, so a dismissed outcome does not open again at once. + match app.framework_dialogs.take::() { + Some(DialogResult::Ok(CheckChoice::CheckNow | CheckChoice::CheckAgain)) => app.updates_rt.check_requested = true, + // The next `run` asks the window to close once no document has unsaved changes. + Some(DialogResult::Ok(CheckChoice::RestartToUpdate)) => app.updates_rt.updater.restart_to_update(), + Some(DialogResult::Ok(CheckChoice::Update)) => { + app.updates_rt.updater.request_install(clean); + } + Some(DialogResult::Ok(CheckChoice::Download)) => ctx.open_url(egui::OpenUrl::new_tab(crate::UPDATE_APP.releases_url())), + // Closing the dialog dismisses the outcome it showed. + Some(_) => app.updates_rt.updater.dismiss_status(), + None => {} + } + match app.updates_rt.updater.run(&mut app.framework_dialogs, clean) { Action::OpenUrl(url) => ctx.open_url(egui::OpenUrl::new_tab(url)), // The whole application, not just the window that drew the prompt: the root window's guarded close. Action::Close => ctx.send_viewport_cmd_to(egui::ViewportId::ROOT, egui::ViewportCommand::Close), - Action::None => {} + _ => {} } - let rt = &mut app.updates_rt; - if result_window_shows(rt.updater.status(), rt.updater.prompt_open()) { - match CheckResultDialog::new(&crate::UPDATE_APP, env!("CARGO_PKG_VERSION")).show(ctx, rt.updater.status()) { - CheckResultResponse::None => {} - CheckResultResponse::Close => rt.updater.dismiss_status(), - CheckResultResponse::CheckAgain => rt.check_requested = true, - // The next `show_if` asks the window to close once no document has unsaved changes. - CheckResultResponse::RestartToUpdate => rt.updater.restart_to_update(), - } + let updater = &app.updates_rt.updater; + let shows = result_window_shows(updater.status(), updater.prompt_open()); + let (status, installing, message) = (updater.status().clone(), updater.is_installing(), updater.status_message()); + let dialogs = &mut app.framework_dialogs; + if shows && !dialogs.is_open::() { + dialogs.open(UpdateCheckDialog::new(env!("CARGO_PKG_VERSION"))); + } else if !shows && dialogs.is_open::() { + dialogs.cancel::(&ctx); } + if let Some(dialog) = dialogs.get_mut::() { + dialog.set_status(status); + dialog.set_installing(installing); + dialog.set_message(message); + } + app.framework_dialogs.run(ui); } #[cfg(target_arch = "wasm32")] @@ -133,7 +162,7 @@ pub(crate) fn show(app: &mut FigApp, ctx: &egui::Context) { .resizable(false) .collapsible(false) .anchor(egui::Align2::CENTER_CENTER, egui::vec2(0.0, 0.0)) - .show(ctx, |ui| { + .show(&ctx, |ui| { if let Some(msg) = &app.updates_rt.status_message { ui.label(msg); } diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs new file mode 100644 index 000000000..95805c72d --- /dev/null +++ b/crates/ui-egui/src/framework.rs @@ -0,0 +1,165 @@ +//! The craft-ui runtime, hosted from FigCraft's own eframe `App` (craft-libs docs/craft-framework.md, section 2.2). +//! The desktop app calls [`install`] once, [`FigApp::before_input`] in `raw_input_hook`, [`FigApp::close_path`] last +//! in `logic`, and [`before_ui`] first in `ui`; the browser build and tests install with [`install_headless`]. The +//! framework dialogs (the update dialogs) run on [`FigApp::framework_dialogs`] after FigCraft's own UI. +//! +//! The runtime takes Escape, Tab and the clipboard events for the whole window unless one of FigCraft's own egui +//! widgets has the keyboard. [`return_window_escape`] puts the window's Escape back into egui's input at the start of +//! each window's frame, so FigCraft's dialogs, menus, tools and shortcuts read it from egui as they read every other +//! key. The canvas is declared to the runtime with [`host_canvas`], which keeps Tab, the edit chords, the clipboard +//! events and FigCraft's Alt+digit panel keys in egui's input for its shortcuts while nothing has the keyboard; a +//! canvas that holds egui's focus (keyboard navigation) keeps Escape too, as one of FigCraft's own widgets does. + +use std::sync::{Arc, OnceLock}; + +use craft_host::target::ShellInfo; +use craft_host::{AppInfo, Host}; +use craft_keymap::{Chord, Mods, Overrides}; +use craft_ui::fonts::{I18nScripts, SystemFonts, UiFonts}; +use craft_ui::runtime::commands::{CommandInput, CommandSet as _, NavCommand}; +use craft_ui::runtime::env::{RootEnv, Scale}; +use craft_ui::runtime::focus::{EditSet, KeepKeys, KeyUse}; +use craft_ui::runtime::frame::{FrameInput, FrameOutput}; +use craft_ui::runtime::keys::{Intent, with_window_intents}; +use craft_ui::shell::embed; +use craft_window::system::WindowSystem; +use figcraft_engine::keymap::{KEYS, Platform}; + +use crate::FigApp; + +/// Each pass of the root window, first in `App::ui`: hands the runtime the native window it answers the hit test of +/// (Windows) and fits the window to its monitor once. +#[cfg(not(target_arch = "wasm32"))] +pub use craft_ui::shell::embed::before_ui; + +/// The id every OS window of the app carries, as the main window's builder sets it. +const APP_ID: &str = "ai.storyteller.figcraft"; + +/// The scripts of the interface languages, for the font stack. +static SCRIPTS: I18nScripts = I18nScripts; + +/// The runtime's first font stack: egui's bundled faces and no installed system fonts. FigCraft's own definitions +/// ([`crate::theme::install_fonts`]) replace it before anything is drawn. +fn ui_fonts() -> UiFonts<'static> { + UiFonts::new(&SCRIPTS).system_fonts(SystemFonts::Off) +} + +fn install_with(ctx: &egui::Context, shell: ShellInfo, windows: Arc) -> Result<(), String> { + let spec = craft_ui::InstallSpec::new(shell, windows).app_id(APP_ID); + embed::install(ctx, spec, &ui_fonts()).map(drop).map_err(|error| format!("the UI runtime could not be installed: {error}")) +} + +/// Installs the runtime on the desktop window's context, once, before the first pass. FigCraft draws its own title +/// bar where it has one (`TitleBar::Custom` and `TitleBar::Inset`), so no frame decision is handed over and the +/// runtime answers no hit test of the window. +#[cfg(not(target_arch = "wasm32"))] +pub fn install(ctx: &egui::Context) -> Result<(), String> { + let shell = ShellInfo::default().backend(craft_host::target::Backend::from_env()); + install_with(ctx, shell, Arc::new(craft_window::system::SystemWindows)) +} + +/// Installs the runtime on a context with no native window of its own: the browser build's canvas and test windows. +pub fn install_headless(ctx: &egui::Context) { + if let Err(error) = install_with(ctx, ShellInfo::default(), Arc::new(craft_window::system::NoWindows)) { + log::warn!("{error}"); + } +} + +/// A context with the runtime installed and no native window, for the test windows that draw FigCraft's UI. +pub fn headless_context() -> egui::Context { + let ctx = egui::Context::default(); + install_headless(&ctx); + ctx +} + +/// Who FigCraft is to the framework's dialogs (the update dialogs show its name and icon). +pub(crate) fn host() -> Arc { + let builder = Host::builder(AppInfo { id: "figcraft", name: "FigCraft", version: env!("CARGO_PKG_VERSION") }); + #[cfg(not(target_arch = "wasm32"))] + let builder = builder.icon_png(include_bytes!("../../../assets/app-icon/hicolor/128x128/apps/ai.storyteller.figcraft.png")); + Arc::new(builder.build()) +} + +/// F6 and Shift+F6 are FigCraft's own region moves (`view.nextRegion`, `view.previousRegion`), so the framework's pane +/// moves are unbound. Overrides are keyed by command id, which the command set gives. +fn command_overrides() -> Arc { + static OVERRIDES: OnceLock> = OnceLock::new(); + OVERRIDES + .get_or_init(|| { + let mut overrides = Overrides::new(); + overrides.insert(NavCommand::NextPane.id(), Vec::new()); + overrides.insert(NavCommand::PreviousPane.id(), Vec::new()); + Arc::new(overrides) + }) + .clone() +} + +/// The Alt+digit chords FigCraft's keymap binds (the panel keys, Alt+1 Layers and the rest). On Windows and Linux +/// the runtime's Alt+numpad code entry takes every Alt+digit a canvas does not claim. +fn alt_digit_claims() -> &'static [Chord] { + static CLAIMS: OnceLock> = OnceLock::new(); + CLAIMS.get_or_init(|| { + let mut claims: Vec = KEYS + .iter() + .flat_map(|binding| binding.keys(Platform::Mac).iter().chain(binding.keys(Platform::Other))) + .filter_map(|spec| Chord::parse(spec).ok()) + .filter(|chord| chord.mods == Mods::ALT && chord.key.is_digit()) + .collect(); + claims.sort(); + claims.dedup(); + claims + }) +} + +impl FigApp { + /// The framework's part of `App::raw_input_hook`, once per frame before the first pass: takes what the runtime + /// gathered since the last frame and gives the coming passes the root values (theme mode, interface scale and + /// direction). + pub fn before_input(&mut self, ctx: &egui::Context) { + embed::before_input(ctx, |output| self.frame_input(output)); + } + + /// The root values of this frame. FigCraft registers no commands with the runtime and lets it toggle no chrome, so + /// the output carries nothing it acts on. The interface scale is the main window's plan + /// ([`crate::ui_scale::plan`], recorded by its last pass): the runtime is the one writer of egui's zoom factor. A + /// Ctrl+wheel stays a wheel event: FigCraft's canvas reads it itself (Preferences ▸ Scroll wheel zoom swaps it with + /// the plain wheel). + fn frame_input(&mut self, _output: FrameOutput) -> FrameInput { + let mode = if self.ui.dark { craft_theme::Mode::Dark } else { craft_theme::Mode::Light }; + let direction = if self.ui.mirrored { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr }; + let root = RootEnv::new().mode(mode).scale(Scale::new(self.ui.ui_scale.zoom)).direction(direction).ctrl_wheel_pinch(false); + FrameInput::new(root).commands(CommandInput::new().overrides(command_overrides())).host(Arc::clone(&self.framework_host)) + } + + /// The framework's part of `App::logic`, last, after FigCraft's own logic: the main window's close path, decided + /// by [`crate::windows::close_decision`]. + pub fn close_path(&mut self, ctx: &egui::Context) { + embed::logic(ctx, || crate::windows::close_decision(self, ctx)); + } +} + +/// Declares the canvas `id`, drawn in this pass, as its window's document canvas. With nothing focused it is the +/// window's key target: Tab, the edit chords, the clipboard events and the Alt+digit panel keys stay in egui's input +/// for FigCraft's shortcuts, as do the arrows, Enter and the page keys. +pub(crate) fn host_canvas(ctx: &egui::Context, id: egui::Id) { + let keys = KeyUse::CANVAS.with_keep(KeepKeys::Tab).with_edits(EditSet::ALL).with_claims(alt_digit_claims()); + craft_ui::runtime::focus::host_canvas(ctx, id, keys); +} + +/// Puts the window's Escape (an Escape while none of FigCraft's widgets and no framework component has the keyboard, +/// which the runtime routes to the window as its cancel) back into egui's input as a key press, first in the window's +/// frame, so FigCraft's dialogs, menus, tools and shortcuts read it from egui as they read every other key. +pub(crate) fn return_window_escape(ctx: &egui::Context) { + let mut taken = false; + with_window_intents(ctx, false, |intents| { + taken = intents.take(Intent::Cancel); + taken + }); + if taken { + ctx.input_mut(|i| { + let modifiers = i.modifiers; + let key = egui::Key::Escape; + i.events.insert(0, egui::Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }); + }); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 32d859f6c..a6b907e08 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -18,8 +18,10 @@ pub mod a11y; pub mod bidi; pub mod canvas; pub mod cjk; +mod combo_menu; pub mod control; pub mod dialogs; +pub mod framework; pub mod home; pub mod i18n; pub mod icons; @@ -876,6 +878,10 @@ pub struct FigApp { pub(crate) ime: egui::ime_context::ImeContextTracker, /// The check for a newer release and its prompt (desktop; [`updates_ui`]). pub(crate) updates_rt: updates_ui::Runtime, + /// The framework dialogs (the update dialogs), run once per frame after the main window's UI. + pub framework_dialogs: craft_ui::dialog::DialogHost, + /// Who FigCraft is to the framework's dialogs ([`framework::host`]). + pub(crate) framework_host: std::sync::Arc, /// Test-only count of the one IME observation each viewport pass makes. #[cfg(test)] pub(crate) ime_observations: u32, diff --git a/crates/ui-egui/src/panels/component_panel.rs b/crates/ui-egui/src/panels/component_panel.rs index 08f5c543d..311db0ba8 100644 --- a/crates/ui-egui/src/panels/component_panel.rs +++ b/crates/ui-egui/src/panels/component_panel.rs @@ -887,7 +887,7 @@ fn component_menu<'a>( checked: impl Fn(NodeId) -> bool, ) -> Option { let opened = field.clicked(); - craft_ui::combo::Menu::new(ui, field) + crate::combo_menu::Menu::new(ui, field) .height(COMP_MENU_HEIGHT) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .style(crate::right::menu_style) diff --git a/crates/ui-egui/src/panels/typography/picker.rs b/crates/ui-egui/src/panels/typography/picker.rs index 11c040805..be14d87cb 100644 --- a/crates/ui-egui/src/panels/typography/picker.rs +++ b/crates/ui-egui/src/panels/typography/picker.rs @@ -76,7 +76,7 @@ pub(crate) fn font_picker( let hi_id = Id::unique("font_highlight"); let q_id = Id::unique("font_query"); let search_id = Id::unique("font_search"); - craft_ui::combo::Menu::new(ui, anchor) + crate::combo_menu::Menu::new(ui, anchor) .height(MENU_HEIGHT) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .style(crate::right::menu_style) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 784ada713..5a06452de 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -371,7 +371,9 @@ pub fn install_fonts(ctx: &Context, system: bool, cjk: u8) { } } } - ctx.set_fonts(fonts); + // Through the runtime's font loader: it records what framework text reads of the definitions + // (the semibold family FigCraft defines above), and a pass that installs them is laid out again. + craft_ui::fonts::load(ctx, fonts); } /// The glyphs macOS shortcuts are written with ([`figcraft_engine::keymap::display`]). diff --git a/crates/ui-egui/src/ui_scale.rs b/crates/ui-egui/src/ui_scale.rs index 3a407dcf8..e2574004c 100644 --- a/crates/ui-egui/src/ui_scale.rs +++ b/crates/ui-egui/src/ui_scale.rs @@ -15,7 +15,7 @@ const ZOOM_RANGE: (f32, f32) = (0.1, 10.0); /// What to give egui for a saved choice on this screen and window. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Plan { - /// For `Context::set_zoom_factor`: the size drawn, relative to the system's scale. + /// The interface scale the runtime applies (`RootEnv::scale`): the size drawn, relative to the system's scale. pub zoom: f32, /// Physical pixels per point once drawn (the zoom times the system's scale). pub drawn: f32, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c0e838e4d..3af729ecd 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -10,6 +10,7 @@ use std::cell::RefCell; +use craft_ui::shell::embed::CloseDecision; use egui::{Context, Pos2, Vec2, ViewportBuilder, ViewportCommand, ViewportId}; use figcraft_engine::{DocState, Session}; use serde_json::{Value, json}; @@ -373,21 +374,30 @@ pub fn list(app: &FigApp) -> Value { ) } -/// The window drawing now was asked to close (its close button, the system's): its files close -/// with it, after asking when one has unsaved changes. The main window closes last: while other -/// windows are open it takes over one of them. The desktop app calls it from the main window's -/// `logic` (which runs even while the window is minimised); other windows call it themselves. +/// Another window drawing now was asked to close (its close button, the system's): its files +/// close with it, after asking when one has unsaved changes. The main window's close goes through +/// the runtime's close path ([`close_decision`]). pub fn on_close_request(app: &mut FigApp, ctx: &Context) { if app.ui.quit || !ctx.input(|i| i.viewport().close_requested()) { return; } - let unsaved = !app.unsaved().is_empty(); - if app.windows.current == 0 && (unsaved || !app.windows.list.is_empty()) { - ctx.send_viewport_cmd(ViewportCommand::CancelClose); - } request_close(app, ctx); } +/// The main window was asked to close (its close button, the system's, a quit): its files close +/// with it, after asking when one has unsaved changes. The main window closes last: while other +/// windows are open it takes over one of them, and the window stays open. Runs in the runtime's +/// close path ([`FigApp::close_path`]), from the main window's `logic`, which runs even while the +/// window is minimised. +pub(crate) fn close_decision(app: &mut FigApp, ctx: &Context) -> CloseDecision { + if app.ui.quit { + return CloseDecision::Close; + } + let hold = !app.unsaved().is_empty() || !app.windows.list.is_empty(); + request_close(app, ctx); + if hold { CloseDecision::Hold } else { CloseDecision::Close } +} + /// The custom title bar's Close button uses the same unsaved-file check as a system close event. pub(crate) fn request_close(app: &mut FigApp, ctx: &Context) { if !app.unsaved().is_empty() {