crcbl-ui 0.3.0

Crucible immediate-mode GUI
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
//! The editing model: every edit against every selection state, word
//! boundaries, multi-byte and combining text, and the keys that make edits.

use super::*;

/// A line written with its caret and anchor in it: `|` is the caret and `[`
/// the anchor, which is left out when it is at the caret.
fn line(marked: &str) -> LineEdit {
    let mut edit = LineEdit::new();
    let (mut caret, mut anchor) = (None, None);
    let mut count = 0;
    for c in marked.chars() {
        match c {
            '|' => caret = Some(count),
            '[' => anchor = Some(count),
            _ => {
                edit.text.push(c);
                count += 1;
            }
        }
    }
    edit.caret = caret.expect("a marked line has a caret");
    edit.anchor = anchor.unwrap_or(edit.caret);
    edit
}

/// `edit` written back the way [`line`] reads it.
fn marked(edit: &LineEdit) -> String {
    let mut out = String::new();
    for (index, c) in edit.text.chars().chain(['\0']).enumerate() {
        if index == edit.anchor && edit.anchor != edit.caret {
            out.push('[');
        }
        if index == edit.caret {
            out.push('|');
        }
        if c != '\0' {
            out.push(c);
        }
    }
    out
}

const fn mv(motion: Motion) -> Edit {
    Edit::Move {
        motion,
        select: false,
    }
}

const fn sel(motion: Motion) -> Edit {
    Edit::Move {
        motion,
        select: true,
    }
}

