codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! Default sizing for built-in UI layouts, kept here so games built on top of
//! `codecraft` don't have to invent their own pixel constants.
use super::rect::Rect;

/// Where a panel sits on screen.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Anchor {
    #[default]
    Center,
    TopLeft,
    TopRight,
    BottomLeft,
    BottomRight,
}

impl Anchor {
    /// Which way a submenu should open from a panel sitting here, when
    /// nothing says otherwise: away from the edge the panel is against.
    ///
    /// A menu in the bottom-right corner has no room to its right, so its
    /// submenus go left. This is only the *preference* -- see
    /// [`submenu_rect`], which will still flip it if the preferred side turns
    /// out not to fit either.
    pub fn expands(self) -> Expand {
        match self {
            Anchor::TopRight | Anchor::BottomRight => Expand::Left,
            Anchor::Center | Anchor::TopLeft | Anchor::BottomLeft => Expand::Right,
        }
    }
}

/// Which side of its parent a submenu opens on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Expand {
    /// Take the parent panel's own preference, and flip it if there is no
    /// room. Almost always what you want.
    #[default]
    Automatic,
    Left,
    Right,
}

pub const BUTTON_WIDTH: f32 = 200.0;
pub const BUTTON_HEIGHT: f32 = 56.0;
pub const BUTTON_SPACING: f32 = 20.0;
pub const PANEL_PADDING: f32 = 5.0;
pub const LABEL_PIXEL_SIZE: f32 = 3.0;

/// How tall a panel's title bar is, and how big its title is drawn.
pub const TITLE_HEIGHT: f32 = 26.0;
pub const TITLE_LABEL_SIZE: f32 = 2.0;
/// The close button is a square in the bar, inset a little from its edges.
pub const TITLE_INSET: f32 = 5.0;

/// Margin between a screen edge and a panel anchored to it.
pub const SCREEN_MARGIN: f32 = 16.0;

/// Room to leave either side of a label inside its button.
pub const LABEL_MARGIN: f32 = 24.0;

/// An application menu, as against a menu in a game.
///
/// A game menu is a handful of big targets you aim at, spaced apart so you
/// cannot hit the wrong one. An application menu is a list you read down and
/// then commit to: the rows touch, the names are left-aligned, and the whole
/// thing is only as wide as its longest entry. The two want different numbers,
/// not the same numbers scaled -- see [`Metrics::menu`].
pub const MENU_ROW_HEIGHT: f32 = 26.0;
pub const MENU_LABEL_SIZE: f32 = 2.0;
/// What a row leaves either side of its label.
pub const MENU_ROW_MARGIN: f32 = 10.0;
/// How big an icon in a menu row is, and the gap between it and the words.
pub const MENU_ICON: f32 = 12.0;
pub const MENU_ICON_GAP: f32 = 6.0;
/// How far a pointer triangle sticks out of the panel it belongs to.
pub const POINTER_SIZE: f32 = 9.0;

/// How big a panel draws its buttons.
///
/// One panel can want smaller buttons than another — a MENU tucked in a
/// corner beside a game is not a main menu — so the sizes travel with the
/// panel rather than being read from the constants at every use.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Metrics {
    pub button_width: f32,
    pub button_height: f32,
    pub spacing: f32,
    pub label_size: f32,
}

impl Default for Metrics {
    fn default() -> Self {
        Self::scaled(1.0)
    }
}

impl Metrics {
    /// The defaults, at `scale`. Padding is deliberately left out: it is the
    /// gap between a panel's edge and what is in it, and a small panel needs
    /// that gap just as much as a big one.
    pub fn scaled(scale: f32) -> Self {
        Self {
            button_width: BUTTON_WIDTH * scale,
            button_height: BUTTON_HEIGHT * scale,
            spacing: BUTTON_SPACING * scale,
            label_size: LABEL_PIXEL_SIZE * scale,
        }
    }

