diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index df93dc6bac..2d2f5e9f4c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -140,7 +140,7 @@ impl VectorcraftApp { momentary: None, selection_box: None, selection_bounds: None, - content_bounds: None, + content_bounds: Vec::new(), variable_rows: None, three_d_exportable: None, pixel_aligned: None, diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 1e1de5ae93..a1ab70c788 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -482,16 +482,32 @@ impl VectorcraftApp { /// The art and the artboards together, the span of the canvas's scroll bars: measured once /// per revision, as the canvas reads it every frame. pub fn content_bounds(&mut self) -> Option { - let st = self.session.active()?; + let index = self.session.active_index()?; + self.content_bounds_of(index) + } + + /// The art and the artboards together of the document at `index`, the size each of its windows' canvases fits + /// and scrolls in: measured once per revision of each open document, as every canvas pass reads it. + pub(crate) fn content_bounds_of(&mut self, index: usize) -> Option { + let docs = self.session.documents(); + let st = docs.get(index)?; let key = (st.uid, st.revision); - if let Some((k, b)) = self.canvas.content_bounds - && k == key - { - return b; + if let Some((_, b)) = self.canvas.content_bounds.iter().find(|(k, _)| *k == key) { + return *b; } + #[cfg(test)] + CONTENT_MEASURES.with(|n| n.set(n.get() + 1)); let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); let b = vectorcraft_geom::union_opt(st.doc.art_bounds(), boards); - self.canvas.content_bounds = Some((key, b)); + // An older revision of this document and the documents that have closed leave the cache. + self.canvas.content_bounds.retain(|((uid, _), _)| *uid != key.0 && docs.iter().any(|d| d.uid == *uid)); + self.canvas.content_bounds.push((key, b)); b } } + +#[cfg(test)] +thread_local! { + /// How many times this thread measured a document's content bounds ([`VectorcraftApp::content_bounds_of`]). + pub(crate) static CONTENT_MEASURES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6907b7ce17..dfac727639 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -82,8 +82,8 @@ pub struct CanvasCache { pub selection_box: Option<((u64, u64, vectorcraft_effects::preview::Measure), Option)>, /// [`VectorcraftApp::selection_bounds`] for (document uid, revision). pub selection_bounds: Option<((u64, u64), Option)>, - /// [`VectorcraftApp::content_bounds`] for (document uid, revision). - pub content_bounds: Option<((u64, u64), Option)>, + /// [`VectorcraftApp::content_bounds_of`] for (document uid, revision), one entry for each open document. + pub content_bounds: Vec<((u64, u64), Option)>, /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). pub three_d_exportable: Option<((u64, u64), bool)>, diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2efe7e984a..49878cb2d8 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -429,13 +429,13 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace) -> Op } /// The size of the art and the artboards together, and the artboard Fit Artboard shows (the view's, -/// the first when it has gone). -pub(crate) fn view_target(app: &VectorcraftApp, win: Win) -> ViewTarget { +/// the first when it has gone). The size is measured once per document revision ([`VectorcraftApp::content_bounds_of`]). +pub(crate) fn view_target(app: &mut VectorcraftApp, win: Win) -> ViewTarget { + let all = app.content_bounds_of(win.0); let (Some(st), Some(view)) = (app.session.documents().get(win.0), doc_windows::view(app, win)) else { return ViewTarget::new(Size::new(1.0, 1.0)); }; - let boards = st.doc.artboards.iter().map(|a| a.rect).reduce(|r, a| r.union(a)); - let target = ViewTarget::new(document_size(vectorcraft_geom::union_opt(st.doc.art_bounds(), boards))); + let target = ViewTarget::new(document_size(all)); match st.doc.artboards.get(view.artboard).or(st.doc.artboards.first()) { Some(a) => target.artboard(a.rect), None => target, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3f1eddb392..3fc37f6433 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6700,3 +6700,42 @@ fn a_move_stops_snapping_to_guides_hidden_during_it() { assert!((centre - xf.to_doc(near).x).abs() < 1e-4 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); } } + +/// The canvas measures the art and the artboards once per document revision, not in every pass: frames that change +/// nothing measure nothing, an edit measures once, and two open documents keep a measure each. +#[test] +fn the_canvas_measures_the_document_once_per_revision() { + let measures = || crate::app::view::CONTENT_MEASURES.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for i in 0..20 { + let x = f64::from(i) * 15.0; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 20, "width": 10, "height": 10})).unwrap(); + } + let ctx = crate::testing::ui_context(); + for _ in 0..3 { + app_step(&mut app, &ctx, vec![]); + } + let before = measures(); + for _ in 0..10 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 0, "frames that change nothing measure nothing"); + app.session.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 10, "height": 10})).unwrap(); + for _ in 0..5 { + app_step(&mut app, &ctx, vec![]); + } + assert_eq!(measures() - before, 1, "an edit measures once"); + let win = crate::doc_windows::current(&app).unwrap(); + let size = super::view_target(&mut app, win).document; + assert!(size.width >= 510.0 && size.height >= 410.0, "the new rectangle is in the size: {size:?}"); + + app.session.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let before = measures(); + for _ in 0..5 { + for index in 0..2 { + let _ = super::view_target(&mut app, (index, 0)); + } + } + assert_eq!(measures() - before, 1, "the new document is measured once, and the first keeps its measure"); +} diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 9848d86f1a..6a922f0c41 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -1,9 +1,11 @@ use super::{ROTATE_VIEW_ANGLES, Ui, VectorcraftApp, json}; -use craft::behavior::IconId; use craft::behavior::kurbo::Size; +use craft::behavior::{CanvasView, IconId}; use craft::ui::bars::{Bar, BarKind, StatusMessage, StatusProgress}; use craft::ui::buttons::{Button, IconButton}; -use craft::ui::contract::{Bind, BodyCx, Entry, Gap, LabelKind, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger}; +use craft::ui::contract::{ + Bind, BodyCx, Entry, Gap, LabelKind, MemoProps, MemoView, Outbox, Outcome as _, Props as _, Show as _, ShowContainer as _, SideLabel, Trigger, +}; use craft::ui::display::{Divider, Elide, Shade, Text}; use craft::ui::form::Field; use craft::ui::layout_components::Row; @@ -22,33 +24,31 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { ui.ctx().request_repaint_after(std::time::Duration::from_secs(secs)); } let print = app.print_ppi(); - let nab = app.session.active().map(|d| d.doc.artboards.len()).unwrap_or(0); + let st = app.session.active(); + let nab = st.map_or(0, |d| d.doc.artboards.len()); let cur = crate::panels::artboards::selected(app, nab); - // PLAN: assumed Artboard::rect has `width()` and `height()`. - let document = - app.session.active().and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); - let boards: Vec> = app - .session - .active() - .map(|d| d.doc.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect()) - .unwrap_or_default(); - let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); let view = app.view(); let rotation = view.map_or(0.0, |v| v.rotation); + let lang = crate::i18n::current(); + let canvas_view = app.canvas_view(); + // PLAN: assumed Artboard::rect has `width()` and `height()`. + let document = st.and_then(|d| d.doc.artboards.get(cur)).map_or(Size::new(1.0, 1.0), |a| Size::new(a.rect.width(), a.rect.height())); + let scaling = app.ui_scaling(); let turned = ROTATE_VIEW_ANGLES.iter().position(|(_, a)| (rotation - a).abs() < 1e-9).unwrap_or(usize::MAX); // An angle between the presets, from the Rotate View tool or `view.rotate`, shows in whole degrees; adding 0.0 // turns the -0 of a small negative angle into 0. - let angle = format!("{}°", rotation.round() + 0.0); + let degrees = rotation.round() + 0.0; + let revision = st.map(|d| (d.uid, d.revision)); + let artboards = st.map_or(&[][..], |d| d.doc.artboards.as_slice()); + let mut picks = Vec::new(); let shows: Vec> = StatusBarShow::ALL.into_iter().map(|s| Entry::new(s, s.label()).checked(app.ui.status_bar_show == s)).collect(); let unit = app.session.general_unit(); - let lang = crate::i18n::current(); let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); let busy = busy_labels(app); - let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false); - let mut invalid_zoom = None; + let (mut show_pick, mut stop) = (None, false); let mut snapping = None; // Convenience controls leave first: direct toggles, then the menu. The existing timings and pointer position // retain their priority, and all trailing groups leave before the navigation, info field or message narrows. @@ -90,56 +90,21 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }; // PLAN: assumed VectorcraftApp::canvas_view() -> Option (cv.S4) and the label msgid "Status Bar". Bar::new(tl!("Status Bar"), BarKind::Status).trailing(readouts).show(ui, |ui, _| { - let zoom = Field::new(tl!("Zoom")) - .side(SideLabel::new().kind(LabelKind::Hidden)) - .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui)); - // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. - if let Some(zoom) = zoom.inner { - if let Some(view) = zoom.view.committed() { - zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print)); - } - invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui))); - } - Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // Entries are keyed by index: an angle is not a hashable value. - rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) - .placeholder(angle.clone()) - .look(SelectLook::Filled) - .enabled(view.is_some()) - .show(ui) - .events - .committed() - .copied(); - }); - Divider::vertical().show(ui); - for (icon, to, tip, enabled) in - [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } - Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { - // With no document the navigator shows a dash, as the info readout does. - if let Some(i) = Select::new(tl!("Artboard"), Bind::given(cur), &boards) - .placeholder("\u{2013}") - .look(SelectLook::Filled) - .enabled(nab > 0) - .show(ui) - .events - .committed() - .copied() - { - go = Some(json!(i)); - } - }); - for (icon, to, tip, enabled) in - [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] - { - if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { - go = Some(json!(to)); - } - } + let navigation = Navigation { + view: canvas_view, + document, + scaling, + print, + has_view: view.is_some(), + turned, + degrees, + cur, + revision, + artboards, + lang, + picked: Outbox::new(&mut picks), + }; + let _ = MemoView::new("status-bar-navigation", navigation, show_navigation).show(ui); Divider::vertical().show(ui); // An empty readout shows a dash. let shown = if info.is_empty() { "\u{2013}" } else { info.as_str() }; @@ -174,6 +139,16 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some((id, params)) = snapping { crate::menus::invoke(app, id, params); } + // The last choice of each kind counts, as the controls report one choice of each in a pass. + let (mut zoom_to, mut invalid_zoom, mut rotate_to, mut go) = (None, None, None, None); + for pick in picks { + match pick { + NavigationPick::Zoom(zoom) => zoom_to = Some(zoom), + NavigationPick::InvalidZoom(message) => invalid_zoom = Some(message), + NavigationPick::Rotate(i) => rotate_to = Some(i), + NavigationPick::Artboard(to) => go = Some(to), + } + } // It fails only without a document, when there is no view to turn or zoom. if let Some(zoom) = zoom_to { app.run("view.setZoom", json!({"zoom": zoom})).ok(); @@ -196,6 +171,118 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// What the status bar's navigation controls read: the Zoom field, the Rotation menu and the artboard navigator. The +/// bar replays them while these hold still and nothing reaches them (`MemoView`), as most frames only move the +/// readouts. +#[derive(MemoProps)] +struct Navigation<'a> { + /// The canvas view the Zoom field shows and edits. + view: Option, + /// The size of the artboard the navigator shows, which the Zoom field fits. + document: Size, + /// UI Scaling, which divides the canvas view's zoom. + scaling: f32, + /// The density zoom percentages count from ([`VectorcraftApp::print_ppi`]). + print: Option, + /// Whether the active document has a view to turn. + has_view: bool, + /// The Rotate View preset the view is turned to, else `usize::MAX`. + turned: usize, + /// The view's angle in whole degrees, shown when it is between the presets. + degrees: f64, + /// The artboard the navigator shows. + cur: usize, + /// The active document's uid and revision. + revision: Option<(u64, u64)>, + #[memo_props(covered_by = "revision", reason = "a document's uid and revision change with every edit of it")] + artboards: &'a [vectorcraft_doc::Artboard], + #[memo_props(hash = "an interface language: an index into the languages offered")] + lang: crate::i18n::Lang, + /// What the controls chose in the pass. + picked: Outbox<'a, NavigationPick>, +} + +/// A choice made in the status bar's navigation controls ([`Navigation`]). +enum NavigationPick { + /// The view's zoom percentage the Zoom field committed (`view.setZoom`). + Zoom(f64), + /// The message of a zoom the Zoom field could not read. + InvalidZoom(String), + /// The Rotate View preset chosen (an index into [`ROTATE_VIEW_ANGLES`]). + Rotate(usize), + /// The `index` of `view.goToArtboard`: an artboard's index, or first, previous, next or last. + Artboard(serde_json::Value), +} + +/// The Zoom field, the Rotation menu and the artboard navigator of the status bar, from [`Navigation`]. +fn show_navigation(p: &mut Navigation<'_>, ui: &mut Ui) { + #[cfg(test)] + tests::NAVIGATION_RUNS.with(|n| n.set(n.get() + 1)); + let (view, document) = (p.view, p.document); + let zoom = Field::new(tl!("Zoom")) + .side(SideLabel::new().kind(LabelKind::Hidden)) + .show(ui, |ui, _| ZoomField::new(tl!("Zoom"), view, document).scrub(true).show(ui)); + // The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom. + if let Some(zoom) = zoom.inner { + if let Some(view) = zoom.view.committed() { + let percent = crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, p.scaling), p.print); + p.picked.send(NavigationPick::Zoom(percent)); + } + if let Some(invalid) = zoom.invalid_zoom { + p.picked.send(NavigationPick::InvalidZoom(invalid.message(&Env::of(ui)))); + } + } + let angles: Vec> = ROTATE_VIEW_ANGLES.iter().enumerate().map(|(i, (label, _))| Entry::new(i, *label)).collect(); + let (turned, angle, has_view) = (p.turned, format!("{}°", p.degrees), p.has_view); + let mut rotate_to = None; + Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // Entries are keyed by index: an angle is not a hashable value. + rotate_to = Select::new(tl!("Rotation"), Bind::given(turned), &angles) + .placeholder(angle.clone()) + .look(SelectLook::Filled) + .enabled(has_view) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = rotate_to { + p.picked.send(NavigationPick::Rotate(i)); + } + Divider::vertical().show(ui); + let (cur, nab) = (p.cur, p.artboards.len()); + for (icon, to, tip, enabled) in + [("chevrons_left", "first", tl!("First Artboard"), cur > 0), ("chevron_left", "previous", tl!("Previous Artboard"), cur > 0)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } + let boards: Vec> = p.artboards.iter().enumerate().map(|(i, a)| Entry::new(i, format!("{} {}", i + 1, a.name))).collect(); + let mut go = None; + Field::new(tl!("Artboard")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| { + // With no document the navigator shows a dash, as the info readout does. + go = Select::new(tl!("Artboard"), Bind::given(cur), &boards) + .placeholder("\u{2013}") + .look(SelectLook::Filled) + .enabled(nab > 0) + .show(ui) + .events + .committed() + .copied(); + }); + if let Some(i) = go { + p.picked.send(NavigationPick::Artboard(json!(i))); + } + for (icon, to, tip, enabled) in + [("chevron_right", "next", tl!("Next Artboard"), cur + 1 < nab), ("chevrons_right", "last", tl!("Last Artboard"), cur + 1 < nab)] + { + if IconButton::new(IconId::new(icon)).label(tip).enabled(enabled).show(ui).clicked() { + p.picked.send(NavigationPick::Artboard(json!(to))); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -272,6 +359,44 @@ mod tests { } } + thread_local! { + /// How many times this thread ran the status bar's navigation controls ([`show_navigation`]). + pub(super) static NAVIGATION_RUNS: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + /// Frames that change nothing the navigation controls show replay them instead of laying them out again; a new + /// zoom or a new artboard runs them once, and they show it. + #[test] + fn idle_frames_replay_the_navigation_controls() { + let runs = || NAVIGATION_RUNS.with(std::cell::Cell::get); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.view_mut().unwrap().rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, 400.0)); + let mut panel = Panel::new(app, status_bar); + panel.room(egui::vec2(1200.0, 300.0)); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames run the navigation controls no more"); + panel.app().run("view.setZoom", json!({"zoom": 200})).unwrap(); + panel.frame(); + panel.frame(); + assert!(runs() > before, "a new zoom runs them again"); + assert_eq!(panel.value("Zoom").as_deref(), Some("200%"), "and the field shows it"); + panel.app().run("artboard.new", json!({"x": 400, "y": 50, "width": 100, "height": 80, "name": "Back"})).unwrap(); + panel.frame(); + panel.frame(); + let before = runs(); + for _ in 0..10 { + panel.frame(); + } + assert_eq!(runs() - before, 0, "idle frames after an edit run them no more"); + assert!(panel.enabled("Next Artboard") || panel.enabled("Previous Artboard"), "the navigator counts the new artboard"); + } + #[test] fn with_no_document_the_artboard_navigator_shows_a_dash() { let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());