diff --git a/crates/ui-canvas/src/canvas/pasteboard/mod.rs b/crates/ui-canvas/src/canvas/pasteboard/mod.rs index f9f1849e3..006d3acfa 100644 --- a/crates/ui-canvas/src/canvas/pasteboard/mod.rs +++ b/crates/ui-canvas/src/canvas/pasteboard/mod.rs @@ -1,28 +1,34 @@ //! `Pasteboard`: the area around a document's pages or artboards, and the frames of the pages on it, a canvas -//! control (20.6). The pasteboard colour and the page border come from the application's preferences; artboards -//! show their names above them, and a click on a name selects the artboard. +//! control (20.6). The pasteboard colour (set on the canvas) and the page border come from the application's +//! preferences; the default colour is the canvas surround. Artboards show their names above them, and a click on a +//! name selects the artboard. #[cfg(feature = "testing")] mod stories; use super::space::canvas_space; use crate::contract::{Access, Common, Component, Cx, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Props as _, Role}; -use crate::primitives::{PaintShape, Rule, StrokeWidth, TextRun}; +use crate::primitives::{CheckerArea, PaintShape, Rule, StrokeWidth, TextRun}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, DataColor, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceStyle, TypeRole}; +use crate::style::{ + ComponentStyle, DataColor, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceStyle, SurroundLook, TypeRole, paint_surround, +}; use craft_behavior::kurbo::{Point, Rect as DocRect}; -use craft_behavior::{CanvasView, HitLevel, HitPriority, Metrics, PartKey, Sense}; +use craft_behavior::{CanvasView, HitLevel, HitPriority, HitShape, Metrics, PartKey, Sense}; use craft_theme::Rgba; use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2}; /// A page name: `NAME.at(i)` for page `i`, in the order of the frames given. const NAME: PartKey = PartKey::new("name"); +/// A visible piece of the pasteboard: `QUAD.at(i)` for the `i`th of [`Pasteboard::quads`] that shows. Inert: it takes +/// no press, and marks where a press keeps a typed draft unapplied. +const QUAD: PartKey = PartKey::new("quad"); /// The pasteboard's colour. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[non_exhaustive] pub enum PasteboardColor { - /// The theme's canvas surface. + /// The canvas surround: the theme's canvas surface and its pattern. #[default] Default, /// Black. @@ -114,8 +120,8 @@ impl PageFrame { pub struct PasteboardStyle { #[style(metrics)] metrics: Metrics, - /// The pasteboard unless the preference sets a colour. - fill: StyleColor, + /// The pasteboard unless the canvas sets a colour, before the pattern preference is applied. + surround: SurroundLook, /// A page's drop shadow: the floating surface's shadow alone, blurred under a page of an unturned view. shadow: SurfaceStyle, /// The shadow's colour and offset, for the plain offset copy under a page of a turned view. @@ -164,9 +170,6 @@ pub struct Pasteboard<'a> { #[common] common: Common, pages: &'a [PageFrame], - /// The pasteboard's colour; the theme's canvas surface by default. - #[prop] - color: PasteboardColor, /// The border round each page; a drop shadow by default. #[prop] border: PageBorder, @@ -185,7 +188,6 @@ impl<'a> Pasteboard<'a> { Pasteboard { common: Common::new(), pages, - color: PasteboardColor::Default, border: PageBorder::DropShadow, uncovered: &[], name_sizes: Vec::new(), @@ -195,15 +197,15 @@ impl<'a> Pasteboard<'a> { .label(label) } - /// The pasteboard as screen quads: the canvas minus the pages, each piece as its four corners (a turned view needs - /// quads, not rects). For an app that draws the pasteboard itself. + /// The pasteboard as screen quads: the canvas minus the pages and the `uncovered` rects (document units), each + /// piece as its four corners (a turned view needs quads, not rects). For an app that draws the pasteboard itself. pub fn quads(view: &CanvasView, pages: &[PageFrame], uncovered: &[DocRect]) -> Vec<[Pos2; 4]> { - let _ = uncovered; // P3(canvas-widgets-w9): cw.C48 let canvas = view.visible(); if !(canvas.x1 > canvas.x0 && canvas.y1 > canvas.y0 && canvas.area().is_finite()) { return Vec::new(); } - let boards: Vec = pages.iter().filter_map(|page| clip(page.rect.abs(), canvas)).collect(); + let boards: Vec = + pages.iter().map(|page| page.rect).chain(uncovered.iter().copied()).filter_map(|rect| clip(rect.abs(), canvas)).collect(); let mut xs = vec![canvas.x0, canvas.x1]; for board in &boards { xs.extend([board.x0, board.x1]); @@ -275,7 +277,7 @@ impl Component for Pasteboard<'_> { cast.map_or((Color32::TRANSPARENT, Vec2::ZERO), |cast| (cast.color, Vec2::new(f32::from(cast.offset[0]), f32::from(cast.offset[1])))); PasteboardStyle { metrics: Metrics::new(), - fill: cx.color(color.surface.canvas), + surround: SurroundLook::of(tokens), shadow: SurfaceStyle { fill: Color32::TRANSPARENT, radius: CornerRadius::ZERO, edge: SurfaceEdge::None, shadow: cast }, turned_shadow: cx.color(Rgba(ink.to_srgba_unmultiplied())), shadow_offset: offset, @@ -293,7 +295,9 @@ impl Component for Pasteboard<'_> { } /// The page names: a click away from the tool. They have no keyboard path of their own; the app's artboard list - /// selects the same page. + /// selects the same page. Then one inert part per visible pasteboard piece, so a press on the pasteboard keeps a + /// typed draft (a zoom being typed) unapplied, and a press on a page, which the pieces leave out, applies it. The + /// press itself still reaches the canvas's background part. fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; self.name_sizes = self @@ -310,6 +314,13 @@ impl Component for Pasteboard<'_> { .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only("the application's artboard list selects the same page"); } + let visible = Self::quads(&space.view, self.pages, self.uncovered).into_iter().filter(|quad| bounds(quad).intersects(space.view.rect)); + for (at, quad) in visible.enumerate() { + cx.part(QUAD.at(at as u64), HitShape::Polygon(quad.to_vec())) + .sense(Sense::empty()) + .holds_drafts() + .pointer_only("an inert area that takes no input; it only marks where a press keeps a typed draft"); + } } fn update(&mut self, cx: &mut Cx<'_, Self>) { @@ -337,14 +348,17 @@ impl Component for Pasteboard<'_> { let Some(space) = canvas_space(&cx.env) else { return }; let (view, style) = (space.view, cx.style); let draw = ui.draw(); + let edges = ui.content_painter(cx); let polygon = |quad: &[Pos2; 4]| PaintShape::Polygon(quad.to_vec()); + // A colour the canvas sets is a plain data fill, with no pattern, as in production. + let fill = space.pasteboard().fill(); + let look = style.surround.shown(cx.env.canvas_pattern()); for quad in Self::quads(&view, self.pages, self.uncovered).iter().filter(|quad| bounds(quad).intersects(view.rect)) { - match self.color.fill() { + match fill { Some(color) => draw.data_fill(&polygon(quad), color), - None => draw.fill(&polygon(quad), style.fill), + None => paint_surround(&edges.painter, CheckerArea::Quad(*quad), &look), } } - let edges = ui.content_painter(cx); let aligned = view.axis_aligned(); let edge = |quad: &[Pos2; 4], color: StyleColor| { if aligned { diff --git a/crates/ui-canvas/src/canvas/pasteboard/stories.rs b/crates/ui-canvas/src/canvas/pasteboard/stories.rs index e321e0d21..0247185db 100644 --- a/crates/ui-canvas/src/canvas/pasteboard/stories.rs +++ b/crates/ui-canvas/src/canvas/pasteboard/stories.rs @@ -1,10 +1,11 @@ //! Stories of the pasteboard. use super::{NAME, PageBorder, PageFrame, Pasteboard, PasteboardColor}; -use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_view, story_view}; +use crate::canvas::Canvas; +use crate::canvas::testing::canvas_story::{StoryDocument, on_canvas_view, on_canvas_with, story_view}; use crate::contract::Show as _; use crate::style::DataColor; -use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story}; +use crate::testing::{Drive, Fixture, StoryData, StoryOutput, stage, story}; use craft_behavior::CanvasView; use craft_behavior::kurbo::{Point, Rect as DocRect}; use egui::{Color32, Rect, Ui}; @@ -56,8 +57,20 @@ fn page_with_a_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let view = view_values(data, 0.0); let border = border_of(data, PageBorder::Line); let pages: &[PageFrame] = data.value("pages", vec![PageFrame::new(DocRect::new(60.0, 40.0, 300.0, 220.0))]); + let room = stage(ui); + let canvas = Canvas::new("Document").view(view(room, ui.pixels_per_point())).pasteboard(PasteboardColor::DarkGray); + on_canvas_with(ui, room, canvas, Some(&StoryDocument::STANDARD), |ui, at| Pasteboard::new("Pasteboard", pages).border(border).show_at(ui, at)) +} + +/// An artboard with loose layers beside it: the pasteboard leaves their rects open, so they show on the canvas. +#[story(Pasteboard<'static>, covers = [Default], drive = Drive::Never)] +fn loose_layers(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let view = view_values(data, 0.0); + let border = border_of(data, PageBorder::DropShadow); + let pages: &[PageFrame] = data.value("pages", vec![PageFrame::new(DocRect::new(40.0, 40.0, 240.0, 200.0)).name("Artboard 1").active(true)]); + let loose = [DocRect::new(280.0, 60.0, 400.0, 140.0), DocRect::new(200.0, 220.0, 320.0, 260.0)]; on_canvas_view(ui, view, Some(&StoryDocument::STANDARD), |ui, at, _| { - Pasteboard::new("Pasteboard", pages).color(PasteboardColor::DarkGray).border(border).show_at(ui, at) + Pasteboard::new("Pasteboard", pages).uncovered(&loose).border(border).show_at(ui, at) }) } diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index 04bbd44fe..6b8b103f0 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -37,15 +37,13 @@ pub struct CanvasSpace { pasteboard: PasteboardColor, /// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a /// measuring pass. - #[allow(dead_code)] // P3(canvas-widgets-w9): cw.C70 `picture` picture: Option, } /// The shape the canvas reserved in its paint hook for the picture: its layer and index, which -/// [`CanvasSpace::paint_picture`] grows into a `Shape::Vec` in show order. -// P3(canvas-widgets-w9): cw.C70 decision (canvas-widgets-w1), `PictureSlot` +/// [`CanvasSpace::paint_picture`] grows into a `Shape::Vec` in show order. The space is `Copy` and holds no painter, +/// so the slot is named by these two. #[derive(Clone, Copy, Debug, PartialEq)] -#[allow(dead_code)] // P3(canvas-widgets-w9): cw.C70 `PictureSlot` pub(crate) struct PictureSlot { pub(crate) layer: egui::LayerId, pub(crate) idx: egui::layers::ShapeIdx, @@ -67,7 +65,7 @@ impl CanvasSpace { background: BackgroundPress::default(), canvas: None, pasteboard: PasteboardColor::Default, - picture: None, // P3(canvas-widgets-w9): cw.C70 + picture: None, } } @@ -141,19 +139,38 @@ impl CanvasSpace { } /// Appends `shapes` to the canvas's picture slot, so they paint under every canvas control of the body, in show - /// order with the displays that use [`RasterDisplay::picture`](super::RasterDisplay::picture). - // P3(canvas-widgets-w9): cw.C70 `ctx` + /// order with the displays that use [`RasterDisplay::picture`](super::RasterDisplay::picture). It takes the + /// context because the space holds none. Outside a canvas's paint (a measuring pass) there is no slot, and it + /// paints nothing. pub fn paint_picture(&self, ctx: &egui::Context, shapes: Vec) { - let _ = (ctx, shapes); - todo!("cw.C70") + let Some(slot) = self.picture else { return }; + if shapes.is_empty() { + return; + } + ctx.graphics_mut(|layers| { + layers.entry(slot.layer).mutate_shape(slot.idx, |clipped| { + if let egui::Shape::Vec(list) = &mut clipped.shape { + list.extend(shapes); + return; + } + let reserved = std::mem::replace(&mut clipped.shape, egui::Shape::Noop); + let list = if matches!(reserved, egui::Shape::Noop) { shapes } else { std::iter::once(reserved).chain(shapes).collect() }; + clipped.shape = egui::Shape::Vec(list); + }); + }); } /// This space with the canvas's picture slot of this pass. #[must_use] - #[allow(dead_code)] // P3(canvas-widgets-w9): cw.C70 `with_picture` - pub(crate) fn with_picture(self, slot: PictureSlot) -> Self { - let _ = slot; - todo!("cw.C70") + pub(crate) fn with_picture(mut self, slot: PictureSlot) -> Self { + self.picture = Some(slot); + self + } + + /// The slot the canvas reserved this pass, `None` before its paint step ran or outside a canvas: a display that + /// paints under the controls paints in place without one. + pub(crate) fn picture_slot(&self) -> Option { + self.picture } /// This space published by the canvas `id`. diff --git a/crates/ui-canvas/tests/it/canvas/pasteboard.rs b/crates/ui-canvas/tests/it/canvas/pasteboard.rs index 87692525f..1922579aa 100644 --- a/crates/ui-canvas/tests/it/canvas/pasteboard.rs +++ b/crates/ui-canvas/tests/it/canvas/pasteboard.rs @@ -1,12 +1,14 @@ //! `Pasteboard`: the Menu key or Shift+F10 on the focused canvas asks for the pasteboard menu at the view's centre, as -//! a secondary click on the pasteboard does where it lands. +//! a secondary click on the pasteboard does where it lands; the pasteboard is the canvas minus the pages and the +//! uncovered rects in any view; and a press on it keeps a typed zoom unapplied, as a press on the image does not. use craft_behavior::CanvasView; -use craft_behavior::kurbo::{Point, Rect}; -use craft_ui::canvas::{Canvas, PageFrame, Pasteboard}; -use craft_ui::contract::{Show as _, ShowContainer as _}; +use craft_behavior::kurbo::{Point, Rect, Size}; +use craft_ui::buttons::Button; +use craft_ui::canvas::{Canvas, NavigatorZoomRow, PageFrame, Pasteboard}; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::testing::{Fixture, trial}; -use egui::{Key, Modifiers}; +use egui::{Key, Modifiers, Pos2, pos2, vec2}; use std::cell::Cell; use std::rc::Rc; @@ -28,3 +30,113 @@ fn the_menu_key_on_the_focused_canvas_asks_for_the_pasteboard_menu_at_the_views_ // The centre lies on the page: a keyed request has no point of its own to test against the pages. assert_eq!(asked.get(), Some(centre)); } + +/// Whether the convex quad `quad` holds `p`: on the inner side of every edge by more than `margin` (a negative margin +/// takes in points just outside). +fn holds(quad: &[Pos2; 4], p: Pos2, margin: f32) -> bool { + let sides: Vec = (0..4) + .map(|i| { + let (a, b) = (quad[i], quad[(i + 1) % 4]); + let edge = b - a; + (edge.x * (p.y - a.y) - edge.y * (p.x - a.x)) / edge.length().max(f32::EPSILON) + }) + .collect(); + sides.iter().all(|side| *side > margin) || sides.iter().all(|side| *side < -margin) +} + +#[trial] +fn uncovered_rects_stay_open_in_a_turned_view() { + let screen = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)); + let pages = [PageFrame::new(Rect::new(120.0, 90.0, 260.0, 200.0))]; + // One loose layer overlaps the page; the other runs past the visible area. + let uncovered = [Rect::new(230.0, 150.0, 320.0, 240.0), Rect::new(340.0, 20.0, 520.0, 110.0)]; + let holes: Vec = pages.iter().map(|page| page.rect).chain(uncovered).collect(); + // Doc points this close to a hole's edge are skipped: either answer is right on the line. + let near = 0.5; + for rotation in [0.0, 30.0] { + let view = CanvasView::new(screen, Point::new(200.0, 150.0), 1.0).rotation(rotation); + let quads = Pasteboard::quads(&view, &pages, &uncovered); + assert!(!quads.is_empty(), "{rotation}°: the pasteboard shows"); + let (mut open, mut covered) = (0, 0); + let samples = (0..55).flat_map(|i| (0..41).map(move |j| pos2(3.7 + 7.3 * i as f32, 2.9 + 7.3 * j as f32))); + for p in samples.filter(|p| screen.contains(*p)) { + let doc = view.to_doc(p); + if holes.iter().any(|hole| hole.inflate(near, near).contains(doc) && !hole.inflate(-near, -near).contains(doc)) { + continue; + } + if holes.iter().any(|hole| hole.contains(doc)) { + open += 1; + assert!(!quads.iter().any(|quad| holds(quad, p, 1e-3)), "{rotation}°: {p:?} (document {doc:?}) lies in a hole and in the pasteboard"); + } else { + covered += 1; + assert!(quads.iter().any(|quad| holds(quad, p, -1e-3)), "{rotation}°: {p:?} (document {doc:?}) lies outside every hole and every quad"); + } + } + assert!(open > 0 && covered > 0, "{rotation}°: the samples reach both the holes and the pasteboard"); + } +} + +const ZOOM_CENTRE: Point = Point::new(200.0, 150.0); +const ZOOM_PAGE: Rect = Rect::new(100.0, 80.0, 300.0, 220.0); +const ZOOM_DOCUMENT: Size = Size::new(2000.0, 1500.0); + +/// Where the zoom trial presses after typing. +#[derive(Clone, Copy, Debug)] +enum PressOn { + /// The pasteboard above the page. + Pasteboard, + /// The middle of the page, the image. + Image, + /// A button outside the canvas. + Button, +} + +/// Types a zoom into the Navigator's zoom field above a canvas turned by `rotation` degrees, then clicks `on`. Returns +/// whether the typed zoom applied (the row committed it; a plain typed number already shows as a proposal) and whether +/// focus stayed in the field. +fn press_after_typing(rotation: f64, on: PressOn) -> (bool, bool) { + let zoom_view = Rc::new(Cell::new(CanvasView::new(egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0)), Point::new(1000.0, 750.0), 1.0))); + let canvas_view: Rc>> = Rc::new(Cell::new(None)); + let committed = Rc::new(Cell::new(false)); + let (zoom_shown, canvas_shown, seen) = (Rc::clone(&zoom_view), Rc::clone(&canvas_view), Rc::clone(&committed)); + let pages = [PageFrame::new(ZOOM_PAGE)]; + let mut fixture = Fixture::new(move |ui| { + let mut given = zoom_shown.get(); + let row = NavigatorZoomRow::new(Bind::bound(&mut given), ZOOM_DOCUMENT).show(ui); + zoom_shown.set(given); + seen.set(seen.get() || row.view.committed().is_some()); + let _ = Button::new("Elsewhere").show(ui); + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, ZOOM_CENTRE, 1.0).rotation(rotation); + canvas_shown.set(Some(view)); + let _ = Canvas::new("Document").view(view).show_at(ui, room, |ui, body| Pasteboard::new("Pasteboard", &pages).show_at(ui, body.rect)); + }); + // Tall enough that the pasteboard 60 points above the page lies on the canvas below the zoom row and the button. + fixture.room(vec2(400.0, 400.0)).settle(); + let field = fixture.by_label("Zoom").expect("the zoom field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("250").settle(); + let typing = fixture.focused_stop(); + assert!(typing.is_some(), "the zoom field holds focus while a zoom is typed"); + assert!(!committed.get(), "a typed zoom waits for its commit"); + let view = canvas_view.get().expect("the canvas showed"); + let at = match on { + PressOn::Pasteboard => view.to_screen(Point::new(ZOOM_CENTRE.x, ZOOM_PAGE.y0 - 60.0)), + PressOn::Image => view.to_screen(ZOOM_CENTRE), + PressOn::Button => fixture.by_label("Elsewhere").expect("the button").center(), + }; + assert!(matches!(on, PressOn::Button) || view.rect.contains(at), "{on:?}: the press lands on the canvas"); + fixture.click_at(at).settle(); + (committed.get(), fixture.focused_stop() == typing) +} + +#[trial] +fn a_press_on_the_pasteboard_keeps_a_typed_zoom_and_one_on_the_image_applies_it() { + for rotation in [0.0, 30.0] { + let (applied, kept) = press_after_typing(rotation, PressOn::Pasteboard); + assert!(!applied, "{rotation}°: a press on the pasteboard leaves the typed zoom unapplied"); + assert!(kept, "{rotation}°: a press on the pasteboard leaves focus in the zoom field"); + } + assert!(press_after_typing(0.0, PressOn::Image).0, "a press on the image applies the typed zoom"); + assert!(press_after_typing(0.0, PressOn::Button).0, "a press on a button elsewhere applies the typed zoom"); +} diff --git a/crates/ui-contract/src/contract/body/presses.rs b/crates/ui-contract/src/contract/body/presses.rs index 02dae5799..ff17c81d2 100644 --- a/crates/ui-contract/src/contract/body/presses.rs +++ b/crates/ui-contract/src/contract/body/presses.rs @@ -46,9 +46,11 @@ impl BodyCx<'_> { } /// Whether the press of [`surface_pressed`](Self::surface_pressed) is the second press of a double click: no child - /// or part takes it and its click count is two or more. One own-surface signal for every container. + /// or part takes it and its click count is two or more. One own-surface signal for every container (an empty + /// workspace opens a file on it). A measuring run sees none, for the reason + /// [`band_double_pressed`](Self::band_double_pressed) gives. pub fn surface_double_pressed(&self) -> bool { - self.memory.recall::(sub(self.id, "surface_press")).double + !self.memory.is_peek() && self.memory.recall::(sub(self.id, "surface_press")).double } /// Requests `cursor` at `priority` for this pass, in the cursor service the parts' and components' requests go @@ -65,12 +67,13 @@ impl BodyCx<'_> { impl BodyHooks<'_> { /// Records for the container's hooks whether this pass's primary press went down on its own surface /// (`BodyCx::surface_pressed`): no shape of last pass under the press takes it, and the press lies in the - /// container's rect on its layer. + /// container's rect on its layer; and whether that press is the second of a double click + /// (`BodyCx::surface_double_pressed`), read from the same press's click count. pub(super) fn surface_press(&self, sensed: bool, cx: &mut Cx<'_, C>) { let ctx = cx.core.ctx.clone(); - let pressed = sensed && { + let surface = if sensed { let pass = pointer::pass_pointer(&ctx); - pass.frame.as_ref().and_then(|frame| frame.press).filter(|press| press.button == craft_behavior::PointerButton::Primary).is_some_and( + pass.frame.as_ref().and_then(|frame| frame.press).filter(|press| press.button == craft_behavior::PointerButton::Primary).filter( |press| { let layer = cx.core.response.layer_id; let at = areas::layer_map(&ctx, layer).map_or(press.origin, |map| map.to_layer(press.origin)); @@ -79,10 +82,12 @@ impl BodyHooks<'_> { && pointer::press_winner(&ctx, press.origin, pass.press_targets).is_none() }, ) + } else { + None }; let shown = cx.core.memory.shown::(sub(sub(cx.core.id, "body"), "surface_press")); - shown.pressed = pressed; - shown.double = false; // P3(canvas-widgets-w9): cw.C46 + shown.pressed = surface.is_some(); + shown.double = surface.is_some_and(|press| press.clicks >= 2); } /// Records for the container's header hooks whether the second press of a double click went down on the move diff --git a/crates/ui-contract/src/style/surround.rs b/crates/ui-contract/src/style/surround.rs index 1cf922b64..fd48924ca 100644 --- a/crates/ui-contract/src/style/surround.rs +++ b/crates/ui-contract/src/style/surround.rs @@ -1,8 +1,18 @@ //! The canvas surround: the fill around a document and the theme's pattern over it. use super::UiTokens; -use crate::primitives::CheckerArea; -use egui::Color32; +use super::paint::color as rgba_color; +use crate::primitives::textures::UNTINTED; +use crate::primitives::{CheckerArea, TextureCache, fill_polygon}; +use egui::epaint::{RectShape, Vertex}; +use egui::{Color32, ColorImage, Mesh, Pos2, Rect, Shape, TextureFilter, TextureOptions, TextureWrapMode}; + +/// The side of the pattern's tile, in points: one dot per tile. +const TILE: f32 = 22.0; + +/// The dot's four texels at the tile centre and their share of the pattern colour's alpha, the dot an antialiased +/// point slightly off the texel grid. +const DOT: [((usize, usize), u8); 4] = [((10, 10), 255), ((11, 10), 110), ((10, 11), 110), ((11, 11), 60)]; /// How the surround around a canvas looks: its fill and the pattern drawn over it. #[derive(Clone, Copy, Debug, PartialEq)] @@ -15,21 +25,75 @@ pub struct SurroundLook { } impl SurroundLook { - /// The surround of the theme `tokens` resolve from. + /// The surround of the theme `tokens` resolve from: the `surface.canvas` fill, and `surface.canvas_pattern` as + /// the pattern where the theme sets one. A theme whose pattern equals its fill has none, so no texture is made + /// that would paint nothing (#4542). pub fn of(tokens: &UiTokens) -> Self { - let _ = tokens; - todo!("cw.C47") + let surface = &tokens.color.surface; + let pattern = (surface.canvas_pattern != surface.canvas).then(|| rgba_color(surface.canvas_pattern)); + Self { fill: rgba_color(surface.canvas), pattern } } - /// The same look with the pattern kept when `pattern_on`, else dropped. + /// The same look with the pattern kept when `pattern_on`, else dropped. Callers pass the app's preference, + /// `EnvView::canvas_pattern`, which a style cannot read. + #[must_use] pub fn shown(self, pattern_on: bool) -> Self { - let _ = pattern_on; - todo!("cw.C47") + Self { pattern: self.pattern.filter(|_| pattern_on), ..self } } } -/// Paints the surround `look` over `area`. +/// Paints the surround `look` over `area`: the fill, and with a pattern one textured shape of the dot tile over it. +/// The tile is laid in screen space from the origin, so the dots hold still while the view scrolls or turns. A rect takes its corners; a quad (a piece of a turned pasteboard) is filled as `Draw` fills a polygon. pub fn paint_surround(painter: &egui::Painter, area: CheckerArea, look: &SurroundLook) { - let _ = (painter, area, look); - todo!("cw.C47") + match area { + CheckerArea::Rect(rect, radius) => { + painter.add(Shape::Rect(RectShape::filled(rect, radius, look.fill))); + } + CheckerArea::Quad(corners) => { + let feather = painter.ctx().tessellation_options(|options| { + if options.feathering { options.feathering_size_in_pixels / painter.pixels_per_point() } else { 0.0 } + }); + let mesh = fill_polygon(&corners, look.fill, feather); + if !mesh.is_empty() { + painter.add(Shape::mesh(mesh)); + } + } + } + let Some(pattern) = look.pattern else { return }; + let texture = dot_texture(painter.ctx(), pattern); + let uv = |p: Pos2| (p.to_vec2() / TILE).to_pos2(); + let shape = match area { + CheckerArea::Rect(rect, radius) => { + Shape::Rect(RectShape::filled(rect, radius, UNTINTED).with_texture(texture, Rect::from_min_max(uv(rect.min), uv(rect.max)))) + } + CheckerArea::Quad(corners) => { + let mut mesh = Mesh::with_texture(texture); + mesh.vertices.extend(corners.iter().map(|&pos| Vertex { pos, uv: uv(pos), color: UNTINTED })); + mesh.indices.extend([0, 1, 2, 0, 2, 3]); + Shape::mesh(mesh) + } + }; + painter.add(shape); +} + +/// The repeating tile of one `pattern` dot, from the runtime's texture cache: one texture per pattern colour. +fn dot_texture(ctx: &egui::Context, pattern: Color32) -> egui::TextureId { + let options = TextureOptions { + magnification: TextureFilter::Linear, + minification: TextureFilter::Linear, + wrap_mode: TextureWrapMode::Repeat, + mipmap_mode: None, + }; + TextureCache::texture_with(ctx, ("craft-ui-surround", pattern), options, || { + let side = TILE as usize; + let [r, g, b, a] = pattern.to_srgba_unmultiplied(); + let mut pixels = vec![Color32::TRANSPARENT; side * side]; + for ((x, y), share) in DOT { + let alpha = (u16::from(a) * u16::from(share) / 255) as u8; + if let Some(pixel) = pixels.get_mut(y * side + x) { + *pixel = Color32::from_rgba_unmultiplied(r, g, b, alpha); + } + } + ColorImage::new([side, side], pixels) + }) } diff --git a/crates/ui-contract/tests/it/paint/mod.rs b/crates/ui-contract/tests/it/paint/mod.rs index f33057ef0..2f42bfe96 100644 --- a/crates/ui-contract/tests/it/paint/mod.rs +++ b/crates/ui-contract/tests/it/paint/mod.rs @@ -2,6 +2,8 @@ mod backdrop; mod painters; +mod surround; + mod text_place; mod texture_store; diff --git a/crates/ui-contract/tests/it/paint/surround.rs b/crates/ui-contract/tests/it/paint/surround.rs new file mode 100644 index 000000000..779da7be9 --- /dev/null +++ b/crates/ui-contract/tests/it/paint/surround.rs @@ -0,0 +1,47 @@ +//! The canvas surround: a theme's pattern draws the dot texture over the fill; a theme without one, or the preference +//! turned off, draws the fill alone and makes no texture (#4542). + +use craft_theme::{Contrast, Mode, Rgba, Size}; +use craft_ui::primitives::CheckerArea; +use craft_ui::style::{SurroundLook, UiTokens, paint_surround}; +use craft_ui::testing::{Frames, trial}; +use egui::{CornerRadius, Rect, Shape, TextureId, pos2, vec2}; +use std::sync::Arc; + +/// `base` with its canvas pattern set to `pattern`, or to the canvas fill for none. +fn with_pattern(base: &UiTokens, pattern: Option) -> UiTokens { + let mut tokens = (**base.tokens()).clone(); + tokens.color.surface.canvas_pattern = pattern.unwrap_or(tokens.color.surface.canvas); + UiTokens::new(Arc::new(tokens), Contrast::Standard, Size::Compact) +} + +#[trial] +fn only_a_theme_pattern_draws_the_canvas_surround_texture() { + let base = craft_ui::testing::style::tokens(Mode::Dark, Contrast::Standard); + let plain = with_pattern(&base, None); + let dot = Rgba([200, 40, 40, 255]); + assert_ne!(dot, base.color.surface.canvas, "the pattern differs from the fill"); + let dotted = with_pattern(&base, Some(dot)); + + let area = Rect::from_min_size(pos2(40.0, 30.0), vec2(200.0, 120.0)); + let mut frames = Frames::new(); + let mut painted = |look: SurroundLook| -> Vec { + let shapes = frames.frame_shapes(|ui| paint_surround(ui.painter(), CheckerArea::Rect(area, CornerRadius::ZERO), &look)); + shapes.into_iter().filter(|shape| shape.visual_bounding_rect() == area).collect() + }; + + let cases = [ + ("a theme whose pattern is its fill", SurroundLook::of(&plain), false), + ("the same theme with the preference on", SurroundLook::of(&plain).shown(true), false), + ("a theme with a pattern", SurroundLook::of(&dotted), true), + ("a theme with a pattern and the preference on", SurroundLook::of(&dotted).shown(true), true), + ("a theme with a pattern and the preference off", SurroundLook::of(&dotted).shown(false), false), + ]; + for (case, look, textured) in cases { + assert_eq!(look.pattern.is_some(), textured, "{case}: the look's pattern"); + let shapes = painted(look); + let fills = shapes.iter().filter(|shape| shape.texture_id() == TextureId::default()).count(); + let dots = shapes.iter().filter(|shape| shape.texture_id() != TextureId::default()).count(); + assert_eq!((fills, dots), (1, usize::from(textured)), "{case}: one fill, and the dot texture only with a pattern"); + } +} diff --git a/crates/ui-shell/src/shell/canvas_shell.rs b/crates/ui-shell/src/shell/canvas_shell.rs index fe61128dd..1319a8327 100644 --- a/crates/ui-shell/src/shell/canvas_shell.rs +++ b/crates/ui-shell/src/shell/canvas_shell.rs @@ -24,8 +24,10 @@ mod stories; use super::app_shell::{RegionBody, RegionFn, ShellRegion}; use super::words::ShellWords; use crate::contract::{BodyCx, NoValue, Outcome, PaneEdge, Props as _, ShellPane, ShowContainer as _}; +use crate::primitives::CheckerArea; use crate::runtime::env::{BodyMode, Env, Label, ShellEntry}; -use egui::{Rect, Response, Ui}; +use crate::style::{SurroundLook, paint_surround}; +use egui::{CornerRadius, Rect, Response, Ui}; /// The slot keys of the preset. pub mod slots { @@ -66,17 +68,19 @@ impl Outcome for CanvasPanelOutput { } /// The canvas panel of a dock: the panel rail at the end edge, spanning the tabs and the document; then, in what is -/// left, the document tab strip flush against the document; then the document area, which the shell's backdrop shows -/// through. Fill the rail with `rails::PanelRail` and the tab strip with `tabs::DocumentTabs`. +/// left, the document tab strip flush against the document; then the document area, over the canvas surround. Fill the +/// rail with `rails::PanelRail` and the tab strip with `tabs::DocumentTabs`. /// /// - **Tabs.** They show in normal mode when the host says so (`ShellCx::tabs_visible`), or while documents are /// [`opening`](CanvasPanel::opening) (a file that is still loading has a tab). Body-only mode shows neither tabs nor /// rail, but the rail shows during a reveal that shows the dock. /// - **Rail.** It is skipped when the dock is hidden (`ShellCx::dock_visible`, or the panels are hidden with /// Shift+Tab). +/// - **Surround.** The document area shows the canvas surround, and a double click on its empty room is +/// [`empty_double`](CanvasPanelOutput::empty_double). /// -/// With no documents the host shows its start screen instead and does not use the panel. Outside a shell the panel -/// shows everything. +/// With no documents the host shows its start screen instead, or the panel with an empty document area. Outside a +/// shell the panel shows everything. #[must_use = "show the panel with `show`"] #[derive(crate::contract::Pattern, crate::contract::Props)] pub struct CanvasPanel<'a> { @@ -125,8 +129,15 @@ impl<'a> CanvasPanel<'a> { .show(ui, |ui, cx| add(ui, cx)); tabs_rect = Some(out.response.rect); } - let out = ShellRegion::pane(ShellPane::new("document")).id_salt("document").label(words.document.clone()).show(ui, |ui, cx| document(ui, cx)); - CanvasPanelOutput { document: out.response.rect, response: out.output.response, rail: rail_rect, tabs: tabs_rect, empty_double: false } // P3(canvas-widgets-w9): cw.C46 + let mut empty_double = false; + let out = ShellRegion::pane(ShellPane::new("document")).id_salt("document").label(words.document.clone()).senses_surface().show(ui, |ui, cx| { + // Painted first, so a document the closure shows covers it. + let look = SurroundLook::of(&env.tokens).shown(cx.env.canvas_pattern()); + paint_surround(ui.painter(), CheckerArea::Rect(cx.rect, CornerRadius::ZERO), &look); + empty_double |= cx.surface_double_pressed(); + document(ui, cx); + }); + CanvasPanelOutput { document: out.response.rect, response: out.output.response, rail: rail_rect, tabs: tabs_rect, empty_double } } } diff --git a/crates/ui-shell/src/shell/canvas_shell/stories.rs b/crates/ui-shell/src/shell/canvas_shell/stories.rs index 2a814a6be..6dfa97b4d 100644 --- a/crates/ui-shell/src/shell/canvas_shell/stories.rs +++ b/crates/ui-shell/src/shell/canvas_shell/stories.rs @@ -20,3 +20,17 @@ fn canvas_panel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { }) .into() } + +/// The empty workspace: rail and tabs with no document, so the canvas surround fills the document area. +#[story(CanvasPanel<'static>, covers = [Default], drive = Drive::Never)] +fn empty_canvas_panel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + CanvasPanel::new() + .rail("Panels", |ui, _| { + Text::new("Rail").show(ui); + }) + .tabs(|ui, _| { + Text::new("Tabs").show(ui); + }) + .show(ui, |_, _| {}) + .into() +} diff --git a/crates/ui-shell/src/shell/start.rs b/crates/ui-shell/src/shell/start.rs index 5b54e9062..d8ea42029 100644 --- a/crates/ui-shell/src/shell/start.rs +++ b/crates/ui-shell/src/shell/start.rs @@ -166,7 +166,7 @@ pub struct StartScreen<'a> { /// With no recent files, the Recent body is a drop card with this hint, and a double click on the page's own room /// reports `StartAction::Open`. #[prop(into)] - #[allow(dead_code)] // P3(canvas-widgets-w9): cw.C45 + #[allow(dead_code)] // P3(top-w5): cw.C45 drop_hint: Option