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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use bevy_ecs::prelude::*;

use super::button::{ButtonColors, ButtonMarker, ClickHandler, OnClick};
use super::color::Color;
use super::geometry::{
    Background, ButtonIcons, Icon, Label, LabelAlign, LabelSize, Position, Size,
};
use super::interaction::Interaction;
use super::layout;
use super::panel::{ClosesPanel, Movable, PanelChild, PanelMarker, TitleBar};
use super::rect::Rect;
use super::resources::{MenuLayout, SubmenuLayout};
use super::visibility::Visibility;
use super::widget::Widget;
use crate::scene::SceneEntity;

fn hide(world: &mut World, entity: Entity) {
    world.entity_mut(entity).insert(Visibility::HIDDEN);
}

/// A button to add to a [`Panel`], with an optional callback run on click.
///
/// ```no_run
/// # use codecraft::ui::Button;
/// Button::new("Quit", || std::process::exit(0));
/// ```
pub struct Button {
    label: String,
    on_click: Option<ClickHandler>,
    opens: Option<Panel>,
    icon: Option<&'static str>,
    trailing: Option<&'static str>,
}

impl Button {
    pub fn new(label: impl Into<String>, on_click: impl FnMut() + Send + Sync + 'static) -> Self {
        Self {
            label: label.into(),
            on_click: Some(Box::new(on_click)),
            opens: None,
            icon: None,
            trailing: None,
        }
    }

    /// A button with no click behavior yet.
    pub fn label(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            on_click: None,
            opens: None,
            icon: None,
            trailing: None,
        }
    }

    /// A button that opens another panel beside it while the pointer is on
    /// it -- or on what it opened, so the pointer can travel from one to the
    /// other without the menu closing under it.
    ///
    /// ```no_run
    /// # use codecraft::ui::{Button, Panel};
    /// Button::submenu("CAMERA", |menu| {
    ///     menu.add(Button::label("ORBIT")).add(Button::label("FLY"))
    /// });
    /// ```
    pub fn submenu(label: impl Into<String>, build: impl FnOnce(Panel) -> Panel) -> Self {
        let label = label.into();
        let panel = build(Panel::new(format!("{label} submenu")));
        Self {
            label,
            on_click: None,
            opens: Some(panel),
            icon: None,
            trailing: None,
        }
    }

    /// An icon before the label, saying what the entry is.
    ///
    /// The one *after* it is not set here: it says which way the entry opens,
    /// which is not known until the frame it opens on. See
    /// [`super::systems::update_submenu_system`].
    pub fn icon(mut self, icon: &'static str) -> Self {
        self.icon = Some(icon);
        self
    }

    /// An icon after the label, fixed.
    ///
    /// For a button whose trailing icon is a property of the button rather
    /// than of what it opened -- the dev badge's caret, which says which way
    /// its menu comes out. A submenu's own caret is not set here; that one is
    /// only known once it has opened.
    pub fn trailing(mut self, icon: &'static str) -> Self {
        self.trailing = Some(icon);
        self
    }
}

/// A vertically-stacked panel of buttons, sized and centered using the
/// defaults in [`super::layout`].
///
/// ```no_run
/// # use bevy_ecs::world::World;
/// # use codecraft::ui::{Button, Panel};
/// # let mut world = World::new();
/// Panel::new("MainMenu")
///     .add(Button::new("New Game", || { /* start a new game */ }))
///     .add(Button::new("Quit", || std::process::exit(0)))
///     .spawn(&mut world, 800.0, 600.0);
/// ```
/// A button that opens a panel: where the panel is, what is in it, and which
/// side it prefers to open on.
///
/// Lives on the *parent* button, because that is the thing whose position
/// decides where the child goes and whose hover decides whether it is up.
#[derive(Component)]
pub struct Submenu {
    /// The panel this button opens.
    pub panel: Entity,
    /// What is in it, so it can be hidden and moved with the panel.
    pub buttons: Vec<Entity>,
    /// The triangle on the panel's edge pointing back at this button.
    pub pointer: Entity,
    pub metrics: layout::Metrics,
    pub expand: layout::Expand,
    /// The side the parent panel's own anchor prefers, taken at spawn.
    pub preferred: layout::Expand,
}

