-
-
Notifications
You must be signed in to change notification settings - Fork 681
/
Copy pathgrid.rs
3640 lines (3536 loc) · 147 KB
/
grid.rs
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::sixel::{PixelRect, SixelGrid, SixelImageStore};
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use zellij_utils::data::Style;
use zellij_utils::errors::prelude::*;
use zellij_utils::regex::Regex;
use std::{
cmp::Ordering,
collections::{BTreeSet, VecDeque},
fmt::{self, Debug, Formatter},
str,
};
use zellij_utils::{
consts::{DEFAULT_SCROLL_BUFFER_SIZE, SCROLL_BUFFER_SIZE},
data::{Palette, PaletteColor},
input::mouse::{MouseEvent, MouseEventType},
pane_size::SizeInPixels,
position::Position,
vte,
};
const TABSTOP_WIDTH: usize = 8; // TODO: is this always right?
pub const MAX_TITLE_STACK_SIZE: usize = 1000;
use vte::{Params, Perform};
use zellij_utils::{consts::VERSION, shared::version_number};
use crate::output::{CharacterChunk, OutputBuffer, SixelImageChunk};
use crate::panes::alacritty_functions::{parse_number, xparse_color};
use crate::panes::link_handler::LinkHandler;
use crate::panes::search::SearchResult;
use crate::panes::selection::Selection;
use crate::panes::terminal_character::{
AnsiCode, CharsetIndex, Cursor, CursorShape, RcCharacterStyles, StandardCharset,
TerminalCharacter, EMPTY_TERMINAL_CHARACTER,
};
use crate::ui::components::UiComponentParser;
fn get_top_non_canonical_rows(rows: &mut Vec<Row>) -> Vec<Row> {
let mut index_of_last_non_canonical_row = None;
for (i, row) in rows.iter().enumerate() {
if row.is_canonical {
break;
} else {
index_of_last_non_canonical_row = Some(i);
}
}
match index_of_last_non_canonical_row {
Some(index_of_last_non_canonical_row) => {
rows.drain(..=index_of_last_non_canonical_row).collect()
},
None => vec![],
}
}
fn get_lines_above_bottom_canonical_row_and_wraps(rows: &mut VecDeque<Row>) -> Vec<Row> {
let mut index_of_last_non_canonical_row = None;
for (i, row) in rows.iter().enumerate().rev() {
index_of_last_non_canonical_row = Some(i);
if row.is_canonical {
break;
}
}
match index_of_last_non_canonical_row {
Some(index_of_last_non_canonical_row) => {
rows.drain(index_of_last_non_canonical_row..).collect()
},
None => vec![],
}
}
fn get_viewport_bottom_canonical_row_and_wraps(viewport: &mut Vec<Row>) -> Vec<Row> {
let mut index_of_last_non_canonical_row = None;
for (i, row) in viewport.iter().enumerate().rev() {
index_of_last_non_canonical_row = Some(i);
if row.is_canonical {
break;
}
}
match index_of_last_non_canonical_row {
Some(index_of_last_non_canonical_row) => {
viewport.drain(index_of_last_non_canonical_row..).collect()
},
None => vec![],
}
}
fn get_top_canonical_row_and_wraps(rows: &mut Vec<Row>) -> Vec<Row> {
let mut index_of_first_non_canonical_row = None;
let mut end_index_of_first_canonical_line = None;
for (i, row) in rows.iter().enumerate() {
if row.is_canonical && end_index_of_first_canonical_line.is_none() {
index_of_first_non_canonical_row = Some(i);
end_index_of_first_canonical_line = Some(i);
continue;
}
if row.is_canonical && end_index_of_first_canonical_line.is_some() {
break;
}
if index_of_first_non_canonical_row.is_some() {
end_index_of_first_canonical_line = Some(i);
continue;
}
}
match (
index_of_first_non_canonical_row,
end_index_of_first_canonical_line,
) {
(Some(first_index), Some(last_index)) => rows.drain(first_index..=last_index).collect(),
(Some(first_index), None) => rows.drain(first_index..).collect(),
_ => vec![],
}
}
fn transfer_rows_from_lines_above_to_viewport(
lines_above: &mut VecDeque<Row>,
viewport: &mut Vec<Row>,
sixel_grid: &mut SixelGrid,
count: usize,
max_viewport_width: usize,
) -> usize {
let mut next_lines: Vec<Row> = vec![];
let mut lines_added_to_viewport: isize = 0;
loop {
if lines_added_to_viewport as usize == count {
break;
}
if next_lines.is_empty() {
match lines_above.pop_back() {
Some(next_line) => {
let mut top_non_canonical_rows_in_dst = get_top_non_canonical_rows(viewport);
lines_added_to_viewport -= top_non_canonical_rows_in_dst.len() as isize;
next_lines.push(next_line);
next_lines.append(&mut top_non_canonical_rows_in_dst);
next_lines =
Row::from_rows(next_lines).split_to_rows_of_length(max_viewport_width);
if next_lines.is_empty() {
// no more lines at lines_above, the line we popped was probably empty
break;
}
},
None => break, // no more rows
}
}
viewport.insert(0, next_lines.pop().unwrap());
lines_added_to_viewport += 1;
}
if !next_lines.is_empty() {
let excess_row = Row::from_rows(next_lines);
bounded_push(lines_above, sixel_grid, excess_row);
}
match usize::try_from(lines_added_to_viewport) {
Ok(n) => n,
_ => 0,
}
}
fn transfer_rows_from_viewport_to_lines_above(
viewport: &mut Vec<Row>,
lines_above: &mut VecDeque<Row>,
sixel_grid: &mut SixelGrid,
count: usize,
max_viewport_width: usize,
) -> isize {
let mut transferred_rows_count: isize = 0;
let drained_lines = std::cmp::min(count, viewport.len());
for next_line in viewport.drain(..drained_lines) {
let mut next_lines: Vec<Row> = vec![];
transferred_rows_count +=
calculate_row_display_height(next_line.width(), max_viewport_width) as isize;
if !next_line.is_canonical {
let mut bottom_canonical_row_and_wraps_in_dst =
get_lines_above_bottom_canonical_row_and_wraps(lines_above);
next_lines.append(&mut bottom_canonical_row_and_wraps_in_dst);
}
next_lines.push(next_line);
let dropped_line_width = bounded_push(lines_above, sixel_grid, Row::from_rows(next_lines));
if let Some(width) = dropped_line_width {
transferred_rows_count -=
calculate_row_display_height(width, max_viewport_width) as isize;
}
}
transferred_rows_count
}
fn transfer_rows_from_lines_below_to_viewport(
lines_below: &mut Vec<Row>,
viewport: &mut Vec<Row>,
count: usize,
max_viewport_width: usize,
) {
let mut next_lines: Vec<Row> = vec![];
for _ in 0..count {
let mut lines_pulled_from_viewport = 0;
if next_lines.is_empty() {
if !lines_below.is_empty() {
let mut top_non_canonical_rows_in_lines_below =
get_top_non_canonical_rows(lines_below);
if !top_non_canonical_rows_in_lines_below.is_empty() {
let mut canonical_line = get_viewport_bottom_canonical_row_and_wraps(viewport);
lines_pulled_from_viewport += canonical_line.len();
canonical_line.append(&mut top_non_canonical_rows_in_lines_below);
next_lines =
Row::from_rows(canonical_line).split_to_rows_of_length(max_viewport_width);
} else {
let canonical_row = get_top_canonical_row_and_wraps(lines_below);
next_lines =
Row::from_rows(canonical_row).split_to_rows_of_length(max_viewport_width);
}
} else {
break; // no more rows
}
}
for _ in 0..(lines_pulled_from_viewport + 1) {
if !next_lines.is_empty() {
viewport.push(next_lines.remove(0));
}
}
}
if !next_lines.is_empty() {
let excess_row = Row::from_rows(next_lines);
lines_below.insert(0, excess_row);
}
}
fn bounded_push(vec: &mut VecDeque<Row>, sixel_grid: &mut SixelGrid, value: Row) -> Option<usize> {
let mut dropped_line_width = None;
if vec.len() >= *SCROLL_BUFFER_SIZE.get().unwrap() {
let line = vec.pop_front();
if let Some(line) = line {
sixel_grid.offset_grid_top();
dropped_line_width = Some(line.width());
}
}
vec.push_back(value);
dropped_line_width
}
pub fn create_horizontal_tabstops(columns: usize) -> BTreeSet<usize> {
let mut i = TABSTOP_WIDTH;
let mut horizontal_tabstops = BTreeSet::new();
loop {
if i > columns {
break;
}
horizontal_tabstops.insert(i);
i += TABSTOP_WIDTH;
}
horizontal_tabstops
}
fn calculate_row_display_height(row_width: usize, viewport_width: usize) -> usize {
if row_width <= viewport_width {
return 1;
}
(row_width as f64 / viewport_width as f64).ceil() as usize
}
fn subtract_isize_from_usize(u: usize, i: isize) -> usize {
if i.is_negative() {
u - i.abs() as usize
} else {
u + i as usize
}
}
macro_rules! dump_screen {
($lines:expr) => {{
let mut is_first = true;
let mut buf = "".to_owned();
for line in &$lines {
if line.is_canonical && !is_first {
buf.push_str("\n");
}
let s: String = (&line.columns).into_iter().map(|x| x.character).collect();
// Replace the spaces at the end of the line. Sometimes, the lines are
// collected with spaces until the end of the panel.
let re = Regex::new("([^ ])[ ]*$").unwrap();
buf.push_str(&(re.replace(&s, "${1}")));
is_first = false;
}
buf
}};
}
fn utf8_mouse_coordinates(column: usize, line: isize) -> Vec<u8> {
let mut coordinates = vec![];
let mouse_pos_encode = |pos: usize| -> Vec<u8> {
let pos = 32 + pos;
let first = 0xC0 + pos / 64;
let second = 0x80 + (pos & 63);
vec![first as u8, second as u8]
};
if column > 95 {
coordinates.append(&mut mouse_pos_encode(column));
} else {
coordinates.push(32 + column as u8);
}
if line > 95 {
coordinates.append(&mut mouse_pos_encode(line as usize));
} else {
coordinates.push(32 + line as u8);
}
coordinates
}
#[derive(Clone)]
pub struct Grid {
pub(crate) lines_above: VecDeque<Row>,
pub(crate) viewport: Vec<Row>,
pub(crate) lines_below: Vec<Row>,
horizontal_tabstops: BTreeSet<usize>,
alternate_screen_state: Option<AlternateScreenState>,
cursor: Cursor,
cursor_is_hidden: bool,
saved_cursor_position: Option<Cursor>,
// FIXME: change scroll_region to be (usize, usize) - where the top line is always the first
// line of the viewport and the bottom line the last unless it's changed with CSI r and friends
// Having it as an Option causes lots of complexity and issues, and according to DECSTBM, this
// should be the behaviour anyway
scroll_region: Option<(usize, usize)>,
active_charset: CharsetIndex,
preceding_char: Option<TerminalCharacter>,
terminal_emulator_colors: Rc<RefCell<Palette>>,
terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>,
pub(crate) output_buffer: OutputBuffer,
title_stack: Vec<String>,
character_cell_size: Rc<RefCell<Option<SizeInPixels>>>,
sixel_grid: SixelGrid,
pub changed_colors: Option<[Option<AnsiCode>; 256]>,
pub should_render: bool,
pub lock_renders: bool,
pub cursor_key_mode: bool, // DECCKM - when set, cursor keys should send ANSI direction codes (eg. "OD") instead of the arrow keys (eg. "[D")
pub bracketed_paste_mode: bool, // when set, paste instructions to the terminal should be escaped with a special sequence
pub erasure_mode: bool, // ERM
pub sixel_scrolling: bool, // DECSDM
pub insert_mode: bool,
pub disable_linewrap: bool,
pub new_line_mode: bool, // Automatic newline LNM
pub clear_viewport_before_rendering: bool,
pub width: usize,
pub height: usize,
pub pending_messages_to_pty: Vec<Vec<u8>>,
pub selection: Selection,
pub title: Option<String>,
pub is_scrolled: bool,
pub link_handler: Rc<RefCell<LinkHandler>>,
pub ring_bell: bool,
scrollback_buffer_lines: usize,
pub mouse_mode: MouseMode,
pub mouse_tracking: MouseTracking,
pub focus_event_tracking: bool,
pub search_results: SearchResult,
pub pending_clipboard_update: Option<String>,
ui_component_bytes: Option<Vec<u8>>,
style: Style,
debug: bool,
arrow_fonts: bool,
styled_underlines: bool,
pub supports_kitty_keyboard_protocol: bool, // has the app requested kitty keyboard support?
explicitly_disable_kitty_keyboard_protocol: bool, // has kitty keyboard support been explicitly
// disabled by user config?
}
#[derive(Clone, Debug)]
pub enum MouseMode {
NoEncoding,
Utf8,
Sgr,
}
impl Default for MouseMode {
fn default() -> Self {
MouseMode::NoEncoding
}
}
#[derive(Clone, Debug)]
pub enum MouseTracking {
Off,
Normal,
ButtonEventTracking,
AnyEventTracking,
}
impl Default for MouseTracking {
fn default() -> Self {
MouseTracking::Off
}
}
impl Debug for Grid {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut buffer: Vec<Row> = self.viewport.clone();
// pad buffer
for _ in buffer.len()..self.height {
buffer.push(Row::new().canonical());
}
// display sixel placeholder
let sixel_indication_character = |x| {
let sixel_indication_word = "Sixel";
sixel_indication_word
.chars()
.nth(x % sixel_indication_word.len())
.unwrap()
};
for image_coordinates in self
.sixel_grid
.image_cell_coordinates_in_viewport(self.height, self.lines_above.len())
{
let (image_top_edge, image_bottom_edge, image_left_edge, image_right_edge) =
image_coordinates;
for y in image_top_edge..image_bottom_edge {
let row = buffer.get_mut(y).unwrap();
for x in image_left_edge..image_right_edge {
let fake_sixel_terminal_character =
TerminalCharacter::new_singlewidth(sixel_indication_character(x));
row.add_character_at(fake_sixel_terminal_character, x);
}
}
}
// display terminal characters with stripped styles
for (i, row) in buffer.iter().enumerate() {
let mut cow_row = Cow::Borrowed(row);
self.search_results
.mark_search_results_in_row(&mut cow_row, i);
if row.is_canonical {
writeln!(f, "{:02?} (C): {:?}", i, cow_row)?;
} else {
writeln!(f, "{:02?} (W): {:?}", i, cow_row)?;
}
}
Ok(())
}
}
impl Grid {
pub fn new(
rows: usize,
columns: usize,
terminal_emulator_colors: Rc<RefCell<Palette>>,
terminal_emulator_color_codes: Rc<RefCell<HashMap<usize, String>>>,
link_handler: Rc<RefCell<LinkHandler>>,
character_cell_size: Rc<RefCell<Option<SizeInPixels>>>,
sixel_image_store: Rc<RefCell<SixelImageStore>>,
style: Style, // TODO: consolidate this with terminal_emulator_colors
debug: bool,
arrow_fonts: bool,
styled_underlines: bool,
explicitly_disable_kitty_keyboard_protocol: bool,
) -> Self {
let sixel_grid = SixelGrid::new(character_cell_size.clone(), sixel_image_store);
// make sure this is initialized as it is used internally
// if it was already initialized (which should happen normally unless this is a test or
// something changed since this comment was written), we get an Error which we ignore
// I don't know why this needs to be a OneCell, but whatevs
let _ = SCROLL_BUFFER_SIZE.set(DEFAULT_SCROLL_BUFFER_SIZE);
Grid {
lines_above: VecDeque::new(),
viewport: vec![Row::new().canonical()],
lines_below: vec![],
horizontal_tabstops: create_horizontal_tabstops(columns),
cursor: Cursor::new(0, 0, styled_underlines),
cursor_is_hidden: false,
saved_cursor_position: None,
scroll_region: None,
preceding_char: None,
width: columns,
height: rows,
should_render: true,
cursor_key_mode: false,
bracketed_paste_mode: false,
erasure_mode: false,
sixel_scrolling: false,
insert_mode: false,
disable_linewrap: false,
new_line_mode: false,
alternate_screen_state: None,
clear_viewport_before_rendering: false,
active_charset: Default::default(),
pending_messages_to_pty: vec![],
terminal_emulator_colors,
terminal_emulator_color_codes,
output_buffer: Default::default(),
selection: Default::default(),
title_stack: vec![],
title: None,
changed_colors: None,
is_scrolled: false,
link_handler,
ring_bell: false,
scrollback_buffer_lines: 0,
mouse_mode: MouseMode::default(),
mouse_tracking: MouseTracking::default(),
focus_event_tracking: false,
character_cell_size,
search_results: Default::default(),
sixel_grid,
pending_clipboard_update: None,
ui_component_bytes: None,
style,
debug,
arrow_fonts,
styled_underlines,
lock_renders: false,
supports_kitty_keyboard_protocol: false,
explicitly_disable_kitty_keyboard_protocol,
}
}
pub fn render_full_viewport(&mut self) {
self.output_buffer.update_all_lines();
}
pub fn update_line_for_rendering(&mut self, line_index: usize) {
self.output_buffer.update_line(line_index);
}
pub fn advance_to_next_tabstop(&mut self, styles: RcCharacterStyles) {
let next_tabstop = self
.horizontal_tabstops
.iter()
.copied()
.find(|&tabstop| tabstop > self.cursor.x && tabstop < self.width);
match next_tabstop {
Some(tabstop) => {
self.cursor.x = tabstop;
},
None => {
self.cursor.x = self.width.saturating_sub(1);
},
}
let mut empty_character = EMPTY_TERMINAL_CHARACTER;
empty_character.styles = styles;
self.pad_current_line_until(self.cursor.x, empty_character);
self.output_buffer.update_line(self.cursor.y);
}
pub fn move_to_previous_tabstop(&mut self) {
let previous_tabstop = self
.horizontal_tabstops
.iter()
.rev()
.copied()
.find(|&tabstop| tabstop < self.cursor.x);
match previous_tabstop {
Some(tabstop) => {
self.cursor.x = tabstop;
},
None => {
self.cursor.x = 0;
},
}
}
pub fn cursor_shape(&self) -> CursorShape {
self.cursor.get_shape()
}
pub fn scrollback_position_and_length(&self) -> (usize, usize) {
// (position, length)
(
self.lines_below.len(),
(self.scrollback_buffer_lines + self.lines_below.len()),
)
}
fn recalculate_scrollback_buffer_count(&self) -> usize {
let mut scrollback_buffer_count = 0;
for row in &self.lines_above {
let row_width = row.width();
// rows in lines_above are unwrapped, so we need to account for that
if row_width > self.width {
scrollback_buffer_count += calculate_row_display_height(row_width, self.width);
} else {
scrollback_buffer_count += 1;
}
}
scrollback_buffer_count
}
fn set_horizontal_tabstop(&mut self) {
self.horizontal_tabstops.insert(self.cursor.x);
}
fn clear_tabstop(&mut self, position: usize) {
self.horizontal_tabstops.remove(&position);
}
fn clear_all_tabstops(&mut self) {
self.horizontal_tabstops.clear();
}
fn save_cursor_position(&mut self) {
self.saved_cursor_position = Some(self.cursor.clone());
}
fn restore_cursor_position(&mut self) {
if let Some(saved_cursor_position) = &self.saved_cursor_position {
self.cursor = saved_cursor_position.clone();
}
}
fn configure_charset(&mut self, charset: StandardCharset, index: CharsetIndex) {
self.cursor.charsets[index] = charset;
}
fn set_active_charset(&mut self, index: CharsetIndex) {
self.active_charset = index;
}
fn cursor_canonical_line_index(&self) -> usize {
let mut cursor_canonical_line_index = 0;
let mut canonical_lines_traversed = 0;
for (i, line) in self.viewport.iter().enumerate() {
if line.is_canonical {
cursor_canonical_line_index = canonical_lines_traversed;
canonical_lines_traversed += 1;
}
if i == self.cursor.y {
break;
}
}
cursor_canonical_line_index
}
// TODO: merge these two functions
fn cursor_index_in_canonical_line(&self) -> usize {
let mut cursor_canonical_line_index = 0;
let mut cursor_index_in_canonical_line = 0;
for (i, line) in self.viewport.iter().enumerate() {
if line.is_canonical {
cursor_canonical_line_index = i;
}
if i == self.cursor.y {
let line_wraps = self.cursor.y.saturating_sub(cursor_canonical_line_index);
cursor_index_in_canonical_line = (line_wraps * self.width) + self.cursor.x;
break;
}
}
cursor_index_in_canonical_line
}
fn saved_cursor_index_in_canonical_line(&self) -> Option<usize> {
if let Some(saved_cursor_position) = self.saved_cursor_position.as_ref() {
let mut cursor_canonical_line_index = 0;
let mut cursor_index_in_canonical_line = 0;
for (i, line) in self.viewport.iter().enumerate() {
if line.is_canonical {
cursor_canonical_line_index = i;
}
if i == saved_cursor_position.y {
let line_wraps = saved_cursor_position.y - cursor_canonical_line_index;
cursor_index_in_canonical_line =
(line_wraps * self.width) + saved_cursor_position.x;
break;
}
}
Some(cursor_index_in_canonical_line)
} else {
None
}
}
fn canonical_line_y_coordinates(&self, canonical_line_index: usize) -> usize {
let mut canonical_lines_traversed = 0;
let mut y_coordinates = 0;
for (i, line) in self.viewport.iter().enumerate() {
if line.is_canonical {
canonical_lines_traversed += 1;
y_coordinates = i;
if canonical_lines_traversed == canonical_line_index + 1 {
break;
}
}
}
y_coordinates
}
pub fn scroll_up_one_line(&mut self) -> bool {
let mut found_something = false;
if !self.lines_above.is_empty() && self.viewport.len() == self.height {
self.is_scrolled = true;
let line_to_push_down = self.viewport.pop().unwrap();
self.lines_below.insert(0, line_to_push_down);
let transferred_rows_height = transfer_rows_from_lines_above_to_viewport(
&mut self.lines_above,
&mut self.viewport,
&mut self.sixel_grid,
1,
self.width,
);
self.scrollback_buffer_lines = self
.scrollback_buffer_lines
.saturating_sub(transferred_rows_height);
self.selection.move_down(1);
// Move all search-selections down one line as well
found_something = self
.search_results
.move_down(1, &self.viewport, self.height);
}
self.output_buffer.update_all_lines();
found_something
}
pub fn scroll_down_one_line(&mut self) -> bool {
let mut found_something = false;
if !self.lines_below.is_empty() && self.viewport.len() == self.height {
let mut line_to_push_up = self.viewport.remove(0);
self.scrollback_buffer_lines +=
calculate_row_display_height(line_to_push_up.width(), self.width);
let line_to_push_up = if line_to_push_up.is_canonical {
line_to_push_up
} else {
match self.lines_above.pop_back() {
Some(mut last_line_above) => {
last_line_above.append(&mut line_to_push_up.columns);
last_line_above
},
None => {
// in this case, this line was not canonical but its beginning line was
// dropped out of scope, so we make it canonical and push it up
line_to_push_up.canonical()
},
}
};
let dropped_line_width =
bounded_push(&mut self.lines_above, &mut self.sixel_grid, line_to_push_up);
if let Some(width) = dropped_line_width {
let dropped_line_height = calculate_row_display_height(width, self.width);
self.scrollback_buffer_lines = self
.scrollback_buffer_lines
.saturating_sub(dropped_line_height);
}
transfer_rows_from_lines_below_to_viewport(
&mut self.lines_below,
&mut self.viewport,
1,
self.width,
);
self.selection.move_up(1);
// Move all search-selections up one line as well
found_something =
self.search_results
.move_up(1, &self.viewport, &self.lines_below, self.height);
self.output_buffer.update_all_lines();
}
if self.lines_below.is_empty() {
self.is_scrolled = false;
}
found_something
}
pub fn force_change_size(&mut self, new_rows: usize, new_columns: usize) {
// this is an ugly hack - it's here because sometimes we need to change_size to the
// existing size (eg. when resizing an alternative_grid to the current height/width) and
// the change_size method is a no-op in that case. Should be fixed by making the
// change_size method atomic
let intermediate_rows = if new_rows == self.height {
new_rows + 1
} else {
new_rows
};
let intermediate_columns = if new_columns == self.width {
new_columns + 1
} else {
new_columns
};
self.change_size(intermediate_rows, intermediate_columns);
self.change_size(new_rows, new_columns);
}
pub fn change_size(&mut self, new_rows: usize, new_columns: usize) {
// Do nothing if this pane hasn't been given a proper size yet
if new_columns == 0 || new_rows == 0 {
return;
}
if self.alternate_screen_state.is_some() {
// in alternate screen we do nothing but log the new size, the program in the terminal
// is in control now...
self.height = new_rows;
self.width = new_columns;
return;
}
self.selection.reset();
self.sixel_grid.character_cell_size_possibly_changed();
let cursors = if new_columns != self.width {
self.horizontal_tabstops = create_horizontal_tabstops(new_columns);
let mut cursor_canonical_line_index = self.cursor_canonical_line_index();
let cursor_index_in_canonical_line = self.cursor_index_in_canonical_line();
let saved_cursor_index_in_canonical_line = self.saved_cursor_index_in_canonical_line();
let mut viewport_canonical_lines = vec![];
for mut row in self.viewport.drain(..) {
if !row.is_canonical
&& viewport_canonical_lines.is_empty()
&& !self.lines_above.is_empty()
{
let mut first_line_above = self.lines_above.pop_back().unwrap();
first_line_above.append(&mut row.columns);
viewport_canonical_lines.push(first_line_above);
cursor_canonical_line_index += 1;
} else if row.is_canonical {
viewport_canonical_lines.push(row);
} else {
match viewport_canonical_lines.last_mut() {
Some(last_line) => {
last_line.append(&mut row.columns);
},
None => {
// the state is corrupted somehow
// this is a bug and I'm not yet sure why it happens
// usually it fixes itself and is a result of some race
// TODO: investigate why this happens and solve it
return;
},
}
}
}
// trim lines after the last empty space that has no following character, because
// terminals don't trim empty lines
for line in &mut viewport_canonical_lines {
let mut trim_at = None;
for (index, character) in line.columns.iter().enumerate() {
if character.character != EMPTY_TERMINAL_CHARACTER.character {
trim_at = None;
} else if trim_at.is_none() {
trim_at = Some(index);
}
}
if let Some(trim_at) = trim_at {
let excess_width_until_trim_at = line.excess_width_until(trim_at);
line.truncate(trim_at + excess_width_until_trim_at);
}
}
let mut new_viewport_rows = vec![];
for mut canonical_line in viewport_canonical_lines {
let mut canonical_line_parts: Vec<Row> = vec![];
if canonical_line.columns.is_empty() {
canonical_line_parts.push(Row::new().canonical());
}
while !canonical_line.columns.is_empty() {
let next_wrap = canonical_line.drain_until(new_columns);
// If the next character is wider than the grid (i.e. there is nothing in
// `next_wrap`, then just abort the resizing
if next_wrap.is_empty() {
break;
}
let row = Row::from_columns(next_wrap);
// if there are no more parts, this row is canonical as long as it originally
// was canonical (it might not have been for example if it's the first row in
// the viewport, and the actual canonical row is above it in the scrollback)
let row = if canonical_line_parts.is_empty() && canonical_line.is_canonical {
row.canonical()
} else {
row
};
canonical_line_parts.push(row);
}
new_viewport_rows.append(&mut canonical_line_parts);
}
self.viewport = new_viewport_rows;
let mut new_cursor_y = self.canonical_line_y_coordinates(cursor_canonical_line_index)
+ (cursor_index_in_canonical_line / new_columns);
let mut saved_cursor_y_coordinates =
self.saved_cursor_position.as_ref().map(|saved_cursor| {
self.canonical_line_y_coordinates(saved_cursor.y)
+ saved_cursor_index_in_canonical_line.as_ref().unwrap() / new_columns
});
// A cursor at EOL has two equivalent positions - end of this line or beginning of
// next. If not already at the beginning of line, bias to EOL so add character logic
// doesn't create spurious canonical lines
let mut new_cursor_x = cursor_index_in_canonical_line % new_columns;
if self.cursor.x != 0 && new_cursor_x == 0 {
new_cursor_y = new_cursor_y.saturating_sub(1);
new_cursor_x = new_columns
}
let saved_cursor_x_coordinates = match (
saved_cursor_index_in_canonical_line.as_ref(),
self.saved_cursor_position.as_mut(),
saved_cursor_y_coordinates.as_mut(),
) {
(
Some(saved_cursor_index_in_canonical_line),
Some(saved_cursor_position),
Some(saved_cursor_y_coordinates),
) => {
let x = saved_cursor_position.x;
let mut new_x = *saved_cursor_index_in_canonical_line % new_columns;
let new_y = saved_cursor_y_coordinates;
if x != 0 && new_x == 0 {
*new_y = new_y.saturating_sub(1);
new_x = new_columns
}
Some(new_x)
},
_ => None,
};
Some((
new_cursor_y,
saved_cursor_y_coordinates,
new_cursor_x,
saved_cursor_x_coordinates,
))
} else if new_rows != self.height {
let saved_cursor_y_coordinates = self
.saved_cursor_position
.as_ref()
.map(|saved_cursor| saved_cursor.y);
let saved_cursor_x_coordinates = self
.saved_cursor_position
.as_ref()
.map(|saved_cursor| saved_cursor.x);
Some((
self.cursor.y,
saved_cursor_y_coordinates,
self.cursor.x,
saved_cursor_x_coordinates,
))
} else {
None
};
if let Some(cursors) = cursors {
// At this point the x coordinates have been calculated, the y coordinates
// will be updated within this block
let (
mut new_cursor_y,
mut saved_cursor_y_coordinates,
new_cursor_x,
saved_cursor_x_coordinates,
) = cursors;
let current_viewport_row_count = self.viewport.len();
match current_viewport_row_count.cmp(&new_rows) {
Ordering::Less => {
let row_count_to_transfer = new_rows - current_viewport_row_count;
transfer_rows_from_lines_above_to_viewport(
&mut self.lines_above,
&mut self.viewport,
&mut self.sixel_grid,
row_count_to_transfer,
new_columns,
);
let rows_pulled = self.viewport.len() - current_viewport_row_count;
new_cursor_y += rows_pulled;
if let Some(saved_cursor_y_coordinates) = saved_cursor_y_coordinates.as_mut() {
*saved_cursor_y_coordinates += rows_pulled;
};
},
Ordering::Greater => {
let row_count_to_transfer = current_viewport_row_count - new_rows;
if row_count_to_transfer > new_cursor_y {
new_cursor_y = 0;
} else {
new_cursor_y -= row_count_to_transfer;
}
if let Some(saved_cursor_y_coordinates) = saved_cursor_y_coordinates.as_mut() {
if row_count_to_transfer > *saved_cursor_y_coordinates {
*saved_cursor_y_coordinates = 0;
} else {
*saved_cursor_y_coordinates -= row_count_to_transfer;
}
}
transfer_rows_from_viewport_to_lines_above(
&mut self.viewport,
&mut self.lines_above,
&mut self.sixel_grid,
row_count_to_transfer,
new_columns,
);
},
Ordering::Equal => {},
}
self.cursor.y = new_cursor_y;
self.cursor.x = new_cursor_x;
if let Some(saved_cursor_position) = self.saved_cursor_position.as_mut() {
match (saved_cursor_x_coordinates, saved_cursor_y_coordinates) {
(Some(saved_cursor_x_coordinates), Some(saved_cursor_y_coordinates)) => {
saved_cursor_position.x = saved_cursor_x_coordinates;
saved_cursor_position.y = saved_cursor_y_coordinates;
},
_ => log::error!(
"invalid state - cannot set saved cursor to {:?} {:?}",
saved_cursor_x_coordinates,
saved_cursor_y_coordinates
),
}
};
}
self.height = new_rows;
self.width = new_columns;
if self.scroll_region.is_some() {
self.set_scroll_region_to_viewport_size();
}
self.scrollback_buffer_lines = self.recalculate_scrollback_buffer_count();
self.search_results.selections.clear();
self.search_viewport();