/// One row of the edit table: the edit, what each state becomes, and what
/// each asks of the clipboard.
type Row = (Edit, [&'static str; 3], [Option<ClipboardOp>; 3]);

/// **Every edit against every selection state.** The three states are one
/// line, `one two`, with the caret after `t` and nothing selected; with
/// `ne t` selected forwards (the anchor before it, the caret after); and with
/// the same text selected backwards. Each row is the edit, then what each
/// state becomes, then what each asks of the clipboard.
#[test]
fn every_edit_against_every_selection_state() {
    const STATES: [&str; 3] = ["one t|wo", "o[ne t|wo", "o|ne t]wo"];
    let offer = |text: &str| Some(ClipboardOp::Offer(text.to_owned()));
    let table: Vec<Row> = vec![
        (
            Edit::Insert("X".to_owned()),
            ["one tX|wo", "oX|wo", "oX|wo"],
            [None, None, None],
        ),
        (
            mv(Motion::Left),
            ["one |two", "o|ne two", "o|ne two"],
            [None, None, None],
        ),
        (
            mv(Motion::Right),
            ["one tw|o", "one t|wo", "one t|wo"],
            [None, None, None],
        ),
        (
            mv(Motion::WordLeft),
            ["one |two", "|one two", "|one two"],
            [None, None, None],
        ),
        (
            mv(Motion::WordRight),
            ["one two|", "one two|", "one two|"],
            [None, None, None],
        ),
        (
            mv(Motion::Home),
            ["|one two", "|one two", "|one two"],
            [None, None, None],
        ),
        (
            mv(Motion::End),
            ["one two|", "one two|", "one two|"],
            [None, None, None],
        ),
        (
            sel(Motion::Left),
            ["one |t[wo", "o[ne |two", "|one t[wo"],
            [None, None, None],
        ),
        (
            sel(Motion::Right),
            ["one t[w|o", "o[ne tw|o", "on|e t[wo"],
            [None, None, None],
        ),
        (
            sel(Motion::WordLeft),
            ["one |t[wo", "o[ne |two", "|one t[wo"],
            [None, None, None],
        ),
        (
            sel(Motion::WordRight),
            ["one t[wo|", "o[ne two|", "one| t[wo"],
            [None, None, None],
        ),
        (
            sel(Motion::Home),
            ["|one t[wo", "|o[ne two", "|one t[wo"],
            [None, None, None],
        ),
        (
            sel(Motion::End),
            ["one t[wo|", "o[ne two|", "one t[wo|"],
            [None, None, None],
        ),
        (
            Edit::Backspace,
            ["one |wo", "o|wo", "o|wo"],
            [None, None, None],
        ),
        (
            Edit::Delete,
            ["one t|o", "o|wo", "o|wo"],
            [None, None, None],
        ),
        (
            Edit::SelectAll,
            ["[one two|", "[one two|", "[one two|"],
            [None, None, None],
        ),
        (Edit::Copy, STATES, [None, offer("ne t"), offer("ne t")]),
        (
            Edit::Cut,
            ["one t|wo", "o|wo", "o|wo"],
            [None, offer("ne t"), offer("ne t")],
        ),
        (
            Edit::Paste,
            STATES,
            [
                Some(ClipboardOp::Read),
                Some(ClipboardOp::Read),
                Some(ClipboardOp::Read),
            ],
        ),
    ];
    // The table's backward state is written with `]` for readability; the
    // reader takes `[` for the anchor wherever it lies.
    let read = |state: &str| line(&state.replace(']', "["));
    for (edit, after, clipboard) in table {
        for ((state, want), want_clipboard) in STATES.iter().zip(after).zip(clipboard) {
            let mut model = read(state);
            let before = model.clone();
            let applied = model.apply(&edit);
            assert_eq!(marked(&model), marked(&read(want)), "{edit:?} on `{state}`");
            assert_eq!(
                applied.clipboard, want_clipboard,
                "{edit:?} on `{state}` asked the clipboard for the wrong thing"
            );
            assert_eq!(
                applied.text,
                model.text != before.text,
                "{edit:?} on `{state}` misreported a text change"
            );
            assert_eq!(
                applied.caret,
                (model.caret, model.anchor) != (before.caret, before.anchor),
                "{edit:?} on `{state}` misreported a caret move"
            );
        }
    }
}

/// **The ends of the line stop every move**, and a deletion with nothing on
/// its side deletes nothing.
#[test]
fn moves_and_deletions_stop_at_the_ends_of_the_line() {
    let mut start = line("|ab");
    for edit in [
        mv(Motion::Left),
        mv(Motion::WordLeft),
        mv(Motion::Home),
        Edit::Backspace,
    ] {
        let applied = start.apply(&edit);
        assert_eq!(marked(&start), "|ab", "{edit:?} at the start");
        assert_eq!(applied, Applied::default(), "{edit:?} reported work");
    }
    let mut end = line("ab|");
    for edit in [
        mv(Motion::Right),
        mv(Motion::WordRight),
        mv(Motion::End),
        Edit::Delete,
    ] {
        let applied = end.apply(&edit);
        assert_eq!(marked(&end), "ab|", "{edit:?} at the end");
        assert_eq!(applied, Applied::default(), "{edit:?} reported work");
    }
}

/// **Word boundaries**: a word is a run of alphanumerics and `_` or a run of
/// other symbols, whitespace between them is passed over, and a move ends at
/// the far edge of the word it reached.
#[test]
fn word_moves_stop_at_the_edges_of_runs_of_one_class() {
    let text: Vec<char> = "  foo_1.bar  -- baz".chars().collect();
    // Every stop a walk right makes from the start, then a walk left from the
    // end: `foo_1` is one word, `.` is its own run, `--` is one run.
    let mut stops = Vec::new();
    let mut at = 0;
    loop {
        let next = word_right(&text, at);
        if next == at {
            break;
        }
        stops.push(next);
        at = next;
    }
    assert_eq!(stops, [7, 8, 11, 15, 19]);

    let mut stops = Vec::new();
    let mut at = text.len();
    loop {
        let next = word_left(&text, at);
        if next == at {
            break;
        }
        stops.push(next);
        at = next;
    }
    assert_eq!(stops, [16, 13, 8, 7, 2, 0]);

    // A double-click's run: the word, the punctuation, or the space it hit.
    assert_eq!(run_at(&text, 3), 2..7, "inside `foo_1`");
    assert_eq!(run_at(&text, 7), 7..8, "the `.`");
    assert_eq!(run_at(&text, 12), 11..13, "the spaces after `bar`");
    assert_eq!(run_at(&text, 99), 16..19, "past the end is the last word");
    assert_eq!(run_at(&[], 0), 0..0);
}

/// **Multi-byte text is edited by `char`, and combining text by cluster.**
/// A precomposed `é` is one caret stop, and so is `e` with U+0301: one Left
/// passes both, and one Delete takes both — the cluster rule the module docs
/// choose. CJK letters are alphanumeric, so they make a word; an emoji is
/// punctuation-class and its own run. No edit cuts a scalar: a byte-indexed
/// model panics on every one of these.
#[test]
fn multi_byte_and_combining_text_is_edited_by_char() {
    let mut precomposed = line("caf\u{e9}|");
    assert!(precomposed.apply(&Edit::Backspace).text);
    assert_eq!(precomposed.text(), "caf");

    let mut combining = line("cafe\u{301}|");
    assert_eq!(combining.len(), 5, "the accent is a char of its own");
    assert!(combining.apply(&mv(Motion::Left)).caret);
    assert_eq!(combining.caret(), 3, "the caret stopped inside the cluster");
    assert!(combining.apply(&Edit::Delete).text);
    assert_eq!(combining.text(), "caf", "Delete left the accent behind");

    let mut cjk = line("|\u{65e5}\u{672c}\u{8a9e} \u{1f600}x");
    cjk.apply(&sel(Motion::WordRight));
    assert_eq!(cjk.selected_text(), "\u{65e5}\u{672c}\u{8a9e}");
    cjk.apply(&Edit::Insert("\u{fc}".to_owned()));
    assert_eq!(cjk.text(), "\u{fc} \u{1f600}x");
    cjk.apply(&mv(Motion::WordRight));
    assert_eq!(cjk.caret(), 3, "the emoji is a run of its own");
    cjk.apply(&sel(Motion::Left));
    assert_eq!(cjk.selected_text(), "\u{1f600}");
    let applied = cjk.apply(&Edit::Cut);
    assert_eq!(
        applied.clipboard,
        Some(ClipboardOp::Offer("\u{1f600}".to_owned()))
    );
    assert_eq!(marked(&cjk), "\u{fc} |x");
}

/// **A paste replaces the selection**, and control characters in it are
/// dropped one by one — a pasted line break joins the two lines.
#[test]
fn a_paste_replaces_the_selection_and_drops_line_breaks() {
    let mut edit = line("say [hello| world");
    assert!(edit.insert("good\r\nbye"));
    assert_eq!(marked(&edit), "say goodbye| world");

    // Nothing left to insert leaves the selection standing.
    let mut edit = line("[ab|");
    assert!(!edit.insert("\n\t"));
    assert_eq!(marked(&edit), "[ab|");
}

/// **A line changed from outside keeps its caret inside it**, and the same
/// line again changes nothing.
#[test]
fn sync_takes_an_outside_edit_and_holds_the_caret_inside_it() {
    let mut edit = line("abc[def|");
    assert!(!edit.sync("abcdef"));
    assert_eq!(marked(&edit), "abc[def|");
    assert!(edit.sync("ab"));
    assert_eq!(marked(&edit), "ab|");
    assert!(edit.sync("abcd"));
    assert_eq!(marked(&edit), "ab|cd", "the caret moved with a longer line");
}

/// **The keys make the edits the module docs name**, `Shift` selects, and
/// `AltGr` reported as `Ctrl`+`Alt` is not a shortcut.
#[test]
fn keys_become_edits() {
    let none = Modifiers::empty();
    let shift = Modifiers::SHIFT;
    assert_eq!(
        Edit::for_key(KeyCode::ArrowLeft, none),
        Some(mv(Motion::Left))
    );
    assert_eq!(
        Edit::for_key(KeyCode::ArrowRight, shift),
        Some(sel(Motion::Right))
    );
    for word in [Modifiers::CTRL, Modifiers::ALT] {
        assert_eq!(
            Edit::for_key(KeyCode::ArrowLeft, word | shift),
            Some(sel(Motion::WordLeft))
        );
        assert_eq!(
            Edit::for_key(KeyCode::ArrowRight, word),
            Some(mv(Motion::WordRight))
        );
    }
    assert_eq!(
        Edit::for_key(KeyCode::ArrowLeft, Modifiers::SUPER),
        Some(mv(Motion::Home))
    );
    assert_eq!(Edit::for_key(KeyCode::End, shift), Some(sel(Motion::End)));
    assert_eq!(Edit::for_key(KeyCode::Home, none), Some(mv(Motion::Home)));
    assert_eq!(
        Edit::for_key(KeyCode::Backspace, none),
        Some(Edit::Backspace)
    );
    assert_eq!(Edit::for_key(KeyCode::Delete, none), Some(Edit::Delete));
    for shortcut in [Modifiers::CTRL, Modifiers::SUPER] {
        assert_eq!(
            Edit::for_key(KeyCode::KeyA, shortcut),
            Some(Edit::SelectAll)
        );
        assert_eq!(Edit::for_key(KeyCode::KeyC, shortcut), Some(Edit::Copy));
        assert_eq!(Edit::for_key(KeyCode::KeyX, shortcut), Some(Edit::Cut));
        assert_eq!(Edit::for_key(KeyCode::KeyV, shortcut), Some(Edit::Paste));
    }
    assert_eq!(Edit::for_key(KeyCode::KeyV, none), None, "a bare V types");
    assert_eq!(
        Edit::for_key(KeyCode::KeyC, Modifiers::CTRL | Modifiers::ALT),
        None,
        "AltGr+C types a character on many layouts"
    );
    for key in [
        KeyCode::Enter,
        KeyCode::Escape,
        KeyCode::Tab,
        KeyCode::Space,
    ] {
        assert_eq!(Edit::for_key(key, none), None, "{key} is not an edit");
    }
}

/// **The caret never stops inside a cluster**: Left and Right pass a ZWJ
/// sequence, a flag and a mark in one step; Backspace and Delete take each
/// whole; a click, a selection and a word move inside one go to its edge;
/// and text typed in front of a mark leaves the caret after the cluster it
/// joined.
#[test]
fn the_caret_never_stops_inside_a_cluster() {
    // a, woman-ZWJ-laptop (three chars), the US flag (two), q and its accent.
    let text = "a\u{1F469}\u{200D}\u{1F4BB}\u{1F1FA}\u{1F1F8}q\u{301}";
    let mut edit = line(&format!("|{text}"));
    let mut stops = vec![edit.caret()];
    while edit.apply(&mv(Motion::Right)).caret {
        stops.push(edit.caret());
    }
    assert_eq!(stops, [0, 1, 4, 6, 8]);
    let mut back = Vec::new();
    while edit.apply(&mv(Motion::Left)).caret {
        back.push(edit.caret());
    }
    assert_eq!(back, [6, 4, 1, 0]);

    let mut edit = line(&format!("{text}|"));
    assert!(edit.apply(&Edit::Backspace).text);
    assert_eq!(edit.caret(), 6, "the accent went with its q");
    assert!(edit.apply(&Edit::Backspace).text);
    assert_eq!(
        edit.text(),
        "a\u{1F469}\u{200D}\u{1F4BB}",
        "the flag went whole"
    );
    edit.place(1, false);
    assert!(edit.apply(&Edit::Delete).text);
    assert_eq!(edit.text(), "a", "the ZWJ sequence went whole");

    let mut edit = line(&format!("{text}|"));
    edit.place(2, false);
    assert_eq!(edit.caret(), 1, "a click inside went back to the start");
    edit.select(2..5);
    assert_eq!(edit.selection(), 1..6, "a selection grew to whole clusters");
    edit.select(0..7);
    assert_eq!(edit.selection(), 0..8);
    let mut words = line("|q\u{301}b c");
    words.apply(&mv(Motion::WordRight));
    assert_eq!(words.caret(), 2, "a word move stops after the accent");

    let mut typed = line("|\u{301}x");
    assert!(typed.insert("e"));
    assert_eq!(typed.caret(), 2, "the caret went past the mark e took");

    // An outside edit puts a mark after the caret's char: back to its start.
    let mut synced = line("ab|c");
    assert!(synced.sync("ab\u{301}c"));
    assert_eq!((synced.caret(), synced.anchor()), (1, 1));
}