some plumbing to use Surface+Change for the mux protocol
This commit is contained in:
1 parent
55caafb0c4
commit
b58d329b07
8 files changed
+216
-78
No files matched your search
@@ -195,4 +195,9 @@ impl Client {
|
||||
rpc!(key_down, SendKeyDown, UnitResponse);
|
||||
rpc!(mouse_event, SendMouseEvent, SendMouseEventResponse);
|
||||
rpc!(resize, Resize, UnitResponse);
|
||||
rpc!(
|
||||
get_tab_render_changes,
|
||||
GetTabRenderChanges,
|
||||
GetTabRenderChangesResponse
|
||||
);
|
||||
}
|
||||
@@ -21,6 +21,7 @@ use serde_derive::*;
|
||||
use std::sync::Arc;
|
||||
use term::{CursorPosition, Line};
|
||||
use termwiz::hyperlink::Hyperlink;
|
||||
use termwiz::surface::{Change, SequenceNo};
|
||||
use varbincode;
|
||||
|
||||
/// Returns the encoded length of the leb128 representation of value
|
||||
@@ -227,6 +228,8 @@ pdu! {
|
||||
SendPaste: 13,
|
||||
Resize: 14,
|
||||
SendMouseEventResponse: 17,
|
||||
GetTabRenderChanges: 18,
|
||||
GetTabRenderChangesResponse: 19,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, PartialEq, Debug)]
|
||||
@@ -335,6 +338,18 @@ pub struct Resize {
|
||||
pub size: PtySize,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, PartialEq, Debug)]
|
||||
pub struct GetTabRenderChanges {
|
||||
pub tab_id: TabId,
|
||||
pub sequence_no: SequenceNo,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, PartialEq, Debug)]
|
||||
pub struct GetTabRenderChangesResponse {
|
||||
pub sequence_no: SequenceNo,
|
||||
pub changes: Vec<Change>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
+82
-2
@@ -1,4 +1,6 @@
|
||||
use crate::config::Config;
|
||||
use crate::mux::renderable::Renderable;
|
||||
use crate::mux::tab::TabId;
|
||||
use crate::mux::Mux;
|
||||
use crate::server::codec::*;
|
||||
use crate::server::UnixListener;
|
||||
@@ -8,6 +10,7 @@ use libc::{mode_t, umask};
|
||||
use log::{debug, error, warn};
|
||||
use native_tls::{Identity, TlsAcceptor};
|
||||
use promise::{Executor, Future};
|
||||
use std::collections::HashMap;
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use std::fs::{remove_file, DirBuilder};
|
||||
use std::io::Read;
|
||||
@@ -15,9 +18,10 @@ use std::net::TcpListener;
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Instant;
|
||||
use termwiz::surface::{Change, Position, SequenceNo, Surface};
|
||||
|
||||
struct LocalListener {
|
||||
listener: UnixListener,
|
||||
@@ -186,6 +190,7 @@ impl NetListener {
|
||||
pub struct ClientSession<S: std::io::Read + std::io::Write> {
|
||||
stream: S,
|
||||
executor: Box<dyn Executor>,
|
||||
surfaces_by_tab: Arc<Mutex<HashMap<TabId, Surface>>>,
|
||||
}
|
||||
|
||||
struct BufferedTerminalHost<'a> {
|
||||
@@ -220,9 +225,43 @@ impl<'a> term::TerminalHost for BufferedTerminalHost<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn update_surface_from_screen(
|
||||
surface: &mut Surface,
|
||||
renderable: &mut dyn Renderable,
|
||||
) -> SequenceNo {
|
||||
let (rows, cols) = renderable.physical_dimensions();
|
||||
let (surface_width, surface_height) = surface.dimensions();
|
||||
|
||||
if (rows != surface_height) || (cols != surface_width) {
|
||||
surface.resize(cols, rows);
|
||||
renderable.make_all_lines_dirty();
|
||||
}
|
||||
|
||||
let (x, y) = surface.cursor_position();
|
||||
let cursor = renderable.get_cursor_position();
|
||||
if (x != cursor.x) || (y as i64 != cursor.y) {
|
||||
surface.add_change(Change::CursorPosition {
|
||||
x: Position::Absolute(cursor.x),
|
||||
y: Position::Absolute(cursor.y as usize),
|
||||
});
|
||||
}
|
||||
|
||||
let mut changes = vec![];
|
||||
|
||||
for (line_idx, line, _selrange) in renderable.get_dirty_lines() {
|
||||
changes.append(&mut surface.diff_against_numbered_line(line_idx, &line));
|
||||
}
|
||||
|
||||
surface.add_changes(changes)
|
||||
}
|
||||
|
||||
impl<S: std::io::Read + std::io::Write> ClientSession<S> {
|
||||
fn new(stream: S, executor: Box<dyn Executor>) -> Self {
|
||||
Self { stream, executor }
|
||||
Self {
|
||||
stream,
|
||||
executor,
|
||||
surfaces_by_tab: Arc::new(Mutex::new(HashMap::new())),
|
||||
}
|
||||
}
|
||||
|
||||
fn process(&mut self) -> Result<(), Error> {
|
||||
@@ -387,12 +426,53 @@ impl<S: std::io::Read + std::io::Write> ClientSession<S> {
|
||||
Pdu::SpawnResponse(result)
|
||||
}
|
||||
|
||||
Pdu::GetTabRenderChanges(GetTabRenderChanges {
|
||||
tab_id,
|
||||
sequence_no,
|
||||
}) => {
|
||||
let surfaces = Arc::clone(&self.surfaces_by_tab);
|
||||
Future::with_executor(self.executor.clone_executor(), move || {
|
||||
let mux = Mux::get().unwrap();
|
||||
let tab = mux
|
||||
.get_tab(tab_id)
|
||||
.ok_or_else(|| format_err!("no such tab {}", tab_id))?;
|
||||
let mut surfaces = surfaces.lock().unwrap();
|
||||
let (rows, cols) = tab.renderer().physical_dimensions();
|
||||
let surface = surfaces
|
||||
.entry(tab_id)
|
||||
.or_insert_with(|| Surface::new(cols, rows));
|
||||
update_surface_from_screen(surface, &mut *tab.renderer());
|
||||
let title = tab.get_title();
|
||||
if title != surface.title() {
|
||||
log::error!("recording surface title {}", title);
|
||||
surface.add_change(Change::Title(title));
|
||||
}
|
||||
|
||||
let (new_seq, changes) = surface.get_changes(sequence_no);
|
||||
let changes = changes.into_owned();
|
||||
|
||||
// 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
|
||||
surface.flush_changes_older_than(new_seq - (rows * cols * 2));
|
||||
Ok(Pdu::GetTabRenderChangesResponse(
|
||||
GetTabRenderChangesResponse {
|
||||
sequence_no: new_seq,
|
||||
changes,
|
||||
},
|
||||
))
|
||||
})
|
||||
.wait()?
|
||||
}
|
||||
|
||||
Pdu::Invalid { .. } => bail!("invalid PDU {:?}", pdu),
|
||||
Pdu::Pong { .. }
|
||||
| Pdu::ListTabsResponse { .. }
|
||||
| Pdu::SendMouseEventResponse { .. }
|
||||
| Pdu::GetCoarseTabRenderableDataResponse { .. }
|
||||
| Pdu::SpawnResponse { .. }
|
||||
| Pdu::GetTabRenderChangesResponse { .. }
|
||||
| Pdu::UnitResponse { .. }
|
||||
| Pdu::ErrorResponse { .. } => bail!("expected a request, got {:?}", pdu),
|
||||
})
|
||||
|
||||
+56
-76
@@ -18,6 +18,7 @@ use term::{CursorPosition, Line};
|
||||
use term::{KeyCode, KeyModifiers, MouseEvent, TerminalHost};
|
||||
use termwiz::hyperlink::Hyperlink;
|
||||
use termwiz::input::KeyEvent;
|
||||
use termwiz::surface::{Change, SequenceNo, Surface};
|
||||
|
||||
pub struct ClientTab {
|
||||
client: Arc<ClientInner>,
|
||||
@@ -38,11 +39,12 @@ impl ClientTab {
|
||||
let render = RenderableState {
|
||||
client: Arc::clone(client),
|
||||
remote_tab_id,
|
||||
coarse: RefCell::new(None),
|
||||
last_poll: RefCell::new(Instant::now()),
|
||||
dirty_all: RefCell::new(true),
|
||||
dead: RefCell::new(false),
|
||||
poll_future: RefCell::new(None),
|
||||
surface: RefCell::new(Surface::new(80, 24)),
|
||||
remote_sequence: RefCell::new(0),
|
||||
local_sequence: RefCell::new(0),
|
||||
};
|
||||
|
||||
let reader = Pipe::new().expect("Pipe::new failed");
|
||||
@@ -68,14 +70,8 @@ impl Tab for ClientTab {
|
||||
|
||||
fn get_title(&self) -> String {
|
||||
let renderable = self.renderable.borrow();
|
||||
let coarse = renderable.coarse.borrow();
|
||||
format!(
|
||||
"[muxed] {}",
|
||||
coarse
|
||||
.as_ref()
|
||||
.map(|coarse| coarse.title.as_str())
|
||||
.unwrap_or("")
|
||||
)
|
||||
let surface = renderable.surface.borrow();
|
||||
format!("[muxed] {} {}", surface.current_seqno(), surface.title())
|
||||
}
|
||||
|
||||
fn send_paste(&self, text: &str) -> Fallible<()> {
|
||||
@@ -97,6 +93,11 @@ impl Tab for ClientTab {
|
||||
}
|
||||
|
||||
fn resize(&self, size: PtySize) -> Fallible<()> {
|
||||
self.renderable
|
||||
.borrow()
|
||||
.surface
|
||||
.borrow_mut()
|
||||
.resize(size.cols as usize, size.rows as usize);
|
||||
let mut client = self.client.client.lock().unwrap();
|
||||
client.resize(Resize {
|
||||
tab_id: self.remote_tab_id,
|
||||
@@ -157,16 +158,25 @@ impl Tab for ClientTab {
|
||||
struct RenderableState {
|
||||
client: Arc<ClientInner>,
|
||||
remote_tab_id: TabId,
|
||||
coarse: RefCell<Option<GetCoarseTabRenderableDataResponse>>,
|
||||
last_poll: RefCell<Instant>,
|
||||
dirty_all: RefCell<bool>,
|
||||
dead: RefCell<bool>,
|
||||
poll_future: RefCell<Option<Future<GetCoarseTabRenderableDataResponse>>>,
|
||||
poll_future: RefCell<Option<Future<GetTabRenderChangesResponse>>>,
|
||||
surface: RefCell<Surface>,
|
||||
remote_sequence: RefCell<SequenceNo>,
|
||||
local_sequence: RefCell<SequenceNo>,
|
||||
}
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
impl RenderableState {
|
||||
fn apply_changes_to_surface(&self, remote_seq: SequenceNo, changes: Vec<Change>) {
|
||||
if let Some(first) = changes.first().as_ref() {
|
||||
log::trace!("{:?}", first);
|
||||
}
|
||||
self.surface.borrow_mut().add_changes(changes);
|
||||
*self.remote_sequence.borrow_mut() = remote_seq;
|
||||
}
|
||||
|
||||
fn poll(&self) -> Fallible<()> {
|
||||
let ready = self
|
||||
.poll_future
|
||||
@@ -175,107 +185,77 @@ impl RenderableState {
|
||||
.map(Future::is_ready)
|
||||
.unwrap_or(false);
|
||||
if ready {
|
||||
let coarse = self.poll_future.borrow_mut().take().unwrap().wait()?;
|
||||
self.coarse.borrow_mut().replace(coarse);
|
||||
let delta = self.poll_future.borrow_mut().take().unwrap().wait()?;
|
||||
|
||||
log::trace!(
|
||||
"poll: got coarse data in {:?}",
|
||||
"poll: got delta {} {} in {:?}",
|
||||
delta.sequence_no,
|
||||
delta.changes.len(),
|
||||
self.last_poll.borrow().elapsed()
|
||||
);
|
||||
self.apply_changes_to_surface(delta.sequence_no, delta.changes);
|
||||
*self.last_poll.borrow_mut() = Instant::now();
|
||||
} else if self.poll_future.borrow().is_some() {
|
||||
// We have a poll in progress
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let dirty_all = *self.dirty_all.borrow();
|
||||
|
||||
if !dirty_all {
|
||||
let last = *self.last_poll.borrow();
|
||||
if last.elapsed() < POLL_INTERVAL {
|
||||
return Ok(());
|
||||
}
|
||||
let last = *self.last_poll.borrow();
|
||||
if last.elapsed() < POLL_INTERVAL {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
{
|
||||
let mut client = self.client.client.lock().unwrap();
|
||||
*self.poll_future.borrow_mut() = Some(client.get_coarse_tab_renderable_data(
|
||||
GetCoarseTabRenderableData {
|
||||
*self.last_poll.borrow_mut() = Instant::now();
|
||||
*self.poll_future.borrow_mut() =
|
||||
Some(client.get_tab_render_changes(GetTabRenderChanges {
|
||||
tab_id: self.remote_tab_id,
|
||||
dirty_all,
|
||||
},
|
||||
));
|
||||
sequence_no: *self.remote_sequence.borrow(),
|
||||
}));
|
||||
}
|
||||
*self.dirty_all.borrow_mut() = false;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for RenderableState {
|
||||
fn get_cursor_position(&self) -> CursorPosition {
|
||||
let coarse = self.coarse.borrow();
|
||||
if let Some(coarse) = coarse.as_ref() {
|
||||
coarse.cursor_position
|
||||
} else {
|
||||
CursorPosition::default()
|
||||
}
|
||||
let (x, y) = self.surface.borrow().cursor_position();
|
||||
CursorPosition { x, y: y as i64 }
|
||||
}
|
||||
|
||||
fn get_dirty_lines(&self) -> Vec<(usize, Line, Range<usize>)> {
|
||||
let coarse = self.coarse.borrow();
|
||||
if let Some(coarse) = coarse.as_ref() {
|
||||
coarse
|
||||
.dirty_lines
|
||||
.iter()
|
||||
.map(|dl| {
|
||||
(
|
||||
dl.line_idx,
|
||||
dl.line.clone(),
|
||||
dl.selection_col_from..dl.selection_col_to,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
let mut surface = self.surface.borrow_mut();
|
||||
let seq = surface.current_seqno();
|
||||
surface.flush_changes_older_than(seq);
|
||||
surface
|
||||
.screen_lines()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, line)| (idx, line, 0..0))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn has_dirty_lines(&self) -> bool {
|
||||
if self.poll().is_err() {
|
||||
*self.dead.borrow_mut() = true;
|
||||
}
|
||||
|
||||
let coarse = self.coarse.borrow();
|
||||
if let Some(coarse) = coarse.as_ref() {
|
||||
!coarse.dirty_lines.is_empty()
|
||||
} else {
|
||||
false
|
||||
}
|
||||
self.surface
|
||||
.borrow()
|
||||
.has_changes(*self.local_sequence.borrow())
|
||||
}
|
||||
|
||||
fn make_all_lines_dirty(&mut self) {
|
||||
*self.dirty_all.borrow_mut() = true;
|
||||
}
|
||||
fn make_all_lines_dirty(&mut self) {}
|
||||
|
||||
fn clean_dirty_lines(&mut self) {
|
||||
if let Some(c) = self.coarse.borrow_mut().as_mut() {
|
||||
c.dirty_lines.clear()
|
||||
}
|
||||
}
|
||||
fn clean_dirty_lines(&mut self) {}
|
||||
|
||||
fn current_highlight(&self) -> Option<Arc<Hyperlink>> {
|
||||
let coarse = self.coarse.borrow();
|
||||
coarse
|
||||
.as_ref()
|
||||
.and_then(|coarse| coarse.current_highlight.clone())
|
||||
None
|
||||
}
|
||||
|
||||
fn physical_dimensions(&self) -> (usize, usize) {
|
||||
let coarse = self.coarse.borrow();
|
||||
if let Some(coarse) = coarse.as_ref() {
|
||||
(coarse.physical_rows, coarse.physical_cols)
|
||||
} else {
|
||||
(24, 80)
|
||||
}
|
||||
let (cols, rows) = self.surface.borrow().dimensions();
|
||||
(rows, cols)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -649,6 +649,17 @@ impl TerminfoRenderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Change::Title(_text) => {
|
||||
// Don't actually render this for now.
|
||||
// The primary purpose of Change::Title at the time of
|
||||
// writing is to transfer tab titles across domains
|
||||
// in the wezterm multiplexer model. It's not clear
|
||||
// that it would be a good idea to unilaterally output
|
||||
// eg: a title change escape sequence here in the
|
||||
// renderer because we might be composing multiple widgets
|
||||
// together, each with its own title.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -316,6 +316,16 @@ impl WindowsConsoleRenderer {
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Change::Title(_text) => {
|
||||
// Don't actually render this for now.
|
||||
// The primary purpose of Change::Title at the time of
|
||||
// writing is to transfer tab titles across domains
|
||||
// in the wezterm multiplexer model. It's not clear
|
||||
// that it would be a good idea to unilaterally output
|
||||
// eg: a title change escape sequence here in the
|
||||
// renderer because we might be composing multiple widgets
|
||||
// together, each with its own title.
|
||||
}
|
||||
}
|
||||
}
|
||||
out.flush()?;
|
||||
|
||||
@@ -82,6 +82,9 @@ pub enum Change {
|
||||
region_size: usize,
|
||||
scroll_count: usize,
|
||||
},
|
||||
/// Change the title of the window in which the surface will be
|
||||
/// rendered.
|
||||
Title(String),
|
||||
}
|
||||
|
||||
impl Change {
|
||||
|
||||
@@ -87,6 +87,7 @@ pub struct Surface {
|
||||
changes: Vec<Change>,
|
||||
cursor_shape: CursorShape,
|
||||
cursor_color: ColorAttribute,
|
||||
title: String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -180,6 +181,10 @@ impl Surface {
|
||||
(self.xpos, self.ypos)
|
||||
}
|
||||
|
||||
pub fn title(&self) -> &str {
|
||||
&self.title
|
||||
}
|
||||
|
||||
/// Resize the Surface to the specified width and height.
|
||||
/// If the width and/or height are smaller than previously, the rows and/or
|
||||
/// columns are truncated. If the width and/or height are larger than
|
||||
@@ -252,6 +257,7 @@ impl Surface {
|
||||
Change::CursorColor(color) => self.cursor_color = *color,
|
||||
Change::CursorShape(shape) => self.cursor_shape = *shape,
|
||||
Change::Image(image) => self.add_image(image),
|
||||
Change::Title(text) => self.title = text.to_owned(),
|
||||
Change::ScrollRegionUp {
|
||||
first_row,
|
||||
region_size,
|
||||
@@ -479,6 +485,10 @@ impl Surface {
|
||||
lines
|
||||
}
|
||||
|
||||
pub fn screen_lines(&self) -> Vec<Line> {
|
||||
self.lines.clone()
|
||||
}
|
||||
|
||||
/// Returns a stream of changes suitable to update the screen
|
||||
/// to match the model. The input `seq` argument should be 0
|
||||
/// on the first call, or in any situation where the screen
|
||||
@@ -510,6 +520,14 @@ impl Surface {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_changes(&self, seq: SequenceNo) -> bool {
|
||||
self.seqno != seq
|
||||
}
|
||||
|
||||
pub fn current_seqno(&self) -> SequenceNo {
|
||||
self.seqno
|
||||
}
|
||||
|
||||
/// After having called `get_changes` and processed the resultant
|
||||
/// change stream, the caller can then pass the returned `SequenceNo`
|
||||
/// value to this call to prune the list of changes and free up
|
||||
@@ -538,6 +556,10 @@ impl Surface {
|
||||
result.push(Change::CursorShape(CursorShape::Hidden));
|
||||
result.push(Change::ClearScreen(Default::default()));
|
||||
|
||||
if !self.title.is_empty() {
|
||||
result.push(Change::Title(self.title.to_owned()));
|
||||
}
|
||||
|
||||
let mut attr = CellAttributes::default();
|
||||
|
||||
let crlf = Change::CursorPosition {
|
||||
@@ -734,6 +756,18 @@ impl Surface {
|
||||
diff_state.changes
|
||||
}
|
||||
|
||||
pub fn diff_against_numbered_line(&self, row_num: usize, other_line: &Line) -> Vec<Change> {
|
||||
let mut diff_state = DiffState::default();
|
||||
if let Some(line) = self.lines.get(row_num) {
|
||||
for ((col_num, cell), (_, other_cell)) in
|
||||
line.visible_cells().zip(other_line.visible_cells())
|
||||
{
|
||||
diff_state.diff_cells(col_num, row_num, cell, other_cell);
|
||||
}
|
||||
}
|
||||
diff_state.changes
|
||||
}
|
||||
|
||||
/// Computes the change stream required to make `self` have the same
|
||||
/// screen contents as `other`.
|
||||
pub fn diff_screens(&self, other: &Surface) -> Vec<Change> {
|
||||
|
||||
Reference in new issue
Block a user