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.

26.0 KB
Raw Blame
//! The mobile client's FFI surface.
//!
//! Everything a shell can call lives on [`Core`], a `Send + Sync` handle
//! that forwards to one core thread. UniFFI requires exported objects to be
//! callable from any thread; the session and (later) the App are single
//! threaded (`Rc`, non-`Send` futures), so the handle is a channel, not the
//! state. Commands are asynchronous except where the plan makes them a
//! handshake: `detach_surface` returns only once the core thread has
//! stopped touching the surface, because an Android `surfaceDestroyed` (and
//! a UIKit view going away) must not return before that.
//!
//! 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. 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;

uniffi::setup_scaffolding!();

/// What the core tells the shell. Called on the core thread.
#[uniffi::export(callback_interface)]
pub trait Notify: Send + Sync {
    /// The core has something to draw; the shell should call `render` from
    /// its display callback (CADisplayLink, Choreographer). Never draw from
    /// inside this call.
    fn on_frame_needed(&self);
    /// The connection's state in a line: connecting, attached to a pane,
    /// disconnected and why.
    fn on_status(&self, status: String);
    /// A line for the shell's log view.
    fn on_log(&self, line: String);
    /// The focused pane's title.
    fn on_title(&self, title: String);
    /// Something the App shows changed (tabs, the tree, the status); the
    /// shell reads the views it wants.
    fn on_change(&self);
    /// Text the App wants on the clipboard.
    fn on_clipboard(&self, text: String);
    /// The App wants the keyboard.
    fn on_focus_input(&self);
    /// Where the cursor cell is, in points, in the terminal view.
    fn on_ime_anchor(&self, left: f64, top: f64, width: f64, height: f64);
    /// Authentication is blocked until the user approves this request's key.
    fn on_host_key_required(&self, request_id: String, fingerprint: String);
    /// Something the App publishes for the display layer, keyed: "bg" is
    /// the terminal's background as a hex colour, for the chrome around it.
    fn on_published(&self, key: String, value: String);
    /// 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`);
    /// 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);
}

/// Rust's `log` output goes to stdout, which the simulator's console shows
/// (a device build will want os_log instead); on Android, to logcat under
/// the tag "thinkterm".
struct StdoutLogger;

impl log::Log for StdoutLogger {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() <= log::Level::Info
    }
    fn log(&self, record: &log::Record) {
        if !self.enabled(record.metadata()) {
            return;
        }
        let line = format!("rust {} {}: {}", record.level(), record.target(), record.args());
        #[cfg(target_os = "android")]
        {
            if let Ok(c) = std::ffi::CString::new(line) {
                let prio = match record.level() {
                    log::Level::Error => ndk_sys::android_LogPriority::ANDROID_LOG_ERROR,
                    log::Level::Warn => ndk_sys::android_LogPriority::ANDROID_LOG_WARN,
                    _ => ndk_sys::android_LogPriority::ANDROID_LOG_INFO,
                };
                // SAFETY: both strings are NUL-terminated and outlive the call.
                unsafe {
                    ndk_sys::__android_log_write(prio.0 as std::ffi::c_int, c"thinkterm".as_ptr(), c.as_ptr());
                }
            }
            return;
        }
        #[allow(unreachable_code)]
        println!("{line}");
    }
    fn flush(&self) {}
}

/// The Android shell cannot reach an `ANativeWindow*` from Kotlin: these
/// two JNI entry points do it for `com.roversx.thinkterm.NativeWindow`.
/// `fromSurface` acquires a reference the shell releases with `release`
/// after `detach_surface`.
#[cfg(target_os = "android")]
#[no_mangle]
pub extern "C" fn Java_com_roversx_thinkterm_NativeWindow_fromSurface(
    env: *mut jni_sys::JNIEnv,
    _class: jni_sys::jclass,
    surface: jni_sys::jobject,
) -> jni_sys::jlong {
    // SAFETY: the JVM hands over a live env and a Surface object.
    unsafe { ndk_sys::ANativeWindow_fromSurface(env as *mut _, surface as *mut _) as jni_sys::jlong }
}

#[cfg(target_os = "android")]
#[no_mangle]
pub extern "C" fn Java_com_roversx_thinkterm_NativeWindow_release(
    _env: *mut jni_sys::JNIEnv,
    _class: jni_sys::jclass,
    window: jni_sys::jlong,
) {
    if window != 0 {
        // SAFETY: a pointer `fromSurface` returned, released once.
        unsafe { ndk_sys::ANativeWindow_release(window as *mut _) }
    }
}

