concinnity-engine 0.19.119

Runtime engine for Concinnity: ECS schedule, graphics, spawn, streaming
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
//! Drives editable TextInput fields: click-to-focus, character entry from the
//! frame's typed characters, and caret editing / movement from the Backspace /
//! Delete / Left / Right / Home / End keys, every event of the frame applied in
//! the order it arrived. Present whenever the world has any `TextInput`
//! (see `World::build_text_input`). Focus and caret live on the component itself
//! (runtime-only fields), so the renderer and any reader see the edited text in
//! place.

use concinnity_core::components::{FrameInput, InputKey, KeyEvent, SpriteFit, TextInput};
use concinnity_core::ecs::{Access, Entity, PipelineContext, StepResult, System};
use concinnity_core::gfx::overlay::OverlayTransform;

// One text edit applied at the caret in a single frame.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Edit {
    Insert(char),
    Backspace,
    Delete,
    Left,
    Right,
    Home,
    End,
}

// The caret edit a non-printable key requests, if any. A printable key's
// character arrives as its own text event (see `edit_from_event`).
fn command_from_key(key: InputKey) -> Option<Edit> {
    match key {
        InputKey::Backspace => Some(Edit::Backspace),
        InputKey::Delete => Some(Edit::Delete),
        InputKey::Left => Some(Edit::Left),
        InputKey::Right => Some(Edit::Right),
        InputKey::Home => Some(Edit::Home),
        InputKey::End => Some(Edit::End),
        _ => None,
    }
}

// The edit one keyboard event requests, if any.
fn edit_from_event(event: &KeyEvent) -> Option<Edit> {
    match event {
        KeyEvent::Text(ch) => Some(Edit::Insert(*ch)),
        KeyEvent::Press(press) => command_from_key(press.key),
    }
}

// Byte offset of the character at `char_idx`, or the string length when the
// index is at (or past) the end. Keeps all edits on a UTF-8 char boundary.
fn char_byte(s: &str, char_idx: usize) -> usize {
    s.char_indices()
        .nth(char_idx)
        .map(|(b, _)| b)
        .unwrap_or(s.len())
}

// Apply one edit to `content` at the caret (a character index). `max_len` of 0
// means no limit. The caret is clamped into range first, so an externally set
// caret (e.g. a pre-filled field) stays valid.
fn apply_edit(content: &mut String, caret: &mut usize, edit: Edit, max_len: usize) {
    let n = content.chars().count();
    let c = (*caret).min(n);
    match edit {
        Edit::Insert(ch) => {
            if max_len != 0 && n >= max_len {
                return;
            }
            let byte = char_byte(content, c);
            content.insert(byte, ch);
            *caret = c + 1;
        }
        Edit::Backspace => {
            if c > 0 {
                let start = char_byte(content, c - 1);
                let end = char_byte(content, c);
                content.replace_range(start..end, "");
                *caret = c - 1;
            }
        }
        Edit::Delete => {
            if c < n {
                let start = char_byte(content, c);
                let end = char_byte(content, c + 1);
                content.replace_range(start..end, "");
                *caret = c;
            }
        }
        Edit::Left => *caret = c.saturating_sub(1),
        Edit::Right => *caret = (c + 1).min(n),
        Edit::Home => *caret = 0,
        Edit::End => *caret = n,
    }
}

// Whether the cursor is inside a field's rect. A screen-owned field is authored in
// the reference canvas, so the cursor is mapped back through the screen's `fit`
// (matching the region hit-test in `UiInputSystem`); a HUD field (no screen) uses
// window pixels directly.
fn cursor_in_field(ti: &TextInput, mx: f32, my: f32, viewport: [f32; 2]) -> bool {
    let (qx, qy) = if ti.screen.is_none() {
        (mx, my)
    } else {
        let overlay = match ti.fit {
            SpriteFit::Bottom => OverlayTransform::bottom_anchored_from_viewport(viewport),
            SpriteFit::Cover => OverlayTransform::cover_from_viewport(viewport),
            SpriteFit::Fit => OverlayTransform::from_viewport(viewport),
        };
        overlay.inverse(mx, my)
    };
    qx >= ti.x && qx < ti.x + ti.width && qy >= ti.y && qy < ti.y + ti.height
}

#[derive(Debug, Default)]
pub(crate) struct TextInputSystem;

impl TextInputSystem {
    pub(crate) fn new() -> Self {
        Self
    }
}

impl System for TextInputSystem {
    fn access(&self) -> Access {
        Access::new()
            .reads_components(crate::component_mask![FrameInput])
            .writes_components(crate::component_mask![TextInput])
    }

