codecraft 0.2.0

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, a yakui-drawn UI, audio and gamepad haptics; its binary maps any folder, and the symbols of its Rust files, as a 3D wall of boxes
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
//! The few widgets of our own, on top of yakui's.
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use yakui::event::{EventInterest, EventResponse, WidgetEvent};
use yakui::font::FontName;
use yakui::geometry::{Color, Constraints, Rect, UVec2, Vec2};
use yakui::input::MouseButton;
use yakui::paint::{PaintRect, Texture, TextureFilter, TextureFormat};
use yakui::style::{TextAlignment, TextStyle};
use yakui::util::{widget, widget_children};
use yakui::widget::{EventContext, LayoutContext, PaintContext, Widget};
use yakui::widgets::{ColoredBox, List, Pad, Reflow, Text};
use yakui::{Alignment, CrossAxisAlignment, Dim2, ManagedTextureId, Pivot, Response};

use super::font::Face;
use super::icons;
use super::state::Panels;

/// The palette.
pub mod palette {
    use yakui::geometry::Color;

    pub const PANEL: Color = Color::rgba(26, 26, 36, 235);
    pub const BAR: Color = Color::rgba(41, 41, 54, 245);
    pub const OUTLINER: Color = Color::rgba(20, 20, 28, 240);
    pub const TEXT: Color = Color::WHITE;
    pub const TITLE: Color = Color::rgb(209, 209, 224);
    pub const DIM: Color = Color::rgb(140, 140, 153);

    /// A game-menu button: at rest, hovered, pressed.
    pub const BUTTON: [Color; 3] = [
        Color::rgb(51, 56, 71),
        Color::rgb(77, 84, 107),
        Color::rgb(36, 41, 54),
    ];
    /// An application-menu row: clear at rest so the panel stays one flat surface.
    pub const ROW: [Color; 3] = [
        Color::CLEAR,
        Color::rgb(61, 89, 140),
        Color::rgb(46, 69, 112),
    ];
    /// A close button: clear at rest, red under the pointer.
    pub const CLOSE: [Color; 3] = [
        Color::CLEAR,
        Color::rgb(158, 56, 56),
        Color::rgb(115, 38, 38),
    ];
}

/// Margin between a screen edge and a panel anchored to it.
pub const SCREEN_MARGIN: f32 = 16.0;
/// Gap between a panel's edge and its contents.
pub const PANEL_PADDING: f32 = 5.0;
/// Height of a window's title bar.
pub const TITLE_HEIGHT: f32 = 26.0;

/// A text style in the frame's face, `px` tall.
pub fn style(px: f32) -> TextStyle {
    let family = yakui::context::dom()
        .get_global_or_init(Face::default)
        .get();
    let mut style = TextStyle::label();
    style.font = FontName::new(family.name());
    style.font_size = px;
    style.color = palette::TEXT;
    style
}

/// A line of lettering, `px` tall, in the frame's face.
pub fn text(px: f32, text: impl Into<String>) -> Response<()> {
    text_colored(px, text, palette::TEXT)
}

/// A line of lettering in a colour.
pub fn text_colored(px: f32, text: impl Into<String>, color: Color) -> Response<()> {
    let mut widget = Text::new(px, text.into());
    widget.style = style(px);
    widget.style.color = color;
    widget.show()
}

/// A full-screen container to [`place`] things in; unplaced children stack as a column.
pub fn screen<F: FnOnce()>(children: F) -> Response<()> {
    let mut list = List::column();
    list.main_axis_size = yakui::MainAxisSize::Max;
    list.cross_axis_alignment = CrossAxisAlignment::Stretch;
    list.show(children)
}

/// Puts its child's `pivot` at a fraction `(x, y)` of its container.
pub fn place<F: FnOnce()>(x: f32, y: f32, pivot: Pivot, children: F) -> Response<()> {
    Reflow::new(Alignment::new(x, y), pivot, Dim2::ZERO).show(children)
}

