diff --git a/crates/design-lint/src/contract/sites.rs b/crates/design-lint/src/contract/sites.rs index aab348a23..e2684c8a2 100644 --- a/crates/design-lint/src/contract/sites.rs +++ b/crates/design-lint/src/contract/sites.rs @@ -18,7 +18,8 @@ pub(crate) const EGUI_ROOTS: [&str; 7] = ["egui", "epaint", "emath", "ecolor", " #[derive(Debug, Default)] pub(crate) struct Args { pub count: usize, - /// Every identifier inside the arguments, nested ones included. + /// Every identifier inside the arguments, nested ones included, except inside a closure argument: its body is + /// read as sites of its own, so a call there does not count as an argument of this one. pub idents: Vec, /// Whether a numeric literal appears. pub has_literal: bool, @@ -140,9 +141,12 @@ fn args_of<'a>(args: impl IntoIterator) -> Args { let mut out = Args::default(); for e in args { out.count += 1; - out.has_closure |= matches!(e, Expr::Closure(_)); + let closure = matches!(e, Expr::Closure(_)); + out.has_closure |= closure; let tokens = e.to_token_stream(); - summarize(tokens.clone(), &mut out.idents); + if !closure { + summarize(tokens.clone(), &mut out.idents); + } out.has_literal |= has_number(tokens); } out diff --git a/crates/design-lint/tests/egui_rules.rs b/crates/design-lint/tests/egui_rules.rs index d4c1d9f2a..5b6bc5fe2 100644 --- a/crates/design-lint/tests/egui_rules.rs +++ b/crates/design-lint/tests/egui_rules.rs @@ -103,3 +103,11 @@ fn family_modules_neither_import_runtime_egui_nor_build_egui_text() { let shell = analyze_contract(&src, Path::new("crates/x/src/shell/app.rs"), &layered, false); assert!(shell.iter().all(|f| f.rule != "contract/runtime-egui"), "layer 7 hosts the adapter"); } + +#[test] +fn a_salt_inside_a_scope_closure_is_not_the_scope_builders() { + let inner = "fn f(ui: &mut Ui) {\n ui.scope_builder(UiBuilder::new().max_rect(r), |ui| Button::new(\"a\").id_salt(\"b\").show(ui));\n}\n"; + assert!(!rules_at(inner, "src/ui/a.rs", &scope()).contains(&"contract/memory")); + let salted = "fn f(ui: &mut Ui) {\n ui.scope_builder(UiBuilder::new().id_salt(\"b\"), |ui| ());\n}\n"; + assert!(rules_at(salted, "src/ui/a.rs", &scope()).contains(&"contract/memory")); +} diff --git a/crates/draw/src/ui/crop/session.rs b/crates/draw/src/ui/crop/session.rs index db5fd330f..46a934fb3 100644 --- a/crates/draw/src/ui/crop/session.rs +++ b/crates/draw/src/ui/crop/session.rs @@ -483,7 +483,7 @@ impl CropSession { /// The first frame edit from the hidden overlay, a ratio or size change or a Straighten press: /// the default frame shows again. - pub fn show(&mut self) { + pub fn show_frame(&mut self) { self.dismissed = None; } diff --git a/crates/draw/src/ui/crop/tool.rs b/crates/draw/src/ui/crop/tool.rs index 37ce2cdb6..34648ba72 100644 --- a/crates/draw/src/ui/crop/tool.rs +++ b/crates/draw/src/ui/crop/tool.rs @@ -284,7 +284,7 @@ impl CropTool { } if !edit.events.is_empty() { // The first edit of a hidden default frame draws a new frame. - self.session.show(); + self.session.show_frame(); } for event in edit.events { match &event { @@ -303,7 +303,7 @@ impl CropTool { if straightened.is_some() || straighten_ended { // The button was armed when the line began: a line made with Cmd alone turns the frame in place. let fit = self.session.straighten().armed(); - self.session.show(); + self.session.show_frame(); // A click with no line spends the armed button too. self.session.straighten_mut().disarm(); if let Some(angle) = straightened { @@ -367,7 +367,7 @@ impl CropTool { /// began with while `editing`, as one box step. Returns the frame's `Set` for the host's mirror, or /// `None` when nothing changed. In image mode the next pass turns the view with the frame. pub fn refit(&mut self, settings: &CropSettings, document: &CropDocument, units: &Units, editing: bool) -> Option { - self.session.show(); + self.session.show_frame(); let base = self.session.ratio_base(editing); self.end_nudges(); if self.dragging { @@ -429,7 +429,7 @@ impl CropTool { } let frame = self.session.frame()?; self.end_nudges(); - self.session.show(); + self.session.show_frame(); let event = self.session.set(frame, false, &self.step); self.synced = None; Some(CropEvent::Frame(event)) diff --git a/crates/draw/src/ui/gradient/fill_editor.rs b/crates/draw/src/ui/gradient/fill_editor.rs index 27ad231f2..cf6fc0e27 100644 --- a/crates/draw/src/ui/gradient/fill_editor.rs +++ b/crates/draw/src/ui/gradient/fill_editor.rs @@ -8,7 +8,7 @@ use craft_color::ui::gradient::{GradientEditor, GradientStops, StopColor, StopRe use craft_theme::Srgba; use craft_ui::buttons::Button; use craft_ui::choice::{Checkbox, Segmented}; -use craft_ui::contract::{Bind, Entry, Outcome, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Entry, Outcome, Props as _, Show as _, ShowContainer as _, clicked}; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; use craft_ui::patterns::presets::PresetState; @@ -206,7 +206,7 @@ impl<'a> GradientFillEditor<'a> { let align = Checkbox::new(Bind::given(now.align)).label(words.align.clone()).show(ui); absorb(&mut events, lift(align.events, &now, |fill, on| fill.align = on)); let reset = Button::new(words.reset_alignment.clone()).enabled(now.offset != kurbo::Vec2::ZERO).show(ui); - if reset.clicked() { + if clicked(&reset) { let mut centred = now.clone(); centred.offset = kurbo::Vec2::ZERO; events.push(EditEvent::set(Mixed::Same(now.clone()), centred, Arc::from(words.reset_alignment.as_str()), None)); diff --git a/crates/imaging/src/ui/adjust/panel.rs b/crates/imaging/src/ui/adjust/panel.rs index 686013465..cce9abba3 100644 --- a/crates/imaging/src/ui/adjust/panel.rs +++ b/crates/imaging/src/ui/adjust/panel.rs @@ -67,10 +67,8 @@ impl<'a> AdjustmentsPanel<'a> { let AdjustmentsPanel { label, kinds } = self; let env = Env::of(ui); let words = env.words::(); - // An icon button is square at the control height; the grid steps by the columns that fit the width given. - let side = env.tokens.tokens().size.control.md; let gap = BUTTON_GAP.points(ui); - let columns = (((ui.available_width() + gap) / (side + gap)).floor() as usize).clamp(1, kinds.len().max(1)); + let columns = ButtonGrid::columns(&StyleCx::of_env(ui.ctx(), &env), ui.available_width(), gap, kinds.len()); let mut picked = None; let shown = ButtonGrid::new(label, columns).show(ui, |ui, _| { for &kind in kinds { @@ -105,6 +103,13 @@ struct ButtonGrid { } impl ButtonGrid { + /// How many of `count` buttons fit across `width` with `gap` between them. An icon button is square at the + /// control height. + fn columns(cx: &StyleCx<'_>, width: f32, gap: f32, count: usize) -> usize { + let side = cx.tokens.size.control.md; + (((width + gap) / (side + gap)).floor() as usize).clamp(1, count.max(1)) + } + fn new(label: Label, columns: usize) -> Self { let props = ContainerProps::new() .pad(Pad::None) diff --git a/crates/imaging/src/ui/raw_develop/stories.rs b/crates/imaging/src/ui/raw_develop/stories.rs index 17f8a6b7a..ba2143f3e 100644 --- a/crates/imaging/src/ui/raw_develop/stories.rs +++ b/crates/imaging/src/ui/raw_develop/stories.rs @@ -12,8 +12,9 @@ use craft_ui::contract::{Bind, Role}; use craft_ui::dialog::{HostedWorkspace, stories::hosted}; use craft_ui::primitives::Revision; use craft_ui::runtime::pending::Job; +use craft_ui::testing::input::key_press; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; -use egui::{Color32, ColorImage, Event, Key, Modifiers, Ui}; +use egui::{Color32, ColorImage, Key, Modifiers, Ui}; use super::{ Demosaic, RawDevelopOpen, RawDevelopPanel, RawDevelopSource, RawDevelopWorkspace, RawFilmItem, RawFilmstrip, RawFloatingScope, RawPreviewRequest, @@ -141,8 +142,7 @@ fn smart_filter_with_edits(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { /// Y goes down and stays down: the workspace shows the picture before the settings. fn hold_before(fixture: &mut Fixture) { - let key = |pressed| Event::Key { key: Key::Y, physical_key: Some(Key::Y), pressed, repeat: false, modifiers: Modifiers::NONE }; - fixture.frame(vec![key(true)]); + fixture.frame(vec![key_press(Key::Y, Modifiers::NONE)]); } #[story(RawDevelopWorkspace, covers = [], drive = Drive::Custom(hold_before))] diff --git a/crates/imaging/src/ui/select/magnetic.rs b/crates/imaging/src/ui/select/magnetic.rs index f46b7a05b..bad19bebe 100644 --- a/crates/imaging/src/ui/select/magnetic.rs +++ b/crates/imaging/src/ui/select/magnetic.rs @@ -660,27 +660,3 @@ impl CanvasTool for SelectToolPass<'_, MagneticLassoTool> { fn close_radius(cx: &ToolContext<'_>, place: &Place) -> f64 { reach(cx).close / place.zoom().max(0.01) } - -#[cfg(test)] -mod tests { - - #[test] - fn width_steps_by_one_and_shift_jumps_to_the_limits() { - let mut settings = MagneticSettings { width: 10.4, ..MagneticSettings::default() }; - settings.step_width(1, false); - assert_eq!(settings.width, 11.0, "a step adds one to the rounded width"); - settings.width = 1.0; - settings.step_width(-1, false); - assert_eq!(settings.width, 1.0, "the step stops at the minimum"); - settings.width = 256.0; - settings.step_width(1, false); - assert_eq!(settings.width, 256.0, "the step stops at the maximum"); - settings.step_width(-1, true); - assert_eq!(settings.width, 1.0, "Shift+[ goes to the minimum"); - settings.step_width(1, true); - assert_eq!(settings.width, 256.0, "Shift+] goes to the maximum"); - settings.width = f32::NAN; - settings.step_width(1, false); - assert_eq!(settings.width, MagneticSettings::default().width, "a width that is no number goes back to the default"); - } -} diff --git a/crates/imaging/src/ui/select_mask/mod.rs b/crates/imaging/src/ui/select_mask/mod.rs index ca1888db8..b2079f213 100644 --- a/crates/imaging/src/ui/select_mask/mod.rs +++ b/crates/imaging/src/ui/select_mask/mod.rs @@ -487,7 +487,7 @@ impl SelectMaskWorkspace { let common = env.words::(); let title = FullWindowTitle::new(words.name.clone()).subject(self.subject.clone()).zoom(self.zoom_percent).label(&env); let slots = SelectMaskTool::slots(); - self.begin_pass(ui.ctx()); + self.start_pass(ui.ctx()); let request = self.request_now(); let key = format!("{request:?}"); let reset = Cell::new(false); @@ -665,7 +665,7 @@ impl SelectMaskWorkspace { /// The start of a pass: the first pass reads the stored settings, a change the app made to the settings since the /// last pass reaches the view and the refinement values, and the edits `perform` recorded are reported. - fn begin_pass(&mut self, ctx: &Context) { + fn start_pass(&mut self, ctx: &Context) { if !std::mem::replace(&mut self.recalled, true) && let Some(key) = &self.remember { diff --git a/crates/imaging/src/ui/warp/cylinder.rs b/crates/imaging/src/ui/warp/cylinder.rs index fc612dfbe..6cb4df3c1 100644 --- a/crates/imaging/src/ui/warp/cylinder.rs +++ b/crates/imaging/src/ui/warp/cylinder.rs @@ -119,7 +119,7 @@ impl CylinderValues { /// silhouettes and the edges keep their order (a moved one stops 1 unit short of the other) and a depth stays /// within the half axis, or within its own reach when it already lies past that (a cylinder read from a file). A /// drag by nothing changes nothing. - fn dragged(self, handle: CylinderHandle, by: DocVec) -> Self { + fn moved(self, handle: CylinderHandle, by: DocVec) -> Self { let mut v = self; let a = ((self.right - self.left) / 2.0).max(MIN_SIDE / 2.0); match handle { @@ -288,7 +288,7 @@ impl<'a> CylinderWarp<'a> { held.began = true; *cx.press_slot::() = Some(held.clone()); } - cx.propose(held.values.dragged(held.handle, view.to_doc(pos) - held.origin)); + cx.propose(held.values.moved(held.handle, view.to_doc(pos) - held.origin)); } PressPhase::Release { .. } => { if cx.press_slot::().take().is_some_and(|held| held.began) { @@ -310,7 +310,7 @@ impl<'a> CylinderWarp<'a> { let Some(handle) = focused else { return }; if let Some((direction, mods)) = cx.intents().take_nudge() { let step = if mods.shift { NUDGE_FAR } else { NUDGE }; - cx.set(values.dragged(handle, space.view.unmap_vec(direction) * step)); + cx.set(values.moved(handle, space.view.unmap_vec(direction) * step)); } } } diff --git a/crates/imaging/tests/it/select.rs b/crates/imaging/tests/it/select.rs index 1c73f777c..b3a0e3bc0 100644 --- a/crates/imaging/tests/it/select.rs +++ b/crates/imaging/tests/it/select.rs @@ -4,8 +4,8 @@ use craft_behavior::geometry::{Constraint, SelectionOperation, SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::{Axis, CancelReason, EditEvent, PixelSize, PointerButton}; use craft_imaging::ui::select::{ - DragKind, EdgeSearch, EdgeTracer, LassoTool, MagneticLassoTool, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectPhase, - SelectToolPass, SelectionDrag, SelectionProbe, SelectionShape, + DragKind, EdgeSearch, EdgeTracer, LassoTool, MagneticLassoTool, MagneticSettings, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, + SelectPhase, SelectToolPass, SelectionDrag, SelectionProbe, SelectionShape, }; use craft_keymap::{Mods, Platform}; use craft_ui::canvas::{CanvasTool, Snap, ToolAccess, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer}; @@ -910,3 +910,24 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() { assert_eq!(circle, caps_lock, "Caps Lock {caps_lock}: {cursor:?}"); } } + +#[trial] +fn width_steps_by_one_and_shift_jumps_to_the_limits() { + let mut settings = MagneticSettings::default(); + settings.width = 10.4; + settings.step_width(1, false); + assert_eq!(settings.width, 11.0, "a step adds one to the rounded width"); + settings.width = 1.0; + settings.step_width(-1, false); + assert_eq!(settings.width, 1.0, "the step stops at the minimum"); + settings.width = 256.0; + settings.step_width(1, false); + assert_eq!(settings.width, 256.0, "the step stops at the maximum"); + settings.step_width(-1, true); + assert_eq!(settings.width, 1.0, "Shift+[ goes to the minimum"); + settings.step_width(1, true); + assert_eq!(settings.width, 256.0, "Shift+] goes to the maximum"); + settings.width = f32::NAN; + settings.step_width(1, false); + assert_eq!(settings.width, MagneticSettings::default().width, "a width that is no number goes back to the default"); +} diff --git a/crates/layers/src/ui/comps/body.rs b/crates/layers/src/ui/comps/body.rs index fe2cd9427..50e54d466 100644 --- a/crates/layers/src/ui/comps/body.rs +++ b/crates/layers/src/ui/comps/body.rs @@ -277,9 +277,9 @@ pub(super) fn show_list(ui: &mut Ui, stack: &mut BodyCx<'_>, selected: &RefCell< if let Some(comp) = comp_at(cx.comps, item.at) && !comp.comment.is_empty() { - let comment: &str = &comp.comment; + let comment = comp.comment.clone(); item.tip(move |ui| { - ui.label(comment); + let _ = Text::new(comment).show(ui); }); } build_row(cx, item.at) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index a6935ed01..be3dac329 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -57,7 +57,6 @@ pub use raster::{DetailPlan, Extent, RasterDisplay, RasterDisplayOutput, RasterS mod opacity_keys; mod snap; pub use opacity_keys::OpacityDigit; -pub(crate) use rulers::LABEL_STEP_MIN; pub use rulers::{NUDGE, NUDGE_FAR}; pub use snap::{GestureSnap, Snap, canvas_snap, snap_suspended, snap_tolerance}; pub(crate) use space::context_menu; @@ -81,7 +80,9 @@ pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view}; mod rulers; mod scrollbars; -pub use rulers::{INCH_EIGHTHS, INCH_SIXTEENTHS, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, RulersOutput, StepLadder, TickRule}; +pub use rulers::{ + INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, RulersOutput, StepLadder, TickRule, +}; pub use scrollbars::{CanvasScrollbars, CanvasScrollbarsOutput}; // canvas-navigator-a @@ -113,7 +114,7 @@ use craft_behavior::{ CanvasTransform, CanvasView, EditEvent, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PointerButton, PressPhase, PressState, Sense, WheelNotch, }; -use egui::{Pos2, Rect, Response, Shape, Vec2}; +use egui::{Pos2, Rect, Response, Vec2}; use zoom_motion::{Steer, ViewMotion}; pub(crate) const BACKGROUND: PartKey = PartKey::new("background"); @@ -203,7 +204,7 @@ pub struct Canvas<'a> { #[prop(name = "view_follows_pointer")] follows_pointer: bool, /// The slot the body's paint reserved for the picture, published in the [`CanvasSpace`]; none in a measuring pass. - picture: Option, + picture: Option, } /// A canvas's view in one pass. @@ -549,10 +550,8 @@ impl Component for Canvas<'_> { } /// Reserves the slot the picture paints into, under every canvas control of the body (`CanvasSpace::paint_picture`). - fn paint(&mut self, _ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { - let layer = cx.response.layer_id; - let idx = cx.core.ctx.graphics_mut(|graphics| graphics.entry(layer).add(cx.content_rect, Shape::Noop)); - self.picture = Some(space::PictureSlot { layer, idx }); + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + self.picture = Some(ui.reserve_slot(cx.content_rect)); } /// The view of this pass, kept for the body and `finish`. diff --git a/crates/ui-canvas/src/canvas/raster/mod.rs b/crates/ui-canvas/src/canvas/raster/mod.rs index 090355157..5fc64edce 100644 --- a/crates/ui-canvas/src/canvas/raster/mod.rs +++ b/crates/ui-canvas/src/canvas/raster/mod.rs @@ -24,7 +24,8 @@ use super::{AppPaint, PixelRect, RasterSource, canvas_space}; use crate::contract::{Access, Common, Component, Cx, NoValue, Outcome, PaintUi, Props as _, Role}; use crate::primitives::textures::UNTINTED; use crate::primitives::{ - CachedTexture, Checker, CheckerArea, Draw, Revision, RuleKind, TextureState, TextureStore, TextureStoreOptions, texture_factor, texture_side, + CachedTexture, Checker, CheckerArea, Draw, PaintSlot, Revision, RuleKind, TextureState, TextureStore, TextureStoreOptions, texture_factor, + texture_side, }; use crate::runtime::env::Label; use crate::runtime::memory::Remember as _; @@ -34,7 +35,6 @@ use craft_behavior::kurbo::{Point as Point64, Rect as Rect64}; use craft_behavior::{CanvasView, Metrics, PixelSize}; use detail::{texel_extent, texel_origin}; use egui::epaint::{Mesh, Vertex}; -use egui::layers::ShapeIdx; use egui::{Color32, ColorImage, Context, Id, Pos2, Response, Shape, TextureFilter, TextureOptions, Vec2, pos2}; use std::collections::HashMap; use std::ops::RangeInclusive; @@ -515,7 +515,7 @@ impl Component for RasterDisplay<'_> { // slot at the end, in show order with every other picture. Outside a canvas, or in a space with no slot, it // paints in place. let space = canvas_space(&cx.env); - let first = (self.under_controls && space.and_then(|space| space.picture_slot()).is_some()).then(|| painter.painter.add(Shape::Noop)); + let first = (self.under_controls && space.and_then(|space| space.picture_slot()).is_some()).then(|| PaintSlot::reserve(&painter.painter)); // The picture's area on screen: the document, or the mapped area. A mapped area with nothing of the unit // square in it has no checkerboard and no edge. let corners = match &self.mapping { @@ -568,18 +568,8 @@ impl Component for RasterDisplay<'_> { painter.with_draw(|draw| edge(draw, corners)); } if let (Some(first), Some(space)) = (first, space) { - let last = painter.painter.add(Shape::Noop); - let (ctx, layer) = (painter.painter.ctx().clone(), painter.painter.layer_id()); - let shapes: Vec = ctx.graphics_mut(|layers| { - let list = layers.entry(layer); - (first.0 + 1..last.0) - .map(|at| { - let mut taken = Shape::Noop; - list.mutate_shape(ShapeIdx(at), |clipped| std::mem::swap(&mut clipped.shape, &mut taken)); - taken - }) - .collect() - }); + let ctx = painter.painter.ctx().clone(); + let shapes = first.take_after(&ctx); space.paint_picture(&ctx, shapes); } } diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index 723fca895..e4c1f20c7 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -6,9 +6,8 @@ mod stories; mod ticks; -pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, RulerTick, StepLadder, TickRule}; +pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; -pub(crate) use self::ticks::LABEL_STEP_MIN; use super::words::CanvasWords; use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, canvas_snap, canvas_space, context_menu, readout}; use crate::contract::overlay::Anchor; diff --git a/crates/ui-canvas/src/canvas/rulers/ticks.rs b/crates/ui-canvas/src/canvas/rulers/ticks.rs index 055df4051..b51d2f64f 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks.rs +++ b/crates/ui-canvas/src/canvas/rulers/ticks.rs @@ -10,7 +10,7 @@ pub const INCH_SIXTEENTHS: [u32; 4] = [16, 8, 4, 2]; pub const INCH_EIGHTHS: [u32; 3] = [8, 4, 2]; /// The least distance between labelled ticks, in points. -pub(crate) const LABEL_STEP_MIN: f32 = 60.0; +pub const LABEL_STEP_MIN: f32 = 60.0; /// The metric rule's subdivisions of a labelled step. const METRIC_SUBDIVISIONS: f32 = 10.0; @@ -141,6 +141,3 @@ pub fn ticks(units: &RulerUnits, rule: TickRule<'_>, zoom: f64, values: RangeInc }) .collect() } - -#[cfg(test)] -mod tests; diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index d05d63299..050c7a677 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -7,6 +7,7 @@ use super::PasteboardColor; use crate::contract::{Component, Cx, Focus as _, Pointer as _}; +use crate::primitives::PaintSlot; use crate::runtime::env::{AppValues, EnvValue, EnvView, UnitKind, Units}; use craft_behavior::canvas::zoom; use craft_behavior::kurbo::{Point, Size}; @@ -38,16 +39,7 @@ pub struct CanvasSpace { precise: bool, /// The canvas's picture slot for this pass, which [`paint_picture`](Self::paint_picture) appends to; `None` in a /// measuring pass. - picture: Option, -} - -/// The shape the canvas reserved in its paint hook for the picture: its layer and index, which -/// [`CanvasSpace::paint_picture`] grows into a `Shape::Vec` in show order. The space is `Copy` and holds no painter, -/// so the slot is named by these two. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(crate) struct PictureSlot { - pub(crate) layer: egui::LayerId, - pub(crate) idx: egui::layers::ShapeIdx, + picture: Option, } impl CanvasSpace { @@ -159,33 +151,21 @@ impl CanvasSpace { /// context because the space holds none. Outside a canvas's paint (a measuring pass) there is no slot, and it /// paints nothing. pub fn paint_picture(&self, ctx: &egui::Context, shapes: Vec) { - let Some(slot) = self.picture else { return }; - if shapes.is_empty() { - return; + if let Some(slot) = self.picture { + slot.extend(ctx, shapes); } - ctx.graphics_mut(|layers| { - layers.entry(slot.layer).mutate_shape(slot.idx, |clipped| { - if let egui::Shape::Vec(list) = &mut clipped.shape { - list.extend(shapes); - return; - } - let reserved = std::mem::replace(&mut clipped.shape, egui::Shape::Noop); - let list = if matches!(reserved, egui::Shape::Noop) { shapes } else { std::iter::once(reserved).chain(shapes).collect() }; - clipped.shape = egui::Shape::Vec(list); - }); - }); } /// This space with the canvas's picture slot of this pass. #[must_use] - pub(crate) fn with_picture(mut self, slot: PictureSlot) -> Self { + pub(crate) fn with_picture(mut self, slot: PaintSlot) -> Self { self.picture = Some(slot); self } /// The slot the canvas reserved this pass, `None` before its paint step ran or outside a canvas: a display that /// paints under the controls paints in place without one. - pub(crate) fn picture_slot(&self) -> Option { + pub(crate) fn picture_slot(&self) -> Option { self.picture } diff --git a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs index ea334db74..86f9aab7a 100644 --- a/crates/ui-canvas/src/canvas/testing/tool_fixture.rs +++ b/crates/ui-canvas/src/canvas/testing/tool_fixture.rs @@ -22,7 +22,7 @@ const ESCAPE_DRAG_START: Vec2 = Vec2::new(0.25, 0.25); /// The id a [`ToolFixture`] gives its canvas labelled `label`: what a body hands to a control keyed by its canvas /// ([`Guides::new`](crate::canvas_controls::Guides::new)), as an app names its own canvas. pub fn canvas_id(label: &'static str) -> Id { - Id::unique(("tool fixture canvas", label)) + crate::runtime::memory::unique(("tool fixture canvas", label)) } /// A tool shown on a canvas that fills the fixture's room, with the gesture phases the host reported. diff --git a/crates/ui-canvas/src/canvas_controls/brush/stories.rs b/crates/ui-canvas/src/canvas_controls/brush/stories.rs index ae3fe8a01..6130826b0 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/stories.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/stories.rs @@ -17,8 +17,7 @@ use crate::testing::{Drive, StoryData, StoryOutput, story}; use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2}; use craft_behavior::{CancelReason, CanvasView, Cursor, PaintedCursor, PointerButton}; use craft_keymap::Mods; -use egui::{Id, Rect, Ui}; -use std::sync::{Arc, Mutex, PoisonError}; +use egui::{Rect, Ui}; /// The zoom, in percent of one device pixel per document pixel. const ZOOM: f64 = 400.0; @@ -66,25 +65,24 @@ fn stamped(y: f64) -> CoverageMask { } /// The footprint of one tone. The mask is kept across passes (stamped once), so the trail uploads only what changed. -fn footprint_of(ui: &mut Ui, name: &'static str, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { - let kept = ui.data_mut(|data| data.get_temp_mut_or_insert_with(Id::unique(("footprint", name)), || Arc::new(Mutex::new(stamped(y)))).clone()); - let mut mask = kept.lock().unwrap_or_else(PoisonError::into_inner); - on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, &mut mask).tone(tone).show_at(ui, rect)) +fn footprint_of(ui: &mut Ui, data: &mut StoryData, label: &'static str, tone: TrailTone, y: f64) -> StoryOutput { + let mask = data.note::>("footprint", None).get_or_insert_with(|| stamped(y)); + on_canvas_view(ui, brush_view, Some(&StoryDocument::STANDARD), |ui, rect, _| StrokeTrail::new(label, mask).tone(tone).show_at(ui, rect)) } #[story(StrokeTrail<'static>, covers = [Default])] -fn footprint_light(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - footprint_of(ui, "light", "Light footprint", TrailTone::Light, 100.0) +fn footprint_light(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + footprint_of(ui, data, "Light footprint", TrailTone::Light, 100.0) } #[story(StrokeTrail<'static>, covers = [Default])] -fn footprint_shade(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - footprint_of(ui, "shade", "Shade footprint", TrailTone::Shade, 100.0) +fn footprint_shade(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + footprint_of(ui, data, "Shade footprint", TrailTone::Shade, 100.0) } #[story(StrokeTrail<'static>, covers = [Default])] -fn footprint_danger(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - footprint_of(ui, "danger", "Danger footprint", TrailTone::Danger, 100.0) +fn footprint_danger(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + footprint_of(ui, data, "Danger footprint", TrailTone::Danger, 100.0) } #[story(SourceMarker, covers = [Default])] diff --git a/crates/ui-canvas/tests/it/canvas/mod.rs b/crates/ui-canvas/tests/it/canvas/mod.rs index dc8238b8a..315dbd878 100644 --- a/crates/ui-canvas/tests/it/canvas/mod.rs +++ b/crates/ui-canvas/tests/it/canvas/mod.rs @@ -14,6 +14,8 @@ mod pasteboard; mod raster; +mod rulers; + mod scrollbars; mod snap; diff --git a/crates/ui-canvas/src/canvas/rulers/ticks/tests.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs similarity index 83% rename from crates/ui-canvas/src/canvas/rulers/ticks/tests.rs rename to crates/ui-canvas/tests/it/canvas/rulers.rs index bc37ef427..94f564452 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks/tests.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -1,6 +1,9 @@ -use super::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, StepLadder, TickRule, ticks}; -use crate::primitives::TickRank; +//! The ruler tick rule (`Rulers::ticks`): labelled ticks stay at least `LABEL_STEP_MIN` apart at every zoom. + use craft_behavior::{RulerUnits, Ticks}; +use craft_ui::canvas::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, Rulers, StepLadder, TickRule}; +use craft_ui::primitives::TickRank; +use craft_ui::testing::trial; /// Screen points per document unit, from far out to deep in. const ZOOMS: [f64; 10] = [0.01, 0.0625, 0.25, 1.0 / 3.0, 1.0, 3.7, 16.0, 64.0, 320.0, 3200.0]; @@ -8,7 +11,7 @@ const ZOOMS: [f64; 10] = [0.01, 0.0625, 0.25, 1.0 / 3.0, 1.0, 3.7, 16.0, 64.0, 3 /// The least distance in points between two consecutive labelled ticks of `rule` at `zoom`, over a ruler 2000 points /// long. fn least_label_gap(units: &RulerUnits, rule: TickRule<'_>, zoom: f64) -> f64 { - let labelled: Vec = ticks(units, rule, zoom, 0.0..=2000.0 / zoom * units.per_doc) + let labelled: Vec = Rulers::ticks(units, rule, zoom, 0.0..=2000.0 / zoom * units.per_doc) .into_iter() .filter(|tick| tick.rank == TickRank::Major) .map(|tick| tick.value) @@ -17,7 +20,7 @@ fn least_label_gap(units: &RulerUnits, rule: TickRule<'_>, zoom: f64) -> f64 { labelled.windows(2).map(|pair| (pair[1] - pair[0]) / units.per_doc * zoom).fold(f64::INFINITY, f64::min) } -#[test] +#[trial] fn labelled_ticks_never_touch_at_any_zoom() { let pixels = RulerUnits::pixels(); let centimetres = RulerUnits::new(2.54 / 72.0, Ticks::decimal(false)); diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 5b8435859..2712ffe9c 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -7,7 +7,7 @@ use super::{ContentPainter, Cx, Show, TipFn}; use super::{InsideLabel, SideLabel}; use crate::primitives::sensing::PartResults; use crate::primitives::text_adapter; -use crate::primitives::{ContentPainterCx, DataMode, Draw, DrawEnv, PaintRecord, TextRun}; +use crate::primitives::{ContentPainterCx, DataMode, Draw, DrawEnv, PaintRecord, PaintSlot, TextRun}; use crate::runtime::access; use crate::runtime::egui::{alloc, child}; use crate::runtime::env::{Env, Label}; @@ -244,6 +244,12 @@ impl PaintUi<'_> { own.faces.push(record); } + /// Reserves an empty shape at the end of the component's layer, clipped to `clip`, for shapes added later by code + /// that holds no painter (`PaintSlot::extend`). + pub fn reserve_slot(&self, clip: Rect) -> PaintSlot { + PaintSlot::reserve_on(self.ui.ctx(), self.response.layer_id, clip) + } + /// The raw painter for an allowlisted content painter, clipped to the component's own rect. Its data paths paint /// data colours as [`draw`](Self::draw) does. pub fn content_painter(&self, cx: &Cx<'_, C>) -> ContentPainterCx<'_> { diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index ea4d25800..2328d5aa6 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -3,10 +3,11 @@ use crate::contract::Pointer as _; use crate::contract::cx::CxCore; use crate::primitives::{FocusKind, FocusRing, PaintShape, StateLayer, StateLayerKind, surface_look_shapes}; +use crate::runtime::egui::areas::Layer; use crate::runtime::env::{Env, EnvValue}; use crate::style::{Ink, StateSet, StyleView, surface_style}; use craft_theme::Opacity; -use egui::{Color32, LayerId, Shape, Ui}; +use egui::{Color32, Shape, Ui}; /// The ink the surface reads in: the surface kind of the state, else `inherited`. pub(crate) fn surface_ink(look: Option<&crate::style::SurfaceLook>, state: &StateSet, inherited: Ink) -> Ink { @@ -16,7 +17,7 @@ pub(crate) fn surface_ink(look: Option<&crate::style::SurfaceLook>, state: &Stat /// Where a faded component's shapes start in its layer's paint list, and the ground its veil takes. #[derive(Clone, Copy)] pub(crate) struct Fade { - layer: LayerId, + layer: Layer, from: usize, ground: Color32, /// The component lies under the veil of a faded owner that shows it from its paint: it paints its enabled look @@ -27,7 +28,7 @@ pub(crate) struct Fade { /// The layer whose open veil the components shown here lie under: set by `PaintUi` for the children a faded /// component shows while its paint runs, which its veil covers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct UnderVeil(pub Option); +pub(crate) struct UnderVeil(pub Option); impl EnvValue for UnderVeil { fn root() -> Self { diff --git a/crates/ui-contract/src/primitives/content.rs b/crates/ui-contract/src/primitives/content.rs index 09832990f..cd13babcf 100644 --- a/crates/ui-contract/src/primitives/content.rs +++ b/crates/ui-contract/src/primitives/content.rs @@ -8,7 +8,6 @@ use crate::runtime::egui::text_layout; use crate::runtime::env::Env; use crate::style::{DataColor, Ink, StyleCx, UiTokens, ink_color}; use craft_i18n::Direction; -use craft_theme::Variant; use egui::epaint::text::{FontId, TextDirection}; use egui::text::{LayoutJob, TextFormat}; use egui::{Color32, Context, FontFamily, Painter, Stroke}; @@ -55,20 +54,7 @@ impl<'a> ContentPainterCx<'a> { /// it draws the face of. #[doc(hidden)] pub fn style_cx(&self) -> StyleCx<'_> { - let env = self.env; - StyleCx::new( - self.painter.ctx(), - &env.tokens, - &env.values, - env.size, - Variant::SECONDARY, - env.direction, - env.scale, - env.os, - env.active, - env.key, - env.line_ratio, - ) + StyleCx::of_env(self.painter.ctx(), self.env) } /// Runs `paint` with a `Draw` over this painter, in the scope's tokens and direction. diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 028534f9f..c633c2674 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -12,6 +12,7 @@ mod icon; mod ime_surface; mod kit; mod marker; +mod paint_slot; pub(crate) mod pointer_art; mod record; mod reset_mark; @@ -43,6 +44,7 @@ pub use kit::{ fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, }; pub use marker::{Marker, MarkerSize}; +pub use paint_slot::PaintSlot; pub use reset_mark::ResetMark; pub use rule::{RectSide, Rule, RuleKind}; pub use scroll_bar::{HiddenContent, ScrollBar}; diff --git a/crates/ui-contract/src/primitives/paint_slot.rs b/crates/ui-contract/src/primitives/paint_slot.rs new file mode 100644 index 000000000..86de4de1a --- /dev/null +++ b/crates/ui-contract/src/primitives/paint_slot.rs @@ -0,0 +1,58 @@ +//! `PaintSlot`: a place in a layer's paint list, reserved while a component paints and filled or read later by code +//! that holds no painter. + +use crate::runtime::egui::areas::Layer; +use egui::layers::ShapeIdx; +use egui::{Context, Painter, Rect, Shape}; + +/// An empty shape reserved in a layer's paint list. Shapes added to it later paint at its place in the paint order; +/// shapes painted on the layer after it can be taken out to move them elsewhere. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PaintSlot { + layer: Layer, + idx: ShapeIdx, +} + +impl PaintSlot { + /// Reserves an empty shape at the end of `painter`'s layer, clipped like the painter. + pub fn reserve(painter: &Painter) -> Self { + PaintSlot { layer: painter.layer_id(), idx: painter.add(Shape::Noop) } + } + + /// Reserves an empty shape at the end of `layer`, clipped to `clip`. + pub(crate) fn reserve_on(ctx: &Context, layer: Layer, clip: Rect) -> Self { + PaintSlot { layer, idx: ctx.graphics_mut(|graphics| graphics.entry(layer).add(clip, Shape::Noop)) } + } + + /// Adds `shapes` to the slot, after the shapes it holds, keeping the slot's clip. + pub fn extend(self, ctx: &Context, shapes: Vec) { + if shapes.is_empty() { + return; + } + ctx.graphics_mut(|graphics| { + graphics.entry(self.layer).mutate_shape(self.idx, |clipped| { + if let Shape::Vec(list) = &mut clipped.shape { + list.extend(shapes); + return; + } + let reserved = std::mem::replace(&mut clipped.shape, Shape::Noop); + let list = if matches!(reserved, Shape::Noop) { shapes } else { std::iter::once(reserved).chain(shapes).collect() }; + clipped.shape = Shape::Vec(list); + }); + }); + } + + /// Takes the shapes painted on the slot's layer after it, in paint order, leaving empty shapes in their places. + pub fn take_after(self, ctx: &Context) -> Vec { + ctx.graphics_mut(|graphics| { + let list = graphics.entry(self.layer); + (self.idx.0 + 1..list.next_idx().0) + .map(|at| { + let mut taken = Shape::Noop; + list.mutate_shape(ShapeIdx(at), |clipped| std::mem::swap(&mut clipped.shape, &mut taken)); + taken + }) + .collect() + }) + } +} diff --git a/crates/ui-contract/src/primitives/pointer_art.rs b/crates/ui-contract/src/primitives/pointer_art.rs index d605c94de..b65d2083f 100644 --- a/crates/ui-contract/src/primitives/pointer_art.rs +++ b/crates/ui-contract/src/primitives/pointer_art.rs @@ -319,6 +319,7 @@ pub(crate) fn type_on(pen: &Pen, path: bool) { .collect() }; let dot = |centre: Vec2, grow: f32, color: Color32| { + // design: allow[literal-size/vec2](pointer art is a fixed bitmap-like drawing around the hotspot, not a layout size) pen.push(Mark::Block(Rect::from_center_size(centre.to_pos2(), Vec2::splat(DOT_SIDE)).expand(grow), 0.0, color)); }; // The dots' halos go under the beam and their fills over it, so a dot on the stem stays whole. @@ -333,6 +334,7 @@ pub(crate) fn type_on(pen: &Pen, path: bool) { /// The locator: a square frame centred on the pointer between halo frames a hairline outside and inside it. pub(crate) fn locator(pen: &Pen) { + // design: allow[literal-size/vec2](pointer art is a fixed bitmap-like drawing around the hotspot, not a layout size) let rect = Rect::from_center_size(Pos2::ZERO, Vec2::splat(LOCATOR_SIDE)); let halo = Stroke::new(pen.thin, pen.halo); pen.push(Mark::Frame(rect.expand(pen.thin), halo)); diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index cb6135c78..dfb88a100 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -327,19 +327,6 @@ fn arrows_from_end(ctx: &Context, widget: Id, len: usize) { } } -/// Removes this pass's Tab and Shift+Tab presses from the input events; returns whether there was one. A Tab with -/// Ctrl, Cmd or Alt is the window's, not the field's, and stays. -fn take_tab(ctx: &Context) -> bool { - ctx.input_mut(|input| { - let before = input.events.len(); - input.events.retain(|event| { - !matches!(event, egui::Event::Key { key: egui::Key::Tab, pressed: true, modifiers, .. } - if !modifiers.ctrl && !modifiers.command && !modifiers.mac_cmd && !modifiers.alt) - }); - input.events.len() != before - }) -} - /// The modifiers held in this pass, which are the Enter press's. fn held_mods(ctx: &Context) -> Mods { let os = crate::runtime::windows::os_of(ctx); @@ -400,7 +387,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut } let separated = input.focused && !input.read_only && state.preedit.is_none() && egui_input::take_separator(ctx, input.options.commit_on); // The part keeps Tab (`keys_of`), so the focus service left it here; it is taken before the widget would insert it. - if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && take_tab(ctx) { + if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && egui_input::take_tab(ctx) { state.end = Some(End::Rewrite { refuses: true }); } let filter = egui_focus::event_filter(input.keys.keep, false); @@ -463,8 +450,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut && !input.options.multiline() && state.preedit.is_none() && state.draft.is_some() - && ctx - .input(|i| [egui::Key::ArrowUp, egui::Key::ArrowDown, egui::Key::PageUp, egui::Key::PageDown].into_iter().any(|key| i.key_pressed(key))); + && egui_input::step_key_pressed(ctx); let submitted = (shown.entered && shown.focused).then(|| held_mods(ctx)).filter(|mods| !input.options.multiline() || (input.options.submits && mods.cmd)); if let Some(mods) = submitted { diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index d4f050a06..191bbf787 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -648,3 +648,21 @@ pub(crate) fn held_press_origin(ctx: &Context) -> Option { pub(crate) fn plain_horizontal_arrow_pressed(ctx: &Context) -> bool { ctx.input(|input| input.modifiers.is_none() && (input.key_pressed(Key::ArrowLeft) || input.key_pressed(Key::ArrowRight))) } + +/// An Up, Down, Page Up or Page Down press reached egui this pass. +pub(crate) fn step_key_pressed(ctx: &Context) -> bool { + ctx.input(|input| [Key::ArrowUp, Key::ArrowDown, Key::PageUp, Key::PageDown].into_iter().any(|key| input.key_pressed(key))) +} + +/// Removes this pass's Tab and Shift+Tab presses from the input events; returns whether there was one. A Tab with +/// Ctrl, Cmd or Alt is the window's, not the field's, and stays. +pub(crate) fn take_tab(ctx: &Context) -> bool { + ctx.input_mut(|input| { + let before = input.events.len(); + input.events.retain(|event| { + !matches!(event, Event::Key { key: Key::Tab, pressed: true, modifiers, .. } + if !modifiers.ctrl && !modifiers.command && !modifiers.mac_cmd && !modifiers.alt) + }); + input.events.len() != before + }) +} diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index ddb6fb2b8..e365ee9ee 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -12,7 +12,7 @@ use crate::runtime::pointer; use craft_behavior::OwnerClass; use craft_behavior::overlay::Side; use egui::emath::TSTransform; -use egui::{Context, Id, LayerId, Pos2, Rect, ViewportId}; +use egui::{Context, Id, Pos2, Rect, ViewportId}; use smallvec::SmallVec; use std::collections::HashMap; @@ -385,7 +385,7 @@ pub fn top(ctx: &Context) -> Option { /// Whether `layer` is the layer of a popup open above `below` in last pass's overlay stack: `layer` belongs to a /// non-exiting popup entry, and `below` is the window's base layer (no entry's layer) or the layer of an entry /// opened before it. The stack, not egui's area order, says which layer was opened above which. -pub(crate) fn popup_above(ctx: &Context, layer: LayerId, below: LayerId) -> bool { +pub(crate) fn popup_above(ctx: &Context, layer: Layer, below: Layer) -> bool { with_pass(ctx, |pass| { // Entries are recorded parent first, so an earlier entry was opened before a later one. let Some(at) = pass.last.iter().position(|entry| entry.layer == layer && entry.rank == Rank::Popup && !entry.exiting) else { diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index 273348f2d..534c66687 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -163,11 +163,10 @@ impl<'a> StyleCx<'a> { } } - /// Runs `f` with the style context of the root scope (`Env::of_root(ctx)`), for code with no `Ui` that reads a - /// component's style, such as the dock's sizes outside a style pass. - pub fn with_root(ctx: &Context, f: impl FnOnce(&StyleCx<'_>) -> R) -> R { - let env = crate::runtime::env::Env::of_root(ctx); - let cx = StyleCx::new( + /// The style context of the scope `env` describes, in the secondary variant: for code outside a style function + /// that works out a layout from a component's style or the scope's tokens. + pub fn of_env(ctx: &'a Context, env: &'a crate::runtime::env::Env) -> Self { + StyleCx::new( ctx, &env.tokens, &env.values, @@ -179,8 +178,14 @@ impl<'a> StyleCx<'a> { env.active, env.key, env.line_ratio, - ); - f(&cx) + ) + } + + /// Runs `f` with the style context of the root scope (`Env::of_root(ctx)`), for code with no `Ui` that reads a + /// component's style, such as the dock's sizes outside a style pass. + pub fn with_root(ctx: &Context, f: impl FnOnce(&StyleCx<'_>) -> R) -> R { + let env = crate::runtime::env::Env::of_root(ctx); + f(&StyleCx::of_env(ctx, &env)) } /// The same context with another variant. diff --git a/crates/ui-panels/src/docking/flyout.rs b/crates/ui-panels/src/docking/flyout.rs index 89a735604..65fcb0095 100644 --- a/crates/ui-panels/src/docking/flyout.rs +++ b/crates/ui-panels/src/docking/flyout.rs @@ -111,10 +111,10 @@ impl Flyout { if bounded { overlay.bounds(self.within) } else { overlay } } - /// Shows the flyout of `popup` while it is open, its top left at `anchor` (a point, or a rect's top left), and - /// returns what it showed; `None` while it is closed. `body` returns the height it measures for + /// Shows the flyout as the layer of `popup` while it is open, its top left at `anchor` (a point, or a rect's top + /// left), and returns what it showed; `None` while it is closed. `body` returns the height it measures for /// `GroupAt::Measure`, or `None` to take the flyout's own height. - pub fn show( + pub fn show_popup( mut self, ui: &mut OverlayUi<'_>, popup: PopupHandle, diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 38c3e0d32..39bf60718 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -553,7 +553,7 @@ impl Component for IconicColumn<'_, P> { let mut resized = None; for (at, plan) in plans.into_iter().enumerate() { let Some(FlyoutPlan { group, top_left, size, fixed, icons_top }) = plan else { continue }; - let shown = Flyout::new(edge, size, auto_collapse).within(bounds).least(least).show( + let shown = Flyout::new(edge, size, auto_collapse).within(bounds).least(least).show_popup( ui, popup.at(at), Anchor::Point(top_left), diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index 0c5f72e66..a403a80ef 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -4,6 +4,7 @@ use super::flyout::GroupAt; use super::spec::PanelSpec; use crate::contract::BodyCx; use crate::menu::PanelRow; +use crate::runtime::memory; use craft_behavior::dock::{Action, Permissions}; use egui::{Context, Id, Ui}; @@ -54,7 +55,7 @@ pub trait DockPanels

{ type Running

= Vec>>; fn running_id() -> Id { - Id::unique("dock area requests") + memory::unique("dock area requests") } /// Hands `actions` to the dock area over panels `P` whose pass is running on `ctx`: a panel body, or code a body @@ -64,33 +65,23 @@ fn running_id() -> Id { /// /// With no such pass running, the actions come back for the caller to apply. pub fn request_actions(ctx: &Context, actions: Vec>) -> Result<(), Vec>> { - ctx.data_mut(|data| { - let running = data.get_temp_mut_or_default::>(running_id()); - if let Some(open) = running.last_mut() { + memory::with_session(ctx, running_id(), |running: &mut Running

| match running.last_mut() { + Some(open) => { open.extend(actions); - return Ok(()); + Ok(()) } - data.remove::>(running_id()); - Err(actions) + None => Err(actions), }) } /// Opens the request list of a dock area's pass on `ctx`. The area calls it before its bodies run. #[doc(hidden)] pub fn open_requests(ctx: &Context) { - ctx.data_mut(|data| data.get_temp_mut_or_default::>(running_id()).push(Vec::new())); + memory::with_session(ctx, running_id(), |running: &mut Running

| running.push(Vec::new())); } -/// Closes the innermost request list on `ctx` and returns what it took. The area calls it when its bodies have run; -/// the last close leaves nothing in the context. +/// Closes the innermost request list on `ctx` and returns what it took. The area calls it when its bodies have run. #[doc(hidden)] pub fn close_requests(ctx: &Context) -> Vec> { - ctx.data_mut(|data| { - let running = data.get_temp_mut_or_default::>(running_id()); - let requested = running.pop().unwrap_or_default(); - if running.is_empty() { - data.remove::>(running_id()); - } - requested - }) + memory::with_session(ctx, running_id(), |running: &mut Running

| running.pop().unwrap_or_default()) } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/guides/trials.rs b/crates/ui-patterns/src/patterns/form_dialogs/guides/trials.rs index d1495a782..85f51c284 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/guides/trials.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/guides/trials.rs @@ -110,14 +110,15 @@ fn a_new_guide_remembers_its_confirmed_values_for_the_next_open() { let position = fixture.by_label("Position").expect("the Position field"); fixture.click(&position).settle(); fixture.key(egui::Key::A, egui::Modifiers::COMMAND); - fixture.type_text("120"); + let typed = 120.0; + fixture.type_text(&typed.to_string()); fixture.key(egui::Key::Enter, egui::Modifiers::NONE).settle(); assert!(!open.get(), "Enter is OK"); let confirmed: Vec<_> = made.borrow().iter().map(|guide| (guide.along, guide.position, guide.color)).collect(); - assert_eq!(confirmed, [(Axis::Y, 120.0, Some(GuideColor::Magenta.rgba()))], "OK makes the guide of the edited values"); + assert_eq!(confirmed, [(Axis::Y, typed, Some(GuideColor::Magenta.rgba()))], "OK makes the guide of the edited values"); reopen(&mut fixture); - assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, 120.0, GuideColor::Magenta), "the next open starts from the confirmed values"); + assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, typed, GuideColor::Magenta), "the next open starts from the confirmed values"); let horizontal = fixture.by_label("Horizontal").expect("the orientation offers Horizontal"); fixture.click(&horizontal).settle(); assert_eq!(values.borrow().along, Axis::X, "the click edits the values"); @@ -126,5 +127,5 @@ fn a_new_guide_remembers_its_confirmed_values_for_the_next_open() { assert_eq!(made.borrow().len(), 1, "Cancel makes no guide"); reopen(&mut fixture); - assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, 120.0, GuideColor::Magenta), "Cancel stored nothing: the OK'd values come back"); + assert_eq!(*values.borrow(), NewGuideValues::new(Axis::Y, typed, GuideColor::Magenta), "Cancel stored nothing: the OK'd values come back"); } diff --git a/crates/ui-patterns/src/patterns/presets/manager.rs b/crates/ui-patterns/src/patterns/presets/manager.rs index 36d4fbe70..52b9831b0 100644 --- a/crates/ui-patterns/src/patterns/presets/manager.rs +++ b/crates/ui-patterns/src/patterns/presets/manager.rs @@ -12,6 +12,7 @@ use super::state::{PresetState, PresetView}; use super::words::PresetWords; use crate::contract::{Bind, Entry, NoValue, Outcome, Pattern, Props, Show as _, ShowContainer as _}; use crate::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use crate::layout_components::Stack; use crate::list::RowTest; use crate::pickers::Select; use crate::runtime::env::{Env, Label}; @@ -142,8 +143,11 @@ impl<'a, G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> PresetManager<' } let shown = dialog.show(ui, |ui, _| { let kind_pick = Select::new(words.manager_kind.clone(), kind.reborrowed(), kinds).show(ui).value().cloned(); - let events: Vec> = ui - .push_id(("preset-kind", index), |ui| { + // Each kind's browser keeps its own state: its search, scroll and open groups. + let events: Vec> = Stack::new() + .id_salt(("preset-kind", index)) + .fill_width() + .show(ui, |ui, _| { PresetBrowser::new(title.clone(), Bind::>::kept(), rows) .view_lock(PresetView::List) .toolbar(false) @@ -156,7 +160,8 @@ impl<'a, G: Value, K: Clone + Eq + Hash + Send + Sync + 'static> PresetManager<' .show(ui) .events }) - .inner; + .inner + .unwrap_or_default(); (kind_pick, events) }); diff --git a/crates/ui-shell/src/shell/caption_icons.rs b/crates/ui-shell/src/shell/caption_icons.rs index e77ed4b57..2d3042ed4 100644 --- a/crates/ui-shell/src/shell/caption_icons.rs +++ b/crates/ui-shell/src/shell/caption_icons.rs @@ -34,7 +34,6 @@ impl CaptionIcon { } /// The icon name the freedesktop themes give the glyph. - #[cfg_attr(not(target_os = "linux"), allow(dead_code))] fn theme_name(self) -> &'static str { match self { CaptionIcon::Minimize => "window-minimize-symbolic", @@ -121,20 +120,10 @@ impl std::fmt::Debug for CaptionIcons { } } -/// The four glyph SVGs of icon theme `theme` (with its parents and `hicolor`), in [`CaptionIcon::ALL`] order. -#[cfg(target_os = "linux")] +/// The four glyph SVGs of icon theme `theme` (with its parents and `hicolor`), in [`CaptionIcon::ALL`] order; none +/// where the platform has no icon themes. fn theme_files(theme: &str) -> [Option>; 4] { - use craft_window::desktop::{IconTheme, base_dirs, read_small}; - let Some(found) = IconTheme::load(theme, &base_dirs(&|key: &str| std::env::var(key).ok())) else { - return Default::default(); - }; - CaptionIcon::ALL.map(|icon| found.find_svg(icon.theme_name()).and_then(|path| read_small(&path)).map(Arc::<[u8]>::from)) -} - -/// The freedesktop lookup is Linux's; elsewhere every glyph is the family's own. -#[cfg(not(target_os = "linux"))] -fn theme_files(_theme: &str) -> [Option>; 4] { - Default::default() + craft_window::desktop::theme_svgs(theme, CaptionIcon::ALL.map(CaptionIcon::theme_name)).map(|file| file.map(Arc::<[u8]>::from)) } /// Bytes drawing one caption icon may allocate, its target included. diff --git a/crates/ui-shell/src/shell/title_bar/bar.rs b/crates/ui-shell/src/shell/title_bar/bar.rs index fc4206c89..a805409b9 100644 --- a/crates/ui-shell/src/shell/title_bar/bar.rs +++ b/crates/ui-shell/src/shell/title_bar/bar.rs @@ -15,6 +15,7 @@ use crate::primitives::{RectSide, RuleKind}; use crate::runtime::access::Name; use crate::runtime::egui::pass; use crate::runtime::env::Env; +use crate::runtime::memory; use crate::runtime::windows::{self, WindowAction, WindowHost}; use crate::shell::app_shell::RegionBody; use crate::shell::{Caption, CaptionButton, CaptionIcons, Frame, ShellWords, SlotSize}; @@ -287,14 +288,15 @@ impl Container for TitleBar<'_> { /// `CaptionIcons::for_desktop` once per desktop value and kept for the app's bars while the desktop stays the same. fn desktop_icons(ctx: &egui::Context) -> Option { let desktop = WindowHost::of(ctx).desktop()?; - let key = egui::Id::unique("craft_ui.title_bar.desktop_icons"); - let kept = ctx.data(|data| data.get_temp::<(Desktop, Option)>(key)); - if let Some((seen, icons)) = &kept - && *seen == desktop - { - return icons.clone(); - } - let icons = CaptionIcons::for_desktop(&desktop, kept.and_then(|(_, icons)| icons)); - ctx.data_mut(|data| data.insert_temp(key, (desktop, icons.clone()))); - icons + let key = memory::unique("craft_ui.title_bar.desktop_icons"); + memory::with_session(ctx, key, |kept: &mut Option<(Desktop, Option)>| { + if let Some((seen, icons)) = kept.as_ref() + && *seen == desktop + { + return icons.clone(); + } + let icons = CaptionIcons::for_desktop(&desktop, kept.take().and_then(|(_, icons)| icons)); + *kept = Some((desktop, icons.clone())); + icons + }) } diff --git a/crates/window/src/desktop.rs b/crates/window/src/desktop.rs index f69840a16..599cd3772 100644 --- a/crates/window/src/desktop.rs +++ b/crates/window/src/desktop.rs @@ -50,6 +50,23 @@ impl Desktop { } } +/// The SVG file of each freedesktop icon name in `icons`, looked up in icon theme `theme` with its parents and +/// `hicolor` and read only when small (`read_small`). Icon themes are Linux's: elsewhere every entry is `None`. +pub fn theme_svgs(theme: &str, icons: [&str; N]) -> [Option>; N] { + #[cfg(target_os = "linux")] + { + let Some(found) = IconTheme::load(theme, &base_dirs(&|key: &str| std::env::var(key).ok())) else { + return [const { None }; N]; + }; + icons.map(|icon| found.find_svg(icon).and_then(|path| read_small(&path))) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (theme, icons); + [const { None }; N] + } +} + #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", test))] /// Compositors and window managers that tile, matched against the `XDG_CURRENT_DESKTOP` entries. const TILING: &[&str] = &["sway", "hyprland", "i3", "niri", "river", "bspwm", "awesome", "dwl", "qtile", "herbstluftwm", "leftwm", "xmonad", "dwm"]; diff --git a/design/exceptions/craft-ui-contract/primitives.toml b/design/exceptions/craft-ui-contract/primitives.toml index 88f56e78b..9927fc74e 100644 --- a/design/exceptions/craft-ui-contract/primitives.toml +++ b/design/exceptions/craft-ui-contract/primitives.toml @@ -1 +1,9 @@ config_version = 1 + +[[exception]] +name = "pointer-art-sides" +kind = "marker" +rule = "literal-size/vec2" +path = "crates/ui-contract/src/primitives/pointer_art.rs" +reason = "Painted pointers are drawn in points around the hotspot like an OS cursor bitmap; their sides are art data, not layout sizes." +count = 2