Skip to main content

crcbl_ui/
menu.rs

1//! Menus: a centred window frame, skinned buttons inside it, and the keyboard
2//! that drives them.
3//!
4//! ```text
5//!                     ┌───────────────────────────┐
6//!                     │         PAUSED            │   ← title
7//!                     │  ┌─────────────────────┐  │
8//!                     │  │ RESUME          ESC │  │   ← selected → Hovered
9//!                     │  ├─────────────────────┤  │
10//!                     │  │ FULLSCREEN      F11 │  │
11//!                     │  └─────────────────────┘  │
12//!                     └───────────────────────────┘
13//!                       centred in the framebuffer
14//! ```
15//!
16//! # What is here and what is not
17//!
18//! **Layout, selection and activation.** Every rectangle this module produces is
19//! in screen pixels, Y **down**, the space the whole crate measures in — so a
20//! menu is positioned, hit-tested and navigated with no device and no art in the
21//! room, which is what lets the interesting properties (it is centred, its
22//! corners do not move, the paused state does not also draw the start menu) be
23//! asserted as arithmetic.
24//!
25//! **The menu is built on the element tree.** [`Menu::layout`] and
26//! [`Menu::render`] build the same [`crate::tree`] of blocks and spans — a
27//! screen, the scrim, the panel, the title and a row per item — lay it out on
28//! Taffy and read the rectangles back or emit it, so the arithmetic that used to
29//! place each label is flexbox now. The tree is a view: which row is selected,
30//! held or hovered stays in this module's model, and each row is built in the
31//! pseudo-class [`Menu::state`] derives, so the keyboard-first API below is
32//! unchanged.
33//!
34//! **The skin is `default.css`'s.** The window frame and the button frames are
35//! `border-image`s over the panel and the rows, which frame a row draws is its
36//! `:hover` or `:active` rule, and every colour is a rule too. The pictures are
37//! a [`MenuSkin`]'s registered images, which [`Menu::render`] binds under the
38//! names the sheet's `url()`s use; the art itself is `crcbl-render`'s
39//! (`crcbl_render::menu::menu_skin` registers it). The lengths stay
40//! [`MenuStyle`]'s, set on the nodes inline, because they are a pixel-art scale
41//! times a base metric and a stylesheet has no arithmetic to scale with; the
42//! frame's insets reach the layout through them, and `crcbl-render`'s tests
43//! read the insets back off the art so the layout and the picture cannot drift.
44//!
45//! # Why the whole menu is one type and not a `Vec<Button>`
46//!
47//! A menu has one property a pile of buttons does not: **it is centred as a
48//! unit**. Its panel has to be measured before any button can be placed, because
49//! the panel's width is the widest button's width and the buttons are centred in
50//! the panel. Handing a caller three `Button`s and letting it do the arithmetic
51//! is handing every sample the same arithmetic to get subtly differently wrong.
52//!
53//! # The keyboard is the primary input, and the pointer is optional
54//!
55//! The samples are played with the keyboard, so a menu that could only be
56//! clicked would be a regression. The model here is keyboard-first:
57//! [`Menu::select_next`]/[`Menu::select_previous`] move a **selection**, and the
58//! selected item draws as [`ButtonState::Hovered`] — the same art the pointer
59//! lights up, because "the thing that will happen if you commit" is the same
60//! idea for both devices. [`Menu::press`] holds it at [`ButtonState::Pressed`]
61//! while the key is down and [`Menu::activate`] fires it.
62//!
63//! The pointer is [`Menu::point`], is entirely optional, and when a cursor is
64//! over an item it takes over the highlight for as long as it is there. A game
65//! that never calls it behaves exactly as if there were no mouse.
66//!
67//! # Three kinds of row
68//!
69//! A row fires, or it carries a value — see [`MenuItemKind`]. A **button**
70//! reports its id from the commit key or a click. A **slider** carries a
71//! position along a groove and reports nothing; the arrows and a drag move it.
72//! A **cycler** carries one choice of a fixed list and reports nothing either:
73//! the arrows walk the list and stop at its ends, the commit key and a click
74//! walk it forward and round. The two value rows are read back by id —
75//! [`Menu::slider`] and [`Menu::cycler`] — rather than fired, so no value ever
76//! reaches a game's action table looking like a button press.
77//!
78//! # Captions
79//!
80//! [`Menu::subtitle`] is lines of text under the title — the controls, a
81//! warning — each a [`Caption`] in a [`CaptionTone`]: the hint's colour, or
82//! the warning's. They are not rows: nothing selects, hovers or fires them,
83//! so the selection, the pointer and every index into [`Menu::items`] are
84//! exactly what they were without them, whatever their tone.
85//!
86//! # Fitting a small window, then scrolling
87//!
88//! [`Menu::layout_with_font_fitted`] lays a menu out in a registered font at
89//! the largest size that fits the window, in two stages:
90//!
91//! 1. **Shrink.** Every font size and gap shrinks by one factor, in steps of
92//!    [`FIT_FONT_STEP`], down to [`MenuStyle::MIN_FONT_SIZE`]; the art stays at
93//!    a whole-number scale of at least one, so the frames' corners stay on
94//!    whole pixels.
95//! 2. **Scroll.** If even the smallest size is too tall, the item list is
96//!    capped at the height left and scrolls; the title and the captions stay
97//!    put. Only a menu too wide at the smallest size — the list scrolls up and
98//!    down only — or too short to show one row is refused, with a
99//!    [`MenuFitError`] saying which.
100//!
101//! A scrolled list follows the keyboard: a selection moved by
102//! [`Menu::select_next`] or [`Menu::select_previous`] is scrolled into view by
103//! the next layout. [`Menu::scroll_wheel`] moves it by the pointer's wheel
104//! instead, until the keyboard next moves the selection. A row scrolled wholly
105//! out of view is neither drawn nor hit.
106
107use std::ops::Range;
108use std::sync::Arc;
109
110use glam::Vec2;
111
112use crate::draw_list::{DrawCommand, DrawList};
113use crate::font::Font;
114use crate::image::{AtlasImage, NineSliceImage};
115use crate::style::{Declaration, Diagnostic, PseudoClasses, Severity, SheetId, Sides, Stylesheet};
116use crate::text::FontAtlas;
117#[cfg(test)]
118use crate::text::LINE_HEIGHT;
119use crate::tree::{
120    AvailableSpace, FamilyName, Length, LengthAuto, LineHeight, NodeKey, Overflow, Ui,
121};
122use crate::widget::{
123    ButtonSkin, ButtonState, NATURAL_FONT_SIZE, PointerInput, SkinInsets, UiState, WidgetId,
124};
125
126// ---------------------------------------------------------------------------
127// Skin
128// ---------------------------------------------------------------------------
129
130/// The pictures a menu is drawn with: a window frame, a button frame per state
131/// and the scrim behind them, all registered in one [`ImageAtlas`](crate::ImageAtlas).
132///
133/// Every sample's menus use the one `crcbl-render` ships; see
134/// `crcbl_render::menu` for why the art lives there.
135///
136/// [`Menu::render`] binds the panel and the three button images under the
137/// names `default.css`'s menu rules give them, and the sheet cuts each at its
138/// own `border-image-slice`: the insets a [`NineSliceImage`] carries are the
139/// art's, which [`PANEL_INSETS`] and [`BUTTON_INSETS`] restate for the layout
140/// and the sheet's slices are held to.
141#[derive(Debug, Clone, Copy, PartialEq)]
142pub struct MenuSkin {
143    /// The window frame, nine-sliced round the panel.
144    pub panel: NineSliceImage,
145    /// The button frames.
146    pub buttons: ButtonSkin,
147    /// Stretched over the whole framebuffer and tinted by the sheet's
148    /// `.menu-scrim` colour, so the art decides its texture and the sheet how
149    /// dark it gets.
150    pub scrim: AtlasImage,
151}
152
153// ---------------------------------------------------------------------------
154// Style
155// ---------------------------------------------------------------------------
156
157/// Every length a menu is laid out with, in **pixels**.
158///
159/// Built from a whole-number `scale` by [`MenuStyle::pixel_art`]: the art is
160/// pixel art and the panel is drawn at one texel per `scale` device pixels, so
161/// every gap, pad and font size is a base metric times the same integer. A
162/// fractional scale would put a nine-slice's fixed corner on a half pixel, which
163/// is the one thing `SampleMode::Pixel` cannot hide.
164#[derive(Debug, Clone, Copy, PartialEq)]
165pub struct MenuStyle {
166    /// Device pixels per texel of the menu art.
167    pub scale: f32,
168    /// The window frame's fixed corners, in pixels.
169    pub panel: SkinInsets,
170    /// A button skin's fixed corners, in pixels.
171    pub button: SkinInsets,
172    /// Space between the panel's frame and its contents.
173    pub panel_padding: Vec2,
174    /// Space between a button's frame and its label.
175    pub button_padding: Vec2,
176    /// Vertical space between two buttons.
177    pub item_gap: f32,
178    /// Vertical space between the title and the first button.
179    pub title_gap: f32,
180    /// The title's font size.
181    pub title_size: f32,
182    /// An item label's font size.
183    pub item_size: f32,
184    /// The least space between an item's label and its key hint.
185    pub hint_gap: f32,
186    /// The least width a [`Slider`] row's groove is given.
187    ///
188    /// A least, not a width: [`Menu::layout_with`] stretches the groove into
189    /// whatever the panel's widest row left over, so a slider beside a long
190    /// label is a long slider. This is what stops it collapsing when the slider
191    /// row *is* the widest one.
192    pub track_width: f32,
193    /// How tall a slider's groove is drawn.
194    pub track_height: f32,
195    /// The handle's size. Its width is also the travel the groove loses at each
196    /// end, so the handle stays inside the groove at both extremes.
197    pub handle_size: Vec2,
198    /// The title's colour.
199    ///
200    /// **This and the other colours restate `default.css`'s menu rules, which
201    /// are what draw them**: a style with different colours lays out the same
202    /// menu and draws it in the sheet's. They are here for a caller measuring
203    /// what a menu drew — the scrim's alpha over a golden image, say — and
204    /// `the_sheet_draws_the_colours_and_the_slices_the_style_restates` holds
205    /// [`MenuStyle::pixel_art`]'s to the sheet's.
206    pub title_color: [f32; 4],
207    /// An item label's colour. See [`MenuStyle::title_color`].
208    pub label_color: [f32; 4],
209    /// A key hint's colour — dimmer than the label it belongs to — and a
210    /// [`CaptionTone::Hint`] caption's. See [`MenuStyle::title_color`].
211    pub hint_color: [f32; 4],
212    /// A [`CaptionTone::Warning`] caption's colour: the console's amber for a
213    /// warning, so a line that warns reads as one. See
214    /// [`MenuStyle::title_color`].
215    pub warning_color: [f32; 4],
216    /// A slider groove's colour, behind the part not filled in. See
217    /// [`MenuStyle::title_color`].
218    pub track_color: [f32; 4],
219    /// The colour of the groove up to the handle. See
220    /// [`MenuStyle::title_color`].
221    pub fill_color: [f32; 4],
222    /// The handle's colour. See [`MenuStyle::title_color`].
223    pub handle_color: [f32; 4],
224    /// What the frame behind the menu is dimmed with. See
225    /// [`MenuStyle::title_color`].
226    pub scrim_color: [f32; 4],
227}
228
229/// The insets of the window frame `crcbl-render` ships, in **texels**.
230///
231/// The source figure the pixel corners come from: [`MenuStyle::pixel_art`] is
232/// the only place texels become pixels, and it multiplies this by the scale
233/// into [`MenuStyle::panel`]. Kept in texels so a menu can be laid out — and
234/// the layout tested — with no renderer and no device, and checked against the
235/// art by `crcbl_render::menu`'s
236/// `the_shipped_art_has_the_insets_the_layout_assumes`, which reads the same
237/// figure back off the registered skin and compares.
238pub const PANEL_INSETS: SkinInsets = SkinInsets::new(4.0, 4.0, 4.0, 4.0);
239
240/// The insets of the button skin `crcbl-render` ships, in **texels**.
241///
242/// The source figure [`MenuStyle::button`] is pre-multiplied from —
243/// [`MenuStyle::pixel_art`] is the only place texels become pixels.
244///
245/// **Currently the same four numbers as [`PANEL_INSETS`], and a separate
246/// constant anyway.** A `.crpix` carries one set of insets for the whole sheet
247/// and the shipped art is one sheet, so the panel and the buttons have to agree
248/// today; they describe different things and a redrawn sheet could split them
249/// without touching a line of layout. `crcbl_render::menu`'s
250/// `the_shipped_art_has_the_insets_the_layout_assumes` reads both back off the
251/// art, so a split shows up as a failure rather than as a silently wrong label
252/// position.
253pub const BUTTON_INSETS: SkinInsets = SkinInsets::new(4.0, 4.0, 4.0, 4.0);
254
255impl MenuStyle {
256    /// The largest scale [`Menu::layout`] will choose.
257    ///
258    /// Four rather than unbounded: past it the title's glyphs are taller than a
259    /// brick and the menu stops reading as part of the game.
260    pub const MAX_SCALE: u32 = 4;
261
262    /// The smallest item font size [`Menu::layout_with_font_fitted`] shrinks
263    /// to, in pixels per em.
264    ///
265    /// Eight: a typical face's x-height is about half an em, so this leaves
266    /// lowercase four pixels tall — the fewest the hinter can snap `e`, `c`
267    /// and `o` apart in. A window that needs smaller text gets a scrolled
268    /// list, or a [`MenuFitError`], rather than a menu nobody can read.
269    pub const MIN_FONT_SIZE: f32 = 8.0;
270
271    /// The shipped look, at `scale` device pixels per texel.
272    ///
273    /// `scale` is clamped to at least one — a menu drawn at zero is not a
274    /// smaller menu, it is an invisible one.
275    #[must_use]
276    pub fn pixel_art(scale: u32) -> Self {
277        let scale = scale.max(1) as f32;
278        Self {
279            scale,
280            panel: scaled(PANEL_INSETS, scale),
281            button: scaled(BUTTON_INSETS, scale),
282            panel_padding: Vec2::new(8.0, 7.0) * scale,
283            button_padding: Vec2::new(6.0, 3.0) * scale,
284            item_gap: 4.0 * scale,
285            title_gap: 8.0 * scale,
286            // Twice the atlas's natural height, so the title is a heading rather
287            // than a bolder line of the same text.
288            title_size: NATURAL_FONT_SIZE * 2.0 * scale,
289            item_size: NATURAL_FONT_SIZE * scale,
290            hint_gap: 10.0 * scale,
291            track_width: 48.0 * scale,
292            track_height: 4.0 * scale,
293            handle_size: Vec2::new(6.0, 12.0) * scale,
294            title_color: [1.0, 0.94, 0.55, 1.0],
295            label_color: [0.94, 0.95, 1.0, 1.0],
296            hint_color: [0.62, 0.64, 0.82, 1.0],
297            warning_color: [1.0, 0.78, 0.35, 1.0],
298            // The groove is the darkest of the three and the handle the
299            // brightest, so the three read as recess, level and grip without
300            // any art behind them.
301            track_color: [0.10, 0.11, 0.18, 1.0],
302            fill_color: [0.42, 0.46, 0.72, 1.0],
303            handle_color: [0.94, 0.95, 1.0, 1.0],
304            // Two thirds, in straight alpha: enough that the panel's own dark
305            // fill separates from the game behind it, not so much that the
306            // player loses track of where the ball was.
307            scrim_color: [0.0, 0.0, 0.0, 0.66],
308        }
309    }
310
311    /// This style with its item font at `item_size`, and every other length
312    /// shrunk by the same factor — what [`Menu::layout_with_font_fitted`]
313    /// tries.
314    ///
315    /// The frames' corners are the art's texels at the whole-number scale the
316    /// factor leaves, never below one, so the nine-slice stays on whole
317    /// pixels. Every other length but the font sizes is rounded to a whole
318    /// pixel, which with [`row_line`]'s whole line pitch makes every row a
319    /// whole number of pixels tall — what lets a scrolled list build only the
320    /// rows in view and still put them where the layout said.
321    fn shrunk(&self, item_size: f32) -> Self {
322        let factor = item_size / self.item_size;
323        let whole = |length: f32| (length * factor).round();
324        let art = (self.scale * factor).floor().max(1.0);
325        let corners = |insets: SkinInsets| {
326            let texels = |length: f32| (length / self.scale * art).round();
327            SkinInsets::new(
328                texels(insets.left),
329                texels(insets.right),
330                texels(insets.top),
331                texels(insets.bottom),
332            )
333        };
334        Self {
335            scale: art,
336            panel: corners(self.panel),
337            button: corners(self.button),
338            panel_padding: Vec2::new(whole(self.panel_padding.x), whole(self.panel_padding.y)),
339            button_padding: Vec2::new(whole(self.button_padding.x), whole(self.button_padding.y)),
340            item_gap: whole(self.item_gap),
341            title_gap: whole(self.title_gap),
342            title_size: self.title_size * factor,
343            item_size,
344            hint_gap: whole(self.hint_gap),
345            track_width: whole(self.track_width),
346            track_height: whole(self.track_height),
347            handle_size: Vec2::new(whole(self.handle_size.x), whole(self.handle_size.y)),
348            ..*self
349        }
350    }
351
352    /// The panel's fixed corners, in device pixels.
353    ///
354    /// [`MenuStyle::panel`] itself: `pixel_art` pre-multiplies the texel
355    /// source figure [`PANEL_INSETS`] by the scale, so the layout reads the
356    /// pixel corners through this accessor the same way it always has.
357    #[must_use]
358    pub fn panel_corners(&self) -> SkinInsets {
359        self.panel
360    }
361
362    /// A button's fixed corners, in device pixels.
363    ///
364    /// [`MenuStyle::button`] itself — see [`panel_corners`](Self::panel_corners).
365    #[must_use]
366    pub fn button_corners(&self) -> SkinInsets {
367        self.button
368    }
369}
370
371fn scaled(insets: SkinInsets, scale: f32) -> SkinInsets {
372    SkinInsets::new(
373        insets.left * scale,
374        insets.right * scale,
375        insets.top * scale,
376        insets.bottom * scale,
377    )
378}
379
380impl Default for MenuStyle {
381    fn default() -> Self {
382        Self::pixel_art(1)
383    }
384}
385
386// ---------------------------------------------------------------------------
387// The model
388// ---------------------------------------------------------------------------
389
390/// A value between zero and one that the player drags along a groove.
391///
392/// **Unitless on purpose.** A slider that knew it was showing an exposure, a
393/// volume or a mouse sensitivity would need to know that exposure is a ratio
394/// and volume is decibels, and it would be wrong for the next one. The caller
395/// owns the mapping in both directions: it writes a position in with
396/// [`Menu::set_slider`] and reads one back with [`Menu::slider`].
397#[derive(Debug, Clone, Copy, PartialEq)]
398pub struct Slider {
399    position: f32,
400}
401
402impl Slider {
403    /// How far one press of a menu key moves the handle, as a share of the
404    /// groove.
405    ///
406    /// Twenty presses end to end, which is the granularity a player expects of
407    /// a volume: fine enough to land where they meant and coarse enough to
408    /// cross the range without holding a key down. A pointer drag is not
409    /// quantised by this at all — it lands wherever the cursor is.
410    pub const KEY_STEP: f32 = 0.05;
411
412    /// A slider whose handle sits `position` of the way along, clamped into
413    /// `0.0..=1.0`.
414    #[must_use]
415    pub fn new(position: f32) -> Self {
416        Self {
417            position: clamp_unit(position),
418        }
419    }
420
421    /// Where the handle sits: `0.0` at the left end of the groove, `1.0` at the
422    /// right. Always in that range.
423    #[must_use]
424    pub const fn position(&self) -> f32 {
425        self.position
426    }
427
428    /// Moves the handle, clamped into `0.0..=1.0`.
429    pub fn set_position(&mut self, position: f32) {
430        self.position = clamp_unit(position);
431    }
432}
433
434/// Into `0.0..=1.0`, with `NaN` landing at zero.
435///
436/// `f32::clamp` propagates a `NaN` rather than replacing it, and a `NaN`
437/// position is a handle drawn nowhere and a caller handed back a number it
438/// cannot map. Zero is the end of the groove, which is a place.
439fn clamp_unit(position: f32) -> f32 {
440    if position.is_nan() {
441        0.0
442    } else {
443        position.clamp(0.0, 1.0)
444    }
445}
446
447/// A row that holds one choice of a fixed, ordered list — a display mode, a
448/// frame cap, an on/off switch.
449///
450/// It knows how many choices there are and which is chosen, and **not what
451/// they are**: the caller owns the list and its spellings, and writes the
452/// chosen one's caption in as the row's hint, exactly as a [`Slider`] leaves
453/// the mapping from a position to a value with the caller. What the widget
454/// owns is the stepping, and it has two rules because a player's hands have
455/// two: the arrows walk the list and **stop at its ends** — [`Menu::nudge_cycler`],
456/// which draws a chevron only on the side a step would go — and the commit
457/// key or a click walks it **forward and round** — [`Menu::activate`] and
458/// [`Menu::point`] — so one key reaches every choice, which is what a row that
459/// was a button did before this existed.
460#[derive(Debug, Clone, Copy, PartialEq, Eq)]
461pub struct Cycler {
462    chosen: usize,
463    count: usize,
464}
465
466impl Cycler {
467    /// `count` choices with `chosen` picked, clamped to the last of them.
468    ///
469    /// No choices at all is a cycler with nothing chosen: [`Cycler::chosen`]
470    /// reads zero and every step is refused, rather than a wrap that would
471    /// divide by the count.
472    #[must_use]
473    pub fn new(count: usize, chosen: usize) -> Self {
474        let mut cycler = Self { chosen: 0, count };
475        cycler.choose(chosen);
476        cycler
477    }
478
479    /// How many choices there are.
480    #[must_use]
481    pub const fn count(&self) -> usize {
482        self.count
483    }
484
485    /// Which choice is picked: an index into the caller's list, always below
486    /// [`Cycler::count`] unless that is zero.
487    #[must_use]
488    pub const fn chosen(&self) -> usize {
489        self.chosen
490    }
491
492    /// Picks a choice, clamped to the last one.
493    pub fn choose(&mut self, index: usize) {
494        self.chosen = index.min(self.count.saturating_sub(1));
495    }
496
497    /// Steps one choice along, and reports whether the choice changed.
498    ///
499    /// Without `wrap` a step past either end stays at that end; with it the
500    /// step goes round. `false` means the choice is where it was, which at an
501    /// end without `wrap` is the ordinary way a held key arrives.
502    pub fn step(&mut self, forward: bool, wrap: bool) -> bool {
503        if self.count == 0 {
504            return false;
505        }
506        let last = self.count - 1;
507        let next = match (forward, wrap) {
508            (true, _) if self.chosen < last => self.chosen + 1,
509            (true, true) => 0,
510            (false, _) if self.chosen > 0 => self.chosen - 1,
511            (false, true) => last,
512            _ => return false,
513        };
514        let moved = next != self.chosen;
515        self.chosen = next;
516        moved
517    }
518
519    /// Whether a step in that direction, without a wrap, would move.
520    #[must_use]
521    pub const fn can_step(&self, forward: bool) -> bool {
522        if forward {
523            self.chosen + 1 < self.count
524        } else {
525            self.chosen > 0
526        }
527    }
528}
529
530/// What a cycler's caption is drawn between: a chevron on each side a step
531/// would go, and the same width of nothing on a side it would not — so the
532/// caption stays put as the chevrons come and go, which needs every glyph to
533/// advance alike and the built-in atlas's do.
534const BACK_CHEVRON: &str = "< ";
535const FORWARD_CHEVRON: &str = " >";
536const NO_CHEVRON: &str = "  ";
537
538/// What a menu row *is*: something that fires, or something that carries a
539/// value.
540#[derive(Debug, Clone, Copy, PartialEq)]
541pub enum MenuItemKind {
542    /// A button. [`Menu::activate`] and a click both report its id.
543    Action,
544    /// A slider. It never fires — see [`Menu::activate`] — and the caller reads
545    /// its value with [`Menu::slider`] instead.
546    Slider(Slider),
547    /// A cycler. The commit key and a click step it rather than fire it, and
548    /// the caller reads which choice is picked with [`Menu::cycler`].
549    Cycler(Cycler),
550}
551
552/// One line of a menu: what it says, what key does it, and what it is called.
553#[derive(Debug, Clone, PartialEq)]
554pub struct MenuItem {
555    /// Names this item to the caller — what [`Menu::activate`] hands back.
556    ///
557    /// A [`WidgetId`] rather than an index, so a menu that grows an entry does
558    /// not silently re-number what the loop is matching on.
559    pub id: WidgetId,
560    /// The label, drawn left-aligned in the button.
561    pub label: String,
562    /// The key that also does this, drawn right-aligned and dimmer. Empty for an
563    /// item with no keyboard shortcut of its own.
564    ///
565    /// **A hint, not a binding.** This type does not read the keyboard; the game
566    /// loop already owns its key handling and this is what tells the player what
567    /// it is.
568    ///
569    /// A [`MenuItemKind::Slider`] row has no key of its own to advertise, so
570    /// this is where its **value** goes — the formatted number the caller
571    /// refreshes as the handle moves. Right-aligned either way. A
572    /// [`MenuItemKind::Cycler`] row's is the caption of the choice it holds,
573    /// which the caller refreshes as the choice changes; it is drawn between
574    /// chevrons — see [`MenuItem::caption`].
575    pub hint: String,
576    /// Whether this row fires or carries a value.
577    pub kind: MenuItemKind,
578}
579
580impl MenuItem {
581    /// An item with a key hint beside it.
582    #[must_use]
583    pub fn new(id: WidgetId, label: impl Into<String>, hint: impl Into<String>) -> Self {
584        Self {
585            id,
586            label: label.into(),
587            hint: hint.into(),
588            kind: MenuItemKind::Action,
589        }
590    }
591
592    /// A slider row: a label, a groove with its handle `position` of the way
593    /// along, and `value` drawn where a key hint would be.
594    #[must_use]
595    pub fn slider(
596        id: WidgetId,
597        label: impl Into<String>,
598        value: impl Into<String>,
599        position: f32,
600    ) -> Self {
601        Self {
602            id,
603            label: label.into(),
604            hint: value.into(),
605            kind: MenuItemKind::Slider(Slider::new(position)),
606        }
607    }
608
609    /// A cycler row: a label, one of `count` choices with `chosen` picked, and
610    /// that choice's `caption` drawn where a key hint would be.
611    #[must_use]
612    pub fn cycler(
613        id: WidgetId,
614        label: impl Into<String>,
615        caption: impl Into<String>,
616        count: usize,
617        chosen: usize,
618    ) -> Self {
619        Self {
620            id,
621            label: label.into(),
622            hint: caption.into(),
623            kind: MenuItemKind::Cycler(Cycler::new(count, chosen)),
624        }
625    }
626
627    /// What this row draws where a key hint goes.
628    ///
629    /// The hint itself for a button or a slider. For a cycler, the hint between
630    /// a `<` and a `>` — each present only on the side a step without a wrap
631    /// would go, and replaced by blank of the same width on the side it would
632    /// not, so the caption does not shift as they come and go.
633    #[must_use]
634    pub fn caption(&self) -> std::borrow::Cow<'_, str> {
635        match self.kind {
636            MenuItemKind::Cycler(cycler) => {
637                let chevron = |forward: bool, chevron: &'static str| {
638                    if cycler.can_step(forward) {
639                        chevron
640                    } else {
641                        NO_CHEVRON
642                    }
643                };
644                std::borrow::Cow::Owned(format!(
645                    "{}{}{}",
646                    chevron(false, BACK_CHEVRON),
647                    self.hint,
648                    chevron(true, FORWARD_CHEVRON)
649                ))
650            }
651            MenuItemKind::Action | MenuItemKind::Slider(_) => {
652                std::borrow::Cow::Borrowed(self.hint.as_str())
653            }
654        }
655    }
656}
657
658/// How a [`Caption`] is drawn: which of [`MenuStyle`]'s colours it takes.
659///
660/// A tone per line rather than a separate warning field on [`Menu`], so a
661/// menu can warn on any of its lines and another tone is another variant.
662#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
663pub enum CaptionTone {
664    /// Explains — the controls, say — in [`MenuStyle::hint_color`].
665    #[default]
666    Hint,
667    /// Warns — of what a choice discards, say — in
668    /// [`MenuStyle::warning_color`].
669    Warning,
670}
671
672/// One line of a menu's [`Menu::subtitle`]: its text, and the tone it is
673/// drawn in.
674///
675/// A `&str` or a `String` converts into a [`CaptionTone::Hint`] caption, so a
676/// line that only explains is `"ARROWS MOVE".into()`.
677#[derive(Debug, Clone, PartialEq, Eq, Default)]
678pub struct Caption {
679    /// The line, drawn centred under the title.
680    pub text: String,
681    /// Which colour it is drawn in.
682    pub tone: CaptionTone,
683}
684
685impl Caption {
686    /// A line in [`CaptionTone::Hint`].
687    #[must_use]
688    pub fn hint(text: impl Into<String>) -> Self {
689        Self {
690            text: text.into(),
691            tone: CaptionTone::Hint,
692        }
693    }
694
695    /// A line in [`CaptionTone::Warning`].
696    #[must_use]
697    pub fn warning(text: impl Into<String>) -> Self {
698        Self {
699            text: text.into(),
700            tone: CaptionTone::Warning,
701        }
702    }
703}
704
705impl From<&str> for Caption {
706    fn from(text: &str) -> Self {
707        Self::hint(text)
708    }
709}
710
711impl From<String> for Caption {
712    fn from(text: String) -> Self {
713        Self::hint(text)
714    }
715}
716
717/// A modal menu: a title, some items, and which one is selected.
718///
719/// Retained across frames — unlike the rest of this crate — because a selection
720/// is state by definition, and an immediate-mode menu whose highlight was
721/// recomputed from nothing every frame would have no keyboard at all.
722#[derive(Debug, Clone, PartialEq, Default)]
723pub struct Menu {
724    /// The heading, drawn above the items.
725    pub title: String,
726    /// Lines drawn under the title, centred and each in its
727    /// [`CaptionTone`]'s colour — see the module's *Captions*. Empty by
728    /// default, which draws exactly the menu there was before captions
729    /// existed.
730    pub subtitle: Vec<Caption>,
731    items: Vec<MenuItem>,
732    selected: usize,
733    /// Whether the selected item is being held down.
734    pressed: bool,
735    /// The item the current press belongs to — the pointer's captured item or
736    /// the keyboard's selection. What decides who draws [`ButtonState::Pressed`]:
737    /// `pressed` alone cannot, because a drag onto a neighbour leaves the
738    /// capture (and the drawn press) with the item it started on.
739    pressed_index: Option<usize>,
740    /// Which item the pointer is over, if any. Takes over the highlight from
741    /// [`Menu::selected`] while it is `Some`.
742    hovered: Option<usize>,
743    /// The slider row the pointer is dragging, if it is dragging one.
744    ///
745    /// What makes [`Menu::set_slider`] leave a handle alone while the player
746    /// has hold of it: a caller pushing the value it last read back in every
747    /// frame would otherwise fight the drag it is reading from.
748    dragging: Option<usize>,
749    /// How far a scrolled item list is scrolled, in pixels: what the next
750    /// [`Menu::layout_with_font_fitted`] starts from before it clamps it to
751    /// the list's reach and, while `follow_selection` holds, scrolls the
752    /// selection into view. Zero for a list that is not scrolled.
753    scroll: f32,
754    /// Whether the next fitted layout scrolls the selection into view. Set by
755    /// every keyboard move and cleared by [`Menu::scroll_wheel`]: a wheel
756    /// snapped back to the selection every frame could never move the list.
757    follow_selection: bool,
758    /// A game's stylesheet over `default.css`'s menu rules; see
759    /// [`Menu::set_stylesheet`].
760    stylesheet: Option<Arc<str>>,
761}
762
763impl Menu {
764    /// A menu with a title and its items, the first selected.
765    #[must_use]
766    pub fn new(title: impl Into<String>, items: Vec<MenuItem>) -> Self {
767        Self {
768            title: title.into(),
769            subtitle: Vec::new(),
770            items,
771            selected: 0,
772            pressed: false,
773            pressed_index: None,
774            hovered: None,
775            dragging: None,
776            scroll: 0.0,
777            follow_selection: true,
778            stylesheet: None,
779        }
780    }
781
782    /// Draws this menu with `css` over `default.css`'s menu rules, or with
783    /// those rules alone for `None`.
784    ///
785    /// The sheet cascades as an app sheet does: after `default.css`, whatever
786    /// either's selectors, and under what the menu sets inline — every length,
787    /// borders' widths among them, which are [`MenuStyle`]'s: a flat 1 px
788    /// border is a style whose [`MenuStyle::panel`] and [`MenuStyle::button`]
789    /// are 1 px, laid out with [`Menu::layout_with`]. So a sheet sets
790    /// the colours, the frames (`border-image: none` drops one, for a flat
791    /// `background-color` and `border-color` in its place) and the text's
792    /// family, and it is used for measuring as well as drawing, so a layout
793    /// and the render it feeds agree. [`MenuStyle`]'s colours keep restating
794    /// `default.css`'s, not this sheet's.
795    ///
796    /// # Errors
797    ///
798    /// The sheet's errors, when it has any; the menu keeps the sheet it had.
799    pub fn set_stylesheet(&mut self, css: Option<&str>) -> Result<(), Vec<Diagnostic>> {
800        if let Some(css) = css {
801            let (_, diagnostics) = Stylesheet::parse(GAME_SHEET, css);
802            let errors: Vec<Diagnostic> = diagnostics
803                .into_iter()
804                .filter(|diagnostic| diagnostic.severity == Severity::Error)
805                .collect();
806            if !errors.is_empty() {
807                return Err(errors);
808            }
809        }
810        self.stylesheet = css.map(Arc::from);
811        Ok(())
812    }
813
814    /// The items, in the order they are drawn.
815    #[must_use]
816    pub fn items(&self) -> &[MenuItem] {
817        &self.items
818    }
819
820    /// Which item is selected. Zero for an empty menu, which has no items to
821    /// index and never activates one.
822    #[must_use]
823    pub const fn selected(&self) -> usize {
824        self.selected
825    }
826
827    /// The selected item, or `None` when there are none.
828    #[must_use]
829    pub fn selected_item(&self) -> Option<&MenuItem> {
830        self.items.get(self.selected)
831    }
832
833    /// Moves the selection down one, wrapping at the end.
834    ///
835    /// A scrolled list — see [`Menu::layout_with_font_fitted`] — is scrolled
836    /// to the new selection by the next layout, by as little as brings it
837    /// wholly into view. "As little" is measured from the scroll the menu
838    /// holds, which [`Menu::point`] and [`Menu::scroll_wheel`] keep up to
839    /// date: a caller that calls neither still always sees the selection, but
840    /// held at the edge it scrolled past rather than moving inside a still
841    /// list.
842    pub fn select_next(&mut self) {
843        self.move_selection(1);
844    }
845
846    /// Moves the selection up one, wrapping at the start. A scrolled list
847    /// follows it, as [`Menu::select_next`] says.
848    pub fn select_previous(&mut self) {
849        self.move_selection(-1);
850    }
851
852    fn move_selection(&mut self, delta: isize) {
853        if self.items.is_empty() {
854            return;
855        }
856        let len = self.items.len() as isize;
857        let next = (self.selected as isize + delta).rem_euclid(len);
858        self.selected = next as usize;
859        self.follow_selection = true;
860        // A keyboard move takes the highlight back off the pointer: otherwise a
861        // cursor left resting over an item makes the arrow keys look dead.
862        self.hovered = None;
863        self.pressed = false;
864        self.pressed_index = None;
865        self.dragging = None;
866    }
867
868    /// Selects the item with this id, if it is in the menu.
869    ///
870    /// Returns whether it was found — a caller restoring a selection across a
871    /// rebuild wants to know when the item it remembered is gone.
872    pub fn select_id(&mut self, id: WidgetId) -> bool {
873        match self.items.iter().position(|item| item.id == id) {
874            Some(index) => {
875                self.selected = index;
876                self.hovered = None;
877                self.follow_selection = true;
878                true
879            }
880            None => false,
881        }
882    }
883
884    /// Holds the highlighted item down, or lets it up.
885    ///
886    /// Called from the key-down and key-up of whatever key commits — the visible
887    /// half of "the button is being pressed". Activation is [`Menu::activate`];
888    /// this only changes what is drawn.
889    pub const fn press(&mut self, down: bool) {
890        self.pressed = down;
891        // A keyboard press belongs to the highlighted item, which is the
892        // selected one until the pointer takes over.
893        self.pressed_index = if down { Some(self.selected) } else { None };
894    }
895
896    /// Fires the highlighted item and returns its id.
897    ///
898    /// The **highlighted** one, which is the hovered item when a pointer is over
899    /// one and the selected item otherwise — so Enter commits what the player can
900    /// see is about to happen, whichever device put the highlight there.
901    /// A [`MenuItemKind::Slider`] row reports **nothing**: there is no press of
902    /// a commit key that means anything to a value, and an id fired from one
903    /// would reach the game's action table as if a button had been clicked. A
904    /// [`MenuItemKind::Cycler`] row reports nothing for the same reason, and
905    /// the press **steps it forward, round the end** — the one-key walk of the
906    /// whole list the caller reads back with [`Menu::cycler`].
907    pub fn activate(&mut self) -> Option<WidgetId> {
908        self.pressed = false;
909        self.pressed_index = None;
910        let index = self.hovered.unwrap_or(self.selected);
911        match self.items.get_mut(index) {
912            Some(item) => match &mut item.kind {
913                MenuItemKind::Action => Some(item.id),
914                MenuItemKind::Cycler(cycler) => {
915                    cycler.step(true, true);
916                    None
917                }
918                MenuItemKind::Slider(_) => None,
919            },
920            None => None,
921        }
922    }
923
924    /// Drops any hover and any held key.
925    ///
926    /// For a menu being taken off the screen: a menu re-shown with a stale
927    /// `Pressed` on it draws a button nobody is touching.
928    pub const fn clear_input(&mut self) {
929        self.hovered = None;
930        self.pressed = false;
931        self.pressed_index = None;
932        self.dragging = None;
933    }
934
935    /// Where the handle of the slider row named `id` sits, in `0.0..=1.0`.
936    ///
937    /// `None` for an id this menu has no row for, and for a row that is a
938    /// button rather than a slider.
939    #[must_use]
940    pub fn slider(&self, id: WidgetId) -> Option<f32> {
941        self.items.iter().find_map(|item| match item.kind {
942            MenuItemKind::Slider(slider) if item.id == id => Some(slider.position()),
943            _ => None,
944        })
945    }
946
947    /// Moves the handle of the slider row named `id`, and reports whether it
948    /// moved.
949    ///
950    /// **Refused while the player is dragging that row**, which is what lets a
951    /// caller push the value back in unconditionally every frame: the state the
952    /// caller is mirroring came from this handle in the first place, so the
953    /// drag is the newer of the two and writing over it would pin the handle
954    /// under the cursor.
955    ///
956    /// So `false` means one of three things — no such row, not a slider, or the
957    /// player has hold of it — and a caller that needs to tell them apart asks
958    /// [`Menu::slider`] first.
959    pub fn set_slider(&mut self, id: WidgetId, position: f32) -> bool {
960        let dragging = self.dragging;
961        for (index, item) in self.items.iter_mut().enumerate() {
962            if item.id != id {
963                continue;
964            }
965            let MenuItemKind::Slider(slider) = &mut item.kind else {
966                return false;
967            };
968            if dragging == Some(index) {
969                return false;
970            }
971            slider.set_position(position);
972            return true;
973        }
974        false
975    }
976
977    /// Moves the highlighted slider one [`Slider::KEY_STEP`], and reports
978    /// whether a handle moved.
979    ///
980    /// **The keyboard's half of a slider**, and until it existed there was no
981    /// such half: [`Menu::activate`] reports nothing for a slider row by
982    /// design, so a player with no pointer could select a volume and then had
983    /// no way to change it. This module's own opening says the keyboard is the
984    /// primary input; a row that only a mouse could work was that claim being
985    /// false in the one place it is most visible.
986    ///
987    /// The **highlighted** row, on [`Menu::activate`]'s terms — the hovered one
988    /// when a pointer is over one, the selected one otherwise — so the key moves
989    /// what the player can see is about to move.
990    ///
991    /// `false` means nothing moved: the row is a button, there is no row, the
992    /// handle is already at that end of the groove, or the pointer has hold of
993    /// it. The last is [`Menu::set_slider`]'s rule and it is here for the same
994    /// reason: a drag is the newer of the two inputs.
995    pub fn nudge_slider(&mut self, forward: bool) -> bool {
996        let index = self.hovered.unwrap_or(self.selected);
997        if self.dragging == Some(index) {
998            return false;
999        }
1000        let Some(item) = self.items.get_mut(index) else {
1001            return false;
1002        };
1003        let MenuItemKind::Slider(slider) = &mut item.kind else {
1004            return false;
1005        };
1006        let before = slider.position();
1007        slider.set_position(if forward {
1008            before + Slider::KEY_STEP
1009        } else {
1010            before - Slider::KEY_STEP
1011        });
1012        slider.position() != before
1013    }
1014
1015    /// Whether the highlighted row is a slider.
1016    ///
1017    /// What a caller deciding whether a key belongs to the menu has to ask
1018    /// **before** offering it: [`nudge_slider`](Self::nudge_slider) reports
1019    /// whether a handle moved, which is also `false` at the end of the groove,
1020    /// and a key claimed on that would be handed back to the game halfway
1021    /// through a player holding it down.
1022    #[must_use]
1023    pub fn slider_highlighted(&self) -> bool {
1024        matches!(
1025            self.items.get(self.hovered.unwrap_or(self.selected)),
1026            Some(item) if matches!(item.kind, MenuItemKind::Slider(_))
1027        )
1028    }
1029
1030    /// Which choice the cycler row named `id` holds: an index into the
1031    /// caller's list.
1032    ///
1033    /// `None` for an id this menu has no row for, and for a row that is not a
1034    /// cycler.
1035    #[must_use]
1036    pub fn cycler(&self, id: WidgetId) -> Option<usize> {
1037        self.items.iter().find_map(|item| match item.kind {
1038            MenuItemKind::Cycler(cycler) if item.id == id => Some(cycler.chosen()),
1039            _ => None,
1040        })
1041    }
1042
1043    /// Picks the choice of the cycler row named `id`, clamped to its last, and
1044    /// reports whether there was such a row.
1045    ///
1046    /// Nothing refuses it: a cycler is never dragged, so the caller's write is
1047    /// always the newer of the two inputs and mirroring a value back in every
1048    /// frame is safe — the row it mirrors into is the row it read.
1049    pub fn set_cycler(&mut self, id: WidgetId, chosen: usize) -> bool {
1050        self.items
1051            .iter_mut()
1052            .find(|item| item.id == id)
1053            .is_some_and(|item| match &mut item.kind {
1054                MenuItemKind::Cycler(cycler) => {
1055                    cycler.choose(chosen);
1056                    true
1057                }
1058                _ => false,
1059            })
1060    }
1061
1062    /// Steps the highlighted cycler one choice, **stopping at the ends**, and
1063    /// reports whether the choice changed.
1064    ///
1065    /// The arrows' half of a cycler, beside [`Menu::nudge_slider`]: the same
1066    /// keys, the same highlighted row, and the same `false` at the end of the
1067    /// list that a slider gives at the end of its groove — a key held against
1068    /// the last choice does not come round to the first, because a player
1069    /// holding Right to reach the top of a list would overshoot it. The commit
1070    /// key is the one that goes round; see [`Menu::activate`].
1071    pub fn nudge_cycler(&mut self, forward: bool) -> bool {
1072        let index = self.hovered.unwrap_or(self.selected);
1073        match self.items.get_mut(index).map(|item| &mut item.kind) {
1074            Some(MenuItemKind::Cycler(cycler)) => cycler.step(forward, false),
1075            _ => false,
1076        }
1077    }
1078
1079    /// Whether the highlighted row is a cycler — [`slider_highlighted`]'s
1080    /// question for the other row the arrows drive, and asked for the same
1081    /// reason.
1082    ///
1083    /// [`slider_highlighted`]: Self::slider_highlighted
1084    #[must_use]
1085    pub fn cycler_highlighted(&self) -> bool {
1086        matches!(
1087            self.items.get(self.hovered.unwrap_or(self.selected)),
1088            Some(item) if matches!(item.kind, MenuItemKind::Cycler(_))
1089        )
1090    }
1091
1092    /// The value text a slider row draws, replaced.
1093    ///
1094    /// Separate from [`Menu::set_slider`] because the two move for different
1095    /// reasons: the handle is refused mid-drag and the caption never is — a
1096    /// player dragging the exposure is precisely who needs to read the number
1097    /// it has reached.
1098    pub fn set_item_hint(&mut self, id: WidgetId, hint: impl Into<String>) -> bool {
1099        match self.items.iter_mut().find(|item| item.id == id) {
1100            Some(item) => {
1101                item.hint = hint.into();
1102                true
1103            }
1104            None => false,
1105        }
1106    }
1107
1108    /// How item `index` is drawn.
1109    ///
1110    /// [`ButtonState::Pressed`] for the item the current press belongs to —
1111    /// the pointer's captured item, or the selected one under the keyboard —
1112    /// [`ButtonState::Hovered`] for the highlighted item otherwise, and
1113    /// [`ButtonState::Idle`] for everything else — which is what makes a
1114    /// keyboard-only player see the same three frames of art a mouse would light
1115    /// up.
1116    #[must_use]
1117    pub fn state(&self, index: usize) -> ButtonState {
1118        if index >= self.items.len() || index != self.hovered.unwrap_or(self.selected) {
1119            return ButtonState::Idle;
1120        }
1121        if self.pressed_index == Some(index) {
1122            ButtonState::Pressed
1123        } else if self.pressed {
1124            // The press belongs to another item (a drag-off): this one must
1125            // stay Idle, exactly as `interact` reports it.
1126            ButtonState::Idle
1127        } else {
1128            ButtonState::Hovered
1129        }
1130    }
1131
1132    /// Runs one frame of pointer input against `layout`, and reports a click.
1133    ///
1134    /// Entirely optional: a game that never calls this is driven by the keyboard
1135    /// alone and every item stays at the state [`Menu::state`] derives from the
1136    /// selection. A game that does call it gets hover, press capture through
1137    /// `ui` — so a press that starts on one item and is released over another
1138    /// fires neither — and a click that also **moves the selection**, so the
1139    /// keyboard picks up where the mouse left off.
1140    ///
1141    /// In a scrolled list only the part of a row inside the list's
1142    /// [`viewport`](MenuLayout::viewport) is hit, and a row scrolled wholly
1143    /// out of it is not hit at all. While the list follows the keyboard, the
1144    /// scroll `layout` settled on is kept as the one the next keyboard move
1145    /// scrolls from — see [`Menu::select_next`].
1146    pub fn point(
1147        &mut self,
1148        layout: &MenuLayout,
1149        ui: &mut UiState,
1150        pointer: PointerInput,
1151    ) -> Option<WidgetId> {
1152        if self.follow_selection {
1153            self.scroll = layout.scroll();
1154        }
1155        let in_view = layout
1156            .viewport()
1157            .is_none_or(|viewport| contains(viewport, pointer.pos));
1158        let mut clicked = None;
1159        let mut hovered = None;
1160        for (index, item) in layout.items.iter().enumerate() {
1161            let inside =
1162                in_view && layout.shows(index) && contains((item.min, item.max), pointer.pos);
1163            let (state, fired) = ui.interact(item.id, inside, pointer.down, pointer.released);
1164            if inside {
1165                hovered = Some(index);
1166            }
1167            let is_slider = matches!(
1168                self.items.get(index).map(|item| item.kind),
1169                Some(MenuItemKind::Slider(_))
1170            );
1171            if state == ButtonState::Pressed && is_slider {
1172                // Tracked whether or not the cursor is still **inside** the
1173                // row, unlike a button's press: a slider dragged off the end of
1174                // its groove — or above it, which is what a hand does while
1175                // watching the frame behind the panel — keeps the handle at the
1176                // end rather than letting go of it.
1177                if let Some(track) = item.track
1178                    && let Some(MenuItemKind::Slider(slider)) =
1179                        self.items.get_mut(index).map(|item| &mut item.kind)
1180                {
1181                    slider.set_position(position_along(
1182                        track,
1183                        layout.style.handle_size.x,
1184                        pointer.pos.x,
1185                    ));
1186                }
1187                self.dragging = Some(index);
1188                self.pressed = true;
1189                self.pressed_index = Some(index);
1190                self.selected = index;
1191            } else if state == ButtonState::Pressed && inside {
1192                self.pressed = true;
1193                self.pressed_index = Some(index);
1194            }
1195            // A release over a slider ends a drag; it is not a click, and an id
1196            // reported from one would reach the game's action table as though a
1197            // button had been pressed. A release over a cycler is its step
1198            // forward and round, `activate`'s rule, and reports nothing either.
1199            if fired {
1200                match self.items.get_mut(index).map(|item| &mut item.kind) {
1201                    Some(MenuItemKind::Action) => {
1202                        clicked = Some(item.id);
1203                        self.selected = index;
1204                    }
1205                    Some(MenuItemKind::Cycler(cycler)) => {
1206                        cycler.step(true, true);
1207                        self.selected = index;
1208                    }
1209                    _ => {}
1210                }
1211            }
1212        }
1213        self.hovered = hovered;
1214        if !pointer.down {
1215            self.pressed = false;
1216            self.pressed_index = None;
1217            self.dragging = None;
1218        }
1219        clicked
1220    }
1221
1222    /// Scrolls a scrolled item list by a wheel's `delta`, in pixels, and says
1223    /// whether it moved: positive `y` moves toward the end of the list, as
1224    /// [`Ui::scroll_wheel`] reads a wheel. `x` is ignored — the list scrolls
1225    /// up and down only.
1226    ///
1227    /// Only while `pointer` is over the panel, since the list is the one thing
1228    /// in it that moves. The list stops following the keyboard's selection
1229    /// until the keyboard next moves it, so the selection may be scrolled out
1230    /// of view — and the scroll is kept to the fraction of a pixel, so a
1231    /// trackpad's small steps add up, while each layout draws it at the whole
1232    /// pixel nearest. `false` for a list that does not scroll, so the caller
1233    /// can give the wheel to something else.
1234    ///
1235    /// A separate call rather than a [`PointerInput`] field, as
1236    /// [`Ui::scroll_wheel`] is, because every caller builds that by literal.
1237    pub fn scroll_wheel(&mut self, layout: &MenuLayout, pointer: Vec2, delta: Vec2) -> bool {
1238        let Some(list) = &layout.setup.list else {
1239            return false;
1240        };
1241        if !contains(layout.panel, pointer) {
1242            return false;
1243        }
1244        let from = if self.follow_selection {
1245            list.scroll
1246        } else {
1247            self.scroll.clamp(0.0, list.reach)
1248        };
1249        let to = (from + delta.y).clamp(0.0, list.reach);
1250        self.follow_selection = false;
1251        self.scroll = to;
1252        to != from
1253    }
1254
1255    /// Lays this menu out centred in an `extent`-sized framebuffer, at the
1256    /// largest scale that fits.
1257    ///
1258    /// The scale is a pure function of the extent and the menu's own contents:
1259    /// the largest whole number up to [`MenuStyle::MAX_SCALE`] whose panel fits
1260    /// inside [`FIT_FRACTION`] of the framebuffer on **both** axes, and 1 when
1261    /// none of them do. Whole numbers because the art is pixel art; the fit
1262    /// because a menu that overflowed a 1440×400 canvas would have its buttons
1263    /// off the bottom of the screen, which is the failure this replaces.
1264    ///
1265    /// **The panel is measured once, at scale 1**, and each candidate is that
1266    /// size times the scale: every length [`MenuStyle::pixel_art`] makes and
1267    /// every glyph advance is a whole number times the scale, so the tree lays
1268    /// the panel out exactly proportionally —
1269    /// `the_panel_grows_exactly_with_the_scale` holds that — and one layout
1270    /// answers every candidate.
1271    #[must_use]
1272    pub fn layout(&self, extent: (u32, u32), atlas: &FontAtlas) -> MenuLayout {
1273        let base = self.panel_size(atlas, &MenuStyle::pixel_art(1));
1274        let mut chosen = 1;
1275        for scale in 2..=MenuStyle::MAX_SCALE {
1276            let size = base * scale as f32;
1277            if size.x <= extent.0 as f32 * FIT_FRACTION && size.y <= extent.1 as f32 * FIT_FRACTION
1278            {
1279                chosen = scale;
1280            } else {
1281                break;
1282            }
1283        }
1284        self.layout_with(extent, atlas, &MenuStyle::pixel_art(chosen))
1285    }
1286
1287    /// Lays this menu out centred, at a style the caller chose.
1288    #[must_use]
1289    pub fn layout_with(
1290        &self,
1291        extent: (u32, u32),
1292        atlas: &FontAtlas,
1293        style: &MenuStyle,
1294    ) -> MenuLayout {
1295        let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
1296        let setup = Setup::default();
1297        self.laid_out(Some(screen), style, None, &setup, atlas, |ui, built| {
1298            Self::read_layout(ui, built, &self.items, screen, style, &setup)
1299        })
1300    }
1301
1302    /// Lays this menu out centred at `style`, with every line of its text
1303    /// measured in `font` rather than the built-in [`FontAtlas`] — and drawn in
1304    /// it too, since [`Menu::render`] draws in the font the layout it is given
1305    /// was measured in.
1306    ///
1307    /// The text is a registered font's in the menu's own tree, so it is
1308    /// measured by the tree's one text path, as any span in a registered font
1309    /// is: `font-size` is [`MenuStyle`]'s, and the line pitch is the font's
1310    /// `line-height: normal`. [`Menu::layout`]'s scale fit has no counterpart
1311    /// here — it counts on the bitmap font's advances growing exactly with the
1312    /// scale, which a parsed font's do not — so `style` is the caller's; see
1313    /// [`Menu::layout_with_font_fitted`] for a fit that measures instead. A
1314    /// cycler's chevrons keep its caption still only in a font whose `<`, `>`
1315    /// and space advance alike.
1316    #[must_use]
1317    pub fn layout_with_font(
1318        &self,
1319        extent: (u32, u32),
1320        style: &MenuStyle,
1321        font: &Font,
1322    ) -> MenuLayout {
1323        let setup = Setup {
1324            font: Some(font.clone()),
1325            ..Setup::default()
1326        };
1327        self.placed(extent_size(extent), style, &setup)
1328    }
1329
1330    /// Lays this menu out centred in `font`, as [`Menu::layout_with_font`]
1331    /// does, at the largest size up to `style` that fits the framebuffer —
1332    /// shrinking it first and scrolling its item list after, as the module's
1333    /// *Fitting a small window, then scrolling* describes.
1334    ///
1335    /// **Fits** is [`Menu::layout`]'s word: inside [`FIT_FRACTION`] of the
1336    /// framebuffer on both axes. `style` is the largest the menu is drawn at,
1337    /// and is what it is drawn at when that fits. Otherwise the item font
1338    /// steps down by [`FIT_FONT_STEP`] to [`MenuStyle::MIN_FONT_SIZE`] — or
1339    /// stays at `style`'s own, if that is smaller — and every other length
1340    /// shrinks with it by the same factor, the art to the whole-number scale
1341    /// the factor leaves and never below one. The step is found by bisection
1342    /// over the steps, which is the largest that fits so long as a smaller
1343    /// step never lays out a bigger panel — every length shrinks with the
1344    /// font, so only a rounded pixel could. If even the smallest step is
1345    /// too tall, the item list at that step is capped at the height the rest
1346    /// of the panel leaves, and scrolls: see [`MenuLayout::viewport`].
1347    ///
1348    /// Every length but the font sizes is rounded to a whole pixel, and each
1349    /// row's line pitch is the font's `line-height: normal` rounded up to one,
1350    /// so every row is a whole number of pixels tall — which is what lets a
1351    /// scrolled list draw only the rows in view where this layout put them. A
1352    /// `style` that fits is therefore drawn at exactly its own lengths only
1353    /// when they are whole, as [`MenuStyle::pixel_art`]'s are.
1354    ///
1355    /// A pure function of the menu — its contents, its selection and its
1356    /// scroll — and its arguments: the same inputs lay out the same menu.
1357    ///
1358    /// # Errors
1359    ///
1360    /// [`MenuFitError::TooWide`] when the panel is wider than the room even at
1361    /// the smallest step, which scrolling up and down cannot help, and
1362    /// [`MenuFitError::TooShort`] when the frame, the title and the captions
1363    /// leave less height than the list's tallest row — or no list at all.
1364    pub fn layout_with_font_fitted(
1365        &self,
1366        extent: (u32, u32),
1367        style: &MenuStyle,
1368        font: &Font,
1369    ) -> Result<MenuLayout, MenuFitError> {
1370        let screen = extent_size(extent);
1371        let room = screen * FIT_FRACTION;
1372        let sizes = fit_sizes(style.item_size);
1373        let measure = |item_size: f32| {
1374            let style = style.shrunk(item_size);
1375            let setup = Setup {
1376                font: Some(font.clone()),
1377                line: Some(row_line(font, &style)),
1378                list: None,
1379            };
1380            let measured = self.measure(&style, &setup);
1381            Candidate {
1382                style,
1383                setup,
1384                measured,
1385            }
1386        };
1387        let fits = |candidate: &Candidate| {
1388            let panel = candidate.measured.panel;
1389            panel.x <= room.x && panel.y <= room.y
1390        };
1391
1392        let mut fitting = measure(sizes[0]);
1393        if !fits(&fitting) {
1394            let last = sizes.len() - 1;
1395            let smallest = if last == 0 {
1396                fitting
1397            } else {
1398                measure(sizes[last])
1399            };
1400            if !fits(&smallest) {
1401                return self.scrolled(screen, room, smallest);
1402            }
1403            // `sizes[lo]` is too big and `sizes[hi]`, which `fitting` holds,
1404            // fits.
1405            fitting = smallest;
1406            let (mut lo, mut hi) = (0, last);
1407            while hi - lo > 1 {
1408                let mid = (lo + hi) / 2;
1409                let candidate = measure(sizes[mid]);
1410                if fits(&candidate) {
1411                    hi = mid;
1412                    fitting = candidate;
1413                } else {
1414                    lo = mid;
1415                }
1416            }
1417        }
1418        Ok(self.placed(screen, &fitting.style, &fitting.setup))
1419    }
1420
1421    /// The fit's second stage: `candidate`, too tall for `room` at the
1422    /// smallest size the fit may use, with its item list capped at the height
1423    /// the rest of the panel leaves, and scrolled.
1424    fn scrolled(
1425        &self,
1426        screen: Vec2,
1427        room: Vec2,
1428        candidate: Candidate,
1429    ) -> Result<MenuLayout, MenuFitError> {
1430        let Candidate {
1431            style,
1432            setup,
1433            measured,
1434        } = candidate;
1435        let font_size = style.item_size;
1436        if measured.panel.x > room.x {
1437            return Err(MenuFitError::TooWide {
1438                font_size,
1439                width: measured.panel.x,
1440                room: room.x,
1441            });
1442        }
1443        let chrome = measured.panel.y - measured.list.y;
1444        let mut height = (room.y - chrome).floor();
1445        loop {
1446            if self.items.is_empty() || height < measured.tallest {
1447                return Err(MenuFitError::TooShort {
1448                    font_size,
1449                    height: chrome + measured.tallest,
1450                    room: room.y,
1451                });
1452            }
1453            // Every row, unscrolled: the geometry `scroll_list` scrolls.
1454            let list = ListView {
1455                size: Vec2::new(measured.list.x, height),
1456                viewport: (Vec2::ZERO, Vec2::ZERO),
1457                scroll: 0.0,
1458                reach: 0.0,
1459                shown: 0..self.items.len(),
1460                shown_top: 0.0,
1461            };
1462            let setup = Setup {
1463                list: Some(list),
1464                ..setup.clone()
1465            };
1466            let layout = self.placed(screen, &style, &setup);
1467            // The panel is its measured chrome plus the list's height, less
1468            // whatever Taffy's rounding moved; a pixel over is a pixel off
1469            // the list.
1470            let over = layout.panel_size().y - room.y;
1471            if over <= 0.0 {
1472                return Ok(self.scroll_list(layout));
1473            }
1474            height -= over.ceil();
1475        }
1476    }
1477
1478    /// Scrolls `layout` — placed with every row of its capped list built and
1479    /// unscrolled — to this menu's scroll, clamped to the list's reach and,
1480    /// while the list follows the keyboard, moved by as little as brings the
1481    /// selected row wholly into view. Every row's rectangles move with it, and
1482    /// the rows left overlapping the viewport are the ones drawn and hit.
1483    fn scroll_list(&self, mut layout: MenuLayout) -> MenuLayout {
1484        let list = layout
1485            .setup
1486            .list
1487            .as_mut()
1488            .expect("a scrolled layout has a list");
1489        let (top, bottom) = (list.viewport.0.y, list.viewport.1.y);
1490        let height = bottom - top;
1491        let end = layout.items.last().map_or(top, |row| row.max.y);
1492        list.reach = (end - top - height).max(0.0);
1493
1494        let mut scroll = self.scroll.round().clamp(0.0, list.reach);
1495        if self.follow_selection
1496            && let Some(row) = layout.items.get(self.selected)
1497        {
1498            let (row_top, row_bottom) = (row.min.y - top, row.max.y - top);
1499            if row_top < scroll {
1500                scroll = row_top;
1501            } else if row_bottom > scroll + height {
1502                scroll = row_bottom - height;
1503            }
1504        }
1505        let scroll = scroll.clamp(0.0, list.reach);
1506        list.scroll = scroll;
1507
1508        let up = Vec2::new(0.0, scroll);
1509        for row in &mut layout.items {
1510            row.min -= up;
1511            row.max -= up;
1512            row.label_pos -= up;
1513            row.hint_pos -= up;
1514            if let Some(track) = &mut row.track {
1515                track.0 -= up;
1516                track.1 -= up;
1517            }
1518        }
1519        let rows = &layout.items;
1520        let first = rows
1521            .iter()
1522            .position(|row| row.max.y > top)
1523            .unwrap_or(rows.len());
1524        let past = rows
1525            .iter()
1526            .rposition(|row| row.min.y < bottom)
1527            .map_or(first, |last| (last + 1).max(first));
1528        list.shown = first..past;
1529        list.shown_top = rows.get(first).map_or(0.0, |row| row.min.y + scroll - top);
1530        layout
1531    }
1532
1533    /// Lays this menu out centred in `screen` at `style`, built as `setup`
1534    /// says, and reads the layout back.
1535    fn placed(&self, screen: Vec2, style: &MenuStyle, setup: &Setup) -> MenuLayout {
1536        self.laid_out(
1537            Some(screen),
1538            style,
1539            None,
1540            setup,
1541            &FontAtlas::built_in(),
1542            |ui, built| Self::read_layout(ui, built, &self.items, screen, style, setup),
1543        )
1544    }
1545
1546    /// The panel, the item list and the list's tallest row at `style`, built
1547    /// as `setup` says, before any of them is placed.
1548    fn measure(&self, style: &MenuStyle, setup: &Setup) -> Measured {
1549        self.laid_out(
1550            None,
1551            style,
1552            None,
1553            setup,
1554            &FontAtlas::built_in(),
1555            |ui, built| {
1556                let size = |key| {
1557                    let (min, max) = ui.rect(key).expect("laid out this frame");
1558                    max - min
1559                };
1560                Measured {
1561                    panel: size(built.panel),
1562                    list: size(built.items),
1563                    tallest: built
1564                        .rows
1565                        .iter()
1566                        .map(|row| size(row.row).y)
1567                        .fold(0.0, f32::max),
1568                }
1569            },
1570        )
1571    }
1572
1573    /// Reads a [`MenuLayout`] back out of `ui`, which [`Menu::laid_out`] built
1574    /// for `items` at `style` in `screen`, as `setup` says.
1575    fn read_layout(
1576        ui: &Ui,
1577        built: &BuiltMenu,
1578        items: &[MenuItem],
1579        screen: Vec2,
1580        style: &MenuStyle,
1581        setup: &Setup,
1582    ) -> MenuLayout {
1583        let rect = |key| ui.rect(key).expect("laid out this frame");
1584        let panel = rect(built.panel);
1585        let corners = style.panel_corners();
1586        let content_min = panel.0 + corners.min_corner() + style.panel_padding;
1587        let content_max = panel.1 - Vec2::new(corners.right, corners.bottom) - style.panel_padding;
1588        // An empty title builds no span, and stands where a zero-width one
1589        // would: centred on the content's top edge.
1590        let title_pos = built.title.map_or(
1591            Vec2::new((content_min.x + content_max.x) * 0.5, content_min.y),
1592            |key| rect(key).0,
1593        );
1594        let items = items
1595            .iter()
1596            .zip(&built.rows)
1597            .map(|(item, row)| {
1598                let (min, max) = rect(row.row);
1599                let label_pos = rect(row.label).0;
1600                let inner = style.button_corners();
1601                let hint_pos = row.hint.map_or(
1602                    Vec2::new(max.x - inner.right - style.button_padding.x, label_pos.y),
1603                    |key| rect(key).0,
1604                );
1605                MenuItemLayout {
1606                    id: item.id,
1607                    min,
1608                    max,
1609                    label_pos,
1610                    hint_pos,
1611                    track: row.groove.map(rect),
1612                }
1613            })
1614            .collect();
1615
1616        let mut setup = setup.clone();
1617        if let Some(list) = &mut setup.list {
1618            list.viewport = rect(built.items);
1619        }
1620        MenuLayout {
1621            style: *style,
1622            setup,
1623            screen,
1624            panel,
1625            title_pos,
1626            items,
1627        }
1628    }
1629
1630    /// The panel's size at `style`, before it is placed anywhere.
1631    ///
1632    /// Public because the *fit* half of [`Menu::layout`] is a question a caller
1633    /// may reasonably ask on its own ("would this menu fit at scale 3?"), and
1634    /// because a test that could not measure the panel without placing it could
1635    /// not tell a menu that grew from one that moved.
1636    #[must_use]
1637    pub fn panel_size(&self, atlas: &FontAtlas, style: &MenuStyle) -> Vec2 {
1638        self.laid_out(None, style, None, &Setup::default(), atlas, |ui, built| {
1639            let (min, max) = ui.rect(built.panel).expect("laid out this frame");
1640            max - min
1641        })
1642    }
1643
1644    /// Builds this menu with [`Menu::build`] and lays it out, in the calling
1645    /// thread's one menu tree, then hands the tree to `read`. Its text is in
1646    /// `setup`'s font, registered in that tree, or in the bitmap font for
1647    /// none.
1648    ///
1649    /// **One tree per thread, rebuilt by every call** — two, one to measure
1650    /// in and one to place in — rather than a fresh
1651    /// [`Ui`] each time: a menu is laid out several times a frame — for its
1652    /// fit, its hit test and its drawing — with the same selectors and the same
1653    /// inline lengths, so a kept tree resolves each node's style from its own
1654    /// last resolve and lays out from Taffy's cache instead of from nothing.
1655    /// It holds no state a call can see: the pointer it begins each frame with
1656    /// is off every rectangle, so no rule's `:hover` applies, every build sets
1657    /// the item list's scroll, and whatever the last call built is replaced
1658    /// and pruned. `read` must not lay out a menu itself, which would borrow
1659    /// the tree twice.
1660    fn laid_out<R>(
1661        &self,
1662        screen: Option<Vec2>,
1663        style: &MenuStyle,
1664        skin: Option<&MenuSkin>,
1665        setup: &Setup,
1666        atlas: &FontAtlas,
1667        read: impl FnOnce(&Ui, &BuiltMenu) -> R,
1668    ) -> R {
1669        let tree = if screen.is_some() {
1670            &PLACED_TREE
1671        } else {
1672            &MEASURED_TREE
1673        };
1674        tree.with(|tree| {
1675            let mut tree = tree.borrow_mut();
1676            tree.use_sheet(self.stylesheet.as_ref());
1677            let ui = &mut tree.ui;
1678            ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
1679            if let Some(font) = &setup.font {
1680                ui.register_font(MENU_FONT, font)
1681                    .expect("the menu's family name is not reserved");
1682            }
1683            let built = self.build(ui, screen, style, skin, setup);
1684            let available = screen.map_or(AvailableSpace::MAX_CONTENT, AvailableSpace::definite);
1685            ui.layout(Vec2::ZERO, available, atlas);
1686            read(ui, &built)
1687        })
1688    }
1689
1690    /// Builds this menu into `ui` at `style`: the tree [`Menu::layout_with`]
1691    /// measures and [`Menu::render`] draws, one for both.
1692    ///
1693    /// `screen` is the framebuffer the panel is centred in, or `None` for a
1694    /// root that is only as big as the panel. `skin` is `Some` only when the
1695    /// tree is to be drawn: it binds the frames `default.css` names and adds
1696    /// the scrim, which is positioned out of the flow and moves nothing.
1697    /// A `setup` with a font names [`MENU_FONT`] on the root, which every span
1698    /// inherits; otherwise the text is `default.css`'s bitmap font. Its line
1699    /// pitch, if any, is set on the item list for every row to inherit, and
1700    /// its list, if any, caps the item list at its size, clips it and builds
1701    /// only the rows it shows, scrolled to where the layout put them.
1702    ///
1703    /// **What comes from where.** Every length is `style`'s, set inline, because
1704    /// it is the pixel-art scale times a base metric and a stylesheet has no
1705    /// arithmetic to scale with. The frames, their slices, which frame each
1706    /// state draws and every colour are `default.css`'s menu rules. Which state
1707    /// a row is in is [`Menu::state`]'s: the tree is this menu's view, and the
1708    /// selection, the press and the pointer's hover stay in the model.
1709    fn build(
1710        &self,
1711        ui: &mut Ui,
1712        screen: Option<Vec2>,
1713        style: &MenuStyle,
1714        skin: Option<&MenuSkin>,
1715        setup: &Setup,
1716    ) -> BuiltMenu {
1717        use Declaration as D;
1718        if let Some(skin) = skin {
1719            ui.set_image(PANEL_IMAGE, skin.panel.image);
1720            ui.set_image(IDLE_IMAGE, skin.buttons.idle.image);
1721            ui.set_image(HOVERED_IMAGE, skin.buttons.hovered.image);
1722            ui.set_image(PRESSED_IMAGE, skin.buttons.pressed.image);
1723        }
1724        let px = LengthAuto::Px;
1725        let mut root = screen.map_or_else(Vec::new, |screen| {
1726            vec![D::Width(px(screen.x)), D::Height(px(screen.y))]
1727        });
1728        if setup.font.is_some() {
1729            root.push(D::FamilyName(Some(FamilyName::new(MENU_FONT))));
1730        }
1731        let panel_corners = style.panel_corners();
1732        let panel = [
1733            D::BorderWidth(Sides::Top, panel_corners.top),
1734            D::BorderWidth(Sides::Right, panel_corners.right),
1735            D::BorderWidth(Sides::Bottom, panel_corners.bottom),
1736            D::BorderWidth(Sides::Left, panel_corners.left),
1737            D::Padding(Sides::Top, Length::Px(style.panel_padding.y)),
1738            D::Padding(Sides::Bottom, Length::Px(style.panel_padding.y)),
1739            D::Padding(Sides::Left, Length::Px(style.panel_padding.x)),
1740            D::Padding(Sides::Right, Length::Px(style.panel_padding.x)),
1741            D::RowGap(Length::Px(style.title_gap)),
1742        ];
1743        let button_corners = style.button_corners();
1744        let row = [
1745            D::BorderWidth(Sides::Top, button_corners.top),
1746            D::BorderWidth(Sides::Right, button_corners.right),
1747            D::BorderWidth(Sides::Bottom, button_corners.bottom),
1748            D::BorderWidth(Sides::Left, button_corners.left),
1749            D::Padding(Sides::Top, Length::Px(style.button_padding.y)),
1750            D::Padding(Sides::Bottom, Length::Px(style.button_padding.y)),
1751            D::Padding(Sides::Left, Length::Px(style.button_padding.x)),
1752            D::Padding(Sides::Right, Length::Px(style.button_padding.x)),
1753        ];
1754        let rows_style = RowStyle {
1755            row,
1756            label: [D::FontSize(style.item_size)],
1757            hint: [
1758                D::FontSize(style.item_size),
1759                D::Margin(Sides::Left, px(style.hint_gap)),
1760            ],
1761            groove: [
1762                D::Margin(Sides::Left, px(style.hint_gap)),
1763                D::MinWidth(px(style.track_width)),
1764                D::Height(px(style.track_height)),
1765            ],
1766            thumb: [
1767                D::Width(px(style.handle_size.x)),
1768                D::Height(px(style.handle_size.y)),
1769            ],
1770        };
1771        let caption = [D::FontSize(style.item_size)];
1772        let mut list = vec![D::RowGap(Length::Px(style.item_gap))];
1773        if let Some(line) = setup.line {
1774            list.push(D::LineHeight(LineHeight::Px(line)));
1775        }
1776        if let Some(view) = &setup.list {
1777            list.extend([
1778                D::Overflow(Overflow::Hidden),
1779                D::FlexShrink(0.0),
1780                D::Width(px(view.size.x)),
1781                D::Height(px(view.size.y)),
1782            ]);
1783        }
1784        let (shown, offset) = setup.list.as_ref().map_or(
1785            (0..self.items.len(), 0.0),
1786            // The first row built is laid out at the list's top, so the
1787            // offset is the scroll less how far down that row starts.
1788            |view| (view.shown.clone(), view.scroll - view.shown_top),
1789        );
1790
1791        let mut title = None;
1792        let mut rows = Vec::with_capacity(shown.len());
1793        let mut panel_key = None;
1794        let mut items_key = None;
1795        ui.block("menu-screen", &root, |ui| {
1796            if let Some(skin) = skin {
1797                ui.span(".menu-scrim", skin.scrim, &[]);
1798            }
1799            panel_key = Some(
1800                ui.block("menu", &panel, |ui| {
1801                    if !self.title.is_empty() {
1802                        title = Some(
1803                            ui.span(
1804                                ".menu-title",
1805                                self.title.as_str(),
1806                                &[D::FontSize(style.title_size)],
1807                            )
1808                            .key,
1809                        );
1810                    }
1811                    if !self.subtitle.is_empty() {
1812                        ui.block(".menu-captions", &[], |ui| {
1813                            for line in &self.subtitle {
1814                                let selector = match line.tone {
1815                                    CaptionTone::Hint => ".menu-caption",
1816                                    CaptionTone::Warning => ".menu-caption.menu-caption-warning",
1817                                };
1818                                ui.span(selector, line.text.as_str(), &caption);
1819                            }
1820                        });
1821                    }
1822                    items_key = Some(
1823                        ui.block(".menu-items", &list, |ui| {
1824                            // Set every build, not only a scrolled one's: the
1825                            // tree is shared, and an offset a scrolled menu
1826                            // left on this node would move the next menu's
1827                            // rows.
1828                            ui.set_scroll_offset(Vec2::new(0.0, offset));
1829                            for (index, item) in self.items.iter().enumerate() {
1830                                if shown.contains(&index) {
1831                                    rows.push(self.build_row(ui, index, item, &rows_style));
1832                                }
1833                            }
1834                        })
1835                        .key,
1836                    );
1837                })
1838                .key,
1839            );
1840        });
1841        BuiltMenu {
1842            panel: panel_key.expect("the screen builds its panel"),
1843            title,
1844            items: items_key.expect("the panel builds its item list"),
1845            rows,
1846        }
1847    }
1848
1849    /// Builds item `index`: a row in the pseudo-class [`Menu::state`] gives it,
1850    /// holding its label, then what the row carries — a groove and its handle
1851    /// for a slider, a spacer for anything with a caption to push right — and
1852    /// then the caption itself.
1853    fn build_row(&self, ui: &mut Ui, index: usize, item: &MenuItem, style: &RowStyle) -> BuiltRow {
1854        let state = match self.state(index) {
1855            ButtonState::Idle => PseudoClasses::NONE,
1856            ButtonState::Hovered => PseudoClasses::HOVER,
1857            ButtonState::Pressed => PseudoClasses::ACTIVE,
1858        };
1859        let mut label = None;
1860        let mut groove = None;
1861        let mut hint = None;
1862        let row = ui
1863            .block_keyed_in_state(index, "menu-item", &style.row, state, |ui| {
1864                label = Some(
1865                    ui.span(".menu-label", item.label.as_str(), &style.label)
1866                        .key,
1867                );
1868                let caption = item.caption();
1869                match item.kind {
1870                    MenuItemKind::Slider(slider) => {
1871                        groove = Some(build_groove(ui, slider, style));
1872                    }
1873                    MenuItemKind::Action | MenuItemKind::Cycler(_) if !caption.is_empty() => {
1874                        ui.block(".menu-spacer", &[], |_| {});
1875                    }
1876                    MenuItemKind::Action | MenuItemKind::Cycler(_) => {}
1877                }
1878                if !caption.is_empty() {
1879                    hint = Some(ui.span(".menu-hint", caption.as_ref(), &style.hint).key);
1880                }
1881            })
1882            .key;
1883        BuiltRow {
1884            row,
1885            label: label.expect("every row builds its label"),
1886            hint,
1887            groove,
1888        }
1889    }
1890
1891    /// Emits the menu's **pictures** alone: the scrim over the framebuffer, the
1892    /// window frame, and each button's frame for its state.
1893    ///
1894    /// The half of [`render`](Self::render) that is art: the same tree, with
1895    /// every command that is not a picture left out — the text, and a
1896    /// slider's groove and handle. The frames are nine-sliced at
1897    /// [`MenuStyle::scale`] pixels per texel, which is what keeps the art's
1898    /// corners the layout's corners.
1899    pub fn render_art(&self, dl: &mut DrawList, layout: &MenuLayout, skin: &MenuSkin) {
1900        let mut whole = DrawList::new();
1901        self.render(&mut whole, layout, skin);
1902        // Each under the clip it was drawn under, which a scrolled list's
1903        // frames need: a row half out of view is cut at the list's edge.
1904        for (command, clip) in whole.commands().iter().zip(whole.clips()) {
1905            if matches!(command, DrawCommand::Image { .. }) {
1906                dl.push_clip(clip.min, clip.max);
1907                dl.push_command(command.clone());
1908                dl.pop_clip()
1909                    .expect("the clip pushed above is still on the stack");
1910            }
1911        }
1912    }
1913
1914    /// Emits the whole menu into `dl`: the tree [`Menu::layout_with`] measured
1915    /// at `layout`'s style and framebuffer, drawn with `skin`. Its text is
1916    /// measured in the font `layout` was — the built-in [`FontAtlas`], or the
1917    /// font [`Menu::layout_with_font`] was given — so it lands where `layout`
1918    /// says.
1919    ///
1920    /// **The order is the tree's paint order**: the scrim first, then the
1921    /// window frame and the title, then each row — its frame, then what sits
1922    /// on it. The draw list is drawn in the order commands went in, so the
1923    /// scrim dims what was pushed before this call, the frame covers the
1924    /// scrim, and every label is drawn over its own row's frame; rows do not
1925    /// overlap, so no frame covers another row's text.
1926    pub fn render(&self, dl: &mut DrawList, layout: &MenuLayout, skin: &MenuSkin) {
1927        self.laid_out(
1928            Some(layout.screen),
1929            &layout.style,
1930            Some(skin),
1931            &layout.setup,
1932            &FontAtlas::built_in(),
1933            |ui, _| ui.emit(dl),
1934        );
1935    }
1936}
1937
1938/// A thread's menu tree, and the game sheet it holds.
1939#[derive(Default)]
1940struct MenuTree {
1941    ui: Ui,
1942    /// The slot a game's sheet is in, once a menu has brought one: an empty
1943    /// sheet while the menu drawn now has none.
1944    slot: Option<SheetId>,
1945    /// What the slot holds now.
1946    sheet: Option<Arc<str>>,
1947}
1948
1949impl MenuTree {
1950    /// Holds `sheet` in the game slot, if it is not already what it holds: a
1951    /// change re-resolves the whole tree, so menus sharing a sheet, or none,
1952    /// keep resolving from their last frame.
1953    fn use_sheet(&mut self, sheet: Option<&Arc<str>>) {
1954        if self.sheet.as_ref() == sheet {
1955            return;
1956        }
1957        let css = sheet.map_or("", |sheet| sheet);
1958        match self.slot {
1959            Some(slot) => self
1960                .ui
1961                .replace_stylesheet(slot, css)
1962                .expect("Menu::set_stylesheet refused a sheet with errors"),
1963            None => self.slot = Some(self.ui.add_stylesheet(GAME_SHEET, css)),
1964        }
1965        self.sheet = sheet.cloned();
1966    }
1967}
1968
1969/// The name a game's sheet goes by in diagnostics.
1970const GAME_SHEET: &str = "game";
1971
1972thread_local! {
1973    /// The tree [`Menu::laid_out`] places and draws menus in; see there.
1974    static PLACED_TREE: std::cell::RefCell<MenuTree> = std::cell::RefCell::default();
1975    /// The tree [`Menu::panel_size`] measures in: apart from
1976    /// [`PLACED_TREE`], because [`Menu::layout`] measures at scale 1 and
1977    /// places at the scale it chose, and one tree alternating between the two
1978    /// would resolve and lay out every node from nothing on every call.
1979    static MEASURED_TREE: std::cell::RefCell<MenuTree> = std::cell::RefCell::default();
1980}
1981
1982/// Where [`Menu::laid_out`]'s pointer is: above and left of every rectangle a
1983/// menu lays out, which all start at the origin.
1984const OFF_SCREEN: Vec2 = Vec2::splat(-1.0);
1985
1986/// The family a font [`Menu::layout_with_font`] is given is registered under
1987/// in the menu trees, which are this module's own, so no app's name collides.
1988const MENU_FONT: &str = "crcbl-menu";
1989
1990/// The names `default.css`'s menu rules give the [`MenuSkin`]'s frames, which
1991/// [`Menu::render`] binds with [`Ui::set_image`].
1992const PANEL_IMAGE: &str = "menu-panel";
1993/// See [`PANEL_IMAGE`].
1994const IDLE_IMAGE: &str = "menu-button-idle";
1995/// See [`PANEL_IMAGE`].
1996const HOVERED_IMAGE: &str = "menu-button-hovered";
1997/// See [`PANEL_IMAGE`].
1998const PRESSED_IMAGE: &str = "menu-button-pressed";
1999
2000/// The nodes [`Menu::build`] made, for reading a layout back.
2001struct BuiltMenu {
2002    panel: NodeKey,
2003    title: Option<NodeKey>,
2004    /// The block the rows are in.
2005    items: NodeKey,
2006    /// The rows built, which a scrolled list's render limits to those in view.
2007    rows: Vec<BuiltRow>,
2008}
2009
2010/// A slider row's groove: the tree's own slider drawing the well and the fill,
2011/// and a handle over it in a rail whose two spaces share out the free width by
2012/// the value — so the handle travels from flush left to flush right and hangs
2013/// over neither end. Returns the groove's key, which is the rectangle a
2014/// pointer's drag is measured against.
2015fn build_groove(ui: &mut Ui, slider: Slider, style: &RowStyle) -> NodeKey {
2016    use Declaration as D;
2017    let share = slider.position();
2018    ui.block(".menu-groove", &style.groove, |ui| {
2019        // The tree's slider reads its value and draws it; the menu's model is
2020        // what moves it, so the copy it is handed goes nowhere.
2021        let mut position = share;
2022        ui.slider(".menu-slider", &mut position, 0.0..=1.0, Slider::KEY_STEP);
2023        ui.block(".menu-thumb-rail", &[], |ui| {
2024            ui.block(".menu-thumb-space", &[D::FlexGrow(share)], |_| {});
2025            ui.block(".menu-thumb", &style.thumb, |_| {});
2026            ui.block(".menu-thumb-space", &[D::FlexGrow(1.0 - share)], |_| {});
2027        });
2028    })
2029    .key
2030}
2031
2032/// The inline declarations every row of one menu is built with, at its style.
2033struct RowStyle {
2034    row: [Declaration; 8],
2035    label: [Declaration; 1],
2036    hint: [Declaration; 2],
2037    groove: [Declaration; 3],
2038    thumb: [Declaration; 2],
2039}
2040
2041/// One row's nodes.
2042struct BuiltRow {
2043    row: NodeKey,
2044    label: NodeKey,
2045    hint: Option<NodeKey>,
2046    groove: Option<NodeKey>,
2047}
2048
2049/// The share of the framebuffer a menu is allowed to fill before
2050/// [`Menu::layout`] drops to a smaller scale.
2051///
2052/// Nine tenths rather than all of it: a modal that reached the edge of the
2053/// window would have no frame visible on the short axis, and the scrim behind it
2054/// would have nothing to dim.
2055pub const FIT_FRACTION: f32 = 0.9;
2056
2057/// How far apart the item font sizes [`Menu::layout_with_font_fitted`] tries
2058/// are, in pixels.
2059///
2060/// A quarter pixel rather than any size at all: a window dragged through
2061/// every size in between then draws at a bounded set of sizes, so the glyph
2062/// atlas is not handed a fresh rasterisation of every glyph for each pixel of
2063/// the drag, and the fit is a bisection over a known list.
2064pub const FIT_FONT_STEP: f32 = 0.25;
2065
2066/// The item font sizes [`Menu::layout_with_font_fitted`] tries, largest first:
2067/// `largest` itself, then every [`FIT_FONT_STEP`] below it down to
2068/// [`MenuStyle::MIN_FONT_SIZE`]. Only `largest` when it is no bigger than
2069/// that.
2070fn fit_sizes(largest: f32) -> Vec<f32> {
2071    let mut sizes = vec![largest];
2072    let spare = largest - MenuStyle::MIN_FONT_SIZE;
2073    if spare > 0.0 {
2074        let steps = (spare / FIT_FONT_STEP).floor() as u32;
2075        sizes.extend(
2076            (0..=steps)
2077                .rev()
2078                .map(|step| MenuStyle::MIN_FONT_SIZE + step as f32 * FIT_FONT_STEP)
2079                .filter(|&size| size < largest),
2080        );
2081    }
2082    sizes
2083}
2084
2085/// A fitted row's line pitch in `font` at `style`: its `line-height: normal`
2086/// rounded up to a whole pixel — see [`MenuStyle::shrunk`].
2087fn row_line(font: &Font, style: &MenuStyle) -> f32 {
2088    font.metrics().normal_line_height(style.item_size).ceil()
2089}
2090
2091/// `extent` as a size in pixels.
2092fn extent_size(extent: (u32, u32)) -> Vec2 {
2093    Vec2::new(extent.0 as f32, extent.1 as f32)
2094}
2095
2096/// Whether `point` is inside `rect`, edges included.
2097fn contains(rect: (Vec2, Vec2), point: Vec2) -> bool {
2098    point.x >= rect.0.x && point.x <= rect.1.x && point.y >= rect.0.y && point.y <= rect.1.y
2099}
2100
2101/// How a menu's tree is built beyond its style: the font its text is in, and
2102/// what [`Menu::layout_with_font_fitted`] decided. The default is the bitmap
2103/// font and every row in the flow — what [`Menu::layout`] builds.
2104#[derive(Debug, Clone, PartialEq, Default)]
2105struct Setup {
2106    /// The font the text is measured and drawn in; `None` for the bitmap font.
2107    font: Option<Font>,
2108    /// Every row's line pitch, in whole pixels; `None` for the font's own.
2109    line: Option<f32>,
2110    /// The item list capped and scrolled; `None` for a list as tall as its
2111    /// rows.
2112    list: Option<ListView>,
2113}
2114
2115/// A scrolled item list: see [`Menu::layout_with_font_fitted`].
2116#[derive(Debug, Clone, PartialEq)]
2117struct ListView {
2118    /// The list's width and its capped height, in whole pixels.
2119    size: Vec2,
2120    /// Where the list shows its rows: `(min, max)` in screen pixels.
2121    viewport: (Vec2, Vec2),
2122    /// How far the rows are scrolled, in whole pixels.
2123    scroll: f32,
2124    /// The furthest they can be.
2125    reach: f32,
2126    /// The rows at least partly in view: the ones built, drawn and hit.
2127    shown: Range<usize>,
2128    /// How far below the list's top the first shown row starts, unscrolled.
2129    shown_top: f32,
2130}
2131
2132/// What [`Menu::measure`] reads off a menu.
2133struct Measured {
2134    panel: Vec2,
2135    list: Vec2,
2136    tallest: f32,
2137}
2138
2139/// One size [`Menu::layout_with_font_fitted`] tries: the style and setup it
2140/// builds with, and what that measured.
2141struct Candidate {
2142    style: MenuStyle,
2143    setup: Setup,
2144    measured: Measured,
2145}
2146
2147/// Why [`Menu::layout_with_font_fitted`] could not fit a menu, even at the
2148/// smallest size it may shrink to with its item list scrolled. Every length is
2149/// in pixels, and `room` is [`FIT_FRACTION`] of the framebuffer.
2150#[derive(Debug, Clone, Copy, PartialEq)]
2151pub enum MenuFitError {
2152    /// The panel is wider than the room, and a list that scrolls up and down
2153    /// cannot make it narrower.
2154    TooWide {
2155        /// The item font size it was measured at.
2156        font_size: f32,
2157        /// The panel's width there.
2158        width: f32,
2159        /// The width it had to fit.
2160        room: f32,
2161    },
2162    /// The frame, the title and the captions leave less height than the
2163    /// list's tallest row — or the menu has no rows to scroll.
2164    TooShort {
2165        /// The item font size it was measured at.
2166        font_size: f32,
2167        /// The panel's height showing one row, its tallest.
2168        height: f32,
2169        /// The height it had to fit.
2170        room: f32,
2171    },
2172}
2173
2174impl std::fmt::Display for MenuFitError {
2175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2176        match *self {
2177            Self::TooWide {
2178                font_size,
2179                width,
2180                room,
2181            } => write!(
2182                f,
2183                "the menu is {width}px wide at a {font_size}px font, the smallest it may \
2184                 shrink to, and the window has room for {room}px"
2185            ),
2186            Self::TooShort {
2187                font_size,
2188                height,
2189                room,
2190            } => write!(
2191                f,
2192                "the menu needs {height}px to show one row at a {font_size}px font, the \
2193                 smallest it may shrink to, and the window has room for {room}px"
2194            ),
2195        }
2196    }
2197}
2198
2199impl std::error::Error for MenuFitError {}
2200
2201#[cfg(test)]
2202fn text_width(atlas: &FontAtlas, text: &str, size: f32) -> f32 {
2203    if text.is_empty() {
2204        return 0.0;
2205    }
2206    atlas.text_width(text, size / NATURAL_FONT_SIZE)
2207}
2208
2209#[cfg(test)]
2210fn line_height(size: f32) -> f32 {
2211    LINE_HEIGHT * (size / NATURAL_FONT_SIZE)
2212}
2213
2214/// Where the **centre** of a handle `handle_width` wide may travel inside
2215/// `track`, as `(leftmost, rightmost)`.
2216///
2217/// Half a handle in from each end, so position `0.0` and position `1.0` both
2218/// draw a handle wholly inside the groove — a handle centred on the end would
2219/// hang half of itself out over the button's face and read as a different
2220/// value at each extreme. A groove narrower than one handle collapses the
2221/// travel to its middle rather than inverting it.
2222fn handle_travel(track: (Vec2, Vec2), handle_width: f32) -> (f32, f32) {
2223    let half = (handle_width * 0.5)
2224        .min((track.1.x - track.0.x) * 0.5)
2225        .max(0.0);
2226    (track.0.x + half, track.1.x - half)
2227}
2228
2229/// The position a pointer at `x` names on `track`, before clamping.
2230fn position_along(track: (Vec2, Vec2), handle_width: f32, x: f32) -> f32 {
2231    let (start, end) = handle_travel(track, handle_width);
2232    if end <= start {
2233        return 0.0;
2234    }
2235    (x - start) / (end - start)
2236}
2237
2238// ---------------------------------------------------------------------------
2239// The layout
2240// ---------------------------------------------------------------------------
2241
2242/// Where one item landed.
2243#[derive(Debug, Clone, Copy, PartialEq)]
2244pub struct MenuItemLayout {
2245    /// The item this rectangle belongs to.
2246    pub id: WidgetId,
2247    /// The button's upper-left corner, in screen pixels.
2248    pub min: Vec2,
2249    /// The button's lower-right corner, in screen pixels.
2250    pub max: Vec2,
2251    /// Where the label's em box starts.
2252    pub label_pos: Vec2,
2253    /// Where the key hint's em box starts — right-aligned inside the button.
2254    pub hint_pos: Vec2,
2255    /// A [`MenuItemKind::Slider`] row's groove: `(min, max)` in screen pixels,
2256    /// between the label and the value. `None` for a button row.
2257    pub track: Option<(Vec2, Vec2)>,
2258}
2259
2260impl MenuItemLayout {
2261    /// The button's size in pixels.
2262    #[must_use]
2263    pub fn size(&self) -> Vec2 {
2264        self.max - self.min
2265    }
2266}
2267
2268/// One frame's placement of a menu: the panel, the title and every button, in
2269/// screen pixels.
2270///
2271/// Produced by [`Menu::layout`] and consumed by [`Menu::render`], for the art
2272/// and the text alike. Carrying the [`MenuStyle`] it was built with is what
2273/// stops the two being measured with different metrics — the failure that puts
2274/// a label a scale out of step with the frame around it.
2275#[derive(Debug, Clone, PartialEq)]
2276pub struct MenuLayout {
2277    style: MenuStyle,
2278    /// How the tree was built: the font the text was measured in and, for a
2279    /// fitted layout, the rows' line pitch and a scrolled list.
2280    setup: Setup,
2281    screen: Vec2,
2282    panel: (Vec2, Vec2),
2283    title_pos: Vec2,
2284    items: Vec<MenuItemLayout>,
2285}
2286
2287impl MenuLayout {
2288    /// The style this layout was measured with.
2289    #[must_use]
2290    pub const fn style(&self) -> &MenuStyle {
2291        &self.style
2292    }
2293
2294    /// The framebuffer this was laid out in, in pixels.
2295    #[must_use]
2296    pub const fn screen(&self) -> Vec2 {
2297        self.screen
2298    }
2299
2300    /// The window frame's rectangle: `(min, max)` in screen pixels.
2301    #[must_use]
2302    pub const fn panel(&self) -> (Vec2, Vec2) {
2303        self.panel
2304    }
2305
2306    /// The panel's size in pixels.
2307    #[must_use]
2308    pub fn panel_size(&self) -> Vec2 {
2309        self.panel.1 - self.panel.0
2310    }
2311
2312    /// The middle of the panel, in screen pixels.
2313    #[must_use]
2314    pub fn panel_centre(&self) -> Vec2 {
2315        (self.panel.0 + self.panel.1) * 0.5
2316    }
2317
2318    /// Where the title's em box starts.
2319    #[must_use]
2320    pub const fn title_pos(&self) -> Vec2 {
2321        self.title_pos
2322    }
2323
2324    /// Every button, in the order they are drawn.
2325    ///
2326    /// In a scrolled list every row is here, where the scroll put it: a row
2327    /// scrolled out of view lies outside the [`viewport`](Self::viewport), and
2328    /// outside the panel too, and is neither drawn nor hit — see
2329    /// [`shows`](Self::shows).
2330    #[must_use]
2331    pub fn items(&self) -> &[MenuItemLayout] {
2332        &self.items
2333    }
2334
2335    /// Where a scrolled item list shows its rows: `(min, max)` in screen
2336    /// pixels, inside the panel. `None` when the list is not scrolled and
2337    /// every row is in view.
2338    ///
2339    /// A row is drawn cut at this rectangle's edges and hit only inside it.
2340    #[must_use]
2341    pub fn viewport(&self) -> Option<(Vec2, Vec2)> {
2342        self.setup.list.as_ref().map(|list| list.viewport)
2343    }
2344
2345    /// How far the item list is scrolled, in pixels: zero unless it scrolls.
2346    #[must_use]
2347    pub fn scroll(&self) -> f32 {
2348        self.setup.list.as_ref().map_or(0.0, |list| list.scroll)
2349    }
2350
2351    /// Whether row `index` is at least partly in view, and so drawn and hit.
2352    /// Every row is, unless the list scrolls; no row past the last is.
2353    #[must_use]
2354    pub fn shows(&self, index: usize) -> bool {
2355        index < self.items.len()
2356            && self
2357                .setup
2358                .list
2359                .as_ref()
2360                .is_none_or(|list| list.shown.contains(&index))
2361    }
2362
2363    /// The whole framebuffer, as the rectangle the scrim covers.
2364    #[must_use]
2365    pub fn scrim(&self) -> (Vec2, Vec2) {
2366        (Vec2::ZERO, self.screen)
2367    }
2368}
2369
2370// ---------------------------------------------------------------------------
2371// Menu set
2372// ---------------------------------------------------------------------------
2373
2374/// Every menu one game owns, which of them is on screen, and the pointer's
2375/// capture that outlives any single frame.
2376///
2377/// A [`Menu`] is one panel. A game has several — a start screen, a pause panel,
2378/// whatever it shows when a run ends — and needs exactly three things a single
2379/// menu cannot give it: a way to say which one this frame draws, a guarantee
2380/// that switching between two does not carry a half-finished click across, and
2381/// one [`UiState`] shared by all of them so a press captured on a button is the
2382/// same capture the release is tested against.
2383///
2384/// `K` names the panels. It is the game's own enum, not one this crate
2385/// dictates, because which states a game has is the one part of a menu system
2386/// that is genuinely per-game. **A `K` with no menu in the set draws nothing**,
2387/// which is how a "no menu this frame" state is spelled: give the set a `shown`
2388/// it holds no entry for — a `None` variant, or `false` for a game whose only
2389/// panel is a pause screen — and every method below becomes a no-op.
2390///
2391/// # What it does with the capture
2392///
2393/// [`UiState`] latches the widget a press started on so a release somewhere else
2394/// fires nothing. That latch has to survive between frames, which means it also
2395/// survives a menu being swapped out from under it, and a capture pointing at a
2396/// button that is no longer on screen is how a click on the pause menu ends up
2397/// firing whatever the start menu happens to draw in the same place. So both
2398/// [`show`](Self::show) and [`replace`](Self::replace) drop it.
2399///
2400/// # Example
2401///
2402/// ```
2403/// use crcbl_ui::menu::{Menu, MenuItem, MenuSet};
2404///
2405/// #[derive(Clone, Copy, PartialEq, Eq, Debug)]
2406/// enum Kind {
2407///     None,
2408///     Paused,
2409/// }
2410///
2411/// let mut menus = MenuSet::new(
2412///     Kind::None,
2413///     vec![(
2414///         Kind::Paused,
2415///         Menu::new("PAUSED", vec![MenuItem::new(1, "RESUME", "ESC")]),
2416///     )],
2417/// );
2418///
2419/// // `Kind::None` has no menu, so the frame draws nothing and the keys do
2420/// // nothing.
2421/// assert!(!menus.is_showing());
2422/// assert_eq!(menus.activate(), None);
2423///
2424/// menus.show(Kind::Paused);
2425/// assert_eq!(menus.activate(), Some(1));
2426/// ```
2427#[derive(Debug)]
2428pub struct MenuSet<K> {
2429    /// The panels, keyed by the state each belongs to. A `Vec` rather than a
2430    /// map because a game has a handful and they are walked, never hashed.
2431    menus: Vec<(K, Menu)>,
2432    /// Which of them this frame draws.
2433    shown: K,
2434    /// The pointer's capture, shared by every menu in the set — see the type's
2435    /// docs for why it cannot be per-menu.
2436    ui: UiState,
2437}
2438
2439impl<K: Copy + Eq> MenuSet<K> {
2440    /// A set of menus, with `shown` on screen.
2441    ///
2442    /// Pass the state that draws no menu as `shown` to open with none.
2443    ///
2444    /// # Panics
2445    ///
2446    /// If two entries name the same `K`. The second would be unreachable —
2447    /// every lookup here takes the first match — so a game that built one by
2448    /// mistake would have a panel it could never show and no way to notice.
2449    #[must_use]
2450    pub fn new(shown: K, menus: Vec<(K, Menu)>) -> Self {
2451        for (index, (kind, _)) in menus.iter().enumerate() {
2452            assert!(
2453                !menus[..index].iter().any(|(seen, _)| seen == kind),
2454                "two menus claim the same state",
2455            );
2456        }
2457        Self {
2458            menus,
2459            shown,
2460            ui: UiState::new(),
2461        }
2462    }
2463
2464    /// Which menu is being shown.
2465    #[must_use]
2466    pub const fn kind(&self) -> K {
2467        self.shown
2468    }
2469
2470    /// Whether this frame has a menu on it.
2471    ///
2472    /// False for a `shown` the set holds no menu for, which is what the games
2473    /// use to decide whether the menu keys are the menu's this frame or the
2474    /// simulation's.
2475    #[must_use]
2476    pub fn is_showing(&self) -> bool {
2477        self.current().is_some()
2478    }
2479
2480    /// Switches to the menu this frame shows.
2481    ///
2482    /// A change drops the outgoing menu's hover and held key and the pointer's
2483    /// capture with it: a menu re-shown with a stale press on it draws a button
2484    /// nobody is touching, and a capture left in [`UiState`] would credit the
2485    /// next click to a widget that is no longer on screen.
2486    ///
2487    /// Showing what is already shown does nothing, so this is safe to call
2488    /// every frame — which is how the games call it.
2489    pub fn show(&mut self, kind: K) {
2490        if kind == self.shown {
2491            return;
2492        }
2493        if let Some(menu) = self.current_mut() {
2494            menu.clear_input();
2495        }
2496        self.ui.clear();
2497        self.shown = kind;
2498    }
2499
2500    /// Swaps the menu a state draws, or adds it if the state had none.
2501    ///
2502    /// For a panel whose buttons are not known until the game is running — a
2503    /// level-up screen offering three upgrades drawn from a seed. The capture
2504    /// goes, for the same reason [`show`](Self::show) drops it: the button the
2505    /// press landed on no longer says what it said.
2506    ///
2507    /// The caller decides *when* the menu is stale. This rebuilds
2508    /// unconditionally, so calling it every frame would throw away the
2509    /// selection every frame.
2510    pub fn replace(&mut self, kind: K, menu: Menu) {
2511        match self.menus.iter_mut().find(|(seen, _)| *seen == kind) {
2512            Some(slot) => slot.1 = menu,
2513            None => self.menus.push((kind, menu)),
2514        }
2515        self.ui.clear();
2516    }
2517
2518    /// The menu being shown, or `None` on a frame with no menu on it.
2519    #[must_use]
2520    pub fn current(&self) -> Option<&Menu> {
2521        let shown = self.shown;
2522        self.menus
2523            .iter()
2524            .find_map(|(kind, menu)| (*kind == shown).then_some(menu))
2525    }
2526
2527    /// The menu being shown, mutably.
2528    pub fn current_mut(&mut self) -> Option<&mut Menu> {
2529        self.get_mut(self.shown)
2530    }
2531
2532    /// One menu of the set by name, mutably, whether or not it is on screen.
2533    ///
2534    /// What a game refreshing a live value on a panel needs and
2535    /// [`current_mut`](Self::current_mut) cannot give it: `crcbl`'s loop asks
2536    /// the game which menu to show *after* the game has had its say, so during
2537    /// that call `current_mut` is still last frame's panel. Naming the menu is
2538    /// exact where "the current one" is a frame out of step.
2539    ///
2540    /// Unlike [`replace`](Self::replace) this keeps the panel's selection and
2541    /// the pointer's capture, which is what makes it safe to call every frame.
2542    pub fn get_mut(&mut self, kind: K) -> Option<&mut Menu> {
2543        self.menus
2544            .iter_mut()
2545            .find_map(|(seen, menu)| (*seen == kind).then_some(menu))
2546    }
2547
2548    /// Moves the selection down, if there is a menu.
2549    pub fn select_next(&mut self) {
2550        if let Some(menu) = self.current_mut() {
2551            menu.select_next();
2552        }
2553    }
2554
2555    /// Moves the selection up, if there is a menu.
2556    pub fn select_previous(&mut self) {
2557        if let Some(menu) = self.current_mut() {
2558            menu.select_previous();
2559        }
2560    }
2561
2562    /// Holds the highlighted button down, or lets it up.
2563    pub fn press(&mut self, down: bool) {
2564        if let Some(menu) = self.current_mut() {
2565            menu.press(down);
2566        }
2567    }
2568
2569    /// Fires the highlighted button, reporting the [`WidgetId`] it carries.
2570    pub fn activate(&mut self) -> Option<WidgetId> {
2571        self.current_mut().and_then(Menu::activate)
2572    }
2573
2574    /// Moves the highlighted slider one step, if there is a menu.
2575    pub fn nudge_slider(&mut self, forward: bool) -> bool {
2576        self.current_mut()
2577            .is_some_and(|menu| menu.nudge_slider(forward))
2578    }
2579
2580    /// Whether the showing menu's highlighted row is a slider.
2581    ///
2582    /// `false` when nothing is showing, so a caller asking "is this key the
2583    /// menu's?" gets the answer for the panel the player can see.
2584    #[must_use]
2585    pub fn slider_highlighted(&self) -> bool {
2586        self.current().is_some_and(Menu::slider_highlighted)
2587    }
2588
2589    /// Steps the highlighted cycler one choice, stopping at the ends, if there
2590    /// is a menu.
2591    pub fn nudge_cycler(&mut self, forward: bool) -> bool {
2592        self.current_mut()
2593            .is_some_and(|menu| menu.nudge_cycler(forward))
2594    }
2595
2596    /// Whether the showing menu's highlighted row is a cycler. `false` when
2597    /// nothing is showing, as [`slider_highlighted`](Self::slider_highlighted)
2598    /// is.
2599    #[must_use]
2600    pub fn cycler_highlighted(&self) -> bool {
2601        self.current().is_some_and(Menu::cycler_highlighted)
2602    }
2603
2604    /// Whether a press is latched onto one of this set's buttons.
2605    ///
2606    /// The question a caller driving the menu from **something other than the
2607    /// pointer** has to ask: a contact is offered to [`point`](Self::point) once
2608    /// and then has to be remembered or forgotten, and this is what says which —
2609    /// a press that latched a button is one whose later events matter, and a
2610    /// press that landed on the panel's background is not the menu's at all.
2611    #[must_use]
2612    pub fn press_captured(&self) -> bool {
2613        self.ui.active().is_some()
2614    }
2615
2616    /// Drops a press in progress **without firing it**.
2617    ///
2618    /// The [`Cancelled`](crcbl_core::input::TouchPhase::Cancelled) path, and the
2619    /// distinction is the same one [`crate::touch::TouchButton`] draws: a lift
2620    /// commits, a gesture the system took away does not. Without it a cancelled
2621    /// contact would leave [`UiState`]'s capture latched onto a button nobody is
2622    /// touching, and the next press could latch nothing at all.
2623    ///
2624    /// A press the pointer made is dropped by this too — there is one capture,
2625    /// and a caller that cancels one cancels the press that is live.
2626    pub fn cancel_press(&mut self) {
2627        self.ui.clear();
2628        if let Some(menu) = self.current_mut() {
2629            menu.clear_input();
2630        }
2631    }
2632
2633    /// Runs one frame of pointer input against the menu on screen.
2634    ///
2635    /// The layout is recomputed here rather than kept, because it depends on
2636    /// the framebuffer's size and on the menu's own contents and both can
2637    /// change between frames — and a hit test against last frame's rectangles
2638    /// is how a resized window gets buttons that are not where they are drawn.
2639    pub fn point(
2640        &mut self,
2641        extent: (u32, u32),
2642        atlas: &FontAtlas,
2643        pointer: PointerInput,
2644    ) -> Option<WidgetId> {
2645        // The menus and the capture are borrowed as **separate fields**: a
2646        // `self.current_mut()` here would borrow the whole struct and `self.ui`
2647        // with it.
2648        let shown = self.shown;
2649        let menu = self
2650            .menus
2651            .iter_mut()
2652            .find_map(|(kind, menu)| (*kind == shown).then_some(menu))?;
2653        let layout = menu.layout(extent, atlas);
2654        menu.point(&layout, &mut self.ui, pointer)
2655    }
2656}
2657
2658// ---------------------------------------------------------------------------
2659// Tests
2660// ---------------------------------------------------------------------------
2661
2662#[cfg(test)]
2663mod tests {
2664    use super::*;
2665    use crate::draw_list::DrawCommand;
2666
2667    /// The five extents every "it is on screen" test in this repository uses:
2668    /// what a window opens at, a smaller 4:3, 16:9, a canvas clamped by
2669    /// `max-height: 68vh`, and one taller than it is wide.
2670    const EXTENTS: [(u32, u32); 5] = [
2671        (960, 720),
2672        (800, 600),
2673        (1920, 1080),
2674        (1440, 400),
2675        (600, 900),
2676    ];
2677
2678    fn atlas() -> FontAtlas {
2679        FontAtlas::built_in()
2680    }
2681
2682    /// A skin of five flat 16x16 images, each a different shade, with the
2683    /// shipped art's insets — enough for `render` to draw, and different
2684    /// enough that a frame drawn from the wrong image samples a different UV.
2685    fn skin() -> MenuSkin {
2686        let mut images = crate::image::ImageAtlas::new();
2687        let mut register = |shade: u8| {
2688            images
2689                .register(16, 16, &[shade; 16 * 16 * 4])
2690                .expect("five 16x16 images fit an empty page")
2691        };
2692        let mut sliced = |shade, insets| NineSliceImage {
2693            image: register(shade),
2694            insets,
2695        };
2696        let panel = sliced(10, PANEL_INSETS);
2697        let buttons = ButtonSkin {
2698            idle: sliced(20, BUTTON_INSETS),
2699            hovered: sliced(30, BUTTON_INSETS),
2700            pressed: sliced(40, BUTTON_INSETS),
2701        };
2702        MenuSkin {
2703            panel,
2704            buttons,
2705            scrim: register(255),
2706        }
2707    }
2708
2709    fn pause_menu() -> Menu {
2710        Menu::new(
2711            "PAUSED",
2712            vec![
2713                MenuItem::new(1, "RESUME", "ESC"),
2714                MenuItem::new(2, "FULLSCREEN", "F11"),
2715                MenuItem::new(3, "DEBUG OVERLAY", "F3"),
2716            ],
2717        )
2718    }
2719
2720    // -----------------------------------------------------------------------
2721    // In a font
2722    // -----------------------------------------------------------------------
2723
2724    /// **A menu laid out in a font measures its text in it and draws it in
2725    /// it**: a row is its label's advances in the font plus the button's frame
2726    /// and padding, and one line of the font tall — where the same style in
2727    /// the atlas measures the atlas's width — and [`Menu::render`] draws that
2728    /// layout's label as a glyph run of the font. [`Menu::layout`] is what it
2729    /// was before, the font registered in the shared trees notwithstanding.
2730    #[cfg(feature = "parsed-font")]
2731    #[test]
2732    fn a_menu_laid_out_in_a_font_measures_and_draws_its_text_in_it() {
2733        use crate::font::FontMetrics;
2734
2735        let font = Font::fixed_pitch(
2736            FontMetrics {
2737                units_per_em: 1000,
2738                ascent: 800.0,
2739                descent: -200.0,
2740                line_gap: 0.0,
2741            },
2742            500.0,
2743        );
2744        let menu = Menu::new("", vec![MenuItem::new(1, "RESUME", "")]);
2745        let style = MenuStyle::pixel_art(1);
2746        let extent = (960, 720);
2747        let before = menu.layout(extent, &atlas());
2748
2749        let in_font = menu.layout_with_font(extent, &style, font);
2750        let in_atlas = menu.layout_with(extent, &atlas(), &style);
2751        let corners = style.button_corners();
2752        let chrome = Vec2::new(
2753            corners.left + corners.right + 2.0 * style.button_padding.x,
2754            corners.top + corners.bottom + 2.0 * style.button_padding.y,
2755        );
2756        let label = |layout: &MenuLayout| layout.items()[0].size() - chrome;
2757        assert_eq!(
2758            label(&in_font),
2759            Vec2::new(6.0 * 0.5 * style.item_size, style.item_size),
2760            "the row was not measured in the font"
2761        );
2762        assert_eq!(
2763            label(&in_atlas),
2764            Vec2::new(
2765                text_width(&atlas(), "RESUME", style.item_size),
2766                line_height(style.item_size)
2767            )
2768        );
2769        assert_ne!(label(&in_font), label(&in_atlas));
2770
2771        let drawn = |layout: &MenuLayout| {
2772            let mut list = DrawList::new();
2773            menu.render(&mut list, layout, &skin());
2774            let runs: Vec<_> = list
2775                .commands()
2776                .iter()
2777                .filter_map(|command| match command {
2778                    DrawCommand::Glyphs { font, .. } => Some(font.id()),
2779                    _ => None,
2780                })
2781                .collect();
2782            let texts = list
2783                .commands()
2784                .iter()
2785                .filter(|command| matches!(command, DrawCommand::Text { .. }))
2786                .count();
2787            (runs, texts)
2788        };
2789        assert_eq!(drawn(&in_font), (vec![font.id()], 0));
2790        assert_eq!(drawn(&in_atlas), (Vec::new(), 1));
2791
2792        assert_eq!(menu.layout(extent, &atlas()), before);
2793    }
2794
2795    // -----------------------------------------------------------------------
2796    // Captions
2797    // -----------------------------------------------------------------------
2798
2799    /// [`pause_menu`] with two lines under its title.
2800    fn captioned_menu() -> Menu {
2801        let mut menu = pause_menu();
2802        menu.subtitle = vec!["ARROWS MOVE".into(), "ENTER PICKS".into()];
2803        menu
2804    }
2805
2806    /// The `(text, pos, colour)` of every bitmap string `dl` draws.
2807    fn texts(dl: &DrawList) -> Vec<(String, Vec2, [f32; 4])> {
2808        dl.commands()
2809            .iter()
2810            .filter_map(|command| match command {
2811                DrawCommand::Text {
2812                    text, pos, color, ..
2813                } => Some((text.clone(), *pos, *color)),
2814                _ => None,
2815            })
2816            .collect()
2817    }
2818
2819    /// **The lines under the title are drawn there, in the hint's colour, and
2820    /// inside the panel** — between the title and the first row, in the
2821    /// order given — and the rows are laid out below them rather than over
2822    /// them.
2823    #[test]
2824    fn captions_are_drawn_under_the_title_in_the_hint_colour() {
2825        let atlas = atlas();
2826        let menu = captioned_menu();
2827        let layout = menu.layout((960, 720), &atlas);
2828        let mut dl = DrawList::new();
2829        menu.render(&mut dl, &layout, &skin());
2830        let drawn = texts(&dl);
2831        let line = |wanted: &str| {
2832            drawn
2833                .iter()
2834                .find(|(text, ..)| text == wanted)
2835                .unwrap_or_else(|| panic!("{wanted} is not drawn: {drawn:?}"))
2836                .clone()
2837        };
2838        let (_, first, first_colour) = line("ARROWS MOVE");
2839        let (_, second, second_colour) = line("ENTER PICKS");
2840        assert_eq!(first_colour, layout.style().hint_color);
2841        assert_eq!(second_colour, layout.style().hint_color);
2842
2843        let title_bottom = layout.title_pos().y + line_height(layout.style().title_size);
2844        let caption_bottom = second.y + line_height(layout.style().item_size);
2845        let (panel_min, panel_max) = layout.panel();
2846        assert!(
2847            title_bottom <= first.y && first.y < second.y,
2848            "the captions are not under the title, in order: {first:?} {second:?}"
2849        );
2850        assert!(
2851            caption_bottom <= layout.items()[0].min.y,
2852            "the first row starts at {} over a caption ending at {caption_bottom}",
2853            layout.items()[0].min.y
2854        );
2855        for pos in [first, second] {
2856            assert!(pos.x >= panel_min.x && pos.x <= panel_max.x, "{pos:?}");
2857        }
2858    }
2859
2860    /// **A caption takes no input from either device.** The keyboard walks
2861    /// the three rows and wraps as it did without captions, the commit key
2862    /// fires the rows' ids, and a pointer over a caption hovers and clicks
2863    /// nothing — the highlight stays with the keyboard.
2864    #[test]
2865    fn captions_are_skipped_by_the_keyboard_and_the_pointer() {
2866        let atlas = atlas();
2867        let mut menu = captioned_menu();
2868        let mut fired = Vec::new();
2869        for _ in 0..=menu.items().len() {
2870            fired.push(menu.activate());
2871            menu.select_next();
2872        }
2873        assert_eq!(fired, [Some(1), Some(2), Some(3), Some(1)]);
2874        assert!(menu.select_id(1));
2875        menu.select_previous();
2876        assert_eq!(menu.activate(), Some(3), "the wrap upward went astray");
2877        assert!(menu.select_id(1));
2878
2879        let layout = menu.layout((960, 720), &atlas);
2880        let mut dl = DrawList::new();
2881        menu.render(&mut dl, &layout, &skin());
2882        let (_, caption, _) = texts(&dl)
2883            .into_iter()
2884            .find(|(text, ..)| text == "ENTER PICKS")
2885            .expect("the caption is drawn");
2886        let on_caption = caption + Vec2::new(2.0, 2.0);
2887        let mut ui = UiState::new();
2888        assert_eq!(menu.point(&layout, &mut ui, press_at(on_caption)), None);
2889        assert_eq!(menu.point(&layout, &mut ui, release_at(on_caption)), None);
2890        assert_eq!(
2891            menu.state(0),
2892            ButtonState::Hovered,
2893            "the caption took the hover"
2894        );
2895        assert_eq!(menu.selected(), 0);
2896    }
2897
2898    /// [`captioned_menu`] with a warning between its two hint lines.
2899    fn warned_menu() -> Menu {
2900        let mut menu = captioned_menu();
2901        menu.subtitle
2902            .insert(1, Caption::warning("PROGRESS WILL BE LOST"));
2903        menu
2904    }
2905
2906    /// **Each caption is drawn in its tone's colour**: a warning in the
2907    /// style's warning colour and the hint lines round it in the hint's,
2908    /// in the order given.
2909    #[test]
2910    fn a_warning_caption_is_drawn_in_the_warning_colour() {
2911        let menu = warned_menu();
2912        let layout = menu.layout((960, 720), &atlas());
2913        let style = layout.style();
2914        assert_ne!(style.warning_color, style.hint_color);
2915        let mut dl = DrawList::new();
2916        menu.render(&mut dl, &layout, &skin());
2917        let captions: Vec<(String, [f32; 4])> = texts(&dl)
2918            .into_iter()
2919            .filter(|(text, ..)| menu.subtitle.iter().any(|line| &line.text == text))
2920            .map(|(text, _, colour)| (text, colour))
2921            .collect();
2922        assert_eq!(
2923            captions,
2924            [
2925                ("ARROWS MOVE".to_owned(), style.hint_color),
2926                ("PROGRESS WILL BE LOST".to_owned(), style.warning_color),
2927                ("ENTER PICKS".to_owned(), style.hint_color),
2928            ]
2929        );
2930    }
2931
2932    /// **A caption's tone moves nothing but its colour.** The same lines
2933    /// as hints and as warnings lay out alike, fitted in a font too; the
2934    /// keyboard walks the same rows; and a pointer on a warning hits
2935    /// nothing.
2936    #[test]
2937    fn a_captions_tone_changes_no_row_or_hit() {
2938        let atlas = atlas();
2939        let hinted = captioned_menu();
2940        let mut warned = captioned_menu();
2941        for line in &mut warned.subtitle {
2942            line.tone = CaptionTone::Warning;
2943        }
2944        assert_eq!(
2945            warned.layout((960, 720), &atlas),
2946            hinted.layout((960, 720), &atlas)
2947        );
2948        #[cfg(feature = "parsed-font")]
2949        assert_eq!(
2950            warned.layout_with_font_fitted(
2951                (480, 360),
2952                &MenuStyle::pixel_art(2),
2953                font_like_roboto()
2954            ),
2955            hinted.layout_with_font_fitted(
2956                (480, 360),
2957                &MenuStyle::pixel_art(2),
2958                font_like_roboto()
2959            ),
2960        );
2961
2962        let mut fired = Vec::new();
2963        for _ in 0..=warned.items().len() {
2964            fired.push(warned.activate());
2965            warned.select_next();
2966        }
2967        assert_eq!(fired, [Some(1), Some(2), Some(3), Some(1)]);
2968        assert!(warned.select_id(1));
2969
2970        let layout = warned.layout((960, 720), &atlas);
2971        let mut dl = DrawList::new();
2972        warned.render(&mut dl, &layout, &skin());
2973        let (_, caption, colour) = texts(&dl)
2974            .into_iter()
2975            .find(|(text, ..)| text == "ENTER PICKS")
2976            .expect("the caption is drawn");
2977        assert_eq!(colour, layout.style().warning_color);
2978        let on_caption = caption + Vec2::new(2.0, 2.0);
2979        let mut ui = UiState::new();
2980        assert_eq!(warned.point(&layout, &mut ui, press_at(on_caption)), None);
2981        assert_eq!(warned.point(&layout, &mut ui, release_at(on_caption)), None);
2982        assert_eq!(warned.state(0), ButtonState::Hovered);
2983        assert_eq!(warned.selected(), 0);
2984    }
2985
2986    /// **A stylesheet's `.menu-caption-warning` rule sets a warning's
2987    /// colour**, over `default.css`'s, and leaves the hint lines alone.
2988    #[test]
2989    fn a_stylesheet_rule_sets_the_warning_colour() {
2990        let menu = warned_menu();
2991        let style = MenuStyle::pixel_art(1);
2992        let red = [1.0, 0.0, 0.0, 1.0];
2993        let mut ui = Ui::new();
2994        ui.add_stylesheet(
2995            "game",
2996            ".menu-caption-warning { color: color(srgb-linear 1 0 0); }",
2997        );
2998        ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
2999        menu.build(
3000            &mut ui,
3001            Some(Vec2::new(960.0, 720.0)),
3002            &style,
3003            None,
3004            &Setup::default(),
3005        );
3006        ui.layout(
3007            Vec2::ZERO,
3008            AvailableSpace::definite(Vec2::new(960.0, 720.0)),
3009            &atlas(),
3010        );
3011        let mut dl = DrawList::new();
3012        ui.emit(&mut dl);
3013        let colour = |wanted: &str| {
3014            texts(&dl)
3015                .into_iter()
3016                .find_map(|(text, _, colour)| (text == wanted).then_some(colour))
3017                .unwrap_or_else(|| panic!("{wanted} is not drawn"))
3018        };
3019        assert_eq!(colour("PROGRESS WILL BE LOST"), red);
3020        assert_eq!(colour("ARROWS MOVE"), style.hint_color);
3021    }
3022
3023    /// A game's sheet in EW's shape: flat panels and buttons in its own
3024    /// colours, the frames dropped with `border-image: none`.
3025    const FLAT_SHEET: &str = "\
3026        menu { border-image: none; background-color: color(srgb-linear 0 0 1); }
3027        menu-item { border-image: none; background-color: color(srgb-linear 0 1 0); }
3028        .menu-title { color: color(srgb-linear 1 0 0); }
3029        .menu-label { color: color(srgb-linear 1 0 1); }";
3030
3031    /// The colours of the rectangles `dl` holds, and how many pictures.
3032    fn fills_and_pictures(dl: &DrawList) -> (Vec<[f32; 4]>, usize) {
3033        let mut fills = Vec::new();
3034        let mut pictures = 0;
3035        for command in dl.commands() {
3036            match command {
3037                DrawCommand::Rect { color, .. } => fills.push(*color),
3038                DrawCommand::Image { .. } => pictures += 1,
3039                _ => {}
3040            }
3041        }
3042        (fills, pictures)
3043    }
3044
3045    /// The colour `wanted` is drawn in.
3046    fn text_colour_in(dl: &DrawList, wanted: &str) -> [f32; 4] {
3047        texts(dl)
3048            .into_iter()
3049            .find_map(|(text, _, colour)| (text == wanted).then_some(colour))
3050            .unwrap_or_else(|| panic!("{wanted} is not drawn"))
3051    }
3052
3053    /// **A game's sheet draws over `default.css`'s menu rules**: its colours,
3054    /// and `border-image: none` drops the frames for its flat fills. **A menu
3055    /// without one, drawn after it on the same thread, is drawn as it always
3056    /// was**, so the sheet stays with the menu that was given it.
3057    #[test]
3058    fn a_menus_own_stylesheet_draws_over_the_default() {
3059        let atlas = atlas();
3060        let skin = skin();
3061        let plain = slider_menu();
3062        let mut themed = plain.clone();
3063        themed
3064            .set_stylesheet(Some(FLAT_SHEET))
3065            .expect("the sheet has no errors");
3066
3067        let layout = themed.layout((960, 720), &atlas);
3068        let mut dl = DrawList::new();
3069        themed.render(&mut dl, &layout, &skin);
3070        assert_eq!(text_colour_in(&dl, "OPTIONS"), [1.0, 0.0, 0.0, 1.0]);
3071        assert_eq!(text_colour_in(&dl, "BACK"), [1.0, 0.0, 1.0, 1.0]);
3072        let (fills, pictures) = fills_and_pictures(&dl);
3073        assert_eq!(
3074            pictures, 1,
3075            "border-image: none drops every frame, leaving the scrim"
3076        );
3077        assert!(fills.contains(&[0.0, 0.0, 1.0, 1.0]), "the panel's fill");
3078        assert!(fills.contains(&[0.0, 1.0, 0.0, 1.0]), "a button's fill");
3079
3080        let layout = plain.layout((960, 720), &atlas);
3081        let mut dl = DrawList::new();
3082        plain.render(&mut dl, &layout, &skin);
3083        assert_eq!(text_colour_in(&dl, "OPTIONS"), layout.style().title_color);
3084        assert_eq!(text_colour_in(&dl, "BACK"), layout.style().label_color);
3085        let (fills, pictures) = fills_and_pictures(&dl);
3086        assert!(pictures > 1, "the frames are drawn again");
3087        assert!(!fills.contains(&[0.0, 0.0, 1.0, 1.0]));
3088    }
3089
3090    /// **A sheet with errors is refused, and the menu keeps the one it had**;
3091    /// `None` takes the sheet away.
3092    #[test]
3093    fn a_sheet_with_errors_is_refused() {
3094        let mut menu = slider_menu();
3095        menu.set_stylesheet(Some(FLAT_SHEET)).expect("no errors");
3096        let errors = menu
3097            .set_stylesheet(Some(".menu-label + .menu-hint { color: red; }"))
3098            .expect_err("a combinator the parser refuses");
3099        assert!(!errors.is_empty());
3100        assert_eq!(menu.stylesheet.as_deref(), Some(FLAT_SHEET));
3101        menu.set_stylesheet(None).expect("no sheet has no errors");
3102        assert_eq!(menu.stylesheet, None);
3103    }
3104
3105    /// A menu of captions and no rows has nothing to select or fire, and lays
3106    /// out, fitted or not, without an index to panic on.
3107    #[cfg(feature = "parsed-font")]
3108    #[test]
3109    fn a_menu_of_only_captions_selects_nothing() {
3110        let mut menu = Menu::new("NOTICE", Vec::new());
3111        menu.subtitle = vec![Caption::warning("NOTHING TO CHOOSE")];
3112        menu.select_next();
3113        menu.select_previous();
3114        assert_eq!(menu.activate(), None);
3115        assert_eq!(menu.selected_item(), None);
3116        let layout = menu.layout((960, 720), &atlas());
3117        assert!(layout.items().is_empty());
3118        let fitted = menu
3119            .layout_with_font_fitted((480, 360), &MenuStyle::pixel_art(1), font_like_roboto())
3120            .expect("a notice fits");
3121        assert!(fitted.items().is_empty() && fitted.viewport().is_none());
3122    }
3123
3124    // -----------------------------------------------------------------------
3125    // Fitted in a font, and scrolled
3126    // -----------------------------------------------------------------------
3127
3128    /// Every glyph's advance in [`font_like_roboto`], in ems.
3129    #[cfg(feature = "parsed-font")]
3130    const ADVANCE_EM: f32 = 0.55;
3131
3132    /// A stand-in for a parsed UI font such as Roboto: every glyph
3133    /// [`ADVANCE_EM`] wide, on a line 1.172 em tall, as Roboto's own metrics
3134    /// give it. One parse per process, as an app's registered font is, so two
3135    /// layouts in it compare equal.
3136    #[cfg(feature = "parsed-font")]
3137    fn font_like_roboto() -> &'static Font {
3138        use crate::font::FontMetrics;
3139        static FONT: std::sync::OnceLock<&'static Font> = std::sync::OnceLock::new();
3140        FONT.get_or_init(|| {
3141            Font::fixed_pitch(
3142                FontMetrics {
3143                    units_per_em: 1000,
3144                    ascent: 928.0,
3145                    descent: -244.0,
3146                    line_gap: 0.0,
3147                },
3148                ADVANCE_EM * 1000.0,
3149            )
3150        })
3151    }
3152
3153    /// The row count of [`scene_menu`].
3154    #[cfg(feature = "parsed-font")]
3155    const SCENES: usize = 17;
3156
3157    /// A stand-in for EW's scene menu: [`SCENES`] rows, each a label and a
3158    /// one-line description in the hint slot — the longest seventy
3159    /// characters — under a title and two captions, the second a warning.
3160    #[cfg(feature = "parsed-font")]
3161    fn scene_menu() -> Menu {
3162        let items = (0..SCENES)
3163            .map(|index| {
3164                let description = format!("{:02} {}", index, "a".repeat(40 + index * 2))
3165                    .chars()
3166                    .take(70)
3167                    .collect::<String>();
3168                MenuItem::new(
3169                    100 + index as WidgetId,
3170                    format!("SCENE {index:02} NAME"),
3171                    description,
3172                )
3173            })
3174            .collect();
3175        let mut menu = Menu::new("SCENES", items);
3176        menu.subtitle = vec![
3177            "UP/DOWN MOVES - ENTER LOADS - ESC CLOSES".into(),
3178            Caption::warning("LOADING A SCENE DISCARDS UNSAVED WORK"),
3179        ];
3180        menu
3181    }
3182
3183    /// The smallest window EW supports.
3184    #[cfg(feature = "parsed-font")]
3185    const SMALL: (u32, u32) = (480, 360);
3186
3187    /// The fitted layout of `menu` at `extent`, from EW's style.
3188    #[cfg(feature = "parsed-font")]
3189    fn fitted(menu: &Menu, extent: (u32, u32)) -> MenuLayout {
3190        menu.layout_with_font_fitted(extent, &MenuStyle::pixel_art(2), font_like_roboto())
3191            .unwrap_or_else(|error| panic!("{extent:?}: {error}"))
3192    }
3193
3194    /// Whether `inner` lies wholly inside `outer`.
3195    #[cfg(feature = "parsed-font")]
3196    fn within(inner: (Vec2, Vec2), outer: (Vec2, Vec2)) -> bool {
3197        inner.0.x >= outer.0.x
3198            && inner.0.y >= outer.0.y
3199            && inner.1.x <= outer.1.x
3200            && inner.1.y <= outer.1.y
3201    }
3202
3203    /// **Seventeen rows with descriptions and two captions fit a 480x360
3204    /// window.** The panel is inside the fit's share of the framebuffer; the
3205    /// font is no smaller than the minimum; the art is at a whole-number
3206    /// scale with the art's corners; seventeen rows do not fit that height
3207    /// at any legible size, so the list scrolls, and its viewport is inside
3208    /// the panel, every row drawn is inside the panel's width and reaches
3209    /// into the viewport, and the widest description ends inside its row.
3210    /// The same inputs lay out the same menu.
3211    #[cfg(feature = "parsed-font")]
3212    #[test]
3213    fn a_seventeen_row_menu_fits_a_480_by_360_window() {
3214        let menu = scene_menu();
3215        let layout = fitted(&menu, SMALL);
3216        let style = layout.style();
3217        let screen = extent_size(SMALL);
3218        let panel = layout.panel();
3219        assert!(
3220            within(panel, (Vec2::ZERO, screen)),
3221            "the panel {panel:?} leaves the window"
3222        );
3223        assert!(layout.panel_size().cmple(screen * FIT_FRACTION).all());
3224        assert!(
3225            style.item_size >= MenuStyle::MIN_FONT_SIZE,
3226            "{}",
3227            style.item_size
3228        );
3229        assert!(
3230            style.scale >= 1.0 && style.scale.fract() == 0.0,
3231            "{}",
3232            style.scale
3233        );
3234        assert_eq!(style.panel_corners().left, PANEL_INSETS.left * style.scale);
3235
3236        let viewport = layout
3237            .viewport()
3238            .expect("seventeen rows scroll at 360 tall");
3239        assert!(within(viewport, panel), "{viewport:?} leaves {panel:?}");
3240        let shown: Vec<usize> = (0..SCENES).filter(|&index| layout.shows(index)).collect();
3241        assert!(shown.len() > 1 && shown.len() < SCENES, "{shown:?}");
3242        for &index in &shown {
3243            let row = layout.items()[index];
3244            assert!(
3245                row.min.x >= panel.0.x && row.max.x <= panel.1.x,
3246                "row {index} {row:?} is wider than the panel"
3247            );
3248            assert!(
3249                row.max.y > viewport.0.y && row.min.y < viewport.1.y,
3250                "row {index} is drawn but nowhere in view"
3251            );
3252            let description = &menu.items()[index].hint;
3253            let end =
3254                row.hint_pos.x + description.chars().count() as f32 * ADVANCE_EM * style.item_size;
3255            assert!(
3256                end <= row.max.x + 0.5,
3257                "row {index}'s description ends at {end}"
3258            );
3259        }
3260        assert!(within(
3261            (layout.items()[0].min, layout.items()[0].max),
3262            viewport
3263        ));
3264        assert_eq!(fitted(&menu, SMALL), layout, "the fit is not deterministic");
3265    }
3266
3267    /// **The fit is the largest step that fits.** At a window big enough to
3268    /// fit without scrolling but too small for the ceiling, the chosen size
3269    /// fits and the next step up does not; and a window big enough for the
3270    /// ceiling gets the ceiling, unscrolled.
3271    #[cfg(feature = "parsed-font")]
3272    #[test]
3273    fn the_fit_takes_the_largest_step_that_fits() {
3274        let menu = scene_menu();
3275        let ceiling = MenuStyle::pixel_art(2);
3276        let font = font_like_roboto();
3277        let extent = (1100, 900);
3278        let layout = fitted(&menu, extent);
3279        let chosen = layout.style().item_size;
3280        assert!(layout.viewport().is_none(), "{extent:?} scrolled");
3281        assert!(
3282            chosen < ceiling.item_size && chosen > MenuStyle::MIN_FONT_SIZE,
3283            "{extent:?} does not exercise the shrink: {chosen}"
3284        );
3285        let panel_at = |size: f32| {
3286            let style = ceiling.shrunk(size);
3287            let setup = Setup {
3288                font: Some(font.clone()),
3289                line: Some(row_line(font, &style)),
3290                list: None,
3291            };
3292            menu.measure(&style, &setup).panel
3293        };
3294        let room = extent_size(extent) * FIT_FRACTION;
3295        assert!(panel_at(chosen).cmple(room).all());
3296        assert!(
3297            !panel_at(chosen + FIT_FONT_STEP).cmple(room).all(),
3298            "a step larger than {chosen} fits too"
3299        );
3300
3301        let roomy = fitted(&menu, (3840, 2160));
3302        assert_eq!(roomy.style().item_size, ceiling.item_size);
3303        assert_eq!(roomy.style().scale, ceiling.scale);
3304        assert!(roomy.viewport().is_none());
3305    }
3306
3307    /// **Below the minimum the fit refuses, and says why.** A window too
3308    /// narrow for the descriptions at [`MenuStyle::MIN_FONT_SIZE`] is too
3309    /// wide a menu, which scrolling cannot help; a window too short for the
3310    /// title, the captions and one row is too short. Neither is laid out at
3311    /// a smaller size than the minimum.
3312    #[cfg(feature = "parsed-font")]
3313    #[test]
3314    fn the_fit_refuses_honestly_below_the_minimum() {
3315        let menu = scene_menu();
3316        let style = MenuStyle::pixel_art(2);
3317        let font = font_like_roboto();
3318        match menu.layout_with_font_fitted((300, 360), &style, font) {
3319            Err(MenuFitError::TooWide {
3320                font_size,
3321                width,
3322                room,
3323            }) => {
3324                assert_eq!(font_size, MenuStyle::MIN_FONT_SIZE);
3325                assert!(
3326                    width > room && room == 300.0 * FIT_FRACTION,
3327                    "{width} {room}"
3328                );
3329            }
3330            other => panic!("a 300px window gave {other:?}"),
3331        }
3332        match menu.layout_with_font_fitted((480, 60), &style, font) {
3333            Err(MenuFitError::TooShort {
3334                font_size,
3335                height,
3336                room,
3337            }) => {
3338                assert_eq!(font_size, MenuStyle::MIN_FONT_SIZE);
3339                assert!(height > room, "{height} {room}");
3340            }
3341            other => panic!("a 60px window gave {other:?}"),
3342        }
3343    }
3344
3345    /// **The keyboard keeps its selection in view, all the way down and all
3346    /// the way back.** Every step of a walk to the last row and back to the
3347    /// first leaves the selected row wholly inside the viewport, both for a
3348    /// caller that only lays out and draws and for one that also runs the
3349    /// pointer — which keeps the list still while the selection moves inside
3350    /// it, as a list does.
3351    #[cfg(feature = "parsed-font")]
3352    #[test]
3353    fn scrolling_keeps_the_selected_row_in_view_down_and_up() {
3354        for with_pointer in [false, true] {
3355            let mut menu = scene_menu();
3356            let mut ui = UiState::new();
3357            let mut scrolls = Vec::new();
3358            let mut step = |menu: &mut Menu, moved: &str| {
3359                let layout = fitted(menu, SMALL);
3360                let viewport = layout.viewport().expect("the list scrolls");
3361                let selected = layout.items()[menu.selected()];
3362                assert!(
3363                    layout.shows(menu.selected()) && within((selected.min, selected.max), viewport),
3364                    "after {moved} to row {}, {selected:?} is not wholly in {viewport:?}",
3365                    menu.selected(),
3366                );
3367                if with_pointer {
3368                    menu.point(&layout, &mut ui, PointerInput::hovering(OFF_SCREEN));
3369                }
3370                scrolls.push(layout.scroll());
3371            };
3372            step(&mut menu, "opening");
3373            for _ in 1..SCENES {
3374                menu.select_next();
3375                step(&mut menu, "down");
3376            }
3377            assert_eq!(menu.selected(), SCENES - 1);
3378            for _ in 1..SCENES {
3379                menu.select_previous();
3380                step(&mut menu, "up");
3381            }
3382            assert_eq!(menu.selected(), 0);
3383            assert!(scrolls[SCENES - 1] > 0.0, "the walk down never scrolled");
3384            assert_eq!(*scrolls.last().expect("walked"), 0.0);
3385            if with_pointer {
3386                // One step up from the bottom stays inside the view, so the
3387                // list does not move.
3388                assert_eq!(scrolls[SCENES], scrolls[SCENES - 1], "{scrolls:?}");
3389            }
3390        }
3391    }
3392
3393    /// **A row scrolled out of view is neither drawn nor hit.** With the last
3394    /// row selected the first is scrolled off the top: a press where it was
3395    /// placed hovers and fires nothing, a row in view still answers, and the
3396    /// draw list holds the title, the captions and the shown rows' text and
3397    /// frames and nothing of the others.
3398    #[cfg(feature = "parsed-font")]
3399    #[test]
3400    fn rows_scrolled_out_of_view_are_neither_drawn_nor_hit() {
3401        let mut menu = scene_menu();
3402        menu.select_previous();
3403        let last = SCENES - 1;
3404        assert_eq!(menu.selected(), last);
3405        let layout = fitted(&menu, SMALL);
3406        let viewport = layout.viewport().expect("the list scrolls");
3407        assert!(!layout.shows(0), "the first row is still in view");
3408        assert!(layout.shows(last));
3409
3410        let mut ui = UiState::new();
3411        let hidden = layout.items()[0];
3412        let where_it_was = (hidden.min + hidden.max) * 0.5;
3413        assert_eq!(menu.point(&layout, &mut ui, press_at(where_it_was)), None);
3414        assert_eq!(menu.point(&layout, &mut ui, release_at(where_it_was)), None);
3415        assert_eq!(
3416            menu.state(0),
3417            ButtonState::Idle,
3418            "a hidden row took the hover"
3419        );
3420        let visible = layout.items()[last];
3421        let on_it = (visible.min + visible.max) * 0.5;
3422        menu.point(&layout, &mut ui, press_at(on_it));
3423        assert_eq!(
3424            menu.point(&layout, &mut ui, release_at(on_it)),
3425            Some(100 + last as WidgetId)
3426        );
3427
3428        let shown = (0..SCENES).filter(|&index| layout.shows(index)).count();
3429        let mut dl = DrawList::new();
3430        menu.render(&mut dl, &layout, &skin());
3431        let runs: Vec<Vec2> = dl
3432            .commands()
3433            .iter()
3434            .filter_map(|command| match command {
3435                DrawCommand::Glyphs { origin, .. } => Some(*origin),
3436                _ => None,
3437            })
3438            .collect();
3439        assert_eq!(runs.len(), 1 + 2 + 2 * shown, "title, captions, shown rows");
3440        let frames = pictures(&dl).len();
3441        assert_eq!(
3442            frames,
3443            1 + 9 + 9 * shown,
3444            "scrim, panel, shown rows' frames"
3445        );
3446        // Every row's text starts inside the viewport's reach: none is drawn
3447        // at a hidden row's place.
3448        for origin in &runs[3..] {
3449            assert!(
3450                origin.y + layout.style().item_size > viewport.0.y && origin.y < viewport.1.y,
3451                "a row's text at {origin:?} is out of {viewport:?}"
3452            );
3453        }
3454        // And the art alone keeps the list's clip.
3455        let mut art = DrawList::new();
3456        menu.render_art(&mut art, &layout, &skin());
3457        assert_eq!(art.len(), frames);
3458        assert!(
3459            art.clips()[10..]
3460                .iter()
3461                .all(|clip| clip.min == viewport.0 && clip.max == viewport.1),
3462            "a row's frame lost the list's clip"
3463        );
3464    }
3465
3466    /// **The wheel scrolls the list, and the keyboard takes it back.** A
3467    /// wheel over the panel moves the list and reports it — even off the
3468    /// selection, which stays where it was — a wheel off the panel, or past
3469    /// the end, reports nothing, and the next keyboard move scrolls its row
3470    /// back into view.
3471    #[cfg(feature = "parsed-font")]
3472    #[test]
3473    fn the_wheel_scrolls_the_list_and_the_keyboard_takes_it_back() {
3474        let mut menu = scene_menu();
3475        let layout = fitted(&menu, SMALL);
3476        let (panel_min, panel_max) = layout.panel();
3477        let over = (panel_min + panel_max) * 0.5;
3478        assert_eq!(layout.scroll(), 0.0);
3479        assert!(!menu.scroll_wheel(&layout, Vec2::new(1.0, 1.0), Vec2::new(0.0, 60.0)));
3480        assert!(menu.scroll_wheel(&layout, over, Vec2::new(0.0, 60.0)));
3481        let wheeled = fitted(&menu, SMALL);
3482        assert_eq!(wheeled.scroll(), 60.0, "the wheel did not move the list");
3483        assert_eq!(menu.selected(), 0);
3484        assert!(!wheeled.shows(0), "60px should scroll the first row away");
3485
3486        assert!(menu.scroll_wheel(&wheeled, over, Vec2::new(0.0, 10_000.0)));
3487        let bottom = fitted(&menu, SMALL);
3488        assert!(!menu.scroll_wheel(&bottom, over, Vec2::new(0.0, 10.0)));
3489        assert!(bottom.shows(SCENES - 1));
3490
3491        menu.select_next();
3492        let back = fitted(&menu, SMALL);
3493        let row = back.items()[1];
3494        assert!(within(
3495            (row.min, row.max),
3496            back.viewport().expect("scrolls")
3497        ));
3498
3499        // A menu that fits unscrolled has no list for the wheel to move.
3500        let small = pause_menu();
3501        let unscrolled = small.layout((960, 720), &atlas());
3502        assert!(!menu.clone().scroll_wheel(
3503            &unscrolled,
3504            unscrolled.panel_centre(),
3505            Vec2::new(0.0, 10.0)
3506        ));
3507    }
3508
3509    // -----------------------------------------------------------------------
3510    // Centred
3511    // -----------------------------------------------------------------------
3512
3513    /// **The ask, as arithmetic.** The panel's centre is the framebuffer's
3514    /// centre, at every aspect ratio and every size — not "on screen", which a
3515    /// menu jammed into the top-left corner also is.
3516    ///
3517    /// Half a pixel of tolerance and no more: [`Menu::layout_with`] rounds the
3518    /// panel's origin to a whole pixel so the nine-slice's corners land on texel
3519    /// boundaries, and a size of odd parity then puts the centre on a half pixel.
3520    /// Anything looser would admit a menu that was merely near the middle.
3521    #[test]
3522    fn the_panel_is_centred_at_every_aspect_ratio() {
3523        let menu = pause_menu();
3524        let atlas = atlas();
3525        for extent in EXTENTS {
3526            let layout = menu.layout(extent, &atlas);
3527            let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
3528            let offset = layout.panel_centre() - screen * 0.5;
3529            assert!(
3530                offset.x.abs() <= 0.5 && offset.y.abs() <= 0.5,
3531                "{extent:?}: the panel's centre is {offset:?} off the screen's",
3532            );
3533        }
3534    }
3535
3536    /// And it is centred at every scale, not only the one the fit happened to
3537    /// choose — so a game that pins a style still gets a centred menu.
3538    #[test]
3539    fn the_panel_is_centred_at_every_scale() {
3540        let menu = pause_menu();
3541        let atlas = atlas();
3542        for scale in 1..=MenuStyle::MAX_SCALE {
3543            let style = MenuStyle::pixel_art(scale);
3544            for extent in EXTENTS {
3545                let layout = menu.layout_with(extent, &atlas, &style);
3546                let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
3547                let offset = layout.panel_centre() - screen * 0.5;
3548                assert!(
3549                    offset.x.abs() <= 0.5 && offset.y.abs() <= 0.5,
3550                    "scale {scale} at {extent:?}: centre off by {offset:?}",
3551                );
3552            }
3553        }
3554    }
3555
3556    /// Everything the menu draws is inside the panel, and the panel is inside
3557    /// the framebuffer. Without this the centring test above would pass on a
3558    /// panel so large it hung off both edges symmetrically.
3559    #[test]
3560    fn the_whole_menu_is_inside_the_screen_at_every_aspect_ratio() {
3561        let menu = pause_menu();
3562        let atlas = atlas();
3563        for extent in EXTENTS {
3564            let layout = menu.layout(extent, &atlas);
3565            let (min, max) = layout.panel();
3566            assert!(
3567                min.x >= 0.0
3568                    && min.y >= 0.0
3569                    && max.x <= extent.0 as f32
3570                    && max.y <= extent.1 as f32,
3571                "{extent:?}: the panel {min:?}..{max:?} leaves the framebuffer",
3572            );
3573            for item in layout.items() {
3574                assert!(
3575                    item.min.x >= min.x
3576                        && item.min.y >= min.y
3577                        && item.max.x <= max.x
3578                        && item.max.y <= max.y,
3579                    "{extent:?}: a button at {:?}..{:?} escapes the panel {min:?}..{max:?}",
3580                    item.min,
3581                    item.max,
3582                );
3583            }
3584        }
3585    }
3586
3587    /// The chosen scale is the largest that fits, which is what makes the menu
3588    /// grow with the window rather than sit at a fixed size in the middle of a
3589    /// 4K screen.
3590    #[test]
3591    fn a_bigger_window_gets_a_bigger_menu() {
3592        let menu = pause_menu();
3593        let atlas = atlas();
3594        let small = menu.layout((640, 480), &atlas);
3595        let large = menu.layout((1920, 1440), &atlas);
3596        assert!(
3597            large.style().scale > small.style().scale,
3598            "640x480 chose {} and 1920x1440 chose {}",
3599            small.style().scale,
3600            large.style().scale,
3601        );
3602        // And the small one is not merely a scale-1 fallback: the fit must have
3603        // been exercised at more than one candidate.
3604        assert!(small.style().scale >= 1.0);
3605        assert!(large.style().scale <= MenuStyle::MAX_SCALE as f32);
3606    }
3607
3608    // -----------------------------------------------------------------------
3609    // The nine-slice property, at the menu's level
3610    // -----------------------------------------------------------------------
3611
3612    /// **The window frame's corners keep their size as the menu grows.**
3613    ///
3614    /// A menu with one short item and one with five long ones produce very
3615    /// different panels at the same scale, and the fixed bands the art refuses to
3616    /// stretch are the same number of pixels in both. This is the layout half of
3617    /// the property [`DrawList::nine_slice`] implements — a caller that laid out
3618    /// against a corner that scaled with the panel would put its content over the
3619    /// frame at one size and inside it at another.
3620    #[test]
3621    fn the_frames_corners_do_not_grow_with_the_menu() {
3622        let atlas = atlas();
3623        let style = MenuStyle::pixel_art(3);
3624        let small = Menu::new("GO", vec![MenuItem::new(1, "OK", "")]);
3625        let large = Menu::new(
3626            "A MUCH LONGER TITLE",
3627            (0..5)
3628                .map(|i| MenuItem::new(i, "A VERY LONG MENU ITEM LABEL", "SHIFT+F11"))
3629                .collect(),
3630        );
3631
3632        let small_size = small.panel_size(&atlas, &style);
3633        let large_size = large.panel_size(&atlas, &style);
3634        assert!(
3635            large_size.x > small_size.x * 1.5 && large_size.y > small_size.y * 1.5,
3636            "the two menus are not different enough to prove anything: \
3637             {small_size:?} vs {large_size:?}",
3638        );
3639
3640        // The corners are the same pixels in both, and they are the art's insets
3641        // times the scale rather than a fraction of the panel.
3642        let corners = style.panel_corners();
3643        assert_eq!(corners.left, PANEL_INSETS.left * style.scale);
3644        assert_eq!(corners.bottom, PANEL_INSETS.bottom * style.scale);
3645
3646        // And the content box of each sits exactly that far inside its panel, so
3647        // the claim is about the layout and not only about the constant.
3648        for (menu, size) in [(&small, small_size), (&large, large_size)] {
3649            let layout = menu.layout_with((1600, 1200), &atlas, &style);
3650            let (min, max) = layout.panel();
3651            assert_eq!(max - min, size);
3652            let item = layout.items()[0];
3653            assert_eq!(
3654                item.min.x - min.x,
3655                corners.left + style.panel_padding.x,
3656                "the first button is not one fixed corner plus the padding in",
3657            );
3658            assert_eq!(max.x - item.max.x, corners.right + style.panel_padding.x);
3659        }
3660    }
3661
3662    /// Every button in one menu is the same size, whatever its label — a menu
3663    /// whose buttons were shrink-to-fit reads as a ragged list rather than as a
3664    /// panel of choices.
3665    #[test]
3666    fn every_button_is_the_same_size() {
3667        let atlas = atlas();
3668        let menu = Menu::new(
3669            "T",
3670            vec![
3671                MenuItem::new(1, "X", ""),
3672                MenuItem::new(2, "A MUCH LONGER LABEL", "F11"),
3673                MenuItem::new(3, "MID", "Q"),
3674            ],
3675        );
3676        let layout = menu.layout((1280, 960), &atlas);
3677        let first = layout.items()[0].size();
3678        for item in layout.items() {
3679            assert_eq!(item.size(), first, "buttons disagree about their size");
3680        }
3681        assert!(first.x > 0.0 && first.y > 0.0);
3682    }
3683
3684    // -----------------------------------------------------------------------
3685    // States
3686    // -----------------------------------------------------------------------
3687
3688    /// **Exactly one item is highlighted, and it is the selected one.**
3689    #[test]
3690    fn only_the_selected_item_is_highlighted() {
3691        let mut menu = pause_menu();
3692        for expected in 0..menu.items().len() {
3693            let states: Vec<ButtonState> = (0..menu.items().len()).map(|i| menu.state(i)).collect();
3694            assert_eq!(states[expected], ButtonState::Hovered, "{states:?}");
3695            assert_eq!(
3696                states.iter().filter(|s| **s != ButtonState::Idle).count(),
3697                1,
3698                "{states:?} lights up more than one item",
3699            );
3700            menu.select_next();
3701        }
3702        // Wrapped back to the start.
3703        assert_eq!(menu.selected(), 0);
3704    }
3705
3706    /// The selection wraps both ways, so a player at the top can reach the
3707    /// bottom without walking the whole list.
3708    #[test]
3709    fn the_selection_wraps_both_ways() {
3710        let mut menu = pause_menu();
3711        menu.select_previous();
3712        assert_eq!(menu.selected(), 2);
3713        menu.select_next();
3714        assert_eq!(menu.selected(), 0);
3715    }
3716
3717    /// **Holding the commit key changes the state, and letting it go changes it
3718    /// back.** Asserted as the three-way state rather than as a bool, because the
3719    /// state is what selects the frame of art the button draws.
3720    #[test]
3721    fn holding_the_commit_key_presses_the_highlighted_button() {
3722        let mut menu = pause_menu();
3723        assert_eq!(menu.state(0), ButtonState::Hovered);
3724        menu.press(true);
3725        assert_eq!(menu.state(0), ButtonState::Pressed);
3726        assert_eq!(menu.state(1), ButtonState::Idle, "the press leaked");
3727        assert_eq!(menu.activate(), Some(1));
3728        assert_eq!(
3729            menu.state(0),
3730            ButtonState::Hovered,
3731            "activating left the button held down",
3732        );
3733    }
3734
3735    /// Activation reports the item's **id**, not its index, and follows the
3736    /// selection.
3737    #[test]
3738    fn activation_reports_the_selected_items_id() {
3739        let mut menu = pause_menu();
3740        assert_eq!(menu.activate(), Some(1));
3741        menu.select_next();
3742        assert_eq!(menu.activate(), Some(2));
3743        assert!(menu.select_id(3));
3744        assert_eq!(menu.activate(), Some(3));
3745        assert!(!menu.select_id(99), "an id that is not in the menu");
3746    }
3747
3748    /// An empty menu has nothing to select, nothing to press and nothing to
3749    /// fire — and says so rather than panicking on an index.
3750    #[test]
3751    fn an_empty_menu_activates_nothing() {
3752        let mut menu = Menu::new("EMPTY", Vec::new());
3753        menu.select_next();
3754        menu.select_previous();
3755        menu.press(true);
3756        assert_eq!(menu.activate(), None);
3757        assert_eq!(menu.state(0), ButtonState::Idle);
3758    }
3759
3760    // -----------------------------------------------------------------------
3761    // The pointer
3762    // -----------------------------------------------------------------------
3763
3764    /// The pointer hovers, presses and clicks — and a press released off the
3765    /// button it started on fires nothing, which is [`UiState`]'s capture doing
3766    /// its job through the menu.
3767    #[test]
3768    fn the_pointer_hovers_presses_and_clicks() {
3769        let atlas = atlas();
3770        let mut menu = pause_menu();
3771        let layout = menu.layout((960, 720), &atlas);
3772        let mut ui = UiState::new();
3773        let second = layout.items()[1];
3774        let over_second = (second.min + second.max) * 0.5;
3775        let outside = Vec2::new(2.0, 2.0);
3776
3777        // Hover moves the highlight off the keyboard's selection.
3778        assert_eq!(
3779            menu.point(&layout, &mut ui, PointerInput::hovering(over_second)),
3780            None
3781        );
3782        assert_eq!(menu.state(1), ButtonState::Hovered);
3783        assert_eq!(
3784            menu.state(0),
3785            ButtonState::Idle,
3786            "the selection still shows"
3787        );
3788
3789        // Press.
3790        let down = PointerInput {
3791            pos: over_second,
3792            down: true,
3793            released: false,
3794            secondary_pressed: false,
3795        };
3796        assert_eq!(menu.point(&layout, &mut ui, down), None);
3797        assert_eq!(menu.state(1), ButtonState::Pressed);
3798
3799        // Released somewhere else: nothing fires, and the capture is dropped.
3800        let elsewhere = PointerInput {
3801            pos: outside,
3802            down: false,
3803            released: true,
3804            secondary_pressed: false,
3805        };
3806        assert_eq!(menu.point(&layout, &mut ui, elsewhere), None);
3807        assert_eq!(ui.active(), None);
3808
3809        // A press and release over the same button fires it, and leaves the
3810        // keyboard's selection on it.
3811        assert_eq!(menu.point(&layout, &mut ui, down), None);
3812        let up = PointerInput {
3813            pos: over_second,
3814            down: false,
3815            released: true,
3816            secondary_pressed: false,
3817        };
3818        assert_eq!(menu.point(&layout, &mut ui, up), Some(2));
3819        assert_eq!(menu.selected(), 1);
3820    }
3821
3822    /// A pointer that is over nothing leaves the keyboard in charge.
3823    #[test]
3824    fn a_pointer_over_nothing_gives_the_highlight_back_to_the_keyboard() {
3825        let atlas = atlas();
3826        let mut menu = pause_menu();
3827        let layout = menu.layout((960, 720), &atlas);
3828        let mut ui = UiState::new();
3829        let third = layout.items()[2];
3830        menu.point(
3831            &layout,
3832            &mut ui,
3833            PointerInput::hovering((third.min + third.max) * 0.5),
3834        );
3835        assert_eq!(menu.state(2), ButtonState::Hovered);
3836        menu.point(
3837            &layout,
3838            &mut ui,
3839            PointerInput::hovering(Vec2::new(1.0, 1.0)),
3840        );
3841        assert_eq!(menu.state(0), ButtonState::Hovered, "back to the selection");
3842        assert_eq!(menu.state(2), ButtonState::Idle);
3843    }
3844
3845    /// **A drag from one item onto a neighbour draws neither of them
3846    /// pressed.** [`UiState`]'s capture belongs to the item the press started
3847    /// on, so the neighbour reports `Idle` even while the cursor is over it —
3848    /// and the drawn state must say the same, not the `Pressed` a menu-global
3849    /// "something is down" bool painted onto whatever was hovered.
3850    #[test]
3851    fn a_drag_onto_a_neighbour_does_not_press_it() {
3852        let atlas = atlas();
3853        let mut menu = pause_menu();
3854        let layout = menu.layout((960, 720), &atlas);
3855        let mut ui = UiState::new();
3856        let first = layout.items()[0];
3857        let second = layout.items()[1];
3858
3859        // Press on the first item: it draws Pressed.
3860        let down = PointerInput {
3861            pos: (first.min + first.max) * 0.5,
3862            down: true,
3863            released: false,
3864            secondary_pressed: false,
3865        };
3866        assert_eq!(menu.point(&layout, &mut ui, down), None);
3867        assert_eq!(menu.state(0), ButtonState::Pressed);
3868
3869        // Drag onto the second: the capture still belongs to the first, so the
3870        // second must draw Idle — and once the cursor leaves it, so must the
3871        // first, exactly as `interact` reports both.
3872        let dragged = PointerInput {
3873            pos: (second.min + second.max) * 0.5,
3874            down: true,
3875            released: false,
3876            secondary_pressed: false,
3877        };
3878        assert_eq!(menu.point(&layout, &mut ui, dragged), None);
3879        assert_eq!(
3880            menu.state(1),
3881            ButtonState::Idle,
3882            "the neighbour drew Pressed while the capture belongs to the first item",
3883        );
3884        assert_eq!(
3885            menu.state(0),
3886            ButtonState::Idle,
3887            "the cursor left the captured item"
3888        );
3889    }
3890
3891    // -----------------------------------------------------------------------
3892    // Text
3893    // -----------------------------------------------------------------------
3894
3895    /// **The menu draws back to front: the scrim, the frame and the title on
3896    /// it, then each button's frame followed by the strings on that button** —
3897    /// every picture before the text that sits on it, so no frame paints over
3898    /// a label — and the text is the title, every label and every hint.
3899    #[test]
3900    fn render_draws_each_frame_before_the_text_on_it() {
3901        let atlas = atlas();
3902        let menu = pause_menu();
3903        let layout = menu.layout((960, 720), &atlas);
3904        let mut dl = DrawList::new();
3905        menu.render(&mut dl, &layout, &skin());
3906
3907        // `I` for a picture, the string itself for text: one scrim, nine panel
3908        // quads (every band non-empty at this size), the title, then nine
3909        // quads and two strings per button.
3910        let shape: Vec<String> = dl
3911            .commands()
3912            .iter()
3913            .map(|command| match command {
3914                DrawCommand::Image { .. } => "I".to_owned(),
3915                DrawCommand::Text { text, .. } => text.clone(),
3916                other => panic!("a menu of buttons drew {other:?}"),
3917            })
3918            .collect();
3919        let quads = |count: usize| std::iter::repeat_n("I".to_owned(), count);
3920        let mut expected: Vec<String> = quads(1 + 9).collect();
3921        expected.push("PAUSED".to_owned());
3922        for (label, hint) in [
3923            ("RESUME", "ESC"),
3924            ("FULLSCREEN", "F11"),
3925            ("DEBUG OVERLAY", "F3"),
3926        ] {
3927            expected.extend(quads(9));
3928            expected.extend([label.to_owned(), hint.to_owned()]);
3929        }
3930        assert_eq!(shape, expected);
3931    }
3932
3933    /// An item with no hint draws one string, not an empty second one.
3934    #[test]
3935    fn an_item_with_no_hint_draws_no_hint() {
3936        let atlas = atlas();
3937        let menu = Menu::new("T", vec![MenuItem::new(1, "OK", "")]);
3938        let layout = menu.layout((960, 720), &atlas);
3939        let mut dl = DrawList::new();
3940        menu.render(&mut dl, &layout, &skin());
3941        assert_eq!(
3942            dl.len(),
3943            1 + 9 + 9 + 2,
3944            "the scrim, the frame, one button, the title and the label, and nothing else"
3945        );
3946    }
3947
3948    /// The `Image` rectangles of `commands`, with their UV origin.
3949    fn pictures(dl: &DrawList) -> Vec<(Vec2, Vec2, Vec2)> {
3950        dl.commands()
3951            .iter()
3952            .filter_map(|command| match command {
3953                DrawCommand::Image {
3954                    min, max, uv_min, ..
3955                } => Some((*min, *max, *uv_min)),
3956                _ => None,
3957            })
3958            .collect()
3959    }
3960
3961    /// **The scrim covers the framebuffer, tinted by the style, and the frame's
3962    /// nine quads tile exactly the panel the layout placed** — so the art is
3963    /// centred wherever the layout is, and the layout's centring tests speak for
3964    /// the picture.
3965    #[test]
3966    fn the_scrim_covers_the_screen_and_the_frame_tiles_the_panel() {
3967        let atlas = atlas();
3968        let menu = pause_menu();
3969        let skin = skin();
3970        for extent in EXTENTS {
3971            let layout = menu.layout(extent, &atlas);
3972            let mut dl = DrawList::new();
3973            menu.render(&mut dl, &layout, &skin);
3974
3975            let DrawCommand::Image { min, max, tint, .. } = &dl.commands()[0] else {
3976                panic!("{extent:?}: the first command is not the scrim");
3977            };
3978            assert_eq!((*min, *max), layout.scrim(), "{extent:?}");
3979            assert_eq!(*tint, layout.style().scrim_color);
3980
3981            let frame = &pictures(&dl)[1..10];
3982            let area: f32 = frame
3983                .iter()
3984                .map(|(min, max, _)| (max.x - min.x) * (max.y - min.y))
3985                .sum();
3986            let (panel_min, panel_max) = layout.panel();
3987            let low = frame
3988                .iter()
3989                .fold(Vec2::splat(f32::MAX), |acc, q| acc.min(q.0));
3990            let high = frame
3991                .iter()
3992                .fold(Vec2::splat(f32::MIN), |acc, q| acc.max(q.1));
3993            assert_eq!((low, high), (panel_min, panel_max), "{extent:?}");
3994            assert_eq!(area, layout.panel_size().x * layout.panel_size().y);
3995        }
3996    }
3997
3998    /// **A button's state changes the picture it samples, not the rectangle it
3999    /// covers.** A `ButtonState` that never reached the art is a menu whose
4000    /// buttons never light up and whose every layout test still passes.
4001    #[test]
4002    fn a_state_change_moves_the_uvs_and_leaves_the_rectangle_alone() {
4003        let atlas = atlas();
4004        let skin = skin();
4005        let mut menu = pause_menu();
4006        let layout = menu.layout((960, 720), &atlas);
4007        let button = |menu: &Menu, index: usize| {
4008            let mut dl = DrawList::new();
4009            menu.render(&mut dl, &layout, &skin);
4010            pictures(&dl)[10 + index * 9..10 + (index + 1) * 9].to_vec()
4011        };
4012
4013        // Item 0 is selected, so it draws `Hovered` and the others `Idle`.
4014        let idle = button(&menu, 1);
4015        let hovered = button(&menu, 0);
4016        menu.press(true);
4017        let pressed = button(&menu, 0);
4018        assert_eq!(menu.state(0), ButtonState::Pressed);
4019
4020        for quad in 0..9 {
4021            assert_eq!(
4022                (hovered[quad].0, hovered[quad].1),
4023                (pressed[quad].0, pressed[quad].1)
4024            );
4025            assert_ne!(hovered[quad].2, pressed[quad].2, "quad {quad}");
4026            assert_ne!(idle[quad].2, hovered[quad].2, "quad {quad}");
4027            assert_ne!(idle[quad].2, pressed[quad].2, "quad {quad}");
4028        }
4029    }
4030
4031    /// **The frame's corners are the art's insets at the menu's scale** — four
4032    /// texels at scale three is twelve pixels — whatever the panel's size.
4033    #[test]
4034    fn the_frames_corner_quads_are_the_insets_at_the_menus_scale() {
4035        let atlas = atlas();
4036        let skin = skin();
4037        let style = MenuStyle::pixel_art(3);
4038        let small = Menu::new("GO", vec![MenuItem::new(1, "OK", "")]);
4039        let large = Menu::new(
4040            "A MUCH LONGER TITLE",
4041            (0..5)
4042                .map(|i| MenuItem::new(i, "A VERY LONG MENU ITEM LABEL", "SHIFT+F11"))
4043                .collect(),
4044        );
4045        let corners = |menu: &Menu| {
4046            let layout = menu.layout_with((1600, 1200), &atlas, &style);
4047            let mut dl = DrawList::new();
4048            menu.render(&mut dl, &layout, &skin);
4049            let frame = pictures(&dl)[1..10].to_vec();
4050            [0usize, 2, 6, 8].map(|index| (frame[index].1 - frame[index].0, frame[index].2))
4051        };
4052        let (a, b) = (corners(&small), corners(&large));
4053        assert_eq!(a, b, "a corner changed size or picture with the menu");
4054        for (size, _) in a {
4055            assert_eq!(size, Vec2::splat(PANEL_INSETS.left * style.scale));
4056        }
4057    }
4058
4059    /// Every glyph a menu draws is inside the button or panel it belongs to.
4060    /// Without this the layout could put a label a hundred pixels to the right
4061    /// and every other test here would still pass.
4062    #[test]
4063    fn every_label_is_inside_the_button_it_belongs_to() {
4064        let atlas = atlas();
4065        let menu = pause_menu();
4066        for extent in EXTENTS {
4067            let layout = menu.layout(extent, &atlas);
4068            let style = layout.style();
4069            for (item, placed) in menu.items().iter().zip(layout.items()) {
4070                let label_end =
4071                    placed.label_pos.x + text_width(&atlas, &item.label, style.item_size);
4072                assert!(
4073                    placed.label_pos.x >= placed.min.x && label_end <= placed.max.x,
4074                    "{extent:?}: {} runs from {} to {label_end} in a button \
4075                     {}..{}",
4076                    item.label,
4077                    placed.label_pos.x,
4078                    placed.min.x,
4079                    placed.max.x,
4080                );
4081                let hint_end = placed.hint_pos.x + text_width(&atlas, &item.hint, style.item_size);
4082                assert!(
4083                    placed.hint_pos.x >= label_end && hint_end <= placed.max.x,
4084                    "{extent:?}: the hint {} overlaps its label or leaves the button",
4085                    item.hint,
4086                );
4087                let bottom = placed.label_pos.y + line_height(style.item_size);
4088                assert!(
4089                    placed.label_pos.y >= placed.min.y && bottom <= placed.max.y,
4090                    "{extent:?}: {} is not vertically inside its button",
4091                    item.label,
4092                );
4093            }
4094            let title_end =
4095                layout.title_pos().x + text_width(&atlas, &menu.title, style.title_size);
4096            let (min, max) = layout.panel();
4097            assert!(layout.title_pos().x >= min.x && title_end <= max.x);
4098        }
4099    }
4100
4101    // -----------------------------------------------------------------------
4102    // MenuSet
4103    // -----------------------------------------------------------------------
4104
4105    /// A stand-in for a game's own menu states — the shape every sample has:
4106    /// one variant that draws nothing and the rest one panel each.
4107    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4108    enum Kind {
4109        None,
4110        Start,
4111        Paused,
4112    }
4113
4114    fn start_menu() -> Menu {
4115        Menu::new(
4116            "START",
4117            vec![
4118                MenuItem::new(10, "PLAY", "SPACE"),
4119                MenuItem::new(2, "FULLSCREEN", "F11"),
4120            ],
4121        )
4122    }
4123
4124    fn menus() -> MenuSet<Kind> {
4125        MenuSet::new(
4126            Kind::None,
4127            vec![(Kind::Start, start_menu()), (Kind::Paused, pause_menu())],
4128        )
4129    }
4130
4131    /// The centre of the `index`-th button, in framebuffer pixels.
4132    fn over(menus: &MenuSet<Kind>, extent: (u32, u32), index: usize) -> Vec2 {
4133        let layout = menus.current().expect("a menu").layout(extent, &atlas());
4134        let item = layout.items()[index];
4135        (item.min + item.max) * 0.5
4136    }
4137
4138    fn press_at(pos: Vec2) -> PointerInput {
4139        PointerInput {
4140            pos,
4141            down: true,
4142            released: false,
4143            secondary_pressed: false,
4144        }
4145    }
4146
4147    fn release_at(pos: Vec2) -> PointerInput {
4148        PointerInput {
4149            pos,
4150            down: false,
4151            released: true,
4152            secondary_pressed: false,
4153        }
4154    }
4155
4156    /// **A state the set holds no menu for draws nothing and takes no input.**
4157    /// This is how every sample spells "no menu this frame" — there is no
4158    /// separate `Option`, the state simply has no entry — so if any of these
4159    /// were to act on the last menu shown, a playing frame would be steering a
4160    /// panel nobody can see.
4161    #[test]
4162    fn a_state_with_no_menu_draws_nothing_and_takes_no_input() {
4163        let extent = (960, 720);
4164        let mut menus = menus();
4165        assert_eq!(menus.kind(), Kind::None);
4166        assert!(!menus.is_showing());
4167        assert!(menus.current().is_none());
4168        assert!(menus.current_mut().is_none());
4169        assert_eq!(menus.activate(), None, "there is no menu to activate");
4170        assert_eq!(menus.point(extent, &atlas(), press_at(Vec2::ZERO)), None);
4171
4172        // And the keys are not merely ignored on the way in: they must not have
4173        // moved the menu that is *about* to be shown.
4174        menus.select_next();
4175        menus.select_previous();
4176        menus.press(true);
4177        menus.show(Kind::Paused);
4178        assert!(menus.is_showing());
4179        assert_eq!(menus.current().expect("a menu").selected(), 0);
4180        assert_eq!(
4181            menus.current().expect("a menu").state(0),
4182            ButtonState::Hovered
4183        );
4184    }
4185
4186    /// **Keyboard activation works**, on whichever menu is shown, and reports
4187    /// the id the selected button carries.
4188    #[test]
4189    fn the_keyboard_selects_and_activates() {
4190        let mut menus = menus();
4191        menus.show(Kind::Paused);
4192        assert_eq!(menus.activate(), Some(1));
4193        menus.select_next();
4194        assert_eq!(menus.activate(), Some(2));
4195        menus.select_next();
4196        assert_eq!(menus.activate(), Some(3));
4197        menus.select_next();
4198        assert_eq!(menus.activate(), Some(1), "it wraps");
4199        menus.select_previous();
4200        assert_eq!(menus.activate(), Some(3));
4201
4202        // A different menu has its own selection and its own ids.
4203        menus.show(Kind::Start);
4204        assert_eq!(menus.activate(), Some(10));
4205    }
4206
4207    /// Holding the commit key presses the highlighted button and nothing else,
4208    /// which is what selects the pressed frame of the skin.
4209    #[test]
4210    fn holding_the_commit_key_presses_the_selected_button() {
4211        let mut menus = menus();
4212        menus.show(Kind::Paused);
4213        menus.select_next();
4214        menus.press(true);
4215        let menu = menus.current().expect("a menu");
4216        assert_eq!(menu.state(1), ButtonState::Pressed);
4217        assert_eq!(menu.state(0), ButtonState::Idle);
4218        menus.press(false);
4219        assert_eq!(
4220            menus.current().expect("a menu").state(1),
4221            ButtonState::Hovered,
4222        );
4223    }
4224
4225    /// **The pointer activates too**, reporting the same ids, and a click over
4226    /// nothing fires nothing.
4227    #[test]
4228    fn the_pointer_clicks_a_button() {
4229        let extent = (960, 720);
4230        let mut menus = menus();
4231        menus.show(Kind::Paused);
4232        let target = over(&menus, extent, 1);
4233
4234        assert_eq!(menus.point(extent, &atlas(), press_at(target)), None);
4235        assert_eq!(
4236            menus.current().expect("a menu").state(1),
4237            ButtonState::Pressed,
4238            "the pointer's press did not reach the art",
4239        );
4240        assert_eq!(menus.point(extent, &atlas(), release_at(target)), Some(2));
4241
4242        let corner = Vec2::new(3.0, 3.0);
4243        assert_eq!(menus.point(extent, &atlas(), press_at(corner)), None);
4244        assert_eq!(menus.point(extent, &atlas(), release_at(corner)), None);
4245    }
4246
4247    /// **A cancelled press fires nothing and leaves nothing latched**, which is
4248    /// what lets the next press latch at all.
4249    ///
4250    /// The second half is the one that matters: a capture left behind by a
4251    /// gesture the system took away is not visible — the panel looks idle — and
4252    /// the symptom is every later press doing nothing, on touch only.
4253    #[test]
4254    fn a_cancelled_press_fires_nothing_and_frees_the_capture() {
4255        let extent = (960, 720);
4256        let mut menus = menus();
4257        menus.show(Kind::Paused);
4258        let target = over(&menus, extent, 1);
4259
4260        assert!(!menus.press_captured(), "nothing is pressed yet");
4261        menus.point(extent, &atlas(), press_at(target));
4262        assert!(menus.press_captured(), "the press latched nothing");
4263
4264        menus.cancel_press();
4265        assert!(
4266            !menus.press_captured(),
4267            "the cancel left the capture behind"
4268        );
4269        assert_eq!(
4270            menus.current().expect("a menu").state(1),
4271            ButtonState::Idle,
4272            "the button stayed pressed under a finger that is gone",
4273        );
4274        assert_eq!(
4275            menus.point(extent, &atlas(), release_at(target)),
4276            None,
4277            "the cancelled press fired on the lift anyway",
4278        );
4279
4280        // And the button still works afterwards, which is what a capture left
4281        // latched would have made impossible.
4282        menus.point(extent, &atlas(), press_at(target));
4283        assert_eq!(menus.point(extent, &atlas(), release_at(target)), Some(2));
4284    }
4285
4286    /// **A press on the panel's background captures nothing**, so a caller
4287    /// driving the menu with contacts can tell the press it must remember from
4288    /// the one it must let go of.
4289    #[test]
4290    fn a_press_that_lands_on_no_button_captures_nothing() {
4291        let extent = (960, 720);
4292        let mut menus = menus();
4293        menus.show(Kind::Paused);
4294
4295        menus.point(extent, &atlas(), press_at(Vec2::new(3.0, 3.0)));
4296        assert!(
4297            !menus.press_captured(),
4298            "a press in the corner of the screen latched a button",
4299        );
4300        menus.point(extent, &atlas(), press_at(over(&menus, extent, 0)));
4301        assert!(menus.press_captured());
4302    }
4303
4304    /// **Switching menus drops the press capture**, so a click that started on
4305    /// one menu cannot land on another menu's button.
4306    ///
4307    /// The reason [`UiState`] lives in the set rather than in each [`Menu`]:
4308    /// the capture spans frames, and the menu on screen can change between
4309    /// them.
4310    ///
4311    /// **The press is put on the `FULLSCREEN` button deliberately, because both
4312    /// menus carry it under the same [`WidgetId`].** [`UiState::interact`]
4313    /// fires on release only when the capture names the *same* id the cursor is
4314    /// over, so a press parked on an id the new menu does not have could not
4315    /// fire whatever the set did with it — and a test built that way would pass
4316    /// with the capture never cleared at all.
4317    #[test]
4318    fn switching_menus_drops_the_press() {
4319        let extent = (960, 720);
4320        let mut menus = menus();
4321        menus.show(Kind::Paused);
4322        assert_eq!(
4323            menus.current().expect("a menu").items()[1].id,
4324            start_menu().items()[1].id,
4325            "the two menus stopped sharing a button, so this test guards nothing",
4326        );
4327
4328        menus.point(extent, &atlas(), press_at(over(&menus, extent, 1)));
4329        assert_eq!(
4330            menus.current().expect("a menu").state(1),
4331            ButtonState::Pressed,
4332        );
4333
4334        menus.show(Kind::Start);
4335        assert_eq!(
4336            menus.current().expect("a menu").state(0),
4337            ButtonState::Hovered,
4338            "the new menu inherited a press nobody is making",
4339        );
4340        let shared = over(&menus, extent, 1);
4341        assert_eq!(
4342            menus.point(extent, &atlas(), release_at(shared)),
4343            None,
4344            "a release fired a button whose press was on another menu",
4345        );
4346
4347        // And the menu that was left behind is clean when it comes back. The
4348        // capture is only half of it: the outgoing menu holds its own hover and
4349        // pressed flags, and a panel re-shown still lit up draws a button
4350        // nobody is touching. `Idle` rather than `Hovered` because the pointer
4351        // pressed the second button while the selection stayed on the first —
4352        // an uncleared menu reports this one `Pressed`.
4353        menus.show(Kind::Paused);
4354        assert_eq!(
4355            menus.current().expect("a menu").state(1),
4356            ButtonState::Idle,
4357            "the menu came back still holding the press it was left with",
4358        );
4359    }
4360
4361    /// Showing what is already shown changes nothing — the samples call `show`
4362    /// every frame, so an unconditional clear here would throw the selection
4363    /// and the press away sixty times a second.
4364    #[test]
4365    fn showing_the_same_menu_again_keeps_the_selection_and_the_press() {
4366        let mut menus = menus();
4367        menus.show(Kind::Paused);
4368        menus.select_next();
4369        menus.press(true);
4370        menus.show(Kind::Paused);
4371        assert_eq!(menus.current().expect("a menu").selected(), 1);
4372        assert_eq!(
4373            menus.current().expect("a menu").state(1),
4374            ButtonState::Pressed,
4375        );
4376    }
4377
4378    /// **A replaced menu drops the capture too** — the press was on a button
4379    /// that no longer says what it said. For a panel whose buttons are built
4380    /// while the game runs.
4381    ///
4382    /// The replacement keeps the **same ids** on purpose, which is what a
4383    /// rebuilt panel really looks like: the same three slots, three different
4384    /// things in them. Ids that changed would make the stale capture
4385    /// unmatchable and the test green whatever `replace` did — see
4386    /// [`switching_menus_drops_the_press`].
4387    #[test]
4388    fn a_replaced_menu_drops_the_press() {
4389        let extent = (960, 720);
4390        let mut menus = menus();
4391        menus.show(Kind::Start);
4392        menus.point(extent, &atlas(), press_at(over(&menus, extent, 0)));
4393        assert_eq!(
4394            menus.current().expect("a menu").state(0),
4395            ButtonState::Pressed,
4396        );
4397
4398        menus.replace(
4399            Kind::Start,
4400            Menu::new(
4401                "START",
4402                vec![
4403                    MenuItem::new(10, "OTHER", "SPACE"),
4404                    MenuItem::new(2, "FULLSCREEN", "F11"),
4405                ],
4406            ),
4407        );
4408        assert_eq!(
4409            menus.current().expect("a menu").items()[0].label,
4410            "OTHER",
4411            "the swap did not take",
4412        );
4413        let same_slot = over(&menus, extent, 0);
4414        assert_eq!(
4415            menus.point(extent, &atlas(), release_at(same_slot)),
4416            None,
4417            "a release fired a button the player never pressed",
4418        );
4419    }
4420
4421    /// `replace` on a state that had no menu adds one, so a set can be filled
4422    /// in after it is built.
4423    #[test]
4424    fn replacing_a_state_with_no_menu_adds_it() {
4425        let mut menus = MenuSet::new(Kind::None, vec![(Kind::Paused, pause_menu())]);
4426        menus.show(Kind::Start);
4427        assert!(!menus.is_showing(), "Start has no menu yet");
4428        menus.replace(Kind::Start, start_menu());
4429        assert!(menus.is_showing());
4430        assert_eq!(menus.current().expect("a menu").title, "START");
4431        assert_eq!(menus.activate(), Some(10));
4432    }
4433
4434    /// Two menus for one state is rejected at construction: the second would be
4435    /// unreachable, because every lookup takes the first match.
4436    #[test]
4437    #[should_panic(expected = "two menus claim the same state")]
4438    fn two_menus_for_one_state_is_rejected() {
4439        let _ = MenuSet::new(
4440            Kind::None,
4441            vec![(Kind::Paused, pause_menu()), (Kind::Paused, start_menu())],
4442        );
4443    }
4444    // -----------------------------------------------------------------------
4445    // Sliders
4446    // -----------------------------------------------------------------------
4447
4448    /// The id of the slider row in [`slider_menu`].
4449    const DIAL: WidgetId = 20;
4450
4451    /// A panel whose second row is a slider, so every test below has a button
4452    /// above it to prove the two kinds do not behave alike.
4453    fn slider_menu() -> Menu {
4454        Menu::new(
4455            "OPTIONS",
4456            vec![
4457                MenuItem::new(10, "BACK", "ESC"),
4458                MenuItem::slider(DIAL, "EXPOSURE", "1.00", 0.5),
4459            ],
4460        )
4461    }
4462
4463    /// The slider row's groove and the travel its handle's centre has inside
4464    /// it, at `extent`.
4465    ///
4466    /// Both read off the layout the menu actually chose. A test that measured
4467    /// the travel at [`MenuStyle::pixel_art`]`(1)` would be a quarter of a
4468    /// handle out at the scale a 960x720 window picks, and would report the
4469    /// clamp as a rounding error.
4470    fn groove(menu: &Menu, extent: (u32, u32)) -> ((Vec2, Vec2), (f32, f32)) {
4471        let layout = menu.layout(extent, &atlas());
4472        let track = layout.items()[1]
4473            .track
4474            .expect("the slider row has a groove");
4475        (track, handle_travel(track, layout.style().handle_size.x))
4476    }
4477
4478    /// **A slider is dragged, not clicked.** The handle follows the pointer's
4479    /// `x` while the press is held, which is the whole of the control.
4480    #[test]
4481    fn dragging_a_slider_moves_the_handle_to_the_pointer() {
4482        let extent = (960, 720);
4483        let mut menu = slider_menu();
4484        let mut ui = UiState::new();
4485        let (track, (start, end)) = groove(&menu, extent);
4486
4487        for (fraction, expected) in [(0.0, 0.0), (0.25, 0.25), (1.0, 1.0)] {
4488            let layout = menu.layout(extent, &atlas());
4489            let x = start + (end - start) * fraction;
4490            let y = (track.0.y + track.1.y) * 0.5;
4491            menu.point(&layout, &mut ui, press_at(Vec2::new(x, y)));
4492            let at = menu.slider(DIAL).expect("the row is a slider");
4493            assert!(
4494                (at - expected).abs() <= 1e-3,
4495                "a press {fraction} of the way along put the handle at {at}",
4496            );
4497        }
4498    }
4499
4500    /// **Past either end is the end, not a wrap and not a `NaN`.** A pointer
4501    /// dragged off the panel entirely is the ordinary way a player reaches the
4502    /// minimum, so the clamp is the feature.
4503    #[test]
4504    fn a_drag_past_either_end_of_the_groove_stops_there() {
4505        let extent = (960, 720);
4506        let mut menu = slider_menu();
4507        let mut ui = UiState::new();
4508        let (track, _) = groove(&menu, extent);
4509        let y = (track.0.y + track.1.y) * 0.5;
4510        let layout = menu.layout(extent, &atlas());
4511
4512        menu.point(&layout, &mut ui, press_at(Vec2::new(track.0.x, y)));
4513        menu.point(
4514            &layout,
4515            &mut ui,
4516            press_at(Vec2::new(track.0.x - 10_000.0, y)),
4517        );
4518        assert_eq!(menu.slider(DIAL), Some(0.0));
4519
4520        menu.point(
4521            &layout,
4522            &mut ui,
4523            press_at(Vec2::new(track.1.x + 10_000.0, y)),
4524        );
4525        assert_eq!(menu.slider(DIAL), Some(1.0));
4526    }
4527
4528    /// **A drag that leaves the row keeps the handle.** Unlike a button, whose
4529    /// press is abandoned when the cursor wanders off it: a player watching the
4530    /// frame behind the panel drags upward out of the row as a matter of course,
4531    /// and a slider that let go there would be unusable.
4532    #[test]
4533    fn a_drag_that_leaves_the_row_still_moves_the_handle() {
4534        let extent = (960, 720);
4535        let mut menu = slider_menu();
4536        let mut ui = UiState::new();
4537        let (track, (start, end)) = groove(&menu, extent);
4538        let layout = menu.layout(extent, &atlas());
4539
4540        let inside = Vec2::new(start, (track.0.y + track.1.y) * 0.5);
4541        menu.point(&layout, &mut ui, press_at(inside));
4542        assert_eq!(menu.slider(DIAL), Some(0.0));
4543
4544        // Three quarters along, and a long way above the panel.
4545        let outside = Vec2::new(start + (end - start) * 0.75, 0.0);
4546        menu.point(&layout, &mut ui, press_at(outside));
4547        let at = menu.slider(DIAL).expect("the row is a slider");
4548        assert!(
4549            (at - 0.75).abs() <= 1e-3,
4550            "the drag left the handle at {at}"
4551        );
4552    }
4553
4554    /// **A slider never reports an id**, from the commit key or from a release
4555    /// over it. Either would arrive at the game's action table looking exactly
4556    /// like a button press, and the game would run whatever that id means.
4557    #[test]
4558    fn a_slider_fires_nothing_from_either_device() {
4559        let extent = (960, 720);
4560        let mut menu = slider_menu();
4561        let mut ui = UiState::new();
4562
4563        menu.select_next();
4564        assert_eq!(menu.selected(), 1, "the slider is the second row");
4565        menu.press(true);
4566        assert_eq!(menu.activate(), None, "the commit key fired the slider");
4567
4568        let (track, _) = groove(&menu, extent);
4569        let at = Vec2::new((track.0.x + track.1.x) * 0.5, (track.0.y + track.1.y) * 0.5);
4570        let layout = menu.layout(extent, &atlas());
4571        menu.point(&layout, &mut ui, press_at(at));
4572        assert_eq!(
4573            menu.point(&layout, &mut ui, release_at(at)),
4574            None,
4575            "letting go of a slider was reported as a click",
4576        );
4577
4578        // And the button above it still does, so the suppression is the
4579        // slider's and not a menu that stopped firing altogether.
4580        menu.select_previous();
4581        assert_eq!(menu.activate(), Some(10));
4582    }
4583
4584    /// **The caller's write loses to the player's drag.** A game mirroring the
4585    /// value it read back into the handle every frame is the normal shape; if
4586    /// that write won, the handle would be pinned wherever the game last
4587    /// committed and the drag would go nowhere.
4588    #[test]
4589    fn a_write_is_refused_while_the_handle_is_held_and_taken_after() {
4590        let extent = (960, 720);
4591        let mut menu = slider_menu();
4592        let mut ui = UiState::new();
4593        let (track, _) = groove(&menu, extent);
4594        let y = (track.0.y + track.1.y) * 0.5;
4595        let layout = menu.layout(extent, &atlas());
4596
4597        assert!(menu.set_slider(DIAL, 0.25), "an untouched handle takes it");
4598        assert_eq!(menu.slider(DIAL), Some(0.25));
4599
4600        menu.point(&layout, &mut ui, press_at(Vec2::new(track.1.x, y)));
4601        assert_eq!(menu.slider(DIAL), Some(1.0));
4602        assert!(
4603            !menu.set_slider(DIAL, 0.25),
4604            "the write went through mid-drag",
4605        );
4606        assert_eq!(menu.slider(DIAL), Some(1.0));
4607
4608        menu.point(&layout, &mut ui, release_at(Vec2::new(track.1.x, y)));
4609        assert!(menu.set_slider(DIAL, 0.25), "the drag was never let go of");
4610        assert_eq!(menu.slider(DIAL), Some(0.25));
4611    }
4612
4613    /// A value neither the caller nor the pointer can name lands at the start of
4614    /// the groove, because `f32::clamp` would hand a `NaN` straight back.
4615    #[test]
4616    fn a_nan_position_lands_at_the_start() {
4617        let mut menu = slider_menu();
4618        assert!(menu.set_slider(DIAL, f32::NAN));
4619        assert_eq!(menu.slider(DIAL), Some(0.0));
4620        assert_eq!(Slider::new(f32::NAN).position(), 0.0);
4621        assert_eq!(Slider::new(f32::INFINITY).position(), 1.0);
4622    }
4623
4624    /// Asking a button row for a value, or a row that is not there, is `None`
4625    /// rather than a number the caller would act on.
4626    #[test]
4627    fn only_a_slider_row_has_a_value() {
4628        let mut menu = slider_menu();
4629        assert_eq!(menu.slider(10), None, "the button row reported a value");
4630        assert_eq!(menu.slider(999), None, "an absent row reported a value");
4631        assert!(!menu.set_slider(10, 0.5), "a button row took a value");
4632    }
4633
4634    /// **The keyboard moves the row the player can see is highlighted**, in
4635    /// both directions and by the step the constant names.
4636    #[test]
4637    fn a_key_moves_the_highlighted_slider_and_nothing_else() {
4638        let mut menu = slider_menu();
4639        // The button row is selected first, so a nudge has no slider to move.
4640        assert!(!menu.nudge_slider(true), "a button row took a nudge");
4641        assert_eq!(menu.slider(DIAL), Some(0.5), "the far row moved anyway");
4642
4643        menu.select_next();
4644        assert!(menu.nudge_slider(true), "the highlighted slider refused");
4645        assert_eq!(menu.slider(DIAL), Some(0.5 + Slider::KEY_STEP));
4646        assert!(menu.nudge_slider(false), "the slider refused to come back");
4647        assert_eq!(menu.slider(DIAL), Some(0.5));
4648    }
4649
4650    /// **The end of the groove is a place, and a key held against it stays
4651    /// there.** The return value is what tells the two apart: nothing moved.
4652    #[test]
4653    fn a_nudge_at_the_end_of_the_groove_moves_nothing() {
4654        let mut menu = slider_menu();
4655        menu.select_next();
4656        // Twenty steps is the whole groove from the middle twice over, so this
4657        // arrives at the end whatever `KEY_STEP` is set to.
4658        for _ in 0..(1.0 / Slider::KEY_STEP) as u32 + 1 {
4659            menu.nudge_slider(true);
4660        }
4661        assert_eq!(menu.slider(DIAL), Some(1.0), "the handle left the groove");
4662        assert!(
4663            !menu.nudge_slider(true),
4664            "a handle at the end reported that it moved"
4665        );
4666    }
4667
4668    /// **A drag is the newer input**, which is [`Menu::set_slider`]'s rule and
4669    /// applies to a key for the same reason: a keyboard repeat arriving while
4670    /// the player has the handle would fight the cursor for it.
4671    #[test]
4672    fn a_key_does_not_move_a_handle_the_pointer_is_holding() {
4673        let extent = (960, 720);
4674        let mut menu = slider_menu();
4675        let mut ui = UiState::new();
4676        let (track, _) = groove(&menu, extent);
4677        let middle = Vec2::new((track.0.x + track.1.x) * 0.5, (track.0.y + track.1.y) * 0.5);
4678        let layout = menu.layout(extent, &atlas());
4679
4680        menu.point(&layout, &mut ui, press_at(middle));
4681        let held = menu.slider(DIAL).expect("the row is a slider");
4682        assert!(!menu.nudge_slider(true), "a held handle took a key");
4683        assert_eq!(menu.slider(DIAL), Some(held), "the held handle moved");
4684
4685        // And it takes one again once the pointer lets go, from the position
4686        // the drag left it — not from the one the key would have written.
4687        menu.point(&layout, &mut ui, release_at(middle));
4688        assert!(
4689            menu.nudge_slider(false),
4690            "the released handle refused a key"
4691        );
4692        assert!(
4693            menu.slider(DIAL).expect("still a slider") < held,
4694            "the key moved it the wrong way, or not at all, from {held}"
4695        );
4696    }
4697
4698    /// **The groove is reserved, not squeezed in.** The panel grows by at least
4699    /// a groove and its gap over the same menu with a button in that row — a
4700    /// slider row that fitted in a button's width would have laid its groove
4701    /// over the label.
4702    #[test]
4703    fn a_slider_row_widens_the_panel_by_its_groove() {
4704        let atlas = atlas();
4705        let style = MenuStyle::pixel_art(1);
4706        let with_button = Menu::new(
4707            "OPTIONS",
4708            vec![
4709                MenuItem::new(10, "BACK", "ESC"),
4710                MenuItem::new(DIAL, "EXPOSURE", "1.00"),
4711            ],
4712        );
4713        let grew =
4714            slider_menu().panel_size(&atlas, &style).x - with_button.panel_size(&atlas, &style).x;
4715        assert!(
4716            grew >= style.track_width + style.hint_gap - 1e-3,
4717            "a slider row only widened the panel by {grew}",
4718        );
4719    }
4720
4721    /// **The groove sits between the label and the value, and the handle inside
4722    /// the groove — at both ends.** A handle centred on the groove's end would
4723    /// hang half of itself over the button's face, so nought and one would look
4724    /// like different amounts of overhang rather than like the two extremes.
4725    #[test]
4726    fn the_handle_stays_inside_the_groove_at_both_ends() {
4727        let extent = (960, 720);
4728        let atlas = atlas();
4729        for position in [0.0, 0.5, 1.0] {
4730            let mut menu = slider_menu();
4731            assert!(menu.set_slider(DIAL, position));
4732            let layout = menu.layout(extent, &atlas);
4733            let placed = layout.items()[1];
4734            let track = placed.track.expect("a groove");
4735
4736            let label_end = placed.label_pos.x + atlas.text_width("EXPOSURE", 1.0);
4737            assert!(
4738                track.0.x >= label_end && track.1.x <= placed.hint_pos.x,
4739                "at {position} the groove {track:?} overlaps the row's text",
4740            );
4741
4742            let mut dl = DrawList::new();
4743            menu.render(&mut dl, &layout, &skin());
4744            let handle = dl
4745                .commands()
4746                .iter()
4747                .filter_map(|command| match command {
4748                    DrawCommand::Rect { min, max, color }
4749                        if *color == layout.style().handle_color =>
4750                    {
4751                        Some((*min, *max))
4752                    }
4753                    _ => None,
4754                })
4755                .next()
4756                .expect("the handle is drawn");
4757            assert!(
4758                handle.0.x >= track.0.x - 1e-3 && handle.1.x <= track.1.x + 1e-3,
4759                "at {position} the handle {handle:?} left the groove {track:?}",
4760            );
4761        }
4762    }
4763
4764    /// The filled part of the groove is what says how far along the handle is
4765    /// without reading the number, so it has to actually track the value.
4766    #[test]
4767    fn the_fill_grows_with_the_value() {
4768        let extent = (960, 720);
4769        let atlas = atlas();
4770        let mut widths = Vec::new();
4771        for position in [0.0, 0.5, 1.0] {
4772            let mut menu = slider_menu();
4773            assert!(menu.set_slider(DIAL, position));
4774            let layout = menu.layout(extent, &atlas);
4775            let mut dl = DrawList::new();
4776            menu.render(&mut dl, &layout, &skin());
4777            let fill = dl
4778                .commands()
4779                .iter()
4780                .find_map(|command| match command {
4781                    DrawCommand::Rect { min, max, color }
4782                        if *color == layout.style().fill_color =>
4783                    {
4784                        Some(max.x - min.x)
4785                    }
4786                    _ => None,
4787                })
4788                .expect("the fill is drawn");
4789            widths.push(fill);
4790        }
4791        assert!(
4792            widths[0] < widths[1] && widths[1] < widths[2],
4793            "the fill widths were {widths:?}",
4794        );
4795    }
4796    // -----------------------------------------------------------------------
4797    // Cyclers
4798    // -----------------------------------------------------------------------
4799
4800    /// The id of the cycler row in [`cycler_menu`].
4801    const MODE: WidgetId = 30;
4802
4803    /// The captions the cycler row in [`cycler_menu`] walks, in order — the
4804    /// caller's list, which the widget never sees.
4805    const MODES: [&str; 3] = ["windowed", "borderless", "exclusive"];
4806
4807    /// A panel whose second row is a cycler holding the middle of three
4808    /// choices, with a button above it for the same reason [`slider_menu`]
4809    /// has one.
4810    fn cycler_menu() -> Menu {
4811        Menu::new(
4812            "OPTIONS",
4813            vec![
4814                MenuItem::new(10, "BACK", "ESC"),
4815                MenuItem::cycler(MODE, "DISPLAY", MODES[1], MODES.len(), 1),
4816            ],
4817        )
4818    }
4819
4820    /// **The arrows walk the list and stop at its ends.** The return value is
4821    /// what tells a step from a key held against the end, exactly as
4822    /// [`Menu::nudge_slider`] reports the end of a groove — and a button row
4823    /// under the highlight takes no step at all.
4824    #[test]
4825    fn a_key_steps_the_highlighted_cycler_and_stops_at_its_ends() {
4826        let mut menu = cycler_menu();
4827        assert!(
4828            !menu.cycler_highlighted(),
4829            "the button row read as a cycler"
4830        );
4831        assert!(!menu.nudge_cycler(true), "a button row took a step");
4832        assert_eq!(menu.cycler(MODE), Some(1), "the far row stepped anyway");
4833
4834        menu.select_next();
4835        assert!(menu.cycler_highlighted());
4836        assert!(menu.nudge_cycler(true), "the highlighted cycler refused");
4837        assert_eq!(menu.cycler(MODE), Some(2));
4838        assert!(
4839            !menu.nudge_cycler(true),
4840            "the last choice reported a step forward"
4841        );
4842        assert_eq!(menu.cycler(MODE), Some(2), "a key at the end went round");
4843
4844        assert!(menu.nudge_cycler(false));
4845        assert!(menu.nudge_cycler(false));
4846        assert_eq!(menu.cycler(MODE), Some(0));
4847        assert!(
4848            !menu.nudge_cycler(false),
4849            "the first choice reported a step back"
4850        );
4851        assert_eq!(menu.cycler(MODE), Some(0), "a key at the start went round");
4852    }
4853
4854    /// **The commit key and a click step a cycler forward and round, and
4855    /// neither reports an id.** One key reaches every choice, which is what
4856    /// the row did when it was a button; and nothing from it arrives at the
4857    /// game's action table, which is the slider's rule for the same reason.
4858    #[test]
4859    fn the_commit_key_and_a_click_step_a_cycler_round_and_report_nothing() {
4860        let extent = (960, 720);
4861        let mut menu = cycler_menu();
4862        let mut ui = UiState::new();
4863
4864        menu.select_next();
4865        menu.press(true);
4866        assert_eq!(menu.activate(), None, "the commit key fired the cycler");
4867        assert_eq!(menu.cycler(MODE), Some(2));
4868        assert_eq!(menu.activate(), None);
4869        assert_eq!(
4870            menu.cycler(MODE),
4871            Some(0),
4872            "the commit key stopped at the end"
4873        );
4874
4875        let layout = menu.layout(extent, &atlas());
4876        let row = layout.items()[1];
4877        let at = (row.min + row.max) * 0.5;
4878        menu.point(&layout, &mut ui, press_at(at));
4879        assert_eq!(
4880            menu.point(&layout, &mut ui, release_at(at)),
4881            None,
4882            "a click on a cycler was reported as a click",
4883        );
4884        assert_eq!(menu.cycler(MODE), Some(1), "the click did not step it");
4885
4886        // And the button above it still fires, so the suppression is the
4887        // cycler's and not a menu that stopped firing altogether.
4888        menu.select_previous();
4889        assert_eq!(menu.activate(), Some(10));
4890    }
4891
4892    /// Asking a button row for a choice, or a row that is not there, is `None`
4893    /// rather than an index the caller would look up; a write past the end
4894    /// lands on the last choice, and a write to a button row is refused.
4895    #[test]
4896    fn only_a_cycler_row_has_a_choice() {
4897        let mut menu = cycler_menu();
4898        assert_eq!(menu.cycler(10), None, "the button row reported a choice");
4899        assert_eq!(menu.cycler(999), None, "an absent row reported a choice");
4900        assert!(!menu.set_cycler(10, 1), "a button row took a choice");
4901        assert!(menu.set_cycler(MODE, 99));
4902        assert_eq!(menu.cycler(MODE), Some(MODES.len() - 1));
4903        assert!(menu.set_cycler(MODE, 0));
4904        assert_eq!(menu.cycler(MODE), Some(0));
4905    }
4906
4907    /// **A chevron is drawn only on the side a step would go, and the caption
4908    /// does not move as they come and go.** The blank that stands in for a
4909    /// missing chevron is the same width, which the built-in atlas's uniform
4910    /// advance guarantees and this checks rather than assumes — with one
4911    /// caption for every choice, so the only thing that changes between the
4912    /// three layouts is the chevrons.
4913    #[test]
4914    fn a_cycler_draws_a_chevron_only_where_a_step_would_go() {
4915        let atlas = atlas();
4916        let extent = (960, 720);
4917        let mut menu = cycler_menu();
4918        assert!(menu.set_item_hint(MODE, "same"));
4919        let mut seen = Vec::new();
4920        for (chosen, expected) in [(1, "< same >"), (0, "  same >"), (2, "< same  ")] {
4921            assert!(menu.set_cycler(MODE, chosen));
4922            let layout = menu.layout(extent, &atlas);
4923            let row = layout.items()[1];
4924            assert!(row.track.is_none(), "a cycler row was given a groove");
4925            let mut dl = DrawList::new();
4926            menu.render(&mut dl, &layout, &skin());
4927            let texts: Vec<&str> = dl
4928                .commands()
4929                .iter()
4930                .filter_map(|command| match command {
4931                    DrawCommand::Text { text, .. } => Some(text.as_str()),
4932                    _ => None,
4933                })
4934                .collect();
4935            assert!(
4936                texts.contains(&expected),
4937                "choice {chosen} drew {texts:?}, not {expected:?}"
4938            );
4939            seen.push((row.hint_pos, layout.panel_size()));
4940        }
4941        let (anchor, panel) = seen[0];
4942        for (pos, size) in &seen[1..] {
4943            assert_eq!(*pos, anchor, "the caption moved as the chevrons changed");
4944            assert_eq!(*size, panel, "the panel resized as the chevrons changed");
4945        }
4946    }
4947
4948    /// A cycler with no choices has nothing to step to and says so from both
4949    /// keys, rather than wrapping through a division by nothing; and a choice
4950    /// past the end lands on the last one.
4951    #[test]
4952    fn a_cycler_with_no_choices_refuses_every_step() {
4953        let mut empty = Cycler::new(0, 3);
4954        assert_eq!(empty.chosen(), 0);
4955        for (forward, wrap) in [(true, true), (true, false), (false, true), (false, false)] {
4956            assert!(!empty.step(forward, wrap), "an empty cycler stepped");
4957        }
4958        assert_eq!(Cycler::new(3, 9).chosen(), 2);
4959
4960        let mut round = Cycler::new(3, 2);
4961        assert!(round.step(true, true), "a wrap from the end did not move");
4962        assert_eq!(round.chosen(), 0);
4963        assert!(round.step(false, true));
4964        assert_eq!(round.chosen(), 2);
4965        assert!(!round.step(true, false));
4966        assert_eq!(round.chosen(), 2);
4967    }
4968
4969    // -----------------------------------------------------------------------
4970    // The tree and the sheet
4971    // -----------------------------------------------------------------------
4972
4973    /// **The panel's size is the scale-1 panel times the scale, exactly**, for
4974    /// every kind of row — the property [`Menu::layout`]'s one-measurement fit
4975    /// rests on. A length that stopped being a whole number times the scale,
4976    /// or a rounding that stopped being exact, fails here rather than as a
4977    /// menu that silently picks the wrong scale.
4978    #[test]
4979    fn the_panel_grows_exactly_with_the_scale() {
4980        let atlas = atlas();
4981        let mut mixed = slider_menu();
4982        mixed
4983            .items
4984            .push(MenuItem::cycler(MODE, "DISPLAY", "windowed", 3, 1));
4985        mixed.items.push(MenuItem::new(40, "NO HINT", ""));
4986        for menu in [pause_menu(), mixed, Menu::new("", Vec::new())] {
4987            let base = menu.panel_size(&atlas, &MenuStyle::pixel_art(1));
4988            assert!(base.x > 0.0 && base.y > 0.0, "{base:?}");
4989            for scale in 2..=MenuStyle::MAX_SCALE {
4990                assert_eq!(
4991                    menu.panel_size(&atlas, &MenuStyle::pixel_art(scale)),
4992                    base * scale as f32,
4993                    "{:?} at scale {scale}",
4994                    menu.title,
4995                );
4996            }
4997        }
4998    }
4999
5000    /// **`default.css` draws the colours [`MenuStyle::pixel_art`] restates,
5001    /// and cuts the frames at the insets the layout assumes** — the two
5002    /// places a sheet and the style could drift apart without a layout test
5003    /// noticing.
5004    #[test]
5005    fn the_sheet_draws_the_colours_and_the_slices_the_style_restates() {
5006        let atlas = atlas();
5007        let skin = skin();
5008        let mut menu = slider_menu();
5009        menu.items.push(MenuItem::new(11, "QUIT", "Q"));
5010        menu.subtitle = vec![Caption::warning("UNSAVED")];
5011        let layout = menu.layout((960, 720), &atlas);
5012        let style = layout.style();
5013        let mut dl = DrawList::new();
5014        menu.render(&mut dl, &layout, &skin);
5015
5016        let text_colour = |wanted: &str| {
5017            dl.commands()
5018                .iter()
5019                .find_map(|command| match command {
5020                    DrawCommand::Text { text, color, .. } if text == wanted => Some(*color),
5021                    _ => None,
5022                })
5023                .unwrap_or_else(|| panic!("{wanted} is not drawn"))
5024        };
5025        assert_eq!(text_colour("OPTIONS"), style.title_color);
5026        assert_eq!(text_colour("BACK"), style.label_color);
5027        assert_eq!(text_colour("ESC"), style.hint_color);
5028        assert_eq!(text_colour("UNSAVED"), style.warning_color);
5029        let rect_colours: Vec<[f32; 4]> = dl
5030            .commands()
5031            .iter()
5032            .filter_map(|command| match command {
5033                DrawCommand::Rect { color, .. } => Some(*color),
5034                _ => None,
5035            })
5036            .collect();
5037        assert_eq!(
5038            rect_colours,
5039            [style.track_color, style.fill_color, style.handle_color],
5040            "the groove, its fill and the handle, in that order"
5041        );
5042        let DrawCommand::Image { tint, .. } = dl.commands()[0] else {
5043            panic!("the scrim is not first");
5044        };
5045        assert_eq!(tint, style.scrim_color);
5046
5047        let corner_uvs = |min: usize| {
5048            let DrawCommand::Image { uv_min, uv_max, .. } = pictures_with_uv_max(&dl)[min] else {
5049                unreachable!("filtered to images");
5050            };
5051            (uv_min, uv_max)
5052        };
5053        assert_eq!(
5054            corner_uvs(1),
5055            (
5056                skin.panel.image.uv(Vec2::ZERO),
5057                skin.panel
5058                    .image
5059                    .uv(Vec2::new(PANEL_INSETS.left, PANEL_INSETS.top))
5060            ),
5061            "the panel is not cut at PANEL_INSETS"
5062        );
5063        // Row 0 is selected, so it draws the hovered frame; row 1 is idle.
5064        assert_eq!(
5065            corner_uvs(10),
5066            (
5067                skin.buttons.hovered.image.uv(Vec2::ZERO),
5068                skin.buttons
5069                    .hovered
5070                    .image
5071                    .uv(Vec2::new(BUTTON_INSETS.left, BUTTON_INSETS.top))
5072            ),
5073            "the buttons are not cut at BUTTON_INSETS"
5074        );
5075        assert_eq!(
5076            corner_uvs(19).0,
5077            skin.buttons.idle.image.uv(Vec2::ZERO),
5078            "an idle row does not draw the idle frame"
5079        );
5080    }
5081
5082    /// Every `Image` command of `dl`, whole.
5083    fn pictures_with_uv_max(dl: &DrawList) -> Vec<DrawCommand> {
5084        dl.commands()
5085            .iter()
5086            .filter(|command| matches!(command, DrawCommand::Image { .. }))
5087            .cloned()
5088            .collect()
5089    }
5090}