-
-
Notifications
You must be signed in to change notification settings - Fork 807
/
renderable.rs
857 lines (778 loc) · 30.3 KB
/
renderable.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
use crate::domain::ClientInner;
use crate::pane::clientpane::ClientPane;
use anyhow::anyhow;
use codec::*;
use config::{configuration, ConfigHandle};
use lru::LruCache;
use mux::pane::PaneId;
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::Mux;
use promise::BrokenPromise;
use rangeset::*;
use ratelim::RateLimiter;
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use termwiz::cell::{Cell, CellAttributes, Underline};
use termwiz::color::AnsiColor;
use termwiz::image::{ImageCell, ImageData};
use termwiz::surface::{SequenceNo, SEQ_ZERO};
use url::Url;
use wezterm_term::{KeyCode, KeyModifiers, Line, StableRowIndex};
const MAX_POLL_INTERVAL: Duration = Duration::from_secs(30);
const BASE_POLL_INTERVAL: Duration = Duration::from_millis(20);
#[derive(Debug)]
enum LineEntry {
// Up to date wrt. server and has been rendered at least once
Line(Line),
// Currently being downloaded from the server
Fetching(Instant),
// We have a version of the line locally and are treating it
// as needing rendering because we are also in the process of
// downloading a newer version from the server
LineAndFetching(Line, Instant),
// We have a local copy but it is stale and will need to be
// fetched again
Stale(Line),
}
impl LineEntry {
fn kind(&self) -> (&'static str, Option<Instant>) {
match self {
Self::Line(_) => ("Line", None),
Self::Fetching(since) => ("Fetching", Some(*since)),
Self::LineAndFetching(_, since) => ("LineAndFetching", Some(*since)),
Self::Stale(_) => ("Stale", None),
}
}
}
pub struct RenderableInner {
pub client: Arc<ClientInner>,
remote_pane_id: PaneId,
local_pane_id: PaneId,
last_poll: Instant,
pub dead: bool,
poll_in_progress: AtomicBool,
poll_interval: Duration,
cursor_position: StableCursorPosition,
pub dimensions: RenderableDimensions,
lines: LruCache<StableRowIndex, LineEntry>,
pub title: String,
pub working_dir: Option<Url>,
pub seqno: SequenceNo,
fetch_limiter: RateLimiter,
last_send_time: Instant,
pub last_recv_time: Instant,
last_late_dirty: Instant,
last_input_rtt: u64,
pub input_serial: InputSerial,
}
pub struct RenderableState {
pub inner: RefCell<RenderableInner>,
}
impl RenderableInner {
pub fn new(
client: &Arc<ClientInner>,
remote_pane_id: PaneId,
local_pane_id: PaneId,
dimensions: RenderableDimensions,
title: &str,
fetch_limiter: RateLimiter,
) -> Self {
let now = Instant::now();
Self {
client: Arc::clone(client),
remote_pane_id,
local_pane_id,
last_poll: now,
dead: false,
poll_in_progress: AtomicBool::new(false),
poll_interval: BASE_POLL_INTERVAL,
cursor_position: StableCursorPosition::default(),
dimensions,
lines: LruCache::new(configuration().scrollback_lines),
title: title.to_string(),
working_dir: None,
fetch_limiter,
last_send_time: now,
last_recv_time: now,
last_late_dirty: now,
last_input_rtt: 0,
input_serial: InputSerial::empty(),
seqno: SEQ_ZERO,
}
}
/// Returns true if we think we should display the laggy connection
/// indicator. If we're past our poll interval and more recently
/// tried to send something than receive something, the UI is worth
/// showing.
pub fn is_tardy(&self) -> bool {
let elapsed = self.last_recv_time.elapsed();
if elapsed > self.poll_interval.max(Duration::from_secs(3)) {
self.last_send_time > self.last_recv_time
} else {
false
}
}
/// Predictive echo can be noisy when the link is working well,
/// so we only employ it when it looks like the latency is high.
fn should_predict(&self) -> bool {
self.client
.local_echo_threshold_ms
.map(|thresh| self.last_input_rtt >= thresh)
.unwrap_or(false)
}
/// Compute a "prediction" and apply it to the line data that we
/// have available, marking it as dirty so that it gets rendered.
/// The prediction is basically just local echo.
/// Open questions:
/// how do we tell if the intent is to suppress local echo during eg:
/// * password prompt? One option is to look back and see if the line
/// looks like a password prompt.
/// * normal mode in vim: letter presses are typically movement or
/// other editor commands
/// There are bound to be a number of other edge cases that we should
/// handle.
fn apply_prediction(&mut self, c: KeyCode, line: &mut Line) {
let text = line.as_str();
if text.contains("sword") {
// This line might be a password prompt. Don't force
// on local echo here, as we don't want to reveal content
// from their password
return;
}
match c {
KeyCode::Enter => {
self.cursor_position.x = 0;
self.cursor_position.y += 1;
}
KeyCode::UpArrow => {
self.cursor_position.y = self.cursor_position.y.saturating_sub(1);
}
KeyCode::DownArrow => {
self.cursor_position.y += 1;
}
KeyCode::RightArrow => {
self.cursor_position.x += 1;
}
KeyCode::LeftArrow => {
self.cursor_position.x = self.cursor_position.x.saturating_sub(1);
}
KeyCode::Delete => {
line.erase_cell(self.cursor_position.x, SEQ_ZERO);
}
KeyCode::Backspace => {
if self.cursor_position.x > 0 {
line.erase_cell(self.cursor_position.x - 1, SEQ_ZERO);
self.cursor_position.x -= 1;
}
}
KeyCode::Char(c) => {
let cell = Cell::new(
c,
CellAttributes::default()
.set_underline(Underline::Double)
.clone(),
);
let width = cell.width();
line.set_cell(self.cursor_position.x, cell, SEQ_ZERO);
// Adjust the cursor to reflect the width of this new cell
self.cursor_position.x += width;
}
_ => {}
}
}
/// Based on a keypress, apply a "prediction" of what the terminal
/// content will look like once we receive the response from the
/// remote system. The prediction helps to reduce perceived latency
/// when a user is typing at any reasonable velocity.
pub fn predict_from_key_event(&mut self, key: KeyCode, mods: KeyModifiers) {
if !self.should_predict() {
return;
}
let c = match key {
KeyCode::LeftArrow
| KeyCode::RightArrow
| KeyCode::UpArrow
| KeyCode::DownArrow
| KeyCode::Delete
| KeyCode::Backspace
| KeyCode::Enter
| KeyCode::Char(_) => key,
_ => return,
};
if mods != KeyModifiers::NONE && mods != KeyModifiers::SHIFT {
return;
}
let row = self.cursor_position.y;
match self.lines.pop(&row) {
Some(LineEntry::Stale(mut line)) | Some(LineEntry::Line(mut line)) => {
self.apply_prediction(c, &mut line);
self.lines.put(row, LineEntry::Line(line));
}
Some(LineEntry::LineAndFetching(mut line, instant)) => {
self.apply_prediction(c, &mut line);
self.lines
.put(row, LineEntry::LineAndFetching(line, instant));
}
Some(entry) => {
self.lines.put(row, entry);
}
None => {}
}
}
fn apply_paste_prediction(&mut self, row: usize, text: &str, line: &mut Line) {
let attrs = CellAttributes::default()
.set_underline(Underline::Double)
.clone();
let text_line = Line::from_text(text, &attrs, SEQ_ZERO, None);
if row == 0 {
for cell in text_line.visible_cells() {
line.set_cell(self.cursor_position.x, cell.as_cell(), SEQ_ZERO);
self.cursor_position.x += cell.width();
}
} else {
// The pasted line replaces the data for the existing line
line.resize_and_clear(0, SEQ_ZERO, CellAttributes::default());
line.append_line(text_line, SEQ_ZERO);
self.cursor_position.x = line.len();
}
}
pub fn predict_from_paste(&mut self, text: &str) {
if !self.should_predict() {
return;
}
let text = textwrap::fill(text, self.dimensions.cols);
let lines: Vec<&str> = text.split("\n").collect();
for (idx, paste_line) in lines.iter().enumerate() {
let row = self.cursor_position.y + idx as StableRowIndex;
match self.lines.pop(&row) {
Some(LineEntry::Stale(mut line)) | Some(LineEntry::Line(mut line)) => {
self.apply_paste_prediction(idx, paste_line, &mut line);
self.lines.put(row, LineEntry::Line(line));
}
Some(LineEntry::LineAndFetching(mut line, instant)) => {
self.apply_paste_prediction(idx, paste_line, &mut line);
self.lines
.put(row, LineEntry::LineAndFetching(line, instant));
}
Some(entry) => {
self.lines.put(row, entry);
}
None => {}
}
}
self.cursor_position.y += lines.len().saturating_sub(1) as StableRowIndex;
}
pub fn update_last_send(&mut self) {
self.last_send_time = Instant::now();
self.poll_interval = BASE_POLL_INTERVAL;
}
pub fn apply_changes_to_surface(
&mut self,
delta: GetPaneRenderChangesResponse,
bonus_lines: Vec<(StableRowIndex, Line)>,
) {
log::trace!(
"apply_changes_to_surface local={} remote={}",
self.local_pane_id,
self.remote_pane_id
);
let now = Instant::now();
self.poll_interval = BASE_POLL_INTERVAL;
self.last_recv_time = now;
let mut dirty = RangeSet::new();
for r in delta.dirty_lines {
dirty.add_range(r.clone());
}
if delta.cursor_position != self.cursor_position {
dirty.add(self.cursor_position.y);
// But note that the server may have sent this in bonus_lines;
// we'll address that below
dirty.add(delta.cursor_position.y);
}
// Keep track of the approximate round trip time by recording how
// long it took for this response to come back
if let Some(serial) = delta.input_serial {
self.last_input_rtt = serial.elapsed_millis();
}
// When it comes to updating the cursor position, if the update was tagged
// with keyboard input, we'll only take the position if the update comes from
// the most recent key event. This helps to prevent the cursor wiggling if the
// user is typing more than one character per roundtrip interval--the wiggle
// manifests because we may have already predicted a local cursor move forwards
// by one character, and we may receive the response to the prior update after
// we have rendered that, and then shortly receive the most recent response.
// The result of that is that the cursor moves right one, left one and then
// finally right one in quick succession.
// If the delta was not from an input event then we trust it; this is most
// like due to a unilateral movement by the application on the other end.
if delta.input_serial.is_none()
|| delta.input_serial.unwrap_or(InputSerial::empty()) >= self.input_serial
{
self.cursor_position = delta.cursor_position;
}
self.dimensions = delta.dimensions;
self.title = delta.title;
self.working_dir = delta.working_dir.map(Into::into);
log::trace!(
"server says: seqno from {} -> {} for local_pane_id={}",
self.seqno,
delta.seqno,
self.local_pane_id
);
self.seqno = delta.seqno;
let config = configuration();
for (stable_row, line) in bonus_lines {
log::trace!("bonus line {} seqno={}", stable_row, line.current_seqno());
self.put_line(stable_row, line, &config, None);
dirty.remove(stable_row);
}
log::trace!(
"apply_changes_to_surface: Generate PaneOutput event for local={}",
self.local_pane_id
);
Mux::get().notify(mux::MuxNotification::PaneOutput(self.local_pane_id));
let mut to_fetch = RangeSet::new();
log::trace!("dirty as of seq {} -> {:?}", delta.seqno, dirty);
for r in dirty.iter() {
for stable_row in r.clone() {
// If a line is in the (probable) viewport region,
// then we'll likely want to fetch it.
// If it is outside that region, remove it from our cache
// so that we'll fetch it on demand later.
let fetchable = stable_row >= delta.dimensions.physical_top;
let prior = self.lines.pop(&stable_row);
let prior_kind = prior.as_ref().map(|e| e.kind());
if !fetchable {
log::trace!("make {} stale bcos not fetchable", stable_row);
self.make_stale(stable_row);
continue;
}
to_fetch.add(stable_row);
let entry = match prior {
Some(LineEntry::Fetching(_)) | None => LineEntry::Fetching(now),
Some(LineEntry::LineAndFetching(old, ..))
| Some(LineEntry::Stale(old))
| Some(LineEntry::Line(old)) => LineEntry::LineAndFetching(old, now),
};
log::trace!(
"row {} {:?} -> {:?} due to dirty and IN viewport",
stable_row,
prior_kind,
entry.kind()
);
self.lines.put(stable_row, entry);
}
}
if !to_fetch.is_empty() {
if self.fetch_limiter.non_blocking_admittance_check(1) {
self.schedule_fetch_lines(to_fetch, now);
} else {
log::warn!(
"exceeded fetch throttle, drop {:?} and mark stale",
to_fetch
);
for r in to_fetch.iter() {
for stable_row in r.clone() {
self.make_stale(stable_row);
}
}
}
}
}
pub fn make_all_stale(&mut self) {
let mut lines = LruCache::unbounded();
while let Some((stable_row, entry)) = self.lines.pop_lru() {
let entry = match entry {
LineEntry::Stale(old) | LineEntry::Line(old) => LineEntry::Stale(old),
entry => entry,
};
lines.put(stable_row, entry);
}
self.lines = lines;
}
fn make_stale(&mut self, stable_row: StableRowIndex) {
match self.lines.pop(&stable_row) {
Some(LineEntry::Stale(old))
| Some(LineEntry::Line(old))
| Some(LineEntry::LineAndFetching(old, _)) => {
self.lines.put(stable_row, LineEntry::Stale(old));
}
Some(LineEntry::Fetching(_)) | None => {}
}
}
fn put_line(
&mut self,
stable_row: StableRowIndex,
mut line: Line,
config: &ConfigHandle,
fetch_start: Option<Instant>,
) {
line.scan_and_create_hyperlinks(&config.hyperlink_rules);
let entry = if let Some(fetch_start) = fetch_start {
// If we're completing a fetch, only replace entries that were
// set to fetching as part of our fetch. If they are now longer
// tagged that way, then someone came along after us and changed
// the state, so we should leave it alone
match self.lines.pop(&stable_row) {
Some(LineEntry::LineAndFetching(_, then)) | Some(LineEntry::Fetching(then))
if fetch_start == then =>
{
log::trace!(
"row {} fetch done -> Line seq={} vs self.seq={}",
stable_row,
line.current_seqno(),
self.seqno
);
line.update_last_change_seqno(self.seqno);
LineEntry::Line(line)
}
Some(e) => {
// It changed since we started: leave it alone!
log::trace!(
"row {} {:?} changed since fetch started at {:?}, so leave it be",
stable_row,
e.kind(),
fetch_start
);
self.lines.put(stable_row, e);
return;
}
None => return,
}
} else {
LineEntry::Line(line)
};
self.lines.put(stable_row, entry);
}
fn schedule_fetch_lines(&mut self, to_fetch: RangeSet<StableRowIndex>, now: Instant) {
if to_fetch.is_empty() || self.dead {
return;
}
let local_pane_id = self.local_pane_id;
log::trace!(
"will fetch lines {:?} for remote tab id {} at {:?}",
to_fetch,
self.remote_pane_id,
now,
);
let client = Arc::clone(&self.client);
let remote_pane_id = self.remote_pane_id;
promise::spawn::spawn(async move {
let result = client
.client
.get_lines(GetLines {
pane_id: remote_pane_id,
lines: to_fetch.clone().into(),
})
.await;
let result = match result {
Ok(result) => {
let lines =
hydrate_lines(Arc::clone(&client), remote_pane_id, result.lines).await;
Ok(lines)
}
Err(err) => Err(err),
};
Self::apply_lines(local_pane_id, result, to_fetch, now)
})
.detach();
}
fn apply_lines(
local_pane_id: PaneId,
result: anyhow::Result<Vec<(StableRowIndex, Line)>>,
to_fetch: RangeSet<StableRowIndex>,
now: Instant,
) -> anyhow::Result<()> {
let mux = Mux::get();
let pane = mux
.get_pane(local_pane_id)
.ok_or_else(|| anyhow!("no such tab {}", local_pane_id))?;
if let Some(client_tab) = pane.downcast_ref::<ClientPane>() {
let renderable = client_tab.renderable.lock();
let mut inner = renderable.inner.borrow_mut();
match result {
Ok(lines) => {
let config = configuration();
log::trace!("fetch complete for {:?} at {:?}", to_fetch, now);
for (stable_row, line) in lines.into_iter() {
inner.put_line(stable_row, line, &config, Some(now));
}
}
Err(err) => {
log::error!("get_lines failed: {}", err);
for r in to_fetch.iter() {
for stable_row in r.clone() {
let entry = match inner.lines.pop(&stable_row) {
Some(LineEntry::Fetching(then)) if then == now => {
// leave it popped
continue;
}
Some(LineEntry::LineAndFetching(line, then)) if then == now => {
// revert to just a line
LineEntry::Line(line)
}
Some(entry) => entry,
None => continue,
};
inner.lines.put(stable_row, entry);
}
}
}
}
}
log::trace!(
"Generate PaneOutput event for local_pane_id={}",
local_pane_id
);
mux.notify(mux::MuxNotification::PaneOutput(local_pane_id));
Ok(())
}
fn poll(&mut self) -> anyhow::Result<()> {
if self.poll_in_progress.load(Ordering::SeqCst) {
// We have a poll in progress
return Ok(());
}
if self.last_poll.elapsed() < self.poll_interval {
return Ok(());
}
let interval = self.poll_interval;
let interval = (interval + interval).min(MAX_POLL_INTERVAL);
self.poll_interval = interval;
self.last_poll = Instant::now();
self.poll_in_progress.store(true, Ordering::SeqCst);
let remote_pane_id = self.remote_pane_id;
let local_pane_id = self.local_pane_id;
let client = Arc::clone(&self.client);
promise::spawn::spawn(async move {
let alive = match client
.client
.get_pane_render_changes(GetPaneRenderChanges {
pane_id: remote_pane_id,
})
.await
{
Ok(resp) => resp.is_alive,
// if we got a timeout on a reconnectable, don't
// consider the tab to be dead; that helps to
// avoid having a tab get shuffled around
Err(_) => client.client.is_reconnectable,
};
let mux = Mux::get();
let tab = mux
.get_pane(local_pane_id)
.ok_or_else(|| anyhow!("no such tab {}", local_pane_id))?;
if let Some(client_tab) = tab.downcast_ref::<ClientPane>() {
let renderable = client_tab.renderable.lock();
let mut inner = renderable.inner.borrow_mut();
inner.dead = !alive;
inner.last_recv_time = Instant::now();
inner.poll_in_progress.store(false, Ordering::SeqCst);
}
Ok::<(), anyhow::Error>(())
})
.detach();
Ok(())
}
}
lazy_static::lazy_static! {
static ref IMAGE_LRU: Mutex<LruCache<[u8;32], Arc<ImageData>>> = Mutex::new(LruCache::new(128));
}
pub(crate) async fn hydrate_lines(
client: Arc<ClientInner>,
pane_id: PaneId,
serialized_lines: SerializedLines,
) -> Vec<(StableRowIndex, Line)> {
let (lines, image_cells) = serialized_lines.extract_data();
if image_cells.is_empty() {
return lines;
}
let mut requests = HashMap::new();
let mut data_by_hash = HashMap::new();
for im in &image_cells {
if let Some(data) = IMAGE_LRU.lock().unwrap().get(&im.data_hash) {
data_by_hash.insert(im.data_hash, Arc::clone(data));
} else {
requests
.entry(&im.data_hash)
.or_insert_with(|| GetImageCell {
pane_id,
line_idx: im.line_idx,
cell_idx: im.cell_idx,
data_hash: im.data_hash,
});
}
}
for (_, request) in requests {
match client.client.get_image_cell(request).await {
Ok(GetImageCellResponse {
data: Some(data), ..
}) => {
IMAGE_LRU
.lock()
.unwrap()
.put(data.hash(), Arc::clone(&data));
data_by_hash.insert(data.hash(), data);
}
Ok(GetImageCellResponse { data: None, .. }) => {
log::error!("no image data!");
}
Err(err) => {
log::error!("failed to retrieve image {err:#}");
}
}
}
let mut line_by_idx = HashMap::new();
for (line_idx, line) in lines {
line_by_idx.insert(line_idx, line);
}
for im in image_cells {
if let Some(data) = data_by_hash.get(&im.data_hash) {
if let Some(line) = line_by_idx.get_mut(&im.line_idx) {
if let Some(cell) = line.cells_mut_for_attr_changes_only().get_mut(im.cell_idx) {
cell.attrs_mut()
.attach_image(Box::new(ImageCell::with_z_index(
im.top_left,
im.bottom_right,
Arc::clone(data),
im.z_index,
im.padding_left,
im.padding_top,
im.padding_right,
im.padding_bottom,
im.image_id,
im.placement_id,
)));
}
}
}
}
line_by_idx.into_iter().collect()
}
impl RenderableState {
pub fn get_cursor_position(&self) -> StableCursorPosition {
self.inner.borrow().cursor_position
}
pub fn get_lines(&self, lines: Range<StableRowIndex>) -> (StableRowIndex, Vec<Line>) {
let mut inner = self.inner.borrow_mut();
let mut result = vec![];
let mut to_fetch = RangeSet::new();
let now = Instant::now();
for idx in lines.clone() {
let entry = match inner.lines.pop(&idx) {
Some(LineEntry::Line(line)) => {
result.push(line.clone());
if line.changed_since(inner.seqno) {
to_fetch.add(idx);
LineEntry::Stale(line)
} else {
LineEntry::Line(line)
}
}
Some(LineEntry::LineAndFetching(line, then)) => {
result.push(line.clone());
LineEntry::LineAndFetching(line, then)
}
Some(LineEntry::Fetching(then)) => {
result.push(Line::with_width(inner.dimensions.cols, SEQ_ZERO));
LineEntry::Fetching(then)
}
Some(LineEntry::Stale(line)) => {
result.push(line.clone());
to_fetch.add(idx);
LineEntry::LineAndFetching(line, now)
}
None => {
result.push(Line::with_width(inner.dimensions.cols, SEQ_ZERO));
to_fetch.add(idx);
LineEntry::Fetching(now)
}
};
if inner.client.overlay_lag_indicator && idx == inner.dimensions.physical_top {
if inner.is_tardy() {
let status = format!(
"wezterm: {:.0?}⏳since last response",
inner.last_recv_time.elapsed()
);
// Right align it in the tab
let col = inner
.dimensions
.cols
.saturating_sub(wezterm_term::unicode_column_width(&status, None));
let mut attr = CellAttributes::default();
attr.set_foreground(AnsiColor::White);
attr.set_background(AnsiColor::Blue);
result
.last_mut()
.unwrap()
.overlay_text_with_attribute(col, &status, attr, SEQ_ZERO);
}
}
inner.lines.put(idx, entry);
}
log::trace!(
"get_lines: {:?}, num result lines={}, will fetch {:?}",
lines,
result.len(),
to_fetch
);
inner.schedule_fetch_lines(to_fetch, now);
(lines.start, result)
}
pub fn get_current_seqno(&self) -> SequenceNo {
self.inner.borrow().seqno
}
pub fn get_changed_since(
&self,
lines: Range<StableRowIndex>,
seqno: SequenceNo,
) -> RangeSet<StableRowIndex> {
let mut inner = self.inner.borrow_mut();
if let Err(err) = inner.poll() {
// We allow for BrokenPromise here for now; for a TLS backed
// session it indicates that we'll retry. For a local unix
// domain session it is terminal... but we will detect that
// terminal condition elsewhere
if let Err(err) = err.downcast::<BrokenPromise>() {
log::error!("remote tab poll failed: {}, marking as dead", err);
inner.dead = true;
}
}
let mut result = RangeSet::new();
for r in lines {
match inner.lines.get(&r) {
None => {
result.add(r);
}
Some(
LineEntry::Line(line)
| LineEntry::Stale(line)
| LineEntry::LineAndFetching(line, _),
) if line.changed_since(seqno) => {
result.add(r);
}
_ => {}
}
}
// If we're behind receiving an update, invalidate the top row so
// that the indicator will update in a more timely fashion
if inner.is_tardy() {
// ... but take care to avoid always reporting it as dirty, so
// that we don't end up busy looping just to repaint it
if inner.last_late_dirty.elapsed() >= Duration::from_secs(1) {
result.add(inner.dimensions.physical_top);
inner.last_late_dirty = Instant::now();
}
}
if !result.is_empty() {
log::trace!("get_changed_since: {} -> {:?}", seqno, result);
}
result
}
pub fn get_dimensions(&self) -> RenderableDimensions {
self.inner.borrow().dimensions
}
}