/// Puts its child's top-left corner at a pixel position in its container.
pub fn place_px<F: FnOnce()>(at: Vec2, children: F) -> Response<()> {
    Reflow::new(
        Alignment::TOP_LEFT,
        Pivot::TOP_LEFT,
        Dim2::pixels(at.x, at.y),
    )
    .show(children)
}

/// Its child against a corner or edge of the screen, a margin in from it.
pub fn corner<F: FnOnce()>(alignment: Alignment, children: F) -> Response<()> {
    yakui::align(alignment, || {
        yakui::pad(Pad::all(SCREEN_MARGIN), children);
    })
}

/// A dark box round its children that swallows clicks and wheel turns.
pub fn panel<F: FnOnce()>(children: F) -> Response<()> {
    panel_colored(palette::PANEL, children)
}

pub fn panel_colored<F: FnOnce()>(color: Color, children: F) -> Response<()> {
    let response = yakui::opaque(|| {
        ColoredBox::container(color).show_children(|| {
            yakui::pad(Pad::all(PANEL_PADDING), children);
        });
    });
    yakui::context::dom()
        .get_global_or_init(Panels::default)
        .0
        .borrow_mut()
        .push(response.id);
    response
}

/// Character advance as a fraction of the em; Monaspace is monospaced, so labels can be measured without layout.
pub const ADVANCE_PER_EM: f32 = 0.62;

const BUTTON_MIN: Vec2 = Vec2::new(200.0, 56.0);
const BUTTON_PX: f32 = 29.0;
const BUTTON_MARGIN: f32 = 24.0;

/// A centred game menu with one big button per label; answers with which was clicked this frame.
///
/// ```no_run
/// # use codecraft::ui;
/// match ui::menu(&["NEW GAME", "QUIT"]) {
///     Some(0) => { /* a new game */ }
///     Some(1) => std::process::exit(0),
///     _ => {}
/// }
/// ```
pub fn menu<S: AsRef<str>>(labels: &[S]) -> Option<usize> {
    let widest = labels
        .iter()
        .map(|label| label.as_ref().chars().count())
        .max()
        .unwrap_or(0) as f32;
    let width = (widest * BUTTON_PX * ADVANCE_PER_EM + BUTTON_MARGIN * 2.0).max(BUTTON_MIN.x);

    let mut clicked = None;
    yakui::center(|| {
        panel(|| {
            let mut column = List::column();
            column.item_spacing = 20.0;
            column.main_axis_size = yakui::MainAxisSize::Min;
            column.show(|| {
                for (index, label) in labels.iter().enumerate() {
                    if sized_button(label.as_ref(), Vec2::new(width, BUTTON_MIN.y), BUTTON_PX) {
                        clicked = Some(index);
                    }
                }
            });
        });
    });
    clicked
}

/// A big game-menu button; says whether it was clicked this frame.
pub fn button(label: impl Into<String>) -> bool {
    sized_button(label, BUTTON_MIN, BUTTON_PX)
}

/// A small button for one that sits beside the game the whole time.
pub fn small_button(label: impl Into<String>) -> bool {
    sized_button(label, Vec2::new(100.0, 28.0), 14.0)
}

/// A button at least `min` big with lettering `px` tall, its label centred.
pub fn sized_button(label: impl Into<String>, min: Vec2, px: f32) -> bool {
    let label = label.into();
    // Sized exactly: yakui's `Align` fills all the room it is given.
    let width = label.chars().count() as f32 * px * ADVANCE_PER_EM + BUTTON_MARGIN * 2.0;
    let size = Vec2::new(width.max(min.x), min.y);
    let mut clicked = false;
    yakui::constrained(Constraints::tight(size), || {
        let response = clickable(Some(palette::BUTTON), || {
            yakui::center(|| {
                let mut widget = Text::new(px, label);
                widget.style = style(px);
                widget.style.align = TextAlignment::Center;
                widget.show();
            });
        });
        clicked = response.clicked;
    });
    clicked
}

