-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
mod.rs
2187 lines (1871 loc) · 70.8 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
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//! Exports the `Term` type which is a high-level API for the Grid
use std::ops::{Range, Index, IndexMut};
use std::ptr;
use std::cmp::{min, max};
use std::io;
use std::time::{Duration, Instant};
use arraydeque::ArrayDeque;
use unicode_width::UnicodeWidthChar;
use font::{self, Size};
use ansi::{self, Color, NamedColor, Attr, Handler, CharsetIndex, StandardCharset, CursorStyle};
use grid::{BidirectionalIterator, Grid, ClearRegion, ToRange, Indexed};
use index::{self, Point, Column, Line, Linear, IndexRange, Contains, RangeInclusive};
use selection::{self, Span, Selection};
use config::{Config, VisualBellAnimation};
use {MouseCursor, Rgb};
use copypasta::{Clipboard, Load, Store};
use input::FONT_SIZE_STEP;
pub mod cell;
pub mod color;
pub use self::cell::Cell;
use self::cell::LineLength;
impl selection::SemanticSearch for Term {
fn semantic_search_left(&self, mut point: Point) -> Point {
let mut iter = self.grid.iter_from(point);
let last_col = self.grid.num_cols() - Column(1);
while let Some(cell) = iter.prev() {
if self.semantic_escape_chars.contains(cell.c) {
break;
}
if iter.cur.col == last_col && !cell.flags.contains(cell::Flags::WRAPLINE) {
break; // cut off if on new line or hit escape char
}
point = iter.cur;
}
point
}
fn semantic_search_right(&self, mut point: Point) -> Point {
let mut iter = self.grid.iter_from(point);
let last_col = self.grid.num_cols() - Column(1);
while let Some(cell) = iter.next() {
if self.semantic_escape_chars.contains(cell.c) {
break;
}
point = iter.cur;
if iter.cur.col == last_col && !cell.flags.contains(cell::Flags::WRAPLINE) {
break; // cut off if on new line or hit escape char
}
}
point
}
}
impl selection::Dimensions for Term {
fn dimensions(&self) -> Point {
Point {
col: self.grid.num_cols(),
line: self.grid.num_lines()
}
}
}
/// Iterator that yields cells needing render
///
/// Yields cells that require work to be displayed (that is, not a an empty
/// background cell). Additionally, this manages some state of the grid only
/// relevant for rendering like temporarily changing the cell with the cursor.
///
/// This manages the cursor during a render. The cursor location is inverted to
/// draw it, and reverted after drawing to maintain state.
pub struct RenderableCellsIter<'a> {
grid: &'a Grid<Cell>,
cursor: &'a Point,
cursor_index: index::Linear,
mode: TermMode,
line: Line,
column: Column,
config: &'a Config,
colors: &'a color::List,
selection: Option<RangeInclusive<index::Linear>>,
cursor_cells: ArrayDeque<[Indexed<Cell>; 3]>,
}
impl<'a> RenderableCellsIter<'a> {
/// Create the renderable cells iterator
///
/// The cursor and terminal mode are required for properly displaying the
/// cursor.
fn new<'b>(
grid: &'b Grid<Cell>,
cursor: &'b Point,
colors: &'b color::List,
mode: TermMode,
config: &'b Config,
selection: Option<RangeInclusive<index::Linear>>,
cursor_style: CursorStyle,
) -> RenderableCellsIter<'b> {
let cursor_index = Linear(cursor.line.0 * grid.num_cols().0 + cursor.col.0);
RenderableCellsIter {
grid,
cursor,
cursor_index,
mode,
line: Line(0),
column: Column(0),
selection,
config,
colors,
cursor_cells: ArrayDeque::new(),
}.initialize(cursor_style)
}
fn push_cursor_cells(
&mut self,
original_cell: Cell,
cursor_cell: Cell,
wide_cell: Cell,
) {
// Prints the char under the cell if cursor is situated on a non-empty cell
self.cursor_cells.push_back(Indexed {
line: self.cursor.line,
column: self.cursor.col,
inner: original_cell,
}).expect("won't exceed capacity");
// Prints the cursor
self.cursor_cells.push_back(Indexed {
line: self.cursor.line,
column: self.cursor.col,
inner: cursor_cell,
}).expect("won't exceed capacity");
// If cursor is over a wide (2 cell size) character,
// print the second cursor cell
if self.is_wide_cursor(&cursor_cell) {
self.cursor_cells.push_back(Indexed {
line: self.cursor.line,
column: self.cursor.col + 1,
inner: wide_cell,
}).expect("won't exceed capacity");
}
}
fn populate_block_cursor(&mut self) {
let (text_color, cursor_color) = if self.config.custom_cursor_colors() {
(
Color::Named(NamedColor::CursorText),
Color::Named(NamedColor::Cursor)
)
} else {
// Swap fg, bg
let cell = &self.grid[self.cursor];
(cell.bg, cell.fg)
};
let original_cell = self.grid[self.cursor];
let mut cursor_cell = self.grid[self.cursor];
cursor_cell.fg = text_color;
cursor_cell.bg = cursor_color;
let mut wide_cell = cursor_cell;
wide_cell.c = ' ';
self.push_cursor_cells(original_cell, cursor_cell, wide_cell);
}
fn populate_char_cursor(&mut self, cursor_cell_char: char, wide_cell_char: char) {
let original_cell = self.grid[self.cursor];
let mut cursor_cell = self.grid[self.cursor];
let cursor_color = self.text_cursor_color(&cursor_cell);
cursor_cell.c = cursor_cell_char;
cursor_cell.fg = cursor_color;
let mut wide_cell = cursor_cell;
wide_cell.c = wide_cell_char;
self.push_cursor_cells(original_cell, cursor_cell, wide_cell);
}
fn populate_underline_cursor(&mut self) {
self.populate_char_cursor(font::UNDERLINE_CURSOR_CHAR, font::UNDERLINE_CURSOR_CHAR);
}
fn populate_beam_cursor(&mut self) {
self.populate_char_cursor(font::BEAM_CURSOR_CHAR, ' ');
}
fn populate_box_cursor(&mut self) {
self.populate_char_cursor(font::BOX_CURSOR_CHAR, ' ');
}
#[inline]
fn is_wide_cursor(&self, cell: &Cell) -> bool {
cell.flags.contains(cell::Flags::WIDE_CHAR) && (self.cursor.col + 1) < self.grid.num_cols()
}
fn text_cursor_color(&self, cell: &Cell) -> Color {
if self.config.custom_cursor_colors() {
Color::Named(NamedColor::Cursor)
} else {
// Cursor is same color as text
cell.fg
}
}
/// Populates list of cursor cells with the original cell
fn populate_no_cursor(&mut self) {
self.cursor_cells.push_back(Indexed {
line: self.cursor.line,
column: self.cursor.col,
inner: self.grid[self.cursor],
}).expect("won't exceed capacity");
}
fn initialize(mut self, cursor_style: CursorStyle) -> Self {
if self.cursor_is_visible() {
match cursor_style {
CursorStyle::HollowBlock => {
self.populate_box_cursor();
},
CursorStyle::Block => {
self.populate_block_cursor();
},
CursorStyle::Beam => {
self.populate_beam_cursor();
},
CursorStyle::Underline => {
self.populate_underline_cursor();
}
}
} else {
self.populate_no_cursor();
}
self
}
/// Check if the cursor should be rendered.
#[inline]
fn cursor_is_visible(&self) -> bool {
self.mode.contains(mode::TermMode::SHOW_CURSOR) && self.grid.contains(self.cursor)
}
fn compute_fg_rgb(&self, fg: Color, cell: &Cell) -> Rgb {
use self::cell::Flags;
match fg {
Color::Spec(rgb) => rgb,
Color::Named(ansi) => {
match (self.config.draw_bold_text_with_bright_colors(), cell.flags & Flags::DIM_BOLD) {
// Draw bold text in bright colors *and* contains bold flag.
(true, self::cell::Flags::DIM_BOLD) |
(true, self::cell::Flags::BOLD) => self.colors[ansi.to_bright()],
// Cell is marked as dim and not bold
(_, self::cell::Flags::DIM) => self.colors[ansi.to_dim()],
// None of the above, keep original color.
_ => self.colors[ansi]
}
},
Color::Indexed(idx) => {
let idx = match (
self.config.draw_bold_text_with_bright_colors(),
cell.flags & Flags::DIM_BOLD,
idx
) {
(true, self::cell::Flags::BOLD, 0...7) => idx as usize + 8,
(false, self::cell::Flags::DIM, 8...15) => idx as usize - 8,
(false, self::cell::Flags::DIM, 0...7) => idx as usize + 260,
_ => idx as usize,
};
self.colors[idx]
}
}
}
#[inline]
fn compute_bg_alpha(&self, bg: Color) -> f32 {
match bg {
Color::Named(NamedColor::Background) => 0.0,
_ => 1.0
}
}
fn compute_bg_rgb(&self, bg: Color) -> Rgb {
match bg {
Color::Spec(rgb) => rgb,
Color::Named(ansi) => self.colors[ansi],
Color::Indexed(idx) => self.colors[idx],
}
}
}
pub struct RenderableCell {
pub line: Line,
pub column: Column,
pub c: char,
pub fg: Rgb,
pub bg: Rgb,
pub bg_alpha: f32,
pub flags: cell::Flags,
}
impl<'a> Iterator for RenderableCellsIter<'a> {
type Item = RenderableCell;
/// Gets the next renderable cell
///
/// Skips empty (background) cells and applies any flags to the cell state
/// (eg. invert fg and bg colors).
#[inline]
fn next(&mut self) -> Option<Self::Item> {
while self.line < self.grid.num_lines() {
while self.column < self.grid.num_cols() {
// Grab current state for this iteration
let line = self.line;
let mut column = self.column;
let cell = &self.grid[line][column];
let index = Linear(line.0 * self.grid.num_cols().0 + column.0);
let (cell, selected) = if index == self.cursor_index {
// Cursor cell
let cell = self.cursor_cells.pop_front().unwrap();
column = cell.column;
// Since there may be multiple cursor cells (for a wide
// char), only update iteration position after all cursor
// cells have been drawn.
if self.cursor_cells.is_empty() {
self.line = cell.line;
self.column = cell.column + 1;
}
(cell.inner, false)
} else {
// Normal cell
self.column += 1;
let selected = self.selection.as_ref()
.map(|range| range.contains_(index))
.unwrap_or(false);
// Skip empty cells
if cell.is_empty() && !selected {
continue;
}
(*cell, selected)
};
// Apply inversion and lookup RGB values
let mut bg_alpha = 1.0;
let fg_rgb;
let bg_rgb;
let invert = selected ^ cell.inverse();
if invert {
if cell.fg == cell.bg {
bg_rgb = self.colors[NamedColor::Foreground];
fg_rgb = self.colors[NamedColor::Background];
bg_alpha = 1.0
} else {
bg_rgb = self.compute_fg_rgb(cell.fg, &cell);
fg_rgb = self.compute_bg_rgb(cell.bg);
}
} else {
fg_rgb = self.compute_fg_rgb(cell.fg, &cell);
bg_rgb = self.compute_bg_rgb(cell.bg);
bg_alpha = self.compute_bg_alpha(cell.bg);
}
return Some(RenderableCell {
line,
column,
flags: cell.flags,
c: cell.c,
fg: fg_rgb,
bg: bg_rgb,
bg_alpha,
})
}
self.column = Column(0);
self.line += 1;
}
None
}
}
pub mod mode {
bitflags! {
pub struct TermMode: u16 {
const SHOW_CURSOR = 0b00_0000_0000_0001;
const APP_CURSOR = 0b00_0000_0000_0010;
const APP_KEYPAD = 0b00_0000_0000_0100;
const MOUSE_REPORT_CLICK = 0b00_0000_0000_1000;
const BRACKETED_PASTE = 0b00_0000_0001_0000;
const SGR_MOUSE = 0b00_0000_0010_0000;
const MOUSE_MOTION = 0b00_0000_0100_0000;
const LINE_WRAP = 0b00_0000_1000_0000;
const LINE_FEED_NEW_LINE = 0b00_0001_0000_0000;
const ORIGIN = 0b00_0010_0000_0000;
const INSERT = 0b00_0100_0000_0000;
const FOCUS_IN_OUT = 0b00_1000_0000_0000;
const ALT_SCREEN = 0b01_0000_0000_0000;
const MOUSE_DRAG = 0b10_0000_0000_0000;
const ANY = 0b11_1111_1111_1111;
const NONE = 0;
}
}
impl Default for TermMode {
fn default() -> TermMode {
TermMode::SHOW_CURSOR | TermMode::LINE_WRAP
}
}
}
pub use self::mode::TermMode;
trait CharsetMapping {
fn map(&self, c: char) -> char {
c
}
}
impl CharsetMapping for StandardCharset {
/// Switch/Map character to the active charset. Ascii is the common case and
/// for that we want to do as little as possible.
#[inline]
fn map(&self, c: char) -> char {
match *self {
StandardCharset::Ascii => c,
StandardCharset::SpecialCharacterAndLineDrawing =>
match c {
'`' => '◆',
'a' => '▒',
'b' => '\t',
'c' => '\u{000c}',
'd' => '\r',
'e' => '\n',
'f' => '°',
'g' => '±',
'h' => '\u{2424}',
'i' => '\u{000b}',
'j' => '┘',
'k' => '┐',
'l' => '┌',
'm' => '└',
'n' => '┼',
'o' => '⎺',
'p' => '⎻',
'q' => '─',
'r' => '⎼',
's' => '⎽',
't' => '├',
'u' => '┤',
'v' => '┴',
'w' => '┬',
'x' => '│',
'y' => '≤',
'z' => '≥',
'{' => 'π',
'|' => '≠',
'}' => '£',
'~' => '·',
_ => c
},
}
}
}
#[derive(Default, Copy, Clone)]
struct Charsets([StandardCharset; 4]);
impl Index<CharsetIndex> for Charsets {
type Output = StandardCharset;
fn index(&self, index: CharsetIndex) -> &StandardCharset {
&self.0[index as usize]
}
}
impl IndexMut<CharsetIndex> for Charsets {
fn index_mut(&mut self, index: CharsetIndex) -> &mut StandardCharset {
&mut self.0[index as usize]
}
}
#[derive(Default, Copy, Clone)]
pub struct Cursor {
/// The location of this cursor
pub point: Point,
/// Template cell when using this cursor
template: Cell,
/// Currently configured graphic character sets
charsets: Charsets,
}
pub struct VisualBell {
/// Visual bell animation
animation: VisualBellAnimation,
/// Visual bell duration
duration: Duration,
/// The last time the visual bell rang, if at all
start_time: Option<Instant>,
}
fn cubic_bezier(p0: f64, p1: f64, p2: f64, p3: f64, x: f64) -> f64 {
(1.0 - x).powi(3) * p0 +
3.0 * (1.0 - x).powi(2) * x * p1 +
3.0 * (1.0 - x) * x.powi(2) * p2 +
x.powi(3) * p3
}
impl VisualBell {
pub fn new(config: &Config) -> VisualBell {
let visual_bell_config = config.visual_bell();
VisualBell {
animation: visual_bell_config.animation(),
duration: visual_bell_config.duration(),
start_time: None,
}
}
/// Ring the visual bell, and return its intensity.
pub fn ring(&mut self) -> f64 {
let now = Instant::now();
self.start_time = Some(now);
self.intensity_at_instant(now)
}
/// Get the currently intensity of the visual bell. The bell's intensity
/// ramps down from 1.0 to 0.0 at a rate determined by the bell's duration.
pub fn intensity(&self) -> f64 {
self.intensity_at_instant(Instant::now())
}
/// Check whether or not the visual bell has completed "ringing".
pub fn completed(&mut self) -> bool {
match self.start_time {
Some(earlier) => {
if Instant::now().duration_since(earlier) >= self.duration {
self.start_time = None;
}
false
},
None => true
}
}
/// Get the intensity of the visual bell at a particular instant. The bell's
/// intensity ramps down from 1.0 to 0.0 at a rate determined by the bell's
/// duration.
pub fn intensity_at_instant(&self, instant: Instant) -> f64 {
// If `duration` is zero, then the VisualBell is disabled; therefore,
// its `intensity` is zero.
if self.duration == Duration::from_secs(0) {
return 0.0;
}
match self.start_time {
// Similarly, if `start_time` is `None`, then the VisualBell has not
// been "rung"; therefore, its `intensity` is zero.
None => 0.0,
Some(earlier) => {
// Finally, if the `instant` at which we wish to compute the
// VisualBell's `intensity` occurred before the VisualBell was
// "rung", then its `intensity` is also zero.
if instant < earlier {
return 0.0;
}
let elapsed = instant.duration_since(earlier);
let elapsed_f = elapsed.as_secs() as f64 +
f64::from(elapsed.subsec_nanos()) / 1e9f64;
let duration_f = self.duration.as_secs() as f64 +
f64::from(self.duration.subsec_nanos()) / 1e9f64;
// Otherwise, we compute a value `time` from 0.0 to 1.0
// inclusive that represents the ratio of `elapsed` time to the
// `duration` of the VisualBell.
let time = (elapsed_f / duration_f).min(1.0);
// We use this to compute the inverse `intensity` of the
// VisualBell. When `time` is 0.0, `inverse_intensity` is 0.0,
// and when `time` is 1.0, `inverse_intensity` is 1.0.
let inverse_intensity = match self.animation {
VisualBellAnimation::Ease | VisualBellAnimation::EaseOut => {
cubic_bezier(0.25, 0.1, 0.25, 1.0, time)
},
VisualBellAnimation::EaseOutSine => cubic_bezier(0.39, 0.575, 0.565, 1.0, time),
VisualBellAnimation::EaseOutQuad => cubic_bezier(0.25, 0.46, 0.45, 0.94, time),
VisualBellAnimation::EaseOutCubic => cubic_bezier(0.215, 0.61, 0.355, 1.0, time),
VisualBellAnimation::EaseOutQuart => cubic_bezier(0.165, 0.84, 0.44, 1.0, time),
VisualBellAnimation::EaseOutQuint => cubic_bezier(0.23, 1.0, 0.32, 1.0, time),
VisualBellAnimation::EaseOutExpo => cubic_bezier(0.19, 1.0, 0.22, 1.0, time),
VisualBellAnimation::EaseOutCirc => cubic_bezier(0.075, 0.82, 0.165, 1.0, time),
VisualBellAnimation::Linear => time,
};
// Since we want the `intensity` of the VisualBell to decay over
// `time`, we subtract the `inverse_intensity` from 1.0.
1.0 - inverse_intensity
}
}
}
pub fn update_config(&mut self, config: &Config) {
let visual_bell_config = config.visual_bell();
self.animation = visual_bell_config.animation();
self.duration = visual_bell_config.duration();
}
}
pub struct Term {
/// The grid
grid: Grid<Cell>,
/// Tracks if the next call to input will need to first handle wrapping.
/// This is true after the last column is set with the input function. Any function that
/// implicitly sets the line or column needs to set this to false to avoid wrapping twice.
/// input_needs_wrap ensures that cursor.col is always valid for use into indexing into
/// arrays. Without it we would have to sanitize cursor.col every time we used it.
input_needs_wrap: bool,
/// Got a request to set title; it's buffered here until next draw.
///
/// Would be nice to avoid the allocation...
next_title: Option<String>,
/// Got a request to set the mouse cursor; it's buffered here until the next draw
next_mouse_cursor: Option<MouseCursor>,
/// Alternate grid
alt_grid: Grid<Cell>,
/// Alt is active
alt: bool,
/// The cursor
cursor: Cursor,
/// The graphic character set, out of `charsets`, which ASCII is currently
/// being mapped to
active_charset: CharsetIndex,
/// Tabstops
tabs: Vec<bool>,
/// Mode flags
mode: TermMode,
/// Scroll region
scroll_region: Range<Line>,
/// Font size
pub font_size: Size,
original_font_size: Size,
/// Size
size_info: SizeInfo,
pub dirty: bool,
pub visual_bell: VisualBell,
pub next_is_urgent: Option<bool>,
/// Saved cursor from main grid
cursor_save: Cursor,
/// Saved cursor from alt grid
cursor_save_alt: Cursor,
semantic_escape_chars: String,
/// Colors used for rendering
colors: color::List,
/// Is color in `colors` modified or not
color_modified: [bool; color::COUNT],
/// Original colors from config
original_colors: color::List,
/// Current style of the cursor
cursor_style: Option<CursorStyle>,
/// Default style for resetting the cursor
default_cursor_style: CursorStyle,
dynamic_title: bool,
/// Number of spaces in one tab
tabspaces: usize,
}
/// Terminal size info
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct SizeInfo {
/// Terminal window width
pub width: f32,
/// Terminal window height
pub height: f32,
/// Width of individual cell
pub cell_width: f32,
/// Height of individual cell
pub cell_height: f32,
/// Horizontal window padding
pub padding_x: f32,
/// Horizontal window padding
pub padding_y: f32,
}
impl SizeInfo {
#[inline]
pub fn lines(&self) -> Line {
Line(((self.height - 2. * self.padding_y) / self.cell_height) as usize)
}
#[inline]
pub fn cols(&self) -> Column {
Column(((self.width - 2. * self.padding_x) / self.cell_width) as usize)
}
fn contains_point(&self, x: usize, y:usize) -> bool {
x <= (self.width - self.padding_x) as usize &&
x >= self.padding_x as usize &&
y <= (self.height - self.padding_y) as usize &&
y >= self.padding_y as usize
}
pub fn pixels_to_coords(&self, x: usize, y: usize) -> Option<Point> {
if !self.contains_point(x, y) {
return None;
}
let col = Column((x - self.padding_x as usize) / (self.cell_width as usize));
let line = Line((y - self.padding_y as usize) / (self.cell_height as usize));
Some(Point {
line: min(line, self.lines() - 1),
col: min(col, self.cols() - 1)
})
}
}
impl Term {
#[inline]
pub fn get_next_title(&mut self) -> Option<String> {
self.next_title.take()
}
#[inline]
pub fn get_next_mouse_cursor(&mut self) -> Option<MouseCursor> {
self.next_mouse_cursor.take()
}
pub fn new(config: &Config, size: SizeInfo) -> Term {
let template = Cell::default();
let num_cols = size.cols();
let num_lines = size.lines();
let grid = Grid::new(num_lines, num_cols, &template);
let tabspaces = config.tabspaces();
let tabs = IndexRange::from(Column(0)..grid.num_cols())
.map(|i| (*i as usize) % tabspaces == 0)
.collect::<Vec<bool>>();
let alt = grid.clone();
let scroll_region = Line(0)..grid.num_lines();
Term {
next_title: None,
next_mouse_cursor: None,
dirty: false,
visual_bell: VisualBell::new(config),
next_is_urgent: None,
input_needs_wrap: false,
grid,
alt_grid: alt,
alt: false,
font_size: config.font().size(),
original_font_size: config.font().size(),
active_charset: Default::default(),
cursor: Default::default(),
cursor_save: Default::default(),
cursor_save_alt: Default::default(),
tabs,
mode: Default::default(),
scroll_region,
size_info: size,
colors: color::List::from(config.colors()),
color_modified: [false; color::COUNT],
original_colors: color::List::from(config.colors()),
semantic_escape_chars: config.selection().semantic_escape_chars.clone(),
cursor_style: None,
default_cursor_style: config.cursor_style(),
dynamic_title: config.dynamic_title(),
tabspaces,
}
}
pub fn change_font_size(&mut self, delta: f32) {
// Saturating addition with minimum font size FONT_SIZE_STEP
let new_size = self.font_size + Size::new(delta);
self.font_size = max(new_size, Size::new(FONT_SIZE_STEP));
self.dirty = true;
}
pub fn reset_font_size(&mut self) {
self.font_size = self.original_font_size;
self.dirty = true;
}
pub fn update_config(&mut self, config: &Config) {
self.semantic_escape_chars = config.selection().semantic_escape_chars.clone();
self.original_colors.fill_named(config.colors());
for i in 0..color::COUNT {
if !self.color_modified[i] {
self.colors[i] = self.original_colors[i];
}
}
self.visual_bell.update_config(config);
self.default_cursor_style = config.cursor_style();
self.dynamic_title = config.dynamic_title();
}
#[inline]
pub fn needs_draw(&self) -> bool {
self.dirty
}
pub fn string_from_selection(&self, span: &Span) -> String {
/// Need a generic push() for the Append trait
trait PushChar {
fn push_char(&mut self, c: char);
fn maybe_newline(&mut self, grid: &Grid<Cell>, line: Line, ending: Column) {
if ending != Column(0) && !grid[line][ending - 1].flags.contains(cell::Flags::WRAPLINE) {
self.push_char('\n');
}
}
}
impl PushChar for String {
#[inline]
fn push_char(&mut self, c: char) {
self.push(c);
}
}
use std::ops::Range;
trait Append : PushChar {
fn append(&mut self, grid: &Grid<Cell>, line: Line, cols: Range<Column>) -> Option<Range<Column>>;
}
impl Append for String {
fn append(
&mut self,
grid: &Grid<Cell>,
line: Line,
cols: Range<Column>
) -> Option<Range<Column>> {
let grid_line = &grid[line];
let line_length = grid_line.line_length();
let line_end = min(line_length, cols.end + 1);
if cols.start >= line_end {
None
} else {
for cell in &grid_line[cols.start..line_end] {
if !cell.flags.contains(cell::Flags::WIDE_CHAR_SPACER) {
self.push(cell.c);
}
}
let range = Some(cols.start..line_end);
if cols.end >= grid.num_cols() - 1 {
if let Some(ref range) = range {
self.maybe_newline(grid, line, range.end);
}
}
range
}
}
}
let mut res = String::new();
let (start, end) = span.to_locations();
let line_count = end.line - start.line;
let max_col = Column(usize::max_value() - 1);
match line_count {
// Selection within single line
Line(0) => {
res.append(&self.grid, start.line, start.col..end.col);
},
// Selection ends on line following start
Line(1) => {
// Starting line
res.append(&self.grid, start.line, start.col..max_col);
// Ending line
res.append(&self.grid, end.line, Column(0)..end.col);
},
// Multi line selection
_ => {
// Starting line
res.append(&self.grid, start.line, start.col..max_col);
let middle_range = IndexRange::from((start.line + 1)..(end.line));
for line in middle_range {
res.append(&self.grid, line, Column(0)..max_col);
}
// Ending line
res.append(&self.grid, end.line, Column(0)..end.col);
}
}
res
}
/// Convert the given pixel values to a grid coordinate
///
/// The mouse coordinates are expected to be relative to the top left. The
/// line and column returned are also relative to the top left.
///
/// Returns None if the coordinates are outside the screen
pub fn pixels_to_coords(&self, x: usize, y: usize) -> Option<Point> {
self.size_info().pixels_to_coords(x, y)
}
/// 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
}
/// Iterate over the *renderable* cells in the terminal
///
/// A renderable cell is any cell which has content other than the default
/// background color. Cells with an alternate background color are
/// considered renderable as are cells with any text content.
pub fn renderable_cells<'b>(
&'b self,
config: &'b Config,
selection: Option<&'b Selection>,
window_focused: bool,
) -> RenderableCellsIter {
let selection = selection.and_then(|s| s.to_span(self))
.map(|span| span.to_range());