crcbl_ui/widget.rs
1//! Immediate-mode UI widgets: label, button, and helpers.
2//!
3//! Widgets are stateless on their own — each frame you call their `render`
4//! method with the current state (hovered, clicked) and they push draw
5//! commands into a [`DrawList`].
6
7use crate::draw_list::DrawList;
8use crate::image::NineSliceImage;
9use crate::text::{FontAtlas, GLYPH_HEIGHT, LINE_HEIGHT};
10use glam::Vec2;
11
12/// The font size at which the built-in atlas renders 1:1.
13///
14/// Measurement and layout both divide by this. They used to disagree — widgets
15/// divided by `14.0` while [`DrawList::to_triangles`] divided by
16/// [`GLYPH_HEIGHT`] — which made every bound and hit rect ~7% smaller than the
17/// glyphs it was supposed to contain.
18///
19/// [`DrawList::to_triangles`]: crate::draw_list::DrawList::to_triangles
20pub const NATURAL_FONT_SIZE: f32 = GLYPH_HEIGHT as f32;
21
22// ---------------------------------------------------------------------------
23// Style
24// ---------------------------------------------------------------------------
25
26/// Colour palette for a widget theme.
27#[derive(Debug, Clone, Copy, PartialEq)]
28pub struct Style {
29 /// Normal text colour.
30 pub text: [f32; 4],
31 /// Normal background colour.
32 pub bg: [f32; 4],
33 /// Background colour when hovered.
34 pub bg_hover: [f32; 4],
35 /// Background colour when pressed/active.
36 pub bg_active: [f32; 4],
37 /// Outline/border colour.
38 pub border: [f32; 4],
39}
40
41impl Default for Style {
42 fn default() -> Self {
43 Self {
44 text: [1.0, 1.0, 1.0, 1.0], // white
45 bg: [0.15, 0.15, 0.15, 0.9], // dark grey
46 bg_hover: [0.25, 0.25, 0.3, 0.9], // slightly lighter
47 bg_active: [0.35, 0.35, 0.4, 0.9], // lighter still
48 border: [0.4, 0.4, 0.4, 1.0], // grey
49 }
50 }
51}
52
53// ---------------------------------------------------------------------------
54// Label
55// ---------------------------------------------------------------------------
56
57/// A static text label.
58///
59/// Renders a single line of text at the given position using the built-in
60/// font atlas. Optionally draws a background rectangle behind the text.
61#[derive(Debug, Clone)]
62pub struct Label {
63 /// Text content.
64 pub text: String,
65 /// Font size in pixels.
66 pub font_size: f32,
67 /// If true, draw a background rect behind the text.
68 pub show_bg: bool,
69}
70
71impl Label {
72 /// Create a new label.
73 #[must_use]
74 pub fn new(text: impl Into<String>) -> Self {
75 Self {
76 text: text.into(),
77 font_size: 14.0,
78 show_bg: false,
79 }
80 }
81
82 /// Set the font size.
83 #[must_use]
84 pub fn with_size(mut self, size: f32) -> Self {
85 self.font_size = size;
86 self
87 }
88
89 /// Enable or disable the background rectangle.
90 #[must_use]
91 pub fn with_bg(mut self, show: bool) -> Self {
92 self.show_bg = show;
93 self
94 }
95
96 /// The layout scale this label's glyphs are drawn at.
97 fn scale(&self) -> f32 {
98 self.font_size / NATURAL_FONT_SIZE
99 }
100
101 /// Render this label into a `DrawList`.
102 ///
103 /// `pos` is the top-left corner of the label, and is the same anchor the
104 /// background rect and [`Label::width`]/[`Label::height`] describe.
105 pub fn render(&self, dl: &mut DrawList, pos: Vec2, atlas: &FontAtlas, style: &Style) {
106 if self.show_bg {
107 let size = self.size(atlas);
108 dl.rect(pos, pos + size, style.bg);
109 }
110
111 dl.text(pos, &self.text, style.text, self.font_size);
112 }
113
114 /// Measure the rendered width.
115 #[must_use]
116 pub fn width(&self, atlas: &FontAtlas) -> f32 {
117 atlas.text_width(&self.text, self.scale()) + 4.0
118 }
119
120 /// Measure the rendered height, which grows with the number of lines.
121 #[must_use]
122 pub fn height_for(&self, atlas: &FontAtlas) -> f32 {
123 atlas.line_count(&self.text) as f32 * LINE_HEIGHT * self.scale()
124 }
125
126 /// Measure the rendered height of a single line.
127 #[must_use]
128 pub fn height(&self) -> f32 {
129 LINE_HEIGHT * self.scale()
130 }
131
132 /// The label's full extent, the rect [`Label::render`] draws its background
133 /// as.
134 #[must_use]
135 pub fn size(&self, atlas: &FontAtlas) -> Vec2 {
136 Vec2::new(self.width(atlas), self.height_for(atlas))
137 }
138}
139
140// ---------------------------------------------------------------------------
141// Button
142// ---------------------------------------------------------------------------
143
144/// Button interaction state (computed externally from mouse input).
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum ButtonState {
147 /// Default idle appearance.
148 Idle,
149 /// Mouse is hovering over the button.
150 Hovered,
151 /// Mouse button is pressed down on the button.
152 Pressed,
153}
154
155// ---------------------------------------------------------------------------
156// SkinInsets
157// ---------------------------------------------------------------------------
158
159/// The fixed corner insets of a nine-slice button skin, in **screen pixels**.
160///
161/// # Why a `Button` carries the insets and not the art
162///
163/// A skinned button needs two things: art to draw, and the sizes that art
164/// refuses to stretch. Only the second is a *layout* fact, and the layout is
165/// what a [`Button`] is: it measures, positions and hit-tests with no picture
166/// in the room. The art is a [`ButtonSkin`] — three registered images — and
167/// [`ButtonSkin::insets`] hands back exactly this type, read off the art itself,
168/// so the two cannot drift.
169///
170/// # Screen space, so `top` is the visually-upper edge
171///
172/// Every rectangle in this crate is Y-**down** with the origin at the
173/// framebuffer's top-left, and these insets follow it: `top` is the inset at the
174/// smaller Y. That agrees with an image's own rows — its top row is its first —
175/// so [`DrawList::nine_slice`] pairs `top` with the image's top band and nothing
176/// flips.
177#[derive(Debug, Clone, Copy, PartialEq, Default)]
178pub struct SkinInsets {
179 /// Fixed width of the left column, in pixels.
180 pub left: f32,
181 /// Fixed width of the right column, in pixels.
182 pub right: f32,
183 /// Fixed height of the top row, in pixels.
184 pub top: f32,
185 /// Fixed height of the bottom row, in pixels.
186 pub bottom: f32,
187}
188
189impl SkinInsets {
190 /// No fixed bands at all — a skin that stretches everywhere.
191 pub const NONE: Self = Self {
192 left: 0.0,
193 right: 0.0,
194 top: 0.0,
195 bottom: 0.0,
196 };
197
198 /// Insets given per side.
199 #[must_use]
200 pub const fn new(left: f32, right: f32, top: f32, bottom: f32) -> Self {
201 Self {
202 left,
203 right,
204 top,
205 bottom,
206 }
207 }
208
209 /// The same inset on all four sides.
210 #[must_use]
211 pub const fn uniform(inset: f32) -> Self {
212 Self::new(inset, inset, inset, inset)
213 }
214
215 /// `(left + right, top + bottom)` — the smallest box that draws all four
216 /// corners at their natural size.
217 ///
218 /// The float twin of `crcbl_sprite::NineSlice::minimum_size`, and the floor
219 /// under [`Button::minimum_size`] before the label is even considered.
220 #[must_use]
221 pub fn minimum_size(&self) -> Vec2 {
222 Vec2::new(self.left + self.right, self.top + self.bottom)
223 }
224
225 /// The top-left corner's size, as an offset from a rect's `min`.
226 #[must_use]
227 pub fn min_corner(&self) -> Vec2 {
228 Vec2::new(self.left, self.top)
229 }
230
231 /// The bottom-right corner's size, as an offset back from a rect's `max`.
232 #[must_use]
233 pub fn max_corner(&self) -> Vec2 {
234 Vec2::new(self.right, self.bottom)
235 }
236}
237
238// ---------------------------------------------------------------------------
239// ButtonSkin
240// ---------------------------------------------------------------------------
241
242/// The art a skinned button draws: one nine-sliced image per [`ButtonState`].
243///
244/// ```text
245/// idle hovered pressed
246/// ┌──┬────────┬──┐ ┌──┬────────┬──┐ ┌──┬────────┬──┐
247/// │ │ │ │ │ │ │ │ │ │ │ │
248/// ├──┤ Play ├──┤ ├──┤ Play ├──┤ ├──┤ Play ├──┤
249/// │ │ │ │ │ │ │ │ │ │ │ │
250/// └──┴────────┴──┘ └──┴────────┴──┘ └──┴────────┴──┘
251/// three pictures — pressing swaps art, it does not tint
252/// ```
253///
254/// Three pictures rather than one picture and three tints, because that is what
255/// the feature is for. A tint can only darken or lighten uniformly; separate
256/// frames let a pressed button have a sunken bevel, a different highlight, or a
257/// shadow that moved — none of which is a multiply.
258///
259/// [`draw`](Self::draw) emits the frame for a state into a [`DrawList`] as
260/// textured quads, so the frame and the label on it are drawn by one pass in
261/// the order they were pushed: frame first, label over it.
262#[derive(Debug, Clone, Copy, PartialEq)]
263pub struct ButtonSkin {
264 /// The frame drawn at rest.
265 pub idle: NineSliceImage,
266 /// The frame drawn under the cursor or the keyboard's selection.
267 pub hovered: NineSliceImage,
268 /// The frame drawn while the button holds the press.
269 pub pressed: NineSliceImage,
270}
271
272impl ButtonSkin {
273 /// One frame for every state — a skin that does not react.
274 #[must_use]
275 pub const fn uniform(frame: NineSliceImage) -> Self {
276 Self {
277 idle: frame,
278 hovered: frame,
279 pressed: frame,
280 }
281 }
282
283 /// The frame `state` draws.
284 #[must_use]
285 pub const fn frame(&self, state: ButtonState) -> &NineSliceImage {
286 match state {
287 ButtonState::Idle => &self.idle,
288 ButtonState::Hovered => &self.hovered,
289 ButtonState::Pressed => &self.pressed,
290 }
291 }
292
293 /// The insets to hand [`Button::with_skin`], in **texels**.
294 ///
295 /// Read off the **idle** frame, and off its clamped insets rather than its
296 /// declared ones, so the layout agrees with the geometry that will actually
297 /// be drawn. Idle specifically, and not "whichever state is current": a
298 /// button whose minimum size changed with the cursor would resize as the
299 /// mouse crossed it. [`insets_agree`](Self::insets_agree) is there for a
300 /// skin whose frames might not.
301 #[must_use]
302 pub fn insets(&self) -> SkinInsets {
303 self.idle.clamped_insets()
304 }
305
306 /// Whether all three frames have the same clamped insets.
307 #[must_use]
308 pub fn insets_agree(&self) -> bool {
309 let idle = self.idle.clamped_insets();
310 self.hovered.clamped_insets() == idle && self.pressed.clamped_insets() == idle
311 }
312
313 /// Pushes `state`'s frame stretched to `min..max`, at `scale` screen pixels
314 /// per texel of its fixed bands — see [`DrawList::nine_slice`].
315 pub fn draw(&self, dl: &mut DrawList, state: ButtonState, min: Vec2, max: Vec2, scale: f32) {
316 dl.nine_slice(min, max, self.frame(state), scale, [1.0; 4]);
317 }
318}
319
320// ---------------------------------------------------------------------------
321// PointerInput / UiState
322// ---------------------------------------------------------------------------
323
324/// The pointer state for one frame.
325///
326/// Bundled rather than passed as three loose arguments because every clickable
327/// widget needs all three, and a bare `bool, bool` pair at a call site is the
328/// kind of thing that gets swapped.
329#[derive(Debug, Clone, Copy, Default, PartialEq)]
330pub struct PointerInput {
331 /// Cursor position in screen-space pixels.
332 pub pos: Vec2,
333 /// Whether the primary pointer button is currently held.
334 pub down: bool,
335 /// Whether the primary pointer button came up this frame.
336 pub released: bool,
337 /// Whether the secondary pointer button went down this frame: what opens a
338 /// context menu ([`Ui::context_menu`](crate::tree::Ui::context_menu)). An
339 /// edge, not a level — nothing captures or drags with it — so a frame
340 /// carries it once per press.
341 pub secondary_pressed: bool,
342}
343
344impl PointerInput {
345 /// Pointer at `pos` with no button activity.
346 #[must_use]
347 pub fn hovering(pos: Vec2) -> Self {
348 Self {
349 pos,
350 down: false,
351 released: false,
352 secondary_pressed: false,
353 }
354 }
355}
356
357/// Identifies a widget across frames.
358///
359/// Immediate-mode widgets are rebuilt every frame, so press capture needs
360/// *something* stable to latch onto. Callers pick the number; the only
361/// requirement is that it names the same widget next frame and no other widget
362/// this frame.
363pub type WidgetId = u64;
364
365/// The one piece of retained state an immediate-mode UI cannot do without:
366/// which widget captured the current press.
367///
368/// Without it a click is credited to whatever the cursor happens to be over on
369/// release, so pressing button A, dragging onto B and releasing fires B. With
370/// it, the press latches an `active` widget and only that widget can be
371/// clicked — and only if the cursor is still over it when the button comes up.
372///
373/// Create one, keep it alive across frames, and drive every clickable widget
374/// through [`UiState::interact`].
375#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
376pub struct UiState {
377 active: Option<WidgetId>,
378}
379
380impl UiState {
381 /// Create state with nothing captured.
382 #[must_use]
383 pub fn new() -> Self {
384 Self { active: None }
385 }
386
387 /// The widget that captured the current press, if any.
388 #[must_use]
389 pub fn active(&self) -> Option<WidgetId> {
390 self.active
391 }
392
393 /// Drop any capture — for a UI that was torn down mid-press.
394 pub fn clear(&mut self) {
395 self.active = None;
396 }
397
398 /// Resolve one widget's visual state and whether it was clicked.
399 ///
400 /// - `hovered`: the cursor is inside the widget this frame.
401 /// - `pointer_down`: the pointer button is currently held.
402 /// - `pointer_released`: the pointer button came up this frame.
403 ///
404 /// Returns `(state, clicked)`. `clicked` is true only when *this* widget
405 /// captured the press **and** still has the cursor at release.
406 pub fn interact(
407 &mut self,
408 id: WidgetId,
409 hovered: bool,
410 pointer_down: bool,
411 pointer_released: bool,
412 ) -> (ButtonState, bool) {
413 // Latch the capture on the frame the press starts over this widget.
414 if pointer_down && hovered && self.active.is_none() {
415 self.active = Some(id);
416 }
417 let captured = self.active == Some(id);
418 let clicked = pointer_released && captured && hovered;
419 if pointer_released && captured {
420 self.active = None;
421 }
422
423 let state = if captured {
424 ButtonState::Pressed
425 } else if hovered && self.active.is_none() {
426 ButtonState::Hovered
427 } else {
428 // Another widget owns the press — this one stays idle even under
429 // the cursor, so a drag-off does not light up its neighbour.
430 ButtonState::Idle
431 };
432 (state, clicked)
433 }
434}
435
436/// A clickable button with text.
437///
438/// Button is stateless — you provide the [`ButtonState`] each frame based
439/// on your input system, normally via [`UiState::interact`] or the
440/// [`Button::interact`] wrapper, and the button draws itself.
441///
442/// # Skinned and unskinned
443///
444/// With no [`skin`](Button::skin) the button paints itself: a filled rect and a
445/// one-pixel outline in [`Style`]'s colours, then the label. That is the whole
446/// widget, and [`Button::render`] emits all three commands.
447///
448/// With a skin, the background is a [`ButtonSkin`]'s nine-sliced frame, so
449/// pressing the button swaps art rather than changing a tint, and stretching it
450/// leaves the corners alone. [`Button::render`] then emits only the label — see
451/// its docs for what the caller owes.
452#[derive(Debug, Clone)]
453pub struct Button {
454 /// Button label.
455 pub text: String,
456 /// Font size.
457 pub font_size: f32,
458 /// Padding inside the button (horizontal, vertical).
459 ///
460 /// Measured **inside the skin's corners**, not from the button's edge: a
461 /// skinned button's content box is its rect inset by the corners and then by
462 /// this. With no skin the corners are zero and it is the plain inset it has
463 /// always been.
464 pub padding: Vec2,
465 /// The skin's fixed corner sizes, or `None` for the flat painted button.
466 ///
467 /// Set it from [`ButtonSkin::insets`] rather than by hand, so the layout and
468 /// the art it is laying out around come from one place.
469 pub skin: Option<SkinInsets>,
470 /// The size the caller wants the button drawn at, before
471 /// [`Button::minimum_size`] is applied. `None` shrinks to fit the label.
472 ///
473 /// A *request*, not a guarantee — see [`Button::size`] for what happens when
474 /// it is too small.
475 pub fixed_size: Option<Vec2>,
476}
477
478impl Button {
479 /// Create a new button with the given text.
480 #[must_use]
481 pub fn new(text: impl Into<String>) -> Self {
482 Self {
483 text: text.into(),
484 font_size: 14.0,
485 padding: Vec2::new(8.0, 4.0),
486 skin: None,
487 fixed_size: None,
488 }
489 }
490
491 /// Set the font size.
492 #[must_use]
493 pub fn with_size(mut self, size: f32) -> Self {
494 self.font_size = size;
495 self
496 }
497
498 /// Lay this button out around a nine-slice skin with the given corners.
499 #[must_use]
500 pub fn with_skin(mut self, insets: SkinInsets) -> Self {
501 self.skin = Some(insets);
502 self
503 }
504
505 /// Ask for a particular size, in pixels.
506 ///
507 /// Clamped up to [`Button::minimum_size`] — a button is never drawn smaller
508 /// than its own corners and label.
509 #[must_use]
510 pub fn with_fixed_size(mut self, size: Vec2) -> Self {
511 self.fixed_size = Some(size);
512 self
513 }
514
515 /// The layout scale this button's label is drawn at.
516 fn scale(&self) -> f32 {
517 self.font_size / NATURAL_FONT_SIZE
518 }
519
520 /// The skin's corners, or zeroes when there is no skin.
521 fn insets(&self) -> SkinInsets {
522 self.skin.unwrap_or(SkinInsets::NONE)
523 }
524
525 /// The label's own extent, with no padding and no corners around it.
526 #[must_use]
527 pub fn label_size(&self, atlas: &FontAtlas) -> Vec2 {
528 let scale = self.scale();
529 Vec2::new(
530 atlas.text_width(&self.text, scale),
531 atlas.line_count(&self.text) as f32 * LINE_HEIGHT * scale,
532 )
533 }
534
535 /// The smallest size this button can be drawn at: **its corners plus its
536 /// label**, with the padding between them.
537 ///
538 /// Both terms are load-bearing and neither is enough alone. The corners are
539 /// the sizes the nine-slice refuses to stretch, so a box narrower than
540 /// `left + right` has nowhere to put them; the label is the content, so a box
541 /// that fits the corners and not the text draws the text over them.
542 ///
543 /// The padding is added rather than absorbed: it is the gap the caller asked
544 /// for *between* the frame and the words, and a minimum that let the two
545 /// touch would silently ignore it at exactly the size where it is most
546 /// visible.
547 ///
548 /// With no skin the corners are zero and this is `label + 2 × padding` — the
549 /// rect an unskinned button has always been.
550 #[must_use]
551 pub fn minimum_size(&self, atlas: &FontAtlas) -> Vec2 {
552 self.insets().minimum_size() + self.label_size(atlas) + self.padding * 2.0
553 }
554
555 /// The size this button is actually drawn at.
556 ///
557 /// [`Button::fixed_size`] when it is at least [`Button::minimum_size`] on
558 /// that axis, and the minimum otherwise — **each axis clamps on its own**, so
559 /// a button asked for a generous width and a mean height keeps the width.
560 ///
561 /// # Why clamp rather than shrink
562 ///
563 /// [`DrawList::nine_slice`] handles a target below its minimum by squashing
564 /// the corners in proportion, which is right for what it was written for: a
565 /// pipe closing to nothing should close continuously rather than vanish or
566 /// spill. A button is the other case. Its content is *text*, which does not
567 /// shrink with the frame — a squashed button would draw a full-size label
568 /// across smudged corners, which is both of the failures this slice exists to
569 /// remove, at once. Growing to the minimum is visible in the layout, where a
570 /// caller can see it and fix it, rather than in the pixels.
571 #[must_use]
572 pub fn size(&self, atlas: &FontAtlas) -> Vec2 {
573 let minimum = self.minimum_size(atlas);
574 self.fixed_size.map_or(minimum, |asked| asked.max(minimum))
575 }
576
577 /// The bounding rectangle for this button at the given position.
578 #[must_use]
579 pub fn rect(&self, pos: Vec2, atlas: &FontAtlas) -> (Vec2, Vec2) {
580 (pos, pos + self.size(atlas))
581 }
582
583 /// The box the label is centred in: the button inset by its corners and then
584 /// by its padding.
585 ///
586 /// Centring here rather than in the button's full rect is what keeps an
587 /// **asymmetric** skin honest. A frame with a 4-pixel left cap and a 20-pixel
588 /// right one has its content box off-centre, and a label centred in the outer
589 /// rect would sit under the fat cap at the minimum size. With no skin the two
590 /// boxes share a centre and this is the ordinary thing.
591 #[must_use]
592 pub fn content_rect(&self, pos: Vec2, atlas: &FontAtlas) -> (Vec2, Vec2) {
593 let insets = self.insets();
594 let (min, max) = self.rect(pos, atlas);
595 (
596 min + insets.min_corner() + self.padding,
597 max - insets.max_corner() - self.padding,
598 )
599 }
600
601 /// Where [`Button::render`] anchors the label — the top-left of its em box.
602 ///
603 /// Centred in [`Button::content_rect`] on both axes, so it stays centred as
604 /// the button is resized.
605 #[must_use]
606 pub fn label_pos(&self, pos: Vec2, atlas: &FontAtlas) -> Vec2 {
607 let (min, max) = self.content_rect(pos, atlas);
608 min + (max - min - self.label_size(atlas)) * 0.5
609 }
610
611 /// Whether the given mouse position is inside the button area.
612 #[must_use]
613 pub fn hit_test(&self, pos: Vec2, mouse: Vec2, atlas: &FontAtlas) -> bool {
614 let (min, max) = self.rect(pos, atlas);
615 mouse.x >= min.x && mouse.x <= max.x && mouse.y >= min.y && mouse.y <= max.y
616 }
617
618 /// Hit-test this button and resolve its state through `ui`'s press capture.
619 ///
620 /// Returns `(state, clicked)` — feed `state` straight to
621 /// [`Button::render`]. `clicked` is true only when the press *started* on
622 /// this button and the cursor is still on it at release.
623 pub fn interact(
624 &self,
625 pos: Vec2,
626 atlas: &FontAtlas,
627 ui: &mut UiState,
628 id: WidgetId,
629 pointer: PointerInput,
630 ) -> (ButtonState, bool) {
631 let hovered = self.hit_test(pos, pointer.pos, atlas);
632 ui.interact(id, hovered, pointer.down, pointer.released)
633 }
634
635 /// Render the button into a `DrawList` at `state`'s appearance.
636 ///
637 /// Click detection is [`Button::interact`]'s job — a renderer that also
638 /// decided whether it had been clicked could only do so from the state it
639 /// was handed, which is exactly the "credited on release to whoever is
640 /// under the cursor" bug.
641 ///
642 /// # A skinned button emits only its label
643 ///
644 /// The layout knows the skin's corners and nothing else, so the frame is
645 /// the caller's to push: [`ButtonSkin::draw`] for the same `state` and the
646 /// same rect, **before** this call — the draw list composites in the order
647 /// commands went in, and a frame pushed after the label paints over it.
648 pub fn render(
649 &self,
650 dl: &mut DrawList,
651 pos: Vec2,
652 atlas: &FontAtlas,
653 style: &Style,
654 state: ButtonState,
655 ) {
656 if self.skin.is_none() {
657 let (min, max) = self.rect(pos, atlas);
658 let bg = match state {
659 ButtonState::Pressed => style.bg_active,
660 ButtonState::Hovered => style.bg_hover,
661 ButtonState::Idle => style.bg,
662 };
663
664 dl.rect(min, max, bg);
665 dl.rect_outline(min, max, 1.0, style.border);
666 }
667
668 dl.text(
669 self.label_pos(pos, atlas),
670 &self.text,
671 style.text,
672 self.font_size,
673 );
674 }
675}
676
677// ---------------------------------------------------------------------------
678// Tests
679// ---------------------------------------------------------------------------
680
681#[cfg(test)]
682mod tests {
683 use super::*;
684 use crate::draw_list::DrawCommand;
685
686 fn atlas() -> FontAtlas {
687 FontAtlas::built_in()
688 }
689
690 fn style() -> Style {
691 Style::default()
692 }
693
694 // ── Label ─────────────────────────────────────────────────────────────
695
696 #[test]
697 fn label_renders_text_command() {
698 let label = Label::new("Hello");
699 let mut dl = DrawList::new();
700 label.render(&mut dl, Vec2::ZERO, &atlas(), &style());
701 assert!(!dl.is_empty());
702 assert!(matches!(dl.commands()[0], DrawCommand::Text { .. }));
703 }
704
705 #[test]
706 fn label_with_bg_adds_rect() {
707 let label = Label::new("Hi").with_bg(true);
708 let mut dl = DrawList::new();
709 label.render(&mut dl, Vec2::ZERO, &atlas(), &style());
710 assert_eq!(dl.len(), 2);
711 assert!(matches!(dl.commands()[0], DrawCommand::Rect { .. }));
712 assert!(matches!(dl.commands()[1], DrawCommand::Text { .. }));
713 }
714
715 #[test]
716 fn label_width_and_height_are_positive() {
717 let label = Label::new("Hello");
718 assert!(label.width(&atlas()) > 0.0);
719 assert!(label.height() > 0.0);
720 }
721
722 /// The bug: measurement divided by 14 while layout divided by
723 /// `GLYPH_HEIGHT` (13), so a label's declared box was ~7% narrower than the
724 /// glyphs drawn inside it.
725 #[test]
726 fn declared_bounds_contain_the_glyphs_they_describe() {
727 let atlas = atlas();
728 for size in [10.0, 14.0, 28.0] {
729 let btn = Button::new("LongButtonLabel").with_size(size);
730 let pos = Vec2::new(50.0, 50.0);
731 let (min, max) = btn.rect(pos, &atlas);
732
733 let mut dl = DrawList::new();
734 btn.render(&mut dl, pos, &atlas, &style(), ButtonState::Idle);
735 let (verts, _) = dl.to_triangles(Some(&atlas), None, 1.0);
736 for v in &verts {
737 assert!(
738 v.pos.x >= min.x - 0.001
739 && v.pos.x <= max.x + 0.001
740 && v.pos.y >= min.y - 0.001
741 && v.pos.y <= max.y + 0.001,
742 "size {size}: vertex {:?} escapes the declared rect {min:?}..{max:?}",
743 v.pos
744 );
745 }
746 }
747 }
748
749 /// The `Text` anchor is a top-left corner, so a label's background must
750 /// contain its own glyphs.
751 #[test]
752 fn label_background_contains_its_glyphs() {
753 let atlas = atlas();
754 let label = Label::new("Hi").with_bg(true);
755 let pos = Vec2::new(10.0, 100.0);
756 let mut dl = DrawList::new();
757 label.render(&mut dl, pos, &atlas, &style());
758
759 let DrawCommand::Rect { min, max, .. } = dl.commands()[0] else {
760 panic!("expected a background Rect");
761 };
762 let (verts, _) = dl.to_triangles(Some(&atlas), None, 1.0);
763 assert!(!verts.is_empty());
764 for v in &verts {
765 assert!(
766 v.pos.y >= min.y - 0.001 && v.pos.y <= max.y + 0.001,
767 "glyph vertex {:?} falls outside the background {min:?}..{max:?}",
768 v.pos
769 );
770 }
771 }
772
773 // ── Button ────────────────────────────────────────────────────────────
774
775 #[test]
776 fn button_in_idle_state_renders_rect_and_text() {
777 let btn = Button::new("Click");
778 let mut dl = DrawList::new();
779 btn.render(&mut dl, Vec2::ZERO, &atlas(), &style(), ButtonState::Idle);
780 assert_eq!(dl.len(), 3);
781 }
782
783 #[test]
784 fn button_hit_test_inside() {
785 let btn = Button::new("Go");
786 let pos = Vec2::new(10.0, 10.0);
787 let (min, max) = btn.rect(pos, &atlas());
788 let centre = (min + max) * 0.5;
789 assert!(btn.hit_test(pos, centre, &atlas()));
790 }
791
792 #[test]
793 fn button_hit_test_outside() {
794 let btn = Button::new("Go");
795 let pos = Vec2::new(10.0, 10.0);
796 assert!(!btn.hit_test(pos, Vec2::new(0.0, 0.0), &atlas()));
797 }
798
799 /// **The sweep `docs/notes/process.md` asks for**, where the two tests
800 /// above are two points.
801 ///
802 /// Two points cannot see a transposed axis: the centre is inside whichever
803 /// way the comparison is spelled, and the origin is outside both ways. A
804 /// grid that straddles all four edges can — every sample is held against the
805 /// rectangle the button itself reports, so a swapped comparison, a wrong
806 /// corner, or a bound that stopped being inclusive each show up as a named
807 /// disagreement at a named point rather than as a count.
808 #[test]
809 fn button_hit_test_agrees_with_its_rect_over_a_grid() {
810 /// How far outside the button the sweep reaches, so every edge is
811 /// crossed rather than approached.
812 const MARGIN: f32 = 6.0;
813 /// Sample spacing. A negative power of two, so stepping accumulates no
814 /// error and the samples are the ones this test says they are.
815 const STEP: f32 = 0.5;
816
817 let btn = Button::new("Go");
818 let atlas = atlas();
819 let pos = Vec2::new(10.0, 10.0);
820 let (min, max) = btn.rect(pos, &atlas);
821 let size = max - min;
822 assert!(
823 (size.x - size.y).abs() > STEP,
824 "the premise: a square button hides a transposed axis, and the sweep \
825 below would pass on one. This button is {size:?}"
826 );
827
828 let mut samples = 0_u32;
829 let mut inside = 0_u32;
830 let mut x = min.x - MARGIN;
831 while x <= max.x + MARGIN {
832 let mut y = min.y - MARGIN;
833 while y <= max.y + MARGIN {
834 let mouse = Vec2::new(x, y);
835 let want = x >= min.x && x <= max.x && y >= min.y && y <= max.y;
836 assert_eq!(
837 btn.hit_test(pos, mouse, &atlas),
838 want,
839 "at {mouse:?}, against a button spanning {min:?} to {max:?}"
840 );
841 samples += 1;
842 inside += u32::from(want);
843 y += STEP;
844 }
845 x += STEP;
846 }
847 assert!(
848 inside > 0 && inside < samples,
849 "a sweep entirely inside or entirely outside asserts nothing about an \
850 edge: {inside} of {samples} samples hit"
851 );
852
853 // The boundary itself, which a grid only straddles: every corner is on
854 // it, and `hit_test` documents an inclusive rectangle.
855 for corner in [min, Vec2::new(max.x, min.y), Vec2::new(min.x, max.y), max] {
856 assert!(
857 btn.hit_test(pos, corner, &atlas),
858 "the rectangle is inclusive, so its own corner {corner:?} is a hit"
859 );
860 }
861 }
862
863 #[test]
864 fn a_press_and_release_over_one_button_is_a_click_and_frees_the_capture() {
865 let btn = Button::new("Fire");
866 let atlas = atlas();
867 let mut ui = UiState::new();
868 let centre = {
869 let (min, max) = btn.rect(Vec2::ZERO, &atlas);
870 (min + max) * 0.5
871 };
872
873 // Press.
874 let down = PointerInput {
875 pos: centre,
876 down: true,
877 released: false,
878 secondary_pressed: false,
879 };
880 let up = PointerInput {
881 pos: centre,
882 down: false,
883 released: true,
884 secondary_pressed: false,
885 };
886 let (state, clicked) = btn.interact(Vec2::ZERO, &atlas, &mut ui, 1, down);
887 assert_eq!(state, ButtonState::Pressed);
888 assert!(!clicked);
889 // Release over the same button.
890 let (_, clicked) = btn.interact(Vec2::ZERO, &atlas, &mut ui, 1, up);
891 assert!(clicked);
892 assert_eq!(ui.active(), None, "the capture must be released");
893 }
894
895 #[test]
896 fn button_no_click_when_not_hovered() {
897 let btn = Button::new("Fire");
898 let atlas = atlas();
899 let mut ui = UiState::new();
900 let outside = PointerInput {
901 pos: Vec2::new(-100.0, -100.0),
902 down: false,
903 released: true,
904 secondary_pressed: false,
905 };
906 let (state, clicked) = btn.interact(Vec2::ZERO, &atlas, &mut ui, 1, outside);
907 assert_eq!(state, ButtonState::Idle);
908 assert!(!clicked);
909 }
910
911 // ── press capture ─────────────────────────────────────────────────────
912
913 /// The bug: a click was credited to whatever the cursor was over on
914 /// release, so press-A / drag-to-B / release fired B.
915 #[test]
916 fn press_on_a_and_release_on_b_clicks_neither() {
917 let atlas = atlas();
918 let a = Button::new("A");
919 let b = Button::new("B");
920 let a_pos = Vec2::new(0.0, 0.0);
921 let b_pos = Vec2::new(200.0, 0.0);
922 let inside = |btn: &Button, pos: Vec2| {
923 let (min, max) = btn.rect(pos, &atlas);
924 (min + max) * 0.5
925 };
926 let a_centre = inside(&a, a_pos);
927 let b_centre = inside(&b, b_pos);
928 let mut ui = UiState::new();
929
930 let held = |pos| PointerInput {
931 pos,
932 down: true,
933 released: false,
934 secondary_pressed: false,
935 };
936 let up = |pos| PointerInput {
937 pos,
938 down: false,
939 released: true,
940 secondary_pressed: false,
941 };
942
943 // Frame 1: press over A.
944 let (a_state, a_clicked) = a.interact(a_pos, &atlas, &mut ui, 1, held(a_centre));
945 let (b_state, b_clicked) = b.interact(b_pos, &atlas, &mut ui, 2, held(a_centre));
946 assert_eq!(a_state, ButtonState::Pressed);
947 assert_eq!(b_state, ButtonState::Idle);
948 assert!(!a_clicked && !b_clicked);
949
950 // Frame 2: still held, cursor dragged onto B. B must not light up.
951 let (a_state, _) = a.interact(a_pos, &atlas, &mut ui, 1, held(b_centre));
952 let (b_state, _) = b.interact(b_pos, &atlas, &mut ui, 2, held(b_centre));
953 assert_eq!(a_state, ButtonState::Pressed, "A still owns the press");
954 assert_eq!(b_state, ButtonState::Idle, "B must not steal the capture");
955
956 // Frame 3: release over B. Neither fires — A lost the cursor, B never
957 // captured the press.
958 let (_, a_clicked) = a.interact(a_pos, &atlas, &mut ui, 1, up(b_centre));
959 let (_, b_clicked) = b.interact(b_pos, &atlas, &mut ui, 2, up(b_centre));
960 assert!(!a_clicked, "A lost the cursor before release");
961 assert!(!b_clicked, "B never captured the press");
962 assert_eq!(ui.active(), None);
963 }
964
965 #[test]
966 fn hover_needs_no_capture_but_a_captured_press_suppresses_it() {
967 let mut ui = UiState::new();
968 // Nothing captured: hover reads as Hovered.
969 assert_eq!(ui.interact(1, true, false, false).0, ButtonState::Hovered);
970 // Widget 1 captures the press…
971 assert_eq!(ui.interact(1, true, true, false).0, ButtonState::Pressed);
972 // …so widget 2 stays idle even under the cursor.
973 assert_eq!(ui.interact(2, true, true, false).0, ButtonState::Idle);
974 ui.clear();
975 assert_eq!(ui.active(), None);
976 }
977
978 #[test]
979 fn button_rect_grows_with_text() {
980 let short = Button::new("A");
981 let long = Button::new("LongButton");
982 let (_, short_max) = short.rect(Vec2::ZERO, &atlas());
983 let (_, long_max) = long.rect(Vec2::ZERO, &atlas());
984 assert!(long_max.x > short_max.x);
985 }
986
987 // ── skinned buttons ───────────────────────────────────────────────────
988
989 /// Deliberately **asymmetric on every side**, so a transposed or mirrored
990 /// pair cannot compare equal by accident: a swapped left/right shifts the
991 /// content box by 16, and a swapped top/bottom by 6.
992 const INSETS: SkinInsets = SkinInsets::new(4.0, 20.0, 3.0, 9.0);
993
994 /// The minimum is the corners **and** the label, with the padding between
995 /// them — neither term alone.
996 #[test]
997 fn a_skinned_buttons_minimum_size_is_its_corners_plus_its_label() {
998 let atlas = atlas();
999 let plain = Button::new("Play");
1000 let skinned = plain.clone().with_skin(INSETS);
1001
1002 let label = plain.label_size(&atlas);
1003 assert!(label.x > 0.0 && label.y > 0.0);
1004
1005 // Unskinned: unchanged from what a button has always measured.
1006 assert_eq!(
1007 plain.minimum_size(&atlas),
1008 label + plain.padding * 2.0,
1009 "an unskinned button's minimum must still be its label plus padding"
1010 );
1011 assert_eq!(plain.rect(Vec2::ZERO, &atlas).1, plain.minimum_size(&atlas));
1012
1013 // Skinned: exactly the corners more.
1014 assert_eq!(
1015 skinned.minimum_size(&atlas) - plain.minimum_size(&atlas),
1016 Vec2::new(INSETS.left + INSETS.right, INSETS.top + INSETS.bottom),
1017 "the skin's corners must be added to the label's own minimum"
1018 );
1019
1020 // And the corners alone are a floor even with no label at all: a
1021 // minimum that only measured text would let the corners overlap.
1022 let empty = Button::new("").with_skin(INSETS);
1023 let corners = INSETS.minimum_size();
1024 assert!(
1025 empty.minimum_size(&atlas).x >= corners.x && empty.minimum_size(&atlas).y >= corners.y,
1026 "an empty label must still leave room for the four corners"
1027 );
1028 }
1029
1030 /// A caller asking for less than the minimum gets the minimum, per axis.
1031 #[test]
1032 fn a_button_asked_for_less_than_its_minimum_grows_to_it() {
1033 let atlas = atlas();
1034 let button = Button::new("Play").with_skin(INSETS);
1035 let minimum = button.minimum_size(&atlas);
1036
1037 // Far too small on both axes.
1038 let squashed = button.clone().with_fixed_size(Vec2::new(1.0, 1.0));
1039 assert_eq!(squashed.size(&atlas), minimum);
1040 assert_eq!(squashed.rect(Vec2::ZERO, &atlas).1, minimum);
1041
1042 // Generous on both axes: honoured exactly.
1043 let roomy = minimum + Vec2::new(200.0, 40.0);
1044 assert_eq!(button.clone().with_fixed_size(roomy).size(&atlas), roomy);
1045
1046 // Each axis clamps on its own — a mean height must not cost the width.
1047 let mixed = button.with_fixed_size(Vec2::new(minimum.x + 200.0, 1.0));
1048 assert_eq!(
1049 mixed.size(&atlas),
1050 Vec2::new(minimum.x + 200.0, minimum.y),
1051 "the width was fine and must survive the height being clamped"
1052 );
1053
1054 // Clamping, not squashing: the content box never inverts, so the label
1055 // is never drawn across the corners.
1056 let (content_min, content_max) = mixed.content_rect(Vec2::ZERO, &atlas);
1057 assert!(
1058 content_max.x >= content_min.x && content_max.y >= content_min.y,
1059 "the content box inverted: {content_min:?}..{content_max:?}"
1060 );
1061 }
1062
1063 /// The label is centred in the content box, and **stays** centred as the
1064 /// button is resized — the property a fixed top-left anchor would fail at
1065 /// every width but one.
1066 #[test]
1067 fn the_label_stays_centred_when_the_button_is_resized() {
1068 let atlas = atlas();
1069 let button = Button::new("Play").with_skin(INSETS);
1070 let pos = Vec2::new(37.0, 11.0);
1071 let label = button.label_size(&atlas);
1072
1073 for width in [button.minimum_size(&atlas).x, 200.0, 640.0] {
1074 for height in [button.minimum_size(&atlas).y, 60.0, 180.0] {
1075 let sized = button.clone().with_fixed_size(Vec2::new(width, height));
1076 let (content_min, content_max) = sized.content_rect(pos, &atlas);
1077 let anchor = sized.label_pos(pos, &atlas);
1078
1079 // Equal slack on the left and the right, and on top and bottom.
1080 let before = anchor - content_min;
1081 let after = content_max - (anchor + label);
1082 assert!(
1083 (before.x - after.x).abs() < 1e-3 && (before.y - after.y).abs() < 1e-3,
1084 "at {width}x{height} the label is off-centre: {before:?} before, \
1085 {after:?} after"
1086 );
1087
1088 // And it is inside the content box, so it never touches a corner.
1089 assert!(
1090 before.x >= -1e-3 && before.y >= -1e-3,
1091 "at {width}x{height} the label escapes its content box"
1092 );
1093 }
1094 }
1095 }
1096
1097 /// Adding a skin must not change where an *unskinned* button puts its text —
1098 /// centring in the content box has to reduce to the old `pos + padding`, or
1099 /// every existing layout shifts.
1100 ///
1101 /// The tolerance is `1e-4` **pixels** and not zero, deliberately. Centring
1102 /// reaches the same point by a different route — `min + (max - min - label) /
1103 /// 2` where the old code wrote `pos + padding` — and at a shrink-to-fit size
1104 /// those two associate the same sum differently, which lands up to a few ulps
1105 /// apart (measured: `58.000004` against `58.0`). That is four millionths of a
1106 /// pixel and is not a layout change; asserting bit equality here would be
1107 /// asserting float associativity, which is not the claim.
1108 #[test]
1109 fn an_unskinned_buttons_label_is_still_anchored_at_pos_plus_padding() {
1110 let atlas = atlas();
1111 for text in ["A", "LongButtonLabel", ""] {
1112 for size in [10.0, 14.0, 28.0] {
1113 let button = Button::new(text).with_size(size);
1114 let pos = Vec2::new(50.0, 50.0);
1115 let moved = (button.label_pos(pos, &atlas) - (pos + button.padding)).abs();
1116 assert!(
1117 moved.x < 1e-4 && moved.y < 1e-4,
1118 "{text:?} at {size}: the label moved by {moved:?} px"
1119 );
1120 }
1121 }
1122 }
1123
1124 /// A skinned button emits **only** its label: the background is the
1125 /// [`ButtonSkin`]'s to push, and a widget that also painted a flat rect
1126 /// would paint it over the skin.
1127 #[test]
1128 fn a_skinned_button_draws_its_label_and_no_background() {
1129 let atlas = atlas();
1130 let button = Button::new("Play").with_skin(INSETS);
1131 for state in [
1132 ButtonState::Idle,
1133 ButtonState::Hovered,
1134 ButtonState::Pressed,
1135 ] {
1136 let mut dl = DrawList::new();
1137 button.render(&mut dl, Vec2::ZERO, &atlas, &style(), state);
1138 assert_eq!(dl.len(), 1, "{state:?} emitted more than the label");
1139 assert!(
1140 matches!(dl.commands()[0], DrawCommand::Text { .. }),
1141 "{state:?} emitted something that is not the label"
1142 );
1143 }
1144
1145 // The unskinned button is untouched: rect, outline, label.
1146 let mut dl = DrawList::new();
1147 Button::new("Play").render(&mut dl, Vec2::ZERO, &atlas, &style(), ButtonState::Idle);
1148 assert_eq!(dl.len(), 3);
1149 }
1150
1151 /// Hit testing follows the drawn rect, so a resized or clamped button is
1152 /// clickable exactly where it is visible — including in the corners, which
1153 /// are part of the button and not decoration around it.
1154 #[test]
1155 fn a_resized_skinned_button_is_clickable_across_its_whole_rect() {
1156 let atlas = atlas();
1157 let button = Button::new("Play")
1158 .with_skin(INSETS)
1159 .with_fixed_size(Vec2::new(400.0, 90.0));
1160 let pos = Vec2::new(10.0, 20.0);
1161 let (min, max) = button.rect(pos, &atlas);
1162 assert_eq!(max - min, Vec2::new(400.0, 90.0));
1163
1164 assert!(button.hit_test(pos, (min + max) * 0.5, &atlas));
1165 assert!(
1166 button.hit_test(pos, min + Vec2::new(1.0, 1.0), &atlas),
1167 "the top-left corner of the skin is part of the button"
1168 );
1169 assert!(
1170 button.hit_test(pos, max - Vec2::new(1.0, 1.0), &atlas),
1171 "the bottom-right corner of the skin is part of the button"
1172 );
1173 assert!(
1174 !button.hit_test(pos, max + Vec2::new(2.0, 2.0), &atlas),
1175 "past the skin is not the button"
1176 );
1177 }
1178
1179 #[test]
1180 fn button_different_styles_affect_bg_color() {
1181 let btn = Button::new("Test");
1182 let mut dl_hover = DrawList::new();
1183 btn.render(
1184 &mut dl_hover,
1185 Vec2::ZERO,
1186 &atlas(),
1187 &style(),
1188 ButtonState::Hovered,
1189 );
1190
1191 let mut dl_idle = DrawList::new();
1192 btn.render(
1193 &mut dl_idle,
1194 Vec2::ZERO,
1195 &atlas(),
1196 &style(),
1197 ButtonState::Idle,
1198 );
1199
1200 // Both should have a Rect command; colors differ.
1201 if let DrawCommand::Rect { color: c1, .. } = &dl_hover.commands()[0] {
1202 if let DrawCommand::Rect { color: c2, .. } = &dl_idle.commands()[0] {
1203 assert_ne!(
1204 c1, c2,
1205 "hover and idle should have different background colors"
1206 );
1207 } else {
1208 panic!("second command not Rect");
1209 }
1210 } else {
1211 panic!("first command not Rect");
1212 }
1213 }
1214
1215 // -----------------------------------------------------------------------
1216 // ButtonSkin
1217 // -----------------------------------------------------------------------
1218
1219 /// Three 16x16 frames in one atlas, with the given insets on each.
1220 fn skin_with(insets: [SkinInsets; 3]) -> ButtonSkin {
1221 let mut images = crate::image::ImageAtlas::new();
1222 let mut frame = |shade: u8, insets| NineSliceImage {
1223 image: images
1224 .register(16, 16, &[shade; 16 * 16 * 4])
1225 .expect("fits an empty page"),
1226 insets,
1227 };
1228 ButtonSkin {
1229 idle: frame(10, insets[0]),
1230 hovered: frame(20, insets[1]),
1231 pressed: frame(30, insets[2]),
1232 }
1233 }
1234
1235 /// **A state draws its own frame and nothing moves**: the same nine
1236 /// rectangles for every state, each state sampling a different image.
1237 #[test]
1238 fn a_button_skin_swaps_the_picture_and_leaves_the_rectangles_alone() {
1239 let skin = skin_with([SkinInsets::new(3.0, 5.0, 2.0, 4.0); 3]);
1240 let quads = |state| {
1241 let mut dl = DrawList::new();
1242 skin.draw(
1243 &mut dl,
1244 state,
1245 Vec2::new(10.0, 10.0),
1246 Vec2::new(90.0, 40.0),
1247 2.0,
1248 );
1249 dl.commands()
1250 .iter()
1251 .map(|command| match command {
1252 DrawCommand::Image {
1253 min, max, uv_min, ..
1254 } => (*min, *max, *uv_min),
1255 other => panic!("a skin drew {other:?}"),
1256 })
1257 .collect::<Vec<_>>()
1258 };
1259 let [idle, hovered, pressed] = [
1260 ButtonState::Idle,
1261 ButtonState::Hovered,
1262 ButtonState::Pressed,
1263 ]
1264 .map(quads);
1265 assert_eq!(idle.len(), 9);
1266 for index in 0..9 {
1267 assert_eq!(
1268 (idle[index].0, idle[index].1),
1269 (pressed[index].0, pressed[index].1),
1270 "quad {index} moved with the state"
1271 );
1272 assert_eq!(
1273 (hovered[index].0, hovered[index].1),
1274 (idle[index].0, idle[index].1)
1275 );
1276 assert_ne!(idle[index].2, hovered[index].2, "quad {index}");
1277 assert_ne!(hovered[index].2, pressed[index].2, "quad {index}");
1278 assert_ne!(idle[index].2, pressed[index].2, "quad {index}");
1279 }
1280 }
1281
1282 #[test]
1283 fn a_skins_insets_are_its_idle_frames_and_disagreement_is_reported() {
1284 let agreed = skin_with([SkinInsets::new(3.0, 5.0, 2.0, 4.0); 3]);
1285 assert_eq!(agreed.insets(), SkinInsets::new(3.0, 5.0, 2.0, 4.0));
1286 assert!(agreed.insets_agree());
1287
1288 let split = skin_with([
1289 SkinInsets::uniform(4.0),
1290 SkinInsets::uniform(4.0),
1291 SkinInsets::uniform(6.0),
1292 ]);
1293 assert!(!split.insets_agree());
1294 // Clamped to the frame, as the drawing is.
1295 let over = skin_with([SkinInsets::new(40.0, 40.0, 0.0, 0.0); 3]);
1296 assert_eq!(over.insets(), SkinInsets::new(16.0, 0.0, 0.0, 0.0));
1297 }
1298}