fn install_logger() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        static LOGGER: StdoutLogger = StdoutLogger;
        let _ = log::set_logger(&LOGGER);
        log::set_max_level(log::LevelFilter::Info);
        // A panic on the core thread ends it silently otherwise: stderr
        // goes nowhere on a phone.
        std::panic::set_hook(Box::new(|info| log::error!("panic: {info}")));
    });
}

/// A key pair the shell asked for: the private half in the unencrypted
/// openssh-key-v1 container, the public half as one authorized_keys line.
#[derive(uniffi::Record)]
pub struct SshKeyPair {
    pub private_pem: String,
    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);

impl rand_core::TryRng for SysRng {
    type Error = std::convert::Infallible;
    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
        let mut b = [0u8; 4];
        self.try_fill_bytes(&mut b)?;
        Ok(u32::from_le_bytes(b))
    }
    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
        let mut b = [0u8; 8];
        self.try_fill_bytes(&mut b)?;
        Ok(u64::from_le_bytes(b))
    }
    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
        use ring::rand::SecureRandom;
        self.0.fill(dst).expect("the system's randomness is available");
        Ok(())
    }
}

impl rand_core::TryCryptoRng for SysRng {}

/// A fresh ed25519 key pair, with `comment` on both halves.
#[uniffi::export]
pub fn generate_ssh_key(comment: String) -> Option<SshKeyPair> {
    use russh::keys::ssh_key::{Algorithm, LineEnding, PrivateKey};
    let mut key = PrivateKey::random(&mut SysRng(ring::rand::SystemRandom::new()), Algorithm::Ed25519).ok()?;
    key.set_comment(comment.as_str());
    let pem = key.to_openssh(LineEnding::LF).ok()?;
    let public_line = key.public_key().to_openssh().ok()?;
    Some(SshKeyPair { private_pem: pem.to_string(), public_line })
}

/// The public line of a private key the user pasted or imported, with
/// `comment` on it; none when the text is not a key (or the passphrase
/// is wrong).
#[uniffi::export]
pub fn ssh_public_line(pem: String, passphrase: Option<String>, comment: String) -> Option<String> {
    let key = russh::keys::decode_secret_key(&pem, passphrase.as_deref().filter(|p| !p.is_empty())).ok()?;
    let mut public = key.public_key().clone();
    public.set_comment(comment.as_str());
    public.to_openssh().ok()
}

