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