/// An application menu: a panel of touching rows, as wide as the widest.
pub fn rows<F: FnOnce()>(children: F) -> Response<()> {
    panel(|| {
        let mut column = List::column();
        column.main_axis_size = yakui::MainAxisSize::Min;
        column.cross_axis_alignment = CrossAxisAlignment::Start;
        column.show(children);
    })
}

/// One application-menu row: a leading icon, the label, a trailing icon.
pub fn menu_row(
    label: impl Into<String>,
    leading: Option<&'static str>,
    trailing: Option<&'static str>,
) -> Response<ClickResponse> {
    const PX: f32 = 19.0;
    const ICON: f32 = 12.0;
    let label = label.into();
    clickable(Some(palette::ROW), || {
        yakui::pad(Pad::balanced(10.0, 3.0), || {
            let mut row = List::row();
            row.item_spacing = 6.0;
            row.main_axis_size = yakui::MainAxisSize::Min;
            row.cross_axis_alignment = CrossAxisAlignment::Center;
            row.show(|| {
                if let Some(path) = leading {
                    icon(path, ICON, palette::TEXT);
                }
                text(PX, label);
                if let Some(path) = trailing {
                    icon(path, ICON, palette::TEXT);
                }
            });
        });
    })
}

/// Height of a [`menu_bar`], so things can be placed under it.
pub const MENU_BAR_HEIGHT: f32 = 34.0;
const MENU_BAR_PX: f32 = 15.0;
const MENU_TITLE_PAD: f32 = 10.0;

/// What a [`menu_bar`] saw the pointer do.
#[derive(Clone, Debug, Default)]
pub struct MenuBarResponse {
    pub clicked: Option<usize>,
    pub hovered: Option<usize>,
    /// Where each title starts, in pixels from the left, for hanging a [`dropdown`] under it.
    pub starts: Vec<f32>,
}

/// A bar of menu titles across the top of a [`screen`]; draw it first so it takes the top edge.
pub fn menu_bar(titles: &[&str], open: Option<usize>) -> MenuBarResponse {
    let mut response = MenuBarResponse::default();
    let mut x = PANEL_PADDING;
    panel_colored(palette::BAR, || {
        let mut row = List::row();
        row.main_axis_size = yakui::MainAxisSize::Min;
        row.cross_axis_alignment = CrossAxisAlignment::Center;
        row.show(|| {
            for (i, title) in titles.iter().enumerate() {
                response.starts.push(x);
                x += title.len() as f32 * MENU_BAR_PX * ADVANCE_PER_EM + 2.0 * MENU_TITLE_PAD;
                let fills = match open == Some(i) {
                    true => palette::BUTTON,
                    false => palette::ROW,
                };
                let title = clickable(Some(fills), || {
                    yakui::pad(Pad::balanced(MENU_TITLE_PAD, 4.0), || {
                        text(MENU_BAR_PX, *title);
                    });
                });
                if title.clicked {
                    response.clicked = Some(i);
                }
                if title.hovering {
                    response.hovered = Some(i);
                }
            }
        });
    });
    response
}

/// The rows of an open menu, hanging under the title that starts `x` pixels in; fill it with [`menu_row`]s.
pub fn dropdown<F: FnOnce()>(x: f32, children: F) {
    place_px(Vec2::new(x, MENU_BAR_HEIGHT), || {
        yakui::widgets::Layer::new().show(|| {
            rows(children);
        });
    });
}

/// What a [`window`] did this frame.
#[derive(Clone, Copy, Debug, Default)]
pub struct WindowResponse {
    /// The X was clicked; the window is drawn regardless.
    pub closed: bool,
}