    /// The compact style an application menu is drawn in: rows that touch,
    /// small type, and only as wide as what is in it. See [`MENU_ROW_HEIGHT`].
    ///
    /// Width is left at zero because a menu has no natural one -- it is
    /// whatever its longest entry needs, which [`Metrics::snug`] works out.
    pub fn menu(scale: f32) -> Self {
        Self {
            button_width: 0.0,
            button_height: MENU_ROW_HEIGHT * scale,
            // The rows touch. A gap between them makes a menu read as a
            // column of buttons, which is what it should not look like.
            spacing: 0.0,
            label_size: MENU_LABEL_SIZE * scale,
        }
    }

    /// Exactly wide enough for these rows, with room for the icons a row may
    /// wear either side of its words.
    ///
    /// Unlike [`fitting`](Self::fitting) this *shrinks*: the default width is
    /// a game menu's and a menu of three-letter entries has no business being
    /// two hundred pixels wide.
    pub fn snug(
        mut self,
        rows: impl IntoIterator<Item = (impl AsRef<str>, bool, bool)>,
        scale: f32,
    ) -> Self {
        let margin = MENU_ROW_MARGIN * scale;
        let icon = (MENU_ICON + MENU_ICON_GAP) * scale;
        self.button_width = rows
            .into_iter()
            .map(|(label, leading, trailing)| {
                super::font::text_width(label.as_ref(), self.label_size)
                    + margin * 2.0
                    + if leading { icon } else { 0.0 }
                    + if trailing { icon } else { 0.0 }
            })
            .fold(0.0f32, f32::max);
        self
    }

    /// The same metrics, widened to fit every one of these labels.
    ///
    /// A fixed width is fine until a label outgrows it — "PLAY ONLINE" is
    /// wider than the default, and a label that runs out of its button looks
    /// broken.
    pub fn fitting(mut self, labels: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        self.button_width = labels
            .into_iter()
            .map(|label| {
                super::font::text_width(label.as_ref(), self.label_size)
                    + LABEL_MARGIN * self.label_size / LABEL_PIXEL_SIZE * 2.0
            })
            .fold(self.button_width, f32::max);
        self
    }
}

/// How wide a button has to be for its label to fit inside it, at the
/// default size.
pub fn button_width_for(labels: impl IntoIterator<Item = impl AsRef<str>>) -> f32 {
    Metrics::default().fitting(labels).button_width
}

/// How big a panel of `button_count` buttons is, at these metrics.
pub fn panel_size(button_count: usize, metrics: Metrics) -> (f32, f32) {
    let content_height = if button_count == 0 {
        0.0
    } else {
        metrics.button_height * button_count as f32 + metrics.spacing * (button_count - 1) as f32
    };
    (
        metrics.button_width + PANEL_PADDING * 2.0,
        content_height + PANEL_PADDING * 2.0,
    )
}

/// A panel with its top-left corner at `x`, `y`, and the buttons stacked
/// inside it.
///
/// Split out from [`vertical_menu`] because a submenu is placed against its
/// parent rather than against the screen, and the stacking is the same either
/// way.
pub fn stack_at(x: f32, y: f32, button_count: usize, metrics: Metrics) -> (Rect, Vec<Rect>) {
    let (panel_width, panel_height) = panel_size(button_count, metrics);
    let panel = Rect::new(x, y, panel_width, panel_height);

    let x = panel.center_x() - metrics.button_width * 0.5;
    let mut y = panel.y + PANEL_PADDING;
    let mut buttons = Vec::with_capacity(button_count);
    for _ in 0..button_count {
        buttons.push(Rect::new(x, y, metrics.button_width, metrics.button_height));
        y += metrics.button_height + metrics.spacing;
    }
    (panel, buttons)
}

