-
-
Notifications
You must be signed in to change notification settings - Fork 835
/
Copy pathmod.rs
2759 lines (2486 loc) · 103 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
// The range_plus_one lint can't see when the LHS is not compatible with
// and inclusive range
#![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))]
use super::*;
use crate::color::{ColorPalette, RgbColor};
use crate::config::{BidiMode, NewlineCanon};
use log::debug;
use num_traits::ToPrimitive;
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::sync::mpsc::{channel, Sender};
use std::sync::Arc;
use terminfo::{Database, Value};
use termwiz::cell::UnicodeVersion;
use termwiz::escape::csi::{
Cursor, CursorStyle, DecPrivateMode, DecPrivateModeCode, Device, Edit, EraseInDisplay,
EraseInLine, Mode, Sgr, TabulationClear, TerminalMode, TerminalModeCode, Window, XtSmGraphics,
XtSmGraphicsAction, XtSmGraphicsItem, XtSmGraphicsStatus, XtermKeyModifierResource,
};
use termwiz::escape::{OneBased, OperatingSystemCommand, CSI};
use termwiz::image::ImageData;
use termwiz::input::KeyboardEncoding;
use termwiz::surface::{CursorShape, CursorVisibility, SequenceNo};
use url::Url;
use wezterm_bidi::ParagraphDirectionHint;
mod image;
mod iterm;
mod keyboard;
mod kitty;
mod mouse;
pub(crate) mod performer;
mod sixel;
use crate::terminalstate::image::*;
use crate::terminalstate::kitty::*;
lazy_static::lazy_static! {
static ref DB: Database = {
let data = include_bytes!("../../../termwiz/data/wezterm");
Database::from_buffer(&data[..]).unwrap()
};
}
pub(crate) struct TabStop {
tabs: Vec<bool>,
tab_width: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CharSet {
Ascii,
Uk,
DecLineDrawing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MouseEncoding {
X10,
Utf8,
SGR,
SgrPixels,
}
impl TabStop {
fn new(screen_width: usize, tab_width: usize) -> Self {
let mut tabs = Vec::with_capacity(screen_width);
for i in 0..screen_width {
tabs.push((i % tab_width) == 0);
}
Self { tabs, tab_width }
}
fn set_tab_stop(&mut self, col: usize) {
self.tabs[col] = true;
}
fn find_prev_tab_stop(&self, col: usize) -> Option<usize> {
for i in (0..col.min(self.tabs.len())).rev() {
if self.tabs[i] {
return Some(i);
}
}
None
}
fn find_next_tab_stop(&self, col: usize) -> Option<usize> {
for i in col + 1..self.tabs.len() {
if self.tabs[i] {
return Some(i);
}
}
None
}
/// Respond to the terminal resizing.
/// If the screen got bigger, we need to expand the tab stops
/// into the new columns with the appropriate width.
fn resize(&mut self, screen_width: usize) {
let current = self.tabs.len();
if screen_width > current {
for i in current..screen_width {
self.tabs.push((i % self.tab_width) == 0);
}
}
}
fn clear(&mut self, to_clear: TabulationClear, col: usize, log_unknown_escape_sequences: bool) {
match to_clear {
TabulationClear::ClearCharacterTabStopAtActivePosition => {
if let Some(t) = self.tabs.get_mut(col) {
*t = false;
}
}
// If we want to exactly match VT100/xterm behavior, then
// we cannot honor ClearCharacterTabStopsAtActiveLine.
TabulationClear::ClearAllCharacterTabStops => {
// | TabulationClear::ClearCharacterTabStopsAtActiveLine
for t in &mut self.tabs {
*t = false;
}
}
_ => {
if log_unknown_escape_sequences {
log::warn!("unhandled TabulationClear {:?}", to_clear);
}
}
}
}
}
#[derive(Debug, Clone)]
struct SavedCursor {
position: CursorPosition,
wrap_next: bool,
pen: CellAttributes,
dec_origin_mode: bool,
g0_charset: CharSet,
g1_charset: CharSet,
// TODO: selective_erase when supported
}
struct ScreenOrAlt {
/// The primary screen + scrollback
screen: Screen,
/// The alternate screen; no scrollback
alt_screen: Screen,
/// Tells us which screen is active
alt_screen_is_active: bool,
saved_cursor: Option<SavedCursor>,
alt_saved_cursor: Option<SavedCursor>,
}
impl Deref for ScreenOrAlt {
type Target = Screen;
fn deref(&self) -> &Screen {
if self.alt_screen_is_active {
&self.alt_screen
} else {
&self.screen
}
}
}
impl DerefMut for ScreenOrAlt {
fn deref_mut(&mut self) -> &mut Screen {
if self.alt_screen_is_active {
&mut self.alt_screen
} else {
&mut self.screen
}
}
}
impl ScreenOrAlt {
pub fn new(
size: TerminalSize,
config: &Arc<dyn TerminalConfiguration>,
seqno: SequenceNo,
bidi_mode: BidiMode,
) -> Self {
let screen = Screen::new(size, config, true, seqno, bidi_mode);
let alt_screen = Screen::new(size, config, false, seqno, bidi_mode);
Self {
screen,
alt_screen,
alt_screen_is_active: false,
saved_cursor: None,
alt_saved_cursor: None,
}
}
pub fn resize(
&mut self,
size: TerminalSize,
cursor_main: CursorPosition,
cursor_alt: CursorPosition,
seqno: SequenceNo,
is_conpty: bool,
) -> (CursorPosition, CursorPosition) {
let cursor_main = self.screen.resize(size, cursor_main, seqno, is_conpty);
let cursor_alt = self.alt_screen.resize(size, cursor_alt, seqno, is_conpty);
(cursor_main, cursor_alt)
}
pub fn activate_alt_screen(&mut self, seqno: SequenceNo) {
self.alt_screen_is_active = true;
self.dirty_top_phys_rows(seqno);
}
pub fn activate_primary_screen(&mut self, seqno: SequenceNo) {
self.alt_screen_is_active = false;
self.dirty_top_phys_rows(seqno);
}
// When switching between alt and primary screen, we implicitly change
// the content associated with StableRowIndex 0..num_rows. The muxer
// use case needs to know to invalidate its cache, so we mark those rows
// as dirty.
fn dirty_top_phys_rows(&mut self, seqno: SequenceNo) {
let num_rows = self.screen.physical_rows;
for line_idx in 0..num_rows {
self.screen
.line_mut(line_idx)
.update_last_change_seqno(seqno);
}
}
pub fn is_alt_screen_active(&self) -> bool {
self.alt_screen_is_active
}
pub fn saved_cursor(&mut self) -> &mut Option<SavedCursor> {
if self.alt_screen_is_active {
&mut self.alt_saved_cursor
} else {
&mut self.saved_cursor
}
}
pub fn full_reset(&mut self) {
self.screen.full_reset();
self.alt_screen.full_reset();
}
}
/// Manages the state for the terminal
pub struct TerminalState {
config: Arc<dyn TerminalConfiguration>,
screen: ScreenOrAlt,
/// The current set of attributes in effect for the next
/// attempt to print to the display
pen: CellAttributes,
/// The current cursor position, relative to the top left
/// of the screen. 0-based index.
cursor: CursorPosition,
/// if true, implicitly move to the next line on the next
/// printed character
wrap_next: bool,
clear_semantic_attribute_on_newline: bool,
/// If true, writing a character inserts a new cell
insert: bool,
/// https://vt100.net/docs/vt510-rm/DECAWM.html
dec_auto_wrap: bool,
/// Reverse Wraparound Mode
reverse_wraparound_mode: bool,
/// Reverse video mode
reverse_video_mode: bool,
/// https://vt100.net/docs/vt510-rm/DECOM.html
/// When OriginMode is enabled, cursor is constrained to the
/// scroll region and its position is relative to the scroll
/// region.
dec_origin_mode: bool,
/// The scroll region
top_and_bottom_margins: Range<VisibleRowIndex>,
left_and_right_margins: Range<usize>,
left_and_right_margin_mode: bool,
/// When set, modifies the sequence of bytes sent for keys
/// designated as cursor keys. This includes various navigation
/// keys. The code in key_down() is responsible for interpreting this.
application_cursor_keys: bool,
modify_other_keys: Option<i64>,
dec_ansi_mode: bool,
/// https://vt100.net/dec/ek-vt38t-ug-001.pdf#page=132 has a
/// discussion on what sixel dispay mode (DECSDM) does.
sixel_display_mode: bool,
use_private_color_registers_for_each_graphic: bool,
/// Graphics mode color register map.
color_map: HashMap<u16, RgbColor>,
/// When set, modifies the sequence of bytes sent for keys
/// in the numeric keypad portion of the keyboard.
application_keypad: bool,
/// When set, pasting the clipboard should bracket the data with
/// designated marker characters.
bracketed_paste: bool,
/// Movement events enabled
any_event_mouse: bool,
focus_tracking: bool,
/// X10 (legacy), SGR, and SGR-Pixels style mouse tracking and
/// reporting is enabled
mouse_encoding: MouseEncoding,
mouse_tracking: bool,
/// Button events enabled
button_event_mouse: bool,
current_mouse_buttons: Vec<MouseButton>,
last_mouse_move: Option<MouseEvent>,
cursor_visible: bool,
keyboard_encoding: KeyboardEncoding,
/// Support for US, UK, and DEC Special Graphics
g0_charset: CharSet,
g1_charset: CharSet,
shift_out: bool,
newline_mode: bool,
tabs: TabStop,
/// The terminal title string (OSC 2)
title: String,
/// The icon title string (OSC 1)
icon_title: Option<String>,
palette: Option<ColorPalette>,
pixel_width: usize,
pixel_height: usize,
dpi: u32,
clipboard: Option<Arc<dyn Clipboard>>,
device_control_handler: Option<Box<dyn DeviceControlHandler>>,
alert_handler: Option<Box<dyn AlertHandler>>,
download_handler: Option<Arc<dyn DownloadHandler>>,
current_dir: Option<Url>,
term_program: String,
term_version: String,
writer: BufWriter<ThreadedWriter>,
image_cache: lru::LruCache<[u8; 32], Arc<ImageData>>,
sixel_scrolls_right: bool,
user_vars: HashMap<String, String>,
kitty_img: KittyImageState,
seqno: SequenceNo,
/// The unicode version that is in effect
unicode_version: UnicodeVersion,
unicode_version_stack: Vec<UnicodeVersionStackEntry>,
enable_conpty_quirks: bool,
/// On Windows, the ConPTY layer emits an OSC sequence to
/// set the title shortly after it starts up.
/// We don't want that, so we use this flag to remember
/// whether we want to skip it or not.
suppress_initial_title_change: bool,
accumulating_title: Option<String>,
/// seqno when we last lost focus
lost_focus_seqno: SequenceNo,
/// seqno when we last emitted Alert::OutputSinceFocusLost
lost_focus_alerted_seqno: SequenceNo,
focused: bool,
/// True if lines should be marked as bidi-enabled, and thus
/// have the renderer apply the bidi algorithm.
/// true is equivalent to "implicit" bidi mode as described in
/// <https://terminal-wg.pages.freedesktop.org/bidi/recommendation/basic-modes.html>
/// If none, then the default value specified by the config is used.
bidi_enabled: Option<bool>,
/// When set, specifies the bidi direction information that should be
/// applied to lines.
/// If none, then the default value specified by the config is used.
bidi_hint: Option<ParagraphDirectionHint>,
}
#[derive(Debug)]
struct UnicodeVersionStackEntry {
vers: UnicodeVersion,
label: Option<String>,
}
fn default_color_map() -> HashMap<u16, RgbColor> {
let mut color_map = HashMap::new();
// Match colors to the VT340 color table:
// https://github.com/hackerb9/vt340test/blob/main/colormap/showcolortable.png
for (idx, r, g, b) in [
(0, 0, 0, 0),
(1, 0x33, 0x33, 0xcc),
(2, 0xcc, 0x23, 0x23),
(3, 0x33, 0xcc, 0x33),
(4, 0xcc, 0x33, 0xcc),
(5, 0x33, 0xcc, 0xcc),
(6, 0xcc, 0xcc, 0xcc),
(7, 0x77, 0x77, 0x77),
(8, 0x44, 0x44, 0x44),
(9, 0x56, 0x56, 0x99),
(10, 0x99, 0x44, 0x44),
(11, 0x56, 0x99, 0x56),
(12, 0x99, 0x56, 0x99),
(13, 0x56, 0x99, 0x99),
(14, 0x99, 0x99, 0x56),
(15, 0xcc, 0xcc, 0xcc),
] {
color_map.insert(idx, RgbColor::new_8bpc(r, g, b));
}
color_map
}
/// This struct implements a writer that sends the data across
/// to another thread so that the write side of the terminal
/// processing never blocks.
///
/// This is important for example when processing large pastes into
/// vim. In that scenario, we can fill up the data pending
/// on vim's input buffer, while it is busy trying to send
/// output to the terminal. A deadlock is reached because
/// send_paste blocks on the writer, but it is unable to make
/// progress until we're able to read the output from vim.
///
/// We either need input or output to be non-blocking.
/// Output seems safest because we want to be able to exert
/// back-pressure when there is a lot of data to read,
/// and we're in control of the write side, which represents
/// input from the interactive user, or pastes.
struct ThreadedWriter {
sender: Sender<WriterMessage>,
}
enum WriterMessage {
Data(Vec<u8>),
Flush,
}
impl ThreadedWriter {
fn new(mut writer: Box<dyn std::io::Write + Send>) -> Self {
let (sender, receiver) = channel::<WriterMessage>();
std::thread::spawn(move || {
while let Ok(msg) = receiver.recv() {
match msg {
WriterMessage::Data(buf) => {
if writer.write(&buf).is_err() {
break;
}
}
WriterMessage::Flush => {
if writer.flush().is_err() {
break;
}
}
}
}
});
Self { sender }
}
}
impl std::io::Write for ThreadedWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.sender
.send(WriterMessage::Data(buf.to_vec()))
.map_err(|err| std::io::Error::new(std::io::ErrorKind::BrokenPipe, err))?;
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.sender
.send(WriterMessage::Flush)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::BrokenPipe, err))?;
Ok(())
}
}
impl TerminalState {
/// Constructs the terminal state.
/// You generally want the `Terminal` struct rather than this one;
/// Terminal contains and dereferences to `TerminalState`.
pub fn new(
size: TerminalSize,
config: Arc<dyn TerminalConfiguration>,
term_program: &str,
term_version: &str,
writer: Box<dyn std::io::Write + Send>,
) -> TerminalState {
let writer = BufWriter::new(ThreadedWriter::new(writer));
let seqno = 1;
let screen = ScreenOrAlt::new(size, &config, seqno, config.bidi_mode());
let color_map = default_color_map();
let unicode_version = config.unicode_version();
TerminalState {
config,
screen,
pen: CellAttributes::default(),
cursor: CursorPosition::default(),
top_and_bottom_margins: 0..size.rows as VisibleRowIndex,
left_and_right_margins: 0..size.cols,
left_and_right_margin_mode: false,
wrap_next: false,
clear_semantic_attribute_on_newline: false,
// We default auto wrap to true even though the default for
// a dec terminal is false, because it is more useful this way.
dec_auto_wrap: true,
reverse_wraparound_mode: false,
reverse_video_mode: false,
dec_origin_mode: false,
insert: false,
application_cursor_keys: false,
modify_other_keys: None,
dec_ansi_mode: false,
sixel_display_mode: false,
use_private_color_registers_for_each_graphic: false,
color_map,
application_keypad: false,
bracketed_paste: false,
focus_tracking: false,
mouse_encoding: MouseEncoding::X10,
keyboard_encoding: KeyboardEncoding::Xterm,
sixel_scrolls_right: false,
any_event_mouse: false,
button_event_mouse: false,
mouse_tracking: false,
last_mouse_move: None,
cursor_visible: true,
g0_charset: CharSet::Ascii,
g1_charset: CharSet::Ascii,
shift_out: false,
newline_mode: false,
current_mouse_buttons: vec![],
tabs: TabStop::new(size.cols, 8),
title: "wezterm".to_string(),
icon_title: None,
palette: None,
pixel_height: size.pixel_height,
pixel_width: size.pixel_width,
dpi: size.dpi,
clipboard: None,
device_control_handler: None,
alert_handler: None,
download_handler: None,
current_dir: None,
term_program: term_program.to_string(),
term_version: term_version.to_string(),
writer,
image_cache: lru::LruCache::new(16),
user_vars: HashMap::new(),
kitty_img: Default::default(),
seqno,
unicode_version,
unicode_version_stack: vec![],
suppress_initial_title_change: false,
enable_conpty_quirks: false,
accumulating_title: None,
lost_focus_seqno: seqno,
lost_focus_alerted_seqno: seqno,
focused: true,
bidi_enabled: None,
bidi_hint: None,
}
}
pub fn enable_conpty_quirks(&mut self) {
self.enable_conpty_quirks = true;
self.suppress_initial_title_change = true;
}
pub fn current_seqno(&self) -> SequenceNo {
self.seqno
}
pub fn increment_seqno(&mut self) {
self.seqno += 1;
}
pub fn set_config(&mut self, config: Arc<dyn TerminalConfiguration>) {
self.config = config;
}
pub fn get_config(&self) -> Arc<dyn TerminalConfiguration> {
Arc::clone(&self.config)
}
pub fn set_clipboard(&mut self, clipboard: &Arc<dyn Clipboard>) {
self.clipboard.replace(Arc::clone(clipboard));
}
pub fn set_device_control_handler(&mut self, handler: Box<dyn DeviceControlHandler>) {
self.device_control_handler.replace(handler);
}
pub fn set_notification_handler(&mut self, handler: Box<dyn AlertHandler>) {
self.alert_handler.replace(handler);
}
pub fn set_download_handler(&mut self, handler: &Arc<dyn DownloadHandler>) {
self.download_handler.replace(handler.clone());
}
/// Returns the title text associated with the terminal session.
/// The title can be changed by the application using a number
/// of escape sequences:
/// OSC 2 is used to set the window title.
/// OSC 1 is used to set the "icon title", which some terminal
/// emulators interpret as a shorter title string for use when
/// showing the tab title.
/// Here in wezterm the terminalstate is isolated from other
/// tabs; we process escape sequences without knowledge of other
/// tabs, so we maintain both title strings here.
/// The gui layer doesn't currently have a concept of what the
/// overall window title should be beyond the title for the
/// active tab with some decoration about the number of tabs.
/// Shell toolkits such as oh-my-zsh prefer OSC 1 titles for
/// abbreviated information.
/// What we do here is prefer to return the OSC 1 icon title
/// if it is set, otherwise return the OSC 2 window title.
pub fn get_title(&self) -> &str {
self.icon_title.as_ref().unwrap_or(&self.title)
}
/// Returns the current working directory associated with the
/// terminal session. The working directory can be changed by
/// the applicaiton using the OSC 7 escape sequence.
pub fn get_current_dir(&self) -> Option<&Url> {
self.current_dir.as_ref()
}
/// Returns a copy of the palette.
/// By default we don't keep a copy in the terminal state,
/// preferring to take the config values from the users
/// config file and updating to changes live.
/// However, if they have used dynamic color scheme escape
/// sequences we'll fork a copy of the palette at that time
/// so that we can start tracking those changes.
pub fn palette(&self) -> ColorPalette {
self.palette
.as_ref()
.cloned()
.unwrap_or_else(|| self.config.color_palette())
}
/// Called in response to dynamic color scheme escape sequences.
/// Will make a copy of the palette from the config file if this
/// is the first of these escapes we've seen.
pub fn palette_mut(&mut self) -> &mut ColorPalette {
if self.palette.is_none() {
self.palette.replace(self.config.color_palette());
}
self.palette.as_mut().unwrap()
}
/// If the current overridden palette is effectively the same as
/// the configured palette, remove the override and treat it as
/// being the same as the configured state.
/// This allows runtime changes to the configuration to take effect.
pub fn implicit_palette_reset_if_same_as_configured(&mut self) {
if self
.palette
.as_ref()
.map(|p| *p == self.config.color_palette())
.unwrap_or(false)
{
self.palette.take();
}
}
/// Returns a reference to the active screen (either the primary or
/// the alternate screen).
pub fn screen(&self) -> &Screen {
&self.screen
}
/// Returns a mutable reference to the active screen (either the primary or
/// the alternate screen).
pub fn screen_mut(&mut self) -> &mut Screen {
&mut self.screen
}
fn set_clipboard_contents(
&self,
selection: ClipboardSelection,
text: Option<String>,
) -> anyhow::Result<()> {
if let Some(clip) = self.clipboard.as_ref() {
clip.set_contents(selection, text)?;
}
Ok(())
}
pub fn erase_scrollback_and_viewport(&mut self) {
// Since we may be called outside of perform_actions,
// we need to ensure that we increment the seqno in
// order to correctly invalidate the display
self.increment_seqno();
self.erase_in_display(EraseInDisplay::EraseScrollback);
let row_index = self.screen.phys_row(self.cursor.y);
let rows = self.screen.lines_in_phys_range(row_index..row_index + 1);
self.erase_in_display(EraseInDisplay::EraseDisplay);
for (idx, row) in rows.into_iter().enumerate() {
*self.screen.line_mut(idx) = row;
}
self.cursor.y = 0;
}
/// Discards the scrollback, leaving only the data that is present
/// in the viewport.
pub fn erase_scrollback(&mut self) {
// Since we may be called outside of perform_actions,
// we need to ensure that we increment the seqno in
// order to correctly invalidate the display
self.increment_seqno();
self.screen_mut().erase_scrollback();
}
/// Returns true if the associated application has enabled any of the
/// supported mouse reporting modes.
/// This is useful for the hosting GUI application to decide how best
/// to dispatch mouse events to the terminal.
pub fn is_mouse_grabbed(&self) -> bool {
self.mouse_tracking || self.button_event_mouse || self.any_event_mouse
}
pub fn is_alt_screen_active(&self) -> bool {
self.screen.is_alt_screen_active()
}
/// Returns true if the associated application has enabled
/// bracketed paste mode, which can be helpful to the hosting
/// GUI application to decide about fragmenting a large paste.
pub fn bracketed_paste_enabled(&self) -> bool {
self.bracketed_paste
}
/// Advise the terminal about a change in its focus state
pub fn focus_changed(&mut self, focused: bool) {
if focused == self.focused {
return;
}
if !focused {
// notify app of release of buttons
let buttons = self.current_mouse_buttons.clone();
for b in buttons {
self.mouse_event(MouseEvent {
kind: MouseEventKind::Release,
button: b,
modifiers: KeyModifiers::NONE,
x: 0,
y: 0,
x_pixel_offset: 0,
y_pixel_offset: 0,
})
.ok();
}
}
if self.focus_tracking {
write!(self.writer, "{}{}", CSI, if focused { "I" } else { "O" }).ok();
self.writer.flush().ok();
}
self.focused = focused;
if !focused {
self.lost_focus_seqno = self.seqno;
}
}
/// Returns true if there is new output since the terminal
/// lost focus
pub fn has_unseen_output(&self) -> bool {
!self.focused && self.seqno > self.lost_focus_seqno
}
pub(crate) fn trigger_unseen_output_notif(&mut self) {
if self.has_unseen_output() {
// We want to avoid over-notifying about output events,
// so here we gate the notification to the case where
// we have lost the focus more recently than the last
// time we notified about it
if self.lost_focus_seqno > self.lost_focus_alerted_seqno {
self.lost_focus_alerted_seqno = self.seqno;
if let Some(handler) = self.alert_handler.as_mut() {
handler.alert(Alert::OutputSinceFocusLost);
}
}
}
}
/// Send text to the terminal that is the result of pasting.
/// If bracketed paste mode is enabled, the paste is enclosed
/// in the bracketing, otherwise it is fed to the writer as-is.
/// De-fang the text by removing any embedded bracketed paste
/// sequence that may be present.
pub fn send_paste(&mut self, text: &str) -> Result<(), Error> {
let mut buf = String::new();
if self.bracketed_paste {
buf.push_str("\x1b[200~");
}
let canon = if self.bracketed_paste {
NewlineCanon::None
} else {
self.config.canonicalize_pasted_newlines()
};
let canon = canon.canonicalize(text);
let de_fanged = canon.replace("\x1b[200~", "").replace("\x1b[201~", "");
buf.push_str(&de_fanged);
if self.bracketed_paste {
buf.push_str("\x1b[201~");
}
self.writer.write_all(buf.as_bytes())?;
self.writer.flush()?;
Ok(())
}
/// Informs the terminal that the viewport of the window has resized to the
/// specified dimensions.
/// We need to resize both the primary and alt screens, adjusting
/// the cursor positions of both accordingly.
pub fn resize(&mut self, size: TerminalSize) {
self.increment_seqno();
let (cursor_main, cursor_alt) = if self.screen.alt_screen_is_active {
(
self.screen
.saved_cursor
.as_ref()
.map(|s| s.position)
.unwrap_or_else(CursorPosition::default),
self.cursor,
)
} else {
(
self.cursor,
self.screen
.alt_saved_cursor
.as_ref()
.map(|s| s.position)
.unwrap_or_else(CursorPosition::default),
)
};
let (adjusted_cursor_main, adjusted_cursor_alt) = self.screen.resize(
size,
cursor_main,
cursor_alt,
self.seqno,
self.enable_conpty_quirks,
);
self.top_and_bottom_margins = 0..size.rows as i64;
self.left_and_right_margins = 0..size.cols;
self.pixel_height = size.pixel_height;
self.pixel_width = size.pixel_width;
self.dpi = size.dpi;
self.tabs.resize(size.cols);
if self.screen.alt_screen_is_active {
self.set_cursor_pos(
&Position::Absolute(adjusted_cursor_alt.x as i64),
&Position::Absolute(adjusted_cursor_alt.y),
);
if let Some(saved) = self.screen.saved_cursor.as_mut() {
saved.position.x = adjusted_cursor_main.x;
saved.position.y = adjusted_cursor_main.y;
saved.position.seqno = self.seqno;
saved.wrap_next = false;
}
} else {
self.set_cursor_pos(
&Position::Absolute(adjusted_cursor_main.x as i64),
&Position::Absolute(adjusted_cursor_main.y),
);
if let Some(saved) = self.screen.alt_saved_cursor.as_mut() {
saved.position.x = adjusted_cursor_alt.x;
saved.position.y = adjusted_cursor_alt.y;
saved.position.seqno = self.seqno;
saved.wrap_next = false;
}
}
}
pub fn get_size(&self) -> TerminalSize {
let screen = self.screen();
TerminalSize {
dpi: self.dpi,
pixel_width: self.pixel_width,
pixel_height: self.pixel_height,
rows: screen.physical_rows,
cols: screen.physical_cols,
}
}
fn palette_did_change(&mut self) {
self.make_all_lines_dirty();
if let Some(handler) = self.alert_handler.as_mut() {
handler.alert(Alert::PaletteChanged);
}
}
/// When dealing with selection, mark a range of lines as dirty
pub fn make_all_lines_dirty(&mut self) {
let seqno = self.seqno;
let screen = self.screen_mut();
screen.for_each_phys_line_mut(|_, line| {
line.update_last_change_seqno(seqno);
});
}
/// Returns the 0-based cursor position relative to the top left of
/// the visible screen
pub fn cursor_pos(&self) -> CursorPosition {
CursorPosition {
x: self.cursor.x,
y: self.cursor.y,
shape: self.cursor.shape,
visibility: if self.cursor_visible {
CursorVisibility::Visible
} else {
CursorVisibility::Hidden
},
seqno: self.cursor.seqno,
}
}
/// Returns the current cell attributes of the screen
pub fn pen(&self) -> CellAttributes {
self.pen.clone()
}
pub fn user_vars(&self) -> &HashMap<String, String> {
&self.user_vars
}
fn clear_semantic_attribute_due_to_movement(&mut self) {
if self.clear_semantic_attribute_on_newline {
self.clear_semantic_attribute_on_newline = false;
self.pen.set_semantic_type(SemanticType::default());
}
}
/// Sets the cursor position to precisely the x and values provided
fn set_cursor_position_absolute(&mut self, x: usize, y: VisibleRowIndex) {
if self.cursor.y != y {
self.clear_semantic_attribute_due_to_movement();
}
self.cursor.y = y;
self.cursor.x = x;
self.cursor.seqno = self.seqno;
self.wrap_next = false;
}
/// Sets the cursor position. x and y are 0-based and relative to the
/// top left of the visible screen.
fn set_cursor_pos(&mut self, x: &Position, y: &Position) {
let x = match *x {
Position::Relative(x) => (self.cursor.x as i64 + x)
.min(
if self.dec_origin_mode {
self.left_and_right_margins.end
} else {
self.screen().physical_cols
} as i64
- 1,
)
.max(0),
Position::Absolute(x) => (x + if self.dec_origin_mode {
self.left_and_right_margins.start
} else {
0
} as i64)
.min(