    fn step(&mut self, ctx: &mut PipelineContext) -> StepResult {
        let input = match ctx.query::<FrameInput>().last().cloned() {
            Some(i) => i,
            None => return StepResult::Continue,
        };

        // Every character typed and editing key pressed this frame, in order,
        // so fast typing at a low frame rate loses nothing.
        let edits: Vec<Edit> = input
            .key_events
            .iter()
            .filter_map(edit_from_event)
            .collect();

        // On a click, focus moves to the top-most visible field under the cursor
        // (last one wins, matching draw order); a click that misses every field
        // blurs them all. Between clicks the focus flag on the component stands,
        // so another system (or the editor) can pre-focus a field.
        let hit: Option<Entity> = if input.left_click {
            let mut hit = None;
            for (entity, ti) in ctx.query_with_entity::<TextInput>() {
                if ti.visible && cursor_in_field(ti, input.mouse_x, input.mouse_y, input.viewport) {
                    hit = Some(entity);
                }
            }
            hit
        } else {
            None
        };

        for (entity, ti) in ctx.query_mut_with_entity::<TextInput>() {
            if input.left_click {
                ti.focused = ti.visible && Some(entity) == hit;
            }
            // Only the focused field's caret is edited or drawn, so only it needs
            // the per-frame char-count walk. A click moves the caret to the end;
            // otherwise clamp it in case `content` changed out from under us.
            if ti.focused {
                let n = ti.content.chars().count();
                ti.caret = if input.left_click { n } else { ti.caret.min(n) };
                if ti.visible {
                    for &edit in &edits {
                        apply_edit(&mut ti.content, &mut ti.caret, edit, ti.max_len as usize);
                    }
                }
            }
        }

        StepResult::Continue
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ecs::SYSTEMS;
    use concinnity_core::ecs::asset_id::AssetId;

    #[test]
    fn insert_appends_and_advances_caret() {
        let mut s = String::new();
        let mut c = 0;
        apply_edit(&mut s, &mut c, Edit::Insert('h'), 0);
        apply_edit(&mut s, &mut c, Edit::Insert('i'), 0);
        assert_eq!(s, "hi");
        assert_eq!(c, 2);
    }

    #[test]
    fn insert_in_the_middle() {
        let mut s = "ac".to_string();
        let mut c = 1;
        apply_edit(&mut s, &mut c, Edit::Insert('b'), 0);
        assert_eq!(s, "abc");
        assert_eq!(c, 2);
    }

    #[test]
    fn backspace_removes_char_before_caret() {
        let mut s = "abc".to_string();
        let mut c = 2;
        apply_edit(&mut s, &mut c, Edit::Backspace, 0);
        assert_eq!(s, "ac");
        assert_eq!(c, 1);
        // Backspace at the start is a no-op.
        let mut c0 = 0;
        let mut s0 = "x".to_string();
        apply_edit(&mut s0, &mut c0, Edit::Backspace, 0);
        assert_eq!(s0, "x");
        assert_eq!(c0, 0);
    }

    #[test]
    fn delete_removes_char_at_caret() {
        let mut s = "abc".to_string();
        let mut c = 1;
        apply_edit(&mut s, &mut c, Edit::Delete, 0);
        assert_eq!(s, "ac");
        assert_eq!(c, 1);
        // Delete at the end is a no-op.
        let mut c2 = 2;
        apply_edit(&mut s, &mut c2, Edit::Delete, 0);
        assert_eq!(s, "ac");
    }

    #[test]
    fn max_len_clamps_inserts() {
        let mut s = "ab".to_string();
        let mut c = 2;
        apply_edit(&mut s, &mut c, Edit::Insert('c'), 2);
        assert_eq!(s, "ab");
        assert_eq!(c, 2);
    }

    #[test]
    fn arrows_move_and_clamp_caret() {
        let mut s = "abc".to_string();
        let mut c = 1;
        apply_edit(&mut s, &mut c, Edit::Left, 0);
        assert_eq!(c, 0);
        apply_edit(&mut s, &mut c, Edit::Left, 0); // clamps at 0
        assert_eq!(c, 0);
        apply_edit(&mut s, &mut c, Edit::Right, 0);
        assert_eq!(c, 1);
        c = 3;
        apply_edit(&mut s, &mut c, Edit::Right, 0); // clamps at len
        assert_eq!(c, 3);
    }

    #[test]
    fn edits_stay_on_char_boundaries() {
        // A multi-byte char must not panic or split.
        let mut s = "aé".to_string(); // 'é' is two bytes
        let mut c = 2;
        apply_edit(&mut s, &mut c, Edit::Backspace, 0);
        assert_eq!(s, "a");
        assert_eq!(c, 1);
    }

    #[test]
    fn command_keys_map_to_edits() {
        assert_eq!(command_from_key(InputKey::Backspace), Some(Edit::Backspace));
        assert_eq!(command_from_key(InputKey::Delete), Some(Edit::Delete));
        assert_eq!(command_from_key(InputKey::Left), Some(Edit::Left));
        assert_eq!(command_from_key(InputKey::Right), Some(Edit::Right));
        assert_eq!(command_from_key(InputKey::Home), Some(Edit::Home));
        assert_eq!(command_from_key(InputKey::End), Some(Edit::End));
        assert_eq!(command_from_key(InputKey::A), None);
        assert_eq!(command_from_key(InputKey::Enter), None);
    }

    #[test]
    fn home_and_end_jump_the_caret() {
        let mut s = "abc".to_string();
        let mut c = 1;
        apply_edit(&mut s, &mut c, Edit::End, 0);
        assert_eq!(c, 3);
        apply_edit(&mut s, &mut c, Edit::Home, 0);
        assert_eq!(c, 0);
    }

    #[test]
    fn hud_field_hit_tests_in_window_pixels() {
        let ti = TextInput {
            x: 100.0,
            y: 50.0,
            width: 200.0,
            height: 40.0,
            screen: None,
            ..Default::default()
        };
        assert!(cursor_in_field(&ti, 150.0, 60.0, [1280.0, 720.0]));
        assert!(!cursor_in_field(&ti, 50.0, 60.0, [1280.0, 720.0]));
        assert!(!cursor_in_field(&ti, 150.0, 100.0, [1280.0, 720.0]));
    }

    use concinnity_core::ecs::World;

    #[test]
    fn focused_field_types_through_the_schedule() {
        // A world with just a TextInput builds only TextInputSystem; a typed
        // character lands in the focused field.
        let mut world = World::new();
        world.push_identified(
            AssetId(1),
            TextInput {
                focused: true,
                screen: None,
                ..Default::default()
            },
        );
        world.start(SYSTEMS).unwrap();
        world.add_component(FrameInput {
            key_events: vec![KeyEvent::Text('h')],
            ..Default::default()
        });
        world.step();
        assert_eq!(world.query::<TextInput>().next().unwrap().content, "h");
    }

    // Several keystrokes landing in one frame all apply, in arrival order: the
    // fast-typing case a one-per-frame pulse used to drop.
    #[test]
    fn every_event_of_a_frame_applies_in_order() {
        let mut world = World::new();
        world.push_identified(
            AssetId(1),
            TextInput {
                focused: true,
                screen: None,
                ..Default::default()
            },
        );
        world.start(SYSTEMS).unwrap();
        world.add_component(FrameInput {
            key_events: vec![
                KeyEvent::press(InputKey::A),
                KeyEvent::Text('a'),
                KeyEvent::press(InputKey::B),
                KeyEvent::Text('b'),
                KeyEvent::press(InputKey::Backspace),
                KeyEvent::press(InputKey::C),
                KeyEvent::Text('c'),
                KeyEvent::press(InputKey::Home),
                KeyEvent::Text('>'),
            ],
            ..Default::default()
        });
        world.step();
        let field = world.query::<TextInput>().next().unwrap();
        assert_eq!(field.content, ">ac");
        assert_eq!(field.caret, 1);
    }

    #[test]
    fn click_focuses_the_field_under_the_cursor() {
        let mut world = World::new();
        world.push_identified(
            AssetId(1),
            TextInput {
                x: 0.0,
                y: 0.0,
                width: 100.0,
                height: 40.0,
                screen: None,
                ..Default::default()
            },
        );
        world.push_identified(
            AssetId(2),
            TextInput {
                x: 200.0,
                y: 0.0,
                width: 100.0,
                height: 40.0,
                screen: None,
                ..Default::default()
            },
        );
        world.start(SYSTEMS).unwrap();
        // Click inside field 2.
        world.add_component(FrameInput {
            mouse_x: 250.0,
            mouse_y: 20.0,
            left_click: true,
            viewport: [1280.0, 720.0],
            ..Default::default()
        });
        world.step();
        let focus: Vec<(u32, bool)> = world
            .join2::<TextInput, concinnity_core::components::Identity>()
            .map(|(_, t, identity)| (identity.id().0, t.focused))
            .collect();
        assert!(focus.contains(&(1, false)));
        assert!(focus.contains(&(2, true)));
    }
}