pub struct Panel {
    name: String,
    buttons: Vec<Button>,
    anchor: layout::Anchor,
    scale: f32,
    offset: (f32, f32),
    expand: layout::Expand,
    title: Option<String>,
    closable: bool,
    movable: Option<bool>,
    /// Drawn as an application menu rather than a game menu: see
    /// [`Panel::menu`].
    menu: bool,
}

impl Panel {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            buttons: Vec::new(),
            anchor: layout::Anchor::default(),
            scale: 1.0,
            offset: (0.0, 0.0),
            expand: layout::Expand::default(),
            title: None,
            closable: false,
            movable: None,
            menu: false,
        }
    }

    /// Draw this panel as an application menu: rows that touch, names read
    /// down the left, and only as wide as the longest entry.
    ///
    /// The default is a game menu -- big targets with air between them. Both
    /// are menus; only one of them is something you point at while looking at
    /// something else. See [`layout::Metrics::menu`].
    pub fn menu(mut self) -> Self {
        self.menu = true;
        self
    }

    /// Give the panel a title bar.
    ///
    /// A bar is also a handle: a titled panel can be dragged around unless
    /// [`movable`](Self::movable) says otherwise, because a bar with a name
    /// on it is the thing a person reaches for.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Put a close button at the right of the title bar.
    ///
    /// It marks the panel [`Closed`](super::panel::Closed) rather than
    /// despawning it: a panel's lifetime belongs to whatever put it up.
    /// Needs a title bar, which is the only place it would go.
    pub fn closable(mut self) -> Self {
        self.closable = true;
        self
    }

    /// Whether the panel can be dragged by its title bar. Titled panels can
    /// by default; a main menu is centred on purpose and says `false`.
    pub fn movable(mut self, movable: bool) -> Self {
        self.movable = Some(movable);
        self
    }

    /// Pixels to move the panel by, once it has been anchored -- for a panel
    /// that has to sit clear of something else already in that corner.
    pub fn offset(mut self, x: f32, y: f32) -> Self {
        self.offset = (x, y);
        self
    }

    /// Which side this panel's submenus open on.
    ///
    /// The default, [`layout::Expand::Automatic`], takes the anchor's own
    /// preference -- away from the edge the panel is against -- and flips it
    /// anyway if the submenu would not fit there.
    pub fn expand(mut self, expand: layout::Expand) -> Self {
        self.expand = expand;
        self
    }

    /// How big the buttons are drawn, against the defaults. A MENU sitting in
    /// the corner of a game does not need to be the size of a main menu.
    pub fn scale(mut self, scale: f32) -> Self {
        self.scale = scale.max(0.05);
        self
    }

    /// Where the panel sits; centered unless told otherwise.
    pub fn anchor(mut self, anchor: layout::Anchor) -> Self {
        self.anchor = anchor;
        self
    }

    pub fn add(mut self, button: Button) -> Self {
        self.buttons.push(button);
        self
    }

    /// Lays the panel and its buttons out centered on a screen of size
    /// `screen_width` x `screen_height` and spawns them into `world`.
    ///
    /// Returns the spawned entities — buttons in the order they were added,
    /// so a scene can keep hold of one and update its [`super::Label`].
    /// Re-calling this (or resizing the screen — see
    /// [`super::systems::relayout_menu_system`]) keeps the layout centered.
    pub fn spawn(self, world: &mut World, screen_width: f32, screen_height: f32) -> MenuLayout {
        let metrics = match self.menu {
            // A menu is as wide as what is in it, icons and all.
            true => layout::Metrics::menu(self.scale).snug(
                self.buttons.iter().map(|b| {
                    (
                        &b.label,
                        b.icon.is_some(),
                        b.opens.is_some() || b.trailing.is_some(),
                    )
                }),
                self.scale,
            ),
            false => layout::Metrics::scaled(self.scale)
                .fitting(self.buttons.iter().map(|b| &b.label)),
        };
        let (panel_rect, button_rects) = layout::vertical_menu_offset(
            screen_width,
            screen_height,
            self.buttons.len(),
            self.anchor,
            metrics,
            self.offset,
        );

        // A title bar grows the panel upwards and pushes the buttons down,
        // so the buttons stay where the layout put them relative to each
        // other and the bar is what is new.
        let bar_height = self.title.as_ref().map_or(0.0, |_| layout::TITLE_HEIGHT);
        let panel_rect = Rect::new(
            panel_rect.x,
            panel_rect.y,
            panel_rect.width,
            panel_rect.height + bar_height,
        );
        let button_rects: Vec<Rect> = button_rects
            .into_iter()
            .map(|rect| Rect::new(rect.x, rect.y + bar_height, rect.width, rect.height))
            .collect();

        let (panel_pos, panel_size) = panel_rect.into();
        let panel = world
            .spawn((
                panel_pos,
                panel_size,
                Background(Color::srgba(0.10, 0.10, 0.14, 0.92)),
                PanelMarker,
                SceneEntity,
                Name::new(self.name),
            ))
            .id();

        // The bar, and the close button in it.
        let mut bar_entity = None;
        let mut close_entity = None;
        if let Some(title) = self.title {
            let bar = Rect::new(panel_rect.x, panel_rect.y, panel_rect.width, bar_height);
            let (pos, size): (Position, Size) = bar.into();
            bar_entity = Some(
                world
                    .spawn((
                        pos,
                        size,
                        Background(Color::srgba(0.16, 0.16, 0.21, 0.96)),
                        Label(title),
                        LabelSize(layout::TITLE_LABEL_SIZE),
                        TitleBar { panel },
                        PanelChild(panel),
                        SceneEntity,
                    ))
                    .id(),
            );

            if self.closable {
                let side = bar_height - layout::TITLE_INSET * 2.0;
                let close = Rect::new(
                    bar.x + bar.width - side - layout::TITLE_INSET,
                    bar.y + layout::TITLE_INSET,
                    side,
                    side,
                );
                let (pos, size): (Position, Size) = close.into();
                close_entity = Some(
                    world
                        .spawn((
                            pos,
                            size,
                            ButtonColors::close(),
                            Icon::new(super::icons::path::X),
                            Interaction::default(),
                            ButtonMarker,
                            ClosesPanel(panel),
                            PanelChild(panel),
                            SceneEntity,
                        ))
                        .id(),
                );
            }

            // Titled unless told otherwise: a bar with a name on it is what a
            // person reaches for.
            if self.movable.unwrap_or(true) {
                world.entity_mut(panel).insert(Movable);
            }
        }

        let expand = self.expand;
        let preferred = self.anchor.expands();
        let scale = self.scale;
        let is_menu = self.menu;

        let mut submenus: Vec<SubmenuLayout> = Vec::new();
        let buttons = self
            .buttons
            .into_iter()
            .zip(button_rects)
            .map(|(button, rect)| {
                let (pos, size): (Position, Size) = rect.into();
                let mut entity = world.spawn((
                    pos,
                    size,
                    ButtonColors::default(),
                    Label(button.label),
                    LabelSize(metrics.label_size),
                    Interaction::default(),
                    ButtonMarker,
                    SceneEntity,
                ));
                entity.insert(PanelChild(panel));
                if is_menu {
                    entity.insert(LabelAlign::Left);
                    entity.insert(ButtonColors::row());
                }
                // The trailing caret is left to `update_submenu_system`: it
                // says which way the entry opens, and that is not settled
                // until the frame it opens on.
                entity.insert(ButtonIcons {
                    leading: button.icon,
                    trailing: button.trailing,
                });
                if let Some(on_click) = button.on_click {
                    entity.insert(OnClick(on_click));
                }
                let id = entity.id();

                // The child is spawned now and hidden; where it goes is
                // decided every frame from where its parent ended up, which
                // is what keeps it in place through a resize.
                if let Some(mut child) = button.opens {
                    if child.scale == 1.0 {
                        // A submenu inherits its parent's size unless it was
                        // given one: a menu whose children are twice the size
                        // of their parents reads as two menus.
                        child.scale = scale;
                    }
                    let child_expand = match child.expand {
                        layout::Expand::Automatic => expand,
                        side => side,
                    };
                    // A menu's children are menus: the style is a fact about
                    // the whole tree, not about one panel in it.
                    child.menu |= is_menu;
                    let child_metrics = match child.menu {
                        true => layout::Metrics::menu(child.scale).snug(
                            child.buttons.iter().map(|b| {
                                (
                        &b.label,
                        b.icon.is_some(),
                        b.opens.is_some() || b.trailing.is_some(),
                    )
                            }),
                            child.scale,
                        ),
                        false => layout::Metrics::scaled(child.scale)
                            .fitting(child.buttons.iter().map(|b| &b.label)),
                    };
                    let layout = child.spawn(world, screen_width, screen_height);
                    hide(world, layout.panel);
                    for &button in &layout.buttons {
                        hide(world, button);
                    }
                    // The triangle that says which row this panel came out
                    // of. Placed every frame with the panel; see
                    // `update_submenu_system`.
                    let pointer = world
                        .spawn((
                            Position { x: 0.0, y: 0.0 },
                            Size {
                                width: 0.0,
                                height: 0.0,
                            },
                            Icon::tinted(
                                super::icons::ours::POINTER_LEFT,
                                Color::srgba(0.10, 0.10, 0.14, 0.92),
                            ),
                            Visibility::HIDDEN,
                            SceneEntity,
                        ))
                        .id();
                    world.entity_mut(id).insert(Submenu {
                        panel: layout.panel,
                        buttons: layout.buttons.clone(),
                        pointer,
                        metrics: child_metrics,
                        expand: child_expand,
                        preferred,
                    });
                    // Owned by this panel, so taking it down takes them with
                    // it: nothing else in the world knows they are here.
                    submenus.push(SubmenuLayout { layout, pointer });
                }
                id
            })
            .collect::<Vec<_>>();

        let layout = MenuLayout {
            panel,
            buttons,
            anchor: self.anchor,
            metrics,
            offset: self.offset,
            bar: bar_entity,
            close: close_entity,
            bar_height,
            submenus,
        };
        world.entity_mut(panel).insert(layout.clone());

        layout
    }
}

