concinnity-dev 0.19.119

The Concinnity dev tooling library: world authoring, the in-engine editor, the debug server, docs and packaging
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
//! The confirmation dialog: a centered panel with a wrapped message, an optional
//! name field, an optional checkbox, and a row of two or three buttons over a
//! translucent dim covering the whole screen.
//! Pure geometry and draw; the open / press / close flow lives in
//! `hook/drive/modal.rs`. Not a registered panel: the dialog has no title bar,
//! drag, focus rank, or View toggle, and while open it is screen-modal -- the
//! hook routes every press and wheel to it before anything else, and its draw
//! layer sits above all other chrome.

use concinnity_core::ecs::World;

use super::hud_ids::{Family, family_base, hud_ids};
use super::widget::{self, point_in};
use super::widget_check::{self, Check, CheckIds};
use super::{hud, theme};

pub(crate) const MAX_BUTTONS: usize = 3;

hud_ids! {
    base: family_base(Family::Modal);
    sprites: [DIM, PANEL_BG, CHECK_BOX, button_bg[MAX_BUTTONS]];
    labels: [MESSAGE, CHECK_CAPTION, CHECK_NOTE, button_label[MAX_BUTTONS]];
    fields: [pub(crate) NAME_INPUT = "world name"];
}

const CHECK: CheckIds = CheckIds {
    box_bg: CHECK_BOX,
    caption: CHECK_CAPTION,
    note: CHECK_NOTE,
};

const PANEL_W: f32 = 380.0;
const PAD: f32 = 14.0;
// The message box's height in wrapped lines; longer text ends in an ellipsis.
const MSG_LINES: u32 = 3;
const BTN_W: f32 = 100.0;
const BTN_H: f32 = 28.0;
const BTN_GAP: f32 = 10.0;
// The name field a prompt dialog carries under its message.
const FIELD_H: f32 = 28.0;

// The screen-wide dim behind the dialog, so the chrome under it reads inactive.
const DIM_TINT: [f32; 4] = [0.02, 0.02, 0.03, 0.55];
// The destructive-action red, matching the editor's other confirm chips.
const DANGER_TINT: [f32; 4] = [0.68, 0.26, 0.28, 1.0];
const DANGER_HOVER_TINT: [f32; 4] = [0.80, 0.32, 0.34, 1.0];

// One dialog button. `danger` draws it in the destructive red so the intent
// is unmistakable; `action` is what pressing it does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Button {
    pub(crate) label: String,
    pub(crate) danger: bool,
    pub(crate) action: Action,
}

// What pressing a dialog button does; the hook runs it as the dialog closes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Action {
    // Close without acting (a Cancel / No button).
    Dismiss,
    // A Worlds-panel decision the dialog was guarding.
    Worlds(super::worlds::WorldsConfirm),
    // Name the untitled world the session is on, with whatever the dialog's
    // field holds, and save it there.
    NameWorld,
    // Leave the Shader source panel's file for `then`, writing it first when
    // `save`.
    LeaveShaderSource {
        save: bool,
        then: super::panels::shader_source::Leave,
    },
    // Delete the Shader of this name, and its files when the dialog's box is
    // checked.
    DeleteShader(String),
    // Delete the volumes reading the distance field at this path, and the
    // file when the dialog's box is checked.
    DeleteSdfField(String),
}

// An open dialog: its message, its buttons left to right, whether it carries
// a name field (a prompt), and its checkbox, if any.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Dialog {
    pub(crate) message: String,
    pub(crate) buttons: Vec<Button>,
    pub(crate) field: bool,
    pub(crate) check: Option<Check>,
}

impl Dialog {
    pub(crate) fn controls(&self) -> Controls {
        Controls {
            field: self.field,
            check: self.check.is_some(),
        }
    }
}

// Which optional controls a dialog carries between its message and buttons.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct Controls {
    pub(crate) field: bool,
    pub(crate) check: bool,
}

impl Controls {
    fn field_h(self) -> f32 {
        if self.field { FIELD_H + PAD } else { 0.0 }
    }

    fn check_h(self) -> f32 {
        if self.check {
            widget_check::HEIGHT + PAD
        } else {
            0.0
        }
    }
}

// The dialog's footprint. A prompt is taller by its field, and a dialog with a
// checkbox by that.
pub(crate) fn size(c: Controls) -> [f32; 2] {
    [
        PANEL_W,
        PAD + MSG_LINES as f32 * widget::LINE_H + c.field_h() + c.check_h() + PAD + BTN_H + PAD,
    ]
}

