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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(mobile): publish views to the shell and draw tab icons
RoversX33775a35a0ad
diff --git a/Cargo.lock b/Cargo.lockindex 3e4a22fa..e7f895c7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8586,16 +8586,19 @@ dependencies = ["ndk-sys","rand_core 0.10.1","raw-window-handle",+ "resvg","ring","russh","serde","serde_json",+ "tempfile","termwiz 0.24.0","thinkterm-font-core","thinkterm-font-web","thinkterm-proto","thinkterm-render","thinkterm-session",+ "thinkterm-tab-icons","thinkterm-web","tokio","uniffi",diff --git a/thinkterm-mobile/Cargo.toml b/thinkterm-mobile/Cargo.tomlindex c0168aaa..cf4bba46 100644--- a/thinkterm-mobile/Cargo.toml+++ b/thinkterm-mobile/Cargo.toml@@ -28,6 +28,8 @@ russh = { version = "0.63.3", default-features = false, features = ["ring"] }# For making keys: ssh-key's generator wants a rand_core 0.10 RNG.rand_core = "0.10"ring = "0.17"+# The tab icon cards' glyphs, drawn into masks the shell tints.+resvg.workspace = trueserde.workspace = trueserde_json.workspace = truetermwiz = { workspace = true, features = ["use_serde"] }@@ -36,6 +38,7 @@ thinkterm-font-web.workspace = truethinkterm-proto.workspace = truethinkterm-render = { workspace = true, features = ["wgpu"] }thinkterm-session.workspace = true+thinkterm-tab-icons.workspace = truethinkterm-web.workspace = truetokio = { workspace = true, features = ["rt", "macros", "sync", "time", "net", "io-util"] }uniffi = { workspace = true, features = ["cli"] }@@ -49,3 +52,6 @@ wgpu.workspace = truejni-sys = "0.3"ndk-sys = "0.5"raw-window-handle.workspace = true++[dev-dependencies]+tempfile.workspace = truediff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rsindex 7746c066..cfb10155 100644--- a/thinkterm-mobile/src/core.rs+++ b/thinkterm-mobile/src/core.rs@@ -9,17 +9,20 @@//! futures and fires the App's timers itself. Nothing here waits on the//! shell.+use crate::icons;use crate::link::SshLink;use crate::painter::{GlyphPainter, GlyphSeams};use crate::platform::MobilePlatform;use crate::ssh::{Net, SshParams};-use crate::Notify;+use crate::{Notify, Published, ViewSet};use anyhow::{anyhow, Context, Result};use futures::executor::LocalPool;use futures::task::LocalSpawnExt;+use std::cell::Cell;use std::rc::Rc;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender};-use std::sync::Arc;+use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use thinkterm_font_core::FontShaper as _;use thinkterm_font_web::{Face, FontSet};@@ -35,6 +38,10 @@ use wezterm_term::KeyModifiers;pub type MobileApp = App<MobilePlatform, SshLink>;+/// The views are made again at most this often: a burst of output is+/// one publication per frame, not one per change.+const VIEWS_EVERY: Duration = Duration::from_millis(16);+pub struct ConnectParams {pub ssh: SshParams,pub font_paths: Vec<String>,@@ -145,6 +152,9 @@ pub enum Cmd {pane: usize,rows: usize,},+ ScreenPreview {+ pane: usize,+ },SelectedText {reply: Sender<Option<String>>,},@@ -153,6 +163,15 @@ pub enum Cmd {value: String,},SetPalette(Option<String>),+ SetShown(bool),+ /// The shell read `Core::views` for the first time.+ ViewsRead,+ WantScreen(bool),+ TextBetween {+ anchor: (usize, usize),+ head: (usize, usize),+ reply: Sender<Option<String>>,+ },}/// The surface currently lent, if any.@@ -225,23 +244,44 @@ struct State {settings: Vec<(String, String)>,/// The chosen scheme's colours as JSON, applied to every App made.palette: Option<String>,+ /// A scheme was chosen while the terminal was off screen or the link+ /// down, when the App tells the server nothing of it: told when it is+ /// shown again over a link that is up (`tell_palette`).+ palette_untold: bool,+ /// Where the views and rows go for the shell to read (`Core::views`).+ published: Arc<Mutex<Published>>,+ /// The shell reads the views there; until it does, none are made.+ views_read: Arc<AtomicBool>,+ /// Something the views show changed since they were last made.+ views_dirty: Rc<Cell<bool>>,+ /// The shell's text input reads the rows: keep them current.+ screen_wanted: bool,+ /// The tab icon cards on show, shared with the shell's thread, which+ /// draws them: the built-in ones, then the host's (`Net::TabIcons`).+ icons: Arc<icons::Shown>,+ /// The host (address, port, user) whose cards those are.+ icons_host: Option<(String, u16, String)>,+ /// A frame was painted since: the rows may have changed.+ screen_dirty: bool,+ /// The shell just asked for the rows: the next made go out as new.+ screen_fresh: bool,+ views_made: Instant,}-pub fn run(cmd_tx: Sender<Cmd>, rx: Receiver<Cmd>, notify: Box<dyn Notify>) {- let mut state = State::new(cmd_tx, notify);+pub fn run(+ cmd_tx: Sender<Cmd>,+ rx: Receiver<Cmd>,+ notify: Box<dyn Notify>,+ published: Arc<Mutex<Published>>,+ views_read: Arc<AtomicBool>,+ icons: Arc<icons::Shown>,+) {+ let mut state = State::new(cmd_tx, notify, published, views_read, icons);state.notify.on_log("core thread up".into());state.set_status("idle");loop {- let now = Instant::now();- let mut wait = Duration::from_secs(3600);- if state.animating && state.target.is_some() && state.app.is_none() {- wait = Duration::from_millis(100);- }- if let Some(due) = state.platform.next_deadline() {- wait = wait.min(due.saturating_duration_since(now));- }- match rx.recv_timeout(wait) {+ match rx.recv_timeout(state.wait(Instant::now())) {Ok(Cmd::Shutdown) | Err(RecvTimeoutError::Disconnected) => break,Ok(cmd) => state.handle(cmd),Err(RecvTimeoutError::Timeout) => {@@ -254,13 +294,20 @@ pub fn run(cmd_tx: Sender<Cmd>, rx: Receiver<Cmd>, notify: Box<dyn Notify>) {state.pool.run_until_stalled();state.platform.fire_due();state.pool.run_until_stalled();+ state.publish_views();}state.disconnect();state.notify.on_log("core thread down".into());}impl State {- fn new(cmd_tx: Sender<Cmd>, notify: Box<dyn Notify>) -> Self {+ fn new(+ cmd_tx: Sender<Cmd>,+ notify: Box<dyn Notify>,+ published: Arc<Mutex<Published>>,+ views_read: Arc<AtomicBool>,+ icons: Arc<icons::Shown>,+ ) -> Self {let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {#[cfg(target_vendor = "apple")]backends: wgpu::Backends::METAL,@@ -296,9 +343,109 @@ impl State {composing: false,settings: Vec::new(),palette: None,+ palette_untold: false,+ published,+ views_read,+ views_dirty: Rc::new(Cell::new(true)),+ screen_wanted: false,+ icons,+ icons_host: None,+ screen_dirty: false,+ screen_fresh: false,+ views_made: Instant::now(),}}+ /// How long the loop may sleep: until a timer is due, a frame of the+ /// idle drawing, or the views owed, which are owed only on show (off+ /// screen they wait, `publish_views`, and the loop with them).+ fn wait(&self, now: Instant) -> Duration {+ let mut wait = Duration::from_secs(3600);+ if self.animating && self.target.is_some() && self.app.is_none() {+ wait = Duration::from_millis(100);+ }+ if let Some(due) = self.platform.next_deadline() {+ wait = wait.min(due.saturating_duration_since(now));+ }+ let owed = self.views_dirty.get() || (self.screen_dirty && self.screen_wanted);+ if owed && self.platform.shown() {+ wait = wait.min((self.views_made + VIEWS_EVERY).saturating_duration_since(now));+ }+ wait+ }++ /// Hand the shell what changed, at most once a frame: the views after+ /// a change the App reported, the rows after a paint while they are+ /// wanted. Everything is made before the lock, which the shell takes+ /// every frame. Called between commands, never from inside the App,+ /// whose state the views borrow.+ fn publish_views(&mut self) {+ if !self.platform.shown() {+ // Nobody looks at a terminal off screen (the app in the back,+ // the hosts in front): what changed is made once it is back.+ return;+ }+ let views_dirty = self.views_dirty.get();+ if !self.screen_wanted {+ // Rows nobody reads are not made at each paint.+ self.screen_dirty = false;+ }+ if !views_dirty && !self.screen_dirty {+ return;+ }+ let now = Instant::now();+ if now < self.views_made + VIEWS_EVERY {+ return;+ }+ self.views_dirty.set(false);+ self.screen_dirty = false;+ self.views_made = now;+ let views = (views_dirty && self.views_read.load(Ordering::Relaxed)).then(|| self.view_set());+ // A change of view (another pane focused) changes the rows too.+ let rows = self.screen_wanted.then(|| self.screen_json());+ let fresh = std::mem::take(&mut self.screen_fresh);+ if let Ok(mut published) = self.published.lock() {+ if let Some(mut views) = views {+ views.revision = published.views.revision + 1;+ published.views = views;+ }+ if let Some(rows) = rows {+ if fresh || rows != published.screen {+ published.screen = rows;+ published.screen_revision += 1;+ }+ }+ }+ // Rows alone come without it: a shell that reads none (Android)+ // would otherwise pull every view at each paint.+ if views_dirty {+ self.notify.on_change();+ }+ }++ fn view_set(&self) -> ViewSet {+ ViewSet {+ revision: 0,+ connection: self.link_serial,+ tabs: self.view("tabs"),+ threads: self.view("threads"),+ tree: self.view("tree"),+ sidebar: self.view("sidebar"),+ navs: self.view("navs"),+ status: self.view("status"),+ layout: self.view("layout"),+ }+ }++ /// The focused pane's visible rows (`App::screen_text`) as JSON.+ fn screen_json(&self) -> String {+ self.app+ .as_ref()+ .and_then(|app| app.screen_text())+ .map(|t| json(&t))+ .unwrap_or_else(|| "null".into())+ }+fn handle(&mut self, cmd: Cmd) {match cmd {Cmd::Attach {@@ -516,13 +663,10 @@ impl State {}}Cmd::ScreenText { reply } => {- let json = self- .app- .as_ref()- .and_then(|app| app.screen_text())- .map(|t| json(&t))- .unwrap_or_else(|| "null".into());- let _ = reply.send(json);+ let _ = reply.send(self.screen_json());+ }+ Cmd::TextBetween { anchor, head, reply } => {+ let _ = reply.send(self.app.as_ref().and_then(|app| app.text_between(anchor, head)));}Cmd::SetSelection { anchor, head } => {if let Some(app) = self.app.clone() {@@ -546,6 +690,18 @@ impl State {});}}+ Cmd::ScreenPreview { pane } => {+ if let Some(app) = self.app.clone() {+ let notify = Arc::clone(&self.notify);+ let task = app.preview_tab(pane);+ let _ = self.pool.spawner().spawn_local(async move {+ match task.await {+ Ok(screen) => notify.on_preview(pane as u32, json(&screen)),+ Err(err) => notify.on_log(format!("tab of pane {pane}: {err:#}")),+ }+ });+ }+ }Cmd::SelectedText { reply } => {let _ = reply.send(self.app.as_ref().and_then(|app| app.selected_text()));}@@ -561,17 +717,64 @@ impl State {if let Err(err) = app.set_setting(&key, &value) {self.notify.on_log(format!("setting {key}: {err}"));}+ if key == "terminal-scheme" && !self.palette_tellable() {+ self.palette_untold = true;+ }}}Cmd::SetPalette(scheme) => {self.palette = scheme.clone();if let Some(app) = self.app.clone() {Self::apply_palette(&app, &self.notify, scheme.as_deref());+ if !self.palette_tellable() {+ self.palette_untold = true;+ }+ }+ }+ Cmd::SetShown(shown) => {+ if !self.platform.set_shown(shown) {+ return;+ }+ self.notify.on_log(format!("shown: {shown}"));+ if let Some(app) = self.app.clone() {+ // As the browser does for a page or a machine coming on+ // show: what it shows is looked at, sized and listed+ // again, so a tab it shows is claimed now.+ app.visibility_changed(shown);+ if shown {+ app.resize();+ app.refresh_layout();+ self.tell_palette(&app);+ }}}+ Cmd::ViewsRead => self.views_dirty.set(true),+ Cmd::WantScreen(wanted) => {+ self.screen_wanted = wanted;+ // Made at once rather than at the next paint, and sent even+ // when they read as the ones left from before.+ self.screen_dirty = wanted;+ self.screen_fresh = wanted;+ }}}+ /// A scheme chosen off screen or while the link is down reaches the+ /// server only from a terminal on show, over a link that is up: told+ /// when both hold, kept until then. (Applying it again would not tell+ /// it: the App has it.)+ fn tell_palette(&mut self, app: &Rc<App<MobilePlatform, SshLink>>) {+ if self.palette_untold && self.palette_tellable() {+ self.palette_untold = false;+ app.advise_palette();+ }+ }++ /// The App tells the server a scheme as it is applied.+ fn palette_tellable(&self) -> bool {+ self.platform.shown() && self.link.as_ref().is_some_and(|link| link.is_open())+ }+fn apply_palette(app: &Rc<App<MobilePlatform, SshLink>>, notify: &Arc<dyn Notify>, scheme: Option<&str>) {let palette = match scheme {None => None,@@ -613,6 +816,7 @@ impl State {if self.status != status {self.status = status.to_string();self.notify.on_status(self.status.clone());+ self.views_dirty.set(true);}}@@ -625,6 +829,13 @@ impl State {fn connect(&mut self, params: ConnectParams, painter: Box<dyn GlyphPainter>) -> Result<()> {self.disconnect();+ // No host's cards on another's tabs: the built-in ones until this+ // host's are read. The same host again keeps its own meanwhile.+ let host = (params.ssh.host.clone(), params.ssh.port, params.ssh.user.clone());+ if self.icons_host.as_ref() != Some(&host) {+ self.show_icons(icons::catalog());+ self.icons_host = Some(host);+ }self.device_id = params.device_id.clone();let mut faces = Vec::new();for path in ¶ms.font_paths {@@ -706,6 +917,7 @@ impl State {}// Every timer and interval belonged to that App.self.platform.clear_timers();+ self.views_dirty.set(true);}self.conn = Conn::Idle;}@@ -769,7 +981,13 @@ impl State {return;};match net {- Net::Connected => link.opened(),+ Net::Connected => {+ link.opened();+ // A scheme still untold for want of a link goes now.+ if let Some(app) = self.app.clone() {+ self.tell_palette(&app);+ }+ }Net::Data(bytes) => {self.stats.bytes_in += bytes.len() as u64;if let Err(err) = link.feed(&bytes) {@@ -785,6 +1003,8 @@ impl State {Net::Exit(code) => self.notify.on_log(format!("remote command exited with {code}")),+ Net::TabIcons(Ok(cards)) => self.show_icons(cards),+ Net::TabIcons(Err(err)) => self.notify.on_log(format!("tab icons: {err}")),Net::Closed(reason) => {if self.app.is_none() {self.conn = Conn::Disconnected(reason.clone());@@ -797,6 +1017,20 @@ impl State {}}+ /// Put `cards` on the tabs, for the App and the shell's drawing.+ fn show_icons(&mut self, cards: thinkterm_tab_icons::WireCatalog) {+ if !self.icons.set(cards) {+ return;+ }+ if let Some(app) = &self.app {+ if let Err(err) = app.set_tab_icons(&self.icons.json()) {+ self.notify.on_log(format!("tab icons: {err}"));+ }+ }+ // The shell redraws the cards when it sees the views move.+ self.views_dirty.set(true);+ }+/// The link is up: attach to the server's active pane at the grid the/// surface holds (measured with the glyph metrics for this screen).fn start_attach(&mut self) {@@ -987,8 +1221,15 @@ impl State {link.set_close_handler(Box::new(move |reason| app.on_close(reason)));}{- let notify = Arc::clone(&self.notify);- app.set_on_change(Rc::new(move || notify.on_change()));+ // Inside the App's own call: only noted here, the views are+ // made between commands (`publish_views`).+ let dirty = Rc::clone(&self.views_dirty);+ app.set_on_change(Rc::new(move || dirty.set(true)));+ }+ if !self.platform.shown() {+ // Made behind the screen (a reconnect while the app is in the+ // background): it looks at nothing until it is shown.+ app.visibility_changed(false);}app.composing(self.composing);for (key, value) in &self.settings {@@ -999,6 +1240,13 @@ impl State {if let Some(scheme) = self.palette.clone() {Self::apply_palette(&app, &self.notify, Some(&scheme));}+ // Made off screen, it told the server no scheme it was given. A new+ // connection holds no scheme of before to undo: the desktop's is+ // its own already.+ self.palette_untold = self.palette.is_some() && !self.platform.shown();+ if let Err(err) = app.set_tab_icons(&self.icons.json()) {+ self.notify.on_log(format!("tab icons: {err}"));+ }app.fetch_tree();app.hide_status();app.refresh_layout();@@ -1010,6 +1258,7 @@ impl State {attached.pane_id, attached.tab_id, attached.server_version, attached.server_id));self.app = Some(app);+ self.views_dirty.set(true);self.conn = Conn::Ready;self.set_status(&format!("pane {} · {}", attached.pane_id, attached.title));}@@ -1188,6 +1437,8 @@ impl State {if self.platform.run_frame() {self.stats.frames += 1;self.stats.last_frame_us = started.elapsed().as_micros();+ // Output changes the rows without changing a view.+ self.screen_dirty = true;}return;}@@ -1272,14 +1523,17 @@ fn stable_identity(device_id: &str) -> (u64, usize) {mod tests {use super::*;- struct QuietNotify;+ /// Says nothing, and counts `on_change`.+ struct QuietNotify(Arc<std::sync::atomic::AtomicUsize>);impl Notify for QuietNotify {fn on_frame_needed(&self) {}fn on_status(&self, _: String) {}fn on_log(&self, _: String) {}fn on_title(&self, _: String) {}- fn on_change(&self) {}+ fn on_change(&self) {+ self.0.fetch_add(1, Ordering::Relaxed);+ }fn on_clipboard(&self, _: String) {}fn on_focus_input(&self) {}fn on_ime_anchor(&self, _: f64, _: f64, _: f64, _: f64) {}@@ -1290,8 +1544,106 @@ mod tests {}fn state() -> State {+ state_with(&Arc::default(), true)+ }++ fn state_with(changes: &Arc<std::sync::atomic::AtomicUsize>, views_read: bool) -> State {let (tx, _) = std::sync::mpsc::channel();- State::new(tx, Box::new(QuietNotify))+ State::new(+ tx,+ Box::new(QuietNotify(Arc::clone(changes))),+ Arc::new(Mutex::new(Published::default())),+ Arc::new(AtomicBool::new(views_read)),+ Arc::new(icons::Shown::new(icons::catalog())),+ )+ }++ #[test]+ fn views_go_out_once_a_frame_and_only_after_a_change() {+ let changes = Arc::default();+ let mut state = state_with(&changes, true);+ state.views_dirty.set(false);+ state.views_made = Instant::now() - VIEWS_EVERY;+ state.publish_views();+ assert_eq!(state.published.lock().unwrap().views.revision, 0, "nothing changed");++ state.views_dirty.set(true);+ state.views_made = Instant::now();+ state.publish_views();+ assert_eq!(state.published.lock().unwrap().views.revision, 0, "a frame has not passed");++ state.views_made = Instant::now() - VIEWS_EVERY;+ state.publish_views();+ let views = state.published.lock().unwrap().views.clone();+ assert_eq!(views.revision, 1);+ assert_eq!(views.tabs, "null", "no App, no views");+ assert!(!state.views_dirty.get());+ assert_eq!(changes.load(Ordering::Relaxed), 1);+ }++ #[test]+ fn views_wait_while_the_terminal_is_off_screen() {+ let changes = Arc::default();+ let mut state = state_with(&changes, true);+ state.platform.set_shown(false);+ state.views_dirty.set(true);+ state.views_made = Instant::now() - VIEWS_EVERY;+ state.publish_views();+ assert_eq!(state.published.lock().unwrap().views.revision, 0, "none made off screen");+ assert!(state.views_dirty.get(), "the change waits");+ assert!(state.wait(Instant::now()) >= Duration::from_secs(60), "and the loop sleeps meanwhile");++ state.platform.set_shown(true);+ assert_eq!(state.wait(Instant::now()), Duration::ZERO, "owed once it is back");+ state.publish_views();+ assert_eq!(state.published.lock().unwrap().views.revision, 1, "made once it is back");+ }++ #[test]+ fn a_shell_that_reads_no_views_is_made_none_but_still_told() {+ let changes = Arc::default();+ let mut state = state_with(&changes, false);+ state.views_made = Instant::now() - VIEWS_EVERY;+ state.publish_views();+ assert_eq!(state.published.lock().unwrap().views.revision, 0);+ assert_eq!(changes.load(Ordering::Relaxed), 1, "it pulls each view itself");+ state.handle(Cmd::ViewsRead);+ assert!(state.views_dirty.get(), "the first read has them made");+ }++ #[test]+ fn rows_are_kept_only_while_wanted_and_tell_nothing() {+ let changes = Arc::default();+ let mut state = state_with(&changes, true);+ state.views_dirty.set(false);+ state.screen_dirty = true;+ state.views_made = Instant::now() - VIEWS_EVERY;+ state.publish_views();+ assert!(!state.screen_dirty, "a paint makes no rows nobody wants");+ state.handle(Cmd::WantScreen(true));+ assert!(state.screen_wanted && state.screen_dirty, "wanted rows are made at once");+ state.publish_views();+ assert!(!state.screen_dirty);+ assert_eq!(changes.load(Ordering::Relaxed), 0, "rows alone come without on_change");+ }++ #[test]+ fn a_status_change_marks_the_views_stale() {+ let mut state = state();+ state.views_dirty.set(false);+ state.set_status("connecting to example");+ assert!(state.views_dirty.get());+ }++ #[test]+ fn shown_reaches_the_platform_once_per_change() {+ let mut state = state();+ assert!(state.platform.shown(), "shown until the shell says otherwise");+ state.handle(Cmd::SetShown(false));+ assert!(!state.platform.shown());+ assert!(!state.platform.set_shown(false), "a repeat is no change");+ state.handle(Cmd::SetShown(true));+ assert!(state.platform.shown());}fn attached() -> Attached {diff --git a/thinkterm-mobile/src/icons.rs b/thinkterm-mobile/src/icons.rsnew file mode 100644index 00000000..fc0aabf4--- /dev/null+++ b/thinkterm-mobile/src/icons.rs@@ -0,0 +1,374 @@+//! The cards heading tabs and pane capsules (`thinkterm_tab_icons`), with+//! each glyph drawn into a coverage mask the shell tints, as the desktop's+//! atlas does. The built-in cards are alike on every machine; a machine's+//! restyled and imported ones live in its desktop's settings, which the+//! network thread reads over the connection's own ssh session (`ssh`), as+//! a page gets them from its server. The commands it runs and what they+//! print are here.++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use thinkterm_tab_icons::{Catalog, GlyphKey, TabIconSettings, WireCard, WireCatalog};++/// The largest glyph a shell may ask for, in pixels.+pub const MAX_SIZE: u32 = 512;++/// The line the commands' answer starts with, on a line of its own:+/// whatever a login profile says comes before it.+const MARKER: &[u8] = b"thinkterm-tab-icons\n";+/// The line it ends with: whatever the shell says on its way out comes+/// after, and an answer cut short has none.+const END: &[u8] = b"thinkterm-tab-icons-end\n";++/// The most of a settings file read; one larger does not parse, and is no+/// settings.+pub const SETTINGS_LIMIT: usize = 4 << 20;+/// The largest imported glyph the desktop keeps, and a page is sent.+const SVG_LIMIT: usize = 256 * 1024;++/// The most `svgs_command` may print for `count` glyphs.+pub fn svgs_limit(count: usize) -> usize {+ count * (SVG_LIMIT + 128) + 1024+}++/// The built-in cards, as a page receives them.+pub fn catalog() -> WireCatalog {+ Catalog::build(&TabIconSettings::default(), |key| key.to_string()).wire(|_| None)+}++/// Prints the desktop's settings file, where the desktop keeps it under+/// the login's home (`config::native_settings_path`), or nothing on a+/// machine without one. `/bin/sh` runs it, whatever the login shell is.+pub fn settings_command() -> String {+ format!(+ r#"/bin/sh -c 'printf "\nthinkterm-tab-icons\n"; f="$HOME/.config/thinkterm/settings.json"; [ -f "$f" ] && head -c {SETTINGS_LIMIT} "$f"; printf "\nthinkterm-tab-icons-end\n"; exit 0'"#+ )+}++/// Prints the imported glyphs `hashes` names, each as a line with its hash+/// and length and then the file as it is (a gzipped `.svgz` has NULs in+/// it). One gone, or larger than the desktop keeps, is left out.+pub fn svgs_command(hashes: &[String]) -> String {+ // Hashes are hex (`is_svg_id`): nothing in them for a shell to read.+ let names = hashes.join(" ");+ format!(+ r#"/bin/sh -c 'printf "\nthinkterm-tab-icons\n"; cd "$HOME/.config/thinkterm/tab-icons" 2>/dev/null && for h in {names}; do [ -f "$h.svg" ] || continue; n=$(wc -c < "$h.svg" | tr -d " "); [ "$n" -le {SVG_LIMIT} ] || continue; printf "%s %s\n" "$h" "$n"; head -c "$n" "$h.svg"; done; printf "thinkterm-tab-icons-end\n"; exit 0'"#+ )+}++/// What follows the marker in a command's output; None if it never came+/// (no `/bin/sh` ran it). The commands print a newline first, so the+/// marker starts a line whatever a profile printed before it.+fn payload(out: &[u8]) -> Option<&[u8]> {+ let mut from = 0;+ loop {+ let at = from + out[from..].windows(MARKER.len()).position(|w| w == MARKER)?;+ if at == 0 || out[at - 1] == b'\n' {+ return Some(&out[at + MARKER.len()..]);+ }+ from = at + 1;+ }+}++/// The cards a desktop's settings make, from what `settings_command`+/// printed: the built-in ones where there are no settings or they cannot+/// be read, as its server has it (`web_relay::tab_icons_at`). None if the+/// command never ran.+pub fn desktop_cards(out: &[u8]) -> Option<Catalog> {+ #[derive(Default, serde::Deserialize)]+ struct Settings {+ #[serde(default)]+ tab_icons: TabIconSettings,+ }+ let text = payload(out)?;+ // Up to the end line: an answer without one was cut short.+ let end = [&b"\n"[..], END].concat();+ let file = &text[..text.windows(end.len()).rposition(|w| w == end.as_slice())?];+ let settings = serde_json::from_slice::<Settings>(file).unwrap_or_default();+ // Names are the desktop's to show; the phone draws only the icons.+ Some(Catalog::build(&settings.tab_icons, |key| key.to_string()))+}++/// The imported glyphs `cards` show, by hash.+pub fn imported(cards: &Catalog) -> Vec<String> {+ let mut hashes: Vec<String> = cards+ .cards+ .iter()+ .filter_map(|card| match &card.glyph {+ GlyphKey::Svg(hash) => Some(hash.to_string()),+ GlyphKey::Builtin(_) => None,+ })+ .collect();+ hashes.sort();+ hashes.dedup();+ hashes+}++/// The glyphs `svgs_command` printed for `hashes`, by hash: those that+/// came whole. One that is not text (a gzipped `.svgz`) is left out, as+/// the host's server leaves it out of a page's.+pub fn imported_svgs(out: &[u8], hashes: &[String]) -> HashMap<String, String> {+ let mut svgs = HashMap::new();+ let Some(mut rest) = payload(out) else {+ return svgs;+ };+ while !rest.starts_with(END) {+ // A line of hash and length, then that many bytes; anything else+ // is an answer cut short, and what came before it stands.+ let Some(eol) = rest.iter().position(|&b| b == b'\n') else {+ break;+ };+ let Some((hash, len)) = std::str::from_utf8(&rest[..eol]).ok().and_then(|line| line.split_once(' ')) else {+ break;+ };+ let Some(len) = len.parse::<usize>().ok().filter(|&len| len <= SVG_LIMIT && eol + 1 + len <= rest.len()) else {+ break;+ };+ if !hashes.iter().any(|h| h == hash) {+ break;+ }+ if let Ok(svg) = std::str::from_utf8(&rest[eol + 1..eol + 1 + len]) {+ if !svg.is_empty() {+ svgs.insert(hash.to_string(), svg.to_string());+ }+ }+ rest = &rest[eol + 1 + len..];+ }+ svgs+}++/// The cards on show: the core thread puts in each connection's, the+/// shell's thread draws them (`Core::tab_icon`).+pub struct Shown {+ /// Taken by the shell's thread to draw: held only to swap or clone the+ /// pointer, never while the cards are compared or written out.+ cards: Mutex<Arc<WireCatalog>>,+ /// Which cards these are, for a shell to drop what it drew before.+ revision: AtomicU64,+}++/// Revisions are numbered across every `Shown` in the process: a shell's+/// drawings are kept for one, whatever core they came from.+fn next_revision() -> u64 {+ static NEXT: AtomicU64 = AtomicU64::new(1);+ NEXT.fetch_add(1, Ordering::Relaxed)+}++impl Shown {+ pub fn new(cards: WireCatalog) -> Self {+ Self {+ cards: Mutex::new(Arc::new(cards)),+ revision: AtomicU64::new(next_revision()),+ }+ }++ fn current(&self) -> Arc<WireCatalog> {+ Arc::clone(&self.cards.lock().unwrap())+ }++ /// Put `cards` on show; false if they are the ones there. Only the core+ /// thread puts cards on show.+ pub fn set(&self, cards: WireCatalog) -> bool {+ if *self.current() == cards {+ return false;+ }+ *self.cards.lock().unwrap() = Arc::new(cards);+ self.revision.store(next_revision(), Ordering::Release);+ true+ }++ pub fn card(&self, id: &str) -> Option<WireCard> {+ self.current().cards.iter().find(|card| card.id == id).cloned()+ }++ /// The cards as an App takes them (`App::set_tab_icons`).+ pub fn json(&self) -> String {+ serde_json::to_string(&*self.current()).unwrap_or_default()+ }++ pub fn revision(&self) -> u64 {+ self.revision.load(Ordering::Acquire)+ }+}++/// The glyph's shape, `size` pixels square and centred: one byte a pixel,+/// row by row, how much of it the shape covers. Its colours are dropped,+/// as the desktop drops them. None for a card with no glyph.+pub fn mask(svg: &str, size: u32) -> Option<Vec<u8>> {+ if svg.is_empty() {+ return None;+ }+ // A host's own SVG is anyone's: a renderer that panics on it costs+ // the glyph, not the app (a panic would cross into the shell).+ std::panic::catch_unwind(|| draw(svg, size)).ok().flatten()+}++fn draw(svg: &str, size: u32) -> Option<Vec<u8>> {+ let size = size.clamp(1, MAX_SIZE);+ let mut options = resvg::usvg::Options::default();+ // An icon is a shape: nothing it names outside itself is ever fetched.+ options.image_href_resolver.resolve_string = Box::new(|_, _| None);+ let tree = resvg::usvg::Tree::from_data(svg.as_bytes(), &options).ok()?;+ let svg_size = tree.size();+ let scale = (size as f32 / svg_size.width()).min(size as f32 / svg_size.height());+ let translate_x = (size as f32 - svg_size.width() * scale) / 2.0;+ let translate_y = (size as f32 - svg_size.height() * scale) / 2.0;+ let transform = resvg::tiny_skia::Transform::from_translate(translate_x, translate_y).pre_scale(scale, scale);+ let mut pixmap = resvg::tiny_skia::Pixmap::new(size, size)?;+ resvg::render(&tree, transform, &mut pixmap.as_mut());+ Some(pixmap.data().chunks_exact(4).map(|pixel| pixel[3]).collect())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_built_in_cards_carry_their_glyphs() {+ let catalog = catalog();+ assert!(catalog.enabled);+ let terminal = catalog.cards.iter().find(|card| card.id == catalog.terminal).expect("the terminal's card");+ assert!(terminal.circle.starts_with('#') && terminal.glyph.starts_with('#'));+ let mask = mask(&terminal.svg, 48).expect("a glyph");+ assert_eq!(mask.len(), 48 * 48);+ assert!(mask.iter().any(|&a| a > 0), "the shape covers something");+ assert!(mask.iter().any(|&a| a == 0), "and not everything");+ }++ #[test]+ fn no_glyph_and_bad_shapes_draw_nothing() {+ assert_eq!(mask("", 32), None);+ assert_eq!(mask("not an svg", 32), None);+ }++ #[test]+ fn a_desktops_settings_make_its_cards() {+ let hash = "c".repeat(64);+ let settings = format!(+ r##"{{"theme":"x","tab_icons":{{"cards":[{{"id":"python","circle":"#E8772E"}},{{"id":"custom-1","programs":["deploy"],"svg":"{hash}","circle":"#112233"}}]}}}}"##+ );+ // A login profile may say something first, without a newline, and+ // the shell something on its way out.+ let out = format!("Welcome!\nthinkterm-tab-icons\n{settings}\nthinkterm-tab-icons-end\nbye\n");+ let cards = desktop_cards(out.as_bytes()).expect("the command ran");+ let hashes = imported(&cards);+ assert_eq!(hashes, vec![hash.clone()]);+ let svg = "<svg id='mine'/>";+ let out = format!("\nthinkterm-tab-icons\n{hash} {}\n{svg}thinkterm-tab-icons-end\n", svg.len());+ let svgs = imported_svgs(out.as_bytes(), &hashes);+ let wire = cards.wire(|hash| svgs.get(hash).cloned());+ let custom = wire.cards.iter().find(|card| card.id == "custom-1").unwrap();+ assert_eq!(custom.svg, svg);+ assert_eq!(custom.circle, "#112233");+ assert_eq!(custom.programs, vec!["deploy".to_string()]);+ assert_eq!(wire.cards.iter().find(|card| card.id == "python").unwrap().circle, "#E8772E");+ }++ #[test]+ fn a_machine_without_settings_has_the_built_in_cards() {+ for out in [+ &b"\nthinkterm-tab-icons\n\nthinkterm-tab-icons-end\n"[..],+ b"\nthinkterm-tab-icons\n{not json\nthinkterm-tab-icons-end\n",+ ] {+ let cards = desktop_cards(out).expect("the command ran");+ assert_eq!(cards.wire(|_| None), catalog());+ }+ // Nothing ran the command, or its answer was cut short: not the+ // same as no settings.+ assert!(desktop_cards(b"sh: not found\n").is_none());+ assert!(desktop_cards(b"xthinkterm-tab-icons\n{}\nthinkterm-tab-icons-end\n").is_none(), "the marker starts a line");+ assert!(desktop_cards(b"\nthinkterm-tab-icons\n{\"tab_icons\":{\"enab").is_none(), "no end line");+ }++ #[test]+ fn glyphs_that_are_not_text_or_cut_short_are_left_out() {+ let (a, b, c) = ("a".repeat(64), "b".repeat(64), "c".repeat(64));+ let hashes = vec![a.clone(), b.clone(), c.clone()];+ // A gzipped glyph (NULs and all) is skipped, the one after it read.+ let mut out = format!("\nthinkterm-tab-icons\n{a} 4\n").into_bytes();+ out.extend_from_slice(&[0x1f, 0x8b, 0x08, 0x00]);+ out.extend_from_slice(format!("{b} 6\n<svg/>thinkterm-tab-icons-end\n").as_bytes());+ let svgs = imported_svgs(&out, &hashes);+ assert_eq!(svgs.len(), 1);+ assert_eq!(svgs[&b], "<svg/>");+ // Cut short in a glyph: the ones before it stand.+ let out = format!("\nthinkterm-tab-icons\n{a} 6\n<svg/>{c} 100\n<svg");+ let svgs = imported_svgs(out.as_bytes(), &hashes);+ assert_eq!(svgs.keys().collect::<Vec<_>>(), vec![&a]);+ // A length past the desktop's limit is not believed.+ let out = format!("\nthinkterm-tab-icons\n{a} {}\n", SVG_LIMIT + 1);+ assert!(imported_svgs(out.as_bytes(), &hashes).is_empty());+ }++ #[test]+ fn the_commands_name_only_hex_inside_their_quotes() {+ let hash = "0123456789abcdef".repeat(4);+ let command = svgs_command(std::slice::from_ref(&hash));+ assert!(command.contains(&format!("for h in {hash};")));+ for command in [settings_command(), command] {+ assert!(command.starts_with("/bin/sh -c '") && command.ends_with('\''));+ assert_eq!(command.matches('\'').count(), 2, "{command}");+ }+ }++ #[cfg(unix)]+ #[test]+ fn the_commands_read_a_desktops_files() {+ // As a login shell runs them, with the home the files are under.+ let run = |home: &std::path::Path, command: String| {+ std::process::Command::new("/bin/sh")+ .arg("-c")+ .arg(command)+ .env("HOME", home)+ .output()+ .expect("running /bin/sh")+ .stdout+ };+ let home = tempfile::tempdir().unwrap();+ let dir = home.path().join(".config").join("thinkterm");+ std::fs::create_dir_all(dir.join("tab-icons")).unwrap();+ // A gzipped glyph sorts first; the text one after it still comes.+ let (gz, text) = ("a".repeat(64), "c".repeat(64));+ std::fs::write(+ dir.join("settings.json"),+ format!(r#"{{"tab_icons":{{"cards":[{{"id":"custom-1","svg":"{gz}"}},{{"id":"custom-2","svg":"{text}"}}]}}}}"#),+ )+ .unwrap();+ std::fs::write(dir.join("tab-icons").join(format!("{gz}.svg")), [0x1f, 0x8b, 0x08, 0x00, 0x00]).unwrap();+ std::fs::write(dir.join("tab-icons").join(format!("{text}.svg")), "<svg id='mine'/>").unwrap();+ let cards = desktop_cards(&run(home.path(), settings_command())).expect("the command ran");+ let hashes = imported(&cards);+ assert_eq!(hashes, vec![gz.clone(), text.clone()]);+ let out = run(home.path(), svgs_command(&hashes));+ assert!(out.len() <= svgs_limit(hashes.len()));+ let svgs = imported_svgs(&out, &hashes);+ assert_eq!(svgs.keys().collect::<Vec<_>>(), vec![&text]);+ assert_eq!(svgs[&text], "<svg id='mine'/>");++ // A home with no desktop: the built-in cards, and no glyphs to read.+ let bare = tempfile::tempdir().unwrap();+ let cards = desktop_cards(&run(bare.path(), settings_command())).expect("the command ran");+ assert_eq!(cards.wire(|_| None), catalog());+ assert!(imported_svgs(&run(bare.path(), svgs_command(&hashes)), &hashes).is_empty());+ }++ #[test]+ fn the_cards_on_show_change_only_when_they_differ() {+ let shown = Shown::new(catalog());+ let first = shown.revision();+ assert!(!shown.set(catalog()));+ assert_eq!(shown.revision(), first);+ let mut other = catalog();+ other.cards[0].circle = "#000000".into();+ let id = other.cards[0].id.clone();+ assert!(shown.set(other.clone()));+ assert_ne!(shown.revision(), first);+ assert_eq!(shown.card(&id).unwrap().circle, "#000000");+ assert!(shown.json().contains("#000000"));+ // Another core's cards, changed as often, are never taken for these.+ let elsewhere = Shown::new(catalog());+ assert!(elsewhere.set(other));+ assert_ne!(elsewhere.revision(), shown.revision());+ }+}diff --git a/thinkterm-mobile/src/lib.rs b/thinkterm-mobile/src/lib.rsindex 6a526dc6..6ca44f3c 100644--- a/thinkterm-mobile/src/lib.rs+++ b/thinkterm-mobile/src/lib.rs@@ -11,14 +11,18 @@//!//! The core thread never waits on the shell's main thread. It talks back//! only through [`Notify`] and [`painter::GlyphPainter`], whose calls the-//! shell must treat as coming from a background thread.+//! shell must treat as coming from a background thread. The views the+//! shell draws from go the other way without a wait: the core thread+//! publishes them after a change, and [`Core::views`] reads the latest.mod core;+mod icons;mod link;pub mod painter;mod platform;mod ssh;+use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{self, Sender};use std::sync::Mutex;use std::thread::JoinHandle;@@ -56,7 +60,9 @@ pub trait Notify: Send + Sync {/// A pane rang its bell.fn on_bell(&self);/// The last rows of a pane, answering `request_preview`: JSON, a list- /// of rows, each a list of `{"text","fg"}` runs (`App::PreviewRow`).+ /// of rows, each a list of `{"text","fg"}` runs (`App::PreviewRow`);+ /// or, answering `request_screen_preview`, an object: the whole tab the+ /// pane is in, each pane's screen where it lies (`App::TabPreview`).fn on_preview(&self, pane: u32, rows: String);}@@ -143,6 +149,74 @@ pub struct SshKeyPair {pub public_line: String,}+/// Every view the shell draws from, as JSON, made on the core thread+/// after a change ("null" while there is no App). `revision` grows with+/// each publication; the same number means nothing new.+#[derive(uniffi::Record, Clone)]+pub struct ViewSet {+ pub revision: u64,+ /// The connection they are from: each `connect` starts a later one, so+ /// a shell that just connected can tell views left from the one before.+ pub connection: u64,+ pub tabs: String,+ pub threads: String,+ pub tree: String,+ pub sidebar: String,+ pub navs: String,+ pub status: String,+ pub layout: String,+}++impl Default for ViewSet {+ fn default() -> Self {+ let null = || "null".to_string();+ Self {+ revision: 0,+ connection: 0,+ tabs: null(),+ threads: null(),+ tree: null(),+ sidebar: null(),+ navs: null(),+ status: null(),+ layout: null(),+ }+ }+}++/// A card heading a tab or a pane's capsule, as the shell draws it: a+/// circle in `circle`, and on it the glyph's shape (`mask`, one byte a+/// pixel, `size` square: how much the shape covers) in `glyph`. The+/// colours are `#rrggbb`.+#[derive(uniffi::Record)]+pub struct TabIcon {+ pub circle: String,+ pub glyph: String,+ pub size: u32,+ pub mask: Vec<u8>,+}++/// What the core thread last published for the shell to read. The lock+/// is held only to copy in or out, never while anything is made.+pub(crate) struct Published {+ pub views: ViewSet,+ /// The focused pane's visible rows (`App::screen_text`), kept current+ /// only while the shell wants them (`Core::set_screen_wanted`), with+ /// a count of their own: output changes them and no view.+ pub screen: String,+ pub screen_revision: u64,+}++impl Default for Published {+ fn default() -> Self {+ Self {+ views: ViewSet::default(),+ screen: "null".into(),+ screen_revision: 0,+ }+ }+}+/// The system's randomness, as ssh-key's generator wants it.struct SysRng(ring::rand::SystemRandom);@@ -193,6 +267,14 @@ pub fn ssh_public_line(pem: String, passphrase: Option<String>, comment: String)pub struct Core {tx: Sender<core::Cmd>,thread: Mutex<Option<JoinHandle<()>>>,+ /// What the core thread last published.+ published: std::sync::Arc<Mutex<Published>>,+ /// The shell reads views from `published`; until it does, the core+ /// makes none there (a shell that pulls each one with `view` never does).+ views_read: std::sync::Arc<AtomicBool>,+ /// The cards the App puts on tabs and capsules: the built-in ones,+ /// then the connected host's.+ icons: std::sync::Arc<icons::Shown>,}#[uniffi::export]@@ -201,16 +283,25 @@ impl Core {pub fn new(notify: Box<dyn Notify>) -> std::sync::Arc<Self> {install_logger();let (tx, rx) = mpsc::channel();+ let published = std::sync::Arc::new(Mutex::new(Published::default()));+ let views_read = std::sync::Arc::new(AtomicBool::new(false));+ let icons = std::sync::Arc::new(icons::Shown::new(icons::catalog()));let thread = std::thread::Builder::new().name("thinkterm-core".into()).spawn({let tx = tx.clone();- move || core::run(tx, rx, notify)+ let published = std::sync::Arc::clone(&published);+ let views_read = std::sync::Arc::clone(&views_read);+ let icons = std::sync::Arc::clone(&icons);+ move || core::run(tx, rx, notify, published, views_read, icons)}).expect("spawning the core thread");std::sync::Arc::new(Self {tx,thread: Mutex::new(Some(thread)),+ published,+ views_read,+ icons,})}@@ -329,8 +420,89 @@ impl Core {// ----- the App's views and commands, for the shell's own interface ------ /// One of the App's views as JSON: "tabs", "sidebar", "navs",- /// "status", "layout" or "strings". "null" while there is no App.+ /// The views the core thread last published, read without waiting+ /// for it; `on_change` says when there are new ones.+ pub fn views(&self) -> ViewSet {+ self.mark_views_read();+ self.published.lock().map(|p| p.views.clone()).unwrap_or_default()+ }++ pub fn views_revision(&self) -> u64 {+ self.mark_views_read();+ self.published.lock().map(|p| p.views.revision).unwrap_or(0)+ }++ /// The connection the published views are from (`ViewSet::connection`),+ /// without copying them.+ pub fn views_connection(&self) -> u64 {+ self.mark_views_read();+ self.published.lock().map(|p| p.views.connection).unwrap_or(0)+ }++ /// The focused pane's visible rows as the core last published them+ /// (`screen_text`'s JSON), current while the shell wants them. Output+ /// changes them without an `on_change`: `screen_revision` says when.+ pub fn screen(&self) -> String {+ self.published.lock().map(|p| p.screen.clone()).unwrap_or_else(|_| "null".into())+ }++ pub fn screen_revision(&self) -> u64 {+ self.published.lock().map(|p| p.screen_revision).unwrap_or(0)+ }++ /// Keep `screen` current: the shell's text input reads the rows (the+ /// keyboard is up, or there is a selection). Unwanted, they are not+ /// made at every paint; `screen_text` makes them on demand.+ pub fn set_screen_wanted(&self, wanted: bool) {+ let _ = self.tx.send(core::Cmd::WantScreen(wanted));+ }++ /// The card `id` (a tab's or a capsule's `icon`), its glyph drawn+ /// `size` pixels square; none for an id there is no card for. Drawn on+ /// the caller's thread, waiting on nothing: a shell keeps what it got+ /// while `tab_icons_revision` stays.+ pub fn tab_icon(&self, id: String, size: u32) -> Option<TabIcon> {+ let card = self.icons.card(&id)?;+ let size = size.clamp(1, icons::MAX_SIZE);+ Some(TabIcon {+ mask: icons::mask(&card.svg, size).unwrap_or_default(),+ circle: card.circle,+ glyph: card.glyph,+ size,+ })+ }++ /// Counts the changes to the cards `tab_icon` draws: each connection+ /// brings its host's. What a shell drew before a change is stale.+ pub fn tab_icons_revision(&self) -> u64 {+ self.icons.revision()+ }++ /// The text between two visible cells of the focused pane, both ends+ /// inclusive, for the clipboard; the pane's own selection is left be.+ pub fn text_between(&self, anchor_row: u32, anchor_col: u32, head_row: u32, head_col: u32) -> Option<String> {+ let (reply, ack) = mpsc::channel();+ let cmd = core::Cmd::TextBetween {+ anchor: (anchor_row as usize, anchor_col as usize),+ head: (head_row as usize, head_col as usize),+ reply,+ };+ if self.tx.send(cmd).is_err() {+ return None;+ }+ ack.recv().unwrap_or(None)+ }++ /// Whether this connection's terminal is on screen with the app in+ /// front. Off screen it keeps its session but takes no tab from+ /// another device and marks no result as seen.+ pub fn set_shown(&self, shown: bool) {+ let _ = self.tx.send(core::Cmd::SetShown(shown));+ }++ /// One of the App's views as JSON: "tabs", "threads", "tree",+ /// "sidebar", "navs", "status", "layout" or "strings", made while the+ /// caller waits; "null" while there is no App. `views` does not wait.pub fn view(&self, name: String) -> String {let (reply, ack) = mpsc::channel();if self.tx.send(core::Cmd::View { name, reply }).is_err() {@@ -453,6 +625,12 @@ impl Core {let _ = self.tx.send(core::Cmd::Preview { pane: pane as usize, rows: rows as usize });}+ /// Ask for the whole tab any pane is in, as it is split, every pane's+ /// screen with every row at its own size; `on_preview` answers.+ pub fn request_screen_preview(&self, pane: u32) {+ let _ = self.tx.send(core::Cmd::ScreenPreview { pane: pane as usize });+ }+pub fn selected_text(&self) -> Option<String> {let (reply, ack) = mpsc::channel();if self.tx.send(core::Cmd::SelectedText { reply }).is_err() {@@ -513,3 +691,13 @@ impl Core {}}}++impl Core {+ /// The first read of the views has the core publish them from then on,+ /// starting with the ones it has now.+ fn mark_views_read(&self) {+ if !self.views_read.swap(true, Ordering::Relaxed) {+ let _ = self.tx.send(core::Cmd::ViewsRead);+ }+ }+}diff --git a/thinkterm-mobile/src/platform.rs b/thinkterm-mobile/src/platform.rsindex 5c52d112..8ce30c77 100644--- a/thinkterm-mobile/src/platform.rs+++ b/thinkterm-mobile/src/platform.rs@@ -45,6 +45,8 @@ pub struct MobilePlatform {/// The last size handed to `set_backing_size`, so a phone that resizes/// its surface itself can tell a real change from a repeat.backing: Cell<(u32, u32)>,+ /// The shell has this connection's terminal on screen, in front.+ shown: Cell<bool>,}impl MobilePlatform {@@ -71,9 +73,15 @@ impl MobilePlatform {}),rng: Cell::new(seed),backing: Cell::new((0, 0)),+ shown: Cell::new(true),}}+ /// Returns whether it changed.+ pub fn set_shown(&self, shown: bool) -> bool {+ self.shown.replace(shown) != shown+ }+/// The surface's size in device pixels and its scale, from the shell.pub fn set_viewport(&self, width: u32, height: u32, scale: f64) {self.viewport.set(Viewport {@@ -238,6 +246,10 @@ impl Platform for MobilePlatform {true}+ fn shown(&self) -> bool {+ self.shown.get()+ }+fn set_title(&self, title: &str) {self.notify.on_title(title.to_string());}diff --git a/thinkterm-mobile/src/ssh.rs b/thinkterm-mobile/src/ssh.rsindex f12dd3c6..64be7051 100644--- a/thinkterm-mobile/src/ssh.rs+++ b/thinkterm-mobile/src/ssh.rs@@ -1,5 +1,7 @@//! The network thread: an ssh session to the host, an exec channel running//! `thinkterm cli --prefer-mux proxy`, and the PDU bytes flowing both ways.+//! Beside it, once a connection, the host desktop's tab icons are read on+//! channels of their own (`icons`).//!//! One tokio thread per connection. Bytes to send arrive on an unbounded//! channel and are written in order; everything that comes back -- data,@@ -10,12 +12,14 @@//! asks for explicit approval and retries with that exact fingerprint pinned.//! A remembered key that changes is always rejected.+use crate::icons;use anyhow::{anyhow, Context, Result};use russh::client::{self, Handler};use russh::keys::{HashAlg, PrivateKeyWithHashAlg, PublicKeyOrCertificate};use russh::ChannelMsg;use std::sync::{Arc, Mutex};use std::time::Duration;+use thinkterm_tab_icons::WireCatalog;use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};#[derive(Debug, Clone)]@@ -61,6 +65,8 @@ pub enum Net {Data(Vec<u8>),Stderr(String),Exit(u32),+ /// The host's tab icon cards, read beside the protocol, or why not.+ TabIcons(Result<WireCatalog, String>),Closed(String),}@@ -153,6 +159,60 @@ async fn find_cli(session: &client::Handle<HostKeyCheck>) -> Result<String> {}}+/// The longest a command beside the protocol may take, all told.+const OUTPUT_DEADLINE: Duration = Duration::from_secs(60);++/// What `command` prints, on a channel of its own beside the protocol's;+/// more than `limit` bytes is an error. A command that runs on (a forced+/// command in place of the shell, a profile that waits) is ended with its+/// channel.+async fn output(session: &client::Handle<HostKeyCheck>, command: String, limit: usize) -> Result<Vec<u8>> {+ let mut channel = bounded("opening a channel", session.channel_open_session()).await?;+ let mut out = Vec::new();+ let read = async {+ bounded("exec", channel.exec(true, command)).await?;+ loop {+ match tokio::time::timeout(STEP, channel.wait()).await {+ Ok(Some(ChannelMsg::Data { data })) => {+ out.extend_from_slice(&data);+ anyhow::ensure!(out.len() <= limit, "more than {limit} bytes");+ }+ Ok(Some(ChannelMsg::Close)) | Ok(None) => return Ok::<(), anyhow::Error>(()),+ Ok(Some(_)) => {}+ Err(_) => anyhow::bail!("no answer"),+ }+ }+ };+ // Each message re-arms the step's timeout; this bounds them all.+ let read = match tokio::time::timeout(OUTPUT_DEADLINE, read).await {+ Ok(read) => read,+ Err(_) => Err(anyhow!("no end in {} s", OUTPUT_DEADLINE.as_secs())),+ };+ if read.is_err() {+ let _ = channel.close().await;+ }+ read.map(|()| out)+}++/// The host desktop's tab icon cards, as its server gives a page them+/// (`icons`): its settings, then the glyphs it imported that they name.+async fn tab_icons(session: &client::Handle<HostKeyCheck>) -> Result<WireCatalog> {+ // Room for what a login profile prints before the file.+ let out = output(session, icons::settings_command(), icons::SETTINGS_LIMIT + 64 * 1024).await?;+ let cards = icons::desktop_cards(&out).ok_or_else(|| anyhow!("no answer from /bin/sh on the host"))?;+ let hashes = icons::imported(&cards);+ // Glyphs that cannot be read are left out and the cards kept, as the+ // host's server sends them to a page.+ let svgs = match hashes.is_empty() {+ true => Default::default(),+ false => output(session, icons::svgs_command(&hashes), icons::svgs_limit(hashes.len()))+ .await+ .map(|out| icons::imported_svgs(&out, &hashes))+ .unwrap_or_default(),+ };+ Ok(cards.wire(|hash| svgs.get(hash).cloned()))+}+/// Start the connection on its own thread. Returns the sender for bytes/// to write; dropping it (or sending `Out::Close`) ends the session.pub fn spawn(params: SshParams, deliver: Box<dyn Fn(Net) + Send>) -> UnboundedSender<Out> {@@ -300,8 +360,17 @@ async fn run(// What the command last said and how it ended: the reason a session// that dies at once gives, instead of a bare "ended".let (mut last_err, mut exit) = (String::new(), None);+ // The host's tab icons come on channels of their own while the+ // terminal is already in use.+ let cards = tab_icons(&session);+ tokio::pin!(cards);+ let mut cards_read = false;loop {tokio::select! {+ read = &mut cards, if !cards_read => {+ cards_read = true;+ deliver(Net::TabIcons(read.map_err(|err| format!("{err:#}"))));+ }sent = &mut sender => {let _ = session.disconnect(russh::Disconnect::ByApplication, "closed", "")