impl Widget for Panel {
    type Output = MenuLayout;

    fn spawn(self, world: &mut World, screen_width: f32, screen_height: f32) -> MenuLayout {
        Panel::spawn(self, world, screen_width, screen_height)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ecs::Application;
    use crate::ui::plugin::UiPlugin;
    use crate::ui::resources::{CursorPosition, MouseInput, ScreenSize};

    fn app() -> Application {
        let mut app = Application::new();
        app.add_plugin(UiPlugin);
        app.world.insert_resource(ScreenSize {
            width: 1280.0,
            height: 800.0,
        });
        app
    }

    fn at(app: &Application, entity: Entity) -> (f32, f32) {
        let pos = app.world.get::<Position>(entity).expect("a position");
        (pos.x, pos.y)
    }

    fn bar_of(app: &mut Application, panel: Entity) -> Entity {
        app.world
            .query::<(Entity, &TitleBar)>()
            .iter(&app.world)
            .find(|(_, bar)| bar.panel == panel)
            .map(|(entity, _)| entity)
            .expect("a title bar")
    }

    /// Press, move, release -- the button held across frames, which is what
    /// makes a drag a drag rather than two clicks.
    fn drag(app: &mut Application, from: (f32, f32), to: (f32, f32)) {
        app.world.insert_resource(CursorPosition {
            x: from.0,
            y: from.1,
        });
        app.world.insert_resource(MouseInput {
            left_down: true,
            just_pressed: true,
            ..MouseInput::default()
        });
        app.update();

        app.world
            .insert_resource(CursorPosition { x: to.0, y: to.1 });
        app.world.insert_resource(MouseInput {
            left_down: true,
            ..MouseInput::default()
        });
        app.update();

        app.world.insert_resource(MouseInput::default());
        app.update();
    }


    /// The bug a resize used to cause: a panel nudged clear of something else
    /// in its corner landed back on top of it, because the relayout did the
    /// anchor sum again and forgot the nudge.

    /// A menu has to be able to say what it owns, or a caller taking one down
    /// walks the `Submenu` components by hand and quietly misses something --
    /// the pointer triangles, in the case this test was written for, which
    /// outlived every menu that had been opened.

    /// The bug in the screenshot: three submenus drawn on top of each other.
    ///
    /// A panel's rows all open into the same strip of screen beside it, so
    /// those menus overlap; when each decided for itself whether the pointer
    /// was inside it, every one of them said yes.
    #[test]
    fn only_one_submenu_of_a_panel_is_ever_up() {
        let mut app = app();
        // The window the menu is actually laid out for, or the first update
        // relayouts it out from under the cursor.
        app.world.insert_resource(ScreenSize {
            width: 320.0,
            height: 240.0,
        });
        let layout = Panel::new("Menu")
            .menu()
            .anchor(layout::Anchor::BottomRight)
            .add(Button::submenu("APP", |menu| {
                menu.add(Button::label("PLAY")).add(Button::label("EXIT"))
            }))
            .add(Button::submenu("FILE", |menu| {
                menu.add(Button::label("OPEN")).add(Button::label("SAVE"))
            }))
            .add(Button::submenu("VIEW", |menu| {
                menu.add(Button::label("ONE")).add(Button::label("TWO"))
            }))
            .spawn(&mut app.world, 320.0, 240.0);
        // Settle the relayout before anything is measured.
        app.update();

        let panels: Vec<Entity> = layout
            .buttons
            .iter()
            .map(|&row| app.world.get::<Submenu>(row).expect("a submenu").panel)
            .collect();
        let up = |app: &Application| {
            panels
                .iter()
                .filter(|&&panel| {
                    app.world
                        .get::<Visibility>(panel)
                        .copied()
                        .unwrap_or_default()
                        .0
                })
                .count()
        };

        // Over each row in turn: exactly one menu, and it is that row's.
        for (index, &row) in layout.buttons.iter().enumerate() {
            let rect = {
                let pos = app.world.get::<Position>(row).unwrap();
                let size = app.world.get::<Size>(row).unwrap();
                pos.rect(size)
            };
            app.world.insert_resource(CursorPosition {
                x: rect.center_x(),
                y: rect.center_y(),
            });
            app.update();

            assert_eq!(up(&app), 1, "row {index} should open one menu, not {}", up(&app));
            assert!(
                app.world
                    .get::<Visibility>(panels[index])
                    .copied()
                    .unwrap_or_default()
                    .0,
                "and it should be row {index}'s own",
            );
        }

        // And away from all of them, none.
        app.world
            .insert_resource(CursorPosition { x: 5.0, y: 5.0 });
        app.update();
        assert_eq!(up(&app), 0, "nothing hovered, nothing open");
    }

    /// Moving from a row into what it opened has to keep it open -- it is the
    /// one movement anybody makes -- without opening its neighbours.
    #[test]
    fn the_pointer_can_travel_into_the_menu_it_opened() {
        let mut app = app();
        app.world.insert_resource(ScreenSize {
            width: 320.0,
            height: 240.0,
        });
        let layout = Panel::new("Menu")
            .menu()
            .anchor(layout::Anchor::BottomRight)
            .add(Button::submenu("APP", |menu| {
                menu.add(Button::label("PLAY")).add(Button::label("EXIT"))
            }))
            .add(Button::submenu("FILE", |menu| {
                menu.add(Button::label("OPEN")).add(Button::label("SAVE"))
            }))
            .spawn(&mut app.world, 320.0, 240.0);
        app.update();

        let rect_of = |app: &Application, entity| {
            let pos = app.world.get::<Position>(entity).unwrap();
            let size = app.world.get::<Size>(entity).unwrap();
            pos.rect(size)
        };
        let opened = app.world.get::<Submenu>(layout.buttons[0]).unwrap().panel;

        let row = rect_of(&app, layout.buttons[0]);
        app.world.insert_resource(CursorPosition {
            x: row.center_x(),
            y: row.center_y(),
        });
        app.update();

        // Into the panel it opened, off the row.
        let panel = rect_of(&app, opened);
        app.world.insert_resource(CursorPosition {
            x: panel.center_x(),
            y: panel.center_y(),
        });
        app.update();

        assert!(
            app.world.get::<Visibility>(opened).copied().unwrap_or_default().0,
            "it should stay up once the pointer is inside it",
        );
        let sibling = app.world.get::<Submenu>(layout.buttons[1]).unwrap().panel;
        assert!(
            !app.world.get::<Visibility>(sibling).copied().unwrap_or_default().0,
            "and its neighbour should not have opened underneath it",
        );
    }

    #[test]
    fn a_menu_knows_every_entity_it_owns() {
        let mut app = app();
        let layout = Panel::new("Owner")
            .menu()
            .add(Button::label("PLAIN"))
            .add(Button::submenu("OPENS", |menu| {
                menu.add(Button::label("ONE")).add(Button::label("TWO"))
            }))
            .spawn(&mut app.world, 1280.0, 800.0);

        let owned = layout.entities();
        let submenu = app
            .world
            .get::<Submenu>(layout.buttons[1])
            .expect("the second row opens a menu");
        for (what, entity) in [
            ("the panel", layout.panel),
            ("a plain row", layout.buttons[0]),
            ("a row that opens", layout.buttons[1]),
            ("the submenu's panel", submenu.panel),
            ("a submenu row", submenu.buttons[0]),
            ("the pointer triangle", submenu.pointer),
        ] {
            assert!(owned.contains(&entity), "{what} is not owned by anything");
        }

        // And despawning what it owns leaves nothing of it behind.
        for entity in owned {
            app.world.despawn(entity);
        }
        assert_eq!(
            app.world.query::<&Position>().iter(&app.world).count(),
            0,
            "something outlived the menu it belonged to",
        );
    }

    /// A submenu of a submenu is owned too -- the walk has to recurse.
    #[test]
    fn ownership_reaches_all_the_way_down() {
        let mut app = app();
        let layout = Panel::new("Deep")
            .menu()
            .add(Button::submenu("ONE", |menu| {
                menu.add(Button::submenu("TWO", |menu| menu.add(Button::label("DEEP"))))
            }))
            .spawn(&mut app.world, 1280.0, 800.0);

        let deepest = {
            let outer = app.world.get::<Submenu>(layout.buttons[0]).unwrap();
            let inner = app.world.get::<Submenu>(outer.buttons[0]).unwrap();
            inner.buttons[0]
        };
        assert!(
            layout.entities().contains(&deepest),
            "a row two menus down is still the top menu's to take away",
        );
    }

    #[test]
    fn a_resize_keeps_a_panel_s_offset() {
        let mut app = app();
        let menu = Panel::new("Offset")
            .anchor(layout::Anchor::BottomRight)
            .offset(0.0, -100.0)
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        let before = at(&app, menu.panel);

        app.world.insert_resource(ScreenSize {
            width: 1280.0,
            height: 900.0,
        });
        app.update();

        let after = at(&app, menu.panel);
        assert_eq!(
            after.1 - before.1,
            100.0,
            "the panel should follow the taller window and keep its nudge",
        );

        let anchored = Panel::new("Anchored")
            .anchor(layout::Anchor::BottomRight)
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 900.0);
        assert_eq!(
            at(&app, menu.panel).1,
            at(&app, anchored.panel).1 - 100.0,
            "and stay exactly that far clear of an unnudged one",
        );
    }