/// A draggable panel with a title bar (and an X if `closable`); draw it inside a [`screen`].
pub fn window<F: FnOnce()>(
    title: impl Into<String>,
    at: Vec2,
    width: f32,
    closable: bool,
    children: F,
) -> WindowResponse {
    let title = title.into();
    let mut response = WindowResponse::default();
    let position = yakui::use_state(move || at);
    let position_now = position.get();

    place_px(position_now, || {
        let body = yakui::opaque(|| {
            ColoredBox::container(palette::OUTLINER).show_children(|| {
                yakui::constrained(
                    Constraints {
                        min: Vec2::new(width, 0.0),
                        max: Vec2::new(width, f32::INFINITY),
                    },
                    || {
                        let mut column = List::column();
                        column.main_axis_size = yakui::MainAxisSize::Min;
                        column.cross_axis_alignment = CrossAxisAlignment::Stretch;
                        column.show(|| {
                            let drag = yakui::draggable(|| {
                                ColoredBox::container(palette::BAR).show_children(|| {
                                    yakui::constrained(
                                        Constraints {
                                            min: Vec2::new(0.0, TITLE_HEIGHT),
                                            max: Vec2::new(f32::INFINITY, TITLE_HEIGHT),
                                        },
                                        || {
                                            let mut bar = List::row();
                                            bar.cross_axis_alignment = CrossAxisAlignment::Center;
                                            bar.show(|| {
                                                yakui::pad(
                                                    Pad::horizontal(PANEL_PADDING * 2.0),
                                                    || {
                                                        text_colored(19.0, title, palette::TITLE);
                                                    },
                                                );
                                                yakui::expanded(|| {});
                                                if closable {
                                                    let side = TITLE_HEIGHT - PANEL_PADDING * 2.0;
                                                    yakui::pad(Pad::all(PANEL_PADDING), || {
                                                        let close =
                                                            clickable(Some(palette::CLOSE), || {
                                                                icon(
                                                                    icons::path::X,
                                                                    side,
                                                                    palette::TEXT,
                                                                );
                                                            });
                                                        response.closed = close.clicked;
                                                    });
                                                }
                                            });
                                        },
                                    );
                                });
                            });
                            // The bar spans the window's top edge, so the bar's drag position is the window's.
                            if let Some(dragging) = drag.dragging {
                                position.set(dragging.current);
                            }
                            yakui::pad(Pad::all(PANEL_PADDING), children);
                        });
                    },
                );
            });
        });
        yakui::context::dom()
            .get_global_or_init(Panels::default)
            .0
            .borrow_mut()
            .push(body.id);
    });
    response
}

/// A progress bar, `fraction` filled from the left.
pub fn progress(fraction: f32, size: Vec2) {
    const PADDING: f32 = 3.0;
    ColoredBox::sized(Color::rgba(41, 43, 56, 235), size).show_children(|| {
        yakui::pad(Pad::all(PADDING), || {
            let inner = size - Vec2::splat(PADDING * 2.0);
            let filled = Vec2::new(inner.x * fraction.clamp(0.0, 1.0), inner.y);
            yakui::align(Alignment::CENTER_LEFT, || {
                yakui::colored_box(Color::rgb(107, 158, 219), filled);
            });
        });
    });
}

/// What a [`clickable`] saw the pointer do.
#[derive(Clone, Copy, Debug, Default)]
pub struct ClickResponse {
    pub hovering: bool,
    /// The button went down and came up on it.
    pub clicked: bool,
}

/// A pressable region with an optional pointer-following fill; hover bubbles so the panel behind sees it too.
pub fn clickable<F: FnOnce()>(fills: Option<[Color; 3]>, children: F) -> Response<ClickResponse> {
    widget_children::<ClickableWidget, F>(children, Clickable { fills })
}

#[derive(Debug)]
pub struct Clickable {
    fills: Option<[Color; 3]>,
}

#[derive(Debug)]
pub struct ClickableWidget {
    props: Clickable,
    hovering: bool,
    down: bool,
    clicked: bool,
}

impl Widget for ClickableWidget {
    type Props<'a> = Clickable;
    type Response = ClickResponse;

    fn new() -> Self {
        Self {
            props: Clickable { fills: None },
            hovering: false,
            down: false,
            clicked: false,
        }
    }

    fn update(&mut self, props: Self::Props<'_>) -> Self::Response {
        self.props = props;
        ClickResponse {
            hovering: self.hovering,
            clicked: std::mem::take(&mut self.clicked),
        }
    }

