idiom_tui 1.0.1

Bundel of tui widgest and layout componenets (split from idiom editor)
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
mod state;

use crate::{
    backend::Backend,
    layout::{IterLines, Line, RectIter},
    StrChunks, UTFSafe, WriteChunks,
};
pub use state::State;
use std::fmt::Display;
use unicode_width::UnicodeWidthChar;

/// Trait that allows faster rendering without checks and can reduce complexity
pub trait Writable<B: Backend>: Display {
    /// check if the line can be rendered as ascii - no control chars should be included
    fn is_simple(&self) -> bool;
    /// width when rendered
    fn width(&self) -> usize;
    fn char_len(&self) -> usize;
    fn len(&self) -> usize;
    /// directly render no checks or bounds
    fn print(&self, backend: &mut B);
    /// prints bounded by line
    fn print_at(&self, line: Line, backend: &mut B);
    /// wraps within rect
    fn wrap(&self, lines: &mut impl IterLines, backend: &mut B);
    /// # Safety
    /// print truncated
    unsafe fn print_truncated(&self, width: usize, backend: &mut B);
    /// # Safety
    /// print truncated start
    unsafe fn print_truncated_start(&self, width: usize, backend: &mut B);

    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// Represents word with additional meta data such as width, style and number of chars, useful when rendering multiple times the same string
#[derive(Clone, PartialEq, Debug, Default)]
pub struct Text<B: Backend> {
    text: String,
    char_len: usize,
    width: usize,
    style: Option<<B as Backend>::Style>,
}

impl<B: Backend> Text<B> {
    pub fn new(text: String, style: Option<<B as Backend>::Style>) -> Self {
        Self {
            char_len: text.char_len(),
            width: text.width(),
            style,
            text,
        }
    }

    pub fn raw(text: String) -> Self {
        Self {
            char_len: text.char_len(),
            width: text.width(),
            style: None,
            text,
        }
    }

    pub fn new_unchecked(
        text: String,
        char_len: usize,
        width: usize,
        style: Option<<B as Backend>::Style>,
    ) -> Self {
        Self {
            text,
            width,
            char_len,
            style,
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.text.as_str()
    }

    #[inline]
    pub fn style(&self) -> Option<<B as Backend>::Style> {
        self.style.clone()
    }

    #[inline]
    pub fn set_style(&mut self, style: Option<<B as Backend>::Style>) {
        self.style = style;
    }

    #[inline]
    pub fn simple_wrap(&self, lines: &mut RectIter, backend: &mut B) {
        let max_width = match lines.move_cursor(backend) {
            Some(width) => width,
            None => return,
        };
        if max_width > self.width {
            match self.style.clone() {
                Some(style) => backend.print_styled(&self.text, style),
                None => backend.print(&self.text),
            };
            backend.pad(max_width - self.width);
        } else {
            let mut remaining = self.width;
            let mut start = 0;
            match self.style.clone() {
                Some(style) => loop {
                    if remaining > max_width {
                        backend.print_styled(&self.text[start..start + max_width], style.clone());
                        remaining -= max_width;
                        start += max_width;
                    } else {
                        backend.print_styled(&self.text[start..], style.clone());
                        if max_width != remaining {
                            backend.pad(max_width - remaining);
                        }
                        return;
                    }
                    if lines.move_cursor(backend).is_none() {
                        return;
                    }
                },
                None => loop {
                    if remaining < max_width {
                        backend.print(&self.text[start..]);
                        if max_width != remaining {
                            backend.pad(max_width - remaining);
                        }
                    } else {
                        backend.print(&self.text[start..start + max_width]);
                        remaining -= max_width;
                        start += max_width;
                    }
                    if lines.move_cursor(backend).is_none() {
                        return;
                    }
                },
            }
        }
    }

    #[inline]
    fn wrap_with_remainder(&self, lines: &mut impl IterLines, backend: &mut B) -> Option<usize> {
        if self.is_simple() {
            self.wrap_with_remainder_simple(lines, backend)
        } else {
            self.wrap_with_remainder_complex(lines, backend)
        }
    }

    #[inline]
    pub fn wrap_with_remainder_simple(
        &self,
        lines: &mut impl IterLines,
        backend: &mut B,
    ) -> Option<usize> {
        let max_width = lines.move_cursor(backend)?;
        if max_width > self.width {
            match self.style.clone() {
                Some(style) => backend.print_styled(&self.text, style),
                None => backend.print(&self.text),
            };
            Some(max_width - self.width)
        } else {
            let mut remaining = self.width;
            let mut start = 0;
            match self.style.clone() {
                Some(style) => loop {
                    if remaining > max_width {
                        backend.print_styled(&self.text[start..start + max_width], style.clone());
                        remaining -= max_width;
                        start += max_width;
                    } else {
                        backend.print_styled(&self.text[start..], style.clone());
                        return Some(max_width - remaining);
                    }
                    lines.move_cursor(backend)?;
                },
                None => loop {
                    if remaining < max_width {
                        backend.print(&self.text[start..]);
                        return Some(max_width - remaining);
                    } else {
                        backend.print(&self.text[start..start + max_width]);
                        remaining -= max_width;
                        start += max_width;
                    }
                    lines.move_cursor(backend)?;
                },
            }
        }
    }

    #[inline]
    pub fn wrap_with_remainder_complex(
        &self,
        lines: &mut impl IterLines,
        backend: &mut B,
    ) -> Option<usize> {
        let max_width = lines.width();
        let mut chunks = WriteChunks::new(&self.text, max_width);
        let StrChunks {
            mut width,
            mut text,
        } = chunks.next()?;
        match self.style.clone() {
            Some(style) => loop {
                lines.move_cursor(backend)?;
                backend.print_styled(text, style.clone());
                match chunks.next() {
                    Some(next_chunk) => {
                        if width < max_width {
                            backend.pad(max_width - width);
                        }
                        StrChunks { width, text } = next_chunk;
                    }
                    None => {
                        return Some(max_width - width);
                    }
                }
            },
            None => loop {
                lines.move_cursor(backend)?;
                backend.print(text);
                match chunks.next() {
                    Some(next_chunk) => {
                        if width < max_width {
                            backend.pad(max_width - width);
                        }
                        StrChunks { width, text } = next_chunk;
                    }
                    None => {
                        return Some(max_width - width);
                    }
                }
            },
        }
    }
}

impl<B: Backend> Writable<B> for Text<B> {
    #[inline(always)]
    fn is_simple(&self) -> bool {
        self.char_len == self.text.len()
    }

