//! `terminal.attach` / `write` / `resize` / `detach` — the raw terminal of a//! session, on whichever device is looking at it.//!//! **THE PHONE OPENS NO SOCKET.** Swift draws a terminal and nothing more://! bytes arrive as `terminal.data` events, keys go back as `terminal.write`,//! the view's size as `terminal.resize`, and leaving the tab is//! `terminal.detach`. Which end the bytes come from is decided HERE and is not//! a thing the app ever asks about — the Mac holding the session dials its own//! helper, and every other device dials that Mac's//! `/v1/sessions/attach` (`cotton_client::session_host::terminal`).//!//! **Four methods and no fifth**, because the terminal has four verbs. They//! are on the CLIENT half of the method table: a phone is the device this was//! designed for ([belief-future-interface-is-mobile]), and a Mac reaches the//! same code through the other dial.//!//! **An attach is idempotent and a detach cannot fail.** A view that reopens//! its tab means "show me this one", and one that goes away has gone away;//! neither is a refusal worth drawing.use std::sync::Arc;use cotton_client::session_host::{TerminalSink, TerminalState, TerminalTransport};use serde_json::{json, Value};usecrate::events::EventKind;usecrate::handle::CottonHandle;usecrate::methods::MethodError;/// Every method this module answers.pubconst METHODS: [&str; 4] = ["terminal.attach","terminal.detach","terminal.resize","terminal.write",];/// The widest terminal this build will ask for.////// A view can be resized to anything; a `cols` of sixty thousand is a bug or a/// caller having fun, and the pseudo-terminal's `TIOCSWINSZ` takes a `u16`/// either way. The floor is one, because zero is not a terminal.const MAX_DIMENSION: i64 = 1_000;pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"terminal.attach" => attach(handle, request),"terminal.write" => write(handle, request),"terminal.resize" => resize(handle, request),"terminal.detach" => detach(handle, request), other => Err(MethodError::new("unknown_method", format!("this core does not answer `{other}`"), )), }}/// `terminal.attach { session, cols, rows }`.pubfn attach(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let session = session_of(request)?;let (cols, rows) = size_of(request)?;let transport = transport_for(handle)?;let hub = handle.terminals(); hub.attach( &transport,Arc::new(EventSink { events: Arc::clone(handle.events()), }), &session, cols, rows, ) .map_err(|reason| MethodError::new("terminal_unavailable", reason))?;Ok(json!({ "session": session, "state": TerminalState::Attached.as_str() }))}/// `terminal.write { session, bytes }` — base64, because keystrokes are not/// text: an arrow key is three bytes that are not a character.pubfn write(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let session = session_of(request)?;let encoded = request .get("bytes") .and_then(Value::as_str) .ok_or_else(|| bad("a write needs its `bytes`, base64-encoded"))?;let bytes = base64_decode(encoded)?; handle .terminals() .write(&session, &bytes) .map_err(|reason| MethodError::new("terminal_unavailable", reason))?;Ok(json!({ "session": session, "wrote": bytes.len() }))}/// `terminal.resize { session, cols, rows }`.pubfn resize(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let session = session_of(request)?;let (cols, rows) = size_of(request)?; handle .terminals() .resize(&session, cols, rows) .map_err(|reason| MethodError::new("terminal_unavailable", reason))?;Ok(json!({ "session": session, "cols": cols, "rows": rows }))}/// `terminal.detach { session }`. Never refuses — see the module note.pubfn detach(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let session = session_of(request)?; handle.terminals().detach(&session);Ok(json!({ "session": session, "state": TerminalState::Closed.as_str() }))}/// Which end this device's terminals come from: none. The Mac that held the/// sessions was dialled over the relay, and this device reaches no Mac.pubfn transport_for(_handle: &CottonHandle) -> Result<TerminalTransport, MethodError> {Err(MethodError::new("no_server_yet","this device has not joined a server, so there is no Mac to ask for a terminal", ))}/// The bytes and the state, on the FFI event bus.structEventSink { events: Arc<crate::events::EventBus>,}impl std::fmt::DebugforEventSink {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("EventSink") }}implTerminalSinkforEventSink {fn data(&self, session_id: &str, bytes: &[u8]) {self.events.emit(EventKind::TerminalData, json!({"session": session_id,// BASE64, because terminal output is not text: it is escape// sequences and whatever the program wrote, and a JSON string// would have to be valid UTF-8."bytes": base64_encode(bytes), }), ); }fn state(&self, session_id: &str, state: TerminalState) {self.events.emit(EventKind::TerminalState, json!({ "session": session_id, "state": state.as_str() }), ); }}fn session_of(request: &Value) -> Result<String, MethodError> { request .get("session") .and_then(Value::as_str) .map(str::trim) .filter(|id| !id.is_empty()) .map(str::to_string) .ok_or_else(|| bad("a terminal call needs its `session`"))}fn size_of(request: &Value) -> Result<(u16, u16), MethodError> {let cols = dimension(request, "cols")?;let rows = dimension(request, "rows")?;Ok((cols, rows))}fn dimension(request: &Value, field: &str) -> Result<u16, MethodError> {match request.get(field).and_then(Value::as_i64) {Some(value) if (1..=MAX_DIMENSION).contains(&value) => Ok(value as u16), _ => Err(bad(format!("`{field}` is how big the terminal is on screen — 1 to {MAX_DIMENSION}" ))), }}fn base64_decode(encoded: &str) -> Result<Vec<u8>, MethodError> {use base64::Engine; base64::engine::general_purpose::STANDARD .decode(encoded) .map_err(|error| bad(format!("`bytes` is not base64 — {error}")))}fn base64_encode(bytes: &[u8]) -> String {use base64::Engine; base64::engine::general_purpose::STANDARD.encode(bytes)}fn bad(message: implInto<String>) -> MethodError {MethodError::new("bad_request", message)}#[cfg(test)]#[path = "terminal_tests.rs"]mod tests;