diff --git a/Cargo.lock b/Cargo.lock index c2ff2081e6..85b87db49c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1870,6 +1870,7 @@ dependencies = [ "craft-metafile", "craft-midi", "craft-mime", + "craft-nightly", "craft-odf", "craft-ods", "craft-offcrypto", @@ -3504,6 +3505,13 @@ dependencies = [ "proptest", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-odf" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 015b02802b..817f5c1065 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -183,6 +183,7 @@ craft-media-testkit = { path = "crates/media-testkit" } craft-midi = { path = "crates/midi" } craft-sf2 = { path = "crates/sf2" } craft-mime = { path = "crates/mime" } +craft-nightly = { path = "crates/nightly" } craft-odf = { path = "crates/odf" } craft-ods = { path = "crates/ods" } craft-prc = { path = "crates/prc" } diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index c64efa2fbd..99281664b3 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -55,6 +55,11 @@ bitflags! { /// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`, /// without `DRAG`. const PASSES_DRAG = 131072; + /// The vertical wheel share, taken only while the component holds key focus or a press armed it, in any wheel + /// scope: a control whose wheel steps what focus picks rather than what the pointer is over (the focused thumb + /// of a range). Every other wheel bit the shape senses waits for focus with it. A control that senses no wheel + /// bit takes no wheel at all, so the wheel over it scrolls the region around it. + const WHEEL_Y_FOCUSED = 262144; } } @@ -63,7 +68,12 @@ impl Sense { pub const PRESS: Sense = Sense::CLICK.union(Sense::DRAG); /// The bits that make a shape register a wheel taker. - pub const WHEELS: Sense = Sense::WHEEL.union(Sense::WHEEL_X).union(Sense::WHEEL_Y).union(Sense::WHEEL_ZOOM).union(Sense::WHEEL_ZOOMS_VIEW); + pub const WHEELS: Sense = Sense::WHEEL + .union(Sense::WHEEL_X) + .union(Sense::WHEEL_Y) + .union(Sense::WHEEL_ZOOM) + .union(Sense::WHEEL_ZOOMS_VIEW) + .union(Sense::WHEEL_Y_FOCUSED); /// Whether a press can start on a shape with this sense. pub const fn takes_press(self) -> bool { diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 2e860a6d26..a5de8554a7 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -455,14 +455,17 @@ impl WheelTaker { /// The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll /// axes and zoom; `WHEEL_X`, `WHEEL_Y` and `WHEEL_ZOOM` take one share each and combine; `WHEEL_ZOOMS_VIEW` - /// makes a zoom zone. + /// makes a zoom zone; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes + /// waits for focus or arming. pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option { let all = sense.contains(Sense::WHEEL); + let focused = sense.contains(Sense::WHEEL_Y_FOCUSED); let taker = WheelTaker::new(owner, rect) .horizontal(all || sense.contains(Sense::WHEEL_X)) - .vertical(all || sense.contains(Sense::WHEEL_Y)) + .vertical(all || focused || sense.contains(Sense::WHEEL_Y)) .zoom(all || sense.contains(Sense::WHEEL_ZOOM)) - .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)); + .zooms_view(sense.contains(Sense::WHEEL_ZOOMS_VIEW)) + .gated(focused); (taker.horizontal || taker.vertical || taker.zoom || taker.zooms_view).then_some(taker) } diff --git a/crates/color-ui/src/ui/eyedropper.rs b/crates/color-ui/src/ui/eyedropper.rs index 4e17c7b572..0f9d0e508a 100644 --- a/crates/color-ui/src/ui/eyedropper.rs +++ b/crates/color-ui/src/ui/eyedropper.rs @@ -260,6 +260,16 @@ pub struct EyedropperPick { pub background: bool, } +/// The sampling ring while the button is held: its centre on screen and the sampled colour it shows. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct EyedropperRing { + /// The pointer at the sample, on screen. + pub center: Pos2, + /// The sampled colour: the upper half of the ring. + pub color: Srgba, +} + /// The pipette icon's tip, in the icon's own 24-unit box. pub(super) const HOTSPOT: [f32; 2] = [2.0, 22.0]; /// The ring's outer radius in points. @@ -274,7 +284,7 @@ const RING_SEGMENTS: usize = 48; pub struct EyedropperTool<'a> { options: EyedropperOptions, sample: Box Option + 'a>, - held: Option<(Pos2, Srgba)>, + held: Option, picked: Option, foreground: Srgba, } @@ -293,6 +303,19 @@ impl<'a> EyedropperTool<'a> { self } + /// The ring a previous tool held: an app that builds the tool anew each pass hands back what + /// [`ring`](Self::ring) gave the last pass, so a pass with no pointer input still paints the ring. + #[must_use] + pub fn held(mut self, ring: Option) -> Self { + self.held = ring; + self + } + + /// The ring while the button is held over the document; `None` once it is up or the gesture is cancelled. + pub fn ring(&self) -> Option { + self.held + } + /// The newest pick, once. pub fn take(&mut self) -> Option { self.picked.take() @@ -303,7 +326,7 @@ impl<'a> EyedropperTool<'a> { let Point { x, y } = space.view.to_doc(pointer.pos); match (self.sample)([x, y], self.options.size, self.options.source) { Some(color) => { - self.held = Some((pointer.pos, color)); + self.held = Some(EyedropperRing { center: pointer.pos, color }); self.picked = Some(EyedropperPick { color, background: pointer.mods.alt }); } None => self.held = None, @@ -351,7 +374,7 @@ impl CanvasTool for EyedropperTool<'_> { } fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) { - let (true, Some((center, new)), Some(style)) = (self.options.show_ring, self.held, cx.style()) else { return }; + let (true, Some(EyedropperRing { center, color: new }), Some(style)) = (self.options.show_ring, self.held, cx.style()) else { return }; let tokens = style.tokens; let inner = RING_OUTER_RADIUS - 2.0 * RING_BAND; band(draw, center, (inner, inner + RING_BAND), (PI, TAU), new); diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index eb39564058..e0fb35b3e2 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -56,7 +56,7 @@ pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle}; pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscHit, DiscLook, DiscMove, DiscRadius, patch_at}; pub use droppers::{DropperButton, DropperButtonOutput, DropperKind, DropperMode, DropperTool}; pub use eyedropper::{ - EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperTool, EyedropperWords, SampleSize, SampleSource, + EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperRing, EyedropperTool, EyedropperWords, SampleSize, SampleSource, }; pub use harmony::{ GuideCell, GuideCellAt, HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked, diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 5504a5a901..e916f66603 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -6,7 +6,7 @@ use craft_ui::buttons::IconButton; use craft_ui::choice::{ChoiceWords, Swatch, SwatchMetrics, SwatchStyle}; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, DragPreview, DropMark, DropOperation, DropTarget, Edit as _, EditResponse, Focus as _, MeasureCx, - Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Meta as _, Name, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth, WellFill}; use craft_ui::runtime::commands::FireSource; @@ -571,8 +571,11 @@ impl Component for SwatchPair<'_, P> { Some(paint) => paint_value(&cx.words::(), paint), None => cx.words::().swatch_mixed.as_str().to_owned(), }; - // The two wells are a choice of the active colour: radios, the front one checked, with the colour as value. - access.node(WELL.at(i as u64), Role::RADIO_BUTTON).value(value); + // The two wells are a choice of the active colour: radios, the front one checked, with the colour as value, + // each named by its own label ("Fill", "Stroke"), not the pair's. + let node = access.node(WELL.at(i as u64), Role::RADIO_BUTTON); + node.name = Name::Text(cx.env.resolve(&well.label).as_str().to_owned()); + node.value(value); } } diff --git a/crates/color-ui/tests/it/pair.rs b/crates/color-ui/tests/it/pair.rs index a53fa2d925..21f5942f44 100644 --- a/crates/color-ui/tests/it/pair.rs +++ b/crates/color-ui/tests/it/pair.rs @@ -203,3 +203,20 @@ fn the_host_activates_the_other_well_while_one_keeps_the_focus_and_an_arrow_acti fixture.key(Key::ArrowRight, Modifiers::NONE).key(Key::ArrowLeft, Modifiers::NONE).settle(); assert_eq!(active.get(), Well::Primary, "the arrow onto Fill makes it active"); } + +/// Each well is named by its own label, not the pair's: a screen reader, and a test, tells the two apart. +#[trial] +fn each_well_is_named_by_its_own_label() { + let mut fixture = Fixture::new(|ui| { + let wells = [PairWell::new("Fill", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Stroke", Srgba::rgb(1.0, 1.0, 1.0))]; + SwatchPair::<()>::new("Fill and Stroke", wells, Bind::given(Well::Primary)).popover(false).show(ui); + }); + fixture.room(vec2(200.0, 200.0)).settle(); + let wells = fixture.by_role(Role::RADIO_BUTTON); + let names: Vec> = wells.iter().map(|well| fixture.tree().name_of(well.node)).collect(); + assert_eq!(names, vec![Some("Fill"), Some("Stroke")], "the two wells are radio buttons named by their own labels, the primary first"); + let fill = fixture.by_label("Fill").expect("a node is named Fill"); + let stroke = fixture.by_label("Stroke").expect("a node is named Stroke"); + assert_eq!(fill.node, wells[0].node, "Fill names the primary well's radio button"); + assert_eq!(stroke.node, wells[1].node, "Stroke names the secondary well's radio button"); +} diff --git a/crates/color-ui/tests/it/sampling.rs b/crates/color-ui/tests/it/sampling.rs index e1a674dbd6..c0faf158a0 100644 --- a/crates/color-ui/tests/it/sampling.rs +++ b/crates/color-ui/tests/it/sampling.rs @@ -9,7 +9,8 @@ use craft_behavior::kurbo::Point; use craft_cms::convert::CmykConverter; use craft_color_ui::ui::{ CaptureResult, CaptureSource, ColorPicker, ColorPickerLayout, ColorSamplerPass, ColorSamplerTool, ColorSamplers, DropperMode, DropperTool, - MAX_SAMPLERS, PickedColor, SamplerCache, SamplerEvent, SamplerReadouts, ScreenColorPicker, ScreenPick, ScreenPickerWords, StillCapture, + EyedropperOptions, EyedropperTool, MAX_SAMPLERS, PickedColor, SamplerCache, SamplerEvent, SamplerReadouts, ScreenColorPicker, ScreenPick, + ScreenPickerWords, StillCapture, }; use craft_theme::Srgba; use craft_ui::contract::Bind; @@ -75,6 +76,25 @@ fn events(tool: &ToolFixture>) -> Vec { tool.tool_mut().take_events() } +#[trial] +fn the_held_sampling_ring_carries_over_to_the_next_pass_tool() { + // An app whose sample closure borrows its state builds the tool anew each pass: the ring the press held must reach + // the next pass's tool, which gets no pointer input to sample again, or the ring flickers (photocraft#17931). + let red = Srgba::rgb(1.0, 0.0, 0.0); + let tool = EyedropperTool::new(EyedropperOptions::default(), move |_, _, _| Some(red)); + let mut tool = ToolFixture::with_view("Eyedropper", tool, sampler_view, |_, _| {}); + tool.fixture().room(vec2(800.0, 600.0)); + tool.fixture().settle(); + let at = tool.canvas().rect.min + vec2(40.0, 30.0); + tool.press_at(at); + let ring = tool.tool().ring().expect("the held button shows the ring"); + assert_eq!((ring.center, ring.color), (at, red)); + let next = EyedropperTool::new(EyedropperOptions::default(), |_, _, _| None).held(Some(ring)); + assert_eq!(next.ring(), Some(ring)); + tool.release_at(at); + assert_eq!(tool.tool().ring(), None, "the release ends the ring"); +} + #[trial] fn a_new_point_lands_at_the_release_and_a_dragged_point_moves_on_release() { // A new point: nothing at the press, an Add at the release; off the canvas or on Escape, nothing. diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index bca67fb734..994f26396f 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -119,6 +119,7 @@ craft-metadata = { workspace = true, optional = true } craft-metafile = { workspace = true, optional = true } craft-midi = { workspace = true, optional = true } craft-mime = { workspace = true, optional = true } +craft-nightly = { workspace = true, optional = true } craft-odf = { workspace = true, optional = true } craft-ods = { workspace = true, optional = true } craft-offcrypto = { workspace = true, optional = true } @@ -690,6 +691,8 @@ midi-serde = ["midi", "craft-midi/serde"] mime = ["dep:craft-mime"] mime-detect = ["mime", "craft-mime/detect"] +nightly = ["dep:craft-nightly"] + odf = ["dep:craft-odf"] odf-text = ["odf", "craft-odf/text"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 60863cda9a..ed6ccb2f84 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -261,6 +261,8 @@ pub use craft_metafile as metafile; pub use craft_midi as midi; #[cfg(feature = "mime")] pub use craft_mime as mime; +#[cfg(feature = "nightly")] +pub use craft_nightly as nightly; #[cfg(feature = "odf")] pub use craft_odf as odf; #[cfg(feature = "ods")] diff --git a/crates/draw/src/ui/brush_presets/picker.rs b/crates/draw/src/ui/brush_presets/picker.rs index 43d612ec1c..dbcbc769fb 100644 --- a/crates/draw/src/ui/brush_presets/picker.rs +++ b/crates/draw/src/ui/brush_presets/picker.rs @@ -20,6 +20,7 @@ use craft_ui::patterns::presets::{ use craft_ui::primitives::{FacePaint, IconSpec}; use craft_ui::runtime::env::{Env, Label, UnitKind}; use craft_ui::runtime::overlay::CloseReason; +use craft_ui::text::RangeAlert; use egui::{Pos2, Response, Ui}; use super::panel::{BRUSH_THUMBS, picks_of}; @@ -156,6 +157,9 @@ pub struct BrushPresetPickerOutput { pub hardness: EditEvents, /// The angle widget: the new angle and roundness. pub tip: EditEvents, + /// A value typed into Size or Hardness outside its range and clamped, in the pass it committed; never for a drag or + /// a step. The host shows the range alert; the picker stays open. + pub out_of_range: Option, /// Escape closed the picker: the values to set back, each the one it had when the picker opened (or a preset /// picked since brought) while it still holds the value the picker's head last set; a value changed from /// elsewhere since keeps that change. `None` when nothing goes back. @@ -355,13 +359,14 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> { let next_search = Cell::new(before.search); let tool_picks: RefCell>> = RefCell::new(Vec::new()); let (mut diameter, mut hardness, mut tip) = (EditEvents::new(), EditEvents::new(), EditEvents::new()); + let mut out_of_range = None; let browser_id = ui.scope_id().with("browser"); let head = |ui: &mut Ui, _: &mut BodyCx<'_>| { let mut sent = Vec::new(); let props = HeadProps { values, max_diameter, sent: Outbox::new(&mut sent) }; let _ = MemoView::new("head", props, head_view).show(ui); for edits in sent { - (diameter, hardness, tip) = (edits.diameter, edits.hardness, edits.tip); + (diameter, hardness, tip, out_of_range) = (edits.diameter, edits.hardness, edits.tip, edits.out_of_range); } if let Some(rows) = app_rows.take() { rows(ui); @@ -431,6 +436,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> { diameter, hardness, tip, + out_of_range, reverted, open: out.open, picks, @@ -445,6 +451,7 @@ impl<'a, K: Value + Eq + Hash + MemoProps> BrushPresetPicker<'a, K> { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new(), + out_of_range: None, reverted: None, open: false, picks: Vec::new(), @@ -462,11 +469,12 @@ struct HeadProps<'a> { sent: Outbox<'a, HeadEdits>, } -/// What a run of the head reports: the Size, Hardness and angle widget edits. +/// What a run of the head reports: the Size, Hardness and angle widget edits, and a value typed out of range. struct HeadEdits { diameter: EditEvents, hardness: EditEvents, tip: EditEvents, + out_of_range: Option, } /// The head: the angle widget, Size and Hardness, then a divider. A memoized view, so a drag of its Size runs it @@ -474,17 +482,20 @@ struct HeadEdits { fn head_view(props: &mut HeadProps<'_>, ui: &mut Ui) { let words = Env::of(ui).words::(); let (values, max_diameter) = (props.values, props.max_diameter); - let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new() }; + let mut edits = HeadEdits { diameter: EditEvents::new(), hardness: EditEvents::new(), tip: EditEvents::new(), out_of_range: None }; Row::new().show(ui, |ui, _| { if let Some(angle) = values.tip { edits.tip = TipEllipse::new(words.tip.clone(), Bind::given(angle)).show(ui).events; } Stack::new().show(ui, |ui, _| { - edits.diameter = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui).edit.events; + let size = BrushSizeField::new(words.size.clone(), Bind::given(values.diameter), max_diameter).show(ui); + edits.diameter = size.edit.events; + edits.out_of_range = size.out_of_range; if let Some(value) = values.hardness { let field = SliderField::new(words.hardness.clone(), Bind::given(value * 100.0), 0.0..=100.0).step(1.0).unit_kind(UnitKind::Percent).show(ui); edits.hardness = field.edit.events.map(|percent| (percent / 100.0).clamp(0.0, 1.0)); + edits.out_of_range = field.out_of_range.or(edits.out_of_range.take()); } }); }); diff --git a/crates/draw/src/ui/brush_settings/size_field.rs b/crates/draw/src/ui/brush_settings/size_field.rs index aec36f81ae..63c7d41d13 100644 --- a/crates/draw/src/ui/brush_settings/size_field.rs +++ b/crates/draw/src/ui/brush_settings/size_field.rs @@ -3,6 +3,7 @@ use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, Show as _}; use craft_ui::form::SliderField; use craft_ui::runtime::env::{Label, UnitKind}; +use craft_ui::text::RangeAlert; use craft_ui::value_drag::SliderScale; use egui::{Response, Ui}; @@ -15,6 +16,9 @@ pub struct BrushSizeOutput { pub response: Response, /// The slider field's edit. pub edit: EditResponse, + /// A value typed into the field outside 1 to the maximum and clamped, in the pass it committed; never for a slider + /// drag or a step. The host shows the range alert. + pub out_of_range: Option, } impl Outcome for BrushSizeOutput { @@ -62,13 +66,8 @@ impl<'a> BrushSizeField<'a> { Some(original) => diameter.reset(original.clamp(1.0, max)), None => diameter, }; - let edit = SliderField::new(label, diameter, 1.0..=max) - .scale(SliderScale::Log) - .step(1.0) - .unit_kind(UnitKind::Pixels) - .enabled(max > 1.0) - .show(ui) - .edit; - BrushSizeOutput { response: edit.response.clone(), edit } + let shown = + SliderField::new(label, diameter, 1.0..=max).scale(SliderScale::Log).step(1.0).unit_kind(UnitKind::Pixels).enabled(max > 1.0).show(ui); + BrushSizeOutput { response: shown.edit.response.clone(), edit: shown.edit, out_of_range: shown.out_of_range } } } diff --git a/crates/draw/src/ui/crop/perspective_tool.rs b/crates/draw/src/ui/crop/perspective_tool.rs index 4e425b41b3..b5c095234d 100644 --- a/crates/draw/src/ui/crop/perspective_tool.rs +++ b/crates/draw/src/ui/crop/perspective_tool.rs @@ -5,7 +5,7 @@ use std::sync::Arc; -use craft_behavior::geometry::Constraint; +use craft_behavior::geometry::{Constraint, SnapKind, SnapKinds}; use craft_behavior::kurbo::Point; use craft_behavior::{CancelReason, Cursor, CursorIcon, EditEvent, GestureId, IconId, Mixed, PaintedCursor, PointerGlyph}; use craft_theme::variant::Tone; @@ -130,6 +130,27 @@ 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)]) } +/// Where a box drag pressed at `press` starts. While the canvas snaps to the document bounds +/// ([`ToolContext::snaps_to_document_bounds`]), a press beyond a document corner (outside on both axes) starts at that +/// corner, and one within the snap distance of an edge starts on the nearest edge ([`ToolContext::snap_of`]). Any other +/// press, and every press on a document whose size is negative or not finite, starts where it was. Clicked corners +/// don't come here: they keep their place. +fn drag_start(press: Point, cx: &ToolContext<'_>) -> Point { + let size = cx.space().and_then(|space| space.document()); + // A size that is negative or not finite has no bounds to start on (and would make `clamp` panic): no snap at all. + if size.is_some_and(|size| !(size.width.is_finite() && size.height.is_finite() && size.width >= 0.0 && size.height >= 0.0)) { + return press; + } + if let Some(size) = size + && cx.snaps_to_document_bounds() + && !(0.0..=size.width).contains(&press.x) + && !(0.0..=size.height).contains(&press.y) + { + return Point::new(press.x.clamp(0.0, size.width), press.y.clamp(0.0, size.height)); + } + cx.snap_of(press, SnapKinds::only(SnapKind::Bounds)) +} + /// What the host hands the perspective crop pass each frame. #[derive(Clone, Copy, Debug, Default)] #[non_exhaustive] @@ -206,7 +227,8 @@ impl CanvasTool for PerspectiveCropPass<'_> { self.tool.events.push(PerspectiveCropEvent::Edit(EditEvent::begin(press.id, Mixed::Same(press.before), label, None))); } if press.began { - let (a, b) = Constraint::Free.corners(press.anchor, space.view.to_doc(pointer.pos), pointer.mods.shift, pointer.mods.alt); + // The snapped start shapes the box from its first move, so the drag shows where its release puts it. + let (a, b) = Constraint::Free.corners(drag_start(press.anchor, cx), space.view.to_doc(pointer.pos), pointer.mods.shift, pointer.mods.alt); self.tool.quad = boxed(a, b); if self.tool.quad.is_some() { // A drag that makes no box keeps the corners clicked so far. diff --git a/crates/draw/tests/it/brush_presets.rs b/crates/draw/tests/it/brush_presets.rs index cbcbfe7b0b..dba1cdf527 100644 --- a/crates/draw/tests/it/brush_presets.rs +++ b/crates/draw/tests/it/brush_presets.rs @@ -1,6 +1,6 @@ //! The Brush Preset picker: Rename Brush… in the gear opens the browser's name field on the current preset; the app //! opens the picker at a point without its field; a resized picker keeps its size; the head edits angle and -//! roundness; Escape reverts the head's edits. +//! roundness; Escape reverts the head's edits; a Size or Hardness typed out of range reports the range alert. use craft_draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushPickerState, BrushPickerValues, BrushPresetPicker, BrushRowPaint, brush_row}; use craft_draw::ui::brush_settings::TipAngle; @@ -10,6 +10,7 @@ use craft_ui::primitives::FacePaint; use craft_ui::runtime::env::Env; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use craft_ui::text::RangeAlert; use egui::{Key, Modifiers, Pos2, Rect, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -74,6 +75,8 @@ struct Opened { at: Option, /// The space above the field. offset: f32, + /// The range alerts the passes reported. + alerts: Vec, } const POINT: Pos2 = Pos2::new(160.0, 120.0); @@ -91,11 +94,12 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc>) tip_edits: 0, at, offset: 0.0, + alerts: Vec::new(), })); let shown = Rc::clone(&host); let mut fixture = Fixture::new(move |ui| { let mut host = shown.borrow_mut(); - let Opened { current, state, values, open, tip_edits, at, offset } = &mut *host; + let Opened { current, state, values, open, tip_edits, at, offset, alerts } = &mut *host; ui.add_space(*offset); let rows = PresetSource::new(state.parts, PresetFns::new(two_rows)); let mut picker = BrushPresetPicker::new("Brush Preset picker", Bind::bound(current), &rows, Bind::bound(state), *values); @@ -116,6 +120,7 @@ fn opened_rig(at_point: bool, remember: bool) -> (Fixture, Rc>) values.tip = Some(*tip); } *tip_edits += out.tip.len(); + alerts.extend(out.out_of_range); if let Some(back) = out.reverted { *values = back; } @@ -226,6 +231,50 @@ fn escape_reverts_size_hardness_angle_and_roundness() { assert_eq!(host.borrow().values, OPENED, "Escape puts all four back"); } +/// Types `text` into the head's number field named `label` and commits it with Enter. +fn type_into(fixture: &mut Fixture, label: &str, text: &str) { + let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|target| fixture.tree().name_of(target.node) == Some(label)); + let field = field.unwrap_or_else(|| panic!("the {label} field shows")); + fixture.click(&field); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.type_text(text); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.idle(3); +} + +/// Size and Hardness typed past their ranges keep the closest value and report the range alert once each, with the +/// picker still open; a typed value in range and a slider press report none. +#[trial] +fn size_and_hardness_typed_out_of_range_report_the_range_alert() { + let (mut fixture, host) = opened_rig(true, false); + type_into(&mut fixture, "Size", "9999"); + { + let host = host.borrow(); + assert_eq!(host.values.diameter, 5000.0, "Size keeps the largest diameter"); + let [alert] = host.alerts.as_slice() else { panic!("one alert for Size: {:?}", host.alerts) }; + assert_eq!((alert.typed, alert.kept, alert.range.clone()), (9999.0, 5000.0, 1.0..=5000.0)); + assert!(host.open, "the picker stays open"); + } + type_into(&mut fixture, "Size", "0"); + assert_eq!(host.borrow().values.diameter, 1.0, "Size keeps the smallest diameter"); + assert_eq!(host.borrow().alerts.len(), 2, "a typed 0 is out of range too"); + type_into(&mut fixture, "Hardness", "150"); + { + let host = host.borrow(); + assert_eq!(host.values.hardness, Some(1.0), "Hardness keeps 100 %"); + let alert = host.alerts.last().expect("an alert for Hardness"); + assert_eq!((host.alerts.len(), alert.typed, alert.kept, alert.range.clone()), (3, 150.0, 100.0, 0.0..=100.0)); + } + type_into(&mut fixture, "Size", "40"); + let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Hardness")); + let slider = slider.expect("the Hardness slider shows").rect; + fixture.click_at(slider.left_center() + Vec2::new(slider.width() * 0.8, 0.0)); + fixture.idle(3); + let host = host.borrow(); + assert_eq!(host.values.diameter, 40.0); + assert_eq!(host.alerts.len(), 3, "a value in range and a slider press alert nothing: {:?}", host.alerts); +} + /// The memoized views of `props` that ran in the last frame. fn views_ran(fixture: &Fixture, props: &str) -> usize { last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count() diff --git a/crates/draw/tests/it/perspective_crop.rs b/crates/draw/tests/it/perspective_crop.rs index 57f95daba2..c2f6ddbaab 100644 --- a/crates/draw/tests/it/perspective_crop.rs +++ b/crates/draw/tests/it/perspective_crop.rs @@ -3,14 +3,15 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; use craft_behavior::CanvasView; -use craft_behavior::geometry::Constraint; +use craft_behavior::geometry::{Constraint, SnapOptions, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect, Size}; use craft_draw::ui::crop::{ CropDocKey, PerspectiveCropEvent, PerspectiveCropQuad, PerspectiveCropTool, PerspectiveInput, grid_lines, grid_steps, is_valid, }; -use craft_ui::canvas::{Canvas, ToolHost, tool_pass}; +use craft_ui::canvas::{Canvas, Snap, ToolHost, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::runtime::access::Role; use craft_ui::testing::{Fixture, trial}; @@ -62,6 +63,17 @@ struct Rig { impl Rig { fn new() -> Self { + Self::snapping(None) + } + + /// A rig whose canvas snaps with `options` to its document's bounds (the targets an app builds for View > Snap To), + /// in a room with a pasteboard of 100 points around the document. + fn snapping(options: Option) -> Self { + let snap = options.map(|options| { + let bounds = DocRect::from_origin_size(Point::ZERO, SIZE); + Snap::new(Arc::new(SnapTargets::new().with_document(&options, bounds, std::iter::empty(), None)), options) + }); + let pasteboard = snap.is_some(); let tool = Rc::new(RefCell::new(PerspectiveCropTool::new())); let document = Rc::new(Cell::new(None)); let apply = Rc::new(Cell::new(false)); @@ -72,7 +84,11 @@ impl Rig { let view = CanvasView::new(room, Point::new(200.0, 150.0), 1.0); let input = PerspectiveInput { document: active.get(), ..Default::default() }; let mut pass = tool.pass(input); - let _ = Canvas::new("Document").document(SIZE).view(view).show(ui, |ui, body| { + let mut canvas = Canvas::new("Document").document(SIZE).view(view); + if let Some(snap) = snap.clone() { + canvas = canvas.snap(snap); + } + let _ = canvas.show(ui, |ui, body| { let output = pass.show_quad(ui, body.rect); applied.set(applied.get() || output.apply); if let Some(canvas) = tool_pass(&body.env) { @@ -80,6 +96,9 @@ impl Rig { } }); }); + if pasteboard { + fixture.room(Vec2::new(SIZE.width as f32 + 200.0, SIZE.height as f32 + 200.0)); + } fixture.settle(); Rig { fixture, tool, document, apply } } @@ -366,3 +385,52 @@ fn a_session_starts_once_and_a_document_switch_discards_it() { rig.fixture.frame(Vec::new()); assert!(rig.tool.borrow_mut().take_events().is_empty(), "the same document keeps its quad"); } + +/// photocraft#11803: with Snap To Document Bounds on, a box drag started on the pasteboard starts on the document. +#[test] +fn a_box_drag_starts_on_the_document_bounds_the_canvas_snaps_to() { + let box_from = |rig: &mut Rig, press: (f64, f64), to: (f64, f64)| { + rig.tool.borrow_mut().clear(); + rig.drag(press, to, Modifiers::NONE); + rig.quad() + }; + let mut rig = Rig::snapping(Some(SnapOptions::default())); + + // Beyond a corner (outside on both axes) the box starts at that corner, from the drag's first move. + rig.tool.borrow_mut().clear(); + let (from, to) = (rig.at(-50.0, -40.0), rig.at(100.0, 100.0)); + rig.fixture.frame(vec![Event::PointerMoved(from)]); + rig.button(from, true, Modifiers::NONE); + rig.fixture.frame(vec![Event::PointerMoved(from + (to - from) * 0.5)]); + let shown = rig.quad().map(|q| q[0]); + assert!(shown.is_some_and(|p| p.x.abs() < 1e-3 && p.y.abs() < 1e-3), "the drag shows the snapped start: {shown:?}"); + rig.fixture.frame(vec![Event::PointerMoved(to)]); + rig.button(to, false, Modifiers::NONE); + rig.fixture.frame(Vec::new()); + assert!(near(rig.quad(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]), "{:?}", rig.quad()); + assert!(near(box_from(&mut rig, (450.0, 340.0), (300.0, 200.0)), [(300.0, 200.0), (400.0, 200.0), (400.0, 300.0), (300.0, 300.0)])); + // Within the snap distance of an edge the start moves onto it, on that axis only. + assert!(near(box_from(&mut rig, (3.0, 4.0), (100.0, 100.0)), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)])); + assert!(near(box_from(&mut rig, (395.0, 150.0), (300.0, 250.0)), [(300.0, 150.0), (400.0, 150.0), (400.0, 250.0), (300.0, 250.0)])); + // Outside on one axis only, beyond the snap distance, and inside away from the edges: the start stays. + assert!(near(box_from(&mut rig, (-50.0, 100.0), (100.0, 200.0)), [(-50.0, 100.0), (100.0, 100.0), (100.0, 200.0), (-50.0, 200.0)])); + assert!(near(box_from(&mut rig, (100.0, 150.0), (200.0, 250.0)), [(100.0, 150.0), (200.0, 150.0), (200.0, 250.0), (100.0, 250.0)])); + + // Clicked corners keep their place, also beyond a corner and near an edge. + rig.tool.borrow_mut().clear(); + for click in [(-30.0, -30.0), (200.0, 3.0), (300.0, 200.0), (3.0, 200.0)] { + rig.click(click); + } + assert!(near(rig.quad(), [(-30.0, -30.0), (200.0, 3.0), (300.0, 200.0), (3.0, 200.0)]), "{:?}", rig.quad()); + + // With Document Bounds off, or snapping off, the press beyond a corner and the one near an edge start where they were. + let mut bounds_off = SnapOptions::default(); + bounds_off.document_bounds = false; + let mut snap_off = SnapOptions::default(); + snap_off.on = false; + for options in [bounds_off, snap_off] { + let mut rig = Rig::snapping(Some(options)); + assert!(near(box_from(&mut rig, (-50.0, -40.0), (100.0, 100.0)), [(-50.0, -40.0), (100.0, -40.0), (100.0, 100.0), (-50.0, 100.0)])); + assert!(near(box_from(&mut rig, (3.0, 4.0), (100.0, 100.0)), [(3.0, 4.0), (100.0, 4.0), (100.0, 100.0), (3.0, 100.0)])); + } +} diff --git a/crates/nightly/Cargo.toml b/crates/nightly/Cargo.toml new file mode 100644 index 0000000000..ac3a3d11d4 --- /dev/null +++ b/crates/nightly/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "craft-nightly" +description = "Self-contained nightly profile isolation, launch protocol, and security fence for Craft desktop apps and ArtCraft Launcher." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[dependencies] + +[target.'cfg(windows)'.dependencies] +winsafe = { version = "0.0.29", default-features = false, features = ["kernel"] } + +[lints] +workspace = true diff --git a/crates/nightly/README.md b/crates/nightly/README.md new file mode 100644 index 0000000000..e5485fc287 --- /dev/null +++ b/crates/nightly/README.md @@ -0,0 +1,27 @@ +# craft-nightly + +Shared nightly-v1 startup and profile-root validation, for use by desktop apps and the launcher. + +## Rollout contract + +- Call `prepare_launch` before opening any application-owned settings, cache, logs, databases, + or other persistent state. Propagate the selected root to helpers that access those paths. + Exit on version-only queries before opening data paths; they intentionally install no global profile. +- Stable builds retain their existing data paths; nightly builds use the selected profile root. + Do not redirect stable data into a nightly profile or use a stable root as a fallback when + validation fails. +- `canonical_profile_root` is the default for new native nightly profiles. Existing launcher + installs may have data in the launcher's `paths.data/profiles/` directory. Before changing + the launcher to the new default, preserve those profiles: continue passing the existing validated + root explicitly until a separately tested, non-destructive migration can be performed. Never + overwrite a populated destination or silently abandon a populated source. Direct launches and + launcher launches must agree on the selected root after migration; the Flatpak sandbox uses + its own XDG data scope, not a host filesystem path passed blindly into the sandbox. +- Validate each app's actual stable paths and environment overrides, not just its package ID. + Test existing stable and nightly settings, direct launch and launcher launch, overrides, + literal arguments, and platform-specific storage behavior before rollout. + +The validator checks the profile at startup; it is not a sandbox or a replacement for safe +filesystem operations in applications. Keep launcher-side transaction and installation +protections when adopting this crate. Windows uses the same safe Win32 wrapper already used +by the launcher for file link identity checks. diff --git a/crates/nightly/src/env.rs b/crates/nightly/src/env.rs new file mode 100644 index 0000000000..28f077d316 --- /dev/null +++ b/crates/nightly/src/env.rs @@ -0,0 +1,41 @@ +use std::ffi::OsString; + +/// Read-only environment lookup abstraction so unit tests can exercise env-dependent +/// behavior without calling `unsafe` `std::env::set_var` under Rust 2024. +pub(crate) trait Env { + fn var_os(&self, key: &str) -> Option; +} + +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct SystemEnv; + +impl Env for SystemEnv { + fn var_os(&self, key: &str) -> Option { + std::env::var_os(key) + } +} + +#[cfg(test)] +#[derive(Clone, Debug, Default)] +pub(crate) struct TestEnv { + vars: std::collections::BTreeMap, +} + +#[cfg(test)] +impl TestEnv { + pub(crate) fn new() -> Self { + Self::default() + } + + pub(crate) fn with_var(mut self, key: impl Into, value: impl Into) -> Self { + self.vars.insert(key.into(), value.into()); + self + } +} + +#[cfg(test)] +impl Env for TestEnv { + fn var_os(&self, key: &str) -> Option { + self.vars.get(key).cloned() + } +} diff --git a/crates/nightly/src/error.rs b/crates/nightly/src/error.rs new file mode 100644 index 0000000000..74b1291591 --- /dev/null +++ b/crates/nightly/src/error.rs @@ -0,0 +1,127 @@ +use std::fmt; +use std::io; +use std::path::PathBuf; + +/// Errors returned while resolving, parsing, or validating a Craft nightly profile. +#[derive(Debug)] +pub enum ProfileError { + /// The application identifier is empty or contains invalid path characters. + InvalidAppId(String), + /// Could not determine the user's home or local application data directory. + MissingHomeDirectory, + /// Nightly launch flags (`--launch-profile` or `--profile-root`) were passed to a stable build. + NightlyFlagsInStableBuild, + /// The app's profile-root override environment variable was set in a stable build. + ProfileRootEnvInStableBuild(&'static str), + /// Both CLI `--launch-profile`/`--profile-root` and the profile-root env var were supplied. + ConflictingProfileOverrides(&'static str), + /// A required value was missing after a nightly CLI flag. + MissingFlagValue(&'static str), + /// A nightly CLI flag was specified more than once. + DuplicateFlag(&'static str), + /// Only one of `--launch-profile` or `--profile-root` was provided. + IncompleteLaunchFlags(&'static str), + /// `--launch-profile` was given an unsupported contract value. + UnsupportedLaunchProfile(String), + /// Nightly launch flags appeared after user arguments. + MisplacedNightlyFlag(String), + /// The profile root path is empty. + EmptyProfileRoot, + /// The profile root path is not absolute. + RelativeProfileRoot(PathBuf), + /// The profile root path contains a parent-directory (`..`) segment. + ParentTraversalInProfileRoot(PathBuf), + /// The profile root path points to a filesystem root. + FilesystemRootProfile(PathBuf), + /// A forbidden environment variable is set while launching a nightly build. + ForbiddenEnvVar(&'static str), + /// `FLATPAK_ID` is set to a value that does not match the app's nightly Flatpak ID. + MismatchedFlatpakId { actual: String, expected: String }, + /// A portable-mode marker was found next to the executable. + PortableModeUnsupported { marker: &'static str, path: PathBuf }, + /// A path component of the profile root is a symlink. + SymlinkInProfilePath(PathBuf), + /// A path component of the profile root exists and is not a directory. + NotADirectory(PathBuf), + /// The profile root overlaps a forbidden directory (stable data, install dir, or extra root). + ForbiddenRootOverlap { profile_root: PathBuf, forbidden_root: PathBuf }, + /// A symlink was found inside the profile root. + SymlinkEntry(PathBuf), + /// An entry required to be a directory is not a directory. + ExpectedDirectoryEntry(PathBuf), + /// A canonicalized entry resolved outside the canonical profile root. + PathEscape { path: PathBuf, root: PathBuf }, + /// A regular file inside the profile root has more than one hard link. + HardlinkedEntry { path: PathBuf, nlink: u64 }, + /// An unsupported filesystem entry type (such as a FIFO or socket) was found. + UnsupportedEntryType(PathBuf), + /// Recursive profile validation exceeded the maximum directory depth. + MaxDepthExceeded { path: PathBuf, max_depth: usize }, + /// The profile root directory is not writable. + NotWritable { path: PathBuf, source: io::Error }, + /// A process-wide profile was already installed with a different value. + AlreadyInitialized, + /// An underlying filesystem I/O error occurred. + Io { path: PathBuf, source: io::Error }, +} + +impl fmt::Display for ProfileError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidAppId(id) => write!(f, "invalid Craft app id for nightly profile: {id:?}"), + Self::MissingHomeDirectory => write!(f, "unable to resolve user home or local data directory for nightly profile"), + Self::NightlyFlagsInStableBuild => write!(f, "nightly launch flags are not permitted in a stable build"), + Self::ProfileRootEnvInStableBuild(var) => write!(f, "profile root environment variable `{var}` is not permitted in a stable build"), + Self::ConflictingProfileOverrides(var) => { + write!(f, "cannot combine `--launch-profile`/`--profile-root` with environment variable `{var}`") + } + Self::MissingFlagValue(flag) => write!(f, "missing value after `{flag}`"), + Self::DuplicateFlag(flag) => write!(f, "duplicate nightly launch flag `{flag}`"), + Self::IncompleteLaunchFlags(missing) => write!(f, "incomplete nightly launch flags: missing `{missing}`"), + Self::UnsupportedLaunchProfile(value) => write!(f, "unsupported `--launch-profile` contract `{value}`"), + Self::MisplacedNightlyFlag(flag) => write!(f, "nightly launch flag `{flag}` must appear before user arguments"), + Self::EmptyProfileRoot => write!(f, "nightly profile root path must not be empty"), + Self::RelativeProfileRoot(path) => write!(f, "nightly profile root must be an absolute path: {}", path.display()), + Self::ParentTraversalInProfileRoot(path) => { + write!(f, "nightly profile root must not contain `..`: {}", path.display()) + } + Self::FilesystemRootProfile(path) => write!(f, "nightly profile root must not be a filesystem root: {}", path.display()), + Self::ForbiddenEnvVar(var) => write!(f, "environment variable `{var}` is forbidden in nightly builds"), + Self::MismatchedFlatpakId { actual, expected } => { + write!(f, "FLATPAK_ID `{actual}` does not match expected nightly Flatpak ID `{expected}`") + } + Self::PortableModeUnsupported { marker, path } => { + write!(f, "portable marker `{marker}` at {} is not supported in nightly builds", path.display()) + } + Self::SymlinkInProfilePath(path) => write!(f, "symlink component in nightly profile path is not allowed: {}", path.display()), + Self::NotADirectory(path) => write!(f, "nightly profile path component is not a directory: {}", path.display()), + Self::ForbiddenRootOverlap { profile_root, forbidden_root } => { + write!(f, "nightly profile root {} overlaps forbidden directory {}", profile_root.display(), forbidden_root.display()) + } + Self::SymlinkEntry(path) => write!(f, "symlink inside nightly profile root is not allowed: {}", path.display()), + Self::ExpectedDirectoryEntry(path) => write!(f, "expected directory entry inside nightly profile root: {}", path.display()), + Self::PathEscape { path, root } => { + write!(f, "entry {} resolved outside nightly profile root {}", path.display(), root.display()) + } + Self::HardlinkedEntry { path, nlink } => { + write!(f, "regular file {} has {nlink} hard links (expected 1)", path.display()) + } + Self::UnsupportedEntryType(path) => write!(f, "unsupported filesystem entry type in nightly profile: {}", path.display()), + Self::MaxDepthExceeded { path, max_depth } => { + write!(f, "nightly profile directory depth exceeded {max_depth} at {}", path.display()) + } + Self::NotWritable { path, source } => write!(f, "nightly profile root {} is not writable: {source}", path.display()), + Self::AlreadyInitialized => write!(f, "craft-nightly profile has already been initialized with a different profile"), + Self::Io { path, source } => write!(f, "filesystem error at {}: {source}", path.display()), + } + } +} + +impl std::error::Error for ProfileError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::NotWritable { source, .. } | Self::Io { source, .. } => Some(source), + _ => None, + } + } +} diff --git a/crates/nightly/src/lib.rs b/crates/nightly/src/lib.rs new file mode 100644 index 0000000000..647205a1de --- /dev/null +++ b/crates/nightly/src/lib.rs @@ -0,0 +1,121 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! Self-contained nightly profile isolation for ArtCraft Launcher and Craft desktop apps. +//! +//! `craft-nightly` defines the shared `nightly-v1` launch protocol, deterministic per-OS +//! canonical nightly profile roots, startup CLI/environment parsing, process-wide `OnceLock` +//! state, and a parameterized filesystem/environment security fence that prevents nightly builds +//! from touching stable user data. +//! +//! Direct launches of a nightly binary automatically self-isolate into [`canonical_profile_root`] +//! while preserving all user arguments, so direct launches and ArtCraft Launcher share the same +//! default nightly profile without refusing direct startup. See the crate README for +//! the consumer rollout and existing-profile preservation contract. + +mod env; +mod error; +mod protocol; +mod startup; +mod validate; + +use std::ffi::OsString; +use std::path::Path; +use std::sync::OnceLock; + +pub use error::ProfileError; +pub use protocol::{ + LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root, launch_arguments, nightly_flatpak_id, nightly_package_id, +}; +pub use startup::{BuildFlavor, Launch, Profile, StartupOptions, parse_startup}; +pub use validate::{AppProfileSpec, validate_and_prepare_root}; + +static CURRENT_PROFILE: OnceLock = OnceLock::new(); + +/// Parses startup arguments for `flavor`, validates and prepares the isolated profile root when +/// running as [`BuildFlavor::NightlyV1`], installs the resolved [`Profile`] into the process-wide +/// `OnceLock`, and returns the [`Launch`] summary. Version-only queries perform no filesystem +/// preparation and do not install a profile. Callers must exit before initializing data paths. +/// +/// Pass `std::env::args_os().skip(1)` as `args`. +pub fn prepare_launch( + flavor: BuildFlavor, + spec: &AppProfileSpec, + args: impl IntoIterator, + options: &StartupOptions, +) -> Result { + let mut launch = parse_startup(flavor, spec, args, options)?; + if launch.is_version_query() { + return Ok(launch); + } + if let Profile::NightlyV1(ref root) = launch.profile { + let canonical = validate_and_prepare_root(root, spec)?; + launch.profile = Profile::NightlyV1(canonical); + } + + install_current_profile(&launch.profile)?; + Ok(launch) +} + +/// Returns the process-wide [`Profile`] installed by [`prepare_launch`], if initialized. +pub fn current() -> Option<&'static Profile> { + CURRENT_PROFILE.get() +} + +/// Returns the canonical nightly profile root installed by [`prepare_launch`], or `None` +/// if uninitialized or running as [`Profile::Stable`]. +pub fn current_root() -> Option<&'static Path> { + CURRENT_PROFILE.get().and_then(Profile::root) +} + +fn install_current_profile(profile: &Profile) -> Result<(), ProfileError> { + match CURRENT_PROFILE.set(profile.clone()) { + Ok(()) => Ok(()), + Err(_) => match CURRENT_PROFILE.get() { + Some(existing) if existing == profile => Ok(()), + _ => Err(ProfileError::AlreadyInitialized), + }, + } +} + +#[cfg(test)] +mod tests { + use std::ffi::OsString; + use std::fs; + + use crate::{AppProfileSpec, BuildFlavor, Profile, StartupOptions, current, current_root, launch_arguments, prepare_launch}; + + #[test] + fn prepare_launch_installs_process_wide_nightly_profile() { + let base = fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let root = base.join(format!("craft-nightly-prepare-test-{}", std::process::id())); + let spec = AppProfileSpec { + app_id: "craft-nightly-test", + display_name: "Craft Nightly Test", + stable_dir_names: &["craft-nightly-test-stable"], + stable_package_id: "ai.storyteller.craft-nightly-test", + nightly_package_id: "ai.storyteller.craft-nightly-test.nightly", + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: &[], + extra_forbidden_roots: Vec::new(), + }; + + let version_args = launch_arguments(&root, &[OsString::from("--version")]); + let version = prepare_launch(BuildFlavor::NightlyV1, &spec, version_args, &StartupOptions::default()).expect("version query"); + assert!(version.is_version_query()); + assert!(current().is_none()); + assert!(!root.exists()); + + let args = launch_arguments(&root, &[OsString::from("sample.doc")]); + let launch = prepare_launch(BuildFlavor::NightlyV1, &spec, args, &StartupOptions::default()).expect("prepare_launch"); + + let expected_canonical = fs::canonicalize(&root).unwrap_or_else(|_| root.clone()); + assert_eq!(launch.profile, Profile::NightlyV1(expected_canonical.clone())); + assert_eq!(launch.passthrough_args, vec![OsString::from("sample.doc")]); + assert_eq!(current(), Some(&Profile::NightlyV1(expected_canonical.clone()))); + assert_eq!(current_root(), Some(expected_canonical.as_path())); + + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/nightly/src/protocol.rs b/crates/nightly/src/protocol.rs new file mode 100644 index 0000000000..eaf605d177 --- /dev/null +++ b/crates/nightly/src/protocol.rs @@ -0,0 +1,231 @@ +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use crate::env::{Env, SystemEnv}; +use crate::error::ProfileError; + +/// CLI flag naming the launch profile contract (for example `nightly-v1`). +pub const LAUNCH_PROFILE_FLAG: &str = "--launch-profile"; + +/// CLI flag specifying the isolated profile root directory. +pub const PROFILE_ROOT_FLAG: &str = "--profile-root"; + +/// Contract identifier for the v1 nightly profile isolation protocol. +pub const NIGHTLY_V1_CONTRACT: &str = "nightly-v1"; + +/// Returns the reverse-DNS nightly package identifier for `app_id`, +/// e.g. `ai.storyteller.photocraft.nightly`. +pub fn nightly_package_id(app_id: &str) -> String { + format!("ai.storyteller.{app_id}.nightly") +} + +/// Returns the Flatpak application ID for the nightly build of `app_id`, +/// replacing `-` with `_` in `app_id` before `.nightly` +/// (e.g. `craft-anything` -> `ai.storyteller.craft_anything.nightly`). +pub fn nightly_flatpak_id(app_id: &str) -> String { + let normalized = app_id.replace('-', "_"); + format!("ai.storyteller.{normalized}.nightly") +} + +/// Resolves the deterministic per-OS canonical nightly profile root for `app_id`. +/// +/// Both direct nightly launches and ArtCraft Launcher share this default location so users +/// keep one consistent nightly profile regardless of how they opened the app: +/// - Inside a Nightly Flatpak (`FLATPAK_ID == nightly_flatpak_id(app_id)`): +/// `${XDG_DATA_HOME:-$HOME/.local/share}/` +/// - Linux / BSD: `${XDG_DATA_HOME:-$HOME/.local/share}/ai.storyteller..nightly` +/// - macOS: `$HOME/Library/Application Support/ai.storyteller..nightly` +/// - Windows: `%LOCALAPPDATA%\ArtCraft\Nightly\` +/// (falling back to `%USERPROFILE%\AppData\Local\ArtCraft\Nightly\`) +pub fn canonical_profile_root(app_id: &str) -> Result { + canonical_profile_root_with_env(app_id, &SystemEnv) +} + +/// Builds the CLI argument vector for launching a nightly app from ArtCraft Launcher: +/// `["--launch-profile", "nightly-v1", "--profile-root", , "--", ]`. +pub fn launch_arguments(profile_root: &Path, user_args: &[OsString]) -> Vec { + let mut args = Vec::with_capacity(5 + user_args.len()); + args.push(OsString::from(LAUNCH_PROFILE_FLAG)); + args.push(OsString::from(NIGHTLY_V1_CONTRACT)); + args.push(OsString::from(PROFILE_ROOT_FLAG)); + args.push(profile_root.as_os_str().to_os_string()); + args.push(OsString::from("--")); + args.extend(user_args.iter().cloned()); + args +} + +pub(crate) fn validate_app_id(app_id: &str) -> Result<(), ProfileError> { + if app_id.is_empty() || app_id == "." || app_id == ".." || !app_id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) { + return Err(ProfileError::InvalidAppId(app_id.to_owned())); + } + Ok(()) +} + +pub(crate) fn canonical_profile_root_with_env(app_id: &str, env: &dyn Env) -> Result { + validate_app_id(app_id)?; + let package_id = nightly_package_id(app_id); + + #[cfg(not(target_os = "windows"))] + if is_nightly_flatpak(app_id, env) { + return xdg_data_dir(env).map(|base| base.join(&package_id)); + } + + #[cfg(target_os = "windows")] + { + let _ = package_id; + windows_local_app_data(env).map(|base| base.join("ArtCraft").join("Nightly").join(app_id)) + } + + #[cfg(target_os = "macos")] + { + home_dir(env).map(|home| home.join("Library").join("Application Support").join(&package_id)) + } + + #[cfg(all(unix, not(target_os = "macos")))] + { + xdg_data_dir(env).map(|base| base.join(&package_id)) + } + + #[cfg(not(any(unix, target_os = "windows")))] + { + let _ = (env, package_id); + Err(ProfileError::MissingHomeDirectory) + } +} + +#[cfg(not(target_os = "windows"))] +fn is_nightly_flatpak(app_id: &str, env: &dyn Env) -> bool { + let expected = nightly_flatpak_id(app_id); + env.var_os("FLATPAK_ID").and_then(|v| v.into_string().ok()).as_deref() == Some(expected.as_str()) +} + +#[cfg(not(target_os = "windows"))] +fn xdg_data_dir(env: &dyn Env) -> Result { + if let Some(xdg) = non_empty_abs_env(env, "XDG_DATA_HOME") { + return Ok(xdg); + } + Ok(home_dir(env)?.join(".local").join("share")) +} + +#[cfg(not(target_os = "windows"))] +fn home_dir(env: &dyn Env) -> Result { + non_empty_abs_env(env, "HOME").ok_or(ProfileError::MissingHomeDirectory) +} + +#[cfg(target_os = "windows")] +fn windows_local_app_data(env: &dyn Env) -> Result { + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + return Ok(local); + } + let user_profile = non_empty_abs_env(env, "USERPROFILE").ok_or(ProfileError::MissingHomeDirectory)?; + Ok(user_profile.join("AppData").join("Local")) +} + +pub(crate) fn non_empty_abs_env(env: &dyn Env, key: &str) -> Option { + let value = env.var_os(key)?; + if value.is_empty() { + return None; + } + let path = PathBuf::from(value); + if path.is_absolute() { Some(path) } else { None } +} + +#[cfg(test)] +mod tests { + use std::ffi::OsString; + use std::path::{Path, PathBuf}; + + use crate::env::TestEnv; + use crate::protocol::{ + LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root_with_env, launch_arguments, nightly_flatpak_id, + nightly_package_id, + }; + + #[test] + fn nightly_ids_format_correctly() { + assert_eq!(nightly_package_id("photocraft"), "ai.storyteller.photocraft.nightly"); + assert_eq!(nightly_package_id("craft-anything"), "ai.storyteller.craft-anything.nightly"); + assert_eq!(nightly_flatpak_id("craft-anything"), "ai.storyteller.craft_anything.nightly"); + assert_eq!(nightly_flatpak_id("photocraft"), "ai.storyteller.photocraft.nightly"); + } + + #[test] + fn launch_arguments_builds_expected_vector() { + let args = launch_arguments(Path::new("/tmp/craft-prof"), &[OsString::from("doc.pdf"), OsString::from("--flag")]); + assert_eq!( + args, + vec![ + OsString::from(LAUNCH_PROFILE_FLAG), + OsString::from(NIGHTLY_V1_CONTRACT), + OsString::from(PROFILE_ROOT_FLAG), + OsString::from("/tmp/craft-prof"), + OsString::from("--"), + OsString::from("doc.pdf"), + OsString::from("--flag"), + ] + ); + } + + #[test] + fn invalid_app_id_is_rejected() { + let env = TestEnv::new().with_var("HOME", "/home/tester"); + assert!(canonical_profile_root_with_env("", &env).is_err()); + assert!(canonical_profile_root_with_env("../escape", &env).is_err()); + assert!(canonical_profile_root_with_env("a/b", &env).is_err()); + } + + #[cfg(all(unix, not(target_os = "macos")))] + #[test] + fn canonical_root_uses_xdg_or_home_on_linux() { + let env_xdg = TestEnv::new().with_var("HOME", "/home/tester").with_var("XDG_DATA_HOME", "/custom/data"); + assert_eq!( + canonical_profile_root_with_env("photocraft", &env_xdg).expect("xdg root"), + PathBuf::from("/custom/data/ai.storyteller.photocraft.nightly") + ); + + let env_home = TestEnv::new().with_var("HOME", "/home/tester"); + assert_eq!( + canonical_profile_root_with_env("photocraft", &env_home).expect("home root"), + PathBuf::from("/home/tester/.local/share/ai.storyteller.photocraft.nightly") + ); + } + + #[cfg(not(target_os = "windows"))] + #[test] + fn canonical_root_inside_nightly_flatpak_uses_sandbox_xdg() { + let env = TestEnv::new() + .with_var("FLATPAK_ID", "ai.storyteller.craft_anything.nightly") + .with_var("HOME", "/home/tester") + .with_var("XDG_DATA_HOME", "/home/tester/.var/app/ai.storyteller.craft_anything.nightly/data"); + assert_eq!( + canonical_profile_root_with_env("craft-anything", &env).expect("flatpak root"), + PathBuf::from("/home/tester/.var/app/ai.storyteller.craft_anything.nightly/data/ai.storyteller.craft-anything.nightly") + ); + } + + #[cfg(target_os = "macos")] + #[test] + fn canonical_root_uses_application_support_on_macos() { + let env = TestEnv::new().with_var("HOME", "/Users/tester"); + assert_eq!( + canonical_profile_root_with_env("photocraft", &env).expect("macos root"), + PathBuf::from("/Users/tester/Library/Application Support/ai.storyteller.photocraft.nightly") + ); + } + + #[cfg(target_os = "windows")] + #[test] + fn canonical_root_uses_localappdata_or_userprofile_on_windows() { + let env_local = TestEnv::new().with_var("LOCALAPPDATA", r"C:\Users\tester\AppData\Local"); + assert_eq!( + canonical_profile_root_with_env("photocraft", &env_local).expect("localappdata root"), + PathBuf::from(r"C:\Users\tester\AppData\Local\ArtCraft\Nightly\photocraft") + ); + + let env_profile = TestEnv::new().with_var("USERPROFILE", r"C:\Users\tester"); + assert_eq!( + canonical_profile_root_with_env("photocraft", &env_profile).expect("userprofile root"), + PathBuf::from(r"C:\Users\tester\AppData\Local\ArtCraft\Nightly\photocraft") + ); + } +} diff --git a/crates/nightly/src/startup.rs b/crates/nightly/src/startup.rs new file mode 100644 index 0000000000..ecbb4db5d7 --- /dev/null +++ b/crates/nightly/src/startup.rs @@ -0,0 +1,515 @@ +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +use crate::env::{Env, SystemEnv}; +use crate::error::ProfileError; +use crate::protocol::{LAUNCH_PROFILE_FLAG, NIGHTLY_V1_CONTRACT, PROFILE_ROOT_FLAG, canonical_profile_root_with_env}; +use crate::validate::AppProfileSpec; + +/// Build channel flavor compiled into the host binary. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BuildFlavor { + /// Standard release build using the app's normal OS storage directories. + Stable, + /// Nightly v1 build using an isolated profile root. + NightlyV1, +} + +/// Resolved runtime profile for the current process. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Profile { + /// Standard stable profile (no nightly override). + Stable, + /// Isolated nightly v1 profile rooted at the contained directory. + NightlyV1(PathBuf), +} + +impl Profile { + /// Returns the isolated profile root directory when running as a nightly profile. + pub fn root(&self) -> Option<&Path> { + match self { + Self::Stable => None, + Self::NightlyV1(path) => Some(path.as_path()), + } + } + + /// Returns `true` when this profile is a nightly isolated profile. + pub fn is_nightly(&self) -> bool { + matches!(self, Self::NightlyV1(_)) + } +} + +/// Parsed startup result separating nightly launch metadata from application arguments. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Launch { + /// Resolved profile (stable or nightly v1 with its root path). + pub profile: Profile, + /// Application arguments after stripping leading flags and nightly launch protocol flags. + pub passthrough_args: Vec, + /// Configured leading flags (for example `["--safe-gpu"]`) preserved before `--launch-profile`. + pub leading_flags: Vec, +} + +impl Launch { + /// Returns `true` when the passthrough arguments are a `--version` or `-V` query + /// (both for plain invocations and after `--` in launcher invocations). + pub fn is_version_query(&self) -> bool { + self.passthrough_args.len() == 1 + && self.passthrough_args.first().and_then(|arg| arg.to_str()).is_some_and(|arg| matches!(arg, "--version" | "-V")) + } +} + +/// Startup parsing options supplied by an application. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StartupOptions { + /// Leading flags permitted before `--launch-profile` (for example `["--safe-gpu"]`). + pub allowed_leading_flags: &'static [&'static str], +} + +impl StartupOptions { + /// Creates default startup options with no leading flags. + pub const fn new() -> Self { + Self { allowed_leading_flags: &[] } + } + + /// Creates startup options permitting the given leading flags before `--launch-profile`. + pub const fn with_leading_flags(allowed_leading_flags: &'static [&'static str]) -> Self { + Self { allowed_leading_flags } + } +} + +/// Parses startup CLI arguments (excluding `argv[0]`) and environment overrides for `flavor`. +/// +/// Pass `std::env::args_os().skip(1)` as `args`. +/// +/// Resolution priority for [`BuildFlavor::NightlyV1`]: +/// 1. Explicit CLI `--launch-profile nightly-v1 --profile-root [-- ]` +/// (cannot be combined with `spec.profile_root_env`). +/// 2. Explicit environment variable override `spec.profile_root_env` when configured and set. +/// 3. Self-isolated direct launch: resolves [`crate::canonical_profile_root`] for `spec.app_id` +/// and preserves all user arguments in `passthrough_args`. +/// +/// For [`BuildFlavor::Stable`], nightly CLI flags and `spec.profile_root_env` are rejected. +pub fn parse_startup( + flavor: BuildFlavor, + spec: &AppProfileSpec, + args: impl IntoIterator, + options: &StartupOptions, +) -> Result { + parse_startup_with_env(flavor, spec, args, options, &SystemEnv) +} + +pub(crate) fn parse_startup_with_env( + flavor: BuildFlavor, + spec: &AppProfileSpec, + args: impl IntoIterator, + options: &StartupOptions, + env: &dyn Env, +) -> Result { + let raw_args: Vec = args.into_iter().collect(); + let (leading_flags, rest) = split_leading_flags(&raw_args, options.allowed_leading_flags); + + if rest.first().is_some_and(|arg| is_nightly_flag(arg)) { + return parse_cli_nightly_launch(flavor, spec, leading_flags, rest, env); + } + + if let Some(misplaced) = find_misplaced_nightly_flag(rest) { + return match flavor { + BuildFlavor::Stable => Err(ProfileError::NightlyFlagsInStableBuild), + BuildFlavor::NightlyV1 => Err(ProfileError::MisplacedNightlyFlag(misplaced)), + }; + } + + resolve_without_cli_flags(flavor, spec, leading_flags, rest.to_vec(), env) +} + +fn split_leading_flags<'a>(args: &'a [OsString], allowed: &[&str]) -> (Vec, &'a [OsString]) { + let mut leading = Vec::new(); + let mut idx = 0; + while let Some(arg) = args.get(idx) { + if arg.to_str().is_some_and(|s| allowed.contains(&s)) { + leading.push(arg.clone()); + idx += 1; + } else { + break; + } + } + (leading, args.get(idx..).unwrap_or_default()) +} + +fn is_nightly_flag(arg: &OsStr) -> bool { + arg.to_str() + .is_some_and(|s| s == LAUNCH_PROFILE_FLAG || s == PROFILE_ROOT_FLAG || s.starts_with("--launch-profile=") || s.starts_with("--profile-root=")) +} + +fn find_misplaced_nightly_flag(args: &[OsString]) -> Option { + for arg in args { + if arg == "--" { + break; + } + if is_nightly_flag(arg) { + return Some(arg.to_string_lossy().into_owned()); + } + } + None +} + +fn parse_cli_nightly_launch( + flavor: BuildFlavor, + spec: &AppProfileSpec, + leading_flags: Vec, + rest: &[OsString], + env: &dyn Env, +) -> Result { + if flavor == BuildFlavor::Stable { + return Err(ProfileError::NightlyFlagsInStableBuild); + } + + let (profile_root, passthrough_args) = parse_nightly_flag_header(rest)?; + if let Some(env_var) = spec.profile_root_env + && env.var_os(env_var).is_some() + { + return Err(ProfileError::ConflictingProfileOverrides(env_var)); + } + + Ok(Launch { profile: Profile::NightlyV1(profile_root), passthrough_args, leading_flags }) +} + +fn parse_nightly_flag_header(args: &[OsString]) -> Result<(PathBuf, Vec), ProfileError> { + let mut saw_contract = false; + let mut profile_root: Option = None; + let mut idx = 0; + let mut saw_separator = false; + + while let Some(arg) = args.get(idx) { + if arg == "--" { + idx += 1; + saw_separator = true; + break; + } + if let Some(consumed) = try_consume_launch_profile(args, idx, &mut saw_contract)? { + idx += consumed; + continue; + } + if let Some(consumed) = try_consume_profile_root(args, idx, &mut profile_root)? { + idx += consumed; + continue; + } + break; + } + + if !saw_contract { + return Err(ProfileError::IncompleteLaunchFlags(LAUNCH_PROFILE_FLAG)); + } + let root = profile_root.ok_or(ProfileError::IncompleteLaunchFlags(PROFILE_ROOT_FLAG))?; + let remaining = args.get(idx..).unwrap_or_default(); + if !saw_separator && let Some(misplaced) = find_misplaced_nightly_flag(remaining) { + return Err(ProfileError::MisplacedNightlyFlag(misplaced)); + } + Ok((root, remaining.to_vec())) +} + +fn try_consume_launch_profile(args: &[OsString], idx: usize, saw_contract: &mut bool) -> Result, ProfileError> { + let Some(arg) = args.get(idx) else { + return Ok(None); + }; + let (value, consumed) = if arg == LAUNCH_PROFILE_FLAG { + let val = args.get(idx + 1).ok_or(ProfileError::MissingFlagValue(LAUNCH_PROFILE_FLAG))?; + (val.to_string_lossy().into_owned(), 2) + } else if let Some(val) = arg.to_str().and_then(|s| s.strip_prefix("--launch-profile=")) { + (val.to_owned(), 1) + } else { + return Ok(None); + }; + + if *saw_contract { + return Err(ProfileError::DuplicateFlag(LAUNCH_PROFILE_FLAG)); + } + if value != NIGHTLY_V1_CONTRACT { + return Err(ProfileError::UnsupportedLaunchProfile(value)); + } + *saw_contract = true; + Ok(Some(consumed)) +} + +fn try_consume_profile_root(args: &[OsString], idx: usize, profile_root: &mut Option) -> Result, ProfileError> { + let Some(arg) = args.get(idx) else { + return Ok(None); + }; + let (value, consumed) = if arg == PROFILE_ROOT_FLAG { + let val = args.get(idx + 1).ok_or(ProfileError::MissingFlagValue(PROFILE_ROOT_FLAG))?; + (val.clone(), 2) + } else if let Some(val) = arg.to_str().and_then(|s| s.strip_prefix("--profile-root=")) { + (OsString::from(val), 1) + } else { + return Ok(None); + }; + + if profile_root.is_some() { + return Err(ProfileError::DuplicateFlag(PROFILE_ROOT_FLAG)); + } + if value.is_empty() { + return Err(ProfileError::EmptyProfileRoot); + } + *profile_root = Some(PathBuf::from(value)); + Ok(Some(consumed)) +} + +fn resolve_without_cli_flags( + flavor: BuildFlavor, + spec: &AppProfileSpec, + leading_flags: Vec, + passthrough_args: Vec, + env: &dyn Env, +) -> Result { + match flavor { + BuildFlavor::Stable => { + if let Some(env_var) = spec.profile_root_env + && env.var_os(env_var).is_some() + { + return Err(ProfileError::ProfileRootEnvInStableBuild(env_var)); + } + Ok(Launch { profile: Profile::Stable, passthrough_args, leading_flags }) + } + BuildFlavor::NightlyV1 => { + if let Some(env_var) = spec.profile_root_env + && let Some(val) = env.var_os(env_var) + { + if val.is_empty() { + return Err(ProfileError::EmptyProfileRoot); + } + return Ok(Launch { profile: Profile::NightlyV1(PathBuf::from(val)), passthrough_args, leading_flags }); + } + let root = canonical_profile_root_with_env(spec.app_id, env)?; + Ok(Launch { profile: Profile::NightlyV1(root), passthrough_args, leading_flags }) + } + } +} + +#[cfg(test)] +mod tests { + use std::ffi::OsString; + use std::path::{Path, PathBuf}; + + use crate::env::TestEnv; + use crate::error::ProfileError; + use crate::protocol::{canonical_profile_root_with_env, launch_arguments}; + use crate::startup::{BuildFlavor, Profile, StartupOptions, parse_startup_with_env}; + use crate::validate::AppProfileSpec; + + fn sample_spec() -> AppProfileSpec { + AppProfileSpec { + app_id: "photocraft", + display_name: "PhotoCraft", + stable_dir_names: &["photocraft", "PhotoCraft"], + stable_package_id: "ai.storyteller.photocraft", + nightly_package_id: "ai.storyteller.photocraft.nightly", + profile_root_env: Some("PHOTOCRAFT_PROFILE_ROOT"), + forbidden_env_vars: &["PHOTOCRAFT_CONFIG_DIR"], + portable_markers: &["portable.marker"], + folder_only_entries: &["config"], + extra_forbidden_roots: Vec::new(), + } + } + + fn base_env() -> TestEnv { + #[cfg(target_os = "windows")] + { + TestEnv::new().with_var("LOCALAPPDATA", r"C:\Users\tester\AppData\Local") + } + #[cfg(not(target_os = "windows"))] + { + TestEnv::new().with_var("HOME", "/home/tester") + } + } + + #[test] + fn direct_nightly_launch_resolves_canonical_root_and_preserves_args() { + let spec = sample_spec(); + let env = base_env(); + let expected_root = canonical_profile_root_with_env(spec.app_id, &env).expect("canonical root"); + + let launch = parse_startup_with_env( + BuildFlavor::NightlyV1, + &spec, + [OsString::from("photo.pcraft"), OsString::from("--open")], + &StartupOptions::default(), + &env, + ) + .expect("direct nightly launch should succeed"); + + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, vec![OsString::from("photo.pcraft"), OsString::from("--open")]); + assert!(launch.leading_flags.is_empty()); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_cli_flags_override_canonical_root_and_split_passthrough() { + let spec = sample_spec(); + let env = base_env(); + let custom_root = PathBuf::from("/tmp/custom-nightly"); + + let launch = parse_startup_with_env( + BuildFlavor::NightlyV1, + &spec, + [ + OsString::from("--launch-profile"), + OsString::from("nightly-v1"), + OsString::from("--profile-root"), + custom_root.as_os_str().to_os_string(), + OsString::from("--"), + OsString::from("file.pdf"), + ], + &StartupOptions::default(), + &env, + ) + .expect("explicit launch should succeed"); + + assert_eq!(launch.profile, Profile::NightlyV1(custom_root)); + assert_eq!(launch.passthrough_args, vec![OsString::from("file.pdf")]); + } + + #[test] + fn leading_flags_are_preserved_before_launch_profile() { + let spec = sample_spec(); + let env = base_env(); + let options = StartupOptions::with_leading_flags(&["--safe-gpu"]); + + let launch = parse_startup_with_env( + BuildFlavor::NightlyV1, + &spec, + [ + OsString::from("--safe-gpu"), + OsString::from("--launch-profile"), + OsString::from("nightly-v1"), + OsString::from("--profile-root"), + OsString::from("/tmp/nightly-safe"), + OsString::from("--"), + OsString::from("image.png"), + ], + &options, + &env, + ) + .expect("leading flag launch should succeed"); + + assert_eq!(launch.leading_flags, vec![OsString::from("--safe-gpu")]); + assert_eq!(launch.profile.root(), Some(Path::new("/tmp/nightly-safe"))); + assert_eq!(launch.passthrough_args, vec![OsString::from("image.png")]); + } + + #[test] + fn env_override_applies_when_cli_flags_absent_and_conflicts_when_combined() { + let spec = sample_spec(); + let env = base_env().with_var("PHOTOCRAFT_PROFILE_ROOT", "/tmp/env-nightly"); + + let launch = parse_startup_with_env(BuildFlavor::NightlyV1, &spec, [OsString::from("doc.pcraft")], &StartupOptions::default(), &env) + .expect("env override should succeed"); + assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from("/tmp/env-nightly"))); + assert_eq!(launch.passthrough_args, vec![OsString::from("doc.pcraft")]); + + let cli_args = launch_arguments(Path::new("/tmp/cli-nightly"), &[OsString::from("doc.pcraft")]); + let conflict = parse_startup_with_env(BuildFlavor::NightlyV1, &spec, cli_args, &StartupOptions::default(), &env); + assert!(matches!(conflict, Err(ProfileError::ConflictingProfileOverrides("PHOTOCRAFT_PROFILE_ROOT")))); + } + + #[test] + fn stable_build_refuses_nightly_flags_and_env_override() { + let spec = sample_spec(); + let env = base_env(); + + let cli_args = launch_arguments(Path::new("/tmp/nightly"), &[]); + let cli_err = parse_startup_with_env(BuildFlavor::Stable, &spec, cli_args, &StartupOptions::default(), &env); + assert!(matches!(cli_err, Err(ProfileError::NightlyFlagsInStableBuild))); + + let env_override = base_env().with_var("PHOTOCRAFT_PROFILE_ROOT", "/tmp/nightly"); + let env_err = parse_startup_with_env(BuildFlavor::Stable, &spec, Vec::new(), &StartupOptions::default(), &env_override); + assert!(matches!(env_err, Err(ProfileError::ProfileRootEnvInStableBuild("PHOTOCRAFT_PROFILE_ROOT")))); + + let ok = parse_startup_with_env(BuildFlavor::Stable, &spec, [OsString::from("a.png")], &StartupOptions::default(), &env) + .expect("normal stable launch should succeed"); + assert_eq!(ok.profile, Profile::Stable); + assert!(!ok.profile.is_nightly()); + assert_eq!(ok.profile.root(), None); + assert_eq!(ok.passthrough_args, vec![OsString::from("a.png")]); + } + + #[test] + fn launch_arguments_round_trips_through_parse_startup() { + let spec = sample_spec(); + let env = base_env(); + let root = PathBuf::from("/tmp/roundtrip-profile"); + let user_args = vec![OsString::from("first.pdf"), OsString::from("--page"), OsString::from("2")]; + + let encoded = launch_arguments(&root, &user_args); + let parsed = + parse_startup_with_env(BuildFlavor::NightlyV1, &spec, encoded, &StartupOptions::default(), &env).expect("round-trip should succeed"); + + assert_eq!(parsed.profile, Profile::NightlyV1(root)); + assert_eq!(parsed.passthrough_args, user_args); + assert!(parsed.leading_flags.is_empty()); + } + + #[test] + fn recognizes_version_queries_plain_and_via_launcher() { + let spec = sample_spec(); + let env = base_env(); + + let plain = parse_startup_with_env(BuildFlavor::NightlyV1, &spec, [OsString::from("--version")], &StartupOptions::default(), &env) + .expect("plain --version"); + assert!(plain.is_version_query()); + + let short = parse_startup_with_env(BuildFlavor::Stable, &spec, [OsString::from("-V")], &StartupOptions::default(), &env).expect("plain -V"); + assert!(short.is_version_query()); + + let via_launcher_args = launch_arguments(Path::new("/tmp/ver-prof"), &[OsString::from("--version")]); + let via_launcher = + parse_startup_with_env(BuildFlavor::NightlyV1, &spec, via_launcher_args, &StartupOptions::default(), &env).expect("launcher --version"); + assert!(via_launcher.is_version_query()); + assert_eq!(via_launcher.passthrough_args, vec![OsString::from("--version")]); + } + + #[test] + fn explicit_header_rejects_misplaced_protocol_flags_without_separator_and_preserves_after_separator() { + let spec = sample_spec(); + let env = base_env(); + + let misplaced = parse_startup_with_env( + BuildFlavor::NightlyV1, + &spec, + [ + OsString::from("--launch-profile"), + OsString::from("nightly-v1"), + OsString::from("--profile-root"), + OsString::from("/nightly"), + OsString::from("file.pcraft"), + OsString::from("--profile-root"), + OsString::from("/other"), + ], + &StartupOptions::default(), + &env, + ); + assert!(matches!(misplaced, Err(ProfileError::MisplacedNightlyFlag(flag)) if flag == "--profile-root")); + + let preserved = parse_startup_with_env( + BuildFlavor::NightlyV1, + &spec, + [ + OsString::from("--launch-profile"), + OsString::from("nightly-v1"), + OsString::from("--profile-root"), + OsString::from("/nightly"), + OsString::from("--"), + OsString::from("file.pcraft"), + OsString::from("--profile-root"), + OsString::from("/other"), + ], + &StartupOptions::default(), + &env, + ) + .expect("args after `--` should be preserved"); + assert_eq!(preserved.profile, Profile::NightlyV1(PathBuf::from("/nightly"))); + assert_eq!(preserved.passthrough_args, vec![OsString::from("file.pcraft"), OsString::from("--profile-root"), OsString::from("/other")]); + } +} diff --git a/crates/nightly/src/validate.rs b/crates/nightly/src/validate.rs new file mode 100644 index 0000000000..e686bffaac --- /dev/null +++ b/crates/nightly/src/validate.rs @@ -0,0 +1,661 @@ +use std::fs::{self, OpenOptions}; +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::env::{Env, SystemEnv}; +use crate::error::ProfileError; +use crate::protocol::non_empty_abs_env; + +#[cfg(not(target_os = "windows"))] +use crate::protocol::nightly_flatpak_id; + +const MAX_WALK_DEPTH: usize = 64; +static PROBE_COUNTER: AtomicU64 = AtomicU64::new(0); + +/// Application-specific isolation specification used to validate a nightly profile root. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AppProfileSpec { + /// Canonical lowercase app identifier (for example `"photocraft"` or `"craft-anything"`). + pub app_id: &'static str, + /// Human-readable application name (for example `"PhotoCraft"`). + pub display_name: &'static str, + /// Directory names used by the stable build under OS config/data/cache directories. + pub stable_dir_names: &'static [&'static str], + /// Reverse-DNS package identifier used by the stable build. + pub stable_package_id: &'static str, + /// Reverse-DNS package identifier used by the nightly build. + pub nightly_package_id: &'static str, + /// Optional environment variable name allowing explicit profile-root overrides in nightly builds. + pub profile_root_env: Option<&'static str>, + /// Environment variables that must not be set when launching a nightly build. + pub forbidden_env_vars: &'static [&'static str], + /// Filenames next to the executable that indicate portable mode (disallowed in nightly). + pub portable_markers: &'static [&'static str], + /// Top-level entries inside the profile root that, if present, must be directories. + pub folder_only_entries: &'static [&'static str], + /// Additional directories that the profile root must not overlap. + pub extra_forbidden_roots: Vec, +} + +/// Validates the security fence for `root` against `spec`, creates and hardens the profile +/// directory (`0o700` on Unix), verifies recursive containment, and probes writability. +/// +/// Returns the canonicalized profile root path on success. +pub fn validate_and_prepare_root(root: &Path, spec: &AppProfileSpec) -> Result { + let exe_path = std::env::current_exe().ok(); + validate_and_prepare_root_with(root, spec, &SystemEnv, exe_path.as_deref()) +} + +pub(crate) fn validate_and_prepare_root_with( + root: &Path, + spec: &AppProfileSpec, + env: &dyn Env, + exe_path: Option<&Path>, +) -> Result { + validate_lexical_path(root)?; + check_environment(spec, env)?; + check_portable_markers(spec, exe_path)?; + check_no_symlink_components(root)?; + + let forbidden_roots = collect_forbidden_roots(spec, env, exe_path); + check_forbidden_overlaps(root, &forbidden_roots)?; + + let canonical = create_and_harden_root(root)?; + check_no_symlink_components(root)?; + check_forbidden_overlaps(&canonical, &forbidden_roots)?; + check_folder_only_entries(&canonical, spec.folder_only_entries)?; + validate_tree_contents(&canonical)?; + probe_writability(&canonical)?; + + Ok(canonical) +} + +fn validate_lexical_path(root: &Path) -> Result<(), ProfileError> { + if root.as_os_str().is_empty() { + return Err(ProfileError::EmptyProfileRoot); + } + if !root.is_absolute() { + return Err(ProfileError::RelativeProfileRoot(root.to_path_buf())); + } + + let mut has_normal = false; + for component in root.components() { + match component { + Component::ParentDir => return Err(ProfileError::ParentTraversalInProfileRoot(root.to_path_buf())), + Component::Normal(_) => has_normal = true, + Component::Prefix(_) | Component::RootDir | Component::CurDir => {} + } + } + + if !has_normal || root.parent().is_none() { + return Err(ProfileError::FilesystemRootProfile(root.to_path_buf())); + } + Ok(()) +} + +fn check_environment(spec: &AppProfileSpec, env: &dyn Env) -> Result<(), ProfileError> { + for &var in spec.forbidden_env_vars { + if env.var_os(var).is_some() { + return Err(ProfileError::ForbiddenEnvVar(var)); + } + } + + #[cfg(not(target_os = "windows"))] + if let Some(actual) = env.var_os("FLATPAK_ID") { + let expected = nightly_flatpak_id(spec.app_id); + if actual.to_str() != Some(expected.as_str()) { + return Err(ProfileError::MismatchedFlatpakId { actual: actual.to_string_lossy().into_owned(), expected }); + } + } + + Ok(()) +} + +fn check_portable_markers(spec: &AppProfileSpec, exe_path: Option<&Path>) -> Result<(), ProfileError> { + let Some(exe_dir) = exe_path.and_then(Path::parent) else { + return Ok(()); + }; + for &marker in spec.portable_markers { + if marker.is_empty() { + continue; + } + let candidate = exe_dir.join(marker); + if candidate.exists() { + return Err(ProfileError::PortableModeUnsupported { marker, path: candidate }); + } + } + Ok(()) +} + +fn check_no_symlink_components(root: &Path) -> Result<(), ProfileError> { + let mut current = PathBuf::new(); + for component in root.components() { + current.push(component.as_os_str()); + if !matches!(component, Component::Normal(_)) { + continue; + } + match fs::symlink_metadata(¤t) { + Ok(meta) => { + if is_alias(&meta) { + return Err(ProfileError::SymlinkInProfilePath(current)); + } + if !meta.is_dir() { + return Err(ProfileError::NotADirectory(current)); + } + } + Err(err) if err.kind() == io::ErrorKind::NotFound => break, + Err(err) => return Err(ProfileError::Io { path: current, source: err }), + } + } + Ok(()) +} + +fn collect_forbidden_roots(spec: &AppProfileSpec, env: &dyn Env, exe_path: Option<&Path>) -> Vec { + let mut forbidden = Vec::new(); + let bases = stable_os_base_dirs(env); + for base in &bases { + for &name in spec.stable_dir_names { + if !name.is_empty() { + forbidden.push(base.join(name)); + } + } + if !spec.stable_package_id.is_empty() { + forbidden.push(base.join(spec.stable_package_id)); + } + } + + if let Some(exe) = exe_path { + if let Some(parent) = exe.parent() { + forbidden.push(parent.to_path_buf()); + } + for ancestor in exe.ancestors() { + if ancestor.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("app")) { + forbidden.push(ancestor.to_path_buf()); + } + } + } + + forbidden.extend(spec.extra_forbidden_roots.iter().cloned()); + forbidden +} + +fn stable_os_base_dirs(env: &dyn Env) -> Vec { + let mut bases = Vec::new(); + + #[cfg(all(unix, not(target_os = "macos")))] + { + for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] { + if let Some(dir) = non_empty_abs_env(env, key) { + bases.push(dir); + } + } + if let Some(home) = non_empty_abs_env(env, "HOME") { + bases.push(home.join(".config")); + bases.push(home.join(".local").join("share")); + bases.push(home.join(".cache")); + bases.push(home.join(".local").join("state")); + } + } + + #[cfg(target_os = "macos")] + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + bases.push(library.join("Application Support")); + bases.push(library.join("Caches")); + bases.push(library.join("Preferences")); + } + + #[cfg(target_os = "windows")] + { + for key in ["APPDATA", "LOCALAPPDATA"] { + if let Some(dir) = non_empty_abs_env(env, key) { + bases.push(dir); + } + } + if let Some(profile) = non_empty_abs_env(env, "USERPROFILE") { + let app_data = profile.join("AppData"); + bases.push(app_data.join("Roaming")); + bases.push(app_data.join("Local")); + } + } + + #[cfg(not(any(unix, target_os = "windows")))] + let _ = env; + + bases +} + +fn check_forbidden_overlaps(candidate: &Path, forbidden_roots: &[PathBuf]) -> Result<(), ProfileError> { + let norm_candidate = normalize_for_overlap(candidate); + for forbidden in forbidden_roots { + if forbidden.as_os_str().is_empty() { + continue; + } + let norm_forbidden = normalize_for_overlap(forbidden); + if paths_overlap(&norm_candidate, &norm_forbidden) { + return Err(ProfileError::ForbiddenRootOverlap { profile_root: candidate.to_path_buf(), forbidden_root: forbidden.clone() }); + } + } + Ok(()) +} + +fn normalize_for_overlap(path: &Path) -> PathBuf { + let resolved = resolve_existing_prefix(path); + #[cfg(target_os = "windows")] + { + normalize_windows_comparison_path(&resolved) + } + #[cfg(target_os = "macos")] + { + // Conservatively compare case-insensitively even on case-sensitive volumes. + PathBuf::from(resolved.to_string_lossy().to_lowercase()) + } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + { + resolved + } +} + +fn resolve_existing_prefix(path: &Path) -> PathBuf { + if let Ok(canonical) = fs::canonicalize(path) { + return canonical; + } + let mut suffix = Vec::new(); + let mut cursor = path; + while let Some(parent) = cursor.parent() { + if let Some(name) = cursor.file_name() { + suffix.push(name.to_os_string()); + } + if let Ok(mut canonical) = fs::canonicalize(parent) { + for part in suffix.into_iter().rev() { + canonical.push(part); + } + return canonical; + } + cursor = parent; + } + path.to_path_buf() +} + +#[cfg(target_os = "windows")] +fn normalize_windows_comparison_path(path: &Path) -> PathBuf { + let raw = path.to_string_lossy(); + let stripped = if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") { + format!(r"\\{rest}") + } else if let Some(rest) = raw.strip_prefix(r"\\?\") { + rest.to_owned() + } else { + raw.into_owned() + }; + PathBuf::from(stripped.to_lowercase()) +} + +fn paths_overlap(a: &Path, b: &Path) -> bool { + a.starts_with(b) || b.starts_with(a) +} + +fn create_and_harden_root(root: &Path) -> Result { + fs::create_dir_all(root).map_err(|source| ProfileError::Io { path: root.to_path_buf(), source })?; + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let perms = fs::Permissions::from_mode(0o700); + fs::set_permissions(root, perms).map_err(|source| ProfileError::Io { path: root.to_path_buf(), source })?; + } + + let meta = fs::symlink_metadata(root).map_err(|source| ProfileError::Io { path: root.to_path_buf(), source })?; + if is_alias(&meta) { + return Err(ProfileError::SymlinkInProfilePath(root.to_path_buf())); + } + if !meta.is_dir() { + return Err(ProfileError::NotADirectory(root.to_path_buf())); + } + + fs::canonicalize(root).map_err(|source| ProfileError::Io { path: root.to_path_buf(), source }) +} + +fn check_folder_only_entries(canonical: &Path, folder_only_entries: &[&str]) -> Result<(), ProfileError> { + for &entry in folder_only_entries { + if entry.is_empty() { + continue; + } + let path = canonical.join(entry); + match fs::symlink_metadata(&path) { + Ok(meta) if is_alias(&meta) => return Err(ProfileError::SymlinkEntry(path)), + Ok(meta) if !meta.is_dir() => return Err(ProfileError::ExpectedDirectoryEntry(path)), + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(source) => return Err(ProfileError::Io { path, source }), + } + } + Ok(()) +} + +fn validate_tree_contents(canonical: &Path) -> Result<(), ProfileError> { + let mut stack = vec![(canonical.to_path_buf(), 0usize)]; + while let Some((dir, depth)) = stack.pop() { + let entries = fs::read_dir(&dir).map_err(|source| ProfileError::Io { path: dir.clone(), source })?; + for entry_res in entries { + let entry = entry_res.map_err(|source| ProfileError::Io { path: dir.clone(), source })?; + validate_tree_entry(canonical, entry.path(), depth, &mut stack)?; + } + } + Ok(()) +} + +fn validate_tree_entry(canonical: &Path, path: PathBuf, depth: usize, stack: &mut Vec<(PathBuf, usize)>) -> Result<(), ProfileError> { + let meta = fs::symlink_metadata(&path).map_err(|source| ProfileError::Io { path: path.clone(), source })?; + let file_type = meta.file_type(); + if is_alias(&meta) { + return Err(ProfileError::SymlinkEntry(path)); + } + + let entry_canonical = fs::canonicalize(&path).map_err(|source| ProfileError::Io { path: path.clone(), source })?; + if !entry_canonical.starts_with(canonical) { + return Err(ProfileError::PathEscape { path, root: canonical.to_path_buf() }); + } + + if file_type.is_dir() { + if depth >= MAX_WALK_DEPTH { + return Err(ProfileError::MaxDepthExceeded { path, max_depth: MAX_WALK_DEPTH }); + } + stack.push((entry_canonical, depth + 1)); + } else if file_type.is_file() { + check_regular_file_nlink(&path, &meta)?; + } else { + return Err(ProfileError::UnsupportedEntryType(path)); + } + Ok(()) +} + +#[cfg(unix)] +fn check_regular_file_nlink(path: &Path, meta: &fs::Metadata) -> Result<(), ProfileError> { + use std::os::unix::fs::MetadataExt; + let nlink = meta.nlink(); + if nlink != 1 { + return Err(ProfileError::HardlinkedEntry { path: path.to_path_buf(), nlink }); + } + Ok(()) +} + +#[cfg(windows)] +fn check_regular_file_nlink(path: &Path, _meta: &fs::Metadata) -> Result<(), ProfileError> { + use winsafe::{HFILE, co}; + let text = path.to_str().ok_or_else(|| ProfileError::Io { + path: path.to_path_buf(), + source: io::Error::new(io::ErrorKind::InvalidData, "non-textual Windows path"), + })?; + let to_io = |error: winsafe::co::ERROR| ProfileError::Io { path: path.to_path_buf(), source: io::Error::other(error.to_string()) }; + let (handle, _) = HFILE::CreateFile( + text, + // Zero desired access queries file metadata without requiring content read permission. + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(to_io)?; + let info = handle.GetFileInformationByHandle().map_err(to_io)?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT) { + return Err(ProfileError::SymlinkEntry(path.to_path_buf())); + } + let nlink = u64::from(info.nNumberOfLinks); + if nlink != 1 { + return Err(ProfileError::HardlinkedEntry { path: path.to_path_buf(), nlink }); + } + Ok(()) +} + +#[cfg(not(any(unix, windows)))] +fn check_regular_file_nlink(path: &Path, _meta: &fs::Metadata) -> Result<(), ProfileError> { + Err(ProfileError::UnsupportedEntryType(path.to_path_buf())) +} + +fn is_alias(meta: &fs::Metadata) -> bool { + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + // All reparse points, including junctions, are outside the supported profile contract. + meta.file_attributes() & 0x400 != 0 + } + #[cfg(not(windows))] + { + meta.file_type().is_symlink() + } +} + +fn probe_writability(canonical: &Path) -> Result<(), ProfileError> { + let seq = PROBE_COUNTER.fetch_add(1, Ordering::Relaxed); + let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos()); + let probe_name = format!(".craft-nightly-probe-{}-{seq}-{nanos}", std::process::id()); + let probe_path = canonical.join(probe_name); + + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&probe_path) + .map_err(|source| ProfileError::NotWritable { path: canonical.to_path_buf(), source })?; + drop(file); + fs::remove_file(&probe_path).map_err(|source| ProfileError::NotWritable { path: canonical.to_path_buf(), source })?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::fs; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicU64, Ordering}; + + use crate::env::TestEnv; + use crate::error::ProfileError; + use crate::validate::{AppProfileSpec, validate_and_prepare_root_with}; + + static TEST_DIR_COUNTER: AtomicU64 = AtomicU64::new(0); + + struct TempDir { + path: PathBuf, + } + + impl TempDir { + fn new(label: &str) -> Self { + let base = fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let id = TEST_DIR_COUNTER.fetch_add(1, Ordering::Relaxed); + let path = base.join(format!("craft-nightly-test-{label}-{}-{id}", std::process::id())); + fs::create_dir_all(&path).expect("create temp test dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + fn test_spec(extra_forbidden: Vec) -> AppProfileSpec { + AppProfileSpec { + app_id: "photocraft", + display_name: "PhotoCraft", + stable_dir_names: &["photocraft", "PhotoCraft"], + stable_package_id: "ai.storyteller.photocraft", + nightly_package_id: "ai.storyteller.photocraft.nightly", + profile_root_env: Some("PHOTOCRAFT_PROFILE_ROOT"), + forbidden_env_vars: &["PHOTOCRAFT_CONFIG_DIR"], + portable_markers: &["portable.marker"], + folder_only_entries: &["config"], + extra_forbidden_roots: extra_forbidden, + } + } + + fn test_env_with_home(home: &Path) -> TestEnv { + #[cfg(target_os = "windows")] + { + TestEnv::new() + .with_var("USERPROFILE", home) + .with_var("APPDATA", home.join("AppData").join("Roaming")) + .with_var("LOCALAPPDATA", home.join("AppData").join("Local")) + } + #[cfg(not(target_os = "windows"))] + { + TestEnv::new().with_var("HOME", home) + } + } + + #[test] + fn valid_profile_root_is_created_and_hardened() { + let tmp = TempDir::new("valid"); + let home = tmp.path().join("home"); + let profile = tmp.path().join("nightly-profile"); + let spec = test_spec(Vec::new()); + let env = test_env_with_home(&home); + + let canonical = validate_and_prepare_root_with(&profile, &spec, &env, None).expect("valid profile root"); + assert!(canonical.is_dir()); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(&canonical).expect("metadata").permissions().mode() & 0o777; + assert_eq!(mode, 0o700); + } + } + + #[test] + fn rejects_relative_parent_traversal_and_root_paths() { + let tmp = TempDir::new("lexical"); + let home = tmp.path().join("home"); + let spec = test_spec(Vec::new()); + let env = test_env_with_home(&home); + + assert!(matches!(validate_and_prepare_root_with(Path::new(""), &spec, &env, None), Err(ProfileError::EmptyProfileRoot))); + assert!(matches!( + validate_and_prepare_root_with(Path::new("relative/profile"), &spec, &env, None), + Err(ProfileError::RelativeProfileRoot(_)) + )); + assert!(matches!( + validate_and_prepare_root_with(&tmp.path().join("a").join("..").join("b"), &spec, &env, None), + Err(ProfileError::ParentTraversalInProfileRoot(_)) + )); + #[cfg(unix)] + assert!(matches!(validate_and_prepare_root_with(Path::new("/"), &spec, &env, None), Err(ProfileError::FilesystemRootProfile(_)))); + } + + #[test] + fn rejects_stable_dir_overlap_equal_ancestor_and_descendant() { + let tmp = TempDir::new("overlap"); + let home = tmp.path().join("home"); + let env = test_env_with_home(&home); + let spec = test_spec(Vec::new()); + + #[cfg(all(unix, not(target_os = "macos")))] + let stable_dir = home.join(".config").join("photocraft"); + #[cfg(target_os = "macos")] + let stable_dir = home.join("Library").join("Application Support").join("photocraft"); + #[cfg(target_os = "windows")] + let stable_dir = home.join("AppData").join("Roaming").join("photocraft"); + + assert!(matches!(validate_and_prepare_root_with(&stable_dir, &spec, &env, None), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root_with(&stable_dir.join("sub"), &spec, &env, None), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root_with(&home, &spec, &env, None), Err(ProfileError::ForbiddenRootOverlap { .. }))); + } + + #[test] + fn rejects_forbidden_env_vars_and_portable_markers() { + let tmp = TempDir::new("env-portable"); + let home = tmp.path().join("home"); + let profile = tmp.path().join("profile"); + let spec = test_spec(Vec::new()); + + let env_forbidden = test_env_with_home(&home).with_var("PHOTOCRAFT_CONFIG_DIR", "/tmp/bad"); + assert!(matches!( + validate_and_prepare_root_with(&profile, &spec, &env_forbidden, None), + Err(ProfileError::ForbiddenEnvVar("PHOTOCRAFT_CONFIG_DIR")) + )); + + let exe_dir = tmp.path().join("install"); + fs::create_dir_all(&exe_dir).expect("create install dir"); + fs::write(exe_dir.join("portable.marker"), b"").expect("write marker"); + let fake_exe = exe_dir.join("photocraft"); + + let env_ok = test_env_with_home(&home); + assert!(matches!( + validate_and_prepare_root_with(&profile, &spec, &env_ok, Some(&fake_exe)), + Err(ProfileError::PortableModeUnsupported { marker: "portable.marker", .. }) + )); + } + + #[cfg(not(target_os = "windows"))] + #[test] + fn rejects_mismatched_flatpak_id_and_accepts_matching_nightly_flatpak_id() { + let tmp = TempDir::new("flatpak"); + let home = tmp.path().join("home"); + let profile = tmp.path().join("profile"); + let spec = test_spec(Vec::new()); + + let bad_env = test_env_with_home(&home).with_var("FLATPAK_ID", "ai.storyteller.photocraft"); + assert!(matches!(validate_and_prepare_root_with(&profile, &spec, &bad_env, None), Err(ProfileError::MismatchedFlatpakId { .. }))); + + let good_env = test_env_with_home(&home).with_var("FLATPAK_ID", "ai.storyteller.photocraft.nightly"); + assert!(validate_and_prepare_root_with(&profile, &spec, &good_env, None).is_ok()); + } + + #[cfg(unix)] + #[test] + fn rejects_symlink_escape_and_hardlinked_file() { + use std::os::unix::fs::symlink; + + let tmp = TempDir::new("symlink"); + let home = tmp.path().join("home"); + let outside = tmp.path().join("outside"); + fs::create_dir_all(&outside).expect("create outside"); + let outside_file = outside.join("secret.txt"); + fs::write(&outside_file, b"secret").expect("write outside file"); + + let env = test_env_with_home(&home); + let spec = test_spec(Vec::new()); + + // Symlink as profile root component + let link_root = tmp.path().join("link-profile"); + symlink(&outside, &link_root).expect("create root symlink"); + assert!(matches!(validate_and_prepare_root_with(&link_root, &spec, &env, None), Err(ProfileError::SymlinkInProfilePath(_)))); + + // Symlink inside profile root + let profile_with_symlink = tmp.path().join("profile-inner-symlink"); + fs::create_dir_all(&profile_with_symlink).expect("create profile"); + symlink(&outside_file, profile_with_symlink.join("escape")).expect("create inner symlink"); + assert!(matches!(validate_and_prepare_root_with(&profile_with_symlink, &spec, &env, None), Err(ProfileError::SymlinkEntry(_)))); + + // Hardlink inside profile root + let profile_with_hardlink = tmp.path().join("profile-hardlink"); + fs::create_dir_all(&profile_with_hardlink).expect("create hardlink profile"); + fs::hard_link(&outside_file, profile_with_hardlink.join("hardlinked.txt")).expect("create hardlink"); + assert!(matches!( + validate_and_prepare_root_with(&profile_with_hardlink, &spec, &env, None), + Err(ProfileError::HardlinkedEntry { nlink: 2, .. }) + )); + } + + #[test] + fn rejects_file_where_folder_only_entry_is_required() { + let tmp = TempDir::new("folder-only"); + let home = tmp.path().join("home"); + let profile = tmp.path().join("profile"); + fs::create_dir_all(&profile).expect("create profile"); + fs::write(profile.join("config"), b"not a directory").expect("write file"); + + let spec = test_spec(Vec::new()); + let env = test_env_with_home(&home); + assert!(matches!(validate_and_prepare_root_with(&profile, &spec, &env, None), Err(ProfileError::ExpectedDirectoryEntry(_)))); + } +} diff --git a/crates/pages/src/ui/column_bar.rs b/crates/pages/src/ui/column_bar.rs index 0d1c87e50f..270b0d2868 100644 --- a/crates/pages/src/ui/column_bar.rs +++ b/crates/pages/src/ui/column_bar.rs @@ -247,9 +247,12 @@ impl Component for ColumnBar<'_> { if cx.part(part).press.double_pressed() { self.double_clicked = Some(*at as usize); } - match divider::pointer(cx, DIVIDER, *at, divider) { - Some(Drag::Start) => cx.begin(), - Some(Drag::To(x)) => cx.propose(resized(&widths, *at as usize, x - rect.left(), width)), + let dragged = divider::pointer(cx, DIVIDER, *at, divider); + if let Some(Drag::Start(_)) = dragged { + cx.begin(); + } + match dragged { + Some(Drag::Start(x) | Drag::To(x)) => cx.propose(resized(&widths, *at as usize, x - rect.left(), width)), Some(Drag::Release) => cx.commit(), _ => {} } diff --git a/crates/pages/src/ui/margins.rs b/crates/pages/src/ui/margins.rs index 4325c9ab31..6618bfa3db 100644 --- a/crates/pages/src/ui/margins.rs +++ b/crates/pages/src/ui/margins.rs @@ -479,16 +479,17 @@ impl Component for MarginHandles<'_> { let snap = if press.mods.alt { 0.0 } else { self.snap }; let origin = if visible.horizontal() { self.page.rect.min.x } else { self.page.rect.min.y }; let dragged = divider::pointer(cx, EDGE, visible.index(), ÷r); + if let Some(Drag::Start(_)) = dragged { + *cx.press_slot::() = Some(Anchor(edges)); + cx.begin(); + } + // The drag's start moves the edge as each later move does, in the same pass. match dragged { - Some(Drag::Start) => { - *cx.press_slot::() = Some(Anchor(edges)); - cx.begin(); - } - Some(Drag::To(coord)) => { + Some(Drag::Start(coord) | Drag::To(coord)) => { let anchor = cx.press_slot::().map_or(edges, |anchor| anchor.0); let change = dragged_margin(visible, f64::from(coord - origin) / scale, &self.rules(anchor, snap)); cx.propose(anchor.with(change)); - if let PressPhase::Drag { pos, .. } = press.phase { + if let PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } = press.phase { let name = visible.name(&words).clone(); readout(cx, pos, &[(name, self.shown(&units, change.points))]); } diff --git a/crates/ui-canvas/src/canvas/split/mod.rs b/crates/ui-canvas/src/canvas/split/mod.rs index d2639e109f..8932f62963 100644 --- a/crates/ui-canvas/src/canvas/split/mod.rs +++ b/crates/ui-canvas/src/canvas/split/mod.rs @@ -457,9 +457,12 @@ impl SplitViews<'_, D> { fn resize(cx: &mut Cx<'_, SplitViews<'_, D>>, at: &SplitAt, laid: &Laid, dividers: &[Divider]) { let rect = cx.rect; for (index, divider) in dividers.iter().enumerate() { - match divider::pointer(cx, DIVIDER, index as u64, divider) { - Some(Drag::Start) => cx.begin(), - Some(Drag::To(coord)) => cx.propose(moved(laid, index, divider, coord, rect)), + let dragged = divider::pointer(cx, DIVIDER, index as u64, divider); + if let Some(Drag::Start(_)) = dragged { + cx.begin(); + } + match dragged { + Some(Drag::Start(coord) | Drag::To(coord)) => cx.propose(moved(laid, index, divider, coord, rect)), Some(Drag::Release) => cx.commit(), None => {} } diff --git a/crates/ui-canvas/src/canvas/tool.rs b/crates/ui-canvas/src/canvas/tool.rs index 98189fd202..ff15b4f1c9 100644 --- a/crates/ui-canvas/src/canvas/tool.rs +++ b/crates/ui-canvas/src/canvas/tool.rs @@ -498,6 +498,13 @@ impl<'a> ToolContext<'a> { self.snap.map_or(point, |snap| snap.point(point, self.mods, super::GestureSnap::default().kinds(kinds)).0) } + /// Whether the canvas snaps to the document bounds now: snapping on and not suspended by its key, with View > Snap + /// To > Document Bounds on. A tool's own rule about the bounds follows it (a Perspective Crop box pressed beyond a + /// document corner starts at that corner). + pub fn snaps_to_document_bounds(&self) -> bool { + self.snap.is_some_and(|snap| snap.options().document_bounds && snap.reach(self.mods, false).is_some()) + } + /// The coordinate `position` across a guide that would run along `along`, snapped as [`snap`](Self::snap) does: /// an x coordinate is across `Axis::Y`. pub fn snap_along(&self, along: Axis, position: f64) -> f64 { diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index 52b929dba4..c810c43890 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -5,6 +5,7 @@ use craft_behavior::geometry::{SnapKind, SnapLine, SnapOptions, SnapTarget, Snap use craft_behavior::kurbo::{Point, Size}; use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GesturePhase, PointerButton, PointerKind, PointerSample}; use craft_keymap::Mods; +use craft_ui::buttons::Button; use craft_ui::canvas::{ Autoscroll, Canvas, CanvasScrollbars, CanvasTool, ContextRequest, CropOverlay, HandTool, Momentary, MomentaryCommands, MomentaryTool, NavigationOptions, Snap, StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer, ToolRegion, @@ -17,6 +18,7 @@ use craft_ui::contract::{ }; use craft_ui::dialog::Dialog; use craft_ui::display::Text; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::primitives::Draw; use craft_ui::runtime::access::Role; use craft_ui::runtime::commands::{CommandGate, CommandSet as _}; @@ -1927,6 +1929,52 @@ fn menu_canvas(momentary: bool, bars: bool) -> MenuRig { (fixture, contexts, view, rect) } +/// A right-click on the canvas while another control's context menu is open closes that menu and reaches the canvas, +/// which asks for its own menu where the button came up, as a second right-click does in a native app: only a primary +/// press outside a menu goes no further. +#[trial] +fn a_right_click_on_the_canvas_closes_another_context_menu_and_asks_for_the_canvas_menu() { + const OPENER: Rect = Rect { min: Pos2::new(8.0, 8.0), max: Pos2::new(120.0, 32.0) }; + let (contexts, rect) = (Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(Rect::NOTHING))); + let (shown_contexts, shown_rect, shown_view) = (Rc::clone(&contexts), Rc::clone(&rect), Cell::new(None::)); + let mut hand = HandTool::new(NavigationOptions::default()); + let mut fixture = Fixture::new(move |ui| { + let layers = Button::new("Layers").show_at(ui, OPENER); + Menu::context("Layers menu", &layers).show(ui, |ui, _| { + MenuItem::new("Duplicate layer").show(ui); + }); + // The canvas fills the right half of the window, clear of the opener and of the menu it opens. + let room = ui.max_rect(); + let room = Rect::from_min_max(Pos2::new(room.center().x, room.min.y), room.max); + let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 4.0)); + shown_rect.set(room); + let mut reply = None; + let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, room, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + reply = Some(ToolHost::new().run(ui, &pass, &mut hand)); + } + }); + let reply = reply.unwrap_or_default(); + shown_contexts.borrow_mut().extend(reply.context); + shown_view.set(Some(reply.view.or(shown.output.view).unwrap_or(current))); + }); + fixture.settle(); + let right_click = |fixture: &mut Fixture, at: Pos2| { + fixture.frame(vec![pointer::moved(at)]).frame(vec![pointer::secondary(at, true)]).frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + }; + let opener = fixture.by_label("Layers").expect("the opener has a node").center(); + right_click(&mut fixture, opener); + let menu = fixture.by_role(Role::MENU).first().map(|menu| menu.rect).expect("the right-click on Layers opens its menu"); + let at = rect.get().center(); + assert!(!menu.contains(at), "the canvas point lies outside the menu: {menu:?} {at:?}"); + assert!(contexts.borrow().is_empty(), "the canvas was not asked yet: {:?}", contexts.borrow()); + right_click(&mut fixture, at); + assert!(fixture.by_label("Duplicate layer").is_none(), "the right-click on the canvas closed the Layers menu"); + let asked = contexts.borrow().iter().map(|request| request.at).collect::>(); + assert_eq!(asked, [at], "the secondary press reached the canvas, which asks for its menu where it came up"); +} + #[trial] fn a_drag_past_the_canvas_edge_scrolls_the_view_and_a_turned_view_scrolls_on_the_clipped_axis() { for (rotation, upright) in [(0.0, true), (90.0, false)] { diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index bf269192e0..c179040c7e 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -27,7 +27,8 @@ use std::sync::Arc; pub struct Activation { /// By `Intent::Activate` (Enter, Space or an AccessKit click) rather than a primary click. pub by_key: bool, - /// The modifiers held at the activation: with the click for a pointer activation, in the pass for a key or AccessKit one. + /// The modifiers held at the activation: those of the click's release, latched ones included, for a pointer + /// activation; those held in the pass for a key or AccessKit one. pub mods: craft_keymap::Mods, } diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index 466fead62e..08fb5d23fb 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -274,6 +274,9 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { page_reveal: Option, /// The row this pass scrolls into view, placed before the rows are built (`place_reveal`). revealing: Option, + /// The row an AccessKit Scroll Into View brings into the collection's own view this pass: once placed, its visible + /// piece goes to the scroll owner around the collection (`content`), as a scroll body passes a reveal on. + reveal_around: Option, /// The row the collection's own press is held on this pass, and where on it. pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. @@ -341,6 +344,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { drags: Drags::default(), page_reveal: None, revealing: None, + reveal_around: None, lead_at_read: None, renaming_at_read: None, pressed: None, diff --git a/crates/ui-contract/src/contract/items/access.rs b/crates/ui-contract/src/contract/items/access.rs index 1684490e5c..62c1323d22 100644 --- a/crates/ui-contract/src/contract/items/access.rs +++ b/crates/ui-contract/src/contract/items/access.rs @@ -77,10 +77,11 @@ impl ItemsHooks<'_, '_, C> { access::report_sub(ctx, &decl); } - /// AccessKit requests on an item row's node or on a section row's collection node (`report_section_node`), while the - /// collection is enabled: Focus moves the lead to the row and key focus to the collection; Click also picks an item and - /// activates it when the collection activates on click, or activates a section it does not select. Expand and - /// Collapse open and close rows with children. + /// AccessKit requests on an item or section row's collection node (`report_section_node`), while the collection + /// and row are enabled: Focus moves the lead to the row and key focus to the collection; Click also picks an item + /// and activates it when the collection activates on click, or activates a section it does not select. Expand and + /// Collapse open and close rows with children. Scroll Into View brings the row into view without moving the lead or + /// focus. If the collection scrolls itself, the outer scroll owner then shows the row's visible piece. pub(super) fn node_by_access( &mut self, comp: &C, @@ -135,6 +136,12 @@ impl ItemsHooks<'_, '_, C> { } } } + AccessAction::ScrollIntoView => { + self.reveal_with(layout, at); + if self.scrolls { + self.reveal_around = Some(at); + } + } AccessAction::Expand | AccessAction::Collapse => { let open = request.action == AccessAction::Expand; if self.source.has_children(at) && self.source.open(at) != open { diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 1d05b1821a..c58a729ac8 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -254,7 +254,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { if cx.core.resolved.enabled && let Some(taker) = WheelTaker::for_sense(cx.core.id, cx.core.rect, crate::contract::Component::sense(comp)) { - wheel::register(&cx.core.ctx, taker.notch(self.notch).gated(cx.core.env.wheel() == WheelScope::Gated)); + wheel::register(&cx.core.ctx, taker.notch(self.notch).gated(taker.gated || cx.core.env.wheel() == WheelScope::Gated)); } } else if self.scrolls { // The taker covers the whole collection, header row and frame included: the wheel over the header scrolls @@ -410,6 +410,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { crate::runtime::egui::repaint::request(&ctx); } let offset = ScrollPos { x: self.offset_x, y: self.offset }; + if let Some(at) = self.reveal_around.take().filter(|&at| layout.shown(at)) { + cx.core.reveal = Some(self.screen(&layout, rect, at, offset, rtl).intersect(rect)); + } Arc::make_mut(&mut layout).set_view(rect.size(), offset); if self.scrolls { note_scroll_regions(ui, rect, self.content, offset, rtl, self.header.view()); diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index f44d7eb0fb..a7169384ea 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -58,6 +58,9 @@ impl ItemsHooks<'_, '_, C> { if layout.mirrors() && rtl { flow.to_physical(Rect::from_min_size(at, Vec2::ZERO)).min } else { at } }; let mods_now = crate::runtime::pointer::frame_raw(&ctx).mods; + // What a click decides and reports reads the modifiers of its release, which a quick click can let go of in the + // same frame. + let click_mods = crate::runtime::pointer::frame_raw(&ctx).pick_mods; // A click on a row the collection does not take (a caption, a disabled row) is no pick: the layers around the // collection (a dropdown's list) stay open. if cx.core.activation.as_ref().is_some_and(|activation| !activation.by_key) @@ -233,7 +236,7 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = layout.hit(local(start.origin), offset).filter(|&at| self.source.enabled(at) && layout.shown(at)) { // A modified click is a command on the thumbnail (load as selection, and so on), not a pick. - let mods = crate::runtime::pointer::frame_raw(&ctx).mods; + let mods = click_mods; if !(mods.shift || mods.cmd || mods.alt) { if !self.keeps_pick(at, start.clicks) { self.click_pick(comp, at, false, false, mods); @@ -248,7 +251,7 @@ impl ItemsHooks<'_, '_, C> { && click && let Some(at) = self.index_of(&key) { - self.click_pick(comp, at, false, false, mods_now); + self.click_pick(comp, at, false, false, click_mods); } if click && props.menu_on_click @@ -276,7 +279,7 @@ impl ItemsHooks<'_, '_, C> { && click && self.index_of(&key).is_some() { - self.events.push(CollectionEvent::CommandClick { key, mods: mods_now }); + self.events.push(CollectionEvent::CommandClick { key, mods: click_mods }); } // The press machine makes a middle release a click only for a collection that senses `MIDDLE_CLICK`. if click @@ -299,9 +302,9 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = self.index_of(&key) { if Self::select_mode(comp) == SelectMode::Single { - self.change_by(SelectionChange::Clear, PickBy::Pointer(mods_now)); + self.change_by(SelectionChange::Clear, PickBy::Pointer(click_mods)); } else { - self.click_pick(comp, at, false, false, mods_now); + self.click_pick(comp, at, false, false, click_mods); } } } @@ -349,8 +352,8 @@ impl ItemsHooks<'_, '_, C> { if !props.primary_picks && !self.holds(at) && self.toggle_cell(props, layout, at, offset, local(pos)).is_none() { let column = if Self::selects_cells(comp) { layout.column_at(local(pos), offset) } else { None }; match column { - Some(column) => self.cell_press(comp, layout, at, column, released.mods), - None => self.pick_by(comp, at, false, false, PickBy::Pointer(released.mods)), + Some(column) => self.cell_press(comp, layout, at, column, released.pick_mods), + None => self.pick_by(comp, at, false, false, PickBy::Pointer(released.pick_mods)), } } self.move_lead(at, LeadSource::Pointer); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 5bbb950eb0..5838a2cddf 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -57,7 +57,9 @@ use std::sync::Arc; /// window facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the requests to collections, /// the scroll view of a nested `Lazy`): a change of one runs only the views that read it; /// - the clock, read through `frame::stepped_clock`: the view runs at the next step; -/// - commands sent to a command scope instance inside it: it runs while one waits. +/// - commands sent to a command scope instance inside it: it runs while one waits; +/// - whether an inspected region is open around it (`runtime::inspect`), since only a run inside a region records +/// the steps a replay adds to it. /// /// Its key is also its content's version: a container inside measures under it, so a run with a new key measures its /// bodies afresh, in the first pass, instead of taking what they measured under the last key. A run with the same key @@ -182,6 +184,8 @@ impl MemoVie let mut key = MemoKey::of_view(ctx); key.feed_hash(&P::identity()); key.write(&(show as usize).to_le_bytes()); + // A run inside an inspected region records the steps that a replay adds to the region. + key.write(&[u8::from(crate::runtime::inspect::recording(ctx))]); let (scope, scope_follows) = env.scope_key(); key.write(&scope.to_le_bytes()); props.key(&mut key); diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 2e73cd8f88..627f6a5e87 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -34,9 +34,12 @@ pub(super) fn dismissal( if dismiss.anchor_gone && layer.overlay.opener.as_ref().is_some_and(|first| !first.active(ctx, None).0.enabled) { return Some(CloseReason::AnchorGone); } - // The input hook removed the press and recorded it; presses inside the family and its anchors never get here. + // The input hook recorded the press (and removed a primary one) as the lone point it landed on; the record stands + // for the layers the pass already had, and presses inside the family and its anchors never get here. if dismiss.outside == Outside::Absorb { - if overlay::absorbed_press(ctx).is_some() { + // A layer that appears in this pass opened after the press was made, so the press is not outside it: `opening` + // is what tells it from the layers the record stands for. + if overlay::absorbed_press(ctx).is_some() && !overlay::opening(ctx, layer.id) { return Some(CloseReason::Outside); } } else if press_outside(ctx, layer, rect, anchor) { diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 290231d08f..6357f13eba 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -23,7 +23,8 @@ pub enum Outside { Close, /// Nothing. Keep, - /// Closes the layer and the press reaches nothing below. + /// Closes the layer. A primary press reaches nothing below; a secondary or middle press goes on to the widget + /// below, so a right-click elsewhere closes a menu and opens the menu there. Absorb, } @@ -272,7 +273,7 @@ impl Overlay { overlay } - /// A menu: a popup the arrow keys move through. A press outside closes it and goes no further. + /// A menu: a popup the arrow keys move through. A press outside closes it, and a primary one goes no further. pub fn menu() -> Overlay { let mut overlay = Overlay::base(Rank::Popup, Overlay::below(), OverlayFit::Content, OwnerClass::Menu, FocusPolicy::MENU); overlay.dismiss = Dismiss::new().outside(Outside::Absorb); diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 66ca1003c5..828ff5d754 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -803,7 +803,10 @@ fn declared_with(parts: &PartsStep, has: impl Fn(&super::cx::PartExtras) -> bool } /// The activation this pass: none for a component that takes none; a key or AccessKit activation of a member -/// (`keyed`); else the click, or the release of a press that opened a popup and ended over this row. +/// (`keyed`); else the click, or the release of a press that opened a popup and ended over this row. A pointer +/// activation carries the modifiers of the release that ended the primary press (`PointerFrame::click_mods`), not the +/// ones still held when the pass runs: an Alt-click whose Alt goes up in the same frame is an Alt-click, and another +/// button's release later in that pass does not take its modifiers. fn activation_of(ctx: &Context, ui: &Ui, rect: Rect, resolved: &Resolved<'_>, keyed: bool, root_sense: Sense, clicked: bool) -> Option { if !steps::takes_activation(resolved) { return None; @@ -819,7 +822,7 @@ fn activation_of(ctx: &Context, ui: &Ui, rect: Rect, resolved: &Resolved<'_>, ke ); (clicked || released).then(|| Activation { by_key: false, - mods: crate::runtime::pointer::with_frame(ctx, |frame, _| frame.map_or(craft_keymap::Mods::NONE, |frame| frame.mods)), + mods: crate::runtime::pointer::with_frame(ctx, |frame, _| frame.map_or(craft_keymap::Mods::NONE, |frame| frame.click_mods)), }) } @@ -1048,7 +1051,7 @@ fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, (host_at, place): (Option< }; if !inert && registers { let sensed = craft_behavior::WheelTaker::for_sense(id, rect, own).map(|taker| taker.notch(e.wheel_notch())); - steps::register_wheel(&ctx, id, rect, sensed, e.bound().0 && !facts.binds_view, facts.text(), env.wheel); + steps::register_wheel(&ctx, sensed, e.bound().0 && !facts.binds_view, facts.text(), env.wheel); } // 8 sense p.trace.mark(Step::Sense); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index d0c8c8c0bf..124937a11b 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -789,10 +789,12 @@ pub(crate) fn paint_face( #[cfg(feature = "testing")] crate::runtime::measure::count_access_build(&ctx); face.access(&mut access, &cx); + // A face that names itself (a `Kbd` by its chord spoken) names its part's sub-node so, as it would its own node; + // a face that declares no text is named by its label, the full text when elided. + let label = || crate::runtime::access::Name::Text(cx.core.paint.borrow().elided.clone().unwrap_or_else(|| step1.label.as_str().to_owned())); let name = match access.name { - crate::runtime::access::Name::FromLabel => { - crate::runtime::access::Name::Text(cx.core.paint.borrow().elided.clone().unwrap_or_else(|| step1.label.as_str().to_owned())) - } + crate::runtime::access::Name::FromLabel => label(), + crate::runtime::access::Name::Text(text) if text.is_empty() => label(), name => name, }; let record = FaceRecord { diff --git a/crates/ui-contract/src/contract/steps/scroll_owner.rs b/crates/ui-contract/src/contract/steps/scroll_owner.rs index edd8dfe9fb..c652de460d 100644 --- a/crates/ui-contract/src/contract/steps/scroll_owner.rs +++ b/crates/ui-contract/src/contract/steps/scroll_owner.rs @@ -7,8 +7,9 @@ use craft_behavior::{MoveMods, NavMove}; use egui::{Context, Id, Rect, Vec2}; /// What the component left untaken that a scroll region serves: page and end moves go to the innermost scroll -/// owner around the component, and an AccessKit request to show the component reveals its rect there. Both are -/// applied at the owner's step 4 of the next pass. +/// owner around the component, and an AccessKit request to show the component, or one of its parts, reveals the +/// component's rect, or the part's, there, as focus on it does. Both are applied at the owner's step 4 of the next +/// pass. pub(super) fn route_to_scroll_owner(core: &mut CxCore<'_>) { let scrolls = |mv: NavMove, _| matches!(mv, NavMove::PageUp | NavMove::PageDown | NavMove::Start | NavMove::End); let mut moves = Vec::new(); @@ -24,14 +25,29 @@ pub(super) fn route_to_scroll_owner(core: &mut CxCore<'_>) { while let Some(mv) = core.intents.take_move_where(scrolls) { moves.push(mv); } - let reveal = core.intents.take_scroll_access(true).is_some(); - if moves.is_empty() && !reveal { + let reveal = match core.intents.take_scroll_access(true) { + Some(_) => Some(core.rect), + None => { + // A part's Scroll Into View: a part the component declared this pass shows its own rect. + let results = &core.results; + let shows_part = |request: &craft_behavior::AccessRequest| { + request.action == craft_behavior::AccessAction::ScrollIntoView + && request.target.is_some_and(|part| results.contains_key(&(part.key, part.index))) + }; + core.intents + .take_access_where(shows_part) + .and_then(|request| request.target) + .and_then(|part| results.get(&(part.key, part.index))) + .map(|result| result.rect) + } + }; + if moves.is_empty() && reveal.is_none() { return; } let Some(owner) = core.env.scroll_owner() else { return }; pass_state::with::(&core.ctx, |queue| queue.0.extend(moves.into_iter().map(|(mv, mods)| (owner, mv, mods, false)))); - if reveal { - pass_state::with::(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(core.rect) })); + if let Some(rect) = reveal { + pass_state::with::(&core.ctx, |reveals| reveals.0.push(Reveal { owner, to: RevealTo::Rect(rect) })); } repaint::request(&core.ctx); } diff --git a/crates/ui-contract/src/contract/steps/sense.rs b/crates/ui-contract/src/contract/steps/sense.rs index b62685d339..91b316d879 100644 --- a/crates/ui-contract/src/contract/steps/sense.rs +++ b/crates/ui-contract/src/contract/steps/sense.rs @@ -4,42 +4,35 @@ use crate::runtime::env::WheelScope; use crate::runtime::wheel; use crate::style::{Flags, StateSet}; use craft_theme::{State, StateMix}; -use egui::{Context, Id, Rect}; +use egui::{Context, Id}; /// Registers a wheel taker for next pass's split (8.6): `sensed`, the taker the wheel bits of the component's sense -/// make (`WheelTaker::for_sense`). Every value control is a `WheelTaker::value` taker, in any scope: a wheel gesture it -/// owns ends with a `WheelPhase::End` share. A value control with a text part that steps by the wheel (it senses a -/// wheel axis: a number field) is a field (`WheelTaker::field`), which takes the plain wheel while focused wherever the -/// pointer is; a text field that does not step leaves the wheel over the rest of the window to what is there. A value -/// control takes the wheel only while focused or armed, on the axes it senses (the vertical one when it senses none); -/// inside a `WheelScope::Free` scope one that senses the wheel takes it without focus. A value control that steps by -/// the wheel declares the axis it steps in its sense, so a free scope frees it; one that does not step keeps the -/// fallback and stays gated. Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that -/// takes no axis itself waits only for a gated scope: its wheel goes to the view around it. -pub(crate) fn register_wheel( - ctx: &Context, - id: Id, - rect: Rect, - sensed: Option>, - value_control: bool, - text: bool, - scope: WheelScope, -) { - let free = sensed.is_some() && scope == WheelScope::Free; - let directional = sensed.is_some() && value_control && scope == WheelScope::Directional; - let zone = sensed.is_some_and(|taker| taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom)); - let taker = sensed.or_else(|| value_control.then(|| craft_behavior::WheelTaker::new(id, rect).vertical(true))); - if let Some(taker) = taker { - wheel::register( - ctx, - taker - .value(value_control) - .field(value_control && text && sensed.is_some()) - .gated(scope == WheelScope::Gated || (value_control && !free && !zone)) - .horizontal(taker.horizontal || directional) - .directional(directional), - ); - } +/// make (`WheelTaker::for_sense`). A component that senses no wheel bit takes no wheel, value control or not: the wheel +/// over a focused check box or text field scrolls the region around it, as native controls do, and a multi-line text +/// part whose text overflows registers its own scroll taker (`text_adapter`), which passes the wheel on at its ends. +/// Every value control that takes the wheel is a `WheelTaker::value` taker, in any scope: a wheel gesture it owns ends +/// with a `WheelPhase::End` share. A value control with a text part that steps by the wheel (a number field) is a field +/// (`WheelTaker::field`), which takes the plain wheel while focused wherever the pointer is. A value control takes the +/// wheel only while focused or armed, on the axes it senses; inside a `WheelScope::Free` scope one that senses the +/// wheel takes it without focus, unless it senses `Sense::WHEEL_Y_FOCUSED`, which no scope frees (a range whose wheel +/// steps its focused thumb). Inside a `WheelScope::Gated` scope every taker waits for focus or arming. A zoom zone that +/// takes no axis itself waits only for a gated scope: its wheel goes to the view around it. In a +/// `WheelScope::Directional` scope, a value control that senses the wheel also takes horizontal intent, and takes +/// vertical intent only while armed. +pub(crate) fn register_wheel(ctx: &Context, sensed: Option>, value_control: bool, text: bool, scope: WheelScope) { + let Some(taker) = sensed else { return }; + let free = !taker.gated && scope == WheelScope::Free; + let directional = value_control && scope == WheelScope::Directional; + let zone = taker.zooms_view && !(taker.horizontal || taker.vertical || taker.zoom); + wheel::register( + ctx, + taker + .value(value_control) + .field(value_control && text) + .gated(taker.gated || scope == WheelScope::Gated || (value_control && !free && !zone)) + .horizontal(taker.horizontal || directional) + .directional(directional), + ); } /// The part states: each part's press and hover from the sensing core, with its own flags. diff --git a/crates/ui-contract/src/primitives/record.rs b/crates/ui-contract/src/primitives/record.rs index b4ed185dda..7b825f5d9d 100644 --- a/crates/ui-contract/src/primitives/record.rs +++ b/crates/ui-contract/src/primitives/record.rs @@ -54,7 +54,8 @@ impl std::fmt::Debug for Adopted { pub struct FaceRecord { /// The part the face looks for. pub part: PartRef, - /// The face's declared accessible name, or its resolved label when it declares none. + /// The name the face's `access` declared (a `Kbd` names itself by its chord spoken), with `Name::FromLabel` and an + /// empty text resolved to the instance's label, the full text when elided. pub name: crate::runtime::access::Name, /// The face's value flags. pub flags: crate::style::Flags, diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 68062ea037..cc84465613 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -119,6 +119,18 @@ pub enum Name { Decorative, } +impl Name { + /// The text the name gives itself: a `Text`'s, or a `Joined`'s texts joined with a comma. `None` for a name taken + /// from a label or another node, and for no name. + pub(crate) fn own_text(&self) -> Option { + match self { + Name::Text(text) => Some(text.clone()), + Name::Joined(parts) => Some(parts.join(", ")), + Name::FromLabel | Name::LabelledBy(_) | Name::Decorative => None, + } + } +} + /// A numeric value. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index aaec987e45..9f368e19bd 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -111,8 +111,7 @@ struct Named { fn named(name: &Name, label: &str, fallbacks: &[Option<&str>]) -> Named { let (text, labelled_by, hidden) = match name { Name::FromLabel => (label.to_owned(), Vec::new(), false), - Name::Text(text) => (text.clone(), Vec::new(), false), - Name::Joined(parts) => (parts.join(", "), Vec::new(), false), + Name::Text(_) | Name::Joined(_) => (name.own_text().unwrap_or_default(), Vec::new(), false), Name::LabelledBy(id) => (String::new(), vec![*id], false), Name::Decorative => (String::new(), Vec::new(), true), }; diff --git a/crates/ui-contract/src/runtime/access/text.rs b/crates/ui-contract/src/runtime/access/text.rs index 00e96fa06f..b1056e016f 100644 --- a/crates/ui-contract/src/runtime/access/text.rs +++ b/crates/ui-contract/src/runtime/access/text.rs @@ -136,6 +136,11 @@ pub(crate) fn report_text(ctx: &Context, owner: Id, facts: &TextFacts, unit: Opt facts.text.clone() } }); + if let Some(value) = value.as_deref() + && crate::runtime::inspect::recording(ctx) + { + crate::runtime::inspect::note_text_value(ctx, owner, value); + } adapter::write_text(ctx, owner, &TextNode { value: value.as_deref(), editable: facts.editable, disabled: facts.disabled, selection }); // The owner's node, registered with its common facts, is disabled with the text part it stands for. if facts.disabled { diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index b427d3c792..a2db51cffc 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -324,6 +324,9 @@ pub(crate) struct PointerRead { pub release: Option, /// Where the pass's last button release went up, and its modifiers. pub released_at: Option<(Pos2, Mods)>, + /// The modifiers of the release that ended the primary press, whatever else went up in the pass after it: a + /// primary click reads these. + pub click_mods: Option, /// The last press of a button other than the primary one: the button and where it went down. pub other_press: Option<(PointerButton, Pos2)>, /// Whether the primary button went down in this pass. @@ -399,6 +402,7 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead { let mut touch_sample = None; let mut release = None; let mut released_at = None; + let mut click_mods = None; let mut touches = Vec::new(); let mut other_press = None; let mut rotation = 0.0; @@ -449,10 +453,14 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead { Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => { released_at = Some((*pos, Mods::from_egui(modifiers, os))); if barrel_press { + // The contact that ends here was the barrel's, whose press went down as the secondary one. barrel_press = false; release = Some(PointerButton::Secondary); events.push(PointerEvent::released_by(PointerButton::Secondary, *pos)); } else { + // The primary press ends here, so a click of it reads this release's modifiers even when + // another button's release overwrites `released_at` in the same pass. + click_mods = Some(Mods::from_egui(modifiers, os)); release = Some(PointerButton::Primary); events.push(PointerEvent::released(*pos)); } @@ -517,6 +525,7 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead { buttons, release, released_at, + click_mods, touches, other_press, primary_pressed: input.pointer.primary_pressed() && !barrel_pressed, diff --git a/crates/ui-contract/src/runtime/egui/memory.rs b/crates/ui-contract/src/runtime/egui/memory.rs index 35e36dda3c..505e76ac55 100644 --- a/crates/ui-contract/src/runtime/egui/memory.rs +++ b/crates/ui-contract/src/runtime/egui/memory.rs @@ -3,7 +3,7 @@ use egui::util::IdTypeMap; use egui::util::id_type_map::RawKey; use egui::{Context, Id}; -use std::any::Any; +use std::any::{Any, TypeId}; use std::collections::HashMap; use std::hash::{BuildHasherDefault, Hash, Hasher}; use std::sync::{Arc, Mutex, OnceLock, PoisonError}; @@ -170,14 +170,98 @@ pub fn service_lookups() -> u64 { LOOKUPS.with(std::cell::Cell::get) } +/// The context data slot every service sits under, one per type. +fn service_slot() -> Id { + static SLOT: OnceLock = OnceLock::new(); + *SLOT.get_or_init(|| unique("craft_ui.service")) +} + +/// How to move one service type's handle out of context data and back: every type a context created, so +/// [`keep_own_services`] can tell runtime state from the rest of a context's data. +#[derive(Clone, Copy)] +struct Kind { + take: fn(&mut Map) -> Option, + put: fn(&mut Map, Removed) -> Option, +} + +fn kinds() -> &'static Mutex> { + static KINDS: OnceLock>> = OnceLock::new(); + KINDS.get_or_init(Mutex::default) +} + +fn take_service(data: &mut Map) -> Option { + take_raw::>(data, service_slot()) +} + +fn put_service(data: &mut Map, handle: Removed) -> Option { + match handle.downcast::>() { + Ok(handle) => put_boxed(data, service_slot(), handle), + Err(other) => Some(other), + } +} + +/// Whether `from` and `to` are one context: two handles to the same egui `Context` share their data, so a fork would +/// copy a context onto itself and detach the original's own state instead of a copy's. +/// +/// `Context::ptr_eq` answers exactly that: the handles are `Clone` around one `Arc`, so a clone compares equal and any +/// two contexts an app built separately do not, whatever either holds. (A probe written into one context and read from +/// the other would answer the same question, but two forks running in opposite directions at once would each see the +/// other's probe and both would refuse a pair that is not aliased.) +pub(crate) fn aliased(from: &Context, to: &Context) -> bool { + from.ptr_eq(to) +} + +/// Replaces `to`'s egui memory with a copy of `from`'s, and leaves `to` with its own runtime services (see +/// [`keep_own_services`]). Both contexts' egui memory closures stay in this module, the one layer the workspace's +/// `contract/egui-import` rule lets at egui's memory. +pub(crate) fn copy_memory(from: &Context, to: &Context) { + let copied = from.memory(Clone::clone); + let mut replaced = None; + let gone = keep_own_services(to, || replaced = Some(to.memory_mut(|memory| std::mem::replace(memory, copied)))); + drop(replaced); + drop(gone); +} + +/// Runs `copy` (which replaces `to`'s egui memory) and leaves `to` with the runtime services it had before: the +/// handles `copy` brought in share another context's state (a `Service` clone shares it), so they are dropped, and a +/// type `to` had none of starts fresh on first use. Returns what was moved out, to drop outside every lock. +pub(crate) fn keep_own_services(to: &Context, copy: impl FnOnce()) -> Vec { + /// The service types a context has created, read with context data held: `Service::of` registers a type's kind under + /// that same lock before it publishes the handle, so a snapshot taken here holds every handle already in the data. + /// Returns them with context data held, as `of` takes them in that order too (data, then kinds). + fn kinds_of() -> Vec { + kinds().lock().unwrap_or_else(PoisonError::into_inner).values().copied().collect() + } + let own: Vec<(Kind, Removed)> = locked(to, |data| kinds_of().iter().filter_map(|kind| (kind.take)(data).map(|handle| (*kind, handle))).collect()); + copy(); + // Read after the copy: a type created while it ran is in this list too, so the handle it brought in is removed. + let kinds = kinds_of(); + locked(to, |data| { + let mut gone: Vec = kinds.iter().filter_map(|kind| (kind.take)(data)).collect(); + gone.extend(own.into_iter().filter_map(|(kind, handle)| (kind.put)(data, handle))); + gone + }) +} + impl Service { /// The context's service of type `S`, created on first use. pub(crate) fn of(ctx: &Context) -> Service { #[cfg(feature = "testing")] LOOKUPS.with(|lookups| lookups.set(lookups.get() + 1)); - static SLOT: OnceLock = OnceLock::new(); - let slot = *SLOT.get_or_init(|| unique("craft_ui.service")); - locked(ctx, |data| data.get_temp_mut_or_default::>(slot).clone()) + let slot = service_slot(); + locked(ctx, |data| match data.get_temp::>(slot) { + Some(handle) => handle, + None => { + // The kind goes in before the handle does, under the data lock a fork holds while it copies: a fork + // that copies this handle therefore finds its kind and removes it from the copy. + kinds() + .lock() + .unwrap_or_else(PoisonError::into_inner) + .entry(TypeId::of::()) + .or_insert(Kind { take: take_service::, put: put_service:: }); + data.get_temp_mut_or_default::>(slot).clone() + } + }) } /// Runs `f` on the context's service of type `S`, created on first use. diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 10d75c74da..6a3a7bef57 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -818,7 +818,7 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { PerViewport::::with(ctx, viewport, |record| record.held.hold_ahead(later)); } Arrived::into_input(events, input); - // H3b: a press outside the top menu family goes no further than the menu's dismissal. + // H3b: a press outside the top menu family closes the menu; a primary one goes no further than its dismissal. let absorbed = overlay::absorb_presses(ctx, input); // H4: release after an OS resize. let released = windows::input_hook(ctx, input); diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index fc48d8fdaf..bd27e8f9d1 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -238,6 +238,8 @@ struct Open { stack: Vec, /// The nodes a label scope named by its label, with the label's node. labels: Vec<(Id, Id)>, + /// The text value noted for each component, kept for its facts, which may arrive later in the pass. + text_values: IdMap, } #[derive(Default)] @@ -255,15 +257,26 @@ const KEEP_PASSES: u64 = 4; /// /// A record that differs from the kept one, after something earlier in the pass read it, reruns the pass, so a /// reader shown before the region gets this pass's record. +/// +/// The steps a run records are only recorded while a region is open, and a replay adds only the steps its run took: +/// whether a region is open is part of a memoized view's key (`contract::MemoView`), so a view settled outside a +/// region runs again in the pass that shows it inside one, and its run records the region's elements. pub fn record(ui: &mut Ui, key: Id, body: impl FnOnce(&mut Ui) -> R) -> (R, Option>) { let ctx = ui.ctx().clone(); if ui.is_sizing_pass() || measure::active(&ctx) { return (body(ui), None); } - let open = Open { layer: ui.layer_id(), elements: Vec::new(), parts: Vec::new(), stack: Vec::new(), labels: Vec::new() }; + let open = + Open { layer: ui.layer_id(), elements: Vec::new(), parts: Vec::new(), stack: Vec::new(), labels: Vec::new(), text_values: IdMap::default() }; + let noted = crate::runtime::replay::mark(&ctx); pass_state::with::(&ctx, |log| log.open.push(open)); let out = body(ui); let Some(open) = pass_state::with::(&ctx, |log| log.open.pop()) else { return (out, None) }; + // What the body's components noted belongs to this region: a replay of a view around it adds only the region's + // own record (below), not those elements to whatever region is open there. + if let Some(noted) = noted { + crate::runtime::replay::withdraw(&ctx, noted, replay_step); + } let recorded = Arc::new(finish(&ctx, open)); keep(&ctx, key, &recorded); // A memoized view that replays this region keeps its record as the run left it. @@ -423,13 +436,143 @@ fn name_from_labels(elements: &mut [Element]) { } } +/// A call a component made to the open region's record. Each is noted in the journal of the records open around it +/// (`replay::journal`), so a memoized view that replays inside a region adds to the region what its run added: the +/// elements, their parts, facts, commands and text values, and the labels that name them. The hit areas and the Tab order need no +/// step: the sensing and focus services replay their own registrations, and [`finish`] reads those for the elements. +#[derive(Clone, Debug, PartialEq)] +enum Step { + /// [`open_element`]. + Open { id: Id, component: &'static str, layer: Layer }, + /// [`close_element`]. + Close { id: Id, rect: Rect, content: Rect }, + /// [`note_command`]. + Command { id: Id, command: Option }, + /// [`node_facts`]. + Facts { id: Id, part: Option, rect: Rect, facts: Facts }, + /// [`labelled`]. + Label { node: Id, label: Id }, + /// [`note_text_value`]. + TextValue { id: Id, value: String }, +} + +/// A replay at another place moves the boxes the step records. +impl crate::runtime::Shift for Step { + fn shifted(&self, by: &egui::RecordShift) -> Self { + match self { + Step::Close { id, rect, content } => Step::Close { id: *id, rect: by.rect(*rect), content: by.rect(*content) }, + Step::Facts { id, part, rect, facts } => Step::Facts { id: *id, part: *part, rect: by.rect(*rect), facts: facts.clone() }, + other => other.clone(), + } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + match (self, to) { + (Step::Close { id, rect, content }, Step::Close { rect: to_rect, content: to_content, .. }) => { + Step::Close { id: *id, rect: rect.snapped(to_rect, within), content: content.snapped(to_content, within) } + } + (Step::Facts { id, part, rect, facts }, Step::Facts { rect: to_rect, .. }) => { + Step::Facts { id: *id, part: *part, rect: rect.snapped(to_rect, within), facts: facts.clone() } + } + (other, _) => other.clone(), + } + } +} + +/// Makes the call `step` stands for in the innermost open region; returns whether a region took it. +fn apply(ctx: &Context, step: &Step) -> bool { + pass_state::with::(ctx, |log| { + let Some(open) = log.open.last_mut() else { return false }; + match step { + Step::Open { id, component, layer } => { + let element = Element { + id: *id, + part: None, + component, + depth: open.stack.len(), + rect: Rect::NOTHING, + content: Rect::NOTHING, + facts: None, + stop: None, + command: None, + }; + open.stack.push(open.elements.len()); + open.elements.push((element, *layer)); + } + Step::Close { id, rect, content } => { + let Some(at) = open.stack.iter().rposition(|index| open.elements[*index].0.id == *id) else { return true }; + let index = open.stack[at]; + open.stack.truncate(at); + let element = &mut open.elements[index].0; + element.rect = *rect; + element.content = *content; + } + Step::Command { id, command } => { + let Some(at) = open.stack.iter().rposition(|index| open.elements[*index].0.id == *id) else { return true }; + let index = open.stack[at]; + open.elements[index].0.command = command.clone(); + } + Step::Facts { id, part, rect, facts } => { + let Some(owner) = open.elements.iter_mut().rev().find(|(element, _)| element.id == *id) else { return true }; + match part { + None => { + let mut facts = facts.clone(); + // A text value noted before the facts arrived; a value the node states itself wins. + if facts.value.is_none() { + facts.value = open.text_values.get(id).cloned(); + } + owner.0.facts = Some(facts); + } + Some(part) => { + let (component, depth) = (owner.0.component, owner.0.depth + 1); + open.parts.retain(|element| !(element.id == *id && element.part == Some(*part))); + open.parts.push(Element { + id: *id, + part: Some(*part), + component, + depth, + rect: *rect, + content: *rect, + facts: Some(facts.clone()), + stop: None, + command: None, + }); + } + } + } + Step::Label { node, label } => open.labels.push((*node, *label)), + Step::TextValue { id, value } => { + // Kept for facts that arrive later in the pass, and written on facts that already did. A value the + // node states itself wins over the text the adapter wrote. + let value = open.text_values.entry(*id).or_insert_with(|| value.clone()); + let owner = open.elements.iter_mut().rev().find(|(element, _)| element.id == *id); + if let Some(facts) = owner.and_then(|(element, _)| element.facts.as_mut()) { + facts.value.get_or_insert_with(|| value.clone()); + } + } + } + true + }) +} + +/// What a replay of a noted step calls. +fn replay_step(ctx: &Context, step: &Step) { + apply(ctx, step); +} + +/// Makes the call `step` stands for and, when a region took it, notes it for the replay of a memoized view around it. +/// With no region open nothing is built or noted. +fn run(ctx: &Context, step: Step) -> bool { + let took = apply(ctx, &step); + if took { + crate::runtime::replay::journal(ctx, || step, replay_step); + } + took +} + /// Records that a label scope named the node of the component `node` by the label's node `label`. pub(crate) fn labelled(ctx: &Context, node: Id, label: Id) { - pass_state::with::(ctx, |log| { - if let Some(open) = log.open.last_mut() { - open.labels.push((node, label)); - } - }); + run(ctx, Step::Label { node, label }); } /// Whether the components shown in `ui` report their nodes for an inspected region: a region is open and the run is @@ -446,74 +589,110 @@ pub(crate) fn open_element(ui: &Ui, id: Id, component: &'static str) -> bool { if measure::active(ctx) { return false; } - let layer = ui.layer_id(); - pass_state::with::(ctx, |log| { - let Some(open) = log.open.last_mut() else { return false }; - let component = component.rsplit("::").next().unwrap_or(component); - let component = component.split('<').next().unwrap_or(component); - let element = Element { - id, - part: None, - component, - depth: open.stack.len(), - rect: Rect::NOTHING, - content: Rect::NOTHING, - facts: None, - stop: None, - command: None, - }; - open.stack.push(open.elements.len()); - open.elements.push((element, layer)); - true - }) + // The type's own name: generic arguments go first, so `Select<'_, alloc::string::String>` is `Select`. + let component = component.split('<').next().unwrap_or(component); + let component = component.rsplit("::").next().unwrap_or(component); + run(ctx, Step::Open { id, component, layer: ui.layer_id() }) } /// Ends the record [`open_element`] started for `id`, with the box the component took and the box inside its padding. pub(crate) fn close_element(ctx: &Context, id: Id, rect: Rect, content: Rect) { - pass_state::with::(ctx, |log| { - let Some(open) = log.open.last_mut() else { return }; - let Some(at) = open.stack.iter().rposition(|index| open.elements[*index].0.id == id) else { return }; - let index = open.stack[at]; - open.stack.truncate(at); - let element = &mut open.elements[index].0; - element.rect = rect; - element.content = content; - }); + run(ctx, Step::Close { id, rect, content }); } /// Notes the command bound to the control `id` in the open region's record; the report step calls it with the /// component's resolved command. It does nothing outside a region or for a component whose record is not open. pub(crate) fn note_command(ctx: &Context, id: Id, command: Option) { - pass_state::with::(ctx, |log| { - let Some(open) = log.open.last_mut() else { return }; - let Some(at) = open.stack.iter().rposition(|index| open.elements[*index].0.id == id) else { return }; - let index = open.stack[at]; - open.elements[index].0.command = command; - }); + run(ctx, Step::Command { id, command }); +} + +/// Notes the text value the text adapter wrote on the node of the component `id` (`report_text`), unless the node +/// states a value itself: the inspector then lists what AccessKit reads for a text field. The value is listed whether +/// the node's facts ([`node_facts`]) arrive before or after it in the pass. +pub(crate) fn note_text_value(ctx: &Context, id: Id, value: &str) { + if recording(ctx) { + run(ctx, Step::TextValue { id, value: value.to_owned() }); + } } /// Records what the node of the component `id`, or of its part `part` at `rect`, says. pub(crate) fn node_facts(ctx: &Context, id: Id, part: Option, rect: Rect, facts: Facts) { - pass_state::with::(ctx, |log| { - let Some(open) = log.open.last_mut() else { return }; - let Some(owner) = open.elements.iter_mut().rev().find(|(element, _)| element.id == id) else { return }; - match part { - None => owner.0.facts = Some(facts), - Some(part) => { - let (component, depth) = (owner.0.component, owner.0.depth + 1); - open.parts.retain(|element| !(element.id == id && element.part == Some(part))); - open.parts.push(Element { - id, - part: Some(part), - component, - depth, - rect, - content: rect, - facts: Some(facts), - stop: None, - command: None, - }); + run(ctx, Step::Facts { id, part, rect, facts }); +} + +/// The record's own order: a text value lists whether the node's facts arrive before or after it in the pass. No +/// component reports its facts after its text, so these trials drive the record's calls directly. +#[cfg(all(feature = "testing", any(test, feature = "suite")))] +pub(crate) mod trials { + use super::{Facts, close_element, node_facts, note_text_value, open_element, record}; + use crate::testing::{Fixture, trial}; + use egui::Id; + use std::cell::RefCell; + use std::rc::Rc; + + /// The facts of a text input node that states `value` itself, or none. + fn facts(value: Option<&str>) -> Facts { + Facts { + role: "TextInput".to_owned(), + name: None, + labelled_by: Vec::new(), + value: value.map(str::to_owned), + actions: Vec::new(), + disabled: false, + interactive: true, + } + } + + /// A text value noted before its node's facts arrive is listed once they do, as it is when they arrived first; + /// facts reported again keep it, and a value the node states itself still wins. + #[trial] + fn a_text_value_is_listed_whichever_order_the_facts_arrive_in() { + let key = Id::NULL.with("trial.inspect.text_value_order"); + let (before, after, again, own) = (key.with("before"), key.with("after"), key.with("again"), key.with("own")); + let seen = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let ctx = ui.ctx().clone(); + let (_, recorded) = record(ui, key, |ui| { + let rect = ui.max_rect(); + // The text value first, then the facts. + open_element(ui, before, "Field"); + note_text_value(&ctx, before, "before"); + node_facts(&ctx, before, None, rect, facts(None)); + close_element(&ctx, before, rect, rect); + // The order the report step takes: the facts, then the text value. + open_element(ui, after, "Field"); + node_facts(&ctx, after, None, rect, facts(None)); + note_text_value(&ctx, after, "after"); + close_element(&ctx, after, rect, rect); + // The facts, the text value, then the facts reported again. + open_element(ui, again, "Field"); + node_facts(&ctx, again, None, rect, facts(None)); + note_text_value(&ctx, again, "again"); + node_facts(&ctx, again, None, rect, facts(None)); + close_element(&ctx, again, rect, rect); + // The node states a value of its own, after the text value. + open_element(ui, own, "Field"); + note_text_value(&ctx, own, "typed"); + node_facts(&ctx, own, None, rect, facts(Some("own"))); + close_element(&ctx, own, rect, rect); + }); + if recorded.is_some() { + *out.borrow_mut() = recorded; } - } - }); + }); + fixture.frame(Vec::new()); + let seen = seen.borrow(); + let recorded = seen.as_deref(); + assert!(recorded.is_some(), "the region ran"); + let Some(recorded) = recorded else { return }; + let value = |id: Id| { + let element = recorded.elements.iter().find(|element| element.id == id && element.part.is_none()); + element.and_then(|element| element.facts.as_ref()).and_then(|facts| facts.value.clone()) + }; + assert_eq!(value(before).as_deref(), Some("before"), "facts arriving after the text value list it: {:?}", recorded.elements); + assert_eq!(value(after).as_deref(), Some("after"), "facts arriving before the text value list it"); + assert_eq!(value(again).as_deref(), Some("again"), "facts reported again keep the text value"); + assert_eq!(value(own).as_deref(), Some("own"), "a value the node states itself wins over the text value"); + } } diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index fd286bbdf4..045249fc58 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -255,6 +255,7 @@ fn detach_owner(reg: &mut Registry, record: &OwnerRecord) { } /// One entry the runtime keeps for a component, and the owner that is tested for its eviction. +#[derive(Clone, Copy)] struct SlotRecord { owner: Id, remove: Remover, @@ -557,6 +558,20 @@ fn forget_tier(ctx: &Context, id: Id, tier: u8) { drop(moved); } +/// Takes the destination's registry records for every slot a fork copied into it: `Registry` is per-context framework +/// state while `fork_into` copies egui memory, so without this the copied slots read as `recorded` (that flag comes from +/// finding the slot in context data) and `write_back` never records them — no owner, so `evict` and `forget_tier` could +/// never reach them. The owner kept is the source's: the slot is that component's state, and the destination's passes +/// record it under their own owner as soon as they write it again. +pub(crate) fn adopt_copied_slots(from: &Context, to: &Context) { + let copied: Vec<((Id, u8, TypeId), SlotRecord)> = pass_state::with::(from, |reg| reg.slots.iter().map(|(k, v)| (*k, *v)).collect()); + pass_state::with::(to, |reg| { + for (key, record) in copied { + reg.slots.insert(key, record); + } + }); +} + /// Registers a slot the motion service wrote straight into context data, so it goes with its owner's shown entries. pub(crate) fn adopt(ctx: &Context, owner: Id, id: Id) { fn remove(data: &mut Map, id: Id) -> Option { @@ -567,6 +582,14 @@ pub(crate) fn adopt(ctx: &Context, owner: Id, id: }); } +/// Edits the shown slot of type `T` under `id` in place, outside a memory stage: the slot moves out of context data, +/// `f` edits it, and it moves back. `f` runs no call that reaches the context. +pub(crate) fn edit_shown(ctx: &Context, id: Id, f: impl FnOnce(&mut T)) { + let Some(mut moved) = store::take::>(ctx, id) else { return }; + f(&mut moved.0); + store::put(ctx, id, moved); +} + /// Moves the shown slot of type `T` under `id` out of context data into the graveyard, as eviction does. pub(crate) fn dispose_shown(ctx: &Context, id: Id) { let moved = pass_state::with::(ctx, |reg| { @@ -579,6 +602,13 @@ pub(crate) fn dispose_shown(ctx: &Context, id: Id) { } } +/// How many slot records the registry of `ctx` holds: a fork copies its source's, so the destination can evict and forget +/// what it was given instead of keeping it for ever. +#[cfg(feature = "testing")] +pub(crate) fn slot_records(ctx: &Context) -> usize { + pass_state::with::(ctx, |reg| reg.slots.len()) +} + /// How many slot records write-back has written in `ctx` so far. #[cfg(feature = "testing")] pub(crate) fn records_written(ctx: &Context) -> usize { @@ -1107,3 +1137,48 @@ pub fn with_session(ctx: &Context, id: Id, f: impl FnOnce(&mut T) -> pub fn unique(source: impl std::hash::Hash + std::fmt::Debug) -> Id { store::unique(source) } + +/// Why [`fork_into`] refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ForkError { + /// `to` is running a pass: fork into a context between its passes. + DuringPass, + /// `from` and `to` are the same context: a fork needs a second one to copy into. + SameContext, +} + +impl std::fmt::Display for ForkError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ForkError::DuringPass => f.write_str("fork into a context between its passes, not during one"), + ForkError::SameContext => f.write_str("fork into a second context, not into the one copied from"), + } + } +} + +impl std::error::Error for ForkError {} + +/// Gives `to` a copy of `from`'s UI memory, for a second context that draws what `from` shows (a headless capture of a +/// window): egui's memory (areas, scroll areas, collapsing states, options) and the components' remembered state +/// (scroll offsets, open sections, the session and shown slots of every component), copied by value. `to` keeps its +/// own runtime: its pass state, focus, overlays, commands, windows and the rest of the services its install made, so +/// a pass of `to` neither reads nor moves `from`'s, and `to` may run a pass inside one of `from`'s. A runtime service +/// `to` has none of yet starts fresh in `to` on first use. +/// +/// Copying egui's memory alone (`to.memory_mut(|m| *m = from.memory(Clone::clone))`) shares the runtime's state +/// between the two: its services are handles, and a copy of a handle reaches the same state. +pub fn fork_into(from: &Context, to: &Context) -> Result<(), ForkError> { + if frame::in_pass(to) { + return Err(ForkError::DuringPass); + } + // Two handles to one context share its data: copying it onto itself would detach the original's own state. + if store::aliased(from, to) { + return Err(ForkError::SameContext); + } + store::copy_memory(from, to); + // the copied slots' registry records follow them, or nothing in the destination could ever evict them + adopt_copied_slots(from, to); + pending::detach_fork(from, to); + Ok(()) +} diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index a89ba1dc73..c4b352c1dd 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -170,7 +170,7 @@ pub struct OpenEntry { pub(crate) cover: Option, /// The layer has a focus scope. pub(crate) scoped: bool, - /// A press outside its family closes it and goes no further. + /// A press outside its family closes it, and a primary one goes no further. pub(crate) absorbs: bool, /// A command run from outside it closes it (`Dismiss::commands`). pub(crate) closes_on_commands: bool, @@ -313,7 +313,7 @@ pub(crate) struct Persist { /// The screen rects a press may land in without closing the top menu family: the family and its anchors. `None` /// when the top layer does not absorb outside presses. absorb_zone: Option>, - /// An outside press the input hook removed for the running pass. + /// An outside press the input hook recorded for the running pass (and removed, for a primary one). outside_press: Option, /// The top live modal layer of the last finished pass in this viewport. top_modal: Option, @@ -747,18 +747,20 @@ pub(crate) fn closed_by_activation(ctx: &Context, id: Id) -> bool { with_pass(ctx, |pass| pass.activated.iter().any(|(component, closes)| closes.contains(&id) && !pass.claimed.contains(component))) } -/// The input hook: removes the primary presses that land outside the top menu family, its anchors and its parents, -/// so nothing below the menu sees them (`Outside::Absorb`), and keeps the first one for the layers' dismissal. -/// Returns whether it removed one. +/// The input hook: keeps the first press of any button that lands outside the top menu family, its anchors and its +/// parents for the layers' dismissal, and removes the primary ones, so nothing below the menu sees them +/// (`Outside::Absorb`). A secondary or middle press goes on to what it lands on: a right-click on another part closes +/// the menu and opens that part's menu. The record is for the layers open when the press was made: a layer that appears +/// in this pass was not, and its dismissal reads none of it (`opening`). Returns whether it removed one. pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::input::RawInput) -> bool { let zone = with_persist(ctx, input.viewport_id, |persist| persist.absorb_zone.clone()); let Some(zone) = zone else { return false }; let before = input.events.len(); let mut first = None; input.events.retain(|event| match event { - egui::Event::PointerButton { pos, pressed: true, .. } if !zone.iter().any(|rect| rect.contains(*pos)) => { + egui::Event::PointerButton { pos, button, pressed: true, .. } if !zone.iter().any(|rect| rect.contains(*pos)) => { first.get_or_insert(*pos); - false + *button != egui::PointerButton::Primary } _ => true, }); @@ -768,7 +770,9 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in input.events.len() != before } -/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`). +/// The outside press the input hook recorded for the running pass: the lone point it landed on, for the layers the pass +/// showed before it. `opening` is how a layer that appears in the pass tells it is none of those. A tracked input +/// (`Input::Press`). pub(crate) fn absorbed_press(ctx: &Context) -> Option { crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); absorbed_press_raw(ctx) diff --git a/crates/ui-contract/src/runtime/pending.rs b/crates/ui-contract/src/runtime/pending.rs index bb2165f550..67ad7a8729 100644 --- a/crates/ui-contract/src/runtime/pending.rs +++ b/crates/ui-contract/src/runtime/pending.rs @@ -224,8 +224,45 @@ pub fn finish_jobs(ctx: &Context, timeout: Duration) -> bool { queue.is_none_or(|queue| queue.finish(timeout)) } +/// The slot types a fork detaches, one entry per type, added when its first slot is tracked. +/// Detaches the copied slot `Id` in the context the fork made: the `PendingSlot` type states what it drops. +type Detacher = fn(&Context, Id); + +static DETACHERS: Mutex> = Mutex::new(Vec::new()); + +/// Detaches the pending results of the copied slot `id`: the fork keeps what the slot showed and drops the `Started` +/// it shared with the context it was copied from, so it neither takes that context's landed result nor holds its +/// cancellation. +fn detach_slot(ctx: &Context, id: Id) { + memory::edit_shown::>(ctx, id, |slot| slot.started = None); +} + +/// Detaches the pending results `from` started from `to`, which copied `from`'s memory (`memory::fork_into`): each +/// copied slot drops the `Started` handle it shares with `from`, so neither context takes the other's landed result, and +/// the window alone keeps the handle whose drop cancels the job. `to` submits its own job on its next real pass. +pub(crate) fn detach_fork(from: &Context, to: &Context) { + let ids: Vec = Service::::run(from, |state| state.tracked.keys().copied().collect()); + if ids.is_empty() { + return; + } + let detachers: Vec = DETACHERS.lock().unwrap_or_else(PoisonError::into_inner).iter().map(|(_, detach)| *detach).collect(); + for id in ids { + for detach in &detachers { + detach(to, id); + } + } +} + /// Notes that `id` was asked for in this pass of the running viewport. fn track(ctx: &Context, id: Id, owner: Id) { + // Keyed by the slot type: a `static` inside a generic function is one item for every instantiation, so a + // first-seen flag would keep every later type from registering. + let slot_type = TypeId::of::>(); + let mut detachers = DETACHERS.lock().unwrap_or_else(PoisonError::into_inner); + if !detachers.iter().any(|(known, _)| *known == slot_type) { + detachers.push((slot_type, detach_slot::)); + } + drop(detachers); let viewport = pass::current_viewport(ctx); let pass = pass::pass_nr(ctx, viewport); frame::register_end_sweep(ctx, TypeId::of::(), sweep); diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 113ef7643b..c44e5992ca 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -56,6 +56,10 @@ pub struct PointerFrame { /// The modifiers of the pass's last button release, with the latched ones added; the held `mods` in a pass with no /// release and in a rerun pass. The one source of a pick's and a drop's modifiers. pub pick_mods: Mods, + /// The modifiers of the release that ended the primary press, with the latched ones added; the held `mods` in a + /// pass whose click completes without one (a release held for the pass after it). A click's activation reads these: + /// a release of another button later in the same pass overwrites `pick_mods`, never this. + pub click_mods: Mods, /// Where the pass's last button release went up; the latest `pos` in a pass with no release and in a rerun pass. The /// one source of a drop's position: a pointer that moves on or leaves the window after the release in the same /// frame does not move the drop. @@ -380,6 +384,7 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { release: read.release, mods, pick_mods: read.released_at.map_or(mods, |(_, released)| with_latched(released, latched)), + click_mods: read.click_mods.map_or(mods, |released| with_latched(released, latched)), pick_pos: read.released_at.map_or(read.pos, |(at, _)| Some(at)), multi_tap: tap, time: read.time, @@ -427,8 +432,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } - // A press or release, or an outside press the layer stack's input hook took before egui saw it. The buttons - // held are part of the press state ([`press_state`]) too. + // Track held buttons as part of the press state. A press, release or recorded outside press bumps it; + // of the outside presses the layer stack records, only a primary press is taken before egui sees it. inputs::observe(ctx, Input::Press, frame.buttons); if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { inputs::bump(ctx, Input::Press); @@ -590,6 +595,7 @@ pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame { release: None, mods: Mods::NONE, pick_mods: Mods::NONE, + click_mods: Mods::NONE, pick_pos: None, multi_tap: None, time: 0.0, diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index aeda33820b..a02b2520c3 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -562,6 +562,28 @@ where } } +/// Where the journal of the running pass ends now, when a record is open: the mark [`withdraw`] takes the entries made +/// since from. +pub(crate) fn mark(ctx: &Context) -> Option { + recording(ctx).then(|| pass_state::with::(ctx, |recorder| recorder.journal.len())) +} + +/// Takes back the entries of the call `again` (as [`journal`] takes it, with arguments of type `A`) that the open +/// records noted since `from` (a [`mark`]): a region that keeps what it shows to itself (`inspect::record`) owns the +/// registrations its components made in it, and a replay of the view around the region must not make them again in +/// whatever record is open there. +pub(crate) fn withdraw(ctx: &Context, from: usize, _again: F) +where + A: PartialEq + fmt::Debug + Shift + Send + Sync + 'static, + F: Fn(&Context, &A) + Copy + Send + Sync + 'static, +{ + pass_state::with::(ctx, |recorder| { + let from = from.min(recorder.journal.len()); + let tail = recorder.journal.split_off(from); + recorder.journal.extend(tail.into_iter().filter(|entry| entry.0.as_any().downcast_ref::>().is_none())); + }); +} + /// Notes that the running code read the value `key`. pub(crate) fn note_read(ctx: &Context, key: BindKey) { if any_open() && frame::running(ctx).is_some() { diff --git a/crates/ui-contract/src/testing/memory.rs b/crates/ui-contract/src/testing/memory.rs index e2f9745b87..f29c1ee5ff 100644 --- a/crates/ui-contract/src/testing/memory.rs +++ b/crates/ui-contract/src/testing/memory.rs @@ -68,6 +68,12 @@ pub fn records_written(ctx: &Context) -> usize { memory::records_written(ctx) } +/// How many slot records the registry of `ctx` holds: a fork copies its source's, so the destination can evict and +/// forget what it was given. +pub fn slot_records(ctx: &Context) -> usize { + memory::slot_records(ctx) +} + /// Drops the slots the end hook evicted. pub fn dispose_evicted(ctx: &Context) { memory::dispose_evicted(ctx); diff --git a/crates/ui-contract/tests/it/contract/inspect_region.rs b/crates/ui-contract/tests/it/contract/inspect_region.rs new file mode 100644 index 0000000000..5f4bdeec78 --- /dev/null +++ b/crates/ui-contract/tests/it/contract/inspect_region.rs @@ -0,0 +1,80 @@ +//! An inspected region and a memoized view: whether a region is open is part of the view's key, since a run records +//! the region's steps for its components and a replay adds only the steps its run took. + +use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _}; +use craft_ui::runtime::inspect::{self, Recorded}; +use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, trial}; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Id, Ui, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +/// The view's props: one probe `size` wide. +#[derive(MemoProps)] +struct Content { + size: f32, +} + +fn content(props: &mut Content, ui: &mut Ui) { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).size(Vec2::splat(props.size)).id_salt("content").show(ui); +} + +/// The view's calls in a frame that shows it `inside` the region or not; the region's record goes to `recorded`. +fn frame(frames: &mut Frames, inside: bool, recorded: &Rc>>>) -> Vec { + frames.frame(Vec::new(), |ui| { + let view = |ui: &mut Ui| { + let _ = MemoView::new("view", Content { size: 40.0 }, content).show(ui); + }; + if inside { + let (_, record) = inspect::record(ui, Id::NULL.with("trial.inspect.memo_region"), view); + *recorded.borrow_mut() = record; + } else { + view(ui); + *recorded.borrow_mut() = None; + } + }); + last_frame_memo_runs(&frames.ctx).into_iter().filter(|(name, _, _)| name.contains("Content")).map(|(_, _, run)| run).collect() +} + +/// Whether every call of the frame replayed the view. +fn settled(runs: &[MemoRun]) -> bool { + !runs.is_empty() && runs.iter().all(|run| *run == MemoRun::Replayed) +} + +/// The components of the region's record, by type name. +fn components(recorded: &Arc) -> Vec<&'static str> { + recorded.elements.iter().filter(|element| element.part.is_none()).map(|element| element.component).collect() +} + +/// A view settled outside a region is not replayed inside one: it runs, and its run records the region's components. +/// A run recorded inside a region is replayed there, and is not replayed outside it either. +#[trial] +fn whether_a_region_is_open_is_part_of_a_memoized_views_key() { + let recorded: Rc>>> = Rc::default(); + let mut frames = Frames::new(); + for _ in 0..3 { + frame(&mut frames, false, &recorded); + } + let runs = frame(&mut frames, false, &recorded); + assert!(settled(&runs), "an idle frame outside a region replays the view: {runs:?}"); + + // The region opens around the unchanged view, which runs: its run records the region's components. + let runs = frame(&mut frames, true, &recorded); + assert!(runs.contains(&MemoRun::Ran), "a view settled outside a region runs when one opens around it: {runs:?}"); + let record = recorded.borrow().clone().expect("the region ran"); + assert_eq!(components(&record), ["Probe"], "the run records the region's components"); + + // Inside the region, unchanged, the view replays: its replay adds those steps to the region again. + let runs = frame(&mut frames, true, &recorded); + assert!(settled(&runs), "inside the region the settled view replays: {runs:?}"); + let record = recorded.borrow().clone().expect("the region ran"); + assert_eq!(components(&record), ["Probe"], "the replay adds the region's steps"); + + // The region closes around the view that ran inside it: it runs again, outside any region. + let runs = frame(&mut frames, false, &recorded); + assert!(runs.contains(&MemoRun::Ran), "a run recorded inside a region is not replayed outside one: {runs:?}"); + let runs = frame(&mut frames, false, &recorded); + assert!(settled(&runs), "and settles outside the region as before: {runs:?}"); +} diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index 2e95af053f..8745668bb0 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod fixes; pub(crate) mod gesture; pub(crate) mod hit_order; +pub(crate) mod inspect_region; pub(crate) mod level; pub(crate) mod memo_key; pub(crate) mod memo_row; diff --git a/crates/ui-contract/tests/it/runtime/fork.rs b/crates/ui-contract/tests/it/runtime/fork.rs new file mode 100644 index 0000000000..439e5aa648 --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/fork.rs @@ -0,0 +1,158 @@ +//! `runtime::memory::fork_into`: a second context (a headless capture of a window) gets the window's UI memory, its +//! components' scroll offsets included, and keeps a runtime of its own: it runs passes inside the window's, and what it +//! does stays its own. + +use craft_host::{AppInfo, Host, Jobs, ManualJobs}; +use craft_ui::contract::{ContainerProps, Job, Pending, Props as _, Remember as _, Scroll, Show as _, ShowContainer as _}; +use craft_ui::runtime::memory::{ForkError, fork_into}; +use craft_ui::testing::layout::{Block, in_region}; +use craft_ui::testing::memory::{Stage, global, slot_records}; +use craft_ui::testing::{Frames, pointer, trial}; +use craft_ui_test_kit::body::Slab; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; +use std::sync::Arc; + +const VIEW: Vec2 = Vec2::new(300.0, 200.0); +const ORIGIN: Pos2 = Pos2::new(10.0, 10.0); +const ROWS: usize = 40; +const ROW_H: f32 = 20.0; + +/// A scrolling list of rows; `top` is where its first row showed. +fn list(ui: &mut Ui, top: &Cell) { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("list").show(ui, |ui, _| { + for row in 0..ROWS { + let rect = Block::new(Vec2::new(VIEW.x, ROW_H)).show(ui).rect; + if row == 0 { + top.set(rect.min.y); + } + } + }); + }); +} + +fn scroll(frames: &mut Frames, top: &Cell, by: f32) { + frames.frame(vec![pointer::moved(ORIGIN + VIEW / 2.0)], |ui| list(ui, top)); + frames.frame(vec![pointer::wheel(by)], |ui| list(ui, top)); + frames.idle(3, |ui| list(ui, top)); +} + +#[trial] +fn a_forked_context_shows_the_windows_scroll_offset_and_keeps_a_runtime_of_its_own() { + let (window_top, shadow_top) = (Cell::new(0.0), Cell::new(0.0)); + let mut window = Frames::new(); + let mut shadow = Frames::new(); + window.idle(3, |ui| list(ui, &window_top)); + let unscrolled = window_top.get(); + scroll(&mut window, &window_top, -120.0); + let scrolled = window_top.get(); + assert!(scrolled < unscrolled - 1.0, "the window's list scrolled: {unscrolled} to {scrolled}"); + + fork_into(&window.ctx, &shadow.ctx).expect("the shadow runs no pass"); + // A headless capture draws the shadow inside one of the window's passes. + window.frame(vec![], |ui| { + list(ui, &window_top); + shadow.frame(vec![], |ui| list(ui, &shadow_top)); + }); + assert!((shadow_top.get() - scrolled).abs() < 0.5, "the shadow shows the window's offset: {} for {scrolled}", shadow_top.get()); + + // What the shadow does stays its own. + scroll(&mut shadow, &shadow_top, -120.0); + window.idle(2, |ui| list(ui, &window_top)); + assert!(shadow_top.get() < scrolled - 1.0, "the shadow scrolled further: {}", shadow_top.get()); + assert!((window_top.get() - scrolled).abs() < 0.5, "the window keeps its offset: {} for {scrolled}", window_top.get()); +} + +#[trial] +fn fork_into_a_context_running_a_pass_is_refused() { + let window = Frames::new(); + let mut shadow = Frames::new(); + let refused = std::cell::RefCell::new(None); + shadow.frame(vec![], |ui| { + *refused.borrow_mut() = Some(fork_into(&window.ctx, ui.ctx())); + }); + assert_eq!(refused.into_inner(), Some(Err(ForkError::DuringPass))); +} + +fn host_over(jobs: Arc) -> Arc { + Arc::new(Host::builder(AppInfo { id: "trial", name: "Trial", version: "0" }).jobs(jobs).build()) +} + +/// The pending result of `"k"` under `id`'s stage, polled in a real pass. The job's answer is `answer`, so a slot of +/// another result type is a job of its own. +fn poll_type(ui: &Ui, id: egui::Id, answer: T) -> Pending +where + T: Clone + Default + Send + Sync + 'static, + E: Clone + Default + Send + Sync + 'static, +{ + let mut stage = Stage::open(ui.ctx(), id); + let result = stage.pending("k", move || Job::new(move |_, _| Ok(answer))).clone(); + stage.finish(); + result +} + +#[trial] +fn a_copied_pending_slot_takes_no_landed_result_from_the_context_it_was_forked_from() { + let jobs = Arc::new(ManualJobs::new()); + let (first, second) = (global("fork.pending", "first"), global("fork.pending", "second")); + let mut window = Frames::new(); + let mut shadow = Frames::new(); + window.host(host_over(jobs.clone())); + shadow.host(host_over(jobs.clone())); + let (seen, shadow_seen) = (RefCell::new(Pending::::default()), RefCell::new(Pending::::default())); + let (other, shadow_other) = (RefCell::new(Pending::::default()), RefCell::new(Pending::::default())); + window.frame(vec![], |ui| { + *seen.borrow_mut() = poll_type(ui, first, 7u32); + *other.borrow_mut() = poll_type(ui, second, 9u64); + }); + assert!(matches!(*seen.borrow(), Pending::Loading { .. }), "the window waits for its jobs: {:?}", seen.borrow()); + jobs.run_all(); + + fork_into(&window.ctx, &shadow.ctx).expect("the shadow runs no pass"); + // The shadow polls first, before the window takes what landed. + shadow.frame(vec![], |ui| { + *shadow_seen.borrow_mut() = poll_type(ui, first, 7u32); + *shadow_other.borrow_mut() = poll_type(ui, second, 9u64); + }); + window.frame(vec![], |ui| { + *seen.borrow_mut() = poll_type(ui, first, 7u32); + *other.borrow_mut() = poll_type(ui, second, 9u64); + }); + assert_eq!(*seen.borrow(), Pending::Ready(7), "the window still takes its own landed result"); + assert_eq!(*other.borrow(), Pending::Ready(9), "and so does its slot of another result type"); + assert_eq!(*shadow_seen.borrow(), Pending::Loading { progress: None }, "the fork submits a job of its own"); + assert_eq!(*shadow_other.borrow(), Pending::Loading { progress: None }, "for each result type it copied"); +} + +#[trial] +fn fork_into_the_same_context_is_refused_and_leaves_its_own_state_alone() { + let jobs = Arc::new(ManualJobs::new()); + let id = global("fork.pending", "same"); + let mut window = Frames::new(); + window.host(host_over(jobs.clone())); + let seen = RefCell::new(Pending::::default()); + window.frame(vec![], |ui| *seen.borrow_mut() = poll_type(ui, id, 5u32)); + jobs.run_all(); + // The same context through a second handle. + let alias = window.ctx.clone(); + assert_eq!(fork_into(&window.ctx, &alias), Err(ForkError::SameContext), "a context is not forked into itself"); + window.frame(vec![], |ui| *seen.borrow_mut() = poll_type(ui, id, 5u32)); + assert_eq!(*seen.borrow(), Pending::Ready(5), "the context still takes its own landed result"); +} + +/// A fork copies the destination's slots, so it copies their registry records too: without them the copied slots read as +/// `recorded` (that flag comes from finding the slot in context data) and write-back never records them, so no owner could +/// ever evict them and `forget` could not reach them. +#[trial] +fn a_fork_takes_the_copied_slots_registry_records_too() { + let mut window = Frames::new(); + let top = Cell::new(0.0); + window.idle(3, |ui| list(ui, &top)); + let shadow = Frames::new(); + assert_eq!(slot_records(&shadow.ctx), 0, "a fresh context holds no slot records"); + fork_into(&window.ctx, &shadow.ctx).expect("the fork runs outside a pass"); + let copied = slot_records(&shadow.ctx); + assert!(copied > 0, "the destination holds the copied scroll slot's record"); + assert_eq!(copied, slot_records(&window.ctx), "every copied slot has a record, none left behind"); +} diff --git a/crates/ui-contract/tests/it/runtime/latch.rs b/crates/ui-contract/tests/it/runtime/latch.rs index 978a8723b8..9b76946f65 100644 --- a/crates/ui-contract/tests/it/runtime/latch.rs +++ b/crates/ui-contract/tests/it/runtime/latch.rs @@ -24,6 +24,8 @@ struct Log { claimed: Vec, /// `pointer::frame(..).mods` of every pass. pointer: Vec, + /// `pointer::frame(..).pick_mods` of every pass: what a pick and a drop read. + pick: Vec, } /// A focusable button that logs its activations' modifiers and the claimed chords it takes. @@ -79,7 +81,10 @@ impl Rig { fn show(&self, ui: &mut Ui) { let response = LatchProbe { common: Common::new(), log: &self.log }.id_salt("latch").show(ui); self.shown.set(Some((response.id, response.rect))); - self.log.borrow_mut().pointer.push(craft_ui::runtime::pointer::frame(ui.ctx()).mods); + let frame = craft_ui::runtime::pointer::frame(ui.ctx()); + let mut log = self.log.borrow_mut(); + log.pointer.push(frame.mods); + log.pick.push(frame.pick_mods); if self.discard.take() { ui.ctx().request_discard("the trial reruns the pass"); } @@ -156,3 +161,62 @@ fn a_latch_change_adds_no_pass() { assert_eq!(held, steady); assert_eq!(released, steady, "releasing runs no extra pass"); } + +#[trial] +fn a_click_reads_the_modifiers_of_its_release() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + rig.clear(); + // A quick Alt-click: the press and the release carry Alt, which is up again when the frame runs. + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::ALT }; + frames.frame(vec![button(true), button(false)], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::ALT], "the activation carries the release's Alt, not the frame's held modifiers"); + assert!(log.pointer.iter().all(|mods| !mods.alt), "nothing is held when the frames run: {:?}", log.pointer); +} + +/// A press or release of `button` at `at`, carrying `modifiers`. +fn pointer_button(at: Pos2, button: egui::PointerButton, pressed: bool, modifiers: Modifiers) -> egui::Event { + egui::Event::PointerButton { pos: at, button, pressed, modifiers } +} + +#[trial] +fn an_alt_click_keeps_its_alt_when_a_plain_secondary_release_follows() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + rig.clear(); + // A quick Alt-click, then an unmodified secondary release in the same pass. The click completes, and it carries + // the Alt of the release that ended its own press, which is not the pass's last release. + let alt = |pressed| pointer_button(at, egui::PointerButton::Primary, pressed, Modifiers::ALT); + let secondary = pointer_button(at, egui::PointerButton::Secondary, false, Modifiers::NONE); + frames.frame(vec![alt(true), alt(false), secondary], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::ALT], "the activation carries the Alt of the release that ended the primary press"); + assert!(log.pick.iter().all(|mods| !mods.alt), "a pick and a drop read the pass's last release, which was the secondary's: {:?}", log.pick); +} + +#[trial] +fn a_plain_click_takes_no_modifier_from_a_secondary_release() { + let rig = Rig::new(); + let mut frames = Frames::new(); + frames.idle(3, |ui| rig.show(ui)); + let at = rig.at(); + frames.frame(vec![moved(at)], |ui| rig.show(ui)); + rig.clear(); + // A plain quick click, then a Shift-carrying secondary release in the same pass: the click gains no Shift. + let plain = |pressed| pointer_button(at, egui::PointerButton::Primary, pressed, Modifiers::NONE); + let secondary = pointer_button(at, egui::PointerButton::Secondary, false, Modifiers::SHIFT); + frames.frame(vec![plain(true), plain(false), secondary], |ui| rig.show(ui)); + frames.idle(1, |ui| rig.show(ui)); + let log = rig.log.borrow(); + assert_eq!(log.activations, [Mods::NONE], "the activation carries the plain release of its own press"); + assert!(log.pick.contains(&Mods::SHIFT), "a pick and a drop read the pass's last release, which carried Shift: {:?}", log.pick); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index c30407d52b..dbddfba74d 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -11,6 +11,7 @@ pub(crate) mod elapsed; pub(crate) mod env; pub(crate) mod fingers; pub(crate) mod focus; +pub(crate) mod fork; pub(crate) mod frame; pub(crate) mod latch; pub(crate) mod layout_memory; diff --git a/crates/ui-gallery/src/bin/contract-api.rs b/crates/ui-gallery/src/bin/contract-api.rs index c8612f56be..7ea5f4994f 100644 --- a/crates/ui-gallery/src/bin/contract-api.rs +++ b/crates/ui-gallery/src/bin/contract-api.rs @@ -1,6 +1,6 @@ //! Writes `docs/contract-api.md`: every public item of craft-behavior and of craft-ui's shared modules (the runtime, //! style, primitives, contract, layout and test kit of craft-ui-contract, and the layout components of -//! craft-ui-widgets), with its path, its signature line and the first line of its doc comment. +//! craft-ui-widgets), with its path, its signature line and the first sentence of its doc comment. //! //! `cl cargo run -p craft-ui-gallery --bin contract-api` rewrites the file. The sources are parsed with `syn`, //! following `mod`, `pub mod` and `pub use` from each crate root, so a re-export is listed under the path it is public @@ -90,7 +90,9 @@ fn workspace_root() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") } -fn first_doc_line(attrs: &[Attribute]) -> String { +/// The text of the doc comment's lines, trimmed. +fn doc_lines(attrs: &[Attribute]) -> Vec { + let mut lines = Vec::new(); for attr in attrs { if !attr.path().is_ident("doc") { continue; @@ -99,14 +101,78 @@ fn first_doc_line(attrs: &[Attribute]) -> String { && let Expr::Lit(literal) = &pair.value && let Lit::Str(text) = &literal.lit { - let line = text.value(); - let line = line.trim(); - if !line.is_empty() { - return line.to_owned(); - } + lines.push(text.value().trim().to_owned()); } } - String::new() + lines +} + +/// The words a doc line may end with without ending its sentence. +const ABBREVIATIONS: [&str; 6] = ["e.g.", "i.e.", "cf.", "vs.", "etc.", "approx."]; + +/// Where `line`'s first sentence ends: just past a full stop, question or exclamation mark that ends the line or that +/// a space and a capital letter follow, and never inside `e.g.` and the other short forms above it. +fn sentence_end(line: &str) -> Option { + for (index, character) in line.char_indices() { + if !matches!(character, '.' | '!' | '?') { + continue; + } + // A run of dots is an ellipsis inside the sentence, not its end: "the run (LRI ... PDI) for ...". + if line[..index].ends_with('.') { + continue; + } + let after = index + character.len_utf8(); + let rest = &line[after..]; + let ends = match rest.chars().next() { + None => true, + Some(' ') => rest[1..].chars().next().is_some_and(char::is_uppercase), + Some(_) => false, + }; + if ends && !ABBREVIATIONS.iter().any(|short| line[..after].ends_with(short)) { + return Some(after); + } + } + None +} + +/// The summary shown for an item: the first sentence of its doc comment's first paragraph. Source doc comments are +/// wrapped by hand, so the sentence starts on the first line and may continue on the next ones: the summary carries +/// them until the sentence ends inside a line, and stops at a colon that introduces a list below. +fn doc_summary(attrs: &[Attribute]) -> String { + let mut summary = String::new(); + let paragraph = doc_lines(attrs).into_iter().skip_while(String::is_empty).take_while(|line| !line.is_empty()); + for line in paragraph { + if !summary.is_empty() { + summary.push(' '); + } + match sentence_end(&line) { + Some(end) => { + summary.push_str(&line[..end]); + break; + } + None if line.ends_with(':') => { + summary.push_str(&line); + break; + } + None => summary.push_str(&line), + } + } + drop_self_links(&summary) +} + +/// `summary` with a link that names an item of its own type left as the reference the file writes for a name it cannot +/// link: `Self::zoom_x` names a method of the page the doc comment belongs to, which rustdoc resolves in the source, +/// and this file has no page to link to, so the link keeps its text and loses its target. +fn drop_self_links(summary: &str) -> String { + let mut out = String::with_capacity(summary.len()); + let mut rest = summary; + while let Some(at) = rest.find("](Self::") { + let Some(end) = rest[at..].find(')') else { break }; + out.push_str(&rest[..=at]); + rest = &rest[at + end + 1..]; + } + out.push_str(rest); + out } fn is_hidden(attrs: &[Attribute]) -> bool { @@ -203,16 +269,16 @@ fn variant_line(variant: &syn::Variant) -> String { fn def_of(item: &Item) -> Option { let (name, signature, doc, vis, members, is_type) = match item { Item::Fn(function) => { - (function.sig.ident.to_string(), fn_line(&function.vis, &function.sig), first_doc_line(&function.attrs), &function.vis, Vec::new(), false) + (function.sig.ident.to_string(), fn_line(&function.vis, &function.sig), doc_summary(&function.attrs), &function.vis, Vec::new(), false) } Item::Struct(item) => { let signature = format!("pub struct {}{}{}", item.ident, generics_and_where(&item.generics), fields_summary(&item.fields)); - (item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true) + (item.ident.to_string(), signature, doc_summary(&item.attrs), &item.vis, Vec::new(), true) } Item::Enum(item) => { let variants: Vec = item.variants.iter().map(variant_line).collect(); let signature = format!("pub enum {}{} {{ {} }}", item.ident, generics_and_where(&item.generics), variants.join(", ")); - (item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true) + (item.ident.to_string(), signature, doc_summary(&item.attrs), &item.vis, Vec::new(), true) } Item::Trait(item) => { let supers = if item.supertraits.is_empty() { String::new() } else { format!(": {}", tidy(&item.supertraits)) }; @@ -221,36 +287,26 @@ fn def_of(item: &Item) -> Option { .items .iter() .filter_map(|member| match member { - TraitItem::Fn(function) => Some(Member { signature: tidy(&function.sig), doc: first_doc_line(&function.attrs) }), - TraitItem::Type(assoc) => Some(Member { signature: format!("type {}", assoc.ident), doc: first_doc_line(&assoc.attrs) }), + TraitItem::Fn(function) => Some(Member { signature: tidy(&function.sig), doc: doc_summary(&function.attrs) }), + TraitItem::Type(assoc) => Some(Member { signature: format!("type {}", assoc.ident), doc: doc_summary(&assoc.attrs) }), TraitItem::Const(assoc) => { - Some(Member { signature: format!("const {}: {}", assoc.ident, tidy(&assoc.ty)), doc: first_doc_line(&assoc.attrs) }) + Some(Member { signature: format!("const {}: {}", assoc.ident, tidy(&assoc.ty)), doc: doc_summary(&assoc.attrs) }) } _ => None, }) .collect(); - (item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, members, true) + (item.ident.to_string(), signature, doc_summary(&item.attrs), &item.vis, members, true) } Item::Type(item) => { let signature = format!("pub type {}{} = {}", item.ident, generics_and_where(&item.generics), tidy(&item.ty)); - (item.ident.to_string(), signature, first_doc_line(&item.attrs), &item.vis, Vec::new(), true) + (item.ident.to_string(), signature, doc_summary(&item.attrs), &item.vis, Vec::new(), true) + } + Item::Const(item) => { + (item.ident.to_string(), format!("pub const {}: {}", item.ident, tidy(&item.ty)), doc_summary(&item.attrs), &item.vis, Vec::new(), false) + } + Item::Static(item) => { + (item.ident.to_string(), format!("pub static {}: {}", item.ident, tidy(&item.ty)), doc_summary(&item.attrs), &item.vis, Vec::new(), false) } - Item::Const(item) => ( - item.ident.to_string(), - format!("pub const {}: {}", item.ident, tidy(&item.ty)), - first_doc_line(&item.attrs), - &item.vis, - Vec::new(), - false, - ), - Item::Static(item) => ( - item.ident.to_string(), - format!("pub static {}: {}", item.ident, tidy(&item.ty)), - first_doc_line(&item.attrs), - &item.vis, - Vec::new(), - false, - ), _ => return None, }; let hidden = is_hidden(attrs_of(item)); @@ -394,7 +450,7 @@ impl Walker<'_> { let stem = path.file_stem().and_then(|stem| stem.to_str()).unwrap_or_default(); let parent = path.parent().map(Path::to_path_buf).unwrap_or_default(); let dir = if matches!(stem, "lib" | "mod" | "main") { parent } else { parent.join(stem) }; - let doc = first_doc_line(&file.attrs); + let doc = doc_summary(&file.attrs); self.items(&file.items, module, &dir, reachable, doc); } @@ -416,7 +472,7 @@ impl Walker<'_> { let public = is_public(&declared.vis); entry.children.push(name.clone()); let inline = declared.content.as_ref().map(|(_, content)| content.clone()); - pending.push((name, dir.to_path_buf(), reachable && public, inline.map(|content| (first_doc_line(&declared.attrs), content)))); + pending.push((name, dir.to_path_buf(), reachable && public, inline.map(|content| (doc_summary(&declared.attrs), content)))); } Item::Use(import) => Self::uses(import, &mut entry, is_hidden(&import.attrs)), Item::Impl(imp) if imp.trait_.is_none() => { @@ -428,11 +484,11 @@ impl Walker<'_> { .iter() .filter_map(|member| match member { ImplItem::Fn(function) if is_public(&function.vis) && !is_hidden(&function.attrs) => { - Some(Member { signature: fn_line(&function.vis, &function.sig), doc: first_doc_line(&function.attrs) }) + Some(Member { signature: fn_line(&function.vis, &function.sig), doc: doc_summary(&function.attrs) }) } ImplItem::Const(constant) if is_public(&constant.vis) => Some(Member { signature: format!("pub const {}: {}", constant.ident, tidy(&constant.ty)), - doc: first_doc_line(&constant.attrs), + doc: doc_summary(&constant.attrs), }), _ => None, }) @@ -449,7 +505,7 @@ impl Walker<'_> { let def = Def { name: format!("{name}!"), signature: format!("macro_rules! {name}"), - doc: first_doc_line(&mac.attrs), + doc: doc_summary(&mac.attrs), public: true, hidden: false, members: Vec::new(), @@ -705,8 +761,8 @@ fn listing(root: &Path) -> String { out.push_str( "# Contract API\n\nGenerated by `cl cargo run -p craft-ui-gallery --bin contract-api`; do not edit. Every public item of\n\ `craft_behavior` and of the shared modules of `craft_ui` (`contract`, `layout`, `layout_components`, `primitives`,\n\ - `runtime`, `style`, `testing` and the crate root), by public path, with its signature line and the first line of\n\ - its doc comment. Inherent methods and trait methods are indented under their type. Setters written by\n\ + `runtime`, `style`, `testing` and the crate root), by public path, with its signature line and the first sentence\n\ + of its doc comment. Inherent methods and trait methods are indented under their type. Setters written by\n\ `#[derive(Props)]` are not listed: each `#[prop]` field of a type is a setter of the same name.\n\n\ craft-ui-contract defines every module listed here except `layout_components`, which craft-ui-widgets defines;\n\ the craft-ui facade re-exports each under the same name. `craft_ui::testing` also re-exports the story helpers\n\ diff --git a/crates/ui-panels/src/docking/divider.rs b/crates/ui-panels/src/docking/divider.rs index 73443a597d..0845fc79d3 100644 --- a/crates/ui-panels/src/docking/divider.rs +++ b/crates/ui-panels/src/docking/divider.rs @@ -66,14 +66,26 @@ impl Divider { /// What the pointer did to a divider this pass. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Drag { - /// The drag started. - Start, + /// The drag started: the press moved past slop, and the pointer is at this coordinate along the divider's axis, + /// in reading order. The container begins its gesture and moves the divider to the coordinate in the same pass, + /// as it does for [`To`](Self::To), so the move that starts the drag shows in the pass it happens. + Start(f32), /// The pointer is at this coordinate along the divider's axis, in reading order. To(f32), /// The pointer was released. Release, } +impl Drag { + /// The coordinate the divider is dragged to this pass: the start's and each later move's; `None` for a release. + pub fn coord(self) -> Option { + match self { + Drag::Start(coord) | Drag::To(coord) => Some(coord), + Drag::Release => None, + } + } +} + /// `x` as a coordinate from the start edge of `rect`: unchanged for left-to-right, mirrored for right-to-left. fn logical_x(rect: Rect, rtl: bool, x: f32) -> f32 { if rtl { rect.right() - (x - rect.left()) } else { x } @@ -121,9 +133,10 @@ pub fn pointer(cx: &Cx<'_, C>, key: PartKey, index: u64, divider: /// What the press phase of a divider's part says the pointer did to `divider`, for a container `rect` that is /// mirrored for right-to-left. A body reads the phase from `BodyCx::part_press`. pub fn drag(phase: PressPhase, rect: Rect, rtl: bool, divider: &Divider) -> Option { + let along = |pos: Pos2| if divider.axis == Axis::X { logical_x(rect, rtl, pos.x) } else { pos.y }; match phase { - PressPhase::DragStart { .. } => Some(Drag::Start), - PressPhase::Drag { pos, .. } => Some(Drag::To(if divider.axis == Axis::X { logical_x(rect, rtl, pos.x) } else { pos.y })), + PressPhase::DragStart { pos, .. } => Some(Drag::Start(along(pos))), + PressPhase::Drag { pos, .. } => Some(Drag::To(along(pos))), PressPhase::Release { .. } => Some(Drag::Release), _ => None, } diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 3ab9079c2e..27ba8ffe6b 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -404,7 +404,7 @@ fn body_plan

( let open = (0..group_sizes.len()).filter(|at| !group_sizes[*at].minimized).collect(); let mut plan = Plan { bar, body, groups, heights, mins: group_sizes.iter().map(|size| size.min).collect(), open }; for (key, index, divider) in plan.dividers(body, sizes.reach) { - if let Some(Drag::To(coord)) = drags(key, ÷r) { + if let Some(coord) = drags(key, ÷r).and_then(Drag::coord) { plan.move_divider(index, coord - divider.at); } } @@ -524,7 +524,7 @@ impl Component for DockColumn<'_, P> { } if own { let edge = self.edge_divider(rect, &sizes); - if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { + if let Some(coord) = divider::pointer(cx, EDGE, 0, &edge).and_then(Drag::coord) { self.move_edge(rect, &edge, coord); } if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.step, sizes.jump) { diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index d21986edec..e770a89132 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -669,7 +669,7 @@ impl Component for IconicColumn<'_, P> { } if self.bar == ColumnBar::Own { let edge = self.edge_divider(rect, &sizes.column); - if let Some(Drag::To(coord)) = divider::pointer(cx, EDGE, 0, &edge) { + if let Some(coord) = divider::pointer(cx, EDGE, 0, &edge).and_then(Drag::coord) { self.move_edge(rect, &edge, coord); } if let Some((_, coord)) = divider::keys(cx, EDGE, &[(0, edge)], sizes.column.step, sizes.column.jump) { diff --git a/crates/ui-panels/src/docking/mod.rs b/crates/ui-panels/src/docking/mod.rs index 77cc4da605..c4712ff11e 100644 --- a/crates/ui-panels/src/docking/mod.rs +++ b/crates/ui-panels/src/docking/mod.rs @@ -524,9 +524,13 @@ impl Component for SplitAr let mut edited = false; for (at, (handle, _)) in frames.handles.iter().enumerate() { let divider = divider_of(handle, (0.0, 0.0), rect, &sizes, rtl); - match divider::pointer(cx, HANDLE, at as u64, ÷r) { - Some(Drag::Start) => cx.begin(), - Some(Drag::To(coord)) => { + let dragged = divider::pointer(cx, HANDLE, at as u64, ÷r); + if let Some(Drag::Start(_)) = dragged { + cx.begin(); + } + // The drag's start moves the handle as each later move does, in the same pass. + match dragged { + Some(Drag::Start(coord) | Drag::To(coord)) => { if let Some(next) = moved(&layout, rect, &sizes, &rules, handle, coord - divider.at) { cx.propose(next); edited = true; diff --git a/crates/ui-panels/src/docking/stack.rs b/crates/ui-panels/src/docking/stack.rs index 5be2dfa929..92385ca8d3 100644 --- a/crates/ui-panels/src/docking/stack.rs +++ b/crates/ui-panels/src/docking/stack.rs @@ -210,7 +210,7 @@ impl Component for StackSections { let sizes = cx.style.sizes; let Plan { open, row, dividers } = self.plan(cx.rect, &sizes); for (key, index, divider) in ÷rs { - if let Some(Drag::To(coord)) = divider::pointer(cx, DIVIDER, *key, divider) { + if let Some(coord) = divider::pointer(cx, DIVIDER, *key, divider).and_then(Drag::coord) { self.move_divider(&open, &row, *index, coord - divider.at, sizes.strip); } } diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index cbbb3c7c17..df33cb9290 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -318,6 +318,25 @@ fn alt_click_steps_a_slot_and_a_modified_click_is_never_a_double_click() { assert_eq!(rig.doubles.get(), 1, "two plain clicks are a double click"); } +/// The primary button going down or up at `pos` with `modifiers` in the event itself. +fn primary_with(pos: Pos2, pressed: bool, modifiers: Modifiers) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } +} + +/// A quick Alt-click whose Alt is up again before the frame ends still steps the slot: the click reads the modifiers +/// of its release, not the ones held when the frame runs. +#[trial] +fn an_alt_click_whose_alt_goes_up_in_the_same_frame_steps_the_slot() { + let mut rig = rig(true); + let at = button(&rig).center(); + // Nothing is held when the frame runs; the press and the release carry Alt. + rig.fixture.hold(Modifiers::NONE); + rig.fixture.frame(vec![moved(at), primary_with(at, true, Modifiers::ALT), primary_with(at, false, Modifiers::ALT)]); + rig.fixture.idle(2); + assert_eq!(*rig.selected.borrow(), [REDO], "the Alt-click picks the next tool, not the shown one"); + assert!(rig.fixture.by_role(Role::MENU).is_empty(), "an Alt-click opens no flyout"); +} + /// The name of the flyout's tear-off bar. const TEAR_OFF: &str = "Tear Off Group"; diff --git a/crates/ui-patterns/tests/it/docking/split.rs b/crates/ui-patterns/tests/it/docking/split.rs index 0e25293988..eff7d10cdc 100644 --- a/crates/ui-patterns/tests/it/docking/split.rs +++ b/crates/ui-patterns/tests/it/docking/split.rs @@ -61,6 +61,22 @@ fn a_column_divider_dragged_past_a_minimum_and_back_stays_under_the_pointer() { ); } +/// The move that carries the press past slop moves the divider in its own pass, not the pass after it. +#[trial] +fn a_column_divider_follows_the_move_that_starts_its_drag_in_the_same_pass() { + let (mut fixture, rects) = column(); + fixture.settle(); + let settled = rects.borrow()[0].bottom(); + let grip = divider(&fixture); + let at = grip.center(); + fixture.press(&grip); + let pressed = rects.borrow()[0].bottom(); + assert!((pressed - settled).abs() < f32::EPSILON, "a press with no move leaves the divider where it was: {pressed} for {settled}"); + fixture.frame(vec![pointer::moved(Pos2::new(at.x, at.y + 20.0))]); + let bottom = rects.borrow()[0].bottom(); + assert!((bottom - (at.y + 20.0)).abs() < 1.0, "the divider is at the pointer in the pass the drag starts: {bottom} for {}", at.y + 20.0); +} + #[trial] fn a_resize_under_a_pruned_view_keeps_the_hidden_panels() { let rest = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![1], 0), Node::tabs(vec![2], 0)); diff --git a/crates/ui-widgets/src/menu/popup.rs b/crates/ui-widgets/src/menu/popup.rs index 14b49bc9e8..9026af1fd9 100644 --- a/crates/ui-widgets/src/menu/popup.rs +++ b/crates/ui-widgets/src/menu/popup.rs @@ -85,8 +85,8 @@ impl Outcome for MenuPick { } } -/// The layer of a menu, or of a submenu: a press outside closes it and reaches nothing below, and running a row -/// closes the chain. +/// The layer of a menu, or of a submenu: a press outside closes it, a primary one reaches nothing below, and running a +/// row closes the chain. #[doc(hidden)] pub fn layer(submenu: bool) -> Overlay { let base = if submenu { Overlay::submenu() } else { Overlay::menu() }; diff --git a/crates/ui-widgets/src/value_drag/range_slider.rs b/crates/ui-widgets/src/value_drag/range_slider.rs index 5499109697..3aff3e74d4 100644 --- a/crates/ui-widgets/src/value_drag/range_slider.rs +++ b/crates/ui-widgets/src/value_drag/range_slider.rs @@ -280,10 +280,10 @@ impl Component for RangeSlider<'_> { Vec2::new(cx.style.length.max(labels), height + self.marks.below(&cx.style.track)) } - /// No wheel bits: as a value control the row takes the vertical wheel only while focused or armed, and no scope - /// frees it, since a wheel over the track has no one thumb to step. + /// The vertical wheel only while focused or armed (`Sense::WHEEL_Y_FOCUSED`), which no scope frees, since a wheel + /// over the track has no one thumb to step: it steps the focused one. fn sense(&self) -> Sense { - Sense::empty() + Sense::WHEEL_Y_FOCUSED } /// The track, and a thumb each that is its own Tab stop and takes the arrow keys. diff --git a/crates/ui-widgets/src/value_drag/slider.rs b/crates/ui-widgets/src/value_drag/slider.rs index 75ff053e0b..97da5bbc70 100644 --- a/crates/ui-widgets/src/value_drag/slider.rs +++ b/crates/ui-widgets/src/value_drag/slider.rs @@ -1,8 +1,8 @@ //! `Slider`: a thumb on a track over an `f64` range. A press on the thumb grabs it and a drag moves it by the pointer's -//! travel; a press on the track jumps the thumb there; arrows, the wheel and AccessKit step the value; a double click -//! or the reset intent restores the binding's reset value. The vertical wheel steps it while it is focused or armed, so -//! a panel scrolls over it; inside a `WheelScope::Free` scope (an adjustment dialog) without focus too. The track maps -//! positions to values through a [`SliderScale`], linear by default. +//! travel; a press on the track, or any press while the value is mixed, jumps the thumb there; arrows, the wheel and +//! AccessKit step the value; a double click or the reset intent restores the binding's reset value. The vertical wheel +//! steps it while it is focused or armed, so a panel scrolls over it; inside a `WheelScope::Free` scope (an adjustment +//! dialog) without focus too. The track maps positions to values through a [`SliderScale`], linear by default. use super::track::{self, Along, Fill, MarkInk, MarkSpace, Marks, Press, Scale, SliderScale, ThumbRing, TrackFace, Travel}; use crate::contract::{ @@ -361,7 +361,11 @@ impl Component for Slider<'_> { marks.snapped(&scale, length, position).unwrap_or_else(|| scale.snap(scale.at_position(position))) }; let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or_else(|| scale.middle()); - let press_at = |cx: &Cx<'_, Self>, x: f32| pick.press(&[along.x(scale.position(current(cx)))], x); + // A mixed value has no thumb to grab, so a press anywhere jumps it to the pointer: a click sets that value. + let press_at = |cx: &Cx<'_, Self>, x: f32| match cx.value() { + Some(value) => pick.press(&[along.x(scale.position(*value))], x), + None => Some(Press::Jump(0)), + }; // Multi-clicks keep the legacy track path: reset wins on Down, and a later drag // can still begin from the reset value through the existing DragStart handling. let follow_track_on_down = self.track_press == TrackPress::OnPress @@ -425,8 +429,8 @@ impl Component for Slider<'_> { && let Some(jump @ Press::Jump(_)) = press_at(&*cx, start.origin.x) && let Some(next) = travel.value(jump, 0.0, &press, false) { - // A press on the track jumps to the pointer; a click on the thumb changes nothing. A second - // click is the reset, which the pipeline applies. + // A press on the track, or on a mixed slider, jumps to the pointer; a click on the thumb + // changes nothing. A second click is the reset, which the pipeline applies. cx.set(at(next)); } } diff --git a/crates/ui-widgets/src/value_drag/thumb_row.rs b/crates/ui-widgets/src/value_drag/thumb_row.rs index bf2ba60e86..1c69504daf 100644 --- a/crates/ui-widgets/src/value_drag/thumb_row.rs +++ b/crates/ui-widgets/src/value_drag/thumb_row.rs @@ -977,10 +977,10 @@ impl Component for ThumbRow<'_, N> { Some(craft_behavior::Axis::X) } - /// No wheel bits: as a value control the row takes the vertical wheel only while focused or armed, and no scope - /// frees it, since a wheel over the track has no one thumb to step. + /// The vertical wheel only while focused or armed (`Sense::WHEEL_Y_FOCUSED`), which no scope frees, since a wheel + /// over the track has no one thumb to step: it steps the focused one. fn sense(&self) -> Sense { - Sense::empty() + Sense::WHEEL_Y_FOCUSED } fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { diff --git a/crates/ui-widgets/tests/it/access/scroll_into_view.rs b/crates/ui-widgets/tests/it/access/scroll_into_view.rs index d55b6c2092..e9584ebee9 100644 --- a/crates/ui-widgets/tests/it/access/scroll_into_view.rs +++ b/crates/ui-widgets/tests/it/access/scroll_into_view.rs @@ -1,10 +1,16 @@ //! A screen reader's Scroll Into View shows its node and leaves keyboard focus where it was; a Focus request moves it. +use craft_behavior::{Selection, keyed}; use craft_ui::buttons::Button; -use craft_ui::contract::Show as _; +use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; +use craft_ui::layout_components::Stack; +use craft_ui::list::{List, ListRow}; use craft_ui::testing::focus::AccessActionKind; +use craft_ui::testing::layout::Block; use craft_ui::testing::{Fixture, trial}; -use egui::{Key, Modifiers}; +use egui::{Id, Key, Modifiers, Rect, Vec2}; +use std::cell::Cell; +use std::rc::Rc; #[trial] fn scroll_into_view_moves_no_focus() { @@ -22,3 +28,64 @@ fn scroll_into_view_moves_no_focus() { fixture.access(AccessActionKind::Focus, &second).settle(); assert_ne!(fixture.focused_stop(), focused, "a Focus request moves it"); } + +/// Whether `view` shows all of `row`: a row out of view may report bounds cut to nothing at the view's edge. +fn shows(view: Rect, row: Rect) -> bool { + row.height() > 1.0 && view.expand(0.5).contains_rect(row) +} + +/// A screen reader's Scroll Into View on a list row scrolls the list's own body until the row shows, as the old egui +/// list's scroll area did for any widget in it; on a row already in view it moves nothing. Row 150 is the selection's +/// anchor, so the list builds it, and reports its node, while it is scrolled out. +#[trial] +fn scroll_into_view_on_a_list_row_scrolls_the_list_to_it() { + let list_id = Id::NULL.with("rows"); + let mut fixture = Fixture::new(move |ui| { + let keys: Vec = (0..200).collect(); + let source = keyed(&keys, |key: &usize| *key); + let list = List::new("Rows").id(list_id).selection(Bind::given(Selection::single(150_usize))); + list.show_items(ui, &source, &mut |key, _| ListRow::new(format!("Row {key}"))); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let view = fixture.node_of(list_id).expect("the list's node").rect; + let row = fixture.by_label("Row 150").expect("row 150's node, kept as the anchor"); + assert!(!shows(view, row.rect), "row 150 starts out of view: {:?} in {view:?}", row.rect); + fixture.access(AccessActionKind::ScrollIntoView, &row).settle(); + let shown = fixture.by_label("Row 150").expect("row 150's node").rect; + assert!(shows(view, shown), "Scroll Into View brought row 150 into the list's view: {shown:?} in {view:?}"); + let near = fixture.by_label("Row 148").expect("row 148, in view beside row 150"); + assert!(shows(view, near.rect), "row 148 shows: {:?} in {view:?}", near.rect); + fixture.access(AccessActionKind::ScrollIntoView, &near).settle(); + let after = fixture.by_label("Row 150").expect("row 150's node").rect; + assert!((after.min - shown.min).length() <= 0.5, "Scroll Into View on a row in view moved nothing: {after:?}, was {shown:?}"); +} + +/// A screen reader's Scroll Into View on a button below a scrolling stack's view scrolls the stack until the button +/// shows, as Tab to it does. `room_height` caps the room a container offers its children, not the container itself, so +/// the 100 points go on a host around the scrolling stack: the stack takes at most that room and scrolls the 300-point +/// block and the button under it, as a small window's dialog column does. +#[trial] +fn scroll_into_view_on_a_button_below_a_stacks_view_scrolls_the_stack_to_it() { + let view = Rc::new(Cell::new(Rect::NOTHING)); + let seen = Rc::clone(&view); + let mut fixture = Fixture::new(move |ui| { + Stack::new().fill_width().room_height(100.0).show(ui, |ui, _| { + Stack::new().fill_width().scroll(Scroll::vertical()).show(ui, |ui, cx| { + if !ui.is_sizing_pass() { + seen.set(cx.rect); + } + Block::new(Vec2::new(100.0, 300.0)).show(ui); + Button::new("Far").show(ui); + }); + }); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + let button = fixture.by_label("Far").expect("the button's node"); + assert!(view.get().height() <= 100.5, "the stack takes at most its host's room: {:?}", view.get()); + assert!(!shows(view.get(), button.rect), "the button starts out of view: {:?} in {:?}", button.rect, view.get()); + fixture.access(AccessActionKind::ScrollIntoView, &button).settle(); + let shown = fixture.by_label("Far").expect("the button's node").rect; + assert!(shows(view.get(), shown), "Scroll Into View brought the button into the stack's view: {shown:?} in {:?}", view.get()); +} diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 4dab115cd8..d2cce17e4d 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -4,10 +4,12 @@ //! the app runs itself), and a picture in the leading icon's place. use craft_behavior::{IconId, PartKey}; +use craft_host::target::Os; use craft_theme::ControlSize; use craft_theme::Variant; use craft_ui::buttons::{ - Arrangement, Button, ButtonChord, ControlPlace, GroupLevel, IconButton, PushButtonLook, SplitButton, SplitMenu, SplitMenuEnablement, ToggleButton, + Arrangement, Button, ButtonChord, CommandSearch, ControlPlace, GroupLevel, IconButton, PushButtonLook, SplitButton, SplitMenu, + SplitMenuEnablement, ToggleButton, }; use craft_ui::contract::tooltip::DELAY; use craft_ui::contract::{Bind, CommandSet, Entry, Hover, PopupKind, Props as _, Role, Show as _, ShowContainer as _, Trigger}; @@ -1483,6 +1485,26 @@ fn a_command_button_shows_its_chord_until_the_room_is_short() { assert_eq!(plain_chord, plain_hidden, "a command with no chord shows none"); } +/// The command-search opener's chord part is named by the chord spoken, the name its `Kbd` face gives itself, not by +/// the command's label. +#[trial] +fn a_command_search_chord_part_is_named_by_its_chord_spoken() { + // Not a Ctrl+Alt+F-key: Linux reserves those for its virtual consoles, so the keymap would drop the default and the + // opener would show no chord. + let find = CommandDef::new(CommandRef::new("demo.find"), "Find", Scope::app()) + .with_default(Binding::parse("Cmd+Alt+K").expect("the trial's chord parses")); + let catalog = AppCatalog::new(vec![find], 1).expect("the trial's catalog is valid"); + let mut fixture = Fixture::new(|ui| { + CommandSearch::new(CommandRef::new("demo.find"), "Search commands").show(ui); + }); + fixture.os(Os::Linux).commands(CommandInput::new().catalog(catalog)); + fixture.settle(); + let opener = fixture.by_label("Search commands").expect("the opener is named by its placeholder"); + let chord = fixture.by_label("Ctrl+Alt+K").expect("a node is named by the opener's chord spoken"); + assert!(opener.rect.contains(chord.rect.center()), "the chord's node is the opener's chord part: {:?} in {:?}", chord.rect, opener.rect); + assert!(fixture.by_label("Find").is_none(), "no node is named by the command's label"); +} + /// A toggle button says whether it is pressed both ways: on is pressed and off is not pressed, bound to a value or /// given a shared one (a mode of several objects), where a button with no toggle has no pressed state. Guards against /// an off toggle reading as a plain button. diff --git a/crates/ui-widgets/tests/it/menu/bar.rs b/crates/ui-widgets/tests/it/menu/bar.rs index c2bd11f0fb..ab193f04e6 100644 --- a/crates/ui-widgets/tests/it/menu/bar.rs +++ b/crates/ui-widgets/tests/it/menu/bar.rs @@ -16,7 +16,8 @@ struct Rig { } fn entries() -> Vec { - // Help rows show their entry's label, which can differ from the command's label. + // A help row shows its entry's label and runs its command; the results keep one row per command, so each entry has + // its own. vec![ HelpEntry::new(EditCommands::Paste, "CafĂ©").with_path(["Edit"]), HelpEntry::new(EditCommands::Copy, "Copy").with_english("Duplicate").with_path(["Edit"]), @@ -60,11 +61,13 @@ fn help_search_ignores_accents_and_matches_the_english_label_and_the_path() { rig.fixture.settle(); let search = rig.fixture.by_label("Search menus").expect("the search field"); rig.fixture.click(&search); + // A row is found by the label it shows. "CafĂ©" runs Paste, but no node is named "Paste": the row's shortcut part is + // named by its chord spoken, not by the command's label. for (typed, found, absent) in [("cafe", "CafĂ©", "Copy"), ("duplic", "Copy", "CafĂ©"), ("clipboard", "Cut", "Copy")] { rig.fixture.key(Key::A, Modifiers::COMMAND); rig.fixture.type_text(typed); rig.fixture.settle(); - assert!(rig.open(found), "{typed:?} finds the help entry labelled {found:?}"); + assert!(rig.open(found), "{typed:?} finds the entry whose row reads {found:?}"); assert!(!rig.open(absent), "{typed:?} leaves {absent:?} out"); } } diff --git a/crates/ui-widgets/tests/it/menu/openers.rs b/crates/ui-widgets/tests/it/menu/openers.rs index f6fbb54c10..65a90f7ec3 100644 --- a/crates/ui-widgets/tests/it/menu/openers.rs +++ b/crates/ui-widgets/tests/it/menu/openers.rs @@ -1,4 +1,4 @@ -//! A menu with several openers: a context menu over a popover. +//! Menus and their openers: a context menu over a popover, and a second opener's menu beside an open one. use craft_behavior::IconId; use craft_ui::buttons::{Button, IconButton, PopupMark}; @@ -9,7 +9,7 @@ use craft_ui::runtime::commands::{self, CommandSet as _, EditCommands, FireSourc use craft_ui::runtime::env::Direction; use craft_ui::runtime::frame::take_output; use craft_ui::testing::{Fixture, pointer, trial}; -use egui::{Rect, Shape, pos2}; +use egui::{Pos2, Rect, Shape, pos2}; use std::cell::Cell; use std::rc::Rc; @@ -126,6 +126,45 @@ fn a_new_right_click_moves_an_open_context_menu_to_the_pointer() { assert!(after.min.x > before.min.x + 40.0, "the menu moved to the second point: {before:?} then {after:?}"); } +/// A right-click on a second opener while a menu is open closes that menu and opens the second one, as it does on the +/// opener of a closed one: the press lay outside the menu it closed, not outside the menu it opened. A press is judged +/// against the menus the pass before it showed: one that appears in the press's own pass comes after that record, and +/// the press is not outside it. +#[trial] +fn a_right_click_on_a_second_opener_closes_the_open_menu_and_opens_its_own() { + const FIRST: Rect = Rect { min: Pos2::new(8.0, 8.0), max: Pos2::new(200.0, 32.0) }; + const SECOND: Rect = Rect { min: Pos2::new(8.0, 240.0), max: Pos2::new(200.0, 264.0) }; + let mut fixture = Fixture::new(|ui| { + let first = Button::new("First target").show_at(ui, FIRST); + Menu::context("First menu", &first).show(ui, |ui, _| { + MenuItem::new("First action").show(ui); + }); + let second = Button::new("Second target").show_at(ui, SECOND); + Menu::context("Second menu", &second).show(ui, |ui, _| { + MenuItem::new("Second action").show(ui); + }); + }); + fixture.settle(); + let (first, second) = (FIRST.center(), SECOND.center()); + right_click(&mut fixture, first); + let open = menu_rect(&fixture).expect("the right-click on the first target opens its menu"); + assert!(fixture.by_label("First action").is_some(), "the first menu is open"); + assert!(fixture.by_label("Second action").is_none(), "and only the first menu"); + assert!(!open.contains(second), "the second target stands clear of the open menu: {open:?} {second:?}"); + // A user's right-click: the press closes the first menu, its release opens the second. + right_click(&mut fixture, second); + assert!(fixture.by_label("Second action").is_some(), "the right-click on the second target opens its menu"); + assert!(fixture.by_label("First action").is_none(), "the first menu closed"); + // A press in the pass a menu appears in: a double right-click on the first target, its second press in the frame of + // the release that opens the first menu. That press is the frame's one press, and it lands outside the zone the + // frame begins with, which the second menu still set in the pass it closed, so the pass records it. The first menu + // appears in that same pass, after the record was made, and the record is not for it. + fixture.frame(vec![pointer::moved(first)]).frame(vec![pointer::secondary(first, true)]); + fixture.frame(vec![pointer::secondary(first, false), pointer::secondary(first, true)]).settle(); + assert!(fixture.by_label("First action").is_some(), "the press recorded in the pass the first menu appears in does not close it"); + assert!(fixture.by_label("Second action").is_none(), "and the second menu closed"); +} + /// A menu request retains its point until an image arrives from the clipboard in a later frame. #[trial] fn context_menu_paste_delivers_image_at_the_requested_point() { diff --git a/crates/ui-widgets/tests/it/menu/rows.rs b/crates/ui-widgets/tests/it/menu/rows.rs index 4b187e3417..79707e2416 100644 --- a/crates/ui-widgets/tests/it/menu/rows.rs +++ b/crates/ui-widgets/tests/it/menu/rows.rs @@ -9,7 +9,7 @@ use craft_ui::contract::{CommandSet, Props as _, Show as _, ShowContainer as _, use craft_ui::list::{CommandHighlight, ThumbAspect}; use craft_ui::menu::{Menu, MenuItem}; use craft_ui::primitives::FacePaint; -use craft_ui::runtime::commands::CommandState; +use craft_ui::runtime::commands::{AppCatalog, Binding, CommandDef, CommandInput, CommandRef, CommandState, Scope}; use craft_ui::runtime::env::{Scale, with_env}; use craft_ui::testing::{Fixture, Room, pointer, trial}; use egui::Rect; @@ -168,6 +168,26 @@ fn a_caller_shortcut_wins_over_the_bound_commands_chord_and_hide_shortcut_shows_ assert_eq!(listed(&fixture, "Plain"), None, "and lists none"); } +/// A command row's shortcut part is named by its chord spoken, the name its `Kbd` face gives itself, not by the row's +/// command label. +#[trial] +fn a_command_rows_shortcut_part_is_named_by_its_chord_spoken() { + let save = + CommandDef::new(CommandRef::new("demo.save"), "Save", Scope::app()).with_default(Binding::parse("Cmd+S").expect("the trial's chord parses")); + let catalog = AppCatalog::new(vec![save], 1).expect("the trial's catalog is valid"); + let mut fixture = Fixture::new(|ui| { + Menu::inline("m").show(ui, |ui, _| { + MenuItem::command(CommandRef::new("demo.save")).show(ui); + }); + }); + fixture.os(Os::Linux).commands(CommandInput::new().catalog(catalog)); + fixture.settle(); + let row = fixture.by_label("Save").expect("the row is named by its command"); + let shortcut = fixture.by_label("Ctrl+S").expect("a node is named by the row's chord spoken"); + assert!(row.rect.contains(shortcut.rect.center()), "the chord's node is the row's shortcut part: {:?} in {:?}", shortcut.rect, row.rect); + assert_ne!(shortcut.node, row.node, "the chord names the shortcut part's sub-node, not the row"); +} + #[trial] fn a_detail_shows_as_a_second_line_under_the_label() { let mut fixture = Fixture::new(|ui| { diff --git a/crates/ui-widgets/tests/it/runtime/inspect.rs b/crates/ui-widgets/tests/it/runtime/inspect.rs index 3f24e90960..5b25e7e957 100644 --- a/crates/ui-widgets/tests/it/runtime/inspect.rs +++ b/crates/ui-widgets/tests/it/runtime/inspect.rs @@ -3,13 +3,13 @@ use craft_ui::buttons::Button; use craft_ui::choice::{Checkbox, Radio, RadioGroup}; -use craft_ui::contract::{Bind, CommandSet, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _}; use craft_ui::display::InspectOverlay; use craft_ui::layout_components::Stack; use craft_ui::runtime::commands::CommandRef; use craft_ui::runtime::inspect::{self, Recorded}; -use craft_ui::testing::{Fixture, trial}; -use egui::{Id, Rect}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use egui::{Id, Rect, Ui}; use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; @@ -201,3 +201,125 @@ fn an_element_records_the_command_it_is_bound_to_with_accesskit_off() { assert!(rect.is_positive() && element.rect.expand(0.5).contains_rect(rect), "{:?} lies on its control {:?}", rect, element.rect); } } + +/// A generic component is recorded by its type's own name (`Select`, not its last generic argument), and a text +/// field's facts list the text AccessKit reads as its value. +#[trial] +fn a_region_names_generic_components_and_lists_text_values() { + use craft_ui::contract::Entry; + use craft_ui::pickers::Select; + use craft_ui::text::TextField; + let key = Id::NULL.with("trial.inspect.generic"); + let seen = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let (mut choice, mut text) = (String::from("one"), String::from("abc")); + let mut fixture = Fixture::new(move |ui| { + let entries = [Entry::new(String::from("one"), "One"), Entry::new(String::from("two"), "Two")]; + let (_, recorded) = inspect::record(ui, key, |ui| { + Select::new("Pick", Bind::bound(&mut choice), &entries).show(ui); + TextField::new("Name", Bind::bound(&mut text)).show(ui); + }); + if recorded.is_some() { + *out.borrow_mut() = recorded; + } + }); + fixture.settle(); + let seen = seen.borrow(); + let recorded = seen.as_deref().expect("the region ran"); + let names: Vec<&str> = recorded.elements.iter().map(|element| element.component).collect(); + assert!(names.contains(&"Select"), "the Select is recorded by its type's name: {names:?}"); + let field = recorded.elements.iter().find(|element| element.component == "TextField").expect("the field is recorded"); + let value = field.facts.as_ref().and_then(|facts| facts.value.as_deref()); + assert_eq!(value, Some("abc"), "the field's facts list its text as the value"); +} + +/// A view showing one button, as a panel shows its slots in a memoized grid, and a text field holding `text`. +#[derive(MemoProps)] +struct Grid { + label: &'static str, + text: &'static str, +} + +fn grid(props: &mut Grid, ui: &mut Ui) { + Button::new(props.label).show(ui); + craft_ui::text::TextField::new("Name", Bind::given(props.text.to_owned())).show(ui); + craft_ui::text::TextField::new("Password", Bind::given(String::from("never-inspect-this"))).masked().show(ui); +} + +/// A recorded element and its index in the record. +type Found<'r> = Option<(usize, &'r inspect::Element)>; + +/// What an inspected region records of a button in a memoized view and of a button beside it. +fn grid_and_footer(recorded: &Recorded) -> (Found<'_>, Found<'_>) { + let named = |name: &str| { + recorded.elements.iter().enumerate().find(|(_, element)| { + element.part.is_none() && element.component == "Button" && element.facts.as_ref().and_then(|facts| facts.name.as_deref()) == Some(name) + }) + }; + (named("Slot"), named("Footer")) +} + +#[trial] +fn a_region_keeps_the_components_of_a_memoized_view_in_the_passes_it_replays() { + let key = Id::NULL.with("trial.inspect.memo"); + let seen: Rc>>> = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let (_, recorded) = inspect::record(ui, key, |ui| { + Stack::new().show(ui, |ui, _| { + MemoView::new("grid", Grid { label: "Slot", text: "abc" }, grid).show(ui); + Button::new("Footer").show(ui); + }) + }); + if recorded.is_some() { + *out.borrow_mut() = recorded; + } + }); + let replayed = + |fixture: &Fixture| last_frame_memo_runs(fixture.ctx()).iter().any(|(of, _, run)| of.contains("Grid") && *run == MemoRun::Replayed); + let mut replays = 0; + for frame in 0..8 { + fixture.frame(Vec::new()); + replays += usize::from(replayed(&fixture)); + let seen = seen.borrow(); + let recorded = seen.as_deref().expect("the region ran"); + let (slot, footer) = grid_and_footer(recorded); + let (slot_at, slot) = slot.unwrap_or_else(|| panic!("frame {frame}: the memoized view's button is recorded: {:?}", recorded.elements)); + let (footer_at, footer) = footer.unwrap_or_else(|| panic!("frame {frame}: the button beside the view is recorded")); + assert!(slot_at < footer_at, "frame {frame}: the view's button is recorded before the one after it"); + assert_eq!(slot.depth, footer.depth, "frame {frame}: both sit in the same stack"); + assert!(slot.rect.is_positive() && slot.facts.as_ref().is_some_and(|facts| facts.interactive), "frame {frame}: {slot:?}"); + assert!(recorded.hits.iter().any(|hit| hit.owner == slot.id && hit.rect.is_positive()), "frame {frame}: the view's button has its hit area"); + assert!(slot.stop.is_some() && slot.stop < footer.stop, "frame {frame}: Tab order runs through both, the view's button first"); + let fields: Vec<_> = recorded.elements.iter().filter(|element| element.component == "TextField" && element.part.is_none()).collect(); + assert_eq!(fields.len(), 2, "frame {frame}: both text fields are recorded"); + let values: Vec<_> = fields.iter().map(|field| field.facts.as_ref().and_then(|facts| facts.value.as_deref())).collect(); + assert_eq!(values, [Some("abc"), None], "frame {frame}: replay keeps the displayed value and excludes the masked one"); + } + assert!(replays > 0, "the view replayed in some of the passes"); +} + +/// Inspect the same displayed text as AccessKit, but not text from a masked editor. +#[trial] +fn a_region_exposes_displayed_text_but_not_masked_text() { + use craft_ui::text::TextField; + let key = Id::NULL.with("trial.inspect.masked"); + let seen = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let (_, recorded) = inspect::record(ui, key, |ui| { + TextField::new("Visible", Bind::given(String::from("shown"))).show(ui); + TextField::new("Password", Bind::given(String::from("never-inspect-this"))).masked().show(ui); + }); + if recorded.is_some() { + *out.borrow_mut() = recorded; + } + }); + fixture.settle(); + let seen = seen.borrow(); + let Some(recorded) = seen.as_deref() else { panic!("the region did not run") }; + let fields: Vec<_> = recorded.elements.iter().filter(|element| element.component == "TextField" && element.part.is_none()).collect(); + assert_eq!(fields.len(), 2, "both fields are present: {fields:?}"); + let exposed: Vec<_> = fields.iter().map(|elem| elem.facts.as_ref().and_then(|facts| facts.value.as_deref())).collect(); + assert_eq!(exposed, [Some("shown"), None], "the masked field’s value stays absent"); +} diff --git a/crates/ui-widgets/tests/it/text/text_field.rs b/crates/ui-widgets/tests/it/text/text_field.rs index a2d03b14d2..8858ce8e31 100644 --- a/crates/ui-widgets/tests/it/text/text_field.rs +++ b/crates/ui-widgets/tests/it/text/text_field.rs @@ -1,12 +1,13 @@ //! `TextField`: the search form's clear part empties the text; a multi-line field grows to `max_lines` or fills its -//! room and scrolls its text inside; a bound caret goes both ways. +//! room and scrolls its text inside; a bound caret goes both ways; the wheel over a focused field or check box scrolls +//! the form around it, and a focused number field or range still takes it. use craft_behavior::PartKey; -use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::layout_components::Stack; use craft_ui::testing::{Fixture, pointer, trial}; -use craft_ui::text::TextField; -use egui::{Id, Key, Modifiers, Rect, Vec2}; +use craft_ui::text::{NumberField, TextField}; +use egui::{Id, Key, Modifiers, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -338,6 +339,107 @@ fn the_clear_part_empties_the_field_in_the_pass_of_its_click() { assert_eq!(fixture.tree().value(id.get()), Some(""), "the field reads empty in the pass of the click"); } +/// A 200 Ă— 120 form: `first`, then twenty text fields, in a scrolling stack a 100-point room caps, so the fields +/// overflow it. +fn scrolling_form(mut first: impl FnMut(&mut Ui) + 'static) -> Fixture { + let texts = Rc::new(RefCell::new(vec![String::new(); 20])); + let mut fixture = Fixture::new(move |ui| { + Stack::new().fill_width().room_height(100.0).show(ui, |ui, _| { + Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + first(ui); + for (row, text) in texts.borrow_mut().iter_mut().enumerate() { + TextField::new(format!("Field {row}"), Bind::bound(text)).id_salt(row).show(ui); + } + }); + }); + }); + fixture.room(Vec2::new(200.0, 120.0)).settle(); + fixture +} + +/// The wheel over a focused single-line text field, which has nothing to scroll or step, scrolls the form around it, +/// as native fields do; a focused number field under the pointer still steps by the wheel and keeps the form still. +#[trial] +fn the_wheel_over_a_focused_text_field_scrolls_the_form_around_it() { + let name = Rc::new(RefCell::new(String::new())); + let shown = Rc::clone(&name); + let mut fixture = scrolling_form(move |ui| { + TextField::new("Name", Bind::bound(&mut *shown.borrow_mut())).id_salt("name").show(ui); + }); + let field = fixture.by_label("Name").expect("the Name field"); + fixture.click(&field).settle(); + assert!(fixture.focused_stop().is_some(), "the click focuses the Name field"); + fixture.frame(vec![pointer::moved(field.center())]); + fixture.frame(vec![pointer::wheel(-40.0)]); + fixture.idle(3); + let moved = fixture.by_label("Name").expect("the Name field").rect; + assert!(moved.top() < field.rect.top() - 1.0, "the wheel scrolls the form, moving the Name field up: {:?} to {moved:?}", field.rect); + + let value = Rc::new(Cell::new(Some(10.0))); + let held = Rc::clone(&value); + let mut fixture = scrolling_form(move |ui| { + let mut current = held.get(); + NumberField::new("Size", Bind::bound(&mut current)).id_salt("size").range(0.0..=100.0).show(ui); + held.set(current); + }); + let field = fixture.by_label("Size").expect("the Size field"); + fixture.click(&field).settle(); + fixture.frame(vec![pointer::moved(field.center())]); + fixture.frame(vec![pointer::wheel_lines(1.0)]); + fixture.idle(3); + assert_ne!(value.get(), Some(10.0), "the wheel steps the focused number field"); + let still = fixture.by_label("Size").expect("the Size field").rect; + assert!((still.top() - field.rect.top()).abs() <= SNAP, "and the form stays put: {:?} to {still:?}", field.rect); +} + +/// The wheel over a focused check box, which neither senses nor reads the wheel, scrolls the form around it; a range +/// slider, which senses the wheel only while focused (`Sense::WHEEL_Y_FOCUSED`), still steps its focused thumb and +/// keeps the form still. +#[trial] +fn the_wheel_over_a_focused_check_box_scrolls_the_form_and_a_focused_range_steps() { + use craft_behavior::Mixed; + use craft_ui::choice::Checkbox; + use craft_ui::testing::focus::AccessActionKind; + use craft_ui::value_drag::RangeSlider; + + let agreed = Rc::new(Cell::new(false)); + let shown = Rc::clone(&agreed); + let mut fixture = scrolling_form(move |ui| { + let mut on = shown.get(); + Checkbox::new(Bind::bound(&mut on)).label("Agree").id_salt("agree").show(ui); + shown.set(on); + }); + let check = fixture.by_label("Agree").expect("the Agree check box"); + fixture.access(AccessActionKind::Focus, &check).settle(); + assert!(fixture.focused_stop().is_some(), "the check box holds focus"); + fixture.frame(vec![pointer::moved(check.center())]); + fixture.frame(vec![pointer::wheel(-40.0)]); + fixture.idle(3); + let moved = fixture.by_label("Agree").expect("the Agree check box").rect; + assert!(moved.top() < check.rect.top() - 1.0, "the wheel scrolls the form, moving the check box up: {:?} to {moved:?}", check.rect); + assert!(!agreed.get(), "the wheel leaves the check box's value alone"); + + let start = (Mixed::Same(20.0), Mixed::Same(80.0)); + let range = Rc::new(Cell::new(start)); + let rect = Rc::new(Cell::new(Rect::NOTHING)); + let (held, seen) = (Rc::clone(&range), Rc::clone(&rect)); + let mut fixture = scrolling_form(move |ui| { + let mut pair = held.get(); + seen.set(RangeSlider::new(Bind::bound(&mut pair), 0.0..=100.0).label("Hue").id_salt("hue").show(ui).response.rect); + held.set(pair); + }); + let slider = rect.get(); + // A click on the span between the thumbs focuses the nearer one and moves neither. + fixture.click_at(slider.center()).settle(); + assert!(fixture.focused_stop().is_some_and(|(_, part)| part.is_some()), "the click focuses a thumb"); + assert_eq!(range.get(), start, "the click moves neither thumb"); + fixture.frame(vec![pointer::moved(slider.center())]); + fixture.frame(vec![pointer::wheel_lines(1.0)]); + fixture.idle(3); + assert_ne!(range.get(), start, "the wheel steps the focused thumb"); + assert!((rect.get().top() - slider.top()).abs() <= SNAP, "and the form stays put: {slider:?} to {:?}", rect.get()); +} + /// A field that keeps its text on Escape (`keeps_on_escape`, a live filter's query) commits the typing, lets focus /// go and leaves the same Escape to its enclosing scope; it reports the focus loss as `text_lost_focus`. #[trial] diff --git a/crates/ui-widgets/tests/it/value_drag.rs b/crates/ui-widgets/tests/it/value_drag.rs index 9b18ffc026..0f3de86a5c 100644 --- a/crates/ui-widgets/tests/it/value_drag.rs +++ b/crates/ui-widgets/tests/it/value_drag.rs @@ -200,6 +200,20 @@ fn a_log_slider_spreads_equal_ratios_evenly() { assert!((bottom - min).abs() < 1e-2 * min, "a travel past the start lands on the minimum: {bottom}"); } +/// A mixed slider has no thumb to grab: a click where a single value's thumb would sit, the middle step, sets that step. +#[trial] +fn a_click_on_a_mixed_slider_sets_the_step_under_it() { + use craft_behavior::Mixed; + let value = Rc::new(RefCell::new(Mixed::::Mixed)); + let shown = value.clone(); + let mut fixture = Fixture::new(move |ui| { + Slider::new(Bind::bound_mixed(&mut *shown.borrow_mut()), 0.0..=10.0).step(1.0).label("Hyphenation Weight").show_at(ui, FIELD); + }); + fixture.motion(MotionMode::Off).settle(); + fixture.click_at(FIELD.center()).settle(); + assert_eq!(*value.borrow(), Mixed::Same(5.0), "the click set the middle step"); +} + /// A trimmed span's ends are drawn across the track, not stops: a drag that ends beside one lands where the drag /// puts it. #[trial] diff --git a/docs/contract-api.md b/docs/contract-api.md index 5183054d88..2af417adfd 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2,8 +2,8 @@ Generated by `cl cargo run -p craft-ui-gallery --bin contract-api`; do not edit. Every public item of `craft_behavior` and of the shared modules of `craft_ui` (`contract`, `layout`, `layout_components`, `primitives`, -`runtime`, `style`, `testing` and the crate root), by public path, with its signature line and the first line of -its doc comment. Inherent methods and trait methods are indented under their type. Setters written by +`runtime`, `style`, `testing` and the crate root), by public path, with its signature line and the first sentence +of its doc comment. Inherent methods and trait methods are indented under their type. Setters written by `#[derive(Props)]` are not listed: each `#[prop]` field of a type is a setter of the same name. craft-ui-contract defines every module listed here except `layout_components`, which craft-ui-widgets defines; @@ -13,7 +13,7 @@ craft-ui-canvas, which are not listed. ## `craft_behavior` -Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item layouts, edit events, +Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item layouts, edit events, `overlay::place`, `fit` and the other rules that read no `Context`. - `craft_behavior::AccessAction`: re-export of `accesskit::Action` (outside these crates). - `craft_behavior::AccessData`: re-export of `accesskit::ActionData` (outside these crates). @@ -27,29 +27,29 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::CancelReason`: re-export of `craft_behavior::value::CancelReason`. - `craft_behavior::CancelRule`: re-export of `craft_behavior::focus::CancelRule`. - `craft_behavior::CanvasTransform`: re-export of `craft_behavior::canvas::CanvasTransform`. -- `craft_behavior::CanvasView`: `pub struct CanvasView { pub rect: ScreenRect, pub center: Point, pub zoom: f64, pub rotation: f64, pub flip_x: bool, pub aspect: f64 }`. How a canvas shows its document: where, how large, turned and mirrored how. Apps convert their +- `craft_behavior::CanvasView`: `pub struct CanvasView { pub rect: ScreenRect, pub center: Point, pub zoom: f64, pub rotation: f64, pub flip_x: bool, pub aspect: f64 }`. How a canvas shows its document: where, how large, turned and mirrored how. - `pub fn new(rect: ScreenRect, center: Point, zoom: f64) -> Self`. An upright, unmirrored, square-pixel view of `rect` showing `center` at `zoom`. - `pub const fn rotation(mut self, degrees: f64) -> Self`. The same view turned `degrees` clockwise. - `pub const fn flip_x(mut self, flip: bool) -> Self`. The same view mirrored left-right (or not). - `pub const fn aspect(mut self, aspect: f64) -> Self`. The same view with a document unit `aspect` times as wide as it is tall. - - `pub fn points_per_unit(device_zoom: f64, pixels_per_point: f32) -> f64`. `zoom` for a view that shows `device_zoom` device pixels per document unit at + - `pub fn points_per_unit(device_zoom: f64, pixels_per_point: f32) -> f64`. `zoom` for a view that shows `device_zoom` device pixels per document unit at `pixels_per_point`: 1 shows one document pixel per device pixel at any interface scale. - `pub fn affine(&self) -> Affine`. Document to screen points. - `pub fn to_screen(&self, p: Point) -> Pos2`. Where the view draws document point `p`. - `pub fn to_doc(&self, p: Pos2) -> Point`. The document point under screen position `p`. - `pub fn map_vec(&self, v: Vec2) -> ScreenVec`. A document vector as the view draws it: stretched, turned, zoomed and mirrored. - - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`](Self::map_vec). + - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`]. - `pub fn zoom_x(&self) -> f64`. Screen points per document unit along the document's x axis: `zoom Ă— aspect`. - - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, - - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), + - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, aspect and flip: the bounding box of [`CanvasView::quad`]. + - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), (x0, y1). - `pub fn visible(&self) -> Rect`. The document bounds of the screen rect: every document point the view can show. - - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by - - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, + - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by [`zoom_x`] for its x axis). + - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, unmirrored and square. `None` for any other view; its controls register parts in screen space through [`to_screen`] instead. - `pub fn axis_aligned(&self) -> bool`. Whether the rotation is a multiple of 90°, so document axes are screen axes. - - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same + - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same zoom, flip and aspect, so ticks measured with it never stretch. - `craft_behavior::Caret`: re-export of `craft_behavior::codec::Caret`. - `craft_behavior::CellAdvance`: `pub enum CellAdvance { Enter, Tab }`. Which key moves the active cell after an entry: Enter goes down the rows, Tab along a row. - `craft_behavior::CellAt`: re-export of `craft_behavior::selection::CellAt`. -- `craft_behavior::CellDirection`: `pub enum CellDirection { Up, Down, Left, Right }`. A move of one cell. Logical: in a right-to-left sheet the widget maps the Left arrow to +- `craft_behavior::CellDirection`: `pub enum CellDirection { Up, Down, Left, Right }`. A move of one cell. - `craft_behavior::CellRange`: re-export of `craft_behavior::selection::CellRange`. - `craft_behavior::CellSelection`: re-export of `craft_behavior::selection::CellSelection`. - `craft_behavior::Codec`: re-export of `craft_behavior::codec::Codec`. @@ -68,6 +68,8 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::DisplayOrder`: re-export of `craft_behavior::item_source::DisplayOrder`. - `craft_behavior::DocKey`: re-export of `craft_behavior::doc_key::DocKey`. - `craft_behavior::DockSide`: re-export of `craft_behavior::dock::DockSide`. +- `craft_behavior::DragModifier`: re-export of `craft_behavior::value_drag::DragModifier`. +- `craft_behavior::DragModifiers`: re-export of `craft_behavior::value_drag::DragModifiers`. - `craft_behavior::DragWarp`: re-export of `craft_behavior::value_drag::DragWarp`. - `craft_behavior::DropOperation`: re-export of `craft_behavior::keys::DropOperation`. - `craft_behavior::EditCommand`: re-export of `craft_behavior::intent::EditCommand`. @@ -133,9 +135,9 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `fn is_section(&self, at: usize) -> bool`. Whether the position is a section header, which a move skips. - `fn enabled(&self, at: usize) -> bool`. Whether the position can take the lead. - `fn row_len(&self, _row: usize) -> Option`. `RaggedGrid`: the number of positions in `row`; rows hold consecutive positions. `None` past the last row. - - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are offset against each other (a honeycomb's). 0 for rows that line up. - `fn columns(&self) -> usize`. `Cell`: the cells of every position (a row of a sheet). - - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a + - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a calendar month), `None` for a grid that fills from its first column. - `fn rect(&self, _at: usize) -> Option`. `Spatial`: where the position sits, in any one coordinate space. - `fn is_empty(&self) -> bool`. Whether there are no positions. - `craft_behavior::NavShape`: `pub enum NavShape { Flat, Tree, WrappedGrid { columns: usize }, BoundedGrid { columns: usize }, RaggedGrid, Cell, Spatial }`. The geometry a collection's keyboard navigation follows. @@ -158,7 +160,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::PartRef`: re-export of `craft_behavior::part::PartRef`. - `craft_behavior::PassInput`: re-export of `craft_behavior::press::PassInput`. - `craft_behavior::PixelSize`: re-export of `craft_behavior::pixel_size::PixelSize`. -- `craft_behavior::PlacedSelection`: `pub struct PlacedSelection`. The selected cells by position in one display order: the rows and columns of each range, and the cells taken out +- `craft_behavior::PlacedSelection`: `pub struct PlacedSelection`. The selected cells by position in one display order: the rows and columns of each range, and the cells taken out of them. - `pub fn of_rows(spans: impl IntoIterator>) -> Self`. The selected rows `spans`, every column of each. - `pub fn of_cells(ranges: Vec<(Range, Range)>, mut removed: Vec<(usize, u32)>) -> Self`. The ranges `ranges` (row positions, column positions) without the cells `removed`. - `pub fn holds_row(&self, at: usize) -> bool`. Whether the row at position `at` has a selected cell. @@ -171,7 +173,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::PointerGlyph`: re-export of `craft_behavior::cursor::PointerGlyph`. - `craft_behavior::PointerKind`: re-export of `craft_behavior::press::PointerKind`. - `craft_behavior::PointerSample`: re-export of `craft_behavior::press::PointerSample`. -- `craft_behavior::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and +- `craft_behavior::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and `index_of` answers without a scan. - `pub const fn new(rows: u32) -> Self`. The order of `rows` rows. - `craft_behavior::PressAside`: re-export of `craft_behavior::press::PressAside`. - `craft_behavior::PressCancel`: re-export of `craft_behavior::press::PressCancel`. @@ -195,19 +197,19 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `pub const fn page(mut self, rows: Option) -> Self`. Rows a Page key covers. - `pub const fn letters(mut self, letters: Letters) -> Self`. Whether letters pick entries. - `pub const fn arrows(mut self, arrows: Arrows) -> Self`. The arrows the group takes. - - `pub const fn first_column(mut self, column: usize) -> Self`. The column of the first member of a wrapped grid with `column` blank cells before it: Up and Down keep the + - `pub const fn first_column(mut self, column: usize) -> Self`. The column of the first member of a wrapped grid with `column` blank cells before it: Up and Down keep the column, Home and End go to the ends of the row. - `pub const fn hands_back(mut self) -> Self`. A move the group cannot make reaches the owning component, which may page or change what the group shows. - `pub const fn keeps_lead_moves(mut self) -> Self`. Left and Right with the lead modifier reach the focused member. - `pub const fn no_lead(mut self, on: bool) -> Self`. Whether the focused member is no lead: the next move starts at an end, as from a group with no lead. - `pub const fn state(&self, lead: Option) -> NavState`. The state a step over this group starts from, at `lead`, or from no lead when the group has none. - - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document + - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document canvas that scrolls sideways), Start and End only with Home and End, and no `lead_step` in a group that `keeps_lead_moves`. - `craft_behavior::RowAt`: re-export of `craft_behavior::selection::RowAt`. -- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; +- `craft_behavior::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` + - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along this axis, with labels at least `step_min` points apart. + - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` screen points per document unit (PhotoCraft's Shift snap, #3770). - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: @@ -232,19 +234,19 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::TileLayout`: re-export of `craft_behavior::item_layout::TileLayout`. - `craft_behavior::TypeAhead`: `pub struct TypeAhead`. Typed letters of the last second as one prefix. - `pub const fn new() -> Self`. An empty buffer. - - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, - - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one + - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, applied in `pick`, so it follows the interface language. + - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one repeated letter (so repeating a letter cycles), from `from` itself for a longer prefix, wrapping at the end. - `craft_behavior::Typed`: re-export of `craft_behavior::typing::Typed`. - `craft_behavior::TypingRun`: re-export of `craft_behavior::typing::TypingRun`. - `craft_behavior::Validity`: re-export of `craft_behavior::value::Validity`. - `craft_behavior::Value`: re-export of `craft_behavior::value::Value`. - `craft_behavior::ValueDrag`: re-export of `craft_behavior::value_drag::ValueDrag`. -- `craft_behavior::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. The app records +- `craft_behavior::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. - `pub const LIMIT: usize`. Entries kept; the oldest go first. - - `pub fn leave(&mut self, place: ViewPlace)`. The view is about to jump away from `place`: its entry keeps the centre and zoom the - - `pub fn visit(&mut self, place: ViewPlace)`. The view jumped to `place`. Visiting after Go Back drops the Go Forward entries; visiting - - `pub fn go(&mut self, step: isize, exists: impl Fn(&K) -> bool) -> Option>`. Go Back or Go Forward: the place to show, skipping places that no longer exist. Going -- `craft_behavior::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's + - `pub fn leave(&mut self, place: ViewPlace)`. The view is about to jump away from `place`: its entry keeps the centre and zoom the jump left it at, so Go Back returns there. + - `pub fn visit(&mut self, place: ViewPlace)`. The view jumped to `place`. + - `pub fn go(&mut self, step: isize, exists: impl Fn(&K) -> bool) -> Option>`. Go Back or Go Forward: the place to show, skipping places that no longer exist. +- `craft_behavior::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's centre and zoom there. - `pub const fn new(key: K, center: Point, zoom: f64) -> Self`. The view of `key` centred on `center` at `zoom`. - `craft_behavior::Wheel`: re-export of `craft_behavior::wheel::Wheel`. - `craft_behavior::WheelEase`: re-export of `craft_behavior::wheel::WheelEase`. @@ -266,9 +268,9 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::is_selectable`: re-export of `craft_behavior::role_rule::is_selectable`. - `craft_behavior::keyed`: re-export of `craft_behavior::item_source::keyed`. - `craft_behavior::kurbo`: re-export of `craft_behavior::kurbo` (defined outside these crates). -- `craft_behavior::lead_step`: `pub const fn lead_step(mv: NavMove, mods: MoveMods) -> Option`. The step Left or Right with the lead modifier makes, physical as the arrows are: Ctrl+Left and Ctrl+Right (Back +- `craft_behavior::lead_step`: `pub const fn lead_step(mv: NavMove, mods: MoveMods) -> Option`. The step Left or Right with the lead modifier makes, physical as the arrows are: Ctrl+Left and Ctrl+Right (Back and Forward with the lead), and Cmd+Left and Cmd+Right on macOS, which the key table makes a move to the start or end of the line. - `craft_behavior::pick_instance`: re-export of `craft_behavior::command::pick_instance`. -- `craft_behavior::resize_cursor`: `pub fn resize_cursor(view: &CanvasView, doc_dir: Vec2) -> CursorIcon`. The resize arrow for moving along document direction `doc_dir`, as `view` shows it (its +- `craft_behavior::resize_cursor`: `pub fn resize_cursor(view: &CanvasView, doc_dir: Vec2) -> CursorIcon`. The resize arrow for moving along document direction `doc_dir`, as `view` shows it (its rotation, flip and aspect): the nearest of the four arrows. - `craft_behavior::resolve`: re-export of `craft_behavior::hit::resolve`. - `craft_behavior::resolve_columns`: re-export of `craft_behavior::grid::resolve_columns`. - `craft_behavior::resolve_flags`: re-export of `craft_behavior::command::resolve_flags`. @@ -277,7 +279,7 @@ Pure UI behaviours (layer 1): press lifecycle, `ValueDrag`, navigation, item lay - `craft_behavior::same_in_f32`: re-export of `craft_behavior::value::same_in_f32`. - `craft_behavior::same_in_f32_at`: re-export of `craft_behavior::value::same_in_f32_at`. - `craft_behavior::sub_row_cells`: re-export of `craft_behavior::columns::sub_row_cells`. -- `craft_behavior::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries +- `craft_behavior::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries ([`Wheel::lines`]), and one for a share of points or pages, up for positive scroll. - `craft_behavior::wrap_value`: re-export of `craft_behavior::value_drag::wrap_value`. ## `craft_behavior::anchor` @@ -293,8 +295,8 @@ The nine points of a box, shared by the transform box rules and the reference po `Arrangement`: a custom placement for a body, in logical coordinates. -- `craft_behavior::arrangement::Arrangement`: `pub trait Arrangement`. A placement of keyed children measured by the caller. Logical: x runs from the start edge of `room`, so - - `fn place(&self, room: Rect, sizes: &[Vec2], out: &mut Vec) -> Vec2`. Fills `out` with one rect per entry of `sizes`, in order, inside `room`; returns the size the placement +- `craft_behavior::arrangement::Arrangement`: `pub trait Arrangement`. A placement of keyed children measured by the caller. + - `fn place(&self, room: Rect, sizes: &[Vec2], out: &mut Vec) -> Vec2`. Fills `out` with one rect per entry of `sizes`, in order, inside `room`; returns the size the placement takes. - `fn mirrors(&self) -> bool`. False for a placement that must not mirror (a free-position board). ## `craft_behavior::canvas` @@ -304,80 +306,80 @@ The transform a canvas body is shown through, and the canvas view with its zoom - `craft_behavior::canvas::CanvasTransform`: `pub struct CanvasTransform { pub scale: f32, pub offset: Vec2 }`. A canvas body's mapping from canvas coordinates to its layer: `screen = canvas * scale + offset`. - `pub const fn new(scale: f32, offset: Vec2) -> Self`. The transform with `scale` layer points per canvas unit and the canvas origin at `offset`. - `pub fn to_layer(&self, canvas: Pos2) -> Pos2`. The position in the layer of a canvas point. -- `craft_behavior::canvas::CanvasView`: `pub struct CanvasView { pub rect: ScreenRect, pub center: Point, pub zoom: f64, pub rotation: f64, pub flip_x: bool, pub aspect: f64 }`. How a canvas shows its document: where, how large, turned and mirrored how. Apps convert their +- `craft_behavior::canvas::CanvasView`: `pub struct CanvasView { pub rect: ScreenRect, pub center: Point, pub zoom: f64, pub rotation: f64, pub flip_x: bool, pub aspect: f64 }`. How a canvas shows its document: where, how large, turned and mirrored how. - `pub fn new(rect: ScreenRect, center: Point, zoom: f64) -> Self`. An upright, unmirrored, square-pixel view of `rect` showing `center` at `zoom`. - `pub const fn rotation(mut self, degrees: f64) -> Self`. The same view turned `degrees` clockwise. - `pub const fn flip_x(mut self, flip: bool) -> Self`. The same view mirrored left-right (or not). - `pub const fn aspect(mut self, aspect: f64) -> Self`. The same view with a document unit `aspect` times as wide as it is tall. - - `pub fn points_per_unit(device_zoom: f64, pixels_per_point: f32) -> f64`. `zoom` for a view that shows `device_zoom` device pixels per document unit at + - `pub fn points_per_unit(device_zoom: f64, pixels_per_point: f32) -> f64`. `zoom` for a view that shows `device_zoom` device pixels per document unit at `pixels_per_point`: 1 shows one document pixel per device pixel at any interface scale. - `pub fn affine(&self) -> Affine`. Document to screen points. - `pub fn to_screen(&self, p: Point) -> Pos2`. Where the view draws document point `p`. - `pub fn to_doc(&self, p: Pos2) -> Point`. The document point under screen position `p`. - `pub fn map_vec(&self, v: Vec2) -> ScreenVec`. A document vector as the view draws it: stretched, turned, zoomed and mirrored. - - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`](Self::map_vec). + - `pub fn unmap_vec(&self, v: ScreenVec) -> Vec2`. The document vector a screen vector shows: the inverse of [`map_vec`]. - `pub fn zoom_x(&self) -> f64`. Screen points per document unit along the document's x axis: `zoom Ă— aspect`. - - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, - - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), + - `pub fn extent(&self, r: Rect) -> ScreenVec`. The screen size of the box that holds document rect `r` at the view's zoom, rotation, aspect and flip: the bounding box of [`CanvasView::quad`]. + - `pub fn quad(&self, r: Rect) -> [Pos2; 4]`. The screen corners of document rect `r`, in order round it: (x0, y0), (x1, y0), (x1, y1), (x0, y1). - `pub fn visible(&self) -> Rect`. The document bounds of the screen rect: every document point the view can show. - - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by - - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, + - `pub fn doc_len(&self, points: f32) -> f64`. A screen distance in document units along the document's y axis (divide by [`zoom_x`] for its x axis). + - `pub fn layer_transform(&self) -> Option`. The transform a canvas body is shown through when this view only scales and moves the document: unturned, unmirrored and square. `None` for any other view; its controls register parts in screen space through [`to_screen`] instead. - `pub fn axis_aligned(&self) -> bool`. Whether the rotation is a multiple of 90°, so document axes are screen axes. - - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same -- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; + - `pub fn level(&self, zero: Point) -> CanvasView`. The view without its rotation, moved so it draws `zero` where this view does: the same zoom, flip and aspect, so ticks measured with it never stretch. +- `craft_behavior::canvas::RulerUnits`: `pub struct RulerUnits { pub per_doc: f64, pub ticks: Ticks, pub labels: TickLabels }`. The ruler unit of one document axis: its size, its ticks and how it labels them. - `pub const fn new(per_doc: f64, ticks: Ticks) -> Self`. Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. - `pub const fn with_labels(mut self, labels: TickLabels) -> Self`. The units with their ticks written as `labels`. - `pub const fn pixels() -> Self`. Whole document pixels. - - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along - - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` + - `pub fn step(&self, zoom: f64, step_min: f32) -> (f64, u32)`. The labelled step in ruler units and its subdivisions when one document unit is `zoom` screen points along this axis, with labels at least `step_min` points apart. + - `pub fn snap_to_tick(&self, position: f64, zero: f64, zoom: f64, step_min: f32) -> f64`. `position` (document units) moved to the nearest minor tick of the ruler counting from `zero`, at `zoom` screen points per document unit (PhotoCraft's Shift snap, #3770). - `pub fn distance(&self, position: f64, zero: f64) -> f64`. The distance of `position` (document units) from `zero`, in ruler units. - `pub fn label_decimals(&self, step: f64) -> RangeInclusive`. The least and most decimals a ruler writes a tick of labelled step `step` with. - `pub fn label_value(&self, value: f64, step: f64) -> f64`. The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: - `craft_behavior::canvas::TickLabels`: `pub enum TickLabels { Distance, Signed }`. How a ruler writes the number at a labelled tick. - `craft_behavior::canvas::Ticks`: `pub enum Ticks { Decimal { whole: bool }, Custom(fn(f64) -> (f64, u32)) }`. How a ruler divides its unit at a zoom. - `pub const fn decimal(whole: bool) -> Self`. PhotoCraft's decimal steps; `whole` keeps the step a whole number of units without 2.5. -- `craft_behavior::canvas::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. The app records +- `craft_behavior::canvas::ViewHistory`: `pub struct ViewHistory`. The places a window jumped between, oldest first, with the one it shows now. - `pub const LIMIT: usize`. Entries kept; the oldest go first. - - `pub fn leave(&mut self, place: ViewPlace)`. The view is about to jump away from `place`: its entry keeps the centre and zoom the - - `pub fn visit(&mut self, place: ViewPlace)`. The view jumped to `place`. Visiting after Go Back drops the Go Forward entries; visiting - - `pub fn go(&mut self, step: isize, exists: impl Fn(&K) -> bool) -> Option>`. Go Back or Go Forward: the place to show, skipping places that no longer exist. Going -- `craft_behavior::canvas::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's + - `pub fn leave(&mut self, place: ViewPlace)`. The view is about to jump away from `place`: its entry keeps the centre and zoom the jump left it at, so Go Back returns there. + - `pub fn visit(&mut self, place: ViewPlace)`. The view jumped to `place`. + - `pub fn go(&mut self, step: isize, exists: impl Fn(&K) -> bool) -> Option>`. Go Back or Go Forward: the place to show, skipping places that no longer exist. +- `craft_behavior::canvas::ViewPlace`: `pub struct ViewPlace { pub key: K, pub center: Point, pub zoom: f64 }`. Where a view stood: what it showed (`key`: a page, an artboard, a document) and the view's centre and zoom there. - `pub const fn new(key: K, center: Point, zoom: f64) -> Self`. The view of `key` centred on `center` at `zoom`. - `craft_behavior::canvas::ZoomFloor`: re-export of `craft_behavior::canvas::zoom::ZoomFloor`. - `craft_behavior::canvas::ZoomScheme`: re-export of `craft_behavior::canvas::zoom::ZoomScheme`. -- `craft_behavior::canvas::resize_cursor`: `pub fn resize_cursor(view: &CanvasView, doc_dir: Vec2) -> CursorIcon`. The resize arrow for moving along document direction `doc_dir`, as `view` shows it (its +- `craft_behavior::canvas::resize_cursor`: `pub fn resize_cursor(view: &CanvasView, doc_dir: Vec2) -> CursorIcon`. The resize arrow for moving along document direction `doc_dir`, as `view` shows it (its rotation, flip and aspect): the nearest of the four arrows. ## `craft_behavior::canvas::zoom` -Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zoom In / Zoom Out rungs, Fit on +Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zoom In / Zoom Out rungs, Fit on Screen and Fill Screen, a zoom about a point and the anchors of wheel zoom. - `craft_behavior::canvas::zoom::ZoomFloor`: `pub enum ZoomFloor { ShorterSide(f64), Fixed(f64) }`. The least zoom: the document's shorter side that many device pixels, or a fixed zoom in scheme units. -- `craft_behavior::canvas::zoom::ZoomScheme`: `pub struct ZoomScheme { pub rungs: &'static [f64], pub max: f64, pub floor: ZoomFloor, pub hundred: f64 }`. A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of +- `craft_behavior::canvas::zoom::ZoomScheme`: `pub struct ZoomScheme { pub rungs: &'static [f64], pub max: f64, pub floor: ZoomFloor, pub hundred: f64 }`. A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of 100 %. - `pub const PHOTOSHOP: ZoomScheme`. Photoshop's: 33 rungs, up to 12800 %, the shorter side 2 px at the least. - `pub const ILLUSTRATOR: ZoomScheme`. Illustrator's: 26 stops from 3.13 % to 64000 %. - `pub const fn with_hundred(self, device: f64) -> Self`. The scheme with `device` as the device zoom of 100 %. - - `pub fn min(&self, size: Size) -> f64`. The least device zoom for a document of `size`. An empty size (a view before its first frame) gives the lowest + - `pub fn min(&self, size: Size) -> f64`. The least device zoom for a document of `size`. - `pub fn max_device(&self) -> f64`. The greatest device zoom. - `pub fn clamp(&self, device: f64, size: Size) -> f64`. `device` within the range for a document of `size`; a zoom that is not a finite number becomes 100 %. - - `pub fn step(&self, device: f64, dir: i32, size: Size) -> f64`. Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it (a zoom within 0.1 % of a rung - - `pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64`. [`step`](Self::step) within an explicit range of device zoom (a navigator or a zoom field with bounds of its - - `pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive`. A zoom field's range in percent: the document's range widened to include `device` itself. A field narrower than + - `pub fn step(&self, device: f64, dir: i32, size: Size) -> f64`. Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it (a zoom within 0.1 % of a rung counts as on it), within the document's range. + - `pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64`. [`step`] within an explicit range of device zoom (a navigator or a zoom field with bounds of its own). + - `pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive`. A zoom field's range in percent: the document's range widened to include `device` itself. - `pub fn percent(&self, device: f64) -> f64`. `device` zoom as percent of the scheme's 100 %. - `pub fn device(&self, percent: f64) -> f64`. The device zoom of `percent` of the scheme's 100 %. -- `craft_behavior::canvas::zoom::about`: `pub fn about(view: &mut CanvasView, screen: Pos2, device_zoom: f64, center_on_point: bool, pixels_per_point: f32)`. Set the zoom to `device_zoom` (clamped by the caller) keeping the document point under +- `craft_behavior::canvas::zoom::about`: `pub fn about(view: &mut CanvasView, screen: Pos2, device_zoom: f64, center_on_point: bool, pixels_per_point: f32)`. Set the zoom to `device_zoom` (clamped by the caller) keeping the document point under `screen` where it is, or, with Zoom Clicked Point to Center (`center_on_point`), moving it to the view's centre. - `craft_behavior::canvas::zoom::anchor`: `pub fn anchor(view: &mut CanvasView, screen: Pos2, doc: Point, device_zoom: f64, pixels_per_point: f32)`. Set the zoom to `device_zoom` with the document point `doc` shown at `screen`. - `craft_behavior::canvas::zoom::device`: `pub fn device(view: &CanvasView, pixels_per_point: f32) -> f64`. `view.zoom` as device zoom (1 = 100 %) at `pixels_per_point`. -- `craft_behavior::canvas::zoom::fill`: `pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme)`. Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend -- `craft_behavior::canvas::zoom::fit`: `pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme)`. Fit on Screen: centre the document and zoom so all of it shows inside `view.rect` less `margin` points on -- `craft_behavior::canvas::zoom::fit_rect`: `pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme)`. Fit a part of the document on screen (an artboard, the selected layers' bounds): centre `rect`, in document -- `craft_behavior::canvas::zoom::fit_up_to`: `pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme)`. [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is -- `craft_behavior::canvas::zoom::step`: `pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool`. View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next rung of the scheme -- `craft_behavior::canvas::zoom::wheel_anchor`: `pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2`. Where a wheel or pinch zoom anchors for a pointer at `screen`: the pointer over the document, +- `craft_behavior::canvas::zoom::fill`: `pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme)`. Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend past the canvas. +- `craft_behavior::canvas::zoom::fit`: `pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme)`. Fit on Screen: centre the document and zoom so all of it shows inside `view.rect` less `margin` points on each side, never past 100 % (one document pixel per device pixel, so a 150 % display does not open documents magnified). `size` is in document units; the view's [`aspect`](CanvasView::aspect) and rotation are taken into account. +- `craft_behavior::canvas::zoom::fit_rect`: `pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme)`. Fit a part of the document on screen (an artboard, the selected layers' bounds): centre `rect`, in document units, and zoom so all of it shows inside `view.rect` less `margin.x` points at the left and right and `margin.y` at the top and bottom, up to the scheme's greatest zoom. +- `craft_behavior::canvas::zoom::fit_up_to`: `pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme)`. [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is magnified to fill the canvas, as Photoshop's Fit on Screen does. +- `craft_behavior::canvas::zoom::step`: `pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool`. View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next rung of the scheme ([`ZoomScheme::step`]), the view's centre unchanged. +- `craft_behavior::canvas::zoom::wheel_anchor`: `pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2`. Where a wheel or pinch zoom anchors for a pointer at `screen`: the pointer over the document, else the document's nearest point (an anchor out on the pasteboard slides the image out of the window after a few notches; Photoshop keeps it in view). - `craft_behavior::canvas::zoom::with_device`: `pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> CanvasView`. `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. -- `craft_behavior::canvas::zoom::wrapped_canvas`: `pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> ScreenVec`. The window-canvas size at which the zoomed document fits: the canvas size less the view's +- `craft_behavior::canvas::zoom::wrapped_canvas`: `pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> ScreenVec`. The window-canvas size at which the zoomed document fits: the canvas size less the view's rect size plus the screen extent of the whole document. ## `craft_behavior::codec` -`Codec`: how a text part turns a value into text and text into a value (18.2), with the library codecs of this +`Codec`: how a text part turns a value into text and text into a value (18.2), with the library codecs of this crate. - `craft_behavior::codec::Caret`: `pub enum Caret { All, End }`. Where the caret goes when the part takes focus. - `craft_behavior::codec::Codec`: `pub trait Codec`. A value's text form. @@ -391,30 +393,31 @@ Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zo - `fn whole_paste(&self, _pasted: &str) -> bool`. Whether a paste the codec reads whole replaces the field's text, wherever the caret is. - `fn normalise(&self, _text: &str, v: &Self::Value) -> String`. The text the field shows after committing `v`, which was parsed from `text`. - `fn caret_on_focus(&self, _text: &str) -> Caret`. Where the caret goes when the part takes focus with this text. - - `fn sample(&self, current: &Self::Value) -> Cow<'_, str>`. The widest typical text, for the field's ideal width. Codecs with bounded text only; `PlainText` returns + - `fn sample(&self, current: &Self::Value) -> Cow<'_, str>`. The widest typical text, for the field's ideal width. - `craft_behavior::codec::NotAValue`: `pub struct NotAValue`. The text is not a value of the codec's type. -- `craft_behavior::codec::NumberCodec`: `pub struct NumberCodec`. An optional number: empty text is `None`; anything else reads through a [`Reader`]. +- `craft_behavior::codec::NumberCodec`: `pub struct NumberCodec`. An optional number: empty text is `None`; anything else reads through a [`Reader`] unless overridden with [`NumberCodec::parse_with`]. - `pub fn new(reader: Reader, decimals: usize) -> Self`. A codec reading with `reader` and writing at most `decimals` decimal places. - - `pub fn fixed(mut self) -> Self`. The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown - - `pub fn zoom_typing(mut self) -> Self`. The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the + - `pub fn fixed(mut self) -> Self`. The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown at a set precision does. + - `pub fn zoom_typing(mut self) -> Self`. The same codec with the typing rules of a zoom field: digits, `/` and the decimal separator, `a/b` as the percentage `a Ă· b Ă— 100`, and a second separator cutting the text. - `pub fn signed_zoom(mut self) -> Self`. Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. - - `pub fn share_of_start(mut self) -> Self`. The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit + - `pub fn share_of_start(mut self) -> Self`. The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit started from, as a size field does: every pass of the edit reads the same value. - `pub fn at_most(mut self, decimals: usize) -> Self`. The same codec writing at most `decimals` decimal places. - - `pub fn or_parse(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the - - `pub fn widest(&self, range: &RangeInclusive) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of + - `pub fn or_parse(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the field's context ("Auto") can stand for numbers. + - `pub fn parse_with(mut self, parse: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self`. The same codec with an authoritative reader for the complete, trimmed, non-empty input. + - `pub fn widest(&self, range: &RangeInclusive) -> String`. The widest text the codec writes for a number in `range`: the longest of each end and the number one place of the last decimal inside it ("100" and "99.9" over 0 to 100 at one decimal), so a field over the range is sized for any value it shows in it. - `pub fn decimals(&self) -> usize`. The most decimal places the codec writes. - `pub fn reader(&self) -> &Reader`. The reader the codec parses with. - `craft_behavior::codec::ParseNote`: `pub struct ParseNote { pub unit: Option, pub held: Option, pub cut: bool }`. What a parse learned beside the value. - `craft_behavior::codec::PlainText`: `pub struct PlainText`. Plain text: every draft is a value. -- `craft_behavior::codec::decimals_for_step`: `pub fn decimals_for_step(step: f64) -> usize`. The decimal places a step needs to be written exactly: 2 for 0.25, 3 for 0.001, 0 for a whole step. A step with +- `craft_behavior::codec::decimals_for_step`: `pub fn decimals_for_step(step: f64) -> usize`. The decimal places a step needs to be written exactly: 2 for 0.25, 3 for 0.001, 0 for a whole step. ## `craft_behavior::columns` Column keys, widths and the sections a grid layout reports. -- `craft_behavior::columns::ColumnKey`: `pub struct ColumnKey`. The key of a column; stable across reordering and resizing. It serializes as its name, or as its position for a +- `craft_behavior::columns::ColumnKey`: `pub struct ColumnKey`. The key of a column; stable across reordering and resizing. - `pub const fn new(key: &'static str) -> Self`. A key named `key`. - - `pub const fn index(column: u32) -> Self`. The key of the column at `column` in a sheet whose columns are numbered rather than named + - `pub const fn index(column: u32) -> Self`. The key of the column at `column` in a sheet whose columns are numbered rather than named (`SheetLayout::lines`). - `pub fn as_str(&self) -> Option<&str>`. The name of a key made by [`ColumnKey::new`]; `None` for a numbered key. - `pub fn position(&self) -> Option`. The position a key made by [`ColumnKey::index`] holds; `None` for a named key. - `craft_behavior::columns::ColumnWidth`: `pub enum ColumnWidth { Content, Fixed(f32), Controls(f32), Toggle, Fill { weight: f32 } }`. How wide a column is. @@ -424,16 +427,16 @@ Column keys, widths and the sections a grid layout reports. - `pub fn new(rect: Rect, columns: Range, edges: Vec) -> Self`. A section at `rect` showing `columns` with their edges. - `craft_behavior::columns::GridView`: `pub struct GridView { pub sections: SmallVec<[GridSection; 4]> }`. The sections of a sheet layout, one per frozen area. - `pub fn new(sections: impl IntoIterator) -> Self`. A view of `sections`, in reading order. -- `craft_behavior::columns::sub_row_cells`: `pub fn sub_row_cells(cells: &mut [(ColumnKey, Rect)], is_toggle: impl Fn(&ColumnKey) -> bool, indent: f32, rtl: bool)`. Moves the toggle cells of a sub-row (`ItemSource::sub_row`) into its content: side by side in column order, each +- `craft_behavior::columns::sub_row_cells`: `pub fn sub_row_cells(cells: &mut [(ColumnKey, Rect)], is_toggle: impl Fn(&ColumnKey) -> bool, indent: f32, rtl: bool)`. Moves the toggle cells of a sub-row (`ItemSource::sub_row`) into its content: side by side in column order, each its column's width, `indent` from the start edge of the first cell that is not a toggle cell, which then starts after them. ## `craft_behavior::command` -The pure rules of command routing (spec 11.3): which state a command resolves to, and which live instance +The pure rules of command routing (spec 11.3): which state a command resolves to, and which live instance of a scope receives a command fired by a key, the menu bar, the palette or automation. - `craft_behavior::command::CommandFlags`: `pub struct CommandFlags { pub enabled: bool, pub checked: Option }`. A command's enabled and checked state. - `pub const fn new(enabled: bool, checked: Option) -> Self`. Flags with the given enabled and checked state. - `pub const DEFAULT: CommandFlags`. A command nobody published a state for: enabled, with no checked state. -- `craft_behavior::command::pick_instance`: `pub fn pick_instance(live: &[I], focused: &[I], last_focused: &[I]) -> Option`. The instance a non-component source delivers to, out of the live instances of the command's scope in +- `craft_behavior::command::pick_instance`: `pub fn pick_instance(live: &[I], focused: &[I], last_focused: &[I]) -> Option`. The instance a non-component source delivers to, out of the live instances of the command's scope in registration order: the one that contains key focus (`focused`, innermost last), else the one that contained it most recently (`last_focused`), else the first live one. `None` when no instance is live. - `craft_behavior::command::resolve_flags`: `pub const fn resolve_flags(this_frame: Option, last_frame: Option) -> CommandFlags`. This frame's state, else last frame's, else the default. ## `craft_behavior::cursor` @@ -448,11 +451,11 @@ Cursor requests as plain data and the rule that picks the winner (8.5). - `craft_behavior::cursor::IconId`: `pub struct IconId`. An icon's egui-free key (5.2), so plain data such as [`PaintedCursor::Tool`] names icons without egui. - `pub const fn new(name: &'static str) -> Self`. The icon named `name`. - `pub fn name(&self) -> &str`. The name. -- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId, badge: Option }, Hidden, IBeam }`. A cursor the overlay host paints. Geometry is in screen points around the pointer (a tool scales its brush +- `craft_behavior::cursor::PaintedCursor`: `pub enum PaintedCursor { Crosshair, Circle { radius: f32, centre: bool, badge: Option }, Outline { rings: Vec>, centre: bool, badge: Option }, Hand, Zoom { out: bool }, Tool { icon: IconId, hotspot: Vec2, badge: Option }, Badged { base: CursorIcon, badge: CursorBadge }, Turn { toward: Vec2 }, Distort { dir: Vec2 }, Skew { dir: Vec2 }, TypeOn { path: bool }, Locator, Arrow { hollow: bool, toward: Option }, PathText { start: bool, end: bool }, PointerTool { pointer: PointerGlyph, icon: IconId, badge: Option }, Hidden, IBeam }`. A cursor the overlay host paints. - `pub const CENTRE_ARM: f32`. The arm of the centre mark of a circle or an outline, in points. - `pub const fn circle(radius: f32) -> Self`. A circle of `radius` points, with no centre mark and no badge. - `pub fn outline(rings: Vec>) -> Self`. App shapes as closed rings, with no centre mark and no badge. - - `pub fn marked(self, centre: bool, badge: Option) -> Self`. A circle or an outline with the centre mark when `centre` and `badge` centred on the pointer; any other cursor + - `pub fn marked(self, centre: bool, badge: Option) -> Self`. A circle or an outline with the centre mark when `centre` and `badge` centred on the pointer; any other cursor unchanged. - `pub const fn zoom(out: bool) -> Self`. A magnifier, zooming out when `out`. - `pub const fn tool(icon: IconId, hotspot: Vec2, badge: Option) -> Self`. A tool's icon with its hotspot and an optional badge. - `pub const fn turn(toward: Vec2) -> Self`. The rotate pointer bent toward screen direction `toward`. @@ -471,12 +474,12 @@ Cursor requests as plain data and the rule that picks the winner (8.5). ## `craft_behavior::digit_keys` -[`DigitKeys`]: Photoshop's number keys for a tool's opacity. 1 sets 10 % … 9 sets 90 %, 0 sets 100 %; two digits +[`DigitKeys`]: Photoshop's number keys for a tool's opacity. 1 sets 10 % … 9 sets 90 %, 0 sets 100 %; two digits typed within [`DigitKeys::TWO_DIGITS`] seconds set the exact value (4 then 5 is 45 %, 0 then 0 is 0 %). - `craft_behavior::digit_keys::DigitEntry`: `pub struct DigitEntry { pub percent: f64, pub second: bool }`. What a number key sets: the percentage and which value. -- `craft_behavior::digit_keys::DigitKeys`: `pub struct DigitKeys`. The number keys' state between presses: the first digit of a pair. The app keeps one. +- `craft_behavior::digit_keys::DigitKeys`: `pub struct DigitKeys`. The number keys' state between presses: the first digit of a pair. - `pub const TWO_DIGITS: f64`. Seconds within which a second digit makes an exact value. - - `pub fn press(&mut self, digit: u8, second: bool, now: f64) -> Option`. One press of `digit` (0..=9) for the second value or not, at `now` seconds: 10 Ă— the digit (0: 100) on its own, + - `pub fn press(&mut self, digit: u8, second: bool, now: f64) -> Option`. One press of `digit` (0..=9) for the second value or not, at `now` seconds: 10 Ă— the digit (0: 100) on its own, or the two-digit value when it follows a first digit for the same value in time. `None` for a digit over 9. ## `craft_behavior::divider` @@ -486,22 +489,22 @@ The resize of a row of segments separated by dividers. - `craft_behavior::divider::Segment`: `pub struct Segment { pub extent: f32, pub min: f32, pub max: f32 }`. One segment of a row: its extent along the row and its limits. - `pub const fn new(extent: f32, min: f32, max: f32) -> Self`. A segment of `extent` that stays within `min` and `max`. - `pub const fn unbounded(extent: f32, min: f32) -> Self`. A segment of `extent` with no upper limit. -- `craft_behavior::divider::resize`: `pub fn resize(row: &[Segment], index: usize, target: f32, give: Give) -> Vec`. The extents of `row` after the divider after `row[index]` moves to `target`, a distance from the row's start, clamped -- `craft_behavior::divider::travel`: `pub fn travel(row: &[Segment], index: usize, give: Give) -> (f32, f32)`. How far the divider after `row[index]` can move: `(lo, hi)`, with `lo <= 0 <= hi`. Toward the start the segments +- `craft_behavior::divider::resize`: `pub fn resize(row: &[Segment], index: usize, target: f32, give: Give) -> Vec`. The extents of `row` after the divider after `row[index]` moves to `target`, a distance from the row's start, clamped to its [`travel`]. +- `craft_behavior::divider::travel`: `pub fn travel(row: &[Segment], index: usize, give: Give) -> (f32, f32)`. How far the divider after `row[index]` can move: `(lo, hi)`, with `lo <= 0 <= hi`. ## `craft_behavior::doc_key` A stable, crate-prefixed semantic key for presence, automation, undo names and programmatic focus. - `craft_behavior::doc_key::DocKey`: `pub struct DocKey`. A document key such as `"craft-ui.find-field"`. - - `pub const fn new(name: &'static str) -> DocKey`. A key `crate-prefix.name`; evaluated in a const context it rejects a malformed name at compile time. The + - `pub const fn new(name: &'static str) -> DocKey`. A key `crate-prefix.name`; evaluated in a const context it rejects a malformed name at compile time. - `pub const fn name(self) -> &'static str`. The name the key was declared with. ## `craft_behavior::dock` -The dock model: the tree of splits over panel frames, the side of a group a drop lands on (20.6), and the rules +The dock model: the tree of splits over panel frames, the side of a group a drop lands on (20.6), and the rules that edit it. -- `craft_behavior::dock::DockSide`: `pub enum DockSide { Start, End, Top, Bottom, Center }`. The side of a group a dropped panel docks on, in reading order: `Start` is the left half in a left-to-right +- `craft_behavior::dock::DockSide`: `pub enum DockSide { Start, End, Top, Bottom, Center }`. The side of a group a dropped panel docks on, in reading order: `Start` is the left half in a left-to-right window and the right half in a right-to-left one. - `pub const fn axis(self) -> Option`. The axis the side splits along; `None` for `Center`. - `pub fn area(self, group: Rect) -> Rect`. The part of `group` a panel docked on this side takes: the half on that side, or the whole group. - `craft_behavior::dock::Action`: `pub enum Action

{ Move { panel: P, anchor: P, placement: DockPlacement

}, Float { panel: P, rect: Rect }, Close { panel: P }, Activate { panel: P }, Open { panel: P, anchor: Option

}, OpenAt { panel: P, anchor: P, placement: DockPlacement

}, MoveFloating { panel: P, rect: Rect, edge: Option }, ResizeSplit { path: Vec, size: SplitSize }, SetStackOpen { panel: P, open: bool }, ResizeStack { panel: P, height: Option }, MoveGroup { panel: P, to: Target

}, StepGroup { panel: P, up: bool }, MoveColumn { panel: P, to: Target

}, MoveWindow { panel: P, to: Target

}, CloseGroup { panel: P }, CloseWindow { panel: P }, CloseOthers { panel: P }, SetMinimized { panel: P, minimized: bool }, SetIconic { panel: P, iconic: bool }, ResizeColumn { panel: P, width: f32 }, SetColumnSteps { panel: P, steps: u16 }, ResizeGroup { panel: P, height: Option }, ResizeFlyoutWidth { panel: P, width: Option }, MoveFlyoutTop { panel: P, offset: Option }, ResizeIconic { panel: P, width: Option }, SetNative { panel: P, placement: Option }, MovePanel { panel: P, to: Target

}, Restore { panel: P, location: Location

} }`. Groups, columns and floating windows are named by a panel they contain. @@ -534,8 +537,8 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn set_native(panel: P, placement: Option) -> Self`. Builds [`Action::SetNative`]. - `pub fn move_panel(panel: P, to: Target

) -> Self`. Builds [`Action::MovePanel`]. - `pub fn restore(panel: P, location: Location

) -> Self`. Builds [`Action::Restore`]. -- `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. The n-up entries split the document area into that many - - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and +- `craft_behavior::dock::Arrangement`: `pub enum Arrangement { TileAllVertically, TileAllHorizontally, TwoUpVertical, TwoUpHorizontal, ThreeUpVertical, ThreeUpHorizontal, ThreeUpStacked, FourUp, SixUp, ConsolidateAllToTabs, Cascade, Tile, FloatInWindow, FloatAllInWindows, NewWindowForDocument, MatchZoom, MatchLocation, MatchRotation, MatchAll }`. One Window › Arrange entry. + - `pub fn group_count(self, documents: usize) -> Option`. How many document groups an n-up or tile arrangement wants, `None` for the window and view entries. - `pub fn enabled(self, documents: usize, groups: usize, floating: usize) -> bool`. Whether the entry is enabled with `documents` open and `floating` floating windows: - `craft_behavior::dock::Column`: `pub struct Column

{ pub groups: Vec>, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. One column of groups from top to bottom: a column of a dock, or the whole of a floating window. - `pub fn new(groups: Vec>) -> Self`. A column of `groups`, expanded at the theme's column width until the user resizes it. @@ -544,34 +547,34 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn with_steps(mut self, steps: u16) -> Self`. The column `steps` content columns wide ([`Self::steps`]). - `pub fn panels(&self) -> impl Iterator`. Every panel of the column, top group first. - `craft_behavior::dock::ColumnLocation`: `pub struct ColumnLocation { pub side: Option, pub width: Option, pub iconic: bool, pub iconic_width: Option, pub steps: Option }`. The column a closed panel's group was in. - - `pub const fn new(side: Option, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side` (`None` for a floating window's column), `width` points wide when expanded (the + - `pub const fn new(side: Option, width: Option, iconic: bool, iconic_width: Option) -> Self`. A column location on `side` (`None` for a floating window's column), `width` points wide when expanded (the theme's column width for `None`). - `pub const fn with_steps(mut self, steps: Option) -> Self`. The location with the column `steps` content columns wide ([`Column::steps`]). -- `craft_behavior::dock::DockEdge`: `pub enum DockEdge { Start, End }`. The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces -- `craft_behavior::dock::DockError`: `pub enum DockError { LimitExceeded, DuplicatePanel, MissingPanel, MissingTarget, InvalidSelection, InvalidGeometry, InvalidPlacement, NotAllowed, UnsupportedVersion }`. Why a layout edit or load was refused. The layout is unchanged when an edit fails. +- `craft_behavior::dock::DockEdge`: `pub enum DockEdge { Start, End }`. The window edge a [`Node::Dock`] sits on, in reading order so right-to-left interfaces mirror. `Start` is the edge of a horizontal split's first child; the renderer maps it to a physical edge from the layout direction. +- `craft_behavior::dock::DockError`: `pub enum DockError { LimitExceeded, DuplicatePanel, MissingPanel, MissingTarget, InvalidSelection, InvalidGeometry, InvalidPlacement, NotAllowed, UnsupportedVersion }`. Why a layout edit or load was refused. - `craft_behavior::dock::DockPlacement`: `pub enum DockPlacement

{ Tab { before: Option

}, Split(DockSide), SplitSized { zone: DockSide, size: SplitSize, outer: SplitSize }, Group { below: bool, height: Option }, Column { after: bool }, Edge(DockSide) }`. Where a moved panel goes relative to an anchor panel. - `pub fn tab(before: Option

) -> Self`. Builds [`DockPlacement::Tab`]. - `pub fn group(below: bool, height: Option) -> Self`. Builds [`DockPlacement::Group`]. - `pub fn column(after: bool) -> Self`. Builds [`DockPlacement::Column`]. - - `pub fn allowed_by(&self, anchor: Permissions) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs` and `shares_column`, a group + - `pub fn allowed_by(&self, anchor: Permissions) -> bool`. Whether the anchor's permissions take this placement: tabs need `accepts_tabs` and `shares_column`, a group in the anchor's column `shares_column`, and side splits `accepts_splits`. - `craft_behavior::dock::DocumentGroup`: `pub struct DocumentGroup { pub id: u64, pub documents: Vec, pub shown: Option }`. A document group: the documents in one tab strip, one of them shown. - `pub fn new(id: u64, documents: Vec) -> Self`. A group with id `id` holding `documents`, none shown. -- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)>, pub arrangement: Option }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. Saved with each - - `pub fn float(&mut self, document: &D, rect: Rect) -> Option`. Float `document` from its group into a new window at `rect`. A document alone in a - - `pub fn float_all(&mut self, area: Rect, size: Vec2, step: f32)`. Every document into its own floating window, cascaded from `area`'s top left. A floating - - `pub fn consolidate(&mut self, active: Option<&D>)`. Every document back into one docked group, the active one shown. A document in several - - `pub fn split_into(&mut self, n: usize)`. Split the docked documents into `n` groups for an n-up arrangement, in order. The first - - `pub fn new_window_for(&mut self, document: &D, rect: Rect) -> u64`. A second view of `document`: the same document id in a new window; the app keeps one - - `pub fn close_window(&mut self, id: u64) -> bool`. Closes floating window `id`. Its documents return to the first docked group, or to a new docked group when - - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. A document a group - - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The -- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column - - `pub fn new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id +- `craft_behavior::dock::DocumentWindows`: `pub struct DocumentWindows { pub docked: Vec>, pub floating: Vec<(DocumentGroup, Rect)>, pub arrangement: Option }`. The document windows of the app: the tabbed groups in the canvas area and the floating ones. + - `pub fn float(&mut self, document: &D, rect: Rect) -> Option`. Float `document` from its group into a new window at `rect`. + - `pub fn float_all(&mut self, area: Rect, size: Vec2, step: f32)`. Every document into its own floating window, cascaded from `area`'s top left. + - `pub fn consolidate(&mut self, active: Option<&D>)`. Every document back into one docked group, the active one shown. + - `pub fn split_into(&mut self, n: usize)`. Split the docked documents into `n` groups for an n-up arrangement, in order. + - `pub fn new_window_for(&mut self, document: &D, rect: Rect) -> u64`. A second view of `document`: the same document id in a new window; the app keeps one view state per (document, window). + - `pub fn close_window(&mut self, id: u64) -> bool`. Closes floating window `id`. + - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. + - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. +- `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. + - `pub fn new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. - `pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self`. The window `id` with one group. - - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. Ids must be unique within a layout. + - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. - `pub fn stack(id: u64, groups: Vec>, rect: Rect) -> Option`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such + - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. - `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. - `pub fn new(panels: Vec

, active: usize) -> Self`. A group of `panels` with tab `active` selected, expanded and with no preferred height or flyout geometry. - `pub fn active_panel(&self) -> Option<&P>`. The selected panel, or `None` when `active` is out of range. @@ -579,22 +582,22 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn new(minimized: bool, height: Option, column: Option) -> Self`. A group location with the given state and column. - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. -- `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. - - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id - - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every +- `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. + - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. + - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every id it has drawn since, so an id, and the OS window it names, is never given to another window while the layout lives. - `pub fn window_floor(&self) -> u64`. The least id above every id the layout holds or has held. - - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and - - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. On excessive input returns no more than the limit. + - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and that no frame, group, column or window is empty. + - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. - `pub fn can_step_group(&self, panel: &P, up: bool, permissions: impl Fn(&P) -> Permissions) -> bool`. Whether [`Action::StepGroup`] would move `panel`'s group, for enabling a menu item. - `pub fn location(&self, panel: &P) -> Result, DockError>`. Capture a panel's nearest surviving group/split neighbor before hiding it. - - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating, - - `pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError>`. Restore an absent panel at a captured location. Missing anchors are reported without + - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. + - `pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError>`. Restore an absent panel at a captured location. - `pub fn open_at_edge(&mut self, panel: P) -> Result<(), DockError>`. Open an absent panel as a frame at the outer edge of the docked area, taking most of it: -- `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option, pub closed_with: Vec

}`. A closed panel's former placement. Applications may retain this beside visibility flags. +- `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option, pub closed_with: Vec

}`. A closed panel's former placement. - `pub fn new(anchor: Option

, placement: DockPlacement

) -> Self`. A location relative to `anchor` by `placement`, with no recorded sizes or siblings. - `craft_behavior::dock::MAX_DEPTH`: `pub const MAX_DEPTH: usize`. Limits are checked before cloning or recursively modifying an application layout. -- `craft_behavior::dock::MAX_PANELS`: `pub const MAX_PANELS: usize`. Most panels a layout may hold. Larger layouts fail with [`DockError::LimitExceeded`](super::DockError::LimitExceeded). +- `craft_behavior::dock::MAX_PANELS`: `pub const MAX_PANELS: usize`. Most panels a layout may hold. - `craft_behavior::dock::NamedWorkspace`: `pub struct NamedWorkspace

{ pub id: String, pub name: String, pub layout: Workspace

, pub chrome: WorkspaceChrome, pub keeps: WorkspaceKeeps }`. One named workspace. - `pub fn new(id: impl Into, name: impl Into, layout: Workspace

) -> Self`. A workspace named `name` with the stable id `id`, showing every bar and capturing nothing beside the layout. - `craft_behavior::dock::Node`: `pub enum Node

{ Split { axis: Axis, size: SplitSize, first: Box>, second: Box> }, Tabs { panels: Vec

, active: usize }, Stack { entries: Vec> }, Dock { side: DockEdge, columns: Vec> } }`. A node of a layout tree. @@ -602,12 +605,12 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn split(axis: Axis, size: SplitSize, first: Node

, second: Node

) -> Self`. Two children along `axis`, sharing the room by `size`. - `pub fn stack(entries: Vec>) -> Self`. Builds [`Node::Stack`]. - `pub fn dock(side: DockEdge, columns: Vec>) -> Self`. Builds [`Node::Dock`]. -- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, group: usize } }`. Where a panel is. Paths lead from the root: false is a split's first child, true its second. +- `craft_behavior::dock::PanelPlace`: `pub enum PanelPlace { Node(Vec), Dock { path: Vec, column: usize, group: usize }, Floating { window: usize, group: usize } }`. Where a panel is. - `pub fn tree_path(&self) -> Option<&[bool]>`. The path of a `Tabs` or `Stack` node of the docked tree; `None` for a group of a column. - `pub fn group_index(&self) -> Option`. The group's index in its column; `None` for a `Tabs` or `Stack` node of the docked tree. -- `craft_behavior::dock::PanelState`: `pub enum PanelState { Hidden, Open, Front }`. What the Window menu shows for a panel. The model does not track the z-order of floating -- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool, pub collapses: bool, pub shares_column: bool, pub docks_outside_columns: bool }`. What may happen to a panel. `Layout::apply_with_permissions` enforces these for every - - `pub const ALL: Self`. Every right: the panel moves, floats, closes, takes tabs and splits, collapses, shares its column and docks +- `craft_behavior::dock::PanelState`: `pub enum PanelState { Hidden, Open, Front }`. What the Window menu shows for a panel. +- `craft_behavior::dock::Permissions`: `pub struct Permissions { pub movable: bool, pub floatable: bool, pub closable: bool, pub accepts_tabs: bool, pub accepts_splits: bool, pub collapses: bool, pub shares_column: bool, pub docks_outside_columns: bool }`. What may happen to a panel. `Layout::apply_with_permissions` enforces these for every action, whoever issues it. + - `pub const ALL: Self`. Every right: the panel moves, floats, closes, takes tabs and splits, collapses, shares its column and docks outside dock columns. - `pub const PROTECTED: Self`. A document canvas: it stays docked and open, and takes neither tabs nor side splits. - `pub const fn movable(mut self, movable: bool) -> Self`. These permissions with [`Self::movable`] set to `movable`. - `pub const fn floatable(mut self, floatable: bool) -> Self`. These permissions with [`Self::floatable`] set to `floatable`. @@ -617,11 +620,11 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn collapses(mut self, collapses: bool) -> Self`. These permissions with [`Self::collapses`] set to `collapses`. - `pub const fn shares_column(mut self, shares_column: bool) -> Self`. These permissions with [`Self::shares_column`] set to `shares_column`. - `pub const fn docks_outside_columns(mut self, docks_outside_columns: bool) -> Self`. These permissions with [`Self::docks_outside_columns`] set to `docks_outside_columns`. - - `pub fn is_protected(self) -> bool`. A canvas: it can neither move, close nor take tabs. `accepts_splits` and `floatable` + - `pub fn is_protected(self) -> bool`. A canvas: it can neither move, close nor take tabs. `accepts_splits` and `floatable` do not matter, so a canvas that opens panels beside it still counts. - `pub fn locked(self) -> Self`. Lock Workspace: nothing moves, floats or closes; tab and split drops and the column rights keep their policy. - `craft_behavior::dock::SIDE_ZONE_DEPTH_SHARE`: `pub const SIDE_ZONE_DEPTH_SHARE: f32`. The most of a body's smaller side that a [`ZoneSize::Depth`] zone reaches, so a body always keeps a middle. -- `craft_behavior::dock::SIDE_ZONE_FRACTION`: `pub const SIDE_ZONE_FRACTION: f32`. Share of a body, from each edge, that means "beside" under [`ZoneSize::Fraction`]: of its width from the start -- `craft_behavior::dock::SplitSize`: `pub enum SplitSize { Ratio(f32), FixedFirst(f32), FixedSecond(f32) }`. A transient sizing request. Applications may adapt their own persisted sizing enum. +- `craft_behavior::dock::SIDE_ZONE_FRACTION`: `pub const SIDE_ZONE_FRACTION: f32`. Share of a body, from each edge, that means "beside" under [`ZoneSize::Fraction`]: of its width from the start and end edges, of its height from the top and bottom edges. +- `craft_behavior::dock::SplitSize`: `pub enum SplitSize { Ratio(f32), FixedFirst(f32), FixedSecond(f32) }`. A transient sizing request. - `craft_behavior::dock::StackEntry`: `pub struct StackEntry

{ pub panel: P, pub open: bool, pub height: Option }`. One panel of a [`Node::Stack`] accordion. - `pub fn new(panel: P) -> Self`. An open accordion section for `panel` with no preferred height. - `craft_behavior::dock::Target`: `pub enum Target

{ At { anchor: P, placement: DockPlacement

}, NewDock { side: DockEdge }, Float { rect: Rect, edge: Option } }`. Where a group, column or floating window goes. @@ -630,52 +633,52 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. - `craft_behavior::dock::Workspace`: `pub struct Workspace

`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating + - `pub const VERSION: u32`. The format version written to files. - `pub fn version(&self) -> u32`. The format version the workspace was read with. - `pub fn layout(&self) -> &Layout

`. The current arrangement. - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels, and the closed panels that were floating, with the docked location each one left. - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. - - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. - - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`] and nothing else. + - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. - `pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool)`. Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. - - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this - - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened - - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. Returns the panels the -- `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. The default shows every bar. + - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. + - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. + - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. +- `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. - `craft_behavior::dock::WorkspaceError`: `pub enum WorkspaceError { UnknownId, NameTaken, EmptyName, CurrentCannotBeDeleted }`. Why a [`WorkspaceSet`] edit was refused. -- `craft_behavior::dock::WorkspaceKeeps`: `pub struct WorkspaceKeeps { pub shortcuts: bool, pub menus: bool, pub toolbar: bool }`. What a saved workspace captures beside the panel layout (the Capture boxes of New Workspace). The application +- `craft_behavior::dock::WorkspaceKeeps`: `pub struct WorkspaceKeeps { pub shortcuts: bool, pub menus: bool, pub toolbar: bool }`. What a saved workspace captures beside the panel layout (the Capture boxes of New Workspace). - `pub const NONE: WorkspaceKeeps`. Captures nothing beside the layout. - `pub const ALL: WorkspaceKeeps`. Captures shortcuts, menus and toolbar. - `pub const fn new(shortcuts: bool, menus: bool, toolbar: bool) -> Self`. The keeps with shortcuts, menus and toolbar as given. -- `craft_behavior::dock::WorkspaceSet`: `pub struct WorkspaceSet

{ pub builtin: Vec>, pub saved: Vec>, pub current: String, pub locked: bool, pub edited: BTreeMap> }`. The app's workspaces: built-ins first, saved ones after, one current. It is a settings +- `craft_behavior::dock::WorkspaceSet`: `pub struct WorkspaceSet

{ pub builtin: Vec>, pub saved: Vec>, pub current: String, pub locked: bool, pub edited: BTreeMap> }`. The app's workspaces: built-ins first, saved ones after, one current. - `pub fn new(builtin: Vec>) -> Self`. A set of `builtin` workspaces with the first one current. - `pub fn current(&self) -> Option<&NamedWorkspace

>`. The current workspace, or `None` when `current` names none. - `pub fn find(&self, id: &str) -> Option<&NamedWorkspace

>`. The workspace with this id. - `pub fn layout(&self) -> Option<&Workspace

>`. The layout the current workspace shows: what it was left with, else its stored one. - - `pub fn select(&mut self, id: &str, live: &mut Workspace

) -> Result<(), WorkspaceError>`. Switch to `id` and replace `live` with the layout it shows; the current workspace's live - - `pub fn check_name<'n>(&self, name: &'n str) -> Result<(&'n str, Option<&str>), WorkspaceError>`. Whether `name` can be saved: the trimmed name, and the id of the saved workspace it would replace (any case), - - `pub fn save(&mut self, name: &str, live: Workspace

, chrome: WorkspaceChrome, keeps: WorkspaceKeeps) -> Result`. Save `live` under `name`, capturing `keeps`, and make it current; [`check_name`](Self::check_name) refuses + - `pub fn select(&mut self, id: &str, live: &mut Workspace

) -> Result<(), WorkspaceError>`. Switch to `id` and replace `live` with the layout it shows; the current workspace's live layout is kept under its id first (Photoshop remembers the state of each workspace until Reset). + - `pub fn check_name<'n>(&self, name: &'n str) -> Result<(&'n str, Option<&str>), WorkspaceError>`. Whether `name` can be saved: the trimmed name, and the id of the saved workspace it would replace (any case), if any. + - `pub fn save(&mut self, name: &str, live: Workspace

, chrome: WorkspaceChrome, keeps: WorkspaceKeeps) -> Result`. Save `live` under `name`, capturing `keeps`, and make it current; [`check_name`] refuses the name or names the saved workspace it replaces. - `pub fn delete(&mut self, id: &str) -> Result<(), WorkspaceError>`. Delete a saved workspace; the current one can't be deleted (Photoshop greys it). - - `pub fn reset(&mut self, live: &mut Workspace

) -> Result<(), WorkspaceError>`. Reset the current workspace: drop what it was left with and replace `live` with its stored + - `pub fn reset(&mut self, live: &mut Workspace

) -> Result<(), WorkspaceError>`. Reset the current workspace: drop what it was left with and replace `live` with its stored layout (a built-in's code layout, or the layout it was saved with). - `craft_behavior::dock::ZoneSize`: `pub enum ZoneSize { Depth(f32), Fraction }`. How deep the side zones of a body are. -- `craft_behavior::dock::arrange_rects`: `pub fn arrange_rects(arrangement: Arrangement, area: Rect, n: usize) -> Option>`. The cells of an n-up or Tile All arrangement inside `area`, in reading order. `Tile All +- `craft_behavior::dock::arrange_rects`: `pub fn arrange_rects(arrangement: Arrangement, area: Rect, n: usize) -> Option>`. The cells of an n-up or Tile All arrangement inside `area`, in reading order. `Tile All Vertically` gives `n` columns, `Horizontally` `n` rows, 3-up Stacked one left cell and two stacked on the right, 4-up and 6-up grids of 2Ă—2 and 3Ă—2. - `craft_behavior::dock::first_active`: `pub fn first_active

(root: &Node

) -> Option<&P>`. The shown panel of a tree's first group. - `craft_behavior::dock::node_at`: `pub fn node_at<'a, P>(mut node: &'a Node

, path: &[bool]) -> Option<&'a Node

>`. The node at `path` from `root`: false is a split's first child, true its second. - `craft_behavior::dock::tree_panels`: `pub fn tree_panels

(root: &Node

) -> Vec<&P>`. The panels of a tree in order, without recursion; at most [`MAX_PANELS`]. -- `craft_behavior::dock::zones`: `pub fn zones(body: Rect, size: ZoneSize, rtl: bool) -> [(DockSide, Rect); 5]`. The zones of `body`, the part of a group below its tab strip: the start and end zones along its full height, +- `craft_behavior::dock::zones`: `pub fn zones(body: Rect, size: ZoneSize, rtl: bool) -> [(DockSide, Rect); 5]`. The zones of `body`, the part of a group below its tab strip: the start and end zones along its full height, the top and bottom zones between them, and the middle. `Start` is the physical left rect, or the right rect when `rtl`. ## `craft_behavior::edit_history` `EditHistory`: the undo and redo of a dialog, a tool session or the keymap editor, fed by edit events. -- `craft_behavior::edit_history::EditHistory`: `pub struct EditHistory`. Undo and redo stacks of a value `T`, at most 100 steps. A gesture is one step: `Begin` opens it, `Commit` closes it, +- `craft_behavior::edit_history::EditHistory`: `pub struct EditHistory`. Undo and redo stacks of a value `T`, at most 100 steps. - `pub fn new(now: &T) -> Self`. A history that starts at `now`. - - `pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self`. The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always - - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. Events of a gesture other than the open one are ignored. A concrete + - `pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self`. The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always stays; each weight is measured once at push. + - `pub fn record(&mut self, event: &EditEvent)`. Takes in one event. - `pub fn is_open(&self) -> bool`. A gesture is open: a caller that restores a draft waits for it to end. - - `pub fn step(&mut self, now: &mut T, step: Step) -> bool`. Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. - - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the + - `pub fn step(&mut self, now: &mut T, step: Step) -> bool`. Steps `now` back or forward. + - `pub fn take_back(&mut self) -> Option`. Takes back the newest undo step without a redo entry, for an edit that was refused: `settled` returns to the value before the step, which is returned for the caller to apply, and the redo steps stay as they were. `None` when there is no step. - `pub fn can_undo(&self) -> bool`. An undo would change something. - `pub fn can_redo(&self) -> bool`. A redo would change something. - `pub fn redo_len(&self) -> usize`. How many steps a redo can go forward. @@ -695,18 +698,18 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn select(anchor: TextPos, focus: TextPos) -> Self`. A `Select` of `anchor` to `focus`. - `pub const fn is_read_only_safe(&self) -> bool`. Whether the input changes no text: a read-only editor receives only these (18.4). - `craft_behavior::editor::SurroundingUnit`: `pub enum SurroundingUnit { Chars, Bytes }`. What an input method counts the text around the caret in. - - `pub fn chars_before(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the end of `text`, the editor's text before the deletion. A character - - `pub fn chars_after(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the start of `text`, the editor's text after the deletion. A + - `pub fn chars_before(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the end of `text`, the editor's text before the deletion. + - `pub fn chars_after(self, n: usize, text: &str) -> usize`. The characters `n` of this unit cover at the start of `text`, the editor's text after the deletion. ## `craft_behavior::eviction` When a component's remembered state is due for eviction. -- `craft_behavior::eviction::owner_due`: `pub fn owner_due(last_pass: u64, last_at: f64, pass_now: u64, now: f64, viewport_live: bool) -> bool`. Whether the owner last registered at pass `last_pass` and time `last_at` is due: both the pass count and the +- `craft_behavior::eviction::owner_due`: `pub fn owner_due(last_pass: u64, last_at: f64, pass_now: u64, now: f64, viewport_live: bool) -> bool`. Whether the owner last registered at pass `last_pass` and time `last_at` is due: both the pass count and the time limit have run out. ## `craft_behavior::fit` -The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and +The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens items that have a short form, in the order their host ranks, and drops command items and titles from the end. - `craft_behavior::fit::Fit`: `pub struct Fit { pub shown: Vec, pub overflow: Vec, pub short: Vec }`. Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. - `craft_behavior::fit::FitItem`: `pub struct FitItem { pub extent: f32, pub section: u16, pub keep: FitKeep, pub short: Option, pub short_order: u16, pub short_late: bool }`. One item as the fit rule sees it: its extent along the strip, its section and whether it may overflow. @@ -717,16 +720,16 @@ The fit rules: which tabs, bar items or titles stay in a strip and which go to a - `craft_behavior::fit::FitKeep`: `pub enum FitKeep { Free, Pinned, Menu }`. Whether an item may move into the overflow menu, or lives there. - `craft_behavior::fit::TabFit`: `pub struct TabFit { pub shown: Vec<(usize, f32)>, pub overflow: Vec, pub overflow_width: f32 }`. Tabs visible on a strip and tabs that need an overflow menu, all in original order. - `craft_behavior::fit::fit`: `pub fn fit(natural: &[f32], selected: usize, available: f32, minimum_width: f32, overflow_width: f32, keep_selected: bool) -> TabFit`. Fit tab widths into `available` points, shrinking the widest tabs first to a common cap. -- `craft_behavior::fit::fit_items`: `pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit`. Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. +- `craft_behavior::fit::fit_items`: `pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit`. Decides which items stay in a strip `available` long. - `craft_behavior::fit::fit_whole`: `pub fn fit_whole(natural: &[f32], selected: usize, kept: &[bool], available: f32, overflow_width: f32) -> TabFit`. Fit tabs at their natural widths; the tabs that do not fit go to an overflow menu. -- `craft_behavior::fit::run_extent`: `pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) -> f64`. The length of the items marked in `shown`, with `gap` between neighbours of a section and `section_gap` between +- `craft_behavior::fit::run_extent`: `pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) -> f64`. The length of the items marked in `shown`, with `gap` between neighbours of a section and `section_gap` between neighbours of different sections. ## `craft_behavior::flow` `Insets`, `Flow` and `Axis`: start and end geometry resolved once for the layout direction. -- `craft_behavior::flow::Axis`: `pub enum Axis { X, Y }`. An axis of the screen or of a document. Saved layouts written with the former split axis names load through -- `craft_behavior::flow::Flow`: `pub struct Flow`. The geometry of one rect in one direction. Components place by start and end and never test direction. +- `craft_behavior::flow::Axis`: `pub enum Axis { X, Y }`. An axis of the screen or of a document. +- `craft_behavior::flow::Flow`: `pub struct Flow`. The geometry of one rect in one direction. - `pub const fn new(rect: Rect, rtl: bool) -> Self`. The flow of `rect`, right to left when `rtl`. - `pub const fn rect(&self) -> Rect`. The rect the flow places in. - `pub const fn is_rtl(&self) -> bool`. Whether start is the right edge. @@ -736,9 +739,9 @@ The fit rules: which tabs, bar items or titles stay in a strip and which go to a - `pub fn take_start(&self, width: f32) -> (Rect, Flow)`. Takes `width` from the start edge: the taken rect, and the flow of the rest. - `pub fn take_end(&self, width: f32) -> (Rect, Flow)`. Takes `width` from the end edge: the taken rect, and the flow of the rest. - `pub fn inset(&self, insets: Insets) -> Rect`. The rect shrunk by `insets`. - - `pub fn align(&self, size: Vec2, h: Align, v: Align) -> Rect`. A rect of `size` in the flow's rect: `h` along the reading direction (`Min` is the start edge), `v` + - `pub fn align(&self, size: Vec2, h: Align, v: Align) -> Rect`. A rect of `size` in the flow's rect: `h` along the reading direction (`Min` is the start edge), `v` from the top. - `pub fn to_physical(&self, logical: Rect) -> Rect`. A rect given in logical x (from the start edge of this flow's rect) as a physical rect. - - `pub const fn unmirrored(rect: Rect, reason: &'static str) -> Flow`. The same rect placed left to right, for a site that places by explicit rects and must not mirror (a + - `pub const fn unmirrored(rect: Rect, reason: &'static str) -> Flow`. The same rect placed left to right, for a site that places by explicit rects and must not mirror (a free-position board, a waveform). `reason` names why; every call site is a counted exception. - `craft_behavior::flow::Insets`: `pub struct Insets { pub start: f32, pub end: f32, pub top: f32, pub bottom: f32 }`. Distances from the four edges of a rect; `start` and `end` follow the reading direction. - `pub const fn new(start: f32, end: f32, top: f32, bottom: f32) -> Self`. Insets of `start`, `end`, `top` and `bottom`. - `pub const fn horizontal(h: f32) -> Self`. `h` at the start and the end. @@ -747,7 +750,7 @@ The fit rules: which tabs, bar items or titles stay in a strip and which go to a ## `craft_behavior::focus` -Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the focus-on-press kinds. The runtime's +Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the focus-on-press kinds. - `craft_behavior::focus::CancelRule`: `pub enum CancelRule { Close, ClearThenClose, Ignore }`. What Escape does in a scope that has no more specific taker. - `craft_behavior::focus::EscapeFacts`: `pub struct EscapeFacts { pub press_captured: bool, pub component_undoable: bool, pub in_row_child: bool, pub scope_clearable: bool }`. The facts the Escape order reads. @@ -762,10 +765,10 @@ Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the f - `craft_behavior::focus::PressFocus`: `pub enum PressFocus { Take, Keep, Release, Unclaimed }`. How a primary press moves key focus (8.3). - `pub const fn commits_draft(self) -> bool`. Whether a focused text part with a draft commits it in the press pass. - `craft_behavior::focus::ScopeKind`: `pub enum ScopeKind { Window, Pane, Dialog, Popup, Menu, Group }`. What a focus scope is. -- `craft_behavior::focus::classify_press`: `pub fn classify_press(winner: Option) -> PressFocus`. The kind of a press from the sense of the shape that wins it, `None` when no shape senses it. A shape that -- `craft_behavior::focus::escape_step`: `pub fn escape_step(facts: EscapeFacts, rule: CancelRule) -> EscapeStep`. The order of Escape for the top egui layer that is not exiting: a captured press, the focused component, -- `craft_behavior::focus::key_owner`: `pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner`. Key ownership, in the order blocked, `Menu`, `Recorder`, `Dialog`, `Text`, `Popup` and `PassivePopup`, -- `craft_behavior::focus::route_escapes`: `pub fn route_escapes(escapes: usize, press_captured: bool) -> EscapeRouting`. Routes `escapes` Escapes of one pass: with a press captured, the first one is the press's (`escape_step`'s +- `craft_behavior::focus::classify_press`: `pub fn classify_press(winner: Option) -> PressFocus`. The kind of a press from the sense of the shape that wins it, `None` when no shape senses it. +- `craft_behavior::focus::escape_step`: `pub fn escape_step(facts: EscapeFacts, rule: CancelRule) -> EscapeStep`. The order of Escape for the top egui layer that is not exiting: a captured press, the focused component, a row's child, then the scope's rule. +- `craft_behavior::focus::key_owner`: `pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner`. Key ownership, in the order blocked, `Menu`, `Recorder`, `Dialog`, `Text`, `Popup` and `PassivePopup`, `Widget`, `App`. `present` lists the classes that have a claim this pass, in any order. +- `craft_behavior::focus::route_escapes`: `pub fn route_escapes(escapes: usize, press_captured: bool) -> EscapeRouting`. Routes `escapes` Escapes of one pass: with a press captured, the first one is the press's (`escape_step`'s first case) and the rest go to the components, in the order they arrived. ## `craft_behavior::frame_step` @@ -776,7 +779,7 @@ The step of one pass of motion: a Hand glide, a held Zoom press and an autoscrol ## `craft_behavior::geometry` -Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the +Pure canvas geometry in document units: the transform box ([`quad`]), snapping ([`snap`]), the outline being drawn by a lasso ([`draft`]), how a selection combines with the current one ([`selection_op`]), the marquee drag rules ([`marquee`]), direction locking ([`lock`]), the move gesture and stroke lock ([`move_gesture`]), the crop frame ([`crop`]), the area outside a crop frame as convex pieces ([`outside`]) and plane helpers ([`geom`]). - `craft_behavior::geometry::AXIS_BAND_DEGREES`: re-export of `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`. - `craft_behavior::geometry::AspectHold`: re-export of `craft_behavior::geometry::crop::AspectHold`. @@ -839,38 +842,38 @@ Pure canvas geometry in document units: the transform box ([`quad`]), snapping ( ## `craft_behavior::geometry::crop` -The crop frame's pure geometry: the box, where a press lands on it, what each gesture makes of it, the +The crop frame's pure geometry: the box, where a press lands on it, what each gesture makes of it, the straighten and image-mode maths, and the composition guides. - `craft_behavior::geometry::crop::AspectHold`: `pub enum AspectHold { Free, Ratio(f64), Diagonal }`. What a resize holds about the frame's proportions. - `craft_behavior::geometry::crop::CropBox`: `pub struct CropBox { pub rect: Rect, pub angle: f64 }`. The crop frame: a document rect and the angle it is turned by about its centre. - `pub const fn new(rect: Rect, angle: f64) -> Self`. The frame `rect` turned `angle` degrees about its centre. - `pub const fn upright(rect: Rect) -> Self`. An unturned frame. - - `pub fn part_at(&self, point: Point, reach: f64) -> BoxPart`. The part a press at `point` (document units) lands on, with `reach` document units of reach: a corner or an + - `pub fn part_at(&self, point: Point, reach: f64) -> BoxPart`. The part a press at `point` (document units) lands on, with `reach` document units of reach: a corner or an edge, [`BoxPart::Inside`] or [`BoxPart::Outside`] (the turn zone). - `pub fn is_finite(&self) -> bool`. Whether the rect and the angle are finite numbers. - `pub fn center(&self) -> Point`. The centre the frame turns about. - `pub fn corners(&self) -> [Point; 4]`. The corners on the page, turned: top left, top right, bottom right, bottom left of the upright frame. - - `pub fn part_point(&self, part: BoxPart) -> Option`. The document point of `part` on the turned frame: a corner or an edge handle, or the centre for - - `pub fn part_direction(&self, part: BoxPart) -> Option`. The direction `part` points out of the frame, as a document vector turned with the frame; none for the - - `pub fn quadrant_diagonal(&self, point: Point) -> Vec2`. The diagonal, as a document vector, from the frame's corner nearest `point` towards the frame's centre + - `pub fn part_point(&self, part: BoxPart) -> Option`. The document point of `part` on the turned frame: a corner or an edge handle, or the centre for [`BoxPart::Inside`]; none for the other parts. + - `pub fn part_direction(&self, part: BoxPart) -> Option`. The direction `part` points out of the frame, as a document vector turned with the frame; none for the parts that are neither a corner nor an edge. + - `pub fn quadrant_diagonal(&self, point: Point) -> Vec2`. The diagonal, as a document vector, from the frame's corner nearest `point` towards the frame's centre reversed: it points out of the centre through the corner of the quadrant `point` lies in, along the frame's own axes. - `pub fn turned_bounds(&self) -> Rect`. The axis-aligned bounds of the turned frame. - `pub fn moved(&self, by: Vec2) -> Self`. The frame moved by `by` on the page, its angle kept. - `pub fn swapped(&self) -> Self`. Width and height swapped about the centre, the angle kept (X). - `pub fn nudged(&self, part: BoxPart, by: Vec2, ratio: Option) -> Self`. The frame after an arrow key moves `part` by `by`, as a plain drag of the part would, with `ratio` held. - - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` + - `pub fn crop_size(&self) -> Option<(f64, f64)>`. The size Enter would crop to: the frame's own width and height in whole document units, at least 1; `None` when they are not finite. - `pub fn size_ok(&self, min: f64) -> bool`. Whether both sides are at least `min`, and never under one document unit whatever `min` says. - - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on - - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`](Self::resized) for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the - - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` - - `pub fn within(self, bounds: Rect, resizing: bool, held: bool) -> Option`. The frame kept inside `bounds`: an unturned frame is cut to it; a turned one is moved by the least that - - `pub fn kept_inside(&self, bounds: Rect) -> Option`. The frame at its angle kept inside `bounds` (#10869, an image-mode turn): `self`, bit for bit, when its turned - - `pub fn level_angle(a: Point, b: Point) -> Option`. The frame angle (degrees, clockwise on the page, in -45..=45) that makes the line from `a` to `b` level, or - - `pub fn fitted(&self, canvas: Size, angle: f64) -> Option`. The largest frame with this one's proportions that fits a canvas of `canvas` at `angle` degrees, centred on + - `pub fn resized(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Self`. The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on the page (or the centre with `alt`), the proportions held as `hold` says. + - `pub fn resized_centred(&self, part: BoxPart, by: Vec2, hold: AspectHold, alt: bool) -> Option`. [`resized`] for Auto Center Preview in image mode: `part` dragged by `by` grows or shrinks the frame about its centre, so the handle stays under the pointer while the frame stays centred on screen. + - `pub fn turned_to(&self, grab: f64, to: Point, step: Option, image: bool) -> Self`. The frame turned from this one's angle by the pointer's sweep about the centre, from direction `grab` (radians, see [`direction`]) to `to`; `step` snaps the angle (⇧). + - `pub fn within(self, bounds: Rect, resizing: bool, held: bool) -> Option`. The frame kept inside `bounds`: an unturned frame is cut to it; a turned one is moved by the least that brings its bounds in, and left as it is when it cannot fit. `None` when a frame that changes size (`resizing`) cannot be kept inside (the caller keeps its last frame). + - `pub fn kept_inside(&self, bounds: Rect) -> Option`. The frame at its angle kept inside `bounds` (#10869, an image-mode turn): `self`, bit for bit, when its turned corners are inside (also when a rounding error puts them a hair past an edge); else moved the shortest way in on each axis, its size kept; else shrunk about its centre to the largest size with its proportions that fits, then moved in. `None` when a size or the angle is not finite or a size is not positive. + - `pub fn level_angle(a: Point, b: Point) -> Option`. The frame angle (degrees, clockwise on the page, in -45..=45) that makes the line from `a` to `b` level, or plumb when it is nearer vertical; `None` for a point or a line that is not finite. + - `pub fn fitted(&self, canvas: Size, angle: f64) -> Option`. The largest frame with this one's proportions that fits a canvas of `canvas` at `angle` degrees, centred on the canvas. `None` when a size or the angle is not a positive finite number. - `craft_behavior::geometry::crop::CropGuide`: `pub enum CropGuide { Thirds, Grid, Diagonal, Triangle, GoldenRatio, GoldenSpiral }`. The composition guide drawn inside a crop frame, in Photoshop's menu order. - `pub const ALL: [CropGuide; 6]`. Every guide, in the order `next` cycles through. - - `pub fn orientations(self) -> u8`. How many distinct orientations `next_orientation` steps through: the Triangle's diagonal runs either way, the + - `pub fn orientations(self) -> u8`. How many distinct orientations `next_orientation` steps through: the Triangle's diagonal runs either way, the Golden Spiral winds into any of the four corners; the others are symmetric. - `pub fn next(self) -> Self`. The next guide (O); the orientation starts over at 0. - - `pub fn next_orientation(self, orientation: u8) -> u8`. The guide's next orientation (Shift+O) after `orientation`; a symmetric guide stays at 0 and a stray value - - `pub fn guides(self, orientation: u8, w: f64, h: f64, grid_step: f64, grid_max: usize) -> Vec>`. The guide's polylines for a frame `w` x `h` screen points, in its unit square (0..1 along its top edge, 0..1 + - `pub fn next_orientation(self, orientation: u8) -> u8`. The guide's next orientation (Shift+O) after `orientation`; a symmetric guide stays at 0 and a stray value comes back in range. + - `pub fn guides(self, orientation: u8, w: f64, h: f64, grid_step: f64, grid_max: usize) -> Vec>`. The guide's polylines for a frame `w` x `h` screen points, in its unit square (0..1 along its top edge, 0..1 down its left edge), so one geometry maps onto an upright or a turned frame. - `craft_behavior::geometry::crop::GuideShow`: `pub enum GuideShow { Auto, Always, Never }`. When the guide shows. - `pub const ALL: [GuideShow; 3]`. Every rule, in menu order. - `pub fn shows(self, gesture: bool) -> bool`. Whether the guide shows, `gesture` being a crop drag in progress. @@ -880,83 +883,83 @@ The crop frame's pure geometry: the box, where a press lands on it, what each ge - `craft_behavior::geometry::crop::drawn`: `pub fn drawn(anchor: Point, cur: Point, ratio: Option, mods: Mods) -> Rect`. A new frame drawn from `anchor` to `cur`: ⇧ square, ⌥ from the centre, `ratio` held. - `craft_behavior::geometry::crop::hit_rect`: `pub fn hit_rect(rect: Rect, point: Point, reach: f64) -> BoxPart`. [`CropBox::part_at`] for a plain upright `rect`, with no frame or view. - `craft_behavior::geometry::crop::image_turn`: `pub fn image_turn(frame_angle: f64) -> f64`. The turn the image-mode readout shows: clockwise positive, the frame's angle undone, never -0. -- `craft_behavior::geometry::crop::normalized_angle`: `pub fn normalized_angle(deg: f64) -> f64`. An angle in degrees brought into (-180, 180]; 0 for anything not finite. An angle already in range comes back +- `craft_behavior::geometry::crop::normalized_angle`: `pub fn normalized_angle(deg: f64) -> f64`. An angle in degrees brought into (-180, 180]; 0 for anything not finite. - `craft_behavior::geometry::crop::screen_step`: `pub fn screen_step(view: &CanvasView, by: Vec2) -> Vec2`. An arrow step `by` (screen points) as the document vector it is in `view`, at one document unit per point. -- `craft_behavior::geometry::crop::snap_angle`: `pub fn snap_angle(deg: f64, step: f64) -> f64`. `deg` on the nearest multiple of `step` degrees, brought into (-180, 180]; a step that is not finite and positive +- `craft_behavior::geometry::crop::snap_angle`: `pub fn snap_angle(deg: f64, step: f64) -> f64`. `deg` on the nearest multiple of `step` degrees, brought into (-180, 180]; a step that is not finite and positive is ignored. - `craft_behavior::geometry::crop::turn`: `pub fn turn(p: Point, c: Point, deg: f64) -> Point`. `p` turned `deg` degrees clockwise on screen (y down) about `c`. -- `craft_behavior::geometry::crop::turn_grid`: `pub fn turn_grid(w: f64, h: f64, step: f64, visible: Rect) -> Vec>`. The lines of the grid a default-mode turn shows over a `w` by `h` frame (screen points), in the frame's unit square +- `craft_behavior::geometry::crop::turn_grid`: `pub fn turn_grid(w: f64, h: f64, step: f64, visible: Rect) -> Vec>`. The lines of the grid a default-mode turn shows over a `w` by `h` frame (screen points), in the frame's unit square as [`CropGuide::guides`] gives them: `step` apart counted from the frame's centre, none on the outline, and only those whose position lies inside `visible` (the part of the frame on screen, in the frame's own axes), so a frame zoomed far past the screen gives only the lines that show. ## `craft_behavior::geometry::draft` An outline being drawn by a selection or freeform tool, and how it closes: [`OutlineDraft`]. -- `craft_behavior::geometry::draft::DraftEvent`: `pub enum DraftEvent { Started { intent: Mods }, Changed, Closed { points: Vec, straight: Vec }, Cancelled }`. What a call on an [`OutlineDraft`] did. Calls that change nothing return `None`. +- `craft_behavior::geometry::draft::DraftEvent`: `pub enum DraftEvent { Started { intent: Mods }, Changed, Closed { points: Vec, straight: Vec }, Cancelled }`. What a call on an [`OutlineDraft`] did. - `craft_behavior::geometry::draft::DraftKind`: `pub enum DraftKind { Freehand, Mixed, Polygonal }`. Which tool's rules an [`OutlineDraft`] follows. - `craft_behavior::geometry::draft::DraftPoint`: `pub struct DraftPoint { pub at: Point, pub mods: Mods, pub zoom: f64 }`. One pointer sample for an [`OutlineDraft`]. - `pub fn new(at: Point, mods: Mods, zoom: f64) -> Self`. A sample at `at` (document units) with `mods` held, at `zoom` screen points per unit. -- `craft_behavior::geometry::draft::DraftReach`: `pub struct DraftReach { pub close: f64, pub same_point: f64 }`. How near a press must be to close an outline, in screen points. The caller passes the hit - - `pub const fn new(close: f64, same_point: f64) -> Self`. A reach closing within `close` screen points of the first vertex and treating a press +- `craft_behavior::geometry::draft::DraftReach`: `pub struct DraftReach { pub close: f64, pub same_point: f64 }`. How near a press must be to close an outline, in screen points. + - `pub const fn new(close: f64, same_point: f64) -> Self`. A reach closing within `close` screen points of the first vertex and treating a press within `same_point` of the last vertex as the same click. - `craft_behavior::geometry::draft::OutlineDraft`: `pub struct OutlineDraft`. The pointer state machine of an outline being drawn, shared by every lasso. - `pub fn new(kind: DraftKind, reach: DraftReach) -> Self`. An empty draft following `kind`'s rules, closing within `reach`. - `pub fn locking_shift_drags(mut self) -> Self`. This draft with ⇧ holding a freehand drag to one of eight directions (see [`DraftKind::Mixed`]). - `pub fn kind(&self) -> DraftKind`. The rules this draft follows. - `pub fn set_reach(&mut self, reach: DraftReach)`. Changes the close radii; an open outline keeps its points. - - `pub fn for_document(&mut self, key: u64) -> Option`. Records `key` as the active document's. An open outline begun under another key is - - `pub fn press(&mut self, at: DraftPoint, has_selection: bool) -> Option`. The primary button went down at `at`; `has_selection` is whether the document has a - - `pub fn drag(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down. Freehand and Mixed: the point is added - - `pub fn move_to(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down while the reposition key is held: the whole outline moves by the - - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the - - `pub fn release(&mut self, at: DraftPoint) -> Option`. The primary button went up at `at`. Freehand: closes. Mixed: closes unless straight - - `pub fn mods_changed(&mut self, mods: Mods) -> Option`. The held modifiers changed. Mixed only: ⌥ pressed after the press (or pressed again after - - `pub fn retract(&mut self) -> Option`. Removes the last vertex while [`takes_retract`](Self::takes_retract); removing the only - - `pub fn close(&mut self) -> Option`. Closes an open outline (Enter, a double-click): [`DraftEvent::Closed`] with 3 or more + - `pub fn for_document(&mut self, key: u64) -> Option`. Records `key` as the active document's. + - `pub fn press(&mut self, at: DraftPoint, has_selection: bool) -> Option`. The primary button went down at `at`; `has_selection` is whether the document has a selection (a path tool passes false: it has nothing to subtract from). + - `pub fn drag(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down. + - `pub fn move_to(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button down while the reposition key is held: the whole outline moves by the pointer's step since its last sample instead of growing, and the rubber band's free end follows. + - `pub fn hover(&mut self, at: DraftPoint) -> Option`. The pointer moved to `at` with the button up: only the rubber band follows, to where a click would place the point (`shift_step`); hover moves never become vertices. [`DraftEvent::Changed`] while an outline is open. + - `pub fn release(&mut self, at: DraftPoint) -> Option`. The primary button went up at `at`. + - `pub fn mods_changed(&mut self, mods: Mods) -> Option`. The held modifiers changed. + - `pub fn retract(&mut self) -> Option`. Removes the last vertex while [`takes_retract`]; removing the only one cancels the outline. + - `pub fn close(&mut self) -> Option`. Closes an open outline (Enter, a double-click): [`DraftEvent::Closed`] with 3 or more points, else [`DraftEvent::Cancelled`]. `None` with no outline. - `pub fn cancel(&mut self) -> Option`. Drops an open outline: [`DraftEvent::Cancelled`]; `None` with no outline. - `pub fn points(&self) -> &[Point]`. The outline's points so far, in document units; empty with no outline. - - `pub fn straight(&self) -> &[usize]`. Indices into [`points`](Self::points) whose incoming segment is straight. - - `pub fn rubber_band(&self) -> Option<[Point; 2]>`. The rubber band from the last vertex to the pointer while straight segments are on and + - `pub fn straight(&self) -> &[usize]`. Indices into [`points`] whose incoming segment is straight. + - `pub fn rubber_band(&self) -> Option<[Point; 2]>`. The rubber band from the last vertex to the pointer while straight segments are on and the button is up, for the tool to paint; `None` otherwise. - `pub fn is_open(&self) -> bool`. Whether an outline is open. - `pub fn is_down(&self) -> bool`. Whether the primary button is down on an open outline. - - `pub fn takes_retract(&self) -> bool`. Whether [`retract`](Self::retract) acts: an outline is open and the button is up (between + - `pub fn takes_retract(&self) -> bool`. Whether [`retract`] acts: an outline is open and the button is up (between clicks). ## `craft_behavior::geometry::geom` -Plane geometry the canvas overlays share, in document or screen units: segment clipping. Pure maths beside +Plane geometry the canvas overlays share, in document or screen units: segment clipping. - `craft_behavior::geometry::geom::clip_segment`: `pub fn clip_segment(a: Point, b: Point, rect: Rect) -> Option<(Point, Point)>`. The part of segment `a`–`b` inside `rect` (Liang–Barsky), or `None` when none is. ## `craft_behavior::geometry::lock` -Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`], +Direction locking for ⇧ drags: [`Directions`], [`lock_direction`], [`round_to_direction`], [`turn_to_45`], [`polygon_step`] and [`axis_or_diagonal`]. -- `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`: `pub const AXIS_BAND_DEGREES: f64`. How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal +- `craft_behavior::geometry::lock::AXIS_BAND_DEGREES`: `pub const AXIS_BAND_DEGREES: f64`. How near an axis, in degrees, a ⇧ line or anchor drag must point to snap onto the axis rather than the diagonal ([`axis_or_diagonal`]). - `craft_behavior::geometry::lock::Directions`: `pub enum Directions { Four, Eight }`. The directions ⇧ locks a move to. - `pub const fn count(self) -> u32`. How many evenly spaced directions: 4 or 8. -- `craft_behavior::geometry::lock::LOCK_HYSTERESIS_DEGREES`: `pub const LOCK_HYSTERESIS_DEGREES: f64`. Extra angle in degrees the pointer must pass the half-way line between two directions by -- `craft_behavior::geometry::lock::axis_or_diagonal`: `pub fn axis_or_diagonal(from: Point, point: Point) -> Point`. Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the -- `craft_behavior::geometry::lock::lock_direction`: `pub fn lock_direction(d: Vec2, previous: Option, directions: Directions) -> Vec2`. `d` locked to the nearest of `directions` evenly spaced directions (0° = right, document y -- `craft_behavior::geometry::lock::polygon_step`: `pub fn polygon_step(from: Point, point: Point) -> Point`. Shift's polygon vertex: `point` moved to the nearest of eight directions from `from`; an axis keeps the -- `craft_behavior::geometry::lock::round_to_direction`: `pub fn round_to_direction(angle: f64, directions: Directions) -> f64`. `angle` (radians, 0 = right, document y down) rounded to the nearest of `directions` evenly -- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle +- `craft_behavior::geometry::lock::LOCK_HYSTERESIS_DEGREES`: `pub const LOCK_HYSTERESIS_DEGREES: f64`. Extra angle in degrees the pointer must pass the half-way line between two directions by before a locked direction switches, so it doesn't flicker near the diagonal. +- `craft_behavior::geometry::lock::axis_or_diagonal`: `pub fn axis_or_diagonal(from: Point, point: Point) -> Point`. Shift's rule for the Line tool and anchor drags: within [`AXIS_BAND_DEGREES`] of an axis, `point` moves onto the axis through `from` and keeps its offset along it; otherwise onto the 45° diagonal, at the shorter of its two offsets on both axes. `point` itself for a zero or non-finite offset. +- `craft_behavior::geometry::lock::lock_direction`: `pub fn lock_direction(d: Vec2, previous: Option, directions: Directions) -> Vec2`. `d` locked to the nearest of `directions` evenly spaced directions (0° = right, document y down). `previous` is the offset this returned last in the same drag: its direction is kept until `d` is more than half a step plus [`LOCK_HYSTERESIS_DEGREES`] away from it. +- `craft_behavior::geometry::lock::polygon_step`: `pub fn polygon_step(from: Point, point: Point) -> Point`. Shift's polygon vertex: `point` moved to the nearest of eight directions from `from`; an axis keeps the segment's length, a diagonal keeps the shorter offset on both axes. `point` itself for a zero-length or non-finite offset. +- `craft_behavior::geometry::lock::round_to_direction`: `pub fn round_to_direction(angle: f64, directions: Directions) -> f64`. `angle` (radians, 0 = right, document y down) rounded to the nearest of `directions` evenly spaced directions: the one angle-rounding rule behind [`lock_direction`] (projection) and [`turn_to_45`] (rotation). +- `craft_behavior::geometry::lock::turn_to_45`: `pub fn turn_to_45(from: Point, point: Point) -> Point`. `point` turned about `from` to the nearest multiple of 45°, keeping its distance: the ⇧ rule for a line, a handle or a segment drawn from a fixed point. ## `craft_behavior::geometry::marquee` -The Ui-free rules of a marquee drag: [`MarqueeGesture`], the options bar's [`Constraint`], and the +The Ui-free rules of a marquee drag: [`MarqueeGesture`], the options bar's [`Constraint`], and the pixel rectangles a marquee selects. -- `craft_behavior::geometry::marquee::Constraint`: `pub enum Constraint { Free, Ratio(f64, f64), Size(f64, f64) }`. The options bar's marquee style. Serialises camelCase (`"free"`, `{"ratio": [1, 1]}`, - - `pub fn corners(self, start: Point, end: Point, square: bool, centre: bool) -> (Point, Point)`. The corners of the marquee dragged from `start` to `end`: the style applied, ⇧ (`square`) -- `craft_behavior::geometry::marquee::MarqueeGesture`: `pub struct MarqueeGesture`. The rules of a marquee drag: ⇧ and ⌥ counted only when pressed after the - - `pub fn press(screen: Pos2, at: Point, mods: Mods) -> Self`. A press at `screen` (screen points) and `at` (document units, snapped by the host) with +- `craft_behavior::geometry::marquee::Constraint`: `pub enum Constraint { Free, Ratio(f64, f64), Size(f64, f64) }`. The options bar's marquee style. + - `pub fn corners(self, start: Point, end: Point, square: bool, centre: bool) -> (Point, Point)`. The corners of the marquee dragged from `start` to `end`: the style applied, ⇧ (`square`) making it square when free, ⌥ (`centre`) drawing it from the centre. +- `craft_behavior::geometry::marquee::MarqueeGesture`: `pub struct MarqueeGesture`. The rules of a marquee drag: ⇧ and ⌥ counted only when pressed after the press (or released and pressed again), Space moving the whole marquee, and the options bar's [`Constraint`]. + - `pub fn press(screen: Pos2, at: Point, mods: Mods) -> Self`. A press at `screen` (screen points) and `at` (document units, snapped by the host) with `mods` held: they choose the selection mode, not square or centre. - `pub fn pointer(&self) -> Pos2`. The pointer on screen as last followed. - `pub fn has_begun(&self) -> bool`. The tool began the gesture with its first drag call. - - `pub fn follow(&mut self, screen: Option, mods: Mods)`. The pass's mods and pointer (`None` keeps the last one): records ⇧ and ⌥ being - - `pub fn begin(&mut self) -> bool`. Begins the gesture: the tool calls it on its first `drag`, the press arena having separated the drag from a - - `pub fn square_and_centre(&self) -> (bool, bool)`. ⇧ (square) and ⌥ (from the centre) for the marquee: held now, and either not held at the - - `pub fn size_to(&mut self, at: Point, space: bool, constraint: Constraint) -> MarqueeRect`. Sizes the marquee to the pointer's document point `at` (the host's snap applied): with + - `pub fn follow(&mut self, screen: Option, mods: Mods)`. The pass's mods and pointer (`None` keeps the last one): records ⇧ and ⌥ being released since the press. + - `pub fn begin(&mut self) -> bool`. Begins the gesture: the tool calls it on its first `drag`, the press arena having separated the drag from a click. + - `pub fn square_and_centre(&self) -> (bool, bool)`. ⇧ (square) and ⌥ (from the centre) for the marquee: held now, and either not held at the press or released since. + - `pub fn size_to(&mut self, at: Point, space: bool, constraint: Constraint) -> MarqueeRect`. Sizes the marquee to the pointer's document point `at` (the host's snap applied): with `space` held the whole marquee moves by the pointer's step instead. - `craft_behavior::geometry::marquee::MarqueeRect`: `pub struct MarqueeRect { pub a: Point, pub b: Point }`. The two corners of a marquee in document space, as dragged: not ordered, not rounded. - `pub const fn new(a: Point, b: Point) -> Self`. The marquee from the corner `a` to the corner `b`. - `pub fn rect(&self) -> Rect`. The rectangle between the corners, with `x0 <= x1` and `y0 <= y1`. -- `craft_behavior::geometry::marquee::fixed_size_pixels`: `pub fn fixed_size_pixels(a: Point, b: Point, size:(f64, f64)) -> Rect`. The pixel rectangle of a fixed-size marquee between the corners `a` and `b`: exactly `size` -- `craft_behavior::geometry::marquee::marquee_pixels`: `pub fn marquee_pixels(a: Point, b: Point) -> Rect`. The pixel rectangle a marquee between two corners selects: both edges snapped outwards to +- `craft_behavior::geometry::marquee::fixed_size_pixels`: `pub fn fixed_size_pixels(a: Point, b: Point, size:(f64, f64)) -> Rect`. The pixel rectangle of a fixed-size marquee between the corners `a` and `b`: exactly `size` `(w, h)` in whole pixels (at least 1 Ă— 1). +- `craft_behavior::geometry::marquee::marquee_pixels`: `pub fn marquee_pixels(a: Point, b: Point) -> Rect`. The pixel rectangle a marquee between two corners selects: both edges snapped outwards to whole pixels, so every pixel the marquee touches is in. - `craft_behavior::geometry::marquee::square_pixels`: `pub fn square_pixels(r: Rect, start: Point, end: Point) -> Rect`. A square marquee's pixel rectangle `r`, as [`marquee_pixels`] returns it, with equal sides. ## `craft_behavior::geometry::move_gesture` @@ -965,18 +968,18 @@ A move by drag: direction lock, stroke lock and snapping along a ray. - `craft_behavior::geometry::move_gesture::ConstrainStyle`: `pub struct ConstrainStyle { pub copy_reach: f64, pub stroke_lock: f64 }`. The distances of the move and stroke rules, in screen points. - `pub const fn new(copy_reach: f64, stroke_lock: f64) -> Self`. A style with the two distances; a tool passes `ToolContext::slop` for both. -- `craft_behavior::geometry::move_gesture::MoveGesture`: `pub struct MoveGesture`. A Move-tool drag in progress: the press, whether ⌥ was held at it, and the last locked +- `craft_behavior::geometry::move_gesture::MoveGesture`: `pub struct MoveGesture`. A Move-tool drag in progress: the press, whether ⌥ was held at it, and the last locked offset. - `pub fn press(style: &ConstrainStyle, start: Point, mods: Mods, directions: Directions) -> MoveGesture`. Starts a drag at `start` (document units) with the keys held at the press. - - `pub fn follow(&mut self, at: Point, mods: Mods, zoom: f64) -> Option`. The pointer moved to `at` (document units) with `mods` at `zoom` screen points per - - `pub fn release(mut self, at: Point, mods: Mods, zoom: f64) -> MoveValue`. The release at `at`: the same lock as [`follow`](Self::follow) applies, so a release where - - `pub fn value(&self) -> MoveValue`. The value of the last [`follow`](Self::follow): the offset and whether it copies. - - `pub fn left_press(&self) -> bool`. Whether the pointer, at a [`follow`](Self::follow), has been half a document unit or more from the press on + - `pub fn follow(&mut self, at: Point, mods: Mods, zoom: f64) -> Option`. The pointer moved to `at` (document units) with `mods` at `zoom` screen points per document unit. ⇧ locks the offset to the gesture's directions with hysteresis from the last locked offset; without ⇧ the offset is free and the lock is forgotten. `copy` turns on when ⌥ was held at the press and `|delta| Ă— zoom ≥ copy_reach`. + - `pub fn release(mut self, at: Point, mods: Mods, zoom: f64) -> MoveValue`. The release at `at`: the same lock as [`follow`] applies, so a release where the last value was ends there. + - `pub fn value(&self) -> MoveValue`. The value of the last [`follow`]: the offset and whether it copies. + - `pub fn left_press(&self) -> bool`. Whether the pointer, at a [`follow`], has been half a document unit or more from the press on either axis (before the ⇧ lock), so a move of whole units has moved off its press. - `pub fn locked(&self) -> Option`. The direction ⇧ holds the offset to, as the last locked offset; `None` while the move is free. - `craft_behavior::geometry::move_gesture::MoveValue`: `pub struct MoveValue { pub delta: Vec2, pub copy: bool }`. The value of a move drag. - - `pub fn changed(&self) -> bool`. Whether the drag changes anything: an offset or a copy. A press and release without -- `craft_behavior::geometry::move_gesture::StrokeLock`: `pub struct StrokeLock`. ⇧ during a painting stroke (every painting tool, the Freeform Pen; which tools is the app's + - `pub fn changed(&self) -> bool`. Whether the drag changes anything: an offset or a copy. +- `craft_behavior::geometry::move_gesture::StrokeLock`: `pub struct StrokeLock`. ⇧ during a painting stroke (every painting tool, the Freeform Pen; which tools is the app's list): the stroke stays on a line at 0°, 45° or 90° from where the lock began. - `pub fn new(style: &ConstrainStyle) -> Self`. No lock yet; `style` gives the screen distance before the direction locks. - - `pub fn constrain(&mut self, last: Point, p: Point, shift: bool, zoom: f64) -> Point`. The stroke point for the pointer at `p` (document units), `last` the stroke's last point, + - `pub fn constrain(&mut self, last: Point, p: Point, shift: bool, zoom: f64) -> Point`. The stroke point for the pointer at `p` (document units), `last` the stroke's last point, `zoom` screen points per document unit. - `pub fn locked(&self) -> bool`. Whether a direction is locked. - `pub fn reset(&mut self)`. Forget the lock (the stroke ended). @@ -984,74 +987,74 @@ A move by drag: direction lock, stroke lock and snapping along a ray. The canvas outside a convex hole, as convex pieces. -- `craft_behavior::geometry::outside::outside_pieces`: `pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec>`. Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each +- `craft_behavior::geometry::outside::outside_pieces`: `pub fn outside_pieces(canvas: [Point; 4], hole: &[Point]) -> Vec>`. Convex pieces that cover the canvas quad outside the convex `hole` exactly once: the canvas clipped by each hole edge's outer half-plane in turn. ## `craft_behavior::geometry::quad` -Box geometry of transform boxes: where the box goes when a part of it is dragged, and the +Box geometry of transform boxes: where the box goes when a part of it is dragged, and the options bar's reading of it. -- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool, pub warp: bool }`. What the box's content allows. PhotoCraft: editable type refuses distort and perspective +- `craft_behavior::geometry::quad::BoxAllow`: `pub struct BoxAllow { pub rotate: bool, pub skew: bool, pub distort: bool, pub warp: bool }`. What the box's content allows. - `pub const fn new(rotate: bool, skew: bool, distort: bool) -> Self`. What the content allows: turning, skewing and distorting. - `pub const fn with_warp(mut self, warp: bool) -> Self`. Whether the content allows warping. - `craft_behavior::geometry::quad::BoxDrag`: `pub enum BoxDrag { Move, Pivot, Rotate, Scale, Distort, Perspective, Skew, SlideCorner }`. What a drag of a box part does ([`BoxRules::drag_kind`]). - `craft_behavior::geometry::quad::BoxHandles`: `pub enum BoxHandles { All, Corners, Sides }`. Which handles of a box are shown. -- `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. Edge `k` joins corners `k` and - - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to - - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`](Self::index), with 0 the inside. +- `craft_behavior::geometry::quad::BoxPart`: `pub enum BoxPart { Corner(u8), Edge(u8), Pivot, Inside, Outside }`. A part of a box under the pointer or picked from the keyboard. + - `pub const fn index(self) -> u64`. The number a part is keyed by in a canvas control's part keys: 0 inside or outside, 1 to 4 the corners, 5 to 8 the edges, 9 the pivot. + - `pub const fn from_index(index: u64) -> Option`. The part keyed by `index`: the inverse of [`index`], with 0 the inside. - `craft_behavior::geometry::quad::BoxRules`: `pub struct BoxRules { pub mode: TransformMode, pub scale: ScaleRule, pub aspect_linked: bool, pub allow: BoxAllow, pub rotate_step: f64, pub min_side: f64, pub handles: BoxHandles, pub edge_band: f32 }`. How drags change a box. - - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and + - `pub fn in_mode(mode: TransformMode) -> BoxRules`. The rules of `mode` with the default scale rule, a linked aspect, everything allowed and a 15 degree rotation step. - `pub fn with_scale(mut self, scale: ScaleRule) -> BoxRules`. The rules with `scale` as the plain corner and edge drag rule. - `pub fn with_aspect_linked(mut self, linked: bool) -> BoxRules`. The rules with the options bar's aspect link on or off. - `pub fn with_allow(mut self, allow: BoxAllow) -> BoxRules`. The rules with `allow` as what the content permits. - `pub fn with_min_side(mut self, side: f64) -> BoxRules`. The rules with `side` as the minimum side of a scaled box, in document units. - `pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules`. The rules with `handles` as the handles the box shows. - - `pub fn with_edge_band(mut self, points: f32) -> BoxRules`. The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). - - `pub fn shows(&self, part: BoxPart) -> bool`. Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides + - `pub fn with_edge_band(mut self, points: f32) -> BoxRules`. The rules with each side grabbed within `points` of its line ([`edge_band`]). + - `pub fn shows(&self, part: BoxPart) -> bool`. Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides and no corner. - `pub fn effective_mode(&self) -> TransformMode`. The mode drags follow: a mode the content refuses scales as Free Transform does. - - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the - - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before -- `craft_behavior::geometry::quad::BoxState`: `pub struct BoxState { pub quad: [Point; 4], pub pivot: Point }`. A transform box: its four corners clockwise from the top left (as the box was before any - - `pub fn origin_of_pivot(&self, rect: Rect) -> Point`. The reference point's place within the box, carried to `rect`: the pivot through the + - `pub fn allows(&self, part: BoxPart) -> bool`. Whether a drag of `part` changes the box: in Distort only the corners, the inside and the reference point; in Skew everything but the outside; the outside only where rotating is allowed; and never a handle the box does not [show]. + - `pub fn drag_kind(&self, part: BoxPart, mods: Mods) -> Option`. What a drag of `part` with `mods` held (as the host has them, before `drag_modifiers`) does to the box, or `None` where the rules refuse the part ([`allows`]). [`drag`] acts on this kind. +- `craft_behavior::geometry::quad::BoxState`: `pub struct BoxState { pub quad: [Point; 4], pub pivot: Point }`. A transform box: its four corners clockwise from the top left (as the box was before any transform) and its reference point, in document space. + - `pub fn origin_of_pivot(&self, rect: Rect) -> Point`. The reference point's place within the box, carried to `rect`: the pivot through the inverse homography onto the unit square, then onto `rect` (the relative X and Y fields' origin). - `pub const fn new(quad: [Point; 4], pivot: Point) -> Self`. A box with the corners `quad`, clockwise from the top left, and the reference point `pivot`. - `pub fn from_rect(r: Rect) -> Self`. The box of `r`, the reference point at its centre. - `pub fn moved(&self, by: Vec2) -> Self`. The box and its reference point moved by `by`. - - `pub fn is_parallelogram(&self) -> bool`. Whether the box is still an affine image of its rect (opposite sides parallel), so W and H - - `pub fn parts(&self, rect: Rect, skew_v: f64) -> Parts`. The box read as the options bar shows it, `rect` being the box before the transform and - - `pub fn with_parts(&self, rect: Rect, skew_v: f64, mut to: Parts) -> Self`. The box with the options bar's fields set to `to`: W and H scale it along its own axes, the - - `pub fn linked_scale(now:(f64, f64), axis: usize, typed: f64) -> (f64, f64)`. The signed factors `(w, h)` after the side on `axis` (0: W, 1: H) is set to `typed` with W - - `pub fn point_at(&self, at: Anchor9) -> Point`. One of the box's nine points, through the box's own frame (a distorted box's centre is - - `pub fn anchor_of_pivot(&self) -> Option`. The point of the nine the reference point is on, within 0.05 document units; `None` for a - - `pub fn part_at(&self, p: Point, tol: f64) -> BoxPart`. The part at `p`: the nearest of the corners, edge midpoints and reference point within + - `pub fn is_parallelogram(&self) -> bool`. Whether the box is still an affine image of its rect (opposite sides parallel), so W and H describe it; a distorted or perspective box is not. + - `pub fn parts(&self, rect: Rect, skew_v: f64) -> Parts`. The box read as the options bar shows it, `rect` being the box before the transform and `skew_v` the V skew the host keeps (degrees). + - `pub fn with_parts(&self, rect: Rect, skew_v: f64, mut to: Parts) -> Self`. The box with the options bar's fields set to `to`: W and H scale it along its own axes, the angle turns it and the skews lean it, each about the reference point, which stays put. + - `pub fn linked_scale(now:(f64, f64), axis: usize, typed: f64) -> (f64, f64)`. The signed factors `(w, h)` after the side on `axis` (0: W, 1: H) is set to `typed` with W and H linked, from the factors `now`. + - `pub fn point_at(&self, at: Anchor9) -> Point`. One of the box's nine points, through the box's own frame (a distorted box's centre is where its diagonals' frame puts it). + - `pub fn anchor_of_pivot(&self) -> Option`. The point of the nine the reference point is on, within 0.05 document units; `None` for a reference point placed elsewhere. + - `pub fn part_at(&self, p: Point, tol: f64) -> BoxPart`. The part at `p`: the nearest of the corners, edge midpoints and reference point within `tol` (on a small box their reaches overlap), else inside or outside the box. - `pub fn contains(&self, p: Point) -> bool`. Whether `p` is inside the box (even-odd, so a folded box has holes). - - `pub fn angle(&self) -> f64`. The direction of the top edge in degrees, clockwise in document space (y down): the rotate - - `pub fn scaled_about_pivot(&self, kx: f64, ky: f64) -> Self`. Scaled by `kx` and `ky` along the box's own axes about the reference point. A negative + - `pub fn angle(&self) -> f64`. The direction of the top edge in degrees, clockwise in document space (y down): the rotate readout. 0 for a collapsed top edge. + - `pub fn scaled_about_pivot(&self, kx: f64, ky: f64) -> Self`. Scaled by `kx` and `ky` along the box's own axes about the reference point. - `pub fn turned_about_pivot(&self, radians: f64) -> Self`. Turned by `radians` about the reference point. -- `craft_behavior::geometry::quad::Homography`: `pub struct Homography`. A projective map of the plane: the unit square onto a box, so a box scales along its own axes - - `pub fn apply_in_front(&self, p: Point, within: Rect) -> Option`. [`Homography::apply`] for a point on the front side of the horizon, the side most of +- `craft_behavior::geometry::quad::Homography`: `pub struct Homography`. A projective map of the plane: the unit square onto a box, so a box scales along its own axes whatever its shape. + - `pub fn apply_in_front(&self, p: Point, within: Rect) -> Option`. [`Homography::apply`] for a point on the front side of the horizon, the side most of `within`'s corners lie on (its centre's side on a two–two split); `None` for a point on the horizon or behind it. - `pub fn from_rows(rows: [[f64; 3]; 3]) -> Homography`. The map with these rows of (x, y, w) coefficients, applied to (x, y, 1). - `pub fn row(&self, i: usize) -> [f64; 3]`. Row `i` (0 to 2) of the matrix: the coefficients of x, y and the constant. - - `pub fn unit_to_quad(q: [Point; 4]) -> Option`. The map taking (0, 0), (1, 0), (1, 1), (0, 1) to `q`'s corners; `None` for a degenerate + - `pub fn unit_to_quad(q: [Point; 4]) -> Option`. The map taking (0, 0), (1, 0), (1, 1), (0, 1) to `q`'s corners; `None` for a degenerate box. - `pub fn apply(&self, p: Point) -> Point`. `p` of the unit square, carried to the box. - `pub fn inverse(&self) -> Option`. The map back from the box to the unit square; `None` when the map is singular. -- `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by +- `craft_behavior::geometry::quad::Parts`: `pub struct Parts { pub w: f64, pub h: f64, pub angle: f64, pub skew_h: f64, pub skew_v: f64 }`. A box read as the options bar shows it: the starting rect scaled by `w` and `h`, skewed by `skew_h` and `skew_v` and turned by `angle`, about the reference point. - `pub const fn new(w: f64, h: f64, angle: f64, skew_h: f64, skew_v: f64) -> Self`. The readings: scale factors `w` and `h`, the `angle` in degrees and the two skews in degrees. - `craft_behavior::geometry::quad::SKEW_LIMIT`: `pub const SKEW_LIMIT: f64`. The skew fields' reach in degrees: a skew of ±90° would flatten the box (PhotoCraft's). - `craft_behavior::geometry::quad::ScaleRule`: `pub enum ScaleRule { Proportional, Free, LargerAxis, Shape, Corners }`. What a plain corner or edge drag does. - `craft_behavior::geometry::quad::TransformMode`: `pub enum TransformMode { Free, Rotate, Skew, Distort, Perspective }`. Edit › Transform's modes. -- `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. The -- `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the -- `craft_behavior::geometry::quad::outset`: `pub fn outset(corners: &[emath::Pos2; 4], by: f32) -> [emath::Pos2; 4]`. The closed polygon `corners` moved `by` points outward, each corner along its mitre (kept +- `craft_behavior::geometry::quad::bisector`: `pub fn bisector(screen: &BoxState, i: usize) -> emath::Vec2`. Corner `i` of `screen`'s unit bisector, pointing into the box; zero for a collapsed corner. +- `craft_behavior::geometry::quad::drag`: `pub fn drag(start: &BoxState, last: &BoxState, part: BoxPart, from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState`. The box after dragging `part` from `from` to `to` (document points) with `mods` held, from the box at the press, `start`. `last` is the box this drag gave last (`start` on its first move): +- `craft_behavior::geometry::quad::outset`: `pub fn outset(corners: &[emath::Pos2; 4], by: f32) -> [emath::Pos2; 4]`. The closed polygon `corners` moved `by` points outward, each corner along its mitre (kept within four times `by` at a sharp corner). ## `craft_behavior::geometry::selection_op` [`SelectionOperation`]: how a new selection combines with the current one. -- `craft_behavior::geometry::selection_op::SelectionOperation`: `pub enum SelectionOperation { New, Add, Subtract, Intersect }`. How a selection made by a click or a drag combines with the current one: the rule the Channels +- `craft_behavior::geometry::selection_op::SelectionOperation`: `pub enum SelectionOperation { New, Add, Subtract, Intersect }`. How a selection made by a click or a drag combines with the current one: the rule the Channels panel's ⌘-click, a mask thumbnail's ⌘-click and the selection tools share (Photoshop's). - `pub const ALL: [SelectionOperation; 4]`. Every operation, in Photoshop's options-bar order. - - `pub fn from_mods(mods: Mods) -> SelectionOperation`. The operation `mods` ask for: Shift and Alt `Intersect`, Shift `Add`, Alt `Subtract`, - - `pub fn resolve(bar: SelectionOperation, mods: Mods, has_selection: bool) -> SelectionOperation`. The operation a selection tool's gesture uses (Photoshop's): the options bar's `bar`, - - `pub fn badge(self) -> Option`. The badge beside the selection pointer: `Add` a plus, `Subtract` a minus, `Intersect` a - - `pub const fn name(self) -> &'static str`. The operation's stable name for commands and settings: `"new"`, `"add"`, `"subtract"`, + - `pub fn from_mods(mods: Mods) -> SelectionOperation`. The operation `mods` ask for: Shift and Alt `Intersect`, Shift `Add`, Alt `Subtract`, else `New`. + - `pub fn resolve(bar: SelectionOperation, mods: Mods, has_selection: bool) -> SelectionOperation`. The operation a selection tool's gesture uses (Photoshop's): the options bar's `bar`, overridden by `mods` as [`from_mods`] reads them (⇧ add, ⌥ subtract, ⇧⌥ intersect). + - `pub fn badge(self) -> Option`. The badge beside the selection pointer: `Add` a plus, `Subtract` a minus, `Intersect` a cross, `New` none. + - `pub const fn name(self) -> &'static str`. The operation's stable name for commands and settings: `"new"`, `"add"`, `"subtract"`, `"intersect"` (PhotoCraft's `select.loadSelection` operation values). ## `craft_behavior::geometry::snap` @@ -1061,7 +1064,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::snap::SnapGesture`: `pub enum SnapGesture { Point, Rect { at_press: Rect }, Axis { along: Axis } }`. How the host snaps a tool's pointer. - `pub const fn rect(at_press: Rect) -> Self`. A moving rectangle that was `at_press` when the gesture began. - `pub const fn axis(along: Axis) -> Self`. Only the coordinate across the lines that run `along` snaps: x for `Axis::Y`. -- `craft_behavior::geometry::snap::SnapKind`: `pub enum SnapKind { Guide, Grid, Bounds, Center, LayerEdge, LayerCenter, Selection }`. What a target is, so an app can filter (Snap To › Guides only) and the lines can be drawn in +- `craft_behavior::geometry::snap::SnapKind`: `pub enum SnapKind { Guide, Grid, Bounds, Center, LayerEdge, LayerCenter, Selection }`. What a target is, so an app can filter (Snap To › Guides only) and the lines can be drawn in the smart-guide colour or the plain one. - `pub const fn is_smart(self) -> bool`. Whether the target's lines draw in the smart-guide colour: `LayerEdge`, `LayerCenter` and `Center`. - `craft_behavior::geometry::snap::SnapKinds`: `pub struct SnapKinds`. A set of [`SnapKind`]s, a bit per kind: the kind filter a gesture passes to its snapping. - `pub const ALL: SnapKinds`. Every kind. @@ -1071,51 +1074,51 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `craft_behavior::geometry::snap::SnapLine`: `pub struct SnapLine { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. The line the UI draws for a snap that happened. - `craft_behavior::geometry::snap::SnapOptions`: `pub struct SnapOptions { pub on: bool, pub guides: bool, pub grid: bool, pub layers: bool, pub document_bounds: bool, pub selection: bool, pub smart_guides: bool, pub suspend: SnapSuspend }`. View › Snap To and View › Show › Smart Guides, as the app stores them. - `craft_behavior::geometry::snap::SnapSuspend`: `pub enum SnapSuspend { Control, Alt }`. The key that suspends snapping. - - `pub fn is_held(self, mods: Mods, os: Platform) -> bool`. Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl + - `pub fn is_held(self, mods: Mods, os: Platform) -> bool`. Whether this key is held in `mods` on `os`: Control is the Control key without ⌘ on macOS and Ctrl elsewhere (where it is `Mods::cmd`); Alt is Alt (⌥). - `craft_behavior::geometry::snap::SnapTarget`: `pub struct SnapTarget { pub along: Axis, pub position: f64, pub kind: SnapKind, pub span: Option<(f64, f64)> }`. One snap position on one axis. - - `pub const fn new(along: Axis, position: f64, kind: SnapKind) -> Self`. A full-height line of `kind` running `along` an axis, at `position` across it: a line along `Axis::Y` + - `pub const fn new(along: Axis, position: f64, kind: SnapKind) -> Self`. A full-height line of `kind` running `along` an axis, at `position` across it: a line along `Axis::Y` snaps x, a line along `Axis::X` snaps y. - `craft_behavior::geometry::snap::SnapTargets`: `pub struct SnapTargets`. The snap targets of one gesture. - `pub fn new() -> Self`. No targets. - - `pub fn reach_past_spans(mut self) -> Self`. These targets with every span reaching past its extent: a target catches a point or box anywhere along its + - `pub fn reach_past_spans(mut self) -> Self`. These targets with every span reaching past its extent: a target catches a point or box anywhere along its line, and its span only shapes the drawn smart guide between the two objects. - `pub fn add(&mut self, target: SnapTarget)`. Add one target. - - `pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind)`. Add a rectangle's four edges as `edge` targets and its two centre lines as `center` - - `pub fn with_document(self, options: &SnapOptions, bounds: Rect, guides: impl IntoIterator, grid: Option<(Point, Vec2)>,) -> Self`. Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the + - `pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind)`. Add a rectangle's four edges as `edge` targets and its two centre lines as `center` targets, each spanning the rectangle: how the app adds each layer (`LayerEdge`, `LayerCenter`) and the selection (`Selection` for both) to the targets [`with_document`] built. + - `pub fn with_document(self, options: &SnapOptions, bounds: Rect, guides: impl IntoIterator, grid: Option<(Point, Vec2)>,) -> Self`. Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the document bounds and centre: what every app has. - `pub fn filtered(&self, keep: impl Fn(SnapKind) -> bool) -> SnapTargets`. Only the targets `keep` accepts (Snap To with one kind off). - `pub fn is_empty(&self) -> bool`. Whether there is no target. - - `pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option`. The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of - - `pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option`. [`nearest_of`](Self::nearest_of) that also takes the query's extent `across` the other axis: a target with a + - `pub fn nearest_of(&self, along: Axis, value: f64, tolerance: f64, kinds: SnapKinds) -> Option`. The nearest target of a kind in `kinds` among the lines that run `along` an axis, within `tolerance` of `value` across them; [`SnapTargets::nearest`] is this with [`SnapKinds::ALL`]. + - `pub fn nearest_within(&self, along: Axis, value: f64, across: Option<(f64, f64)>, tolerance: f64, kinds: SnapKinds) -> Option`. [`nearest_of`] that also takes the query's extent `across` the other axis: a target with a span catches only a point or box overlapping that span there; without `across`, or for a target without a span, it is `nearest_of`. - `pub fn nearest(&self, along: Axis, value: f64, tolerance: f64) -> Option`. The nearest target among the lines that run `along` an axis, within `tolerance` of `value` across them. - `pub fn snap_point(&self, point: Point, tolerance: f64) -> (Point, Vec)`. `point` snapped on each axis independently, with the lines to draw. - - `pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec)`. [`snap_point`](Self::snap_point) to the targets of a kind in `kinds` only (a Distort corner snaps to guides - - `pub fn snap_rect(&self, rect: Rect, tolerance: f64) -> (Vec2, Vec)`. The offset that moves `rect` so its nearest edge or centre meets a target on each axis, - - `pub fn snap_rect_of(&self, rect: Rect, tolerance: f64, kinds: SnapKinds) -> (Vec2, Vec)`. [`snap_rect`](Self::snap_rect) to the targets of a kind in `kinds` only (moving a selection skips the selection's + - `pub fn snap_point_of(&self, point: Point, tolerance: f64, kinds: SnapKinds) -> (Point, Vec)`. [`snap_point`] to the targets of a kind in `kinds` only (a Distort corner snaps to guides only). + - `pub fn snap_rect(&self, rect: Rect, tolerance: f64) -> (Vec2, Vec)`. The offset that moves `rect` so its nearest edge or centre meets a target on each axis, with the lines to draw. + - `pub fn snap_rect_of(&self, rect: Rect, tolerance: f64, kinds: SnapKinds) -> (Vec2, Vec)`. [`snap_rect`] to the targets of a kind in `kinds` only (moving a selection skips the selection's own edges). - `craft_behavior::geometry::snap::across_axis`: `pub const fn across_axis(along: Axis) -> Axis`. The axis across `along`: a line running along `Axis::Y` (vertical) is placed on `Axis::X`. - `craft_behavior::geometry::snap::coordinate_across`: `pub const fn coordinate_across(along: Axis, p: Point) -> f64`. The coordinate of `p` a line running `along` an axis is placed by: x for a line along `Axis::Y`. -- `craft_behavior::geometry::snap::motion_across`: `pub fn motion_across(along: Axis) -> Vec2`. The document direction a line running `along` an axis moves in: x for a line along `Axis::Y`. A screen caller +- `craft_behavior::geometry::snap::motion_across`: `pub fn motion_across(along: Axis) -> Vec2`. The document direction a line running `along` an axis moves in: x for a line along `Axis::Y`. - `craft_behavior::geometry::snap::union`: `pub fn union(rects: impl IntoIterator) -> Option`. The bounding rectangle of `rects`, or `None` for none. ## `craft_behavior::grid` The `Grid` cursor: columns resolved from last pass's measurements, and the cell each child takes. -- `craft_behavior::grid::GridCursor`: `pub struct GridCursor`. Hands out the cells of one `Grid` pass, row-major. Cells are placed from `last` pass's measurements; this - - `pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A - - `pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor for a measuring run under a body sized from its content: each `Fill` column of `columns` is placed - - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column - - `pub fn each_alone(mut self) -> Self`. The cursor with each `Content` column measuring in the room the other columns leave at their least, whatever - - `pub fn short(&self) -> bool`. Whether the columns, as this sweep measured them, do not fit beside each other: the columns that do not share +- `craft_behavior::grid::GridCursor`: `pub struct GridCursor`. Hands out the cells of one `Grid` pass, row-major. + - `pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. + - `pub fn sized_by_content(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self`. A cursor for a measuring run under a body sized from its content: each `Fill` column of `columns` is placed as a `Content` column, taking the width its cells take, while the room of the cells after it stays what the fill column leaves them. `last` gives the rows and the columns' least. + - `pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self`. A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column measure in no bound along x, so each column measures its widest cell. + - `pub fn each_alone(mut self) -> Self`. The cursor with each `Content` column measuring in the room the other columns leave at their least, whatever the columns before it took: each column asks for what it would take alone, so `short` tells whether the columns fit beside each other. + - `pub fn short(&self) -> bool`. Whether the columns, as this sweep measured them, do not fit beside each other: the columns that do not share the room left take more than the room, or a cell of a `Fill` column took more than its share. - `pub fn cell(&mut self, size: Vec2) -> Rect`. The cell of the next child, whose measured size is `size`. - - `pub fn room(&self) -> Vec2`. The room the next child measures in: as wide as its column, or for a `Content` column as wide as the columns - - `pub fn region(&self) -> Rect`. The rect the next child measures and is placed in: from its column's start edge and its row's top, as large - - `pub fn fill_room(&self) -> Vec2`. The room the next child fills when it fills its width: its column's width, which for a `Content` column is the + - `pub fn room(&self) -> Vec2`. The room the next child measures in: as wide as its column, or for a `Content` column as wide as the columns that do not fill leave, and as tall as the grid below its row's top. + - `pub fn region(&self) -> Rect`. The rect the next child measures and is placed in: from its column's start edge and its row's top, as large as `room()`. + - `pub fn fill_room(&self) -> Vec2`. The room the next child fills when it fills its width: its column's width, which for a `Content` column is the width its cells have measured, not the room the cell measures in. - `pub fn in_content_column(&self) -> bool`. Whether the next child goes in a `Content` column. - `pub fn column(&self) -> usize`. The column the next child goes in. - - `pub fn widen(&mut self, size: Vec2)`. The cell last placed measured `size` after all: its column and row record that, and a `Content` column offers + - `pub fn widen(&mut self, size: Vec2)`. The cell last placed measured `size` after all: its column and row record that, and a `Content` column offers the cells after it in this pass the wider width. - `pub fn measured(&self) -> &GridMeasure`. What this pass measured. -- `craft_behavior::grid::GridMeasure`: `pub struct GridMeasure { pub columns: Vec, pub rows: Vec, pub least: Vec }`. What a `Grid` pass measured: the widest child per column and the tallest per row, and the least each column +- `craft_behavior::grid::GridMeasure`: `pub struct GridMeasure { pub columns: Vec, pub rows: Vec, pub least: Vec }`. What a `Grid` pass measured: the widest child per column and the tallest per row, and the least each column takes when the grid asked its columns for it. - `pub const fn new(columns: Vec, rows: Vec) -> Self`. A measurement of `columns` and `rows`. - `pub fn with_least(mut self, least: Vec) -> Self`. The measurement with the least width of each column. -- `craft_behavior::grid::resolve_columns`: `pub fn resolve_columns(columns: &[ColumnWidth], content: &[f32], room: f32, gap: f32) -> Vec`. The width of each column in `room`: `Fixed` is the app's width, `Content` the widest child of last pass +- `craft_behavior::grid::resolve_columns`: `pub fn resolve_columns(columns: &[ColumnWidth], content: &[f32], room: f32, gap: f32) -> Vec`. The width of each column in `room`: `Fixed` is the app's width, `Content` the widest child of last pass (`content[i]`, zero when unknown), and `Fill` columns share what is left by weight. `Controls` and `Toggle` widths take no room until their owner resolves them. ## `craft_behavior::hit` @@ -1129,36 +1132,36 @@ Hit shapes, their priority and the arena's resolve rule (8.3). - `pub const fn circle(center: Pos2, radius: f32) -> Self`. A disc. - `pub const fn segment(a: Pos2, b: Pos2) -> Self`. A line segment. - `pub fn polyline(points: Vec, closed: bool) -> Self`. A chain of segments, closed when `closed`, hit within [`LINE_REACH`]. - - `pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self`. A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from + - `pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self`. A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from a line's. - `pub fn outside_polygon(within: Rect, polygon: Vec) -> Self`. The part of `within` outside `polygon`. - `pub fn excluding(shape: HitShape, holes: Vec<(Pos2, f32)>) -> HitShape`. `shape` without the discs `holes` (a centre and a radius each). - `pub fn bounds(&self) -> Rect`. The smallest rectangle around the shape. - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. - - `pub fn snapped(&self, to: &HitShape, within: f32) -> Self`. The shape with each coordinate taken from `to`'s where the two lie within `within` points, when both are the + - `pub fn snapped(&self, to: &HitShape, within: f32) -> Self`. The shape with each coordinate taken from `to`'s where the two lie within `within` points, when both are the same kind of shape with as many points: two shapes `==` finds equal after it differ by no more than `within`. - `pub fn hit(&self, point: Pos2) -> bool`. Whether `point` hits the shape. - `craft_behavior::hit::LINE_REACH`: `pub const LINE_REACH: f32`. How far from a line a point still hits it, in points. - `craft_behavior::hit::ResolveFor`: `pub enum ResolveFor { Press, Hover }`. What a resolution is for. - `craft_behavior::hit::Shape`: `pub struct Shape { pub shape: HitShape, pub sense: Sense, pub owner: O, pub part: Option, pub priority: HitPriority, pub position: u32, pub local: bool, pub min_across: f32, pub stacking: u32, pub drag_to_root: bool }`. One registered shape of the shape record: a root's, a member's or a part's. - `pub fn translated(&self, by: Vec2) -> Self`. The shape moved by `by`. - - `pub fn snapped(&self, to: &Shape, within: f32) -> Self`. The shape with its geometry and least size across taken from `to`'s where they lie within `within` points + - `pub fn snapped(&self, to: &Shape, within: f32) -> Self`. The shape with its geometry and least size across taken from `to`'s where they lie within `within` points ([`HitShape::snapped`]). - `pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self`. A shape of `owner` at stack `position`. - `pub const fn min_across(mut self, across: f32) -> Self`. The hit area is at least `across` points wide and high. - `pub const fn stacking(mut self, order: u32) -> Self`. The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre. - `pub const fn local(mut self, local: bool) -> Self`. The shape lies in the body layer's space. - - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. The + - `pub fn hits(&self, point: Pos2) -> bool`. Whether `point` lies in the hit area: the shape grown to be at least its `min_across` wide and high. - `craft_behavior::hit::Winner`: `pub struct Winner { pub index: usize, pub owner: O, pub part: Option, pub sense: Sense, pub local: bool, pub drag_to_root: bool }`. The shape that won a resolution. -- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest +- `craft_behavior::hit::resolve`: `pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option>`. The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest centre, the last registered. - `craft_behavior::hit::resolve_mapped`: `pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFor, to_local: impl Fn(Pos2) -> Pos2) -> Option>`. [`resolve`] where shapes with `local` set are tested at `to_local(point)`. ## `craft_behavior::hold_repeat` Steps due while a press is held, as a spinner button repeats. -- `craft_behavior::hold_repeat::HoldRepeat`: `pub struct HoldRepeat`. A press held on a spinner button, known by the pass time it began. It keeps nothing between passes: a pass builds it +- `craft_behavior::hold_repeat::HoldRepeat`: `pub struct HoldRepeat`. A press held on a spinner button, known by the pass time it began. - `pub const DELAY: f64`. Seconds a press is held before the steps repeat. - `pub const INTERVAL: f64`. Seconds between repeated steps. - `pub const fn new(start: f64) -> Self`. A press that began at pass time `start`, in seconds. - - `pub fn due(&self, now: f64, elapsed: f64) -> u32`. The repeats due in the pass at `now` that follows another `elapsed` seconds after: the repeat instants in + - `pub fn due(&self, now: f64, elapsed: f64) -> u32`. The repeats due in the pass at `now` that follows another `elapsed` seconds after: the repeat instants in `(now - elapsed, now]`. - `pub fn next_repeat(&self, now: f64) -> f64`. The first repeat instant after `now`, the time to ask the next pass for while the press is held. ## `craft_behavior::input` @@ -1184,7 +1187,7 @@ Intents: a key, an AccessKit action or typed text turned into meaning (spec 9.2) - `pub const PLAIN: MoveMods`. A move by one unit with no modifier. - `pub const fn new(extend: bool, lead: bool, by: Granularity) -> MoveMods`. Modifiers with the given parts and no fine flag. - `pub const fn fine(mut self, on: bool) -> MoveMods`. The same modifiers with the fine flag set to `on`. -- `craft_behavior::intent::NavMove`: `pub enum NavMove { Back, Forward, Up, Down, PageUp, PageDown, Start, End }`. A logical move. `Back` and `Forward` follow the reading direction; the runtime flips physical arrows +- `craft_behavior::intent::NavMove`: `pub enum NavMove { Back, Forward, Up, Down, PageUp, PageDown, Start, End }`. A logical move. `Back` and `Forward` follow the reading direction; the runtime flips physical arrows under right-to-left text when it delivers them. - `craft_behavior::intent::TextPos`: `pub struct TextPos { pub line: usize, pub byte: usize }`. A position in a text document. - `pub const fn new(line: usize, byte: usize) -> TextPos`. The position `byte` bytes into `line`. @@ -1194,21 +1197,21 @@ Item geometry: where each item of a collection sits for a scroll offset and view - `craft_behavior::item_layout::FreeLayout`: `pub struct FreeLayout { pub rects: Vec }`. Items at positions the document stores: a freeform bin or a node graph. - `pub fn new(rects: Vec) -> Self`. Items at `rects`, in content coordinates. -- `craft_behavior::item_layout::ItemLayout`: `pub trait ItemLayout`. Item geometry in content units. Offsets are `f64`, so a sheet of a million rows places its last row +- `craft_behavior::item_layout::ItemLayout`: `pub trait ItemLayout`. Item geometry in content units. - `fn mirrors(&self) -> bool`. False for a layout whose positions are document data (`FreeLayout`); the item step then leaves them as given. - `fn content_size(&self) -> ScrollPos`. Finite and non-negative. - `fn visible(&self, offset: ScrollPos, view: Vec2, out: &mut Vec)`. The indices of the items that intersect a viewport of size `view` scrolled to `offset`, ascending. - `fn rect(&self, at: usize, offset: ScrollPos) -> Rect`. The rect of item `at`. - `fn hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item under `point`. - - `fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while + - `fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option`. The item whose drop area contains `point`. - `fn nav(&self) -> NavShape`. How arrow keys move through the items. - - `fn row_len(&self, _row: usize) -> Option`. `NavShape::RaggedGrid`: the number of items in `row`, rows holding consecutive items and a run of hidden items - - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows + - `fn row_len(&self, _row: usize) -> Option`. `NavShape::RaggedGrid`: the number of items in `row`, rows holding consecutive items and a run of hidden items counting as a row of its own; `None` past the last row. + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `NavShape::RaggedGrid`: the columns a vertical move from row `from` to row `to` shifts the column by, when the rows are offset against each other; 0 when they line up. - `fn shown(&self, _at: usize) -> bool`. Whether item `at` takes a place in the layout; a hidden item (in a closed group) cannot take the lead. - `fn cells(&self, _at: usize, _offset: ScrollPos, _out: &mut Vec<(ColumnKey, Rect)>)`. The cells of item `at`, with their rects. - `fn grid(&self) -> Option<&GridView>`. Column virtualisation and sections of a sheet. - - `fn frozen_band(&self, _at: usize) -> f32`. The height at the top of the view that item `at` must not paint into: the zoomed frozen-row band for a scrolled - - `fn first_navigable(&self) -> usize`. The first item that is not frozen: where Ctrl or Cmd with Home goes. Zero for a layout without frozen rows. + - `fn frozen_band(&self, _at: usize) -> f32`. The height at the top of the view that item `at` must not paint into: the zoomed frozen-row band for a scrolled row, zero for a frozen row and for a layout without frozen rows. + - `fn first_navigable(&self) -> usize`. The first item that is not frozen: where Ctrl or Cmd with Home goes. - `fn set_columns(&mut self, _columns: &[(ColumnKey, f32)])`. The column widths the collection resolved, from the start edge; layouts without columns ignore them. - `fn column_count(&self) -> usize`. The number of columns of a table or sheet; 0 for a layout with none. - `fn column_shown(&self, _index: usize) -> bool`. Whether the column at position `index` is shown; a hidden column has no cell and the arrows skip it. @@ -1217,30 +1220,30 @@ Item geometry: where each item of a collection sits for a scroll offset and view - `fn is_auto(&self, _at: usize) -> bool`. Whether item `at` is as tall as it measures itself. - `fn measured(&mut self, _heights: &dyn Fn(usize) -> Option)`. Takes the measured heights of the auto items: `heights(at)` is `None` before the item's first measure. - `fn set_height(&mut self, _at: usize, _height: f32)`. An auto item measured `height` in this pass; the items after it move. - - `fn auto_widths(&self) -> bool`. Whether the items are as wide as they measure themselves. A layout that asks for widths places the items - - `fn set_width(&mut self, _at: usize, _ideal: f32, _min: f32)`. An auto-width item measured `ideal` and `min` width. The values of the previous pass arrive before - - `fn set_view(&mut self, _viewport: Vec2, _offset: ScrollPos)`. The viewport and scroll offset the grid view describes. Layouts without a grid ignore it. - - `fn set_fit(&mut self, _at: usize, _width: Option)`. Item `at` is as wide as it measured, `width` from the start edge, in a layout that gives every item one width; -- `craft_behavior::item_layout::LineIndex`: `pub struct LineIndex`. Lines (rows or columns) with a default size, the lines whose size differs and their prefix sums, so the start + - `fn auto_widths(&self) -> bool`. Whether the items are as wide as they measure themselves. + - `fn set_width(&mut self, _at: usize, _ideal: f32, _min: f32)`. An auto-width item measured `ideal` and `min` width. + - `fn set_view(&mut self, _viewport: Vec2, _offset: ScrollPos)`. The viewport and scroll offset the grid view describes. + - `fn set_fit(&mut self, _at: usize, _width: Option)`. Item `at` is as wide as it measured, `width` from the start edge, in a layout that gives every item one width; `None` gives it that width again. +- `craft_behavior::item_layout::LineIndex`: `pub struct LineIndex`. Lines (rows or columns) with a default size, the lines whose size differs and their prefix sums, so the start of a line and the line at a position are a binary search over the differing lines only: a sheet of 1,048,576 rows or 16,384 columns of which a few differ stores a few entries. - `pub fn uniform(size: f32, count: u32) -> Self`. `count` lines of `size` each (negative or NaN sizes count as `0.0`). - - `pub fn set(&mut self, line: u32, size: f32)`. Gives `line` the size `size`; the lines after it move. A line at or past `count` is ignored. - - `pub fn start(&self, line: u32) -> f64`. The start of `line`: the sum of the sizes before it. A line past the last one continues at the default size. + - `pub fn set(&mut self, line: u32, size: f32)`. Gives `line` the size `size`; the lines after it move. + - `pub fn start(&self, line: u32) -> f64`. The start of `line`: the sum of the sizes before it. - `pub fn end(&self, line: u32) -> f64`. The end of `line`: its start plus its size. - `pub fn shown(&self, line: u32) -> bool`. Whether `line` exists and has a size above zero. - `pub fn count(&self) -> u32`. The number of lines. - `pub fn total(&self) -> f64`. The sum of all sizes: where the line after the last would start. - `craft_behavior::item_layout::SHEET_ZOOM`: `pub const SHEET_ZOOM: RangeInclusive`. The least and greatest zoom of a sheet (10 %…400 %). -- `craft_behavior::item_layout::SheetLayout`: `pub struct SheetLayout`. Rows of a sheet: one position per row, each split into the sheet's columns, over one [`LineIndex`] for the rows +- `craft_behavior::item_layout::SheetLayout`: `pub struct SheetLayout`. Rows of a sheet: one position per row, each split into the sheet's columns, over one [`LineIndex`] for the rows and one for the columns. - `pub fn new(source: &dyn DisplayOrder, row_h: f32, columns: Vec<(ColumnKey, f32)>) -> Self`. A row of `row_h` per entry of `source`, split into `columns`, each with its key and width. - - `pub fn lines(rows: LineIndex, columns: LineIndex) -> Self`. A sheet with the size of every row and column in `rows` and `columns`, at 100 % zoom. A column's key is + - `pub fn lines(rows: LineIndex, columns: LineIndex) -> Self`. A sheet with the size of every row and column in `rows` and `columns`, at 100 % zoom. - `pub fn frozen(mut self, count: usize) -> Self`. The first `count` columns stay in view while the others scroll. - - `pub fn frozen_rows(mut self, count: u32) -> Self`. The first `count` rows stay in view while the others scroll. Hidden rows among them take no room. + - `pub fn frozen_rows(mut self, count: u32) -> Self`. The first `count` rows stay in view while the others scroll. - `pub fn zoom(mut self, zoom: f32) -> Self`. Every row height and column width is multiplied by `zoom`, clamped to [`SHEET_ZOOM`]. - `pub fn rows(&self) -> &LineIndex`. The row extents at 100 %. - `pub fn columns(&self) -> &LineIndex`. The column extents at 100 %. - `craft_behavior::item_layout::SpanLayout`: `pub struct SpanLayout { pub row_h: f32, pub count: usize, pub width: f32, pub columns: Vec<(ColumnKey, f32)>, pub tree: bool }`. Rows of equal height, optionally split into columns: lists, popup lists, tab strips and timeline tracks. - `pub fn new(source: &dyn DisplayOrder, width: f32, row_h: f32) -> Self`. One row of `row_h` per entry of `source`, `width` wide, with no columns. - - `pub fn sized(source: &dyn ItemSource, width: f32, row_h: f32) -> Self`. Rows as tall as `source` says: `Height` and `Rect` are the app's, `Aspect` follows the width, and `Auto` + - `pub fn sized(source: &dyn ItemSource, width: f32, row_h: f32) -> Self`. Rows as tall as `source` says: `Height` and `Rect` are the app's, `Aspect` follows the width, and `Auto` rows take `row_h` until the item step feeds their measured height. - `pub fn columns(mut self, columns: Vec<(ColumnKey, f32)>) -> Self`. The columns with their widths, from the start edge. - `pub fn tree(mut self) -> Self`. Rows that expand and collapse. - `craft_behavior::item_layout::TileLayout`: `pub struct TileLayout { pub tile: Vec2, pub gap: f32, pub count: usize, pub width: f32, pub fixed_columns: Option }`. Equal tiles that wrap at the width: tile grids, preset grids, font cards and swatch grids. @@ -1252,9 +1255,9 @@ Item geometry: where each item of a collection sits for a scroll offset and view `MarqueeSelect`: the rectangle a drag over list items sweeps and the selection it makes (8.7). -- `craft_behavior::item_marquee::MarqueeMode`: `pub enum MarqueeMode { Replace, Add, Toggle, Subtract }`. How the swept items combine with the selection the drag started from. Items follow the list rule (Cmd or Ctrl +- `craft_behavior::item_marquee::MarqueeMode`: `pub enum MarqueeMode { Replace, Add, Toggle, Subtract }`. How the swept items combine with the selection the drag started from. - `pub const fn of(mods: Mods) -> MarqueeMode`. The mode a press with `mods` starts: Shift adds, Cmd or Ctrl toggles, Alt subtracts, none replaces. -- `craft_behavior::item_marquee::MarqueeSelect`: `pub struct MarqueeSelect`. A marquee drag in progress. It holds the selection the drag started from, so a cancel restores it. +- `craft_behavior::item_marquee::MarqueeSelect`: `pub struct MarqueeSelect`. A marquee drag in progress. - `pub fn begin(origin: Pos2, mods: Mods, base: Vec) -> Self`. A marquee that began at `origin` over `base`, in the mode `mods` pick. - `pub fn mode(&self) -> MarqueeMode`. The mode the drag runs in. - `pub fn update(&mut self, pos: Pos2)`. Moves the free corner to `pos`. @@ -1266,17 +1269,17 @@ Item geometry: where each item of a collection sits for a scroll offset and view Where a collection's items come from: the data traits and the one way to show a slice. -- `craft_behavior::item_source::DisplayOrder`: `pub trait DisplayOrder`. The order a collection shows its entries in. The library never owns the data. +- `craft_behavior::item_source::DisplayOrder`: `pub trait DisplayOrder`. The order a collection shows its entries in. - `fn len(&self) -> usize`. The number of entries. - - `fn key(&self, at: usize) -> K`. The key of entry `at`. Items take their id from it, never from the position. - - `fn index_of(&self, key: &K) -> Option where K: PartialEq,`. The position of `key`, `None` when the source no longer holds it. The default scans; a source over a + - `fn key(&self, at: usize) -> K`. The key of entry `at`. + - `fn index_of(&self, key: &K) -> Option where K: PartialEq,`. The position of `key`, `None` when the source no longer holds it. - `fn depth(&self, _at: usize) -> usize`. The nesting depth of entry `at`, 0 for a root. - `fn has_children(&self, _at: usize) -> bool`. Whether entry `at` has children. - `fn open(&self, _at: usize) -> bool`. Whether the children of entry `at` show. - `fn is_section(&self, _at: usize) -> bool`. Whether entry `at` is a section header, which navigation skips. - - `fn section_stop(&self, _at: usize) -> bool`. Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a + - `fn section_stop(&self, _at: usize) -> bool`. Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a press, and opens or closes with Forward and Back when it has children. - `fn selectable_section(&self, _at: usize) -> bool`. Whether a section stop also represents an item that keyboard selection can pick or extend over. - - `fn section_stops_before(&self, _at: usize) -> usize`. How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so + - `fn section_stops_before(&self, _at: usize) -> usize`. How many section stops (`section_stop`) come before entry `at`. - `fn enabled(&self, _at: usize) -> bool`. Whether entry `at` can take the lead. - `fn text(&self, _at: usize) -> Option>`. The text type-ahead matches entry `at` against. - `fn revision(&self) -> Option`. A number that changes whenever the entries or their order change; `None` when the source does not report. @@ -1284,11 +1287,11 @@ Where a collection's items come from: the data traits and the one way to show a - `craft_behavior::item_source::ItemSource`: `pub trait ItemSource: DisplayOrder`. A display order that also says how tall its entries want to be. - `fn size_hint(&self, _at: usize) -> SizeHint`. The size entry `at` wants. - `fn toggled(&self, _at: usize, _column: &ColumnKey) -> bool`. Whether the cell of entry `at` in the toggle column `column` is on. - - `fn toggle_enabled(&self, _at: usize, _column: &ColumnKey) -> bool`. Whether the cell of entry `at` in the toggle column `column` can be flipped: a locked field's cell shows its - - `fn sub_row(&self, _at: usize) -> Option`. `Some(steps)` when entry `at` is a sub-row of an entry above it (a layer's effects): a compact row whose toggle + - `fn toggle_enabled(&self, _at: usize, _column: &ColumnKey) -> bool`. Whether the cell of entry `at` in the toggle column `column` can be flipped: a locked field's cell shows its value and takes neither a press, a sweep nor the Space key. + - `fn sub_row(&self, _at: usize) -> Option`. `Some(steps)` when entry `at` is a sub-row of an entry above it (a layer's effects): a compact row whose toggle cells sit in its content, `steps` indent steps from its start, instead of in their columns (`sub_row_cells`). - `craft_behavior::item_source::Keyed`: `pub struct Keyed<'a, T, K>`. A slice as an item source, each entry keyed by `key`. - `pub fn with_text(mut self, text: impl for<'t> Fn(&'t T) -> Cow<'t, str> + 'a) -> Self`. The text type-ahead matches each entry against. - - `pub fn with_toggled(mut self, toggled: impl Fn(&T, &ColumnKey) -> bool + 'a) -> Self`. Whether an entry's cell in a toggle column is on. Without it every toggle cell is off. + - `pub fn with_toggled(mut self, toggled: impl Fn(&T, &ColumnKey) -> bool + 'a) -> Self`. Whether an entry's cell in a toggle column is on. - `craft_behavior::item_source::Outline`: `pub struct Outline<'a, K>`. `DisplayOrder` as the key-free outline the navigation core steps over. - `pub fn new(order: &'a dyn DisplayOrder) -> Self`. The outline of `order`. - `pub fn columns(mut self, columns: usize) -> Self`. The cells of every position, for a sheet's cell navigation. @@ -1322,13 +1325,13 @@ The key table (spec 9.2): the one place that maps a key press to an intent and m - `pub const fn owner_arrows(mut self, on: bool) -> Self`. The arrow keys are the enclosing component's, not this role's moves. - `pub const fn home_row(mut self, row: usize) -> Self`. Ctrl or Cmd with Home goes to item `row`. - `pub const fn text(mut self, on: bool) -> Self`. The stop is a text part. -- `craft_behavior::keys::REORDER_KEYS`: `pub const REORDER_KEYS: [Chord; 6]`. The stacking keys (Photoshop's Bring Forward and Send Backward): Cmd+] moves the selected items one place toward the +- `craft_behavior::keys::REORDER_KEYS`: `pub const REORDER_KEYS: [Chord; 6]`. The stacking keys (Photoshop's Bring Forward and Send Backward): Cmd+] moves the selected items one place toward the front, Cmd+[ one place toward the back, and with Shift all the way. - `craft_behavior::keys::ReorderKeys`: `pub enum ReorderKeys { Stacking, AltArrows }`. The named key scheme of a reorderable collection. -- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation`. The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on +- `craft_behavior::keys::drop_operation`: `pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation`. The drop operation the held modifiers pick over a target that copies with `copy`. - `craft_behavior::keys::intent`: `pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option`. The intent a key press has for a stop of `role`, if any. `Enter` and `Space` as activation are not rows: -- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option`. The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other +- `craft_behavior::keys::reorder_intent`: `pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option`. The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other press. - `craft_behavior::keys::split_digits`: `pub fn split_digits(text: &str) -> (Vec, String)`. Typed `text` split for a role that takes digits: the ASCII digits it holds, in order, and the text without them. -- `craft_behavior::keys::toward_end`: `pub fn toward_end(front: bool, axis: Axis) -> bool`. Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical +- `craft_behavior::keys::toward_end`: `pub fn toward_end(front: bool, axis: Axis) -> bool`. Whether a move toward the front goes toward the end of an order laid out along `axis`. ## `craft_behavior::label_column` @@ -1336,7 +1339,7 @@ The key table (spec 9.2): the one place that maps a key press to an intent and m - `craft_behavior::label_column::LabelColumn`: `pub struct LabelColumn { pub width: f32, pub stack_below: f32, pub gap: f32 }`. The label column of a row: a width token, and the row width under which the label moves above the control. - `pub const fn new(width: f32, stack_below: f32, gap: f32) -> Self`. A column `width` wide that stacks below `stack_below`, with `gap` between label and control. - - `pub fn place(&self, flow: Flow, label: Vec2, label_baseline: f32, control_baseline: Option) -> LabelPlacement`. Places a label of `label` size whose baseline is `label_baseline` below its top, and the control in the + - `pub fn place(&self, flow: Flow, label: Vec2, label_baseline: f32, control_baseline: Option) -> LabelPlacement`. Places a label of `label` size whose baseline is `label_baseline` below its top, and the control in the rest of `flow`'s rect. `control_baseline` is the distance from the control's top to its first baseline as measured last pass; with it the label's baseline lines up with the control's. `None` (the first appearance) aligns the tops. - `craft_behavior::label_column::LabelPlacement`: `pub struct LabelPlacement { pub label: Rect, pub control: Rect, pub stacked: bool }`. What `LabelColumn::place` decided for one row. ## `craft_behavior::layout_memory` @@ -1348,7 +1351,7 @@ The tolerance rule of layout memory: when a measured size asks for a discard pas - `pub fn at(&self, now: f64) -> Vec2`. The size at clock reading `now`, eased in and out. - `pub fn is_done(&self, now: f64) -> bool`. Whether the tween has reached its end at `now`. - `craft_behavior::layout_memory::measure_tolerance`: `pub fn measure_tolerance(pixels_per_point: f32) -> f32`. The tolerance in points under which a measured size equals the one placement used: half a physical pixel. -- `craft_behavior::layout_memory::measured_change_asks_for_discard`: `pub fn measured_change_asks_for_discard(recorded: Option, real: Vec2, changed_last_frame: bool, tolerance: f32) -> bool`. Whether a measured size asks for a discard pass. `recorded` is the size placement used this frame +- `craft_behavior::layout_memory::measured_change_asks_for_discard`: `pub fn measured_change_asks_for_discard(recorded: Option, real: Vec2, changed_last_frame: bool, tolerance: f32) -> bool`. Whether a measured size asks for a discard pass. `recorded` is the size placement used this frame (`None` on a block's first appearance), `real` the size the block measured, `changed_last_frame` whether the block's size also changed in the previous frame, `tolerance` the size under which two sizes are equal ([`measure_tolerance`]). ## `craft_behavior::middle_scroll` @@ -1357,10 +1360,10 @@ The middle button's auto-scroll latch: the gesture state of one middle press. - `craft_behavior::middle_scroll::MiddleButton`: `pub enum MiddleButton { Pan, AutoScroll }`. What the middle button does over a scroll area. - `craft_behavior::middle_scroll::MiddleScroll`: `pub struct MiddleScroll`. The auto-scroll latch of one middle press. - `pub fn press(&mut self, at: Pos2, inside: bool)`. A middle press: inside the scroll area it latches at `at`; a second press ends the latch. - - `pub fn release(&mut self)`. The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier - - `pub fn swallows(&mut self, phase: PressPhase) -> bool`. Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the + - `pub fn release(&mut self)`. The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier release keeps it. + - `pub fn swallows(&mut self, phase: PressPhase) -> bool`. Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the `Down` that cancels an active latch and for each later phase of that press through its release or cancel. - `pub fn cancel(&mut self)`. Ends the latch. - - `pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2`. One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and + - `pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2`. One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and returns the vertical scroll for the step `frame_step(dt)`, at `|d|^2.2 Ă— 0.04` points per second, reversed by `invert`. - `pub fn anchor(&self) -> Option`. Where the latch is anchored, `None` when there is none. - `pub fn active(&self) -> bool`. Whether a latch is active. @@ -1368,11 +1371,11 @@ The middle button's auto-scroll latch: the gesture state of one middle press. The connected monitors, as every window placement reads them. -- `craft_behavior::monitor::Monitor`: `pub struct Monitor { pub key: MonitorKey, pub pos_px: [i32; 2], pub size_px: [u32; 2], pub scale: f32, pub work_px: Option<([i32; 2], [u32; 2])> }`. A connected monitor, in physical pixels of the desktop's coordinate space (negative for a monitor left of or +- `craft_behavior::monitor::Monitor`: `pub struct Monitor { pub key: MonitorKey, pub pos_px: [i32; 2], pub size_px: [u32; 2], pub scale: f32, pub work_px: Option<([i32; 2], [u32; 2])> }`. A connected monitor, in physical pixels of the desktop's coordinate space (negative for a monitor left of or above the primary). - `pub fn new(key: MonitorKey, pos_px: [i32; 2], size_px: [u32; 2], scale: f32) -> Self`. A monitor at `pos_px` of `size_px` pixels with `scale`, usable in full. - - `pub fn with_work_px(mut self, pos_px: [i32; 2], size_px: [u32; 2]) -> Self`. Sets the usable area (see [`work_px`](Self::work_px)). + - `pub fn with_work_px(mut self, pos_px: [i32; 2], size_px: [u32; 2]) -> Self`. Sets the usable area (see [`work_px`]). - `pub fn rect_px(&self) -> Rect`. The monitor's area in pixels. - - `pub fn points_at(&self, window_scale: f32) -> Rect`. The monitor's area in points of a window whose scale is `window_scale`. Monitors that touch in pixels touch + - `pub fn points_at(&self, window_scale: f32) -> Rect`. The monitor's area in points of a window whose scale is `window_scale`. - `craft_behavior::monitor::MonitorKey`: `pub struct MonitorKey { pub name: String, pub size_px: [u32; 2] }`. Identifies a monitor across launches: the name the platform reports and its size in pixels. - `pub fn new(name: impl Into, size_px: [u32; 2]) -> Self`. A key for the monitor called `name` with size `size_px`. @@ -1388,7 +1391,7 @@ The motion level an animation runs at. ## `craft_behavior::nav` -The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving groups, type-ahead and +The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving groups, type-ahead and single-value keys. - `craft_behavior::nav::Arrows`: `pub enum Arrows { All, Horizontal, Vertical, None }`. Which arrow keys a roving group moves its lead with. - `craft_behavior::nav::LARGE_STEPS`: `pub const LARGE_STEPS: f64`. How many small steps one large step is, when a control sets no large step of its own. @@ -1401,9 +1404,9 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `fn is_section(&self, at: usize) -> bool`. Whether the position is a section header, which a move skips. - `fn enabled(&self, at: usize) -> bool`. Whether the position can take the lead. - `fn row_len(&self, _row: usize) -> Option`. `RaggedGrid`: the number of positions in `row`; rows hold consecutive positions. `None` past the last row. - - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are + - `fn column_shift(&self, _from: usize, _to: usize) -> isize`. `RaggedGrid`: how many columns a vertical move from row `from` to row `to` shifts the column by, for rows that are offset against each other (a honeycomb's). 0 for rows that line up. - `fn columns(&self) -> usize`. `Cell`: the cells of every position (a row of a sheet). - - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a + - `fn first_column(&self) -> Option`. `WrappedGrid`: the column of position 0 when the grid has blank cells before it (the leading days of a calendar month), `None` for a grid that fills from its first column. - `fn rect(&self, _at: usize) -> Option`. `Spatial`: where the position sits, in any one coordinate space. - `fn is_empty(&self) -> bool`. Whether there are no positions. - `craft_behavior::nav::NavShape`: `pub enum NavShape { Flat, Tree, WrappedGrid { columns: usize }, BoundedGrid { columns: usize }, RaggedGrid, Cell, Spatial }`. The geometry a collection's keyboard navigation follows. @@ -1423,35 +1426,35 @@ The navigation core (spec 9.5): shapes, the key-free outline, stepping, roving g - `pub const fn page(mut self, rows: Option) -> Self`. Rows a Page key covers. - `pub const fn letters(mut self, letters: Letters) -> Self`. Whether letters pick entries. - `pub const fn arrows(mut self, arrows: Arrows) -> Self`. The arrows the group takes. - - `pub const fn first_column(mut self, column: usize) -> Self`. The column of the first member of a wrapped grid with `column` blank cells before it: Up and Down keep the + - `pub const fn first_column(mut self, column: usize) -> Self`. The column of the first member of a wrapped grid with `column` blank cells before it: Up and Down keep the column, Home and End go to the ends of the row. - `pub const fn hands_back(mut self) -> Self`. A move the group cannot make reaches the owning component, which may page or change what the group shows. - `pub const fn keeps_lead_moves(mut self) -> Self`. Left and Right with the lead modifier reach the focused member. - `pub const fn no_lead(mut self, on: bool) -> Self`. Whether the focused member is no lead: the next move starts at an end, as from a group with no lead. - `pub const fn state(&self, lead: Option) -> NavState`. The state a step over this group starts from, at `lead`, or from no lead when the group has none. - - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document + - `pub const fn takes(&self, mv: NavMove, mods: MoveMods) -> bool`. Whether the group handles `mv` with `mods`: Page moves only with a page size and without `lead` (on a document canvas that scrolls sideways), Start and End only with Home and End, and no `lead_step` in a group that `keeps_lead_moves`. - `craft_behavior::nav::STEP_SHARE`: `pub const STEP_SHARE: f64`. The share of a value's span that one small step is, when a control sets no step. - `craft_behavior::nav::StepResult`: `pub enum StepResult { Set(f64), Ignored }`. What a single-value move does. - `craft_behavior::nav::TypeAhead`: `pub struct TypeAhead`. Typed letters of the last second as one prefix. - `pub const fn new() -> Self`. An empty buffer. - - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, - - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one + - `pub fn push(&mut self, letter: char, now: f64) -> &str`. Adds `letter` typed at `now` seconds and returns the prefix, its letters as typed: case is the caller's fold, applied in `pick`, so it follows the interface language. + - `pub fn pick<'a>(prefix: &str, from: Option, len: usize, label: impl Fn(usize) -> std::borrow::Cow<'a, str>, fold: impl Fn(&str) -> String,) -> Option`. The entry a prefix picks: the first match from the position after `from` when the prefix is one letter or one repeated letter (so repeating a letter cycles), from `from` itself for a longer prefix, wrapping at the end. - `craft_behavior::nav::ValueAxes`: `pub enum ValueAxes { Horizontal, Vertical, Both }`. The axes a single-value control reads moves on. - `craft_behavior::nav::ValueSteps`: `pub struct ValueSteps { pub value: f64, pub min: f64, pub max: f64, pub small: f64, pub large: f64, pub fine: f64, pub notch: f64 }`. The value and steps of a single-value control. - - `pub const fn new(value: f64, min: f64, max: f64, small: f64, large: f64) -> Self`. Steps over `min..=max` from `value`. The fine step is `small / LARGE_STEPS` and a wheel notch is `small`. + - `pub const fn new(value: f64, min: f64, max: f64, small: f64, large: f64) -> Self`. Steps over `min..=max` from `value`. - `pub const fn fine(mut self, fine: f64) -> Self`. The same steps with an Alt arrow of `fine`. - `pub const fn notch(mut self, notch: f64) -> Self`. The same steps with a wheel notch of `notch`. -- `craft_behavior::nav::lead_step`: `pub const fn lead_step(mv: NavMove, mods: MoveMods) -> Option`. The step Left or Right with the lead modifier makes, physical as the arrows are: Ctrl+Left and Ctrl+Right (Back -- `craft_behavior::nav::snap_to_step`: `pub fn snap_to_step(value: f64, step: f64, origin: f64, range: RangeInclusive) -> f64`. `value` clamped to `range`, then on the nearest of the stops `origin + k * step` and the ends of `range`; a tie -- `craft_behavior::nav::step`: `pub fn step(shape: NavShape, outline: &dyn NavOutline, state: &mut NavState, mv: NavMove, mods: MoveMods) -> NavStep`. Steps the lead of a navigation of `shape` over `outline` by `mv`. `mods.extend` keeps the anchor at the -- `craft_behavior::nav::step_until_changed`: `pub fn step_until_changed(from: T, step: impl Fn(T) -> T, same: impl Fn(T) -> bool) -> T`. The value `step` reaches from `from`, stepped again while a step still moves it and `same` says the value is the -- `craft_behavior::nav::step_value`: `pub fn step_value(steps: &ValueSteps, axes: ValueAxes, mv: NavMove, mods: MoveMods) -> StepResult`. Maps a move to the new value of a slider, dial, rating, resize handle or colour pad. `Forward`, `Up` and -- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries +- `craft_behavior::nav::lead_step`: `pub const fn lead_step(mv: NavMove, mods: MoveMods) -> Option`. The step Left or Right with the lead modifier makes, physical as the arrows are: Ctrl+Left and Ctrl+Right (Back and Forward with the lead), and Cmd+Left and Cmd+Right on macOS, which the key table makes a move to the start or end of the line. +- `craft_behavior::nav::snap_to_step`: `pub fn snap_to_step(value: f64, step: f64, origin: f64, range: RangeInclusive) -> f64`. `value` clamped to `range`, then on the nearest of the stops `origin + k * step` and the ends of `range`; a tie goes to the larger stop. +- `craft_behavior::nav::step`: `pub fn step(shape: NavShape, outline: &dyn NavOutline, state: &mut NavState, mv: NavMove, mods: MoveMods) -> NavStep`. Steps the lead of a navigation of `shape` over `outline` by `mv`. `mods.extend` keeps the anchor at the old lead; any other move clears it. `RaggedGrid` reads `row_len`, `Cell` reads `columns` and `Spatial` reads `rect` from the outline. +- `craft_behavior::nav::step_until_changed`: `pub fn step_until_changed(from: T, step: impl Fn(T) -> T, same: impl Fn(T) -> bool) -> T`. The value `step` reaches from `from`, stepped again while a step still moves it and `same` says the value is the same one as `from` to the control: a control that reports quantised values (a web-safe colour) steps on to the next value that differs, or as far as it can go. +- `craft_behavior::nav::step_value`: `pub fn step_value(steps: &ValueSteps, axes: ValueAxes, mv: NavMove, mods: MoveMods) -> StepResult`. Maps a move to the new value of a slider, dial, rating, resize handle or colour pad. `Forward`, `Up` and `PageUp` increase; `Start` and `End` go to the ends. +- `craft_behavior::nav::wheel_step`: `pub fn wheel_step(steps: &ValueSteps, axes: ValueAxes, wheel: &Wheel, rtl: bool) -> StepResult`. Maps a wheel share to the new value of a single-value control: one `notch` per whole wheel line the share carries ([`Wheel::lines`]), and one for a share of points or pages, up for positive scroll. ## `craft_behavior::one_press` The one-press-per-pass rule: a pass carries at most one press, as its last pointer event. -- `craft_behavior::one_press::split_after_first_press`: `pub fn split_after_first_press(mut events: Vec, is_press: impl Fn(&E) -> bool) -> (Vec, Vec)`. Splits `events` after the first press. The first part is what this pass receives, up to and including the +- `craft_behavior::one_press::split_after_first_press`: `pub fn split_after_first_press(mut events: Vec, is_press: impl Fn(&E) -> bool) -> (Vec, Vec)`. Splits `events` after the first press. ## `craft_behavior::overlay` @@ -1459,7 +1462,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `craft_behavior::overlay::Align`: `pub enum Align { Start, Center, End }`. How the overlay lines up with the anchor along the edge it hangs from. - `craft_behavior::overlay::MinWidth`: `pub enum MinWidth { None, Anchor, Points(f32) }`. The narrowest an overlay may be. - - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, + - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, `End`) an overlay shares no horizontal edge with it, so `Anchor` asks for nothing there. - `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool, pub covers_anchor: bool, pub offset: Vec2, pub clear: Option }`. What `place` reads. - `pub const fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self`. A request for `size` around `anchor` inside `bounds`: below, aligned to the start, no gap, free width. - `pub const fn size(mut self, size: Vec2) -> Self`. Sets the content size. @@ -1475,7 +1478,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `pub const fn covers_anchor(mut self, on: bool) -> Self`. Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds. - `craft_behavior::overlay::Placement`: `pub struct Placement { pub rect: Rect, pub side: Side }`. Where `place` put the overlay. - `craft_behavior::overlay::Side`: `pub enum Side { Below, Above, Start, End }`. The side of the anchor an overlay prefers. `Start` and `End` follow the reading direction. -- `craft_behavior::overlay::place`: `pub fn place(request: &PlaceRequest) -> Placement`. Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to +- `craft_behavior::overlay::place`: `pub fn place(request: &PlaceRequest) -> Placement`. Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to stay inside the bounds, its height (or width, beside the anchor) capped to the room. ## `craft_behavior::part` @@ -1483,9 +1486,9 @@ Part keys and part references: the one name for a part in focus, style, results, - `craft_behavior::part::PartKey`: `pub struct PartKey`. The key of a part, declared as a const by the component that owns it. - `pub const fn new(name: &'static str) -> PartKey`. A key named `name`; the name is unique within one component. - - `pub const CELL: PartKey`. A cell of a sheet row: `CELL.at(column)`. The item step writes the cell's `SELECTED` and `LEAD` flags into + - `pub const CELL: PartKey`. A cell of a sheet row: `CELL.at(column)`. - `pub const fn name(self) -> &'static str`. The name the key was declared with. - - `pub const fn at(self, i: u64) -> PartRef`. One of a repeated part: `POINT.at(id)`. `i` is a stable sub-key, an entity id where the repeats + - `pub const fn at(self, i: u64) -> PartRef`. One of a repeated part: `POINT.at(id)`. `i` is a stable sub-key, an entity id where the repeats are data and the position only for fixed repeats. - `craft_behavior::part::PartRef`: `pub struct PartRef { pub key: PartKey, pub index: Option }`. A part's key with an optional index. ## `craft_behavior::pixel_size` @@ -1497,7 +1500,7 @@ A size in whole pixels. ## `craft_behavior::placement` -Where windows go on the desktop: where a saved window opens ([`place`]), which monitor a window is on, and where +Where windows go on the desktop: where a saved window opens ([`place`]), which monitor a window is on, and where the next window of a cascade opens. - `craft_behavior::placement::Defaults`: `pub struct Defaults { pub size: [f32; 2], pub min: [f32; 2], pub screen_room: [f32; 2], pub restore_fullscreen: bool, pub no_position: bool }`. What the app wants when nothing (usable) is saved, and how the platform behaves. - `pub fn new(size: [f32; 2], min: [f32; 2]) -> Self`. Defaults for a first window of `size` points and a minimum of `min` points. @@ -1510,19 +1513,19 @@ Where windows go on the desktop: where a saved window opens ([`place`]), which m - `pub fn repaired(&self) -> Option`. The record with out-of-range numbers repaired, or `None` when its size is no size. - `pub fn position(&self) -> Option<[f32; 2]>`. The outer top-left corner in desktop points at the saved scale, where the position is known. - `craft_behavior::placement::capped`: `pub fn capped(size: Vec2, monitor: &Monitor, frame: Vec2, min: Vec2) -> Vec2`. `size` at least `min` and at most the monitor's usable area less `frame`; the cap wins over the minimum. -- `craft_behavior::placement::cascade`: `pub fn cascade(previous: Rect, size: Vec2, bounds: Rect, step: f32) -> Rect`. Where a window of `size` opens after the one at `previous`: one `step` right and down. An axis on which that -- `craft_behavior::placement::cascade_rects`: `pub fn cascade_rects(area: Rect, size: Vec2, n: usize, step: f32) -> Vec`. `n` windows of `size` in a cascade inside `area`: the first at its top left, each next one [`cascade`]d from the -- `craft_behavior::placement::monitor_of`: `pub fn monitor_of(monitors: &[Monitor], window_px: Rect) -> Option<&Monitor>`. The monitor the window at `window_px` (desktop pixels) is on: the one showing most of it or, when none shows it, -- `craft_behavior::placement::place`: `pub fn place(saved: Option<&Placement>, monitors: &[Monitor], home: Option, d: &Defaults) -> Placement`. Where a window opens: `saved` kept on a connected monitor, else the default size on `home` +- `craft_behavior::placement::cascade`: `pub fn cascade(previous: Rect, size: Vec2, bounds: Rect, step: f32) -> Rect`. Where a window of `size` opens after the one at `previous`: one `step` right and down. +- `craft_behavior::placement::cascade_rects`: `pub fn cascade_rects(area: Rect, size: Vec2, n: usize, step: f32) -> Vec`. `n` windows of `size` in a cascade inside `area`: the first at its top left, each next one [`cascade`]d from the one before. +- `craft_behavior::placement::monitor_of`: `pub fn monitor_of(monitors: &[Monitor], window_px: Rect) -> Option<&Monitor>`. The monitor the window at `window_px` (desktop pixels) is on: the one showing most of it or, when none shows it, the nearest. +- `craft_behavior::placement::place`: `pub fn place(saved: Option<&Placement>, monitors: &[Monitor], home: Option, d: &Defaults) -> Placement`. Where a window opens: `saved` kept on a connected monitor, else the default size on `home` (index into `monitors` of the monitor the system opens it on; the one at the origin, else the first, when `None`). ## `craft_behavior::press` -Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime converts egui's events once per +Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime converts egui's events once per pass and feeds them to a [`PressMachine`]. - `craft_behavior::press::Buttons`: `pub struct Buttons: u8 (flag set)`. The pointer buttons held. - `pub const fn of(button: PointerButton) -> Buttons`. The flag of one button. - `craft_behavior::press::MULTI_CLICK_TIME`: `pub const MULTI_CLICK_TIME: f64`. The longest gap between presses that still count as one multi-click, in seconds. -- `craft_behavior::press::MULTI_TAP_SLOP`: `pub const MULTI_TAP_SLOP: f32`. How far a finger of a multi-finger tap may move from where it landed, in points: fingers drift more than a +- `craft_behavior::press::MULTI_TAP_SLOP`: `pub const MULTI_TAP_SLOP: f32`. How far a finger of a multi-finger tap may move from where it landed, in points: fingers drift more than a pointer does while the others land. - `craft_behavior::press::MULTI_TAP_TIME`: `pub const MULTI_TAP_TIME: f64`. The longest the fingers of a multi-finger tap may stay down, in seconds. - `craft_behavior::press::MultiTap`: `pub struct MultiTap { pub fingers: u8, pub at: Pos2 }`. Two or more fingers came down and all lifted within [`MULTI_TAP_TIME`] without moving past [`MULTI_TAP_SLOP`]. - `pub const fn new(fingers: u8, at: Pos2) -> Self`. A tap of `fingers` around `at`. @@ -1533,7 +1536,7 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn delta(mut self, delta: Vec2) -> Self`. The pointer movement of the pass. - `pub const fn cancel(mut self, cancel: Option) -> Self`. A reason the captured press ends now. - `craft_behavior::press::PointerButton`: `pub enum PointerButton { Primary, Secondary, Middle, Extra1, Extra2 }`. A pointer button. -- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved { at: Pos2, sample: Option }, Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. The press lifecycle follows the primary button and the +- `craft_behavior::press::PointerEvent`: `pub enum PointerEvent { Moved { at: Pos2, sample: Option }, Pressed { button: PointerButton, pos: Pos2, time: f64, clicks: u32 }, Released { button: PointerButton, pos: Pos2 }, Gone }`. A button event of one pass, in the order it arrived. - `pub const fn moved(at: Pos2, sample: Option) -> Self`. The pointer moved to `at`, with the pen's reading for the move when the runtime has one. - `pub const fn pressed(pos: Pos2, time: f64, clicks: u32) -> Self`. The primary button going down at `pos`, `time`, as the `clicks`th press in a row. - `pub const fn released(pos: Pos2) -> Self`. The primary button going up at `pos`. @@ -1542,8 +1545,8 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `craft_behavior::press::PointerKind`: `pub enum PointerKind { Mouse, Pen, Touch }`. What kind of device the pointer is. - `craft_behavior::press::PointerSample`: `pub struct PointerSample { pub pressure: f32, pub tilt: [f32; 2], pub rotation: f32, pub eraser: bool, pub wheel: Option }`. Pressure and tilt of the current contact. - `pub const fn new(pressure: f32) -> Self`. A sample with no tilt or rotation. - - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value -- `craft_behavior::press::PressAside`: `pub struct PressAside { pub target: T, pub start: PressStart, pub pos: Pos2 }`. A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one + - `pub fn sanitized(self) -> Self`. The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value replaced by its neutral one. +- `craft_behavior::press::PressAside`: `pub struct PressAside { pub target: T, pub start: PressStart, pub pos: Pos2 }`. A secondary press made and released while a primary press was open ([`PressStep::aside`]). - `craft_behavior::press::PressCancel`: `pub enum PressCancel { Escape, FocusLost, Disabled, Removed, Host, Gesture }`. Why a captured press ended without a release. - `craft_behavior::press::PressMachine`: `pub struct PressMachine`. The press lifecycle of one root: the press winner it picked, kept until release or cancel. - `pub const fn new() -> Self`. A machine with no press. @@ -1551,17 +1554,17 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub fn button(&self) -> Option`. The button of the open press. - `pub fn dragging(&self) -> bool`. Whether a drag holds the pointer. - `pub fn start(&self) -> Option`. The press the open press began as. - - `pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart)`. Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next - - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may - - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed - - `pub fn hand_over(&mut self, target: T, sense: Sense) -> Option>`. Makes `target` the open press's target in the pass that reported `passes`, dragging from the same + - `pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart)`. Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input, each with a start that says it was handed over ([`PressStart::handed`]). + - `pub fn release_held(&self) -> bool`. Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may come to start it. + - `pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep`. Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed there; it returns `None` when no shape of this root takes the press. + - `pub fn hand_over(&mut self, target: T, sense: Sense) -> Option>`. Makes `target` the open press's target in the pass that reported `passes`, dragging from the same `PressStart`. - `craft_behavior::press::PressPhase`: `pub enum PressPhase { Idle, Hover, Down { start: PressStart }, Held { start: PressStart, pos: Pos2 }, DragStart { start: PressStart, pos: Pos2 }, Drag { start: PressStart, pos: Pos2, delta: Vec2 }, Release { start: PressStart, pos: Pos2, click: bool }, Cancel { start: PressStart, reason: PressCancel } }`. One part's press state in one pass. - `pub const fn is_press(&self) -> bool`. A press is in progress or just ended: not `Idle` or `Hover`. - `pub const fn start(&self) -> Option`. The press the phase belongs to. - `pub const fn button_down(&self) -> bool`. Whether the button is down: `Down`, `Held`, `DragStart` or `Drag`. - `pub const fn is_drag(&self) -> bool`. Whether the phase is a drag in progress. - `pub const fn is_click(&self) -> bool`. Whether the phase is a click: a release within slop. - - `pub fn mapped(self, point: impl Fn(Pos2) -> Pos2, delta: impl Fn(Vec2) -> Vec2) -> PressPhase`. The phase with its positions mapped by `point` and its drag delta by `delta`, for a part whose space + - `pub fn mapped(self, point: impl Fn(Pos2) -> Pos2, delta: impl Fn(Vec2) -> Vec2) -> PressPhase`. The phase with its positions mapped by `point` and its drag delta by `delta`, for a part whose space differs from the screen's. - `craft_behavior::press::PressPick`: `pub struct PressPick { pub target: T, pub sense: Sense, pub passed: bool }`. The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it. - `pub fn new(target: T, sense: Sense) -> Self`. `target`, sensing `sense`, takes the press. - `pub fn passed(mut self) -> Self`. The press's click went to a shape above that passes its drag to this target. @@ -1574,27 +1577,27 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver - `pub const fn mods(mut self, mods: Mods) -> Self`. The modifiers held. - `pub const fn sample(mut self, sample: Option) -> Self`. The pen sample of the contact. - `pub const fn captured(mut self, captured: bool) -> Self`. Whether a drag holds the pointer. - - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is + - `pub const fn double_pressed(&self) -> bool`. Whether the phase is the `Down` of the second press of a double click: true once, false while the button is held and for a first press. - `craft_behavior::press::PressStep`: `pub struct PressStep { pub target: Option, pub phase: Option, pub dragging: bool, pub activated: Option, pub passes: Option, pub aside: Option> }`. What one pass did to the press. -- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, +- `craft_behavior::press::count_clicks`: `pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32`. The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, mods)`: one more when it follows within [`MULTI_CLICK_TIME`] and `slop` of the previous one with the same modifiers, else 1. ## `craft_behavior::quantity` -`quantity::Reader`: the one number and unit parser (18.3): locale digits, unit spellings, expressions and +`quantity::Reader`: the one number and unit parser (18.3): locale digits, unit spellings, expressions and relative input. - `craft_behavior::quantity::Reader`: `pub struct Reader`. Reads numbers, expressions and unit quantities written in one locale. - `pub fn new() -> Self`. A reader for plain numbers written with `.` as the decimal separator. - - `pub fn bare(mut self, factor: f64) -> Self`. A number with no unit counts as `factor` of the reader's base unit (a picas field reads bare numbers as + - `pub fn bare(mut self, factor: f64) -> Self`. A number with no unit counts as `factor` of the reader's base unit (a picas field reads bare numbers as points: `1.0 / 12.0`). - `pub fn decimal(mut self, decimal: char) -> Self`. The decimal separator. - - `pub fn group(mut self, group: char) -> Self`. The digit-group separator, which the reader skips between digits. A comma or point after zero reads as a + - `pub fn group(mut self, group: char) -> Self`. The digit-group separator, which the reader skips between digits. - `pub fn unit(mut self, spelling: &str, factor: f64) -> Self`. A unit spelling (case-insensitive; letters or the symbols `%`, `°`) and its factor to the base unit. - `pub fn unit_tagged(mut self, spelling: &str, factor: f64, tag: u32) -> Self`. Like [`Reader::unit`], with a `tag` that [`Reader::read_tagged`] returns when the text names this spelling. - - `pub fn split_unit(mut self, spelling: &str, factor: f64, rest: f64, tag: u32) -> Self`. Like [`Reader::unit_tagged`], where a number written right after the spelling adds that many of `rest`: picas + - `pub fn split_unit(mut self, spelling: &str, factor: f64, rest: f64, tag: u32) -> Self`. Like [`Reader::unit_tagged`], where a number written right after the spelling adds that many of `rest`: picas and points read as `2p6`, two picas and six points. - `pub fn decimal_separator(&self) -> char`. The decimal separator the reader reads and writes. - `pub fn read(&self, text: &str, start: Option) -> Result`. The value of `text`. `start` is the value relative input applies to. - - `pub fn read_tagged(&self, text: &str, start: Option) -> Result<(f64, Option), NotAValue>`. The value of `text` and the tag of the unit its last quantity named (`None` for a bare number or an untagged - - `pub fn share(&self, text: &str) -> Option`. The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; -- `craft_behavior::quantity::is_unit_spelling`: `pub fn is_unit_spelling(spelling: &str) -> bool`. Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can + - `pub fn read_tagged(&self, text: &str, start: Option) -> Result<(f64, Option), NotAValue>`. The value of `text` and the tag of the unit its last quantity named (`None` for a bare number or an untagged unit). + - `pub fn share(&self, text: &str) -> Option`. The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; `None` for any other text. +- `craft_behavior::quantity::is_unit_spelling`: `pub fn is_unit_spelling(spelling: &str) -> bool`. Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can tell it from a number or an operator, or one `/` followed by them (`/in`, a count per inch). ## `craft_behavior::role_rule` @@ -1622,15 +1625,15 @@ Pointer values and the press lifecycle (8.1, 8.2), egui-free: the runtime conver Scroll positions and the range a scroll part shows. -- `craft_behavior::scroll::ScrollPos`: `pub struct ScrollPos { pub x: f64, pub y: f64 }`. Offsets and extents in content units. They are `f64` so a sheet of a million rows scrolls exactly. -- `craft_behavior::scroll::ScrollSpan`: `pub struct ScrollSpan { pub content: Range, pub visible: Range, pub resize_ends: bool }`. The range a scroll part shows. `content` is what the part's track stands for (it may start below zero +- `craft_behavior::scroll::ScrollPos`: `pub struct ScrollPos { pub x: f64, pub y: f64 }`. Offsets and extents in content units. +- `craft_behavior::scroll::ScrollSpan`: `pub struct ScrollSpan { pub content: Range, pub visible: Range, pub resize_ends: bool }`. The range a scroll part shows. `content` is what the part's track stands for (it may start below zero for overscroll), `visible` is the thumb. - `pub const fn new(content: Range, visible: Range) -> ScrollSpan`. A span whose thumb ends do not resize. - `pub const fn resize_ends(mut self, on: bool) -> ScrollSpan`. Lets the thumb ends change the visible length. - `craft_behavior::scroll::drag`: `pub fn drag(span: &ScrollSpan, track: f32, min_thumb: f32, delta: f32) -> Range`. The visible range after the thumb moved `delta` points along the track, kept inside the content range. -- `craft_behavior::scroll::jump`: `pub fn jump(span: &ScrollSpan, mv: NavMove) -> Option>`. The visible range after a navigation move that scrolls: a page up or down, or to the start or the end of the +- `craft_behavior::scroll::jump`: `pub fn jump(span: &ScrollSpan, mv: NavMove) -> Option>`. The visible range after a navigation move that scrolls: a page up or down, or to the start or the end of the content. `None` for any other move. - `craft_behavior::scroll::page`: `pub fn page(span: &ScrollSpan, toward_end: bool) -> Range`. The visible range one visible length further toward the end (or the start), kept inside the content range. - `craft_behavior::scroll::shifted`: `pub fn shifted(span: &ScrollSpan, shift: f64) -> Range`. Moves the visible range by `shift` content units, keeping it within the scrollable range. -- `craft_behavior::scroll::thumb`: `pub fn thumb(span: &ScrollSpan, track: f32, min_thumb: f32) -> (f32, f32)`. The thumb of `span` on a track `track` points long: its start along the track and its length, at least +- `craft_behavior::scroll::thumb`: `pub fn thumb(span: &ScrollSpan, track: f32, min_thumb: f32) -> (f32, f32)`. The thumb of `span` on a track `track` points long: its start along the track and its length, at least `min_thumb`. ## `craft_behavior::selection` @@ -1638,8 +1641,8 @@ Selection models: what a collection's selection holds and how a change applies t - `craft_behavior::selection::CellAt`: `pub struct CellAt { pub row: K, pub column: u32 }`. A cell: its row key and its column position. `CellAt` is a cell by position. - `pub fn new(row: K, column: u32) -> Self`. The cell of `row` at column position `column`. -- `craft_behavior::selection::CellRange`: `pub struct CellRange { pub first: K, pub last: K, pub columns: Range, pub lead_column: u32 }`. A rectangle of cells: the rows from `first` to `last` in the display order (either may come first), the column - - `pub fn new(first: K, last: K, columns: Range, lead_column: u32) -> Self`. The cells of the rows from `first` to `last` in `columns`, with the lead cell in `lead_column`. A range has at +- `craft_behavior::selection::CellRange`: `pub struct CellRange { pub first: K, pub last: K, pub columns: Range, pub lead_column: u32 }`. A rectangle of cells: the rows from `first` to `last` in the display order (either may come first), the column positions `columns` and the column of the lead cell. + - `pub fn new(first: K, last: K, columns: Range, lead_column: u32) -> Self`. The cells of the rows from `first` to `last` in `columns`, with the lead cell in `lead_column`. - `pub fn cells(from: CellAt, to: CellAt) -> Self`. The rectangle from the anchor cell `from` to the lead cell `to`, whichever way round they lie. - `pub fn cell(c: CellAt) -> Self`. One cell. - `pub fn contains(&self, c: CellAt) -> bool`. Whether `c` lies in the range. @@ -1647,28 +1650,28 @@ Selection models: what a collection's selection holds and how a change applies t - `pub fn column_span(&self) -> RangeInclusive`. The columns the range spans. - `pub fn intersects(&self, other: &Self) -> bool`. Whether the two ranges share a cell. - `pub fn union(&self, other: &Self) -> Self`. The smallest range holding both. - - `pub fn covering_merges(self, merges: &[CellRange]) -> Self`. The range grown until no merged cell (`merges`: each merge's range) crosses its edge, as Excel, InDesign and -- `craft_behavior::selection::CellSelection`: `pub struct CellSelection`. The cell selection of a sheet or table: ranges of cells, the active cell, the anchor and the cells toggled + - `pub fn covering_merges(self, merges: &[CellRange]) -> Self`. The range grown until no merged cell (`merges`: each merge's range) crosses its edge, as Excel, InDesign and Word grow a selection over a merged cell. +- `craft_behavior::selection::CellSelection`: `pub struct CellSelection`. The cell selection of a sheet or table: ranges of cells, the active cell, the anchor and the cells toggled against the ranges. - `pub fn ranges(&self) -> &[CellRange]`. The selected ranges, in the order they were added. - `pub fn current(&self) -> Option<&CellRange>`. The range Shift extends: the last one added, until Enter or Tab moves into another. - `pub fn active(&self) -> Option<&CellAt>`. The active cell: the one an entry goes into. - `pub fn anchor_cell(&self) -> Option<&CellAt>`. The cell of the current range that Shift extends from. - `pub fn toggled(&self) -> &[CellAt]`. The cells taken out of the ranges. - - `pub fn cell(c: CellAt) -> Self`. One cell, active and the anchor. A cell inside a merge selects the merge through `select` instead. + - `pub fn cell(c: CellAt) -> Self`. One cell, active and the anchor. - `pub fn range(r: CellRange) -> Self`. One range with its first row and first column active and the anchor. - - `pub fn from_ranges(ranges: Vec>, active: CellAt) -> Option`. Several ranges with `active` in the last one, which is the current range, and the anchor at `active`. `None` + - `pub fn from_ranges(ranges: Vec>, active: CellAt) -> Option`. Several ranges with `active` in the last one, which is the current range, and the anchor at `active`. `None` when `ranges` is empty or the last range's columns do not hold the column of `active`. - `pub fn bounds(&self, space: &CellSpace<'_, K>) -> Option>`. The smallest range holding every selected range, by position; `None` for the empty selection. - - `pub fn head(&self, space: &CellSpace<'_, K>) -> Option>`. The corner of the current range opposite the anchor: the end Shift+arrows move; `None` for the empty - - `pub fn select(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. A click, or an arrow's landing cell: `c` alone (its merged cell whole, the active cell at the merge's - - `pub fn select_range(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. A header click, a header drag or Select All: `range` alone, covered over merges unless it is whole lines - - `pub fn extend_to(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Shift+click and a drag: the current range runs from the anchor to `c`, covered over merges; the active cell - - `pub fn add(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on a cell no range holds: a new range at `c` (its merged cell whole) after the others; - - `pub fn add_range(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on a row or column header: `range` joins as a new range after the others, covered over - - `pub fn extend_current(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. Shift+click on a header and a drag over the headers: the current range becomes `range`, covered as - - `pub fn toggle(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on any cell: a cell a range holds is taken out of the selection (and joins it again - - `pub fn step(&mut self, direction: CellDirection, space: &CellSpace<'_, K>) -> bool`. An arrow: the selection collapses to the active cell's neighbour toward `direction` - - `pub fn change(&self) -> SelectionChange`. The change that reports this selection: [`SelectionChange::Cells`] when one range says it (the anchor cell and -- `craft_behavior::selection::RowAt`: `pub struct RowAt<'a, K> { pub key: &'a K, pub at: usize, pub order: &'a dyn DisplayOrder }`. A row as the item step reads it: its key, its position and the order that places other keys. A rectangle of + - `pub fn head(&self, space: &CellSpace<'_, K>) -> Option>`. The corner of the current range opposite the anchor: the end Shift+arrows move; `None` for the empty selection. + - `pub fn select(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. A click, or an arrow's landing cell: `c` alone (its merged cell whole, the active cell at the merge's top-left), active and the anchor. + - `pub fn select_range(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. A header click, a header drag or Select All: `range` alone, covered over merges unless it is whole lines ([`CellSpace::cover`]); the active cell and the anchor at its top-left. + - `pub fn extend_to(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Shift+click and a drag: the current range runs from the anchor to `c`, covered over merges; the active cell stays (Excel keeps it at the anchor). + - `pub fn add(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on a cell no range holds: a new range at `c` (its merged cell whole) after the others; `c` becomes active and the anchor. + - `pub fn add_range(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on a row or column header: `range` joins as a new range after the others, covered over merges unless it is whole lines ([`CellSpace::cover`]); the active cell and the anchor at its top-left. + - `pub fn extend_current(&mut self, range: CellRange, space: &CellSpace<'_, K>) -> bool`. Shift+click on a header and a drag over the headers: the current range becomes `range`, covered as [`select_range`] covers it; the other ranges, the active cell and the anchor stay. + - `pub fn toggle(&mut self, c: CellAt, space: &CellSpace<'_, K>) -> bool`. Cmd+click (Ctrl+click) on any cell: a cell a range holds is taken out of the selection (and joins it again when it was taken out); any other cell joins as a new range ([`add`]). + - `pub fn step(&mut self, direction: CellDirection, space: &CellSpace<'_, K>) -> bool`. An arrow: the selection collapses to the active cell's neighbour toward `direction` ([`CellSpace::neighbour`]), as [`select`] does. + - `pub fn change(&self) -> SelectionChange`. The change that reports this selection: [`SelectionChange::Cells`] when one range says it (the anchor cell and the active cell at its opposite corners), [`SelectionChange::Clear`] for the empty selection, else [`SelectionChange::CellSet`]. +- `craft_behavior::selection::RowAt`: `pub struct RowAt<'a, K> { pub key: &'a K, pub at: usize, pub order: &'a dyn DisplayOrder }`. A row as the item step reads it: its key, its position and the order that places other keys. - `pub fn new(key: &'a K, at: usize, order: &'a dyn DisplayOrder) -> Self`. The row `key` at position `at` of `order`. - `craft_behavior::selection::Selection`: `pub struct Selection { pub items: Vec, pub lead: Option, pub anchor: Option }`. A set of keys with a lead and an anchor. - `pub fn new(items: Vec, lead: Option, anchor: Option) -> Self`. A selection of `items` with `lead` and `anchor`. @@ -1682,17 +1685,17 @@ Selection models: what a collection's selection holds and how a change applies t - `fn apply(&mut self, change: SelectionChange)`. Applies a change. - `fn lead_column(&self) -> Option`. The column position of the lead cell; `None` for a model of rows. - `fn contains_cell(&self, row: RowAt<'_, K>, _column: u32) -> bool`. Whether the cell of row `row` in column position `column` is selected. - - `fn cells(&self) -> Option<&CellSelection>`. The cell rules of a model of cells, which the item step runs on a copy over the collection's `CellSpace`; the - - `fn placed(&self, order: &dyn DisplayOrder) -> PlacedSelection`. The selection by position in `order`, placed once so that the reads of a pass scan no keys. The default + - `fn cells(&self) -> Option<&CellSelection>`. The cell rules of a model of cells, which the item step runs on a copy over the collection's `CellSpace`; the result goes back through [`apply`]. `None` for a model of rows. + - `fn placed(&self, order: &dyn DisplayOrder) -> PlacedSelection`. The selection by position in `order`, placed once so that the reads of a pass scan no keys. - `craft_behavior::selection::CellAdvance`: `pub enum CellAdvance { Enter, Tab }`. Which key moves the active cell after an entry: Enter goes down the rows, Tab along a row. -- `craft_behavior::selection::CellDirection`: `pub enum CellDirection { Up, Down, Left, Right }`. A move of one cell. Logical: in a right-to-left sheet the widget maps the Left arrow to -- `craft_behavior::selection::PlacedSelection`: `pub struct PlacedSelection`. The selected cells by position in one display order: the rows and columns of each range, and the cells taken out +- `craft_behavior::selection::CellDirection`: `pub enum CellDirection { Up, Down, Left, Right }`. A move of one cell. +- `craft_behavior::selection::PlacedSelection`: `pub struct PlacedSelection`. The selected cells by position in one display order: the rows and columns of each range, and the cells taken out of them. - `pub fn of_rows(spans: impl IntoIterator>) -> Self`. The selected rows `spans`, every column of each. - `pub fn of_cells(ranges: Vec<(Range, Range)>, mut removed: Vec<(usize, u32)>) -> Self`. The ranges `ranges` (row positions, column positions) without the cells `removed`. - `pub fn holds_row(&self, at: usize) -> bool`. Whether the row at position `at` has a selected cell. - `pub fn holds_cell(&self, at: usize, column: u32) -> bool`. Whether the cell at row position `at` and column position `column` is selected. - `pub fn rows(&self) -> Vec`. The positions of the rows that have a selected cell, ascending. -- `craft_behavior::selection::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and +- `craft_behavior::selection::Positions`: `pub struct Positions`. The display order of a grid whose row keys are their positions (a sheet, a document table): `key(at) == at`, and `index_of` answers without a scan. - `pub const fn new(rows: u32) -> Self`. The order of `rows` rows. ## `craft_behavior::sense` @@ -1708,7 +1711,7 @@ The library's sense set, for a root or a part. `Proposal`, `Metrics` and `ControlMetrics`: what a measure call is asked and what a style gives it to add. -- `craft_behavior::sizing::ControlMetrics`: `pub struct ControlMetrics { pub height: f32, pub icon: f32, pub pad_x: f32, pub gap: f32, pub field: f32, pub number: f32 }`. The sizes a control takes from its `ControlSize`: height, icon side, horizontal padding, gap and the widths of a +- `craft_behavior::sizing::ControlMetrics`: `pub struct ControlMetrics { pub height: f32, pub icon: f32, pub pad_x: f32, pub gap: f32, pub field: f32, pub number: f32 }`. The sizes a control takes from its `ControlSize`: height, icon side, horizontal padding, gap and the widths of a field and a number field. - `pub fn at(size: ControlSize, height: &BySize, icon: &BySize, pad_x: &BySize, gap: &BySize, field: &BySize, number: &BySize,) -> Self`. The entries of the six tables at `size`. - `pub const fn metrics(&self) -> Metrics`. The `Metrics` of a control of this height: horizontal padding, the height as the least height, the gap. - `craft_behavior::sizing::Metrics`: `pub struct Metrics { pub padding: Insets, pub min_size: Vec2, pub max_width: Option, pub gap: f32, pub min_text: f32, pub ideal_width: f32, pub least_width: Option }`. What the pipeline adds around a component's measured content. @@ -1741,21 +1744,21 @@ The library's sense set, for a root or a part. - `pub fn codec(&self) -> &C`. The codec. - `pub fn shown(&self, run: &EditRun, value: &C::Value) -> String`. The text to show: the draft, else the value's text. - `pub fn open(&self, run: &mut EditRun, start: &C::Value)`. Opens the run on `start` when none is open. - - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> (Typed, bool)`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. The `bool` - - `pub fn rewrite(&self, run: &mut EditRun) -> bool`. Replaces the draft with the codec's normal form of the value it reads (`Codec::normalise`, as a commit + - `pub fn edit(&self, run: &mut EditRun, start: &C::Value, text: &str) -> (Typed, bool)`. The draft is now `text`: characters the codec refuses and characters past the limit drop out. + - `pub fn rewrite(&self, run: &mut EditRun) -> bool`. Replaces the draft with the codec's normal form of the value it reads (`Codec::normalise`, as a commit shows it); whether it read one. - `pub fn commit(&self, run: &mut EditRun) -> Ended`. Commits the draft: a value closes the run, a draft that is no value keeps it open. - - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, ParseNote)`. [`commit`](Self::commit), with the note of the committed text (`Codec::parse_tagged`); the default note for a + - `pub fn commit_tagged(&self, run: &mut EditRun) -> (Ended, ParseNote)`. [`commit`], with the note of the committed text (`Codec::parse_tagged`); the default note for a rejected or idle run. - `pub fn cancel(&self, run: &mut EditRun) -> Option`. Closes the run without a commit and returns the value from before it; `None` when no run was open. - - `pub fn escape(&self, run: &mut EditRun) -> Escaped`. Applies the escape rule. A codec that refuses the empty text keeps the cleared draft open under + - `pub fn escape(&self, run: &mut EditRun) -> Escaped`. Applies the escape rule. ## `craft_behavior::value` -The value core of chapter 10: the bound every value type meets, `Mixed`, edit events and the list a pass's events +The value core of chapter 10: the bound every value type meets, `Mixed`, edit events and the list a pass's events fold into. - `craft_behavior::value::Applied`: `pub enum Applied { Changed, Unchanged, Restored }`. What applying an event did to a value. - `craft_behavior::value::CancelReason`: `pub enum CancelReason { Refused, Dismissed, Escape, Blur, Removed, HostChanged, UndoDuringGesture, Unchanged }`. Why a gesture ended without a commit. - - `pub const fn document_moved(self) -> bool`. The document changed under the gesture, so the gesture's own edits stay and a revert would also take back the -- `craft_behavior::value::EditEvent`: `pub enum EditEvent { Begin { id: GestureId, before: Mixed, label: Arc, doc_key: Option }, Update { id: GestureId, value: T }, Commit { id: GestureId, before: Mixed, after: T }, Cancel { id: GestureId, reason: CancelReason, before: Option> }, Set { before: Mixed, after: T, label: Arc, doc_key: Option } }`. One step of an edit. A pass raises several; [`EditEvents`] holds them in order. + - `pub const fn document_moved(self) -> bool`. The document changed under the gesture, so the gesture's own edits stay and a revert would also take back the change. +- `craft_behavior::value::EditEvent`: `pub enum EditEvent { Begin { id: GestureId, before: Mixed, label: Arc, doc_key: Option }, Update { id: GestureId, value: T }, Commit { id: GestureId, before: Mixed, after: T }, Cancel { id: GestureId, reason: CancelReason, before: Option> }, Set { before: Mixed, after: T, label: Arc, doc_key: Option } }`. One step of an edit. - `pub fn begin(id: GestureId, before: Mixed, label: Arc, doc_key: Option) -> Self`. A gesture began. - `pub fn update(id: GestureId, value: T) -> Self`. A proposed value of the running gesture. - `pub fn commit(id: GestureId, before: Mixed, after: T) -> Self`. The gesture committed `after`. @@ -1767,9 +1770,9 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn value(&self) -> Option<&T>`. The value the event carries: a proposal, a commit or a set. - `pub fn landed(&self) -> Option<&T>`. The value the binding holds after the event: the carried value, or the value a cancel restores. - `pub fn phase(&self) -> Option`. Where the gesture stands after this event; a `Set` is not a gesture. - - `pub fn apply(&self, v: &mut T) -> Applied`. Applies the event to `v`: a proposal, commit or set writes its value, a cancel restores the value from before + - `pub fn apply(&self, v: &mut T) -> Applied`. Applies the event to `v`: a proposal, commit or set writes its value, a cancel restores the value from before the gesture. - `pub fn apply_mixed(&self, v: &mut Mixed) -> Applied`. Applies the event to a value that may be mixed: the written value is a concrete one. -- `craft_behavior::value::EditEvents`: `pub struct EditEvents`. The edit events of one pass, in order. `push` folds what loses nothing, within one gesture: a later `Update`, +- `craft_behavior::value::EditEvents`: `pub struct EditEvents`. The edit events of one pass, in order. `push` folds what loses nothing, within one gesture: a later `Update`, `Commit` or `Cancel` replaces the `Update` before it (it carries the value on), `Begin` then `Commit` is one `Set`, and `Begin` then `Cancel` is nothing. - `pub fn committed(&self) -> Option<&T>`. The value of the last `Commit` or `Set` in the events; `None` if there is none. - `pub fn new() -> Self`. No events. - `pub fn push(&mut self, event: EditEvent)`. Adds the next event of the pass, folding it with the one before when that loses nothing. @@ -1785,13 +1788,13 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub fn map(self, f: impl Fn(T) -> U) -> EditEvents`. Maps the carried values of every event. - `pub fn filter_map(self, f: impl Fn(T) -> Option) -> EditEvents`. Maps the carried values of every event, dropping the events `f` has no value for. - `craft_behavior::value::EditPolicy`: `pub enum EditPolicy { WriteThrough, OnCommit }`. When a write-through source is written: on every proposal of a gesture or only on its commit. -- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool, pub wheel: bool, pub note: Option }`. The running gesture of a value component, kept in shown memory under the component. Plain data; the pipeline +- `craft_behavior::value::Gesture`: `pub struct Gesture { pub id: GestureId, pub before: Option>, pub proposal: Option, pub last_given: Option, pub emitted: Option, pub reported: Option, pub dead: bool, pub cancel_seen: u64, pub watched: bool, pub wheel: bool, pub note: Option }`. The running gesture of a value component, kept in shown memory under the component. - `pub fn ended(&self, dead: bool) -> Gesture`. The gesture after it ended: no value, the id kept, and `dead` while the press that carried it is held. - `pub fn is_running(&self) -> bool`. A gesture is running. - `craft_behavior::value::GestureId`: `pub struct GestureId(pub u64)`. Names a gesture; ids grow in the order the gestures begin. - `pub const fn new(n: u64) -> GestureId`. The id numbered `n`. - `pub const fn next(self) -> GestureId`. The id of the gesture after this one. -- `craft_behavior::value::GestureNote`: `pub struct GestureNote`. A typed note a component sets on its running gesture for readers outside its pass, such as the guide a guides +- `craft_behavior::value::GestureNote`: `pub struct GestureNote`. A typed note a component sets on its running gesture for readers outside its pass, such as the guide a guides drag moves. - `pub fn new(note: N) -> Self`. A note holding `note`. - `pub fn get(&self) -> Option<&N>`. The note, when it is an `N`. - `craft_behavior::value::GesturePhase`: `pub enum GesturePhase { Begin, Update, Commit, Cancel }`. Where a gesture stands in one pass. @@ -1800,42 +1803,46 @@ The value core of chapter 10: the bound every value type meets, `Mixed`, edit ev - `pub const fn or<'a>(&'a self, start: &'a T) -> &'a T`. The shared value, or `start` while the items differ. - `pub fn each(values: [T; N]) -> [Mixed; N]`. Every part of `values` as a shared value: the per-part form of a composite value no part of which differs. - `pub fn parts(self) -> [Mixed; N]`. The per-part form of a composite value: a whole `Mixed` binding means every part differs. -- `craft_behavior::value::Preview`: `pub enum Preview { Unchanged, Shows(V), Ended }`. What one pass did to a live preview a component shows beside its value (the family under the pointer in a font +- `craft_behavior::value::Preview`: `pub enum Preview { Unchanged, Shows(V), Ended }`. What one pass did to a live preview a component shows beside its value (the family under the pointer in a font list): only the pass that starts, moves or ends the preview reports it, so a second control that previews nothing never ends the preview of another. - `pub fn map(self, f: impl FnOnce(V) -> W) -> Preview`. The same change over the value `f` makes of the shown one. - `craft_behavior::value::Validity`: `pub enum Validity { Ok, Fix(T), Warn(M), Refuse(M), Error(M) }`. What a check says about a value. `M` is the message type: craft-ui exports the alias with its own `Message`. - `craft_behavior::value::Value`: `pub trait Value: Clone + PartialEq + Send + Sync + 'static`. What a bound value must be: cloneable, comparable and shareable across threads. - `craft_behavior::value::same_in_f32`: `pub fn same_in_f32(proposed: f64, host: f64) -> bool`. Whether `host`, a number an app wrote back, is the proposal `proposed` as a host that keeps it in `f32` stores it: -- `craft_behavior::value::same_in_f32_at`: `pub fn same_in_f32_at(proposed: f64, host: f64, magnitude: f64) -> bool`. [`same_in_f32`] for a number the host computes in `f32` from terms as large as `magnitude`: a corner of a box it +- `craft_behavior::value::same_in_f32_at`: `pub fn same_in_f32_at(proposed: f64, host: f64, magnitude: f64) -> bool`. [`same_in_f32`] for a number the host computes in `f32` from terms as large as `magnitude`: a corner of a box it transforms lies near zero while the terms it sums do not, and holds their precision, not its own. ## `craft_behavior::value_drag` `ValueDrag`: the drag maths of sliders, dials, scrubbing number fields and rulers, written once (8.7). -- `craft_behavior::value_drag::DragWarp`: `pub struct DragWarp`. The pointer warps of one drag. The OS reports the pointer at its new place a frame after a warp, so a warp - - `pub fn shift(&mut self, pos: Pos2) -> Vec2`. The total warp so far, given the pointer `pos` of this pass. Pass it to [`ValueDrag::value_shifted`]. +- `craft_behavior::value_drag::DragModifier`: `pub enum DragModifier { Alt, Shift, Control, Command }`. A modifier that changes continuous pointer-drag sensitivity. +- `craft_behavior::value_drag::DragModifiers`: `pub struct DragModifiers`. The pointer-only fine/coarse bindings of a continuous drag. + - `pub const fn new(fine: Option, coarse: Option) -> Self`. Selects the fine and coarse bindings; `None` disables that binding. +- `craft_behavior::value_drag::DragWarp`: `pub struct DragWarp`. The pointer warps of one drag. + - `pub fn shift(&mut self, pos: Pos2) -> Vec2`. The total warp so far, given the pointer `pos` of this pass. - `pub const fn pending(&self) -> bool`. Whether a warp waits for the pointer to show up at its new place: no second warp starts before it does. - `pub fn sent(&mut self, from: Pos2, by: Vec2)`. Records that the pointer at `from` was warped by `by`. -- `craft_behavior::value_drag::ValueDrag`: `pub struct ValueDrag`. Turns a press into a value. Components set it as data and call [`ValueDrag::value`] in `update`. +- `craft_behavior::value_drag::ValueDrag`: `pub struct ValueDrag`. Turns a press into a value. - `pub fn absolute(track: Range, range: RangeInclusive) -> Self`. The value follows the pointer on `track`: `range.start()` at `track.start`, `range.end()` at `track.end`. - - `pub fn relative(rate: f64, range: RangeInclusive) -> Self`. The value changes by `rate` units per point of travel from the press. Vertical travel upwards increases it. + - `pub fn relative(rate: f64, range: RangeInclusive) -> Self`. The value changes by `rate` units per point of travel from the press. - `pub const fn axis(mut self, axis: Axis) -> Self`. The axis the pointer travels on; the default is horizontal. - `pub const fn fine(mut self, factor: f64) -> Self`. The factor Alt (Option) applies to travel. - - `pub const fn coarse(mut self, factor: f64) -> Self`. The factor Shift applies to travel. A drag sets none by default: on an absolute drag such as a slider's a - - `pub const fn warp(mut self, on: bool) -> Self`. Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end + - `pub const fn coarse(mut self, factor: f64) -> Self`. The factor Shift applies to travel. + - `pub const fn modifiers(mut self, modifiers: DragModifiers) -> Self`. Selects pointer fine/coarse bindings without changing keyboard or wheel behavior. + - `pub const fn warp(mut self, on: bool) -> Self`. Warps the pointer to the other side of the window when the drag reaches an edge, so the drag has no end ([`ValueDrag::warp_by`], [`DragWarp`]). - `pub const fn hide_cursor(mut self, on: bool) -> Self`. Hides the pointer while the drag runs, as a scrub does that warps the pointer. - `pub const fn warps(&self) -> bool`. Whether the pointer warps at a window edge. - - `pub fn warp_by(&self, pos: Pos2, bounds: Rect) -> Option`. How far to move the pointer when the drag at `pos` has reached an edge of `bounds` on the drag's axis: to - - `pub fn value(&self, start: f64, press: &PressState, rtl: bool) -> Option`. The value the press gives, `None` while it gives none: before a drag starts, and after a cancel. `start` is the - - `pub fn value_shifted(&self, start: f64, press: &PressState, rtl: bool, shift: Vec2) -> Option`. [`ValueDrag::value`] for a pointer that warped by `shift` in total ([`DragWarp::shift`]): the pointer - - `pub fn at(&self, pos: Pos2, rtl: bool) -> Option`. The value at `pos` on an absolute drag's track, in the range: what a press there sets. `None` for a relative -- `craft_behavior::value_drag::wrap_value`: `pub fn wrap_value(value: f64, low: f64, period: f64) -> f64`. `value` moved by whole periods into `low..low + period`, as a wrapping slider or dial holds it. A period that is + - `pub fn warp_by(&self, pos: Pos2, bounds: Rect) -> Option`. How far to move the pointer when the drag at `pos` has reached an edge of `bounds` on the drag's axis: to the far side, inside the zone that warps. `None` away from the edges and for a drag that does not warp. + - `pub fn value(&self, start: f64, press: &PressState, rtl: bool) -> Option`. The value the press gives, `None` while it gives none: before a drag starts, and after a cancel. `start` is the value when the drag began. + - `pub fn value_shifted(&self, start: f64, press: &PressState, rtl: bool, shift: Vec2) -> Option`. [`ValueDrag::value`] for a pointer that warped by `shift` in total ([`DragWarp::shift`]): the pointer counts as where it would be without the warps, so the value stays continuous across them. + - `pub fn at(&self, pos: Pos2, rtl: bool) -> Option`. The value at `pos` on an absolute drag's track, in the range: what a press there sets. `None` for a relative drag, whose value comes from travel, not from a place. +- `craft_behavior::value_drag::wrap_value`: `pub fn wrap_value(value: f64, low: f64, period: f64) -> f64`. `value` moved by whole periods into `low..low + period`, as a wrapping slider or dial holds it. ## `craft_behavior::wheel` Wheel gesture values, as craft-behavior's copy of egui's types so the wheel split is egui-free. - `craft_behavior::wheel::GESTURE_GAP`: `pub const GESTURE_GAP: f64`. The seconds between wheel events that still belong to one gesture. -- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. +- `craft_behavior::wheel::Wheel`: `pub struct Wheel { pub scroll: Vec2, pub lines: Vec2, pub zoom: f32, pub zoom_lines: Vec2, pub zoom_gathered: Vec2, pub mods: Mods, pub unit: WheelUnit, pub phase: WheelPhase, pub source: WheelSource, pub at: Option, pub zooms: bool, pub touch_zoom: f32, pub rotation: f32, pub touch_rotation: f32, pub touch_pan: Vec2, pub gathered: Vec2, pub moved: bool, pub held: Mods, pub modal: bool }`. One wheel event, or the sum of one pass's, as a taker reads it with `take_wheel`. - `pub const fn new(scroll: Vec2, mods: Mods, unit: WheelUnit, phase: WheelPhase) -> Self`. A scroll of `scroll` points with no zoom. - `pub const fn zoom(mut self, zoom: f32) -> Self`. The same gesture with zoom factor `zoom`. - `pub const fn zoom_lines(mut self, lines: Vec2) -> Self`. The same gesture with `lines` wheel lines of motion that zoom (`Wheel::zoom_lines`). @@ -1846,28 +1853,28 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn source(mut self, source: WheelSource) -> Self`. The same gesture from `source`. - `pub const fn at(mut self, at: Pos2) -> Self`. The same gesture with the pointer at `at`. - `craft_behavior::wheel::WheelEase`: `pub struct WheelEase`. The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. - - `pub fn feed(&mut self, pan: Vec2, now: f64)`. Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart + - `pub fn feed(&mut self, pan: Vec2, now: f64)`. Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart accelerates it, a reversal or 0.3 s idle resets the burst. - `pub fn cancel_axis(&mut self, x: bool, y: bool)`. Drops the owed motion on the axes marked. - `pub fn step(&mut self, now: f64) -> Vec2`. The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass. - `pub fn owes(&self) -> bool`. Whether motion is still owed. - `craft_behavior::wheel::WheelFocus`: `pub struct WheelFocus { pub taker: Option, pub app_field: bool, pub by_position: bool }`. Who holds key focus, as the split reads it. - `pub const fn new(taker: Option) -> Self`. Focus on `taker`, or on nothing that takes the wheel. - `pub const fn app_field(mut self, on: bool) -> Self`. The same focus, in a text field the app drew itself when `on`. - - `pub const fn by_position(mut self, on: bool) -> Self`. The same focus, with the pointer over a layer that takes the wheel by position when `on` -- `craft_behavior::wheel::WheelGesture`: `pub struct WheelGesture { pub owner: Option, pub last: f64 }`. A wheel gesture: events closer than [`GESTURE_GAP`] seconds, or inside one device phase. `owner` is `None` while - - `pub fn runs(&self, now: f64) -> bool`. Whether an event at `now` continues the gesture: one is open, the device has not ended it and the gap since - - `pub fn end(&mut self, now: f64) -> Option`. Closes the gesture once `now - last` reaches [`GESTURE_GAP`], or at once after a device end, and returns the + - `pub const fn by_position(mut self, on: bool) -> Self`. The same focus, with the pointer over a layer that takes the wheel by position when `on` ([`by_position`]). +- `craft_behavior::wheel::WheelGesture`: `pub struct WheelGesture { pub owner: Option, pub last: f64 }`. A wheel gesture: events closer than [`GESTURE_GAP`] seconds, or inside one device phase. `owner` is `None` while no taker took it. [`split`] keeps it across events; its caller calls [`WheelGesture::end`] before each split. + - `pub fn runs(&self, now: f64) -> bool`. Whether an event at `now` continues the gesture: one is open, the device has not ended it and the gap since its last event is shorter than [`GESTURE_GAP`]. + - `pub fn end(&mut self, now: f64) -> Option`. Closes the gesture once `now - last` reaches [`GESTURE_GAP`], or at once after a device end, and returns the owner it had. - `craft_behavior::wheel::WheelNotch`: `pub enum WheelNotch { Points(f32), ViewShare(f32) }`. The distance one wheel line scrolls a taker. - `pub const DEFAULT: WheelNotch`. The distance of a taker that states none. - `pub fn points(self, extent: f32) -> f32`. The notch in points, for a taker whose view is `extent` points along the axis. - `craft_behavior::wheel::WheelPhase`: `pub enum WheelPhase { Start, Move, End, Cancel }`. A wheel gesture's phase. -- `craft_behavior::wheel::WheelRoom`: `pub struct WheelRoom { pub positive: Vec2, pub negative: Vec2 }`. The scroll left in a region, in points of wheel scroll: `positive` is what a wheel with positive `scroll` can +- `craft_behavior::wheel::WheelRoom`: `pub struct WheelRoom { pub positive: Vec2, pub negative: Vec2 }`. The scroll left in a region, in points of wheel scroll: `positive` is what a wheel with positive `scroll` can still move, `negative` the same for negative `scroll`. - `pub const fn new(positive: Vec2, negative: Vec2) -> Self`. A room of `positive` and `negative` points. - `craft_behavior::wheel::WheelSource`: `pub enum WheelSource { Unknown, Wheel, Trackpad, Momentum }`. The device a wheel event came from, where the system says (egui reports it on macOS only). - `pub const fn fingers(self) -> bool`. Whether fingers drive the scroll: a trackpad or its momentum. -- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass. +- `craft_behavior::wheel::WheelTaker`: `pub struct WheelTaker { pub owner: O, pub rect: Rect, pub horizontal: bool, pub vertical: bool, pub zoom: bool, pub gated: bool, pub directional: bool, pub scrolls: bool, pub notch: WheelNotch, pub room: Option, pub zooms_view: bool, pub field: bool, pub value: bool }`. A component that takes wheel input, as registered last pass. - `pub const fn new(owner: O, rect: Rect) -> Self`. A taker over `rect` that takes no axis yet. - - `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option`. The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll + - `pub fn for_sense(owner: O, rect: Rect, sense: Sense) -> Option`. The taker a shape with `sense` registers, `None` when `sense` has no wheel bit: `WHEEL` takes both scroll axes and zoom; `WHEEL_X`, `WHEEL_Y` and `WHEEL_ZOOM` take one share each and combine; `WHEEL_ZOOMS_VIEW` makes a zoom zone; `WHEEL_Y_FOCUSED` takes the vertical share and makes the taker gated, so every axis it takes waits for focus or arming. - `pub const fn zooms_view(mut self, on: bool) -> Self`. Whether it is a zoom zone (`WheelTaker::zooms_view`). - `pub const fn field(mut self, on: bool) -> Self`. Whether it is a value field (`WheelTaker::field`). - `pub const fn value(mut self, on: bool) -> Self`. Whether it is a value control (`WheelTaker::value`). @@ -1875,18 +1882,19 @@ Wheel gesture values, as craft-behavior's copy of egui's types so the wheel spli - `pub const fn vertical(mut self, on: bool) -> Self`. Whether it takes vertical scroll. - `pub const fn zoom(mut self, on: bool) -> Self`. Whether it takes zoom. - `pub const fn gated(mut self, on: bool) -> Self`. Whether every axis needs focus or arming. + - `pub const fn directional(mut self, on: bool) -> Self`. Opts a value control into directional editing, without changing the default focus gate. - `pub const fn notch(mut self, notch: WheelNotch) -> Self`. The distance of one wheel line. - `pub const fn scrolls(mut self, on: bool) -> Self`. The taker is a scroll region (`WheelTaker::scrolls`). - `pub const fn room(mut self, room: WheelRoom) -> Self`. The taker's scroll room: it passes a wheel on an axis it has no room left for to the next enclosing taker. - - `pub fn points(&self, scroll: Vec2, unit: WheelUnit) -> Vec2`. `scroll`, given in `unit`s of the device, as points of this taker's view: a line is one notch, a page is + - `pub fn points(&self, scroll: Vec2, unit: WheelUnit) -> Vec2`. `scroll`, given in `unit`s of the device, as points of this taker's view: a line is one notch, a page is the view. - `craft_behavior::wheel::WheelUnit`: `pub enum WheelUnit { Point, Line, Page }`. How far one wheel event reaches. -- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option, gesture: &mut WheelGesture, now: f64,) -> Vec<(O, Wheel)>`. The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes +- `craft_behavior::wheel::split`: `pub fn split(takers: &[WheelTaker], at: Pos2, wheel: Wheel, focus: WheelFocus, armed: Option, gesture: &mut WheelGesture, now: f64,) -> Vec<(O, Wheel)>`. The split rule. ## `craft_ui` -The base of the craft UI library: runtime, style, fonts, primitives, the component contract, layout and the test +The base of the craft UI library: runtime, style, fonts, primitives, the component contract, layout and the test kit (layers 2 to 4). -- `craft_ui::bind_tracked!`: `macro_rules! bind_tracked`. Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` +- `craft_ui::bind_tracked!`: `macro_rules! bind_tracked`. Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` gives one [`Bind`], `bind_tracked!(doc => title, style.size)` a tuple with one per field path (field names and tuple indices only), and `bind_tracked!(name)` one binding to the whole value. - `craft_ui::stays!`: `macro_rules! stays`. Types with no place: they stay as they are at any place. - `craft_ui::InstallError`: re-export of `craft_ui::runtime::install::InstallError`. - `craft_ui::InstallSpec`: re-export of `craft_ui::runtime::install::InstallSpec`. @@ -1904,111 +1912,111 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `type Selection`. The selection model. - `type Item`. The item component. - `type ItemEvent`. Events an item reports. - - `const MEMBERS: bool`. Whether the items are members of the collection's run instead of runs of their own. Each visible item is then + - `const MEMBERS: bool`. Whether the items are members of the collection's run instead of runs of their own. - `fn items(&self) -> &CollectionProps`. Plain data: selection mode, reorder, rename, columns. - `fn shows_row_focus(&self) -> bool`. Whether keyboard focus shows a ring on the lead row, or on a populated rows viewport with no visible lead. - `fn selection(&mut self) -> Option>`. The selection binding; `None` keeps it in session memory. - - `fn column_layout(&mut self) -> Option>`. The column arrangement binding; `None` keeps it in the header's own memory. The header starts each pass from - - `fn cell_space<'s>(&'s self, space: CellSpace<'s, Self::Key>) -> CellSpace<'s, Self::Key>`. The grid a model of cells selects in (17.7). The item step passes the grid it knows, the source's rows and the + - `fn column_layout(&mut self) -> Option>`. The column arrangement binding; `None` keeps it in the header's own memory. + - `fn cell_space<'s>(&'s self, space: CellSpace<'s, Self::Key>) -> CellSpace<'s, Self::Key>`. The grid a model of cells selects in (17.7). - `fn reveal(&self) -> Option<&Self::Key>`. A one-shot request to scroll an item into view. - `fn item_layout(&self, source: &dyn ItemSource, width: f32, cx: &StyleCx<'_>) -> Self::ItemLayout`. The layout of `source` at `width`. - - `fn item_layout_from(&self, _previous: Option, source: &dyn ItemSource, width: f32, _item: Option, cx: &StyleCx<'_>,) -> Self::ItemLayout`. The layout of `source` at `width`, given the layout of the last pass. An implementor may reuse `previous` - - `fn measures_items(&self) -> bool`. Whether the layout sizes its items from their own measure: the items step measures every item at its ideal + - `fn item_layout_from(&self, _previous: Option, source: &dyn ItemSource, width: f32, _item: Option, cx: &StyleCx<'_>,) -> Self::ItemLayout`. The layout of `source` at `width`, given the layout of the last pass. + - `fn measures_items(&self) -> bool`. Whether the layout sizes its items from their own measure: the items step measures every item at its ideal size and hands the largest to `item_layout_from` and `ideal_width`. - `fn dress_inputs(&self) -> u64`. What `dress` reads of the collection, hashed: a kept measure of the items serves only while it is the same. - - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of - - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env, _kept: Option<&Self::Key>,) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. `kept` is the - - `fn rings_lead(&self) -> bool`. Whether the focus ring goes around the lead item while the collection has keyboard-visible focus: the item step - - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this + - `fn ideal_width(&self, _item: Option, _rows: usize, _cx: &StyleCx<'_>) -> f32`. The width the collection asks for when it takes its width from its content, over its widest row: a grid of cards asks for its declared number of columns. 0 asks for nothing. `item` is as `item_layout_from` gets it; `rows` is the number of rows the source holds, for a collection whose rows stand side by side. + - `fn filtered<'s>(&self, _source: &'s dyn ItemSource, _env: &crate::runtime::env::Env, _kept: Option<&Self::Key>,) -> Option + 's>>`. A view of `source` for this pass, such as the rows a filter keeps; `None` shows `source` as it is. `kept` is the item whose rename runs: the view keeps it whether or not it matches, so it is named in place. + - `fn rings_lead(&self) -> bool`. Whether the focus ring goes around the lead item while the collection has keyboard-visible focus: the item step gives the ring the lead's rect (`Cx::focus_shape`), or the collection's own rect while it has no lead or its lead is not shown. + - `fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r>`. Adjusts the item the closure built for a row, from the row's state. - `fn rename_editor(&mut self, _ui: &mut Ui, _draft: Bind<'_, String>, _label: Rect, _name: &str) -> Option>`. The rename editor at `label`: the label rect the renaming item reports (`ItemOutput::label_rect`), else its row. - - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` - - `fn header_cell(&mut self, _ui: &mut PaintUi<'_>, _column: &ColumnKey, _key: HostedKey, _rect: Rect)`. Hosts a component in the header cell of `column`, in `rect`, measured and shown under `key` (the column's index + - `fn hosts_header(&self, _column: &ColumnKey) -> bool`. Whether the collection hosts a component in the header cell of `column`: the header then calls `header_cell` for it and paints no label. + - `fn header_cell(&mut self, _ui: &mut PaintUi<'_>, _column: &ColumnKey, _key: HostedKey, _rect: Rect)`. Hosts a component in the header cell of `column`, in `rect`, measured and shown under `key` (the column's index among the declared columns, so a move or a hide keeps it). - `fn rename_draft(&self, _key: &Self::Key) -> Option`. The text the rename field of the item `key` opens with; `None` for the item's own text. - `fn can_rename(&self, _key: &Self::Key) -> bool`. Whether the item `key` may be renamed; a rename request on another item does nothing. - `fn can_drag(&self, _key: &Self::Key) -> bool`. Whether the item `key` may be dragged (reordered, moved in a free layout, or dragged to another collection). - - `fn accepts(&self, _drag: &ListDrag, _over: Option<&Self::Key>, _insert: usize) -> bool`. Whether the collection's own dragged items may land before `insert` (a position of the display order, `over` is - - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's - - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as - - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): the items step reports - - `fn zoom_anchor(&self, _wheel: Option) -> Option`. The point whose row stays in place across a zoom step this collection takes in the current pass, in screen - - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. The - - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. The default shows `CollectionProps::empty`. + - `fn accepts(&self, _drag: &ListDrag, _over: Option<&Self::Key>, _insert: usize) -> bool`. Whether the collection's own dragged items may land before `insert` (a position of the display order, `over` is the item the pointer is on, none over an empty collection). + - `fn drops(&self) -> &[DropKind<'_, Self::Key>]`. What the collection takes from drags that did not start in it, in order: the first kind that takes the drag's payload at the place under the pointer gets the drop, reported as `CollectionEvent::Dropped`. + - `fn edge_press(&self) -> Option<&EdgePress<'_, Self::Key>>`. The press on the line between two adjacent rows the collection takes, reported as `CollectionEvent::EdgePressed`; none by default, and without one the rows take every press as they do. + - `fn zooms(&self) -> bool`. Whether the collection takes the zoom share of the wheel (Ctrl or Cmd with the wheel): the items step reports it as `CollectionEvent::Zoom`. + - `fn zoom_anchor(&self, _wheel: Option) -> Option`. The point whose row stays in place across a zoom step this collection takes in the current pass, in screen points. `wheel` is the point of the `CollectionEvent::Zoom` the items step reported in this pass, `None` when it reported none; a collection that also takes zoom keys answers the pointer it read with them. + - `fn empty_height(&self, width: f32, ui: &Ui, cx: &StyleCx<'_>) -> f32`. The height of the empty state at `width`: a `Sizing::Content` collection with no rows is this tall. + - `fn empty(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>)`. The empty state at the rect the item step placed. - `craft_ui::contract::Component`: `pub trait Component: Meta + Sized`. The core trait: every UI type is a `Component`. - `const ROLE: Role`. The AccessKit role. - `const ALT_ROLES: &'static [Role]`. Roles `access` may pick per instance. - `const INPUT: Input`. How input reaches the component. - `const ESCAPE: EscapeEdit`. What Escape does to the running gesture. - `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16. - - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except - - `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its - - `fn focus_scope(&self) -> crate::runtime::focus::FocusPolicy`. The focus scope this instance runs in. The default is `FOCUS_SCOPE`; a component whose scope is a choice of its + - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts hook, the measure view it reads and the memory of the last state) and leaves the sense step with no part regions. + - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except for the roving group of a body the shape declares. + - `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its parts lie inside it, and `FocusPolicy::NONE` (the default) opens none. + - `fn focus_scope(&self) -> crate::runtime::focus::FocusPolicy`. The focus scope this instance runs in. - `const KEYS: crate::runtime::focus::KeyUse`. Keys the focused component keeps from egui and the shortcut dispatcher. - - `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends - - `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a - - `const LABELLED_AFTER: bool`. Whether the control draws only its mark and its text is the label step's, placed after it: a check box, a - - `const SINGLE_VALUE: bool`. Whether the component edits one value that several selected things cannot disagree on (a colour picker's - - `const BINDS_VIEW: bool`. Whether the binding is the component's view of what it shows (a time area's scroll and zoom, a navigator's + - `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. + - `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a glyph: with no tooltip set, its label is then its tooltip, since the label is the only visible name the pointer can reach. + - `const LABELLED_AFTER: bool`. Whether the control draws only its mark and its text is the label step's, placed after it: a check box, a radio button or a switch. `Show::show` then runs the label step for an instance that carries a label and sits in no label scope. + - `const SINGLE_VALUE: bool`. Whether the component edits one value that several selected things cannot disagree on (a colour picker's area, strip or ramp: it edits the colour it is given). + - `const BINDS_VIEW: bool`. Whether the binding is the component's view of what it shows (a time area's scroll and zoom, a navigator's canvas view), not a value the user edits. - `const DISABLED: DisabledLook`. How a disabled instance looks: token states (the default), or its enabled look faded. - - `const RULE: bool`. Whether the component is a rule between groups of members (a divider). In a bar's line the bar draws it, as a + - `const RULE: bool`. Whether the component is a rule between groups of members (a divider). - `type Style`. The style type. - `type Output`. `Response`, `EditResponse` or a richer type. - - `fn shows_label(&self) -> bool`. Whether this instance paints its label as visible text; `SHOWS_LABEL` unless an instance prop decides, as - - `fn label_detail(&self) -> Option`. The muted line a `LABELLED_AFTER` control's label shows after its text (`SideLabel::detail`), as a radio's + - `fn shows_label(&self) -> bool`. Whether this instance paints its label as visible text; `SHOWS_LABEL` unless an instance prop decides, as `icon_only` does. + - `fn label_detail(&self) -> Option`. The muted line a `LABELLED_AFTER` control's label shows after its text (`SideLabel::detail`), as a radio's `detail`; none by default. - `fn paint_outset(_tokens: &crate::style::UiTokens) -> f32`. How far the component paints outside its rect by design, in points (a graph node's ports sit on its edge). - - `fn default_variant(_env: &crate::runtime::env::Env) -> Option`. The variant an instance that asks for none takes in `env`; `None` takes the style's first. A variant the caller + - `fn default_variant(_env: &crate::runtime::env::Env) -> Option`. The variant an instance that asks for none takes in `env`; `None` takes the style's first. - `fn style(cx: &StyleCx<'_>, key: Self::StyleKey) -> Self::Style`. Pure function of the resolved context and the key. - - `fn padding(&self, _rect: Rect, style: &Self::Style) -> craft_behavior::Insets`. The insets from `rect` to the content rect where the component is shown: the style's padding. A component + - `fn padding(&self, _rect: Rect, style: &Self::Style) -> craft_behavior::Insets`. The insets from `rect` to the content rect where the component is shown: the style's padding. - `fn measure(&mut self, _cx: &MeasureCx<'_, Self>) -> Vec2`. Content size only; the pipeline adds padding and minimum size. - - `fn fills(&self) -> Option`. The axis along which the component takes all the room the flow offers when that is more than it measured, - - `fn cut_first(&self) -> bool`. Whether the content is made to be cut where it does not fit: an elided line or a path. In a row too short for + - `fn fills(&self) -> Option`. The axis along which the component takes all the room the flow offers when that is more than it measured, as a container with `Sizing::Fill` does: the width when its caller set `Sizing::FillWidth` (a search field before a count) or `Sizing::Fill` (which takes the height as well). + - `fn cut_first(&self) -> bool`. Whether the content is made to be cut where it does not fit: an elided line or a path. - `fn sense(&self) -> Sense`. The root's sense; the shape's default unless a canvas control. - - `fn wheel_notch(&self) -> craft_behavior::WheelNotch`. The distance one wheel line scrolls the component when it senses the wheel itself: the service converts the + - `fn wheel_notch(&self) -> craft_behavior::WheelNotch`. The distance one wheel line scrolls the component when it senses the wheel itself: the service converts the device's lines to points with it. - `fn parts(&mut self, _rect: Rect, _cx: &mut PartsCx<'_, Self>)`. Named sub-rects: thumbs, chevrons, handles, segments and the roving groups over them. - `fn bind(&mut self) -> Option>>`. Value components return their binding; the same binding on every call, with no side effects. - - `fn same_value(&self, proposed: &ValueOf, host: &ValueOf) -> bool`. Whether `host`, a value the app wrote back, is the value `proposed` as the component holds values: a host that - - `fn scrub(&self) -> Option>>`. Lets a drag on the scrub's sources (the side label, the body, a part) change the value; the pipeline runs the - - `fn scroll(&mut self) -> Option>`. The scroll offset's owner when the app drives scrolling; `None` keeps it in session memory. The app restores a - - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. Runs at step 13, and in a measuring run of the body before it. + - `fn same_value(&self, proposed: &ValueOf, host: &ValueOf) -> bool`. Whether `host`, a value the app wrote back, is the value `proposed` as the component holds values: a host that stores a proposal rounded to the component's precision has not changed the document under a gesture. + - `fn scrub(&self) -> Option>>`. Lets a drag on the scrub's sources (the side label, the body, a part) change the value; the pipeline runs the gesture (16.3, B2). + - `fn scroll(&mut self) -> Option>`. The scroll offset's owner when the app drives scrolling; `None` keeps it in session memory. + - `fn content_env(&self, _cx: &Cx<'_, Self>, _values: &mut crate::runtime::env::AppValues)`. App values for content the component does not build: its body or its items. - `fn update(&mut self, _cx: &mut Cx<'_, Self>)`. After sensing, before paint: value maths, memory, popup triggers. - - `fn overlay(&mut self, _ui: &mut OverlayUi<'_>, _cx: &mut Cx<'_, Self>)`. Anchored popups. Runs before flags and paint. + - `fn overlay(&mut self, _ui: &mut OverlayUi<'_>, _cx: &mut Cx<'_, Self>)`. Anchored popups. - `fn flags(&self) -> Flags`. Value-driven flags (checked, open, invalid, busy). - `fn activated(&self, cx: &Cx<'_, Self>) -> bool`. When a bound command fires; the default is a primary click or `Intent::Activate`. - `fn paint(&mut self, _ui: &mut PaintUi<'_>, _cx: &Cx<'_, Self>)`. Content only; surface, state fill and focus ring are painted by the pipeline. - `fn paint_over(&mut self, _ui: &mut PaintUi<'_>, _cx: &Cx<'_, Self>)`. Content above the body or items. - `fn access(&self, _access: &mut Access, _cx: &Cx<'_, Self>)`. Value, range, relations, sub-nodes and custom actions beyond role, label and flags. - - `fn value_text(&self, _cx: &Cx<'_, Self>) -> Option`. The shown value as the component words it ("40.0", "20 to 60"), which assistive technology reads and a viewer - - `fn word_value(&self, _value: &ValueOf, _cx: &Cx<'_, Self>) -> Option`. Words `value` as the control shows it ("40.0", "20 to 60"); `None` for a component that words no value. The + - `fn value_text(&self, _cx: &Cx<'_, Self>) -> Option`. The shown value as the component words it ("40.0", "20 to 60"), which assistive technology reads and a viewer shows beside the component (`Outcome::value_text`); `None` for a component that words no value. + - `fn word_value(&self, _value: &ValueOf, _cx: &Cx<'_, Self>) -> Option`. Words `value` as the control shows it ("40.0", "20 to 60"); `None` for a component that words no value. - `fn finish(self, cx: Cx<'_, Self>) -> Self::Output`. Builds the output from the finished context. - `craft_ui::contract::Container`: `pub trait Container: Component + HasProps + Meta`. A component whose caller supplies a body. - `fn open(&mut self) -> Option>`. The open state's owner: the caller's binding. `None`: a session slot under the id. - `fn header(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the header region the body step laid out. - - `fn header_parts(&self, _cx: &MeasureCx<'_, Self>) -> HeaderParts`. The room the container's own parts take at the edges of its header's line (a menu button, a drag band). The + - `fn header_parts(&self, _cx: &MeasureCx<'_, Self>) -> HeaderParts`. The room the container's own parts take at the edges of its header's line (a menu button, a drag band). - `fn controls(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the header's trailing region. - `fn footer(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the footer region. - `fn body_end(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the region under the body and above the footer, whatever the footer's place. - `fn end(&mut self, _ui: &mut Ui, _cx: &mut BodyCx<'_>)`. Fills the end region, after the body. - - `fn closed(&mut self, _why: CloseReason)`. The container closed, and why: a layer's dismissal rule, a close the body or footer asked for with - - `fn placement_changed(&mut self, _change: &overlay::PlacementChange)`. The user moved or resized the container's layer: by the move band, a grip or the keyboard Move and Size + - `fn closed(&mut self, _why: CloseReason)`. The container closed, and why: a layer's dismissal rule, a close the body or footer asked for with `BodyCx::request_close_as`, `overlay::request_close`, or the OS closing its window. + - `fn placement_changed(&mut self, _change: &overlay::PlacementChange)`. The user moved or resized the container's layer: by the move band, a grip or the keyboard Move and Size modes. - `craft_ui::contract::ContentPainter`: `pub trait ContentPainter: Component`. Implemented by the allowlisted components that paint content with a raw painter (a preview, a waveform). -- `craft_ui::contract::DisabledLook`: `pub enum DisabledLook { States, Faded }`. How a component that is not enabled looks (`Component::DISABLED`). Either way it takes no input, its access node +- `craft_ui::contract::DisabledLook`: `pub enum DisabledLook { States, Faded }`. How a component that is not enabled looks (`Component::DISABLED`). - `craft_ui::contract::EscapeEdit`: `pub enum EscapeEdit { Cancel, Commit }`. What Escape does to a value component's running gesture (step 9). - `craft_ui::contract::HasProps`: `pub trait HasProps`. Written by the derive from a `#[container]` field, for containers and collections. - `fn props(&self, _: Internal) -> &ContainerProps`. - `craft_ui::contract::IdSource`: `pub enum IdSource { Auto, Salt(IdSalt), Id(Id) }`. Where an element's id comes from. - `craft_ui::contract::Inner`: `pub struct Inner { pub output: O, pub inner: Option, pub settle: Option }`. The container show output: the component's own output and the body's result. - - `pub fn settle(&mut self, f: impl FnOnce(&mut SettleCx<'_>, &mut R) -> T) -> Option`. Runs `f` once, after the pass's real run, with the body's memory (`keep`, `memory`, `saved`, `pending`, + - `pub fn settle(&mut self, f: impl FnOnce(&mut SettleCx<'_>, &mut R) -> T) -> Option`. Runs `f` once, after the pass's real run, with the body's memory (`keep`, `memory`, `saved`, `pending`, `take`, as the body has it) and the real run's result. - `pub fn map_output(self, f: impl FnOnce(O) -> O2) -> Inner`. Maps the component's own output and keeps the body's result and its settle handle. -- `craft_ui::contract::Internal`: `pub struct Internal`. A token only craft-ui can build: the private field and `pub(crate)` constructor let derive output in any +- `craft_ui::contract::Internal`: `pub struct Internal`. A token only craft-ui can build: the private field and `pub(crate)` constructor let derive output in any crate implement the accessors below, while only craft-ui can call them. - `craft_ui::contract::ItemFn`: `pub type ItemFn<'r, C> = dyn FnMut(&::Key, &mut ItemCx<'_, 'r,::Key>) ->::Item<'r> + 'r`. The item closure of `ShowCollection::show_items`: one call per visible key. - `craft_ui::contract::MAX_EXTENT`: `pub const MAX_EXTENT: f32`. The most a component may measure on either side, in points. - `craft_ui::contract::Meta`: `pub trait Meta`. Written by `#[derive(Component)]`; never by hand. - `type Shape`. The shape: leaf, body or items. - `type StyleKey`. The instance inputs the style depends on. - - `const CANVAS_CONTROL: bool`. A leaf the `Canvas` body shows (`#[component(canvas_control)]`): its default sense is empty, so a press away + - `const CANVAS_CONTROL: bool`. A leaf the `Canvas` body shows (`#[component(canvas_control)]`): its default sense is empty, so a press away from its parts reaches the tool, and its type is a canvas control. - `fn style_key(&self) -> Self::StyleKey`. The style key of this instance. - `fn common(&self, _: Internal) -> &Common`. - `fn common_mut(&mut self, _: Internal) -> &mut Common`. - - `fn set_sizing(&mut self, sizing: Sizing, _: Internal)`. Takes the caller's `Props::sizing`: a leaf keeps it in its `Common`; the derive writes a container's or a + - `fn set_sizing(&mut self, sizing: Sizing, _: Internal)`. Takes the caller's `Props::sizing`: a leaf keeps it in its `Common`; the derive writes a container's or a collection's into its `ContainerProps`, over the default its constructor set. - `craft_ui::contract::Pattern`: `pub trait Pattern`. A type that only assembles components: a composition with no contract shape of its own (24.4). - `craft_ui::contract::ShapeKind`: `pub enum ShapeKind { Leaf, Body, Items }`. The shape of a component, as a value: what a registration records. - `craft_ui::contract::Show`: `pub trait Show: Component + Meta + sealed::Show`. Shows a leaf. @@ -2016,14 +2024,14 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `fn show_at(self, ui: &mut Ui, rect: Rect) -> Self::Output`. Shows the component at `rect`, with no allocation. - `fn show_with_tip(self, ui: &mut Ui, tip: impl FnOnce(&mut Ui)) -> Self::Output`. Shows the component with rich tooltip content from the same call. - `fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, tip: impl FnOnce(&mut Ui)) -> Self::Output`. Shows the component at `rect` with rich tooltip content. - - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal) -> Vec2`. Measures without allocating: steps 1 to 5 under the id `show` would use next. It registers no id, opens no + - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal) -> Vec2`. Measures without allocating: steps 1 to 5 under the id `show` would use next. - `craft_ui::contract::ShowCollection`: `pub trait ShowCollection: Collection + sealed::ShowCollection`. Shows a collection's items. - `fn show_items<'r>(self, ui: &mut Ui, source: &dyn ItemSource, item: &mut ItemFn<'r, Self>) -> Self::Output`. Shows the visible items of `source`, one `item` call each. - `craft_ui::contract::ShowContainer`: `pub trait ShowContainer: Container + sealed::ShowContainer`. Shows a container with its body. - `fn show(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container in the flow of `ui`. - `fn show_at(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places. - - `fn show_at_taking_room(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies - - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2`. Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with + - `fn show_at_taking_room(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner`. Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies past it, as after [`show`]. + - `fn measure_in(&mut self, ui: &Ui, proposal: Proposal, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Vec2`. Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with the body, header, footer and end regions run once in an invisible sizing pass, laid out as `show` lays them out. - `fn show_with_tip(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner`. Shows the container with rich tooltip content. - `fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui),) -> Inner`. Shows the container at `rect` with rich tooltip content. - `craft_ui::contract::ShowShape`: `pub trait ShowShape: sealed::ShowShape`. Which show trait applies, and the shape's default sense. @@ -2038,76 +2046,76 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::Activation`: `pub struct Activation { pub by_key: bool, pub mods: craft_keymap::Mods }`. How a component was activated this pass. - `craft_ui::contract::Animate`: re-export of `craft_ui::runtime::motion::Animate`. - `craft_ui::contract::BandFill`: `pub enum BandFill { Surface(SurfaceKind), Tone(Tone) }`. What the band behind a header paints. -- `craft_ui::contract::Bind`: `pub struct Bind<'a, T>`. The binding of a value component: a value the app owns, the check on it and the value a reset restores. The same +- `craft_ui::contract::Bind`: `pub struct Bind<'a, T>`. The binding of a value component: a value the app owns, the check on it and the value a reset restores. - `pub fn given(v: impl Into>) -> Self`. A value in; every edit comes out as an event. - `pub fn bound(v: &'a mut T) -> Self`. Edits write through to `v`. - `pub fn bound_mixed(v: &'a mut Mixed) -> Self`. Edits write through to a field that may be mixed; an edit makes it concrete. - - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. Until something is stored, it reads - - `pub fn saved(mut self, key: SaveKey) -> Self where T: Savable,`. A kept value that is also saved across runs under `key`. The `Savable` bound sits here; the pipeline reaches + - `pub fn kept() -> Self`. No caller value: the component keeps it in session memory under its id. + - `pub fn saved(mut self, key: SaveKey) -> Self where T: Savable,`. A kept value that is also saved across runs under `key`. - `pub fn policy(mut self, policy: EditPolicy) -> Self`. When a write-through source is written. - - `pub fn check(self, check: fn(&T) -> Validity) -> Self where T: 'a,`. The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` - - `pub fn check_with(mut self, inputs: I, check: fn(&I, &T) -> Validity) -> Self where T: 'a,`. The check `check` on a value, reading `inputs` beside it (a limit, the names already taken). The inputs are + - `pub fn check(self, check: fn(&T) -> Validity) -> Self where T: 'a,`. The check on a value: `Fix` replaces it; `Warn`, `Refuse` and `Error` set the component's state, and `Refuse` also refuses a commit. `check` is a `fn`, which captures nothing; a check that reads other values takes them as inputs ([`check_with`]). + - `pub fn check_with(mut self, inputs: I, check: fn(&I, &T) -> Validity) -> Self where T: 'a,`. The check `check` on a value, reading `inputs` beside it (a limit, the names already taken). - `pub fn reset(mut self, default: T) -> Self`. The value a reset gesture restores, and the value a kept binding reads while nothing is stored. - - `pub fn reborrowed(&mut self) -> Bind<'_, T>`. A binding with the same source, check, policy and reset that borrows this one, so a composite can hand its + - `pub fn reborrowed(&mut self) -> Bind<'_, T>`. A binding with the same source, check, policy and reset that borrows this one, so a composite can hand its own binding to a child component for the length of one pass. - `pub fn value(&self) -> Option<&T>`. The one value the binding holds before this pass's edits; `None` for a mixed or kept binding. - `pub fn reborrow(&mut self) -> BindMut<'_, T>`. The binding as the pipeline reads and writes it. - `craft_ui::contract::BindCheck`: `pub struct BindCheck<'c, T>`. A binding's check as props (`BindMut::check_of`): by the key of its inputs and its `fn`. - `pub fn validity(&self, value: &T) -> Validity`. The check's verdict on `value`. -- `craft_ui::contract::BindMut`: `pub struct BindMut<'a, T>`. A reborrow of a [`Bind`] the pipeline reads at steps 4, 11, 15 and 17. `Component::bind` returns it, and returns the - - `pub fn check_of(&self) -> BindCheck<'_, T>`. The binding's check, as the inputs of a child's check (`Bind::check_with`): a composite hands its own check to - - `pub fn read(&self, cx: &mut impl StageAccess) -> Option>`. The binding's value for code that runs no pipeline step: a given or write-through value, or the kept value - - `pub fn write(&mut self, cx: &mut impl StageAccess, event: &EditEvent) -> bool`. Writes `event` as the pipeline's apply step does: the check may replace the value (`Fix`) or refuse it -- `craft_ui::contract::BodyCx`: `pub struct BodyCx<'a> { pub id: Id, pub env: EnvView<'a>, pub resolved: &'a Resolved<'a>, pub rect: Rect, pub memory: &'a mut MemoryStage }`. What a body closure and the header, footer and empty hooks read: a view over the pipeline's memory stage - - `pub fn open_url(&mut self, url: &str, new_tab: bool)`. Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set: the opener - - `pub fn take_pick_answer(&self, ticket: craft_host::PickId) -> Option`. The host file service's answer to the picker `ticket`, taken once. A measuring run gets none and leaves - - `pub fn is_exiting(&self) -> bool`. Whether the container has closed and its body only stays on screen while it fades out. `is_open` reads true - - `pub fn field_message(&self) -> Option<(Message, craft_theme::variant::Tone)>`. The validity message of the first control in the container's label scope, recorded last frame, with the - - `pub fn moving(&self) -> bool`. Whether a drag of the container's move band (`DragBand::Move`) moves its layer in this pass, from the pass the +- `craft_ui::contract::BindMut`: `pub struct BindMut<'a, T>`. A reborrow of a [`Bind`] the pipeline reads at steps 4, 11, 15 and 17. `Component::bind` returns it, and returns the same binding on every call. + - `pub fn check_of(&self) -> BindCheck<'_, T>`. The binding's check, as the inputs of a child's check (`Bind::check_with`): a composite hands its own check to the children that edit its value. + - `pub fn read(&self, cx: &mut impl StageAccess) -> Option>`. The binding's value for code that runs no pipeline step: a given or write-through value, or the kept value under the base id of `cx` (the saved tier when the binding has a `SaveKey`). `None` for a kept binding that holds nothing yet. + - `pub fn write(&mut self, cx: &mut impl StageAccess, event: &EditEvent) -> bool`. Writes `event` as the pipeline's apply step does: the check may replace the value (`Fix`) or refuse it (nothing is written). +- `craft_ui::contract::BodyCx`: `pub struct BodyCx<'a> { pub id: Id, pub env: EnvView<'a>, pub resolved: &'a Resolved<'a>, pub rect: Rect, pub memory: &'a mut MemoryStage }`. What a body closure and the header, footer and empty hooks read: a view over the pipeline's memory stage keyed by the body's base id. + - `pub fn open_url(&mut self, url: &str, new_tab: bool)`. Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set: the opener `Link` uses. + - `pub fn take_pick_answer(&self, ticket: craft_host::PickId) -> Option`. The host file service's answer to the picker `ticket`, taken once. + - `pub fn is_exiting(&self) -> bool`. Whether the container has closed and its body only stays on screen while it fades out. `is_open` reads true then; a region that belongs to the open container (a companion layer) is not shown. + - `pub fn field_message(&self) -> Option<(Message, craft_theme::variant::Tone)>`. The validity message of the first control in the container's label scope, recorded last frame, with the tone it shows in: a container whose footer declares `FooterRegion::status` shows it as its status text. `None` when the container has no label or no control reported one. + - `pub fn moving(&self) -> bool`. Whether a drag of the container's move band (`DragBand::Move`) moves its layer in this pass, from the pass the drag starts to the one before its release: a grip in the body shows the move. - `pub fn is_open(&self) -> bool`. Whether the body is open. - `pub fn open(&mut self) -> &mut bool`. The open state: a title row's disclosure binds to it, and step 15 writes a change to its owner. - - `pub fn gate(&mut self) -> Option<&mut bool>`. The gate's shown copy, for a container whose value is a bool: a title row's check box binds to it, and + - `pub fn gate(&mut self) -> Option<&mut bool>`. The gate's shown copy, for a container whose value is a bool: a title row's check box binds to it, and step 15 applies a change. - `pub fn gate_is_mixed(&self) -> bool`. Whether the gate's value is mixed: `gate` then reads off, and a title row's check box shows the mixed face. - `pub fn request_close(&mut self)`. Asks the container to close, as `CloseReason::Requested`: step 15 closes it. - - `pub fn request_close_as(&mut self, why: CloseReason)`. Asks the container to close and tells it why (an OK button is `Activated`, Enter is `Enter`): step 15 - - `pub fn labelled(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C) -> C::Output`. Runs the label step (B2, 16.3) for one leaf child in the body's flow: `label` sits beside the child or above - - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The - - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places - - `pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` - - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it + - `pub fn request_close_as(&mut self, why: CloseReason)`. Asks the container to close and tells it why (an OK button is `Activated`, Enter is `Enter`): step 15 closes it and `Container::closed` gets `why`. + - `pub fn labelled(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C) -> C::Output`. Runs the label step (B2, 16.3) for one leaf child in the body's flow: `label` sits beside the child or above it, with the icon and detail of `side`, and the child takes the width the label leaves. + - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). + - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body reads what its container's style holds (a dock root's docking sizes). `None` when the body's container has another style type, and for a body with no container: a popup's body or a collection's empty state. + - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places content of its own beside them. `None` for a body with no container: a popup's body or a collection's empty state. + - `pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` ([`runtime::derived`](crate::runtime::derived::derived), under the body's id). + - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it is empty. `true` once per Escape; the enclosing scope (a dialog, a popover) then does not act on it. - `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. - `pub const fn row() -> Self`. Children side by side from the start edge, with no wrap. - - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's + - `pub fn grid(columns: impl Into>) -> Self`. Children row-major over `columns`: a `'static` slice, or columns built in the pass. - `pub fn fit(self, fit: GridFit) -> Self`. A `Grid` with `fit`; any other layout is unchanged. - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. -- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and +- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and height to their chain): a tick from each of the first and the last row's controls to the middle child's centre line, joined along that line. - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. -- `craft_ui::contract::CaptionColumn`: `pub struct CaptionColumn`. Whether the beside captions of a [`LabelScheme::Inline`] form share one column. Off (the default), each caption is +- `craft_ui::contract::CaptionColumn`: `pub struct CaptionColumn`. Whether the beside captions of a [`LabelScheme::Inline`] form share one column. - `pub const SHARED: CaptionColumn`. The captions share one column. - `pub const OWN: CaptionColumn`. Each caption is as wide as its own text (the default). - `pub const fn shared(self) -> bool`. Whether the captions share one column. -- `craft_ui::contract::CaptionInk`: `pub enum CaptionInk { Muted, Normal }`. The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio, +- `craft_ui::contract::CaptionInk`: `pub enum CaptionInk { Muted, Normal }`. The ink of a side label's name, other than a link's ([`LinkLabelInk`]) and the text after a check box or a radio, which reads at full ink. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. - `pub const fn new() -> Self`. A collapsible body that starts open, animated. - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. - `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection { change: SelectionChange, by: LeadSource, mods: craft_keymap::Mods }, Picked { key: K, mods: craft_keymap::Mods }, LeadMoved { key: K, by: LeadSource }, Activate(K), Refused(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, MiddleClick(K), Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

+ Send + Sync + 'static) -> Self`. A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag - - `pub fn carry(mut self, payload: DragPayload) -> Self`. A row drag carries `payload` of it too, beside the payloads given before: a host adds its own payload type to a + - `pub fn drag_payload(self, map: impl Fn(&ListDrag) -> Option

+ Send + Sync + 'static) -> Self`. A row drag carries `map` of it, for the drop targets of type `P`; a row the map gives `None` for does not drag unless a reorder rule is set. + - `pub fn carry(mut self, payload: DragPayload) -> Self`. A row drag carries `payload` of it too, beside the payloads given before: a host adds its own payload type to a drag the component already maps. - `pub const fn drag_preview(mut self, preview: RowPreview) -> Self`. What a row drag shows while it runs (a badge by the pointer by default). - `pub const fn drag_count(mut self, count: Counted) -> Self`. A row drag's preview reads `count` for the number of dragged items. - `pub const fn pages(mut self, on: bool) -> Self`. The items are pages (`CollectionProps::pages`). - `pub fn rename(mut self, on: bool) -> Self`. Rename runs through the collection's editor. - - `pub fn rename_column(mut self, column: ColumnKey) -> Self`. A double click on `column` of a renamable item (`rename`, `Collection::can_rename`) opens its rename editor; the + - `pub fn rename_column(mut self, column: ColumnKey) -> Self`. A double click on `column` of a renamable item (`rename`, `Collection::can_rename`) opens its rename editor; the double click elsewhere on the row activates it. - `pub const fn slow_click_rename(mut self, on: bool) -> Self`. A slow second click on the label of the only selected item opens its rename editor. - `pub fn columns(mut self, columns: Vec) -> Self`. The columns. - `pub fn sort(mut self, sort: impl Into>) -> Self`. The column the rows are sorted by. @@ -2140,13 +2148,13 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn invert_middle(mut self, on: bool) -> Self`. Flips the direction of middle-button pan and auto-scroll (see [`CollectionProps::invert_middle`]). - `pub fn wheel_notch(&self, line: f32) -> craft_behavior::WheelNotch`. The wheel distance of one notch, with a text line `line` points high: the set notch, else the default. - `pub const fn overflow(mut self, axis: Axis) -> Self`. The axis the rows overflow along (see [`CollectionProps::overflow`]). - - `pub fn current(mut self, key: Option) -> Self`. The current item: `Some(key)` marks the item with that key, `None` marks none. `K` is the collection's key type; + - `pub fn current(mut self, key: Option) -> Self`. The current item: `Some(key)` marks the item with that key, `None` marks none. `K` is the collection's key type; a key of another type marks nothing. - `pub const fn picks_beside_current(mut self, on: bool) -> Self`. Keeps the selection a pick beside the current item (see [`CollectionProps::picks_beside_current`]). - `pub fn empty(mut self, text: impl Into

+ Send + Sync + 'static) -> Self`. The payload `map` makes of a drag of the collection whose keys are `K`; `None` for a row that carries none. - `craft_ui::contract::DragPreview`: re-export of `craft_ui::runtime::drag::DragPreview`. - `craft_ui::contract::DropAt`: `pub enum DropAt { Gap { key: Option, insert: usize }, Onto(K) }`. The place of one drop. - `pub const fn gap(key: Option, insert: usize) -> Self`. Between items, over `key`, before `insert`. - `pub fn key(&self) -> Option<&K>`. The item under the pointer. -- `craft_ui::contract::DropKind`: `pub struct DropKind<'a, K>`. A payload type a collection takes from a drag that did not start in it, at one place, where `accepts` passes. A +- `craft_ui::contract::DropKind`: `pub struct DropKind<'a, K>`. A payload type a collection takes from a drag that did not start in it, at one place, where `accepts` passes. - `pub fn new(place: DropPlace, accepts: impl Fn(&P, &DropAt) -> bool + 'a) -> Self`. Drops of payload type `P` at `place` where `accepts` passes for the payload and the place under the pointer. - `craft_ui::contract::DropMark`: re-export of `craft_ui::runtime::drag::DropMark`. - `craft_ui::contract::DropOperation`: re-export of `craft_behavior::keys::DropOperation`. @@ -2256,49 +2264,49 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::DropPlace`: `pub enum DropPlace { Between, Onto }`. Where a drop kind takes its drops. - `craft_ui::contract::DropTarget`: re-export of `craft_ui::runtime::drag::DropTarget`. - `craft_ui::contract::DropZone`: re-export of `craft_ui::runtime::drag::DropZone`. -- `craft_ui::contract::EDIT_MENU`: `pub const EDIT_MENU: &str`. The popup name of a text part's edit menu: step 8b registers it for every text part, and the text control opens -- `craft_ui::contract::EdgePress`: `pub struct EdgePress<'a, K>`. The line between two adjacent rows as a target of its own while `mods` are held (Photoshop's Alt-click between two +- `craft_ui::contract::EDIT_MENU`: `pub const EDIT_MENU: &str`. The popup name of a text part's edit menu: step 8b registers it for every text part, and the text control opens and shows it from its `overlay` hook. +- `craft_ui::contract::EdgePress`: `pub struct EdgePress<'a, K>`. The line between two adjacent rows as a target of its own while `mods` are held (Photoshop's Alt-click between two layers clips the upper one). - `pub fn new(mods: Mods, test: impl Fn(&K, &K) -> Option + 'a) -> Self`. The edge press while exactly `mods` are held, on the lines `test` takes. -- `craft_ui::contract::Edit`: `pub trait Edit`. Values and edits (chapter 10). `value`, `validity`, `gesture`, `gesture_before`, `adopt` and `edit_response` take +- `craft_ui::contract::Edit`: `pub trait Edit`. Values and edits (chapter 10). `value`, `validity`, `gesture`, `gesture_before`, `adopt` and `edit_response` take `&self`, so `paint` can call them. - `type Value`. The component's value type. - - `fn value(&self) -> Option<&Self::Value>`. The shown value: the running gesture's proposal, else the binding's. `None` for a mixed binding, a kept + - `fn value(&self) -> Option<&Self::Value>`. The shown value: the running gesture's proposal, else the binding's. `None` for a mixed binding, a kept binding with nothing in it, and a component with no value. - `fn validity(&self) -> Validity`. What the binding's check says about the shown value. - `fn gesture(&self) -> Option`. Where this pass's gesture stands. - - `fn gesture_before(&self) -> Option>`. The value the running gesture began with, as its `Begin` reported it: the same in every pass of the gesture, - - `fn adopt(&self, child: &EditResponse, start: &Self::Value, map: impl Fn(&V, &mut Self::Value))`. Maps each of the child's events onto a clone of this component's shown value and queues the resulting events, in + - `fn gesture_before(&self) -> Option>`. The value the running gesture began with, as its `Begin` reported it: the same in every pass of the gesture, while [`value`] follows each proposal. + - `fn adopt(&self, child: &EditResponse, start: &Self::Value, map: impl Fn(&V, &mut Self::Value))`. Maps each of the child's events onto a clone of this component's shown value and queues the resulting events, in the child's order, for step 15. - `fn edit_response(&self) -> EditResponse`. The `EditResponse` a value component returns from `finish`. - - `fn propose(&mut self, v: Self::Value)`. Sets the running gesture's value, beginning a gesture if none runs and the press that carries it has had no + - `fn propose(&mut self, v: Self::Value)`. Sets the running gesture's value, beginning a gesture if none runs and the press that carries it has had no gesture cancelled. - `fn set(&mut self, v: Self::Value)`. A one-shot change outside a gesture. - `fn begin(&mut self)`. Opens a gesture. - `fn commit(&mut self)`. Commits the proposed value. - `fn cancel(&mut self, reason: CancelReason)`. Cancels the running gesture. -- `craft_ui::contract::EditResponse`: `pub struct EditResponse { pub response: Response, pub events: EditEvents, pub submitted: bool, pub submit_mods: craft_keymap::Mods, pub activation_mods: craft_keymap::Mods, pub left_by_tab: Option, pub text_lost_focus: bool, pub escaped: bool, pub unparsed: bool, pub validity: Validity, pub shown: Option>>, pub value_text: Option, pub tab: Option, pub caret: Option, pub hover: Hover }`. The output of a component that edits a value. Only `cx.edit_response()` builds it. - - `pub fn lifted(response: Response, events: EditEvents, shown: Option>>) -> Self`. The response of a composite that edits one value through several child components: `events` are the edits of - - `pub fn value(&self) -> Option<&T>`. The latest value the pass's events carry: a proposal, a commit or a set; `None` when nothing was edited or no - - `pub fn map(self, f: impl Fn(T) -> U) -> EditResponse`. The response of a child component's edit as the response of the edit of a value built from it: the events, the -- `craft_ui::contract::EditorHandle`: `pub struct EditorHandle`. The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a +- `craft_ui::contract::EditResponse`: `pub struct EditResponse { pub response: Response, pub events: EditEvents, pub submitted: bool, pub submit_mods: craft_keymap::Mods, pub activation_mods: craft_keymap::Mods, pub left_by_tab: Option, pub text_lost_focus: bool, pub escaped: bool, pub unparsed: bool, pub validity: Validity, pub shown: Option>>, pub value_text: Option, pub tab: Option, pub caret: Option, pub hover: Hover }`. The output of a component that edits a value. + - `pub fn lifted(response: Response, events: EditEvents, shown: Option>>) -> Self`. The response of a composite that edits one value through several child components: `events` are the edits of the whole value the composite lifted from its children's events, `shown` the value it showed after the pass, and `response` its own. + - `pub fn value(&self) -> Option<&T>`. The latest value the pass's events carry: a proposal, a commit or a set; `None` when nothing was edited or no event carries one (a gesture's begin or cancel). + - `pub fn map(self, f: impl Fn(T) -> U) -> EditResponse`. The response of a child component's edit as the response of the edit of a value built from it: the events, the shown value and a fix are mapped by `f`; the response and flags are the child's own. +- `craft_ui::contract::EditorHandle`: `pub struct EditorHandle`. The editor part's widget, rect, purpose, focus, read-only and disabled state of this pass, which a body that runs inside a component reports through for the component's editor part. - `pub fn focused(&self) -> bool`. Whether the editor part holds the key focus this pass, whether or not its window has the system's. - - `pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>)`. Reports the caret and composition to the input-method engine and puts the text facts in the running pass's - - `pub fn ime_receipt(&self, ctx: &egui::Context, before: ImeStamp, after: ImeStamp) -> bool`. Notes the input-method receipt between the stamps `before` and `after` for this editor part; true when the + - `pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>)`. Reports the caret and composition to the input-method engine and puts the text facts in the running pass's editor record, which the owning component's report step reads in the same pass. + - `pub fn ime_receipt(&self, ctx: &egui::Context, before: ImeStamp, after: ImeStamp) -> bool`. Notes the input-method receipt between the stamps `before` and `after` for this editor part; true when the stamps prove the engine applied it. - `pub fn ime_application_change(&self, ctx: &egui::Context)`. Notes an application change of this editor part's committed text. - - `pub fn ime_interrupt(&self, ctx: &egui::Context)`. Asks for the OS composition to be interrupted this pass, because this editor part refused an input method's + - `pub fn ime_interrupt(&self, ctx: &egui::Context)`. Asks for the OS composition to be interrupted this pass, because this editor part refused an input method's edit and the input method's view of the text is stale. - `craft_ui::contract::EditorStep`: `pub enum EditorStep { Input(EditorInput), Command(S, Fired) }`. One step of an editor's pass, in the order of the events it came from ([`Cx::editor_steps`]). -- `craft_ui::contract::EndRegion`: `pub struct EndRegion { pub full_height: bool, pub gap: Gap, pub rule: bool, pub fit: bool }`. An end region, filled by `Container::end`: content in reading order at the line's end edge, beside the body and +- `craft_ui::contract::EndRegion`: `pub struct EndRegion { pub full_height: bool, pub gap: Gap, pub rule: bool, pub fit: bool }`. An end region, filled by `Container::end`: content in reading order at the line's end edge, beside the body and outside its scroll region, as wide as it measured. - `pub const fn new() -> Self`. An end region as high as the line, `space.gap.tight` from the body, with no rule. - `pub const fn fit(mut self, on: bool) -> Self`. Whether the region joins the body's fit. - `pub const fn rule(mut self, on: bool) -> Self`. Whether a rule separates the end region from the body. - `pub const fn full_height(mut self, on: bool) -> Self`. Whether the region takes the full height under the header. - `pub const fn gap(mut self, gap: Gap) -> Self`. Sets the gap between the body and the region. -- `craft_ui::contract::Entry`: `pub struct Entry`. A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator +- `craft_ui::contract::Entry`: `pub struct Entry`. A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator between groups of items. - `pub fn new(value: T, label: impl Into

, Pos2)>`. The active drag payload of type `P` and the pointer position in this component's egui layer space (8.3), from any - - `fn drop_target>(&mut self, target: &T) -> Option`. Registers `target` over this component's rect for this pass, in `update`. Returns the drop released over it this - - `fn window_drop_target>(&mut self, target: &T) -> Option`. Registers `target` over the whole window of the running viewport for this pass, in `update`; a target over a - - `fn drag_ended(&self) -> Option`. The operation of a drop of this component's payload, in the pass after the drop; `None` while dragging, when the - - `fn scroll_moved(&self, key: PartKey) -> Option>`. The visible range the scroll part `key` moved to this pass (thumb or end drag, page press, or an AccessKit click + - `fn start_drag_also(&mut self, payload: P, also: Vec>, preview: DragPreview,)`. Starts the drag session with `payload`, which also carries the payloads `also`, one per type: targets of any of these types see the one drag. + - `fn dragging(&self) -> Option<(Arc

, Pos2)>`. The active drag payload of type `P` and the pointer position in this component's egui layer space (8.3), from any viewport. + - `fn drop_target>(&mut self, target: &T) -> Option`. Registers `target` over this component's rect for this pass, in `update`. + - `fn window_drop_target>(&mut self, target: &T) -> Option`. Registers `target` over the whole window of the running viewport for this pass, in `update`; a target over a component beats it wherever that accepts. + - `fn drag_ended(&self) -> Option`. The operation of a drop of this component's payload, in the pass after the drop; `None` while dragging, when the drag was cancelled and when no target took it. + - `fn scroll_moved(&self, key: PartKey) -> Option>`. The visible range the scroll part `key` moved to this pass (thumb or end drag, page press, or an AccessKit click on the track, which pages toward the track's centre). - `craft_ui::contract::Politeness`: re-export of `craft_ui::runtime::access::Politeness`. - `craft_ui::contract::Popup`: `pub struct Popup`. The open state of a container's layer that has an opener and no binding, driven from the opener's side. - `pub fn open(opener: impl Into, cx: &mut Cx<'_, C>)`. Opens the container hung from `opener` (a [`PopupHandle`] or the id of the opener's response). - `pub fn close(opener: impl Into, cx: &mut Cx<'_, C>)`. Closes the container hung from `opener`. - `pub fn toggle(opener: impl Into, cx: &mut Cx<'_, C>)`. Opens the container hung from `opener` when it is closed, else closes it. - - `pub fn opening(popup: PopupHandle, cx: &Cx<'_, C>) -> bool`. Whether the layer `popup` shows first in this pass: true in the passes of the frame it first shows, false + - `pub fn opening(popup: PopupHandle, cx: &Cx<'_, C>) -> bool`. Whether the layer `popup` shows first in this pass: true in the passes of the frame it first shows, false in the frames after, so what a body resets on opening resets once. - `craft_ui::contract::PopupHandle`: `pub struct PopupHandle`. An id and a name; `Copy`, never a snapshot of the open state. - - `pub fn at(self, index: usize) -> PopupHandle`. The popup of the repeat `index` of this name: a component with one popup per part or per entry gives each its + - `pub fn at(self, index: usize) -> PopupHandle`. The popup of the repeat `index` of this name: a component with one popup per part or per entry gives each its own. - `pub fn id(self) -> Id`. The popup's id: its open state's and its entry in the layer stack. - `pub fn name(self) -> &'static str`. The name given to `cx.popup`. - `pub fn trigger(self, trigger: Trigger, cx: &mut Cx<'_, C>)`. Toggles or opens the popup from `trigger` at step 9, as the pass's pending open change. - - `pub fn open(self, cx: &mut Cx<'_, C>)`. Queues an open that step 15 writes. For `Trigger::Manual` this and the binding are the only ways it opens. + - `pub fn open(self, cx: &mut Cx<'_, C>)`. Queues an open that step 15 writes. - `pub fn close(self, cx: &mut Cx<'_, C>)`. Queues a close; step 15 writes the slot, so this pass still shows the popup open. - - `pub fn changed(self, cx: &mut Cx<'_, C>) -> bool`. Whether a toggle, `open` or `close` queued in this pass leaves the popup's open state different from the - - `pub fn bind_open(self, cx: &mut Cx<'_, C>, mut open: BindMut<'_, bool>) -> bool`. Binds the popup's open state to `open`: call it in `update`, after the toggles and closes the component + - `pub fn changed(self, cx: &mut Cx<'_, C>) -> bool`. Whether a toggle, `open` or `close` queued in this pass leaves the popup's open state different from the state the pass began with. + - `pub fn bind_open(self, cx: &mut Cx<'_, C>, mut open: BindMut<'_, bool>) -> bool`. Binds the popup's open state to `open`: call it in `update`, after the toggles and closes the component queues. - `pub fn is_open(self, cx: &mut Cx<'_, C>) -> bool`. Whether the popup is open in this pass: valid from step 8, with the changes queued so far applied. - `craft_ui::contract::PopupKind`: re-export of `craft_ui::runtime::access::PopupKind`. - `craft_ui::contract::Presence`: re-export of `craft_ui::runtime::motion::Presence`. - `craft_ui::contract::Progress`: re-export of `craft_ui::runtime::pending::Progress`. - `craft_ui::contract::Props`: re-export of `craft_ui_macros::Props` (outside these crates). -- `craft_ui::contract::QuietHeader`: `pub enum QuietHeader { Ruled, Heads }`. Whether a titled header that draws no rule under it (a quiet title, [`HeaderRegion::heads`]) still heads its body as +- `craft_ui::contract::QuietHeader`: `pub enum QuietHeader { Ruled, Heads }`. Whether a titled header that draws no rule under it (a quiet title, [`HeaderRegion::heads`]) still heads its body as a rule would. - `craft_ui::contract::Remember`: re-export of `craft_ui::runtime::memory::Remember`. - `craft_ui::contract::Rename`: `pub struct Rename { pub key: K, pub name: String }`. A committed rename. - `pub fn new(key: K, name: impl Into) -> Self`. The rename of `key` to `name`. @@ -2675,29 +2686,29 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn new() -> Self`. A rule that only moves. - `pub const fn keys(mut self, keys: ReorderKeys) -> Self`. The key scheme that reorders the items. - `pub const fn into_groups(mut self) -> Self`. Items may land inside the groups of a tree. - - `pub const fn copy_with(mut self, keys: CopyKeys) -> Self`. A drag with `keys` held copies: [`CopyKeys::Alt`] in a design app's layers, [`CopyKeys::Platform`] (Ctrl off + - `pub const fn copy_with(mut self, keys: CopyKeys) -> Self`. A drag with `keys` held copies: [`CopyKeys::Alt`] in a design app's layers, [`CopyKeys::Platform`] (Ctrl off macOS) in a file or page grid. - `craft_ui::contract::Resolved`: `pub struct Resolved<'p> { pub id: Id, pub label: &'p str, pub enabled: bool, pub read_only: bool, pub size: ControlSize, pub variant: Variant, pub selected: Option, pub description: Option<&'p str>, pub tooltip: Option<&'p Tooltip>, pub doc_key: Option }`. `Common` after step 1; it borrows locals of the pipeline frame, never the component. - `pub fn sizing(&self) -> Option`. The sizing the host set on this component, if any: a leaf with `Sizing::Content` sizes to its content. - - `pub fn tooltip_text(&self, env: &crate::runtime::env::EnvView<'_>) -> Option`. The text of the component's own tooltip as the tooltip shows it: its disabled text while the component is + - `pub fn tooltip_text(&self, env: &crate::runtime::env::EnvView<'_>) -> Option`. The text of the component's own tooltip as the tooltip shows it: its disabled text while the component is disabled. `None` when the component has no tooltip. - `craft_ui::contract::Revision`: re-export of `craft_tracked::Revision` (outside these crates). - `craft_ui::contract::Role`: re-export of `craft_ui::runtime::access::Role`. - `craft_ui::contract::RowAlign`: `pub enum RowAlign { Start, Center, End, SpaceBetween }`. Where a `Row` places its block of children along the row. -- `craft_ui::contract::RowHeight`: `pub enum RowHeight { Control, Text }`. How tall a collection's rows are. Read-only display tables (a metadata table) take text rows; lists the user picks +- `craft_ui::contract::RowHeight`: `pub enum RowHeight { Control, Text }`. How tall a collection's rows are. - `pub fn of(self, cx: &StyleCx<'_>) -> f32`. The height of one row under `cx`. - `craft_ui::contract::RowPressed`: `pub enum RowPressed { Row, Cell(ColumnKey), Part { was_lead: bool } }`. Where the collection holds a primary press on a row, within slop, or the press a part of the row holds. -- `craft_ui::contract::RowPreview`: `pub enum RowPreview { Badge, Named, None }`. What a row drag shows while it runs. The text is the count word for the dragged items -- `craft_ui::contract::RowState`: `pub struct RowState { pub selected: bool, pub lead: bool, pub drop_target: bool, pub dragging: bool, pub renaming: bool, pub emphasized: bool, pub current: bool, pub striped: bool, pub open: bool, pub hovered: bool, pub pointer_over: bool, pub pressed: Option, pub menu_open: bool, pub sub_row: Option, pub continued: bool, pub last: bool, pub first: bool, pub activated_by_key: bool }`. What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. The -- `craft_ui::contract::Sampler`: `pub trait Sampler: sealed::Host`. The canvas reach under a modal layer (15.5, 8.3): a control of a dialog keeps the canvas below it usable. It is - - `fn pass_canvas_gesture(&mut self, canvas: Id, gesture: CanvasGesture)`. Lets `gesture` on `canvas` (the canvas component's id) through the modal layer, and the view navigation with it - - `fn keep_view_open(&mut self, canvas: Id)`. Keeps the view of `canvas` (the canvas component's id) usable under the modal layer: the wheel scrolls and +- `craft_ui::contract::RowPreview`: `pub enum RowPreview { Badge, Named, None }`. What a row drag shows while it runs. +- `craft_ui::contract::RowState`: `pub struct RowState { pub selected: bool, pub lead: bool, pub drop_target: bool, pub dragging: bool, pub renaming: bool, pub emphasized: bool, pub current: bool, pub striped: bool, pub open: bool, pub hovered: bool, pub pointer_over: bool, pub pressed: Option, pub menu_open: bool, pub sub_row: Option, pub continued: bool, pub last: bool, pub first: bool, pub activated_by_key: bool }`. What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. +- `craft_ui::contract::Sampler`: `pub trait Sampler: sealed::Host`. The canvas reach under a modal layer (15.5, 8.3): a control of a dialog keeps the canvas below it usable. + - `fn pass_canvas_gesture(&mut self, canvas: Id, gesture: CanvasGesture)`. Lets `gesture` on `canvas` (the canvas component's id) through the modal layer, and the view navigation with it (`keep_view_open`): an armed eyedropper's press ([`CanvasGesture::PRIMARY`]), a dialog's drag on the image, a ⌘-click (`CanvasGesture::PRIMARY.with(Mods::CMD)`). + - `fn keep_view_open(&mut self, canvas: Id)`. Keeps the view of `canvas` (the canvas component's id) usable under the modal layer: the wheel scrolls and zooms it, and a middle press pans it, as in Photoshop's Color Picker and Levels dialogs; Space held over the canvas adds the primary press for the pan. - `craft_ui::contract::Savable`: re-export of `craft_ui::runtime::memory::Savable`. - `craft_ui::contract::SaveKey`: re-export of `craft_ui::runtime::memory::SaveKey`. - `craft_ui::contract::Scroll`: `pub struct Scroll { pub axes: ScrollAxes, pub anchor: ScrollAnchor, pub notch: Notch, pub indicator: ScrollIndicator, pub at_rest: bool }`. A scrolling body. - `pub const fn strips(mut self) -> Scroll`. Shows the overflow along y as scroll strips instead of a bar. - `pub const fn has_strips(&self) -> bool`. Whether the overflow along y shows as scroll strips. - - `pub const fn overlay(mut self) -> Scroll`. Shows the overflow as a bar in the container's padding that takes no room from the content and shows only + - `pub const fn overlay(mut self) -> Scroll`. Shows the overflow as a bar in the container's padding that takes no room from the content and shows only under the pointer ([`ScrollIndicator::Overlay`]). - `pub const fn has_overlay(&self) -> bool`. Whether the overflow shows as an overlay bar. - - `pub const fn at_rest(mut self) -> Scroll`. Shows an overlay bar whenever the content overflows, also while the pointer is away from the container. A bar of + - `pub const fn at_rest(mut self) -> Scroll`. Shows an overlay bar whenever the content overflows, also while the pointer is away from the container. - `pub const fn overlay_hides_at_rest(&self) -> bool`. Whether the overlay bar shows only while the pointer is over the container or presses the bar. - `pub const fn vertical() -> Scroll`. Scrolls along y. - `pub const fn horizontal() -> Scroll`. Scrolls along x. @@ -2709,22 +2720,22 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::ScrollAnchor`: `pub enum ScrollAnchor { Start, End }`. Which end of the content a scroll region stays at when the content grows. - `craft_ui::contract::ScrollAxes`: `pub enum ScrollAxes { Vertical, Horizontal, Both }`. The axes a body scrolls on. - `craft_ui::contract::ScrollIndicator`: `pub enum ScrollIndicator { Bar, Strips, Overlay }`. How a scrolling body shows that its content overflows. -- `craft_ui::contract::Scrub`: `pub struct Scrub`. How a drag changes a control's value: the drag maths over the control's number, and the sources a drag starts on +- `craft_ui::contract::Scrub`: `pub struct Scrub`. How a drag changes a control's value: the drag maths over the control's number, and the sources a drag starts on (`by_label`, `on_field`, `part`). - `pub fn new(drag: ValueDrag, read: impl Fn(&V) -> f64 + Send + Sync + 'static, write: impl Fn(f64) -> V + Send + Sync + 'static) -> Self`. A scrub by `drag`, reading the number a value holds with `read` and making a value of a number with `write`. - - `pub fn by_label(mut self) -> Self`. A drag on the control's side label scrubs, with or without the focus in the control; the label senses the - - `pub fn part(mut self, part: impl Into, drag: ValueDrag) -> Self`. A drag on the part `part` scrubs by `drag`, with or without the focus in the control: a scrub handle, or an - - `pub fn on_field(mut self) -> Self`. A drag on the control's body scrubs while its text part does not take the pointer: a field that is not in -- `craft_ui::contract::SectionRhythm`: `pub enum SectionRhythm { Tight, Spaced }`. The room around the rule above a header ([`HeaderRegion::rule_above`]), as a `Section` has. An app sets it once at its + - `pub fn by_label(mut self) -> Self`. A drag on the control's side label scrubs, with or without the focus in the control; the label senses the drag from the pass after the control first declared it. + - `pub fn part(mut self, part: impl Into, drag: ValueDrag) -> Self`. A drag on the part `part` scrubs by `drag`, with or without the focus in the control: a scrub handle, or an opener whose drag moves the value as far as its popup's control would. + - `pub fn on_field(mut self) -> Self`. A drag on the control's body scrubs while its text part does not take the pointer: a field that is not in edit. +- `craft_ui::contract::SectionRhythm`: `pub enum SectionRhythm { Tight, Spaced }`. The room around the rule above a header ([`HeaderRegion::rule_above`]), as a `Section` has. - `craft_ui::contract::SelectMode`: `pub enum SelectMode { None, Single, Multi, Cells }`. What a collection lets the user select. - `craft_ui::contract::SetPosition`: re-export of `craft_ui::runtime::access::SetPosition`. -- `craft_ui::contract::SettleCx`: `pub struct SettleCx<'a>`. The body's memory after the real run: the same `Remember` access the body's context has, and the `Held` and +- `craft_ui::contract::SettleCx`: `pub struct SettleCx<'a>`. The body's memory after the real run: the same `Remember` access the body's context has, and the `Held` and `Bind` reads and writes that take it. - `craft_ui::contract::ShellPane`: `pub struct ShellPane { pub name: &'static str, pub edge: PaneEdge, pub extent: Option, pub at: Option }`. One of `AppShell`'s panes. - `pub const fn new(name: &'static str) -> Self`. The central pane named `name`. - `pub const fn edge(mut self, edge: PaneEdge) -> Self`. The pane at `edge`. - `pub const fn extent(mut self, extent: f32) -> Self`. The pane's size along its edge, exactly: the pane host shows it at this extent in every pass. - - `pub const fn at(mut self, rect: Rect) -> Self`. The pane in `rect`, which the caller laid out for this pass. The pane takes no room from its siblings. + - `pub const fn at(mut self, rect: Rect) -> Self`. The pane in `rect`, which the caller laid out for this pass. - `craft_ui::contract::ShownRow`: `pub struct ShownRow { pub key: K, pub id: egui::Id, pub rect: egui::Rect, pub cells: Vec<(ColumnKey, egui::Rect)>, pub openers: Vec<(crate::contract::ItemOpener, Response)>, pub hovered: bool }`. The geometry of one row the collection showed this pass. -- `craft_ui::contract::SideLabel`: `pub struct SideLabel { pub kind: LabelKind, pub layout: FieldLayout, pub role: FieldLabelRole, pub scrub: bool, pub reset_dot: bool, pub icon: Option>, pub detail: Option

`. What a component registers with `Pointer::window_drop_target`: a target over the whole window, optionally waiting +- `craft_ui::runtime::drag::OsFiles`: `pub struct OsFiles { pub files: Vec }`. The payload of a drag that comes from the OS: files held over the window, then the files dropped. +- `craft_ui::runtime::drag::WindowDropTarget`: `pub trait WindowDropTarget

`. What a component registers with `Pointer::window_drop_target`: a target over the whole window, optionally waiting for a pointer position before it accepts. - `type Drop`. What a drop on this target carries to the component's caller. - `fn requires_pointer(&self) -> bool`. Whether this target waits for a pointer position before taking a drop. - `fn accept(&self, payload: &P, op: DropOperation) -> Option`. `None` rejects. `op` is the operation the held modifiers pick, which a target may refuse. - `fn mark(&self, drop: &Self::Drop) -> DropMark`. Where `drop` would land, a value the ghost layer paints. - - `fn under_modal(&self) -> bool`. Whether the target takes OS file drops (`OsFiles`) while a modal layer holds input, as -- `craft_ui::runtime::drag::active`: `pub fn active(ctx: &Context) -> Option>`. The active drag payload of type `P`, from any viewport. For code without a `Cx`. -- `craft_ui::runtime::drag::amend`: `pub fn amend(ctx: &Context, change: impl FnOnce(&mut P)) -> bool`. Changes the running session's payload of type `P` (or its further payload of that type) with `change`, in the frame + - `fn under_modal(&self) -> bool`. Whether the target takes OS file drops (`OsFiles`) while a modal layer holds input, as [`DropTarget::under_modal`] says. +- `craft_ui::runtime::drag::active`: `pub fn active(ctx: &Context) -> Option>`. The active drag payload of type `P`, from any viewport. +- `craft_ui::runtime::drag::amend`: `pub fn amend(ctx: &Context, change: impl FnOnce(&mut P)) -> bool`. Changes the running session's payload of type `P` (or its further payload of that type) with `change`, in the frame the session started only: a host completes what a drag its component started carries with what only the host knows (a dock measures the panel a tab drag floats). - `craft_ui::runtime::drag::cancel`: `pub fn cancel(ctx: &Context, reason: CancelReason)`. Ends the session without a drop; the source's press ends with it, so nobody gets a drop. - `craft_ui::runtime::drag::mark`: `pub fn mark(ctx: &Context) -> Option`. The mark of the target that would take a drop now, in screen space: `None` while no target accepts the payload. -- `craft_ui::runtime::drag::zone_target`: `pub fn zone_target>(ui: &egui::Ui, owner: Id, zone: DropZone, target: &T) -> Option`. `Pointer::drop_target` over a zone the caller names instead of its own visible rect: the drop of a payload of type +- `craft_ui::runtime::drag::zone_target`: `pub fn zone_target>(ui: &egui::Ui, owner: Id, zone: DropZone, target: &T) -> Option`. `Pointer::drop_target` over a zone the caller names instead of its own visible rect: the drop of a payload of type `P` released over `zone`, with the same layer order, operation and mark as a component's own target. `owner` is the caller's stable id; it registers in every pass a drag may reach the zone. ## `craft_ui::runtime::edit` The pass's edit events and edit-command routing: the context-free calls an app makes around edits. -- `craft_ui::runtime::edit::PreviewWatch`: `pub struct PreviewWatch`. The preview watch of a component with a live preview, kept in its shown memory. When eviction drops an armed +- `craft_ui::runtime::edit::PreviewWatch`: `pub struct PreviewWatch`. The preview watch of a component with a live preview, kept in its shown memory. - `pub fn arm(&mut self, ctx: &Context, owner: Id)`. Arms the watch for the component `owner`. - `pub fn disarm(&mut self)`. Disarms the watch: its drop notes nothing. -- `craft_ui::runtime::edit::cancel_all`: `pub fn cancel_all(ctx: &Context, reason: CancelReason)`. Cancels every running gesture at its next step 4, which then stays cancelled under its press. The app's undo and -- `craft_ui::runtime::edit::gesture_note`: `pub fn gesture_note(ctx: &Context, id: Id) -> Option`. The note the component `id` set on its running gesture with [`Cx::propose_with`](crate::contract::Cx::propose_with), -- `craft_ui::runtime::edit::next_gesture_id`: `pub fn next_gesture_id(ctx: &Context) -> GestureId`. A gesture id no gesture of this context has had: ids grow in the order gestures begin, across components and -- `craft_ui::runtime::edit::watch_gestures`: `pub fn watch_gestures(ctx: &Context, body: impl FnOnce() -> R) -> (R, bool)`. Runs `body` and says whether a gesture of a component shown inside it was running after the component's apply +- `craft_ui::runtime::edit::cancel_all`: `pub fn cancel_all(ctx: &Context, reason: CancelReason)`. Cancels every running gesture at its next step 4, which then stays cancelled under its press. +- `craft_ui::runtime::edit::gesture_note`: `pub fn gesture_note(ctx: &Context, id: Id) -> Option`. The note the component `id` set on its running gesture with [`Cx::propose_with`](crate::contract::Cx::propose_with), when it is an `N`; `None` while no gesture of the component runs. `V` is the component's value type, under which its gesture is kept. +- `craft_ui::runtime::edit::next_gesture_id`: `pub fn next_gesture_id(ctx: &Context) -> GestureId`. A gesture id no gesture of this context has had: ids grow in the order gestures begin, across components and across a component's eviction, as `GestureHost` assumes. +- `craft_ui::runtime::edit::watch_gestures`: `pub fn watch_gestures(ctx: &Context, body: impl FnOnce() -> R) -> (R, bool)`. Runs `body` and says whether a gesture of a component shown inside it was running after the component's apply step: a drag or a typing run under way. + +## `craft_ui::runtime::egui` + +The one egui adapter: the only importer of egui's behavioural APIs. + +- `craft_ui::runtime::egui::LayerId`: re-export of `egui::LayerId` (outside these crates). ## `craft_ui::runtime::egui::access` -AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: the one place that names +AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: the one place that names AccessKit's node API. `node` writes a decided node, `patch` applies the label scope and the status node, `tree` reads a finished tree update, which automation keeps per viewport (`keep_trees`). - `craft_ui::runtime::egui::access::NodeId`: `pub type NodeId = accesskit::NodeId`. The AccessKit id of a node, as a host test holds it. -- `craft_ui::runtime::egui::access::bounds`: `pub fn bounds(ctx: &Context, id: Id) -> Option`. The rect `id`'s response had in the last finished pass, converted as the node's bounds are; `None` when absent, -- `craft_ui::runtime::egui::access::focused_node`: `pub fn focused_node(ctx: &Context) -> Option`. The node that held key focus at the end of the running viewport's last finished pass, the one reported to -- `craft_ui::runtime::egui::access::prune_controls`: `pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate)`. The step itself: every `controls` id of `update` that names no node of `update` is dropped. Other +- `craft_ui::runtime::egui::access::bounds`: `pub fn bounds(ctx: &Context, id: Id) -> Option`. The rect `id`'s response had in the last finished pass, converted as the node's bounds are; `None` when absent, without area, or behind the open modal. +- `craft_ui::runtime::egui::access::focused_node`: `pub fn focused_node(ctx: &Context) -> Option`. The node that held key focus at the end of the running viewport's last finished pass, the one reported to assistive technology: a focused part's node ([`sub_node_id`](crate::runtime::access::sub_node_id)), the shown item of a list that holds focus, else the focused component's own; `None` when nothing holds focus. +- `craft_ui::runtime::egui::access::prune_controls`: `pub fn prune_controls(update: &mut egui::accesskit::TreeUpdate)`. The step itself: every `controls` id of `update` that names no node of `update` is dropped. - `craft_ui::runtime::egui::access::AccessTree`: `pub struct AccessTree`. The AccessKit tree update of one frame. - `pub fn has(&self, id: Id) -> bool`. Whether the node of `id` exists. - `pub fn role(&self, id: Id) -> Option`. The role of the node of `id`. @@ -3885,7 +3904,7 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: - `pub fn live(&self, id: Id) -> Option`. The live politeness of the node of `id`. - `pub fn invalid(&self, id: Id) -> bool`. Whether the node of `id` is marked invalid. - `pub fn run_texts(&self, id: Id) -> Vec`. The text of each `TextRun` node below `id`, in order. - - `pub fn run_texts_of(&self, key: NodeKey) -> Vec`. The text of each `TextRun` node below the node `key`, in order: a text node's editable text, which its value + - `pub fn run_texts_of(&self, key: NodeKey) -> Vec`. The text of each `TextRun` node below the node `key`, in order: a text node's editable text, which its value may read with more (a number field's unit). - `pub fn text_selection(&self, id: Id) -> Option<((NodeKey, usize),(NodeKey, usize))>`. The selection of the text node `id` as the run node and character index of its anchor and focus. - `pub fn name_of(&self, key: NodeKey) -> Option<&str>`. The name of a node by key. - `pub fn toggled_of(&self, key: NodeKey) -> Option>`. The toggled state of a node by key. @@ -3899,7 +3918,7 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: - `pub fn parent_of_key(&self, key: NodeKey) -> Option`. [`AccessTree::parent_of`] for a node by key. - `pub fn root_key(&self) -> Option`. The root node, when the frame made a tree: where reading order starts. - `pub fn focused_key(&self) -> NodeKey`. The node AccessKit reports as focused. - - `pub fn in_ltr_axis(&self, key: NodeKey) -> bool`. Whether the node is, or lies inside, a component whose horizontal axis keeps its left-to-right order + - `pub fn in_ltr_axis(&self, key: NodeKey) -> bool`. Whether the node is, or lies inside, a component whose horizontal axis keeps its left-to-right order (`Props::ltr_axis`): it or an ancestor declares left-to-right text direction on a node that is not a text run, which only that declaration does. - `pub fn keys(&self) -> Vec`. Every node that assistive technology reports. - `pub fn node_count(&self) -> usize`. The number of nodes that assistive technology reports. - `pub fn role_of(&self, key: NodeKey) -> Option`. The role of a node by key. @@ -3915,7 +3934,7 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: - `pub fn of(id: Id) -> NodeKey`. The key of the node of `id`. - `craft_ui::runtime::egui::access::TreeUpdate`: re-export of `accesskit::TreeUpdate` (outside these crates). - `craft_ui::runtime::egui::access::is_interactive`: `pub fn is_interactive(tree: &AccessTree, key: NodeKey) -> bool`. Whether the node declares an action a user can take: focus, click or a value change. -- `craft_ui::runtime::egui::access::name`: `pub fn name(tree: &AccessTree, key: NodeKey) -> Option<&str>`. The accessible name of the node, when it has a non-empty one: its own, else the first non-empty name of the nodes +- `craft_ui::runtime::egui::access::name`: `pub fn name(tree: &AccessTree, key: NodeKey) -> Option<&str>`. The accessible name of the node, when it has a non-empty one: its own, else the first non-empty name of the nodes that label it (`labelled_by`). ## `craft_ui::runtime::egui::areas` @@ -3927,17 +3946,17 @@ AccessKit node building, `register_accesskit_parent` and `set_accesskit_focus`: ## `craft_ui::runtime::egui::injected` -Injected input: pointer moves, clicks, keys and text an automation client asks for, and the event builders +Injected input: pointer moves, clicks, keys and text an automation client asks for, and the event builders injected input and the trials' fixture share. - `craft_ui::runtime::egui::injected::InjectedFiles`: `pub struct InjectedFiles { pub paths: Vec, pub dropped: bool }`. Files an injected step hovers over a window, and whether the step after it drops them. -- `craft_ui::runtime::egui::injected::InjectedPointer`: `pub enum InjectedPointer { Down { button: PointerButton, at: Pos2, mods: Mods, pen: Option }, Move { at: Pos2, mods: Mods, pen: Option, rest: f64 }, Up { at: Pos2, mods: Mods } }`. One pointer step an automation client drives as a device would, with the modifiers held and, for a pen, its +- `craft_ui::runtime::egui::injected::InjectedPointer`: `pub enum InjectedPointer { Down { button: PointerButton, at: Pos2, mods: Mods, pen: Option }, Move { at: Pos2, mods: Mods, pen: Option, rest: f64 }, Up { at: Pos2, mods: Mods } }`. One pointer step an automation client drives as a device would, with the modifiers held and, for a pen, its reading, which the step's pass reads in place of the tablet's. - `pub const fn down(button: PointerButton, at: Pos2, mods: Mods, pen: Option) -> Self`. `button` goes down at `at` with `mods` held and the pen's reading `pen`. - `pub const fn move_to(at: Pos2, mods: Mods, pen: Option) -> Self`. The pointer moves to `at` with `mods` held and the pen's reading `pen`. - - `pub const fn move_resting(at: Pos2, mods: Mods, pen: Option, rest: f64) -> Self`. The pointer moves to `at` with `mods` held and the pen's reading `pen`, and the step counts as processed once + - `pub const fn move_resting(at: Pos2, mods: Mods, pen: Option, rest: f64) -> Self`. The pointer moves to `at` with `mods` held and the pen's reading `pen`, and the step counts as processed once the pointer has rested there `rest` seconds. - `pub const fn up(at: Pos2, mods: Mods) -> Self`. Every injected button comes up at `at` with `mods` held. - `craft_ui::runtime::egui::injected::Released`: `pub enum Released { Button(PointerButton), Key(Key), All }`. What a button or key release names: one button, one key, or everything held (the modifiers too). -- `craft_ui::runtime::egui::injected::hook_without_pass`: `pub fn hook_without_pass(ctx: &Context, viewport: ViewportId) -> Vec`. The input of one hook call for `viewport` with no pass behind it: the events the hook appends. Stands in for -- `craft_ui::runtime::egui::injected::move_focus_without_pass`: `pub fn move_focus_without_pass(ctx: &Context, viewport: ViewportId, id: Id)`. Moves the focus the end hook recorded for `viewport` to the component `id` with no pass, as the application does +- `craft_ui::runtime::egui::injected::hook_without_pass`: `pub fn hook_without_pass(ctx: &Context, viewport: ViewportId) -> Vec`. The input of one hook call for `viewport` with no pass behind it: the events the hook appends. +- `craft_ui::runtime::egui::injected::move_focus_without_pass`: `pub fn move_focus_without_pass(ctx: &Context, viewport: ViewportId, id: Id)`. Moves the focus the end hook recorded for `viewport` to the component `id` with no pass, as the application does between handing input over and its pass. ## `craft_ui::runtime::egui::input` @@ -3952,9 +3971,9 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `craft_ui::runtime::egui::screenshot::ScreenshotError`: `pub enum ScreenshotError { DimensionsOverflow { width: usize, height: usize }, MalformedImage { width: usize, height: usize, pixels: usize }, ImageTooLarge { bytes: usize, max_bytes: usize } }`. Why a completed screenshot was rejected and released. - `craft_ui::runtime::egui::screenshot::ScreenshotFacts`: `pub struct ScreenshotFacts { pub size_points: Vec2, pub pixels_per_point: f32, pub zoom: f32, pub max_texture_side: usize, pub minimized: bool }`. What a screenshot of one viewport measures this pass. -- `craft_ui::runtime::egui::screenshot::ScreenshotSlot`: `pub struct ScreenshotSlot`. The live request side of a screenshot. Keep it alive until the result is taken or the request is cancelled; +- `craft_ui::runtime::egui::screenshot::ScreenshotSlot`: `pub struct ScreenshotSlot`. The live request side of a screenshot. - `pub fn take(&self) -> Option, ScreenshotError>>`. Takes the completed result, at most once. - - `pub fn cancel(&self)`. Cancels the request and releases any completed image. A completion that published its result before this + - `pub fn cancel(&self)`. Cancels the request and releases any completed image. - `pub fn detached(ctx: &Context, viewport: ViewportId, max_image_bytes: usize) -> (Self, ScreenshotCallback)`. A slot with its callback and no command sent, for trials that stand in for the renderer. - `pub fn complete(&self, image: Arc)`. Completes the slot with `image` as the renderer would, without the callback. - `pub fn lock_is_free(&self) -> bool`. Whether the slot mutex is free, proving the wakeup runs after the lock was released. @@ -3970,22 +3989,22 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn today(&self) -> Option`. Today's date as the host supplied it with `RootEnv::today`; `None` when it gave none. - `pub fn units(&self) -> Units`. The scope's number format and unit words, to read and write numbers with their unit. - `pub fn relative_age(&self, seconds: u64, style: AgeStyle) -> String`. How long ago `seconds` was, in the scope's language and digits: "Just now", "3 minutes ago", "Yesterday". - - `pub fn of(ui: &Ui) -> Env`. The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui` - - `pub fn root_hit_reach(ctx: &Context) -> f32`. How far from a handle, point or edge a press still takes it, in screen points: the theme's `size.hit.target` as - - `pub fn get(&self) -> T`. A clone of the innermost app value, else `T::root()`. Large values hold an `Arc`. + - `pub fn of(ui: &Ui) -> Env`. The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui` of an egui `Area` or `Window` reads the app's root values. + - `pub fn root_hit_reach(ctx: &Context) -> f32`. How far from a handle, point or edge a press still takes it, in screen points: the theme's `size.hit.target` as the running viewport's root env has it. `ToolContext::reach` reads the same value; code with no tool context (a menu capture hit-testing a canvas point) reads it here. + - `pub fn get(&self) -> T`. A clone of the innermost app value, else `T::root()`. - `pub fn capture(&self) -> EnvCapture`. The inherited group only; layer-local fields start fresh where the capture is installed. - `pub fn view(&self) -> EnvView<'_>`. What component code sees of this env. - `pub fn folder(&self) -> Folder`. Folds text for search in the scope's language: case and accents ignored, dotted and dotless i by locale. - `pub fn collator(&self) -> Arc`. Orders text in the scope's language, with runs of digits by value (`Layer 2` before `Layer 10`). - `craft_ui::runtime::env::EnvCapture`: `pub struct EnvCapture`. The inherited group of an env, captured to open a popup or viewport: the layer-local fields are reset. -- `craft_ui::runtime::env::Inherited`: `pub struct Inherited { pub tokens: Arc, pub os: Os, pub active: bool, pub words: Arc, pub canvas_pattern: bool, pub line_ratio: f32, pub motion: MotionPolicy, pub scale: Scale, pub values: AppValues }`. The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's +- `craft_ui::runtime::env::Inherited`: `pub struct Inherited { pub tokens: Arc, pub os: Os, pub active: bool, pub words: Arc, pub canvas_pattern: bool, pub line_ratio: f32, pub motion: MotionPolicy, pub scale: Scale, pub values: AppValues }`. The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's values. `Scoped` reads them through `Deref`. - `craft_ui::runtime::env::Scoped`: `pub struct Scoped { pub ink: Ink, pub key: EnvKey, pub size: ControlSize, pub glyphs: GlyphRole, pub enabled: bool, pub read_only: bool, pub wheel: WheelScope, pub direction: Direction, pub text_direction: Direction, pub ids_stable: bool, pub arena: Option, pub transform: Option }`. The values of an env. - `pub fn hit_reach(&self) -> f32`. How far from a handle, point or edge a press still takes it, in screen points: the theme's `size.hit.target`. - - `pub fn layer_direction(&self) -> Direction`. The direction of a layer opened from this scope: the interface's (`text_direction`), which an axis that keeps + - `pub fn layer_direction(&self) -> Direction`. The direction of a layer opened from this scope: the interface's (`text_direction`), which an axis that keeps its left-to-right order (`Props::ltr_axis`) leaves alone. - `craft_ui::runtime::env::AgeStyle`: re-export of `craft_i18n::AgeStyle` (outside these crates). - `craft_ui::runtime::env::AltCodePages`: `pub struct AltCodePages { pub ansi: u16, pub oem: u16 }`. Code pages that decode Alt+numpad codes; the app sets them from the system locale. - `pub const fn new(ansi: u16, oem: u16) -> Self`. The ANSI and OEM code pages. -- `craft_ui::runtime::env::AppValues`: `pub struct AppValues`. The app values a root, a scope or a component's `content_env` carries: one entry per `EnvValue` type, the +- `craft_ui::runtime::env::AppValues`: `pub struct AppValues`. The app values a root, a scope or a component's `content_env` carries: one entry per `EnvValue` type, the innermost wins. - `pub fn set(&mut self, value: T) -> &mut Self`. Sets the value of type `T`. - `craft_ui::runtime::env::ArenaId`: `pub struct ArenaId(pub Id)`. The id of an arena, carried in `Env.arena`. - `pub const fn new(id: Id) -> Self`. The arena whose id is `id`. @@ -3994,20 +4013,20 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `craft_ui::runtime::env::ColumnSize`: `pub struct ColumnSize { pub width: f64, pub gutter: f64 }`. The column size of a document: `n` columns are `n·(width + gutter) − gutter` points. - `pub const fn new(width: f64, gutter: f64) -> Self`. The column size with columns `width` points wide `gutter` points apart. - `pub fn points(self, columns: f64, relative: bool) -> f64`. `columns` columns as points; a `relative` change converts the span of `|columns|` with its sign, and 0 stays 0. - - `pub fn columns(self, points: f64, relative: bool) -> f64`. `points` as columns; the inverse of [`points`](Self::points). + - `pub fn columns(self, points: f64, relative: bool) -> f64`. `points` as columns; the inverse of [`points`]. - `craft_ui::runtime::env::Count`: re-export of `craft_i18n::Count` (outside these crates). - `craft_ui::runtime::env::Counted`: re-export of `craft_i18n::Counted` (outside these crates). - `craft_ui::runtime::env::Direction`: re-export of `craft_i18n::Direction` (outside these crates). - `craft_ui::runtime::env::EnvValue`: re-export of `craft_ui_macros::EnvValue` (outside these crates). -- `craft_ui::runtime::env::EnvView`: `pub struct EnvView<'a>`. What component code sees: everything in `Env` except tokens, size, enabled, read-only, arena, transform - - `pub fn surface(&self) -> crate::style::SurfaceKind`. The surface the component sits on: the innermost container or collection surface that paints a fill, else the +- `craft_ui::runtime::env::EnvView`: `pub struct EnvView<'a>`. What component code sees: everything in `Env` except tokens, size, enabled, read-only, arena, transform and `ids_stable`. + - `pub fn surface(&self) -> crate::style::SurfaceKind`. The surface the component sits on: the innermost container or collection surface that paints a fill, else the window's background. - `pub fn direction(&self) -> Direction`. The flow direction: layout order, arrow keys and roving. - `pub fn text_direction(&self) -> Direction`. The paragraph direction of text, which only a scope that sets the interface's direction changes. - - `pub fn mode(&self) -> Mode`. The light or dark mode the scope's tokens are resolved in: the app's, or the one a scope with its own tokens + - `pub fn mode(&self) -> Mode`. The light or dark mode the scope's tokens are resolved in: the app's, or the one a scope with its own tokens set. - `pub fn motion(&self) -> MotionPolicy`. The motion mode in effect. - `pub fn canvas_pattern(&self) -> bool`. Whether the canvas surround shows the theme's pattern (`RootEnv::canvas_pattern`). - `pub fn scale(&self) -> Scale`. The pixels per point. - - `pub fn shell(&self) -> &'a ShellInfo`. The platform and the running viewport's window facts: the OS, the capabilities and the window's kind, + - `pub fn shell(&self) -> &'a ShellInfo`. The platform and the running viewport's window facts: the OS, the capabilities and the window's kind, chrome, state, insets and focus. - `pub fn keyboard_layout(&self) -> &'a craft_keymap::Layout`. The keyboard layout: which character each key position types, for text that names a key. - `pub fn host(&self) -> Option<&'a Arc>`. The app's `Host`, from `FrameInput.host`. - `pub fn get(&self) -> T`. A clone of the innermost app value, else `T::root()`. @@ -4018,28 +4037,28 @@ One-shot screenshot slots and the facts a screenshot is measured against. - `pub fn units(&self) -> Units`. The scope's number format and unit words, to read and write numbers with their unit. - `pub fn relative_age(&self, seconds: u64, style: AgeStyle) -> String`. How long ago `seconds` was, in the scope's language and digits: "Just now", "3 minutes ago", "Yesterday". - `pub fn counted(&self, count: Counted, n: u64) -> String`. `n` things by the count word `count`, in the scope's language and digits: "1 page", "3 pages". - - `pub fn resolve(&self, label: &Label) -> Label`. `label` with a `Word` replaced by its text in the scope's language: what domain code that draws a `Label` -- `craft_ui::runtime::env::Label`: `pub enum Label { Empty, Static(&'static str), Shared(Arc), Word(Word) }`. A label: a literal stays borrowed, a built string is shared. Cloning is cheap. + - `pub fn resolve(&self, label: &Label) -> Label`. `label` with a `Word` replaced by its text in the scope's language: what domain code that draws a `Label` itself shows. +- `craft_ui::runtime::env::Label`: `pub enum Label { Empty, Static(&'static str), Shared(Arc), Word(Word) }`. A label: a literal stays borrowed, a built string is shared. - `pub fn as_str(&self) -> &str`. The text of a label whose `Word` is not resolved yet reads as its English text. - `pub fn from_cow(text: Cow<'static, str>) -> Self`. The label of `text`: a borrowed text stays borrowed. -- `craft_ui::runtime::env::LengthUnits`: `pub struct LengthUnits { pub stored: UnitKind, pub shown: UnitKind, pub pixels_per_inch: f64, pub bare: Option }`. A length kept in one unit and shown in another: what a length field reads and writes (`stored`, the document's +- `craft_ui::runtime::env::LengthUnits`: `pub struct LengthUnits { pub stored: UnitKind, pub shown: UnitKind, pub pixels_per_inch: f64, pub bare: Option }`. A length kept in one unit and shown in another: what a length field reads and writes (`stored`, the document's unit) and what it shows and, unless `bare` names another unit, parses bare numbers in (`shown`, the user's unit). - `pub const fn new(stored: UnitKind, shown: UnitKind, pixels_per_inch: f64) -> Self`. A length kept in `stored` and shown in `shown`, with `pixels_per_inch` sizing pixels. - - `pub const fn bare_in(mut self, unit: UnitKind) -> Self`. A number typed without a unit is in `unit` rather than in the shown unit (a preference such as "numbers -- `craft_ui::runtime::env::Message`: `pub struct Message { pub text: Label, pub tone: Option }`. The text of a `Validity`: a label and an optional tone override. `Warn` defaults to `Tone::Warn`, `Refuse` to + - `pub const fn bare_in(mut self, unit: UnitKind) -> Self`. A number typed without a unit is in `unit` rather than in the shown unit (a preference such as "numbers without units are points"). +- `craft_ui::runtime::env::Message`: `pub struct Message { pub text: Label, pub tone: Option }`. The text of a `Validity`: a label and an optional tone override. `Warn` defaults to `Tone::Warn`, `Refuse` to `Tone::Bad`; `effective_tone` is the one place that default is decided. - `pub fn new(text: impl Into