/// Where a submenu of `button_count` buttons goes, opening from `row` inside
/// `parent_panel`.
///
/// Sideways it is placed against the *panel*, not against the row: a submenu
/// that starts at its parent row's edge covers the rest of the panel it came
/// from, and a covered sibling is still a sibling -- the pointer sitting on
/// the submenu is then also sitting on the row underneath, and both open at
/// once. Flush outside the panel, nothing overlaps and only one is ever up.
///
/// The preferred side is taken first; if the panel would run off that edge
/// the other side is used, and if neither fits it is clamped to the screen --
/// a menu half off the screen is bad, and one entirely off it is useless.
/// Vertically it lines up with its row and is nudged back inside.
pub fn submenu_rect(
    parent_panel: Rect,
    row: Rect,
    button_count: usize,
    metrics: Metrics,
    expand: Expand,
    preferred: Expand,
    screen_width: f32,
    screen_height: f32,
) -> (Rect, Vec<Rect>) {
    let (width, height) = panel_size(button_count, metrics);

    let want = match expand {
        Expand::Automatic => preferred,
        side => side,
    };
    let left = parent_panel.x - width;
    let right = parent_panel.x + parent_panel.width;
    let fits = |x: f32| x >= 0.0 && x + width <= screen_width;

    let x = match want {
        Expand::Left if fits(left) => left,
        Expand::Left if fits(right) => right,
        Expand::Left => left,
        // `Automatic` has already been resolved; treat anything else as
        // opening rightwards.
        _ if fits(right) => right,
        _ if fits(left) => left,
        _ => right,
    };

    // Level with the row it opened from, so its first entry lines up with the
    // row that names it. If it will not fit downwards from there -- a menu in
    // the bottom corner with seven entries in it -- it hangs the other way
    // instead, growing up from the row rather than down from it. Clamping
    // alone would slide it off its own row and, in a short window, cut it off.
    let top = row.y + row.height * 0.5 - metrics.button_height * 0.5 - PANEL_PADDING;
    let bottom = row.y + row.height * 0.5 + metrics.button_height * 0.5 + PANEL_PADDING - height;
    let floor = screen_height - SCREEN_MARGIN;
    let y = match top + height <= floor {
        true => top,
        false => bottom,
    };
    // And if it fits neither way the screen wins: a menu whose head is off the
    // top cannot be read at all, so that edge is the one that gives.
    let y = y.min(floor - height).max(SCREEN_MARGIN);

    stack_at(
        x.clamp(0.0, (screen_width - width).max(0.0)),
        y,
        button_count,
        metrics,
    )
}

/// Computes a panel rect and the vertically stacked button rects inside it,
/// sized for `button_count` buttons using the constants above and placed
/// according to `anchor`.
pub fn vertical_menu(
    screen_width: f32,
    screen_height: f32,
    button_count: usize,
    anchor: Anchor,
    metrics: Metrics,
) -> (Rect, Vec<Rect>) {
    vertical_menu_offset(
        screen_width,
        screen_height,
        button_count,
        anchor,
        metrics,
        (0.0, 0.0),
    )
}