// The dialog's rect: centered in the viewport, clamped fully on screen below
// the top bar for tiny windows.
pub(crate) fn panel_rect(vp: [f32; 2], c: Controls) -> [f32; 4] {
    let s = size(c);
    let centered = [(vp[0] - s[0]) * 0.5, (vp[1] - s[1]) * 0.5];
    widget::outer_rect(widget::clamp_origin(centered, s, vp, hud::BAR_H), s)
}

fn message_rect(p: [f32; 4]) -> [f32; 4] {
    [
        p[0] + PAD,
        p[1] + PAD,
        p[2] - 2.0 * PAD,
        MSG_LINES as f32 * widget::LINE_H,
    ]
}

// The prompt's name field, between the message and the buttons.
fn field_rect(p: [f32; 4]) -> [f32; 4] {
    let m = message_rect(p);
    [m[0], m[1] + m[3] + PAD, m[2], FIELD_H]
}

// The checkbox, under the message and any field.
fn check_rect(p: [f32; 4], c: Controls) -> [f32; 4] {
    let m = message_rect(p);
    [
        m[0],
        m[1] + m[3] + PAD + c.field_h(),
        m[2],
        widget_check::HEIGHT,
    ]
}

// Button `i` of `count`, in caller order left to right along the dialog's
// bottom edge, the last flush with the right padding.
pub(crate) fn button_rect(p: [f32; 4], count: usize, i: usize) -> [f32; 4] {
    let right = p[0] + p[2] - PAD;
    let x = right - (count - i) as f32 * BTN_W - (count - 1 - i) as f32 * BTN_GAP;
    [x, p[1] + p[3] - PAD - BTN_H, BTN_W, BTN_H]
}

// The button under `(mx, my)`, or `None` for a press anywhere else -- which
// the dialog swallows without acting (a click-away is not a cancel).
pub(crate) fn hit_button(
    mx: f32,
    my: f32,
    vp: [f32; 2],
    count: usize,
    c: Controls,
) -> Option<usize> {
    let p = panel_rect(vp, c);
    (0..count.min(MAX_BUTTONS)).find(|&i| point_in(mx, my, button_rect(p, count, i)))
}

// Whether `(mx, my)` is on the dialog's checkbox, when it has one.
pub(crate) fn hit_check(mx: f32, my: f32, vp: [f32; 2], c: Controls) -> bool {
    c.check && widget_check::hit(mx, my, check_rect(panel_rect(vp, c), c))
}

fn button_tint(danger: bool, hovered: bool) -> [f32; 4] {
    match (danger, hovered) {
        (true, true) => DANGER_HOVER_TINT,
        (true, false) => DANGER_TINT,
        (false, true) => theme::HOVER_TINT,
        (false, false) => theme::BUTTON_TINT,
    }
}

pub(crate) fn place(world: &mut World, vp: [f32; 2], dialog: &Dialog, mouse: [f32; 2]) {
    let c = dialog.controls();
    let buttons = &dialog.buttons;
    widget::place_sprite(world, DIM, [0.0, 0.0, vp[0], vp[1]], DIM_TINT, true);
    let p = panel_rect(vp, c);
    widget::place_panel(world, PANEL_BG, p);
    widget::place_message(
        world,
        MESSAGE,
        message_rect(p),
        &dialog.message,
        theme::LABEL,
        true,
    );
    // A prompt's field always owns the keyboard: the dialog is screen-modal, so
    // nothing else can be typing into anything.
    match dialog.field {
        true => widget::show_field(world, NAME_INPUT, field_rect(p), true),
        false => widget::hide_field(world, NAME_INPUT),
    }
    match &dialog.check {
        Some(check) => widget_check::place(world, CHECK, check_rect(p, c), check, mouse),
        None => widget_check::hide(world, CHECK),
    }
    for slot in 0..MAX_BUTTONS {
        match buttons.get(slot) {
            Some(b) => {
                let r = button_rect(p, buttons.len(), slot);
                let hovered = point_in(mouse[0], mouse[1], r);
                widget::place_rounded(
                    world,
                    button_bg(slot),
                    r,
                    button_tint(b.danger, hovered),
                    theme::CONTROL_RADIUS,
                    true,
                );
                widget::place_center_label(
                    world,
                    button_label(slot),
                    [r[0] + r[2] * 0.5, r[1] + r[3] * 0.5 - theme::TEXT_HALF],
                    &widget::clip_text(&b.label, 12),
                    theme::LABEL,
                    true,
                );
            }
            None => {
                widget::set_sprite_visible(world, button_bg(slot), false);
                widget::set_label_visible(world, button_label(slot), false);
            }
        }
    }
}

pub(crate) fn hide(world: &mut World) {
    ids().hide(world);
}

