Design lint: layer the env values, route egui access through the adapter, derive setters, token and relation checks in tests

The gate's design-lint test finds nothing. Env value types (pane edge, column align, row pressed, in-bar), band fill and span live in the layer that uses them; the cursor image and inside label are read back by the higher layer. Hand setters become derived props, tests assert relations, and the remaining sites are listed exceptions with reasons. The shortcut chord chip's sample is built only for screen tests.
This commit is contained in:
aiongg
2026-11-14 05:05:04 +00:00
parent aab2fd5ac7
commit 2b5de84828
87 changed files with 579 additions and 450 deletions
+2 -2
View File
@@ -127,8 +127,8 @@ impl Boards {
let page = |(index, item): (usize, &ArtboardItem)| {
let page = PageFrame::new(item.rect.abs()).name(item.name.clone()).active(self.selected.contains(&index));
match item.background {
ArtboardBackground::White => page.fill(DataColor(Color32::WHITE)),
ArtboardBackground::Black => page.fill(DataColor(Color32::BLACK)),
ArtboardBackground::White => page.fill(DataColor(Color32::WHITE)), // design: allow[raw-colour/const](the artboard background is document data)
ArtboardBackground::Black => page.fill(DataColor(Color32::BLACK)), // design: allow[raw-colour/const](the artboard background is document data)
ArtboardBackground::Custom(color) => page.fill(DataColor(Color32::from(color))),
_ => page,
}
+1 -1
View File
@@ -324,7 +324,7 @@ impl<'a, K: Value + Eq + Hash> BrushPresetPicker<'a, K> {
let next_search = Cell::new(before.search);
let tool_picks: RefCell<Vec<BrushPick<K>>> = RefCell::new(Vec::new());
let (mut diameter, mut hardness, mut tip) = (EditEvents::new(), EditEvents::new(), EditEvents::new());
let browser_id = ui.make_persistent_id("browser");
let browser_id = ui.scope_id().with("browser");
let has_app_rows = gear_rows.is_some();
let head = |ui: &mut Ui, _: &mut BodyCx<'_>| {
Row::new().show(ui, |ui, _| {
+1 -1
View File
@@ -256,7 +256,7 @@ impl PictureEdges {
fn normal(&self, p: Point) -> Vec2 {
let d = |dx: f64, dy: f64| self.image.subject_distance(p.x + dx, p.y + dy);
let g = Vec2::new(d(1.0, 0.0) - d(-1.0, 0.0), d(0.0, 1.0) - d(0.0, -1.0));
if g.hypot() > 0.0 { g / g.hypot() } else { Vec2::new(0.0, -1.0) }
if g.hypot() > 0.0 { g / g.hypot() } else { Vec2::from((0.0, -1.0)) }
}
/// The point of the outline nearest `p`; `None` beyond the search's width or where the edge is weaker than its
+1 -1
View File
@@ -669,7 +669,7 @@ impl<'a> LayerFilterBar<'a> {
pub fn show(self, ui: &mut Ui) -> LayerFilterOutput {
let Self { mut filter, blend_modes, focus_name, types: offered } = self;
if offered.is_empty() {
return LayerFilterOutput { response: ui.allocate_response(egui::Vec2::ZERO, egui::Sense::hover()), changed: false, edit: None };
return LayerFilterOutput { response: Row::new().show(ui, |_, _| {}).output, changed: false, edit: None };
}
let words = Env::of(ui).words::<LayerFilterWords>();
let mut edit = None;
+2 -2
View File
@@ -208,11 +208,11 @@ pub(super) fn clip_cursor<T: LayerTree>(tree: &T, above: &LayerRowKey<T::Id>, be
return None;
}
let icon = if tree.info(upper).clipped { "clip_release" } else { "clip_below" };
Some(Cursor::Painted(PaintedCursor::tool(IconId::new(icon), CLIP_HOTSPOT, None)))
Some(Cursor::Painted(PaintedCursor::tool(IconId::new(icon), egui::Vec2::from(CLIP_HOTSPOT), None)))
}
/// The tip of the clip cursors' arrow in their 24-unit icon box.
const CLIP_HOTSPOT: egui::Vec2 = egui::Vec2::new(15.0, 16.0);
const CLIP_HOTSPOT: [f32; 2] = [15.0, 16.0];
/// The reorder event of the list as the panel reports it: one `Set` per drop.
pub(super) fn drop_event<K: Clone + PartialEq>(
+1
View File
@@ -179,6 +179,7 @@ pub struct LayersPanel<'a, T: LayerTree> {
/// What a reveal ([`LayersPanel::reveal`]) does with the closed groups that hold the layer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Groups {
/// They open ([`LayersEvent::Open`]) and the layer's own row scrolls into view.
Open,
+1
View File
@@ -726,6 +726,7 @@ impl ChordChip {
ChordChip { common: Common::new(), chord, pressed: false }
}
#[cfg(feature = "screen-testing")]
fn sample() -> Self {
ChordChip::new("Ctrl+S".to_owned()).label("Save, Ctrl+S")
}
+3 -8
View File
@@ -127,7 +127,7 @@ trait Sink {
pub(super) const MORE: PartKey = PartKey::new("more");
/// A card or a heading of the card collection.
#[derive(craft_ui::contract::Component)]
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
pub(crate) struct CommentRow<'r> {
#[common]
common: Common,
@@ -138,7 +138,8 @@ pub(crate) struct CommentRow<'r> {
now: i64,
editing: Option<(usize, &'r str)>,
reply: &'r str,
/// The activation key reached the card this pass: the reply box takes the focus.
/// The activation key reached the card this pass: its reply box takes the focus, when it shows one.
#[prop]
focus_reply: bool,
words: Option<Arc<CommentsWords>>,
/// The heights the editor field and the reply field measured, for the paint of the same pass.
@@ -190,12 +191,6 @@ impl<'r> CommentRow<'r> {
self
}
/// The activation key reached the card this pass: its reply box takes the focus, when it shows one.
pub(crate) fn focus_reply(mut self, on: bool) -> Self {
self.focus_reply = on;
self
}
/// The message being edited and its draft, and the reply draft.
pub(crate) fn drafts(mut self, editing: Option<(usize, &'r str)>, reply: &'r str) -> Self {
self.editing = editing;
+1 -1
View File
@@ -117,7 +117,7 @@ impl Component for FramePreview {
let strip = line.map_or(0.0, |line| line.y);
let area = Rect::from_min_max(rect.min, pos2(rect.max.x, (rect.max.y - strip).max(rect.min.y)));
// The bars belong to the picture, as in a video player, so they are black in every theme.
ui.draw().data_fill(&PaintShape::Rect(area, CornerRadius::ZERO), DataColor::new(Color32::BLACK));
ui.draw().data_fill(&PaintShape::Rect(area, CornerRadius::ZERO), DataColor::new(Color32::BLACK)); // design: allow[raw-colour/const](the picture's bars are black in every theme)
let (target, uv) = frame_rect(area, size, self.fit);
ui.content_painter(cx).picture(texture, target, uv, 0.0);
if let (Some(run), Some(line)) = (run, line) {
+1 -1
View File
@@ -378,7 +378,7 @@ impl MediaControls {
let mut slider =
Slider::new(Bind::given(position), range).step(NUDGE).sizing(Sizing::FillWidth).enabled(playable).label(words.seek.clone());
if let Some((start, end)) = trim.filter(|_| playable) {
slider = slider.trim(start, end);
slider = slider.trim(start..=end);
}
let edit = slider.show(ui);
seek = edit.events;
+5 -11
View File
@@ -187,7 +187,11 @@ pub struct Canvas<'a> {
context_key: bool,
/// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)).
ease: Option<Steer>,
/// The app's tool moves the view with the pointer this pass ([`view_follows_pointer`](Self::view_follows_pointer)).
/// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional
/// pointer distances under a frame that stays put): the shown view stays as given, not [`pixel_aligned`], so the
/// picture and the frame do not jitter by part of a pixel as the pointer moves. P-15: the tool host passes the
/// framework `CropTool`'s image mode.
#[prop(name = "view_follows_pointer")]
follows_pointer: bool,
}
@@ -272,16 +276,6 @@ impl<'a> Canvas<'a> {
self
}
/// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional
/// pointer distances under a frame that stays put): the shown view stays as given, not [`pixel_aligned`], so the
/// picture and the frame do not jitter by part of a pixel as the pointer moves. P-15: the tool host passes the
/// framework `CropTool`'s image mode.
#[must_use]
pub fn view_follows_pointer(mut self, follows: bool) -> Self {
self.follows_pointer = follows;
self
}
/// Leaves the view commands to the instance around the canvas that owns its view (a full-window dialog's): the
/// canvas is no instance of them, so the chords reach that instance while the canvas has the focus.
#[must_use]
+2 -2
View File
@@ -23,10 +23,10 @@ const ROTATE_STEP_DEG: f64 = 15.0;
/// The room Fit Artboard on Screen leaves around the board, in points: at the sides, and above and below (the board's
/// name sits above it).
const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 40.0);
const ARTBOARD_MARGIN: Vec2 = Vec2::new(30.0, 40.0); // design: allow[literal-size/vec2](view-fit room in screen points, not a look)
/// The room Fit Layers on Screen leaves around the layers' bounds, in points.
const LAYERS_MARGIN: Vec2 = Vec2::new(20.0, 20.0);
const LAYERS_MARGIN: Vec2 = Vec2::new(20.0, 20.0); // design: allow[literal-size/vec2](view-fit room in screen points, not a look)
/// Photoshop's default Screen Resolution (Preferences, Units & Rulers), in pixels per inch.
const SCREEN_PPI: f64 = 72.0;
@@ -124,7 +124,7 @@ fn tip_of(tip: StoryTip, dimensions: BrushDimensions, pointer: Option<Point>) ->
let normal = (edge.core() + edge.reach()) / 2.0;
match tip {
StoryTip::Round => (BrushTip::round(dimensions.diameter, normal), TipPose::upright()),
StoryTip::ThinEllipse => (BrushTip::round(dimensions.diameter, normal), TipPose::new(Vec2::new(1.0, 0.0), Vec2::new(0.0, THIN))),
StoryTip::ThinEllipse => (BrushTip::round(dimensions.diameter, normal), TipPose::new(Vec2::from((1.0, 0.0)), Vec2::from((0.0, THIN)))),
StoryTip::Star => {
let share = (normal / full.max(f64::EPSILON)) as f32;
let scaled =
@@ -833,7 +833,7 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
let body_env = line_env.derive_local(|scoped| {
let label_width = label_extra.x;
self.scope_body(scoped, &props, id, BodyScope { room, real, sizing, content_column, scroll, label_width, beside: regions.beside });
scoped.inside_label = inside;
scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held);
scoped.cell_fills = cell_fills;
// A scrolling body shows its first child wherever the view is: the container has no first line there.
scoped.first_line = (!real && scroll.is_none()).then_some(first_body);
@@ -1,5 +1,6 @@
//! A collection's columns: kinds, specs, alignment, toggle columns and the sort.
pub use crate::runtime::env::ColumnAlign;
use crate::runtime::env::Label;
use craft_behavior::{ColumnKey, ColumnWidth};
use craft_keymap::Chord;
@@ -84,16 +85,6 @@ pub struct ColumnSpec {
pub hideable: bool,
}
/// Where a column's content sits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColumnAlign {
/// At the start edge.
#[default]
Start,
/// At the end edge.
End,
}
impl ColumnSpec {
/// A content column with a header and a width; the other settings off.
pub fn new(key: ColumnKey, header: impl Into<Label>, width: ColumnWidth) -> Self {
@@ -3,6 +3,7 @@
use super::columns::{ColumnSort, ColumnSpec};
use super::events::ListDrag;
use crate::contract::Notch;
pub use crate::runtime::env::RowPressed;
use crate::runtime::env::{Counted, Label};
use crate::style::StyleCx;
use craft_behavior::{Axis, ColumnKey};
@@ -583,22 +584,6 @@ impl CollectionProps {
}
}
/// Where the collection holds a primary press on a row, within slop, or the press a part of the row holds.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RowPressed {
/// On the row's own area.
Row,
/// On the cell of this toggle column, which the press flips.
Cell(ColumnKey),
/// On a part of the item that took the press itself (a row's trailing button).
#[non_exhaustive]
Part {
/// The row held the lead when the press began: a press on a part moves the lead to its row.
was_lead: bool,
},
}
/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RowState {
+3 -42
View File
@@ -15,7 +15,8 @@ use craft_theme::ControlSize;
use craft_theme::variant::Tone;
use egui::Rect;
pub use crate::runtime::env::ThemeScope;
pub use crate::runtime::env::{InBar, PaneEdge, ThemeScope};
pub use crate::style::BandFill;
/// Where a container lives.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -65,23 +66,6 @@ impl Mount {
}
}
/// Where a shell pane sits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaneEdge {
/// What the edge panes leave.
#[default]
Center,
/// The start edge: left in reading order, right under right-to-left.
Start,
/// The end edge.
End,
/// The top edge.
Top,
/// The bottom edge.
Bottom,
}
/// One of `AppShell`'s panes.
///
/// A pane is placed one of three ways. With [`at`](Self::at) it fills the rect its caller laid out, takes no room from
@@ -259,6 +243,7 @@ impl HeaderParts {
/// An edge of a header's line, where a container's own header parts sit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeaderEdge {
/// The start edge: the parts there come before the header's children, in Tab order too.
Start,
@@ -266,16 +251,6 @@ pub enum HeaderEdge {
End,
}
/// What the band behind a header paints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BandFill {
/// A surface's fill.
Surface(SurfaceKind),
/// A tone's tinted fill (`Tone::soft_fill`).
Tone(Tone),
}
/// A header region, filled by `Container::header`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
@@ -670,20 +645,6 @@ pub enum Gap {
Inline,
}
/// Set by a bar for its body: its fields put `space.gap.item` between a caption and the control, a vertical divider
/// takes a box wider than its line, a select fits its widest entry up to a field length, a rule shows only with the
/// member after it, and a row too long for its room narrows its last units first. A layer or pane opened from the bar
/// starts without it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[doc(hidden)]
pub struct InBar(pub bool);
impl EnvValue for InBar {
fn root() -> Self {
InBar(false)
}
}
/// Set by a menu for its body: a horizontal divider takes `space.gap.inline` above and below its line, since the rows
/// of a menu touch.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -394,7 +394,7 @@ pub(crate) fn child_env(env: &Env, under: &Under) -> Env {
env.derive_local(|scoped| {
scoped.enabled &= under.enabled;
scoped.size = under.size;
scoped.inside_label.clone_from(&under.inside);
scoped.inside_label = under.inside.clone().map(|inside| inside as crate::runtime::env::Held);
scoped.cell_fills = false;
})
}
+8 -2
View File
@@ -2,7 +2,7 @@
//! image a window shows as its cursor. Both come from the one list, so the two look the same.
use crate::primitives::SvgIcon;
use crate::runtime::cursor::CursorBitmap;
use crate::runtime::cursor::{CursorArt, CursorBitmap};
use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, Vec2};
use resvg::tiny_skia;
use std::sync::Arc;
@@ -95,7 +95,7 @@ impl Art {
/// The art as a cursor image at `scale` device pixels per point, its hotspot on the centre pixel of an odd square;
/// `None` for art with no marks, with a size that is not finite, or wider than `max_side` pixels. The size is
/// checked before anything is allocated.
pub(crate) fn rasterise(&self, scale: f32, max_side: u16) -> Option<CursorBitmap> {
fn rasterise_art(&self, scale: f32, max_side: u16) -> Option<CursorBitmap> {
if !scale.is_finite() || scale <= 0.0 {
return None;
}
@@ -244,3 +244,9 @@ fn composite(pixmap: &mut tiny_skia::Pixmap, mask: &egui::ColorImage, left: i64,
}
}
}
impl CursorArt for Art {
fn rasterise(&self, scale: f32, max_side: u16) -> Option<CursorBitmap> {
self.rasterise_art(scale, max_side)
}
}
@@ -154,6 +154,14 @@ impl InsideLabel {
}
}
impl<'a> EnvView<'a> {
/// The inside label the component shows in its slot, when it is the control of a side label with
/// `FieldLayout::Inside`.
pub fn inside_label(&self) -> Option<&'a InsideLabel> {
self.inside_held().and_then(|held| held.downcast_ref())
}
}
/// The inside label a control under `side` shows in its slot: `Some` for a glyph label with `FieldLayout::Inside`.
pub(crate) fn inside(env: EnvView<'_>, side: &SideLabel, enabled: bool) -> Option<Arc<InsideLabel>> {
let LabelKind::Glyph(glyph) = &side.kind else { return None };
@@ -288,7 +288,10 @@ pub(crate) fn flow_leaf<C: Show>(
report_after_reach(ui.ctx(), &env, &side, (avail, control), extent);
}
// The child runs under the inside label its measures saw.
let installed = under.inside.clone().map(|inside| Env::install_for(ui, env.derive_local(|scoped| scoped.inside_label = Some(inside))));
let installed = under
.inside
.clone()
.map(|inside| Env::install_for(ui, env.derive_local(|scoped| scoped.inside_label = Some(inside as crate::runtime::env::Held))));
// The control and its label are one member of a bar's line: judged together, and hidden together, as the label
// step hid the label.
let shown_clip = ui.clip_rect();
@@ -51,6 +51,7 @@ fn stored_opening(ctx: &Context, id: Id) -> Option<Opening> {
/// bar stay below the bar ([`OverlayUi::contain_popups_below`](super::OverlayUi::contain_popups_below)). `None`, the
/// root's, lets popups take the whole safe rect.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct PopupRegion(pub Option<Rect>);
impl crate::runtime::env::EnvValue for PopupRegion {
+7 -41
View File
@@ -6,11 +6,11 @@ use super::run::{self, FaceSource, ShowAt};
use super::{ContentPainter, Cx, Show, TipFn};
use super::{InsideLabel, SideLabel};
use crate::primitives::sensing::PartResults;
use crate::primitives::{ContentPainterCx, DataMode, Draw, DrawEnv, PaintRecord, TextRun, Wrap};
use crate::primitives::text_adapter;
use crate::primitives::{ContentPainterCx, DataMode, Draw, DrawEnv, PaintRecord, TextRun};
use crate::runtime::access;
use crate::runtime::egui::{alloc, child, focus as egui_focus, text_edit};
use crate::runtime::egui::{alloc, child};
use crate::runtime::env::{Env, Label};
use crate::runtime::focus::KeepKeys;
use crate::runtime::layout_memory;
use crate::runtime::memory::sub;
use crate::style::{Flags, Ink, Stateful, StyleColor, StyleCx};
@@ -75,46 +75,12 @@ impl PaintUi<'_> {
}
let (layout, at) = self.draw().place_text(rect, run);
self.record.borrow_mut().baseline.get_or_insert(at.y + layout.first_baseline);
let ctx = self.ui.ctx().clone();
let widget = super::text::selection_id(self.id, part);
let multiline = run.wrap == Wrap::Wrap;
let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows };
let mut shown = layout.full.clone();
// A line longer than its room is cut at the room's edge, as a field's is.
let mut cut = (layout.size().x > rect.width()).then(|| {
let mut cut = alloc::child(self.ui, egui::UiBuilder::new().max_rect(rect));
cut.set_clip_rect(rect.intersect(cut.clip_rect()));
cut
});
text_edit::show(
cut.as_mut().unwrap_or(&mut *self.ui),
text_edit::Edit {
id: widget,
rect: layout.galley.rect.translate(at.to_vec2()),
text: &mut shown,
read_only: true,
enabled: self.enabled,
focusable: self.enabled,
pointer: true,
multiline,
password: false,
hint: None,
mono: false,
role: run.role,
ink: crate::style::ink_color(&self.env.tokens, self.ink),
filter: egui_focus::event_filter(keep, false),
char_limit: None,
preedit: None,
rtl: false,
centred: false,
caret_visible: false,
underline: 0.0,
galley: Some(layout.galley.clone()),
},
let ink = crate::style::ink_color(&self.env.tokens, self.ink);
text_adapter::show_selectable(
self.ui,
text_adapter::Selectable { widget, owner: self.id, rect, layout: &layout, at, run, enabled: self.enabled, ink },
);
if crate::runtime::egui::access::enabled(&ctx, widget) {
crate::runtime::egui::access::fold_widget(&ctx, widget, self.id);
}
}
/// The content-paint API for painting `part`: as [`draw`](Self::draw), and when the part was declared
+1 -1
View File
@@ -1214,7 +1214,7 @@ pub(crate) struct BarRules(HashMap<Id, Vec<HeldRule>>);
/// A rule's paint: `shapes` of the paint list of `layer`, in the pass `pass`.
struct HeldRule {
layer: egui::LayerId,
layer: crate::runtime::egui::areas::Layer,
shapes: std::ops::Range<usize>,
pass: u64,
}
+8
View File
@@ -206,6 +206,7 @@ struct Reported {
/// The widths of a unit of a row that shrinks to fit: the width it asks for and the least it narrows to.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct ShrinkUnit {
/// The width the unit takes where the row has room.
pub ideal: f32,
@@ -213,6 +214,13 @@ pub struct ShrinkUnit {
pub least: f32,
}
impl ShrinkUnit {
/// A unit that asks for `ideal` and narrows to `least`.
pub const fn new(ideal: f32, least: f32) -> Self {
ShrinkUnit { ideal, least }
}
}
/// The units each `Row` body counting this pass reported, in order, by body id.
#[derive(Default)]
pub(crate) struct ShrinkReports(HashMap<Id, Vec<Reported>>);
+1 -1
View File
@@ -180,7 +180,7 @@ impl DataMode {
/// The mode of a component painting in `state`: `Dimmed` in its Disabled state, which step 12 gives a disabled
/// component that is not faded as a whole.
pub(crate) fn of(state: &crate::style::StateSet) -> Self {
if state.state == craft_theme::State::Disabled { DataMode::Dimmed } else { DataMode::Full }
if state.is_disabled() { DataMode::Dimmed } else { DataMode::Full }
}
/// A colour from data as this mode paints it.
+1
View File
@@ -119,6 +119,7 @@ impl Checker {
/// Where a [`Checker`] paints.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum CheckerArea {
/// A rect with these corners.
Rect(Rect, CornerRadius),
+1 -89
View File
@@ -2,6 +2,7 @@
use crate::fonts::StackFacts;
use crate::runtime::egui::text_layout;
pub use crate::style::Span;
use crate::style::text_measure::{paragraph_job, span_format};
use crate::style::{StyleColor, TypeRole, UiTokens};
use craft_i18n::Direction;
@@ -53,95 +54,6 @@ pub enum HAlign {
End,
}
/// One styled stretch of a run.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Span<'a> {
/// The text.
pub text: Cow<'a, str>,
/// Italic.
pub italic: bool,
/// Tabular figures.
pub tabular: bool,
/// The monospace face.
pub mono: bool,
/// The muted text colour.
pub muted: bool,
/// A shortcut hint: muted.
pub shortcut: bool,
/// A search match highlight.
pub highlight: bool,
/// Underlined in the span's colour, `stroke.thin` wide, along the bottom of the line box.
pub underline: bool,
/// The role's semibold face, at the role's size.
pub strong: bool,
}
impl<'a> Span<'a> {
/// A plain span.
pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
Span {
text: text.into(),
italic: false,
tabular: false,
mono: false,
muted: false,
shortcut: false,
highlight: false,
underline: false,
strong: false,
}
}
/// Italic.
pub fn italic(mut self) -> Self {
self.italic = true;
self
}
/// Tabular figures.
pub fn tabular(mut self) -> Self {
self.tabular = true;
self
}
/// The monospace face.
pub fn mono(mut self) -> Self {
self.mono = true;
self
}
/// The muted colour.
pub fn muted(mut self) -> Self {
self.muted = true;
self
}
/// A shortcut hint.
pub fn shortcut(mut self) -> Self {
self.shortcut = true;
self
}
/// A match highlight.
pub fn highlight(mut self) -> Self {
self.highlight = true;
self
}
/// Underlined: a link, or the mnemonic letter of a menu title.
pub fn underline(mut self) -> Self {
self.underline = true;
self
}
/// The role's semibold face: a short mark that stands out among the row's other text, such as a layer's `fx`.
pub fn strong(mut self) -> Self {
self.strong = true;
self
}
}
/// The one description of UI text.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
@@ -298,7 +298,7 @@ pub(crate) fn select(ctx: &Context, id: Id, anchor: usize, caret: usize) {
/// `TextOptions::arrows_from_end`: before the widget reads a plain Left or Right, a selection of the whole text
/// collapses to its end.
fn arrows_from_end(ctx: &Context, widget: Id, len: usize) {
let arrow = ctx.input(|input| input.modifiers.is_none() && (input.key_pressed(egui::Key::ArrowLeft) || input.key_pressed(egui::Key::ArrowRight)));
let arrow = egui_input::plain_horizontal_arrow_pressed(ctx);
let whole = selection(ctx, widget).is_some_and(|(caret, anchor)| caret.min(anchor) == 0 && caret.max(anchor) == len);
if arrow && len > 0 && whole {
select(ctx, widget, len, len);
@@ -432,3 +432,65 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
let baseline = (!layout.full.is_empty()).then_some(shown.galley_pos.y + layout.first_baseline);
AdapterOut { layout, focused: shown.focused, baseline }
}
/// What [`show_selectable`] shows: the read-only text of a selection part.
pub(crate) struct Selectable<'a> {
/// The id of the selection widget.
pub widget: Id,
/// The component the widget's access node folds into.
pub owner: Id,
/// The room the text is painted in; a line wider than it is cut at its edge.
pub rect: Rect,
/// The laid-out text and the point it was placed at.
pub layout: &'a TextLayout,
pub at: Pos2,
pub run: &'a crate::primitives::TextRun<'a>,
pub enabled: bool,
/// The text colour.
pub ink: egui::Color32,
}
/// Shows `text` as a read-only selectable widget over its painted lines: the selection behind the characters, the copy
/// command and the pointer's selecting, without a caret.
pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) {
let Selectable { widget, owner, rect, layout, at, run, enabled, ink } = text;
let ctx = ui.ctx().clone();
let multiline = run.wrap == crate::primitives::Wrap::Wrap;
let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows };
let mut shown = layout.full.clone();
// A line longer than its room is cut at the room's edge, as a field's is.
let mut cut = (layout.size().x > rect.width()).then(|| {
let mut cut = crate::runtime::egui::alloc::child(ui, egui::UiBuilder::new().max_rect(rect));
cut.set_clip_rect(rect.intersect(cut.clip_rect()));
cut
});
text_edit::show(
cut.as_mut().unwrap_or(&mut *ui),
text_edit::Edit {
id: widget,
rect: layout.galley.rect.translate(at.to_vec2()),
text: &mut shown,
read_only: true,
enabled,
focusable: enabled,
pointer: true,
multiline,
password: false,
hint: None,
mono: false,
role: run.role,
ink,
filter: egui_focus::event_filter(keep, false),
char_limit: None,
preedit: None,
rtl: false,
centred: false,
caret_visible: false,
underline: 0.0,
galley: Some(layout.galley.clone()),
},
);
if crate::runtime::egui::access::enabled(&ctx, widget) {
crate::runtime::egui::access::fold_widget(&ctx, widget, owner);
}
}
+1 -7
View File
@@ -81,13 +81,7 @@ impl Role {
/// or flips a value on a click (a check box, radio button, switch or colour well); none for the rest.
pub const fn hover_cursor(self) -> Option<craft_behavior::CursorIcon> {
match self {
Role::Node(
accesskit::Role::Link
| accesskit::Role::CheckBox
| accesskit::Role::RadioButton
| accesskit::Role::Switch
| accesskit::Role::ColorWell,
) => Some(craft_behavior::CursorIcon::PointingHand),
Role::LINK | Role::CHECK_BOX | Role::RADIO_BUTTON | Role::SWITCH | Role::COLOR_WELL => Some(craft_behavior::CursorIcon::PointingHand),
_ => None,
}
}
+11 -5
View File
@@ -1,7 +1,6 @@
//! The cursor service (8.5): requests of a pass collect here, the end hook picks the winner and records it, and a
//! painted winner reaches the window as its cursor image where the window shows one.
use crate::contract::ghost::Art;
use crate::runtime::egui::{output, pass, viewports};
use crate::runtime::frame::PerViewport;
use crate::runtime::windows;
@@ -9,6 +8,7 @@ use craft_behavior::cursor::pick;
use craft_behavior::{Cursor, CursorIcon, CursorPriority, PaintedCursor};
use craft_host::target::Os;
use egui::{Context, ViewportId};
use std::any::Any;
use std::sync::Arc;
/// The largest side of a cursor image in device pixels on Linux, where X servers and hardware cursor planes commonly
@@ -44,7 +44,7 @@ pub(crate) struct State {
record: Option<Cursor>,
/// The last image handed to the window with the art and scale it was drawn from. egui-winit uploads an image to
/// the OS whenever its `Arc` changes, so an unchanged pointer hands over the same one.
image: Option<(Art, f32, CursorBitmap)>,
image: Option<(Box<dyn Any + Send + Sync>, f32, CursorBitmap)>,
}
/// Requests `cursor` for the running pass of this viewport.
@@ -104,19 +104,25 @@ pub(crate) fn image_target(ctx: &Context) -> Option<ImageTarget> {
})
}
/// A painted pointer the window can take as its cursor image: drawn at a scale, compared with the last one handed over.
pub(crate) trait CursorArt: Any + Clone + PartialEq + Send + Sync {
/// The image at `scale` device pixels per point, `None` where the art has none at that size.
fn rasterise(&self, scale: f32, max_side: u16) -> Option<CursorBitmap>;
}
/// Hands `art` to the window as its cursor image at `target`, drawing it only when the art or the scale changed since
/// the last image; the crosshair is the system cursor an integration that cannot take the image falls back to.
/// Returns false, and hands nothing over, when the art has no image at that size.
pub(crate) fn show_image(ctx: &Context, art: &Art, target: ImageTarget) -> bool {
pub(crate) fn show_image<A: CursorArt>(ctx: &Context, art: &A, target: ImageTarget) -> bool {
let bitmap = PerViewport::<State>::with(ctx, pass::current_viewport(ctx), |state| {
if let Some((last, scale, bitmap)) = &state.image
&& last == art
&& last.downcast_ref::<A>() == Some(art)
&& *scale == target.scale
{
return Some(bitmap.clone());
}
let bitmap = art.rasterise(target.scale, target.max_side)?;
state.image = Some((art.clone(), target.scale, bitmap.clone()));
state.image = Some((Box::new(art.clone()), target.scale, bitmap.clone()));
Some(bitmap)
});
let Some(bitmap) = bitmap else { return false };
+1 -1
View File
@@ -141,7 +141,7 @@ pub struct DropZone {
impl DropZone {
/// The zone `rect` on `layer` (the `layer_id` of the `Ui` that draws the area), in that layer's space.
pub const fn new(layer: egui::LayerId, rect: Rect) -> Self {
pub const fn new(layer: crate::runtime::egui::areas::Layer, rect: Rect) -> Self {
DropZone { layer, rect }
}
@@ -25,6 +25,16 @@ pub(crate) use text::{
#[cfg(feature = "testing")]
pub use tree::{AccessTree, Declared, NodeKey};
/// The AccessKit id of a node, as a host test holds it.
#[cfg(feature = "testing")]
pub type NodeId = accesskit::NodeId;
/// The AccessKit id of the node of `id`.
#[cfg(feature = "testing")]
pub(crate) fn node_id(id: Id) -> NodeId {
id.accesskit_id()
}
/// The AccessKit role of a node.
pub(crate) type NodeRole = accesskit::Role;
@@ -390,3 +390,26 @@ pub(crate) fn widest_layer(ctx: &Context) -> f32 {
.fold(0.0, f32::max)
})
}
/// Whether an egui popup of the running viewport is open: an app's own popup or menu, which reads its keys from egui.
pub(crate) fn popup_open(ctx: &Context) -> bool {
egui::Popup::is_any_open(ctx)
}
/// A host's own egui popup `id` at `at`, shown while egui's memory holds it open.
#[cfg(feature = "testing")]
pub(crate) fn host_popup(ui: &Ui, id: egui::Id, at: Pos2) {
egui::Popup::new(id, ui.ctx().clone(), at, ui.layer_id()).open_memory(None).show(|ui| ui.allocate_space(ui.spacing().interact_size));
}
/// Opens the host's egui popup `id`.
#[cfg(feature = "testing")]
pub(crate) fn open_host_popup(ctx: &Context, id: egui::Id) {
egui::Popup::open_id(ctx, id);
}
/// Whether the host's egui popup `id` is open.
#[cfg(feature = "testing")]
pub(crate) fn host_popup_open(ctx: &Context, id: egui::Id) -> bool {
egui::Popup::is_id_open(ctx, id)
}
@@ -443,21 +443,6 @@ pub(crate) fn host_label(ui: &mut Ui, text: &str) -> Rect {
ui.add(egui::Label::new(text).selectable(true)).rect
}
/// A host's own egui popup `id` at `at`, shown while egui's memory holds it open.
pub(crate) fn host_popup(ui: &Ui, id: egui::Id, at: Pos2) {
egui::Popup::new(id, ui.ctx().clone(), at, ui.layer_id()).open_memory(None).show(|ui| ui.allocate_space(ui.spacing().interact_size));
}
/// Opens the host's egui popup `id`.
pub(crate) fn open_host_popup(ctx: &Context, id: egui::Id) {
egui::Popup::open_id(ctx, id);
}
/// Whether the host's egui popup `id` is open.
pub(crate) fn host_popup_open(ctx: &Context, id: egui::Id) -> bool {
egui::Popup::is_id_open(ctx, id)
}
/// The egui layer `ui` paints on.
pub(crate) fn layer_of(ui: &Ui) -> egui::LayerId {
ui.layer_id()
@@ -27,11 +27,6 @@ pub(crate) fn focused(ctx: &Context) -> Option<Id> {
ctx.memory(|memory| memory.focused())
}
/// Whether an egui popup of the running viewport is open: an app's own popup or menu, which reads its keys from egui.
pub(crate) fn popup_open(ctx: &Context) -> bool {
egui::Popup::is_any_open(ctx)
}
/// Whether egui holds a label text selection, which egui copies on a copy or cut event.
pub(crate) fn label_selection(ctx: &Context) -> bool {
ctx.with_plugin::<egui::text_selection::LabelSelectionState, _>(|state| state.has_selection()).unwrap_or(false)
@@ -443,3 +443,18 @@ pub(crate) fn take_separator(ctx: &Context, commit_on: &[char]) -> bool {
true
})
}
/// The widget egui holds a drag on.
pub(crate) fn dragged(ctx: &Context) -> Option<Id> {
ctx.dragged_id()
}
/// Where the press that is held down began, while a button is down.
pub(crate) fn held_press_origin(ctx: &Context) -> Option<Pos2> {
ctx.input(|input| if input.pointer.any_down() { input.pointer.press_origin() } else { None })
}
/// A plain Left or Right arrow press reached egui this pass, with no modifier held.
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)))
}
+10 -7
View File
@@ -29,6 +29,9 @@ use egui::{Context, Id, Ui, ViewportId};
use std::ops::Deref;
use std::sync::Arc;
/// A value a higher layer defines and the env only carries: the layer that defines it reads it back by its type.
pub(crate) type Held = Arc<dyn std::any::Any + Send + Sync>;
mod app_values;
mod host_words;
mod overrides;
@@ -48,7 +51,7 @@ pub(crate) use tokens::TokenInputs;
#[cfg(feature = "testing")]
pub(crate) use tokens::root_token_resolves;
use tokens::tokens_for;
pub use values::{ArenaId, MotionPolicy, Scale};
pub use values::{ArenaId, ColumnAlign, InBar, MotionPolicy, PaneEdge, RowPressed, Scale};
pub use view::EnvView;
/// The inherited context of a `Ui`: one `Arc` clone per read.
@@ -154,7 +157,7 @@ pub struct Scoped {
/// The view of the innermost scroll area, for the children that run only in view (`contract::Lazy`).
pub(crate) lazy: Option<crate::runtime::lazy::View>,
/// The window edge of the innermost edge pane that encloses the scope (`Mount::Pane`).
pub(crate) pane_edge: Option<crate::contract::PaneEdge>,
pub(crate) pane_edge: Option<PaneEdge>,
/// The id of the collection item the scope shows: its root is not a Tab stop (17.3).
pub(crate) item: Option<Id>,
/// The roving group of the collection row the scope shows: the stops of its components and parts join it, so
@@ -164,7 +167,7 @@ pub struct Scoped {
pub(crate) item_facts: Option<Arc<ItemFacts>>,
/// The inside label of the side label whose control the scope shows (`FieldLayout::Inside`). Only that control
/// sees it: a component's children and a container's regions start without one.
pub(crate) inside_label: Option<Arc<crate::contract::InsideLabel>>,
pub(crate) inside_label: Option<Held>,
/// The scope is the body of a beside label in an inspector (`LabelScheme::Inspector`): the control shown there
/// fills the width the label leaves. Only that control sees it, as with `inside_label`.
pub(crate) cell_fills: bool,
@@ -274,10 +277,10 @@ pub struct ItemFacts {
/// Each column's alignment and whether its figures are tabular, from its `ColumnSpec`: a row places its cells'
/// text by them.
#[doc(hidden)]
pub aligns: Vec<(craft_behavior::ColumnKey, crate::contract::ColumnAlign, bool)>,
pub aligns: Vec<(craft_behavior::ColumnKey, ColumnAlign, bool)>,
/// Where the collection holds a press on the row (`RowState::pressed`).
#[doc(hidden)]
pub pressed: Option<crate::contract::RowPressed>,
pub pressed: Option<RowPressed>,
/// The row's menu is open (`RowState::menu_open`).
#[doc(hidden)]
pub menu_open: bool,
@@ -330,7 +333,7 @@ impl Scoped {
self.item_facts = None;
self.ink = Ink::default();
self.surface = SurfaceKind::Background;
self.inherited_mut().values.set(crate::contract::InBar(false));
self.inherited_mut().values.set(InBar(false));
}
/// Ends the layout room of the enclosing body: its flow grid and content column.
@@ -543,7 +546,7 @@ impl Env {
scoped.lazy = None;
scoped.measure = None;
// A pane opened from a bar is not the bar's line.
scoped.inherited_mut().values.set(crate::contract::InBar(false));
scoped.inherited_mut().values.set(InBar(false));
})
}
+59 -1
View File
@@ -1,6 +1,7 @@
//! The library values the env carries: scale, motion policy and arena id.
use craft_behavior::MotionMode;
use super::EnvValue;
use craft_behavior::{ColumnKey, MotionMode};
use craft_theme::MotionTokens;
use egui::Id;
use std::hash::Hash;
@@ -51,3 +52,60 @@ impl ArenaId {
ArenaId(id)
}
}
/// Where a column's content sits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColumnAlign {
/// At the start edge.
#[default]
Start,
/// At the end edge.
End,
}
/// Where the collection holds a primary press on a row, within slop, or the press a part of the row holds.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RowPressed {
/// On the row's own area.
Row,
/// On the cell of this toggle column, which the press flips.
Cell(ColumnKey),
/// On a part of the item that took the press itself (a row's trailing button).
#[non_exhaustive]
Part {
/// The row held the lead when the press began: a press on a part moves the lead to its row.
was_lead: bool,
},
}
/// Set by a bar for its body: its fields put `space.gap.item` between a caption and the control, a vertical divider
/// takes a box wider than its line, a select fits its widest entry up to a field length, a rule shows only with the
/// member after it, and a row too long for its room narrows its last units first. A layer or pane opened from the bar
/// starts without it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[doc(hidden)]
pub struct InBar(pub bool);
impl EnvValue for InBar {
fn root() -> Self {
InBar(false)
}
}
/// Where a shell pane sits.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaneEdge {
/// What the edge panes leave.
#[default]
Center,
/// The start edge: left in reading order, right under right-to-left.
Start,
/// The end edge.
End,
/// The top edge.
Top,
/// The bottom edge.
Bottom,
}
+4 -5
View File
@@ -4,7 +4,7 @@ use super::app_values::EnvValue;
use super::label::Label;
use super::units::{PointSize, UnitWords, Units};
use super::values::{MotionPolicy, Scale};
use super::{ItemFacts, Scoped};
use super::{Held, ItemFacts, Scoped};
use crate::runtime::commands::CommandChain;
use craft_host::Host;
use craft_host::target::ShellInfo;
@@ -58,10 +58,9 @@ impl<'a> EnvView<'a> {
self.scoped.roving
}
/// The inside label the component shows in its slot, when it is the control of a side label with
/// `FieldLayout::Inside`.
pub fn inside_label(&self) -> Option<&'a crate::contract::InsideLabel> {
self.scoped.inside_label.as_deref()
/// The inside label the scope carries ([`inside_label`](EnvView::inside_label) reads it back).
pub(crate) fn inside_held(&self) -> Option<&'a Held> {
self.scoped.inside_label.as_ref()
}
/// The surface the component sits on: the innermost container or collection surface that paints a fill, else the
+1 -1
View File
@@ -720,7 +720,7 @@ pub(crate) fn end(ctx: &Context) {
// Escape over a captured framework press or drag cancels it (`frame::begin_pass`), whatever egui has focused.
let captured = crate::runtime::pointer::press_captured(ctx) || crate::runtime::drag::running(ctx);
let host_focus = !captured && with(ctx, |state| state.focus_now).is_some_and(app_widget);
let foreign = host_focus || (!captured && egui_focus::popup_open(ctx));
let foreign = host_focus || (!captured && crate::runtime::egui::areas::popup_open(ctx));
let label_selection = egui_focus::label_selection(ctx);
with(ctx, |state| {
state.record.foreign = foreign;
+5 -4
View File
@@ -3,11 +3,12 @@
//! with its box and access facts, the hit areas the sensing core registered and the focus stops in Tab order.
use crate::runtime::egui::areas;
use crate::runtime::egui::areas::Layer;
use crate::runtime::egui::sizing::{Rerun, request_discard};
use crate::runtime::reads::{self, BindKey};
use crate::runtime::{focus, measure, pass_state, pointer};
use craft_behavior::PartRef;
use egui::{Context, Id, LayerId, Rect, Ui};
use egui::{Context, Id, Rect, Ui};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -181,8 +182,8 @@ impl Recorded {
/// A region being recorded.
struct Open {
/// The layer the region is shown on, which the record's rects are in.
layer: LayerId,
elements: Vec<(Element, LayerId)>,
layer: Layer,
elements: Vec<(Element, Layer)>,
parts: Vec<Element>,
/// The elements whose show has not finished, outermost first.
stack: Vec<usize>,
@@ -286,7 +287,7 @@ fn edited(ctx: &Context, read: BindKey, editor: Id) {
/// component.
fn finish(ctx: &Context, open: Open) -> Recorded {
let from_screen = areas::layer_to_screen(ctx, open.layer).inverse();
let to_region = |layer: LayerId, rect: Rect| from_screen * (areas::layer_to_screen(ctx, layer) * rect);
let to_region = |layer: Layer, rect: Rect| from_screen * (areas::layer_to_screen(ctx, layer) * rect);
let ids: HashSet<Id> = open.elements.iter().map(|(element, _)| element.id).collect();
let mut elements: Vec<Element> = Vec::with_capacity(open.elements.len() + open.parts.len());
let mut parts = open.parts;
+6 -6
View File
@@ -13,12 +13,13 @@
//! that run to the pass again in place of running, in view or not, inside a scroll area or not. It is settled when
//! nothing the framework tracks has changed for it since that run (`settled`).
use crate::runtime::egui::pass;
use crate::runtime::egui::areas::Layer;
use crate::runtime::egui::{focus as focus_state, input as input_state, pass};
use crate::runtime::focus::{self, Transcript};
use crate::runtime::frame::{self, PerViewport};
use crate::runtime::reads::BindKey;
use crate::runtime::replay::{self, Record};
use egui::{Context, Id, LayerId, Layout, Rect, Vec2};
use egui::{Context, Id, Layout, Rect, Vec2};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -124,7 +125,7 @@ pub(crate) struct Place {
/// The region its parent offered it.
pub(crate) room: Rect,
pub(crate) clip: Rect,
pub(crate) layer: LayerId,
pub(crate) layer: Layer,
pub(crate) layout: Layout,
pub(crate) pixels_per_point: f32,
}
@@ -261,7 +262,7 @@ pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, pl
});
let targets = focus::targets(ctx);
let now = frame::clock(ctx);
let held = (ctx.dragged_id(), ctx.memory(|memory| memory.focused()));
let held = (input_state::dragged(ctx), focus_state::focused(ctx));
let settled = with(ctx, |store, pass_nr, frame| {
if store.changes.scanned != pass_nr {
store.changes.scanned = pass_nr;
@@ -318,8 +319,7 @@ pub(crate) fn settled(ctx: &Context, owner: Option<Id>, id: Id, sizing: bool, pl
fn engaged(ctx: &Context, settled: &Settled) -> bool {
let rect = settled.rect.intersect(settled.place.clip);
let screen = ctx.layer_transform_to_global(settled.place.layer).map_or(rect, |transform| transform * rect);
ctx.rect_contains_pointer(settled.place.layer, rect)
|| ctx.input(|input| input.pointer.any_down() && input.pointer.press_origin().is_some_and(|origin| screen.contains(origin)))
ctx.rect_contains_pointer(settled.place.layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin))
}
/// Adds the last real run of the settling child `id` to the running pass, in place of running it.
+2 -2
View File
@@ -370,8 +370,8 @@ pub(crate) fn part_bounds(ctx: &Context, owner: Id, part: craft_behavior::PartRe
/// [`part_bounds`] of the owner whose AccessKit node is `node`, for a test that holds the node it found, not the id.
#[cfg(feature = "testing")]
pub(crate) fn node_part_bounds(ctx: &Context, node: accesskit::NodeId, part: craft_behavior::PartRef) -> Option<egui::Rect> {
owned_part_bounds(ctx, |shape_owner| shape_owner.accesskit_id() == node, part)
pub(crate) fn node_part_bounds(ctx: &Context, node: crate::runtime::egui::access::NodeId, part: craft_behavior::PartRef) -> Option<egui::Rect> {
owned_part_bounds(ctx, |shape_owner| crate::runtime::egui::access::node_id(shape_owner) == node, part)
}
fn owned_part_bounds(ctx: &Context, owner: impl Fn(Id) -> bool, part: craft_behavior::PartRef) -> Option<egui::Rect> {
+3 -2
View File
@@ -9,11 +9,12 @@
//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another
//! layer, a label scope open around it). Such a record is never replayed: the region runs.
use crate::runtime::egui::areas::Layer;
use crate::runtime::focus::{self, Transcript};
use crate::runtime::frame;
use crate::runtime::pass_state;
use crate::runtime::reads::BindKey;
use egui::{Context, Id, LayerId};
use egui::{Context, Id};
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -86,7 +87,7 @@ pub(crate) fn open(ctx: &Context) {
}
/// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it.
pub(crate) fn close(ctx: &Context, layer: LayerId) -> Record {
pub(crate) fn close(ctx: &Context, layer: Layer) -> Record {
OPEN.fetch_sub(1, Ordering::AcqRel);
let (open, journal) = pass_state::with::<Recorder, _>(ctx, |recorder| {
// A close with no open record ends one that holds nothing and is never replayed.
+3 -1
View File
@@ -7,6 +7,7 @@ mod key;
mod look;
mod paint;
mod replacements;
mod span;
mod state;
mod surface;
pub(crate) mod text_measure;
@@ -28,8 +29,9 @@ pub use paint::{
};
pub(crate) use paint::{min_thumb, scroll_bar_look};
pub use replacements::{DuplicateStyle, StyleReplacements};
pub use span::Span;
pub use state::StateSet;
pub use surface::{SurfaceEdge, SurfaceStyle};
pub use surface::{BandFill, SurfaceEdge, SurfaceStyle};
pub use tokens::UiTokens;
#[doc(hidden)]
+92
View File
@@ -0,0 +1,92 @@
//! `Span`: one styled stretch of a text run.
use std::borrow::Cow;
/// One styled stretch of a run.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Span<'a> {
/// The text.
pub text: Cow<'a, str>,
/// Italic.
pub italic: bool,
/// Tabular figures.
pub tabular: bool,
/// The monospace face.
pub mono: bool,
/// The muted text colour.
pub muted: bool,
/// A shortcut hint: muted.
pub shortcut: bool,
/// A search match highlight.
pub highlight: bool,
/// Underlined in the span's colour, `stroke.thin` wide, along the bottom of the line box.
pub underline: bool,
/// The role's semibold face, at the role's size.
pub strong: bool,
}
impl<'a> Span<'a> {
/// A plain span.
pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
Span {
text: text.into(),
italic: false,
tabular: false,
mono: false,
muted: false,
shortcut: false,
highlight: false,
underline: false,
strong: false,
}
}
/// Italic.
pub fn italic(mut self) -> Self {
self.italic = true;
self
}
/// Tabular figures.
pub fn tabular(mut self) -> Self {
self.tabular = true;
self
}
/// The monospace face.
pub fn mono(mut self) -> Self {
self.mono = true;
self
}
/// The muted colour.
pub fn muted(mut self) -> Self {
self.muted = true;
self
}
/// A shortcut hint.
pub fn shortcut(mut self) -> Self {
self.shortcut = true;
self
}
/// A match highlight.
pub fn highlight(mut self) -> Self {
self.highlight = true;
self
}
/// Underlined: a link, or the mnemonic letter of a menu title.
pub fn underline(mut self) -> Self {
self.underline = true;
self
}
/// The role's semibold face: a short mark that stands out among the row's other text, such as a layer's `fx`.
pub fn strong(mut self) -> Self {
self.strong = true;
self
}
}
+5
View File
@@ -21,6 +21,11 @@ impl StateSet {
StateSet { state, flags, t }
}
/// The component is disabled.
pub fn is_disabled(&self) -> bool {
self.state == State::Disabled
}
/// The value of `look` in this state.
pub fn resolve<T: Mix>(&self, look: &Stateful<T>) -> T {
look.resolve(self.state, self.flags, self.t)
+12 -2
View File
@@ -2,10 +2,20 @@
use super::look::SurfaceKind;
use super::tokens::UiTokens;
use crate::contract::BandFill;
use craft_theme::variant::Tone;
use craft_theme::{Edge, Elevation, Rgba, Stroke as StrokeStep};
use egui::{Color32, CornerRadius, Shadow, Stroke};
/// What the band behind a header paints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BandFill {
/// A surface's fill.
Surface(SurfaceKind),
/// A tone's tinted fill (`Tone::soft_fill`).
Tone(Tone),
}
/// A surface's edge, resolved from the theme's edge style.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
@@ -81,7 +91,6 @@ fn shadow(e: Elevation) -> Option<Shadow> {
(shadow.color.a() > 0).then_some(shadow)
}
/// The look of `kind` in `tokens`.
/// The colour a band behind a header paints: the surface's fill, or the tone's tinted fill.
pub(crate) fn band_color(tokens: &UiTokens, fill: BandFill) -> Color32 {
match fill {
@@ -90,6 +99,7 @@ pub(crate) fn band_color(tokens: &UiTokens, fill: BandFill) -> Color32 {
}
}
/// The look of `kind` in `tokens`.
pub(crate) fn surface_style(tokens: &UiTokens, kind: SurfaceKind) -> SurfaceStyle {
use SurfaceKind as K;
let c = &tokens.color;
+1 -1
View File
@@ -2,9 +2,9 @@
//! the width of a line. `TextRun` lays out through the first two and `StyleCx::text_width` through the third, so the
//! sizes that follow the text agree with the text that is drawn.
use super::Span;
use super::tokens::UiTokens;
use crate::fonts::StackFacts;
use crate::primitives::Span;
use crate::runtime::egui::text_layout;
use craft_i18n::Direction;
use craft_theme::TypeRole;
@@ -2,7 +2,7 @@
use crate::runtime::commands::{CommandInput, CommandSet as _, EditCommands, NavCommand};
use crate::runtime::drag::{self, DragPreview};
use crate::runtime::egui::fixture;
use crate::runtime::egui::{areas, fixture};
use crate::runtime::env::RootEnv;
use crate::runtime::focus::{EditSet, FocusTarget, KeepKeys, KeyUse, host_canvas, request};
use crate::runtime::frame::{ChromeToggle, take_output};
@@ -163,16 +163,16 @@ fn an_open_egui_popup_keeps_escape() {
let (host, mut base) = host_window();
let mut show = move |ui: &mut Ui| {
base(ui);
fixture::host_popup(ui, popup, Pos2::ZERO);
areas::host_popup(ui, popup, Pos2::ZERO);
};
let mut frames = Frames::new();
frames.frame(Vec::new(), &mut show);
fixture::open_host_popup(&frames.ctx, popup);
areas::open_host_popup(&frames.ctx, popup);
frames.frame(Vec::new(), &mut show);
assert!(fixture::host_popup_open(&frames.ctx, popup));
assert!(areas::host_popup_open(&frames.ctx, popup));
press_key(&mut frames, &mut show, Key::Escape);
assert_eq!(seen(&host), (vec![Key::Escape], 0), "the popup's Escape is egui's");
assert!(!fixture::host_popup_open(&frames.ctx, popup), "egui closed the popup");
assert!(!areas::host_popup_open(&frames.ctx, popup), "egui closed the popup");
frames.frame(Vec::new(), &mut show);
press_key(&mut frames, &mut show, Key::Escape);
assert_eq!(seen(&host), (Vec::new(), 1), "with the popup closed, Escape is the window's Cancel again");
+5 -1
View File
@@ -95,7 +95,11 @@ pub fn cancel_captured_presses(ctx: &egui::Context) {
/// pass: how a host test that found a component by its node (a list row by its name) finds a pointer-only part of it
/// (a thumbnail, a drag handle), which has no node of its own. [`Fixture::part_rect`](super::Fixture::part_rect) is
/// the same lookup by the component's id. Callers assert how rects relate (inside, below), not their size.
pub fn part_rect_of_node(ctx: &egui::Context, node: accesskit::NodeId, part: impl Into<craft_behavior::PartRef>) -> Option<egui::Rect> {
pub fn part_rect_of_node(
ctx: &egui::Context,
node: crate::runtime::egui::access::NodeId,
part: impl Into<craft_behavior::PartRef>,
) -> Option<egui::Rect> {
crate::runtime::pointer::node_part_bounds(ctx, node, part.into())
}
@@ -16,6 +16,26 @@ pub fn above(a: Rect, b: Rect) -> bool {
a.max.y <= b.min.y + EPS
}
/// `lower` starts below where `upper` ends, with a gap between them.
pub fn apart_above(upper: Rect, lower: Rect) -> bool {
lower.min.y > upper.max.y + EPS
}
/// `inner` ends above the foot of `outer`, not on it.
pub fn off_foot(inner: Rect, outer: Rect) -> bool {
inner.max.y < outer.max.y - EPS
}
/// `a` and `b` start at the same left edge.
pub fn aligned_left(a: Rect, b: Rect) -> bool {
(a.min.x - b.min.x).abs() <= EPS
}
/// `a` and `b` stand in one column: the same left edge and the same width.
pub fn same_column(a: Rect, b: Rect) -> bool {
aligned_left(a, b) && (a.width() - b.width()).abs() <= EPS
}
/// `inner` lies within `outer`.
pub fn inside(inner: Rect, outer: Rect) -> bool {
inner.min.x >= outer.min.x - EPS && inner.min.y >= outer.min.y - EPS && inner.max.x <= outer.max.x + EPS && inner.max.y <= outer.max.y + EPS
+6 -1
View File
@@ -331,7 +331,12 @@ impl StoryBody {
}
if let (Some((key, layers)), Some(recorded)) = (self.inspect, recorded) {
let pointed = inspect::pointed(ui.ctx(), key);
InspectOverlay::new(recorded).layers(layers).pointed(pointed).show_at(ui, surface.output.rect);
let overlay = InspectOverlay::new(recorded).layers(layers);
let overlay = match pointed {
Some(index) => overlay.pointed(index),
None => overlay,
};
overlay.show_at(ui, surface.output.rect);
}
if let Some(shown) = ran.get() {
let dialog = &mut state.dialog;
+2
View File
@@ -31,6 +31,7 @@ const ONE: &[ColumnWidth] = &[ColumnWidth::fill(1.0)];
const TWO: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 2];
/// One story of a card to show.
#[non_exhaustive]
pub struct SpecStory {
/// The index of the story in the catalog.
pub index: usize,
@@ -49,6 +50,7 @@ impl SpecStory {
}
/// The card of one component to show, before it is laid out.
#[non_exhaustive]
pub struct Spec {
/// The id scope of the card.
pub key: String,
@@ -3,7 +3,7 @@
use craft_behavior::{CancelReason, EditEvent, EditEvents, EditPolicy as Policy, GestureId};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Gap, Pad, Pattern, Props, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Gap, Pad, Pattern, Props, Show as _, ShowContainer as _, clicked};
use craft_ui::display::{Shade, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::edit::cancel_all;
@@ -160,10 +160,10 @@ impl EditPolicy {
state.events("field", &label, Before::Label);
});
Row::new().gap(Gap::Item).show(ui, |ui, _| {
if Button::new("Undo during gesture").show(ui).clicked() {
if clicked(&Button::new("Undo during gesture").show(ui)) {
state.undo(ui);
}
if Button::new("Switch document").show(ui).clicked() {
if clicked(&Button::new("Switch document").show(ui)) {
state.switch(ui);
}
});
+6 -5
View File
@@ -10,6 +10,7 @@ use crate::layout_components::Row;
use crate::runtime::overlay::CloseReason;
use crate::sections::{DialogRole, FooterButton};
use crate::testing::input::key_press;
use crate::testing::relations::{apart_above, grows_with, inside, off_foot, same_column};
use crate::testing::{Fixture, Frames, trial};
use crate::text::TextField;
use egui::{Key, Modifiers, Rect, Ui};
@@ -171,9 +172,9 @@ fn a_dialogs_body_stands_apart_from_its_header_and_its_footer() {
else {
panic!("every part is shown");
};
assert!(body.min.y > title.max.y + 1.0, "a space separates the body from the title row's rule: {title:?} {body:?}");
assert!(ok.min.y > body.max.y + 1.0, "a space separates the body from the footer: {body:?} {ok:?}");
assert!(ok.max.y < dialog.max.y - 1.0, "the buttons stay off the dialog's foot: {ok:?} {dialog:?}");
assert!(apart_above(title, body), "a space separates the body from the title row's rule: {title:?} {body:?}");
assert!(apart_above(body, ok), "a space separates the body from the footer: {body:?} {ok:?}");
assert!(inside(ok, dialog) && off_foot(ok, dialog), "the buttons stay off the dialog's foot: {ok:?} {dialog:?}");
}
#[trial]
@@ -215,10 +216,10 @@ fn side_buttons_stand_in_one_column_beside_the_body() {
};
assert!(ok.max.y <= cancel.min.y && cancel.max.y <= other.min.y, "OK, Cancel, then the other button, top to bottom");
for button in [cancel, other] {
assert!((button.min.x - ok.min.x).abs() < 0.5 && (button.width() - ok.width()).abs() < 0.5, "one column, one width: {ok:?} {button:?}");
assert!(same_column(ok, button), "one column, one width: {ok:?} {button:?}");
}
assert!(ok.min.x >= body.max.x, "the column stands past the body's end edge");
assert!((ok.min.y - body.min.y).abs() < 4.0, "the column starts at the body's top: {ok:?} {body:?}");
assert!(grows_with(body.min.y, ok.min.y) && ok.min.y <= body.center().y, "the column starts at the body's top: {ok:?} {body:?}");
assert!(preview.min.y >= other.max.y, "the footer content sits under the buttons");
}
+8 -5
View File
@@ -284,7 +284,7 @@ impl<'a, P: Clone + Hash + Send + Sync + 'static> DockGroup<'a, P> {
}
/// Whether the panel menu button shows: it is asked for and the menu has rows.
fn menu_button(&self) -> bool {
fn shows_menu_button(&self) -> bool {
self.panel_menu_shown && !self.menu.is_empty()
}
@@ -324,7 +324,7 @@ impl<P: Clone + Hash + Send + Sync + 'static> Component for DockGroup<'_, P> {
let (band, rest) = flow.take_start(grip_width(&cx.tokens.size.handle));
let sense = if self.movable { Sense::CLICK | Sense::DRAG | Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS };
let _ = cx.header_part(HeaderEdge::End, GRIP, band).sense(sense).focusable();
if self.menu_button() {
if self.shows_menu_button() {
// An icon button is square: its side is the slot's room past the band and the gap.
let side = (slot.width() - grip_width(&cx.tokens.size.handle) - cx.tokens.space.gap.item).max(0.0);
let end = rest.take_end(side).0;
@@ -414,8 +414,11 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
/// The drag band, then the panel menu button when it shows, at the header's end edge.
fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts {
let band = grip_width(&cx.tokens.size.handle);
let button =
if self.menu_button() { cx.tokens.space.gap.item + cx.face(Self::menu_face(cx.words::<DockWords>().panel_menu.clone())).x } else { 0.0 };
let button = if self.shows_menu_button() {
cx.tokens.space.gap.item + cx.face(Self::menu_face(cx.words::<DockWords>().panel_menu.clone())).x
} else {
0.0
};
HeaderParts::NONE.end(band + button)
}
@@ -445,7 +448,7 @@ impl<P: Clone + Hash + Send + Sync + 'static> Container for DockGroup<'_, P> {
let drags = crate::runtime::drag::started(ui.ctx());
let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) };
ui.with_layout(layout, |ui| {
ui.spacing_mut().item_spacing.x = gap;
ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap)
if let Some(hook) = extra.as_mut() {
hook.run(ui, cx);
}
+4 -7
View File
@@ -105,7 +105,7 @@ pub struct IconicColumnStyle {
/// The ink of a panel's name in a wide column.
name: StyleColor,
/// The ink of the name of the panel whose flyout is open.
name_selected: StyleColor,
name_open: StyleColor,
/// The room between an icon and its name.
name_gap: f32,
}
@@ -311,7 +311,7 @@ impl<P: Value + Hash + 'static> Component for IconicColumn<'_, P> {
metrics: Metrics::new(),
sizes: IconicSizes::style(cx),
name: cx.color(colors.text.normal),
name_selected: cx.color(colors.accent.text),
name_open: cx.color(colors.accent.text),
name_gap: cx.tokens.space.gap.item,
}
}
@@ -445,7 +445,7 @@ impl<P: Value + Hash + 'static> Component for IconicColumn<'_, P> {
if let Some(name) = self.laid.as_ref().and_then(|plan| plan.names.get(at)) {
let style = &cx.style;
let room = if cx.flow.is_rtl() { name.with_max_x(name.max.x - style.name_gap) } else { name.with_min_x(name.min.x + style.name_gap) };
let ink = if selected { style.name_selected } else { style.name };
let ink = if selected { style.name_open } else { style.name };
let _ = ui.draw().text(room, &TextRun::new(spec.label.as_str().to_owned()).color(ink).elide());
}
ui.face(CELL.at(at as u64), IconButton::new(icon).label(spec.label).selected(selected));
@@ -554,10 +554,7 @@ impl<P: Value + Hash + 'static> Container for IconicColumn<'_, P> {
/// The chevron's square at the bar's outer end.
fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts {
let side = cx.style.sizes.column.bar;
match chevron_edge(self.edge) {
HeaderEdge::Start => HeaderParts::NONE.start(side),
HeaderEdge::End => HeaderParts::NONE.end(side),
}
if chevron_edge(self.edge) == HeaderEdge::End { HeaderParts::NONE.end(side) } else { HeaderParts::NONE.start(side) }
}
/// The column bar, over the icons. What the user did on it is read in `finish`.
@@ -27,7 +27,7 @@ fn at_stage<'a>(
) -> IconicColumnOutput<u8> {
let room = stage(ui);
let env = Env::of(ui);
let width = env.tokens.tokens().size.rail.width;
let width = env.tokens.tokens().size.rail.width; // design: allow[style/token-read](a story sizes its stage from the rail token)
let cell = if env.direction.is_rtl() {
Rect::from_min_max(room.min, egui::pos2(room.left() + width, room.bottom()))
} else {
@@ -15,6 +15,9 @@ fn spec(panel: &u8) -> PanelSpec {
PanelSpec::new(if *panel == 0 { "Brushes" } else { "Swatches" })
}
/// The width of the column that shows names beside its icons.
const WIDE_COLUMN: f32 = 200.0;
/// A column `width` wide over two icon-less panels, and the panel whose flyout is open.
fn column(width: f32) -> (Fixture, Rc<Cell<Option<u8>>>) {
let open = Rc::new(Cell::new(None));
@@ -42,10 +45,10 @@ fn an_icon_less_panel_shows_its_initial_and_a_wide_column_shows_names_that_open_
assert!(painted(&narrow, "B") && painted(&narrow, "S"), "each icon-less panel shows its initial");
assert!(!painted(&narrow, "Brushes"), "a narrow column shows no names");
let (mut wide, open) = column(200.0);
let (mut wide, open) = column(WIDE_COLUMN);
assert!(painted(&wide, "Brushes") && painted(&wide, "Swatches"), "a wide column shows the names");
let icon = wide.by_label("Swatches").expect("the Swatches icon");
assert!(icon.rect.width() < 200.0 / 2.0, "the icon keeps its square at the start: {:?}", icon.rect);
assert!(icon.rect.width() < WIDE_COLUMN, "the icon keeps its square at the start: {:?}", icon.rect);
// The name has no node of its own: the icon is its keyboard stop. Click on it, past the icon.
wide.click_at(icon.rect.right_center() + Vec2::new(icon.rect.width(), 0.0)).idle(3);
assert_eq!(open.get(), Some(1), "a click on the name opens its panel's flyout");
+3 -7
View File
@@ -67,6 +67,9 @@ pub struct DockRoot<'a, T: 'static> {
props: ContainerProps,
take_drop: TakeDrop<'a, T>,
dropped: Option<T>,
/// The arrangement the pattern shows, which the drags started in the body record.
#[doc(hidden)]
#[prop]
shows: Option<Arrangement>,
}
@@ -82,13 +85,6 @@ impl<'a, T: 'static> DockRoot<'a, T> {
shows: None,
}
}
/// The arrangement the pattern shows, which the drags started in the body record.
#[doc(hidden)]
pub fn shows(mut self, arrangement: Arrangement) -> Self {
self.shows = Some(arrangement);
self
}
}
impl<T: 'static> Component for DockRoot<'_, T> {
@@ -7,6 +7,7 @@ use crate::contract::Show as _;
use crate::rails::tool::stories::{StoryTools, tools};
use crate::runtime::commands::CommandState;
use crate::testing::pointer::{moved, wheel};
use crate::testing::relations::{above, grows_with};
use crate::testing::{Fixture, trial};
use egui::{Rect, Shape, Vec2};
use std::cell::Cell;
@@ -41,8 +42,8 @@ fn in_a_short_window_the_icons_scroll_above_the_footer_that_stays_in_view() {
}
fixture.settle();
let last = rect(&fixture, "Clone Stamp");
assert!(last.top() >= first.top() - 0.5, "{height}: the last icon is in view after scrolling: {last:?}");
assert!(last.bottom() <= foot.top() + 0.5, "{height}: the last icon is above the footer after scrolling: {last:?}");
assert!(grows_with(first.top(), last.top()), "{height}: the last icon is in view after scrolling: {last:?}");
assert!(above(last, foot), "{height}: the last icon is above the footer after scrolling: {last:?}");
assert_eq!(rect(&fixture, "Foot"), foot, "{height}: the footer stays put");
}
}
@@ -6,6 +6,7 @@ use crate::canvas_data::GuideColor;
use crate::contract::Bind;
use crate::runtime::env::UnitKind;
use crate::runtime::requests::ColorRequest;
use crate::testing::relations::{aligned_left, grows_with};
use crate::testing::{Fixture, trial};
use craft_theme::Rgba;
use std::cell::{Cell, RefCell};
@@ -31,7 +32,7 @@ fn the_preview_check_box_under_the_side_buttons_starts_on_at_every_open() {
let (Some(preview), Some(ok)) = (fixture.by_label("Preview"), fixture.by_label("OK")) else {
panic!("the Preview check box and OK are shown");
};
assert!(preview.rect.min.y >= ok.rect.max.y && (preview.rect.min.x - ok.rect.min.x).abs() < 0.5, "Preview sits under the buttons");
assert!(grows_with(ok.rect.max.y, preview.rect.min.y) && aligned_left(ok.rect, preview.rect), "Preview sits under the buttons");
fixture.click(&preview);
fixture.settle();
assert!(!previewing.get(), "with Preview off the dialog previews nothing");
@@ -242,7 +242,7 @@ pub struct PreviewPane<'a> {
click_centres: bool,
/// The well's width over its height: the pane is as tall as its width over this. Without one, the height is the
/// one its container gives, at least the plot height.
#[prop]
#[prop(quantity = "aspect ratio")]
aspect: Option<f32>,
/// The view after this pass, when the user changed it.
moved: Option<PreviewView>,
@@ -230,7 +230,7 @@ impl RowData {
/// One line: the label, then the menu path, which drops out when the label would get too narrow, and the chord
/// at the end.
fn row(&self) -> ListRow<'static> {
let row = ListRow::new(self.label.clone()).option().command().enabled(self.enabled);
let row = ListRow::new(self.label.clone()).option().command_row().enabled(self.enabled);
// The first trailing item is the outermost: the chord ends the row and the path sits before it.
let row = match &self.chord {
Some(chord) => row.trailing(chord.clone()),
@@ -23,9 +23,9 @@ use std::cell::RefCell;
use std::sync::Arc;
/// The size the window opens at until the user resizes it.
pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0);
pub const DEFAULT_SIZE: Vec2 = vec2(1040.0, 800.0); // design: allow[literal-size/vec2](the window's own opening size in points)
/// The least size the window may be resized to.
pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0);
pub const MIN_SIZE: Vec2 = vec2(560.0, 400.0); // design: allow[literal-size/vec2](the window's own least size in points)
/// What the window keeps between passes; the host owns it and binds it with [`PreferencesWindow::new`].
#[derive(Clone, Debug, Default, PartialEq)]
@@ -252,7 +252,7 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
max_rows: Option<u16>,
/// The browser takes the presets' height, up to `room_height` (then they scroll), instead of the available
/// height: for a host that sizes to its content, such as a floating panel.
#[prop]
#[prop(quantity = "room the host's panel offers, in points")]
room_height: Option<f32>,
/// The columns of tiles the grid asks for where it takes its width from its content (a popover): its width holds
/// this many tiles. 0 asks for none.
+5 -8
View File
@@ -264,7 +264,10 @@ pub struct AppShell<'a, S> {
window: WindowKey,
bare: bool,
embedded: bool,
/// An embedded shell as tall as its content, with the most a body that fills takes.
/// An embedded shell as wide as the room of the flow it is shown in and as tall as its body's content and its top
/// and bottom slots, from the measure its body keeps while its inputs hold; a body that fills takes at most this
/// room. Shown with [`show`](Self::show), it takes that room in the flow.
#[prop(name = "content_height", quantity = "room the host's flow offers, in points")]
content_room: Option<f32>,
/// The screen mode. Without a binding the shell keeps it, starting at `Standard`.
#[prop]
@@ -320,13 +323,6 @@ impl<'a, S> AppShell<'a, S> {
AppShell { embedded: true, ..Self::new(window) }
}
/// An embedded shell as wide as the room of the flow it is shown in and as tall as its body's content and its top
/// and bottom slots, from the measure its body keeps while its inputs hold; a body that fills takes at most `room`.
/// Shown with [`show`](Self::show), it takes that room in the flow.
pub fn content_height(self, room: f32) -> Self {
AppShell { embedded: true, content_room: Some(room), ..self }
}
/// The title bar slot, the first top slot, keyed `"title"`: visible, and revealing in body-only mode. The title bar
/// types fill it.
pub fn title_bar(self, add: impl FnMut(&mut Ui, &mut BodyCx<'_>, &mut S) + 'a) -> Self {
@@ -419,6 +415,7 @@ impl<'a, S> AppShell<'a, S> {
slots,
mut body,
} = self;
let embedded = embedded || content_room.is_some();
let env = Env::of(ui);
let outer = env.get::<ShellEntry>().0;
let words = env.words::<ShellWords>();
+9 -3
View File
@@ -6,6 +6,8 @@
//! [`crate::runtime::keys::with_window_intents`], last in the app's UI.
use crate::fonts::{Stack, UiFonts};
#[cfg(feature = "app")]
use crate::runtime::egui::memory;
use crate::runtime::frame::{FrameInput, FrameOutput, set_input, take_output};
use crate::runtime::windows;
use crate::runtime::{InstallError, InstallSpec};
@@ -62,15 +64,19 @@ pub fn before_ui(ctx: &Context, frame: &eframe::Frame) {
fit_once(ctx);
}
/// Whether the fit has run for this context.
#[cfg(feature = "app")]
#[derive(Default)]
struct Fitted(bool);
/// Runs [`fit_first`] from the first passes until its monitor is known, then never again for this context.
#[cfg(feature = "app")]
fn fit_once(ctx: &Context) {
let key = egui::Id::unique("craft_ui_shell::embed::fitted");
if ctx.data(|data| data.get_temp::<bool>(key)).unwrap_or(false) {
if memory::with::<Fitted, _>(ctx, |fitted| fitted.0) {
return;
}
if fit_first(ctx) {
ctx.data_mut(|data| data.insert_temp(key, true));
memory::with::<Fitted, _>(ctx, |fitted| fitted.0 = true);
}
}
+4 -8
View File
@@ -44,7 +44,10 @@ impl Outcome for ViewportWindowOutput {
#[derive(Pattern, Props)]
pub struct ViewportWindow {
title: Label,
/// What lies over the app's other windows while this one is open and blocks them; `None` blocks nothing.
/// Makes the app's other windows ignore input while this one is open, with `backdrop` over them where the window is
/// a layer (`Backdrop::Scrim` dims them, `Backdrop::None` leaves them as they are). Without it the window blocks
/// nothing.
#[prop(name = "app_modal")]
modal: Option<Backdrop>,
/// Changes the layer the window has where windows are unavailable, whose limits and place its OS window takes.
overlay: Option<Box<dyn FnOnce(Overlay) -> Overlay>>,
@@ -59,13 +62,6 @@ impl ViewportWindow {
ViewportWindow { title: title.into(), modal: None, overlay: None, remember: None }
}
/// Makes the app's other windows ignore input while this one is open, with `backdrop` over them where the window is
/// a layer (`Backdrop::Scrim` dims them, `Backdrop::None` leaves them as they are).
pub fn app_modal(mut self, backdrop: Backdrop) -> Self {
self.modal = Some(backdrop);
self
}
/// Changes the layer the window falls back to, which starts as the resizable dialog layer: the smallest and
/// largest size (`Overlay::size_limits`), the place (`Overlay::placed`) and the resizability. Calls compose in
/// order.
+1 -1
View File
@@ -93,7 +93,7 @@ impl StatusProgress {
let percent = Env::of(ui).format().percent(f64::from(Progress::clamped(fraction)), 0);
Text::new(percent).role(TypeRole::Mono).shade(Shade::Muted).show(ui);
}
let cancelled = self.cancel.is_some_and(|label| IconButton::new(IconId::new("close")).label(label).show(ui).clicked());
let cancelled = self.cancel.is_some_and(|label| crate::contract::clicked(&IconButton::new(IconId::new("close")).label(label).show(ui)));
StatusProgressOutput { response, cancelled }
}
}
@@ -56,15 +56,24 @@ pub struct InspectOverlayStyle {
/// ```ignore
/// let (_, recorded) = inspect::record(ui, key, |ui| story(ui));
/// if let Some(recorded) = recorded {
/// InspectOverlay::new(recorded).pointed(inspect::pointed(ui.ctx(), key)).show_at(ui, rect);
/// let overlay = InspectOverlay::new(recorded);
/// match inspect::pointed(ui.ctx(), key) {
/// Some(index) => overlay.pointed(index),
/// None => overlay,
/// }
/// .show_at(ui, rect);
/// }
/// ```
#[derive(crate::contract::Component)]
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct InspectOverlay {
#[common]
common: Common,
recorded: Arc<Recorded>,
/// The layers shown.
#[prop]
layers: InspectLayers,
/// Marks the element at this index of the record, the one the inspector's list points at.
#[prop]
pointed: Option<usize>,
}
@@ -73,18 +82,6 @@ impl InspectOverlay {
pub fn new(recorded: Arc<Recorded>) -> Self {
InspectOverlay { common: Common::new(), recorded, layers: InspectLayers::default(), pointed: None }
}
/// The layers shown.
pub fn layers(mut self, layers: InspectLayers) -> Self {
self.layers = layers;
self
}
/// Marks the element at this index of the record, the one the inspector's list points at.
pub fn pointed(mut self, pointed: Option<usize>) -> Self {
self.pointed = pointed;
self
}
}
/// The band between `outer` and `content` as up to four rects.
@@ -191,20 +188,3 @@ impl InspectOverlay {
}
}
}
#[cfg(test)]
mod tests {
use super::band_parts;
use egui::{Rect, pos2, vec2};
#[test]
fn the_padding_band_is_the_outer_rect_less_the_content() {
let outer = Rect::from_min_max(pos2(0.0, 0.0), pos2(20.0, 10.0));
let content = outer.shrink2(vec2(4.0, 2.0));
let parts: Vec<Rect> = band_parts(outer, content).collect();
let area: f32 = parts.iter().map(|part| part.area()).sum();
assert_eq!(area, outer.area() - content.area());
assert!(parts.iter().all(|part| !part.intersects(content.shrink(0.1))));
assert_eq!(band_parts(outer, outer).count(), 0);
}
}
+4 -9
View File
@@ -149,8 +149,10 @@ pub struct ListRow<'a> {
#[style_key]
#[prop]
pub(super) role: Option<TypeRole>,
/// How tall the row is: its collection sets it from `CollectionProps::row_height` in `Collection::dress`.
/// The row is `rows` tall: the height its collection's rows take. Its collection sets it from
/// `CollectionProps::row_height` in `Collection::dress`.
#[style_key]
#[prop]
pub(super) rows: RowHeight,
/// The sub-row form, from the collection's row state (`RowState::sub_row`): a small control high, the icon and
/// toggle marks at the small control's icon side, and its toggle cells `sub_steps` indent steps into its content
@@ -265,7 +267,7 @@ pub struct ListRow<'a> {
/// On an option that runs a command (a command palette's row): the lead row is the command highlight, as a menu's,
/// and no edge outlines the lead or the chosen row.
#[style_key]
#[prop(flag)]
#[prop(flag, name = "command_row")]
pub(super) command: bool,
/// On an option of a list that picks a value: the row keeps a mark column, with the check mark when `true`.
#[prop]
@@ -378,13 +380,6 @@ impl<'a> ListRow<'a> {
self
}
/// The row is `rows` tall: the height its collection's rows take.
#[must_use]
pub(crate) fn rows(mut self, rows: RowHeight) -> Self {
self.rows = rows;
self
}
/// The sub-row form and the divider under the row, from the collection's row state.
#[must_use]
pub(crate) fn sub_row(mut self, row: &RowState) -> Self {
+2 -2
View File
@@ -422,8 +422,8 @@ impl ListRow<'_> {
.iter()
.zip(&kept)
.filter(|(_, kept)| **kept)
.map(|(item, _)| ShrinkUnit { ideal: item.width, least: item.least })
.chain(std::iter::once(ShrinkUnit { ideal: indent_full, least: 0.0 }))
.map(|(item, _)| ShrinkUnit::new(item.width, item.least))
.chain(std::iter::once(ShrinkUnit::new(indent_full, 0.0)))
.collect();
let gaps = kept.iter().filter(|kept| **kept).count() as f32 * sizes.gap;
let mut given = shrink_widths(&units, base + column + leading_width + sizes.min_label + gaps, end, ShrinkOrder::Even);
+1 -1
View File
@@ -42,7 +42,7 @@ pub struct TableStyle {
/// for the app to save. A table of groups and their children is a tree: the label column is
/// indented by depth and groups open and close as in a `List`.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(collection, probe(Table<'static, usize>))]
#[component(collection, overlay, probe(Table<'static, usize>))]
pub struct Table<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
#[common]
common: Common,
+1
View File
@@ -109,6 +109,7 @@ pub struct AltTextFieldStyle {
/// An alt text editor: a multi-line description box and a Mark as decorative check. While the check is on, the box
/// keeps its text and does not edit it. The field's label is the prompt that names the box.
#[derive(crate::contract::Component)]
#[component(overlay)]
pub struct AltTextField<'a> {
#[common]
common: Common,
+3 -3
View File
@@ -152,11 +152,11 @@ impl<'a> Slider<'a> {
self
}
/// The kept part of the range, from `start` to `end`: a trimmed clip's In and Out on a seek track. Each end is a
/// The kept part of the range, `kept`: a trimmed clip's In and Out on a seek track. Each end is a
/// line across the track, a thumb high, in the warning colour; the thumb does not snap to them. An end outside
/// the range is not drawn.
pub fn trim(mut self, start: f64, end: f64) -> Self {
self.trim = Some((start, end));
pub fn trim(mut self, kept: std::ops::RangeInclusive<f64>) -> Self {
self.trim = Some((*kept.start(), *kept.end()));
self
}
+1 -1
View File
@@ -43,7 +43,7 @@ impl Slide {
slider = slider.wheel_step(step);
}
if let Some((start, end)) = self.trim {
slider = slider.trim(start, end);
slider = slider.trim(start..=end);
}
self.events.borrow_mut().extend(slider.show_at(ui, FIELD).events);
}
-15
View File
@@ -3,21 +3,6 @@ paths = ["crates/behavior", "crates/ui", "crates/ui-contract", "crates/ui-widget
include-tests = false
deny-unused = true
[[exempt]]
path = "crates/ui-contract/src/runtime/egui"
rules = ["style-mutation"]
reason = "the egui adapter: the one place that sets egui's style and zoom from the theme"
[[exempt]]
path = "crates/ui-contract/src/testing"
rules = ["literal-size"]
reason = "test fixtures: rooms, drag offsets and window sizes, not looks"
[[exempt]]
path = "crates/ui-canvas/src/canvas/testing"
rules = ["literal-size"]
reason = "test fixtures: rooms, drag offsets and window sizes, not looks"
[[exempt]]
path = "crates/ui-panels/src/rails/panel_rail/trials.rs"
rules = ["literal-size"]
+8
View File
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "artboard-story-backgrounds"
kind = "marker"
rule = "raw-colour/const"
path = "crates/draw/src/ui/artboard/stories.rs"
reason = "The artboard background is document data in a story, not a UI colour."
count = 2
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "preview-picture-bars"
kind = "marker"
rule = "raw-colour/const"
path = "crates/timeline/src/ui/preview.rs"
reason = "The bars around a video picture are black in every theme, as in a video player."
count = 1
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "view-fit-margins"
kind = "marker"
rule = "literal-size/vec2"
path = "crates/ui-canvas/src/canvas/tools.rs"
reason = "The room a view fit leaves around the document is in screen points, not a look."
count = 2
@@ -1,2 +1,25 @@
config_version = 1
[[exception]]
name = "dock-header-gap"
kind = "marker"
rule = "style-mutation"
path = "crates/ui-panels/src/docking/group.rs"
reason = "The header lays its title cells with an egui layout and sets that layout gap."
count = 1
[[exception]]
name = "iconic-story-stage"
kind = "marker"
rule = "style/token-read"
path = "crates/ui-panels/src/docking/iconic/stories.rs"
reason = "A story sizes its stage from the rail token."
count = 1
[[exception]]
name = "iconic-trial-rooms"
kind = "exempt"
rule = "literal-size"
path = "crates/ui-panels/src/docking/iconic/trials.rs"
reason = "Trial rooms, not looks."
count = 1
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "panel-rail-trial-rooms"
kind = "exempt"
rule = "literal-size"
path = "crates/ui-panels/src/rails/panel_rail/trials.rs"
reason = "Trial rooms, not looks."
count = 1
@@ -1 +1,9 @@
config_version = 1
[[exception]]
name = "preferences-window-sizes"
kind = "marker"
rule = "literal-size/vec2"
path = "crates/ui-patterns/src/patterns/preferences/window.rs"
reason = "The window opens at and shrinks to sizes of its own, in points."
count = 2
@@ -1,22 +1 @@
config_version = 1
[[exception]]
name = "selectable-text-mixed"
kind = "probe"
rule = "probe/exempt/state:Mixed"
path = "crates/ui-widgets/src/text/selectable_text.rs"
reason = "Read-only text has no mixed state."
[[exception]]
name = "selectable-text-invalid"
kind = "probe"
rule = "probe/exempt/state:Invalid"
path = "crates/ui-widgets/src/text/selectable_text.rs"
reason = "Read-only text has no value a check can refuse."
[[exception]]
name = "selectable-text-values"
kind = "probe"
rule = "probe/exempt/values"
path = "crates/ui-widgets/src/text/selectable_text.rs"
reason = "Read-only text has no value a drive can change."