#[derive(uniffi::Object)]
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]
impl Core {
    #[uniffi::constructor]
    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();
                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,
        })
    }

    /// Give the core a CAMetalLayer (`layer` is the unretained pointer) to
    /// draw on. Returns the surface generation the shell must quote back
    /// in `resize` and `detach_surface`, or 0 if the GPU could not be set
    /// up (the reason goes to `on_log`).
    pub fn attach_surface(&self, layer: u64, width: u32, height: u32, scale: f64) -> u64 {
        let (reply, ack) = mpsc::channel();
        if self
            .tx
            .send(core::Cmd::Attach {
                layer: layer as usize,
                width,
                height,
                scale,
                reply,
            })
            .is_err()
        {
            return 0;
        }
        ack.recv().unwrap_or(0)
    }

    /// The surface's drawable size changed (rotation, keyboard, split
    /// view). Asynchronous; a stale generation is ignored.
    pub fn resize(&self, generation: u64, width: u32, height: u32, scale: f64) {
        let _ = self.tx.send(core::Cmd::Resize {
            generation,
            width,
            height,
            scale,
        });
    }

    /// The handshake: returns once the core thread has dropped the surface
    /// and will not touch the layer again. The only call a shell may block
    /// its main thread on.
    pub fn detach_surface(&self, generation: u64) {
        let (reply, ack) = mpsc::channel();
        if self
            .tx
            .send(core::Cmd::Detach { generation, reply })
            .is_ok()
        {
            let _ = ack.recv();
        }
    }

    /// Draw one frame if a surface is attached. Asynchronous: the shell
    /// calls this from its display callback and returns immediately.
    pub fn render(&self) {
        let _ = self.tx.send(core::Cmd::Render);
    }

    /// Start or stop the demo animation drawn while no pane is attached.
    pub fn set_animating(&self, on: bool) {
        let _ = self.tx.send(core::Cmd::Animate(on));
    }

    /// Connect over ssh, exec the proxy on the host and attach to its
    /// active pane. `font_paths` are the TTF files to shape with (base face
    /// first); `painter` draws what they lack.
    /// `auth_kind` is "key-path" (the secret is a file path), "key" (the
    /// secret is the private key's text, `passphrase` its passphrase) or
    /// "password". `known_host` is the fingerprint remembered from an
    /// earlier connection, if any. `device_id` names this install to the
    /// server, the same every launch: a tab this phone held is still its
    /// own after a relaunch, rather than "another device's".
    #[allow(clippy::too_many_arguments)]
    pub fn connect(
        &self,
        request_id: String,
        host: String,
        port: u16,
        user: String,
        auth_kind: String,
        secret: String,
        passphrase: Option<String>,
        known_host: Option<String>,
        remote_command: String,
        device_id: String,
        keepalive_secs: u32,
        font_paths: Vec<String>,
        size_pt: f64,
        painter: Box<dyn painter::GlyphPainter>,
    ) {
        let auth = match auth_kind.as_str() {
            "password" => ssh::Auth::Password(secret),
            "key" => ssh::Auth::KeyPem {
                pem: secret,
                passphrase: passphrase.filter(|p| !p.is_empty()),
            },
            _ => ssh::Auth::KeyPath(secret),
        };
        let _ = self.tx.send(core::Cmd::Connect {
            params: core::ConnectParams {
                ssh: ssh::SshParams {
                    request_id,
                    host,
                    port,
                    user,
                    auth,
                    known_host: known_host.filter(|k| !k.is_empty()),
                    remote_command,
                    keepalive_secs: keepalive_secs as u64,
                },
                font_paths,
                size_pt,
                device_id,
            },
            painter,
        });
    }

    // ----- the App's views and commands, for the shell's own interface -----

    /// 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() {
            return "null".into();
        }
        ack.recv().unwrap_or_else(|_| "null".into())
    }

    /// A click on the tab strip or a pane's bar: "pane", "new-tab",
    /// "new-pane", "split-right", "split-below", "zoom", "close",
    /// "close-pane", "close-tab", "follow".
    pub fn chrome_click(&self, action: String, pane: Option<u32>, tab: Option<u32>) {
        let _ = self.tx.send(core::Cmd::ChromeClick { action, pane, tab });
    }

    /// A click in the sidebar: "thread", "window", "toggle-project",
    /// "new-thread", "pin", "delete", "archive", "unarchive"...
    pub fn side_click(&self, kind: String, id: Option<String>, flag: Option<bool>) {
        let _ = self.tx.send(core::Cmd::SideClick { kind, id, flag });
    }

    /// A key in the sidebar's text field ("Enter" commits, "Escape"
    /// cancels) with the field's text.
    pub fn side_key(&self, key: String, value: String) {
        let _ = self.tx.send(core::Cmd::SideKey { key, value });
    }

    /// The context menu for `kind` ("pane", "tab", "thread", "project",
    /// "space"...) and `id`, as JSON.
    pub fn context_menu(&self, kind: String, id: String) -> String {
        let (reply, ack) = mpsc::channel();
        if self
            .tx
            .send(core::Cmd::ContextMenu { kind, id, reply })
            .is_err()
        {
            return "[]".into();
        }
        ack.recv().unwrap_or_else(|_| "[]".into())
    }

    /// Do what a menu row asks; the outcome says whether it was handled
    /// and whether the shell should copy or paste.
    pub fn menu_action(&self, id: String) -> String {
        let (reply, ack) = mpsc::channel();
        if self.tx.send(core::Cmd::MenuAction { id, reply }).is_err() {
            return "{\"handled\":false,\"copy\":null,\"paste\":false}".into();
        }
        ack.recv().unwrap_or_default()
    }

    pub fn set_space(&self, id: String) {
        let _ = self.tx.send(core::Cmd::SetSpace(id));
    }

    pub fn take_over(&self) {
        let _ = self.tx.send(core::Cmd::TakeOver);
    }

    /// A touch on the terminal, in points: "down", "move" or "up".
    pub fn pointer(&self, kind: String, x: f64, y: f64) {
        let _ = self.tx.send(core::Cmd::Pointer { kind, x, y });
    }

    /// Scroll at a point by `lines`; positive is back into history.
    pub fn wheel(&self, x: f64, y: f64, lines: f64) {
        let _ = self.tx.send(core::Cmd::Wheel { x, y, lines });
    }

    /// Scroll at a point by `px` points of finger travel; positive is down
    /// the page, towards the newest row. The App keeps the fraction of a
    /// row, so this is what a drag with inertia sends.
    pub fn wheel_px(&self, x: f64, y: f64, px: f64) {
        let _ = self.tx.send(core::Cmd::WheelPx { x, y, px });
    }

    /// One of the App's preferences, as JSON: `set_setting("scroll-mode",
    /// "\"stepped\"")`. Kept by the core and applied to every App it makes.
    pub fn set_setting(&self, key: String, value: String) {
        let _ = self.tx.send(core::Cmd::SetSetting { key, value });
    }

    /// The terminal's colour scheme: one entry of `schemes.json` as JSON
    /// (`{"foreground":"#...","background":"#...","ansi":[...],...}`), or
    /// none to follow the host's own scheme. Kept like a setting.
    pub fn set_palette(&self, scheme: Option<String>) {
        let _ = self.tx.send(core::Cmd::SetPalette(scheme));
    }

    /// Scale the focused pane's font by a tenth per step; 0 resets.
    pub fn step_font(&self, by: f64) {
        let _ = self.tx.send(core::Cmd::StepFont(by));
    }

    /// The focused pane's visible rows as a document for the platform's
    /// text system, as JSON (`App::screen_text`); "null" without a pane.
    pub fn screen_text(&self) -> String {
        let (reply, ack) = mpsc::channel();
        if self.tx.send(core::Cmd::ScreenText { reply }).is_err() {
            return "null".into();
        }
        ack.recv().unwrap_or_else(|_| "null".into())
    }

    /// Select between two visible cells (row, col) of the focused pane.
    pub fn set_selection(&self, anchor_row: u32, anchor_col: u32, head_row: u32, head_col: u32) {
        let _ = self.tx.send(core::Cmd::SetSelection {
            anchor: (anchor_row as usize, anchor_col as usize),
            head: (head_row as usize, head_col as usize),
        });
    }

    pub fn clear_selection(&self) {
        let _ = self.tx.send(core::Cmd::ClearSelection);
    }

    /// The selected text of the focused pane, for the clipboard.
    /// Ask for the last `rows` rows of any pane; `on_preview` answers.
    pub fn request_preview(&self, pane: u32, rows: u32) {
        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() {
            return None;
        }
        ack.recv().unwrap_or(None)
    }

    pub fn disconnect(&self) {
        let _ = self.tx.send(core::Cmd::Disconnect);
    }

    /// A key by its DOM name ("Enter", "Backspace", "ArrowUp", "c"...).
    pub fn key(&self, name: String, ctrl: bool, alt: bool, shift: bool) {
        let _ = self.tx.send(core::Cmd::Key {
            name,
            ctrl,
            alt,
            shift,
        });
    }

    /// The IME is composing (a Pinyin buffer is open, say): keys are the
    /// IME's until it ends, and nothing reaches the pane meanwhile.
    pub fn set_composing(&self, on: bool) {
        let _ = self.tx.send(core::Cmd::Composing(on));
    }

    /// Committed text from the soft keyboard or an IME.
    pub fn text(&self, text: String) {
        let _ = self.tx.send(core::Cmd::Text(text));
    }

    pub fn paste(&self, text: String) {
        let _ = self.tx.send(core::Cmd::Paste(text));
    }

    /// Scroll the view by whole lines; positive is back into history.
    pub fn scroll(&self, lines: i32) {
        let _ = self.tx.send(core::Cmd::Scroll(lines));
    }

    /// Counters for the probe's screen: frames drawn, attach/detach
    /// generations, last frame time, errors, connection state.
    pub fn stats(&self) -> String {
        let (reply, ack) = mpsc::channel();
        if self.tx.send(core::Cmd::Stats { reply }).is_err() {
            return "core thread gone".into();
        }
        ack.recv().unwrap_or_else(|_| "core thread gone".into())
    }

    /// Stop the core thread. Blocks until it has exited.
    pub fn shutdown(&self) {
        let _ = self.tx.send(core::Cmd::Shutdown);
        if let Some(thread) = self.thread.lock().unwrap().take() {
            let _ = thread.join();
        }
    }
}

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);
        }
    }
}