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