Repository navigation
Expand file tree
/
Copy pathbuilder.rs
More file actions
1723 lines (1513 loc) · 62.3 KB
/
Copy pathbuilder.rs
File metadata and controls
1723 lines (1513 loc) · 62.3 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::sliding_window::StatefulSlidingWindow;
use super::unicode::{Directions, PipeStyle, pipe};
use crate::palette::{ButtonState, Palette};
use rand::prelude::*;
use ratatui::buffer::Cell;
use ratatui::layout::Rect;
use ratatui::style::Modifier;
use ratatui::text::{Line, Span, StyledGrapheme};
use ratatui::widgets::Widget;
use std::collections::HashMap;
use std::sync::Mutex;
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
/// Describes how tags are applied to the graphemes of a [`TaggedSpan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpanTag<T> {
/// Every grapheme in the span gets the same tag.
Constant(T),
/// One tag per grapheme in the span, indexed by grapheme position.
/// Falls back to `T::default()` for out-of-range indices.
PerGrapheme(Vec<T>),
}
impl<T: Clone + Copy + Default> SpanTag<T> {
/// Return the tag for the grapheme at `idx`.
pub fn get(&self, idx: usize) -> T {
match self {
SpanTag::Constant(tag) => *tag,
SpanTag::PerGrapheme(tags) => tags.get(idx).copied().unwrap_or_default(),
}
}
}
/// A ratatui [`Span`] paired with a [`SpanTag`] that describes the semantic tag
/// for each grapheme in the span.
#[derive(Debug, Clone)]
pub struct TaggedSpan<'a, T> {
pub span: Span<'a>,
pub tag: SpanTag<T>,
}
impl<'a, T: Clone + Copy + Default> TaggedSpan<'a, T> {
/// Create a `TaggedSpan` where every grapheme gets the same `tag`.
pub fn new(span: Span<'a>, tag: T) -> Self {
TaggedSpan {
span,
tag: SpanTag::Constant(tag),
}
}
/// Create a `TaggedSpan` with a per-grapheme tag vector.
pub fn per_grapheme(span: Span<'a>, tags: Vec<T>) -> Self {
TaggedSpan {
span,
tag: SpanTag::PerGrapheme(tags),
}
}
/// Consume `self` and return a new `TaggedSpan` whose style has the
/// styling for the given non-normal [`ButtonState`] applied on top of the
/// original style.
pub fn with_button_state(self, state: ButtonState) -> Self {
let new_style = Palette::apply_button_style(self.span.style, state);
TaggedSpan {
span: self.span.style(new_style),
tag: self.tag,
}
}
}
impl<'a, T: Clone + Copy + Default> From<Span<'a>> for TaggedSpan<'a, T> {
/// Converts a [`Span`] into a [`TaggedSpan`] with `T::default()` applied to all graphemes.
fn from(span: Span<'a>) -> Self {
TaggedSpan::new(span, T::default())
}
}
/// A sequence of [`TaggedSpan`]s forming a logical line, analogous to ratatui's [`Line`].
#[derive(Debug, Clone, Default)]
pub struct TaggedLine<'a, T> {
pub spans: Vec<TaggedSpan<'a, T>>,
}
impl<'a, T: Clone + Copy + Default> TaggedLine<'a, T> {
/// Create a [`TaggedLine`] from a ratatui [`Line`], assigning `tag` to every span.
pub fn from_line(line: Line<'a>, tag: T) -> Self {
TaggedLine {
spans: line
.spans
.into_iter()
.map(|s| TaggedSpan::new(s, tag))
.collect(),
}
}
/// Return the total display width of all spans in the line, in terminal columns.
pub fn width(&self) -> u16 {
self.spans.iter().map(|ts| ts.span.width() as u16).sum()
}
}
impl<'a, T> From<Vec<TaggedSpan<'a, T>>> for TaggedLine<'a, T> {
fn from(spans: Vec<TaggedSpan<'a, T>>) -> Self {
TaggedLine { spans }
}
}
impl<'a, T: Clone + Copy + Default> From<TaggedSpan<'a, T>> for TaggedLine<'a, T> {
fn from(span: TaggedSpan<'a, T>) -> Self {
TaggedLine { spans: vec![span] }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Coord {
pub row: u16,
pub col: u16,
}
impl Coord {
pub fn new(row: u16, col: u16) -> Self {
Coord { row, col }
}
pub fn abs_diff(&self, other: &Coord) -> usize {
self.col.abs_diff(other.col) as usize + self.row.abs_diff(other.row) as usize
}
pub fn interpolate(&self, other: &Coord, factor: f32) -> Coord {
// factor = 0.0 => self
// factor = 1.0 => other
let col = self.col as f32 + (other.col as f32 - self.col as f32) * factor;
let row = self.row as f32 + (other.row as f32 - self.row as f32) * factor;
Coord::new(row.round() as u16, col.round() as u16)
}
}
/// Represents a position relative to the current terminal cursor position.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct RelativePosition {
/// Target column coordinate.
pub col: u16,
/// Vertical row offset relative to the terminal cursor position (e.g. -2 for 2 rows above cursor).
pub dy: i32,
}
impl RelativePosition {
/// Calculate relative position of `pos` relative to `cursor_pos`.
pub fn relative_to(pos: Coord, cursor_pos: Coord) -> Self {
Self {
col: pos.col,
dy: pos.row as i32 - cursor_pos.row as i32,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct TaggedCell<T> {
pub cell: Cell,
pub tag: T,
pub is_continuation: bool,
}
impl<T: Clone + Copy> TaggedCell<T> {
pub fn update(&mut self, graph: &StyledGrapheme, tag: T) {
self.cell.set_symbol(graph.symbol).set_style(graph.style);
self.tag = tag;
self.is_continuation = false;
}
}
pub struct Contents<T> {
pub buf: Vec<Vec<TaggedCell<T>>>, // each inner Vec is a row of Cells of width `width`
pub width: u16,
cursor_pos: Coord, // visual cursor position with line wrapping
/// Where the terminal emulator thinks the cursor is.
pub term_cursor_pos: Option<Coord>,
/// The row to keep visible when content exceeds the terminal height.
/// Falls back to the cursor row when `None`; set by fuzzy search, tab completions,
/// and AI selection mode to point at the currently selected item.
pub focus_row: Option<u16>,
pub prompt_start: Option<Coord>,
pub prompt_end: Option<Coord>,
/// Clipboard content for each tag slot, populated via [`Contents::setup_clipboard`].
pub clipboards: HashMap<T, String>,
}
impl<T: Clone + Copy + PartialEq + Eq + std::hash::Hash + Default> Contents<T> {
// All the line wrapping logic is handled here.
// So app::ui just handles lines according to the edit buffer
/// Create a new Content with an empty buffer for the given area
pub fn new(width: u16) -> Self {
Contents {
buf: vec![],
width,
cursor_pos: Coord::new(0, 0),
term_cursor_pos: None,
focus_row: None,
prompt_start: None,
prompt_end: None,
clipboards: HashMap::new(),
}
}
/// Register clipboard content for the given `tag`.
/// The `text` is appended to any content already stored for that tag.
pub fn setup_clipboard(&mut self, tag: T, text: String) {
self.clipboards.entry(tag).or_default().push_str(&text);
}
/// Set the focus row – the row that `get_row_range_to_show` will try to keep visible.
pub fn set_focus_row(&mut self, row: u16) {
self.focus_row = Some(row);
}
/// Get the current cursor position (x, y)
pub fn cursor_position(&self) -> Coord {
self.cursor_pos
}
/// Returns the prompt start position relative to the terminal cursor position.
pub fn prompt_start_relative(&self) -> Option<RelativePosition> {
let cursor = self.term_cursor_pos?;
let start = self.prompt_start?;
Some(RelativePosition::relative_to(start, cursor))
}
/// Returns the prompt end position relative to the terminal cursor position.
pub fn prompt_end_relative(&self) -> Option<RelativePosition> {
let cursor = self.term_cursor_pos?;
let end = self.prompt_end?;
Some(RelativePosition::relative_to(end, cursor))
}
pub fn increase_buf_single_row(&mut self) {
let blank_row = vec![TaggedCell::default(); self.width as usize];
self.buf.push(blank_row);
}
pub fn height(&self) -> u16 {
self.buf.len() as u16
}
pub fn get_buffer_lines(&self) -> Vec<String> {
self.buf
.iter()
.map(|row| {
row.iter()
.map(|c| {
let sym = c.cell.symbol();
if sym.is_empty() { " " } else { sym }
})
.collect::<String>()
})
.collect()
}
pub fn move_to_next_insertion_point(
&mut self,
graph: &StyledGrapheme,
overwrite: bool,
area: Option<Rect>,
) -> bool {
let graph_w = graph.symbol.width() as u16;
let (left, right, bottom) = if let Some(area) = area {
let left = area.left().min(self.width);
let right = area.right().min(self.width);
if left >= right {
return false;
}
(left, right, area.bottom())
} else {
(0, self.width, u16::MAX)
};
const MAX_ITERATIONS: usize = 1000; // safety to prevent infinite loops
let mut iterations = 0;
loop {
if iterations >= MAX_ITERATIONS {
return false;
}
iterations += 1;
if self.cursor_pos.row >= self.buf.len() as u16 {
if self.cursor_pos.row >= bottom {
return false;
}
self.increase_buf_single_row();
}
if self.cursor_pos.col < left {
self.cursor_pos.col = left;
}
if self.cursor_pos.col + graph_w > right {
if self.cursor_pos.row + 1 >= bottom {
return false;
}
self.cursor_pos.row += 1;
self.cursor_pos.col = left;
continue;
}
if !overwrite {
let row = &self.buf[self.cursor_pos.row as usize];
let cells =
&row[self.cursor_pos.col as usize..(self.cursor_pos.col + graph_w) as usize];
if cells.iter().all(|cell| cell.tag == T::default()) {
return true;
} else {
self.cursor_pos.col += 1;
continue;
}
} else {
return true;
}
}
}
/// Write a single tagged span at the current cursor position.
/// Will automatically wrap to the next line if necessary.
fn write_span_internal(
&mut self,
tagged_span: &TaggedSpan<T>,
overwrite: bool,
area: Option<Rect>,
) -> bool {
if let SpanTag::Constant(tag) = &tagged_span.tag
&& *tag != T::default()
{
self.setup_clipboard(*tag, tagged_span.span.content.to_string());
}
let graphemes = tagged_span.span.styled_graphemes(tagged_span.span.style);
for (i, graph) in graphemes.enumerate() {
let graph_w = graph.symbol.width() as u16;
if graph_w == 0 {
continue;
}
if !self.move_to_next_insertion_point(&graph, overwrite, area) {
return false;
}
let next_graph_x = self.cursor_pos.col + graph_w;
let tag = tagged_span.tag.get(i);
self.buf[self.cursor_pos.row as usize][self.cursor_pos.col as usize]
.update(&graph, tag);
self.cursor_pos.col += 1;
// Reset following cells if multi-width (they would be hidden by the grapheme),
while self.cursor_pos.col < next_graph_x {
let cell =
&mut self.buf[self.cursor_pos.row as usize][self.cursor_pos.col as usize];
cell.cell.reset();
cell.tag = tag;
cell.is_continuation = true;
self.cursor_pos.col += 1;
}
}
true
}
/// Write a tagged span at the current cursor position, skipping cells that are already filled.
pub fn write_tagged_span_dont_overwrite(&mut self, tagged_span: &TaggedSpan<T>) -> bool {
self.write_span_internal(tagged_span, false, None)
}
/// Write a tagged span at the current cursor position, overwriting any existing content.
pub fn write_tagged_span(&mut self, tagged_span: &TaggedSpan<T>) -> bool {
self.write_span_internal(tagged_span, true, None)
}
/// Write a tagged span at the current cursor position, overwriting any existing content,
/// but only within the given `area`.
pub fn write_tagged_span_area(&mut self, tagged_span: &TaggedSpan<T>, area: Rect) -> bool {
self.write_span_internal(tagged_span, true, Some(area))
}
/// Write a tagged line at the current cursor position.
/// If `insert_new_line` is true, moves to the next line after writing.
pub fn write_tagged_line(&mut self, line: &TaggedLine<T>, insert_new_line: bool) -> bool {
for tagged_span in &line.spans {
if !self.write_tagged_span(tagged_span) {
return false;
}
}
if insert_new_line {
self.newline();
}
true
}
/// Write a tagged line at the current cursor position, but only within the given `area`.
#[allow(unused)]
pub fn write_tagged_line_area(&mut self, line: &TaggedLine<T>, area: Rect) -> bool {
for tagged_span in &line.spans {
if !self.write_span_internal(tagged_span, true, Some(area)) {
return false;
}
}
true
}
/// Write a tagged line left-aligned, fill the gap, then write another tagged line
/// right-aligned — all on the same terminal row.
///
/// If the left line wraps to a second row the fill and right line are skipped.
/// When `leave_cursor_after_l_line` is true the cursor is restored to the position
/// immediately after the left line once the function returns.
pub fn write_tagged_line_lrjustified(
&mut self,
l_line: &TaggedLine<T>,
fill_line: &TaggedLine<T>,
r_line: &TaggedLine<T>,
leave_cursor_after_l_line: bool,
) {
let r_width = r_line.width();
let starting_row = self.cursor_pos.row;
self.write_tagged_line(l_line, false);
let cursor_after_l_line = self.cursor_pos.col;
if self.cursor_pos.row == starting_row {
let target_col = self.width.saturating_sub(r_width);
// Collect styled graphemes and their tags from the fill line.
let fill_graphemes: Vec<StyledGrapheme> = fill_line
.spans
.iter()
.flat_map(|ts| ts.span.styled_graphemes(ts.span.style))
.collect();
let fill_grapheme_tags: Vec<T> = fill_line
.spans
.iter()
.flat_map(|ts| {
ts.span
.content
.graphemes(true)
.enumerate()
.map(|(i, _)| ts.tag.get(i))
})
.collect();
let has_nonzero_width = fill_graphemes.iter().any(|g| g.symbol.width() > 0);
if !has_nonzero_width {
// Zero-width fill: no progress can be made, just move the cursor
self.cursor_pos.col = target_col;
} else if fill_graphemes.len() == 1
&& fill_graphemes[0].symbol == " "
&& fill_graphemes[0].style == ratatui::style::Style::default()
{
// Filling with unstyled spaces: just move the cursor without writing fill chars
self.cursor_pos.col = target_col;
} else {
// Cycle through graphemes one at a time until there isn't room for the next one
let mut idx = 0;
loop {
let graph = &fill_graphemes[idx % fill_graphemes.len()];
let graph_w = graph.symbol.width() as u16;
if graph_w == 0 {
idx += 1;
continue;
}
if self.cursor_pos.col + graph_w > target_col {
break;
}
let fill_tag = fill_grapheme_tags[idx % fill_grapheme_tags.len()];
let span = Span::styled(graph.symbol.to_string(), graph.style);
self.write_tagged_span(&TaggedSpan::new(span, fill_tag));
idx += 1;
}
// Move cursor to where right-aligned content should start
self.cursor_pos.col = target_col;
}
}
if r_width > 0 {
self.write_tagged_line(r_line, false);
}
if leave_cursor_after_l_line {
self.cursor_pos.row = starting_row;
self.cursor_pos.col = cursor_after_l_line;
}
}
/// Move the cursor to a specific column on the current row.
/// This allows positioning the cursor before writing content (e.g. right-aligned ellipsis).
/// `col` is clamped to `self.width` to avoid an inconsistent cursor position.
pub fn set_cursor_col(&mut self, col: u16) {
self.cursor_pos.col = col.min(self.width);
}
/// Fill the rest of the current row with spaces tagged with the given tag
pub fn fill_line(&mut self, tag: T) {
let remaining = self.width.saturating_sub(self.cursor_pos.col) as usize;
if remaining > 0 {
self.write_tagged_span(&TaggedSpan::new(Span::raw(" ".repeat(remaining)), tag));
}
}
pub fn move_to_final_line(&mut self) {
self.cursor_pos.row = self.buf.len().saturating_sub(1) as u16;
self.cursor_pos.col = 0;
}
/// Move the cursor to a specific row and column.
/// Row is clamped to the last buffer row; col is clamped to `self.width`.
pub fn move_cursor_to(&mut self, row: u16, col: u16) {
self.cursor_pos.row = row.min(self.buf.len().saturating_sub(1) as u16);
self.cursor_pos.col = col.min(self.width);
}
pub fn get_tagged_cell(&self, row: u16, col: u16) -> Option<&TaggedCell<T>> {
self.buf.get(row as usize)?.get(col as usize)
}
pub fn get_tagged_cell_mut(&mut self, row: u16, col: u16) -> Option<&mut TaggedCell<T>> {
self.buf.get_mut(row as usize)?.get_mut(col as usize)
}
/// Returns the (start_col, end_col) inclusive column range of the full TaggedSpan
/// that contains the cell at (`row`, `col`).
///
/// Traverses left and right from (`row`, `col`) as long as adjacent cells share the same
/// non-default `Tag`. Multi-width continuation cells are treated as part of their preceding
/// cell's tag.
///
/// Returns `None` if the cell at (`row`, `col`) is default/out-of-bounds.
pub fn get_tagged_span_range(&self, row: usize, col: usize) -> Option<(usize, usize)> {
let row_cells = self.buf.get(row)?;
let cell = row_cells.get(col)?;
let tag = cell.tag;
if tag == T::default() {
return None;
}
// Search backwards (left) for the start of this span
let mut start = col;
while start > 0 && row_cells[start - 1].tag == tag {
start -= 1;
}
// Search forwards (right) for the end of this span
let mut end = col;
let max_col = row_cells.len().saturating_sub(1);
while end < max_col && row_cells[end + 1].tag == tag {
end += 1;
}
Some((start, end))
}
/// Clears any multi-width grapheme that spans across `col` on the given `row`,
/// and writes the specified `symbol` with `style` and `tag` at the start of that grapheme or at `col`.
pub fn overwrite_with_char(
&mut self,
row: usize,
col: usize,
symbol: &str,
style: ratatui::style::Style,
tag: T,
) {
if row >= self.buf.len() {
return;
}
let width = self.width as usize;
if col >= width {
return;
}
// Find the start of the multi-width grapheme if we are on a continuation cell
let mut start_col = col;
if self.buf[row][start_col].is_continuation {
while start_col > 0 && self.buf[row][start_col].is_continuation {
start_col -= 1;
}
}
// Find the end of the multi-width grapheme
let mut end_col = start_col;
while end_col + 1 < width && self.buf[row][end_col + 1].is_continuation {
end_col += 1;
}
// Clear all cells spanning this grapheme
for c in start_col..=end_col {
self.buf[row][c].cell.reset();
self.buf[row][c].tag = T::default();
self.buf[row][c].is_continuation = false;
}
// Set cursor to start_col and write the character using write_span_internal
let old_cursor = self.cursor_pos;
self.cursor_pos = Coord::new(row as u16, start_col as u16);
let span = TaggedSpan::new(Span::styled(symbol.to_string(), style), tag);
self.write_span_internal(&span, true, None);
self.cursor_pos = old_cursor;
}
/// Move to the next line (carriage return + line feed)
pub fn newline(&mut self) {
self.cursor_pos.row += 1;
self.cursor_pos.col = 0;
for _ in self.buf.len()..(self.cursor_pos.row as usize + 1) {
self.increase_buf_single_row();
}
}
fn set_style(&mut self, area: Rect, style: ratatui::style::Style) {
for _ in self.buf.len()..area.bottom() as usize {
self.increase_buf_single_row();
}
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
if let Some(row) = self.buf.get_mut(y as usize)
&& let Some(tagged_cell) = row.get_mut(x as usize)
{
tagged_cell.cell.set_style(style);
}
}
}
}
pub fn set_term_cursor_pos(&mut self, cursor: Coord, style: Option<ratatui::style::Style>) {
self.term_cursor_pos = Some(cursor);
if let Some(style) = style {
self.set_style(Rect::new(cursor.col, cursor.row, 1, 1), style);
}
}
pub fn get_row_range_to_show(&self, term_height: u16) -> std::ops::Range<u16> {
let mut window =
StatefulSlidingWindow::new(0, term_height as usize, self.height() as usize, None);
if let Some(focus_row) = self.focus_row {
window.move_index_to(focus_row as usize);
} else if let Some(term_cursor_pos) = self.term_cursor_pos {
window.move_index_to(term_cursor_pos.row as usize);
}
let range = window.get_window_range();
range.start as u16..range.end as u16
}
pub fn apply_matrix_anim(
&mut self,
now: std::time::Instant,
viewport_top: u16,
terminal_height: u16,
) {
// Extend the buffer so it reaches the bottom of the terminal from the viewport top.
let rows_needed = terminal_height.saturating_sub(viewport_top) as usize;
if rows_needed == 0 {
return;
}
for _ in self.buf.len()..rows_needed {
self.increase_buf_single_row();
}
let mut state_guard = MATRIX_ANIM_STATE.lock().unwrap();
let state = state_guard.get_or_insert_with(MatrixAnimState::new);
let just_started = state.tendrils.is_empty();
// State is updated using the full terminal height so tendril positions are
// terminal-absolute (row 0 = top of terminal, not top of viewport).
state.update(now, self.width, terminal_height);
// When the animation has just started and the viewport is below the top of the
// terminal, fast-forward so that tendrils are already visible in the viewport
// rather than needing to fall viewport_top rows before becoming visible.
if just_started && viewport_top > 0 {
for _ in 0..viewport_top {
state.step(terminal_height);
}
}
for (col_idx, _tendril) in state.tendrils.iter().enumerate() {
let styled_graphs = state.tendril_idx_to_graphemes(col_idx);
// styled_graphs[i] corresponds to terminal-absolute row i.
// Skip rows above the viewport; map the rest into the buffer.
for (term_row, styled_graph) in styled_graphs
.into_iter()
.enumerate()
.skip(viewport_top as usize)
{
let buf_row = term_row - viewport_top as usize;
if let Some(row) = self.buf.get_mut(buf_row)
&& let Some(cell) = row.get_mut(col_idx)
&& cell.tag == T::default()
{
cell.cell
.set_symbol(styled_graph.symbol)
.set_style(styled_graph.style);
}
}
}
}
#[allow(dead_code)]
pub fn write_buffer(&mut self, buffer: &ratatui::buffer::Buffer, tag: T) {
for pos in buffer.area().positions() {
for _ in self.buf.len()..=pos.y as usize {
self.increase_buf_single_row();
}
if let Some(cell) = buffer.cell(pos)
&& let Some(row) = self.buf.get_mut(pos.y as usize)
&& let Some(tagged_cell) = row.get_mut(pos.x as usize)
{
tagged_cell.cell = cell.clone();
tagged_cell.tag = tag;
self.cursor_pos = Coord::new(pos.y, pos.x);
}
}
}
fn get_char_for_box(x: u16, y: u16, area: Rect, is_selected: bool) -> char {
let char = match (x, y) {
(x, y) if x == area.left() && y == area.top() => '╭',
(x, y) if x == area.right() - 1 && y == area.top() => '╮',
(x, y) if x == area.left() && y == area.bottom() - 1 => '╰',
(x, y) if x == area.right() - 1 && y == area.bottom() - 1 => '╯',
(_x, y) if y == area.bottom() - 1 => '─',
(_x, y) if y == area.top() => '─',
(x, _y) if x == area.left() => '│',
(x, _y) if x == area.right() - 1 => '│',
_ => ' ',
};
if !is_selected {
return char;
}
match char {
'╭' => '╔',
'╮' => '╗',
'╰' => '╚',
'╯' => '╝',
'─' => '═', // if y == area.top() { '▂' } else { '🬂' },
'│' => '║', // if x == area.left() { '🮇' } else { '' },
// ' ' => unicode_helpers::FULL_BLOCK, // 🮖 █
_ => char,
}
// match char {
// '╭' => '▗',
// '╮' => '▖',
// '╰' => '▝',
// '╯' => '▘',
// '─' => if y == area.top() { '▄' } else { '▀' },
// '│' => if x == area.left() { '▐' } else { '▌' },
// ' ' => '🮖', // 🮖 █
// _ => char
// }
// match char {
// '╭' => '▗',
// '╮' => '▖',
// '╰' => '',
// '╯' => '▘',
// '─' => if y == area.top() { '🮏' } else { '🮎' },
// '│' => if x == area.left() { '🮍' } else { '🮌' },
// ' ' => '🮐', // 🮖 █
// _ => char
// }
// match char {
// '╭' => '🬆',
// '╮' => '🬊',
// '╰' => '🬱',
// '╯' => '🬵',
// '─' => if y == area.top() { '🮏' } else { '🮎' },
// '│' => if x == area.left() { '🮍' } else { '🮌' },
// ' ' => '🮐', // 🮖 █
// _ => char
// }
// match char { // These ones are good but generally people dont have the font to render them
// // '╭' => '🬆',
// // '╮' => '🬊',
// // '╰' => '🬱',
// // '╯' => '🬵',
// '─' => {
// if y == area.top() {
// '🮏'
// } else {
// '🮎'
// }
// }
// '│' => {
// if x == area.left() {
// '🮍'
// } else {
// '🮌'
// }
// }
// ' ' => '🮐', // 🮖 █
// _ => char,
// }
}
pub fn render_block(&mut self, area: Rect, label: &str, tag: T, state: ButtonState) {
for _ in self.buf.len()..area.bottom() as usize {
self.increase_buf_single_row();
}
let is_selected = !matches!(state, ButtonState::Normal);
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
if let Some(row) = self.buf.get_mut(y as usize)
&& let Some(tagged_cell) = row.get_mut(x as usize)
{
let char = Self::get_char_for_box(x, y, area, is_selected);
let style = if matches!(state, ButtonState::Normal) {
ratatui::style::Style::default()
} else {
Palette::apply_button_style(ratatui::style::Style::default(), state)
};
tagged_cell
.cell
.set_symbol(&char.to_string())
.set_style(style);
tagged_cell.tag = tag;
}
}
// write label in center of block:
let label_style = if matches!(state, ButtonState::Normal) {
ratatui::style::Style::default()
} else {
Palette::apply_button_style(ratatui::style::Style::default(), state)
};
let label_span = Span::styled(label.to_string(), label_style);
let label_width = label_span.width() as u16;
if label_width < area.width {
let label_x = area.left() + (area.width - label_width) / 2;
let label_y = area.top() + ((area.height - 1) / 2);
self.set_cursor_col(label_x);
self.cursor_pos.row = label_y;
self.write_tagged_span(&TaggedSpan::new(label_span, tag));
}
}
}
pub fn render_border(
&mut self,
area: Rect,
tag: T,
style: ratatui::style::Style,
is_selected: bool,
connector_from: Option<Coord>,
status_line: Option<TaggedLine<T>>,
) {
if area.width < 2 || area.height < 2 {
return;
}
let saved_cursor_pos = self.cursor_pos;
for _ in self.buf.len()..area.bottom() as usize {
self.increase_buf_single_row();
}
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
let is_border = y == area.top()
|| y == area.bottom() - 1
|| x == area.left()
|| x == area.right() - 1;
if !is_border {
continue;
}
if let Some(row) = self.buf.get_mut(y as usize)
&& let Some(tagged_cell) = row.get_mut(x as usize)
{
let ch = Self::get_char_for_box(x, y, area, is_selected);
tagged_cell.cell.reset();
tagged_cell
.cell
.set_symbol(&ch.to_string())
.set_style(style);
tagged_cell.tag = tag;
}
}
}
if let Some(status) = status_line {
let max_status_width = area.width.saturating_sub(2) as usize;
let rect_for_status = Rect {
x: area.left() + 2,
y: area.bottom() - 1,
width: max_status_width as u16,
height: 1,
};
self.cursor_pos = Coord {
col: rect_for_status.x,
row: rect_for_status.y,
};
self.write_tagged_line_area(&status, rect_for_status);
}
if let Some(cursor_pos) = connector_from
&& cursor_pos.row < area.y
{
let box_left = area.x;
let box_right = area.right().saturating_sub(1);
let connector_col = if cursor_pos.col >= box_left && cursor_pos.col <= box_right {
cursor_pos.col
} else {
(box_left + 1).min(box_right.saturating_sub(1))
};
let vertical =
pipe(Directions::TOP | Directions::BOTTOM, PipeStyle::Single).unwrap_or(' ');
let box_join_dirs = if connector_col == box_left {
Directions::TOP | Directions::RIGHT | Directions::BOTTOM
} else if connector_col == box_right {
Directions::TOP | Directions::LEFT | Directions::BOTTOM
} else {
Directions::TOP | Directions::LEFT | Directions::RIGHT
};
let box_join = pipe(box_join_dirs, PipeStyle::Single).unwrap_or(' ');
for row in cursor_pos.row.saturating_add(1)..area.y {
self.move_cursor_to(row, connector_col);
self.write_tagged_span(&TaggedSpan::new(
Span::styled(vertical.to_string(), style),
tag,
));
}
self.move_cursor_to(area.y, connector_col);
self.write_tagged_span(&TaggedSpan::new(
Span::styled(box_join.to_string(), style),
tag,
));
}
self.cursor_pos = saved_cursor_pos;
}
pub fn tag_rect(&mut self, area: Rect, tag: T) {
for _ in self.buf.len()..area.bottom() as usize {
self.increase_buf_single_row();
}
for y in area.top()..area.bottom() {
for x in area.left()..area.right() {
if let Some(row) = self.buf.get_mut(y as usize)
&& let Some(tagged_cell) = row.get_mut(x as usize)
{
tagged_cell.tag = tag;
}
}
}
}
pub fn fill_rect(&mut self, area: Rect, symbol: &str, style: ratatui::style::Style, tag: T) {
for _ in self.buf.len()..area.bottom() as usize {
self.increase_buf_single_row();
}
for y in area.top()..area.bottom() {
if let Some(row) = self.buf.get_mut(y as usize) {
for x in area.left()..area.right() {
if let Some(tagged_cell) = row.get_mut(x as usize) {
tagged_cell.cell.reset();
tagged_cell.cell.set_symbol(symbol).set_style(style);
tagged_cell.tag = tag;
}
}
}
}
}
pub fn draw_popup(
&mut self,
message: &str,
y_start: u16,
x_start: u16,
max_height: u16,
style: ratatui::style::Style,
tag: T,
) {
let max_width = (self.width as usize).saturating_sub(4).clamp(20, 60);
let mut lines = Vec::new();
for paragraph in message.lines() {
let mut current_line = String::new();
for word in paragraph.split_whitespace() {
if current_line.is_empty() {
current_line = word.to_string();
} else if current_line.len() + 1 + word.len() <= max_width {
current_line.push(' ');
current_line.push_str(word);
} else {
lines.push(current_line);