mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
Merge branch 'fw/merge-fb' into area/fwb2
This commit is contained in:
@@ -176,6 +176,8 @@ pub enum PressPhase {
|
||||
Held {
|
||||
/// The press.
|
||||
start: PressStart,
|
||||
/// The pointer position this pass.
|
||||
pos: Pos2,
|
||||
},
|
||||
/// The press moved past slop on a part that senses a drag.
|
||||
#[non_exhaustive]
|
||||
@@ -225,7 +227,7 @@ impl PressPhase {
|
||||
pub const fn start(&self) -> Option<PressStart> {
|
||||
match self {
|
||||
PressPhase::Down { start }
|
||||
| PressPhase::Held { start }
|
||||
| PressPhase::Held { start, .. }
|
||||
| PressPhase::DragStart { start, .. }
|
||||
| PressPhase::Drag { start, .. }
|
||||
| PressPhase::Release { start, .. }
|
||||
@@ -259,7 +261,7 @@ impl PressPhase {
|
||||
match self {
|
||||
PressPhase::Idle | PressPhase::Hover => self,
|
||||
PressPhase::Down { start } => PressPhase::Down { start: at(start) },
|
||||
PressPhase::Held { start } => PressPhase::Held { start: at(start) },
|
||||
PressPhase::Held { start, pos } => PressPhase::Held { start: at(start), pos: point(pos) },
|
||||
PressPhase::DragStart { start, pos } => PressPhase::DragStart { start: at(start), pos: point(pos) },
|
||||
PressPhase::Drag { start, pos, delta: d } => PressPhase::Drag { start: at(start), pos: point(pos), delta: delta(d) },
|
||||
PressPhase::Release { start, pos, click } => PressPhase::Release { start: at(start), pos: point(pos), click },
|
||||
@@ -642,7 +644,7 @@ impl<T: Copy> PressMachine<T> {
|
||||
} else if open.dragging {
|
||||
PressPhase::Drag { start: open.start, pos, delta: input.delta }
|
||||
} else {
|
||||
PressPhase::Held { start: open.start }
|
||||
PressPhase::Held { start: open.start, pos }
|
||||
};
|
||||
open.reported = true;
|
||||
PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None }
|
||||
@@ -703,6 +705,15 @@ mod tests {
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn held_reports_the_pointer_of_its_pass_within_slop() {
|
||||
let mut machine = PressMachine::new();
|
||||
pass(&mut machine, &[press(0.0, 1.0)], Sense::DRAG);
|
||||
let near = pos2(SLOP / 2.0, 0.0);
|
||||
let step = pass(&mut machine, &[PointerEvent::Moved { at: near, sample: None }], Sense::DRAG);
|
||||
assert!(matches!(step.phase, Some(PressPhase::Held { pos, .. }) if pos == near), "{:?}", step.phase);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_clicks_whose_passes_share_a_release_and_a_press_report_every_phase_in_order() {
|
||||
let up = PointerEvent::released(pos2(0.0, 0.0));
|
||||
|
||||
@@ -5,7 +5,7 @@ use bitflags::bitflags;
|
||||
bitflags! {
|
||||
/// What a root or a part senses. The egui adapter maps the root's sense to egui's.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct Sense: u16 {
|
||||
pub struct Sense: u32 {
|
||||
/// Hover only.
|
||||
const HOVER = 1;
|
||||
/// A press released within slop activates.
|
||||
@@ -45,6 +45,11 @@ bitflags! {
|
||||
/// A zoom zone: a vertical wheel over the shape zooms the view of the innermost enclosing taker of the zoom
|
||||
/// share (a ruler over its time area). The shape takes no wheel share itself.
|
||||
const WHEEL_ZOOMS_VIEW = 32768;
|
||||
/// The gesture begins at the first move after the press, inside slop, and the value follows the pointer from
|
||||
/// there, so it does not jump when the press passes slop. A press released with no move is a click. Declared
|
||||
/// with `DRAG` by a part whose click does nothing a drag could be mistaken for (a transform box's handles).
|
||||
/// The component begins the gesture from `PressPhase::Held`.
|
||||
const FOLLOWS_IN_SLOP = 65536;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -37,6 +37,14 @@ craft_ui::words! {
|
||||
pos_y: "info.posY" = "Y";
|
||||
w: "info.w" = "W";
|
||||
h: "info.h" = "H";
|
||||
/// The Ruler tool's angle.
|
||||
angle: "info.angle" = "A";
|
||||
/// A plain ruler's length.
|
||||
length: "info.length" = "L";
|
||||
/// A protractor's first arm.
|
||||
length1: "info.length1" = "L1";
|
||||
/// A protractor's second arm.
|
||||
length2: "info.length2" = "L2";
|
||||
/// The document size template.
|
||||
document: template "info.document" = "Doc: {width} x {height}";
|
||||
no_document: "info.noDocument" = "No document";
|
||||
@@ -62,6 +70,40 @@ impl InfoColor {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ruler tool's measure, its values as the app formats them in the ruler's unit.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum InfoMeasure {
|
||||
/// A plain ruler: its angle and length.
|
||||
Line {
|
||||
/// The angle.
|
||||
angle: Label,
|
||||
/// The length.
|
||||
length: Label,
|
||||
},
|
||||
/// A protractor: the angle between its arms and the arms' lengths.
|
||||
Protractor {
|
||||
/// The angle between the arms.
|
||||
angle: Label,
|
||||
/// The first arm's length.
|
||||
first: Label,
|
||||
/// The second arm's length.
|
||||
second: Label,
|
||||
},
|
||||
}
|
||||
|
||||
impl InfoMeasure {
|
||||
/// A plain ruler's measure.
|
||||
pub fn line(angle: impl Into<Label>, length: impl Into<Label>) -> Self {
|
||||
InfoMeasure::Line { angle: angle.into(), length: length.into() }
|
||||
}
|
||||
|
||||
/// A protractor's measure.
|
||||
pub fn protractor(angle: impl Into<Label>, first: impl Into<Label>, second: impl Into<Label>) -> Self {
|
||||
InfoMeasure::Protractor { angle: angle.into(), first: first.into(), second: second.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Info panel shows.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -72,6 +114,8 @@ pub struct InfoReadings<'a> {
|
||||
pub position: Option<[Label; 2]>,
|
||||
/// The selection's extent.
|
||||
pub extent: Option<[Label; 2]>,
|
||||
/// The Ruler tool's measure, while it has a ruler.
|
||||
pub measure: Option<InfoMeasure>,
|
||||
/// The document's size; `None` is the no-document state.
|
||||
pub document: Option<[u32; 2]>,
|
||||
/// The colour samplers' readouts with their position labels.
|
||||
@@ -105,6 +149,13 @@ impl<'a> InfoReadings<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the Ruler tool's measure.
|
||||
#[must_use]
|
||||
pub fn measure(mut self, measure: Option<InfoMeasure>) -> Self {
|
||||
self.measure = measure;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the document size.
|
||||
#[must_use]
|
||||
pub fn document(mut self, document: Option<[u32; 2]>) -> Self {
|
||||
@@ -120,7 +171,8 @@ impl<'a> InfoReadings<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A read-only grid: RGB beside CMYK, X/Y beside W/H, the document size, then one row group per sampler; a dash for a
|
||||
/// A read-only grid: RGB beside CMYK, the Ruler tool's measure (the angle A beside the length L, or a protractor's arms
|
||||
/// L1 and L2 stacked beside it), X/Y beside W/H, the document size, then one row group per sampler; a dash for a
|
||||
/// missing value; `document: None` shows "No document" as a centred notice in place of the grid.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
@@ -195,6 +247,16 @@ impl<'a> InfoPanel<'a> {
|
||||
let rgb = rgb_names.get(at).map(|rgb_name| (rgb_name.clone(), number(readings.color.map(|color| color.rgb[at]))));
|
||||
lines.push([rgb, Some((cmyk_name.clone(), number(readings.color.map(|color| color.cmyk[at]))))]);
|
||||
}
|
||||
match &readings.measure {
|
||||
Some(InfoMeasure::Line { angle, length }) => {
|
||||
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length), Some(length.clone())))]);
|
||||
}
|
||||
Some(InfoMeasure::Protractor { angle, first, second }) => {
|
||||
lines.push([Some((name(&words.angle), Some(angle.clone()))), Some((name(&words.length1), Some(first.clone())))]);
|
||||
lines.push([None, Some((name(&words.length2), Some(second.clone())))]);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
let (position, extent) = (readings.position.as_ref(), readings.extent.as_ref());
|
||||
let axes = [(name(&words.x), name(&words.w)), (name(&words.pos_y), name(&words.h))];
|
||||
for (axis, (position_name, extent_name)) in axes.into_iter().enumerate() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Stories of `InfoPanel`: a full reading with two samplers, readings with every value missing, and no document.
|
||||
//! Stories of `InfoPanel`: a full reading with two samplers, a protractor's measure, readings with every value missing,
|
||||
//! and no document.
|
||||
|
||||
use super::{InfoColor, InfoPanel, InfoReadings};
|
||||
use super::{InfoColor, InfoMeasure, InfoPanel, InfoReadings};
|
||||
use crate::ui::SamplerReadout;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
@@ -36,3 +37,14 @@ fn info_panel_no_document(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
let readings = InfoReadings::new();
|
||||
InfoPanel::new("Info", &readings).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(InfoPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn info_panel_protractor(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
|
||||
let readings = InfoReadings::new()
|
||||
.color(Some(InfoColor { rgb: [64, 128, 192], cmyk: [67, 33, 0, 25] }))
|
||||
.measure(Some(InfoMeasure::protractor("45.0°", "200.00", "141.42")))
|
||||
.position(Some(pair("100", "80")))
|
||||
.extent(Some(pair("200", "0")))
|
||||
.document(Some([1920, 1080]));
|
||||
InfoPanel::new("Info", &readings).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -58,7 +58,7 @@ pub use harmony::{
|
||||
};
|
||||
pub use hex::{HexPair, HexPairField, PairCodec};
|
||||
pub use hud::{ColorHud, ColorHudOutput};
|
||||
pub use info::{InfoColor, InfoPanel, InfoReadings, InfoWords};
|
||||
pub use info::{InfoColor, InfoMeasure, InfoPanel, InfoReadings, InfoWords};
|
||||
pub use lut_picker::{LutChoice, LutPicker, LutPickerOutput, LutWords};
|
||||
pub use paint_chip::{
|
||||
FillKind, GradientPreview, ImagePreview, Paint, PaintChip, PaintChipOutput, PaintEditor, PaintLink, PaintLinkKind, PaintList, PaintListEvent,
|
||||
|
||||
@@ -370,3 +370,29 @@ fn a_swatch_table_cell_reports_its_colour_selects_on_click_and_shows_its_name()
|
||||
fixture.settle();
|
||||
assert!(fixture.texts().iter().any(|run| run.text == "Red"), "the pointer's rest on a cell shows its name");
|
||||
}
|
||||
|
||||
/// Whether the Info panel over `measure` shows each of the names "A", "L", "L1", "L2".
|
||||
fn measure_names(measure: Option<craft_color::ui::InfoMeasure>) -> [bool; 4] {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let readings = craft_color::ui::InfoReadings::new().measure(measure.clone()).document(Some([640, 480]));
|
||||
let _ = craft_color::ui::InfoPanel::new("Info", &readings).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
["A", "L", "L1", "L2"].map(|name| fixture.by_label(name).is_some())
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_info_panel_shows_the_rulers_measure_while_it_has_one() {
|
||||
use craft_color::ui::InfoMeasure;
|
||||
assert_eq!(measure_names(Some(InfoMeasure::line("-36.9°", "250.00"))), [true, true, false, false], "a ruler: A and L");
|
||||
assert_eq!(measure_names(Some(InfoMeasure::protractor("45.0°", "200.00", "141.42"))), [true, false, true, true], "a protractor: A, L1 and L2");
|
||||
assert_eq!(measure_names(None), [false; 4], "no ruler, no measure names");
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let readings = craft_color::ui::InfoReadings::new().measure(Some(InfoMeasure::protractor("45.0°", "200.00", "141.42"))).document(Some([640, 480]));
|
||||
let _ = craft_color::ui::InfoPanel::new("Info", &readings).show(ui);
|
||||
});
|
||||
fixture.settle();
|
||||
for value in ["45.0°", "200.00", "141.42"] {
|
||||
assert!(fixture.by_label(value).is_some(), "the protractor's {value} shows");
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ use crate::contract::Cx;
|
||||
|
||||
fn pressed(cx: &Cx<'_, Chip>) -> bool {
|
||||
let state: &PressState = cx.press();
|
||||
matches!(state.phase(), Some(PressPhase::Held))
|
||||
matches!(state.phase(), Some(PressPhase::Held { .. }))
|
||||
}
|
||||
|
||||
fn stack(scopes: &mut Stack) {
|
||||
|
||||
@@ -22,8 +22,8 @@ use egui::{CornerRadius, Pos2, Rect, Response, Vec2};
|
||||
|
||||
use super::words::CropWords;
|
||||
|
||||
/// The quad of a perspective crop in document units, corners ordered top left, top right, bottom right, bottom left;
|
||||
/// `None` before one is drawn.
|
||||
/// The quad of a perspective crop in document units, its corners in the order of the crop's top left, top right,
|
||||
/// bottom right, bottom left; `None` before one is drawn.
|
||||
pub type PerspectiveQuad = Option<[Point; 4]>;
|
||||
|
||||
/// Fewest and most grid steps along a side.
|
||||
@@ -119,8 +119,9 @@ struct Report {
|
||||
/// - Shift on a corner drag keeps the axis the pointer moved less along; Alt on a corner of an upright quad moves the
|
||||
/// neighbouring corners too, so it stays a rectangle.
|
||||
/// - With a `shield` the document outside a valid quad is dimmed, under the grid.
|
||||
/// - A quad that is not convex or is wound differently from its box draws in the invalid colour without the grid and
|
||||
/// cannot be committed.
|
||||
/// - The corners stay where the user puts them: a quad wound counter-clockwise (a box flipped on one axis) applies
|
||||
/// mirrored, a box turned half way round applies upside down.
|
||||
/// - A quad that is not convex draws in the invalid colour without the grid and cannot be committed.
|
||||
/// - The quad and its corners are one Tab stop. Page Down and Page Up pick the whole quad or a corner; the arrows move
|
||||
/// the picked corner (1 document unit, Shift 10), or the whole quad when it is picked. Enter applies a valid quad.
|
||||
/// Esc cancels a drag, else discards.
|
||||
@@ -155,7 +156,7 @@ impl<'a> PerspectiveCropQuad<'a> {
|
||||
pub struct PerspectiveCropOutput {
|
||||
/// A drag (`Begin` on the first move, `Commit` on release; Esc cancels it) or an arrow key's `Set`.
|
||||
pub edit: EditResponse<PerspectiveQuad>,
|
||||
/// Enter while the quad is convex and wound like its box.
|
||||
/// Enter while the quad is convex ([`is_valid`]).
|
||||
pub apply: bool,
|
||||
/// Esc with no drag.
|
||||
pub discard: bool,
|
||||
@@ -201,7 +202,8 @@ fn upright(q: &[Point; 4]) -> bool {
|
||||
///
|
||||
/// - Shift keeps the press position's coordinate of the corner on the axis the drag moved less along.
|
||||
/// - Alt on a corner of an upright quad moves the two neighbouring corners one coordinate each, so it stays a
|
||||
/// rectangle, put in order when the corner passes the opposite one. A skewed quad's corner moves alone.
|
||||
/// rectangle. The corners stay as they lie when the corner passes the opposite one, so the box flips. A skewed
|
||||
/// quad's corner moves alone.
|
||||
fn dragged(drag: &Drag, to: Point, mods: Mods) -> [Point; 4] {
|
||||
match drag.grab {
|
||||
Grab::Corner { index, offset } => {
|
||||
@@ -222,7 +224,6 @@ fn dragged(drag: &Drag, to: Point, mods: Mods) -> [Point; 4] {
|
||||
let (in_row, in_column) = if index % 2 == 0 { (next, prev) } else { (prev, next) };
|
||||
quad[in_row].y = target.y;
|
||||
quad[in_column].x = target.x;
|
||||
return ordered(quad);
|
||||
}
|
||||
quad
|
||||
}
|
||||
@@ -433,10 +434,15 @@ pub fn ordered(points: [Point; 4]) -> [Point; 4] {
|
||||
v
|
||||
}
|
||||
|
||||
/// Whether `q` (top left, top right, bottom right, bottom left) is a usable perspective crop quad: finite, strictly
|
||||
/// convex with every corner angle above about 0.06 degrees, wound clockwise on screen (y down) and at least one unit^2
|
||||
/// in area.
|
||||
/// Whether `q` (top left, top right, bottom right, bottom left of the crop it maps onto) is a usable perspective crop
|
||||
/// quad: finite, strictly convex in either winding, every corner angle above about 0.06 degrees and at least one
|
||||
/// unit^2 in area. A quad wound counter-clockwise on screen (a box flipped on one axis) applies mirrored.
|
||||
pub fn is_valid(q: &[Point; 4]) -> bool {
|
||||
wound_clockwise(q) || wound_clockwise(&[q[0], q[3], q[2], q[1]])
|
||||
}
|
||||
|
||||
/// [`is_valid`] for a quad wound clockwise on screen (y down).
|
||||
fn wound_clockwise(q: &[Point; 4]) -> bool {
|
||||
if !finite(q) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -130,11 +130,6 @@ fn boxed(anchor: Point, to: Point) -> PerspectiveQuad {
|
||||
(x1 > x0 && y1 > y0).then_some([Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)])
|
||||
}
|
||||
|
||||
/// Whether `q` is convex whichever way it is wound: the preview of corners clicked in any order.
|
||||
fn convex(q: &[Point; 4]) -> bool {
|
||||
is_valid(q) || is_valid(&[q[0], q[3], q[2], q[1]])
|
||||
}
|
||||
|
||||
/// What the host hands the perspective crop pass each frame.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
@@ -271,7 +266,7 @@ impl CanvasTool for PerspectiveCropPass<'_> {
|
||||
_ => None,
|
||||
};
|
||||
if let Some(quad) = preview {
|
||||
let ok = clicks.len() == 2 || convex(&quad);
|
||||
let ok = clicks.len() == 2 || is_valid(&quad);
|
||||
if ok && self.input.show_grid {
|
||||
let grid = grid_color(style);
|
||||
for [a, b] in grid_lines(view, &quad, grid_step(style)) {
|
||||
|
||||
@@ -18,7 +18,7 @@ pub use bar::{RulerBar, RulerBarOutput};
|
||||
pub use distances::box_distances;
|
||||
pub use model::{MIN_LINE, RulerLine, RulerPart, RulerReading};
|
||||
pub use overlay::{RulerOverlay, RulerOverlayStyle};
|
||||
pub use tool::{RulerPass, RulerTool};
|
||||
pub use tool::{RulerPass, RulerTool, show_ruler};
|
||||
pub use words::RulerWords;
|
||||
|
||||
use craft_ui::patterns::form_dialogs::{Param, ParamDialog, ParamKind};
|
||||
|
||||
@@ -103,22 +103,6 @@ impl RulerLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// The part a press at `at` grabs within `reach` document units: the protractor's end first,
|
||||
/// then the end, then the start (PhotoCraft's order); `None` elsewhere.
|
||||
pub fn part_at(&self, at: Point, reach: f64) -> Option<RulerPart> {
|
||||
// pc: crates/ui-egui/src/tools/analysis_ui.rs:250 (the Down branch's match order).
|
||||
let near = |p: Point| p.distance(at) <= reach;
|
||||
if self.protractor.is_some_and(near) {
|
||||
Some(RulerPart::Protractor)
|
||||
} else if near(self.end) {
|
||||
Some(RulerPart::End)
|
||||
} else if near(self.start) {
|
||||
Some(RulerPart::Start)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The numbers of the line. The engine's `ruler_info` duplicates them on PhotoCraft's side
|
||||
/// (lead call 19); a PhotoCraft test compares the two.
|
||||
pub fn reading(&self) -> RulerReading {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
//! [`RulerOverlay`]: the end handles of the Ruler line, a canvas control. Its three points are parts in the canvas's
|
||||
//! arena, so a press on one stays with the overlay and a press elsewhere reaches the Ruler tool.
|
||||
//! [`RulerOverlay`]: the end handles of the Ruler line, a canvas control. Its three points and the line are parts in
|
||||
//! the canvas's arena, so a press on one stays with the overlay and a press elsewhere reaches the Ruler tool.
|
||||
|
||||
use super::model::{RulerLine, RulerPart};
|
||||
use super::words::RulerWords;
|
||||
use craft_behavior::geometry::turn_to_45;
|
||||
use craft_behavior::kurbo::{Point, Vec2 as DocVec};
|
||||
use craft_behavior::{Granularity, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense};
|
||||
use craft_behavior::{
|
||||
Cursor, CursorIcon, CursorPriority, Granularity, HitLevel, HitPriority, HitShape, IconId, Intent, Metrics, NavShape, PaintedCursor, PartKey,
|
||||
PartRef, PointerButton, PointerGlyph, PressPhase, Roving, Sense,
|
||||
};
|
||||
use craft_theme::{Stateful, States};
|
||||
use craft_ui::canvas::{CanvasSpace, NUDGE, NUDGE_FAR, canvas_space};
|
||||
use craft_ui::contract::{
|
||||
@@ -20,6 +23,8 @@ use egui::{Rect, Vec2};
|
||||
|
||||
/// The part of one point of the line: `POINT.at(RulerPart::index)`.
|
||||
pub(super) const POINT: PartKey = PartKey::new("point");
|
||||
/// The line between the ends, of a ruler without a protractor: `LINE.at(0)`.
|
||||
const LINE: PartKey = PartKey::new("line");
|
||||
|
||||
/// The style of the Ruler overlay: a cross at each point in the look of the line (a thin line over a thick halo).
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
@@ -33,24 +38,79 @@ pub struct RulerOverlayStyle {
|
||||
line: Stateful<StyleColor>,
|
||||
/// The halo under the cross, so it reads on any image.
|
||||
halo: StyleColor,
|
||||
/// A press within this many screen points of a point grabs it.
|
||||
/// A press within this many screen points of a point on either axis grabs it; within as many of the line, the
|
||||
/// line.
|
||||
reach: f32,
|
||||
}
|
||||
|
||||
/// The point a drag in progress moves, kept until the button comes up.
|
||||
/// What a drag in progress moves, kept until the button comes up.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Grab(Option<RulerPart>);
|
||||
struct Grab(Option<Grabbed>);
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Grabbed {
|
||||
/// One point.
|
||||
Point(RulerPart),
|
||||
/// The whole ruler: the press in document units and the line then.
|
||||
Whole { from: Point, at_press: RulerLine },
|
||||
}
|
||||
|
||||
/// A part of the overlay.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Target {
|
||||
Point(RulerPart),
|
||||
Line,
|
||||
}
|
||||
|
||||
impl Target {
|
||||
fn reference(self) -> PartRef {
|
||||
match self {
|
||||
Target::Point(part) => POINT.at(part.key()),
|
||||
Target::Line => LINE.at(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a primary press on the target grabs: the line, and a protractor's vertex, the whole ruler.
|
||||
fn grabs(self, line: RulerLine, from: Point) -> Grabbed {
|
||||
match self {
|
||||
Target::Line => Grabbed::Whole { from, at_press: line },
|
||||
Target::Point(RulerPart::Start) if line.protractor.is_some() => Grabbed::Whole { from, at_press: line },
|
||||
Target::Point(part) => Grabbed::Point(part),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an Alt press on the target starts the protractor arm: an end of a plain ruler, or a protractor's far
|
||||
/// end (the vertex moves the whole protractor).
|
||||
fn starts_arm(self, line: RulerLine) -> bool {
|
||||
matches!(self.grabs(line, Point::ZERO), Grabbed::Point(RulerPart::Start | RulerPart::End))
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ruler's pointer: the arrow with a ruler, or with a protractor where an Alt press starts the protractor arm;
|
||||
/// the crosshair while the canvas shows precise cursors.
|
||||
pub(super) fn ruler_cursor(precise: bool, protractor: bool) -> Cursor {
|
||||
if precise {
|
||||
return CursorIcon::Crosshair.into();
|
||||
}
|
||||
PaintedCursor::pointer_tool(PointerGlyph::Arrow, IconId::new(if protractor { "protractor" } else { "ruler" })).into()
|
||||
}
|
||||
|
||||
/// The Ruler line's points as handles: Start, End and, with a protractor, its free end.
|
||||
///
|
||||
/// - **Pointer:** a press within the reach of a point grabs it (the protractor's end first, then the end, then the
|
||||
/// start); a drag moves it and Shift puts it on the nearest 45° ray about the fixed end (about the vertex for the
|
||||
/// protractor's arm), at the pointer's distance from it. Alt-press on an end starts the protractor arm at that
|
||||
/// vertex (the ends swap first when the far end was pressed). Escape puts the line back.
|
||||
/// - **Pointer:** a press in the square of the reach around a point grabs it (the protractor's end first, then the
|
||||
/// end, then the start); a drag moves it and Shift puts it on the nearest 45° ray about the fixed end (about the
|
||||
/// vertex for the protractor's arm), at the pointer's distance from it. Alt-press on an end starts the protractor
|
||||
/// arm at that vertex (the ends swap first when the far end was pressed). A press within the reach of a plain
|
||||
/// ruler's line, or on a protractor's vertex with or without Alt, moves the whole ruler by the drag; a protractor's
|
||||
/// arm lines take no press. Escape puts the line back.
|
||||
/// - **Cursor:** the Ruler's arrow with a ruler; with a protractor where an Alt press starts the protractor arm; the
|
||||
/// crosshair while the canvas shows precise cursors.
|
||||
/// - **Keyboard:** the points are one Tab stop; Page Up and Page Down pick a point, the arrows move it 1 unit and
|
||||
/// Shift 10, Delete and Backspace clear the line.
|
||||
/// - It paints a cross at each point, in the line's look; the app shows the line and the arm with `StraightLinePreview`
|
||||
/// ([`RulerPass::show_line`](super::RulerPass::show_line)).
|
||||
/// - [Read only](Self::read_only), it paints the crosses at rest and takes no press, key or focus: the ruler drawn
|
||||
/// under the other tools ([`show_ruler`](super::show_ruler)).
|
||||
/// - **AccessKit:** the group's value reads "Length L, angle A°" in the ruler's units; each point is named and valued
|
||||
/// "x, y" in the ruler's units.
|
||||
#[derive(Component, craft_ui::contract::Props)]
|
||||
@@ -59,15 +119,23 @@ pub struct RulerOverlay<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
line: Bind<'a, Option<RulerLine>>,
|
||||
/// Whether the overlay only paints: no parts, no Tab stop, no keys.
|
||||
#[prop]
|
||||
read_only: bool,
|
||||
}
|
||||
|
||||
impl<'a> RulerOverlay<'a> {
|
||||
/// An overlay named `label` over the Ruler `line` (document units).
|
||||
pub fn new(label: impl Into<Label>, line: Bind<'a, Option<RulerLine>>) -> Self {
|
||||
RulerOverlay { common: Common::new(), line }.label(label)
|
||||
RulerOverlay { common: Common::new(), line, read_only: false }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
/// `line` moved by `by` as a whole.
|
||||
pub(super) fn translated(line: RulerLine, by: DocVec) -> RulerLine {
|
||||
RulerLine { start: line.start + by, end: line.end + by, protractor: line.protractor.map(|arm| arm + by) }
|
||||
}
|
||||
|
||||
/// The line with the grabbed `part` moved to `to`, Shift on 45° rays about the fixed point: the end for the start, the
|
||||
/// start for the end and the protractor.
|
||||
pub(super) fn moved(line: RulerLine, part: RulerPart, to: Point, shift: bool) -> RulerLine {
|
||||
@@ -110,59 +178,88 @@ impl Component for RulerOverlay<'_> {
|
||||
Some(self.line.reborrow())
|
||||
}
|
||||
|
||||
/// The points: drag parts at handle priority in one roving group, in keyboard order.
|
||||
/// The points: drag parts at handle priority in one roving group, in keyboard order; a plain ruler's line: a drag
|
||||
/// part under them.
|
||||
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
if self.read_only {
|
||||
return;
|
||||
}
|
||||
let (Some(space), Some(line)) = (canvas_space(&cx.env), cx.value().copied().flatten()) else { return };
|
||||
let reach = cx.style.reach;
|
||||
let mut any = false;
|
||||
for (sub, part) in [(0u8, RulerPart::Start), (1, RulerPart::End), (2, RulerPart::Protractor)] {
|
||||
let Some(at) = line.point(part) else { continue };
|
||||
cx.part(POINT.at(part.key()), HitShape::circle(space.view.to_screen(at), reach))
|
||||
let square = Rect::from_center_size(space.view.to_screen(at), Vec2::splat(2.0 * reach));
|
||||
cx.part(POINT.at(part.key()), HitShape::Rect(square))
|
||||
.sense(Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Handle, sub))
|
||||
.cursor(craft_behavior::CursorIcon::Crosshair)
|
||||
.focusable();
|
||||
any = true;
|
||||
}
|
||||
if any {
|
||||
cx.roving(Roving::new(NavShape::Flat).page(Some(1)));
|
||||
}
|
||||
let (a, b) = (space.view.to_screen(line.start), space.view.to_screen(line.end));
|
||||
let along = b - a;
|
||||
if line.protractor.is_none() && along.length() > 0.0 {
|
||||
let across = along.normalized().rot90() * reach;
|
||||
cx.part(LINE.at(0), HitShape::Polygon(vec![a + across, b + across, b - across, a - across]))
|
||||
.sense(Sense::DRAG)
|
||||
.priority(HitPriority::new(HitLevel::Edge, 0))
|
||||
.pointer_only("the arrow keys move the whole ruler while no end has focus");
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
if self.read_only {
|
||||
return;
|
||||
}
|
||||
let (Some(space), Some(line)) = (canvas_space(&cx.env), cx.value().copied().flatten()) else { return };
|
||||
for part in [RulerPart::Protractor, RulerPart::End, RulerPart::Start] {
|
||||
let Some(result) = cx.part_if_declared(POINT.at(part.key())) else { continue };
|
||||
let press = result.press;
|
||||
let targets = [Target::Point(RulerPart::Protractor), Target::Point(RulerPart::End), Target::Point(RulerPart::Start), Target::Line];
|
||||
for target in targets {
|
||||
let Some(result) = cx.part_if_declared(target.reference()) else { continue };
|
||||
let (press, hovered) = (result.press, result.hovered);
|
||||
let running = cx.press_slot::<Grab>().is_some_and(|grab| grab.0.is_some());
|
||||
if hovered && !press.phase.is_press() && !running {
|
||||
let arm = press.mods.alt && target.starts_arm(line);
|
||||
cx.cursor(ruler_cursor(space.precise(), arm), CursorPriority::Part);
|
||||
}
|
||||
// The line the grab gives with the pointer at `pos`.
|
||||
let at = |grabbed: Grabbed, base: RulerLine, pos: egui::Pos2| match grabbed {
|
||||
Grabbed::Point(part) => moved(base, part, space.view.to_doc(pos), press.mods.shift),
|
||||
Grabbed::Whole { from, at_press } => translated(at_press, space.view.to_doc(pos) - from),
|
||||
};
|
||||
match press.phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
|
||||
cx.press_slot::<Grab>().replace(Grab(Some(part)));
|
||||
cx.press_slot::<Grab>().replace(Grab(Some(target.grabs(line, space.view.to_doc(start.origin)))));
|
||||
}
|
||||
PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => {
|
||||
let grabbed = cx.press_slot::<Grab>().get_or_insert(Grab(Some(part))).0.unwrap_or(part);
|
||||
let (base, grabbed) = if press.mods.alt && grabbed != RulerPart::Protractor {
|
||||
let pressed = target.grabs(line, space.view.to_doc(start.origin));
|
||||
let grabbed = cx.press_slot::<Grab>().get_or_insert(Grab(Some(pressed))).0.unwrap_or(pressed);
|
||||
let (base, grabbed) = match grabbed {
|
||||
// Alt at an end starts the protractor arm at that vertex; the far end swaps in first.
|
||||
let mut base = line;
|
||||
if grabbed == RulerPart::End {
|
||||
std::mem::swap(&mut base.start, &mut base.end);
|
||||
Grabbed::Point(part @ (RulerPart::Start | RulerPart::End)) if press.mods.alt => {
|
||||
let mut base = line;
|
||||
if part == RulerPart::End {
|
||||
std::mem::swap(&mut base.start, &mut base.end);
|
||||
}
|
||||
(base.with_protractor(space.view.to_doc(pos)), Grabbed::Point(RulerPart::Protractor))
|
||||
}
|
||||
(base.with_protractor(space.view.to_doc(pos)), RulerPart::Protractor)
|
||||
} else {
|
||||
(line, grabbed)
|
||||
grabbed => (line, grabbed),
|
||||
};
|
||||
cx.press_slot::<Grab>().replace(Grab(Some(grabbed)));
|
||||
cx.begin();
|
||||
cx.propose(Some(moved(base, grabbed, space.view.to_doc(pos), press.mods.shift)));
|
||||
cx.propose(Some(at(grabbed, base, pos)));
|
||||
}
|
||||
PressPhase::Drag { start, pos, .. } if start.button == PointerButton::Primary => {
|
||||
if let Some(grabbed) = cx.press_slot::<Grab>().map(|grab| grab.0).flatten() {
|
||||
cx.propose(Some(moved(line, grabbed, space.view.to_doc(pos), press.mods.shift)));
|
||||
if let Some(grabbed) = cx.press_slot::<Grab>().and_then(|grab| grab.0) {
|
||||
cx.propose(Some(at(grabbed, line, pos)));
|
||||
}
|
||||
}
|
||||
PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => {
|
||||
let grab = cx.press_slot::<Grab>().take();
|
||||
if let Some(grabbed) = grab.and_then(|grab| grab.0).filter(|_| !click) {
|
||||
cx.propose(Some(moved(line, grabbed, space.view.to_doc(pos), press.mods.shift)));
|
||||
cx.propose(Some(at(grabbed, line, pos)));
|
||||
cx.commit();
|
||||
}
|
||||
}
|
||||
@@ -211,6 +308,9 @@ impl Component for RulerOverlay<'_> {
|
||||
let units = cx.env.units();
|
||||
let rulers = space.rulers();
|
||||
access.value(reading_text(&line, &space, &units, &words));
|
||||
if self.read_only {
|
||||
return;
|
||||
}
|
||||
for (part, name) in [(RulerPart::Start, &words.start), (RulerPart::End, &words.end), (RulerPart::Protractor, &words.protractor)] {
|
||||
let Some(at) = line.point(part) else { continue };
|
||||
let value = format!("{}, {}", rulers.x.format_value(&units, at.x, 0.0), rulers.y.format_value(&units, at.y, 0.0));
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
//! line from a press on the background and moves the whole line with the arrow keys.
|
||||
|
||||
use super::model::{MIN_LINE, RulerLine, RulerPart};
|
||||
use super::overlay::{RulerOverlay, moved, reading_text};
|
||||
use super::overlay::{RulerOverlay, moved, reading_text, ruler_cursor, translated};
|
||||
use super::words::RulerWords;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, Mixed};
|
||||
use craft_behavior::{CancelReason, Cursor, EditEvent, GestureId, Mixed};
|
||||
use craft_ui::canvas::{CanvasTool, NUDGE, NUDGE_FAR, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::canvas_controls::StraightLinePreview;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
@@ -31,7 +31,9 @@ struct Drag {
|
||||
/// - **Events:** the line's changes, in order, from [`take_events`](Self::take_events) after the host has run: the
|
||||
/// overlay's edits and the tool's. A drag is `Begin`, `Update`s and `Commit` (`Cancel` on Escape); a key press is a
|
||||
/// `Set`. The app stores the value; it is not an undo step.
|
||||
/// - **Cursor:** the crosshair.
|
||||
/// - **Cursor:** the Ruler's arrow with a ruler; the crosshair while the canvas shows precise cursors. Over an end
|
||||
/// with Alt the overlay shows the protractor ([`RulerOverlay`]).
|
||||
/// - Under the other tools the app draws the line with [`show_ruler`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct RulerTool {
|
||||
drag: Option<Drag>,
|
||||
@@ -68,10 +70,7 @@ impl RulerPass<'_> {
|
||||
pub fn show_line(&mut self, ui: &mut Ui, rect: Rect) {
|
||||
let Some(line) = self.line else { return };
|
||||
let words = craft_ui::runtime::env::Env::of(ui).words::<RulerWords>();
|
||||
StraightLinePreview::new(words.group.clone(), line.start, line.end).show_at(ui, rect);
|
||||
if let Some(arm) = line.protractor {
|
||||
StraightLinePreview::new(words.protractor.clone(), line.start, arm).show_at(ui, rect);
|
||||
}
|
||||
show_lines(ui, rect, line, &words);
|
||||
let mut shown = Some(line);
|
||||
let edit = RulerOverlay::new(words.group.clone(), Bind::bound(&mut shown)).show_at(ui, rect);
|
||||
if !edit.events.is_empty() {
|
||||
@@ -102,19 +101,32 @@ impl RulerPass<'_> {
|
||||
if by.hypot() == 0.0 {
|
||||
return false;
|
||||
}
|
||||
let by = by / by.hypot() * step;
|
||||
let mut next = line;
|
||||
next.start += by;
|
||||
next.end += by;
|
||||
next.protractor = line.protractor.map(|arm| arm + by);
|
||||
let next = translated(line, by / by.hypot() * step);
|
||||
self.report(Some(next), EditEvent::set(Mixed::Same(Some(line)), Some(next), Self::label(cx), None));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The Ruler line and its protractor arm.
|
||||
fn show_lines(ui: &mut Ui, rect: Rect, line: RulerLine, words: &RulerWords) {
|
||||
StraightLinePreview::new(words.group.clone(), line.start, line.end).show_at(ui, rect);
|
||||
if let Some(arm) = line.protractor {
|
||||
StraightLinePreview::new(words.protractor.clone(), line.start, arm).show_at(ui, rect);
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the Ruler `line` read only over the canvas `rect`: the line, the protractor arm and the crosses at its
|
||||
/// points, taking no press, key or focus. The app calls it in the canvas body while another tool is active (the ruler
|
||||
/// stays drawn until View > Extras hides it); under the Ruler tool, [`RulerPass::show_line`] draws it.
|
||||
pub fn show_ruler(ui: &mut Ui, rect: Rect, line: RulerLine) {
|
||||
let words = craft_ui::runtime::env::Env::of(ui).words::<RulerWords>();
|
||||
show_lines(ui, rect, line, &words);
|
||||
let _ = RulerOverlay::new(words.group.clone(), Bind::given(Some(line))).read_only(true).show_at(ui, rect);
|
||||
}
|
||||
|
||||
impl CanvasTool for RulerPass<'_> {
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
Cursor::System(CursorIcon::Crosshair)
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
|
||||
ruler_cursor(cx.precise(), false)
|
||||
}
|
||||
|
||||
/// Starts a new line at the press (Begin).
|
||||
|
||||
@@ -82,7 +82,7 @@ pub use gradient::{
|
||||
GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette, GradientRef,
|
||||
GradientSwatch, LineGradient, LinePart,
|
||||
};
|
||||
pub use measure::{MIN_LINE, RulerBar, RulerBarOutput, RulerLine, RulerOverlay, RulerPass, RulerTool, RulerWords, box_distances, ruler_line_form};
|
||||
pub use measure::{MIN_LINE, RulerBar, RulerBarOutput, RulerLine, RulerOverlay, RulerPass, RulerTool, RulerWords, box_distances, ruler_line_form, show_ruler};
|
||||
pub use paint_bar::{
|
||||
EraserMode, MIXER_COMBINATIONS, MIXER_GROUP_STARTS, MixerValues, PaintBar, PaintBarOutput, PaintBarWords, PaintTool, PaintValues, Smoothing,
|
||||
};
|
||||
|
||||
@@ -217,6 +217,13 @@ struct Grip {
|
||||
last: BoxState,
|
||||
}
|
||||
|
||||
impl Grip {
|
||||
/// Whether the box follows the pointer inside the slop: every part whose click means nothing.
|
||||
fn follows_in_slop(&self) -> bool {
|
||||
self.part != BoxPart::Outside && !self.moves_pivot
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Grip {
|
||||
fn default() -> Self {
|
||||
let none = BoxState::from_rect(DocRect::ZERO);
|
||||
@@ -535,27 +542,35 @@ impl<'a> TransformBox<'a> {
|
||||
let (part, begin) = if moves_pivot { (BoxPart::Pivot, BoxState::new(shown.quad, from)) } else { (part, *shown) };
|
||||
held = Some(Grip { part, start: begin, from, began: false, moves_pivot, last: *shown });
|
||||
}
|
||||
// Inside the slop the box follows every move of a part whose click means nothing, so it does not jump
|
||||
// when the drag is recognised. Outside (a click applies) and an Alt pivot press (a click sets the
|
||||
// pivot) start at the drag.
|
||||
PressPhase::Held { start, pos, .. } => {
|
||||
let Some(mut grip) = held else { continue };
|
||||
if !self.rules.allows(grip.part) || !grip.follows_in_slop() || (!grip.began && pos == start.origin) {
|
||||
continue;
|
||||
}
|
||||
if !grip.began {
|
||||
cx.begin();
|
||||
grip.began = true;
|
||||
}
|
||||
self.follow(cx, space, snap.as_ref(), &mut grip, pos, mods);
|
||||
held = Some(grip);
|
||||
}
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
|
||||
let Some(mut grip) = held else { continue };
|
||||
if !self.rules.allows(grip.part) {
|
||||
continue;
|
||||
}
|
||||
if matches!(press.phase, PressPhase::DragStart { .. }) {
|
||||
if matches!(press.phase, PressPhase::DragStart { .. }) && !grip.began {
|
||||
cx.begin();
|
||||
grip.began = true;
|
||||
}
|
||||
if !grip.began {
|
||||
continue;
|
||||
}
|
||||
let (next, lines) = self.proposal(space, snap.as_ref(), &grip, pos, mods);
|
||||
self.report.snapped = lines;
|
||||
grip.last = next;
|
||||
self.follow(cx, space, snap.as_ref(), &mut grip, pos, mods);
|
||||
held = Some(grip);
|
||||
cx.propose(next);
|
||||
let rows = self.readout_rows(cx, space, grip.part, &next, &grip.start);
|
||||
readout(&*cx, pos, &rows);
|
||||
let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, mods, true);
|
||||
cx.cursor(cursor, CursorPriority::Drag);
|
||||
}
|
||||
PressPhase::Release { start, click, .. } => {
|
||||
// A double click inside applies, whether or not the first press of the release was seen.
|
||||
@@ -578,6 +593,20 @@ impl<'a> TransformBox<'a> {
|
||||
*cx.press_slot::<Grip>() = held;
|
||||
}
|
||||
|
||||
/// One step of a begun grip with the pointer at `pos`: the proposal and its snap lines, the readout and the drag
|
||||
/// cursor.
|
||||
fn follow(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, snap: Option<&Snap>, grip: &mut Grip, pos: Pos2, mods: Mods) {
|
||||
let style = cx.style;
|
||||
let (next, lines) = self.proposal(space, snap, grip, pos, mods);
|
||||
self.report.snapped = lines;
|
||||
grip.last = next;
|
||||
cx.propose(next);
|
||||
let rows = self.readout_rows(cx, space, grip.part, &next, &grip.start);
|
||||
readout(&*cx, pos, &rows);
|
||||
let cursor = self.cursor(&CursorLook { space, screen: &on_screen(&space.view, &next), style }, grip.part, pos, mods, true);
|
||||
cx.cursor(cursor, CursorPriority::Drag);
|
||||
}
|
||||
|
||||
/// The session keys: the arrows nudge the picked part (the whole box when no part has focus), Enter applies and
|
||||
/// Escape closes the box. Untaken, a session's arrows go back to the canvas's tool.
|
||||
fn run_keys(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, shown: &BoxState, pressing: bool) {
|
||||
@@ -762,7 +791,7 @@ impl Component for TransformBox<'_> {
|
||||
)
|
||||
}
|
||||
};
|
||||
cx.part(BOX.at(part.index()), shape).sense(sense).priority(priority).focus_shape(focus).focusable();
|
||||
cx.part(BOX.at(part.index()), shape).sense(sense | Sense::FOLLOWS_IN_SLOP).priority(priority).focus_shape(focus).focusable();
|
||||
any = true;
|
||||
}
|
||||
if self.line.is_some() {
|
||||
@@ -774,14 +803,14 @@ impl Component for TransformBox<'_> {
|
||||
for k in (0..4u8).filter(|&k| self.rules.allows(BoxPart::Edge(k))) {
|
||||
let side = usize::from(k);
|
||||
cx.part(EDGE.at(u64::from(k)), HitShape::segment(quad[side], quad[(side + 1) % 4]))
|
||||
.sense(Sense::DRAG)
|
||||
.sense(Sense::DRAG | Sense::FOLLOWS_IN_SLOP)
|
||||
.priority(HitPriority::new(HitLevel::Handle, EDGE_SUB))
|
||||
.pointer_only(EDGE_BY_KEY);
|
||||
}
|
||||
if self.declares_centre() {
|
||||
let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0;
|
||||
cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::FOLLOWS_IN_SLOP)
|
||||
.priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB))
|
||||
.pointer_only(MOVE_BY_KEY);
|
||||
}
|
||||
@@ -790,7 +819,7 @@ impl Component for TransformBox<'_> {
|
||||
for side in 0..4usize {
|
||||
let next = (side + 1) % 4;
|
||||
cx.part(MOVE_RING.at(side as u64), HitShape::Polygon(vec![quad[side], quad[next], outer[next], outer[side]]))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::FOLLOWS_IN_SLOP)
|
||||
.priority(HitPriority::new(HitLevel::Body, RING_SUB))
|
||||
.pointer_only(MOVE_BY_KEY);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The Ruler: its line model, the options bar, the handles and the tool, and the distances between boxes.
|
||||
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
use craft_behavior::kurbo::{self, Point, Rect};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView, EditEvent};
|
||||
use craft_draw::ui::measure::{MIN_LINE, RulerLine, RulerOverlay, RulerTool, box_distances};
|
||||
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
@@ -111,6 +111,11 @@ impl CanvasTool for Driven {
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
// The Ruler's cursor reads only the line and the canvas, so a pass of a new tool gives it.
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> craft_behavior::Cursor {
|
||||
RulerTool::new().pass(*self.line.borrow()).cursor(cx)
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Ruler Line... command")
|
||||
}
|
||||
@@ -120,6 +125,8 @@ struct Shown {
|
||||
fixture: ToolFixture<Driven>,
|
||||
/// The line the tool's events left, as the app would store it.
|
||||
line: Rc<RefCell<Option<RulerLine>>>,
|
||||
/// The phases of the tool's and the overlay's edits, in order.
|
||||
log: Rc<RefCell<Vec<&'static str>>>,
|
||||
}
|
||||
|
||||
fn shown(start: Option<RulerLine>) -> Shown {
|
||||
@@ -145,7 +152,7 @@ fn shown(start: Option<RulerLine>) -> Shown {
|
||||
*body_line.borrow_mut() = line;
|
||||
},
|
||||
);
|
||||
Shown { fixture, line }
|
||||
Shown { fixture, line, log }
|
||||
}
|
||||
|
||||
/// A line near the canvas's top left corner (the view puts the document origin at the room's corner), away from the
|
||||
@@ -198,3 +205,205 @@ fn escape_during_a_ruler_drag_keeps_the_line_from_before_the_press() {
|
||||
fn the_ruler_tool_passes_the_tool_checks() {
|
||||
shown(None).fixture.check();
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
/// The screen point of document point `p`: the view puts the room's centre at the document's (w/2, h/2).
|
||||
fn screen(&self, p: Point) -> egui::Pos2 {
|
||||
let rect = self.fixture.canvas().rect;
|
||||
rect.center() + egui::vec2(p.x as f32 - rect.width() / 2.0, p.y as f32 - rect.height() / 2.0)
|
||||
}
|
||||
|
||||
/// The document point at the canvas's centre.
|
||||
fn middle(&self) -> Point {
|
||||
let rect = self.fixture.canvas().rect;
|
||||
Point::new(f64::from(rect.width()) / 2.0, f64::from(rect.height()) / 2.0)
|
||||
}
|
||||
|
||||
/// Presses at document point `from`, moves to `to` in two steps and releases, with `mods` held.
|
||||
fn drag(&mut self, from: Point, to: Point, mods: egui::Modifiers) {
|
||||
let (a, b) = (self.screen(from), self.screen(to));
|
||||
self.fixture.fixture().hold(mods);
|
||||
self.fixture.press_at(a);
|
||||
self.fixture.move_to(a.lerp(b, 0.5));
|
||||
self.fixture.move_to(b);
|
||||
self.fixture.release_at(b);
|
||||
self.fixture.fixture().hold(egui::Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// The cursor with the pointer resting at document point `at` and `mods` held.
|
||||
fn cursor_at(&mut self, at: Point, mods: egui::Modifiers) -> Option<craft_behavior::Cursor> {
|
||||
let to = self.screen(at);
|
||||
self.fixture.fixture().hold(mods);
|
||||
self.fixture.move_to(to);
|
||||
self.fixture.fixture().frame(Vec::new());
|
||||
let cursor = craft_ui::runtime::cursor::current(self.fixture.fixture().ctx());
|
||||
self.fixture.fixture().hold(egui::Modifiers::NONE);
|
||||
cursor
|
||||
}
|
||||
|
||||
fn count(&self, phase: &str) -> usize {
|
||||
self.log.borrow().iter().filter(|seen| **seen == phase).count()
|
||||
}
|
||||
}
|
||||
|
||||
/// The overlay's reach in screen points (the view is at scale 1, so also in document units).
|
||||
fn reach() -> f64 {
|
||||
f64::from(craft_ui::testing::style::tokens(craft_theme::Mode::Light, craft_theme::Contrast::Standard).size.hit.target)
|
||||
}
|
||||
|
||||
/// A plain ruler through the canvas's middle along (0.8, 0.6), 150 units long.
|
||||
fn plain(middle: Point) -> RulerLine {
|
||||
RulerLine::new(middle - kurbo::Vec2::new(60.0, 45.0), middle + kurbo::Vec2::new(60.0, 45.0))
|
||||
}
|
||||
|
||||
/// `plain` with a protractor arm 60 units down from its start.
|
||||
fn protractor(middle: Point) -> RulerLine {
|
||||
let line = plain(middle);
|
||||
line.with_protractor(line.start + kurbo::Vec2::new(0.0, 60.0))
|
||||
}
|
||||
|
||||
fn near(a: Point, b: Point) -> bool {
|
||||
a.distance(b) < 1e-3
|
||||
}
|
||||
|
||||
/// From upstream PhotoCraft's analysis_ruler_move_tests (#14978): a press on a plain ruler's line moves the whole
|
||||
/// ruler, the ends are hit in squares and move alone, and a press past the reach starts a new ruler.
|
||||
#[trial]
|
||||
fn a_drag_on_the_line_moves_the_whole_ruler_and_the_ends_are_hit_in_squares() {
|
||||
let r = reach();
|
||||
let across = kurbo::Vec2::new(-0.6, 0.8);
|
||||
let by = kurbo::Vec2::new(20.0, 30.0);
|
||||
|
||||
let mut ruler = shown(None);
|
||||
let middle = ruler.middle();
|
||||
let line = plain(middle);
|
||||
*ruler.line.borrow_mut() = Some(line);
|
||||
let from = middle + across * (0.75 * r);
|
||||
ruler.drag(from, from + by, egui::Modifiers::NONE);
|
||||
let moved = (*ruler.line.borrow()).expect("a line");
|
||||
assert!(near(moved.start, line.start + by) && near(moved.end, line.end + by), "the whole ruler moved by the drag: {moved:?}");
|
||||
assert_eq!((ruler.count("begin"), ruler.count("commit")), (1, 1), "one gesture: {:?}", ruler.log.borrow());
|
||||
|
||||
let mut ruler = shown(Some(line));
|
||||
let from = middle + across * (2.0 * r);
|
||||
ruler.drag(from, from + by, egui::Modifiers::NONE);
|
||||
let new = (*ruler.line.borrow()).expect("a line");
|
||||
assert!(near(new.start, from), "twice the reach off the line a press starts a new ruler: {new:?}");
|
||||
|
||||
// Inside the end's square, outside the circle of the same reach.
|
||||
let mut ruler = shown(Some(line));
|
||||
let to = line.end + kurbo::Vec2::new(30.0, -10.0);
|
||||
ruler.drag(line.end + kurbo::Vec2::new(0.8 * r, 0.8 * r), to, egui::Modifiers::NONE);
|
||||
let after = (*ruler.line.borrow()).expect("a line");
|
||||
assert!(near(after.end, to) && near(after.start, line.start), "the end goes to the pointer, alone: {after:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_protractors_vertex_moves_the_whole_protractor_and_its_arm_end_moves_alone() {
|
||||
let by = kurbo::Vec2::new(20.0, 30.0);
|
||||
for mods in [egui::Modifiers::NONE, egui::Modifiers::ALT] {
|
||||
let mut ruler = shown(None);
|
||||
let line = protractor(ruler.middle());
|
||||
*ruler.line.borrow_mut() = Some(line);
|
||||
ruler.drag(line.start, line.start + by, mods);
|
||||
let moved = (*ruler.line.borrow()).expect("a line");
|
||||
let arm = moved.protractor.expect("the arm stays");
|
||||
assert!(
|
||||
near(moved.start, line.start + by) && near(moved.end, line.end + by) && near(arm, line.protractor.unwrap() + by),
|
||||
"{mods:?}: all three points move: {moved:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut ruler = shown(None);
|
||||
let line = protractor(ruler.middle());
|
||||
*ruler.line.borrow_mut() = Some(line);
|
||||
let to = line.protractor.unwrap() + kurbo::Vec2::new(-10.0, 10.0);
|
||||
ruler.drag(line.protractor.unwrap(), to, egui::Modifiers::NONE);
|
||||
let after = (*ruler.line.borrow()).expect("a line");
|
||||
assert!(after.protractor.is_some_and(|arm| near(arm, to)) && near(after.start, line.start) && near(after.end, line.end), "{after:?}");
|
||||
|
||||
// The arm's line takes no press: a new ruler starts there.
|
||||
let mut ruler = shown(Some(line));
|
||||
let from = line.start + kurbo::Vec2::new(0.0, 30.0);
|
||||
ruler.drag(from, from + by, egui::Modifiers::NONE);
|
||||
let new = (*ruler.line.borrow()).expect("a line");
|
||||
assert!(near(new.start, from) && new.protractor.is_none(), "a press on the arm's line starts a new ruler: {new:?}");
|
||||
}
|
||||
|
||||
/// From upstream PhotoCraft's ruler_tests (#13438): the Ruler's arrow everywhere, the protractor with Alt exactly where
|
||||
/// an Alt press starts the protractor arm, and the crosshair while the canvas shows precise cursors.
|
||||
#[trial]
|
||||
fn the_ruler_shows_its_pointer_and_the_protractor_where_alt_starts_the_arm() {
|
||||
use craft_behavior::{Cursor, IconId, PaintedCursor, PointerGlyph};
|
||||
let pointer = |icon: &'static str| Some(Cursor::Painted(PaintedCursor::pointer_tool(PointerGlyph::Arrow, IconId::new(icon))));
|
||||
let alt = egui::Modifiers::ALT;
|
||||
|
||||
let mut empty = shown(None);
|
||||
let middle = empty.middle();
|
||||
assert_eq!(empty.cursor_at(middle, alt), pointer("ruler"), "no ruler: no end to mark");
|
||||
|
||||
let mut ruler = shown(Some(plain(middle)));
|
||||
let line = plain(middle);
|
||||
assert_eq!(ruler.cursor_at(middle + kurbo::Vec2::new(0.0, 40.0), egui::Modifiers::NONE), pointer("ruler"), "away from the ruler");
|
||||
assert_eq!(ruler.cursor_at(middle, egui::Modifiers::NONE), pointer("ruler"), "on its line");
|
||||
assert_eq!(ruler.cursor_at(line.end, egui::Modifiers::NONE), pointer("ruler"), "on an end without Alt");
|
||||
assert_eq!(ruler.cursor_at(line.end, egui::Modifiers::SHIFT), pointer("ruler"), "on an end with Shift");
|
||||
assert_eq!(ruler.cursor_at(line.end, alt), pointer("protractor"), "on the end with Alt");
|
||||
assert_eq!(ruler.cursor_at(line.start, alt), pointer("protractor"), "on the start with Alt");
|
||||
assert_eq!(ruler.cursor_at(middle, alt), pointer("ruler"), "on the line with Alt");
|
||||
|
||||
let mut with_arm = shown(Some(protractor(middle)));
|
||||
let line = protractor(middle);
|
||||
assert_eq!(with_arm.cursor_at(line.start, alt), pointer("ruler"), "a protractor's vertex moves the whole ruler, Alt or not");
|
||||
assert_eq!(with_arm.cursor_at(line.end, alt), pointer("protractor"), "its far end starts a new arm with Alt");
|
||||
|
||||
let ctx = ruler.fixture.fixture().ctx().clone();
|
||||
craft_ui::runtime::windows::WindowHost::of(&ctx).set_caps_lock(Some(true));
|
||||
let line = plain(middle);
|
||||
for (at, mods) in [(middle + kurbo::Vec2::new(0.0, 40.0), egui::Modifiers::NONE), (line.end, alt)] {
|
||||
assert_eq!(ruler.cursor_at(at, mods), Some(Cursor::System(craft_behavior::CursorIcon::Crosshair)), "precise: the crosshair");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ruler drawn under another tool: the line and the crosses paint, and a press on an end reaches the tool.
|
||||
#[trial]
|
||||
fn a_read_only_ruler_paints_and_takes_no_press() {
|
||||
let line = Rc::new(RefCell::new(None::<RulerLine>));
|
||||
let drawn = Rc::new(std::cell::Cell::new(None::<RulerLine>));
|
||||
let (tool_line, body_drawn) = (Rc::clone(&line), Rc::clone(&drawn));
|
||||
let driven = Driven { tool: RulerTool::new(), line: tool_line, log: Rc::new(RefCell::new(Vec::new())) };
|
||||
let mut fixture = ToolFixture::with_view(
|
||||
"Ruler",
|
||||
driven,
|
||||
|room| CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0),
|
||||
move |ui, body| {
|
||||
if let Some(shown) = body_drawn.get() {
|
||||
craft_draw::ui::measure::show_ruler(ui, body.rect, shown);
|
||||
}
|
||||
},
|
||||
);
|
||||
let rect = fixture.canvas().rect;
|
||||
let middle = Point::new(f64::from(rect.width()) / 2.0, f64::from(rect.height()) / 2.0);
|
||||
let screen = |p: Point| rect.center() + egui::vec2(p.x as f32 - rect.width() / 2.0, p.y as f32 - rect.height() / 2.0);
|
||||
let ruler = protractor(middle);
|
||||
drawn.set(Some(ruler));
|
||||
fixture.fixture().frame(Vec::new());
|
||||
let end = screen(ruler.end);
|
||||
let shapes = fixture.fixture().frame_shapes();
|
||||
let paths =
|
||||
|test: &dyn Fn(&[egui::Pos2]) -> bool| shapes.iter().filter(|shape| matches!(shape, egui::Shape::Path(path) if test(&path.points))).count();
|
||||
let close = |a: egui::Pos2, b: egui::Pos2| (a - b).length() < 0.5;
|
||||
assert!(
|
||||
paths(&|points: &[egui::Pos2]| points.iter().any(|p| close(*p, screen(ruler.start))) && points.iter().any(|p| close(*p, end))) > 0,
|
||||
"the line paints"
|
||||
);
|
||||
assert!(paths(&|points: &[egui::Pos2]| points.len() == 2 && close(points[0].lerp(points[1], 0.5), end)) >= 2, "the cross at the end paints");
|
||||
|
||||
fixture.press_at(end).release_at(end);
|
||||
let started = (*line.borrow()).is_none();
|
||||
assert!(started, "a click on the drawn end reaches the tool, whose click leaves no line: {:?}", line.borrow());
|
||||
let to = end + egui::vec2(40.0, 0.0);
|
||||
fixture.press_at(end).move_to(end + egui::vec2(20.0, 0.0)).move_to(to).release_at(to);
|
||||
let new = (*line.borrow()).expect("the tool drew a line");
|
||||
assert!(new.start.distance(ruler.end) < 1e-3, "the tool's new line starts at the press on the drawn end: {new:?}");
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use craft_ui::canvas::{Canvas, ToolHost};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, Vec2};
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2};
|
||||
|
||||
const SIZE: Size = Size::new(400.0, 300.0);
|
||||
const SHIFT: Modifiers = Modifiers { shift: true, ..Modifiers::NONE };
|
||||
@@ -25,13 +25,16 @@ struct Rig {
|
||||
tool: Rc<RefCell<PerspectiveCropTool>>,
|
||||
/// The active document the pass is given; `None` keys nothing.
|
||||
document: Rc<Cell<Option<CropDocKey>>>,
|
||||
/// Whether the quad reported `apply` in any frame since the last [`Rig::applied`].
|
||||
apply: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new() -> Self {
|
||||
let tool = Rc::new(RefCell::new(PerspectiveCropTool::new()));
|
||||
let document = Rc::new(Cell::new(None));
|
||||
let (shown, active) = (Rc::clone(&tool), Rc::clone(&document));
|
||||
let apply = Rc::new(Cell::new(false));
|
||||
let (shown, active, applied) = (Rc::clone(&tool), Rc::clone(&document), Rc::clone(&apply));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut tool = shown.borrow_mut();
|
||||
let room = ui.available_rect_before_wrap();
|
||||
@@ -39,12 +42,13 @@ impl Rig {
|
||||
let input = PerspectiveInput { document: active.get(), ..Default::default() };
|
||||
let mut pass = tool.pass(input);
|
||||
let canvas = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| {
|
||||
let _ = pass.show_quad(ui, body.rect);
|
||||
let output = pass.show_quad(ui, body.rect);
|
||||
applied.set(applied.get() || output.apply);
|
||||
});
|
||||
let _ = ToolHost::new().run(ui, &canvas.output, &mut pass);
|
||||
});
|
||||
fixture.settle();
|
||||
Rig { fixture, tool, document }
|
||||
Rig { fixture, tool, document, apply }
|
||||
}
|
||||
|
||||
/// The screen point of document point `(x, y)`: the view shows (200, 150) at the canvas's centre.
|
||||
@@ -110,6 +114,15 @@ impl Rig {
|
||||
fn placing(&self) -> usize {
|
||||
self.tool.borrow().placing()
|
||||
}
|
||||
|
||||
/// Presses Enter and whether the quad applied.
|
||||
fn enter_applies(&mut self) -> bool {
|
||||
self.fixture.frame(Vec::new());
|
||||
self.apply.set(false);
|
||||
self.fixture.key(Key::Enter, Modifiers::NONE);
|
||||
self.fixture.frame(Vec::new());
|
||||
self.apply.take()
|
||||
}
|
||||
}
|
||||
|
||||
fn near(got: Option<[Point; 4]>, want: [(f64, f64); 4]) -> bool {
|
||||
@@ -197,8 +210,29 @@ fn perspective_box_and_corner_modifiers_and_clicks() {
|
||||
rig.drag((300.0, 220.0), (320.0, 230.0), ALT);
|
||||
assert!(near(rig.quad(), [(120.0, 80.0), (300.0, 80.0), (320.0, 230.0), (100.0, 220.0)]), "a skewed quad's corner moves alone: {:?}", rig.quad());
|
||||
rig.set(upright);
|
||||
rig.drag((300.0, 220.0), (50.0, 220.0), ALT);
|
||||
assert!(
|
||||
near(rig.quad(), [(100.0, 80.0), (50.0, 80.0), (50.0, 220.0), (100.0, 220.0)]),
|
||||
"Alt past the opposite corner along x keeps the corners as they lie, a mirrored box: {:?}",
|
||||
rig.quad()
|
||||
);
|
||||
assert!(rig.quad().is_some_and(|q| is_valid(&q)), "a mirrored box is valid");
|
||||
assert!(rig.enter_applies(), "Enter applies a mirrored box");
|
||||
rig.set(upright);
|
||||
rig.drag((300.0, 220.0), (50.0, 40.0), ALT);
|
||||
assert!(rig.quad().is_some_and(|q| is_valid(&q)), "Alt past the opposite corner stays a valid quad: {:?}", rig.quad());
|
||||
assert!(
|
||||
near(rig.quad(), [(100.0, 80.0), (50.0, 80.0), (50.0, 40.0), (100.0, 40.0)]),
|
||||
"Alt past the opposite corner on both axes keeps the corners as they lie, a box turned upside down: {:?}",
|
||||
rig.quad()
|
||||
);
|
||||
assert!(rig.enter_applies(), "Enter applies an upside-down box");
|
||||
// A bow-tie and a quad with three corners on a line are invalid in either winding and do not apply.
|
||||
for quad in [[(100.0, 80.0), (300.0, 220.0), (300.0, 80.0), (100.0, 220.0)], [(100.0, 80.0), (200.0, 80.0), (300.0, 80.0), (200.0, 220.0)]] {
|
||||
let points = quad.map(|(x, y)| Point::new(x, y));
|
||||
assert!(!is_valid(&points) && !is_valid(&[points[0], points[3], points[2], points[1]]), "{quad:?} is invalid");
|
||||
rig.set(quad);
|
||||
assert!(!rig.enter_applies(), "Enter does not apply {quad:?}");
|
||||
}
|
||||
|
||||
// A click on a corner with no drag changes nothing.
|
||||
rig.set(upright);
|
||||
|
||||
@@ -672,3 +672,67 @@ fn a_level_live_lines_ends_stand_for_the_sides() {
|
||||
fn kurbo_vec(x: f64, y: f64) -> craft_behavior::kurbo::Vec2 {
|
||||
craft_behavior::kurbo::Vec2::new(x, y)
|
||||
}
|
||||
|
||||
/// How far the box's first corner moved from where `RECT` puts it, in screen points (the view is upright at scale 1).
|
||||
fn moved_by(h: &Harness) -> Vec2 {
|
||||
let corner = h.state().quad[0];
|
||||
by((corner.x - RECT.x0) as f32, (corner.y - RECT.y0) as f32)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_box_moves_from_the_first_pointer_move_after_the_press_and_keeps_up_with_no_jump() {
|
||||
let mut h = upright();
|
||||
let slop = craft_ui::testing::input::slop(h.fixture.ctx());
|
||||
// Inside, away from the reference point at the box's centre.
|
||||
let from = h.screen(Point::new(150.0, 120.0));
|
||||
frame(&mut h, vec![pointer::moved(from)]);
|
||||
frame(&mut h, vec![pointer::press(from)]);
|
||||
frame(&mut h, Vec::new());
|
||||
assert!(h.host.borrow().events.is_empty(), "a press alone moves nothing: {:?}", h.host.borrow().events);
|
||||
// One step per frame, a third of the slop each, through the slop and past it.
|
||||
for step in 1..=9 {
|
||||
let offset = by(slop / 3.0 * step as f32, slop / 6.0 * step as f32);
|
||||
frame(&mut h, vec![pointer::moved(from + offset)]);
|
||||
assert!((moved_by(&h) - offset).length() < 1e-3, "step {step}: the box keeps the pointer's offset {offset:?}, moved {:?}", moved_by(&h));
|
||||
}
|
||||
let end = from + by(slop * 3.0, slop * 1.5);
|
||||
frame(&mut h, vec![pointer::release(end)]);
|
||||
frame(&mut h, Vec::new());
|
||||
let events = h.host.borrow().events.clone();
|
||||
assert_eq!(events.iter().filter(|seen| **seen == Seen::Begin).count(), 1, "one gesture: {events:?}");
|
||||
assert_eq!(events.iter().filter(|seen| **seen == Seen::Commit).count(), 1, "one commit: {events:?}");
|
||||
|
||||
// A move inside the slop and a release there still commit the move the user saw.
|
||||
let mut h = upright();
|
||||
let from = h.screen(Point::new(150.0, 120.0));
|
||||
frame(&mut h, vec![pointer::moved(from)]);
|
||||
frame(&mut h, vec![pointer::press(from)]);
|
||||
frame(&mut h, vec![pointer::moved(from + by(slop / 2.0, 0.0))]);
|
||||
frame(&mut h, vec![pointer::release(from + by(slop / 2.0, 0.0))]);
|
||||
frame(&mut h, Vec::new());
|
||||
assert!((moved_by(&h) - by(slop / 2.0, 0.0)).length() < 1e-3, "the box stays where it followed to: {:?}", moved_by(&h));
|
||||
assert_eq!(h.host.borrow().events.last(), Some(&Seen::Commit), "{:?}", h.host.borrow().events);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_click_on_the_box_moves_nothing_and_a_jittery_click_outside_applies_the_box_as_it_was() {
|
||||
let mut h = upright();
|
||||
let slop = craft_ui::testing::input::slop(h.fixture.ctx());
|
||||
let inside = h.screen(Point::new(150.0, 120.0));
|
||||
frame(&mut h, vec![pointer::moved(inside)]);
|
||||
frame(&mut h, vec![pointer::press(inside)]);
|
||||
frame(&mut h, vec![pointer::release(inside)]);
|
||||
frame(&mut h, Vec::new());
|
||||
assert!(h.host.borrow().events.is_empty(), "a click on the box proposes nothing: {:?}", h.host.borrow().events);
|
||||
assert_eq!(h.state(), BoxState::from_rect(RECT));
|
||||
|
||||
let outside = h.screen(Point::new(340.0, 260.0));
|
||||
frame(&mut h, vec![pointer::moved(outside)]);
|
||||
frame(&mut h, vec![pointer::press(outside)]);
|
||||
frame(&mut h, vec![pointer::moved(outside + by(slop / 2.0, slop / 3.0))]);
|
||||
frame(&mut h, vec![pointer::release(outside + by(slop / 2.0, slop / 3.0))]);
|
||||
frame(&mut h, Vec::new());
|
||||
assert!(h.host.borrow().events.is_empty(), "a jittery click outside turns nothing: {:?}", h.host.borrow().events);
|
||||
assert_eq!(h.state(), BoxState::from_rect(RECT), "the box stays as it was");
|
||||
assert_eq!(h.host.borrow().applied, 1, "the click outside applies");
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! only when its key changes (box, zoom, document revision, display key, texture level, filter).
|
||||
//! The composite is drawn over transparency with Normal blending, like the mesh it replaces.
|
||||
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_behavior::geometry::Homography;
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
@@ -23,7 +23,7 @@ use super::{PreviewDisplay, PreviewQuality, PreviewTextures};
|
||||
const COORD_LIMIT: f64 = 5.0e8;
|
||||
/// Rounds of shrinking the scale until the content fits the budget.
|
||||
const ROUNDS: u32 = 6;
|
||||
/// The salt of the styled composite's texture stores.
|
||||
/// The salt of the styled composites' texture stores: one per filter in a context, keyed by the preview's name.
|
||||
const STORE: &str = "craft_imaging.styled_preview";
|
||||
|
||||
/// How long a styled rebuild may take (LC25, LC26): the work pixels a composite may have are the
|
||||
@@ -316,14 +316,14 @@ struct StyledState {
|
||||
/// The styled composite of a session's moving layer, kept until its key changes. The app keeps one
|
||||
/// per session while the layer has a style.
|
||||
pub struct StyledPreview {
|
||||
name: String,
|
||||
name: Arc<str>,
|
||||
state: Mutex<StyledState>,
|
||||
}
|
||||
|
||||
impl StyledPreview {
|
||||
/// `name` keys the texture in egui.
|
||||
pub fn new(name: impl Into<String>) -> Self {
|
||||
Self { name: name.into(), state: Mutex::new(StyledState::default()) }
|
||||
Self { name: Arc::from(name.into()), state: Mutex::new(StyledState::default()) }
|
||||
}
|
||||
|
||||
/// How many times the composite was made: once per change of its key.
|
||||
@@ -332,10 +332,11 @@ impl StyledPreview {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner).builds
|
||||
}
|
||||
|
||||
/// The store of the composite's picture: one per filter, one entry each.
|
||||
fn store(&self, ctx: &Context, crisp: bool) -> TextureStore<()> {
|
||||
/// The store of the composites with `crisp`'s filter. Every preview of the context shares it, so a closed
|
||||
/// preview's composite is evicted when the store needs the room.
|
||||
fn store(ctx: &Context, crisp: bool) -> TextureStore<Arc<str>> {
|
||||
let filter = if crisp { TextureOptions::NEAREST } else { TextureOptions::LINEAR };
|
||||
TextureStore::in_context(ctx, (STORE, self.name.as_str(), crisp), TextureStoreOptions::frames().filter(filter))
|
||||
TextureStore::in_context(ctx, (STORE, crisp), TextureStoreOptions::frames().filter(filter))
|
||||
}
|
||||
|
||||
/// The composite for `frame` and the document rectangle it covers, compositing again through
|
||||
@@ -366,7 +367,7 @@ impl StyledPreview {
|
||||
};
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(shown) = state.shown.as_ref().filter(|s| s.key == key)
|
||||
&& let Some(texture) = self.store(ctx, shown.crisp).state(ctx, &(), shown.revision).shown()
|
||||
&& let Some(texture) = Self::store(ctx, shown.crisp).state(ctx, &self.name, shown.revision).shown()
|
||||
{
|
||||
return Some((texture.id, shown.rect));
|
||||
}
|
||||
@@ -388,8 +389,8 @@ impl StyledPreview {
|
||||
None => composed,
|
||||
};
|
||||
let revision = Revision::new(state.builds + 1);
|
||||
self.store(ctx, !crisp).forget(ctx, &());
|
||||
let texture = self.store(ctx, crisp).put(ctx, (), revision, pixels);
|
||||
Self::store(ctx, !crisp).forget(ctx, &self.name);
|
||||
let texture = Self::store(ctx, crisp).put(ctx, Arc::clone(&self.name), revision, pixels);
|
||||
let rect = plan.document_rect();
|
||||
state.failed = None;
|
||||
state.shown = Some(Shown { key, revision, crisp, rect });
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
//! [`PreviewPixels`] and [`PreviewTextures`]: the moving pixels of a transform, read once and
|
||||
//! uploaded as a mip chain built on demand.
|
||||
//! uploaded as a mip chain built on demand, off the UI thread where a finer level can stand in.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_ui::primitives::{Revision, TextureStore, TextureStoreOptions};
|
||||
use craft_host::queue::Cancel;
|
||||
use craft_ui::primitives::{
|
||||
LoadFailure, LoadResult, LoadedPicture, LoaderOptions, Priority, Revision, TextureLoader, TextureState, TextureStatistics, TextureStore, TextureStoreOptions,
|
||||
};
|
||||
use egui::{Color32, ColorImage, Context, TextureId, TextureOptions};
|
||||
|
||||
use super::PreviewQuality;
|
||||
|
||||
/// The salt of the preview's texture stores.
|
||||
/// The salt of the previews' texture stores and loader.
|
||||
const STORE: &str = "craft_imaging.transform_preview";
|
||||
|
||||
/// The app's pixels of the moving layer: premultiplied texels of which `base_uv` covers the
|
||||
@@ -106,15 +110,28 @@ pub struct TextureChoice {
|
||||
pub nearest: bool,
|
||||
}
|
||||
|
||||
/// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box
|
||||
/// filtered) and the nearest-filtered variants on first use. The CPU levels are kept for the
|
||||
/// session; the uploads live in the texture store under the preview's name (one entry per level
|
||||
/// and filter), and a new display key replaces them in place, so a profile change does not pile
|
||||
/// up textures. Two previews of one context must not share a name.
|
||||
/// The key of a preview's level in the shared stores: the preview's name and the level.
|
||||
type LevelKey = (Arc<str>, u32);
|
||||
|
||||
/// Tells previews apart in the store revisions: a preview made under an old name with new pixels gets a new serial.
|
||||
static SERIAL: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// The moving pixels uploaded for the preview: level 0 at once, the other mip levels (2 × 2 box filtered) and the
|
||||
/// nearest-filtered level 0 on first use. The CPU levels are kept for the session.
|
||||
///
|
||||
/// - **Stores.** Every preview of a context shares one store of linear levels and one of nearest ones, keyed by the
|
||||
/// preview's name and the level, so a closed preview's uploads are evicted under the stores' budget. Two previews
|
||||
/// painted at once must not share a name. The revision is the preview's own (new pixels under an old name replace
|
||||
/// the old textures in place) with the display key (a profile change replaces them in place too).
|
||||
/// - **Off the UI thread.** A level first needed while a finer level is uploaded for this preview and display is
|
||||
/// built (halved, converted, uploaded) by a job of the context's `TextureLoader`; the closest finer uploaded level
|
||||
/// shows until it lands. A level with nothing finer uploaded is built in the pass. A preview no longer painted for
|
||||
/// two frames drops its jobs and their results, as every loader key does.
|
||||
pub struct PreviewTextures {
|
||||
name: String,
|
||||
/// The CPU levels built so far, premultiplied; level 0 first.
|
||||
images: Mutex<Vec<Arc<ColorImage>>>,
|
||||
name: Arc<str>,
|
||||
serial: u64,
|
||||
/// The CPU levels built so far, premultiplied; level 0 first. Shared with the jobs that build levels.
|
||||
images: Arc<Mutex<Vec<Arc<ColorImage>>>>,
|
||||
base_uv: [f32; 2],
|
||||
}
|
||||
|
||||
@@ -123,13 +140,18 @@ impl PreviewTextures {
|
||||
/// uploaded until the preview is painted.
|
||||
pub fn new(name: impl Into<String>, pixels: PreviewPixels) -> Self {
|
||||
let base_uv = pixels.base_uv;
|
||||
Self { name: name.into(), images: Mutex::new(vec![Arc::new(pixels.image)]), base_uv }
|
||||
Self::over(name, vec![Arc::new(pixels.image)], base_uv)
|
||||
}
|
||||
|
||||
/// The preview over `levels` already built, level 0 first, covering the source with `base_uv`.
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub(crate) fn from_levels(name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
Self { name: name.into(), images: Mutex::new(levels), base_uv }
|
||||
Self::over(name, levels, base_uv)
|
||||
}
|
||||
|
||||
fn over(name: impl Into<String>, levels: Vec<Arc<ColorImage>>, base_uv: [f32; 2]) -> Self {
|
||||
let serial = SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||
Self { name: Arc::from(name.into()), serial, images: Arc::new(Mutex::new(levels)), base_uv }
|
||||
}
|
||||
|
||||
/// How many mip levels are built so far (level 0 counts): levels are built when asked for.
|
||||
@@ -142,6 +164,11 @@ impl PreviewTextures {
|
||||
self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |image| image.size)
|
||||
}
|
||||
|
||||
/// What the store of every preview's linear levels in `ctx` holds and uploaded this frame.
|
||||
pub fn statistics(ctx: &Context) -> TextureStatistics {
|
||||
linear_store(ctx).statistics(ctx)
|
||||
}
|
||||
|
||||
/// The level and filter for a source pixel shown at `zoom` screen pixels per document pixel,
|
||||
/// where the transform scales it by `scale` (PhotoCraft's rule, LC24): with `nearest`
|
||||
/// interpolation always level 0 nearest (point sampling; a mip level would blur pixel art);
|
||||
@@ -164,41 +191,116 @@ impl PreviewTextures {
|
||||
TextureChoice { level: 0, nearest: zoom >= PreviewQuality::CRISP_ZOOM && scale <= PreviewQuality::CRISP_SCALE }
|
||||
}
|
||||
|
||||
/// The texture and its uv extent for [`choose`](Self::choose)'s answer, uploading that level
|
||||
/// and filter on first use; with `display`, the converted upload (the CPU level stays raw).
|
||||
/// Each pass asks again: a store hit costs a lookup.
|
||||
/// The texture and its uv extent for [`choose`](Self::choose)'s answer; with `display`, the converted upload (the
|
||||
/// CPU level stays raw). Level 0, its nearest variant and a level with nothing finer uploaded for this display are
|
||||
/// uploaded in the pass on first use; any other level is built by a job while the closest finer uploaded level
|
||||
/// stands in. Each pass asks again: a store hit costs a lookup.
|
||||
pub fn pick(&self, ctx: &Context, choice: TextureChoice, display: Option<&PreviewDisplay>) -> Option<(TextureId, [f32; 2])> {
|
||||
let (image, uv) = self.level_image(choice.level)?;
|
||||
let options = if choice.nearest { TextureOptions::NEAREST } else { TextureOptions::LINEAR };
|
||||
let store = TextureStore::<u32>::in_context(ctx, (STORE, self.name.as_str(), choice.nearest), TextureStoreOptions::pages().filter(options));
|
||||
let revision = Revision::of(&display.map_or(0, |d| d.key));
|
||||
let texture = store.get_or_put(ctx, choice.level, revision, || match display {
|
||||
Some(d) => (d.convert)(&image),
|
||||
None => ColorImage::clone(&image),
|
||||
let revision = Revision::of(&(self.serial, display.map_or(0, |d| d.key)));
|
||||
let key = |level: u32| (Arc::clone(&self.name), level);
|
||||
let (level, uv) = self.extent(choice.level)?;
|
||||
if choice.nearest || level == 0 {
|
||||
let store = if choice.nearest { nearest_store(ctx) } else { linear_store(ctx) };
|
||||
let texture = store.get_or_put(ctx, key(level), revision, || self.shown(level, display));
|
||||
return Some((texture.id, uv));
|
||||
}
|
||||
let loader = TextureLoader::<LevelKey>::in_context(ctx, STORE, LoaderOptions::new().store(TextureStoreOptions::pages()).lanes(2));
|
||||
let store = loader.cache();
|
||||
// The level itself, else the closest finer level uploaded for this display.
|
||||
let shown = (0..=level).rev().find_map(|at| match store.state(ctx, &key(at), revision) {
|
||||
TextureState::Ready(texture) => Some((at, texture)),
|
||||
_ => None,
|
||||
});
|
||||
let texture = match shown {
|
||||
Some((at, texture)) if at == level => texture,
|
||||
Some((finer, stand_in)) => {
|
||||
let job = || {
|
||||
let (images, convert) = (Arc::clone(&self.images), display.map(|d| Arc::clone(&d.convert)));
|
||||
move |_: &Cancel| -> LoadResult {
|
||||
let image = level_of(&images, level).map(|(image, _)| image).ok_or(LoadFailure::Missing)?;
|
||||
Ok(LoadedPicture::Image(converted(&image, convert.as_deref())))
|
||||
}
|
||||
};
|
||||
match loader.request(ctx, &key(level), revision, Priority::VISIBLE, job) {
|
||||
TextureState::Ready(texture) => texture,
|
||||
_ => return Some((stand_in.id, self.extent(finer)?.1)),
|
||||
}
|
||||
}
|
||||
None => store.get_or_put(ctx, key(level), revision, || self.shown(level, display)),
|
||||
};
|
||||
Some((texture.id, uv))
|
||||
}
|
||||
|
||||
/// Level `level` built in the pass, converted for `display`.
|
||||
fn shown(&self, level: u32, display: Option<&PreviewDisplay>) -> ColorImage {
|
||||
match self.level_image(level) {
|
||||
Some((image, _)) => converted(&image, display.map(|d| &*d.convert)),
|
||||
None => ColorImage::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Level `n` of the mip chain (built on demand, at most down to one texel) and its uv extent
|
||||
/// covering the source. The styled preview resamples from it.
|
||||
pub fn level_image(&self, n: u32) -> Option<(Arc<ColorImage>, [f32; 2])> {
|
||||
let mut images = self.images.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
while images.len() <= n as usize {
|
||||
let previous = images.last()?;
|
||||
if previous.size[0] <= 1 && previous.size[1] <= 1 {
|
||||
break;
|
||||
}
|
||||
let next = Arc::new(halve(previous));
|
||||
images.push(next);
|
||||
let (image, level) = level_of(&self.images, n)?;
|
||||
Some((image, self.extent(level)?.1))
|
||||
}
|
||||
|
||||
/// The level the chain gives for `n` (the last one when it ends at one texel above `n`) and its uv extent
|
||||
/// covering the source, from level 0's size alone.
|
||||
fn extent(&self, n: u32) -> Option<(u32, [f32; 2])> {
|
||||
let base = self.images.lock().unwrap_or_else(PoisonError::into_inner).first()?.size;
|
||||
let (mut size, mut level) = (base, 0);
|
||||
while level < n && (size[0] > 1 || size[1] > 1) {
|
||||
size = [size[0].div_ceil(2).max(1), size[1].div_ceil(2).max(1)];
|
||||
level += 1;
|
||||
}
|
||||
let level = (images.len() - 1).min(n as usize);
|
||||
let image = Arc::clone(images.get(level)?);
|
||||
let base = images.first()?.size;
|
||||
// Level k covers size × 2^k base texels; the last row or column may be padding.
|
||||
let factor = (1u64 << level) as f32;
|
||||
let uv = |axis: usize| (self.base_uv[axis] * base[axis] as f32 / (image.size[axis] as f32 * factor).max(1.0)).min(1.0);
|
||||
let uv = [uv(0), uv(1)];
|
||||
Some((image, uv))
|
||||
let uv = |axis: usize| (self.base_uv[axis] * base[axis] as f32 / (size[axis] as f32 * factor).max(1.0)).min(1.0);
|
||||
Some((level, [uv(0), uv(1)]))
|
||||
}
|
||||
}
|
||||
|
||||
/// The store of every preview's linear levels in `ctx`: the loader's.
|
||||
fn linear_store(ctx: &Context) -> TextureStore<LevelKey> {
|
||||
TextureStore::in_context(ctx, STORE, TextureStoreOptions::pages())
|
||||
}
|
||||
|
||||
/// The store of every preview's nearest-filtered level 0 in `ctx`.
|
||||
fn nearest_store(ctx: &Context) -> TextureStore<LevelKey> {
|
||||
TextureStore::in_context(ctx, (STORE, "nearest"), TextureStoreOptions::pages().filter(TextureOptions::NEAREST))
|
||||
}
|
||||
|
||||
/// `image` converted by `convert`, or as it is.
|
||||
fn converted(image: &ColorImage, convert: Option<&(dyn Fn(&ColorImage) -> ColorImage + Send + Sync)>) -> ColorImage {
|
||||
match convert {
|
||||
Some(convert) => convert(image),
|
||||
None => image.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Level `n` of the chain in `images` and its index (the last level when the chain ends at one texel above `n`),
|
||||
/// built on demand. The halving runs with the lock released, so a job building a level never holds up the pass;
|
||||
/// when two callers build the same level, the first one's stays.
|
||||
fn level_of(images: &Mutex<Vec<Arc<ColorImage>>>, n: u32) -> Option<(Arc<ColorImage>, u32)> {
|
||||
let lock = || images.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
loop {
|
||||
let (previous, built) = {
|
||||
let images = lock();
|
||||
if let Some(image) = images.get(n as usize) {
|
||||
return Some((Arc::clone(image), n));
|
||||
}
|
||||
(Arc::clone(images.last()?), images.len())
|
||||
};
|
||||
if previous.size[0] <= 1 && previous.size[1] <= 1 {
|
||||
return Some((previous, (built - 1) as u32));
|
||||
}
|
||||
let next = Arc::new(halve(&previous));
|
||||
let mut images = lock();
|
||||
if images.len() == built {
|
||||
images.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_host::{AppInfo, Host, ManualJobs};
|
||||
use craft_imaging::fold_order::cell_order;
|
||||
use craft_imaging::ui::transform_preview::{
|
||||
PreviewDisplay, PreviewMap, PreviewPixels, PreviewTextures, StylePlan, StyledBudget, StyledContent, StyledFrame, StyledPreview, StyledSource,
|
||||
@@ -12,7 +14,7 @@ use craft_imaging::ui::transform_preview::{
|
||||
};
|
||||
use craft_imaging::ui::warp::WarpMesh;
|
||||
use craft_ui::canvas::{Canvas, PixelRect};
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Lazy, Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Color32, ColorImage, Shape};
|
||||
|
||||
@@ -354,7 +356,225 @@ fn the_styled_frame_is_rebuilt_only_when_its_key_changes() {
|
||||
expect_build(&nearest, &source, Some(&display), "filter");
|
||||
}
|
||||
|
||||
/// Previews made one after another, as Free Transform sessions are, each composited in its own frame and then
|
||||
/// closed: the context keeps fewer composites than there were previews, since the closed ones are evicted when the
|
||||
/// store needs the room.
|
||||
#[trial]
|
||||
fn closed_styled_previews_leave_their_composites_to_eviction() {
|
||||
const PREVIEWS: usize = 600;
|
||||
let (mut fixture, ctx) = context();
|
||||
let (textures, source) = (styled_textures(), Fake::new(2));
|
||||
let allocated = || ctx.tex_manager().read().num_allocated();
|
||||
let before = allocated();
|
||||
for n in 0..PREVIEWS {
|
||||
let preview = StyledPreview::new(format!("session-{n}"));
|
||||
assert!(preview.composite(&ctx, &frame(&textures, square(10.0, 10.0, 8.0), 1.0), &source, None).is_some());
|
||||
fixture.idle(1);
|
||||
}
|
||||
let kept = allocated() - before;
|
||||
assert!(kept < PREVIEWS, "{kept} composites kept for {PREVIEWS} closed previews");
|
||||
}
|
||||
|
||||
// The budget is 30 ms dragging and 120 ms at rest over the cost per pixel plus the resample's, clamped to 0.25 to 8
|
||||
// million pixels.
|
||||
|
||||
// With nearest interpolation every zoom and scale gives level 0 with nearest filtering.
|
||||
|
||||
/// Previews painted every frame of a fixture whose host runs jobs only when a trial says (upstream's 5 × 3 white
|
||||
/// image).
|
||||
struct Mips {
|
||||
fixture: Fixture,
|
||||
jobs: Arc<ManualJobs>,
|
||||
/// The previews the next frames paint, each at its scale.
|
||||
painted: Rc<RefCell<Vec<(Rc<PreviewTextures>, f32)>>>,
|
||||
/// The display every painted preview is converted for.
|
||||
display: Rc<RefCell<Option<PreviewDisplay>>>,
|
||||
/// What each painted preview showed in the last frame.
|
||||
shown: Rc<RefCell<Vec<Option<(egui::TextureId, [f32; 2])>>>>,
|
||||
/// The previews' uploads in the last frame, read in the frame.
|
||||
uploads: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
fn white(name: &str) -> Rc<PreviewTextures> {
|
||||
Rc::new(PreviewTextures::new(name, PreviewPixels::new(solid([5, 3], Color32::WHITE), [1.0, 1.0])))
|
||||
}
|
||||
|
||||
impl Mips {
|
||||
fn new() -> Self {
|
||||
Self::with(false)
|
||||
}
|
||||
|
||||
/// The previews painted inside a settling region (`Lazy::settles`), which replays its last run while nothing the
|
||||
/// framework tracks changed for it.
|
||||
fn settling() -> Self {
|
||||
Self::with(true)
|
||||
}
|
||||
|
||||
fn with(settles: bool) -> Self {
|
||||
let jobs = Arc::new(ManualJobs::new());
|
||||
let painted = Rc::new(RefCell::new(Vec::<(Rc<PreviewTextures>, f32)>::new()));
|
||||
let display = Rc::new(RefCell::new(None::<PreviewDisplay>));
|
||||
let shown = Rc::new(RefCell::new(Vec::new()));
|
||||
let uploads = Rc::new(Cell::new(0));
|
||||
let (paint, converted, seen, counted) = (Rc::clone(&painted), Rc::clone(&display), Rc::clone(&shown), Rc::clone(&uploads));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let run = |ui: &mut egui::Ui| {
|
||||
let display = converted.borrow();
|
||||
let picks = paint
|
||||
.borrow()
|
||||
.iter()
|
||||
.map(|(textures, scale)| textures.pick(ui.ctx(), PreviewTextures::choose(1.0, *scale, false), display.as_ref()))
|
||||
.collect();
|
||||
*seen.borrow_mut() = picks;
|
||||
};
|
||||
if settles {
|
||||
Lazy::new("previews", 0.0).settles(true).show(ui, run);
|
||||
} else {
|
||||
run(ui);
|
||||
}
|
||||
counted.set(PreviewTextures::statistics(ui.ctx()).uploads);
|
||||
});
|
||||
fixture.host(Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs.clone()).build()));
|
||||
fixture.settle();
|
||||
Mips { fixture, jobs, painted, display, shown, uploads }
|
||||
}
|
||||
|
||||
/// One frame painting `previews`.
|
||||
/// A change of the previews or their scales arrives with input, as a drag's does.
|
||||
fn paint(&mut self, previews: &[(&Rc<PreviewTextures>, f32)]) {
|
||||
let next: Vec<_> = previews.iter().map(|(textures, scale)| (Rc::clone(textures), *scale)).collect();
|
||||
let changed = {
|
||||
let painted = self.painted.borrow();
|
||||
painted.len() != next.len() || painted.iter().zip(&next).any(|(a, b)| !Rc::ptr_eq(&a.0, &b.0) || a.1 != b.1)
|
||||
};
|
||||
*self.painted.borrow_mut() = next;
|
||||
self.fixture.frame(if changed { vec![egui::Event::WindowFocused(true)] } else { Vec::new() });
|
||||
}
|
||||
|
||||
/// The texture and uv extent the `at`th preview showed.
|
||||
fn shown(&self, at: usize) -> (egui::TextureId, [f32; 2]) {
|
||||
self.shown.borrow()[at].expect("a texture")
|
||||
}
|
||||
|
||||
fn uploads(&self) -> usize {
|
||||
self.uploads.get()
|
||||
}
|
||||
}
|
||||
|
||||
fn near_uv(uv: [f32; 2], want: [f32; 2]) -> bool {
|
||||
(uv[0] - want[0]).abs() < 1e-6 && (uv[1] - want[1]).abs() < 1e-6
|
||||
}
|
||||
|
||||
/// P91 (#13382): the frame that first needs a mip level builds none on the UI thread; level 0 stands in, the frames
|
||||
/// while its job waits do no work for it, and the landing frame uploads it once. In a settling region the frame
|
||||
/// after the job lands runs the region again with no other input and shows the level.
|
||||
#[trial]
|
||||
fn a_mip_level_first_needed_mid_drag_is_built_off_the_ui_thread() {
|
||||
for settles in [false, true] {
|
||||
mips_first_needed_mid_drag(if settles { Mips::settling() } else { Mips::new() });
|
||||
}
|
||||
}
|
||||
|
||||
fn mips_first_needed_mid_drag(mut mips: Mips) {
|
||||
let t = white("drag");
|
||||
mips.paint(&[(&t, 1.0)]);
|
||||
let (level0, _) = mips.shown(0);
|
||||
let built = t.levels_built();
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!(mips.shown(0).0, level0, "level 0 stands in");
|
||||
assert_eq!(t.levels_built(), built, "the frame built no level");
|
||||
assert_eq!(mips.jobs.waiting(), 1, "one job builds level 1");
|
||||
for _ in 0..3 {
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!(mips.jobs.waiting(), 1, "a frame while the job waits queues no second one");
|
||||
assert_eq!(t.levels_built(), built, "and builds no level");
|
||||
assert_eq!(mips.uploads(), 0, "and uploads nothing");
|
||||
}
|
||||
mips.jobs.run_all();
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
let (level1, uv) = mips.shown(0);
|
||||
assert_ne!(level1, level0, "level 1 has its own texture");
|
||||
assert!(near_uv(uv, [5.0 / 6.0, 3.0 / 4.0]), "level 1's extent: {uv:?}");
|
||||
assert_eq!(mips.uploads(), 1, "the landing frame uploads one texture");
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!((mips.shown(0).0, mips.uploads()), (level1, 0), "a later frame uploads nothing");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_closest_finer_level_stands_in_while_a_level_builds() {
|
||||
let mut mips = Mips::new();
|
||||
let t = white("finer");
|
||||
mips.paint(&[(&t, 1.0)]);
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
mips.jobs.run_all();
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
let level1 = mips.shown(0);
|
||||
mips.paint(&[(&t, 0.1)]);
|
||||
assert_eq!(mips.shown(0), level1, "level 1 stands in for level 3");
|
||||
mips.jobs.run_all();
|
||||
mips.paint(&[(&t, 0.1)]);
|
||||
let (level3, uv) = mips.shown(0);
|
||||
assert_ne!(level3, level1.0);
|
||||
assert!(near_uv(uv, [5.0 / 8.0, 3.0 / 8.0]), "level 3's extent: {uv:?}");
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() {
|
||||
let mut mips = Mips::new();
|
||||
let t = white("at-once");
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!(mips.jobs.waiting(), 0, "a first frame at level 1 builds it in the frame");
|
||||
assert!(near_uv(mips.shown(0).1, [5.0 / 6.0, 3.0 / 4.0]), "level 1 shows at once");
|
||||
mips.paint(&[(&t, 1.0)]);
|
||||
*mips.display.borrow_mut() = Some(PreviewDisplay::new(7, ColorImage::clone));
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
assert_eq!(mips.jobs.waiting(), 0, "nothing is uploaded for the new display, so level 1 is built in the frame");
|
||||
assert!(near_uv(mips.shown(0).1, [5.0 / 6.0, 3.0 / 4.0]));
|
||||
}
|
||||
|
||||
/// A preview closed while its level builds neither uploads the level nor keeps it; one still painted does.
|
||||
#[trial]
|
||||
fn levels_finishing_after_the_box_closed_are_not_uploaded_and_while_it_is_open_are() {
|
||||
let mut entries = Vec::new();
|
||||
for open in [false, true] {
|
||||
let mut mips = Mips::new();
|
||||
let (t, other) = (white("closing"), white("other"));
|
||||
mips.paint(&[(&t, 1.0)]);
|
||||
mips.paint(&[(&t, 0.3)]);
|
||||
for _ in 0..2 {
|
||||
if open { mips.paint(&[(&t, 0.3)]) } else { mips.paint(&[]) }
|
||||
}
|
||||
mips.jobs.run_all();
|
||||
// The other preview's second frame asks the loader, which stores or drops the finished level.
|
||||
for scale in [1.0, 0.3] {
|
||||
let mut previews = vec![(&other, scale)];
|
||||
if open {
|
||||
previews.push((&t, 0.3));
|
||||
}
|
||||
mips.paint(&previews);
|
||||
}
|
||||
entries.push(PreviewTextures::statistics(mips.fixture.ctx()).entries);
|
||||
}
|
||||
assert_eq!(entries[1], entries[0] + 1, "only the open preview's level is uploaded: {entries:?}");
|
||||
}
|
||||
|
||||
/// A new preview under an old name with other pixels shows its own pixels, not the old textures.
|
||||
#[trial]
|
||||
fn a_new_preview_under_the_same_name_shows_its_own_pixels() {
|
||||
let ctx = egui::Context::default();
|
||||
let uploaded = |id: egui::TextureId| {
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
let texel = delta.set.get(&id).and_then(|sets| sets.first()).map(|set| match &set.image {
|
||||
egui::ImageData::Color(image) => image.pixels[0],
|
||||
});
|
||||
delta.clear();
|
||||
texel
|
||||
};
|
||||
let first = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::WHITE), [1.0, 1.0]));
|
||||
let (id, _) = first.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded");
|
||||
assert_eq!(uploaded(id), Some(Color32::WHITE));
|
||||
drop(first);
|
||||
let second = PreviewTextures::new("same", PreviewPixels::new(solid([2, 2], Color32::BLACK), [1.0, 1.0]));
|
||||
let (id, _) = second.pick(&ctx, TextureChoice::new(0, false), None).expect("uploaded");
|
||||
assert_eq!(uploaded(id), Some(Color32::BLACK), "the new pixels go up");
|
||||
}
|
||||
|
||||
@@ -1256,3 +1256,63 @@ fn the_tool_and_the_canvas_controls_read_one_precise_cursor_from_the_canvas() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool that asks for a readout, or a hud, on every drag step.
|
||||
struct Measuring {
|
||||
hud: bool,
|
||||
}
|
||||
|
||||
impl CanvasTool for Measuring {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
let rows = vec![(craft_ui::runtime::env::Label::from("W"), "123 px".to_owned())];
|
||||
if self.hud { cx.hud(rows) } else { cx.readout(rows) }
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Measure command")
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds a drag of a `Measuring` tool under Show Transformation Values `shown`: whether the value painted and whether
|
||||
/// the host reported the rows.
|
||||
fn readout_during_a_drag(hud: bool, shown: Option<bool>) -> (bool, bool) {
|
||||
let reported = Rc::new(Cell::new(false));
|
||||
let seen = Rc::clone(&reported);
|
||||
let tool = RefCell::new(Measuring { hud });
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(CanvasView::new(room, Point::new(600.0, 450.0), 0.5)).show(ui, |_, _| {});
|
||||
let reply = ToolHost::new().run(ui, &shown.output, &mut *tool.borrow_mut());
|
||||
seen.set(reply.readout.is_some_and(|readout| readout.rows.iter().any(|(_, value)| value == "123 px")));
|
||||
});
|
||||
if let Some(shown) = shown {
|
||||
fixture.root_value(craft_ui::canvas::ShowReadouts(shown));
|
||||
}
|
||||
fixture.settle();
|
||||
let centre = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").center();
|
||||
// The last frame is a move, so the tool's drag asks for its rows in the frame the texts are read from.
|
||||
fixture.frame(vec![pointer::moved(centre)]);
|
||||
fixture.frame(vec![pointer::press(centre)]);
|
||||
for step in 1..=4 {
|
||||
fixture.frame(vec![pointer::moved(centre + BY * (step as f32 / 4.0))]);
|
||||
}
|
||||
let painted = fixture.texts().iter().any(|run| run.text.contains("123 px"));
|
||||
(painted, reported.get())
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn show_transformation_values_gates_the_readouts_paint_and_never_the_hud() {
|
||||
assert_eq!(readout_during_a_drag(false, None), (true, true), "by default a tool's readout paints and is reported");
|
||||
assert_eq!(readout_during_a_drag(false, Some(false)), (false, true), "Show Transformation Values off: nothing paints, the rows are still reported");
|
||||
assert_eq!(readout_during_a_drag(true, Some(false)), (true, true), "a hud paints with Show Transformation Values off");
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::store::{Revision, TextureKey, TextureState, TextureStore, TextureStor
|
||||
use super::words::TextureWords;
|
||||
use crate::runtime::egui::{memory, pass, repaint};
|
||||
use crate::runtime::env::Env;
|
||||
use crate::runtime::replay;
|
||||
use craft_host::queue::{Cancel, JobQueue, QueueOptions};
|
||||
use craft_host::{Jobs, Wake, default_jobs};
|
||||
use egui::{Color32, ColorImage, Context};
|
||||
@@ -154,12 +155,15 @@ impl<K> Default for Pools<K> {
|
||||
/// default). The rest wait for later frames and the loader asks for the next pass at once. A result for a
|
||||
/// revision other than the one last asked for is discarded; a `LoadedPicture::Blank` answer is stored with
|
||||
/// `TextureStore::put_empty` and a failure with `TextureStore::put_failure`.
|
||||
/// - **Dropping.** In that first call, keys nobody asked for in this frame or the previous one are dropped from the
|
||||
/// queue: rows scrolled away, a panel closed. A frame that does not draw the list asks for nothing, so its jobs
|
||||
/// - **Dropping.** In that first call, keys nobody asked for in this frame or the previous one are dropped in every
|
||||
/// state of their job: queued jobs leave the queue, running ones are cancelled and finished results are discarded
|
||||
/// unstored: rows scrolled away, a panel closed. A frame that does not draw the list asks for nothing, so its jobs
|
||||
/// are dropped at the next frame that draws. Asked keys move to the priority they were last asked with.
|
||||
/// - **Failures.** A job returns a `LoadFailure`; the state carries it. A job that panics is stored as
|
||||
/// `LoadFailure::Panicked`.
|
||||
/// - **Waking.** The queue asks for a pass when a job finishes; no timed repaint.
|
||||
/// - **Waking.** The queue asks for a pass when a job finishes; no timed repaint. A `Loading` answer notes the
|
||||
/// asking code as still moving (`runtime::replay`), so a settled region that shows a stand-in runs in that pass,
|
||||
/// asks again and shows the finished picture, and its asking keeps the job.
|
||||
/// - **Without lanes** (`lanes == 0`) the first call in a frame runs one job inline.
|
||||
pub struct TextureLoader<K: TextureKey> {
|
||||
store: TextureStore<K>,
|
||||
@@ -233,6 +237,7 @@ impl<K: TextureKey> TextureLoader<K> {
|
||||
asked.frame = frame;
|
||||
Some(())
|
||||
})?;
|
||||
replay::note_unsettled(ctx);
|
||||
Some(TextureState::Loading { stand_in: state.shown() })
|
||||
}
|
||||
|
||||
@@ -262,6 +267,7 @@ impl<K: TextureKey> TextureLoader<K> {
|
||||
// The job runs in the next frame's `run_frame_work`; the web repaints only on input.
|
||||
repaint::request(ctx);
|
||||
}
|
||||
replay::note_unsettled(ctx);
|
||||
TextureState::Loading { stand_in }
|
||||
}
|
||||
|
||||
@@ -280,9 +286,9 @@ impl<K: TextureKey> TextureLoader<K> {
|
||||
})
|
||||
}
|
||||
|
||||
/// In the first call of a frame, runs the frame's work: an inline job when there are no lanes, dropping jobs
|
||||
/// nobody asked for, then storing finished results while the store's upload allowance lasts. A result for
|
||||
/// another revision than the one last asked for is discarded.
|
||||
/// In the first call of a frame, runs the frame's work: an inline job when there are no lanes, dropping the jobs
|
||||
/// and results of keys nobody asked for, then storing finished results while the store's upload allowance lasts.
|
||||
/// A result for another revision than the one last asked for is discarded.
|
||||
fn run_frame_work(&self, ctx: &Context) {
|
||||
let frame = pass::root_frame_nr(ctx);
|
||||
let first = self.with(ctx, |pool| pool.polled.replace(frame) != Some(frame));
|
||||
@@ -295,9 +301,9 @@ impl<K: TextureKey> TextureLoader<K> {
|
||||
let batch = self.with(ctx, |pool| {
|
||||
let recent = frame.saturating_sub(1);
|
||||
let asked = &mut pool.asked;
|
||||
for key in pool.queue.reprioritize(|key, _| asked.get(key).filter(|asked| asked.frame >= recent).map(|asked| asked.priority)) {
|
||||
asked.remove(&key);
|
||||
}
|
||||
pool.queue.reprioritize(|key, _| asked.get(key).filter(|asked| asked.frame >= recent).map(|asked| asked.priority));
|
||||
// A key nobody asked for recently loses its record, so its finished result is discarded below too.
|
||||
asked.retain(|_, asked| asked.frame >= recent);
|
||||
while let Some(finished) = pool.queue.try_recv() {
|
||||
let (revision, result) = finished.result;
|
||||
pool.waiting.push((finished.key, revision, result));
|
||||
|
||||
@@ -248,7 +248,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) {
|
||||
/// also needs the child at the `place` it ran at, which a measuring run cannot tell.
|
||||
///
|
||||
/// It replays when its last run was in an earlier frame and since then:
|
||||
/// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no wake time reached;
|
||||
/// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still
|
||||
/// loading, no wake time reached;
|
||||
/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and
|
||||
/// none of that held in its last run;
|
||||
/// - none of its stops holds focus or is the target of a focus request, now or in its last run;
|
||||
|
||||
@@ -413,6 +413,20 @@ pub(crate) fn part_bounds(ctx: &Context, owner: Id, part: craft_behavior::PartRe
|
||||
owned_part_bounds(ctx, |shape_owner| shape_owner == owner, part)
|
||||
}
|
||||
|
||||
/// Whether the part `part` of `owner` (the arena root or a member) senses all of `sense` in last pass's shape record.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn part_senses(ctx: &Context, owner: Id, part: craft_behavior::PartRef, sense: craft_behavior::Sense) -> bool {
|
||||
let viewport = pass::current_viewport(ctx);
|
||||
PerViewport::<Shapes>::with(ctx, viewport, |record| {
|
||||
record
|
||||
.last
|
||||
.values()
|
||||
.flat_map(|roots| roots.values())
|
||||
.flat_map(|root| root.shapes.iter())
|
||||
.any(|shape| shape.owner == owner && shape.part == Some(part) && shape.sense.contains(sense))
|
||||
})
|
||||
}
|
||||
|
||||
/// [`part_bounds`] of the owner whose AccessKit node is `node`, for a test that holds the node it found, not the id.
|
||||
#[cfg(feature = "testing")]
|
||||
pub(crate) fn node_part_bounds(ctx: &Context, node: crate::runtime::egui::access::NodeId, part: craft_behavior::PartRef) -> Option<egui::Rect> {
|
||||
|
||||
@@ -294,6 +294,13 @@ impl Fixture {
|
||||
self.set_root(|root| root.scale = scale)
|
||||
}
|
||||
|
||||
/// Sets the root app value of type `T` for every following frame, as an app's `FrameInput.root.values` does.
|
||||
pub fn root_value<T: crate::runtime::env::EnvValue>(&mut self, value: T) -> &mut Self {
|
||||
self.set_root(|root| {
|
||||
root.values.set(value);
|
||||
})
|
||||
}
|
||||
|
||||
/// The host every following frame is given: its language, catalogs and services.
|
||||
pub fn host(&mut self, host: std::sync::Arc<craft_host::Host>) -> &mut Self {
|
||||
self.frames.host(host);
|
||||
|
||||
@@ -27,7 +27,8 @@ fn gesture(fixture: &mut Fixture, target: &Target, by: f32) {
|
||||
}
|
||||
|
||||
/// A release within slop of a press on a clicking component is one click. A press that moves past slop starts one
|
||||
/// drag on a component that drags and is no click on one that does not. The slop is the runtime's: it installs the
|
||||
/// drag on a component that drags and is no click on one that does not. A drag part that senses `SETS_ON_PRESS` or
|
||||
/// `FOLLOWS_IN_SLOP` begins one gesture within slop too, ended by a Commit. The slop is the runtime's: it installs the
|
||||
/// theme's `size.hit.slop` as egui's click distance.
|
||||
fn slop_separates_click_from_drag(subject: &Subject) -> Result<(), String> {
|
||||
let probe = subject.probe;
|
||||
@@ -50,11 +51,11 @@ fn slop_separates_click_from_drag(subject: &Subject) -> Result<(), String> {
|
||||
}
|
||||
}
|
||||
Plan::Drag(Grip { part, .. }) if probe.carries_value() => {
|
||||
// A part whose press sets the value begins its gesture at the press, within slop or not.
|
||||
let on_press = fixture
|
||||
.root_id()
|
||||
.is_some_and(|id| crate::runtime::pointer::sensing_parts(fixture.ctx(), id, Sense::SETS_ON_PRESS).contains(&part));
|
||||
for (by, begins) in [(0.5 * slop, usize::from(on_press)), (2.0 * slop, 1)] {
|
||||
// A part whose press sets the value begins its gesture at the press, and one that follows within slop at
|
||||
// the first move: either begins within slop.
|
||||
let senses = |sense: Sense| fixture.root_id().is_some_and(|id| crate::runtime::pointer::part_senses(fixture.ctx(), id, part, sense));
|
||||
let within = senses(Sense::SETS_ON_PRESS) || senses(Sense::FOLLOWS_IN_SLOP);
|
||||
for (by, begins) in [(0.5 * slop, usize::from(within)), (2.0 * slop, 1)] {
|
||||
let mut fixture = input_fixture(story);
|
||||
let Some(grip) = fixture.root_id().and_then(|id| fixture.part(id, part)) else { continue };
|
||||
fixture.take_outputs();
|
||||
@@ -67,8 +68,8 @@ fn slop_separates_click_from_drag(subject: &Subject) -> Result<(), String> {
|
||||
story.name
|
||||
));
|
||||
}
|
||||
if on_press && by < slop && kinds.last() != Some(&EditKind::Commit) {
|
||||
return Err(format!("{}: a press within slop that sets the value ended {kinds:?}, not with a Commit", story.name));
|
||||
if within && by < slop && kinds.last() != Some(&EditKind::Commit) {
|
||||
return Err(format!("{}: a press within slop that begins a gesture ended {kinds:?}, not with a Commit", story.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +89,41 @@ fn frame(frames: &mut Frames, run: impl FnOnce()) {
|
||||
});
|
||||
}
|
||||
|
||||
/// A job that finishes after its key went unasked for two frames is discarded like a queued one; asked in the frame
|
||||
/// before, its result is stored.
|
||||
#[trial]
|
||||
fn a_result_finishing_while_its_key_goes_unasked_is_not_stored() {
|
||||
for asked_again in [false, true] {
|
||||
let mut frames = Frames::new();
|
||||
let ctx = frames.ctx.clone();
|
||||
let (loader, jobs) = loader_with(&ctx, 1, 16);
|
||||
let runs = Arc::new(AtomicUsize::new(0));
|
||||
frame(&mut frames, || {
|
||||
loader.request(&ctx, &1, Revision::new(1), Priority::VISIBLE, || counted(&runs, SMALL));
|
||||
});
|
||||
frame(&mut frames, || {
|
||||
if asked_again {
|
||||
loader.ask(&ctx, &1, Revision::new(1), Priority::VISIBLE);
|
||||
}
|
||||
loader.request(&ctx, &2, Revision::new(1), Priority::VISIBLE, || counted(&runs, SMALL));
|
||||
});
|
||||
jobs.run_all();
|
||||
assert_eq!(runs.load(Ordering::Relaxed), 2, "both jobs ran");
|
||||
let (first, second) = (Cell::new(TextureState::Missing), Cell::new(TextureState::Missing));
|
||||
frame(&mut frames, || {
|
||||
second.set(loader.ask(&ctx, &2, Revision::new(1), Priority::VISIBLE).expect("settled"));
|
||||
first.set(loader.cache().state(&ctx, &1, Revision::new(1)));
|
||||
});
|
||||
assert!(ready(&second.into_inner()), "the asked key's result is stored");
|
||||
let first = first.into_inner();
|
||||
if asked_again {
|
||||
assert!(ready(&first), "asked in the frame before, the result is stored: {first:?}");
|
||||
} else {
|
||||
assert!(matches!(first, TextureState::Missing), "unasked for two frames, the result is dropped: {first:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_result_of_an_older_revision_is_discarded() {
|
||||
let mut frames = Frames::new();
|
||||
|
||||
+1
-1
@@ -115,7 +115,7 @@ Read-only text the user can select and copy is a selection part: `parts` declare
|
||||
|
||||
### Values
|
||||
|
||||
A value component's `Output` is `EditResponse<T>`. It binds with `Bind<T>` and reports through `cx.propose`, `cx.commit` and `cx.adopt`; each gesture ends in one `EditEvent::Commit`. A part whose press sets the value under the pointer (a colour field, a point on a well) senses `Sense::SETS_ON_PRESS` and runs its gesture with `cx.follow_press`. Components with `Input::Editor` own their caret through `ImeSurface`.
|
||||
A value component's `Output` is `EditResponse<T>`. It binds with `Bind<T>` and reports through `cx.propose`, `cx.commit` and `cx.adopt`; each gesture ends in one `EditEvent::Commit`. A part whose press sets the value under the pointer (a colour field, a point on a well) senses `Sense::SETS_ON_PRESS` and runs its gesture with `cx.follow_press`. A drag part that begins at the first move inside slop, so the value follows the pointer with no jump (a transform box's handles), senses `Sense::FOLLOWS_IN_SLOP` and begins its gesture from `PressPhase::Held`. Components with `Input::Editor` own their caret through `ImeSurface`.
|
||||
|
||||
## Looks
|
||||
|
||||
|
||||
Reference in New Issue
Block a user