diff --git a/Cargo.lock b/Cargo.lock index 57f9dd235..b81b50ea0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5,6 +5,14 @@ name = "adler32" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "ahash" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "const-random 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "aho-corasick" version = "0.6.10" @@ -317,6 +325,24 @@ name = "color_quant" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "const-random" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "const-random-macro 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro-hack 0.5.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "const-random-macro" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro-hack 0.5.11 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.7.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "constant_time_eq" version = "0.1.4" @@ -914,6 +940,15 @@ name = "hashbrown" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "hashbrown" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "ahash 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)", + "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "hdrhistogram" version = "6.3.4" @@ -1149,6 +1184,14 @@ dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "lru" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "hashbrown 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "lyon_geom" version = "0.14.1" @@ -1697,6 +1740,16 @@ dependencies = [ "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "proc-macro-hack" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "proc-macro2 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 1.0.11 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "proc-macro2" version = "0.4.30" @@ -2789,6 +2842,7 @@ dependencies = [ "leb128 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", + "lru 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", "metrics 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", "native-tls 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "notify 4.0.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3043,6 +3097,7 @@ dependencies = [ [metadata] "checksum adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" +"checksum ahash 0.2.18 (registry+https://github.com/rust-lang/crates.io-index)" = "6f33b5018f120946c1dcf279194f238a9f146725593ead1c08fa47ff22b0b5d3" "checksum aho-corasick 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "81ce3d38065e618af2d7b77e10c5ad9a069859b4be3c2250f674af3840d9c8a5" "checksum aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d" "checksum alloc-no-stdlib 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5192ec435945d87bc2f70992b4d818154b5feede43c09fb7592146374eac90a6" @@ -3082,6 +3137,8 @@ dependencies = [ "checksum cmake 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "81fb25b677f8bf1eb325017cb6bb8452f87969db0fedb4f757b297bee78a7c62" "checksum cocoa 0.20.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0a4736c86d51bd878b474400d9ec888156f4037015f5d09794fab9f26eab1ad4" "checksum color_quant 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0dbbb57365263e881e805dc77d94697c9118fd94d8da011240555aa7b23445bd" +"checksum const-random 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "7b641a8c9867e341f3295564203b1c250eb8ce6cb6126e007941f78c4d2ed7fe" +"checksum const-random-macro 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c750ec12b83377637110d5a57f5ae08e895b06c4b16e2bdbf1a94ef717428c59" "checksum constant_time_eq 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "995a44c877f9212528ccc74b21a232f66ad69001e40ede5bcee2ac9ef2657120" "checksum core-foundation 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)" = "25b9e03f145fd4f2bf705e07b900cd41fc636598fe5dc452fd0db1441c3f496d" "checksum core-foundation 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "57d24c7a13c43e870e37c1556b74555437870a04514f7685f5b354e090567171" @@ -3145,6 +3202,7 @@ dependencies = [ "checksum glium 0.26.0-alpha5 (registry+https://github.com/rust-lang/crates.io-index)" = "a5562f15bd5c6f23d5b07090bb990a6478da430df018ee85e3fbc370230ef058" "checksum glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" "checksum hashbrown 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e1de41fb8dba9714efd92241565cdff73f78508c95697dd56787d3cba27e2353" +"checksum hashbrown 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8e6073d0ca812575946eb5f35ff68dbe519907b25c42530389ff946dc84c6ead" "checksum hdrhistogram 6.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "08d331ebcdbca4acbefe5da8c3299b2e246f198a8294cc5163354e743398b89d" "checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205" "checksum hermit-abi 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f629dc602392d3ec14bfc8a09b5e644d7ffd725102b48b81e59f90f2633621d7" @@ -3173,6 +3231,7 @@ dependencies = [ "checksum line_drawing 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f81902e542483002b103c6424d23e765c2e5a65f732923299053a601bce50ab2" "checksum lock_api 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e57b3997725d2b60dbec1297f6c2e2957cc383db1cebd6be812163f969c7d586" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" +"checksum lru 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "0609345ddee5badacf857d4f547e0e5a2e987db77085c24cd887f73573a04237" "checksum lyon_geom 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ca04310c9807612a311506106000b6eccb2e27bca9bfb594ce80fb8a31231f9d" "checksum lyon_path 0.14.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0bcb57ac24a5428539e2c7c0592766d5933c937d703f430990c669c00de96862" "checksum lzw 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7d947cbb889ed21c2a84be6ffbaebf5b4e0f4340638cba0444907e38b56be084" @@ -3230,6 +3289,7 @@ dependencies = [ "checksum ppv-lite86 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "74490b50b9fbe561ac330df47c08f3f33073d2d00c150f719147d7c54522fa1b" "checksum pretty_assertions 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3f81e1644e1b54f5a68959a29aa86cde704219254669da328ecfdf6a1f09d427" "checksum pretty_env_logger 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "717ee476b1690853d222af4634056d830b5197ffd747726a9a1eee6da9f49074" +"checksum proc-macro-hack 0.5.11 (registry+https://github.com/rust-lang/crates.io-index)" = "ecd45702f76d6d3c75a80564378ae228a85f0b59d2f3ed43c91b4a69eb2ebfc5" "checksum proc-macro2 0.4.30 (registry+https://github.com/rust-lang/crates.io-index)" = "cf3d2011ab5c909338f7887f4fc896d35932e29146c12c8d01da6b22a80ba759" "checksum proc-macro2 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "9c9e470a8dc4aeae2dee2f335e8f533e2d4b347e1434e5671afc49b054592f27" "checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" diff --git a/Cargo.toml b/Cargo.toml index 4302aa89d..448be49cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,7 @@ lazy_static = "1.3" leb128 = "0.2" libc = "0.2" log = "0.4" +lru = "0.4" open = "1.2" metrics = { version="0.12", features=["std"]} hdrhistogram = "6.3" diff --git a/src/frontend/gui/selection.rs b/src/frontend/gui/selection.rs index a3716c1cd..76cce5f5c 100644 --- a/src/frontend/gui/selection.rs +++ b/src/frontend/gui/selection.rs @@ -14,6 +14,7 @@ pub struct Selection { } impl Selection { + #[allow(dead_code)] pub fn clear(&mut self) { self.range = None; self.start = None; diff --git a/src/ratelim.rs b/src/ratelim.rs index 974e470cb..b2b5e06a4 100644 --- a/src/ratelim.rs +++ b/src/ratelim.rs @@ -48,6 +48,7 @@ impl RateLimiter { } } + #[allow(dead_code)] pub fn non_blocking_admittance_check(&mut self, amount: u32) -> bool { self.check_config_reload(); self.lim.check_n(amount).is_ok() diff --git a/src/server/client.rs b/src/server/client.rs index 232ee69d3..11c4dbf93 100644 --- a/src/server/client.rs +++ b/src/server/client.rs @@ -311,8 +311,8 @@ impl Reconnectable { let mut chan = sess.channel_session()?; let cmd = if initial { - // "/home/wez/wez-personal/wezterm/target/debug/wezterm cli proxy" - "wezterm cli proxy" + "/home/wez/wez-personal/wezterm/target/debug/wezterm cli proxy" + //"wezterm cli proxy" } else { "wezterm cli --no-auto-start proxy" }; @@ -622,4 +622,5 @@ impl Client { rpc!(mouse_event, SendMouseEvent, UnitResponse); rpc!(resize, Resize, UnitResponse); rpc!(get_tab_render_changes, GetTabRenderChanges, UnitResponse); + rpc!(get_lines, GetLines, GetLinesResponse); } diff --git a/src/server/codec.rs b/src/server/codec.rs index 75c99fda8..2a89df2fb 100644 --- a/src/server/codec.rs +++ b/src/server/codec.rs @@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize}; use std::io::Cursor; use std::ops::Range; use term::StableRowIndex; -use termwiz::surface::{Change, Line, SequenceNo}; +use termwiz::surface::Line; use varbincode; /// Returns the encoded length of the leb128 representation of value @@ -413,24 +413,16 @@ pub struct Resize { #[derive(Deserialize, Serialize, PartialEq, Debug)] pub struct GetTabRenderChanges { pub tab_id: TabId, - pub sequence_no: SequenceNo, -} - -#[derive(Deserialize, Serialize, PartialEq, Debug)] -pub struct LineRange { - pub start: StableRowIndex, - pub end: StableRowIndex, } #[derive(Deserialize, Serialize, PartialEq, Debug)] pub struct GetTabRenderChangesResponse { pub tab_id: TabId, - pub sequence_no: SequenceNo, - pub changes: Vec, pub mouse_grabbed: bool, pub cursor_position: StableCursorPosition, pub dimensions: RenderableDimensions, - pub dirty_lines: Vec, + pub dirty_lines: Vec>, + pub title: String, } #[derive(Deserialize, Serialize, PartialEq, Debug)] diff --git a/src/server/listener.rs b/src/server/listener.rs index df1fda1f7..a35c21baf 100644 --- a/src/server/listener.rs +++ b/src/server/listener.rs @@ -1,10 +1,8 @@ use crate::config::{configuration, TlsDomainServer, UnixDomain}; use crate::create_user_owned_dirs; use crate::frontend::executor; -use crate::mux::renderable::{RenderableDimensions, StableCursorPosition}; use crate::mux::tab::{Tab, TabId}; use crate::mux::{Mux, MuxNotification, MuxSubscriber}; -use crate::ratelim::RateLimiter; use crate::server::codec::*; use crate::server::pollable::*; use crate::server::UnixListener; @@ -29,7 +27,6 @@ use std::thread; use std::time::Instant; use term::terminal::Clipboard; use term::StableRowIndex; -use termwiz::surface::{Change, Position, SequenceNo, Surface}; struct LocalListener { listener: UnixListener, @@ -395,8 +392,7 @@ fn maybe_push_tab_changes( let dims = tab.renderer().get_dimensions(); let surface = surfaces .entry(tab_id) - .or_insert_with(|| ClientSurfaceState::new(dims.cols, dims.viewport_rows)); - surface.update_surface_from_screen(&tab); + .or_insert_with(|| ClientSurfaceState::new()); let mut dirty_rows = RangeSet::new(); for idx in tab.renderer().get_dirty_lines( @@ -406,136 +402,42 @@ fn maybe_push_tab_changes( } let dirty_delta = dirty_rows.difference(&surface.informed_dirty_rows); - let dirty_lines = dirty_delta - .iter() - .map(|r| LineRange { - start: r.start, - end: r.end, - }) - .collect(); + let dirty_lines = dirty_delta.iter().cloned().collect(); surface.informed_dirty_rows.add_set(&dirty_rows); let cursor_position = tab.renderer().get_cursor_position(); - let (new_seq, changes) = surface.get_and_flush_changes(surface.last_seq); - if !changes.is_empty() { - sender.send(DecodedPdu { - pdu: Pdu::GetTabRenderChangesResponse(GetTabRenderChangesResponse { - tab_id, - sequence_no: surface.last_seq, - changes, - mouse_grabbed, - dirty_lines, - dimensions: dims, - cursor_position, - }), - serial: 0, - })?; - surface.last_seq = new_seq; - } + let title = tab.get_title(); + + sender.send(DecodedPdu { + pdu: Pdu::GetTabRenderChangesResponse(GetTabRenderChangesResponse { + tab_id, + mouse_grabbed, + dirty_lines, + dimensions: dims, + cursor_position, + title, + }), + serial: 0, + })?; Ok(()) } struct ClientSurfaceState { - surface: Surface, - last_seq: SequenceNo, - push_limiter: RateLimiter, - update_limiter: RateLimiter, - /// The set of rows that we have informed the peer are dirty. /// We'll remove a row from here each time the peer requests /// the corresponding line. /// We use this to determine the delta when additional rows /// are dirty. informed_dirty_rows: RangeSet, - - /// The cursor position that we last sent to the peer - cursor_position: StableCursorPosition, - - /// The dimensions that we last sent to the peer - dimensions: RenderableDimensions, } impl ClientSurfaceState { - fn new(cols: usize, rows: usize) -> Self { - let push_limiter = RateLimiter::new(|config| config.ratelimit_mux_output_pushes_per_second); - let update_limiter = - RateLimiter::new(|config| config.ratelimit_mux_output_scans_per_second); - let surface = Surface::new(cols, rows); + fn new() -> Self { Self { - surface, - last_seq: 0, - push_limiter, - update_limiter, informed_dirty_rows: RangeSet::new(), - cursor_position: StableCursorPosition::default(), - dimensions: RenderableDimensions::default(), } } - - fn update_surface_from_screen(&mut self, tab: &Rc) { - if !self.update_limiter.non_blocking_admittance_check(1) { - return; - } - - { - let renderable = tab.renderer(); - let dims = renderable.get_dimensions(); - let (surface_width, surface_height) = self.surface.dimensions(); - - if (dims.viewport_rows != surface_height) || (dims.cols != surface_width) { - self.surface.resize(dims.cols, dims.viewport_rows); - } - - let (x, y) = self.surface.cursor_position(); - let cursor = renderable.get_cursor_position(); - if (x != cursor.x) || (y as StableRowIndex != cursor.y) { - // Update the cursor, but if we're scrolled back - // and it is our of range, skip the update. - if cursor.y < dims.viewport_rows as StableRowIndex { - self.surface.add_change(Change::CursorPosition { - x: Position::Absolute(cursor.x), - y: Position::Absolute(cursor.y as usize), - }); - } - } - - todo!(); - /* - let mut changes = vec![]; - for (line_idx, line, _selrange) in renderable.get_dirty_lines() { - changes.append(&mut self.surface.diff_against_numbered_line(line_idx, &line)); - } - - self.surface.add_changes(changes); - */ - } - - let title = tab.get_title(); - if title != self.surface.title() { - self.surface.add_change(Change::Title(title)); - } - } - - fn get_and_flush_changes(&mut self, seq: SequenceNo) -> (SequenceNo, Vec) { - let (new_seq, changes) = self.surface.get_changes(seq); - - if !changes.is_empty() && !self.push_limiter.non_blocking_admittance_check(1) { - // Pretend that there are no changes - return (seq, vec![]); - } - - let changes = changes.into_owned(); - let (rows, cols) = self.surface.dimensions(); - - // Keep the change log in the surface bounded; - // we don't completely blow away the log each time - // so that multiple clients have an opportunity to - // resync from a smaller delta - self.surface - .flush_changes_older_than(new_seq.saturating_sub(rows * cols * 2)); - (new_seq, changes) - } } struct RemoteClipboard { @@ -839,9 +741,11 @@ impl ClientSession { .get_tab(tab_id) .ok_or_else(|| anyhow!("no such tab {}", tab_id))?; let mut renderer = tab.renderer(); + let surface = surfaces - .get_mut(&tab_id) - .ok_or_else(|| anyhow!("no surface for tab {}", tab_id))?; + .entry(tab_id) + .or_insert_with(|| ClientSurfaceState::new()); + surface.informed_dirty_rows.remove_range(lines.clone()); let (first_row, lines) = renderer.get_lines(lines); surface diff --git a/src/server/tab.rs b/src/server/tab.rs index 9e0c4055e..40e5af291 100644 --- a/src/server/tab.rs +++ b/src/server/tab.rs @@ -3,21 +3,22 @@ use crate::frontend::executor; use crate::mux::domain::DomainId; use crate::mux::renderable::{Renderable, RenderableDimensions, StableCursorPosition}; use crate::mux::tab::{alloc_tab_id, Tab, TabId}; +use crate::mux::Mux; use crate::server::client::Client; use crate::server::codec::*; use crate::server::domain::ClientInner; +use anyhow::anyhow; use anyhow::bail; use filedescriptor::Pipe; use log::{error, info}; +use lru::LruCache; use portable_pty::PtySize; use promise::{BrokenPromise, Future}; use rangeset::RangeSet; use std::cell::RefCell; use std::cell::RefMut; use std::collections::VecDeque; -use std::convert::TryInto; use std::ops::Range; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use term::color::ColorPalette; @@ -27,12 +28,10 @@ use term::{ }; use termwiz::hyperlink::Hyperlink; use termwiz::input::KeyEvent; -use termwiz::surface::{SequenceNo, Surface}; struct MouseState { future: Option>, queue: VecDeque, - something_changed: Arc, client: Client, remote_tab_id: TabId, } @@ -95,7 +94,6 @@ impl MouseState { fn next(state: &Arc>) -> anyhow::Result<()> { let mut mouse = state.lock().unwrap(); if let Some(event) = mouse.pop()? { - let something_changed = Arc::clone(&mouse.something_changed); let state = Arc::clone(state); mouse.future = Some( @@ -105,10 +103,7 @@ impl MouseState { tab_id: mouse.remote_tab_id, event, }) - .then(move |resp| { - if let Ok(_) = resp.as_ref() { - something_changed.store(true, Ordering::SeqCst); - } + .then(move |_| { Future::with_executor(executor(), move || { Self::next(&state)?; Ok(()) @@ -140,11 +135,9 @@ impl ClientTab { client: Arc::clone(client), remote_tab_id, }; - let something_changed = Arc::new(AtomicBool::new(true)); let highlight = Arc::new(Mutex::new(None)); let mouse = Arc::new(Mutex::new(MouseState { - something_changed: Arc::clone(&something_changed), remote_tab_id, client: client.client.clone(), future: None, @@ -154,18 +147,23 @@ impl ClientTab { inner: RefCell::new(RenderableInner { client: Arc::clone(client), remote_tab_id, + local_tab_id, last_poll: Instant::now(), dead: false, poll_future: None, poll_interval: BASE_POLL_INTERVAL, - surface: Surface::new(size.cols as usize, size.rows as usize), - remote_sequence: 0, - local_sequence: 0, - something_changed, highlight, cursor_position: StableCursorPosition::default(), dirty_rows: RangeSet::new(), - dimensions: RenderableDimensions::default(), + dimensions: RenderableDimensions { + cols: size.cols as _, + viewport_rows: size.rows as _, + scrollback_rows: size.rows as _, + physical_top: 0, + scrollback_top: 0, + }, + lines: LruCache::unbounded(), + title: "wezterm".to_string(), }), }; @@ -187,7 +185,6 @@ impl ClientTab { pub fn process_unilateral(&self, pdu: Pdu) -> anyhow::Result<()> { match pdu { Pdu::GetTabRenderChangesResponse(delta) => { - log::trace!("new delta {}", delta.sequence_no); *self.mouse_grabbed.borrow_mut() = delta.mouse_grabbed; self.renderable .borrow() @@ -239,8 +236,8 @@ impl Tab for ClientTab { fn get_title(&self) -> String { let renderable = self.renderable.borrow(); - let surface = &renderable.inner.borrow().surface; - surface.title().to_string() + let inner = renderable.inner.borrow(); + inner.title.clone() } fn send_paste(&self, text: &str) -> anyhow::Result<()> { @@ -261,12 +258,6 @@ impl Tab for ClientTab { } fn resize(&self, size: PtySize) -> anyhow::Result<()> { - self.renderable - .borrow() - .inner - .borrow_mut() - .surface - .resize(size.cols as usize, size.rows as usize); self.client.client.resize(Resize { tab_id: self.remote_tab_id, size, @@ -320,19 +311,19 @@ impl Tab for ClientTab { struct RenderableInner { client: Arc, remote_tab_id: TabId, + local_tab_id: TabId, last_poll: Instant, dead: bool, poll_future: Option>, - surface: Surface, - remote_sequence: SequenceNo, - local_sequence: SequenceNo, poll_interval: Duration, - something_changed: Arc, highlight: Arc>>>, dirty_rows: RangeSet, cursor_position: StableCursorPosition, dimensions: RenderableDimensions, + + lines: LruCache, + title: String, } struct RenderableState { @@ -344,19 +335,80 @@ const BASE_POLL_INTERVAL: Duration = Duration::from_millis(20); impl RenderableInner { fn apply_changes_to_surface(&mut self, delta: GetTabRenderChangesResponse) { - if let Some(first) = delta.changes.first().as_ref() { - log::trace!("{:?}", first); - } self.poll_interval = BASE_POLL_INTERVAL; - self.surface.add_changes(delta.changes); - self.remote_sequence = delta.sequence_no; + let mut to_fetch = delta.dimensions.physical_top..delta.dimensions.physical_top; for r in delta.dirty_lines { - self.dirty_rows.add_range(r.start..r.end); + log::error!("apply changes: marking {:?} dirty", r); + self.dirty_rows.add_range(r.clone()); + for idx in r { + // 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. + if idx >= delta.dimensions.physical_top { + to_fetch.start = to_fetch.start.min(idx); + to_fetch.end = to_fetch.end.max(idx); + } else { + self.lines.pop(&idx); + } + } } + self.fetch_lines(to_fetch); + + if delta.cursor_position != self.cursor_position { + self.dirty_rows.add(self.cursor_position.y); + self.dirty_rows.add(delta.cursor_position.y); + } self.cursor_position = delta.cursor_position; self.dimensions = delta.dimensions; + self.title = delta.title; + } + + fn fetch_lines(&mut self, to_fetch: Range) { + if to_fetch.start == to_fetch.end { + return; + } + let local_tab_id = self.local_tab_id; + log::error!( + "will fetch lines {:?} for remote tab id {}", + to_fetch, + self.remote_tab_id + ); + self.client + .client + .get_lines(GetLines { + tab_id: self.remote_tab_id, + lines: to_fetch, + }) + .then(move |result| { + match result { + Ok(result) => { + Future::with_executor(executor(), move || { + let mux = Mux::get().unwrap(); + let tab = mux + .get_tab(local_tab_id) + .ok_or_else(|| anyhow!("no such tab {}", local_tab_id))?; + if let Some(client_tab) = tab.downcast_ref::() { + let renderable = client_tab.renderable.borrow_mut(); + let mut inner = renderable.inner.borrow_mut(); + log::error!("got {} lines", result.lines.len()); + for (idx, line) in result.lines.into_iter().enumerate() { + let stable_row = result.first_row + idx as StableRowIndex; + inner.lines.put(stable_row, line); + inner.dirty_rows.add(stable_row); + } + } + Ok(()) + }); + } + Err(err) => { + log::error!("get_lines failed: {}", err); + } + } + Ok(()) + }); } fn poll(&mut self) -> anyhow::Result<()> { @@ -387,7 +439,6 @@ impl RenderableInner { self.poll_future = Some(self.client.client.get_tab_render_changes( GetTabRenderChanges { tab_id: self.remote_tab_id, - sequence_no: self.remote_sequence, }, )); } @@ -397,30 +448,30 @@ impl RenderableInner { impl Renderable for RenderableState { fn get_cursor_position(&self) -> StableCursorPosition { - let surface = &self.inner.borrow().surface; - let (x, y) = surface.cursor_position(); - let shape = surface.cursor_shape(); - StableCursorPosition { - x, - y: y as StableRowIndex, - shape, - } + self.inner.borrow().cursor_position } fn get_lines(&mut self, lines: Range) -> (StableRowIndex, Vec) { - // FIXME: mark clean - let inner = self.inner.borrow_mut(); - ( - lines.start, - inner - .surface - .screen_lines() - .into_iter() - .skip(lines.start.try_into().unwrap()) - .take((lines.end - lines.start).try_into().unwrap()) - .map(|line| line.into_owned()) - .collect(), - ) + let mut inner = self.inner.borrow_mut(); + let mut result = vec![]; + let mut to_fetch = 0..0; + for idx in lines.clone() { + match inner.lines.get(&idx) { + Some(line) => { + result.push(line.clone()); + // mark clean + inner.dirty_rows.remove(idx); + } + None => { + to_fetch.start = to_fetch.start.min(idx); + to_fetch.end = to_fetch.end.max(idx + 1); + result.push(Line::with_width(inner.dimensions.cols)); + } + } + } + + inner.fetch_lines(to_fetch); + (lines.start, result) } fn get_dirty_lines(&self, lines: Range) -> Vec { @@ -443,53 +494,13 @@ impl Renderable for RenderableState { } } + if !result.is_empty() { + log::error!("get_dirty_lines: {:?}", result); + } + result } - /* - fn get_dirty_lines(&self) -> Vec<(usize, Cow, Range)> { - let mut inner = self.inner.borrow_mut(); - let seq = inner.surface.current_seqno(); - inner.surface.flush_changes_older_than(seq); - let selection = *inner.selection_range.lock().unwrap(); - inner.something_changed.store(false, Ordering::SeqCst); - inner.local_sequence = seq; - inner - .surface - .screen_lines() - .into_iter() - .enumerate() - .map(|(idx, line)| { - let r = match selection { - None => 0..0, - Some(sel) => sel.normalize().cols_for_row(idx as i32), - }; - (idx, Cow::Owned(line.into_owned()), r) - }) - .collect() - } - */ - - /* - fn has_dirty_lines(&self) -> bool { - 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::() { - log::error!("remote tab poll failed: {}, marking as dead", err); - inner.dead = true; - } - } - if inner.something_changed.load(Ordering::SeqCst) { - return true; - } - inner.surface.has_changes(inner.local_sequence) - } - */ - fn current_highlight(&self) -> Option> { self.inner .borrow() @@ -501,14 +512,7 @@ impl Renderable for RenderableState { } fn get_dimensions(&self) -> RenderableDimensions { - let (cols, viewport_rows) = self.inner.borrow().surface.dimensions(); - RenderableDimensions { - viewport_rows, - cols, - scrollback_rows: viewport_rows, - physical_top: 0, - scrollback_top: 0, - } + self.inner.borrow().dimensions } }