bernardo-tui 0.2.7

A keyboard-only, distraction-free TUI widget library
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
// Copyright 2021-2023 Andrzej J Skalski, 2018-2020 Google LLC
// This version of the file (2021+) is licensed with GNU LGPLv3 License.
// For older version of file (licensed under Apache 2 license), see sly-editor, at
// https://github.com/njskalski/sly-editor/blob/master/src/cursor_set.rs

// Cursor == (Selection, Anchor), thanks Kakoune!
// both positions and anchor are counted in CHARS not offsets.
// Furthermore, I impose a following invariant: the anchor is always above one of selection ends.

// The cursor points to a index where a NEW character will be included, or old character will be
// REPLACED.

// Cursor pointing to a newline character is visualized as an option to append preceding it line.

// So Cursor can point 1 character BEYOND length of buffer!

// Newline is always an end of previous line, not a beginning of new.

// TODO change the selection to Option<usize> to ENFORCE the invariant by reducing the volume of
// data.

//TODO add "invariant protectors" to cursor set and warnings/errors, maybe add tests.

use std::cmp::Ordering;
use std::ops::Range;

use log::{error, warn};

use crate::cursor::cursor_set::CursorSet;
use crate::primitives::has_invariant::HasInvariant;
use crate::text::text_buffer::TextBuffer;

pub const NEWLINE_WIDTH: u16 = 1; // TODO(njskalski): add support for multisymbol newlines?

pub const ZERO_CURSOR: Cursor = Cursor::new(0);

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum CursorStatus {
    None,
    WithinSelection,
    UnderCursor,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
/*
   Describes a selection of text.
   Invariant: anchor is at begin OR end, never in between.
*/
pub struct Selection {
    //begin inclusive
    pub b: usize,
    //end EXCLUSIVE (as *everywhere*)
    pub e: usize,
}

impl Selection {
    pub fn new(b: usize, e: usize) -> Self {
        //TODO got a panic here with move_vertically_by on cursor up
        debug_assert!(b < e, "b {} e {}", b, e);
        Selection { b, e }
    }

    pub fn within(&self, char_idx: usize) -> bool {
        char_idx >= self.b && char_idx < self.e
    }

    pub fn len(&self) -> usize {
        debug_assert!(self.b < self.e);
        if self.b >= self.e {
            error!("selection with begin > end, returning 0 for length: {:?}", self);
            0
        } else {
            self.e - self.b
        }
    }
}

impl PartialOrd<Self> for Selection {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(Ord::cmp(self, other))
    }
}

impl Ord for Selection {
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(&self.b, &other.b).then(Ord::cmp(&self.e, &other.e))
    }
}

/* both signatures are buffer, first idx, current idx, returns whether to continue moving cursor or not
TODO add what happens on any of indices being invalid. Right now I just return false, meaning "stop progressing"
 */
pub type ForwardWordDeterminant = dyn Fn(&dyn TextBuffer, usize, usize) -> bool;
pub type BackwardWordDeterminant = dyn Fn(&dyn TextBuffer, usize, usize) -> bool;