    #[inline(always)]
    fn char_len(&self) -> usize {
        self.char_len
    }

    #[inline(always)]
    fn width(&self) -> usize {
        self.width
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.text.len()
    }

    fn print(&self, backend: &mut B) {
        match self.style.clone() {
            Some(style) => backend.print_styled(&self.text, style),
            None => backend.print(&self.text),
        }
    }

    unsafe fn print_truncated(&self, width: usize, backend: &mut B) {
        if self.is_simple() {
            match self.style.clone() {
                Some(style) => backend.print_styled(self.text.get_unchecked(..width), style),
                None => backend.print(self.text.get_unchecked(..width)),
            }
        } else {
            let (remaining_w, text) = self.text.truncate_width(width);
            match self.style.clone() {
                Some(style) => backend.print_styled(text, style),
                None => backend.print(text),
            }
            if remaining_w != 0 {
                backend.pad(remaining_w);
            }
        };
    }

    unsafe fn print_truncated_start(&self, width: usize, backend: &mut B) {
        if self.is_simple() {
            match self.style.clone() {
                Some(style) => {
                    backend.print_styled(self.text.get_unchecked(self.len() - width..), style)
                }
                None => backend.print(self.text.get_unchecked(self.len() - width..)),
            }
        } else {
            let (remaining_w, text) = self.text.truncate_width_start(width);
            if remaining_w != 0 {
                backend.pad(remaining_w);
            }
            match self.style.clone() {
                Some(style) => backend.print_styled(text, style),
                None => backend.print(text),
            }
        };
    }

    fn print_at(&self, line: Line, backend: &mut B) {
        let Line { width, row, col } = line;
        backend.go_to(row, col);
        if self.width > width {
            unsafe { self.print_truncated(width, backend) };
            return;
        }
        let pad_width = width - self.width;
        self.print(backend);
        if pad_width != 0 {
            backend.pad(pad_width);
        }
    }

    fn wrap(&self, lines: &mut impl IterLines, backend: &mut B) {
        match self.wrap_with_remainder(lines, backend) {
            Some(pad_width) if pad_width != 0 => backend.pad(pad_width),
            _ => (),
        }
    }
}

/// Collection of styled texts, useful when rendering multiple times the same string, as it holds meta data for width / charcer len of words
#[derive(Clone, PartialEq, Default, Debug)]
pub struct StyledLine<B: Backend> {
    inner: Vec<Text<B>>,
}

impl<B: Backend> Writable<B> for StyledLine<B> {
    fn is_simple(&self) -> bool {
        self.inner.iter().all(|text| text.is_simple())
    }

    #[inline(always)]
    fn char_len(&self) -> usize {
        self.inner.iter().fold(0, |sum, text| sum + text.char_len)
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.inner.iter().fold(0, |sum, text| sum + text.len())
    }

    fn width(&self) -> usize {
        self.inner.iter().fold(0, |sum, text| sum + text.width)
    }

    fn print(&self, backend: &mut B) {
        for text in self.inner.iter() {
            text.print(backend)
        }
    }

    unsafe fn print_truncated(&self, mut width: usize, backend: &mut B) {
        for text in self.inner.iter() {
            if text.width > width {
                text.print_truncated(width, backend);
                return;
            }
            width -= text.width;
            text.print(backend);
        }
    }

    unsafe fn print_truncated_start(&self, width: usize, backend: &mut B) {
        let mut skipped = self.width() - width;
        let mut iter = self.inner.iter();
        for text in iter.by_ref() {
            if text.width > skipped {
                text.print_truncated_start(text.width - skipped, backend);
                break;
            }
            skipped -= text.width;
        }

        for text in iter {
            text.print(backend);
        }
    }