#[cfg(test)]
mod tests {
    use super::*;
    use concinnity_core::components::TextInput;
    use concinnity_core::components::{Sprite, TextAlign, TextLabel};
    use concinnity_core::ecs::asset_id::AssetId;

    const VP: [f32; 2] = [1280.0, 720.0];
    const PLAIN: Controls = Controls {
        field: false,
        check: false,
    };
    const PROMPT: Controls = Controls {
        field: true,
        check: false,
    };

    fn dialog(message: &str, buttons: &[Button], field: bool) -> Dialog {
        Dialog {
            message: message.to_string(),
            buttons: buttons.to_vec(),
            field,
            check: None,
        }
    }

    fn world_with_elements() -> World {
        ids().test_world()
    }

    fn plain(label: &str) -> Button {
        Button {
            label: label.to_string(),
            danger: false,
            action: Action::Dismiss,
        }
    }

    fn danger(label: &str) -> Button {
        Button {
            label: label.to_string(),
            danger: true,
            action: Action::Dismiss,
        }
    }

    fn sprite(world: &World, id: AssetId) -> Sprite {
        world.get_by_id::<Sprite>(id).cloned().unwrap()
    }

    fn label(world: &World, id: AssetId) -> TextLabel {
        world.get_by_id::<TextLabel>(id).cloned().unwrap()
    }

    #[test]
    fn panel_centers_and_clamps_below_the_top_bar() {
        let p = panel_rect(VP, PLAIN);
        let s = size(PLAIN);
        assert_eq!(p[0], (VP[0] - s[0]) * 0.5);
        assert_eq!(p[1], (VP[1] - s[1]) * 0.5);
        assert_eq!((p[2], p[3]), (s[0], s[1]));
        // A viewport too short to center in pins the dialog below the bar.
        let tiny = panel_rect([500.0, 120.0], PLAIN);
        assert!(tiny[1] >= hud::BAR_H);
        assert!(tiny[0] >= 0.0);
    }

    #[test]
    fn buttons_lay_out_left_to_right_inside_the_dialog() {
        let p = panel_rect(VP, PLAIN);
        for count in [2, 3] {
            let rects: Vec<[f32; 4]> = (0..count).map(|i| button_rect(p, count, i)).collect();
            for w in rects.windows(2) {
                assert!(w[0][0] + w[0][2] < w[1][0], "no overlap, caller order");
            }
            let last = rects[count - 1];
            assert_eq!(
                last[0] + last[2],
                p[0] + p[2] - PAD,
                "the last button is flush with the right padding"
            );
            for r in &rects {
                assert!(
                    r[0] >= p[0] && r[0] + r[2] <= p[0] + p[2],
                    "inside the dialog"
                );
                assert!(r[1] + r[3] <= p[1] + p[3], "inside the dialog");
                let m = message_rect(p);
                assert!(r[1] >= m[1] + m[3], "below the message area");
            }
        }
    }

    #[test]
    fn hit_button_resolves_each_button_and_misses_the_rest() {
        let p = panel_rect(VP, PLAIN);
        for count in [2, 3] {
            for i in 0..count {
                let r = button_rect(p, count, i);
                assert_eq!(
                    hit_button(r[0] + 2.0, r[1] + 2.0, VP, count, PLAIN),
                    Some(i)
                );
            }
            // The message area, the dimmed screen, and the gap between two
            // buttons all miss.
            assert_eq!(hit_button(p[0] + 2.0, p[1] + 2.0, VP, count, PLAIN), None);
            assert_eq!(hit_button(5.0, 5.0, VP, count, PLAIN), None);
            let r1 = button_rect(p, count, 1);
            assert_eq!(hit_button(r1[0] - 1.0, r1[1] + 2.0, VP, count, PLAIN), None);
        }
    }

