canvas-widgets-w9: net change of 3 commits

- canvas-widgets-w9: written by an agent
- canvas-widgets-w9: review fixes (review-1)
- canvas-widgets-w9: the typed-zoom press trial reads the row's commit (a plain typed number proposes as typed) and shows the canvas tall enough for its pasteboard press (fwcw round 3)
This commit is contained in:
aiongg
2026-11-15 04:46:06 +00:00
parent e0104d06d6
commit b7ee7384fc
13 changed files with 460 additions and 68 deletions
+35 -21
View File
@@ -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<DocRect> = pages.iter().filter_map(|page| clip(page.rect.abs(), canvas)).collect();
let boards: Vec<DocRect> =
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 {
@@ -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)
})
}
+30 -13
View File
@@ -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<PictureSlot>,
}
/// 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<egui::Shape>) {
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<PictureSlot> {
self.picture
}
/// This space published by the canvas `id`.
+117 -5
View File
@@ -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<f32> = (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<Rect> = 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<Cell<Option<CanvasView>>> = 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");
}
@@ -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::<SurfacePress>(sub(self.id, "surface_press")).double
!self.memory.is_peek() && self.memory.recall::<SurfacePress>(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<C: Container>(&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::<SurfacePress>(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
+75 -11
View File
@@ -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)
})
}
+2
View File
@@ -2,6 +2,8 @@ mod backdrop;
mod painters;
mod surround;
mod text_place;
mod texture_store;
@@ -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<Rgba>) -> 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<Shape> {
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");
}
}
+18 -7
View File
@@ -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 }
}
}
@@ -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()
}
+1 -1
View File
@@ -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<Label>,
}
@@ -0,0 +1,92 @@
//! `CanvasPanel`: a double click on the empty document area is the panel's `empty_double` (the host opens a file);
//! over a document whose canvas takes the press, it is never reported.
use craft_behavior::{HitLevel, HitPriority, PartKey, Sense};
use craft_ui::contract::{Common, Component, Cx, MeasureCx, PartsCx, Role, Show as _};
use craft_ui::shell::CanvasPanel;
use craft_ui::testing::pointer::{moved, press, release};
use craft_ui::testing::trial;
use craft_ui_test_kit::contract::PlainStyle;
use craft_ui_test_kit::windows::Windows;
use egui::{Event, Rect, Response, Vec2};
const BACKGROUND: PartKey = PartKey::new("background");
/// A document's canvas as the panel sees it: one background part over its rect that takes presses, as a `Canvas`'s
/// background part does (ui-shell cannot reach ui-canvas).
#[derive(craft_ui::contract::Component)]
struct Document {
#[common]
common: Common,
}
impl Component for Document {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &craft_ui::style::StyleCx<'_>, _: DocumentStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::ZERO
}
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
cx.part(BACKGROUND, rect)
.priority(HitPriority::new(HitLevel::Background, 0))
.sense(Sense::CLICK | Sense::DRAG)
.pointer_only("the document's tool takes the press");
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// Shows a panel with rail and tabs, and a document filling its document area when `with_document`; after two
/// settling frames, moves to the area's centre and clicks there `clicks` times, one frame per press and per release.
/// Returns the steps (0 the move) in which the panel reported `empty_double`.
fn empty_doubles(with_document: bool, clicks: usize) -> Vec<usize> {
let windows = Windows::new();
let mut document = Rect::NOTHING;
let mut reported = false;
let frame = |events: Vec<Event>, document: &mut Rect, reported: &mut bool| {
windows.frame(events, vec![], |ui| {
let shown = CanvasPanel::new().rail("Panels", |_, _| {}).tabs(|_, _| {}).show(ui, |ui, cx| {
if with_document {
Document { common: Common::new() }.show_at(ui, cx.rect);
}
});
*document = shown.document;
*reported |= shown.empty_double;
});
};
for _ in 0..2 {
frame(vec![], &mut document, &mut reported);
}
assert!(document.is_positive(), "the panel has a document area");
let at = document.center();
let mut steps = vec![vec![moved(at)]];
for _ in 0..clicks {
steps.extend([vec![press(at)], vec![release(at)]]);
}
let mut frames = Vec::new();
for (step, events) in steps.into_iter().enumerate() {
reported = false;
frame(events, &mut document, &mut reported);
if reported {
frames.push(step);
}
}
frames
}
#[trial]
fn an_empty_canvas_panel_reports_a_double_click_on_its_room() {
assert_eq!(empty_doubles(false, 1), Vec::<usize>::new(), "a single click on the empty room is no double click");
// Steps: move, press, release, press (the second press of the double click), release.
assert_eq!(empty_doubles(false, 2), vec![3], "the second press on the empty room reports once");
assert_eq!(empty_doubles(true, 2), Vec::<usize>::new(), "a document that takes the press leaves the room's double click unreported");
}
+1
View File
@@ -1,5 +1,6 @@
//! The window skeleton's interface: what `ShellCx` answers by mode and reveal, and how a body reads it.
mod canvas_panel;
mod caption_button;
mod document_window;
mod embed;