    /// A title bar grows the panel upwards and pushes the rows down. A
    /// relayout that forgets it puts the rows under the bar.
    #[test]
    fn a_resize_keeps_the_room_a_title_bar_takes() {
        let mut app = app();
        let menu = Panel::new("Titled")
            .title("TITLED")
            .anchor(layout::Anchor::TopLeft)
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        let bar = bar_of(&mut app, menu.panel);
        let gap = at(&app, menu.buttons[0]).1 - at(&app, bar).1;

        app.world.insert_resource(ScreenSize {
            width: 1000.0,
            height: 700.0,
        });
        app.update();

        assert_eq!(
            at(&app, menu.buttons[0]).1 - at(&app, bar).1,
            gap,
            "the row should still clear the bar",
        );
        assert_eq!(at(&app, bar), at(&app, menu.panel), "and the bar cap it");
    }

    #[test]
    fn a_panel_without_a_title_has_no_bar_and_cannot_move() {
        let mut app = app();
        let menu =
            Panel::new("MainMenu")
                .add(Button::label("PLAY"))
                .spawn(&mut app.world, 1280.0, 800.0);
        app.update();

        assert_eq!(app.world.query::<&TitleBar>().iter(&app.world).count(), 0);
        assert!(
            app.world.get::<Movable>(menu.panel).is_none(),
            "nothing to drag it by, so nothing that moves it",
        );
    }

