forked from alacritty/alacritty
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.rs
3181 lines (2639 loc) · 106 KB
/
mod.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
//! Exports the `Term` type which is a high-level API for the Grid.
use std::ops::{Index, IndexMut, Range};
use std::sync::Arc;
use std::{cmp, mem, ptr, slice, str};
use bitflags::bitflags;
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use unicode_width::UnicodeWidthChar;
use crate::ansi::{
self, Attr, CharsetIndex, Color, CursorShape, CursorStyle, Handler, NamedColor, StandardCharset,
};
use crate::config::Config;
use crate::event::{Event, EventListener};
use crate::grid::{Dimensions, Grid, GridCell, GridIterator, Scroll};
use crate::index::{self, Boundary, Column, Direction, Line, Point, Side};
use crate::selection::{Selection, SelectionRange, SelectionType};
use crate::term::cell::{Cell, Flags, LineLength};
use crate::term::color::{Colors, Rgb};
use crate::vi_mode::{ViModeCursor, ViMotion};
pub mod cell;
pub mod color;
pub mod search;
/// Minimum number of columns.
///
/// A minimum of 2 is necessary to hold fullwidth unicode characters.
pub const MIN_COLUMNS: usize = 2;
/// Minimum number of visible lines.
pub const MIN_SCREEN_LINES: usize = 1;
/// Max size of the window title stack.
const TITLE_STACK_MAX_DEPTH: usize = 4096;
/// Default tab interval, corresponding to terminfo `it` value.
const INITIAL_TABSTOPS: usize = 8;
bitflags! {
pub struct TermMode: u32 {
const NONE = 0;
const SHOW_CURSOR = 0b0000_0000_0000_0000_0001;
const APP_CURSOR = 0b0000_0000_0000_0000_0010;
const APP_KEYPAD = 0b0000_0000_0000_0000_0100;
const MOUSE_REPORT_CLICK = 0b0000_0000_0000_0000_1000;
const BRACKETED_PASTE = 0b0000_0000_0000_0001_0000;
const SGR_MOUSE = 0b0000_0000_0000_0010_0000;
const MOUSE_MOTION = 0b0000_0000_0000_0100_0000;
const LINE_WRAP = 0b0000_0000_0000_1000_0000;
const LINE_FEED_NEW_LINE = 0b0000_0000_0001_0000_0000;
const ORIGIN = 0b0000_0000_0010_0000_0000;
const INSERT = 0b0000_0000_0100_0000_0000;
const FOCUS_IN_OUT = 0b0000_0000_1000_0000_0000;
const ALT_SCREEN = 0b0000_0001_0000_0000_0000;
const MOUSE_DRAG = 0b0000_0010_0000_0000_0000;
const MOUSE_MODE = 0b0000_0010_0000_0100_1000;
const UTF8_MOUSE = 0b0000_0100_0000_0000_0000;
const ALTERNATE_SCROLL = 0b0000_1000_0000_0000_0000;
const VI = 0b0001_0000_0000_0000_0000;
const URGENCY_HINTS = 0b0010_0000_0000_0000_0000;
const ANY = u32::MAX;
}
}
impl Default for TermMode {
fn default() -> TermMode {
TermMode::SHOW_CURSOR
| TermMode::LINE_WRAP
| TermMode::ALTERNATE_SCROLL
| TermMode::URGENCY_HINTS
}
}
/// Terminal size info.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq)]
pub struct SizeInfo<T = f32> {
/// Terminal window width.
width: T,
/// Terminal window height.
height: T,
/// Width of individual cell.
cell_width: T,
/// Height of individual cell.
cell_height: T,
/// Horizontal window padding.
padding_x: T,
/// Vertical window padding.
padding_y: T,
/// Number of lines in the viewport.
screen_lines: usize,
/// Number of columns in the viewport.
columns: usize,
}
impl From<SizeInfo<f32>> for SizeInfo<u32> {
fn from(size_info: SizeInfo<f32>) -> Self {
Self {
width: size_info.width as u32,
height: size_info.height as u32,
cell_width: size_info.cell_width as u32,
cell_height: size_info.cell_height as u32,
padding_x: size_info.padding_x as u32,
padding_y: size_info.padding_y as u32,
screen_lines: size_info.screen_lines,
columns: size_info.screen_lines,
}
}
}
impl<T: Clone + Copy> SizeInfo<T> {
#[inline]
pub fn width(&self) -> T {
self.width
}
#[inline]
pub fn height(&self) -> T {
self.height
}
#[inline]
pub fn cell_width(&self) -> T {
self.cell_width
}
#[inline]
pub fn cell_height(&self) -> T {
self.cell_height
}
#[inline]
pub fn padding_x(&self) -> T {
self.padding_x
}
#[inline]
pub fn padding_y(&self) -> T {
self.padding_y
}
}
impl SizeInfo<f32> {
#[allow(clippy::too_many_arguments)]
pub fn new(
width: f32,
height: f32,
cell_width: f32,
cell_height: f32,
mut padding_x: f32,
mut padding_y: f32,
dynamic_padding: bool,
) -> SizeInfo {
if dynamic_padding {
padding_x = Self::dynamic_padding(padding_x.floor(), width, cell_width);
padding_y = Self::dynamic_padding(padding_y.floor(), height, cell_height);
}
let lines = (height - 2. * padding_y) / cell_height;
let screen_lines = cmp::max(lines as usize, MIN_SCREEN_LINES);
let columns = (width - 2. * padding_x) / cell_width;
let columns = cmp::max(columns as usize, MIN_COLUMNS);
SizeInfo {
width,
height,
cell_width,
cell_height,
padding_x: padding_x.floor(),
padding_y: padding_y.floor(),
screen_lines,
columns,
}
}
#[inline]
pub fn reserve_lines(&mut self, count: usize) {
self.screen_lines = cmp::max(self.screen_lines.saturating_sub(count), MIN_SCREEN_LINES);
}
/// Check if coordinates are inside the terminal grid.
///
/// The padding, message bar or search are not counted as part of the grid.
#[inline]
pub fn contains_point(&self, x: usize, y: usize) -> bool {
x <= (self.padding_x + self.columns as f32 * self.cell_width) as usize
&& x > self.padding_x as usize
&& y <= (self.padding_y + self.screen_lines as f32 * self.cell_height) as usize
&& y > self.padding_y as usize
}
/// Calculate padding to spread it evenly around the terminal content.
#[inline]
fn dynamic_padding(padding: f32, dimension: f32, cell_dimension: f32) -> f32 {
padding + ((dimension - 2. * padding) % cell_dimension) / 2.
}
}
impl Dimensions for SizeInfo {
#[inline]
fn columns(&self) -> usize {
self.columns
}
#[inline]
fn screen_lines(&self) -> usize {
self.screen_lines
}
#[inline]
fn total_lines(&self) -> usize {
self.screen_lines()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LineDamageBounds {
/// Damaged line number.
pub line: usize,
/// Leftmost damaged column.
pub left: usize,
/// Rightmost damaged column.
pub right: usize,
}
impl LineDamageBounds {
#[inline]
pub fn undamaged(line: usize, num_cols: usize) -> Self {
Self { line, left: num_cols, right: 0 }
}
#[inline]
pub fn reset(&mut self, num_cols: usize) {
*self = Self::undamaged(self.line, num_cols);
}
#[inline]
pub fn expand(&mut self, left: usize, right: usize) {
self.left = cmp::min(self.left, left);
self.right = cmp::max(self.right, right);
}
#[inline]
pub fn is_damaged(&self) -> bool {
self.left <= self.right
}
}
/// Terminal damage information collected since the last [`Term::reset_damage`] call.
#[derive(Debug)]
pub enum TermDamage<'a> {
/// The entire terminal is damaged.
Full,
/// Iterator over damaged lines in the terminal.
Partial(TermDamageIterator<'a>),
}
/// Iterator over the terminal's damaged lines.
#[derive(Clone, Debug)]
pub struct TermDamageIterator<'a> {
line_damage: slice::Iter<'a, LineDamageBounds>,
}
impl<'a> TermDamageIterator<'a> {
fn new(line_damage: &'a [LineDamageBounds]) -> Self {
Self { line_damage: line_damage.iter() }
}
}
impl<'a> Iterator for TermDamageIterator<'a> {
type Item = LineDamageBounds;
fn next(&mut self) -> Option<Self::Item> {
self.line_damage.find(|line| line.is_damaged()).copied()
}
}
/// State of the terminal damage.
struct TermDamageState {
/// Hint whether terminal should be damaged entirely regardless of the actual damage changes.
is_fully_damaged: bool,
/// Information about damage on terminal lines.
lines: Vec<LineDamageBounds>,
/// Old terminal cursor point.
last_cursor: Point,
/// Old selection range.
last_selection: Option<SelectionRange>,
}
impl TermDamageState {
fn new(num_cols: usize, num_lines: usize) -> Self {
let lines =
(0..num_lines).map(|line| LineDamageBounds::undamaged(line, num_cols)).collect();
Self {
is_fully_damaged: true,
lines,
last_cursor: Default::default(),
last_selection: Default::default(),
}
}
#[inline]
fn resize(&mut self, num_cols: usize, num_lines: usize) {
// Reset point, so old cursor won't end up outside of the viewport.
self.last_cursor = Default::default();
self.last_selection = None;
self.is_fully_damaged = true;
self.lines.clear();
self.lines.reserve(num_lines);
for line in 0..num_lines {
self.lines.push(LineDamageBounds::undamaged(line, num_cols));
}
}
/// Damage point inside of the viewport.
#[inline]
fn damage_point(&mut self, point: Point<usize>) {
self.damage_line(point.line, point.column.0 as usize, point.column.0 as usize);
}
/// Expand `line`'s damage to span at least `left` to `right` column.
#[inline]
fn damage_line(&mut self, line: usize, left: usize, right: usize) {
self.lines[line].expand(left, right);
}
fn damage_selection(
&mut self,
selection: SelectionRange,
display_offset: usize,
num_cols: usize,
) {
let display_offset = display_offset as i32;
let last_visible_line = self.lines.len() as i32 - 1;
// Don't damage invisible selection.
if selection.end.line.0 + display_offset < 0
|| selection.start.line.0.abs() < display_offset - last_visible_line
{
return;
};
let start = cmp::max(selection.start.line.0 + display_offset, 0);
let end = cmp::min(cmp::max(selection.end.line.0 + display_offset, 0), last_visible_line);
for line in start as usize..=end as usize {
self.damage_line(line, 0, num_cols - 1);
}
}
/// Reset information about terminal damage.
fn reset(&mut self, num_cols: usize) {
self.is_fully_damaged = false;
self.lines.iter_mut().for_each(|line| line.reset(num_cols));
}
}
pub struct Term<T> {
/// Terminal focus controlling the cursor shape.
pub is_focused: bool,
/// Cursor for keyboard selection.
pub vi_mode_cursor: ViModeCursor,
pub selection: Option<Selection>,
/// Currently active grid.
///
/// Tracks the screen buffer currently in use. While the alternate screen buffer is active,
/// this will be the alternate grid. Otherwise it is the primary screen buffer.
grid: Grid<Cell>,
/// Currently inactive grid.
///
/// Opposite of the active grid. While the alternate screen buffer is active, this will be the
/// primary grid. Otherwise it is the alternate screen buffer.
inactive_grid: Grid<Cell>,
/// Index into `charsets`, pointing to what ASCII is currently being mapped to.
active_charset: CharsetIndex,
/// Tabstops.
tabs: TabStops,
/// Mode flags.
mode: TermMode,
/// Scroll region.
///
/// Range going from top to bottom of the terminal, indexed from the top of the viewport.
scroll_region: Range<Line>,
semantic_escape_chars: String,
/// Modified terminal colors.
colors: Colors,
/// Current style of the cursor.
cursor_style: Option<CursorStyle>,
/// Default style for resetting the cursor.
default_cursor_style: CursorStyle,
/// Style of the vi mode cursor.
vi_mode_cursor_style: Option<CursorStyle>,
/// Proxy for sending events to the event loop.
event_proxy: T,
/// Current title of the window.
title: Option<String>,
/// Stack of saved window titles. When a title is popped from this stack, the `title` for the
/// term is set.
title_stack: Vec<Option<String>>,
/// Information about cell dimensions.
cell_width: usize,
cell_height: usize,
/// Information about damaged cells.
damage: TermDamageState,
}
impl<T> Term<T> {
#[inline]
pub fn scroll_display(&mut self, scroll: Scroll)
where
T: EventListener,
{
let old_display_offset = self.grid.display_offset();
self.grid.scroll_display(scroll);
self.event_proxy.send_event(Event::MouseCursorDirty);
// Clamp vi mode cursor to the viewport.
let viewport_start = -(self.grid.display_offset() as i32);
let viewport_end = viewport_start + self.bottommost_line().0;
let vi_cursor_line = &mut self.vi_mode_cursor.point.line.0;
*vi_cursor_line = cmp::min(viewport_end, cmp::max(viewport_start, *vi_cursor_line));
self.vi_mode_recompute_selection();
// Damage everything if display offset changed.
if old_display_offset != self.grid().display_offset() {
self.mark_fully_damaged();
}
}
pub fn new(config: &Config, size: SizeInfo, event_proxy: T) -> Term<T> {
let num_cols = size.columns;
let num_lines = size.screen_lines;
let history_size = config.scrolling.history() as usize;
let grid = Grid::new(num_lines, num_cols, history_size);
let alt = Grid::new(num_lines, num_cols, 0);
let tabs = TabStops::new(grid.columns());
let scroll_region = Line(0)..Line(grid.screen_lines() as i32);
// Initialize terminal damage, covering the entire terminal upon launch.
let damage = TermDamageState::new(num_cols, num_lines);
Term {
grid,
inactive_grid: alt,
active_charset: Default::default(),
vi_mode_cursor: Default::default(),
tabs,
mode: Default::default(),
scroll_region,
colors: color::Colors::default(),
semantic_escape_chars: config.selection.semantic_escape_chars.to_owned(),
cursor_style: None,
default_cursor_style: config.cursor.style(),
vi_mode_cursor_style: config.cursor.vi_mode_style(),
event_proxy,
is_focused: true,
title: None,
title_stack: Vec::new(),
selection: None,
cell_width: size.cell_width as usize,
cell_height: size.cell_height as usize,
damage,
}
}
/// Go to next prompt farthest down in history.
pub fn goto_next_prompt(&mut self)
where
T: EventListener,
{
let point = if self.mode.contains(TermMode::VI) {
self.vi_mode_cursor.point
} else {
let display_offset = self.grid.display_offset() as i32;
// If we're outside of Vi mode use bottom most visible line.
Point::new(Line(self.screen_lines() as i32 - 1 - display_offset), Column(0))
};
let prompt_point = match self.next_prompt(point) {
Some(point) => point,
None => return,
};
if self.mode().contains(TermMode::VI) {
self.vi_goto_point(prompt_point);
} else {
let scroll = Scroll::Delta(point.line.0 - prompt_point.line.0);
self.scroll_display(scroll);
}
}
/// Go to previous prompt farthest up in history.
pub fn goto_previous_prompt(&mut self)
where
T: EventListener,
{
let point = if self.mode.contains(TermMode::VI) {
self.vi_mode_cursor.point
} else {
// If we're outside of Vi mode use topmost visible line.
Point::new(Line(-(self.grid.display_offset() as i32)), Column(0))
};
let prompt_point = match self.previous_prompt(point) {
Some(point) => point,
None => return,
};
if self.mode.contains(TermMode::VI) {
self.vi_goto_point(prompt_point);
} else {
let scroll = Scroll::Delta(point.line.0 - prompt_point.line.0);
self.scroll_display(scroll);
}
}
#[must_use]
pub fn damage(&mut self, selection: Option<SelectionRange>) -> TermDamage<'_> {
// Ensure the entire terminal is damaged after entering insert mode.
// Leaving is handled in the ansi handler.
if self.mode.contains(TermMode::INSERT) {
self.mark_fully_damaged();
}
// Early return if the entire terminal is damaged.
if self.damage.is_fully_damaged {
self.damage.last_cursor = self.grid.cursor.point;
self.damage.last_selection = selection;
return TermDamage::Full;
}
// Add information about old cursor position and new one if they are not the same, so we
// cover everything that was produced by `Term::input`.
if self.damage.last_cursor != self.grid.cursor.point {
// Cursor cooridanates are always inside viewport even if you have `display_offset`.
let point =
Point::new(self.damage.last_cursor.line.0 as usize, self.damage.last_cursor.column);
self.damage.damage_point(point);
}
// Always damage current cursor.
self.damage_cursor();
self.damage.last_cursor = self.grid.cursor.point;
// Damage Vi cursor if it's present.
if self.mode.contains(TermMode::VI) {
self.damage_vi_cursor();
}
if self.damage.last_selection != selection {
let display_offset = self.grid().display_offset();
for selection in self.damage.last_selection.into_iter().chain(selection) {
self.damage.damage_selection(selection, display_offset, self.columns());
}
}
self.damage.last_selection = selection;
TermDamage::Partial(TermDamageIterator::new(&self.damage.lines))
}
/// Resets the terminal damage information.
pub fn reset_damage(&mut self) {
self.damage.reset(self.columns());
}
#[inline]
pub fn mark_fully_damaged(&mut self) {
self.damage.is_fully_damaged = true;
}
/// Damage line in a terminal viewport.
#[inline]
pub fn damage_line(&mut self, line: usize, left: usize, right: usize) {
self.damage.damage_line(line, left, right);
}
pub fn update_config(&mut self, config: &Config)
where
T: EventListener,
{
self.semantic_escape_chars = config.selection.semantic_escape_chars.to_owned();
self.default_cursor_style = config.cursor.style();
self.vi_mode_cursor_style = config.cursor.vi_mode_style();
let title_event = match &self.title {
Some(title) => Event::Title(title.clone()),
None => Event::ResetTitle,
};
self.event_proxy.send_event(title_event);
if self.mode.contains(TermMode::ALT_SCREEN) {
self.inactive_grid.update_history(config.scrolling.history() as usize);
} else {
self.grid.update_history(config.scrolling.history() as usize);
}
// Damage everything on config updates.
self.mark_fully_damaged();
}
/// Convert the active selection to a String.
pub fn selection_to_string(&self) -> Option<String> {
let selection_range = self.selection.as_ref().and_then(|s| s.to_range(self))?;
let SelectionRange { start, end, .. } = selection_range;
let mut res = String::new();
match self.selection.as_ref() {
Some(Selection { ty: SelectionType::Block, .. }) => {
for line in (start.line.0..end.line.0).map(Line::from) {
res += self
.line_to_string(line, start.column..end.column, start.column.0 != 0)
.trim_end();
res += "\n";
}
res += self.line_to_string(end.line, start.column..end.column, true).trim_end();
},
Some(Selection { ty: SelectionType::Lines, .. }) => {
res = self.bounds_to_string(start, end) + "\n";
},
_ => {
res = self.bounds_to_string(start, end);
},
}
Some(res)
}
/// Convert range between two points to a String.
pub fn bounds_to_string(&self, start: Point, end: Point) -> String {
let mut res = String::new();
for line in (start.line.0..=end.line.0).map(Line::from) {
let start_col = if line == start.line { start.column } else { Column(0) };
let end_col = if line == end.line { end.column } else { self.last_column() };
res += &self.line_to_string(line, start_col..end_col, line == end.line);
}
res.strip_suffix('\n').map(str::to_owned).unwrap_or(res)
}
/// Convert a single line in the grid to a String.
fn line_to_string(
&self,
line: Line,
mut cols: Range<Column>,
include_wrapped_wide: bool,
) -> String {
let mut text = String::new();
let grid_line = &self.grid[line];
let line_length = cmp::min(grid_line.line_length(), cols.end + 1);
// Include wide char when trailing spacer is selected.
if grid_line[cols.start].flags.contains(Flags::WIDE_CHAR_SPACER) {
cols.start -= 1;
}
let mut tab_mode = false;
for column in (cols.start.0..line_length.0).map(Column::from) {
let cell = &grid_line[column];
// Skip over cells until next tab-stop once a tab was found.
if tab_mode {
if self.tabs[column] || cell.c != ' ' {
tab_mode = false;
} else {
continue;
}
}
if cell.c == '\t' {
tab_mode = true;
}
if !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
// Push cells primary character.
text.push(cell.c);
// Push zero-width characters.
for c in cell.zerowidth().into_iter().flatten() {
text.push(*c);
}
}
}
if cols.end >= self.columns() - 1
&& (line_length.0 == 0
|| !self.grid[line][line_length - 1].flags.contains(Flags::WRAPLINE))
{
text.push('\n');
}
// If wide char is not part of the selection, but leading spacer is, include it.
if line_length == self.columns()
&& line_length.0 >= 2
&& grid_line[line_length - 1].flags.contains(Flags::LEADING_WIDE_CHAR_SPACER)
&& include_wrapped_wide
{
text.push(self.grid[line - 1i32][Column(0)].c);
}
text
}
/// Terminal content required for rendering.
#[inline]
pub fn renderable_content(&self) -> RenderableContent<'_>
where
T: EventListener,
{
RenderableContent::new(self)
}
/// Access to the raw grid data structure.
///
/// This is a bit of a hack; when the window is closed, the event processor
/// serializes the grid state to a file.
pub fn grid(&self) -> &Grid<Cell> {
&self.grid
}
/// Mutable access for swapping out the grid during tests.
#[cfg(test)]
pub fn grid_mut(&mut self) -> &mut Grid<Cell> {
&mut self.grid
}
/// Resize terminal to new dimensions.
pub fn resize(&mut self, size: SizeInfo) {
self.cell_width = size.cell_width as usize;
self.cell_height = size.cell_height as usize;
let old_cols = self.columns();
let old_lines = self.screen_lines();
let num_cols = size.columns;
let num_lines = size.screen_lines;
if old_cols == num_cols && old_lines == num_lines {
debug!("Term::resize dimensions unchanged");
return;
}
debug!("New num_cols is {} and num_lines is {}", num_cols, num_lines);
// Move vi mode cursor with the content.
let history_size = self.history_size();
let mut delta = num_lines as i32 - old_lines as i32;
let min_delta = cmp::min(0, num_lines as i32 - self.grid.cursor.point.line.0 - 1);
delta = cmp::min(cmp::max(delta, min_delta), history_size as i32);
self.vi_mode_cursor.point.line += delta;
// Invalidate selection and tabs only when necessary.
if old_cols != num_cols {
self.selection = None;
// Recreate tabs list.
self.tabs.resize(num_cols);
} else if let Some(selection) = self.selection.take() {
let range = Line(0)..Line(num_lines as i32);
self.selection = selection.rotate(self, &range, -delta);
}
let is_alt = self.mode.contains(TermMode::ALT_SCREEN);
self.grid.resize(!is_alt, num_lines, num_cols);
self.inactive_grid.resize(is_alt, num_lines, num_cols);
// Clamp vi cursor to viewport.
let vi_point = self.vi_mode_cursor.point;
let viewport_top = Line(-(self.grid.display_offset() as i32));
let viewport_bottom = viewport_top + self.bottommost_line();
self.vi_mode_cursor.point.line =
cmp::max(cmp::min(vi_point.line, viewport_bottom), viewport_top);
self.vi_mode_cursor.point.column = cmp::min(vi_point.column, self.last_column());
// Reset scrolling region.
self.scroll_region = Line(0)..Line(self.screen_lines() as i32);
// Resize damage information.
self.damage.resize(num_cols, num_lines);
}
/// Active terminal modes.
#[inline]
pub fn mode(&self) -> &TermMode {
&self.mode
}
/// Swap primary and alternate screen buffer.
pub fn swap_alt(&mut self) {
if !self.mode.contains(TermMode::ALT_SCREEN) {
// Set alt screen cursor to the current primary screen cursor.
self.inactive_grid.cursor = self.grid.cursor.clone();
// Drop information about the primary screens saved cursor.
self.grid.saved_cursor = self.grid.cursor.clone();
// Reset alternate screen contents.
self.inactive_grid.reset_region(..);
}
mem::swap(&mut self.grid, &mut self.inactive_grid);
self.mode ^= TermMode::ALT_SCREEN;
self.selection = None;
self.mark_fully_damaged();
}
/// Scroll screen down.
///
/// Text moves down; clear at bottom
/// Expects origin to be in scroll range.
#[inline]
fn scroll_down_relative(&mut self, origin: Line, mut lines: usize) {
trace!("Scrolling down relative: origin={}, lines={}", origin, lines);
lines = cmp::min(lines, (self.scroll_region.end - self.scroll_region.start).0 as usize);
lines = cmp::min(lines, (self.scroll_region.end - origin).0 as usize);
let region = origin..self.scroll_region.end;
// Scroll selection.
self.selection =
self.selection.take().and_then(|s| s.rotate(self, ®ion, -(lines as i32)));
// Scroll vi mode cursor.
let line = &mut self.vi_mode_cursor.point.line;
if region.start <= *line && region.end > *line {
*line = cmp::min(*line + lines, region.end - 1);
}
// Scroll between origin and bottom
self.grid.scroll_down(®ion, lines);
self.mark_fully_damaged();
}
/// Scroll screen up
///
/// Text moves up; clear at top
/// Expects origin to be in scroll range.
#[inline]
fn scroll_up_relative(&mut self, origin: Line, mut lines: usize) {
trace!("Scrolling up relative: origin={}, lines={}", origin, lines);
lines = cmp::min(lines, (self.scroll_region.end - self.scroll_region.start).0 as usize);
let region = origin..self.scroll_region.end;
// Scroll selection.
self.selection = self.selection.take().and_then(|s| s.rotate(self, ®ion, lines as i32));
self.grid.scroll_up(®ion, lines);
// Scroll vi mode cursor.
let viewport_top = Line(-(self.grid.display_offset() as i32));
let top = if region.start == 0 { viewport_top } else { region.start };
let line = &mut self.vi_mode_cursor.point.line;
if (top <= *line) && region.end > *line {
*line = cmp::max(*line - lines, top);
}
self.mark_fully_damaged();
}
fn deccolm(&mut self)
where
T: EventListener,
{
// Setting 132 column font makes no sense, but run the other side effects.
// Clear scrolling region.
self.set_scrolling_region(1, None);
// Clear grid.
self.grid.reset_region(..);
self.mark_fully_damaged();
}
#[inline]
pub fn exit(&mut self)
where
T: EventListener,
{
self.event_proxy.send_event(Event::Exit);
}
/// Toggle the vi mode.
#[inline]
pub fn toggle_vi_mode(&mut self)
where
T: EventListener,
{
self.mode ^= TermMode::VI;
if self.mode.contains(TermMode::VI) {
let display_offset = self.grid.display_offset() as i32;
if self.grid.cursor.point.line > self.bottommost_line() - display_offset {
// Move cursor to top-left if terminal cursor is not visible.
let point = Point::new(Line(-display_offset), Column(0));
self.vi_mode_cursor = ViModeCursor::new(point);
} else {
// Reset vi mode cursor position to match primary cursor.
self.vi_mode_cursor = ViModeCursor::new(self.grid.cursor.point);
}
}
// Update UI about cursor blinking state changes.
self.event_proxy.send_event(Event::CursorBlinkingChange);
}
/// Move vi mode cursor.
#[inline]
pub fn vi_motion(&mut self, motion: ViMotion)
where
T: EventListener,
{
// Require vi mode to be active.
if !self.mode.contains(TermMode::VI) {
return;
}
// Move cursor.
self.damage_vi_cursor();
self.vi_mode_cursor = self.vi_mode_cursor.motion(self, motion);
self.damage_vi_cursor();
self.vi_mode_recompute_selection();
}
/// Move vi cursor to a point in the grid.
#[inline]
pub fn vi_goto_point(&mut self, point: Point)
where
T: EventListener,
{
self.damage_vi_cursor();
// Move viewport to make point visible.
self.scroll_to_point(point);
// Move vi cursor to the point.
self.vi_mode_cursor.point = point;
self.vi_mode_recompute_selection();
self.damage_vi_cursor();
}
/// Update the active selection to match the vi mode cursor position.
#[inline]
fn vi_mode_recompute_selection(&mut self) {
// Require vi mode to be active.
if !self.mode.contains(TermMode::VI) {
return;
}
// Update only if non-empty selection is present.
if let Some(selection) = self.selection.as_mut().filter(|s| !s.is_empty()) {
selection.update(self.vi_mode_cursor.point, Side::Left);
selection.include_all();
}
}
/// Scroll display to point if it is outside of viewport.