/// [`vertical_menu`], moved by `offset` pixels -- for a panel that has to sit
/// clear of something else already in that corner.
pub fn vertical_menu_offset(
    screen_width: f32,
    screen_height: f32,
    button_count: usize,
    anchor: Anchor,
    metrics: Metrics,
    offset: (f32, f32),
) -> (Rect, Vec<Rect>) {
    let (panel_width, panel_height) = panel_size(button_count, metrics);
    let right = screen_width - panel_width - SCREEN_MARGIN;
    let bottom = screen_height - panel_height - SCREEN_MARGIN;

    let (x, y) = match anchor {
        Anchor::Center => (
            screen_width * 0.5 - panel_width * 0.5,
            screen_height * 0.5 - panel_height * 0.5,
        ),
        Anchor::TopLeft => (SCREEN_MARGIN, SCREEN_MARGIN),
        Anchor::TopRight => (right, SCREEN_MARGIN),
        Anchor::BottomLeft => (SCREEN_MARGIN, bottom),
        Anchor::BottomRight => (right, bottom),
    };

    stack_at(x + offset.0, y + offset.1, button_count, metrics)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_short_label_leaves_the_button_at_its_default_width() {
        assert_eq!(button_width_for(["QUIT"]), BUTTON_WIDTH);
        assert_eq!(button_width_for(["BACK", "QUIT"]), BUTTON_WIDTH);
    }

    #[test]
    fn the_default_width_is_a_floor_rather_than_a_size() {
        // A long enough label is wider than the fixed width once its margins
        // are counted, which is why the panel has to measure its labels. What
        // counts as long enough moves with `LABEL_PIXEL_SIZE`, so this uses a
        // label no plausible size would fit.
        assert!(button_width_for(["A REALLY RATHER LONG LABEL"]) > BUTTON_WIDTH);
    }

    #[test]
    fn a_long_label_widens_the_button_to_fit() {
        // "PLAY ONLINE" is wider than the default, and used to run out of it.
        let width = button_width_for(["PLAY ONLINE"]);
        assert!(
            width > BUTTON_WIDTH,
            "the button should have grown: {width}"
        );
        assert!(
            width
                >= super::super::font::text_width("PLAY ONLINE", LABEL_PIXEL_SIZE)
                    + LABEL_MARGIN * 2.0,
            "the label plus its margins must fit",
        );
    }

    #[test]
    fn a_panel_is_as_wide_as_its_widest_label() {
        let mixed = button_width_for(["QUIT", "QUICK PAIR 5+0", "BACK"]);
        assert_eq!(mixed, button_width_for(["QUICK PAIR 5+0"]));
    }

    #[test]
    fn a_scaled_panel_shrinks_its_buttons_and_their_labels() {
        let half = Metrics::scaled(0.5);

        assert_eq!(half.button_width, BUTTON_WIDTH * 0.5);
        assert_eq!(half.button_height, BUTTON_HEIGHT * 0.5);
        assert_eq!(half.label_size, LABEL_PIXEL_SIZE * 0.5);
        // A small panel's label still has to fit in its own small button.
        let fitted = half.fitting(["MENU"]);
        assert!(
            fitted.button_width >= super::super::font::text_width("MENU", half.label_size),
            "{fitted:?}",
        );
        assert!(
            fitted.button_width < BUTTON_WIDTH,
            "half size should be smaller than a full button: {fitted:?}",
        );
    }

    #[test]
    fn a_scaled_panel_is_half_as_tall_as_a_full_one() {
        let metrics = Metrics::scaled(1.0).fitting(["MENU"]);
        let (full, _) = vertical_menu(800.0, 600.0, 1, Anchor::TopLeft, metrics);
        let (half, _) = vertical_menu(
            800.0,
            600.0,
            1,
            Anchor::TopLeft,
            Metrics::scaled(0.5).fitting(["MENU"]),
        );

        let content = |rect: Rect| rect.height - PANEL_PADDING * 2.0;
        assert!(
            (content(half) - content(full) * 0.5).abs() < 0.01,
            "{} vs {}",
            content(half),
            content(full),
        );
    }

    #[test]
    fn every_button_gets_the_width_the_panel_was_given() {
        let metrics = Metrics {
            button_width: 320.0,
            ..Metrics::default()
        };
        let (panel, buttons) = vertical_menu(800.0, 600.0, 3, Anchor::Center, metrics);

        assert_eq!(buttons.len(), 3);
        for button in &buttons {
            assert_eq!(button.width, 320.0);
            assert!(button.x >= panel.x, "buttons sit inside the panel");
            assert!(button.x + button.width <= panel.x + panel.width);
        }
        assert_eq!(panel.width, 320.0 + PANEL_PADDING * 2.0);
    }

    /// The corner a menu is in decides which way its children go, because
    /// the useful direction is always away from the nearest edge.

    /// The bug in the screenshot: a submenu placed against its parent *row*
    /// covers the rest of the panel that row is in, so the pointer sitting on
    /// the submenu is also sitting on the row beneath the one it came from,
    /// and both open at once.

    /// A long menu opened from a row near the bottom hangs upward from that
    /// row instead of being slid up the screen off its own row.
    #[test]
    fn a_submenu_with_no_room_below_grows_upward() {
        let metrics = Metrics::menu(1.0).snug([("RECENTER VIEW", false, false)], 1.0);
        let (_, height) = panel_size(7, metrics);
        let screen = (320.0, 240.0);

        // The dev menu's corner: a row near the foot of a short window.
        let panel = Rect::new(200.0, 200.0, 110.0, 30.0);
        let row = Rect::new(205.0, 205.0, 100.0, MENU_ROW_HEIGHT);

        let (child, rows) = submenu_rect(
            panel,
            row,
            7,
            metrics,
            Expand::Left,
            Expand::Left,
            screen.0,
            screen.1,
        );

        assert!(
            child.y + height <= screen.1,
            "it should fit on the screen: {child:?} in a {screen:?} window",
        );
        assert!(child.y >= 0.0, "and not run off the top: {child:?}");
        assert_eq!(rows.len(), 7, "with every entry laid out");
        assert!(
            rows.last().unwrap().y + rows.last().unwrap().height <= screen.1,
            "including the last one: {:?}",
            rows.last(),
        );
        assert!(
            child.y < row.y,
            "it grew up from the row rather than down: {child:?} against {row:?}",
        );
    }

    /// The ordinary case is unchanged: plenty of room below, so it lines up
    /// with the row that names it.
    #[test]
    fn a_submenu_with_room_below_lines_up_with_its_row() {
        let metrics = Metrics::menu(1.0).snug([("ONE", false, false)], 1.0);
        let panel = Rect::new(200.0, 100.0, 110.0, 200.0);
        let row = Rect::new(205.0, 120.0, 100.0, MENU_ROW_HEIGHT);

        let (child, rows) =
            submenu_rect(panel, row, 3, metrics, Expand::Right, Expand::Right, 1920.0, 1080.0);
        assert!(
            (rows[0].y - row.y).abs() < 1.0,
            "the first entry should sit level with its row: {:?} against {row:?}",
            rows[0],
        );
        assert!(child.y <= row.y);
    }

    #[test]
    fn a_submenu_never_covers_the_panel_it_came_from() {
        let metrics = Metrics::menu(1.0).snug([("RECENTER VIEW", false, false)], 1.0);
        let panel = Rect::new(1000.0, 400.0, 120.0, 200.0);

        for (row, side) in [
            (Rect::new(1005.0, 420.0, 110.0, MENU_ROW_HEIGHT), Expand::Left),
            (Rect::new(1005.0, 420.0, 110.0, MENU_ROW_HEIGHT), Expand::Right),
        ] {
            let (child, _) = submenu_rect(panel, row, 7, metrics, side, side, 1920.0, 1080.0);
            let overlaps = child.x < panel.x + panel.width && panel.x < child.x + child.width;
            assert!(
                !overlaps,
                "{side:?}: submenu {child:?} overlaps its parent panel {panel:?}",
            );
        }
    }

    /// It still lines up with the row it came out of, which is what the
    /// pointer triangle is drawn against.
    #[test]
    fn a_submenu_lines_up_with_its_row() {
        let metrics = Metrics::menu(1.0).snug([("OPEN SCENE", false, false)], 1.0);
        let panel = Rect::new(400.0, 300.0, 120.0, 200.0);
        let top = Rect::new(405.0, 320.0, 110.0, MENU_ROW_HEIGHT);
        let lower = Rect::new(405.0, 420.0, 110.0, MENU_ROW_HEIGHT);

        let at = |row| {
            submenu_rect(panel, row, 3, metrics, Expand::Right, Expand::Right, 1920.0, 1080.0)
                .0
                .y
        };
        assert!(at(lower) > at(top), "a lower row opens a lower menu");
    }

    /// An application menu is as wide as its longest entry and no wider. The
    /// game menu's two hundred pixels is not a floor for it.
    #[test]
    fn a_menu_shrinks_to_what_is_in_it() {
        let wide = Metrics::menu(1.0).snug([("RECENTER VIEW", false, false)], 1.0);
        let narrow = Metrics::menu(1.0).snug([("APP", false, false)], 1.0);

        assert!(narrow.button_width < wide.button_width);
        assert!(
            narrow.button_width < BUTTON_WIDTH,
            "three letters should not need a game menu's width: {}",
            narrow.button_width,
        );
    }

    /// A row wearing icons needs room for them, or the words run underneath.
    #[test]
    fn a_row_makes_room_for_its_icons() {
        let plain = Metrics::menu(1.0).snug([("VIEW", false, false)], 1.0);
        let both = Metrics::menu(1.0).snug([("VIEW", true, true)], 1.0);
        assert!(both.button_width > plain.button_width);
    }

    /// The rows of a menu touch. A gap between them makes it read as a column
    /// of buttons, which is what it should not look like.
    #[test]
    fn menu_rows_touch() {
        let metrics = Metrics::menu(1.0).snug([("A", false, false)], 1.0);
        let (_, rows) = stack_at(0.0, 0.0, 3, metrics);
        assert_eq!(rows[0].y + rows[0].height, rows[1].y);
        assert_eq!(rows[1].y + rows[1].height, rows[2].y);
    }

    #[test]
    fn a_corner_menu_opens_its_submenus_away_from_its_edge() {
        assert_eq!(Anchor::BottomRight.expands(), Expand::Left);
        assert_eq!(Anchor::TopRight.expands(), Expand::Left);
        assert_eq!(Anchor::BottomLeft.expands(), Expand::Right);
        assert_eq!(Anchor::TopLeft.expands(), Expand::Right);
        assert_eq!(Anchor::Center.expands(), Expand::Right);
    }

    #[test]
    fn a_submenu_takes_the_side_it_was_asked_for() {
        let metrics = Metrics::default();
        let parent = Rect::new(400.0, 300.0, 200.0, BUTTON_HEIGHT);
        let go = |expand, preferred| {
            submenu_rect(parent, parent, 2, metrics, expand, preferred, 1280.0, 800.0)
                .0
                .x
        };

        // Explicit wins over the preference.
        assert!(go(Expand::Left, Expand::Right) < parent.x);
        assert!(go(Expand::Right, Expand::Left) >= parent.x + parent.width);
        // Automatic takes the preference.
        assert!(go(Expand::Automatic, Expand::Left) < parent.x);
        assert!(go(Expand::Automatic, Expand::Right) >= parent.x + parent.width);
    }

    #[test]
    fn a_submenu_with_no_room_on_its_side_opens_on_the_other() {
        let metrics = Metrics::default();
        let (width, height) = panel_size(2, metrics);

        // Hard against the left edge: there is no room to the left, however
        // much it would prefer it.
        let hugging_left = Rect::new(0.0, 300.0, 120.0, BUTTON_HEIGHT);
        let (panel, _) = submenu_rect(
            hugging_left,
            hugging_left,
            2,
            metrics,
            Expand::Left,
            Expand::Left,
            1280.0,
            800.0,
        );
        assert_eq!(
            panel.x, 120.0,
            "no room on the left, so it should have flipped to the right",
        );

        // And the same the other way.
        let hugging_right = Rect::new(1280.0 - 120.0, 300.0, 120.0, BUTTON_HEIGHT);
        let (panel, _) = submenu_rect(
            hugging_right,
            hugging_right,
            2,
            metrics,
            Expand::Right,
            Expand::Right,
            1280.0,
            800.0,
        );
        assert!(
            panel.x + width <= 1280.0,
            "no room on the right, so it should have flipped: {panel:?}",
        );
        assert!(panel.y + height <= 800.0);
    }

    #[test]
    fn a_submenu_near_an_edge_is_pushed_back_onto_the_screen() {
        let metrics = Metrics::default();
        let (_, height) = panel_size(4, metrics);

        // A parent near the bottom would put a four-item child off the
        // screen; it should ride up instead.
        let low = Rect::new(1000.0, 780.0, 200.0, BUTTON_HEIGHT);
        let (panel, buttons) = submenu_rect(
            low,
            low,
            4,
            metrics,
            Expand::Automatic,
            Expand::Left,
            1280.0,
            800.0,
        );
        assert!(panel.y >= 0.0 && panel.y + height <= 800.0, "{panel:?}");
        for button in buttons {
            assert!(button.y >= panel.y);
            assert!(button.y + button.height <= panel.y + panel.height);
        }
    }

    #[test]
    fn a_full_size_panel_never_shrinks_below_the_default_width() {
        // Fitting only ever widens, so a short label leaves the default.
        let metrics = Metrics::default().fitting(["OK"]);
        let (_, buttons) = vertical_menu(800.0, 600.0, 1, Anchor::Center, metrics);

        assert_eq!(buttons[0].width, BUTTON_WIDTH);
    }
}