    #[test]
    fn place_dims_the_whole_screen_behind_the_dialog() {
        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog("Delete?", &[plain("Cancel"), danger("Delete")], false),
            [0.0, 0.0],
        );
        let dim = sprite(&world, DIM);
        assert!(dim.visible);
        assert_eq!(
            (dim.x, dim.y, dim.width, dim.height),
            (0.0, 0.0, VP[0], VP[1])
        );
        assert!(dim.tint[3] < 1.0, "translucent, not a blackout");
        assert!(sprite(&world, PANEL_BG).visible);
    }

    #[test]
    fn danger_styling_marks_the_flagged_button_only() {
        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog(
                "Discard changes?",
                &[plain("Cancel"), danger("Discard")],
                false,
            ),
            [0.0, 0.0],
        );
        assert_eq!(sprite(&world, button_bg(0)).tint, theme::BUTTON_TINT);
        assert_eq!(sprite(&world, button_bg(1)).tint, DANGER_TINT);
        let l = label(&world, button_label(1));
        assert!(l.visible && l.content == "Discard");
        assert_eq!(l.align, TextAlign::Center);
    }

    #[test]
    fn hover_highlights_the_button_under_the_cursor() {
        let p = panel_rect(VP, PLAIN);
        let buttons = [plain("Cancel"), danger("Discard")];
        let r0 = button_rect(p, 2, 0);
        let r1 = button_rect(p, 2, 1);

        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog("m", &buttons, false),
            [r0[0] + 2.0, r0[1] + 2.0],
        );
        assert_eq!(sprite(&world, button_bg(0)).tint, theme::HOVER_TINT);
        assert_eq!(sprite(&world, button_bg(1)).tint, DANGER_TINT);

        place(
            &mut world,
            VP,
            &dialog("m", &buttons, false),
            [r1[0] + 2.0, r1[1] + 2.0],
        );
        assert_eq!(sprite(&world, button_bg(0)).tint, theme::BUTTON_TINT);
        assert_eq!(sprite(&world, button_bg(1)).tint, DANGER_HOVER_TINT);
    }

    #[test]
    fn a_two_button_dialog_hides_the_third_slot_and_bounds_the_message() {
        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog(
                "a long message that must wrap inside the dialog",
                &[plain("No"), plain("Yes")],
                false,
            ),
            [0.0, 0.0],
        );
        assert!(!sprite(&world, button_bg(2)).visible);
        assert!(!label(&world, button_label(2)).visible);
        let m = label(&world, MESSAGE);
        assert!(m.visible);
        assert_eq!(m.max_lines, MSG_LINES);
        assert_eq!(m.wrap_width, PANEL_W - 2.0 * PAD);
    }

    #[test]
    fn hide_blanks_every_element() {
        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog("m", &[plain("No"), plain("Yes")], false),
            [0.0, 0.0],
        );
        hide(&mut world);
        assert!(world.query::<Sprite>().all(|s| !s.visible));
        assert!(world.query::<TextLabel>().all(|l| !l.visible));
        assert!(world.query::<TextInput>().all(|t| !t.visible && !t.focused));
    }

    // A prompt carries a focused name field between its message and its
    // buttons, and grows to make room for it; a plain dialog carries none.
    #[test]
    fn a_prompt_shows_a_focused_name_field_and_a_plain_dialog_does_not() {
        let mut world = world_with_elements();
        place(
            &mut world,
            VP,
            &dialog("Name this world", &[plain("Save")], true),
            [0.0, 0.0],
        );
        let field = world.get_by_id::<TextInput>(NAME_INPUT).cloned().unwrap();
        assert!(field.visible && field.focused);
        let p = panel_rect(VP, PROMPT);
        let m = label(&world, MESSAGE);
        assert!(field.y > m.y, "the field sits under the message");
        let button = button_rect(p, 1, 0);
        assert!(field.y + field.height <= button[1], "and above the buttons");
        assert!(size(PROMPT)[1] > size(PLAIN)[1], "the prompt is taller");

        place(
            &mut world,
            VP,
            &dialog("Delete?", &[plain("No")], false),
            [0.0, 0.0],
        );
        assert!(world.query::<TextInput>().all(|t| !t.visible && !t.focused));
    }

    // A checkbox sits between the message and the buttons, grows the dialog,
    // and is hit by its own row only.
    #[test]
    fn a_checkbox_sits_above_the_buttons() {
        let mut d = dialog("Delete?", &[plain("Cancel"), danger("Delete")], false);
        d.check = Some(Check {
            caption: "Also delete its files".to_string(),
            on: false,
            enabled: true,
            note: None,
        });
        let c = d.controls();
        assert!(size(c)[1] > size(PLAIN)[1]);
        let mut world = world_with_elements();
        place(&mut world, VP, &d, [0.0, 0.0]);
        let caption = label(&world, CHECK.caption);
        assert!(caption.visible && caption.content == "Also delete its files");
        let p = panel_rect(VP, c);
        let r = check_rect(p, c);
        assert!(r[1] + r[3] <= button_rect(p, 2, 0)[1]);
        assert!(hit_check(r[0] + 2.0, r[1] + 2.0, VP, c));
        assert!(!hit_check(r[0] + 2.0, r[1] + 2.0, VP, PLAIN));
        assert_eq!(hit_button(r[0] + 2.0, r[1] + 2.0, VP, 2, c), None);

        place(
            &mut world,
            VP,
            &dialog("m", &[plain("No")], false),
            [0.0, 0.0],
        );
        assert!(!label(&world, CHECK.caption).visible);
    }
}