pub fn default_word_determinant(buffer: &dyn TextBuffer, first_idx: usize, current_idx: usize) -> bool {
    match (buffer.char_at(first_idx), buffer.char_at(current_idx)) {
        (Some(first_char), Some(current_char)) => first_char.is_whitespace() == current_char.is_whitespace(),
        _ => false,
    }

    // warn!("word {} first char {:?} curr_char {:?} wd {:?}",
    //             buffer.to_string(),
    //             buffer.char_at(first_idx),
    //             buffer.char_at(current_idx),
    //             return_value,
    //         );
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Cursor {
    // selection. Invariant: anchor is either at begin or end of selection, never inside.
    pub s: Option<Selection>,
    // anchor (position)
    pub a: usize,
    pub preferred_column: Option<usize>,
}

impl Cursor {
    pub fn single() -> Self {
        Cursor {
            s: None,
            a: 0,
            preferred_column: None,
        }
    }

    pub const fn new(anc: usize) -> Self {
        Cursor {
            s: None,
            a: anc,
            preferred_column: None,
        }
    }

    pub fn as_cursor_set(self) -> CursorSet {
        CursorSet::singleton(self)
    }

    pub fn with_selection(self, selection: Selection) -> Self {
        debug_assert!(selection.b == self.a || selection.e == self.a);

        let a = if selection.e == self.a || selection.b == self.a {
            self.a
        } else {
            warn!("Attempted setting selection not respecting invariant. Moving anchor to re-establish it.");
            selection.e
        };

        Cursor {
            s: Some(selection),
            a,
            ..self
        }
    }

    pub fn with_preferred_column(self, preferred_column: usize) -> Self {
        Cursor {
            preferred_column: Some(preferred_column),
            ..self
        }
    }

    pub fn shift_by(&mut self, shift: isize) -> bool {
        debug_assert!(self.check_invariant());

        if shift == 0 {
            return false;
        }

        if shift < 0 {
            let abs_shift = shift.unsigned_abs();

            if self.a < abs_shift || self.s.map(|sel| sel.b < abs_shift).unwrap_or(false) {
                error!("attempted to substract {} from {:?}, ignoring completely.", shift, self);
                return false;
            }
        }

        self.a = (shift + self.a as isize) as usize;
        if let Some(sel) = self.s {
            self.s = Some(Selection::new((shift + sel.b as isize) as usize, (shift + sel.e as isize) as usize));
        }

        debug_assert!(self.check_invariant());

        true
    }

    pub fn advance_and_clear(&mut self, advance_by: isize) -> bool {
        debug_assert!(self.check_invariant());

        let result = if advance_by < 0 && self.a < advance_by.unsigned_abs() {
            error!("attempted to substract {} from {}, using 0 as failsafe.", advance_by, self.a);
            self.a = 0;
            self.clear_both();
            false
        } else {
            // TODO overflow?
            self.a = (advance_by + self.a as isize) as usize;
            self.clear_both();
            true
        };

        debug_assert!(self.check_invariant());
        result
    }

    // Updates selection, had it changed.
    // old_pos is one of selection ends.
    // new_pos is where THAT end is moved.
    // if there is no selection, I behave as if 0-length selection at old_pos was present, so
    //      it gets expanded towards new_pos.
    pub fn update_select(&mut self, old_pos: usize, new_pos: usize) {
        if old_pos == new_pos {
            return;
        }

        match self.s {
            None => self.s = Some(Selection::new(usize::min(old_pos, new_pos), usize::max(old_pos, new_pos))),
            Some(sel) => {
                /* and here'd be dragons:
                   so I need to cover a following scenario:
                   [   ]
                    [  ]
                      []
                       |
                       []
                       [ ]
                       [  ]
                   So shift initially engaged at middle position, then user moved left while holding
                   it, then decided to go right. In this scenario, selection shrinks.
                */

                debug_assert!(old_pos == sel.b || old_pos == sel.e);

                // for explaination why "min" and "max" in two statements below, see single_cursor_to_flip_selection_bug_2 - it is possible that begin and end flip sides.

                if sel.b == old_pos {
                    if new_pos != sel.e {
                        self.s = Some(Selection::new(usize::min(new_pos, sel.e), usize::max(new_pos, sel.e)));
                    } else {
                        self.s = None;
                    }
                } else if sel.e == old_pos {
                    if sel.b != new_pos {
                        self.s = Some(Selection::new(usize::min(new_pos, sel.b), usize::max(new_pos, sel.b)));
                    } else {
                        self.s = None;
                    }
                } else {
                    error!("invariant that selection begins or ends with anchor broken. Not crashing, but fix it.");
                }
            }
        };

        debug_assert!(self.check_invariant());
    }

    pub fn clear_selection(&mut self) {
        self.s = None;
        debug_assert!(self.check_invariant());
    }

    pub fn clear_pc(&mut self) {
        self.preferred_column = None;
        debug_assert!(self.check_invariant());
    }

    // Clears both selection and preferred column.
    pub fn clear_both(&mut self) -> bool {
        let res = self.s.is_some() || self.preferred_column.is_some();
        self.s = None;
        self.preferred_column = None;

        debug_assert!(self.check_invariant());

        res
    }

    pub fn get_cursor_status_for_char(&self, char_idx: usize) -> CursorStatus {
        if char_idx == self.a {
            return CursorStatus::UnderCursor;
        }

        if self.s.is_some() && self.s.unwrap().within(char_idx) {
            return CursorStatus::WithinSelection;
        }

        CursorStatus::None
    }

    // Returns FALSE if noop.
    pub fn move_home(&mut self, rope: &dyn TextBuffer, selecting: bool) -> bool {
        debug_assert!(self.check_invariant());

        let old_pos = self.a;
        let line = rope.char_to_line(self.a).unwrap(); //TODO
        let new_pos = rope.line_to_char(line).unwrap(); //TODO

        debug_assert!(new_pos <= old_pos);

        let result = if new_pos == self.a {
            // in this variant we are just clearing the preferred column. Any selection is not
            // important.
            if self.preferred_column.is_some() {
                self.preferred_column = None;

                true
            } else {
                false
            }
        } else {
            self.a = new_pos;
            if selecting {
                self.update_select(old_pos, new_pos);
            } else {
                self.clear_selection();
            }

            self.preferred_column = None;

            true
        };

        debug_assert!(self.check_invariant());

        result
    }

    // Returns FALSE if noop.
    pub fn move_end(&mut self, rope: &dyn TextBuffer, selecting: bool) -> bool {
        debug_assert!(self.check_invariant());

        let old_pos = self.a;
        let next_line = rope.char_to_line(self.a).unwrap() + 1; // TODO

        let new_pos = if rope.len_lines() > next_line {
            rope.line_to_char(next_line).unwrap() - 1 //TODO
        } else {
            rope.len_chars() // yes, one beyond num chars
        };

        debug_assert!(new_pos >= old_pos);

        let res = if new_pos == self.a {
            // in this variant we are just clearing the preferred column. Any selection is not
            // important.
            if self.preferred_column.is_some() {
                self.preferred_column = None;

                true
            } else {
                false
            }
        } else {
            self.a = new_pos;
            if selecting {
                self.update_select(old_pos, new_pos);
            } else {
                self.clear_selection();
            }
            self.preferred_column = None;

            true
        };

        debug_assert!(self.check_invariant());

        res
    }

    // Returns FALSE on noop.
    // word_determinant should return FALSE when word ends, and TRUE while it continues.
    pub(crate) fn word_begin(&mut self, buffer: &dyn TextBuffer, selecting: bool, word_determinant: &BackwardWordDeterminant) -> bool {
        debug_assert!(self.check_invariant());

        if self.a == 0 {
            return false;
        }

        let old_pos = self.a;

        if self.a > 0 {
            self.a -= 1;

            // this is different than in word_end, because we want "more of the same as the first
            // character we jumped over", so we first move, then remember "what we jumped over"
            let first_char_pos = self.a;

            // if word_determinant(buffer, old_pos, self.a - 1) {
            // case when cursor is within a word
            while self.a > 0 && word_determinant(buffer, first_char_pos, self.a - 1) {
                self.a -= 1;
            }
            // }
        }

        if selecting {
            self.update_select(old_pos, self.a);
        } else {
            self.clear_selection();
        }

        debug_assert!(old_pos >= self.a);
        debug_assert!(self.check_invariant());

        old_pos != self.a
    }

    pub(crate) fn word_end(&mut self, buffer: &dyn TextBuffer, selecting: bool, word_determinant: &ForwardWordDeterminant) -> bool {
        if self.a == buffer.len_chars() {
            return false;
        }

        let old_pos = self.a;

        if self.a < buffer.len_chars() {
            if word_determinant(buffer, old_pos, self.a) {
                // variant within the word
                while self.a < buffer.len_chars() && word_determinant(buffer, old_pos, self.a) {
                    self.a += 1;
                }
            } else {
                self.a += 1;
            }
        }

        if selecting {
            self.update_select(old_pos, self.a);
        } else {
            self.clear_selection();
        }

        debug_assert!(old_pos <= self.a);
        debug_assert!(self.check_invariant());

        old_pos != self.a
    }

    /*
    Drops selection and preferred column.
     */
    pub fn simplify(&mut self) -> bool {
        let mut res = false;
        if self.preferred_column.is_some() {
            self.preferred_column = None;
            res = true;
        }

        if self.s.is_some() {
            self.s = None;
            res = true;
        }

        debug_assert!(self.check_invariant());

        res
    }

    /*
    This one IGNORES preferred column
     */
    pub fn is_simple(&self) -> bool {
        self.s.is_none()
    }

    pub fn anchor_left(&self) -> bool {
        self.s.map(|s| s.b == self.a).unwrap_or(false)
    }

    pub fn anchor_right(&self) -> bool {
        self.s.map(|s| s.e == self.a).unwrap_or(false)
    }

    pub fn get_begin(&self) -> usize {
        self.s.map(|s| s.b).unwrap_or(self.a)
    }

    pub fn get_end(&self) -> usize {
        self.s.map(|s| s.e).unwrap_or(self.a)
    }

    // TODO tests
    pub fn intersects(&self, char_range: &Range<usize>) -> bool {
        debug_assert!(self.check_invariant());

        if self.is_simple() {
            return char_range.start <= self.a && self.a < char_range.end;
        }

        // I will use simple "bracket" evaluation: true opens bracket, false closes bracket
        //  (because in case of idx collision we want to first close and then open)
        let mut brackets = vec![
            (char_range.start, true),
            (char_range.end, false),
            (self.get_begin(), true),
            (self.get_end(), false),
        ];

        brackets.sort();

        let mut how_many_open_brackets: u8 = 0;
        for b in brackets {
            if b.1 {
                how_many_open_brackets += 1;
            } else {
                how_many_open_brackets -= 1;
            }
            if how_many_open_brackets > 1 {
                return true;
            }
        }
        false
    }
}

impl HasInvariant for Cursor {
    fn check_invariant(&self) -> bool {
        if let Some(s) = self.s {
            s.b != s.e && (s.b == self.a || s.e == self.a)
        } else {
            true
        }
    }
}

impl PartialOrd<Self> for Cursor {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(Ord::cmp(self, other))
    }
}

impl Ord for Cursor {
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(&self.a, &other.a).then(Ord::cmp(&self.s, &other.s).then(Ord::cmp(&self.preferred_column, &other.preferred_column)))
    }
}

impl From<(usize, usize, usize)> for Cursor {
    fn from(val: (usize, usize, usize)) -> Self {
        Cursor {
            s: Some(Selection { b: val.0, e: val.1 }),
            a: val.2,
            preferred_column: None,
        }
    }
}

impl From<usize> for Cursor {
    fn from(val: usize) -> Self {
        Cursor {
            s: None,
            a: val,
            preferred_column: None,
        }
    }
}