From e317a77e270cdca436aea40bf893020feb699df8 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:27:16 +0700 Subject: [PATCH] canvas-w29: net change of 2 commits - canvas-w29: written from its sheet - canvas-w29: repair 1 --- crates/ui-egui/src/canvas/panes.rs | 643 ++++++------------ crates/ui-egui/src/canvas/panes/tests.rs | 802 ++++++----------------- 2 files changed, 435 insertions(+), 1010 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 63d89f2be2..c54bb3c6de 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,43 +1,82 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document //! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the -//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its -//! document from a render of its own, with its artboards, guides and selected objects, and a press -//! in it makes its document the current one. A Selection drag released in it drops the dragged -//! artwork into its document ([`crate::document_drag::drop_on_pane`]). Each view Window › New -//! Window opened has a pane of its own ([`crate::doc_windows`]). +//! rest under their tabs ([`Layout`]). The panes are the panes of a [`SplitViews`]. The current +//! document's pane is the live canvas; each other pane shows its document as a picture from a render +//! of its own ([`pane_picture`]), and a press in it makes its document the current one. Each view +//! Window › New Window opened has a pane of its own ([`crate::doc_windows`]). use std::collections::HashMap; use std::sync::Arc; -use super::grid::LineLook; -use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; -use super::view::fit_zoom; -use super::{ - Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, - cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, - rulers, shows_artboards, textured_quad, vec2, view_rects, -}; -use crate::doc_windows::Win; -use crate::thumb_worker::ThumbWorker; +use craft_ui::canvas::{SplitAt, SplitLayout, SplitViews}; +use craft_ui::contract::{Bind, ShowContainer as _}; +use craft_ui::primitives::textures::{LoadedPicture, Priority, Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails}; -/// A pane's render: what it shows, the document, its size in pixels and view, and its options. -type PaneFrame = (CacheKey, Arc, ((u32, u32), Affine), vectorcraft_render::RenderOptions); +use super::{Affine, BodyKind, CacheKey, Point, Tokens, Ui, VectorcraftApp, View, backdrop, cache_key, frame_options, frame_ppp, frame_view, json}; +use super::{pixel_region, placed_key, plugin_key}; +use crate::doc_windows::Win; /// Whose render a pane draws: its document's uid and its view's number. type Slot = (u64, u32); -/// The renders that the panes of the windows other than the current one draw. +/// The margin, in points, a pane's fit leaves around the artboard. +const FIT_MARGIN: f64 = 30.0; + +/// The key of a pane's picture in the [`Thumbnails`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) struct PaneKey { + /// The document's uid and the view's number. + slot: Slot, +} + +/// What a pane's render needs, owned so the render can run off the UI thread. +struct PaneFrame { + key: PaneKey, + /// Fingerprint of everything the picture shows: the render's cache key. + revision: Revision, + cache: CacheKey, + doc: Arc, + /// The frame's size in pixels and the view it is rendered through. + size: (u32, u32), + view: Affine, + opts: vectorcraft_render::RenderOptions, + // PLAN: assumed `craft_color_ui::display::DisplayTransform`, the type canvas-w12's `render_pane` takes. + display: Option>, + cms: Arc, + /// Where the picture lies on the screen: the pane's art area, or the document pixels' rect in Pixel Preview. + placed: egui::Rect, +} + +/// The [`ThumbSource`] of one pane's frame. +pub(super) struct PaneSource { + frame: PaneFrame, +} + +impl ThumbSource for PaneSource { + fn revision(&self, _: &PaneKey, _: &ThumbRequest) -> Revision { + self.frame.revision + } + + fn render(&self, _: &PaneKey, _: &ThumbRequest) -> ThumbRender { + let f = &self.frame; + let (doc, opts, display, cms, cache, (w, h), view) = (f.doc.clone(), f.opts.clone(), f.display.clone(), f.cms.clone(), f.cache.clone(), f.size, f.view); + ThumbRender::Later(Box::new(move |_| { + let mut renderer = vectorcraft_render::Renderer::new(); + let img = render_pane(&mut renderer, (&doc, w, h, view, &opts), display.as_deref(), cms, cache.over()); + Ok(LoadedPicture::Image(super::raster::color_image_owned(img))) + })) + } +} + +/// The thumbnails the panes' pictures live in. +fn thumbnails(ctx: &egui::Context) -> Thumbnails { + let max_side = ctx.input(|i| i.max_texture_side) as u32; + Thumbnails::in_context(ctx, "vectorcraft.panes", ThumbnailOptions::new().max_side(max_side)) +} + +/// The windows' pane state of the tiled and floating windows other than the current one. #[derive(Default)] pub struct Panes { - /// Renders off the UI thread (None: on it, as on wasm). - worker: Option>, - pub(crate) worker_started: bool, - /// Renders on the UI thread when there is no worker. - renderer: Option, - /// By slot: the render shown and what it shows. - pub(crate) shown: HashMap, - /// By slot: the render the worker is making. - pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, /// The slots of `last`'s windows, in the same order: which windows they were, as document @@ -46,132 +85,17 @@ pub struct Panes { /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, - /// By slot: the outlines of the selected objects the pane drew last, and what they show. - outlines: HashMap, - /// How many times a pane's outlines were made. - outlines_made: u64, -} - -/// A pane's selected-object outlines as screen shapes, and the document revision, document, -/// selection and screen mapping they were made for. -struct Outlines { - revision: u64, - /// A weak reference to the document: while it exists, no other document can take the - /// allocation's address. - doc: std::sync::Weak, - selection: Vec, - affine: [f64; 6], - shapes: Vec, -} - -impl Outlines { - /// Whether these outlines show `st`'s selection through the screen mapping `affine`. - fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool { - self.revision == st.revision && self.doc.ptr_eq(&Arc::downgrade(&st.doc)) && self.affine == *affine && self.selection == st.selection.objects - } + /// Where the dividers between the tiled panes lie. + at: SplitAt, } impl Panes { - /// Forget every render and pane. + /// Forget every pane. The pictures go with the next frame that does not tile. fn clear(&mut self) { - self.shown.clear(); - self.pending.clear(); self.last.clear(); self.last_slots.clear(); self.fits.clear(); - self.outlines.clear(); - } - - /// Upload `img`, the render `key` describes, for `slot`. - fn upload(&mut self, ctx: &egui::Context, slot: Slot, key: CacheKey, img: &vectorcraft_render::Rendered) { - let color = super::color_image(img); - // Pixel Preview's document pixels show hard-edged, as on the canvas. - let options = if key.pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; - match self.shown.get_mut(&slot) { - Some((k, tex)) => { - tex.set(color, options); - *k = key; - } - None => { - let tex = ctx.load_texture(format!("arrange-pane-{}-{}", slot.0, slot.1), color, options); - self.shown.insert(slot, (key, tex)); - } - } - } - - /// Bring `slot`'s render up to `key` (`size` pixels through `view`), on the worker when there - /// is one, converted into the display profile `display`, then draw the slot's latest render - /// through `xf`, turned and scaled into the view it was rendered for. - fn draw( - &mut self, - ctx: &egui::Context, - painter: &egui::Painter, - xf: &Xf, - slot: Slot, - frame: PaneFrame, - display: Option>, - ) { - let (key, doc, ((w, h), view), opts) = frame; - if !self.worker_started { - self.worker_started = true; - self.worker = ThumbWorker::spawn(ctx, "arrange-panes"); - } - match self.worker.as_ref().map(ThumbWorker::poll) { - Some(Some(done)) => { - for d in done { - let (s, k) = d.key; - if self.pending.get(&s) == Some(&k) { - self.pending.remove(&s); - } - if let Some(img) = d.img { - self.upload(ctx, s, k, &img); - } - } - } - // The thread is gone: render here from now on. - Some(None) => { - self.worker = None; - self.pending.clear(); - } - None => {} - } - let current = self.shown.get(&slot).is_some_and(|(k, _)| *k == key) || self.pending.get(&slot) == Some(&key); - if !current { - // The document draws through its own assigned profiles, not the front document's, on - // the worker too. - let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(&doc); - let mut queued = false; - if let Some(worker) = &self.worker { - let (job_doc, job_opts, job_display, job_cms, job_key) = (doc.clone(), opts.clone(), display.clone(), cms.clone(), key.clone()); - queued = worker.submit( - slot, - (slot, key.clone()), - Box::new(move |r| Some(render_pane(r, (&job_doc, w, h, view, &job_opts), job_display.as_deref(), job_cms, job_key.over()))), - ); - if queued { - self.pending.insert(slot, key.clone()); - } else { - self.worker = None; - } - } - if !queued { - let r = self.renderer.get_or_insert_with(vectorcraft_render::Renderer::new); - let img = render_pane(r, (&doc, w, h, view, &opts), display.as_deref(), cms, key.over()); - self.upload(ctx, slot, key, &img); - } - } - if let Some((k, tex)) = self.shown.get(&slot) { - // Document pixels: placed over the document rect they cover. - if let Some([x0, y0, x1, y1]) = k.pixel { - textured_quad(painter, tex.id(), &xf.quad(Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64)), (1.0, 1.0)); - return; - } - let ppp = if k.ppp > 0.0 { k.ppp } else { 1.0 }; - let old_rect = egui::Rect::from_center_size(xf.rect.center(), vec2(k.w as f32 / ppp, k.h as f32 / ppp)); - let old = Xf { rect: old_rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: k.rot.to_radians() }; - let q = [old_rect.left_top(), old_rect.right_top(), old_rect.right_bottom(), old_rect.left_bottom()].map(|c| xf.to_screen(old.to_doc(c))); - textured_quad(painter, tex.id(), &q, (1.0, 1.0)); - } + self.at = SplitAt::default(); } } @@ -181,7 +105,7 @@ impl Panes { fn render_pane( r: &mut vectorcraft_render::Renderer, (doc, w, h, view, opts): (&vectorcraft_doc::Document, u32, u32, Affine, &vectorcraft_render::RenderOptions), - display: Option<&vectorcraft_color::cms::display::DisplayTransform>, + display: Option<&craft_color_ui::display::DisplayTransform>, cms: Arc, over: Option<(&crate::display_profile::Backdrop, f64)>, ) -> vectorcraft_render::Rendered { @@ -191,6 +115,65 @@ fn render_pane( img } +/// The frame window `w`'s pane renders, painted into `space`; `None` when the window has no document. +fn pane_frame(app: &mut VectorcraftApp, ui: &Ui, space: egui::Rect, w: Win) -> Option { + let ctx = ui.ctx(); + let t = Tokens::get(ctx); + let ppp = ctx.pixels_per_point(); + let ui_zoom = ctx.zoom_factor(); + let v = crate::doc_windows::view(app, w).copied()?; + let st = app.session.documents().get(w.0)?; + let cv = v.canvas(ui_zoom, space); + // View › Pixel Preview, as the canvas draws it. + let max_side = ctx.input(|i| i.max_texture_side); + // PLAN: assumed `pixel_region(&CanvasView, max_side)`, the replacement of the `Xf` form. + let pixel = (app.ui.view.pixel_preview && v.screen_zoom(ui_zoom) * f64::from(ppp) > 1.0).then(|| pixel_region(&cv, max_side)).flatten(); + // The pane's frame fits the largest texture side the display supports, as the canvas's does. + let ppp = frame_ppp(space.size(), ppp, max_side); + let side = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)); + let (pw, ph) = (side(space.width()), side(space.height())); + let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; + let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); + let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st); + let drawn = v.on_screen(ui_zoom); + let mut cache = cache_key(app, ui, st, &t, &drawn, (pw, ph, ppp), (pixel, smooth_images, plugins, placed)); + // The current document's drag and Image Trace hold are not this document's, and this view has + // its own Outline or Preview. + (cache.dragging, cache.trace_source, cache.outline) = (false, None, v.outline); + cache.backdrop = backdrop(app, st, v.outline); + let opts = frame_options(app, &cache, st.shown_mask(), smooth_images); + let (fw, fh, view) = frame_view(pixel, (pw, ph), &drawn, ppp); + let on_screen = match pixel { + Some([x0, y0, x1, y1]) => egui::Rect::from_two_pos(cv.to_screen(Point::new(x0 as f64, y0 as f64)), cv.to_screen(Point::new(x1 as f64, y1 as f64))), + None => space, + }; + Some(PaneFrame { + key: PaneKey { slot: (st.uid, w.1) }, + revision: Revision::of(&format!("{cache:?}")), + cache, + doc: st.doc.clone(), + size: (fw, fh), + view, + opts, + display: app.display_profile.transform(app.session.prefs.monitor_profile_display), + cms: vectorcraft_engine::cmd::colormgmt::doc_cms(&st.doc), + placed: on_screen, + }) +} + +/// Paint window `w`'s picture over `space`, its art area, from the render of its document: the +/// previous picture shows until a new one lands. +pub(super) fn pane_picture(app: &mut VectorcraftApp, ui: &mut Ui, space: egui::Rect, w: Win) { + let Some(frame) = pane_frame(app, ui, space, w) else { return }; + let ctx = ui.ctx().clone(); + let request = ThumbRequest::for_cell(space.width().max(space.height()), ctx.pixels_per_point()); + let (key, placed) = (frame.key, frame.placed); + let state = thumbnails(&ctx).state(&ctx, &PaneSource { frame }, &key, &request, Priority::VISIBLE); + if let Some(texture) = state.shown() { + ui.painter_at(space).image(texture.id, placed, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + } +} + /// How Tile lays out the panes (`window.arrange.tile`'s `layout`). #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Layout { @@ -242,40 +225,22 @@ impl Layout { _ => n, } } - - /// How many columns the layout puts `n` panes in. - fn columns(self, n: usize) -> usize { - match self { - Layout::Grid => grid_columns(n), - Layout::Vertical => n, - Layout::Horizontal => 1, - Layout::Up(k) if k <= 3 => n, - Layout::Up(k) => grid_columns(k).min(n), - } - } } -/// The square root of `n` rounded up. -fn grid_columns(n: usize) -> usize { - let mut cols = 1; - while cols * cols < n { - cols += 1; +/// The arrangement `layout` lays `shown` panes out in: an n-up layout with fewer panes than cells +/// uses the smaller arrangement that holds them. +fn arrangement(layout: Layout, shown: usize) -> SplitLayout { + match layout { + Layout::Grid => SplitLayout::Tile, + Layout::Vertical => SplitLayout::TileAllVertically, + Layout::Horizontal => SplitLayout::TileAllHorizontally, + Layout::Up(k) => match (k, shown) { + (_, 0..=2) => SplitLayout::TwoUpVertical, + (4, _) => SplitLayout::FourUp, + (6, 4..) => SplitLayout::SixUp, + _ => SplitLayout::ThreeUpVertical, + }, } - cols -} - -/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns -/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to -/// edge and cover `area`; the spare cells of the last row stay empty. -pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; - } - let cols = layout.columns(n).clamp(1, n); - let rows = n.div_ceil(cols); - let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; - let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; - (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } /// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of @@ -306,6 +271,7 @@ pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result bool { let n = docked.len(); let tiling = app.ui.tiled && n > 1 && app.ui.screen_mode < 3 && !crate::menus::home_showing(app); if !tiling { - // The floating windows draw their panes from the same renders. - if app.ui.floating.is_empty() && (!app.canvas.panes.shown.is_empty() || !app.canvas.panes.last.is_empty()) { - app.canvas.panes.clear(); + // The floating windows draw their panes from the same pictures. + if app.ui.floating.is_empty() { + thumbnails(ui.ctx()).retain(ui.ctx(), |_| false); + app.canvas.panes.fits.clear(); } app.canvas.panes.last.clear(); - // Only the floating windows draw panes now. - let floating = &app.ui.floating; - app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n)); app.canvas.panes.last_slots.clear(); return false; } @@ -347,13 +311,11 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { let layout = app.ui.tile_layout; let shown = shown_windows(layout, &docked, active); app.sync_views(); - // The renders of the panes and the floating windows stay; a window under its tab has none. + // The pictures of the panes and the floating windows stay; a window under its tab has none. let live: Vec = crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); - app.canvas.panes.shown.retain(|s, _| live.contains(s)); - app.canvas.panes.pending.retain(|s, _| live.contains(s)); + thumbnails(ui.ctx()).retain(ui.ctx(), |k| live.contains(&k.slot)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - app.canvas.panes.outlines.retain(|s, _| live.contains(s)); // A window that moved to another pane fits it, and so does a window whose pane changed place or // size because a window opened, closed, floated or docked, or because the panes came back from // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its @@ -362,8 +324,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { // documents after it, and panes by their place in the layout. let before = std::mem::take(&mut app.canvas.panes.last_slots); let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); - let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); - let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); + let unit = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::Vec2::splat(1.0)); + let place = |count: usize| SplitAt::default().rects(arrangement(layout, count), count, unit); + let (cells_before, cells_now) = (place(before.len()), place(now.len())); for (i, (w, s)) in shown.iter().zip(&now).enumerate() { if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { continue; @@ -373,131 +336,53 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { } } app.canvas.panes.last_slots = now; - let t = Tokens::get(ui.ctx()); - let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); - let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); - let unfitted = refit_resized(app, &areas); - let mut activate = None; - let (mut cursor, mut dropped) = (None, None); - // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) - // stays over them. - for ((w, cell), (_, area)) in cells.iter().copied().zip(areas.iter().copied()).filter(|((w, _), _)| Some(*w) != active) { - if pane(app, ui, w, cell) { - activate = Some(w); + let arranged = arrangement(layout, shown.len()); + let active_pane = active.and_then(|a| shown.iter().position(|w| *w == a)).unwrap_or(0); + let mut lines = std::mem::take(&mut app.canvas.panes.at); + let placed = lines.clone(); + let mut cells: Vec<(Win, egui::Rect)> = vec![]; + let split = SplitViews::new("Documents", arranged, Bind::bound(&mut lines)).count(shown.len()).active(active_pane).show(ui, |ui, body| { + cells = shown.iter().copied().zip(placed.placed(arranged, shown.len(), body.rect, body.env.direction().is_rtl())).collect(); + let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, art_area(app, *w, *cell))).collect(); + let unfitted = refit_resized(app, &areas); + // The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar) + // stays over them. + for (w, cell) in cells.iter().copied().filter(|(w, _)| Some(*w) != active) { + pane(app, ui, w, cell); } - match artwork_over(app, ui, w, area) { - Some(Over::Held(c)) => cursor = Some(c), - Some(Over::Released(at, carried)) => dropped = Some((w, at, carried)), - None => {} + if let Some((w, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) { + show_body(app, ui, w, cell, BodyKind::Live); } - ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); - } - if let Some((_, cell)) = cells.iter().copied().find(|(w, _)| Some(*w) == active) { - let mut canvas = ui.new_child(egui::UiBuilder::new().max_rect(cell)); - super::show(app, &mut canvas); - ui.painter().rect_stroke(cell, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); - } - // After the canvas, which sets the cursor of the drag it holds. - if let Some(c) = cursor { - ui.ctx().set_cursor_icon(c); - } - // Note the fits this frame made, for `refit_resized`. - for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { - if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { - app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); + // Note the fits this frame made, for `refit_resized`. + for ((w, area), was_unfitted) in areas.iter().zip(unfitted) { + if let (true, Some(v), Some(s)) = (was_unfitted, crate::doc_windows::view(app, *w).filter(|v| v.fitted).copied(), slot(app, *w)) { + app.canvas.panes.fits.insert(s, (area.size(), v.zoom, v.center)); + } } - } + }); + let activated = split.output.activated; + app.canvas.panes.at = lines; app.canvas.panes.last = cells; - if let Some((w, at, carried)) = dropped { - crate::document_drag::drop_on_pane(app, ui.ctx(), w, at, carried); - } else if let Some(w) = activate { + if let Some(&(w, _)) = activated.and_then(|i| app.canvas.panes.last.get(i)) { crate::doc_windows::show_window(app, w); } true } -/// A Selection drag's artwork over another window's tiled pane. -enum Over { - /// Held there: the cursor that shows whether a release moves or copies it. - Held(egui::CursorIcon), - /// Released there, at a document point in the pane's own view. - Released(Point, crate::document_drag::Carried), -} - -/// A Selection drag's artwork over `area`, the part of window `w`'s pane inside its rulers and -/// scroll bars, where no panel or floating window is over the pointer. A release there takes the -/// artwork before the canvas sees the release ([`crate::document_drag::take_for_pane`]). -fn artwork_over(app: &mut VectorcraftApp, ui: &Ui, w: Win, area: egui::Rect) -> Option { - let (uid, _) = slot(app, w)?; - let p = ui.input(crate::document_drag::released_at)?; - if !area.contains(p) || ui.ctx().layer_id_at(p).is_some_and(|l| l != ui.layer_id()) { - return None; - } - let cursor = crate::document_drag::pane_cursor(app, ui.ctx(), uid)?; - if !ui.input(|i| i.pointer.primary_released()) { - return Some(Over::Held(cursor)); - } - let v = crate::doc_windows::view(app, w).copied()?; - let at = Xf::at(area, &v, ui.ctx().zoom_factor()).to_doc(p); - Some(Over::Released(at, crate::document_drag::take_for_pane(app, ui.ctx())?)) -} - -/// Note window `w`'s pane, drawn in `cell` of `ui` outside Tile (a floating window inside the main -/// window, or the main window while the current window floats), as a place a Selection drag's -/// artwork can be released in ([`release_on_noted`]): the part inside its rulers and scroll bars. -pub(crate) fn note_drop(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) { - let Some(s) = slot(app, w) else { return }; - let area = view_rects(app, cell, ui.ctx().pixels_per_point()).1; - app.canvas.windows.drops.push((s, area, ui.layer_id())); -} - -/// The noted pane ([`note_drop`]) at `p`, where no panel or other window is over it: its window -/// and its art area. -fn noted_at(app: &VectorcraftApp, ctx: &egui::Context, p: egui::Pos2) -> Option<(Win, egui::Rect)> { - let top = ctx.layer_id_at(p); - let (s, area, _) = app.canvas.windows.drops.iter().rev().find(|(_, area, layer)| area.contains(p) && top.is_none_or(|l| l == *layer))?; - let w = crate::doc_windows::windows(app).into_iter().find(|w| slot(app, *w) == Some(*s))?; - Some((w, *area)) -} - -/// A Selection drag's artwork released over a pane the last frame noted ([`note_drop`]) drops into -/// its document ([`crate::document_drag::drop_on_pane`]), at the document point where the button -/// went up, in that pane's own view. Runs at the start of a frame, before any canvas sees the release. -pub(crate) fn release_on_noted(app: &mut VectorcraftApp, ctx: &egui::Context) { - if app.canvas.windows.drops.is_empty() || !ctx.input(|i| i.pointer.primary_released()) { - return; - } - let Some(p) = ctx.input(crate::document_drag::released_at) else { return }; - let Some((w, area)) = noted_at(app, ctx, p) else { return }; - let Some(v) = crate::doc_windows::view(app, w).copied() else { return }; - let at = Xf::at(area, &v, ctx.zoom_factor()).to_doc(p); - if let Some(carried) = crate::document_drag::take_for_pane(app, ctx) { - crate::document_drag::drop_on_pane(app, ctx, w, at, carried); - } -} - -/// While a Selection drag's artwork is held over a pane this frame noted ([`note_drop`]), the cursor -/// shows whether a release there moves or copies it ([`crate::document_drag::pane_cursor`]). -pub(crate) fn noted_cursor(app: &VectorcraftApp, ctx: &egui::Context) { - let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; - if let Some((w, _)) = noted_at(app, ctx, p) - && let Some((uid, _)) = slot(app, w) - && let Some(c) = crate::document_drag::pane_cursor(app, ctx, uid) - { - ctx.set_cursor_icon(c); - } -} - /// Window `w`'s [`Slot`]. fn slot(app: &VectorcraftApp, (i, n): Win) -> Option { app.session.documents().get(i).map(|d| (d.uid, n)) } +/// The area window `w`'s view shows its art in: what its body last showed, `cell` before the first. +fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect { + crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell) +} + /// Unfit each window whose view is still where a pane fit left it when its view's area (`areas`, /// by window) has changed size, as when the window or a panel is resized: it fits its pane again. /// A view zoomed or scrolled since keeps its place. → which of `areas`' views are unfitted now. -fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)]) -> Vec { +pub(crate) fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)]) -> Vec { areas .iter() .map(|(w, area)| { @@ -515,141 +400,47 @@ fn refit_resized(app: &mut VectorcraftApp, areas: &[(Win, egui::Rect)]) -> Vec CanvasView` and `View::set_canvas(&CanvasView, ui_scaling)` (cv.S4). + let mut view = v.canvas(ui_zoom, area); + craft_behavior::canvas::zoom::fit_rect(&mut view, target, target.size(), pixels_per_point, kurbo::Vec2::new(FIT_MARGIN, FIT_MARGIN), scheme); + v.set_canvas(&view, ui_zoom); v.fitted = true; } } -/// The pane of window `w` (document `i`'s view `n`), not the current one, in `cell`: its paper, -/// art, grid, artboards, guides and selected objects, and its rulers and the room of the canvas's -/// scroll bars, so the document stays where it is when the pane becomes the canvas. True when a -/// press in the pane asks for its window to become the current one. A floating window draws its -/// view with this too ([`crate::doc_windows`]). The document's colors, its paper and transparency -/// grid included, draw through its own assigned profiles, not the front document's. -pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool { +/// Fit window `w`'s view to its pane when it is unfitted. +fn fit_window(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, cell: egui::Rect) { + let area = art_area(app, w, cell); + let Some(doc) = app.session.documents().get(w.0).map(|st| st.doc.clone()) else { return }; + // PLAN: assumed `crate::view::zoom_scheme(&VectorcraftApp) -> craft_behavior::ZoomScheme` (cv.F13). + let scheme = crate::view::zoom_scheme(app); + if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { + fit_pane(v, &doc, area, (ctx.zoom_factor(), ctx.pixels_per_point()), &scheme); + } +} + +/// Window `w`'s document body of `kind` in `cell`, its view fitted first. True when a press in its +/// canvas background asks for its window to become the current one. +fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, w: Win, cell: egui::Rect, kind: BodyKind) -> bool { + fit_window(app, ui.ctx(), w, cell); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(cell)); + // PLAN: assumed `show_document(app, ui, win, kind) -> bool` (cv.S1 returns whether the background got a press). + super::show_document(app, &mut child, w, kind) +} + +/// The pane of window `w` (document `i`'s view `n`), not the current one, in `cell`: its picture +/// with the rulers, guides and selection the body draws over it. True when a press in the pane asks +/// for its window to become the current one. A floating window shows its view with this too +/// ([`crate::doc_windows`]). The document's colors, its paper and transparency grid included, draw +/// through its own assigned profiles, not the front document's. +pub(crate) fn pane(app: &mut VectorcraftApp, ui: &mut Ui, w: Win, cell: egui::Rect) -> bool { let Some(st) = app.session.documents().get(w.0) else { return false }; let cms = vectorcraft_engine::cmd::colormgmt::doc_cms(&st.doc); - vectorcraft_color::cms::with_active(cms, || draw_pane(app, ui, w, cell)) -} - -/// [`pane`], drawn through the color settings in place. -fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> bool { - let t = Tokens::get(ui.ctx()); - let ppp = ui.ctx().pixels_per_point(); - let (full, rect) = view_rects(app, cell, ppp); - let Some(st) = app.session.documents().get(w.0) else { return false }; - let doc = st.doc.clone(); - let ui_zoom = ui.ctx().zoom_factor(); - if let Some(v) = crate::doc_windows::view_mut(app, w).filter(|v| !v.fitted) { - fit_pane(v, &doc, rect, ui_zoom); - } - let v = crate::doc_windows::view(app, w).copied().unwrap_or_default(); - let Some(st) = app.session.documents().get(w.0) else { return false }; - let slot = (st.uid, w.1); - let xf = Xf::at(rect, &v, ui_zoom); - let painter = ui.painter_at(rect); - paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline)); - let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs)); - let grids_in_back = app.session.prefs.grids_in_back; - if let Some(look) = grid_look.filter(|_| grids_in_back) { - grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); - } - // View › Pixel Preview, as the canvas draws it. - let max_side = ui.ctx().input(|i| i.max_texture_side); - let pixel = (app.ui.view.pixel_preview && xf.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf, max_side)).flatten(); - // The pane's frame fits the largest texture side the display supports, as the canvas's does. - let ppp = frame_ppp(rect.size(), ppp, max_side); - let size = |l: f32| ((l * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)); - let (pw, ph) = (size(rect.width()), size(rect.height())); - let smooth_images = pixel.is_none() || app.session.prefs.anti_aliased_bitmaps; - let plugins = plugin_key(&mut app.canvas.plugin_keys, &app.session, st); - let placed = placed_key(&mut app.canvas.placed_keys, &app.session, st); - let drawn = v.on_screen(ui_zoom); - let mut key = cache_key(app, ui, st, &t, &drawn, (pw, ph, ppp), (pixel, smooth_images, plugins, placed)); - // The current document's drag and Image Trace hold are not this document's, and this view has - // its own Outline or Preview. - (key.dragging, key.trace_source, key.outline) = (false, None, v.outline); - key.backdrop = backdrop(app, st, v.outline); - let opts = frame_options(app, &key, st.shown_mask(), smooth_images); - let (fw, fh, view) = frame_view(pixel, (pw, ph), &drawn, ppp); - let doc = st.doc.clone(); - let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); - app.canvas.panes.draw(ui.ctx(), &painter, &xf, slot, (key, doc, ((fw, fh), view), opts), display); - let Some(st) = app.session.documents().get(w.0) else { return false }; - if let Some(look) = grid_look.filter(|_| !grids_in_back) { - grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); - } - if shows_artboards(app) { - artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); - } - if app.ui.view.guides_shown() { - guides_of(app, st, (&painter, &xf, &t), rect); - } - if app.ui.view.edges { - selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf); - } else { - app.canvas.panes.outlines.remove(&slot); - } - if app.ui.view.rulers && app.ui.screen_mode < 3 { - rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t); - } - if app.ui.screen_mode < 2 { - let bars = [ - egui::Rect::from_min_max(pos2(full.right(), cell.top()), cell.max), - egui::Rect::from_min_max(pos2(cell.left(), full.bottom()), cell.max), - ]; - for bar in bars { - ui.painter().rect_filled(bar, 0.0, t.ruler); - } - } - let resp = ui.interact(cell, egui::Id::unique(("arrange-pane", st.uid, w.1)), Sense::click_and_drag()); - resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed()) -} - -/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from -/// the outlines `panes` kept for the slot while they show the same revision, document, selection -/// and screen mapping, and made again otherwise. -fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { - let affine = xf.affine().as_coeffs(); - if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) { - let shapes = outline_shapes(st, xf); - let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: st.selection.objects.clone(), affine, shapes }; - panes.outlines.insert(slot, kept); - panes.outlines_made += 1; - } - for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) { - painter.add(shape.clone()); - } -} - -/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their -/// layers' colors; their bounds when they have too many points to outline. -fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { - let mut shapes = vec![]; - if st.selection.objects.is_empty() { - return shapes; - } - let symbols = st.doc.symbol_boxes(); - let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = - st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); - let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); - let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s))); - if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { - let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); - if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { - stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); - } - return shapes; - } - for (id, n) in nodes { - stroke(&node_outline(n, &symbols), color(id)); - } - shapes + vectorcraft_color::cms::with_active(cms, || show_body(app, ui, w, cell, BodyKind::Pane)) } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index b7829a7542..8b95c0f3e5 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -1,5 +1,7 @@ use std::collections::BTreeSet; +use std::time::Duration; +use craft_ui::primitives::textures::{CachedTexture, TextureState}; use egui::{Color32, Pos2, Shape}; use vectorcraft_engine::Session; use vectorcraft_geom::Rect; @@ -43,50 +45,120 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } -/// Tile's grid of `n` panes in `area`. -fn cells(n: usize, area: egui::Rect) -> Vec { - layout_cells(Layout::Grid, n, area) -} /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() } -#[test] -fn cells_tile_the_area_edge_to_edge() { - let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); - assert!(cells(0, area).is_empty()); - for (n, cols, rows) in [(1, 1, 1), (2, 2, 1), (3, 2, 2), (4, 2, 2), (5, 3, 2), (6, 3, 2), (7, 3, 3), (10, 4, 3)] { - let c = cells(n, area); - assert_eq!(c.len(), n); - let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); - let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); - assert_eq!((lefts.len(), tops.len()), (cols, rows), "{n} panes: columns and rows"); - assert_eq!((c[0].left(), c[0].top()), (area.left(), area.top()), "{n} panes start at the corner"); - for (i, r) in c.iter().enumerate() { - assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{n} panes: {r:?}"); - let last_column = i % cols == cols - 1; - match c.get(i + 1).filter(|_| !last_column) { - Some(next) => { - assert_eq!((r.right(), r.top(), r.bottom()), (next.left(), next.top(), next.bottom()), "{n} panes: {i} meets its neighbor") - } - None if last_column => assert_eq!(r.right(), area.right(), "{n} panes: {i} reaches the right edge"), - None => {} - } - match c.get(i + cols) { - Some(below) => assert_eq!(r.bottom(), below.top(), "{n} panes: {i} meets the pane below"), - None if i / cols == rows - 1 => assert_eq!(r.bottom(), area.bottom(), "{n} panes: {i} reaches the bottom"), - None => {} - } - for o in &c[i + 1..] { - assert!(r.intersect(*o).area() <= 0.0, "{n} panes overlap: {r:?} {o:?}"); - } +/// One headless frame of the canvas panel's body as [`frame`] runs it → the whole output. +fn run_out(app: &mut VectorcraftApp, ctx: &egui::Context) -> egui::FullOutput { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), + max_texture_side: Some(8192), + ..Default::default() + }; + ctx.run_ui(raw, |ui| app.canvas_area(ui)) +} + +/// Window `w`'s view as the pane body shows it, in its art area. +fn pane_view(app: &VectorcraftApp, w: Win) -> CanvasView { + let v = *crate::doc_windows::view(app, w).unwrap(); + v.canvas(app.ui_scaling(), v.rect) +} + +/// Whether window `w`'s 400 × 300 artboard is fitted to its pane: the view's extent of it lies in +/// the art area and, with the fit margin on both sides, fills it along one axis. +fn fits(app: &VectorcraftApp, w: Win) -> bool { + let Some(v) = crate::doc_windows::view(app, w) else { return false }; + let extent = pane_view(app, w).extent(Rect::new(0.0, 0.0, 400.0, 300.0)); + let room = v.rect.size() - vec2(2.0 * FIT_MARGIN, 2.0 * FIT_MARGIN); + v.fitted + && extent.x <= v.rect.width() + 0.01 + && extent.y <= v.rect.height() + 0.01 + && ((extent.x - room.x).abs() < 1.0 || (extent.y - room.y).abs() < 1.0) +} + +/// The source of window `w`'s pane picture, as the pane body builds it. +fn pane_source(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win) -> PaneSource { + let view = pane_view(app, w); + PaneSource::new(app, ctx, w, &view).expect("the window's document is open") +} + +/// What the thumbnails hold for document `uid`'s picture in the pane of `w`, asked without +/// starting a render. +fn picture_of(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, uid: u64) -> TextureState { + let view = pane_view(app, w); + let source = pane_source(app, ctx, w); + let thumbs = app.canvas.panes.thumbnails(ctx); + thumbs.hold(true); + let state = thumbs.state(ctx, &source, &PaneKey { uid, view: w.1 }, &request(&view, ctx.pixels_per_point()), Priority::VISIBLE); + thumbs.hold(false); + state +} + +/// Whether the thumbnails show something for document `uid`, asked through the pane of `w`. +fn has_picture(app: &mut VectorcraftApp, ctx: &egui::Context, w: Win, uid: u64) -> bool { + picture_of(app, ctx, w, uid).shown().is_some() +} + +/// Run frames with `run` until window `w`'s pane has its picture and the upload of it was seen, +/// starting from the uploads `seed` holds → the picture and every upload seen. +fn wait_ready( + app: &mut VectorcraftApp, + ctx: &egui::Context, + w: Win, + seed: Vec, + run: &mut dyn FnMut(&mut VectorcraftApp) -> egui::FullOutput, +) -> (CachedTexture, Vec) { + let uid = app.session.documents()[w.0].uid; + let mut uploads = seed; + for _ in 0..400 { + if let TextureState::Ready(texture) = picture_of(app, ctx, w, uid) + && uploads.iter().flat_map(|d| d.set.iter()).any(|e| e.0 == texture.id) + { + return (texture, uploads); } - let covered: f32 = c.iter().map(egui::Rect::area).sum(); - let whole = area.area() * n as f32 / (cols * rows) as f32; - assert!((covered - whole).abs() < 1.0, "{n} panes cover {covered}, not {whole}"); + let mut out = run(app); + uploads.push(std::mem::take(&mut out.textures_delta)); + std::thread::sleep(Duration::from_millis(5)); } + panic!("the pane of window {w:?} never got its picture"); +} + +/// The picture `id` as `uploads` uploaded it: its pixels and size. +fn uploaded(uploads: &[egui::TexturesDelta], id: egui::TextureId) -> (Vec, [usize; 2]) { + let image = uploads + .iter() + .rev() + .flat_map(|d| d.set.iter()) + .find(|e| e.0.eq(&id)) + .and_then(|e| e.1.last()) + .map(|d| d.image.clone()) + .expect("the picture was uploaded"); + let egui::ImageData::Color(img) = image; + (img.pixels.clone(), img.size) +} + +/// Drop every picture and pane the panes hold, so the next frames make them again. +fn forget(app: &mut VectorcraftApp, ctx: &egui::Context) { + app.canvas.panes.clear(); + app.canvas.panes.thumbnails(ctx).retain(ctx, |_| false); +} + +/// The RGB of the middle pixel of the picture window `(i, 1)`'s pane shows once it has arrived; +/// `seed` holds the uploads of frames already run and `run` runs the frames until then. +fn pane_middle( + app: &mut VectorcraftApp, + ctx: &egui::Context, + i: usize, + seed: Vec, + run: &mut dyn FnMut(&mut VectorcraftApp) -> egui::FullOutput, +) -> [u8; 3] { + let (texture, uploads) = wait_ready(app, ctx, (i, 1), seed, run); + let (pixels, [w, h]) = uploaded(&uploads, texture.id); + let p = pixels[h / 2 * w + w / 2]; + [p.r(), p.g(), p.b()] } /// The distinct left and top edges of `c`: how many columns and rows its panes take. @@ -96,67 +168,6 @@ fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { (lefts.len(), tops.len()) } -#[test] -fn each_tile_layout_places_its_panes_edge_to_edge() { - let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); - let cases = [ - (Layout::Vertical, 3, (3, 1)), - (Layout::Vertical, 7, (7, 1)), - (Layout::Horizontal, 3, (1, 3)), - (Layout::Up(2), 2, (2, 1)), - (Layout::Up(3), 3, (3, 1)), - (Layout::Up(3), 2, (2, 1)), - (Layout::Up(4), 4, (2, 2)), - (Layout::Up(4), 3, (2, 2)), - (Layout::Up(6), 6, (3, 2)), - (Layout::Up(6), 4, (3, 2)), - (Layout::Up(6), 2, (2, 1)), - ]; - for (layout, n, shape) in cases { - let c = layout_cells(layout, n, area); - assert_eq!(c.len(), n); - assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); - assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); - let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); - let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); - assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); - for (i, r) in c.iter().enumerate() { - assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); - for o in &c[i + 1..] { - assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); - } - } - } - assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); -} - -#[test] -fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { - let mut app = app_with(3); - let ctx = egui::Context::default(); - let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); - assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); - frame(&mut app, &ctx, vec![]); - let (docs, rects) = panes(&app); - assert_eq!(docs, [0, 1, 2]); - assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); - let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); - assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); - frame(&mut app, &ctx, vec![]); - let (docs, rects) = panes(&app); - assert_eq!(docs, [0, 1, 2]); - assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); - // Each document fits its new pane. - let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); - let canvas = app.canvas_rect.unwrap(); - for (i, r) in docs.iter().zip(&rects) { - let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; - let v = app.views[*i]; - assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); - } - assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); -} #[test] fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { @@ -168,19 +179,18 @@ fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { app.run("document.activate", json!({"index": 1})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); - let second = (app.session.documents()[1].uid, 1); + let second = app.session.documents()[1].uid; app.run("document.activate", json!({"index": 0})).unwrap(); frame(&mut app, &ctx, vec![]); - assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + // The second document is rendered for its pane. + wait_ready(&mut app, &ctx, (1, 1), vec![], &mut |a| run_out(a, &ctx)); app.run("document.activate", json!({"index": 3})).unwrap(); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); - assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); - let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); - let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; - assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); - assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + assert!(!has_picture(&mut app, &ctx, (0, 1), second), "a document under its tab keeps no render"); + assert!(fits(&app, (0, 1))); + assert!(app.canvas_view().is_some_and(|c| rects[1].contains_rect(c.rect)), "the current document's pane is the canvas"); // A document brought into the last pane leaves the first pane's zoom as it is. app.views[0].zoom *= 2.0; let zoomed = app.views[0].zoom; @@ -188,8 +198,8 @@ fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0, [0, 2]); assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); - let last = app.canvas_rect.unwrap(); - assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + frame(&mut app, &ctx, vec![]); + assert!(fits(&app, (2, 1)), "the document brought in fits its pane"); assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); @@ -224,12 +234,11 @@ fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { app.views[1].zoom *= 3.0; app.run("file.close", json!({"index": 0})).unwrap(); frame(&mut app, &ctx, vec![]); - let (docs, rects) = panes(&app); + frame(&mut app, &ctx, vec![]); + let (docs, _) = panes(&app); assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); assert_eq!(app.session.documents()[0].uid, moving); - let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; - let v = app.views[0]; - assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); + assert!(fits(&app, (0, 1)), "it fits its new pane: {:?}", app.views[0]); } /// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the @@ -258,11 +267,10 @@ fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { app.views[1].zoom *= 2.0; app.run("file.close", json!({"index": 2})).unwrap(); frame(&mut app, &ctx, vec![]); - let (docs, rects) = panes(&app); + frame(&mut app, &ctx, vec![]); + let (docs, _) = panes(&app); assert_eq!(docs, [0, 1]); - let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; - let v = app.views[1]; - assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); + assert!(fits(&app, (1, 1)), "it fits its wider pane: {:?}", app.views[1]); } #[test] @@ -339,48 +347,19 @@ fn the_tile_items_check_the_layout_the_panes_show() { } } -/// One frame of the application bar with screen-reader nodes on → the nodes. -fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - app_bar_frame_in(app, ctx, events, 1400.0) -} - -/// [`app_bar_frame`] on a window `width` points wide. -fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { - let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); - let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); - out.textures_delta.clear(); - out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() -} - -/// The center of the application bar's node whose label, without its leading spaces, is `name` -/// (or starts with it and a shortcut in parentheses). -fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { - let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); - let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; - Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) -} - -/// Click the application bar's node labeled `name`. -fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { - let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); - app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); - app_bar_frame(app, ctx, vec![button(at, false)]); -} - +/// The Arrange Documents items tile and consolidate through the commands they name. #[test] -fn the_arrange_documents_button_tiles_and_consolidates() { - crate::i18n::set_current(crate::i18n::Lang::EN); +fn the_arrange_documents_items_tile_and_consolidate() { let mut app = app_with(3); - let ctx = egui::Context::default(); - ctx.enable_accesskit(); - crate::theme::install_fonts(&ctx); - app_bar_frame(&mut app, &ctx, vec![]); - let nodes = app_bar_frame(&mut app, &ctx, vec![]); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands")); - let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search shows")); - assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search: {arrange:?}, {search:?}"); - click_app_bar(&mut app, &ctx, "Arrange Documents"); - let menu = app_bar_frame(&mut app, &ctx, vec![]); + // PLAN: assumed `menus::arrange_documents_items() -> Vec` (shell-w9's request). + let items = crate::menus::arrange_documents_items(); + let labels: Vec<&str> = items + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); for item in [ "Consolidate All Windows", "Tile", @@ -391,114 +370,56 @@ fn the_arrange_documents_button_tiles_and_consolidates() { "4-Up Layout", "6-Up Layout", ] { - assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + assert!(labels.contains(&item), "the items list {item}"); } - click_app_bar(&mut app, &ctx, "Tile All Vertically"); + let choose = |app: &mut VectorcraftApp, label: &str| { + let found = items.iter().find_map(|i| match i { + crate::menus::Item::Cmd(l, id, p) if *l == label => Some((*id, p.clone())), + _ => None, + }); + let (id, p) = found.unwrap_or_else(|| panic!("{label} is listed")); + app.run(id, if p.is_null() { json!({}) } else { p }).unwrap(); + }; + choose(&mut app, "Tile All Vertically"); assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); - click_app_bar(&mut app, &ctx, "Arrange Documents"); - click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + choose(&mut app, "Consolidate All Windows"); assert!(!app.ui.tiled); } -/// As the application bar narrows, Arrange Documents goes before the search. -#[test] -fn a_narrow_application_bar_keeps_search_before_arrange_documents() { - crate::i18n::set_current(crate::i18n::Lang::EN); - let mut app = app_with(3); - let ctx = egui::Context::default(); - ctx.enable_accesskit(); - crate::theme::install_fonts(&ctx); - let mut search_alone = false; - for width in (200..=1400).rev().step_by(4) { - app_bar_frame_in(&mut app, &ctx, vec![], width as f32); - let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands").is_some()); - assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search"); - search_alone |= search && !arrange; - } - assert!(search_alone, "some width shows the search without Arrange Documents"); -} - #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); let ctx = egui::Context::default(); frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); - let tabbed = app.canvas_rect.unwrap(); + let tabbed = app.canvas_view().unwrap().rect; assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); // Three documents: two columns and two rows, the lower-right cell empty. assert_eq!(rects[0].top(), rects[1].top()); assert_eq!(rects[0].left(), rects[2].left()); assert!(rects[2].top() > rects[0].top()); - let canvas = app.canvas_rect.unwrap(); + let canvas = app.canvas_view().unwrap().rect; assert!(rects[2].contains_rect(canvas) && canvas.width() < tabbed.width() / 2.0, "the current document's pane is the canvas: {canvas:?}"); let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); - for (i, r) in docs.iter().zip(&rects) { + for i in &docs { let v = app.views[*i]; - let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; - assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + assert!(fits(&app, (*i, 1)), "document {i} fits its pane: {v:?}"); assert_eq!(v.center, artboard.center()); } - assert_eq!(app.canvas.panes.shown.len(), 2, "the other two documents are rendered for their panes"); + // The other two documents are rendered for their panes. + for i in [0, 1] { + wait_ready(&mut app, &ctx, (i, 1), vec![], &mut |a| run_out(a, &ctx)); + } let inspected = crate::control::inspect(&app, &ctx); assert_eq!(inspected["tiled"], json!(true)); let active: Vec = inspected["panes"].as_array().unwrap().iter().map(|p| p["active"].as_bool().unwrap()).collect(); assert_eq!(active, [false, false, true]); } -/// With the interface zoomed by Preferences › User Interface › UI Scaling, each tiled document -/// fits its pane with 30 interface points to spare: its zoom is the zoom that fits it in an -/// unscaled interface times the UI Scaling. -#[test] -fn tiled_documents_fit_their_panes_at_every_ui_scaling() { - for ui_zoom in [0.75_f32, 1.5, 2.0] { - let mut app = app_with(3); - let ctx = egui::Context::default(); - ctx.set_zoom_factor(ui_zoom); - let size = vec2(1200.0, 800.0) / ui_zoom; - frame_in(&mut app, &ctx, vec![], size); - app.run("window.arrange.tile", json!({})).unwrap(); - frame_in(&mut app, &ctx, vec![], size); - let (docs, rects) = panes(&app); - for (i, r) in docs.iter().zip(&rects).filter(|(i, _)| **i != 2) { - let shown = view_rects(&app, *r, ctx.pixels_per_point()).1; - let unscaled = ((f64::from(shown.width()) - 60.0) / 400.0).min((f64::from(shown.height()) - 60.0) / 300.0); - let v = app.views[*i]; - assert!(v.fitted && (v.zoom - unscaled * f64::from(ui_zoom)).abs() < 1e-9, "UI Scaling {ui_zoom}×: document {i} fits its pane: {v:?}"); - } - } -} - -#[test] -fn a_press_in_another_pane_makes_its_document_current_without_drawing() { - let mut app = app_with(3); - let ctx = egui::Context::default(); - app.run("window.arrange.tile", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - app.select_tool("rectangle"); - let pane = panes(&app).1[0]; - let (from, to) = (pane.center() - vec2(30.0, 20.0), pane.center() + vec2(30.0, 20.0)); - let drag = |app: &mut VectorcraftApp| { - frame(app, &ctx, vec![egui::Event::PointerMoved(from)]); - frame(app, &ctx, vec![button(from, true)]); - for k in 1..=4 { - frame(app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * (k as f32 / 4.0))]); - } - frame(app, &ctx, vec![button(to, false)]); - frame(app, &ctx, vec![]); - }; - drag(&mut app); - assert_eq!(app.session.active_index(), Some(0), "the press made the first document current"); - assert!(app.session.documents()[0].doc.art_bounds().is_none(), "the press that switched documents drew nothing"); - assert!(app.canvas_rect.is_some_and(|c| pane.contains_rect(c)), "its pane is the canvas now"); - drag(&mut app); - assert!(app.session.documents()[0].doc.art_bounds().is_some(), "a drag in the current pane draws"); - assert!(app.session.documents()[1..].iter().all(|d| d.doc.art_bounds().is_none())); -} /// One headless frame at `time` seconds as the app runs it: a Selection move released off the /// canvas ends first ([`crate::canvas::release_over_panel`]), then the tabs and the panes draw. @@ -544,17 +465,16 @@ fn tiled_pair() -> (VectorcraftApp, egui::Context) { /// Press on document point `at` on the canvas and move the pointer 20 × 10 points, still on the /// canvas: the Selection tool moves the art under it. fn grab(app: &mut VectorcraftApp, ctx: &egui::Context, at: Point) { - let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(at); + let p = app.canvas_view().unwrap().to_screen(at); app_frame(app, ctx, vec![egui::Event::PointerMoved(p), button(p, true)]); app_frame(app, ctx, vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]); assert!(app.session.in_interaction(), "the Selection tool moves the art"); } /// Window `w`'s pane: the screen point that shows document point `at` in it, and the pane. -fn in_pane(app: &VectorcraftApp, ctx: &egui::Context, w: Win, at: Point) -> (Pos2, egui::Rect) { +fn in_pane(app: &VectorcraftApp, _ctx: &egui::Context, w: Win, at: Point) -> (Pos2, egui::Rect) { let (_, cell) = app.canvas.panes.last.iter().copied().find(|(o, _)| *o == w).unwrap(); - let area = view_rects(app, cell, ctx.pixels_per_point()).1; - (Xf::at(area, crate::doc_windows::view(app, w).unwrap(), 1.0).to_screen(at), cell) + (pane_view(app, w).to_screen(at), cell) } /// How many objects document `i`'s first layer holds. @@ -710,7 +630,7 @@ fn art_carried_through_a_tab_drops_into_a_third_documents_pane() { timed_frame(&mut app, &ctx, Some(0.0), vec![]); let tabs = titles(timed_frame(&mut app, &ctx, Some(0.01), vec![])); assert_eq!(tabs.len(), 3); - let p = Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), 1.0).to_screen(Point::new(100.0, 100.0)); + let p = app.canvas_view().unwrap().to_screen(Point::new(100.0, 100.0)); timed_frame(&mut app, &ctx, Some(0.05), vec![egui::Event::PointerMoved(p), button(p, true)]); timed_frame(&mut app, &ctx, Some(0.1), vec![egui::Event::PointerMoved(p + vec2(20.0, 10.0))]); timed_frame(&mut app, &ctx, Some(0.2), vec![egui::Event::PointerMoved(tabs[2].center())]); @@ -757,14 +677,17 @@ fn consolidate_all_windows_shows_one_document_again() { let mut app = app_with(2); let ctx = egui::Context::default(); frame(&mut app, &ctx, vec![]); - let tabbed = app.canvas_rect.unwrap(); + let tabbed = app.canvas_view().map(|v| v.rect); app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0.len(), 2); + let uid = app.session.documents()[0].uid; + wait_ready(&mut app, &ctx, (0, 1), vec![], &mut |a| run_out(a, &ctx)); assert_eq!(app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(), json!({"tiled": false, "floating": []})); frame(&mut app, &ctx, vec![]); - assert!(panes(&app).0.is_empty() && app.canvas.panes.shown.is_empty()); - assert_eq!(app.canvas_rect, Some(tabbed), "the current document fills the document area again"); + assert!(panes(&app).0.is_empty()); + assert!(!has_picture(&mut app, &ctx, (1, 1), uid), "no pane keeps a picture"); + assert_eq!(app.canvas_view().map(|v| v.rect), tabbed, "the current document fills the document area again"); } #[test] @@ -808,15 +731,15 @@ fn closing_a_document_while_tiled_tiles_the_others() { app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert_eq!(panes(&app).0, [0, 1, 2]); - let first = (app.session.documents()[0].uid, 1); - assert!(app.canvas.panes.shown.contains_key(&first)); + let first = app.session.documents()[0].uid; + wait_ready(&mut app, &ctx, (0, 1), vec![], &mut |a| run_out(a, &ctx)); // The first document, not the current one, closes. app.run("file.close", json!({"index": 0})).unwrap(); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1]); assert_eq!(rects[0].height(), rects[1].height(), "two panes side by side"); - assert!(!app.canvas.panes.shown.contains_key(&first), "the closed document's render is dropped"); + assert!(!has_picture(&mut app, &ctx, (0, 1), first), "the closed document's render is dropped"); app.run("file.close", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "one document fills the document area"); @@ -830,18 +753,14 @@ fn an_edit_shows_in_its_pane_once_another_document_is_current() { app.run("document.activate", json!({"index": 0})).unwrap(); app.run("window.arrange.tile", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); - let uid = (app.session.documents()[1].uid, 1); - let before = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.revision); - assert_eq!(before, Some(app.session.documents()[1].revision), "the second document's pane shows it"); + let before = pane_source(&mut app, &ctx, (1, 1)).revision; + assert_eq!(pane_source(&mut app, &ctx, (1, 1)).revision, before, "without an edit the pane's picture stays"); app.run("document.activate", json!({"index": 1})).unwrap(); frame(&mut app, &ctx, vec![]); app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap(); app.run("document.activate", json!({"index": 0})).unwrap(); frame(&mut app, &ctx, vec![]); - let edited = &app.session.documents()[1]; - assert_ne!(Some(edited.revision), before); - let shown = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.revision); - assert_eq!(shown, Some(edited.revision), "the pane shows the document as edited"); + assert_ne!(pane_source(&mut app, &ctx, (1, 1)).revision, before, "the pane shows the document as edited"); } #[test] @@ -851,175 +770,17 @@ fn other_panes_draw_their_guides_and_selected_objects() { let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap(); app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); app.session.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap(); - let st = &app.session.documents()[0]; - let layer = super::c32(st.doc.layer_color(vectorcraft_doc::NodeId(id))); app.run("document.activate", json!({"index": 1})).unwrap(); app.run("window.arrange.tile", json!({})).unwrap(); let ctx = egui::Context::default(); frame(&mut app, &ctx, vec![]); - let shapes = frame(&mut app, &ctx, vec![]); - let pane = panes(&app).1[0]; - let xf = Xf::new(view_rects(&app, pane, ctx.pixels_per_point()).1, &app.views[0]); - let outline: Vec = shapes - .iter() - .filter_map(|s| match s { - Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(layer) => Some(p.points.clone()), - _ => None, - }) - .flatten() - .collect(); - let corner = xf.to_screen(Point::new(50.0, 50.0)); - assert!(outline.iter().any(|p| p.distance(corner) < 1.0), "the selected rectangle is outlined in its pane: {outline:?}"); - let guide_x = xf.to_screen(Point::new(300.0, 0.0)).x; - let guide = LineLook::guides(&app.session.prefs, &Tokens::get(&ctx)).color; - let guides = shapes.iter().any(|s| { - matches!(s, Shape::LineSegment { points: [a, b], stroke } if stroke.color == guide && (a.x - guide_x).abs() < 0.5 && (b.x - guide_x).abs() < 0.5 && pane.contains(*a)) - }); - assert!(guides, "the guide is drawn in its pane"); - assert_ne!(layer, Color32::TRANSPARENT); -} - -/// The selected objects' outlines as the panes made them on every frame before they kept them, -/// to hold the kept outlines against. -fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { - let mut shapes = vec![]; - let symbols = st.doc.symbol_boxes(); - let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = - st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); - let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); - let mut stroke_path = |bp: &BezPath, s: Stroke| { - for line in to_screen_path(bp, xf) { - shapes.push(Shape::line(line, s)); - } - }; - if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { - let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); - if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { - stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); - } - return shapes; - } - for (id, n) in nodes { - stroke_path(&node_outline(n, &symbols), color(id)); - } - shapes -} - -/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they -/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order. -fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] { - let pane = panes(app).1[0]; - let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]); - let slot = (app.session.documents()[0].uid, 1); - let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes; - assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh"); - assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines"); - kept -} - -/// Run `cmd` on the first document of a tiled pair, then make the second current again. -fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value { - app.run("document.activate", json!({"index": 0})).unwrap(); - let out = app.session.execute(cmd, &args).unwrap(); - app.run("document.activate", json!({"index": 1})).unwrap(); - out -} - -#[test] -fn kept_outlines_do_not_show_for_a_new_document_that_takes_a_freed_documents_address() { - let affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; - let st = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); - let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: vec![], affine, shapes: vec![] }; - assert!(kept.shows(&st, &affine), "the outlines show the document they were made for"); - let freed = Arc::as_ptr(&st.doc); - drop(st); - let mut reused = false; - for _ in 0..64 { - let other = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); - reused |= Arc::as_ptr(&other.doc) == freed; - assert!(!kept.shows(&other, &affine), "a different document with the same revision, selection and mapping is not the one shown"); - } - assert!(!reused, "the weak reference keeps the freed document's address from being taken"); -} - -#[test] -fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { - let mut app = app_with(2); - app.run("document.activate", json!({"index": 1})).unwrap(); - app.run("window.arrange.tile", json!({})).unwrap(); - let ctx = egui::Context::default(); - let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); - let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); - in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]})); frame(&mut app, &ctx, vec![]); - let drawn = frame(&mut app, &ctx, vec![]); - assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined"); - let made = app.canvas.panes.outlines_made; - let drawn = frame(&mut app, &ctx, vec![]); - kept_outlines(&app, &ctx, &drawn); - assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines"); - let changed = |app: &mut VectorcraftApp, what: &str| { - let made = app.canvas.panes.outlines_made; - let drawn = frame(app, &ctx, vec![]); - kept_outlines(app, &ctx, &drawn); - assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once"); - let drawn = frame(app, &ctx, vec![]); - kept_outlines(app, &ctx, &drawn); - assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines"); - }; - in_first(&mut app, "select.set", json!({"ids": [ellipse]})); - changed(&mut app, "a new selection"); - in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10})); - changed(&mut app, "a move"); - let layer = app.session.documents()[0].doc.layers[0].id.0; - in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"})); - changed(&mut app, "a new layer color"); - app.views[0].center.x += 25.0; - changed(&mut app, "a pan"); - app.views[0].zoom *= 1.5; - app.views[0].rotation = 20.0; - changed(&mut app, "a zoom and a turn"); - app.ui.view.edges = false; - frame(&mut app, &ctx, vec![]); - assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept"); - app.ui.view.edges = true; - changed(&mut app, "Edges on again"); - in_first(&mut app, "select.none", json!({})); - changed(&mut app, "an empty selection"); - let drawn = frame(&mut app, &ctx, vec![]); - assert!(kept_outlines(&app, &ctx, &drawn).is_empty()); - // 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds. + // The pane hands its document's guides and selected objects to the overlays it shows. let st = &app.session.documents()[0]; - let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap(); - app.run("document.activate", json!({"index": 0})).unwrap(); - app.session - .edit("Fill", |d, _| { - let layer = d.layers[0].id; - for _ in 0..30_000 { - let mut n = rect.clone(); - n.id = d.alloc_id(); - d.insert(Some(layer), usize::MAX, n)?; - } - Ok(()) - }) - .unwrap(); - app.run("select.all", json!({})).unwrap(); - app.run("document.activate", json!({"index": 1})).unwrap(); - changed(&mut app, "selecting more points than are outlined"); - let drawn = frame(&mut app, &ctx, vec![]); - assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds"); - app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines"); - // Panes that stop showing before their render arrives keep no outlines either. - app.run("window.arrange.tile", json!({})).unwrap(); - frame(&mut app, &ctx, vec![]); - assert_eq!(app.canvas.panes.outlines.len(), 1); - app.ui.tiled = false; - app.canvas.panes.shown.clear(); - app.canvas.panes.last.clear(); - frame(&mut app, &ctx, vec![]); - assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept"); + // PLAN: assumed `guides::shown(app, st)` and `selection::outlines(app, st)` (canvas-w16, canvas-w17). + let guides = format!("{:?}", crate::canvas::guides::shown(&app, st)); + assert!(guides.contains("300"), "the guide at 300 is shown in the pane: {guides}"); + assert!(!crate::canvas::selection::outlines(&app, st).is_empty(), "the selected rectangle is outlined in its pane"); } #[test] @@ -1031,10 +792,9 @@ fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let side_by_side = app.views[0].zoom; app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); frame(&mut app, &ctx, vec![]); - let pane = panes(&app).1[0]; - let rect = view_rects(&app, pane, ctx.pixels_per_point()).1; + frame(&mut app, &ctx, vec![]); let v = app.views[0]; - assert!((v.zoom - fit_zoom(rect, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "fitted to its new pane: {v:?}"); + assert!(fits(&app, (0, 1)), "fitted to its new pane: {v:?}"); assert_ne!(v.zoom, side_by_side, "the pane changed size"); } @@ -1047,10 +807,8 @@ fn other_panes_show_pixel_preview() { app.ui.view.pixel_preview = true; app.views[0].zoom = 4.0; frame(&mut app, &ctx, vec![]); - let uid = (app.session.documents()[0].uid, 1); - let key = app.canvas.panes.shown.get(&uid).map(|(k, _)| k.clone()).unwrap(); - let [x0, y0, x1, y1] = key.pixel.expect("the pane renders document pixels"); - assert!(x1 > x0 && y1 > y0); + let region = pane_source(&mut app, &ctx, (0, 1)).pixel.expect("the pane renders document pixels"); + assert!(region.x1 > region.x0 && region.y1 > region.y0); } /// A pane more device pixels across than the largest texture side the display supports renders @@ -1058,33 +816,27 @@ fn other_panes_show_pixel_preview() { #[test] fn other_panes_render_within_the_largest_texture_side() { let mut app = app_with(2); - app.canvas.panes.worker_started = true; // every pane renders on this thread let ctx = egui::Context::default(); ctx.set_pixels_per_point(2.0); app.run("window.arrange.tile", json!({})).unwrap(); - // The first frame sets the pixels a point, the second draws at them. - for _ in 0..2 { + let mut run = |app: &mut VectorcraftApp| { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), max_texture_side: Some(1024), ..Default::default() }; - ctx.run_ui(raw, |ui| app.canvas_area(ui)).textures_delta.clear(); + ctx.run_ui(raw, |ui| app.canvas_area(ui)) + }; + // The first frames set the pixels a point and the panes' areas, the next draw at them. + for _ in 0..3 { + run(&mut app).textures_delta.clear(); } - let uid = (app.session.documents()[0].uid, 1); - let (key, tex) = app.canvas.panes.shown.get(&uid).map(|(k, t)| (k.clone(), t.size())).expect("the other document's pane rendered"); - assert_eq!(tex[0].max(tex[1]), 1024, "the pane's frame is {tex:?} pixels"); - let (docs, cells) = panes(&app); - let pane = docs.iter().zip(cells).find(|(i, _)| **i == 0).map(|(_, r)| r).unwrap(); - let rect = view_rects(&app, pane, ctx.pixels_per_point()).1; + let (texture, _) = wait_ready(&mut app, &ctx, (0, 1), vec![], &mut run); + let (w, h) = (texture.size.width as f32, texture.size.height as f32); + assert_eq!(w.max(h), 1024.0, "the pane's frame is {w} × {h} pixels"); + let rect = crate::doc_windows::view(&app, (0, 1)).unwrap().rect; assert!(rect.width().max(rect.height()) * ctx.pixels_per_point() > 1024.0, "the pane is {rect:?} at {} pixels a point", ctx.pixels_per_point()); - assert!( - (key.w as f32 / key.ppp - rect.width()).abs() < 1.0 && (key.h as f32 / key.ppp - rect.height()).abs() < 1.0, - "the frame covers the pane {rect:?}: {} × {} pixels at {} a point", - key.w, - key.h, - key.ppp - ); + assert!((w / h - rect.width() / rect.height()).abs() < 0.02, "the frame covers the pane {rect:?}: {w} × {h} pixels"); } /// A pane's render key takes its document's [`CacheKey::placed`] value ([`placed_key`]), which a @@ -1094,13 +846,13 @@ fn a_panes_key_takes_its_documents_placed_value() { let mut app = app_with(2); let ctx = egui::Context::default(); app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let before = pane_source(&mut app, &ctx, (0, 1)).revision; let uid = app.session.documents()[0].uid; let generation = vectorcraft_render::placed_document::generation(); let marked = generation.wrapping_add(1000); app.canvas.placed_keys.insert(uid, crate::PlacedKey { checked: generation, key: marked, before: (marked, generation) }); - frame(&mut app, &ctx, vec![]); - let key = app.canvas.panes.shown.get(&(uid, 1)).map(|(k, _)| k.placed); - assert_eq!(key, Some(marked)); + assert_ne!(pane_source(&mut app, &ctx, (0, 1)).revision, before, "the picture follows the document's placed value"); } #[test] @@ -1114,24 +866,14 @@ fn a_resized_window_fits_the_tiled_documents_again_unless_one_was_zoomed() { let zoomed = app.views[1]; let smaller = vec2(900.0, 600.0); frame_in(&mut app, &ctx, vec![], smaller); - let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); - let (_, rects) = panes(&app); + frame_in(&mut app, &ctx, vec![], smaller); + frame_in(&mut app, &ctx, vec![], smaller); for i in [0, 2] { - let area = if i == 2 { app.canvas_rect.unwrap() } else { view_rects(&app, rects[i], ctx.pixels_per_point()).1 }; - assert!((app.views[i].zoom - fit_zoom(area, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its smaller pane: {:?}", app.views[i]); + assert!(fits(&app, (i, 1)), "document {i} fits its smaller pane: {:?}", app.views[i]); } assert_eq!(app.views[1].zoom, zoomed.zoom, "the zoomed document keeps its zoom"); } -/// The RGB of the middle pixel of the render that document `i`'s pane uploaded in `out`. -fn pane_middle(app: &VectorcraftApp, out: &egui::FullOutput, i: usize) -> [u8; 3] { - let uid = app.session.documents()[i].uid; - let id = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, (_, tex))| tex.id()).unwrap(); - let image = out.textures_delta.set.iter().find(|(t, _)| **t == id).and_then(|(_, d)| d.last()).map(|d| d.image.clone()).unwrap(); - let egui::ImageData::Color(img) = image; - let p = img.pixels[img.size[1] / 2 * img.size[0] + img.size[0] / 2]; - [p.r(), p.g(), p.b()] -} #[test] fn other_panes_draw_through_their_documents_profiles() { @@ -1193,11 +935,10 @@ fn other_panes_draw_through_their_documents_profiles() { app.run("window.arrange.tile", json!({})).unwrap(); // The first document in front: the second one's pane draws through Display P3, its paper too. app.run("document.activate", json!({"index": 0})).unwrap(); - let mut out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); - let shown = pane_middle(&app, &out, 1); + let out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); assert!(fills(&out, paper_p3), "the back document's paper draws through its Display P3: {paper_p3:?}"); assert!(!fills(&out, [0xcc, 0x66, 0x33]), "the back document's paper does not draw through the working space"); - out.textures_delta.clear(); + let shown = pane_middle(&mut app, &ctx, 1, vec![out.textures_delta.clone()], &mut |a| ctx.run_ui(raw(), |ui| a.canvas_area(ui))); assert!(near(shown, p3), "the back document draws through its Display P3: {shown:?}, not {p3:?}"); // The same in a floating window. app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); @@ -1214,32 +955,19 @@ fn other_panes_draw_through_their_documents_profiles() { for _ in 0..30 { floating(&mut app).textures_delta.clear(); } - app.canvas.panes.clear(); - let mut out = floating(&mut app); - let shown = pane_middle(&app, &out, 1); + forget(&mut app, &ctx); + let out = floating(&mut app); assert!(fills(&out, paper_p3), "the floating document's paper draws through its Display P3: {paper_p3:?}"); - out.textures_delta.clear(); + let shown = pane_middle(&mut app, &ctx, 1, vec![out.textures_delta.clone()], &mut |a| floating(a)); assert!(near(shown, p3), "the floating document draws through its Display P3: {shown:?}, not {p3:?}"); app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); app.run("window.arrange.tile", json!({})).unwrap(); - app.canvas.panes.clear(); + forget(&mut app, &ctx); // The second document in front: the first one's pane draws through the working sRGB. app.run("document.activate", json!({"index": 1})).unwrap(); - let mut out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); - let shown = pane_middle(&app, &out, 0); - out.textures_delta.clear(); + let out = ctx.run_ui(raw(), |ui| app.canvas_area(ui)); + let shown = pane_middle(&mut app, &ctx, 0, vec![out.textures_delta.clone()], &mut |a| ctx.run_ui(raw(), |ui| a.canvas_area(ui))); assert!(near(shown, srgb), "the back document draws through the working space: {shown:?}, not {srgb:?}"); - // The same off the UI thread. - app.canvas.panes.clear(); - app.canvas.panes.worker = crate::thumb_worker::ThumbWorker::start(&ctx, "test-panes"); - app.canvas.panes.worker_started = true; - ctx.run_ui(raw(), |ui| app.canvas_area(ui)).textures_delta.clear(); - let done = app.canvas.panes.worker.as_ref().unwrap().wait().unwrap(); - assert_eq!(done.key.0.0, app.session.documents()[0].uid); - let img = done.img.unwrap(); - let at = ((img.height / 2 * img.width + img.width / 2) * 4) as usize; - let shown = [img.pixels[at], img.pixels[at + 1], img.pixels[at + 2]]; - assert!(near(shown, srgb), "the worker draws the back document through the working space: {shown:?}, not {srgb:?}"); // A CMYK document behind the front one draws through its own assigned CMYK profile. app.run("document.activate", json!({"index": 0})).unwrap(); let steps = json!([ @@ -1256,13 +984,8 @@ fn other_panes_draw_through_their_documents_profiles() { let front = to_u8(cms::active().display_rgb(&ink)); let close = |a: [u8; 3], b: [u8; 3]| a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= 3); assert!(!close(device, front), "the two CMYK profiles draw the color differently: {device:?}, {front:?}"); - app.canvas.panes.clear(); - ctx.run_ui(raw(), |ui| app.canvas_area(ui)).textures_delta.clear(); - let done = app.canvas.panes.worker.as_ref().unwrap().wait().unwrap(); - assert_eq!(done.key.0.0, app.session.documents()[0].uid); - let img = done.img.unwrap(); - let at = ((img.height / 2 * img.width + img.width / 2) * 4) as usize; - let shown = [img.pixels[at], img.pixels[at + 1], img.pixels[at + 2]]; + forget(&mut app, &ctx); + let shown = pane_middle(&mut app, &ctx, 0, vec![], &mut |a| ctx.run_ui(raw(), |ui| a.canvas_area(ui))); assert!(close(shown, device), "the back CMYK document draws through its Device CMYK: {shown:?}, not {device:?} (front: {front:?})"); assert!(near(cms::active().display_rgb(&color).map(|v| (v * 255.0).round() as u8), p3), "the front document's profile stays active"); } @@ -1275,7 +998,6 @@ fn other_panes_draw_through_their_documents_profiles() { fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_conversion() { use crate::display_profile::{Found, Reading}; let mut app = app_with(2); - app.canvas.panes.worker_started = true; // every pane renders on this thread let (front_paper, back_paper) = ([0x20, 0x40, 0xc0], [0xe0, 0xc0, 0x20]); app.run("document.activate", json!({"index": 0})).unwrap(); app.run("document.setup", json!({"gridColors": ["#2040c0", "#ffffff"], "simulatePaper": true})).unwrap(); @@ -1287,36 +1009,25 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con app.run("select.none", json!({})).unwrap(); app.run("window.arrange.tile", json!({})).unwrap(); app.run("document.activate", json!({"index": 0})).unwrap(); - let uid = app.session.documents()[1].uid; let ctx = egui::Context::default(); - // The second document's pane: the raster one frame uploads, its width, and the key it was rendered for. - let pane = |app: &mut VectorcraftApp| -> (Vec, usize, CacheKey) { - let raw = egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0))), - max_texture_side: Some(8192), - ..Default::default() - }; - let mut out = ctx.run_ui(raw, |ui| app.canvas_area(ui)); - let (key, tex) = app.canvas.panes.shown.iter().find(|(slot, _)| slot.0 == uid).map(|(_, s)| s).expect("the second document's pane rendered"); - let id = tex.id(); - let up = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| { - let egui::ImageData::Color(img) = &d.image; - (img.pixels.clone(), img.width()) - }); - let key = key.clone(); - out.textures_delta.clear(); - let (pixels, width) = up.expect("the pane uploads"); - (pixels, width, key) + // The second document's pane: the picture it shows, and its width. + let pane = |app: &mut VectorcraftApp| -> (Vec, usize) { + forget(app, &ctx); + let (texture, uploads) = wait_ready(app, &ctx, (1, 1), vec![], &mut |a| run_out(a, &ctx)); + let (pixels, [width, _]) = uploaded(&uploads, texture.id); + (pixels, width) }; app.session.prefs.monitor_profile_display = false; - let (srgb, width, key) = pane(&mut app); - assert!(key.backdrop.is_none(), "no display profile: nothing to blend"); + let (srgb, width) = pane(&mut app); + assert!(pane_source(&mut app, &ctx, (1, 1)).over.is_none(), "no display profile: nothing to blend"); let p3 = crate::display_profile::tests::p3(); - let t = vectorcraft_color::cms::display::DisplayTransform::from_icc(&p3).unwrap(); app.display_profile.report(Reading { display: Some("DP-1".into()), found: Found::Profile { icc: p3, from: "test".into() } }); app.session.prefs.monitor_profile_display = true; - let (shown, _, key) = pane(&mut app); - let backdrop = key.backdrop.as_deref().expect("the pane's Preview blends with its paper"); + // PLAN: the display transform comes from the app's display profile; assumed it keeps `apply_premultiplied` and `apply8`. + let t = app.display_profile.transform(true).expect("the reported profile gives a transform"); + let (shown, _) = pane(&mut app); + let source = pane_source(&mut app, &ctx, (1, 1)); + let (backdrop, _) = source.over.as_ref().expect("the pane's Preview blends with its paper"); assert!( !backdrop.artboards.is_empty() && backdrop.artboards.iter().all(|(_, c)| *c == back_paper), "the pane blends with its own document's paper: {backdrop:?}" @@ -1357,81 +1068,4 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); } -fn thread_cpu_ns() -> Option { - std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() -} -/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and -/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so -/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the -/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or -/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time -/// per frame of 7 runs is printed. -/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`. -#[test] -#[ignore = "manual timing probe; performance depends on machine load"] -fn pane_outlines_timing() { - const FRAMES: u32 = 20; - let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; - eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames"); - for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] { - let mut app = app_with(1); - let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); - let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); - app.session - .edit("Fill", |d, _| { - let layer = d.layers[0].id; - for _ in 1..count { - let mut n = node.clone(); - n.id = d.alloc_id(); - d.insert(Some(layer), usize::MAX, n)?; - } - Ok(()) - }) - .unwrap(); - app.run("select.all", json!({})).unwrap(); - let st = app.session.active().unwrap(); - assert_eq!(st.selection.objects.len(), count); - let ctx = egui::Context::default(); - let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)); - let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 }; - let mut kept = Panes::default(); - let slot = (st.uid, 1); - let mut pass = |fresh: bool| { - let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() }; - let out = ctx.run_ui(raw, |ui| { - let painter = ui.painter_at(area); - if fresh { - for s in outlines_made_each_frame(st, &xf) { - painter.add(s); - } - } else { - selected_objects(&mut kept, slot, st, &painter, &xf); - } - }); - ctx.tessellate(out.shapes, out.pixels_per_point).len() - }; - assert_eq!(pass(true), pass(false), "both sides draw as much"); - let mut time = |fresh: bool| { - let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); - for _ in 0..FRAMES { - pass(fresh); - } - let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); - ns as f64 / f64::from(FRAMES) / 1e6 - }; - let (mut fresh, mut cached) = (vec![], vec![]); - for _ in 0..7 { - fresh.push(time(true)); - cached.push(time(false)); - } - let median = |v: &mut Vec| { - v.sort_by(f64::total_cmp); - v[v.len() / 2] - }; - let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len()); - eprintln!("{count} x {shape} ({shapes} lines drawn)"); - eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh)); - eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached)); - } -}