    fn print_at(&self, line: Line, backend: &mut B) {
        let Line {
            row,
            col,
            mut width,
        } = line;
        backend.go_to(row, col);
        for text in self.inner.iter() {
            if width < text.width {
                unsafe { text.print_truncated(width, backend) };
                return;
            }
            width -= text.width;
            text.print(backend);
        }
        if width != 0 {
            backend.pad(width);
        }
    }

    fn wrap(&self, lines: &mut impl IterLines, backend: &mut B) {
        let mut width = match lines.move_cursor(backend) {
            Some(width) => width,
            None => return,
        };
        for word in self.inner.iter() {
            if word.width > width {
                if width == 0 {
                    width = match word.wrap_with_remainder(lines, backend) {
                        Some(new_width) => new_width,
                        None => return,
                    }
                } else if word.is_simple() {
                    let mut remaining = word.width;
                    let mut start = 0;
                    match word.style.clone() {
                        Some(style) => loop {
                            if remaining > width {
                                backend
                                    .print_styled(&word.text[start..start + width], style.clone());
                                remaining -= width;
                                start += width;
                            } else {
                                backend.print_styled(&word.text[start..], style.clone());
                                width -= remaining;
                                break;
                            }
                            match lines.move_cursor(backend) {
                                Some(max_width) => width = max_width,
                                None => return,
                            };
                        },
                        None => loop {
                            if remaining > width {
                                backend.print(&word.text[start..start + width]);
                                remaining -= width;
                                start += width;
                            } else {
                                backend.print(&word.text[start..]);
                                width -= remaining;
                                break;
                            }
                            match lines.move_cursor(backend) {
                                Some(max_width) => width = max_width,
                                None => return,
                            };
                        },
                    };
                } else {
                    match word.style.clone() {
                        Some(style) => {
                            for ch in word.text.chars() {
                                let ch_width = match UnicodeWidthChar::width(ch) {
                                    Some(ch_width) => ch_width,
                                    None => continue,
                                };
                                if ch_width > width {
                                    if width != 0 {
                                        backend.pad(width);
                                    }
                                    width = match lines.move_cursor(backend) {
                                        Some(new_width) => {
                                            backend.print_styled(ch, style.clone());
                                            new_width - ch_width
                                        }
                                        None => {
                                            if width != 0 {
                                                backend.pad(width);
                                            };
                                            return;
                                        }
                                    }
                                } else {
                                    backend.print_styled(ch, style.clone());
                                    width -= ch_width;
                                }
                            }
                        }
                        None => {
                            for ch in word.text.chars() {
                                let ch_width = match UnicodeWidthChar::width(ch) {
                                    Some(ch_width) => ch_width,
                                    None => continue,
                                };
                                if ch_width > width {
                                    if width != 0 {
                                        backend.pad(width);
                                    }
                                    width = match lines.move_cursor(backend) {
                                        Some(new_width) => {
                                            backend.print(ch);
                                            new_width - ch_width
                                        }
                                        None => {
                                            if width != 0 {
                                                backend.pad(width);
                                            };
                                            return;
                                        }
                                    }
                                } else {
                                    backend.print(ch);
                                    width -= ch_width;
                                }
                            }
                        }
                    }
                }
            } else {
                width -= word.width;
                word.print(backend);
            }
        }
        if width != 0 {
            backend.pad(width);
        }
    }
}

impl<B: Backend> Display for Text<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text)
    }
}

impl<B: Backend> From<String> for Text<B> {
    fn from(text: String) -> Self {
        Self {
            char_len: text.char_len(),
            width: text.width(),
            text,
            style: None,
        }
    }
}

impl<B: Backend> From<char> for Text<B> {
    #[inline]
    fn from(value: char) -> Self {
        Self {
            char_len: 1,
            width: UnicodeWidthChar::width(value).unwrap_or_default(),
            text: value.to_string(),
            style: None,
        }
    }
}

impl<B: Backend> From<(String, <B as Backend>::Style)> for Text<B> {
    #[inline]
    fn from((text, style): (String, <B as Backend>::Style)) -> Self {
        Self {
            char_len: text.char_len(),
            width: text.width(),
            text,
            style: Some(style),
        }
    }
}

impl<B: Backend> Display for StyledLine<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for text in self.inner.iter() {
            text.fmt(f)?;
        }
        Ok(())
    }
}

impl<B: Backend> From<Vec<Text<B>>> for StyledLine<B> {
    fn from(inner: Vec<Text<B>>) -> Self {
        Self { inner }
    }
}

impl<B: Backend> From<String> for StyledLine<B> {
    fn from(text: String) -> Self {
        Self {
            inner: vec![text.into()],
        }
    }
}

impl<B: Backend> From<(String, <B as Backend>::Style)> for StyledLine<B> {
    fn from(text: (String, <B as Backend>::Style)) -> Self {
        Self {
            inner: vec![text.into()],
        }
    }
}

#[cfg(test)]
mod tests;