use std::ops::Range;
use glam::Vec2;
use crate::draw_list::{DrawCommand, DrawList};
use crate::font::Font;
use crate::image::{AtlasImage, NineSliceImage};
use crate::style::{Declaration, PseudoClasses, Sides};
use crate::text::FontAtlas;
#[cfg(test)]
use crate::text::LINE_HEIGHT;
use crate::tree::{
AvailableSpace, FamilyName, Length, LengthAuto, LineHeight, NodeKey, Overflow, Ui,
};
use crate::widget::{
ButtonSkin, ButtonState, NATURAL_FONT_SIZE, PointerInput, SkinInsets, UiState, WidgetId,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MenuSkin {
pub panel: NineSliceImage,
pub buttons: ButtonSkin,
pub scrim: AtlasImage,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MenuStyle {
pub scale: f32,
pub panel: SkinInsets,
pub button: SkinInsets,
pub panel_padding: Vec2,
pub button_padding: Vec2,
pub item_gap: f32,
pub title_gap: f32,
pub title_size: f32,
pub item_size: f32,
pub hint_gap: f32,
pub track_width: f32,
pub track_height: f32,
pub handle_size: Vec2,
pub title_color: [f32; 4],
pub label_color: [f32; 4],
pub hint_color: [f32; 4],
pub warning_color: [f32; 4],
pub track_color: [f32; 4],
pub fill_color: [f32; 4],
pub handle_color: [f32; 4],
pub scrim_color: [f32; 4],
}
pub const PANEL_INSETS: SkinInsets = SkinInsets::new(4.0, 4.0, 4.0, 4.0);
pub const BUTTON_INSETS: SkinInsets = SkinInsets::new(4.0, 4.0, 4.0, 4.0);
impl MenuStyle {
pub const MAX_SCALE: u32 = 4;
pub const MIN_FONT_SIZE: f32 = 8.0;
#[must_use]
pub fn pixel_art(scale: u32) -> Self {
let scale = scale.max(1) as f32;
Self {
scale,
panel: scaled(PANEL_INSETS, scale),
button: scaled(BUTTON_INSETS, scale),
panel_padding: Vec2::new(8.0, 7.0) * scale,
button_padding: Vec2::new(6.0, 3.0) * scale,
item_gap: 4.0 * scale,
title_gap: 8.0 * scale,
title_size: NATURAL_FONT_SIZE * 2.0 * scale,
item_size: NATURAL_FONT_SIZE * scale,
hint_gap: 10.0 * scale,
track_width: 48.0 * scale,
track_height: 4.0 * scale,
handle_size: Vec2::new(6.0, 12.0) * scale,
title_color: [1.0, 0.94, 0.55, 1.0],
label_color: [0.94, 0.95, 1.0, 1.0],
hint_color: [0.62, 0.64, 0.82, 1.0],
warning_color: [1.0, 0.78, 0.35, 1.0],
track_color: [0.10, 0.11, 0.18, 1.0],
fill_color: [0.42, 0.46, 0.72, 1.0],
handle_color: [0.94, 0.95, 1.0, 1.0],
scrim_color: [0.0, 0.0, 0.0, 0.66],
}
}
fn shrunk(&self, item_size: f32) -> Self {
let factor = item_size / self.item_size;
let whole = |length: f32| (length * factor).round();
let art = (self.scale * factor).floor().max(1.0);
let corners = |insets: SkinInsets| {
let texels = |length: f32| (length / self.scale * art).round();
SkinInsets::new(
texels(insets.left),
texels(insets.right),
texels(insets.top),
texels(insets.bottom),
)
};
Self {
scale: art,
panel: corners(self.panel),
button: corners(self.button),
panel_padding: Vec2::new(whole(self.panel_padding.x), whole(self.panel_padding.y)),
button_padding: Vec2::new(whole(self.button_padding.x), whole(self.button_padding.y)),
item_gap: whole(self.item_gap),
title_gap: whole(self.title_gap),
title_size: self.title_size * factor,
item_size,
hint_gap: whole(self.hint_gap),
track_width: whole(self.track_width),
track_height: whole(self.track_height),
handle_size: Vec2::new(whole(self.handle_size.x), whole(self.handle_size.y)),
..*self
}
}
#[must_use]
pub fn panel_corners(&self) -> SkinInsets {
self.panel
}
#[must_use]
pub fn button_corners(&self) -> SkinInsets {
self.button
}
}
fn scaled(insets: SkinInsets, scale: f32) -> SkinInsets {
SkinInsets::new(
insets.left * scale,
insets.right * scale,
insets.top * scale,
insets.bottom * scale,
)
}
impl Default for MenuStyle {
fn default() -> Self {
Self::pixel_art(1)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Slider {
position: f32,
}
impl Slider {
pub const KEY_STEP: f32 = 0.05;
#[must_use]
pub fn new(position: f32) -> Self {
Self {
position: clamp_unit(position),
}
}
#[must_use]
pub const fn position(&self) -> f32 {
self.position
}
pub fn set_position(&mut self, position: f32) {
self.position = clamp_unit(position);
}
}
fn clamp_unit(position: f32) -> f32 {
if position.is_nan() {
0.0
} else {
position.clamp(0.0, 1.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cycler {
chosen: usize,
count: usize,
}
impl Cycler {
#[must_use]
pub fn new(count: usize, chosen: usize) -> Self {
let mut cycler = Self { chosen: 0, count };
cycler.choose(chosen);
cycler
}
#[must_use]
pub const fn count(&self) -> usize {
self.count
}
#[must_use]
pub const fn chosen(&self) -> usize {
self.chosen
}
pub fn choose(&mut self, index: usize) {
self.chosen = index.min(self.count.saturating_sub(1));
}
pub fn step(&mut self, forward: bool, wrap: bool) -> bool {
if self.count == 0 {
return false;
}
let last = self.count - 1;
let next = match (forward, wrap) {
(true, _) if self.chosen < last => self.chosen + 1,
(true, true) => 0,
(false, _) if self.chosen > 0 => self.chosen - 1,
(false, true) => last,
_ => return false,
};
let moved = next != self.chosen;
self.chosen = next;
moved
}
#[must_use]
pub const fn can_step(&self, forward: bool) -> bool {
if forward {
self.chosen + 1 < self.count
} else {
self.chosen > 0
}
}
}
const BACK_CHEVRON: &str = "< ";
const FORWARD_CHEVRON: &str = " >";
const NO_CHEVRON: &str = " ";
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MenuItemKind {
Action,
Slider(Slider),
Cycler(Cycler),
}
#[derive(Debug, Clone, PartialEq)]
pub struct MenuItem {
pub id: WidgetId,
pub label: String,
pub hint: String,
pub kind: MenuItemKind,
}
impl MenuItem {
#[must_use]
pub fn new(id: WidgetId, label: impl Into<String>, hint: impl Into<String>) -> Self {
Self {
id,
label: label.into(),
hint: hint.into(),
kind: MenuItemKind::Action,
}
}
#[must_use]
pub fn slider(
id: WidgetId,
label: impl Into<String>,
value: impl Into<String>,
position: f32,
) -> Self {
Self {
id,
label: label.into(),
hint: value.into(),
kind: MenuItemKind::Slider(Slider::new(position)),
}
}
#[must_use]
pub fn cycler(
id: WidgetId,
label: impl Into<String>,
caption: impl Into<String>,
count: usize,
chosen: usize,
) -> Self {
Self {
id,
label: label.into(),
hint: caption.into(),
kind: MenuItemKind::Cycler(Cycler::new(count, chosen)),
}
}
#[must_use]
pub fn caption(&self) -> std::borrow::Cow<'_, str> {
match self.kind {
MenuItemKind::Cycler(cycler) => {
let chevron = |forward: bool, chevron: &'static str| {
if cycler.can_step(forward) {
chevron
} else {
NO_CHEVRON
}
};
std::borrow::Cow::Owned(format!(
"{}{}{}",
chevron(false, BACK_CHEVRON),
self.hint,
chevron(true, FORWARD_CHEVRON)
))
}
MenuItemKind::Action | MenuItemKind::Slider(_) => {
std::borrow::Cow::Borrowed(self.hint.as_str())
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CaptionTone {
#[default]
Hint,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Caption {
pub text: String,
pub tone: CaptionTone,
}
impl Caption {
#[must_use]
pub fn hint(text: impl Into<String>) -> Self {
Self {
text: text.into(),
tone: CaptionTone::Hint,
}
}
#[must_use]
pub fn warning(text: impl Into<String>) -> Self {
Self {
text: text.into(),
tone: CaptionTone::Warning,
}
}
}
impl From<&str> for Caption {
fn from(text: &str) -> Self {
Self::hint(text)
}
}
impl From<String> for Caption {
fn from(text: String) -> Self {
Self::hint(text)
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Menu {
pub title: String,
pub subtitle: Vec<Caption>,
items: Vec<MenuItem>,
selected: usize,
pressed: bool,
pressed_index: Option<usize>,
hovered: Option<usize>,
dragging: Option<usize>,
scroll: f32,
follow_selection: bool,
}
impl Menu {
#[must_use]
pub fn new(title: impl Into<String>, items: Vec<MenuItem>) -> Self {
Self {
title: title.into(),
subtitle: Vec::new(),
items,
selected: 0,
pressed: false,
pressed_index: None,
hovered: None,
dragging: None,
scroll: 0.0,
follow_selection: true,
}
}
#[must_use]
pub fn items(&self) -> &[MenuItem] {
&self.items
}
#[must_use]
pub const fn selected(&self) -> usize {
self.selected
}
#[must_use]
pub fn selected_item(&self) -> Option<&MenuItem> {
self.items.get(self.selected)
}
pub fn select_next(&mut self) {
self.move_selection(1);
}
pub fn select_previous(&mut self) {
self.move_selection(-1);
}
fn move_selection(&mut self, delta: isize) {
if self.items.is_empty() {
return;
}
let len = self.items.len() as isize;
let next = (self.selected as isize + delta).rem_euclid(len);
self.selected = next as usize;
self.follow_selection = true;
self.hovered = None;
self.pressed = false;
self.pressed_index = None;
self.dragging = None;
}
pub fn select_id(&mut self, id: WidgetId) -> bool {
match self.items.iter().position(|item| item.id == id) {
Some(index) => {
self.selected = index;
self.hovered = None;
self.follow_selection = true;
true
}
None => false,
}
}
pub const fn press(&mut self, down: bool) {
self.pressed = down;
self.pressed_index = if down { Some(self.selected) } else { None };
}
pub fn activate(&mut self) -> Option<WidgetId> {
self.pressed = false;
self.pressed_index = None;
let index = self.hovered.unwrap_or(self.selected);
match self.items.get_mut(index) {
Some(item) => match &mut item.kind {
MenuItemKind::Action => Some(item.id),
MenuItemKind::Cycler(cycler) => {
cycler.step(true, true);
None
}
MenuItemKind::Slider(_) => None,
},
None => None,
}
}
pub const fn clear_input(&mut self) {
self.hovered = None;
self.pressed = false;
self.pressed_index = None;
self.dragging = None;
}
#[must_use]
pub fn slider(&self, id: WidgetId) -> Option<f32> {
self.items.iter().find_map(|item| match item.kind {
MenuItemKind::Slider(slider) if item.id == id => Some(slider.position()),
_ => None,
})
}
pub fn set_slider(&mut self, id: WidgetId, position: f32) -> bool {
let dragging = self.dragging;
for (index, item) in self.items.iter_mut().enumerate() {
if item.id != id {
continue;
}
let MenuItemKind::Slider(slider) = &mut item.kind else {
return false;
};
if dragging == Some(index) {
return false;
}
slider.set_position(position);
return true;
}
false
}
pub fn nudge_slider(&mut self, forward: bool) -> bool {
let index = self.hovered.unwrap_or(self.selected);
if self.dragging == Some(index) {
return false;
}
let Some(item) = self.items.get_mut(index) else {
return false;
};
let MenuItemKind::Slider(slider) = &mut item.kind else {
return false;
};
let before = slider.position();
slider.set_position(if forward {
before + Slider::KEY_STEP
} else {
before - Slider::KEY_STEP
});
slider.position() != before
}
#[must_use]
pub fn slider_highlighted(&self) -> bool {
matches!(
self.items.get(self.hovered.unwrap_or(self.selected)),
Some(item) if matches!(item.kind, MenuItemKind::Slider(_))
)
}
#[must_use]
pub fn cycler(&self, id: WidgetId) -> Option<usize> {
self.items.iter().find_map(|item| match item.kind {
MenuItemKind::Cycler(cycler) if item.id == id => Some(cycler.chosen()),
_ => None,
})
}
pub fn set_cycler(&mut self, id: WidgetId, chosen: usize) -> bool {
self.items
.iter_mut()
.find(|item| item.id == id)
.is_some_and(|item| match &mut item.kind {
MenuItemKind::Cycler(cycler) => {
cycler.choose(chosen);
true
}
_ => false,
})
}
pub fn nudge_cycler(&mut self, forward: bool) -> bool {
let index = self.hovered.unwrap_or(self.selected);
match self.items.get_mut(index).map(|item| &mut item.kind) {
Some(MenuItemKind::Cycler(cycler)) => cycler.step(forward, false),
_ => false,
}
}
#[must_use]
pub fn cycler_highlighted(&self) -> bool {
matches!(
self.items.get(self.hovered.unwrap_or(self.selected)),
Some(item) if matches!(item.kind, MenuItemKind::Cycler(_))
)
}
pub fn set_item_hint(&mut self, id: WidgetId, hint: impl Into<String>) -> bool {
match self.items.iter_mut().find(|item| item.id == id) {
Some(item) => {
item.hint = hint.into();
true
}
None => false,
}
}
#[must_use]
pub fn state(&self, index: usize) -> ButtonState {
if index >= self.items.len() || index != self.hovered.unwrap_or(self.selected) {
return ButtonState::Idle;
}
if self.pressed_index == Some(index) {
ButtonState::Pressed
} else if self.pressed {
ButtonState::Idle
} else {
ButtonState::Hovered
}
}
pub fn point(
&mut self,
layout: &MenuLayout,
ui: &mut UiState,
pointer: PointerInput,
) -> Option<WidgetId> {
if self.follow_selection {
self.scroll = layout.scroll();
}
let in_view = layout
.viewport()
.is_none_or(|viewport| contains(viewport, pointer.pos));
let mut clicked = None;
let mut hovered = None;
for (index, item) in layout.items.iter().enumerate() {
let inside =
in_view && layout.shows(index) && contains((item.min, item.max), pointer.pos);
let (state, fired) = ui.interact(item.id, inside, pointer.down, pointer.released);
if inside {
hovered = Some(index);
}
let is_slider = matches!(
self.items.get(index).map(|item| item.kind),
Some(MenuItemKind::Slider(_))
);
if state == ButtonState::Pressed && is_slider {
if let Some(track) = item.track
&& let Some(MenuItemKind::Slider(slider)) =
self.items.get_mut(index).map(|item| &mut item.kind)
{
slider.set_position(position_along(
track,
layout.style.handle_size.x,
pointer.pos.x,
));
}
self.dragging = Some(index);
self.pressed = true;
self.pressed_index = Some(index);
self.selected = index;
} else if state == ButtonState::Pressed && inside {
self.pressed = true;
self.pressed_index = Some(index);
}
if fired {
match self.items.get_mut(index).map(|item| &mut item.kind) {
Some(MenuItemKind::Action) => {
clicked = Some(item.id);
self.selected = index;
}
Some(MenuItemKind::Cycler(cycler)) => {
cycler.step(true, true);
self.selected = index;
}
_ => {}
}
}
}
self.hovered = hovered;
if !pointer.down {
self.pressed = false;
self.pressed_index = None;
self.dragging = None;
}
clicked
}
pub fn scroll_wheel(&mut self, layout: &MenuLayout, pointer: Vec2, delta: Vec2) -> bool {
let Some(list) = &layout.setup.list else {
return false;
};
if !contains(layout.panel, pointer) {
return false;
}
let from = if self.follow_selection {
list.scroll
} else {
self.scroll.clamp(0.0, list.reach)
};
let to = (from + delta.y).clamp(0.0, list.reach);
self.follow_selection = false;
self.scroll = to;
to != from
}
#[must_use]
pub fn layout(&self, extent: (u32, u32), atlas: &FontAtlas) -> MenuLayout {
let base = self.panel_size(atlas, &MenuStyle::pixel_art(1));
let mut chosen = 1;
for scale in 2..=MenuStyle::MAX_SCALE {
let size = base * scale as f32;
if size.x <= extent.0 as f32 * FIT_FRACTION && size.y <= extent.1 as f32 * FIT_FRACTION
{
chosen = scale;
} else {
break;
}
}
self.layout_with(extent, atlas, &MenuStyle::pixel_art(chosen))
}
#[must_use]
pub fn layout_with(
&self,
extent: (u32, u32),
atlas: &FontAtlas,
style: &MenuStyle,
) -> MenuLayout {
let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
let setup = Setup::default();
self.laid_out(Some(screen), style, None, &setup, atlas, |ui, built| {
Self::read_layout(ui, built, &self.items, screen, style, &setup)
})
}
#[must_use]
pub fn layout_with_font(
&self,
extent: (u32, u32),
style: &MenuStyle,
font: &Font,
) -> MenuLayout {
let setup = Setup {
font: Some(font.clone()),
..Setup::default()
};
self.placed(extent_size(extent), style, &setup)
}
pub fn layout_with_font_fitted(
&self,
extent: (u32, u32),
style: &MenuStyle,
font: &Font,
) -> Result<MenuLayout, MenuFitError> {
let screen = extent_size(extent);
let room = screen * FIT_FRACTION;
let sizes = fit_sizes(style.item_size);
let measure = |item_size: f32| {
let style = style.shrunk(item_size);
let setup = Setup {
font: Some(font.clone()),
line: Some(row_line(font, &style)),
list: None,
};
let measured = self.measure(&style, &setup);
Candidate {
style,
setup,
measured,
}
};
let fits = |candidate: &Candidate| {
let panel = candidate.measured.panel;
panel.x <= room.x && panel.y <= room.y
};
let mut fitting = measure(sizes[0]);
if !fits(&fitting) {
let last = sizes.len() - 1;
let smallest = if last == 0 {
fitting
} else {
measure(sizes[last])
};
if !fits(&smallest) {
return self.scrolled(screen, room, smallest);
}
fitting = smallest;
let (mut lo, mut hi) = (0, last);
while hi - lo > 1 {
let mid = (lo + hi) / 2;
let candidate = measure(sizes[mid]);
if fits(&candidate) {
hi = mid;
fitting = candidate;
} else {
lo = mid;
}
}
}
Ok(self.placed(screen, &fitting.style, &fitting.setup))
}
fn scrolled(
&self,
screen: Vec2,
room: Vec2,
candidate: Candidate,
) -> Result<MenuLayout, MenuFitError> {
let Candidate {
style,
setup,
measured,
} = candidate;
let font_size = style.item_size;
if measured.panel.x > room.x {
return Err(MenuFitError::TooWide {
font_size,
width: measured.panel.x,
room: room.x,
});
}
let chrome = measured.panel.y - measured.list.y;
let mut height = (room.y - chrome).floor();
loop {
if self.items.is_empty() || height < measured.tallest {
return Err(MenuFitError::TooShort {
font_size,
height: chrome + measured.tallest,
room: room.y,
});
}
let list = ListView {
size: Vec2::new(measured.list.x, height),
viewport: (Vec2::ZERO, Vec2::ZERO),
scroll: 0.0,
reach: 0.0,
shown: 0..self.items.len(),
shown_top: 0.0,
};
let setup = Setup {
list: Some(list),
..setup.clone()
};
let layout = self.placed(screen, &style, &setup);
let over = layout.panel_size().y - room.y;
if over <= 0.0 {
return Ok(self.scroll_list(layout));
}
height -= over.ceil();
}
}
fn scroll_list(&self, mut layout: MenuLayout) -> MenuLayout {
let list = layout
.setup
.list
.as_mut()
.expect("a scrolled layout has a list");
let (top, bottom) = (list.viewport.0.y, list.viewport.1.y);
let height = bottom - top;
let end = layout.items.last().map_or(top, |row| row.max.y);
list.reach = (end - top - height).max(0.0);
let mut scroll = self.scroll.round().clamp(0.0, list.reach);
if self.follow_selection
&& let Some(row) = layout.items.get(self.selected)
{
let (row_top, row_bottom) = (row.min.y - top, row.max.y - top);
if row_top < scroll {
scroll = row_top;
} else if row_bottom > scroll + height {
scroll = row_bottom - height;
}
}
let scroll = scroll.clamp(0.0, list.reach);
list.scroll = scroll;
let up = Vec2::new(0.0, scroll);
for row in &mut layout.items {
row.min -= up;
row.max -= up;
row.label_pos -= up;
row.hint_pos -= up;
if let Some(track) = &mut row.track {
track.0 -= up;
track.1 -= up;
}
}
let rows = &layout.items;
let first = rows
.iter()
.position(|row| row.max.y > top)
.unwrap_or(rows.len());
let past = rows
.iter()
.rposition(|row| row.min.y < bottom)
.map_or(first, |last| (last + 1).max(first));
list.shown = first..past;
list.shown_top = rows.get(first).map_or(0.0, |row| row.min.y + scroll - top);
layout
}
fn placed(&self, screen: Vec2, style: &MenuStyle, setup: &Setup) -> MenuLayout {
self.laid_out(
Some(screen),
style,
None,
setup,
&FontAtlas::built_in(),
|ui, built| Self::read_layout(ui, built, &self.items, screen, style, setup),
)
}
fn measure(&self, style: &MenuStyle, setup: &Setup) -> Measured {
self.laid_out(
None,
style,
None,
setup,
&FontAtlas::built_in(),
|ui, built| {
let size = |key| {
let (min, max) = ui.rect(key).expect("laid out this frame");
max - min
};
Measured {
panel: size(built.panel),
list: size(built.items),
tallest: built
.rows
.iter()
.map(|row| size(row.row).y)
.fold(0.0, f32::max),
}
},
)
}
fn read_layout(
ui: &Ui,
built: &BuiltMenu,
items: &[MenuItem],
screen: Vec2,
style: &MenuStyle,
setup: &Setup,
) -> MenuLayout {
let rect = |key| ui.rect(key).expect("laid out this frame");
let panel = rect(built.panel);
let corners = style.panel_corners();
let content_min = panel.0 + corners.min_corner() + style.panel_padding;
let content_max = panel.1 - Vec2::new(corners.right, corners.bottom) - style.panel_padding;
let title_pos = built.title.map_or(
Vec2::new((content_min.x + content_max.x) * 0.5, content_min.y),
|key| rect(key).0,
);
let items = items
.iter()
.zip(&built.rows)
.map(|(item, row)| {
let (min, max) = rect(row.row);
let label_pos = rect(row.label).0;
let inner = style.button_corners();
let hint_pos = row.hint.map_or(
Vec2::new(max.x - inner.right - style.button_padding.x, label_pos.y),
|key| rect(key).0,
);
MenuItemLayout {
id: item.id,
min,
max,
label_pos,
hint_pos,
track: row.groove.map(rect),
}
})
.collect();
let mut setup = setup.clone();
if let Some(list) = &mut setup.list {
list.viewport = rect(built.items);
}
MenuLayout {
style: *style,
setup,
screen,
panel,
title_pos,
items,
}
}
#[must_use]
pub fn panel_size(&self, atlas: &FontAtlas, style: &MenuStyle) -> Vec2 {
self.laid_out(None, style, None, &Setup::default(), atlas, |ui, built| {
let (min, max) = ui.rect(built.panel).expect("laid out this frame");
max - min
})
}
fn laid_out<R>(
&self,
screen: Option<Vec2>,
style: &MenuStyle,
skin: Option<&MenuSkin>,
setup: &Setup,
atlas: &FontAtlas,
read: impl FnOnce(&Ui, &BuiltMenu) -> R,
) -> R {
let tree = if screen.is_some() {
&PLACED_TREE
} else {
&MEASURED_TREE
};
tree.with(|tree| {
let mut ui = tree.borrow_mut();
ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
if let Some(font) = &setup.font {
ui.register_font(MENU_FONT, font)
.expect("the menu's family name is not reserved");
}
let built = self.build(&mut ui, screen, style, skin, setup);
let available = screen.map_or(AvailableSpace::MAX_CONTENT, AvailableSpace::definite);
ui.layout(Vec2::ZERO, available, atlas);
read(&ui, &built)
})
}
fn build(
&self,
ui: &mut Ui,
screen: Option<Vec2>,
style: &MenuStyle,
skin: Option<&MenuSkin>,
setup: &Setup,
) -> BuiltMenu {
use Declaration as D;
if let Some(skin) = skin {
ui.set_image(PANEL_IMAGE, skin.panel.image);
ui.set_image(IDLE_IMAGE, skin.buttons.idle.image);
ui.set_image(HOVERED_IMAGE, skin.buttons.hovered.image);
ui.set_image(PRESSED_IMAGE, skin.buttons.pressed.image);
}
let px = LengthAuto::Px;
let mut root = screen.map_or_else(Vec::new, |screen| {
vec![D::Width(px(screen.x)), D::Height(px(screen.y))]
});
if setup.font.is_some() {
root.push(D::FamilyName(Some(FamilyName::new(MENU_FONT))));
}
let panel_corners = style.panel_corners();
let panel = [
D::BorderWidth(Sides::Top, panel_corners.top),
D::BorderWidth(Sides::Right, panel_corners.right),
D::BorderWidth(Sides::Bottom, panel_corners.bottom),
D::BorderWidth(Sides::Left, panel_corners.left),
D::Padding(Sides::Top, Length::Px(style.panel_padding.y)),
D::Padding(Sides::Bottom, Length::Px(style.panel_padding.y)),
D::Padding(Sides::Left, Length::Px(style.panel_padding.x)),
D::Padding(Sides::Right, Length::Px(style.panel_padding.x)),
D::RowGap(Length::Px(style.title_gap)),
];
let button_corners = style.button_corners();
let row = [
D::BorderWidth(Sides::Top, button_corners.top),
D::BorderWidth(Sides::Right, button_corners.right),
D::BorderWidth(Sides::Bottom, button_corners.bottom),
D::BorderWidth(Sides::Left, button_corners.left),
D::Padding(Sides::Top, Length::Px(style.button_padding.y)),
D::Padding(Sides::Bottom, Length::Px(style.button_padding.y)),
D::Padding(Sides::Left, Length::Px(style.button_padding.x)),
D::Padding(Sides::Right, Length::Px(style.button_padding.x)),
];
let rows_style = RowStyle {
row,
label: [D::FontSize(style.item_size)],
hint: [
D::FontSize(style.item_size),
D::Margin(Sides::Left, px(style.hint_gap)),
],
groove: [
D::Margin(Sides::Left, px(style.hint_gap)),
D::MinWidth(px(style.track_width)),
D::Height(px(style.track_height)),
],
thumb: [
D::Width(px(style.handle_size.x)),
D::Height(px(style.handle_size.y)),
],
};
let caption = [D::FontSize(style.item_size)];
let mut list = vec![D::RowGap(Length::Px(style.item_gap))];
if let Some(line) = setup.line {
list.push(D::LineHeight(LineHeight::Px(line)));
}
if let Some(view) = &setup.list {
list.extend([
D::Overflow(Overflow::Hidden),
D::FlexShrink(0.0),
D::Width(px(view.size.x)),
D::Height(px(view.size.y)),
]);
}
let (shown, offset) = setup.list.as_ref().map_or(
(0..self.items.len(), 0.0),
|view| (view.shown.clone(), view.scroll - view.shown_top),
);
let mut title = None;
let mut rows = Vec::with_capacity(shown.len());
let mut panel_key = None;
let mut items_key = None;
ui.block("menu-screen", &root, |ui| {
if let Some(skin) = skin {
ui.span(".menu-scrim", skin.scrim, &[]);
}
panel_key = Some(
ui.block("menu", &panel, |ui| {
if !self.title.is_empty() {
title = Some(
ui.span(
".menu-title",
self.title.as_str(),
&[D::FontSize(style.title_size)],
)
.key,
);
}
if !self.subtitle.is_empty() {
ui.block(".menu-captions", &[], |ui| {
for line in &self.subtitle {
let selector = match line.tone {
CaptionTone::Hint => ".menu-caption",
CaptionTone::Warning => ".menu-caption.menu-caption-warning",
};
ui.span(selector, line.text.as_str(), &caption);
}
});
}
items_key = Some(
ui.block(".menu-items", &list, |ui| {
ui.set_scroll_offset(Vec2::new(0.0, offset));
for (index, item) in self.items.iter().enumerate() {
if shown.contains(&index) {
rows.push(self.build_row(ui, index, item, &rows_style));
}
}
})
.key,
);
})
.key,
);
});
BuiltMenu {
panel: panel_key.expect("the screen builds its panel"),
title,
items: items_key.expect("the panel builds its item list"),
rows,
}
}
fn build_row(&self, ui: &mut Ui, index: usize, item: &MenuItem, style: &RowStyle) -> BuiltRow {
let state = match self.state(index) {
ButtonState::Idle => PseudoClasses::NONE,
ButtonState::Hovered => PseudoClasses::HOVER,
ButtonState::Pressed => PseudoClasses::ACTIVE,
};
let mut label = None;
let mut groove = None;
let mut hint = None;
let row = ui
.block_keyed_in_state(index, "menu-item", &style.row, state, |ui| {
label = Some(
ui.span(".menu-label", item.label.as_str(), &style.label)
.key,
);
let caption = item.caption();
match item.kind {
MenuItemKind::Slider(slider) => {
groove = Some(build_groove(ui, slider, style));
}
MenuItemKind::Action | MenuItemKind::Cycler(_) if !caption.is_empty() => {
ui.block(".menu-spacer", &[], |_| {});
}
MenuItemKind::Action | MenuItemKind::Cycler(_) => {}
}
if !caption.is_empty() {
hint = Some(ui.span(".menu-hint", caption.as_ref(), &style.hint).key);
}
})
.key;
BuiltRow {
row,
label: label.expect("every row builds its label"),
hint,
groove,
}
}
pub fn render_art(&self, dl: &mut DrawList, layout: &MenuLayout, skin: &MenuSkin) {
let mut whole = DrawList::new();
self.render(&mut whole, layout, skin);
for (command, clip) in whole.commands().iter().zip(whole.clips()) {
if matches!(command, DrawCommand::Image { .. }) {
dl.push_clip(clip.min, clip.max);
dl.push_command(command.clone());
dl.pop_clip()
.expect("the clip pushed above is still on the stack");
}
}
}
pub fn render(&self, dl: &mut DrawList, layout: &MenuLayout, skin: &MenuSkin) {
self.laid_out(
Some(layout.screen),
&layout.style,
Some(skin),
&layout.setup,
&FontAtlas::built_in(),
|ui, _| ui.emit(dl),
);
}
}
thread_local! {
static PLACED_TREE: std::cell::RefCell<Ui> = std::cell::RefCell::new(Ui::new());
static MEASURED_TREE: std::cell::RefCell<Ui> = std::cell::RefCell::new(Ui::new());
}
const OFF_SCREEN: Vec2 = Vec2::splat(-1.0);
const MENU_FONT: &str = "crcbl-menu";
const PANEL_IMAGE: &str = "menu-panel";
const IDLE_IMAGE: &str = "menu-button-idle";
const HOVERED_IMAGE: &str = "menu-button-hovered";
const PRESSED_IMAGE: &str = "menu-button-pressed";
struct BuiltMenu {
panel: NodeKey,
title: Option<NodeKey>,
items: NodeKey,
rows: Vec<BuiltRow>,
}
fn build_groove(ui: &mut Ui, slider: Slider, style: &RowStyle) -> NodeKey {
use Declaration as D;
let share = slider.position();
ui.block(".menu-groove", &style.groove, |ui| {
let mut position = share;
ui.slider(".menu-slider", &mut position, 0.0..=1.0, Slider::KEY_STEP);
ui.block(".menu-thumb-rail", &[], |ui| {
ui.block(".menu-thumb-space", &[D::FlexGrow(share)], |_| {});
ui.block(".menu-thumb", &style.thumb, |_| {});
ui.block(".menu-thumb-space", &[D::FlexGrow(1.0 - share)], |_| {});
});
})
.key
}
struct RowStyle {
row: [Declaration; 8],
label: [Declaration; 1],
hint: [Declaration; 2],
groove: [Declaration; 3],
thumb: [Declaration; 2],
}
struct BuiltRow {
row: NodeKey,
label: NodeKey,
hint: Option<NodeKey>,
groove: Option<NodeKey>,
}
pub const FIT_FRACTION: f32 = 0.9;
pub const FIT_FONT_STEP: f32 = 0.25;
fn fit_sizes(largest: f32) -> Vec<f32> {
let mut sizes = vec![largest];
let spare = largest - MenuStyle::MIN_FONT_SIZE;
if spare > 0.0 {
let steps = (spare / FIT_FONT_STEP).floor() as u32;
sizes.extend(
(0..=steps)
.rev()
.map(|step| MenuStyle::MIN_FONT_SIZE + step as f32 * FIT_FONT_STEP)
.filter(|&size| size < largest),
);
}
sizes
}
fn row_line(font: &Font, style: &MenuStyle) -> f32 {
font.metrics().normal_line_height(style.item_size).ceil()
}
fn extent_size(extent: (u32, u32)) -> Vec2 {
Vec2::new(extent.0 as f32, extent.1 as f32)
}
fn contains(rect: (Vec2, Vec2), point: Vec2) -> bool {
point.x >= rect.0.x && point.x <= rect.1.x && point.y >= rect.0.y && point.y <= rect.1.y
}
#[derive(Debug, Clone, PartialEq, Default)]
struct Setup {
font: Option<Font>,
line: Option<f32>,
list: Option<ListView>,
}
#[derive(Debug, Clone, PartialEq)]
struct ListView {
size: Vec2,
viewport: (Vec2, Vec2),
scroll: f32,
reach: f32,
shown: Range<usize>,
shown_top: f32,
}
struct Measured {
panel: Vec2,
list: Vec2,
tallest: f32,
}
struct Candidate {
style: MenuStyle,
setup: Setup,
measured: Measured,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MenuFitError {
TooWide {
font_size: f32,
width: f32,
room: f32,
},
TooShort {
font_size: f32,
height: f32,
room: f32,
},
}
impl std::fmt::Display for MenuFitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
Self::TooWide {
font_size,
width,
room,
} => write!(
f,
"the menu is {width}px wide at a {font_size}px font, the smallest it may \
shrink to, and the window has room for {room}px"
),
Self::TooShort {
font_size,
height,
room,
} => write!(
f,
"the menu needs {height}px to show one row at a {font_size}px font, the \
smallest it may shrink to, and the window has room for {room}px"
),
}
}
}
impl std::error::Error for MenuFitError {}
#[cfg(test)]
fn text_width(atlas: &FontAtlas, text: &str, size: f32) -> f32 {
if text.is_empty() {
return 0.0;
}
atlas.text_width(text, size / NATURAL_FONT_SIZE)
}
#[cfg(test)]
fn line_height(size: f32) -> f32 {
LINE_HEIGHT * (size / NATURAL_FONT_SIZE)
}
fn handle_travel(track: (Vec2, Vec2), handle_width: f32) -> (f32, f32) {
let half = (handle_width * 0.5)
.min((track.1.x - track.0.x) * 0.5)
.max(0.0);
(track.0.x + half, track.1.x - half)
}
fn position_along(track: (Vec2, Vec2), handle_width: f32, x: f32) -> f32 {
let (start, end) = handle_travel(track, handle_width);
if end <= start {
return 0.0;
}
(x - start) / (end - start)
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MenuItemLayout {
pub id: WidgetId,
pub min: Vec2,
pub max: Vec2,
pub label_pos: Vec2,
pub hint_pos: Vec2,
pub track: Option<(Vec2, Vec2)>,
}
impl MenuItemLayout {
#[must_use]
pub fn size(&self) -> Vec2 {
self.max - self.min
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct MenuLayout {
style: MenuStyle,
setup: Setup,
screen: Vec2,
panel: (Vec2, Vec2),
title_pos: Vec2,
items: Vec<MenuItemLayout>,
}
impl MenuLayout {
#[must_use]
pub const fn style(&self) -> &MenuStyle {
&self.style
}
#[must_use]
pub const fn screen(&self) -> Vec2 {
self.screen
}
#[must_use]
pub const fn panel(&self) -> (Vec2, Vec2) {
self.panel
}
#[must_use]
pub fn panel_size(&self) -> Vec2 {
self.panel.1 - self.panel.0
}
#[must_use]
pub fn panel_centre(&self) -> Vec2 {
(self.panel.0 + self.panel.1) * 0.5
}
#[must_use]
pub const fn title_pos(&self) -> Vec2 {
self.title_pos
}
#[must_use]
pub fn items(&self) -> &[MenuItemLayout] {
&self.items
}
#[must_use]
pub fn viewport(&self) -> Option<(Vec2, Vec2)> {
self.setup.list.as_ref().map(|list| list.viewport)
}
#[must_use]
pub fn scroll(&self) -> f32 {
self.setup.list.as_ref().map_or(0.0, |list| list.scroll)
}
#[must_use]
pub fn shows(&self, index: usize) -> bool {
index < self.items.len()
&& self
.setup
.list
.as_ref()
.is_none_or(|list| list.shown.contains(&index))
}
#[must_use]
pub fn scrim(&self) -> (Vec2, Vec2) {
(Vec2::ZERO, self.screen)
}
}
#[derive(Debug)]
pub struct MenuSet<K> {
menus: Vec<(K, Menu)>,
shown: K,
ui: UiState,
}
impl<K: Copy + Eq> MenuSet<K> {
#[must_use]
pub fn new(shown: K, menus: Vec<(K, Menu)>) -> Self {
for (index, (kind, _)) in menus.iter().enumerate() {
assert!(
!menus[..index].iter().any(|(seen, _)| seen == kind),
"two menus claim the same state",
);
}
Self {
menus,
shown,
ui: UiState::new(),
}
}
#[must_use]
pub const fn kind(&self) -> K {
self.shown
}
#[must_use]
pub fn is_showing(&self) -> bool {
self.current().is_some()
}
pub fn show(&mut self, kind: K) {
if kind == self.shown {
return;
}
if let Some(menu) = self.current_mut() {
menu.clear_input();
}
self.ui.clear();
self.shown = kind;
}
pub fn replace(&mut self, kind: K, menu: Menu) {
match self.menus.iter_mut().find(|(seen, _)| *seen == kind) {
Some(slot) => slot.1 = menu,
None => self.menus.push((kind, menu)),
}
self.ui.clear();
}
#[must_use]
pub fn current(&self) -> Option<&Menu> {
let shown = self.shown;
self.menus
.iter()
.find_map(|(kind, menu)| (*kind == shown).then_some(menu))
}
pub fn current_mut(&mut self) -> Option<&mut Menu> {
self.get_mut(self.shown)
}
pub fn get_mut(&mut self, kind: K) -> Option<&mut Menu> {
self.menus
.iter_mut()
.find_map(|(seen, menu)| (*seen == kind).then_some(menu))
}
pub fn select_next(&mut self) {
if let Some(menu) = self.current_mut() {
menu.select_next();
}
}
pub fn select_previous(&mut self) {
if let Some(menu) = self.current_mut() {
menu.select_previous();
}
}
pub fn press(&mut self, down: bool) {
if let Some(menu) = self.current_mut() {
menu.press(down);
}
}
pub fn activate(&mut self) -> Option<WidgetId> {
self.current_mut().and_then(Menu::activate)
}
pub fn nudge_slider(&mut self, forward: bool) -> bool {
self.current_mut()
.is_some_and(|menu| menu.nudge_slider(forward))
}
#[must_use]
pub fn slider_highlighted(&self) -> bool {
self.current().is_some_and(Menu::slider_highlighted)
}
pub fn nudge_cycler(&mut self, forward: bool) -> bool {
self.current_mut()
.is_some_and(|menu| menu.nudge_cycler(forward))
}
#[must_use]
pub fn cycler_highlighted(&self) -> bool {
self.current().is_some_and(Menu::cycler_highlighted)
}
#[must_use]
pub fn press_captured(&self) -> bool {
self.ui.active().is_some()
}
pub fn cancel_press(&mut self) {
self.ui.clear();
if let Some(menu) = self.current_mut() {
menu.clear_input();
}
}
pub fn point(
&mut self,
extent: (u32, u32),
atlas: &FontAtlas,
pointer: PointerInput,
) -> Option<WidgetId> {
let shown = self.shown;
let menu = self
.menus
.iter_mut()
.find_map(|(kind, menu)| (*kind == shown).then_some(menu))?;
let layout = menu.layout(extent, atlas);
menu.point(&layout, &mut self.ui, pointer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::draw_list::DrawCommand;
const EXTENTS: [(u32, u32); 5] = [
(960, 720),
(800, 600),
(1920, 1080),
(1440, 400),
(600, 900),
];
fn atlas() -> FontAtlas {
FontAtlas::built_in()
}
fn skin() -> MenuSkin {
let mut images = crate::image::ImageAtlas::new();
let mut register = |shade: u8| {
images
.register(16, 16, &[shade; 16 * 16 * 4])
.expect("five 16x16 images fit an empty page")
};
let mut sliced = |shade, insets| NineSliceImage {
image: register(shade),
insets,
};
let panel = sliced(10, PANEL_INSETS);
let buttons = ButtonSkin {
idle: sliced(20, BUTTON_INSETS),
hovered: sliced(30, BUTTON_INSETS),
pressed: sliced(40, BUTTON_INSETS),
};
MenuSkin {
panel,
buttons,
scrim: register(255),
}
}
fn pause_menu() -> Menu {
Menu::new(
"PAUSED",
vec![
MenuItem::new(1, "RESUME", "ESC"),
MenuItem::new(2, "FULLSCREEN", "F11"),
MenuItem::new(3, "DEBUG OVERLAY", "F3"),
],
)
}
#[cfg(feature = "parsed-font")]
#[test]
fn a_menu_laid_out_in_a_font_measures_and_draws_its_text_in_it() {
use crate::font::FontMetrics;
let font = Font::fixed_pitch(
FontMetrics {
units_per_em: 1000,
ascent: 800.0,
descent: -200.0,
line_gap: 0.0,
},
500.0,
);
let menu = Menu::new("", vec![MenuItem::new(1, "RESUME", "")]);
let style = MenuStyle::pixel_art(1);
let extent = (960, 720);
let before = menu.layout(extent, &atlas());
let in_font = menu.layout_with_font(extent, &style, font);
let in_atlas = menu.layout_with(extent, &atlas(), &style);
let corners = style.button_corners();
let chrome = Vec2::new(
corners.left + corners.right + 2.0 * style.button_padding.x,
corners.top + corners.bottom + 2.0 * style.button_padding.y,
);
let label = |layout: &MenuLayout| layout.items()[0].size() - chrome;
assert_eq!(
label(&in_font),
Vec2::new(6.0 * 0.5 * style.item_size, style.item_size),
"the row was not measured in the font"
);
assert_eq!(
label(&in_atlas),
Vec2::new(
text_width(&atlas(), "RESUME", style.item_size),
line_height(style.item_size)
)
);
assert_ne!(label(&in_font), label(&in_atlas));
let drawn = |layout: &MenuLayout| {
let mut list = DrawList::new();
menu.render(&mut list, layout, &skin());
let runs: Vec<_> = list
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Glyphs { font, .. } => Some(font.id()),
_ => None,
})
.collect();
let texts = list
.commands()
.iter()
.filter(|command| matches!(command, DrawCommand::Text { .. }))
.count();
(runs, texts)
};
assert_eq!(drawn(&in_font), (vec![font.id()], 0));
assert_eq!(drawn(&in_atlas), (Vec::new(), 1));
assert_eq!(menu.layout(extent, &atlas()), before);
}
fn captioned_menu() -> Menu {
let mut menu = pause_menu();
menu.subtitle = vec!["ARROWS MOVE".into(), "ENTER PICKS".into()];
menu
}
fn texts(dl: &DrawList) -> Vec<(String, Vec2, [f32; 4])> {
dl.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text {
text, pos, color, ..
} => Some((text.clone(), *pos, *color)),
_ => None,
})
.collect()
}
#[test]
fn captions_are_drawn_under_the_title_in_the_hint_colour() {
let atlas = atlas();
let menu = captioned_menu();
let layout = menu.layout((960, 720), &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let drawn = texts(&dl);
let line = |wanted: &str| {
drawn
.iter()
.find(|(text, ..)| text == wanted)
.unwrap_or_else(|| panic!("{wanted} is not drawn: {drawn:?}"))
.clone()
};
let (_, first, first_colour) = line("ARROWS MOVE");
let (_, second, second_colour) = line("ENTER PICKS");
assert_eq!(first_colour, layout.style().hint_color);
assert_eq!(second_colour, layout.style().hint_color);
let title_bottom = layout.title_pos().y + line_height(layout.style().title_size);
let caption_bottom = second.y + line_height(layout.style().item_size);
let (panel_min, panel_max) = layout.panel();
assert!(
title_bottom <= first.y && first.y < second.y,
"the captions are not under the title, in order: {first:?} {second:?}"
);
assert!(
caption_bottom <= layout.items()[0].min.y,
"the first row starts at {} over a caption ending at {caption_bottom}",
layout.items()[0].min.y
);
for pos in [first, second] {
assert!(pos.x >= panel_min.x && pos.x <= panel_max.x, "{pos:?}");
}
}
#[test]
fn captions_are_skipped_by_the_keyboard_and_the_pointer() {
let atlas = atlas();
let mut menu = captioned_menu();
let mut fired = Vec::new();
for _ in 0..=menu.items().len() {
fired.push(menu.activate());
menu.select_next();
}
assert_eq!(fired, [Some(1), Some(2), Some(3), Some(1)]);
assert!(menu.select_id(1));
menu.select_previous();
assert_eq!(menu.activate(), Some(3), "the wrap upward went astray");
assert!(menu.select_id(1));
let layout = menu.layout((960, 720), &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let (_, caption, _) = texts(&dl)
.into_iter()
.find(|(text, ..)| text == "ENTER PICKS")
.expect("the caption is drawn");
let on_caption = caption + Vec2::new(2.0, 2.0);
let mut ui = UiState::new();
assert_eq!(menu.point(&layout, &mut ui, press_at(on_caption)), None);
assert_eq!(menu.point(&layout, &mut ui, release_at(on_caption)), None);
assert_eq!(
menu.state(0),
ButtonState::Hovered,
"the caption took the hover"
);
assert_eq!(menu.selected(), 0);
}
fn warned_menu() -> Menu {
let mut menu = captioned_menu();
menu.subtitle
.insert(1, Caption::warning("PROGRESS WILL BE LOST"));
menu
}
#[test]
fn a_warning_caption_is_drawn_in_the_warning_colour() {
let menu = warned_menu();
let layout = menu.layout((960, 720), &atlas());
let style = layout.style();
assert_ne!(style.warning_color, style.hint_color);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let captions: Vec<(String, [f32; 4])> = texts(&dl)
.into_iter()
.filter(|(text, ..)| menu.subtitle.iter().any(|line| &line.text == text))
.map(|(text, _, colour)| (text, colour))
.collect();
assert_eq!(
captions,
[
("ARROWS MOVE".to_owned(), style.hint_color),
("PROGRESS WILL BE LOST".to_owned(), style.warning_color),
("ENTER PICKS".to_owned(), style.hint_color),
]
);
}
#[test]
fn a_captions_tone_changes_no_row_or_hit() {
let atlas = atlas();
let hinted = captioned_menu();
let mut warned = captioned_menu();
for line in &mut warned.subtitle {
line.tone = CaptionTone::Warning;
}
assert_eq!(
warned.layout((960, 720), &atlas),
hinted.layout((960, 720), &atlas)
);
#[cfg(feature = "parsed-font")]
assert_eq!(
warned.layout_with_font_fitted(
(480, 360),
&MenuStyle::pixel_art(2),
font_like_roboto()
),
hinted.layout_with_font_fitted(
(480, 360),
&MenuStyle::pixel_art(2),
font_like_roboto()
),
);
let mut fired = Vec::new();
for _ in 0..=warned.items().len() {
fired.push(warned.activate());
warned.select_next();
}
assert_eq!(fired, [Some(1), Some(2), Some(3), Some(1)]);
assert!(warned.select_id(1));
let layout = warned.layout((960, 720), &atlas);
let mut dl = DrawList::new();
warned.render(&mut dl, &layout, &skin());
let (_, caption, colour) = texts(&dl)
.into_iter()
.find(|(text, ..)| text == "ENTER PICKS")
.expect("the caption is drawn");
assert_eq!(colour, layout.style().warning_color);
let on_caption = caption + Vec2::new(2.0, 2.0);
let mut ui = UiState::new();
assert_eq!(warned.point(&layout, &mut ui, press_at(on_caption)), None);
assert_eq!(warned.point(&layout, &mut ui, release_at(on_caption)), None);
assert_eq!(warned.state(0), ButtonState::Hovered);
assert_eq!(warned.selected(), 0);
}
#[test]
fn a_stylesheet_rule_sets_the_warning_colour() {
let menu = warned_menu();
let style = MenuStyle::pixel_art(1);
let red = [1.0, 0.0, 0.0, 1.0];
let mut ui = Ui::new();
ui.add_stylesheet(
"game",
".menu-caption-warning { color: color(srgb-linear 1 0 0); }",
);
ui.begin_frame(PointerInput::hovering(OFF_SCREEN));
menu.build(
&mut ui,
Some(Vec2::new(960.0, 720.0)),
&style,
None,
&Setup::default(),
);
ui.layout(
Vec2::ZERO,
AvailableSpace::definite(Vec2::new(960.0, 720.0)),
&atlas(),
);
let mut dl = DrawList::new();
ui.emit(&mut dl);
let colour = |wanted: &str| {
texts(&dl)
.into_iter()
.find_map(|(text, _, colour)| (text == wanted).then_some(colour))
.unwrap_or_else(|| panic!("{wanted} is not drawn"))
};
assert_eq!(colour("PROGRESS WILL BE LOST"), red);
assert_eq!(colour("ARROWS MOVE"), style.hint_color);
}
#[cfg(feature = "parsed-font")]
#[test]
fn a_menu_of_only_captions_selects_nothing() {
let mut menu = Menu::new("NOTICE", Vec::new());
menu.subtitle = vec![Caption::warning("NOTHING TO CHOOSE")];
menu.select_next();
menu.select_previous();
assert_eq!(menu.activate(), None);
assert_eq!(menu.selected_item(), None);
let layout = menu.layout((960, 720), &atlas());
assert!(layout.items().is_empty());
let fitted = menu
.layout_with_font_fitted((480, 360), &MenuStyle::pixel_art(1), font_like_roboto())
.expect("a notice fits");
assert!(fitted.items().is_empty() && fitted.viewport().is_none());
}
#[cfg(feature = "parsed-font")]
const ADVANCE_EM: f32 = 0.55;
#[cfg(feature = "parsed-font")]
fn font_like_roboto() -> &'static Font {
use crate::font::FontMetrics;
static FONT: std::sync::OnceLock<&'static Font> = std::sync::OnceLock::new();
FONT.get_or_init(|| {
Font::fixed_pitch(
FontMetrics {
units_per_em: 1000,
ascent: 928.0,
descent: -244.0,
line_gap: 0.0,
},
ADVANCE_EM * 1000.0,
)
})
}
#[cfg(feature = "parsed-font")]
const SCENES: usize = 17;
#[cfg(feature = "parsed-font")]
fn scene_menu() -> Menu {
let items = (0..SCENES)
.map(|index| {
let description = format!("{:02} {}", index, "a".repeat(40 + index * 2))
.chars()
.take(70)
.collect::<String>();
MenuItem::new(
100 + index as WidgetId,
format!("SCENE {index:02} NAME"),
description,
)
})
.collect();
let mut menu = Menu::new("SCENES", items);
menu.subtitle = vec![
"UP/DOWN MOVES - ENTER LOADS - ESC CLOSES".into(),
Caption::warning("LOADING A SCENE DISCARDS UNSAVED WORK"),
];
menu
}
#[cfg(feature = "parsed-font")]
const SMALL: (u32, u32) = (480, 360);
#[cfg(feature = "parsed-font")]
fn fitted(menu: &Menu, extent: (u32, u32)) -> MenuLayout {
menu.layout_with_font_fitted(extent, &MenuStyle::pixel_art(2), font_like_roboto())
.unwrap_or_else(|error| panic!("{extent:?}: {error}"))
}
#[cfg(feature = "parsed-font")]
fn within(inner: (Vec2, Vec2), outer: (Vec2, Vec2)) -> bool {
inner.0.x >= outer.0.x
&& inner.0.y >= outer.0.y
&& inner.1.x <= outer.1.x
&& inner.1.y <= outer.1.y
}
#[cfg(feature = "parsed-font")]
#[test]
fn a_seventeen_row_menu_fits_a_480_by_360_window() {
let menu = scene_menu();
let layout = fitted(&menu, SMALL);
let style = layout.style();
let screen = extent_size(SMALL);
let panel = layout.panel();
assert!(
within(panel, (Vec2::ZERO, screen)),
"the panel {panel:?} leaves the window"
);
assert!(layout.panel_size().cmple(screen * FIT_FRACTION).all());
assert!(
style.item_size >= MenuStyle::MIN_FONT_SIZE,
"{}",
style.item_size
);
assert!(
style.scale >= 1.0 && style.scale.fract() == 0.0,
"{}",
style.scale
);
assert_eq!(style.panel_corners().left, PANEL_INSETS.left * style.scale);
let viewport = layout
.viewport()
.expect("seventeen rows scroll at 360 tall");
assert!(within(viewport, panel), "{viewport:?} leaves {panel:?}");
let shown: Vec<usize> = (0..SCENES).filter(|&index| layout.shows(index)).collect();
assert!(shown.len() > 1 && shown.len() < SCENES, "{shown:?}");
for &index in &shown {
let row = layout.items()[index];
assert!(
row.min.x >= panel.0.x && row.max.x <= panel.1.x,
"row {index} {row:?} is wider than the panel"
);
assert!(
row.max.y > viewport.0.y && row.min.y < viewport.1.y,
"row {index} is drawn but nowhere in view"
);
let description = &menu.items()[index].hint;
let end =
row.hint_pos.x + description.chars().count() as f32 * ADVANCE_EM * style.item_size;
assert!(
end <= row.max.x + 0.5,
"row {index}'s description ends at {end}"
);
}
assert!(within(
(layout.items()[0].min, layout.items()[0].max),
viewport
));
assert_eq!(fitted(&menu, SMALL), layout, "the fit is not deterministic");
}
#[cfg(feature = "parsed-font")]
#[test]
fn the_fit_takes_the_largest_step_that_fits() {
let menu = scene_menu();
let ceiling = MenuStyle::pixel_art(2);
let font = font_like_roboto();
let extent = (1100, 900);
let layout = fitted(&menu, extent);
let chosen = layout.style().item_size;
assert!(layout.viewport().is_none(), "{extent:?} scrolled");
assert!(
chosen < ceiling.item_size && chosen > MenuStyle::MIN_FONT_SIZE,
"{extent:?} does not exercise the shrink: {chosen}"
);
let panel_at = |size: f32| {
let style = ceiling.shrunk(size);
let setup = Setup {
font: Some(font.clone()),
line: Some(row_line(font, &style)),
list: None,
};
menu.measure(&style, &setup).panel
};
let room = extent_size(extent) * FIT_FRACTION;
assert!(panel_at(chosen).cmple(room).all());
assert!(
!panel_at(chosen + FIT_FONT_STEP).cmple(room).all(),
"a step larger than {chosen} fits too"
);
let roomy = fitted(&menu, (3840, 2160));
assert_eq!(roomy.style().item_size, ceiling.item_size);
assert_eq!(roomy.style().scale, ceiling.scale);
assert!(roomy.viewport().is_none());
}
#[cfg(feature = "parsed-font")]
#[test]
fn the_fit_refuses_honestly_below_the_minimum() {
let menu = scene_menu();
let style = MenuStyle::pixel_art(2);
let font = font_like_roboto();
match menu.layout_with_font_fitted((300, 360), &style, font) {
Err(MenuFitError::TooWide {
font_size,
width,
room,
}) => {
assert_eq!(font_size, MenuStyle::MIN_FONT_SIZE);
assert!(
width > room && room == 300.0 * FIT_FRACTION,
"{width} {room}"
);
}
other => panic!("a 300px window gave {other:?}"),
}
match menu.layout_with_font_fitted((480, 60), &style, font) {
Err(MenuFitError::TooShort {
font_size,
height,
room,
}) => {
assert_eq!(font_size, MenuStyle::MIN_FONT_SIZE);
assert!(height > room, "{height} {room}");
}
other => panic!("a 60px window gave {other:?}"),
}
}
#[cfg(feature = "parsed-font")]
#[test]
fn scrolling_keeps_the_selected_row_in_view_down_and_up() {
for with_pointer in [false, true] {
let mut menu = scene_menu();
let mut ui = UiState::new();
let mut scrolls = Vec::new();
let mut step = |menu: &mut Menu, moved: &str| {
let layout = fitted(menu, SMALL);
let viewport = layout.viewport().expect("the list scrolls");
let selected = layout.items()[menu.selected()];
assert!(
layout.shows(menu.selected()) && within((selected.min, selected.max), viewport),
"after {moved} to row {}, {selected:?} is not wholly in {viewport:?}",
menu.selected(),
);
if with_pointer {
menu.point(&layout, &mut ui, PointerInput::hovering(OFF_SCREEN));
}
scrolls.push(layout.scroll());
};
step(&mut menu, "opening");
for _ in 1..SCENES {
menu.select_next();
step(&mut menu, "down");
}
assert_eq!(menu.selected(), SCENES - 1);
for _ in 1..SCENES {
menu.select_previous();
step(&mut menu, "up");
}
assert_eq!(menu.selected(), 0);
assert!(scrolls[SCENES - 1] > 0.0, "the walk down never scrolled");
assert_eq!(*scrolls.last().expect("walked"), 0.0);
if with_pointer {
assert_eq!(scrolls[SCENES], scrolls[SCENES - 1], "{scrolls:?}");
}
}
}
#[cfg(feature = "parsed-font")]
#[test]
fn rows_scrolled_out_of_view_are_neither_drawn_nor_hit() {
let mut menu = scene_menu();
menu.select_previous();
let last = SCENES - 1;
assert_eq!(menu.selected(), last);
let layout = fitted(&menu, SMALL);
let viewport = layout.viewport().expect("the list scrolls");
assert!(!layout.shows(0), "the first row is still in view");
assert!(layout.shows(last));
let mut ui = UiState::new();
let hidden = layout.items()[0];
let where_it_was = (hidden.min + hidden.max) * 0.5;
assert_eq!(menu.point(&layout, &mut ui, press_at(where_it_was)), None);
assert_eq!(menu.point(&layout, &mut ui, release_at(where_it_was)), None);
assert_eq!(
menu.state(0),
ButtonState::Idle,
"a hidden row took the hover"
);
let visible = layout.items()[last];
let on_it = (visible.min + visible.max) * 0.5;
menu.point(&layout, &mut ui, press_at(on_it));
assert_eq!(
menu.point(&layout, &mut ui, release_at(on_it)),
Some(100 + last as WidgetId)
);
let shown = (0..SCENES).filter(|&index| layout.shows(index)).count();
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let runs: Vec<Vec2> = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Glyphs { origin, .. } => Some(*origin),
_ => None,
})
.collect();
assert_eq!(runs.len(), 1 + 2 + 2 * shown, "title, captions, shown rows");
let frames = pictures(&dl).len();
assert_eq!(
frames,
1 + 9 + 9 * shown,
"scrim, panel, shown rows' frames"
);
for origin in &runs[3..] {
assert!(
origin.y + layout.style().item_size > viewport.0.y && origin.y < viewport.1.y,
"a row's text at {origin:?} is out of {viewport:?}"
);
}
let mut art = DrawList::new();
menu.render_art(&mut art, &layout, &skin());
assert_eq!(art.len(), frames);
assert!(
art.clips()[10..]
.iter()
.all(|clip| clip.min == viewport.0 && clip.max == viewport.1),
"a row's frame lost the list's clip"
);
}
#[cfg(feature = "parsed-font")]
#[test]
fn the_wheel_scrolls_the_list_and_the_keyboard_takes_it_back() {
let mut menu = scene_menu();
let layout = fitted(&menu, SMALL);
let (panel_min, panel_max) = layout.panel();
let over = (panel_min + panel_max) * 0.5;
assert_eq!(layout.scroll(), 0.0);
assert!(!menu.scroll_wheel(&layout, Vec2::new(1.0, 1.0), Vec2::new(0.0, 60.0)));
assert!(menu.scroll_wheel(&layout, over, Vec2::new(0.0, 60.0)));
let wheeled = fitted(&menu, SMALL);
assert_eq!(wheeled.scroll(), 60.0, "the wheel did not move the list");
assert_eq!(menu.selected(), 0);
assert!(!wheeled.shows(0), "60px should scroll the first row away");
assert!(menu.scroll_wheel(&wheeled, over, Vec2::new(0.0, 10_000.0)));
let bottom = fitted(&menu, SMALL);
assert!(!menu.scroll_wheel(&bottom, over, Vec2::new(0.0, 10.0)));
assert!(bottom.shows(SCENES - 1));
menu.select_next();
let back = fitted(&menu, SMALL);
let row = back.items()[1];
assert!(within(
(row.min, row.max),
back.viewport().expect("scrolls")
));
let small = pause_menu();
let unscrolled = small.layout((960, 720), &atlas());
assert!(!menu.clone().scroll_wheel(
&unscrolled,
unscrolled.panel_centre(),
Vec2::new(0.0, 10.0)
));
}
#[test]
fn the_panel_is_centred_at_every_aspect_ratio() {
let menu = pause_menu();
let atlas = atlas();
for extent in EXTENTS {
let layout = menu.layout(extent, &atlas);
let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
let offset = layout.panel_centre() - screen * 0.5;
assert!(
offset.x.abs() <= 0.5 && offset.y.abs() <= 0.5,
"{extent:?}: the panel's centre is {offset:?} off the screen's",
);
}
}
#[test]
fn the_panel_is_centred_at_every_scale() {
let menu = pause_menu();
let atlas = atlas();
for scale in 1..=MenuStyle::MAX_SCALE {
let style = MenuStyle::pixel_art(scale);
for extent in EXTENTS {
let layout = menu.layout_with(extent, &atlas, &style);
let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
let offset = layout.panel_centre() - screen * 0.5;
assert!(
offset.x.abs() <= 0.5 && offset.y.abs() <= 0.5,
"scale {scale} at {extent:?}: centre off by {offset:?}",
);
}
}
}
#[test]
fn the_whole_menu_is_inside_the_screen_at_every_aspect_ratio() {
let menu = pause_menu();
let atlas = atlas();
for extent in EXTENTS {
let layout = menu.layout(extent, &atlas);
let (min, max) = layout.panel();
assert!(
min.x >= 0.0
&& min.y >= 0.0
&& max.x <= extent.0 as f32
&& max.y <= extent.1 as f32,
"{extent:?}: the panel {min:?}..{max:?} leaves the framebuffer",
);
for item in layout.items() {
assert!(
item.min.x >= min.x
&& item.min.y >= min.y
&& item.max.x <= max.x
&& item.max.y <= max.y,
"{extent:?}: a button at {:?}..{:?} escapes the panel {min:?}..{max:?}",
item.min,
item.max,
);
}
}
}
#[test]
fn a_bigger_window_gets_a_bigger_menu() {
let menu = pause_menu();
let atlas = atlas();
let small = menu.layout((640, 480), &atlas);
let large = menu.layout((1920, 1440), &atlas);
assert!(
large.style().scale > small.style().scale,
"640x480 chose {} and 1920x1440 chose {}",
small.style().scale,
large.style().scale,
);
assert!(small.style().scale >= 1.0);
assert!(large.style().scale <= MenuStyle::MAX_SCALE as f32);
}
#[test]
fn the_frames_corners_do_not_grow_with_the_menu() {
let atlas = atlas();
let style = MenuStyle::pixel_art(3);
let small = Menu::new("GO", vec![MenuItem::new(1, "OK", "")]);
let large = Menu::new(
"A MUCH LONGER TITLE",
(0..5)
.map(|i| MenuItem::new(i, "A VERY LONG MENU ITEM LABEL", "SHIFT+F11"))
.collect(),
);
let small_size = small.panel_size(&atlas, &style);
let large_size = large.panel_size(&atlas, &style);
assert!(
large_size.x > small_size.x * 1.5 && large_size.y > small_size.y * 1.5,
"the two menus are not different enough to prove anything: \
{small_size:?} vs {large_size:?}",
);
let corners = style.panel_corners();
assert_eq!(corners.left, PANEL_INSETS.left * style.scale);
assert_eq!(corners.bottom, PANEL_INSETS.bottom * style.scale);
for (menu, size) in [(&small, small_size), (&large, large_size)] {
let layout = menu.layout_with((1600, 1200), &atlas, &style);
let (min, max) = layout.panel();
assert_eq!(max - min, size);
let item = layout.items()[0];
assert_eq!(
item.min.x - min.x,
corners.left + style.panel_padding.x,
"the first button is not one fixed corner plus the padding in",
);
assert_eq!(max.x - item.max.x, corners.right + style.panel_padding.x);
}
}
#[test]
fn every_button_is_the_same_size() {
let atlas = atlas();
let menu = Menu::new(
"T",
vec![
MenuItem::new(1, "X", ""),
MenuItem::new(2, "A MUCH LONGER LABEL", "F11"),
MenuItem::new(3, "MID", "Q"),
],
);
let layout = menu.layout((1280, 960), &atlas);
let first = layout.items()[0].size();
for item in layout.items() {
assert_eq!(item.size(), first, "buttons disagree about their size");
}
assert!(first.x > 0.0 && first.y > 0.0);
}
#[test]
fn only_the_selected_item_is_highlighted() {
let mut menu = pause_menu();
for expected in 0..menu.items().len() {
let states: Vec<ButtonState> = (0..menu.items().len()).map(|i| menu.state(i)).collect();
assert_eq!(states[expected], ButtonState::Hovered, "{states:?}");
assert_eq!(
states.iter().filter(|s| **s != ButtonState::Idle).count(),
1,
"{states:?} lights up more than one item",
);
menu.select_next();
}
assert_eq!(menu.selected(), 0);
}
#[test]
fn the_selection_wraps_both_ways() {
let mut menu = pause_menu();
menu.select_previous();
assert_eq!(menu.selected(), 2);
menu.select_next();
assert_eq!(menu.selected(), 0);
}
#[test]
fn holding_the_commit_key_presses_the_highlighted_button() {
let mut menu = pause_menu();
assert_eq!(menu.state(0), ButtonState::Hovered);
menu.press(true);
assert_eq!(menu.state(0), ButtonState::Pressed);
assert_eq!(menu.state(1), ButtonState::Idle, "the press leaked");
assert_eq!(menu.activate(), Some(1));
assert_eq!(
menu.state(0),
ButtonState::Hovered,
"activating left the button held down",
);
}
#[test]
fn activation_reports_the_selected_items_id() {
let mut menu = pause_menu();
assert_eq!(menu.activate(), Some(1));
menu.select_next();
assert_eq!(menu.activate(), Some(2));
assert!(menu.select_id(3));
assert_eq!(menu.activate(), Some(3));
assert!(!menu.select_id(99), "an id that is not in the menu");
}
#[test]
fn an_empty_menu_activates_nothing() {
let mut menu = Menu::new("EMPTY", Vec::new());
menu.select_next();
menu.select_previous();
menu.press(true);
assert_eq!(menu.activate(), None);
assert_eq!(menu.state(0), ButtonState::Idle);
}
#[test]
fn the_pointer_hovers_presses_and_clicks() {
let atlas = atlas();
let mut menu = pause_menu();
let layout = menu.layout((960, 720), &atlas);
let mut ui = UiState::new();
let second = layout.items()[1];
let over_second = (second.min + second.max) * 0.5;
let outside = Vec2::new(2.0, 2.0);
assert_eq!(
menu.point(&layout, &mut ui, PointerInput::hovering(over_second)),
None
);
assert_eq!(menu.state(1), ButtonState::Hovered);
assert_eq!(
menu.state(0),
ButtonState::Idle,
"the selection still shows"
);
let down = PointerInput {
pos: over_second,
down: true,
released: false,
secondary_pressed: false,
};
assert_eq!(menu.point(&layout, &mut ui, down), None);
assert_eq!(menu.state(1), ButtonState::Pressed);
let elsewhere = PointerInput {
pos: outside,
down: false,
released: true,
secondary_pressed: false,
};
assert_eq!(menu.point(&layout, &mut ui, elsewhere), None);
assert_eq!(ui.active(), None);
assert_eq!(menu.point(&layout, &mut ui, down), None);
let up = PointerInput {
pos: over_second,
down: false,
released: true,
secondary_pressed: false,
};
assert_eq!(menu.point(&layout, &mut ui, up), Some(2));
assert_eq!(menu.selected(), 1);
}
#[test]
fn a_pointer_over_nothing_gives_the_highlight_back_to_the_keyboard() {
let atlas = atlas();
let mut menu = pause_menu();
let layout = menu.layout((960, 720), &atlas);
let mut ui = UiState::new();
let third = layout.items()[2];
menu.point(
&layout,
&mut ui,
PointerInput::hovering((third.min + third.max) * 0.5),
);
assert_eq!(menu.state(2), ButtonState::Hovered);
menu.point(
&layout,
&mut ui,
PointerInput::hovering(Vec2::new(1.0, 1.0)),
);
assert_eq!(menu.state(0), ButtonState::Hovered, "back to the selection");
assert_eq!(menu.state(2), ButtonState::Idle);
}
#[test]
fn a_drag_onto_a_neighbour_does_not_press_it() {
let atlas = atlas();
let mut menu = pause_menu();
let layout = menu.layout((960, 720), &atlas);
let mut ui = UiState::new();
let first = layout.items()[0];
let second = layout.items()[1];
let down = PointerInput {
pos: (first.min + first.max) * 0.5,
down: true,
released: false,
secondary_pressed: false,
};
assert_eq!(menu.point(&layout, &mut ui, down), None);
assert_eq!(menu.state(0), ButtonState::Pressed);
let dragged = PointerInput {
pos: (second.min + second.max) * 0.5,
down: true,
released: false,
secondary_pressed: false,
};
assert_eq!(menu.point(&layout, &mut ui, dragged), None);
assert_eq!(
menu.state(1),
ButtonState::Idle,
"the neighbour drew Pressed while the capture belongs to the first item",
);
assert_eq!(
menu.state(0),
ButtonState::Idle,
"the cursor left the captured item"
);
}
#[test]
fn render_draws_each_frame_before_the_text_on_it() {
let atlas = atlas();
let menu = pause_menu();
let layout = menu.layout((960, 720), &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let shape: Vec<String> = dl
.commands()
.iter()
.map(|command| match command {
DrawCommand::Image { .. } => "I".to_owned(),
DrawCommand::Text { text, .. } => text.clone(),
other => panic!("a menu of buttons drew {other:?}"),
})
.collect();
let quads = |count: usize| std::iter::repeat_n("I".to_owned(), count);
let mut expected: Vec<String> = quads(1 + 9).collect();
expected.push("PAUSED".to_owned());
for (label, hint) in [
("RESUME", "ESC"),
("FULLSCREEN", "F11"),
("DEBUG OVERLAY", "F3"),
] {
expected.extend(quads(9));
expected.extend([label.to_owned(), hint.to_owned()]);
}
assert_eq!(shape, expected);
}
#[test]
fn an_item_with_no_hint_draws_no_hint() {
let atlas = atlas();
let menu = Menu::new("T", vec![MenuItem::new(1, "OK", "")]);
let layout = menu.layout((960, 720), &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
assert_eq!(
dl.len(),
1 + 9 + 9 + 2,
"the scrim, the frame, one button, the title and the label, and nothing else"
);
}
fn pictures(dl: &DrawList) -> Vec<(Vec2, Vec2, Vec2)> {
dl.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Image {
min, max, uv_min, ..
} => Some((*min, *max, *uv_min)),
_ => None,
})
.collect()
}
#[test]
fn the_scrim_covers_the_screen_and_the_frame_tiles_the_panel() {
let atlas = atlas();
let menu = pause_menu();
let skin = skin();
for extent in EXTENTS {
let layout = menu.layout(extent, &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin);
let DrawCommand::Image { min, max, tint, .. } = &dl.commands()[0] else {
panic!("{extent:?}: the first command is not the scrim");
};
assert_eq!((*min, *max), layout.scrim(), "{extent:?}");
assert_eq!(*tint, layout.style().scrim_color);
let frame = &pictures(&dl)[1..10];
let area: f32 = frame
.iter()
.map(|(min, max, _)| (max.x - min.x) * (max.y - min.y))
.sum();
let (panel_min, panel_max) = layout.panel();
let low = frame
.iter()
.fold(Vec2::splat(f32::MAX), |acc, q| acc.min(q.0));
let high = frame
.iter()
.fold(Vec2::splat(f32::MIN), |acc, q| acc.max(q.1));
assert_eq!((low, high), (panel_min, panel_max), "{extent:?}");
assert_eq!(area, layout.panel_size().x * layout.panel_size().y);
}
}
#[test]
fn a_state_change_moves_the_uvs_and_leaves_the_rectangle_alone() {
let atlas = atlas();
let skin = skin();
let mut menu = pause_menu();
let layout = menu.layout((960, 720), &atlas);
let button = |menu: &Menu, index: usize| {
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin);
pictures(&dl)[10 + index * 9..10 + (index + 1) * 9].to_vec()
};
let idle = button(&menu, 1);
let hovered = button(&menu, 0);
menu.press(true);
let pressed = button(&menu, 0);
assert_eq!(menu.state(0), ButtonState::Pressed);
for quad in 0..9 {
assert_eq!(
(hovered[quad].0, hovered[quad].1),
(pressed[quad].0, pressed[quad].1)
);
assert_ne!(hovered[quad].2, pressed[quad].2, "quad {quad}");
assert_ne!(idle[quad].2, hovered[quad].2, "quad {quad}");
assert_ne!(idle[quad].2, pressed[quad].2, "quad {quad}");
}
}
#[test]
fn the_frames_corner_quads_are_the_insets_at_the_menus_scale() {
let atlas = atlas();
let skin = skin();
let style = MenuStyle::pixel_art(3);
let small = Menu::new("GO", vec![MenuItem::new(1, "OK", "")]);
let large = Menu::new(
"A MUCH LONGER TITLE",
(0..5)
.map(|i| MenuItem::new(i, "A VERY LONG MENU ITEM LABEL", "SHIFT+F11"))
.collect(),
);
let corners = |menu: &Menu| {
let layout = menu.layout_with((1600, 1200), &atlas, &style);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin);
let frame = pictures(&dl)[1..10].to_vec();
[0usize, 2, 6, 8].map(|index| (frame[index].1 - frame[index].0, frame[index].2))
};
let (a, b) = (corners(&small), corners(&large));
assert_eq!(a, b, "a corner changed size or picture with the menu");
for (size, _) in a {
assert_eq!(size, Vec2::splat(PANEL_INSETS.left * style.scale));
}
}
#[test]
fn every_label_is_inside_the_button_it_belongs_to() {
let atlas = atlas();
let menu = pause_menu();
for extent in EXTENTS {
let layout = menu.layout(extent, &atlas);
let style = layout.style();
for (item, placed) in menu.items().iter().zip(layout.items()) {
let label_end =
placed.label_pos.x + text_width(&atlas, &item.label, style.item_size);
assert!(
placed.label_pos.x >= placed.min.x && label_end <= placed.max.x,
"{extent:?}: {} runs from {} to {label_end} in a button \
{}..{}",
item.label,
placed.label_pos.x,
placed.min.x,
placed.max.x,
);
let hint_end = placed.hint_pos.x + text_width(&atlas, &item.hint, style.item_size);
assert!(
placed.hint_pos.x >= label_end && hint_end <= placed.max.x,
"{extent:?}: the hint {} overlaps its label or leaves the button",
item.hint,
);
let bottom = placed.label_pos.y + line_height(style.item_size);
assert!(
placed.label_pos.y >= placed.min.y && bottom <= placed.max.y,
"{extent:?}: {} is not vertically inside its button",
item.label,
);
}
let title_end =
layout.title_pos().x + text_width(&atlas, &menu.title, style.title_size);
let (min, max) = layout.panel();
assert!(layout.title_pos().x >= min.x && title_end <= max.x);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
None,
Start,
Paused,
}
fn start_menu() -> Menu {
Menu::new(
"START",
vec![
MenuItem::new(10, "PLAY", "SPACE"),
MenuItem::new(2, "FULLSCREEN", "F11"),
],
)
}
fn menus() -> MenuSet<Kind> {
MenuSet::new(
Kind::None,
vec![(Kind::Start, start_menu()), (Kind::Paused, pause_menu())],
)
}
fn over(menus: &MenuSet<Kind>, extent: (u32, u32), index: usize) -> Vec2 {
let layout = menus.current().expect("a menu").layout(extent, &atlas());
let item = layout.items()[index];
(item.min + item.max) * 0.5
}
fn press_at(pos: Vec2) -> PointerInput {
PointerInput {
pos,
down: true,
released: false,
secondary_pressed: false,
}
}
fn release_at(pos: Vec2) -> PointerInput {
PointerInput {
pos,
down: false,
released: true,
secondary_pressed: false,
}
}
#[test]
fn a_state_with_no_menu_draws_nothing_and_takes_no_input() {
let extent = (960, 720);
let mut menus = menus();
assert_eq!(menus.kind(), Kind::None);
assert!(!menus.is_showing());
assert!(menus.current().is_none());
assert!(menus.current_mut().is_none());
assert_eq!(menus.activate(), None, "there is no menu to activate");
assert_eq!(menus.point(extent, &atlas(), press_at(Vec2::ZERO)), None);
menus.select_next();
menus.select_previous();
menus.press(true);
menus.show(Kind::Paused);
assert!(menus.is_showing());
assert_eq!(menus.current().expect("a menu").selected(), 0);
assert_eq!(
menus.current().expect("a menu").state(0),
ButtonState::Hovered
);
}
#[test]
fn the_keyboard_selects_and_activates() {
let mut menus = menus();
menus.show(Kind::Paused);
assert_eq!(menus.activate(), Some(1));
menus.select_next();
assert_eq!(menus.activate(), Some(2));
menus.select_next();
assert_eq!(menus.activate(), Some(3));
menus.select_next();
assert_eq!(menus.activate(), Some(1), "it wraps");
menus.select_previous();
assert_eq!(menus.activate(), Some(3));
menus.show(Kind::Start);
assert_eq!(menus.activate(), Some(10));
}
#[test]
fn holding_the_commit_key_presses_the_selected_button() {
let mut menus = menus();
menus.show(Kind::Paused);
menus.select_next();
menus.press(true);
let menu = menus.current().expect("a menu");
assert_eq!(menu.state(1), ButtonState::Pressed);
assert_eq!(menu.state(0), ButtonState::Idle);
menus.press(false);
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Hovered,
);
}
#[test]
fn the_pointer_clicks_a_button() {
let extent = (960, 720);
let mut menus = menus();
menus.show(Kind::Paused);
let target = over(&menus, extent, 1);
assert_eq!(menus.point(extent, &atlas(), press_at(target)), None);
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Pressed,
"the pointer's press did not reach the art",
);
assert_eq!(menus.point(extent, &atlas(), release_at(target)), Some(2));
let corner = Vec2::new(3.0, 3.0);
assert_eq!(menus.point(extent, &atlas(), press_at(corner)), None);
assert_eq!(menus.point(extent, &atlas(), release_at(corner)), None);
}
#[test]
fn a_cancelled_press_fires_nothing_and_frees_the_capture() {
let extent = (960, 720);
let mut menus = menus();
menus.show(Kind::Paused);
let target = over(&menus, extent, 1);
assert!(!menus.press_captured(), "nothing is pressed yet");
menus.point(extent, &atlas(), press_at(target));
assert!(menus.press_captured(), "the press latched nothing");
menus.cancel_press();
assert!(
!menus.press_captured(),
"the cancel left the capture behind"
);
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Idle,
"the button stayed pressed under a finger that is gone",
);
assert_eq!(
menus.point(extent, &atlas(), release_at(target)),
None,
"the cancelled press fired on the lift anyway",
);
menus.point(extent, &atlas(), press_at(target));
assert_eq!(menus.point(extent, &atlas(), release_at(target)), Some(2));
}
#[test]
fn a_press_that_lands_on_no_button_captures_nothing() {
let extent = (960, 720);
let mut menus = menus();
menus.show(Kind::Paused);
menus.point(extent, &atlas(), press_at(Vec2::new(3.0, 3.0)));
assert!(
!menus.press_captured(),
"a press in the corner of the screen latched a button",
);
menus.point(extent, &atlas(), press_at(over(&menus, extent, 0)));
assert!(menus.press_captured());
}
#[test]
fn switching_menus_drops_the_press() {
let extent = (960, 720);
let mut menus = menus();
menus.show(Kind::Paused);
assert_eq!(
menus.current().expect("a menu").items()[1].id,
start_menu().items()[1].id,
"the two menus stopped sharing a button, so this test guards nothing",
);
menus.point(extent, &atlas(), press_at(over(&menus, extent, 1)));
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Pressed,
);
menus.show(Kind::Start);
assert_eq!(
menus.current().expect("a menu").state(0),
ButtonState::Hovered,
"the new menu inherited a press nobody is making",
);
let shared = over(&menus, extent, 1);
assert_eq!(
menus.point(extent, &atlas(), release_at(shared)),
None,
"a release fired a button whose press was on another menu",
);
menus.show(Kind::Paused);
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Idle,
"the menu came back still holding the press it was left with",
);
}
#[test]
fn showing_the_same_menu_again_keeps_the_selection_and_the_press() {
let mut menus = menus();
menus.show(Kind::Paused);
menus.select_next();
menus.press(true);
menus.show(Kind::Paused);
assert_eq!(menus.current().expect("a menu").selected(), 1);
assert_eq!(
menus.current().expect("a menu").state(1),
ButtonState::Pressed,
);
}
#[test]
fn a_replaced_menu_drops_the_press() {
let extent = (960, 720);
let mut menus = menus();
menus.show(Kind::Start);
menus.point(extent, &atlas(), press_at(over(&menus, extent, 0)));
assert_eq!(
menus.current().expect("a menu").state(0),
ButtonState::Pressed,
);
menus.replace(
Kind::Start,
Menu::new(
"START",
vec![
MenuItem::new(10, "OTHER", "SPACE"),
MenuItem::new(2, "FULLSCREEN", "F11"),
],
),
);
assert_eq!(
menus.current().expect("a menu").items()[0].label,
"OTHER",
"the swap did not take",
);
let same_slot = over(&menus, extent, 0);
assert_eq!(
menus.point(extent, &atlas(), release_at(same_slot)),
None,
"a release fired a button the player never pressed",
);
}
#[test]
fn replacing_a_state_with_no_menu_adds_it() {
let mut menus = MenuSet::new(Kind::None, vec![(Kind::Paused, pause_menu())]);
menus.show(Kind::Start);
assert!(!menus.is_showing(), "Start has no menu yet");
menus.replace(Kind::Start, start_menu());
assert!(menus.is_showing());
assert_eq!(menus.current().expect("a menu").title, "START");
assert_eq!(menus.activate(), Some(10));
}
#[test]
#[should_panic(expected = "two menus claim the same state")]
fn two_menus_for_one_state_is_rejected() {
let _ = MenuSet::new(
Kind::None,
vec![(Kind::Paused, pause_menu()), (Kind::Paused, start_menu())],
);
}
const DIAL: WidgetId = 20;
fn slider_menu() -> Menu {
Menu::new(
"OPTIONS",
vec![
MenuItem::new(10, "BACK", "ESC"),
MenuItem::slider(DIAL, "EXPOSURE", "1.00", 0.5),
],
)
}
fn groove(menu: &Menu, extent: (u32, u32)) -> ((Vec2, Vec2), (f32, f32)) {
let layout = menu.layout(extent, &atlas());
let track = layout.items()[1]
.track
.expect("the slider row has a groove");
(track, handle_travel(track, layout.style().handle_size.x))
}
#[test]
fn dragging_a_slider_moves_the_handle_to_the_pointer() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
let (track, (start, end)) = groove(&menu, extent);
for (fraction, expected) in [(0.0, 0.0), (0.25, 0.25), (1.0, 1.0)] {
let layout = menu.layout(extent, &atlas());
let x = start + (end - start) * fraction;
let y = (track.0.y + track.1.y) * 0.5;
menu.point(&layout, &mut ui, press_at(Vec2::new(x, y)));
let at = menu.slider(DIAL).expect("the row is a slider");
assert!(
(at - expected).abs() <= 1e-3,
"a press {fraction} of the way along put the handle at {at}",
);
}
}
#[test]
fn a_drag_past_either_end_of_the_groove_stops_there() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
let (track, _) = groove(&menu, extent);
let y = (track.0.y + track.1.y) * 0.5;
let layout = menu.layout(extent, &atlas());
menu.point(&layout, &mut ui, press_at(Vec2::new(track.0.x, y)));
menu.point(
&layout,
&mut ui,
press_at(Vec2::new(track.0.x - 10_000.0, y)),
);
assert_eq!(menu.slider(DIAL), Some(0.0));
menu.point(
&layout,
&mut ui,
press_at(Vec2::new(track.1.x + 10_000.0, y)),
);
assert_eq!(menu.slider(DIAL), Some(1.0));
}
#[test]
fn a_drag_that_leaves_the_row_still_moves_the_handle() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
let (track, (start, end)) = groove(&menu, extent);
let layout = menu.layout(extent, &atlas());
let inside = Vec2::new(start, (track.0.y + track.1.y) * 0.5);
menu.point(&layout, &mut ui, press_at(inside));
assert_eq!(menu.slider(DIAL), Some(0.0));
let outside = Vec2::new(start + (end - start) * 0.75, 0.0);
menu.point(&layout, &mut ui, press_at(outside));
let at = menu.slider(DIAL).expect("the row is a slider");
assert!(
(at - 0.75).abs() <= 1e-3,
"the drag left the handle at {at}"
);
}
#[test]
fn a_slider_fires_nothing_from_either_device() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
menu.select_next();
assert_eq!(menu.selected(), 1, "the slider is the second row");
menu.press(true);
assert_eq!(menu.activate(), None, "the commit key fired the slider");
let (track, _) = groove(&menu, extent);
let at = Vec2::new((track.0.x + track.1.x) * 0.5, (track.0.y + track.1.y) * 0.5);
let layout = menu.layout(extent, &atlas());
menu.point(&layout, &mut ui, press_at(at));
assert_eq!(
menu.point(&layout, &mut ui, release_at(at)),
None,
"letting go of a slider was reported as a click",
);
menu.select_previous();
assert_eq!(menu.activate(), Some(10));
}
#[test]
fn a_write_is_refused_while_the_handle_is_held_and_taken_after() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
let (track, _) = groove(&menu, extent);
let y = (track.0.y + track.1.y) * 0.5;
let layout = menu.layout(extent, &atlas());
assert!(menu.set_slider(DIAL, 0.25), "an untouched handle takes it");
assert_eq!(menu.slider(DIAL), Some(0.25));
menu.point(&layout, &mut ui, press_at(Vec2::new(track.1.x, y)));
assert_eq!(menu.slider(DIAL), Some(1.0));
assert!(
!menu.set_slider(DIAL, 0.25),
"the write went through mid-drag",
);
assert_eq!(menu.slider(DIAL), Some(1.0));
menu.point(&layout, &mut ui, release_at(Vec2::new(track.1.x, y)));
assert!(menu.set_slider(DIAL, 0.25), "the drag was never let go of");
assert_eq!(menu.slider(DIAL), Some(0.25));
}
#[test]
fn a_nan_position_lands_at_the_start() {
let mut menu = slider_menu();
assert!(menu.set_slider(DIAL, f32::NAN));
assert_eq!(menu.slider(DIAL), Some(0.0));
assert_eq!(Slider::new(f32::NAN).position(), 0.0);
assert_eq!(Slider::new(f32::INFINITY).position(), 1.0);
}
#[test]
fn only_a_slider_row_has_a_value() {
let mut menu = slider_menu();
assert_eq!(menu.slider(10), None, "the button row reported a value");
assert_eq!(menu.slider(999), None, "an absent row reported a value");
assert!(!menu.set_slider(10, 0.5), "a button row took a value");
}
#[test]
fn a_key_moves_the_highlighted_slider_and_nothing_else() {
let mut menu = slider_menu();
assert!(!menu.nudge_slider(true), "a button row took a nudge");
assert_eq!(menu.slider(DIAL), Some(0.5), "the far row moved anyway");
menu.select_next();
assert!(menu.nudge_slider(true), "the highlighted slider refused");
assert_eq!(menu.slider(DIAL), Some(0.5 + Slider::KEY_STEP));
assert!(menu.nudge_slider(false), "the slider refused to come back");
assert_eq!(menu.slider(DIAL), Some(0.5));
}
#[test]
fn a_nudge_at_the_end_of_the_groove_moves_nothing() {
let mut menu = slider_menu();
menu.select_next();
for _ in 0..(1.0 / Slider::KEY_STEP) as u32 + 1 {
menu.nudge_slider(true);
}
assert_eq!(menu.slider(DIAL), Some(1.0), "the handle left the groove");
assert!(
!menu.nudge_slider(true),
"a handle at the end reported that it moved"
);
}
#[test]
fn a_key_does_not_move_a_handle_the_pointer_is_holding() {
let extent = (960, 720);
let mut menu = slider_menu();
let mut ui = UiState::new();
let (track, _) = groove(&menu, extent);
let middle = Vec2::new((track.0.x + track.1.x) * 0.5, (track.0.y + track.1.y) * 0.5);
let layout = menu.layout(extent, &atlas());
menu.point(&layout, &mut ui, press_at(middle));
let held = menu.slider(DIAL).expect("the row is a slider");
assert!(!menu.nudge_slider(true), "a held handle took a key");
assert_eq!(menu.slider(DIAL), Some(held), "the held handle moved");
menu.point(&layout, &mut ui, release_at(middle));
assert!(
menu.nudge_slider(false),
"the released handle refused a key"
);
assert!(
menu.slider(DIAL).expect("still a slider") < held,
"the key moved it the wrong way, or not at all, from {held}"
);
}
#[test]
fn a_slider_row_widens_the_panel_by_its_groove() {
let atlas = atlas();
let style = MenuStyle::pixel_art(1);
let with_button = Menu::new(
"OPTIONS",
vec![
MenuItem::new(10, "BACK", "ESC"),
MenuItem::new(DIAL, "EXPOSURE", "1.00"),
],
);
let grew =
slider_menu().panel_size(&atlas, &style).x - with_button.panel_size(&atlas, &style).x;
assert!(
grew >= style.track_width + style.hint_gap - 1e-3,
"a slider row only widened the panel by {grew}",
);
}
#[test]
fn the_handle_stays_inside_the_groove_at_both_ends() {
let extent = (960, 720);
let atlas = atlas();
for position in [0.0, 0.5, 1.0] {
let mut menu = slider_menu();
assert!(menu.set_slider(DIAL, position));
let layout = menu.layout(extent, &atlas);
let placed = layout.items()[1];
let track = placed.track.expect("a groove");
let label_end = placed.label_pos.x + atlas.text_width("EXPOSURE", 1.0);
assert!(
track.0.x >= label_end && track.1.x <= placed.hint_pos.x,
"at {position} the groove {track:?} overlaps the row's text",
);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let handle = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Rect { min, max, color }
if *color == layout.style().handle_color =>
{
Some((*min, *max))
}
_ => None,
})
.next()
.expect("the handle is drawn");
assert!(
handle.0.x >= track.0.x - 1e-3 && handle.1.x <= track.1.x + 1e-3,
"at {position} the handle {handle:?} left the groove {track:?}",
);
}
}
#[test]
fn the_fill_grows_with_the_value() {
let extent = (960, 720);
let atlas = atlas();
let mut widths = Vec::new();
for position in [0.0, 0.5, 1.0] {
let mut menu = slider_menu();
assert!(menu.set_slider(DIAL, position));
let layout = menu.layout(extent, &atlas);
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let fill = dl
.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Rect { min, max, color }
if *color == layout.style().fill_color =>
{
Some(max.x - min.x)
}
_ => None,
})
.expect("the fill is drawn");
widths.push(fill);
}
assert!(
widths[0] < widths[1] && widths[1] < widths[2],
"the fill widths were {widths:?}",
);
}
const MODE: WidgetId = 30;
const MODES: [&str; 3] = ["windowed", "borderless", "exclusive"];
fn cycler_menu() -> Menu {
Menu::new(
"OPTIONS",
vec![
MenuItem::new(10, "BACK", "ESC"),
MenuItem::cycler(MODE, "DISPLAY", MODES[1], MODES.len(), 1),
],
)
}
#[test]
fn a_key_steps_the_highlighted_cycler_and_stops_at_its_ends() {
let mut menu = cycler_menu();
assert!(
!menu.cycler_highlighted(),
"the button row read as a cycler"
);
assert!(!menu.nudge_cycler(true), "a button row took a step");
assert_eq!(menu.cycler(MODE), Some(1), "the far row stepped anyway");
menu.select_next();
assert!(menu.cycler_highlighted());
assert!(menu.nudge_cycler(true), "the highlighted cycler refused");
assert_eq!(menu.cycler(MODE), Some(2));
assert!(
!menu.nudge_cycler(true),
"the last choice reported a step forward"
);
assert_eq!(menu.cycler(MODE), Some(2), "a key at the end went round");
assert!(menu.nudge_cycler(false));
assert!(menu.nudge_cycler(false));
assert_eq!(menu.cycler(MODE), Some(0));
assert!(
!menu.nudge_cycler(false),
"the first choice reported a step back"
);
assert_eq!(menu.cycler(MODE), Some(0), "a key at the start went round");
}
#[test]
fn the_commit_key_and_a_click_step_a_cycler_round_and_report_nothing() {
let extent = (960, 720);
let mut menu = cycler_menu();
let mut ui = UiState::new();
menu.select_next();
menu.press(true);
assert_eq!(menu.activate(), None, "the commit key fired the cycler");
assert_eq!(menu.cycler(MODE), Some(2));
assert_eq!(menu.activate(), None);
assert_eq!(
menu.cycler(MODE),
Some(0),
"the commit key stopped at the end"
);
let layout = menu.layout(extent, &atlas());
let row = layout.items()[1];
let at = (row.min + row.max) * 0.5;
menu.point(&layout, &mut ui, press_at(at));
assert_eq!(
menu.point(&layout, &mut ui, release_at(at)),
None,
"a click on a cycler was reported as a click",
);
assert_eq!(menu.cycler(MODE), Some(1), "the click did not step it");
menu.select_previous();
assert_eq!(menu.activate(), Some(10));
}
#[test]
fn only_a_cycler_row_has_a_choice() {
let mut menu = cycler_menu();
assert_eq!(menu.cycler(10), None, "the button row reported a choice");
assert_eq!(menu.cycler(999), None, "an absent row reported a choice");
assert!(!menu.set_cycler(10, 1), "a button row took a choice");
assert!(menu.set_cycler(MODE, 99));
assert_eq!(menu.cycler(MODE), Some(MODES.len() - 1));
assert!(menu.set_cycler(MODE, 0));
assert_eq!(menu.cycler(MODE), Some(0));
}
#[test]
fn a_cycler_draws_a_chevron_only_where_a_step_would_go() {
let atlas = atlas();
let extent = (960, 720);
let mut menu = cycler_menu();
assert!(menu.set_item_hint(MODE, "same"));
let mut seen = Vec::new();
for (chosen, expected) in [(1, "< same >"), (0, " same >"), (2, "< same ")] {
assert!(menu.set_cycler(MODE, chosen));
let layout = menu.layout(extent, &atlas);
let row = layout.items()[1];
assert!(row.track.is_none(), "a cycler row was given a groove");
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin());
let texts: Vec<&str> = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Text { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert!(
texts.contains(&expected),
"choice {chosen} drew {texts:?}, not {expected:?}"
);
seen.push((row.hint_pos, layout.panel_size()));
}
let (anchor, panel) = seen[0];
for (pos, size) in &seen[1..] {
assert_eq!(*pos, anchor, "the caption moved as the chevrons changed");
assert_eq!(*size, panel, "the panel resized as the chevrons changed");
}
}
#[test]
fn a_cycler_with_no_choices_refuses_every_step() {
let mut empty = Cycler::new(0, 3);
assert_eq!(empty.chosen(), 0);
for (forward, wrap) in [(true, true), (true, false), (false, true), (false, false)] {
assert!(!empty.step(forward, wrap), "an empty cycler stepped");
}
assert_eq!(Cycler::new(3, 9).chosen(), 2);
let mut round = Cycler::new(3, 2);
assert!(round.step(true, true), "a wrap from the end did not move");
assert_eq!(round.chosen(), 0);
assert!(round.step(false, true));
assert_eq!(round.chosen(), 2);
assert!(!round.step(true, false));
assert_eq!(round.chosen(), 2);
}
#[test]
fn the_panel_grows_exactly_with_the_scale() {
let atlas = atlas();
let mut mixed = slider_menu();
mixed
.items
.push(MenuItem::cycler(MODE, "DISPLAY", "windowed", 3, 1));
mixed.items.push(MenuItem::new(40, "NO HINT", ""));
for menu in [pause_menu(), mixed, Menu::new("", Vec::new())] {
let base = menu.panel_size(&atlas, &MenuStyle::pixel_art(1));
assert!(base.x > 0.0 && base.y > 0.0, "{base:?}");
for scale in 2..=MenuStyle::MAX_SCALE {
assert_eq!(
menu.panel_size(&atlas, &MenuStyle::pixel_art(scale)),
base * scale as f32,
"{:?} at scale {scale}",
menu.title,
);
}
}
}
#[test]
fn the_sheet_draws_the_colours_and_the_slices_the_style_restates() {
let atlas = atlas();
let skin = skin();
let mut menu = slider_menu();
menu.items.push(MenuItem::new(11, "QUIT", "Q"));
menu.subtitle = vec![Caption::warning("UNSAVED")];
let layout = menu.layout((960, 720), &atlas);
let style = layout.style();
let mut dl = DrawList::new();
menu.render(&mut dl, &layout, &skin);
let text_colour = |wanted: &str| {
dl.commands()
.iter()
.find_map(|command| match command {
DrawCommand::Text { text, color, .. } if text == wanted => Some(*color),
_ => None,
})
.unwrap_or_else(|| panic!("{wanted} is not drawn"))
};
assert_eq!(text_colour("OPTIONS"), style.title_color);
assert_eq!(text_colour("BACK"), style.label_color);
assert_eq!(text_colour("ESC"), style.hint_color);
assert_eq!(text_colour("UNSAVED"), style.warning_color);
let rect_colours: Vec<[f32; 4]> = dl
.commands()
.iter()
.filter_map(|command| match command {
DrawCommand::Rect { color, .. } => Some(*color),
_ => None,
})
.collect();
assert_eq!(
rect_colours,
[style.track_color, style.fill_color, style.handle_color],
"the groove, its fill and the handle, in that order"
);
let DrawCommand::Image { tint, .. } = dl.commands()[0] else {
panic!("the scrim is not first");
};
assert_eq!(tint, style.scrim_color);
let corner_uvs = |min: usize| {
let DrawCommand::Image { uv_min, uv_max, .. } = pictures_with_uv_max(&dl)[min] else {
unreachable!("filtered to images");
};
(uv_min, uv_max)
};
assert_eq!(
corner_uvs(1),
(
skin.panel.image.uv(Vec2::ZERO),
skin.panel
.image
.uv(Vec2::new(PANEL_INSETS.left, PANEL_INSETS.top))
),
"the panel is not cut at PANEL_INSETS"
);
assert_eq!(
corner_uvs(10),
(
skin.buttons.hovered.image.uv(Vec2::ZERO),
skin.buttons
.hovered
.image
.uv(Vec2::new(BUTTON_INSETS.left, BUTTON_INSETS.top))
),
"the buttons are not cut at BUTTON_INSETS"
);
assert_eq!(
corner_uvs(19).0,
skin.buttons.idle.image.uv(Vec2::ZERO),
"an idle row does not draw the idle frame"
);
}
fn pictures_with_uv_max(dl: &DrawList) -> Vec<DrawCommand> {
dl.commands()
.iter()
.filter(|command| matches!(command, DrawCommand::Image { .. }))
.cloned()
.collect()
}
}