Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

Move the protocol's data types into thinkterm-proto

RoversX17a3a883da15
diff --git a/Cargo.lock b/Cargo.lock
index d40a969d..d9adf55f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -856,18 +856,17 @@ dependencies = [
"anyhow",
"base91",
"chrono",
- "config",
"futures-lite",
"leb128",
"log",
"metrics",
- "mux",
"portable-pty",
"rangeset",
"ruzstd",
"serde",
"serde_json",
"termwiz 0.24.0",
+ "thinkterm-proto",
"thiserror 1.0.69",
"varbincode",
"wezterm-term",
@@ -988,6 +987,7 @@ dependencies = [
"smol",
"tempfile",
"termwiz 0.24.0",
+ "thinkterm-proto",
"toml 0.8.23",
"umask",
"wezterm-bidi 0.2.3",
@@ -3814,6 +3814,7 @@ dependencies = [
"termwiz 0.24.0",
"termwiz-funcs",
"textwrap",
+ "thinkterm-proto",
"thiserror 1.0.69",
"url",
"wezterm-dynamic 0.2.1",
@@ -6432,6 +6433,21 @@ dependencies = [
"tempfile",
]
+[[package]]
+name = "thinkterm-proto"
+version = "0.1.0"
+dependencies = [
+ "bintree",
+ "chrono",
+ "luahelper",
+ "mlua",
+ "serde",
+ "termwiz 0.24.0",
+ "url",
+ "wezterm-dynamic 0.2.1",
+ "wezterm-term",
+]
+
[[package]]
name = "thinkterm-syntax"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 5b2b6d67..cc2cbfb2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -7,6 +7,7 @@ members = [
"sync-color-schemes",
"thinkterm-syntax",
"thinkterm-core",
+ "thinkterm-proto",
"thinkterm-tui",
"deps/cairo",
"wezterm",
@@ -74,6 +75,7 @@ color-funcs = { path = "lua-api-crates/color-funcs" }
colorgrad = "0.6"
config = { path = "config" }
thinkterm-core = { path = "thinkterm-core" }
+thinkterm-proto = { path = "thinkterm-proto" }
core-foundation = "=0.10.0"
core-graphics = "=0.24.0"
core-text = "=21.0.0"
diff --git a/codec/Cargo.toml b/codec/Cargo.toml
index 1e1ccf98..c2fa35fd 100644
--- a/codec/Cargo.toml
+++ b/codec/Cargo.toml
@@ -9,13 +9,12 @@ publish = false
[dependencies]
anyhow.workspace = true
-config.workspace = true
leb128.workspace = true
log.workspace = true
metrics.workspace = true
-mux.workspace = true
portable-pty = { workspace = true, features = ["serde_support"]}
rangeset.workspace = true
+thinkterm-proto.workspace = true
serde = {workspace=true, features = ["rc", "derive"]}
futures-lite.workspace = true
termwiz.workspace = true
diff --git a/codec/src/lib.rs b/codec/src/lib.rs
index 3e5cb5a6..f1793053 100644
--- a/codec/src/lib.rs
+++ b/codec/src/lib.rs
@@ -12,12 +12,10 @@
#![allow(clippy::range_plus_one)]
use anyhow::{Context as _, Error, bail};
-use config::keyassignment::{PaneDirection, ScrollbackEraseMode};
-use mux::client::{ClientId, ClientInfo};
-use mux::pane::PaneId;
-use mux::renderable::{RenderableDimensions, StableCursorPosition};
-use mux::tab::{PaneNode, SerdeUrl, SplitRequest, TabId};
-use mux::window::WindowId;
+use thinkterm_proto::{
+ ClientId, ClientInfo, PaneDirection, PaneId, PaneNode, RenderableDimensions,
+ ScrollbackEraseMode, SerdeUrl, SplitRequest, StableCursorPosition, TabId, WindowId,
+};
use portable_pty::CommandBuilder;
use rangeset::*;
use serde::{Deserialize, Serialize};
@@ -741,7 +739,7 @@ pub struct SplitPane {
pub split_request: SplitRequest,
pub command: Option<CommandBuilder>,
pub command_dir: Option<String>,
- pub domain: config::keyassignment::SpawnTabDomain,
+ pub domain: thinkterm_proto::SpawnTabDomain,
/// Instead of spawning a command, move the specified
/// pane into the new split target
pub move_pane_id: Option<PaneId>,
@@ -754,7 +752,7 @@ pub struct SpawnPaneInStack {
pub pane_id: PaneId,
pub command: Option<CommandBuilder>,
pub command_dir: Option<String>,
- pub domain: config::keyassignment::SpawnTabDomain,
+ pub domain: thinkterm_proto::SpawnTabDomain,
}
/// Make `pane_id` the visible pane of the stack that contains it.
@@ -788,7 +786,7 @@ pub struct MovePaneToNewTabResponse {
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SpawnV2 {
- pub domain: config::keyassignment::SpawnTabDomain,
+ pub domain: thinkterm_proto::SpawnTabDomain,
/// If None, create a new window for this new tab
pub window_id: Option<WindowId>,
pub command: Option<CommandBuilder>,
@@ -1500,14 +1498,14 @@ pub struct EraseScrollbackRequest {
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SearchScrollbackRequest {
pub pane_id: PaneId,
- pub pattern: mux::pane::Pattern,
+ pub pattern: thinkterm_proto::Pattern,
pub range: Range<StableRowIndex>,
pub limit: Option<u32>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
pub struct SearchScrollbackResponse {
- pub results: Vec<mux::pane::SearchResult>,
+ pub results: Vec<thinkterm_proto::SearchResult>,
}
#[derive(Deserialize, Serialize, PartialEq, Debug)]
@@ -1532,10 +1530,10 @@ mod golden {
//! without any error. These literals were captured before the move;
//! they must stay green, byte for byte, after it.
use super::*;
- use mux::client::{ClientId, ClientInfo};
- use mux::pane::Pattern;
- use mux::tab::{PaneEntry, PaneStackEntry, SplitDirection, SplitDirectionAndSize, SplitSize};
use std::sync::Arc;
+ use thinkterm_proto::{
+ PaneEntry, PaneStackEntry, Pattern, SplitDirection, SplitDirectionAndSize, SplitSize,
+ };
fn varbincode_bytes<T: serde::Serialize>(t: &T) -> Vec<u8> {
let mut buf = Vec::new();
@@ -1612,7 +1610,7 @@ mod golden {
},
command: None,
command_dir: Some("/home".to_string()),
- domain: config::keyassignment::SpawnTabDomain::DomainName("dom".to_string()),
+ domain: thinkterm_proto::SpawnTabDomain::DomainName("dom".to_string()),
move_pane_id: Some(2),
}
}
diff --git a/config/Cargo.toml b/config/Cargo.toml
index ce043e36..2afaa4de 100644
--- a/config/Cargo.toml
+++ b/config/Cargo.toml
@@ -35,6 +35,7 @@ serde_json.workspace = true
shlex.workspace = true
smol.workspace = true
termwiz = { workspace=true, features=["use_serde"] }
+thinkterm-proto.workspace = true
toml.workspace = true
umask.workspace = true
wezterm-bidi.workspace = true
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rs
index 01dac7d5..2dd71865 100644
--- a/config/src/keyassignment.rs
+++ b/config/src/keyassignment.rs
@@ -4,11 +4,10 @@ use crate::window::WindowLevel;
use luahelper::impl_lua_conversion_dynamic;
use ordered_float::NotNan;
use portable_pty::CommandBuilder;
-use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::path::PathBuf;
-use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value};
+use wezterm_dynamic::{FromDynamic, ToDynamic};
use wezterm_input_types::{KeyCode, Modifiers};
use wezterm_term::input::MouseButton;
use wezterm_term::SemanticType;
@@ -150,25 +149,9 @@ pub enum MouseEventTrigger {
Up { streak: usize, button: MouseButton },
}
-/// When spawning a tab, specify which domain should be used to
-/// host/spawn that tab.
-#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, FromDynamic, ToDynamic)]
-pub enum SpawnTabDomain {
- /// Use the default domain
- DefaultDomain,
- /// Use the domain from the current tab in the associated window
- CurrentPaneDomain,
- /// Use a specific domain by name
- DomainName(String),
- /// Use a specific domain by id
- DomainId(usize),
-}
-
-impl Default for SpawnTabDomain {
- fn default() -> Self {
- Self::CurrentPaneDomain
- }
-}
+// Moved to thinkterm-proto (it travels in spawn PDUs); re-exported so the
+// config::keyassignment::SpawnTabDomain path keeps resolving.
+pub use thinkterm_proto::SpawnTabDomain;
#[derive(Default, Clone, PartialEq, FromDynamic, ToDynamic)]
pub struct SpawnCommand {
@@ -266,46 +249,9 @@ impl SpawnCommand {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, FromDynamic, ToDynamic)]
-pub enum PaneDirection {
- Up,
- Down,
- Left,
- Right,
- Next,
- Prev,
-}
-
-impl PaneDirection {
- pub fn direction_from_str(arg: &str) -> Result<PaneDirection, String> {
- for candidate in PaneDirection::variants() {
- if candidate.to_lowercase() == arg.to_lowercase() {
- if let Ok(direction) = PaneDirection::from_dynamic(
- &Value::String(candidate.to_string()),
- FromDynamicOptions::default(),
- ) {
- return Ok(direction);
- }
- }
- }
- Err(format!(
- "invalid direction {arg}, possible values are {:?}",
- PaneDirection::variants()
- ))
- }
-}
-
-#[derive(Debug, Copy, Clone, PartialEq, Eq, FromDynamic, ToDynamic, Serialize, Deserialize)]
-pub enum ScrollbackEraseMode {
- ScrollbackOnly,
- ScrollbackAndViewport,
-}
-
-impl Default for ScrollbackEraseMode {
- fn default() -> Self {
- Self::ScrollbackOnly
- }
-}
+// Moved to thinkterm-proto (they travel in PDUs); re-exported so existing
+// config::keyassignment paths keep resolving.
+pub use thinkterm_proto::{PaneDirection, ScrollbackEraseMode};
#[derive(Debug, Clone, Copy, PartialEq, Eq, FromDynamic, ToDynamic)]
pub enum ClipboardCopyDestination {
diff --git a/mux/Cargo.toml b/mux/Cargo.toml
index 3aa00b58..f1619aed 100644
--- a/mux/Cargo.toml
+++ b/mux/Cargo.toml
@@ -43,6 +43,7 @@ terminfo.workspace = true
termwiz-funcs.workspace = true
termwiz.workspace = true
textwrap.workspace = true
+thinkterm-proto = { workspace = true, features = ["lua"] }
thiserror.workspace = true
url.workspace = true
wezterm-dynamic.workspace = true
diff --git a/mux/src/client.rs b/mux/src/client.rs
index 4c35be9b..7b15245a 100644
--- a/mux/src/client.rs
+++ b/mux/src/client.rs
@@ -1,11 +1,11 @@
-use crate::PaneId;
-use chrono::serde::ts_seconds;
-use chrono::{DateTime, Utc};
-use serde::*;
use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
use std::time::SystemTime;
+// The types moved to thinkterm-proto (they travel on the wire); this module
+// keeps the process-facing constructor, which needs hostname, getpid and the
+// ssh agent proxy -- none of which belong in the wire crate.
+pub use thinkterm_proto::{ClientId, ClientInfo};
+
static CLIENT_ID: AtomicUsize = AtomicUsize::new(0);
lazy_static::lazy_static! {
static ref EPOCH: u64 = SystemTime::now()
@@ -13,106 +13,22 @@ lazy_static::lazy_static! {
.unwrap().as_secs();
}
-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
-pub struct ClientId {
- pub hostname: String,
- pub username: String,
- pub pid: u32,
- pub epoch: u64,
- pub id: usize,
- pub ssh_auth_sock: Option<String>,
-}
-
-impl ClientId {
- pub fn new() -> Self {
- let id = CLIENT_ID.fetch_add(1, Ordering::Relaxed);
- Self {
- hostname: hostname::get()
- .map(|s| s.to_string_lossy().to_string())
- .unwrap_or_else(|_| "localhost".to_string()),
- username: config::username_from_env().unwrap_or_else(|_| "somebody".to_string()),
- pid: unsafe { libc::getpid() as u32 },
- epoch: *EPOCH,
- id,
- ssh_auth_sock: crate::AgentProxy::default_ssh_auth_sock(),
- }
- }
-
- /// Whether two ids describe the same logical client, allowing for the
- /// transport-only decoration applied by an SSH mux proxy.
- ///
- /// The server appends ` (via proxy pid N)` to the hostname and replaces
- /// `ssh_auth_sock` so that `list-clients` can explain the route. Neither
- /// change should make the originating renderer stop recognizing itself.
- pub fn same_logical_client(&self, other: &Self) -> bool {
- proxy_hostname_base(&self.hostname) == proxy_hostname_base(&other.hostname)
- && self.username == other.username
- && self.pid == other.pid
- && self.epoch == other.epoch
- && self.id == other.id
- }
-}
-
-fn proxy_hostname_base(hostname: &str) -> &str {
- const PREFIX: &str = " (via proxy pid ";
-
- let Some((base, suffix)) = hostname.rsplit_once(PREFIX) else {
- return hostname;
- };
- let Some(pid) = suffix.strip_suffix(')') else {
- return hostname;
- };
- if !pid.is_empty() && pid.bytes().all(|byte| byte.is_ascii_digit()) {
- base
- } else {
- hostname
+/// Identify this process as a client. Formerly `ClientId::new()`; it cannot
+/// live on the type any more because the type moved out of this crate.
+pub fn generate_client_id() -> ClientId {
+ let id = CLIENT_ID.fetch_add(1, Ordering::Relaxed);
+ ClientId {
+ hostname: hostname::get()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|_| "localhost".to_string()),
+ username: config::username_from_env().unwrap_or_else(|_| "somebody".to_string()),
+ pid: unsafe { libc::getpid() as u32 },
+ epoch: *EPOCH,
+ id,
+ ssh_auth_sock: crate::AgentProxy::default_ssh_auth_sock(),
}
}
-#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
-pub struct ClientInfo {
- pub client_id: Arc<ClientId>,
- /// The time this client last connected
- #[serde(with = "ts_seconds")]
- pub connected_at: DateTime<Utc>,
- /// Which workspace is active
- pub active_workspace: Option<String>,
- /// The last time we received input from this client
- #[serde(with = "ts_seconds")]
- pub last_input: DateTime<Utc>,
- /// The currently-focused pane
- pub focused_pane_id: Option<PaneId>,
-}
-
-impl ClientInfo {
- pub fn new(client_id: Arc<ClientId>) -> Self {
- let now = utc_now();
- Self {
- client_id,
- connected_at: now,
- active_workspace: None,
- last_input: now,
- focused_pane_id: None,
- }
- }
-
- pub fn update_last_input(&mut self) {
- self.last_input = utc_now();
- }
-
- pub fn update_focused_pane(&mut self, pane_id: PaneId) {
- self.focused_pane_id.replace(pane_id);
- }
-}
-
-fn utc_now() -> DateTime<Utc> {
- let duration = SystemTime::now()
- .duration_since(SystemTime::UNIX_EPOCH)
- .unwrap_or_default();
- DateTime::<Utc>::from_timestamp(duration.as_secs() as i64, duration.subsec_nanos())
- .expect("system time should fit chrono timestamp range")
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/mux/src/pane.rs b/mux/src/pane.rs
index ebf82520..ebb7c7a4 100644
--- a/mux/src/pane.rs
+++ b/mux/src/pane.rs
@@ -22,7 +22,7 @@ use wezterm_term::{
};
static PANE_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
-pub type PaneId = usize;
+pub use thinkterm_proto::{PaneId, Pattern, SearchResult};
pub fn alloc_pane_id() -> PaneId {
PANE_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
@@ -107,52 +107,8 @@ pub enum PerformAssignmentResult {
BlockAssignmentAndRouteToKeyDown,
}
-#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
-pub struct SearchResult {
- pub start_y: StableRowIndex,
- /// The cell index into the line of the start of the match
- pub start_x: usize,
- pub end_y: StableRowIndex,
- /// The cell index into the line of the end of the match
- pub end_x: usize,
- /// An identifier that can be used to group results that have
- /// the same textual content
- pub match_id: usize,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
-pub enum Pattern {
- CaseSensitiveString(String),
- CaseInSensitiveString(String),
- Regex(String),
-}
-
-impl Default for Pattern {
- fn default() -> Self {
- Self::CaseSensitiveString("".to_string())
- }
-}
-
-impl std::ops::Deref for Pattern {
- type Target = String;
- fn deref(&self) -> &String {
- match self {
- Pattern::CaseSensitiveString(s) => s,
- Pattern::CaseInSensitiveString(s) => s,
- Pattern::Regex(s) => s,
- }
- }
-}
-
-impl std::ops::DerefMut for Pattern {
- fn deref_mut(&mut self) -> &mut String {
- match self {
- Pattern::CaseSensitiveString(s) => s,
- Pattern::CaseInSensitiveString(s) => s,
- Pattern::Regex(s) => s,
- }
- }
-}
+// SearchResult and Pattern moved to thinkterm-proto; re-exported at the top
+// of this module. PatternType stays: it is not a wire type.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub enum PatternType {
diff --git a/mux/src/renderable.rs b/mux/src/renderable.rs
index 94a2faca..af0ab65b 100644
--- a/mux/src/renderable.rs
+++ b/mux/src/renderable.rs
@@ -1,51 +1,13 @@
use crate::pane::{ForEachPaneLogicalLine, WithPaneLines};
-use luahelper::impl_lua_conversion_dynamic;
use rangeset::RangeSet;
-use serde::{Deserialize, Serialize};
use std::ops::Range;
use termwiz::surface::SequenceNo;
-use wezterm_dynamic::{FromDynamic, ToDynamic};
use wezterm_term::{Line, StableRowIndex, Terminal};
-/// Describes the location of the cursor
-#[derive(
- Debug, Default, Copy, Clone, Hash, Eq, PartialEq, Deserialize, Serialize, FromDynamic, ToDynamic,
-)]
-pub struct StableCursorPosition {
- pub x: usize,
- pub y: StableRowIndex,
- pub shape: termwiz::surface::CursorShape,
- pub visibility: termwiz::surface::CursorVisibility,
-}
-impl_lua_conversion_dynamic!(StableCursorPosition);
-
-#[derive(
- Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize, FromDynamic, ToDynamic,
-)]
-pub struct RenderableDimensions {
- /// The viewport width
- pub cols: usize,
- /// How many rows fit in the viewport
- pub viewport_rows: usize,
- /// The total number of lines in the scrollback, including the viewport
- pub scrollback_rows: usize,
-
- /// The top of the physical, non-scrollback, screen expressed
- /// as a stable index. It is envisioned that this will be used
- /// to compute row/cols for mouse events and to produce a range
- /// for the `get_lines` call when the scroll position is at the
- /// bottom of the screen.
- pub physical_top: StableRowIndex,
- /// The top of the scrollback (the earliest row we remember)
- /// expressed as a stable index.
- pub scrollback_top: StableRowIndex,
- pub dpi: u32,
- pub pixel_width: usize,
- pub pixel_height: usize,
- /// True if the lines should be rendered reversed
- pub reverse_video: bool,
-}
-impl_lua_conversion_dynamic!(RenderableDimensions);
+// Moved to thinkterm-proto together with their lua conversions (which the
+// orphan rule ties to the defining crate; mux enables proto's `lua` feature
+// to keep them).
+pub use thinkterm_proto::{RenderableDimensions, StableCursorPosition};
/// Implements Pane::get_cursor_position for Terminal
pub fn terminal_get_cursor_position(term: &mut Terminal) -> StableCursorPosition {
diff --git a/mux/src/tab.rs b/mux/src/tab.rs
index 03557e59..8bc688f2 100644
--- a/mux/src/tab.rs
+++ b/mux/src/tab.rs
@@ -1,18 +1,15 @@
use crate::domain::DomainId;
use crate::pane::*;
-use crate::renderable::StableCursorPosition;
use crate::{Mux, MuxNotification, WindowId};
use bintree::PathBranch;
use config::configuration;
use config::keyassignment::PaneDirection;
use parking_lot::Mutex;
use rangeset::intersects_range;
-use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::TryInto;
use std::sync::Arc;
-use url::Url;
-use wezterm_term::{StableRowIndex, TerminalSize};
+use wezterm_term::TerminalSize;
pub type PaneStackId = usize;
pub type Tree = bintree::Tree<PaneStack, SplitDirectionAndSize>;
@@ -27,7 +24,7 @@ static PANE_STACK_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::At
pub fn alloc_pane_stack_id() -> PaneStackId {
PANE_STACK_ID.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
}
-pub type TabId = usize;
+pub use thinkterm_proto::TabId;
#[derive(Default)]
struct Recency {
@@ -292,102 +289,12 @@ impl std::fmt::Debug for PositionedPane {
}
}
-#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
-pub enum SplitDirection {
- Horizontal,
- Vertical,
-}
-
-/// The size is of the (first, second) child of the split
-#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
-pub struct SplitDirectionAndSize {
- pub direction: SplitDirection,
- pub first: TerminalSize,
- pub second: TerminalSize,
-}
-
-#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
-pub enum SplitSize {
- Cells(usize),
- Percent(u8),
-}
-
-impl Default for SplitSize {
- fn default() -> Self {
- Self::Percent(50)
- }
-}
-
-#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
-pub struct SplitRequest {
- pub direction: SplitDirection,
- /// Whether the newly created item will be in the second part
- /// of the split (right/bottom)
- pub target_is_second: bool,
- /// Split across the top of the tab rather than the active pane
- pub top_level: bool,
- /// The size of the new item
- pub size: SplitSize,
-}
-
-impl Default for SplitRequest {
- fn default() -> Self {
- Self {
- direction: SplitDirection::Horizontal,
- target_is_second: true,
- top_level: false,
- size: SplitSize::default(),
- }
- }
-}
-
-impl SplitDirectionAndSize {
- fn top_of_second(&self) -> usize {
- match self.direction {
- SplitDirection::Horizontal => 0,
- SplitDirection::Vertical => self.first.rows as usize + 1,
- }
- }
-
- fn left_of_second(&self) -> usize {
- match self.direction {
- SplitDirection::Horizontal => self.first.cols as usize + 1,
- SplitDirection::Vertical => 0,
- }
- }
-
- pub fn width(&self) -> usize {
- if self.direction == SplitDirection::Horizontal {
- self.first.cols + self.second.cols + 1
- } else {
- self.first.cols
- }
- }
-
- pub fn height(&self) -> usize {
- if self.direction == SplitDirection::Vertical {
- self.first.rows + self.second.rows + 1
- } else {
- self.first.rows
- }
- }
-
- pub fn size(&self) -> TerminalSize {
- let cell_width = self.first.pixel_width / self.first.cols;
- let cell_height = self.first.pixel_height / self.first.rows;
-
- let rows = self.height();
- let cols = self.width();
-
- TerminalSize {
- rows,
- cols,
- pixel_height: cell_height * rows,
- pixel_width: cell_width * cols,
- dpi: self.first.dpi,
- }
- }
-}
+// Moved to thinkterm-proto (the wire crate); re-exported here so the
+// `mux::tab::*` paths used across the tree keep resolving.
+pub use thinkterm_proto::{
+ PaneEntry, PaneNode, PaneStackEntry, SerdeUrl, SplitDirection, SplitDirectionAndSize,
+ SplitRequest, SplitSize,
+};
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct PositionedSplit {
@@ -3783,144 +3690,8 @@ impl TabInner {
}
}
-/// This type is used directly by the codec, take care to bump
-/// the codec version if you change this
-#[derive(Deserialize, Serialize, PartialEq, Debug)]
-pub enum PaneNode {
- Empty,
- Split {
- left: Box<PaneNode>,
- right: Box<PaneNode>,
- node: SplitDirectionAndSize,
- },
- Leaf(PaneEntry),
- Stack(PaneStackEntry),
-}
-
-impl PaneNode {
- pub fn into_tree(self) -> bintree::Tree<PaneStackEntry, SplitDirectionAndSize> {
- match self {
- PaneNode::Empty => bintree::Tree::Empty,
- PaneNode::Split { left, right, node } => bintree::Tree::Node {
- left: Box::new((*left).into_tree()),
- right: Box::new((*right).into_tree()),
- data: Some(node),
- },
- PaneNode::Leaf(e) => bintree::Tree::Leaf(PaneStackEntry {
- active: 0,
- panes: vec![e],
- pane_stack_id: None,
- }),
- PaneNode::Stack(stack) => bintree::Tree::Leaf(stack),
- }
- }
-
- pub fn root_size(&self) -> Option<TerminalSize> {
- match self {
- PaneNode::Empty => None,
- PaneNode::Split { node, .. } => Some(node.size()),
- PaneNode::Leaf(entry) => Some(entry.size),
- PaneNode::Stack(stack) => stack
- .panes
- .get(stack.active)
- .or_else(|| stack.panes.first())
- .map(|entry| entry.size),
- }
- }
-
- pub fn window_and_tab_ids(&self) -> Option<(WindowId, TabId)> {
- match self {
- PaneNode::Empty => None,
- PaneNode::Split { left, right, .. } => match left.window_and_tab_ids() {
- Some(res) => Some(res),
- None => right.window_and_tab_ids(),
- },
- PaneNode::Leaf(entry) => Some((entry.window_id, entry.tab_id)),
- PaneNode::Stack(stack) => stack
- .panes
- .get(stack.active)
- .or_else(|| stack.panes.first())
- .map(|entry| (entry.window_id, entry.tab_id)),
- }
- }
-}
-
-/// This type is used directly by the codec, take care to bump
-/// the codec version if you change this
-#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
-pub struct PaneStackEntry {
- pub active: usize,
- pub panes: Vec<PaneEntry>,
- /// Stable identity of the stack on the side that owns it (the mux
- /// server). Clients translate this to a stable local id so that GUI
- /// state keyed by stack id survives resyncs. Optional for backwards
- /// compatibility with older layout snapshots.
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub pane_stack_id: Option<usize>,
-}
-
-/// This type is used directly by the codec, take care to bump
-/// the codec version if you change this
-#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
-pub struct PaneEntry {
- pub window_id: WindowId,
- pub tab_id: TabId,
- pub pane_id: PaneId,
- pub title: String,
- pub size: TerminalSize,
- pub working_dir: Option<SerdeUrl>,
- pub is_active_pane: bool,
- pub is_zoomed_pane: bool,
- /// Whether the pane is showing the alternate screen. Carried here as well
- /// as in render changes so that a renderer knows it the moment it learns
- /// the pane exists, rather than only once something in it next changes.
- ///
- /// Defaulted for the same reason as `PaneStackEntry::pane_stack_id`: this
- /// type is the on-disk format of a Thread's saved layout, and every
- /// snapshot written before the field existed omits it. Without a default,
- /// adding it made all of them fail to decode, which meant every Thread
- /// opened as a single empty pane and then overwrote its own saved layout.
- #[serde(default)]
- pub alt_screen: bool,
- pub workspace: String,
- pub cursor_pos: StableCursorPosition,
- pub physical_top: StableRowIndex,
- pub top_row: usize,
- pub left_col: usize,
- pub tty_name: Option<String>,
-}
-
-#[derive(Deserialize, Clone, Serialize, PartialEq, Debug)]
-#[serde(try_from = "String", into = "String")]
-pub struct SerdeUrl {
- pub url: Url,
-}
-
-impl std::convert::TryFrom<String> for SerdeUrl {
- type Error = url::ParseError;
- fn try_from(s: String) -> Result<SerdeUrl, url::ParseError> {
- let url = Url::parse(&s)?;
- Ok(SerdeUrl { url })
- }
-}
-
-impl From<Url> for SerdeUrl {
- fn from(url: Url) -> SerdeUrl {
- SerdeUrl { url }
- }
-}
-
-impl Into<Url> for SerdeUrl {
- fn into(self) -> Url {
- self.url
- }
-}
-
-impl Into<String> for SerdeUrl {
- fn into(self) -> String {
- self.url.as_str().into()
- }
-}
+// PaneNode, PaneStackEntry, PaneEntry and SerdeUrl moved to
+// thinkterm-proto; re-exported above so mux::tab::* paths keep working.
#[cfg(test)]
mod test {
@@ -4569,7 +4340,7 @@ mod test {
let tab_size = test_size();
let mux = Mux::get();
let (tab, first, second) = split_tab_for_viewport(tab_size);
- let client = crate::client::ClientId::new();
+ let client = crate::client::generate_client_id();
let before_layout = tab
.iter_panes()
.into_iter()
diff --git a/mux/src/window.rs b/mux/src/window.rs
index c802381a..b4aab4f1 100644
--- a/mux/src/window.rs
+++ b/mux/src/window.rs
@@ -6,7 +6,7 @@ use std::collections::BTreeSet;
use std::sync::Arc;
static WIN_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::AtomicUsize::new(0);
-pub type WindowId = usize;
+pub use thinkterm_proto::WindowId;
pub type WindowUiSurfaceId = String;
pub struct Window {
diff --git a/thinkterm-proto/Cargo.toml b/thinkterm-proto/Cargo.toml
new file mode 100644
index 00000000..b686ccd7
--- /dev/null
+++ b/thinkterm-proto/Cargo.toml
@@ -0,0 +1,36 @@
+[package]
+name = "thinkterm-proto"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# The pure-data types shared by the mux wire protocol (codec), the mux
+# server, and every client. This crate must always build for
+# wasm32-unknown-unknown; that constraint is what keeps a pure client
+# (web, mobile) able to speak the protocol. Do not add dependencies that
+# touch processes, files, sockets or threads.
+
+[dependencies]
+bintree.workspace = true
+chrono.workspace = true
+serde = { workspace = true, features = ["rc", "derive"] }
+termwiz = { workspace = true, features = ["use_serde"] }
+url.workspace = true
+wezterm-dynamic.workspace = true
+wezterm-term = { workspace = true, features = ["use_serde"] }
+
+# The lua conversions expand to mlua trait impls, which the orphan rule
+# forces into this crate. They ride behind a feature so that the wasm
+# build (codec and below) never sees vendored Lua.
+luahelper = { workspace = true, optional = true }
+mlua = { workspace = true, optional = true, features = [
+ "vendored",
+ "lua54",
+ "async",
+ "send",
+ "serialize",
+] }
+
+[features]
+default = []
+lua = ["dep:luahelper", "dep:mlua"]
diff --git a/thinkterm-proto/src/client.rs b/thinkterm-proto/src/client.rs
new file mode 100644
index 00000000..f4e3e6c9
--- /dev/null
+++ b/thinkterm-proto/src/client.rs
@@ -0,0 +1,100 @@
+use crate::PaneId;
+use chrono::serde::ts_seconds;
+use chrono::{DateTime, Utc};
+use serde::*;
+use std::sync::Arc;
+
+#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
+pub struct ClientId {
+ pub hostname: String,
+ pub username: String,
+ pub pid: u32,
+ pub epoch: u64,
+ pub id: usize,
+ pub ssh_auth_sock: Option<String>,
+}
+
+impl ClientId {
+ // The constructor that fills these fields in from the running process
+ // lives in mux (`mux::client::generate_client_id`); it needs hostname,
+ // getpid and the ssh agent proxy, none of which belong in a wire crate.
+
+ /// Whether two ids describe the same logical client, allowing for the
+ /// transport-only decoration applied by an SSH mux proxy.
+ ///
+ /// The server appends ` (via proxy pid N)` to the hostname and replaces
+ /// `ssh_auth_sock` so that `list-clients` can explain the route. Neither
+ /// change should make the originating renderer stop recognizing itself.
+ pub fn same_logical_client(&self, other: &Self) -> bool {
+ proxy_hostname_base(&self.hostname) == proxy_hostname_base(&other.hostname)
+ && self.username == other.username
+ && self.pid == other.pid
+ && self.epoch == other.epoch
+ && self.id == other.id
+ }
+}
+
+fn proxy_hostname_base(hostname: &str) -> &str {
+ const PREFIX: &str = " (via proxy pid ";
+
+ let Some((base, suffix)) = hostname.rsplit_once(PREFIX) else {
+ return hostname;
+ };
+ let Some(pid) = suffix.strip_suffix(')') else {
+ return hostname;
+ };
+ if !pid.is_empty() && pid.bytes().all(|byte| byte.is_ascii_digit()) {
+ base
+ } else {
+ hostname
+ }
+}
+
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct ClientInfo {
+ pub client_id: Arc<ClientId>,
+ /// The time this client last connected
+ #[serde(with = "ts_seconds")]
+ pub connected_at: DateTime<Utc>,
+ /// Which workspace is active
+ pub active_workspace: Option<String>,
+ /// The last time we received input from this client
+ #[serde(with = "ts_seconds")]
+ pub last_input: DateTime<Utc>,
+ /// The currently-focused pane
+ pub focused_pane_id: Option<PaneId>,
+}
+
+// The methods that stamp the current time are only meaningful on the side
+// that owns the session (the server); SystemTime::now panics on
+// wasm32-unknown-unknown, and a pure client only ever receives ClientInfo.
+#[cfg(not(target_family = "wasm"))]
+impl ClientInfo {
+ pub fn new(client_id: Arc<ClientId>) -> Self {
+ let now = utc_now();
+ Self {
+ client_id,
+ connected_at: now,
+ active_workspace: None,
+ last_input: now,
+ focused_pane_id: None,
+ }
+ }
+
+ pub fn update_last_input(&mut self) {
+ self.last_input = utc_now();
+ }
+
+ pub fn update_focused_pane(&mut self, pane_id: PaneId) {
+ self.focused_pane_id.replace(pane_id);
+ }
+}
+
+#[cfg(not(target_family = "wasm"))]
+fn utc_now() -> DateTime<Utc> {
+ let duration = std::time::SystemTime::now()
+ .duration_since(std::time::SystemTime::UNIX_EPOCH)
+ .unwrap_or_default();
+ DateTime::<Utc>::from_timestamp(duration.as_secs() as i64, duration.subsec_nanos())
+ .expect("system time should fit chrono timestamp range")
+}
diff --git a/thinkterm-proto/src/keyassignment.rs b/thinkterm-proto/src/keyassignment.rs
new file mode 100644
index 00000000..95c5dbaf
--- /dev/null
+++ b/thinkterm-proto/src/keyassignment.rs
@@ -0,0 +1,63 @@
+use serde::{Deserialize, Serialize};
+use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value};
+
+/// When spawning a tab, specify which domain should be used to
+/// host/spawn that tab.
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, FromDynamic, ToDynamic)]
+pub enum SpawnTabDomain {
+ /// Use the default domain
+ DefaultDomain,
+ /// Use the domain from the current tab in the associated window
+ CurrentPaneDomain,
+ /// Use a specific domain by name
+ DomainName(String),
+ /// Use a specific domain by id
+ DomainId(usize),
+}
+
+impl Default for SpawnTabDomain {
+ fn default() -> Self {
+ Self::CurrentPaneDomain
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, FromDynamic, ToDynamic)]
+pub enum PaneDirection {
+ Up,
+ Down,
+ Left,
+ Right,
+ Next,
+ Prev,
+}
+
+impl PaneDirection {
+ pub fn direction_from_str(arg: &str) -> Result<PaneDirection, String> {
+ for candidate in PaneDirection::variants() {
+ if candidate.to_lowercase() == arg.to_lowercase() {
+ if let Ok(direction) = PaneDirection::from_dynamic(
+ &Value::String(candidate.to_string()),
+ FromDynamicOptions::default(),
+ ) {
+ return Ok(direction);
+ }
+ }
+ }
+ Err(format!(
+ "invalid direction {arg}, possible values are {:?}",
+ PaneDirection::variants()
+ ))
+ }
+}
+
+#[derive(Debug, Copy, Clone, PartialEq, Eq, FromDynamic, ToDynamic, Serialize, Deserialize)]
+pub enum ScrollbackEraseMode {
+ ScrollbackOnly,
+ ScrollbackAndViewport,
+}
+
+impl Default for ScrollbackEraseMode {
+ fn default() -> Self {
+ Self::ScrollbackOnly
+ }
+}
diff --git a/thinkterm-proto/src/layout.rs b/thinkterm-proto/src/layout.rs
new file mode 100644
index 00000000..5ece154d
--- /dev/null
+++ b/thinkterm-proto/src/layout.rs
@@ -0,0 +1,146 @@
+use crate::split::SplitDirectionAndSize;
+use crate::{TabId, WindowId};
+use serde::{Deserialize, Serialize};
+use url::Url;
+use wezterm_term::{StableRowIndex, TerminalSize};
+
+use crate::renderable::StableCursorPosition;
+
+/// This type is used directly by the codec, take care to bump
+/// the codec version if you change this
+#[derive(Deserialize, Serialize, PartialEq, Debug)]
+pub enum PaneNode {
+ Empty,
+ Split {
+ left: Box<PaneNode>,
+ right: Box<PaneNode>,
+ node: SplitDirectionAndSize,
+ },
+ Leaf(PaneEntry),
+ Stack(PaneStackEntry),
+}
+
+impl PaneNode {
+ pub fn into_tree(self) -> bintree::Tree<PaneStackEntry, SplitDirectionAndSize> {
+ match self {
+ PaneNode::Empty => bintree::Tree::Empty,
+ PaneNode::Split { left, right, node } => bintree::Tree::Node {
+ left: Box::new((*left).into_tree()),
+ right: Box::new((*right).into_tree()),
+ data: Some(node),
+ },
+ PaneNode::Leaf(e) => bintree::Tree::Leaf(PaneStackEntry {
+ active: 0,
+ panes: vec![e],
+ pane_stack_id: None,
+ }),
+ PaneNode::Stack(stack) => bintree::Tree::Leaf(stack),
+ }
+ }
+
+ pub fn root_size(&self) -> Option<TerminalSize> {
+ match self {
+ PaneNode::Empty => None,
+ PaneNode::Split { node, .. } => Some(node.size()),
+ PaneNode::Leaf(entry) => Some(entry.size),
+ PaneNode::Stack(stack) => stack
+ .panes
+ .get(stack.active)
+ .or_else(|| stack.panes.first())
+ .map(|entry| entry.size),
+ }
+ }
+
+ pub fn window_and_tab_ids(&self) -> Option<(WindowId, TabId)> {
+ match self {
+ PaneNode::Empty => None,
+ PaneNode::Split { left, right, .. } => match left.window_and_tab_ids() {
+ Some(res) => Some(res),
+ None => right.window_and_tab_ids(),
+ },
+ PaneNode::Leaf(entry) => Some((entry.window_id, entry.tab_id)),
+ PaneNode::Stack(stack) => stack
+ .panes
+ .get(stack.active)
+ .or_else(|| stack.panes.first())
+ .map(|entry| (entry.window_id, entry.tab_id)),
+ }
+ }
+}
+
+/// This type is used directly by the codec, take care to bump
+/// the codec version if you change this
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct PaneStackEntry {
+ pub active: usize,
+ pub panes: Vec<PaneEntry>,
+ /// Stable identity of the stack on the side that owns it (the mux
+ /// server). Clients translate this to a stable local id so that GUI
+ /// state keyed by stack id survives resyncs. Optional for backwards
+ /// compatibility with older layout snapshots.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pane_stack_id: Option<usize>,
+}
+
+/// This type is used directly by the codec, take care to bump
+/// the codec version if you change this
+#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
+pub struct PaneEntry {
+ pub window_id: WindowId,
+ pub tab_id: TabId,
+ pub pane_id: crate::PaneId,
+ pub title: String,
+ pub size: TerminalSize,
+ pub working_dir: Option<SerdeUrl>,
+ pub is_active_pane: bool,
+ pub is_zoomed_pane: bool,
+ /// Whether the pane is showing the alternate screen. Carried here as well
+ /// as in render changes so that a renderer knows it the moment it learns
+ /// the pane exists, rather than only once something in it next changes.
+ ///
+ /// Defaulted for the same reason as `PaneStackEntry::pane_stack_id`: this
+ /// type is the on-disk format of a Thread's saved layout, and every
+ /// snapshot written before the field existed omits it. Without a default,
+ /// adding it made all of them fail to decode, which meant every Thread
+ /// opened as a single empty pane and then overwrote its own saved layout.
+ #[serde(default)]
+ pub alt_screen: bool,
+ pub workspace: String,
+ pub cursor_pos: StableCursorPosition,
+ pub physical_top: StableRowIndex,
+ pub top_row: usize,
+ pub left_col: usize,
+ pub tty_name: Option<String>,
+}
+
+#[derive(Deserialize, Clone, Serialize, PartialEq, Debug)]
+#[serde(try_from = "String", into = "String")]
+pub struct SerdeUrl {
+ pub url: Url,
+}
+
+impl std::convert::TryFrom<String> for SerdeUrl {
+ type Error = url::ParseError;
+ fn try_from(s: String) -> Result<SerdeUrl, url::ParseError> {
+ let url = Url::parse(&s)?;
+ Ok(SerdeUrl { url })
+ }
+}
+
+impl From<Url> for SerdeUrl {
+ fn from(url: Url) -> SerdeUrl {
+ SerdeUrl { url }
+ }
+}
+
+impl Into<Url> for SerdeUrl {
+ fn into(self) -> Url {
+ self.url
+ }
+}
+
+impl Into<String> for SerdeUrl {
+ fn into(self) -> String {
+ self.url.as_str().into()
+ }
+}
diff --git a/thinkterm-proto/src/lib.rs b/thinkterm-proto/src/lib.rs
new file mode 100644
index 00000000..e182815c
--- /dev/null
+++ b/thinkterm-proto/src/lib.rs
@@ -0,0 +1,31 @@
+//! Pure-data types shared by the mux protocol (codec), the mux server and
+//! every client. Moved here verbatim from `mux` and `config`, which
+//! re-export them from their original paths, so the rest of the tree is
+//! unaffected by the move.
+//!
+//! Two encodings depend on these definitions staying put, and codec's
+//! `golden` test module pins both:
+//! * the wire: varbincode is positional, so **field order** is the contract;
+//! * saved Thread layouts: serde_json, so **field names** are the contract.
+//!
+//! The ids are `usize`. On the wire they travel as leb128 varints, so a
+//! 32-bit peer (wasm) caps out at `u32::MAX` of them per session — accepted
+//! deliberately; they are per-session counters and never get near that.
+
+pub mod client;
+pub mod keyassignment;
+pub mod layout;
+pub mod pane;
+pub mod renderable;
+pub mod split;
+
+pub use client::{ClientId, ClientInfo};
+pub use keyassignment::{PaneDirection, ScrollbackEraseMode, SpawnTabDomain};
+pub use layout::{PaneEntry, PaneNode, PaneStackEntry, SerdeUrl};
+pub use pane::{Pattern, SearchResult};
+pub use renderable::{RenderableDimensions, StableCursorPosition};
+pub use split::{SplitDirection, SplitDirectionAndSize, SplitRequest, SplitSize};
+
+pub type WindowId = usize;
+pub type TabId = usize;
+pub type PaneId = usize;
diff --git a/thinkterm-proto/src/pane.rs b/thinkterm-proto/src/pane.rs
new file mode 100644
index 00000000..da2e8553
--- /dev/null
+++ b/thinkterm-proto/src/pane.rs
@@ -0,0 +1,49 @@
+use serde::{Deserialize, Serialize};
+use wezterm_term::StableRowIndex;
+
+#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
+pub struct SearchResult {
+ pub start_y: StableRowIndex,
+ /// The cell index into the line of the start of the match
+ pub start_x: usize,
+ pub end_y: StableRowIndex,
+ /// The cell index into the line of the end of the match
+ pub end_x: usize,
+ /// An identifier that can be used to group results that have
+ /// the same textual content
+ pub match_id: usize,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
+pub enum Pattern {
+ CaseSensitiveString(String),
+ CaseInSensitiveString(String),
+ Regex(String),
+}
+
+impl Default for Pattern {
+ fn default() -> Self {
+ Self::CaseSensitiveString("".to_string())
+ }
+}
+
+impl std::ops::Deref for Pattern {
+ type Target = String;
+ fn deref(&self) -> &String {
+ match self {
+ Pattern::CaseSensitiveString(s) => s,
+ Pattern::CaseInSensitiveString(s) => s,
+ Pattern::Regex(s) => s,
+ }
+ }
+}
+
+impl std::ops::DerefMut for Pattern {
+ fn deref_mut(&mut self) -> &mut String {
+ match self {
+ Pattern::CaseSensitiveString(s) => s,
+ Pattern::CaseInSensitiveString(s) => s,
+ Pattern::Regex(s) => s,
+ }
+ }
+}
diff --git a/thinkterm-proto/src/renderable.rs b/thinkterm-proto/src/renderable.rs
new file mode 100644
index 00000000..65025a1e
--- /dev/null
+++ b/thinkterm-proto/src/renderable.rs
@@ -0,0 +1,49 @@
+#[cfg(feature = "lua")]
+use luahelper::impl_lua_conversion_dynamic;
+use serde::{Deserialize, Serialize};
+use wezterm_dynamic::{FromDynamic, ToDynamic};
+use wezterm_term::StableRowIndex;
+
+/// Describes the location of the cursor
+#[derive(
+ Debug, Default, Copy, Clone, Hash, Eq, PartialEq, Deserialize, Serialize, FromDynamic, ToDynamic,
+)]
+pub struct StableCursorPosition {
+ pub x: usize,
+ pub y: StableRowIndex,
+ pub shape: termwiz::surface::CursorShape,
+ pub visibility: termwiz::surface::CursorVisibility,
+}
+// The lua impls must live beside the type (orphan rule), but they must not
+// reach the wasm build, whose whole point is having no Lua underneath.
+#[cfg(feature = "lua")]
+impl_lua_conversion_dynamic!(StableCursorPosition);
+
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize, FromDynamic, ToDynamic,
+)]
+pub struct RenderableDimensions {
+ /// The viewport width
+ pub cols: usize,
+ /// How many rows fit in the viewport
+ pub viewport_rows: usize,
+ /// The total number of lines in the scrollback, including the viewport
+ pub scrollback_rows: usize,
+
+ /// The top of the physical, non-scrollback, screen expressed
+ /// as a stable index. It is envisioned that this will be used
+ /// to compute row/cols for mouse events and to produce a range
+ /// for the `get_lines` call when the scroll position is at the
+ /// bottom of the screen.
+ pub physical_top: StableRowIndex,
+ /// The top of the scrollback (the earliest row we remember)
+ /// expressed as a stable index.
+ pub scrollback_top: StableRowIndex,
+ pub dpi: u32,
+ pub pixel_width: usize,
+ pub pixel_height: usize,
+ /// True if the lines should be rendered reversed
+ pub reverse_video: bool,
+}
+#[cfg(feature = "lua")]
+impl_lua_conversion_dynamic!(RenderableDimensions);
diff --git a/thinkterm-proto/src/split.rs b/thinkterm-proto/src/split.rs
new file mode 100644
index 00000000..cfc4c43a
--- /dev/null
+++ b/thinkterm-proto/src/split.rs
@@ -0,0 +1,102 @@
+use serde::{Deserialize, Serialize};
+use wezterm_term::TerminalSize;
+
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
+pub enum SplitDirection {
+ Horizontal,
+ Vertical,
+}
+
+/// The size is of the (first, second) child of the split
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
+pub struct SplitDirectionAndSize {
+ pub direction: SplitDirection,
+ pub first: TerminalSize,
+ pub second: TerminalSize,
+}
+
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
+pub enum SplitSize {
+ Cells(usize),
+ Percent(u8),
+}
+
+impl Default for SplitSize {
+ fn default() -> Self {
+ Self::Percent(50)
+ }
+}
+
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
+pub struct SplitRequest {
+ pub direction: SplitDirection,
+ /// Whether the newly created item will be in the second part
+ /// of the split (right/bottom)
+ pub target_is_second: bool,
+ /// Split across the top of the tab rather than the active pane
+ pub top_level: bool,
+ /// The size of the new item
+ pub size: SplitSize,
+}
+
+impl Default for SplitRequest {
+ fn default() -> Self {
+ Self {
+ direction: SplitDirection::Horizontal,
+ target_is_second: true,
+ top_level: false,
+ size: SplitSize::default(),
+ }
+ }
+}
+
+impl SplitDirectionAndSize {
+ // top_of_second and left_of_second were private when this lived in
+ // mux::tab; they are pub only because mux still calls them from another
+ // crate now.
+ pub fn top_of_second(&self) -> usize {
+ match self.direction {
+ SplitDirection::Horizontal => 0,
+ SplitDirection::Vertical => self.first.rows as usize + 1,
+ }
+ }
+
+ pub fn left_of_second(&self) -> usize {
+ match self.direction {
+ SplitDirection::Horizontal => self.first.cols as usize + 1,
+ SplitDirection::Vertical => 0,
+ }
+ }
+
+ pub fn width(&self) -> usize {
+ if self.direction == SplitDirection::Horizontal {
+ self.first.cols + self.second.cols + 1
+ } else {
+ self.first.cols
+ }
+ }
+
+ pub fn height(&self) -> usize {
+ if self.direction == SplitDirection::Vertical {
+ self.first.rows + self.second.rows + 1
+ } else {
+ self.first.rows
+ }
+ }
+
+ pub fn size(&self) -> TerminalSize {
+ let cell_width = self.first.pixel_width / self.first.cols;
+ let cell_height = self.first.pixel_height / self.first.rows;
+
+ let rows = self.height();
+ let cols = self.width();
+
+ TerminalSize {
+ rows,
+ cols,
+ pixel_height: cell_height * rows,
+ pixel_width: cell_width * cols,
+ dpi: self.first.dpi,
+ }
+ }
+}
diff --git a/thinkterm-tui/src/lib.rs b/thinkterm-tui/src/lib.rs
index 2da1d484..ee0ef33e 100644
--- a/thinkterm-tui/src/lib.rs
+++ b/thinkterm-tui/src/lib.rs
@@ -16,7 +16,6 @@ use codec::{ClientViewport, FrontendAccessMode, ThinkTermSessionState};
use config::keyassignment::{PaneDirection, SpawnTabDomain};
use config::{ConfigHandle, SshMultiplexing};
use model::{AppModel, ThreadKey, TreeNodeKey};
-use mux::client::ClientId;
use mux::connui::ConnectionUI;
use mux::domain::{Domain, DomainState, SplitSource};
use mux::pane::{Pane, PaneId, Pattern};
@@ -569,7 +568,7 @@ async fn run_async(config: ConfigHandle, options: TuiOptions) -> Result<()> {
let connection_items = connection_catalog(&available, &catalog.local_domain_name);
let mux = Arc::new(Mux::new(None));
Mux::set_mux(&mux);
- let client_id = Arc::new(ClientId::new());
+ let client_id = Arc::new(mux::client::generate_client_id());
mux.register_client(Arc::clone(&client_id));
mux.replace_identity(Some(client_id));
diff --git a/wezterm-client/src/client.rs b/wezterm-client/src/client.rs
index 095dc4ab..667c0769 100644
--- a/wezterm-client/src/client.rs
+++ b/wezterm-client/src/client.rs
@@ -1503,7 +1503,7 @@ impl Client {
let is_reconnectable = reconnectable.reconnectable();
let is_local = reconnectable.is_local();
let (sender, mut receiver) = unbounded();
- let client_id = ClientId::new();
+ let client_id = mux::client::generate_client_id();
let connection_phase = Arc::new(AtomicU8::new(ClientConnectionPhase::Registering as u8));
let reader_connection_phase = Arc::clone(&connection_phase);
let (resume_reconnect_tx, resume_reconnect_rx) = channel::<()>();
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 1db8d643..9c559895 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -1085,7 +1085,7 @@ fn setup_mux(
) -> anyhow::Result<Arc<Mux>> {
let mux = Arc::new(mux::Mux::new(Some(local_domain.clone())));
Mux::set_mux(&mux);
- let client_id = Arc::new(mux::client::ClientId::new());
+ let client_id = Arc::new(mux::client::generate_client_id());
mux.register_client(client_id.clone());
mux.replace_identity(Some(client_id));
let default_workspace_name = default_workspace_name.unwrap_or(
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index b4f1913e..cb0acb34 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -1959,7 +1959,7 @@ mod tests {
.to_string();
assert!(missing_identity.contains("identified client"));
- let client = Arc::new(ClientId::new());
+ let client = Arc::new(mux::client::generate_client_id());
let missing_registration = claim_viewport_for_pane(&mux, Some(&client), None, usize::MAX)
.unwrap_err()
.to_string();
@@ -1978,7 +1978,7 @@ mod tests {
fn moved_pane_workspace_is_resolved_from_the_requesting_client() {
config::use_test_configuration();
let mux = Mux::new(None);
- let client = Arc::new(ClientId::new());
+ let client = Arc::new(mux::client::generate_client_id());
mux.register_client(Arc::clone(&client));
mux.set_active_workspace_for_client(&client, "space-2");
diff --git a/wezterm/src/cli/proxy.rs b/wezterm/src/cli/proxy.rs
index cbdc5c96..23d3884f 100644
--- a/wezterm/src/cli/proxy.rs
+++ b/wezterm/src/cli/proxy.rs
@@ -2,7 +2,6 @@ use clap::Parser;
use codec::{Pdu, SetClientId};
use config::ConfigHandle;
use mux::activity::Activity;
-use mux::client::ClientId;
use mux::Mux;
use std::io::{Read, Write};
use std::sync::Arc;
@@ -31,7 +30,7 @@ impl ProxyCommand {
let mut stream = unix_connect_with_retry(&target, false, None)?;
let pdu = Pdu::SetClientId(SetClientId {
- client_id: ClientId::new(),
+ client_id: mux::client::generate_client_id(),
is_proxy: true,
});
let serial = 1;