    fn paint(&self, ctx: PaintContext<'_>) {
        if let Some(fills) = self.props.fills {
            let rect = ctx.layout.get(ctx.dom.current()).unwrap().rect;
            let mut fill = PaintRect::new(rect);
            fill.color = match (self.down, self.hovering) {
                (true, _) => fills[2],
                (false, true) => fills[1],
                (false, false) => fills[0],
            };
            fill.add(ctx.paint);
        }
        self.default_paint(ctx);
    }

    fn event_interest(&self) -> EventInterest {
        EventInterest::MOUSE_INSIDE | EventInterest::MOUSE_OUTSIDE
    }

    fn event(&mut self, _ctx: EventContext<'_>, event: &WidgetEvent) -> EventResponse {
        match event {
            WidgetEvent::MouseEnter => {
                self.hovering = true;
                EventResponse::Bubble
            }
            WidgetEvent::MouseLeave => {
                self.hovering = false;
                EventResponse::Bubble
            }
            WidgetEvent::MouseButtonChanged {
                button: MouseButton::One,
                down,
                inside,
                ..
            } => {
                if *down {
                    if *inside {
                        self.down = true;
                        return EventResponse::Sink;
                    }
                    EventResponse::Bubble
                } else {
                    let was_down = std::mem::take(&mut self.down);
                    if was_down && *inside {
                        self.clicked = true;
                        return EventResponse::Sink;
                    }
                    EventResponse::Bubble
                }
            }
            _ => EventResponse::Bubble,
        }
    }
}

/// An icon from [`icons`], `side` pixels square, tinted `color`. Draws nothing, warning once, if not compiled in.
pub fn icon(path: &'static str, side: f32, color: Color) -> Response<()> {
    widget::<IconWidget>(Icon { path, side, color })
}

#[derive(Debug)]
pub struct Icon {
    path: &'static str,
    side: f32,
    color: Color,
}

#[derive(Debug)]
pub struct IconWidget {
    props: Icon,
}

/// Rasterised icon size in pixels; usually drawn smaller and filtered down.
pub const ICON_SIZE: u32 = 32;