    #[test]
    fn a_titled_panel_moves_with_its_bar_and_its_buttons_come_along() {
        let mut app = app();
        let panel = Panel::new("Tools")
            .title("TOOLS")
            .add(Button::label("ONE"))
            .add(Button::label("TWO"))
            .spawn(&mut app.world, 1280.0, 800.0);
        app.update();

        let before = at(&app, panel.panel);
        let button_before = at(&app, panel.buttons[0]);
        let bar = bar_of(&mut app, panel.panel);
        let grab = at(&app, bar);

        drag(
            &mut app,
            (grab.0 + 20.0, grab.1 + 5.0),
            (grab.0 + 120.0, grab.1 + 65.0),
        );

        let after = at(&app, panel.panel);
        assert_eq!(
            (after.0 - before.0, after.1 - before.1),
            (100.0, 60.0),
            "the panel follows the pointer",
        );
        let button_after = at(&app, panel.buttons[0]);
        assert_eq!(
            (
                button_after.0 - button_before.0,
                button_after.1 - button_before.1,
            ),
            (100.0, 60.0),
            "and what is in it comes along",
        );
    }

    #[test]
    fn a_panel_told_not_to_move_stays_put() {
        let mut app = app();
        let panel = Panel::new("Fixed")
            .title("FIXED")
            .movable(false)
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        app.update();

        let before = at(&app, panel.panel);
        let bar = bar_of(&mut app, panel.panel);
        let grab = at(&app, bar);
        drag(
            &mut app,
            (grab.0 + 20.0, grab.1 + 5.0),
            (grab.0 + 120.0, grab.1 + 65.0),
        );

        assert_eq!(at(&app, panel.panel), before);
    }

    #[test]
    fn only_a_closable_panel_gets_an_x() {
        let mut app = app();
        Panel::new("Plain")
            .title("PLAIN")
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        app.update();
        assert_eq!(
            app.world.query::<&ClosesPanel>().iter(&app.world).count(),
            0
        );

        Panel::new("Closable")
            .title("CLOSABLE")
            .closable()
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        app.update();
        assert_eq!(
            app.world.query::<&ClosesPanel>().iter(&app.world).count(),
            1
        );
    }

    #[test]
    fn clicking_the_x_marks_the_panel_closed_rather_than_despawning_it() {
        let mut app = app();
        let panel = Panel::new("Closable")
            .title("CLOSABLE")
            .closable()
            .add(Button::label("ONE"))
            .spawn(&mut app.world, 1280.0, 800.0);
        app.update();

        let x = app
            .world
            .query::<(Entity, &ClosesPanel)>()
            .iter(&app.world)
            .next()
            .map(|(entity, _)| entity)
            .expect("an X");
        let (px, py) = at(&app, x);
        let size = *app.world.get::<Size>(x).expect("a size");

        app.world.insert_resource(CursorPosition {
            x: px + size.width * 0.5,
            y: py + size.height * 0.5,
        });
        app.world.insert_resource(MouseInput {
            left_down: true,
            just_pressed: true,
            ..MouseInput::default()
        });
        app.update();

        assert!(
            app.world
                .get::<crate::ui::panel::Closed>(panel.panel)
                .is_some()
        );
        assert!(
            app.world.get_entity(panel.panel).is_ok(),
            "whatever put the panel up owns when it goes",
        );
    }
}