/// Icon path -> texture; `None` records a missing icon so it is warned about once.
#[derive(Clone, Default)]
struct IconTextures(Rc<RefCell<HashMap<&'static str, Option<ManagedTextureId>>>>);

impl Widget for IconWidget {
    type Props<'a> = Icon;
    type Response = ();

    fn new() -> Self {
        Self {
            props: Icon {
                path: "",
                side: 0.0,
                color: Color::WHITE,
            },
        }
    }

    fn update(&mut self, props: Self::Props<'_>) -> Self::Response {
        self.props = props;
    }

    fn layout(&self, _ctx: LayoutContext<'_>, constraints: Constraints) -> Vec2 {
        constraints.constrain(Vec2::splat(self.props.side))
    }

    fn paint(&self, ctx: PaintContext<'_>) {
        let textures = ctx.dom.get_global_or_init(IconTextures::default);
        let mut textures = textures.0.borrow_mut();
        let texture = *textures.entry(self.props.path).or_insert_with(|| {
            let path = self.props.path;
            let svg = icons::source(path).or_else(|| {
                log::warn!("{path} is not compiled in; add it to `icons::embedded`");
                None
            })?;
            let pixels = icons::rasterize(svg.as_bytes(), ICON_SIZE).or_else(|| {
                log::warn!("cannot rasterise {path}");
                None
            })?;
            let mut texture = Texture::new(
                TextureFormat::Rgba8Srgb,
                UVec2::new(ICON_SIZE, ICON_SIZE),
                pixels,
            );
            texture.min_filter = TextureFilter::Linear;
            texture.mag_filter = TextureFilter::Linear;
            Some(ctx.paint.add_texture(texture))
        });
        let Some(texture) = texture else {
            return;
        };
        let rect = ctx.layout.get(ctx.dom.current()).unwrap().rect;
        let mut image = PaintRect::new(rect);
        image.color = self.props.color;
        image.texture = Some((texture.into(), Rect::ONE));
        image.add(ctx.paint);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::state::Ui;
    use yakui::event::Event;
    use yakui::paint::Pipeline;

    fn ui() -> Ui {
        let mut ui = Ui::new();
        ui.yakui.set_surface_size(Vec2::new(400.0, 300.0));
        ui.yakui
            .set_unscaled_viewport(Rect::from_pos_size(Vec2::ZERO, Vec2::new(400.0, 300.0)));
        ui
    }

    /// (fills, glyphs) a frame painted.
    fn painted(ui: &mut Ui) -> (usize, usize) {
        let dom = ui.yakui.paint();
        let (mut text, mut main) = (0, 0);
        for layer in dom.layers().iter() {
            for call in &layer.calls {
                match call.pipeline {
                    Pipeline::Text => text += call.indices.len() / 6,
                    _ => main += call.indices.len() / 6,
                }
            }
        }
        (main, text)
    }

    #[test]
    fn a_menu_paints_its_panel_its_buttons_and_their_lettering() {
        let mut ui = ui();
        ui.yakui.start();
        menu(&["NEW GAME", "QUIT"]);
        ui.yakui.finish();

        let (fills, glyphs) = painted(&mut ui);
        assert!(fills >= 3, "a panel and two buttons: {fills}");
        assert!(glyphs >= "NEWGAMEQUIT".len(), "a glyph a letter: {glyphs}");
    }

    #[test]
    fn a_button_answers_a_click() {
        let mut ui = ui();
        let frame = |ui: &mut Ui| {
            ui.yakui.start();
            let clicked = menu(&["HIT"]) == Some(0);
            ui.yakui.finish();
            clicked
        };
        assert!(!frame(&mut ui));

        ui.yakui
            .handle_event(Event::CursorMoved(Some(Vec2::new(200.0, 150.0))));
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: true,
        });
        assert!(!frame(&mut ui), "held, not yet let go");
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: false,
        });
        assert!(frame(&mut ui), "let go on it: a click");
        assert!(!frame(&mut ui), "and only the once");
    }

    #[test]
    fn a_window_can_be_dragged_by_its_bar_and_closed_by_its_x() {
        let mut ui = ui();
        let frame = |ui: &mut Ui| {
            ui.yakui.start();
            let mut closed = false;
            screen(|| {
                let response = window("TEST", Vec2::new(20.0, 20.0), 160.0, true, || {
                    text(14.0, "inside");
                });
                closed = response.closed;
            });
            ui.yakui.finish();
            closed
        };
        frame(&mut ui);

        let root = ui.yakui.dom().root();
        let window_id = {
            let dom = ui.yakui.dom();
            let screen = dom.get(root).unwrap().children[0];
            // A state node precedes the window, so the reflow placing it is the last child.
            let reflow = *dom.get(screen).unwrap().children.last().unwrap();
            dom.get(reflow).unwrap().children[0]
        };
        let before = ui.rect_of(window_id).unwrap();
        assert_eq!(before.pos(), Vec2::new(20.0, 20.0));

        let grab = before.pos() + Vec2::new(30.0, TITLE_HEIGHT * 0.5);
        ui.yakui.handle_event(Event::CursorMoved(Some(grab)));
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: true,
        });
        frame(&mut ui);
        ui.yakui
            .handle_event(Event::CursorMoved(Some(grab + Vec2::new(100.0, 60.0))));
        frame(&mut ui);
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: false,
        });
        frame(&mut ui);
        let after = ui.rect_of(window_id).unwrap();
        assert_eq!(after.pos() - before.pos(), Vec2::new(100.0, 60.0));

        let x = after.pos() + Vec2::new(after.size().x - TITLE_HEIGHT * 0.5, TITLE_HEIGHT * 0.5);
        ui.yakui.handle_event(Event::CursorMoved(Some(x)));
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: true,
        });
        frame(&mut ui);
        ui.yakui.handle_event(Event::MouseButtonChanged {
            button: MouseButton::One,
            down: false,
        });
        assert!(frame(&mut ui), "the X closes it");
    }
}