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.

feat(plugins): add panels, background modes and remote asks

RoversX258a795e719c
diff --git a/Cargo.lock b/Cargo.lock
index 8e547461..96e5dcc2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8586,6 +8586,7 @@ dependencies = [
"serde",
"serde_json",
"tempfile",
+ "toml 0.8.23",
"wezterm-uds",
]
@@ -8600,6 +8601,15 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "thinkterm-plugin-panel"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "thinkterm-plugin-sdk"
version = "0.1.0"
@@ -8608,6 +8618,7 @@ dependencies = [
"serde",
"serde_json",
"thinkterm-plugin-channel",
+ "thinkterm-plugin-panel",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index e84a7d41..87c70f5b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,6 +16,7 @@ members = [
"thinkterm-mobile",
"thinkterm-plugin-channel",
"thinkterm-plugin-example",
+ "thinkterm-plugin-panel",
"thinkterm-plugin-sdk",
"thinkterm-plugin-server",
"thinkterm-session",
@@ -184,6 +185,7 @@ thinkterm-font-core = { path = "thinkterm-font-core" }
thinkterm-font-web = { path = "thinkterm-font-web" }
thinkterm-i18n = { path = "thinkterm-i18n" }
thinkterm-plugin-channel = { path = "thinkterm-plugin-channel", default-features = false }
+thinkterm-plugin-panel = { path = "thinkterm-plugin-panel" }
thinkterm-plugin-sdk = { path = "thinkterm-plugin-sdk" }
thinkterm-proto = { path = "thinkterm-proto" }
thinkterm-render = { path = "thinkterm-render" }
diff --git a/thinkterm-plugin-channel/Cargo.toml b/thinkterm-plugin-channel/Cargo.toml
index 16771c46..66ef73b9 100644
--- a/thinkterm-plugin-channel/Cargo.toml
+++ b/thinkterm-plugin-channel/Cargo.toml
@@ -8,14 +8,15 @@ publish = false
default = ["native"]
# Finding, starting and talking to the plugin host. Without it the crate is
# the message format alone, which a browser speaks through the mux.
-native = ["dep:anyhow", "dep:dirs-next", "dep:log", "dep:wezterm-uds"]
+native = ["dep:anyhow", "dep:dirs-next", "dep:log", "dep:toml", "dep:wezterm-uds"]
[dependencies]
anyhow = { workspace = true, optional = true }
dirs-next = { workspace = true, optional = true }
log = { workspace = true, optional = true }
serde = { workspace = true, features = ["derive", "std"] }
-serde_json.workspace = true
+serde_json = { workspace = true, features = ["raw_value"] }
+toml = { workspace = true, optional = true }
wezterm-uds = { workspace = true, optional = true }
[dev-dependencies]
diff --git a/thinkterm-plugin-channel/src/client.rs b/thinkterm-plugin-channel/src/client.rs
index 069cdf8c..a83f37b4 100644
--- a/thinkterm-plugin-channel/src/client.rs
+++ b/thinkterm-plugin-channel/src/client.rs
@@ -1,7 +1,7 @@
//! Reaching the host: connecting to it, starting it when nothing answers,
//! and replacing one that speaks an older protocol.
-use crate::wire::{read_frame, write_frame, FromHost, ToHost, PROTOCOL};
+use crate::wire::{read_frame, write_frame, FromHost, PanelEvent, PanelRequest, ToHost, PROTOCOL};
use anyhow::{anyhow, bail, Context};
use serde_json::Value;
use std::collections::HashMap;
@@ -245,6 +245,198 @@ impl Connection {
}
}
+/// How often a keeper looks at whether any plugin runs always: soon after
+/// one is chosen to, it runs.
+const KEEP_LOOK: Duration = Duration::from_secs(2);
+/// The pause before a keeper reaches the host again after losing it,
+/// doubling while the host stays away.
+const KEEP_RETRY_FIRST: Duration = Duration::from_secs(1);
+const KEEP_RETRY_LAST: Duration = Duration::from_secs(30);
+/// A keeper's stack: room to read a manifest nested as deep as the TOML
+/// parser lets one go (80 levels), which takes 512 KiB in a release build
+/// and 2 MiB in a debug one, unoptimized: twice that. A thread that runs
+/// out aborts the process -- the desktop, or the mux with every session.
+const KEEP_STACK: usize = if cfg!(debug_assertions) {
+ 4 * 1024 * 1024
+} else {
+ 1024 * 1024
+};
+
+/// Keeps the host up while any plugin runs always, for as long as this
+/// process runs, telling it this is ThinkTerm running on the machine
+/// (`registry::Request::Keep`): while one is connected so, those plugins
+/// run, and once none is, they stop with the host. For the desktop and the
+/// mux server. Which plugins run always is the host's word, in a file of
+/// its data directory ([`crate::paths::always`]): with none, no host is
+/// started or kept for this -- unless a plugin whose manifest says it runs
+/// always was installed where the host has not looked since, which the
+/// host is then started to look at.
+pub fn keep_host_up() {
+ let keeping = std::thread::Builder::new()
+ .name("plugin-keeper".into())
+ .stack_size(KEEP_STACK)
+ .spawn(|| {
+ let plugins = crate::paths::plugins_dir();
+ let mut manifests = Manifests::default();
+ let mut retry = KEEP_RETRY_FIRST;
+ loop {
+ // Read first, so that the host's answer marks what it looked at.
+ let unlooked = manifests.unlooked(&plugins);
+ if !unlooked && !any_runs_always() {
+ std::thread::sleep(KEEP_LOOK);
+ continue;
+ }
+ let kept = Host::for_this_build()
+ .map_err(anyhow::Error::from)
+ .and_then(|host| host.connect())
+ .and_then(|mut connection| {
+ keep(&mut connection)?;
+ connection.stream.set_read_timeout(Some(KEEP_LOOK))?;
+ Ok(connection)
+ });
+ match kept {
+ Ok(mut connection) => {
+ retry = KEEP_RETRY_FIRST;
+ // Held until the host goes, or nothing runs always
+ // any more. The host looks for new plugins at each
+ // `keep`, and has once it answers.
+ loop {
+ match connection.recv() {
+ Ok(FromHost::Ok { .. } | FromHost::Error { .. }) => {
+ manifests.looked();
+ }
+ Ok(_) => {}
+ Err(err) if is_timeout(&err) => {
+ if manifests.unlooked(&plugins) {
+ if keep(&mut connection).is_err() {
+ break;
+ }
+ } else if !any_runs_always() {
+ break;
+ }
+ }
+ Err(_) => break,
+ }
+ }
+ connection.shutdown();
+ }
+ Err(err) => log::info!("keeping the plugin host up: {err:#}"),
+ }
+ std::thread::sleep(retry);
+ retry = (retry * 2).min(KEEP_RETRY_LAST);
+ }
+ });
+ if let Err(err) = keeping {
+ log::warn!("cannot keep the plugin host up: {err}");
+ }
+}
+
+/// Tells the host this is ThinkTerm running on the machine.
+fn keep(connection: &mut Connection) -> io::Result<()> {
+ connection.send(&ToHost::Call {
+ id: 1,
+ plugin: crate::registry::PLUGIN.into(),
+ body: serde_json::json!({"op": "keep"}),
+ })
+}
+
+/// Whether the host last said some plugin runs always.
+fn any_runs_always() -> bool {
+ std::fs::read_to_string(crate::paths::always())
+ .is_ok_and(|ids| ids.lines().any(|id| !id.trim().is_empty()))
+}
+
+/// What a keeper knows of the installed plugins' manifests, each read again
+/// only once it changed: whether it says its plugin runs always, and
+/// whether the host has looked at it as it is since. Only the host says
+/// for sure what runs always -- a plugin can be off, or not for this
+/// system -- so a manifest that says so has it looked at once.
+#[derive(Default)]
+struct Manifests {
+ known: HashMap<PathBuf, Known>,
+}
+
+struct Known {
+ changed: (Option<std::time::SystemTime>, u64),
+ always: bool,
+ looked: bool,
+}
+
+impl Manifests {
+ /// Whether a manifest under `plugins`, a plugins directory, says its
+ /// plugin runs always and has not been looked at as it is.
+ fn unlooked(&mut self, plugins: &Path) -> bool {
+ let Ok(entries) = fs::read_dir(plugins) else {
+ self.known.clear();
+ return false;
+ };
+ let mut found = std::collections::HashSet::new();
+ for entry in entries
+ .filter_map(Result::ok)
+ .take(crate::registry::DIR_LIMIT)
+ {
+ if entry.file_name().to_string_lossy().starts_with('.') {
+ continue;
+ }
+ let manifest = entry.path().join("plugin.toml");
+ let Ok(meta) = fs::metadata(&manifest) else {
+ continue;
+ };
+ let changed = (meta.modified().ok(), meta.len());
+ if !self
+ .known
+ .get(&manifest)
+ .is_some_and(|known| known.changed == changed)
+ {
+ let always = says_always(&manifest);
+ self.known.insert(
+ manifest.clone(),
+ Known {
+ changed,
+ always,
+ looked: false,
+ },
+ );
+ }
+ found.insert(manifest);
+ }
+ self.known.retain(|manifest, _| found.contains(manifest));
+ self.known
+ .values()
+ .any(|known| known.always && !known.looked)
+ }
+
+ /// The host has looked at every manifest as it last was.
+ fn looked(&mut self) {
+ for known in self.known.values_mut() {
+ known.looked = true;
+ }
+ }
+}
+
+/// Whether the manifest at `path` says its plugin runs always.
+fn says_always(path: &Path) -> bool {
+ #[derive(serde::Deserialize)]
+ struct Manifest {
+ #[serde(default)]
+ run: Option<Run>,
+ }
+ #[derive(serde::Deserialize)]
+ struct Run {
+ #[serde(default)]
+ background: Option<String>,
+ }
+ fs::read_to_string(path)
+ .ok()
+ .and_then(|text| toml::from_str::<Manifest>(&text).ok())
+ .and_then(|manifest| manifest.run?.background)
+ .is_some_and(|background| background == "always")
+}
+
+fn is_timeout(err: &io::Error) -> bool {
+ matches!(err.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut)
+}
+
/// A call's answer, or why there is none.
pub type Answer = Result<Value, String>;
@@ -263,6 +455,8 @@ pub const CALL_TIMEOUT: Duration = Duration::from_secs(10);
/// own: the host is started when it is not running, a lost connection is
/// made again with a pause that grows while the host keeps going away, and
/// every call is answered, with an error when the host cannot answer it.
+/// A plugin's panel lives on one connection: one lost takes its panels
+/// with it, and the owner opens them again when told it is connected.
/// Dropping the session ends it.
pub struct Session {
jobs: Sender<Job>,
@@ -280,6 +474,7 @@ struct Call {
enum Job {
Call(Call),
+ Panel(u64, PanelRequest),
/// What the host sent over connection number `.0`.
Heard(u64, io::Result<FromHost>),
Stop,
@@ -288,13 +483,16 @@ enum Job {
/// What a session tells its owner, on the session's thread.
#[derive(Debug)]
pub enum Notice {
- /// Connected, for the first time or again: whatever the owner follows
- /// is to be asked for anew.
- Connected,
+ /// Connected, for the first time or `again`: whatever the owner follows
+ /// is to be asked for anew, and, connected again, its panels opened
+ /// anew -- the last connection took them with it.
+ Connected { again: bool },
/// The host cannot be reached, and why. The session keeps trying.
Trouble(String),
/// Something a plugin told the clients watching it.
Event { plugin: String, body: Value },
+ /// About the owner's panel `view`.
+ Panel { view: u64, event: PanelEvent },
}
impl Session {
@@ -341,6 +539,13 @@ impl Session {
(call.reply)(Err("the plugin session has ended".into()));
}
}
+
+ /// Tells the host about the owner's panel `view`. Made while there is
+ /// no connection, it goes nowhere: the panels are opened again once
+ /// there is.
+ pub fn panel(&self, view: u64, request: PanelRequest) {
+ let _ = self.jobs.send(Job::Panel(view, request));
+ }
}
impl Drop for Session {
@@ -370,6 +575,9 @@ fn serve_session(
let mut retry = SESSION_RETRY_FIRST;
// Calls made while there was no connection, sent on the next one.
let mut queued: Vec<Call> = Vec::new();
+ // Something about a panel went nowhere: the owner opens its panels
+ // again on the next connection, the first one included.
+ let mut panels_lost = false;
loop {
let connected = host.connect().and_then(|connection| {
let reader = connection.try_clone()?;
@@ -383,7 +591,7 @@ fn serve_session(
(call.reply)(Err(why.clone()));
}
notice(Notice::Trouble(why));
- if !pause(&queue, retry, &mut queued) {
+ if !pause(&queue, retry, &mut queued, &mut panels_lost) {
return;
}
retry = (retry * 2).min(SESSION_RETRY_LAST);
@@ -405,12 +613,15 @@ fn serve_session(
if let Err(err) = listening {
log::warn!("cannot read from the plugin host: {err}");
connection.shutdown();
- if !pause(&queue, retry, &mut queued) {
+ if !pause(&queue, retry, &mut queued, &mut panels_lost) {
return;
}
continue;
}
- notice(Notice::Connected);
+ notice(Notice::Connected {
+ again: generation > 1 || panels_lost,
+ });
+ panels_lost = false;
let mut waiting = Waiting::new();
let mut alive = true;
@@ -439,6 +650,10 @@ fn serve_session(
Ok(Job::Call(call)) => {
alive = send_call(&mut connection, &mut next_id, &mut waiting, call)
}
+ Ok(Job::Panel(view, request)) => {
+ alive = connection.send(&ToHost::Panel { view, request }).is_ok();
+ panels_lost |= !alive;
+ }
Ok(Job::Heard(from, _)) if from != generation => {}
Ok(Job::Heard(_, Ok(FromHost::Ok { id, body }))) => {
retry = SESSION_RETRY_FIRST;
@@ -454,6 +669,9 @@ fn serve_session(
Ok(Job::Heard(_, Ok(FromHost::Event { plugin, body }))) => {
notice(Notice::Event { plugin, body })
}
+ Ok(Job::Heard(_, Ok(FromHost::Panel { view, event }))) => {
+ notice(Notice::Panel { view, event })
+ }
Ok(Job::Heard(_, Ok(FromHost::Hello { .. }))) => {}
Ok(Job::Heard(_, Err(_))) => alive = false,
Ok(Job::Stop) | Err(()) => {
@@ -471,7 +689,7 @@ fn serve_session(
}
// A host that answered reset this; one that keeps failing is asked
// less and less often.
- if !pause(&queue, retry, &mut queued) {
+ if !pause(&queue, retry, &mut queued, &mut panels_lost) {
return;
}
retry = (retry * 2).min(SESSION_RETRY_LAST);
@@ -529,9 +747,15 @@ fn give_up_overdue(waiting: &mut Waiting) {
}
/// Waits `delay` before the next attempt, keeping the calls made meanwhile;
-/// a call cuts the wait short, since someone is waiting on it. False when
-/// the session was ended.
-fn pause(queue: &Receiver<Job>, delay: Duration, queued: &mut Vec<Call>) -> bool {
+/// a call cuts the wait short, since someone is waiting on it. What is said
+/// about a panel meanwhile goes nowhere, and `panels_lost` says so. False
+/// when the session was ended.
+fn pause(
+ queue: &Receiver<Job>,
+ delay: Duration,
+ queued: &mut Vec<Call>,
+ panels_lost: &mut bool,
+) -> bool {
let until = Instant::now() + delay;
loop {
let left = until.saturating_duration_since(Instant::now());
@@ -544,8 +768,70 @@ fn pause(queue: &Receiver<Job>, delay: Duration, queued: &mut Vec<Call>) -> bool
return true;
}
Ok(Job::Heard(..)) => {}
+ Ok(Job::Panel(..)) => *panels_lost = true,
Ok(Job::Stop) | Err(RecvTimeoutError::Disconnected) => return false,
Err(RecvTimeoutError::Timeout) => return true,
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_manifest_that_says_it_runs_always_is_looked_at_once_as_it_is() {
+ let dir = tempfile::tempdir().unwrap();
+ let plugins = dir.path().join("plugins");
+ let mut manifests = Manifests::default();
+ assert!(!manifests.unlooked(&plugins), "nothing installed");
+ let install = |name: &str, run: &str| {
+ let at = plugins.join(name);
+ fs::create_dir_all(&at).unwrap();
+ let manifest = format!("id = \"{name}\"\nname = \"N\"\napi = 1\n[run]\n{run}\n");
+ fs::write(at.join("plugin.toml"), manifest).unwrap();
+ };
+ install("a", "program = \"a\"");
+ install("b", "program = \"b\"\nbackground = \"never\"");
+ fs::create_dir_all(plugins.join(".hidden")).unwrap();
+ assert!(!manifests.unlooked(&plugins), "none says it runs always");
+
+ install("c", "program = \"c\"\nbackground = \"always\"");
+ assert!(manifests.unlooked(&plugins), "the host has to say");
+ assert!(manifests.unlooked(&plugins), "until it has looked");
+ manifests.looked();
+ assert!(!manifests.unlooked(&plugins), "looked at, as it is");
+
+ install("c", "program = \"c2\"\nbackground = \"always\"");
+ assert!(manifests.unlooked(&plugins), "changed since");
+ manifests.looked();
+ fs::remove_dir_all(plugins.join("c")).unwrap();
+ assert!(!manifests.unlooked(&plugins));
+ assert_eq!(manifests.known.len(), 2, "what is gone is let go of");
+ }
+
+ #[test]
+ fn a_manifest_nested_as_deep_as_toml_goes_is_read_on_a_keepers_stack() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("plugin.toml");
+ // The parser takes 80 levels, and refuses more.
+ let deepest = |open: &str, close: &str| {
+ format!(
+ "id = \"a\"\nx = {}1{}\n[run]\nbackground = \"always\"\n",
+ open.repeat(79),
+ close.repeat(79)
+ )
+ };
+ for manifest in [deepest("[", "]"), deepest("{a=", "}")] {
+ fs::write(&path, manifest).unwrap();
+ let path = path.clone();
+ let read = std::thread::Builder::new()
+ .stack_size(KEEP_STACK)
+ .spawn(move || says_always(&path))
+ .unwrap()
+ .join()
+ .unwrap();
+ assert!(read, "read, not aborted");
+ }
+ }
+}
diff --git a/thinkterm-plugin-channel/src/paths.rs b/thinkterm-plugin-channel/src/paths.rs
index cf235841..00181e12 100644
--- a/thinkterm-plugin-channel/src/paths.rs
+++ b/thinkterm-plugin-channel/src/paths.rs
@@ -31,6 +31,30 @@ pub fn plugins_dir_in(data_dir: &Path) -> PathBuf {
data_dir.join("plugins")
}
+/// Where the host writes the plugins that run always, one id a line, for
+/// ThinkTerm to keep it up for them; there is no file while none does.
+/// Scoped to the build profile, as the host's socket is: a debug build's
+/// ThinkTerm keeps the debug host up, not a second host for the release
+/// build's plugins.
+pub fn always() -> PathBuf {
+ always_in(&data_dir())
+}
+
+/// [`always`], for a host keeping its data in `data_dir`.
+pub fn always_in(data_dir: &Path) -> PathBuf {
+ data_dir.join(profile_scoped("plugins-always"))
+}
+
+/// Whether anything is installed in `dir`, a plugins directory: an entry
+/// that is not hidden. Reads the directory, so off a thread that paints.
+pub fn any_installed(dir: &Path) -> bool {
+ std::fs::read_dir(dir).is_ok_and(|mut entries| {
+ entries.any(|entry| {
+ entry.is_ok_and(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
+ })
+ })
+}
+
fn home_dir() -> PathBuf {
dirs_next::home_dir().unwrap_or_default()
}
@@ -39,12 +63,15 @@ fn home_dir() -> PathBuf {
/// `runtime_file_name` scopes the mux's files: a debug build never reaches
/// the release build's host.
fn runtime_file(base: &str) -> PathBuf {
- let name = if cfg!(debug_assertions) {
+ runtime_dir().join(profile_scoped(base))
+}
+
+fn profile_scoped(base: &str) -> String {
+ if cfg!(debug_assertions) {
format!("{base}-debug")
} else {
base.to_string()
- };
- runtime_dir().join(name)
+ }
}
pub fn socket() -> PathBuf {
diff --git a/thinkterm-plugin-channel/src/registry.rs b/thinkterm-plugin-channel/src/registry.rs
index 25e36d65..22c889e2 100644
--- a/thinkterm-plugin-channel/src/registry.rs
+++ b/thinkterm-plugin-channel/src/registry.rs
@@ -1,12 +1,49 @@
//! The plugin host's own API: the plugins it knows, turning them on and
-//! off, and reloading them. It is called as the plugin named [`PLUGIN`],
-//! and its events go to every client that asked for the list.
+//! off, how long they run unused, and reloading them. It is called as the
+//! plugin named [`PLUGIN`], and its events go to every client that asked
+//! for the list.
use serde::{Deserialize, Serialize};
+use std::time::Duration;
/// The name calls address and events carry.
pub const PLUGIN: &str = "plugins";
+/// Directories looked at in the plugins directory; one with more than this
+/// is not a plugins directory someone keeps by hand.
+pub const DIR_LIMIT: usize = 256;
+
+/// How long an installed plugin's program runs while nothing uses it --
+/// no panel of it on show, no call to it unanswered, no client watching
+/// it. Its manifest says which it needs; the user can choose another.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Background {
+ /// Started with ThinkTerm and kept running for as long as ThinkTerm
+ /// runs on the machine: its desktop or its mux server.
+ Always,
+ /// Stopped when it has not been used for [`Background::BRIEFLY`].
+ #[default]
+ Briefly,
+ /// Stopped once it has not been used for [`Background::NEVER`]: a
+ /// moment, so that a panel shown again at once finds it running.
+ Never,
+}
+
+impl Background {
+ pub const BRIEFLY: Duration = Duration::from_secs(120);
+ pub const NEVER: Duration = Duration::from_secs(10);
+
+ /// How long it runs unused, `None` for as long as ThinkTerm does.
+ pub fn unused_for(self) -> Option<Duration> {
+ match self {
+ Self::Always => None,
+ Self::Briefly => Some(Self::BRIEFLY),
+ Self::Never => Some(Self::NEVER),
+ }
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Request {
@@ -20,6 +57,19 @@ pub enum Request {
/// Turn a plugin on or off. Answered with `null`; the change is
/// announced.
SetEnabled { id: String, enabled: bool },
+ /// Choose how long a plugin runs unused; `None` goes back to what its
+ /// manifest says. Answered with `null`; the change is announced.
+ SetBackground {
+ id: String,
+ #[serde(default)]
+ background: Option<Background>,
+ },
+ /// The caller is ThinkTerm running on this machine -- a desktop or a
+ /// mux server -- and stays connected for as long as it runs: while one
+ /// is, the plugins that run [`Background::Always`] do. The host looks
+ /// for new plugins first, so that one installed meanwhile is among
+ /// them. Answered with `null`.
+ Keep,
/// Stop a plugin, read its manifest again and forget that it failed;
/// every installed plugin when `id` is absent, looking for new and
/// removed ones too. Answered with `null`; the change is announced.
@@ -46,6 +96,26 @@ pub struct Info {
pub dir: Option<String>,
pub enabled: bool,
pub state: State,
+ /// The panel it adds to the right sidebar, if it adds one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub panel: Option<Panel>,
+ /// How long it runs unused: the user's choice, else its manifest's.
+ /// A built-in plugin runs inside the host, and is never started or
+ /// stopped: this is its default.
+ #[serde(default)]
+ pub background: Background,
+ /// What its manifest says, which the user's choice is shown against.
+ #[serde(default)]
+ pub background_default: Background,
+}
+
+/// A plugin's panel in the right sidebar, which the selector offers under
+/// the plugin's name.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Panel {
+ /// A Lucide icon's name, for the selector; one a client does not have
+ /// shows as a puzzle piece.
+ pub icon: String,
}
impl Info {
@@ -134,6 +204,28 @@ mod tests {
Request::Reload { id: None }
);
assert!(serde_json::from_value::<Request>(json!({"op": "run"})).is_err());
+ assert_eq!(
+ serde_json::from_value::<Request>(
+ json!({"op": "set_background", "id": "a", "background": "always"})
+ )
+ .unwrap(),
+ Request::SetBackground {
+ id: "a".into(),
+ background: Some(Background::Always)
+ }
+ );
+ assert_eq!(
+ serde_json::from_value::<Request>(json!({"op": "set_background", "id": "a"})).unwrap(),
+ Request::SetBackground {
+ id: "a".into(),
+ background: None
+ },
+ "none goes back to the manifest's"
+ );
+ assert_eq!(to_value(Request::Keep).unwrap(), json!({"op": "keep"}));
+ assert_eq!(Background::default(), Background::Briefly);
+ assert_eq!(Background::Always.unused_for(), None);
+ assert_eq!(Background::Never.unused_for(), Some(Background::NEVER));
assert_eq!(
to_value(State::Crashed {
reason: "exit status 1".into()
@@ -159,6 +251,9 @@ mod tests {
dir: None,
enabled: true,
state: State::Idle,
+ panel: None,
+ background: Background::Briefly,
+ background_default: Background::Briefly,
};
assert!(info.usable());
info.state = State::Failed {
diff --git a/thinkterm-plugin-channel/src/wire.rs b/thinkterm-plugin-channel/src/wire.rs
index e2d3820f..2c9446bd 100644
--- a/thinkterm-plugin-channel/src/wire.rs
+++ b/thinkterm-plugin-channel/src/wire.rs
@@ -1,15 +1,19 @@
//! The messages, and the frames that carry them.
+use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
+use serde_json::value::RawValue;
use serde_json::Value;
+use std::fmt;
use std::io::{self, Read, Write};
/// The version of this format and of what the host answers. A client that
/// finds a host speaking an older one asks it to quit and starts its own;
/// one that finds a newer host leaves it alone. 2 added the host's own API
/// (`registry`) and installed plugins; 3 took commands and notifications
-/// out of it.
-pub const PROTOCOL: u32 = 3;
+/// out of it; 4 added plugins' panels; 5 what a panel's plugin asks of
+/// another machine, and how long plugins run unused.
+pub const PROTOCOL: u32 = 5;
/// The largest frame either side sends or accepts, so a confused peer
/// cannot have the other allocate without bound. A thousand scripts of
@@ -26,6 +30,8 @@ pub enum ToHost {
plugin: String,
body: Value,
},
+ /// About a panel the client shows, `view` being its own number for it.
+ Panel { view: u64, request: PanelRequest },
/// Exit now: a newer build is replacing this host.
Quit,
}
@@ -50,6 +56,103 @@ pub enum FromHost {
plugin: String,
body: Value,
},
+ /// About the client's panel `view`.
+ Panel {
+ view: u64,
+ event: PanelEvent,
+ },
+}
+
+/// What a client asks of a plugin's panel it shows. What the panel's
+/// messages say -- the `thinkterm-plugin-panel` types, as JSON -- is
+/// between the client and the plugin: the host carries them unread.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PanelRequest {
+ /// Show plugin `plugin`'s panel for an `Env`: its program is started
+ /// if it is not running. An open under a number the client already
+ /// uses replaces that panel. With `extends`, the client's number for a
+ /// panel of the same plugin whose frame asked for it (`Frame::extend`),
+ /// it is that panel's extended view instead, and closes with it.
+ Open {
+ plugin: String,
+ env: Raw,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ extends: Option<u64>,
+ },
+ /// Its size, fonts or theme changed: an `Env`.
+ Env { env: Raw },
+ /// What the user did in it: an `Input`.
+ Input { input: Raw },
+ /// Rows of one of its lists: a `RowsWanted`.
+ Rows { wanted: Raw },
+ /// The client has taken in the last frame, and can take the next. A
+ /// panel is sent one frame at a time: the newest is held back until
+ /// the client has the one before, and any older one is dropped, so a
+ /// plugin drawing faster than a client keeps up never queues frames.
+ Shown,
+ /// It went off show.
+ Close,
+ /// What came of what the plugin asked, [`PanelEvent::Remote`] `id`: an
+ /// `Answer`.
+ Answer { id: u64, answer: Raw },
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PanelEvent {
+ /// The plugin drew the panel: a `Frame`.
+ Frame { frame: Raw },
+ /// Rows the client asked for: a `Rows`.
+ Rows { rows: Raw },
+ /// The panel is no longer served: its plugin stopped, went off, or
+ /// could not start. With `again`, opening it anew may work -- the
+ /// plugin was restarted, or was on its way out -- and the client may
+ /// try after a pause.
+ Closed { reason: String, again: bool },
+ /// The plugin asks something of `machine`, the one the client told it
+ /// the terminal beside the panel runs on (`Env::remote`): an `Ask`,
+ /// answered with [`PanelRequest::Answer`] and the same `id`. The client
+ /// does it only while the terminal is still on that machine.
+ Remote { id: u64, machine: String, ask: Raw },
+}
+
+/// JSON passed along unread: parsed only far enough to know where it ends,
+/// and written out as it came.
+#[derive(Clone, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct Raw(Box<RawValue>);
+
+impl Raw {
+ pub fn new<T: Serialize + ?Sized>(value: &T) -> Self {
+ Self(serde_json::value::to_raw_value(value).expect("a panel message always serialises"))
+ }
+
+ /// A copy of JSON borrowed from what it was read out of.
+ pub fn copy_of(raw: &RawValue) -> Self {
+ Self(raw.to_owned())
+ }
+
+ /// What it says, read as a `T`.
+ pub fn read<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
+ serde_json::from_str(self.0.get())
+ }
+
+ pub fn get(&self) -> &str {
+ self.0.get()
+ }
+}
+
+impl PartialEq for Raw {
+ fn eq(&self, other: &Self) -> bool {
+ self.get() == other.get()
+ }
+}
+
+impl fmt::Debug for Raw {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(self.get())
+ }
}
impl ToHost {
@@ -137,6 +240,99 @@ mod tests {
assert_eq!(FromHost::decode(&hello.encode()).unwrap(), hello);
}
+ #[test]
+ fn a_panel_message_is_carried_as_it_was_written() {
+ let frame =
+ br#"{"panel":{"view":3,"event":{"frame":{"frame":{"items":[ {"rect":{"x":1}} ]}}}}}"#;
+ let decoded = FromHost::decode(frame).unwrap();
+ let FromHost::Panel {
+ view: 3,
+ event: PanelEvent::Frame { frame: raw },
+ } = &decoded
+ else {
+ panic!("{decoded:?}")
+ };
+ assert_eq!(
+ raw.get(),
+ r#"{"items":[ {"rect":{"x":1}} ]}"#,
+ "unread, spaces and all"
+ );
+ assert_eq!(
+ raw.read::<Value>().unwrap(),
+ json!({"items": [{"rect": {"x": 1}}]})
+ );
+ assert_eq!(FromHost::decode(&decoded.encode()).unwrap(), decoded);
+
+ let open = ToHost::Panel {
+ view: 1,
+ request: PanelRequest::Open {
+ plugin: "stocks".into(),
+ env: Raw::new(&json!({"width": 300})),
+ extends: None,
+ },
+ };
+ assert_eq!(
+ serde_json::to_value(&open).unwrap(),
+ json!({"panel": {"view": 1, "request": {"open": {"plugin": "stocks", "env": {"width": 300}}}}})
+ );
+ let extended = ToHost::decode(
+ br#"{"panel": {"view": 2, "request": {"open": {"plugin": "diff", "env": {}, "extends": 1}}}}"#,
+ )
+ .unwrap();
+ assert!(
+ matches!(
+ extended,
+ ToHost::Panel {
+ view: 2,
+ request: PanelRequest::Open {
+ extends: Some(1),
+ ..
+ }
+ }
+ ),
+ "{extended:?}"
+ );
+ let shown = ToHost::Panel {
+ view: 1,
+ request: PanelRequest::Shown,
+ };
+ assert_eq!(
+ serde_json::to_value(&shown).unwrap(),
+ json!({"panel": {"view": 1, "request": "shown"}})
+ );
+ assert_eq!(ToHost::decode(&shown.encode()).unwrap(), shown);
+
+ let asked = FromHost::decode(
+ br#"{"panel": {"view": 4, "event": {"remote": {"id": 9, "machine": "m1", "ask": {"op": "stat", "path": "/x"}}}}}"#,
+ )
+ .unwrap();
+ let FromHost::Panel {
+ view: 4,
+ event:
+ PanelEvent::Remote {
+ id: 9,
+ machine,
+ ask,
+ },
+ } = &asked
+ else {
+ panic!("{asked:?}")
+ };
+ assert_eq!(machine, "m1");
+ assert_eq!(ask.get(), r#"{"op": "stat", "path": "/x"}"#);
+ let answer = ToHost::Panel {
+ view: 4,
+ request: PanelRequest::Answer {
+ id: 9,
+ answer: Raw::new(&json!({"result": "failed", "why": "no"})),
+ },
+ };
+ assert_eq!(
+ serde_json::to_value(&answer).unwrap(),
+ json!({"panel": {"view": 4, "request": {"answer": {"id": 9, "answer": {"result": "failed", "why": "no"}}}}})
+ );
+ }
+
#[test]
fn frames_round_trip_and_refuse_what_is_too_long() {
let mut wire = Vec::new();
diff --git a/thinkterm-plugin-panel/Cargo.toml b/thinkterm-plugin-panel/Cargo.toml
new file mode 100644
index 00000000..a048699c
--- /dev/null
+++ b/thinkterm-plugin-panel/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "thinkterm-plugin-panel"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# A plugin's panel in the right sidebar: the picture a plugin draws, what it
+# is told back, and the player every ThinkTerm client shows the picture with.
+# Plain data and arithmetic, so it builds anywhere, WebAssembly included.
+
+[dependencies]
+base64 = { workspace = true, features = ["std"] }
+serde = { workspace = true, features = ["derive", "std"] }
+serde_json = { workspace = true, features = ["raw_value"] }
diff --git a/thinkterm-plugin-panel/src/lib.rs b/thinkterm-plugin-panel/src/lib.rs
new file mode 100644
index 00000000..2aecded9
--- /dev/null
+++ b/thinkterm-plugin-panel/src/lib.rs
@@ -0,0 +1,55 @@
+//! A plugin's panel in ThinkTerm's right sidebar.
+//!
+//! A plugin draws its panel by hand: it sends a [`Frame`], a list of
+//! rectangles, text, lines, filled areas and the hits that make parts of it
+//! answer a click, in the panel's own units. Every ThinkTerm client shows
+//! it with the same [`Player`], painting its items with the client's own
+//! renderer and fonts and in ThinkTerm's colours, so a panel looks the same
+//! on the desktop and in a browser without the plugin knowing which it is.
+//!
+//! The player never waits for the plugin. Hovering and scrolling happen in
+//! it at once; a click is sent to the plugin, which answers with a new
+//! frame when it is ready. A long list is drawn a page of rows at a time,
+//! as the player asks for them, so a plugin with ten thousand rows sends
+//! the few dozen that show.
+//!
+//! A panel whose frame asks for it (`Frame::extend`) gets an extended view
+//! as well: a wide area beside the sidebar, which the client opens as a
+//! second view of the panel and shows with a player of its own.
+//!
+//! What passes to and fro goes over the plugin channel and the plugin
+//! protocol as JSON (docs/thinkterm/plugins.md): [`Env`] and [`Input`] to
+//! the plugin, [`Frame`] and [`Rows`] from it. A panel beside a terminal on
+//! another machine ([`Env::remote`]) has its plugin [`Ask`] the client for
+//! what it wants done there, which the client answers ([`Answer`]).
+
+pub mod player;
+pub mod scene;
+pub mod wire;
+
+/// The Lucide icons a panel can be shown by in the sidebar's selector;
+/// every client has these. A manifest naming another gets the first.
+pub const ICONS: [&str; 12] = [
+ "puzzle",
+ "activity",
+ "bug",
+ "calendar",
+ "chart-candlestick",
+ "chart-line",
+ "cpu",
+ "database",
+ "gauge",
+ "git-branch",
+ "git-compare",
+ "list-todo",
+];
+
+pub use player::{Draw, Drawn, Op, Painting, Player};
+pub use scene::{
+ Align, Area, Bounds, Color, Cursor, Font, Frame, Hit, Item, Jump, Line, List, Rect, Scroll,
+ Size, Text, Token,
+};
+pub use wire::{
+ Answer, Ask, Button, Bytes, Click, CloseButton, Entry, EntryKind, Env, Input, Mods,
+ MonoMetrics, Remote, Rows, RowsWanted, TextMetrics,
+};
diff --git a/thinkterm-plugin-panel/src/player.rs b/thinkterm-plugin-panel/src/player.rs
new file mode 100644
index 00000000..c958365b
--- /dev/null
+++ b/thinkterm-plugin-panel/src/player.rs
@@ -0,0 +1,1731 @@
+//! Showing a panel: the frame its plugin sent last, the rows of its lists
+//! near the view, how far its scroll areas are scrolled, and what the
+//! pointer is over. Nothing here waits for the plugin. A paint draws what
+//! has arrived; a scroll moves at once and asks for the rows it will need
+//! next; a hover tints at once.
+//!
+//! A client paints what [`Player::draw`] gives it with its own renderer,
+//! and hands the pointer and the wheel in. What is to go to the plugin
+//! comes back from [`Player::click`] and [`Player::wanted`].
+
+use crate::scene::{
+ Align, Area, Bounds, Color, Cursor, Font, Frame, Hit, Item, Line, List, Rect, Scroll, Size,
+ Text,
+};
+use crate::wire::{Button, Click, Env, Input, Mods, Rows, RowsWanted};
+use serde::Serialize;
+use std::collections::HashMap;
+
+/// Items a frame may hold, its scroll areas' included, and a page of rows;
+/// the rest are dropped. Far more than a panel shows.
+pub const ITEM_LIMIT: usize = 20_000;
+/// Rows a list keeps. The ones furthest from the view go first.
+pub const ROW_LIMIT: usize = 2_048;
+/// The longest text drawn, in characters: the part a panel can show, and
+/// no burden on the shaper.
+pub const TEXT_LIMIT: usize = 2_000;
+/// The most numbers a line or an area is drawn through.
+pub const POINT_LIMIT: usize = 8_192;
+/// Pages of rows one list may be waiting for at once.
+const ASKING_LIMIT: usize = 3;
+/// Rows are asked for a screenful at a time, and never fewer than this.
+const PAGE_MIN: u32 = 32;
+/// A scrollbar's thumb: how wide, how far in from the edge, how short at
+/// the shortest.
+const THUMB_WIDTH: f32 = 4.0;
+const THUMB_GAP: f32 = 2.0;
+const THUMB_MIN: f32 = 16.0;
+
+/// One thing to paint, in order: what, moved by `dx`, `dy` from its own
+/// units to the panel's, and cut to `clip`.
+#[derive(Debug, Clone, Copy)]
+pub struct Draw<'a> {
+ pub what: Drawn<'a>,
+ pub dx: f32,
+ pub dy: f32,
+ pub clip: Bounds,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub enum Drawn<'a> {
+ Rect(&'a Rect),
+ Text(&'a Text),
+ Line(&'a Line),
+ Area(&'a Area),
+ /// A hit the pointer is over, to be filled with its `hover` where it is
+ /// in the order: under what the plugin drew after it.
+ Hover(&'a Hit),
+ /// The thumb of a scroll area or a list taller than it shows, in the
+ /// panel's units already.
+ Thumb(Bounds),
+}
+
+/// What [`Player::draw`] gives, as plain data in the panel's units: for a
+/// client that paints in another language -- the page's script, a phone's
+/// own toolkit -- and so cannot hold the player's items.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct Painting {
+ /// The regions the ops are cut to, as left, top, right, bottom; each op
+ /// names its own by index.
+ pub clips: Vec<[f32; 4]>,
+ pub ops: Vec<Op>,
+ /// Over what the pointer is, the cursor to show; none over the rest.
+ pub cursor: Option<Cursor>,
+}
+
+/// One thing to paint, in the panel's units, moved into place already.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(tag = "op", rename_all = "snake_case")]
+pub enum Op {
+ Rect {
+ clip: usize,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ fill: Option<Color>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ border: Option<Color>,
+ radius: f32,
+ },
+ Text {
+ clip: usize,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ text: String,
+ color: Color,
+ font: Font,
+ size: Size,
+ bold: bool,
+ align: Align,
+ },
+ /// Through `points`, x, y and so on.
+ Line {
+ clip: usize,
+ points: Vec<f32>,
+ width: f32,
+ color: Color,
+ },
+ Area {
+ clip: usize,
+ points: Vec<f32>,
+ base: f32,
+ color: Color,
+ fade: bool,
+ },
+ /// A scrollbar's thumb, in the client's own colour for one.
+ Thumb {
+ clip: usize,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ },
+}
+
+/// Where a hit is: which item, and inside what.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Spot {
+ /// The frame's item at this index.
+ Top(usize),
+ /// Item `.1` of the scroll area at index `.0`.
+ Scrolled(usize, usize),
+ /// Item `.2` of row `.1` of the list at index `.0`.
+ Row(usize, u32, usize),
+}
+
+struct ScrollState {
+ offset: f32,
+ /// The last jump taken.
+ seq: Option<u32>,
+}
+
+struct ListState {
+ key: String,
+ version: u32,
+ count: u32,
+ offset: f32,
+ /// How far its rows are scrolled sideways.
+ offset_x: f32,
+ seq: Option<u32>,
+ rows: HashMap<u32, Kept>,
+ /// Pages asked for and not had: where each starts and ends.
+ asking: Vec<(u32, u32)>,
+}
+
+/// A row kept, and what it was drawn for: a list's version and the
+/// panel's layout. One drawn for others stays on show until it is drawn
+/// anew.
+struct Kept {
+ version: u32,
+ layout: u32,
+ items: Vec<Item>,
+}
+
+pub struct Player {
+ env: Env,
+ frame: Frame,
+ shown: bool,
+ /// Counts changes to what [`draw`](Self::draw) gives.
+ revision: u64,
+ /// Counts what makes the rows drawn before out of date: the panel's
+ /// size and fonts changing, which rows are drawn for, and the plugin
+ /// starting again, which may draw them otherwise under the same key
+ /// and version. A row drawn for another is asked for again.
+ layout: u32,
+ lists: HashMap<String, ListState>,
+ scrolls: HashMap<String, ScrollState>,
+ pointer: Option<(f32, f32)>,
+ hover: Option<Spot>,
+ wanted: Vec<RowsWanted>,
+}
+
+impl Player {
+ /// A panel of `env`'s size, blank until its plugin sends a frame.
+ pub fn new(env: Env) -> Self {
+ Self {
+ env,
+ frame: Frame::default(),
+ shown: false,
+ revision: 0,
+ layout: 0,
+ lists: HashMap::new(),
+ scrolls: HashMap::new(),
+ pointer: None,
+ hover: None,
+ wanted: Vec::new(),
+ }
+ }
+
+ pub fn env(&self) -> &Env {
+ &self.env
+ }
+
+ /// Whether the plugin has drawn the panel yet.
+ pub fn shown(&self) -> bool {
+ self.shown
+ }
+
+ /// Whether the panel's last frame asks for its extended view.
+ pub fn extend(&self) -> bool {
+ self.frame.extend
+ }
+
+ /// Changes whenever what [`draw`](Self::draw) gives may have: a client
+ /// that keeps what it painted can paint it again while this stays.
+ pub fn revision(&self) -> u64 {
+ self.revision
+ }
+
+ /// The panel's size, fonts or theme changed. True when they did, and
+ /// the plugin is to be told -- before it is asked for what
+ /// [`wanted`](Self::wanted) gives from now on, which is drawn for them.
+ pub fn set_env(&mut self, env: Env) -> bool {
+ if env == self.env {
+ return false;
+ }
+ self.env = env;
+ // Rows are drawn for a size: the ones on show are asked for again,
+ // and what was asked for the old size is not taken when it comes,
+ // nor asked for if it is not yet.
+ self.layout = self.layout.wrapping_add(1);
+ for state in self.lists.values_mut() {
+ state.asking.clear();
+ }
+ self.wanted.clear();
+ self.settle();
+ true
+ }
+
+ /// The plugin drew the panel anew.
+ pub fn frame(&mut self, mut frame: Frame) {
+ let mut budget = ITEM_LIMIT;
+ keep(&mut frame.items, &mut budget, false);
+ let mut lists = HashMap::new();
+ let mut scrolls = HashMap::new();
+ for item in &frame.items {
+ match item {
+ Item::List(list) => {
+ let mut state = self.lists.remove(&list.id).unwrap_or_else(|| ListState {
+ key: list.key.clone(),
+ version: list.version,
+ count: 0,
+ offset: 0.0,
+ offset_x: 0.0,
+ seq: None,
+ rows: HashMap::new(),
+ asking: Vec::new(),
+ });
+ state.follow(list);
+ lists.insert(list.id.clone(), state);
+ }
+ Item::Scroll(scroll) => {
+ let mut state = self.scrolls.remove(&scroll.id).unwrap_or(ScrollState {
+ offset: 0.0,
+ seq: None,
+ });
+ if let Some(jump) = scroll.top.filter(|jump| state.seq != Some(jump.seq)) {
+ state.offset = jump.to;
+ state.seq = Some(jump.seq);
+ }
+ scrolls.insert(scroll.id.clone(), state);
+ }
+ _ => {}
+ }
+ }
+ self.lists = lists;
+ self.scrolls = scrolls;
+ self.frame = frame;
+ self.shown = true;
+ self.settle();
+ }
+
+ /// Rows the plugin sent for a list: taken when they answer a page it
+ /// waits for, drawn for the list and the panel as they are now. Rows
+ /// it was asked for and left out are kept empty, so they are not asked
+ /// for again and again.
+ pub fn rows(&mut self, rows: Rows) {
+ let layout = self.layout;
+ let Some(state) = self.lists.get_mut(&rows.list) else {
+ return;
+ };
+ if state.key != rows.key || state.version != rows.version || rows.layout != layout {
+ return;
+ }
+ // Only an answer to what is asked for is taken: one for a page let
+ // go of since is not the list's any more.
+ let Some(at) = state.asking.iter().position(|(from, _)| *from == rows.from) else {
+ return;
+ };
+ let (from, to) = state.asking.swap_remove(at);
+ let to = to.min(state.count);
+ let version = state.version;
+ let mut budget = ITEM_LIMIT;
+ let mut next = from;
+ for mut items in rows.rows {
+ if next >= to {
+ break;
+ }
+ keep(&mut items, &mut budget, true);
+ let kept = Kept {
+ version,
+ layout,
+ items,
+ };
+ state.rows.insert(next, kept);
+ next += 1;
+ }
+ for missing in next..to {
+ let empty = Kept {
+ version,
+ layout,
+ items: Vec::new(),
+ };
+ state.rows.insert(missing, empty);
+ }
+ self.settle();
+ }
+
+ /// What is to be asked of the plugin: the rows its lists need next.
+ pub fn wanted(&mut self) -> Vec<RowsWanted> {
+ std::mem::take(&mut self.wanted)
+ }
+
+ /// The plugin's program was started again: what the last one was asked
+ /// will not be answered, and is asked again, and so are the rows on
+ /// show, which stay until the new ones come.
+ pub fn restarted(&mut self) {
+ self.layout = self.layout.wrapping_add(1);
+ for state in self.lists.values_mut() {
+ state.asking.clear();
+ }
+ self.wanted.clear();
+ self.settle();
+ }
+
+ /// The pointer moved to `x`, `y`. True when what it is over changed,
+ /// and the panel is to be painted again.
+ pub fn pointer_moved(&mut self, x: f32, y: f32) -> bool {
+ self.pointer = Some((x, y));
+ self.rehover()
+ }
+
+ pub fn pointer_left(&mut self) -> bool {
+ self.pointer = None;
+ self.rehover()
+ }
+
+ /// The cursor over what the pointer is on; `None` where nothing
+ /// answers a click.
+ pub fn cursor(&self) -> Option<Cursor> {
+ let (hit, ..) = self.hit(self.hover?)?;
+ Some(hit.cursor)
+ }
+
+ /// The wheel turned `dx` units across and `dy` down at `x`, `y`: the
+ /// region there scrolls -- down for a positive `dy`, right for a
+ /// positive `dx` -- whichever way the turn mostly went, so a stroke
+ /// down a trackpad does not drift sideways. True when it moved.
+ pub fn wheel(&mut self, x: f32, y: f32, dx: f32, dy: f32) -> bool {
+ if !dx.is_finite() || !dy.is_finite() {
+ return false;
+ }
+ let (dx, dy) = if dx.abs() > dy.abs() {
+ (dx, 0.0)
+ } else {
+ (0.0, dy)
+ };
+ let mut moved = false;
+ for item in self.frame.items.iter().rev() {
+ let region = item.bounds();
+ if !region.contains(x, y) {
+ continue;
+ }
+ match item {
+ Item::List(list) => {
+ if let Some(state) = self.lists.get_mut(&list.id) {
+ let before = (state.offset, state.offset_x);
+ state.offset = (before.0 + dy).clamp(0.0, list_room(list, state.count));
+ state.offset_x = (before.1 + dx).clamp(0.0, list_room_x(list));
+ moved = (state.offset, state.offset_x) != before;
+ }
+ break;
+ }
+ Item::Scroll(scroll) => {
+ if let Some(state) = self.scrolls.get_mut(&scroll.id) {
+ let before = state.offset;
+ state.offset = (before + dy).clamp(0.0, scroll_room(scroll));
+ moved = state.offset != before;
+ }
+ break;
+ }
+ _ => {}
+ }
+ }
+ if moved {
+ self.settle();
+ }
+ moved
+ }
+
+ /// A press at `x`, `y`: the plugin is to hear of it when it landed on a
+ /// hit.
+ pub fn click(
+ &mut self,
+ x: f32,
+ y: f32,
+ button: Button,
+ count: u32,
+ mods: Mods,
+ ) -> Option<Input> {
+ self.pointer = Some((x, y));
+ self.rehover();
+ let (hit, dx, dy) = self.hit(self.spot_at(x, y)?)?;
+ Some(Input::Click(Click {
+ id: hit.id.clone(),
+ x: x - (hit.x + dx),
+ y: y - (hit.y + dy),
+ button,
+ count,
+ mods,
+ }))
+ }
+
+ /// What to paint, in order, leaving out what does not show.
+ pub fn draw(&self) -> Vec<Draw<'_>> {
+ let panel = self.panel();
+ let mut out = Vec::new();
+ for (index, item) in self.frame.items.iter().enumerate() {
+ match item {
+ Item::Scroll(scroll) => {
+ let Some(state) = self.scrolls.get(&scroll.id) else {
+ continue;
+ };
+ let clip = item.bounds().intersect(&panel);
+ if clip.is_empty() {
+ continue;
+ }
+ let (dx, dy) = (scroll.x, scroll.y - state.offset);
+ for (inner, child) in scroll.items.iter().enumerate() {
+ self.push(&mut out, child, Spot::Scrolled(index, inner), dx, dy, clip);
+ }
+ let room = scroll_room(scroll);
+ if let Some(thumb) = thumb(item.bounds(), scroll.height, state.offset, room) {
+ push_thumb(&mut out, thumb, panel);
+ }
+ }
+ Item::List(list) => {
+ let Some(state) = self.lists.get(&list.id) else {
+ continue;
+ };
+ let clip = item.bounds().intersect(&panel);
+ if clip.is_empty() {
+ continue;
+ }
+ let (first, last) = state.visible(list);
+ for row in first..last {
+ let Some(Kept { items, .. }) = state.rows.get(&row) else {
+ continue;
+ };
+ let dy = list.y + row as f32 * list.row - state.offset;
+ for (inner, child) in items.iter().enumerate() {
+ let (dx, cut) = across(list, state.offset_x, child, clip);
+ let spot = Spot::Row(index, row, inner);
+ self.push(&mut out, child, spot, dx, dy, cut);
+ }
+ }
+ let height = state.count as f32 * list.row;
+ let room = list_room(list, state.count);
+ if let Some(thumb) = thumb(item.bounds(), height, state.offset, room) {
+ push_thumb(&mut out, thumb, panel);
+ }
+ if let Some(thumb) = thumb_x(list, state.offset_x) {
+ push_thumb(&mut out, thumb, panel);
+ }
+ }
+ _ => self.push(&mut out, item, Spot::Top(index), 0.0, 0.0, panel),
+ }
+ }
+ out
+ }
+
+ /// [`draw`](Self::draw), as plain data.
+ pub fn painting(&self) -> Painting {
+ let mut clips: Vec<[f32; 4]> = Vec::new();
+ let mut ops = Vec::new();
+ for draw in self.draw() {
+ let clip = [
+ draw.clip.left,
+ draw.clip.top,
+ draw.clip.right,
+ draw.clip.bottom,
+ ];
+ if clips.last() != Some(&clip) {
+ clips.push(clip);
+ }
+ let clip = clips.len() - 1;
+ let (dx, dy) = (draw.dx, draw.dy);
+ let moved = |points: &[f32]| -> Vec<f32> {
+ points
+ .iter()
+ .enumerate()
+ .map(|(n, value)| value + if n % 2 == 0 { dx } else { dy })
+ .collect()
+ };
+ ops.push(match draw.what {
+ Drawn::Rect(rect) => Op::Rect {
+ clip,
+ x: rect.x + dx,
+ y: rect.y + dy,
+ w: rect.w,
+ h: rect.h,
+ fill: rect.fill,
+ border: rect.border,
+ radius: rect.radius,
+ },
+ Drawn::Hover(hit) => Op::Rect {
+ clip,
+ x: hit.x + dx,
+ y: hit.y + dy,
+ w: hit.w,
+ h: hit.h,
+ fill: hit.hover,
+ border: None,
+ radius: hit.radius,
+ },
+ Drawn::Text(text) => Op::Text {
+ clip,
+ x: text.x + dx,
+ y: text.y + dy,
+ w: text.w,
+ h: text.h,
+ text: text.text.clone(),
+ color: text.color,
+ font: text.font,
+ size: text.size,
+ bold: text.bold,
+ align: text.align,
+ },
+ Drawn::Line(line) => Op::Line {
+ clip,
+ points: moved(&line.points),
+ width: line.width,
+ color: line.color,
+ },
+ Drawn::Area(area) => Op::Area {
+ clip,
+ points: moved(&area.points),
+ base: area.base + dy,
+ color: area.color,
+ fade: area.fade,
+ },
+ Drawn::Thumb(thumb) => Op::Thumb {
+ clip,
+ x: thumb.left,
+ y: thumb.top,
+ w: thumb.width(),
+ h: thumb.height(),
+ },
+ });
+ }
+ Painting {
+ clips,
+ ops,
+ cursor: self.cursor(),
+ }
+ }
+
+ /// Rows a list keeps now, for looking at what the player holds.
+ pub fn rows_kept(&self) -> usize {
+ self.lists.values().map(|state| state.rows.len()).sum()
+ }
+
+ fn push<'a>(
+ &self,
+ out: &mut Vec<Draw<'a>>,
+ item: &'a Item,
+ spot: Spot,
+ dx: f32,
+ dy: f32,
+ clip: Bounds,
+ ) {
+ if !item.bounds().offset(dx, dy).touches(&clip) {
+ return;
+ }
+ let what = match item {
+ Item::Rect(rect) => Drawn::Rect(rect),
+ Item::Text(text) => Drawn::Text(text),
+ Item::Line(line) => Drawn::Line(line),
+ Item::Area(area) => Drawn::Area(area),
+ Item::Hit(hit) if hit.hover.is_some() && self.hover == Some(spot) => Drawn::Hover(hit),
+ Item::Hit(_) | Item::Scroll(_) | Item::List(_) => return,
+ };
+ out.push(Draw { what, dx, dy, clip });
+ }
+
+ fn panel(&self) -> Bounds {
+ Bounds::new(0.0, 0.0, self.env.width, self.env.height)
+ }
+
+ /// Brings the regions in line with the frame and the size: scrolled no
+ /// further than they reach, the rows near each list's view asked for
+ /// and the rest let go, and the hover found again.
+ fn settle(&mut self) {
+ self.revision += 1;
+ for item in &self.frame.items {
+ match item {
+ Item::List(list) => {
+ if let Some(state) = self.lists.get_mut(&list.id) {
+ state.offset = state.offset.clamp(0.0, list_room(list, state.count));
+ state.offset_x = state.offset_x.clamp(0.0, list_room_x(list));
+ state.serve(list, self.layout, &mut self.wanted);
+ }
+ }
+ Item::Scroll(scroll) => {
+ if let Some(state) = self.scrolls.get_mut(&scroll.id) {
+ state.offset = state.offset.clamp(0.0, scroll_room(scroll));
+ }
+ }
+ _ => {}
+ }
+ }
+ self.rehover();
+ }
+
+ fn rehover(&mut self) -> bool {
+ let hover = self.pointer.and_then(|(x, y)| self.spot_at(x, y));
+ let changed = hover != self.hover;
+ if changed {
+ self.revision += 1;
+ }
+ self.hover = hover;
+ changed
+ }
+
+ /// The topmost hit at `x`, `y`.
+ fn spot_at(&self, x: f32, y: f32) -> Option<Spot> {
+ if !self.panel().contains(x, y) {
+ return None;
+ }
+ for (index, item) in self.frame.items.iter().enumerate().rev() {
+ match item {
+ Item::Hit(_) if item.bounds().contains(x, y) => return Some(Spot::Top(index)),
+ Item::Scroll(scroll) if item.bounds().contains(x, y) => {
+ let Some(state) = self.scrolls.get(&scroll.id) else {
+ continue;
+ };
+ let (dx, dy) = (scroll.x, scroll.y - state.offset);
+ let found = scroll.items.iter().enumerate().rev().find(|(_, child)| {
+ matches!(child, Item::Hit(_))
+ && child.bounds().offset(dx, dy).contains(x, y)
+ });
+ if let Some((inner, _)) = found {
+ return Some(Spot::Scrolled(index, inner));
+ }
+ }
+ Item::List(list) if item.bounds().contains(x, y) => {
+ let Some(state) = self.lists.get(&list.id) else {
+ continue;
+ };
+ let row = ((y - list.y + state.offset) / list.row).floor();
+ if !(row >= 0.0 && row < state.count as f32) {
+ continue;
+ }
+ let row = row as u32;
+ let Some(Kept { items, .. }) = state.rows.get(&row) else {
+ continue;
+ };
+ let dy = list.y + row as f32 * list.row - state.offset;
+ let found = items.iter().enumerate().rev().find(|(_, child)| {
+ let (dx, cut) = across(list, state.offset_x, child, item.bounds());
+ matches!(child, Item::Hit(_))
+ && cut.contains(x, y)
+ && child.bounds().offset(dx, dy).contains(x, y)
+ });
+ if let Some((inner, _)) = found {
+ return Some(Spot::Row(index, row, inner));
+ }
+ }
+ _ => {}
+ }
+ }
+ None
+ }
+
+ /// The hit at `spot`, and what moves it into the panel's units.
+ fn hit(&self, spot: Spot) -> Option<(&Hit, f32, f32)> {
+ let (item, dx, dy) = match spot {
+ Spot::Top(index) => (self.frame.items.get(index)?, 0.0, 0.0),
+ Spot::Scrolled(index, inner) => {
+ let Item::Scroll(scroll) = self.frame.items.get(index)? else {
+ return None;
+ };
+ let state = self.scrolls.get(&scroll.id)?;
+ (scroll.items.get(inner)?, scroll.x, scroll.y - state.offset)
+ }
+ Spot::Row(index, row, inner) => {
+ let Item::List(list) = self.frame.items.get(index)? else {
+ return None;
+ };
+ let state = self.lists.get(&list.id)?;
+ let dy = list.y + row as f32 * list.row - state.offset;
+ let child = state.rows.get(&row)?.items.get(inner)?;
+ let (dx, _) = across(list, state.offset_x, child, Bounds::EMPTY);
+ (child, dx, dy)
+ }
+ };
+ match item {
+ Item::Hit(hit) => Some((hit, dx, dy)),
+ _ => None,
+ }
+ }
+}
+
+impl ListState {
+ /// Takes in the list as the new frame draws it.
+ fn follow(&mut self, list: &List) {
+ if self.key != list.key {
+ self.key = list.key.clone();
+ self.rows.clear();
+ self.asking.clear();
+ self.offset = 0.0;
+ self.offset_x = 0.0;
+ self.seq = None;
+ } else if self.version != list.version {
+ // What is on show stays until it is drawn anew; what was asked
+ // for the old version comes back as that, and is dropped.
+ self.asking.clear();
+ }
+ self.version = list.version;
+ if list.count < self.count {
+ let count = list.count;
+ self.rows.retain(|row, _| *row < count);
+ self.asking.retain(|(from, _)| *from < count);
+ }
+ self.count = list.count;
+ if let Some(jump) = list.top.filter(|jump| self.seq != Some(jump.seq)) {
+ self.offset = jump.to * list.row;
+ self.seq = Some(jump.seq);
+ }
+ }
+
+ /// The rows that show, as `first..last`.
+ fn visible(&self, list: &List) -> (u32, u32) {
+ if self.count == 0 {
+ return (0, 0);
+ }
+ let first = ((self.offset / list.row).floor().max(0.0) as u32).min(self.count - 1);
+ let last = ((self.offset + list.h) / list.row).ceil().max(0.0) as u32;
+ (first, last.clamp(first + 1, self.count))
+ }
+
+ /// Asks for the pages within a screen of the view that are neither had
+ /// nor asked for -- those showing first, then the ones below, then the
+ /// ones above -- and lets go of the rows more than a page beyond them,
+ /// and of asking for them: one not answered by then is asked for again
+ /// if it comes back. What is asked for is always within what is kept:
+ /// a page let go as soon as it came would be asked for again, and
+ /// again. Counted in u64, so a list of u32::MAX rows adds up.
+ fn serve(&mut self, list: &List, layout: u32, wanted: &mut Vec<RowsWanted>) {
+ if self.count == 0 {
+ self.rows.clear();
+ self.asking.clear();
+ return;
+ }
+ let count = u64::from(self.count);
+ let screen = u64::from(screen_rows(list));
+ let page = screen.max(u64::from(PAGE_MIN));
+ let (first, last) = self.visible(list);
+ let (first, last) = (u64::from(first), u64::from(last));
+ let low = first.saturating_sub(screen) / page;
+ let high = ((last + screen).min(count) - 1) / page;
+ let (shown_low, shown_high) = (first / page, (last - 1) / page);
+ let kept = low.saturating_sub(1) * page..(high + 2) * page;
+ self.rows.retain(|row, _| kept.contains(&u64::from(*row)));
+ self.asking
+ .retain(|(from, to)| u64::from(*from) < kept.end && u64::from(*to) > kept.start);
+ if self.rows.len() > ROW_LIMIT {
+ let middle = first + (last - first) / 2;
+ let mut rows: Vec<u32> = self.rows.keys().copied().collect();
+ rows.sort_by_key(|row| u64::from(*row).abs_diff(middle));
+ for row in rows.into_iter().skip(ROW_LIMIT) {
+ self.rows.remove(&row);
+ }
+ }
+ let order = (shown_low..=shown_high)
+ .chain(shown_high + 1..=high)
+ .chain((low..shown_low).rev());
+ for number in order {
+ if self.asking.len() >= ASKING_LIMIT || self.rows.len() >= ROW_LIMIT {
+ break;
+ }
+ // Below `count`, which is a u32.
+ let from = (number * page) as u32;
+ let to = (u64::from(from) + page).min(count) as u32;
+ let asked = self
+ .asking
+ .iter()
+ .any(|(start, end)| *start < to && *end > from);
+ let had = (from..to).all(|row| {
+ self.rows
+ .get(&row)
+ .is_some_and(|kept| kept.version == self.version && kept.layout == layout)
+ });
+ if asked || had {
+ continue;
+ }
+ self.asking.push((from, to));
+ wanted.push(RowsWanted {
+ list: list.id.clone(),
+ key: self.key.clone(),
+ version: self.version,
+ layout,
+ from,
+ to,
+ });
+ }
+ }
+}
+
+/// Rows in a screenful of `list`: at least one, and never so many that a
+/// few pages of them do not fit in [`ROW_LIMIT`].
+fn screen_rows(list: &List) -> u32 {
+ ((list.h / list.row).ceil() as u32).clamp(1, ROW_LIMIT as u32 / 8)
+}
+
+/// How far a list scrolls.
+fn list_room(list: &List, count: u32) -> f32 {
+ (count as f32 * list.row - list.h).max(0.0)
+}
+
+/// How far a list's rows scroll sideways.
+fn list_room_x(list: &List) -> f32 {
+ (list.width - list.w).max(0.0)
+}
+
+/// Where item `child` of a row of `list` goes across, and what it is cut
+/// to: one starting past the list's fixed part moves with the rows' scroll
+/// sideways, and is cut where that part ends; the rest stay.
+fn across(list: &List, offset_x: f32, child: &Item, clip: Bounds) -> (f32, Bounds) {
+ if list_room_x(list) <= 0.0 || child.bounds().left < list.fixed {
+ return (list.x, clip);
+ }
+ let left = clip.left.max(list.x + list.fixed);
+ (list.x - offset_x, Bounds { left, ..clip })
+}
+
+fn scroll_room(scroll: &Scroll) -> f32 {
+ (scroll.height - scroll.h).max(0.0)
+}
+
+/// Where the thumb of a region `height` tall, scrolled `offset` of its
+/// `room`, goes: along the right edge of `region`, as long as the share of
+/// it that shows. None when all of it shows.
+fn thumb(region: Bounds, height: f32, offset: f32, room: f32) -> Option<Bounds> {
+ let view = region.height();
+ if room < 0.5 || height <= 0.0 || view <= 0.0 {
+ return None;
+ }
+ let length = (view * view / height).clamp(THUMB_MIN.min(view), view);
+ let top = region.top + (offset / room) * (view - length);
+ let left = region.right - THUMB_WIDTH - THUMB_GAP;
+ Some(Bounds::new(left, top, THUMB_WIDTH, length))
+}
+
+/// Where the thumb of a list's scroll sideways goes: along its bottom
+/// edge, under the part that scrolls and clear of the other thumb, as long
+/// as the share of that part that shows. None when all of it shows.
+fn thumb_x(list: &List, offset_x: f32) -> Option<Bounds> {
+ let room = list_room_x(list);
+ let left = list.x + list.fixed.clamp(0.0, list.w);
+ let right = list.x + list.w - THUMB_WIDTH - THUMB_GAP * 2.0;
+ let view = right - left;
+ if room < 0.5 || view <= 0.0 {
+ return None;
+ }
+ let shown = (list.w - list.fixed).max(1.0);
+ let length = (view * shown / (shown + room)).clamp(THUMB_MIN.min(view), view);
+ let x = left + (offset_x / room) * (view - length);
+ let top = list.y + list.h - THUMB_WIDTH - THUMB_GAP;
+ Some(Bounds::new(x, top, length, THUMB_WIDTH))
+}
+
+fn push_thumb(out: &mut Vec<Draw<'_>>, thumb: Bounds, panel: Bounds) {
+ out.push(Draw {
+ what: Drawn::Thumb(thumb),
+ dx: 0.0,
+ dy: 0.0,
+ clip: panel,
+ });
+}
+
+/// Keeps what can be drawn of `items`, and no more than `budget` of them
+/// between these and any already kept: regions do not go in regions, and
+/// an item whose numbers are not all numbers is left out. Text and lines
+/// are cut to their limits.
+fn keep(items: &mut Vec<Item>, budget: &mut usize, nested: bool) {
+ items.retain_mut(|item| {
+ if *budget == 0 || !drawable(item) {
+ return false;
+ }
+ match item {
+ Item::Scroll(_) | Item::List(_) if nested => return false,
+ Item::Scroll(scroll) => {
+ *budget -= 1;
+ keep(&mut scroll.items, budget, true);
+ return true;
+ }
+ Item::Text(text) => {
+ if let Some((cut, _)) = text.text.char_indices().nth(TEXT_LIMIT) {
+ text.text.truncate(cut);
+ }
+ }
+ Item::Line(Line { points, .. }) | Item::Area(Area { points, .. }) => {
+ points.truncate(POINT_LIMIT);
+ if points.len() % 2 == 1 {
+ points.pop();
+ }
+ }
+ _ => {}
+ }
+ *budget -= 1;
+ true
+ });
+}
+
+fn drawable(item: &Item) -> bool {
+ let finite = |values: &[f32]| values.iter().all(|value| value.is_finite());
+ match item {
+ Item::Rect(rect) => finite(&[rect.x, rect.y, rect.w, rect.h, rect.radius]),
+ Item::Text(text) => finite(&[text.x, text.y, text.w, text.h]),
+ Item::Line(line) => finite(&line.points) && line.width.is_finite() && line.width > 0.0,
+ Item::Area(area) => finite(&area.points) && area.base.is_finite(),
+ Item::Hit(hit) => finite(&[hit.x, hit.y, hit.w, hit.h, hit.radius]),
+ Item::Scroll(scroll) => {
+ finite(&[scroll.x, scroll.y, scroll.w, scroll.h, scroll.height])
+ && scroll.top.is_none_or(|jump| jump.to.is_finite())
+ }
+ Item::List(list) => {
+ finite(&[list.x, list.y, list.w, list.h, list.width, list.fixed])
+ && list.row.is_finite()
+ && list.row >= 1.0
+ && list.top.is_none_or(|jump| jump.to.is_finite())
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::scene::{Color, Jump, Token};
+ use crate::wire::{MonoMetrics, TextMetrics};
+
+ fn env(width: f32, height: f32) -> Env {
+ let text = TextMetrics {
+ size: 13.0,
+ line: 18.0,
+ };
+ Env {
+ width,
+ height,
+ scale: 2.0,
+ dark: true,
+ small: text,
+ body: text,
+ title: text,
+ mono: MonoMetrics {
+ size: 12.0,
+ line: 18.0,
+ advance: 7.0,
+ },
+ locale: String::new(),
+ cwd: None,
+ remote: None,
+ can_extend: false,
+ close: None,
+ }
+ }
+
+ fn hit(id: &str, x: f32, y: f32, w: f32, h: f32) -> Item {
+ Item::Hit(Hit {
+ id: id.into(),
+ x,
+ y,
+ w,
+ h,
+ hover: Some(Token::BgHover.into()),
+ radius: 0.0,
+ cursor: Cursor::Pointer,
+ })
+ }
+
+ fn list(count: u32, key: &str, top: Option<Jump>) -> Item {
+ Item::List(List {
+ id: "l".into(),
+ x: 10.0,
+ y: 100.0,
+ w: 200.0,
+ h: 200.0,
+ count,
+ row: 20.0,
+ key: key.into(),
+ version: 0,
+ width: 0.0,
+ fixed: 0.0,
+ top,
+ })
+ }
+
+ /// Row `index` of a list: a hit across it, and its label.
+ fn row(index: u32) -> Vec<Item> {
+ vec![
+ hit(&format!("row:{index}"), 0.0, 0.0, 200.0, 20.0),
+ Item::Text(Text {
+ x: 4.0,
+ y: 0.0,
+ w: 190.0,
+ h: 20.0,
+ text: format!("row {index}"),
+ color: Color::default(),
+ font: Default::default(),
+ size: Default::default(),
+ bold: false,
+ align: Default::default(),
+ }),
+ ]
+ }
+
+ /// Answers what the player wants with rows made by `row`.
+ fn answer(player: &mut Player) -> Vec<RowsWanted> {
+ let wanted = player.wanted();
+ answer_these(player, &wanted);
+ wanted
+ }
+
+ fn answer_these(player: &mut Player, wanted: &[RowsWanted]) {
+ for want in wanted {
+ player.rows(Rows {
+ list: want.list.clone(),
+ key: want.key.clone(),
+ version: want.version,
+ layout: want.layout,
+ from: want.from,
+ rows: (want.from..want.to).map(row).collect(),
+ });
+ }
+ }
+
+ fn texts(player: &Player) -> Vec<String> {
+ player
+ .draw()
+ .iter()
+ .filter_map(|draw| match draw.what {
+ Drawn::Text(text) => Some(text.text.clone()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ #[test]
+ fn a_list_asks_for_the_rows_it_shows_and_the_next_screen() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(10_000, "a", None)],
+ ..Frame::default()
+ });
+ let wanted = player.wanted();
+ // Ten rows show; a page is PAGE_MIN rows, which covers the next
+ // screen too, and there is nothing above.
+ assert_eq!(wanted.len(), 1, "{wanted:?}");
+ assert_eq!((wanted[0].from, wanted[0].to), (0, 32));
+ assert!(player.wanted().is_empty(), "asked once");
+ player.rows(Rows {
+ list: "l".into(),
+ key: "a".into(),
+ version: 0,
+ layout: 0,
+ from: 0,
+ rows: (0..32).map(row).collect(),
+ });
+ let shown = texts(&player);
+ assert_eq!(shown.first().map(String::as_str), Some("row 0"));
+ assert_eq!(shown.len(), 10, "only the rows that show are drawn");
+ assert!(player.wanted().is_empty(), "the next screen is had");
+ }
+
+ #[test]
+ fn scrolling_moves_at_once_asks_ahead_and_lets_far_rows_go() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(10_000, "a", None)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ assert!(player.wheel(50.0, 150.0, 0.0, 20.0 * 100.0));
+ let shown = texts(&player);
+ assert!(
+ shown.is_empty(),
+ "rows 100 and on are not here yet: {shown:?}"
+ );
+ let wanted = answer(&mut player);
+ assert!(
+ wanted.iter().any(|want| want.from <= 100 && want.to > 100),
+ "{wanted:?}"
+ );
+ assert_eq!(texts(&player).first().map(String::as_str), Some("row 100"));
+ assert!(
+ player.rows_kept() < 100,
+ "the first rows are let go: {}",
+ player.rows_kept()
+ );
+
+ let mut turns = 0;
+ while player.wheel(50.0, 150.0, 0.0, 20.0 * 17.0) {
+ answer(&mut player);
+ turns += 1;
+ assert!(turns < 1_000);
+ // What is kept stays near the view: a page or so to each side.
+ assert!(player.rows_kept() <= 4 * 32, "{}", player.rows_kept());
+ }
+ answer(&mut player);
+ assert!(player.wanted().is_empty(), "nothing asked twice");
+ assert_eq!(texts(&player).last().map(String::as_str), Some("row 9999"));
+ }
+
+ #[test]
+ fn a_new_key_starts_over_and_a_jump_is_taken_once() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(1_000, "a", None)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ player.wheel(50.0, 150.0, 0.0, 400.0);
+ answer(&mut player);
+ assert_eq!(texts(&player)[0], "row 20");
+ // The same list drawn again keeps its place and its rows.
+ player.frame(Frame {
+ items: vec![list(1_000, "a", None)],
+ ..Frame::default()
+ });
+ assert_eq!(texts(&player)[0], "row 20");
+ assert!(player.wanted().is_empty());
+ // Other rows start at the top, with none of the old ones.
+ player.frame(Frame {
+ items: vec![list(1_000, "b", None)],
+ ..Frame::default()
+ });
+ assert!(texts(&player).is_empty());
+ let wanted = player.wanted();
+ assert!(wanted.iter().all(|want| want.key == "b") && wanted[0].from == 0);
+ // Rows for the old key are not taken.
+ player.rows(Rows {
+ list: "l".into(),
+ key: "a".into(),
+ version: 0,
+ layout: 0,
+ from: 0,
+ rows: (0..32).map(row).collect(),
+ });
+ assert!(texts(&player).is_empty());
+
+ let jump = Some(Jump { to: 500.0, seq: 1 });
+ player.frame(Frame {
+ items: vec![list(1_000, "b", jump)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ assert_eq!(texts(&player)[0], "row 500");
+ player.wheel(50.0, 150.0, 0.0, 200.0);
+ player.frame(Frame {
+ items: vec![list(1_000, "b", jump)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ assert_eq!(
+ texts(&player)[0],
+ "row 510",
+ "the same jump is not taken twice"
+ );
+ }
+
+ #[test]
+ fn a_new_version_redraws_the_rows_in_place() {
+ let mut player = Player::new(env(300.0, 400.0));
+ let versioned = |version| {
+ let Item::List(list) = list(1_000, "a", None) else {
+ unreachable!()
+ };
+ Item::List(list.version(version))
+ };
+ player.frame(Frame {
+ items: vec![versioned(0)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ player.wheel(50.0, 150.0, 0.0, 400.0);
+ answer(&mut player);
+ assert_eq!(texts(&player)[0], "row 20");
+
+ player.frame(Frame {
+ items: vec![versioned(1)],
+ ..Frame::default()
+ });
+ assert_eq!(
+ texts(&player)[0],
+ "row 20",
+ "the old rows stay on show, in place"
+ );
+ let wanted = player.wanted();
+ assert!(
+ !wanted.is_empty() && wanted.iter().all(|want| want.version == 1),
+ "{wanted:?}"
+ );
+ // An answer to the old version is dropped; the new one is taken.
+ player.rows(Rows {
+ list: "l".into(),
+ key: "a".into(),
+ version: 0,
+ layout: 0,
+ from: wanted[0].from,
+ rows: vec![Vec::new(); 64],
+ });
+ assert_eq!(texts(&player)[0], "row 20");
+ player.rows(Rows {
+ list: "l".into(),
+ key: "a".into(),
+ version: 1,
+ layout: 0,
+ from: wanted[0].from,
+ rows: vec![Vec::new(); 64],
+ });
+ assert!(texts(&player).is_empty(), "drawn anew: empty rows");
+ }
+
+ #[test]
+ fn a_new_size_asks_again_and_what_was_drawn_for_the_old_is_not_taken() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(1_000, "a", None)],
+ ..Frame::default()
+ });
+ let old = player.wanted();
+ assert!(player.set_env(env(360.0, 400.0)));
+ assert!(texts(&player).is_empty(), "nothing was had yet");
+ let new = player.wanted();
+ assert!(new.iter().all(|want| want.layout == 1), "{new:?}");
+ // The answer to the first ask comes: drawn for the old size, it is
+ // not taken; the one asked for the new size is.
+ for want in &old {
+ player.rows(Rows {
+ list: want.list.clone(),
+ key: want.key.clone(),
+ version: want.version,
+ layout: want.layout,
+ from: want.from,
+ rows: (want.from..want.to).map(row).collect(),
+ });
+ }
+ assert!(
+ texts(&player).is_empty(),
+ "the old size's rows are not taken"
+ );
+ answer_these(&mut player, &new);
+ assert_eq!(texts(&player)[0], "row 0");
+
+ // Rows on show stay while the new size's come.
+ assert!(player.set_env(env(300.0, 400.0)));
+ assert_eq!(texts(&player)[0], "row 0");
+ assert!(!player.wanted().is_empty());
+ }
+
+ #[test]
+ fn rows_are_asked_for_again_from_a_plugin_started_again() {
+ let mut player = Player::new(env(300.0, 400.0));
+ let frame = || Frame {
+ items: vec![list(1_000, "a", None)],
+ ..Frame::default()
+ };
+ player.frame(frame());
+ answer(&mut player);
+ assert_eq!(texts(&player)[0], "row 0");
+ // Reloaded, the new run draws the same key and version, and may
+ // have other rows under them.
+ player.restarted();
+ player.frame(frame());
+ let wanted = player.wanted();
+ assert!(!wanted.is_empty(), "the rows on show are asked for again");
+ assert_eq!(texts(&player)[0], "row 0", "and stay until the new come");
+ for want in &wanted {
+ player.rows(Rows {
+ list: want.list.clone(),
+ key: want.key.clone(),
+ version: want.version,
+ layout: want.layout,
+ from: want.from,
+ rows: (want.from..want.to)
+ .map(|n| vec![Text::new(0.0, 0.0, 100.0, 20.0, format!("new {n}")).into()])
+ .collect(),
+ });
+ }
+ assert_eq!(texts(&player)[0], "new 0");
+ assert!(player.wanted().is_empty(), "asked once");
+ }
+
+ /// A list 200 wide with rows 600 wide, the first 40 of them fixed: a
+ /// number in the fixed part, the line and a hit on it past it.
+ fn wide_list(player: &mut Player) {
+ let Item::List(list) = list(100, "a", None) else {
+ unreachable!()
+ };
+ player.frame(Frame {
+ items: vec![Item::List(list.wide(600.0, 40.0))],
+ ..Frame::default()
+ });
+ for want in player.wanted() {
+ player.rows(Rows {
+ list: want.list.clone(),
+ key: want.key.clone(),
+ version: want.version,
+ layout: want.layout,
+ from: want.from,
+ rows: (want.from..want.to)
+ .map(|n| {
+ vec![
+ Text::new(0.0, 0.0, 36.0, 20.0, n.to_string()).into(),
+ hit(&format!("line:{n}"), 40.0, 0.0, 560.0, 20.0),
+ Text::new(40.0, 0.0, 560.0, 20.0, format!("line {n}")).into(),
+ ]
+ })
+ .collect(),
+ });
+ }
+ }
+
+ #[test]
+ fn a_wide_list_scrolls_sideways_and_its_fixed_part_stays() {
+ let mut player = Player::new(env(300.0, 400.0));
+ wide_list(&mut player);
+ let place = |player: &Player, text: &str| {
+ player
+ .draw()
+ .iter()
+ .find_map(|draw| match draw.what {
+ Drawn::Text(t) if t.text == text => Some((t.x + draw.dx, draw.clip.left)),
+ _ => None,
+ })
+ .unwrap()
+ };
+ assert_eq!(place(&player, "0"), (10.0, 10.0));
+ assert_eq!(place(&player, "line 0"), (50.0, 50.0));
+ // A stroke mostly down scrolls down only.
+ assert!(player.wheel(100.0, 150.0, 5.0, 40.0));
+ assert_eq!(place(&player, "line 2"), (50.0, 50.0));
+ // Across: the lines move, cut where the numbers end; they stay.
+ assert!(player.wheel(100.0, 150.0, 120.0, 0.0));
+ assert_eq!(place(&player, "2"), (10.0, 10.0));
+ assert_eq!(place(&player, "line 2"), (-70.0, 50.0));
+ // No further than the rows reach.
+ assert!(player.wheel(100.0, 150.0, 5_000.0, 0.0));
+ assert_eq!(place(&player, "line 2").0, 50.0 - 400.0);
+ assert!(!player.wheel(100.0, 150.0, 10.0, 0.0), "at the end");
+ let thumbs: Vec<Bounds> = player
+ .draw()
+ .iter()
+ .filter_map(|draw| match draw.what {
+ Drawn::Thumb(bounds) => Some(bounds),
+ _ => None,
+ })
+ .collect();
+ let across = thumbs
+ .iter()
+ .find(|thumb| thumb.width() > thumb.height())
+ .expect("a thumb across");
+ assert_eq!(across.bottom, 300.0 - THUMB_GAP);
+ assert!((across.right - (210.0 - THUMB_WIDTH - THUMB_GAP * 2.0)).abs() < 0.01);
+
+ // A click lands on the line where it shows now, not where it was.
+ let clicked = player.click(60.0, 110.0, Button::Left, 1, Mods::default());
+ let Some(Input::Click(click)) = clicked else {
+ panic!("{clicked:?}")
+ };
+ assert_eq!(click.id, "line:2");
+ assert_eq!(click.x, 60.0 - (40.0 + 10.0 - 400.0));
+ // Over the numbers, the line under them does not answer.
+ assert_eq!(
+ player.click(20.0, 110.0, Button::Left, 1, Mods::default()),
+ None
+ );
+
+ // Other rows start at the left again.
+ let Item::List(other) = list(100, "b", None) else {
+ unreachable!()
+ };
+ player.frame(Frame {
+ items: vec![Item::List(other.wide(600.0, 40.0))],
+ ..Frame::default()
+ });
+ assert!(player.wheel(100.0, 150.0, 1.0, 0.0), "back from the start");
+ }
+
+ #[test]
+ fn a_hover_tint_has_the_corners_of_its_hit() {
+ let mut player = Player::new(env(300.0, 400.0));
+ let Item::Hit(round) = hit("a", 10.0, 10.0, 100.0, 30.0) else {
+ unreachable!()
+ };
+ player.frame(Frame {
+ items: vec![Item::Hit(round.radius(6.0))],
+ ..Frame::default()
+ });
+ player.pointer_moved(20.0, 20.0);
+ let painting = player.painting();
+ assert!(
+ painting
+ .ops
+ .iter()
+ .any(|op| matches!(op, Op::Rect { radius, .. } if *radius == 6.0)),
+ "{painting:?}"
+ );
+ }
+
+ #[test]
+ fn a_page_never_answered_is_asked_for_again_when_it_comes_back() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(10_000, "a", None)],
+ ..Frame::default()
+ });
+ let first = player.wanted();
+ assert_eq!(first[0].from, 0);
+ // The answer never comes; the list is scrolled far away and back.
+ player.wheel(50.0, 150.0, 0.0, 20.0 * 5_000.0);
+ answer(&mut player);
+ player.wheel(50.0, 150.0, 0.0, -20.0 * 5_000.0);
+ let again = player.wanted();
+ assert!(again.iter().any(|want| want.from == 0), "{again:?}");
+ }
+
+ #[test]
+ fn a_list_of_every_row_a_u32_counts_adds_up() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(u32::MAX, "a", None)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ assert!(player.wheel(50.0, 150.0, 0.0, f32::MAX));
+ let wanted = answer(&mut player);
+ assert!(wanted.iter().all(|want| want.from < want.to), "{wanted:?}");
+ assert!(wanted.iter().any(|want| want.to == u32::MAX), "{wanted:?}");
+ assert!(player.wanted().is_empty(), "asked once");
+ }
+
+ #[test]
+ fn rows_left_out_are_not_asked_for_again() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![list(50, "a", None)],
+ ..Frame::default()
+ });
+ let wanted = player.wanted();
+ player.rows(Rows {
+ list: "l".into(),
+ key: "a".into(),
+ version: 0,
+ layout: 0,
+ from: wanted[0].from,
+ rows: (0..5).map(row).collect(),
+ });
+ assert!(
+ player.wanted().iter().all(|want| want.from >= 32),
+ "no loop"
+ );
+ }
+
+ #[test]
+ fn hover_tints_at_once_and_a_click_names_the_hit() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![hit("top", 0.0, 0.0, 300.0, 40.0), list(100, "a", None)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ let before = player.revision();
+ assert!(player.pointer_moved(20.0, 10.0));
+ assert!(player.revision() > before, "a new hover is a new picture");
+ let before = player.revision();
+ assert!(!player.pointer_moved(25.0, 12.0), "the same hit");
+ assert_eq!(player.revision(), before, "the same picture");
+ assert_eq!(player.cursor(), Some(Cursor::Pointer));
+ let hovered: Vec<_> = player
+ .draw()
+ .into_iter()
+ .filter(|draw| matches!(draw.what, Drawn::Hover(_)))
+ .collect();
+ assert_eq!(hovered.len(), 1);
+
+ // Row 2 of the list sits at 140..160 before any scroll.
+ let input = player.click(30.0, 145.0, Button::Left, 1, Mods::default());
+ let Some(Input::Click(click)) = input else {
+ panic!("{input:?}")
+ };
+ assert_eq!(click.id, "row:2");
+ assert_eq!((click.x, click.y), (20.0, 5.0), "within the hit");
+ player.wheel(30.0, 145.0, 0.0, 20.0);
+ let Some(Input::Click(click)) = player.click(30.0, 145.0, Button::Left, 1, Mods::default())
+ else {
+ panic!()
+ };
+ assert_eq!(click.id, "row:3", "the rows moved under the pointer");
+ assert!(player
+ .click(299.0, 399.0, Button::Left, 1, Mods::default())
+ .is_none());
+ assert_eq!(player.cursor(), None, "over nothing that answers");
+ player.pointer_moved(20.0, 10.0);
+ assert!(player.pointer_left());
+ assert_eq!(player.cursor(), None);
+ }
+
+ #[test]
+ fn a_scroll_area_scrolls_is_cut_to_itself_and_shows_its_thumb() {
+ let mut player = Player::new(env(300.0, 400.0));
+ let scroll = |top| Scroll {
+ id: "s".into(),
+ x: 0.0,
+ y: 50.0,
+ w: 300.0,
+ h: 100.0,
+ height: 400.0,
+ items: vec![hit("inner", 0.0, 120.0, 300.0, 20.0)],
+ top,
+ };
+ player.frame(Frame {
+ items: vec![Item::Scroll(scroll(None))],
+ ..Frame::default()
+ });
+ assert!(
+ player
+ .click(10.0, 180.0, Button::Left, 1, Mods::default())
+ .is_none(),
+ "below"
+ );
+ assert!(player.wheel(10.0, 60.0, 0.0, 100.0));
+ let Some(Input::Click(click)) = player.click(10.0, 75.0, Button::Left, 1, Mods::default())
+ else {
+ panic!()
+ };
+ assert_eq!((click.id.as_str(), click.y), ("inner", 5.0));
+ let draws = player.draw();
+ let thumb = draws
+ .iter()
+ .find_map(|draw| match draw.what {
+ Drawn::Thumb(thumb) => Some(thumb),
+ _ => None,
+ })
+ .expect("a thumb");
+ assert_eq!(thumb.height(), 25.0, "a quarter of it shows");
+ assert!(draws
+ .iter()
+ .filter(|draw| !matches!(draw.what, Drawn::Thumb(_)))
+ .all(|draw| draw.clip == Bounds::new(0.0, 50.0, 300.0, 100.0)));
+ player.frame(Frame {
+ items: vec![Item::Scroll(scroll(Some(Jump { to: 0.0, seq: 7 })))],
+ ..Frame::default()
+ });
+ assert!(
+ player
+ .click(10.0, 75.0, Button::Left, 1, Mods::default())
+ .is_none(),
+ "jumped back"
+ );
+ }
+
+ #[test]
+ fn a_painting_is_the_draw_as_plain_data_moved_into_place() {
+ let mut player = Player::new(env(300.0, 400.0));
+ player.frame(Frame {
+ items: vec![hit("top", 0.0, 0.0, 300.0, 40.0), list(100, "a", None)],
+ ..Frame::default()
+ });
+ answer(&mut player);
+ player.wheel(50.0, 150.0, 0.0, 5.0);
+ player.pointer_moved(20.0, 10.0);
+ let painting = player.painting();
+ assert_eq!(painting.cursor, Some(Cursor::Pointer));
+ assert_eq!(painting.clips[0], [0.0, 0.0, 300.0, 400.0]);
+ assert!(
+ matches!(
+ painting.ops[0],
+ Op::Rect {
+ clip: 0,
+ w: 300.0,
+ ..
+ }
+ ),
+ "the hover"
+ );
+ let first_row = painting
+ .ops
+ .iter()
+ .find_map(|op| match op {
+ Op::Text { text, y, clip, .. } => Some((text.clone(), *y, *clip)),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(
+ first_row,
+ ("row 0".to_string(), 95.0, 1),
+ "the list's own region, scrolled"
+ );
+ let json = serde_json::to_value(&painting.ops[0]).unwrap();
+ assert_eq!(json["op"], "rect");
+ assert_eq!(json["fill"], "bg-hover");
+ }
+
+ #[test]
+ fn what_cannot_be_drawn_is_left_out() {
+ let mut player = Player::new(env(300.0, 400.0));
+ let mut items = vec![hit("nan", f32::NAN, 0.0, 1.0, 1.0)];
+ items.push(Item::Scroll(Scroll {
+ id: "s".into(),
+ x: 0.0,
+ y: 0.0,
+ w: 10.0,
+ h: 10.0,
+ height: 10.0,
+ items: vec![list(3, "a", None), hit("kept", 0.0, 0.0, 1.0, 1.0)],
+ top: None,
+ }));
+ items.extend((0..ITEM_LIMIT + 10).map(|n| hit(&n.to_string(), 0.0, 0.0, 1.0, 1.0)));
+ items.push(Item::Text(Text {
+ x: 0.0,
+ y: 0.0,
+ w: 1.0,
+ h: 1.0,
+ text: "x".repeat(TEXT_LIMIT * 2),
+ color: Color::default(),
+ font: Default::default(),
+ size: Default::default(),
+ bold: false,
+ align: Default::default(),
+ }));
+ player.frame(Frame {
+ items,
+ ..Frame::default()
+ });
+ let Item::Scroll(scroll) = &player.frame.items[0] else {
+ panic!("the NaN hit went")
+ };
+ assert_eq!(scroll.items.len(), 1, "no list in a scroll area");
+ assert_eq!(
+ player.frame.items.len(),
+ ITEM_LIMIT - 1,
+ "the scroll area's item counts"
+ );
+ assert!(!player
+ .frame
+ .items
+ .iter()
+ .any(|item| matches!(item, Item::Text(_))));
+
+ let long = Item::Text(Text {
+ x: 0.0,
+ y: 0.0,
+ w: 1.0,
+ h: 1.0,
+ text: "\u{4e2d}".repeat(TEXT_LIMIT + 1),
+ color: Color::default(),
+ font: Default::default(),
+ size: Default::default(),
+ bold: false,
+ align: Default::default(),
+ });
+ player.frame(Frame {
+ items: vec![long],
+ ..Frame::default()
+ });
+ let Item::Text(text) = &player.frame.items[0] else {
+ panic!()
+ };
+ assert_eq!(text.text.chars().count(), TEXT_LIMIT);
+ }
+
+ #[test]
+ fn a_page_that_comes_is_kept_while_it_is_near() {
+ // A screen of one row: pages are PAGE_MIN rows, far more than the
+ // screen, and each one asked for must stay once it has come.
+ let mut player = Player::new(env(300.0, 400.0));
+ let mut short = list(1_000, "a", None);
+ if let Item::List(list) = &mut short {
+ list.h = 20.0;
+ }
+ player.frame(Frame {
+ items: vec![short],
+ ..Frame::default()
+ });
+ for step in 0..200 {
+ let wanted = answer(&mut player);
+ assert!(wanted.len() <= 3, "{wanted:?}");
+ player.wheel(50.0, 105.0, 0.0, if step % 7 == 6 { -60.0 } else { 30.0 });
+ }
+ answer(&mut player);
+ assert!(player.wanted().is_empty(), "every page asked for was kept");
+ }
+
+ #[test]
+ fn each_frame_says_whether_the_extended_view_is_wanted() {
+ let mut player = Player::new(env(300.0, 400.0));
+ assert!(!player.extend(), "nothing drawn asks nothing");
+ player.frame(Frame {
+ items: Vec::new(),
+ extend: true,
+ });
+ assert!(player.extend());
+ player.frame(Frame::default());
+ assert!(!player.extend(), "a frame that does not ask lets it go");
+ }
+}
diff --git a/thinkterm-plugin-panel/src/scene.rs b/thinkterm-plugin-panel/src/scene.rs
new file mode 100644
index 00000000..abc1bb89
--- /dev/null
+++ b/thinkterm-plugin-panel/src/scene.rs
@@ -0,0 +1,879 @@
+//! What a plugin draws: a list of items, painted in order, in the panel's
+//! own units -- logical pixels from its top left corner, the ones
+//! [`Env`](crate::Env) gives its size in.
+//!
+//! There are no widgets. A button is a rounded rectangle, its label and a
+//! hit over both; the player draws what it is given and nothing else, so a
+//! panel looks the same wherever it is shown. Colours are ThinkTerm's own,
+//! by name, so a panel follows the theme without being told of it.
+//!
+//! An item that does not read -- a coordinate a plugin wrote as `null`, a
+//! kind a newer ThinkTerm knows and this one does not -- is left out, and
+//! the rest of its list stays.
+
+use serde::de::{Deserializer, Visitor};
+use serde::{Deserialize, Serialize, Serializer};
+use serde_json::value::RawValue;
+use std::fmt;
+
+/// The whole panel. Each frame replaces the last.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct Frame {
+ #[serde(default, deserialize_with = "items")]
+ pub items: Vec<Item>,
+ /// A panel's frame asks for its extended view with this: a wide area
+ /// beside the sidebar, as wide as the user makes it, which the plugin
+ /// draws as a view of its own. It stays while the panel's frames ask for
+ /// it, and goes when one does not. An extended view's own frame asks
+ /// nothing.
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub extend: bool,
+}
+
+/// A list of items, keeping the ones that read. JSON only: an item is read
+/// from its own text.
+pub(crate) fn items<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Item>, D::Error> {
+ let raw: Vec<Box<RawValue>> = Vec::deserialize(deserializer)?;
+ Ok(raw
+ .iter()
+ .filter_map(|item| serde_json::from_str(item.get()).ok())
+ .collect())
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Item {
+ Rect(Rect),
+ Text(Text),
+ Line(Line),
+ Area(Area),
+ Hit(Hit),
+ Scroll(Scroll),
+ List(List),
+}
+
+/// A filled rectangle, with rounded corners and a one-unit border when
+/// asked for.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Rect {
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fill: Option<Color>,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub radius: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub border: Option<Color>,
+}
+
+/// One line of text in a box: centred in its height, placed across its
+/// width as `align` says, and cut to fit -- with an ellipsis in the
+/// interface font, at the box's edge in the monospaced one, whose columns a
+/// plugin lines up itself.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Text {
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ pub text: String,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub color: Color,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub font: Font,
+ /// The interface font's size; the monospaced font has the one.
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub size: Size,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub bold: bool,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub align: Align,
+}
+
+/// A line through `points`, given as x, y, x, y and so on.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Line {
+ pub points: Vec<f32>,
+ #[serde(default = "one")]
+ pub width: f32,
+ pub color: Color,
+}
+
+/// What lies between a line through `points` -- x, y pairs, left to right
+/// -- and the level `base`: the fill under a chart. With `fade` it thins
+/// out toward `base`.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Area {
+ pub points: Vec<f32>,
+ pub base: f32,
+ pub color: Color,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub fade: bool,
+}
+
+/// Where a click is the plugin's to hear, as a click on `id`. While the
+/// pointer is over it the player tints it with `hover`, without asking,
+/// its corners rounded by `radius`.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Hit {
+ pub id: String,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub hover: Option<Color>,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub radius: f32,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub cursor: Cursor,
+}
+
+/// A region whose `items` scroll: they are in its own units, `height`
+/// tall, and cut to the region. The player scrolls it without asking.
+/// Scroll areas and lists do not go inside one.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Scroll {
+ pub id: String,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ pub height: f32,
+ #[serde(default, deserialize_with = "items")]
+ pub items: Vec<Item>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub top: Option<Jump>,
+}
+
+/// `count` rows, each `row` tall, which the plugin draws as they come into
+/// view: the player asks for them a page at a time as it scrolls, keeps
+/// the ones near the view and lets the rest go. A new `key` says the rows
+/// are other ones: the old are dropped, and the list starts at its top. A
+/// new `version` says the same rows look different now -- one was picked,
+/// a price moved: they are asked for again where they show, and the old
+/// ones stay on show until the new ones come.
+///
+/// Rows `width` wide, wider than the list, scroll sideways too, all but
+/// what starts within `fixed` of their left edge: line numbers stay while
+/// the lines move.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct List {
+ pub id: String,
+ pub x: f32,
+ pub y: f32,
+ pub w: f32,
+ pub h: f32,
+ pub count: u32,
+ pub row: f32,
+ pub key: String,
+ #[serde(default, skip_serializing_if = "is_default")]
+ pub version: u32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub width: f32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub fixed: f32,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub top: Option<Jump>,
+}
+
+/// Scrolls a region to `to` -- a row of a list, a height in a scroll area
+/// -- once for each new `seq`, so a plugin that sends it in every frame
+/// does not keep pulling the region back.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct Jump {
+ pub to: f32,
+ pub seq: u32,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Font {
+ /// The font the sidebar is written in.
+ #[default]
+ Ui,
+ /// The terminal's font.
+ Mono,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Size {
+ Small,
+ #[default]
+ Body,
+ Title,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Align {
+ #[default]
+ Left,
+ Center,
+ Right,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Cursor {
+ /// The hand: something to press.
+ #[default]
+ Pointer,
+ /// The arrow: a region that answers clicks without looking like it.
+ Arrow,
+}
+
+/// A colour: one of ThinkTerm's by name, which follow its theme, or a fixed
+/// one written `#rrggbb` or `#rrggbbaa`. A name this ThinkTerm does not
+/// know draws as [`Token::Text`], so a plugin written for a newer one still
+/// shows.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Color {
+ Token(Token),
+ Rgba([u8; 4]),
+}
+
+impl Default for Color {
+ fn default() -> Self {
+ Self::Token(Token::Text)
+ }
+}
+
+impl From<Token> for Color {
+ fn from(token: Token) -> Self {
+ Self::Token(token)
+ }
+}
+
+/// ThinkTerm's colours, as the sidebar uses them.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Token {
+ Text,
+ TextMuted,
+ TextFaint,
+ /// The panel's own ground.
+ Bg,
+ /// A card or a field on the ground.
+ BgRaised,
+ BgHover,
+ BgSelected,
+ Border,
+ Accent,
+ /// Text on `Accent`.
+ OnAccent,
+ /// Added, up, fine.
+ Positive,
+ /// Removed, down, wrong.
+ Negative,
+ Warning,
+ /// Grounds for a line or a row: under text in `Text`.
+ PositiveBg,
+ NegativeBg,
+ /// Stronger, for a word within such a line.
+ PositiveBgStrong,
+ NegativeBgStrong,
+}
+
+impl Token {
+ pub const ALL: [Self; 17] = [
+ Self::Text,
+ Self::TextMuted,
+ Self::TextFaint,
+ Self::Bg,
+ Self::BgRaised,
+ Self::BgHover,
+ Self::BgSelected,
+ Self::Border,
+ Self::Accent,
+ Self::OnAccent,
+ Self::Positive,
+ Self::Negative,
+ Self::Warning,
+ Self::PositiveBg,
+ Self::NegativeBg,
+ Self::PositiveBgStrong,
+ Self::NegativeBgStrong,
+ ];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Text => "text",
+ Self::TextMuted => "text-muted",
+ Self::TextFaint => "text-faint",
+ Self::Bg => "bg",
+ Self::BgRaised => "bg-raised",
+ Self::BgHover => "bg-hover",
+ Self::BgSelected => "bg-selected",
+ Self::Border => "border",
+ Self::Accent => "accent",
+ Self::OnAccent => "on-accent",
+ Self::Positive => "positive",
+ Self::Negative => "negative",
+ Self::Warning => "warning",
+ Self::PositiveBg => "positive-bg",
+ Self::NegativeBg => "negative-bg",
+ Self::PositiveBgStrong => "positive-bg-strong",
+ Self::NegativeBgStrong => "negative-bg-strong",
+ }
+ }
+
+ pub fn from_name(name: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|token| token.name() == name)
+ }
+}
+
+impl Color {
+ /// `#rrggbb`, `#rrggbbaa` or a token's name.
+ pub fn parse(text: &str) -> Self {
+ let parsed = match text.strip_prefix('#') {
+ Some(hex) => parse_hex(hex).map(Self::Rgba),
+ None => Token::from_name(text).map(Self::Token),
+ };
+ parsed.unwrap_or_default()
+ }
+}
+
+fn parse_hex(hex: &str) -> Option<[u8; 4]> {
+ if !(hex.len() == 6 || hex.len() == 8) || !hex.is_ascii() {
+ return None;
+ }
+ let byte = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok();
+ let alpha = if hex.len() == 8 { byte(6)? } else { 255 };
+ Some([byte(0)?, byte(2)?, byte(4)?, alpha])
+}
+
+impl fmt::Display for Color {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Token(token) => f.write_str(token.name()),
+ Self::Rgba([r, g, b, 255]) => write!(f, "#{r:02x}{g:02x}{b:02x}"),
+ Self::Rgba([r, g, b, a]) => write!(f, "#{r:02x}{g:02x}{b:02x}{a:02x}"),
+ }
+ }
+}
+
+impl Serialize for Color {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.collect_str(self)
+ }
+}
+
+impl<'de> Deserialize<'de> for Color {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct Named;
+ impl Visitor<'_> for Named {
+ type Value = Color;
+ fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("a colour's name, or #rrggbb")
+ }
+ fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Color, E> {
+ Ok(Color::parse(text))
+ }
+ }
+ deserializer.deserialize_str(Named)
+ }
+}
+
+impl Frame {
+ pub fn push(&mut self, item: impl Into<Item>) {
+ self.items.push(item.into());
+ }
+
+ /// Asks for the panel's extended view, or stops asking.
+ pub fn extend(&mut self, extend: bool) {
+ self.extend = extend;
+ }
+}
+
+impl Rect {
+ pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
+ Self {
+ x,
+ y,
+ w,
+ h,
+ fill: None,
+ radius: 0.0,
+ border: None,
+ }
+ }
+
+ pub fn fill(mut self, color: impl Into<Color>) -> Self {
+ self.fill = Some(color.into());
+ self
+ }
+
+ pub fn radius(mut self, radius: f32) -> Self {
+ self.radius = radius;
+ self
+ }
+
+ pub fn border(mut self, color: impl Into<Color>) -> Self {
+ self.border = Some(color.into());
+ self
+ }
+}
+
+impl Text {
+ pub fn new(x: f32, y: f32, w: f32, h: f32, text: impl Into<String>) -> Self {
+ Self {
+ x,
+ y,
+ w,
+ h,
+ text: text.into(),
+ color: Color::default(),
+ font: Font::Ui,
+ size: Size::Body,
+ bold: false,
+ align: Align::Left,
+ }
+ }
+
+ pub fn color(mut self, color: impl Into<Color>) -> Self {
+ self.color = color.into();
+ self
+ }
+
+ pub fn mono(mut self) -> Self {
+ self.font = Font::Mono;
+ self
+ }
+
+ pub fn size(mut self, size: Size) -> Self {
+ self.size = size;
+ self
+ }
+
+ pub fn bold(mut self) -> Self {
+ self.bold = true;
+ self
+ }
+
+ pub fn align(mut self, align: Align) -> Self {
+ self.align = align;
+ self
+ }
+}
+
+impl Line {
+ pub fn new(points: Vec<f32>, color: impl Into<Color>) -> Self {
+ Self {
+ points,
+ width: 1.0,
+ color: color.into(),
+ }
+ }
+
+ pub fn width(mut self, width: f32) -> Self {
+ self.width = width;
+ self
+ }
+}
+
+impl Area {
+ pub fn new(points: Vec<f32>, base: f32, color: impl Into<Color>) -> Self {
+ Self {
+ points,
+ base,
+ color: color.into(),
+ fade: false,
+ }
+ }
+
+ pub fn fade(mut self) -> Self {
+ self.fade = true;
+ self
+ }
+}
+
+impl Hit {
+ pub fn new(id: impl Into<String>, x: f32, y: f32, w: f32, h: f32) -> Self {
+ Self {
+ id: id.into(),
+ x,
+ y,
+ w,
+ h,
+ hover: None,
+ radius: 0.0,
+ cursor: Cursor::Pointer,
+ }
+ }
+
+ pub fn hover(mut self, color: impl Into<Color>) -> Self {
+ self.hover = Some(color.into());
+ self
+ }
+
+ /// The corners of the hover tint: those of what it lights up.
+ pub fn radius(mut self, radius: f32) -> Self {
+ self.radius = radius;
+ self
+ }
+
+ pub fn cursor(mut self, cursor: Cursor) -> Self {
+ self.cursor = cursor;
+ self
+ }
+}
+
+impl Scroll {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: impl Into<String>,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ height: f32,
+ items: Vec<Item>,
+ ) -> Self {
+ Self {
+ id: id.into(),
+ x,
+ y,
+ w,
+ h,
+ height,
+ items,
+ top: None,
+ }
+ }
+
+ pub fn top(mut self, jump: Jump) -> Self {
+ self.top = Some(jump);
+ self
+ }
+}
+
+impl List {
+ #[allow(clippy::too_many_arguments)]
+ pub fn new(
+ id: impl Into<String>,
+ x: f32,
+ y: f32,
+ w: f32,
+ h: f32,
+ count: u32,
+ row: f32,
+ key: impl Into<String>,
+ ) -> Self {
+ Self {
+ id: id.into(),
+ x,
+ y,
+ w,
+ h,
+ count,
+ row,
+ key: key.into(),
+ version: 0,
+ width: 0.0,
+ fixed: 0.0,
+ top: None,
+ }
+ }
+
+ pub fn version(mut self, version: u32) -> Self {
+ self.version = version;
+ self
+ }
+
+ /// Rows `width` wide, scrolling sideways but for what starts within
+ /// `fixed` of their left edge.
+ pub fn wide(mut self, width: f32, fixed: f32) -> Self {
+ self.width = width;
+ self.fixed = fixed;
+ self
+ }
+
+ pub fn top(mut self, jump: Jump) -> Self {
+ self.top = Some(jump);
+ self
+ }
+}
+
+macro_rules! into_item {
+ ($($kind:ident),*) => {
+ $(impl From<$kind> for Item {
+ fn from(item: $kind) -> Self {
+ Self::$kind(item)
+ }
+ })*
+ };
+}
+
+into_item!(Rect, Text, Line, Area, Hit, Scroll, List);
+
+impl Color {
+ pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
+ Self::Rgba([r, g, b, 255])
+ }
+
+ pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
+ Self::Rgba([r, g, b, a])
+ }
+}
+
+fn one() -> f32 {
+ 1.0
+}
+
+fn is_zero(value: &f32) -> bool {
+ *value == 0.0
+}
+
+fn is_default<T: Default + PartialEq>(value: &T) -> bool {
+ *value == T::default()
+}
+
+impl Item {
+ /// The box it covers in its own units, for telling whether it shows:
+ /// a line's with room for its width.
+ pub fn bounds(&self) -> Bounds {
+ match self {
+ Self::Rect(rect) => Bounds::new(rect.x, rect.y, rect.w, rect.h),
+ Self::Text(text) => Bounds::new(text.x, text.y, text.w, text.h),
+ Self::Hit(hit) => Bounds::new(hit.x, hit.y, hit.w, hit.h),
+ Self::Scroll(scroll) => Bounds::new(scroll.x, scroll.y, scroll.w, scroll.h),
+ Self::List(list) => Bounds::new(list.x, list.y, list.w, list.h),
+ Self::Line(line) => points_bounds(&line.points, None).grow(line.width / 2.0),
+ Self::Area(area) => points_bounds(&area.points, Some(area.base)),
+ }
+ }
+}
+
+fn points_bounds(points: &[f32], base: Option<f32>) -> Bounds {
+ let mut bounds = Bounds::EMPTY;
+ for [x, y] in points.as_chunks::<2>().0 {
+ bounds = bounds.include(*x, *y);
+ if let Some(base) = base {
+ bounds = bounds.include(*x, base);
+ }
+ }
+ bounds
+}
+
+/// A box by its edges.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Bounds {
+ pub left: f32,
+ pub top: f32,
+ pub right: f32,
+ pub bottom: f32,
+}
+
+impl Bounds {
+ /// Covers nothing, and grows from anything it includes.
+ pub const EMPTY: Self = Self {
+ left: f32::INFINITY,
+ top: f32::INFINITY,
+ right: f32::NEG_INFINITY,
+ bottom: f32::NEG_INFINITY,
+ };
+
+ pub fn new(x: f32, y: f32, w: f32, h: f32) -> Self {
+ Self {
+ left: x,
+ top: y,
+ right: x + w.max(0.0),
+ bottom: y + h.max(0.0),
+ }
+ }
+
+ pub fn width(&self) -> f32 {
+ (self.right - self.left).max(0.0)
+ }
+
+ pub fn height(&self) -> f32 {
+ (self.bottom - self.top).max(0.0)
+ }
+
+ pub fn is_empty(&self) -> bool {
+ !(self.right > self.left && self.bottom > self.top)
+ }
+
+ pub fn contains(&self, x: f32, y: f32) -> bool {
+ x >= self.left && x < self.right && y >= self.top && y < self.bottom
+ }
+
+ /// Whether any of it lies within `other`. A line with no width still
+ /// shows, so this is by edges rather than by area.
+ pub fn touches(&self, other: &Bounds) -> bool {
+ self.left <= other.right
+ && self.right >= other.left
+ && self.top <= other.bottom
+ && self.bottom >= other.top
+ }
+
+ /// What the two have in common; empty when nothing.
+ pub fn intersect(&self, other: &Bounds) -> Bounds {
+ Bounds {
+ left: self.left.max(other.left),
+ top: self.top.max(other.top),
+ right: self.right.min(other.right),
+ bottom: self.bottom.min(other.bottom),
+ }
+ }
+
+ pub fn offset(&self, dx: f32, dy: f32) -> Bounds {
+ Bounds {
+ left: self.left + dx,
+ top: self.top + dy,
+ right: self.right + dx,
+ bottom: self.bottom + dy,
+ }
+ }
+
+ fn include(self, x: f32, y: f32) -> Bounds {
+ Bounds {
+ left: self.left.min(x),
+ top: self.top.min(y),
+ right: self.right.max(x),
+ bottom: self.bottom.max(y),
+ }
+ }
+
+ fn grow(self, by: f32) -> Bounds {
+ Bounds {
+ left: self.left - by,
+ top: self.top - by,
+ right: self.right + by,
+ bottom: self.bottom + by,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{json, to_value};
+
+ fn read(value: serde_json::Value) -> Frame {
+ serde_json::from_str(&value.to_string()).unwrap()
+ }
+
+ #[test]
+ fn an_item_that_does_not_read_is_left_out_and_the_rest_stay() {
+ let frame = read(json!({"items": [
+ {"rect": {"x": null, "y": 0, "w": 1, "h": 1}},
+ {"sparkle": {"x": 0}},
+ {"hit": {"id": "kept", "x": 0, "y": 0, "w": 1, "h": 1}},
+ {"scroll": {"id": "s", "x": 0, "y": 0, "w": 9, "h": 9, "height": 20, "items": [
+ "not an item",
+ {"text": {"x": 0, "y": 0, "w": 9, "h": 9, "text": "inside"}}
+ ]}}
+ ]}));
+ assert_eq!(frame.items.len(), 2, "{frame:?}");
+ let Item::Scroll(scroll) = &frame.items[1] else {
+ panic!("{frame:?}")
+ };
+ assert_eq!(scroll.items.len(), 1);
+ }
+
+ #[test]
+ fn items_are_json_named_by_kind() {
+ let frame = read(json!({"items": [
+ {"rect": {"x": 0, "y": 0, "w": 10, "h": 4, "fill": "bg-hover", "radius": 3}},
+ {"text": {"x": 1, "y": 0, "w": 8, "h": 4, "text": "hi", "font": "mono", "align": "right"}},
+ {"line": {"points": [0, 1, 2, 3], "color": "#ff0000"}},
+ {"hit": {"id": "a", "x": 0, "y": 0, "w": 10, "h": 4}},
+ {"list": {"id": "l", "x": 0, "y": 4, "w": 10, "h": 20, "count": 100, "row": 2, "key": "k"}},
+ ]}));
+ let Item::Text(text) = &frame.items[1] else {
+ panic!("{frame:?}")
+ };
+ assert_eq!(text.color, Color::Token(Token::Text), "text by default");
+ assert_eq!(
+ (text.font, text.size, text.align),
+ (Font::Mono, Size::Body, Align::Right)
+ );
+ let Item::Line(line) = &frame.items[2] else {
+ panic!("{frame:?}")
+ };
+ assert_eq!(line.width, 1.0);
+ assert_eq!(line.color, Color::Rgba([255, 0, 0, 255]));
+ let Item::Hit(hit) = &frame.items[3] else {
+ panic!("{frame:?}")
+ };
+ assert_eq!(hit.cursor, Cursor::Pointer);
+
+ // What is the default is left out.
+ assert_eq!(
+ to_value(&frame.items[1]).unwrap(),
+ json!({"text": {"x": 1.0, "y": 0.0, "w": 8.0, "h": 4.0, "text": "hi", "font": "mono", "align": "right"}})
+ );
+ assert!(!frame.extend);
+ assert!(to_value(&frame).unwrap().get("extend").is_none());
+ let mut extending = read(json!({"items": [], "extend": true}));
+ assert!(extending.extend);
+ extending.extend(false);
+ assert_eq!(to_value(&extending).unwrap(), json!({"items": []}));
+ }
+
+ #[test]
+ fn colours_are_names_or_hex_and_the_unknown_is_text() {
+ assert_eq!(Color::parse("negative-bg"), Color::Token(Token::NegativeBg));
+ assert_eq!(Color::parse("#0a0b0c"), Color::Rgba([10, 11, 12, 255]));
+ assert_eq!(Color::parse("#0a0b0c80"), Color::Rgba([10, 11, 12, 128]));
+ for unknown in ["sparkle", "#12", "#gg0000", "", "#ééé"] {
+ assert_eq!(
+ Color::parse(unknown),
+ Color::Token(Token::Text),
+ "{unknown}"
+ );
+ }
+ for color in [
+ Color::Rgba([1, 2, 3, 255]),
+ Color::Rgba([1, 2, 3, 4]),
+ Token::Accent.into(),
+ ] {
+ assert_eq!(Color::parse(&color.to_string()), color);
+ }
+ for token in Token::ALL {
+ assert_eq!(Token::from_name(token.name()), Some(token));
+ }
+ }
+
+ #[test]
+ fn bounds_cover_what_an_item_draws() {
+ let line = Item::Line(Line {
+ points: vec![10.0, 5.0, 20.0, 1.0],
+ width: 2.0,
+ color: Color::default(),
+ });
+ assert_eq!(
+ line.bounds(),
+ Bounds {
+ left: 9.0,
+ top: 0.0,
+ right: 21.0,
+ bottom: 6.0
+ }
+ );
+ let area = Item::Area(Area {
+ points: vec![0.0, 5.0, 4.0, 2.0],
+ base: 10.0,
+ color: Color::default(),
+ fade: true,
+ });
+ assert_eq!(
+ area.bounds(),
+ Bounds {
+ left: 0.0,
+ top: 2.0,
+ right: 4.0,
+ bottom: 10.0
+ }
+ );
+ let flat = Bounds::new(0.0, 3.0, 5.0, 0.0);
+ assert!(flat.touches(&Bounds::new(0.0, 0.0, 10.0, 10.0)));
+ assert!(Bounds::new(0.0, 0.0, 1.0, 1.0)
+ .intersect(&Bounds::new(2.0, 2.0, 1.0, 1.0))
+ .is_empty());
+ }
+}
diff --git a/thinkterm-plugin-panel/src/wire.rs b/thinkterm-plugin-panel/src/wire.rs
new file mode 100644
index 00000000..aa1cd02e
--- /dev/null
+++ b/thinkterm-plugin-panel/src/wire.rs
@@ -0,0 +1,401 @@
+//! What passes between a panel and its plugin besides the frames: what the
+//! plugin is told about the panel, what the user does in it, the rows of
+//! its lists, and what it asks ThinkTerm to do on another machine.
+
+use crate::scene::Item;
+use base64::Engine;
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use serde_json::value::RawValue;
+
+/// What a plugin is told of a panel it draws: its size, how large
+/// ThinkTerm's text is there, whether it is dark, the language ThinkTerm
+/// speaks, and where the terminal beside it is. Sent when the panel opens,
+/// and again whenever any of it changes.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Env {
+ pub width: f32,
+ pub height: f32,
+ /// Device pixels to a unit, for lines meant to fall on whole pixels.
+ pub scale: f32,
+ pub dark: bool,
+ pub small: TextMetrics,
+ pub body: TextMetrics,
+ pub title: TextMetrics,
+ pub mono: MonoMetrics,
+ /// ThinkTerm's language, as a tag: "en-US", "zh-CN". Empty from a
+ /// ThinkTerm that does not say.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub locale: String,
+ /// The directory of the terminal beside the panel -- the pane in focus
+ /// in its window -- when that terminal runs on the machine the plugin
+ /// does; none otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cwd: Option<String>,
+ /// Where that terminal runs when it is another machine, reached over
+ /// SSH: what the plugin wants of its files and programs there, it asks
+ /// ThinkTerm for ([`Ask`]).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub remote: Option<Remote>,
+ /// Whether the panel would get its extended view were its frame to ask
+ /// for one: the client shows them, and has the room. So a plugin knows
+ /// whether to fit what it would put there into the panel itself. Never
+ /// so for an extended view.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub can_extend: bool,
+ /// In an extended view, the close button ThinkTerm draws over its top
+ /// left corner: a plugin leaves that square empty, and lines its first
+ /// row up with it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub close: Option<CloseButton>,
+}
+
+/// The other machine the terminal beside a panel runs on.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Remote {
+ /// The machine, by the name ThinkTerm shows the user.
+ pub host: String,
+ /// The machine, and the account ThinkTerm reaches it as, by a word to
+ /// compare rather than show: two accounts on one host share a `host`,
+ /// not this. What the plugin asks of it names it, and is done only
+ /// while the terminal beside the panel is still there.
+ pub machine: String,
+ /// The terminal's directory there.
+ pub cwd: String,
+}
+
+/// What a plugin asks ThinkTerm to do on the machine the terminal beside
+/// one of its panels runs on, when that is another ([`Env::remote`]), over
+/// ThinkTerm's own connection to it. Answered with an [`Answer`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "op", rename_all = "snake_case")]
+pub enum Ask {
+ /// Runs `args` -- a program and its arguments -- in the directory
+ /// `cwd`, keeping at most `limit` bytes of what it prints.
+ Run {
+ args: Vec<String>,
+ cwd: String,
+ limit: u64,
+ },
+ /// At most `limit` bytes of the file at `path`.
+ Read { path: String, limit: u64 },
+ /// What is at `path`, a link not followed.
+ Stat { path: String },
+}
+
+/// What came of an [`Ask`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "result", rename_all = "snake_case")]
+pub enum Answer {
+ /// The program ran and ended with `status`, `None` when it was killed.
+ /// `out` is what it printed, `cut` when it printed more than that.
+ Ran {
+ status: Option<i32>,
+ out: Bytes,
+ #[serde(default)]
+ cut: bool,
+ },
+ /// The file's bytes, `cut` when it has more.
+ Read {
+ bytes: Bytes,
+ #[serde(default)]
+ cut: bool,
+ },
+ /// What is there, if anything is.
+ Stat { entry: Option<Entry> },
+ /// It could not be done, and why. With `connect`, ThinkTerm is not
+ /// connected to the machine: the panel shows the user a button that
+ /// connects it, and asking again after that may work.
+ Failed {
+ why: String,
+ #[serde(default, skip_serializing_if = "is_false")]
+ connect: bool,
+ },
+}
+
+impl Answer {
+ pub fn failed(why: impl Into<String>) -> Self {
+ Self::Failed {
+ why: why.into(),
+ connect: false,
+ }
+ }
+}
+
+/// A file, a directory, a link or something else, as [`Ask::Stat`] finds it.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Entry {
+ pub kind: EntryKind,
+ pub len: u64,
+ /// When it last changed, in seconds since 1970.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub modified: Option<u64>,
+ /// Where a link points.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub target: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum EntryKind {
+ File,
+ Dir,
+ Link,
+ Other,
+}
+
+/// Bytes, carried in JSON as base64.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct Bytes(pub Vec<u8>);
+
+impl Serialize for Bytes {
+ fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(&self.0))
+ }
+}
+
+impl<'de> Deserialize<'de> for Bytes {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let text = std::borrow::Cow::<str>::deserialize(deserializer)?;
+ base64::engine::general_purpose::STANDARD
+ .decode(text.as_bytes())
+ .map(Bytes)
+ .map_err(serde::de::Error::custom)
+ }
+}
+
+/// Where a close button sits, in a view's units: its top left corner, and
+/// its side.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct CloseButton {
+ pub x: f32,
+ pub y: f32,
+ pub size: f32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct TextMetrics {
+ /// The font's size.
+ pub size: f32,
+ /// How tall a line of it is.
+ pub line: f32,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct MonoMetrics {
+ pub size: f32,
+ pub line: f32,
+ /// How wide a column is: a character most scripts write in one, twice
+ /// that for one they write in two.
+ pub advance: f32,
+}
+
+/// Something the user did in the panel. Hovering and scrolling are not
+/// among them: the player does both without asking.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Input {
+ /// A press on a hit, at `x`, `y` within it.
+ Click(Click),
+ /// The user closed an extended view with its close button. It goes
+ /// whatever the plugin does, and its panel gets no other until its
+ /// frames have stopped asking for one: this is for the plugin to stop.
+ Close,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Click {
+ pub id: String,
+ pub x: f32,
+ pub y: f32,
+ #[serde(default)]
+ pub button: Button,
+ /// 2 for the second press of a double click.
+ #[serde(default = "one")]
+ pub count: u32,
+ #[serde(default)]
+ pub mods: Mods,
+}
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Button {
+ #[default]
+ Left,
+ Middle,
+ Right,
+}
+
+/// The modifier keys held. `cmd` is Command on a Mac, and the Windows or
+/// Super key elsewhere.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Mods {
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub shift: bool,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub ctrl: bool,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub alt: bool,
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub cmd: bool,
+}
+
+/// Rows `from..to` of the list `list`, as drawn with `key` and `version`.
+/// `layout` counts what makes rows drawn before out of date -- the panel's
+/// size and fonts changing, the plugin starting again: it is only echoed.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RowsWanted {
+ pub list: String,
+ pub key: String,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub version: u32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub layout: u32,
+ pub from: u32,
+ pub to: u32,
+}
+
+/// Rows answering a [`RowsWanted`], its `list`, `key`, `version`, `layout`
+/// and `from` repeated: `rows[0]` is row `from`. A row's items are in its
+/// own units, from the list's left edge and the row's top. Scroll areas and
+/// lists do not go in a row; an item that does not read is left out.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Rows {
+ pub list: String,
+ pub key: String,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub version: u32,
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub layout: u32,
+ pub from: u32,
+ #[serde(deserialize_with = "rows")]
+ pub rows: Vec<Vec<Item>>,
+}
+
+/// Rows, each keeping the items that read; a row that is not a list is
+/// empty.
+fn rows<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Vec<Item>>, D::Error> {
+ let raw: Vec<Box<RawValue>> = Vec::deserialize(deserializer)?;
+ Ok(raw
+ .iter()
+ .map(|row| {
+ let mut read = serde_json::Deserializer::from_str(row.get());
+ crate::scene::items(&mut read).unwrap_or_default()
+ })
+ .collect())
+}
+
+fn one() -> u32 {
+ 1
+}
+
+fn is_false(value: &bool) -> bool {
+ !value
+}
+
+fn is_zero(value: &u32) -> bool {
+ *value == 0
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{json, to_value};
+
+ #[test]
+ fn input_is_json_named_by_kind() {
+ let click = Input::Click(Click {
+ id: "file:2".into(),
+ x: 3.0,
+ y: 4.5,
+ button: Button::Left,
+ count: 1,
+ mods: Mods {
+ shift: true,
+ ..Mods::default()
+ },
+ });
+ let value = to_value(&click).unwrap();
+ assert_eq!(
+ value,
+ json!({"click": {"id": "file:2", "x": 3.0, "y": 4.5, "button": "left", "count": 1, "mods": {"shift": true}}})
+ );
+ let bare: Input =
+ serde_json::from_value(json!({"click": {"id": "a", "x": 0, "y": 0}})).unwrap();
+ let Input::Click(bare) = bare else {
+ panic!("{bare:?}")
+ };
+ assert_eq!(
+ (bare.count, bare.button, bare.mods),
+ (1, Button::Left, Mods::default())
+ );
+ assert_eq!(to_value(Input::Close).unwrap(), json!("close"));
+ assert_eq!(
+ serde_json::from_value::<Input>(json!("close")).unwrap(),
+ Input::Close
+ );
+ }
+
+ #[test]
+ fn asks_and_answers_are_json_named_by_what_they_are() {
+ let run = Ask::Run {
+ args: vec!["git".into(), "status".into()],
+ cwd: "/home/user/repo".into(),
+ limit: 1024,
+ };
+ assert_eq!(
+ to_value(&run).unwrap(),
+ json!({"op": "run", "args": ["git", "status"], "cwd": "/home/user/repo", "limit": 1024})
+ );
+ let ran = Answer::Ran {
+ status: Some(0),
+ out: Bytes(b"a\0\xff".to_vec()),
+ cut: false,
+ };
+ let sent = to_value(&ran).unwrap();
+ assert_eq!(
+ sent,
+ json!({"result": "ran", "status": 0, "out": "YQD/", "cut": false})
+ );
+ assert_eq!(
+ serde_json::from_value::<Answer>(sent).unwrap(),
+ ran,
+ "bytes round trip"
+ );
+ assert_eq!(
+ to_value(Answer::failed("no")).unwrap(),
+ json!({"result": "failed", "why": "no"})
+ );
+ let stat: Answer = serde_json::from_value(json!({
+ "result": "stat",
+ "entry": {"kind": "link", "len": 7, "target": "elsewhere"}
+ }))
+ .unwrap();
+ let Answer::Stat { entry: Some(entry) } = stat else {
+ panic!("{stat:?}")
+ };
+ assert_eq!((entry.kind, entry.modified), (EntryKind::Link, None));
+ assert!(serde_json::from_value::<Answer>(
+ json!({"result": "ran", "status": 0, "out": "not base64!"})
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn a_row_keeps_what_reads_of_it_and_its_place() {
+ let rows: Rows = serde_json::from_value(json!({
+ "list": "l", "key": "k", "layout": 3, "from": 10,
+ "rows": [
+ [{"rect": {"x": 0, "y": 0, "w": null, "h": 1}}, {"hit": {"id": "a", "x": 0, "y": 0, "w": 1, "h": 1}}],
+ "not a row",
+ []
+ ]
+ }))
+ .unwrap();
+ assert_eq!((rows.version, rows.layout, rows.from), (0, 3, 10));
+ let lengths: Vec<usize> = rows.rows.iter().map(Vec::len).collect();
+ assert_eq!(lengths, [1, 0, 0], "each row stays where it was");
+ let sent = to_value(&rows).unwrap();
+ assert!(sent.get("version").is_none(), "0 is left out: {sent}");
+ assert_eq!(sent["layout"], 3);
+ }
+}
diff --git a/thinkterm-plugin-sdk/Cargo.toml b/thinkterm-plugin-sdk/Cargo.toml
index 733a6520..4908a411 100644
--- a/thinkterm-plugin-sdk/Cargo.toml
+++ b/thinkterm-plugin-sdk/Cargo.toml
@@ -4,12 +4,14 @@ version = "0.1.0"
edition = "2021"
publish = false
-# What a ThinkTerm plugin is written with: the Plugin trait, and the loop
-# that speaks the plugin protocol over standard input and output. Kept to
-# serde and anyhow, so a plugin that uses it stays small.
+# What a ThinkTerm plugin is written with: the Plugin trait, the loop that
+# speaks the plugin protocol over standard input and output, and the items a
+# panel is drawn with. Kept to serde and anyhow, so a plugin that uses it
+# stays small.
[dependencies]
anyhow.workspace = true
serde = { workspace = true, features = ["derive", "std"] }
serde_json.workspace = true
thinkterm-plugin-channel.workspace = true
+thinkterm-plugin-panel.workspace = true
diff --git a/thinkterm-plugin-sdk/src/lib.rs b/thinkterm-plugin-sdk/src/lib.rs
index 0c1757a7..18e65577 100644
--- a/thinkterm-plugin-sdk/src/lib.rs
+++ b/thinkterm-plugin-sdk/src/lib.rs
@@ -25,17 +25,55 @@
//! }
//! ```
//!
+//! A plugin with a panel in the right sidebar draws it by hand, from the
+//! items in [`panel`], each time [`Plugin::draw`] is called:
+//!
+//! ```no_run
+//! use thinkterm_plugin_sdk::panel::{Frame, Rect, Text, Token};
+//! use thinkterm_plugin_sdk::{Plugin, View};
+//!
+//! struct Greeting;
+//!
+//! impl Plugin for Greeting {
+//! fn draw(&mut self, view: &View, frame: &mut Frame) {
+//! let line = view.env.body.line;
+//! frame.push(Rect::new(8.0, 8.0, view.env.width - 16.0, line + 12.0).fill(Token::BgRaised).radius(6.0));
+//! frame.push(Text::new(16.0, 14.0, view.env.width - 32.0, line, "Hello"));
+//! }
+//! }
+//! ```
+//!
+//! A panel with more to show than a sidebar has room for asks for its
+//! extended view, a wide area beside the sidebar that the user sizes, with
+//! [`Frame::extend`](panel::Frame::extend()). It comes as a view of its own,
+//! drawn the same way: [`View::extended`] tells the two apart, and
+//! [`View::panel`] names the panel either belongs to, for what they share.
+//!
+//! When the terminal beside a panel runs on another machine, the view's
+//! [`Env::remote`](panel::Env::remote) says which, and the plugin has
+//! ThinkTerm run programs and read files there with [`Emitter::ask`], over
+//! ThinkTerm's own connection to it.
+//!
//! The plugins built into ThinkTerm implement the same trait, and run
//! inside the plugin host instead of in a program of their own.
pub mod protocol;
+pub use thinkterm_plugin_panel as panel;
+
use anyhow::anyhow;
+use panel::{Answer, Ask, Env, Frame, Input, Item, Rows, RowsWanted};
use protocol::{FromPlugin, ToPlugin};
use serde_json::Value;
-use std::io::{self, BufRead};
+use std::collections::{BTreeMap, HashMap};
+use std::io;
use std::panic::AssertUnwindSafe;
use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use thinkterm_plugin_channel::wire::Raw;
pub trait Plugin: Send {
/// Answers a client's call: any JSON, as the plugin defines it. The
@@ -44,6 +82,36 @@ pub trait Plugin: Send {
let _ = (body, cx);
anyhow::bail!("this plugin takes no calls")
}
+
+ /// Draws the panel `view` shows into `frame`, which starts empty: when
+ /// it comes on show, when its size, fonts or theme change, after each
+ /// input, and whenever [`Cx::redraw`] or [`Emitter::redraw`] asks. A
+ /// frame the same as the last one sent is not sent again. The default
+ /// draws nothing.
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ let _ = (view, frame);
+ }
+
+ /// Rows of a list [`draw`](Self::draw) put in `view`'s frame, as
+ /// `wanted` says: at most `wanted.to - wanted.from` of them, from
+ /// `wanted.from` on.
+ fn rows(&mut self, view: &View, wanted: &RowsWanted) -> Vec<Vec<Item>> {
+ let _ = (view, wanted);
+ Vec::new()
+ }
+
+ /// What the user did in `view`: a click, or, in an extended view, the
+ /// close button pressed -- the view goes, and the panel is to stop
+ /// asking for it. The panel is drawn again after it, and its extended
+ /// view with it.
+ fn input(&mut self, view: &View, input: Input, cx: &mut Cx) {
+ let _ = (view, input, cx);
+ }
+
+ /// `view` went off show.
+ fn closed(&mut self, view: &View) {
+ let _ = view;
+ }
}
/// A plugin chosen at run time, among several.
@@ -51,12 +119,65 @@ impl<P: Plugin + ?Sized> Plugin for Box<P> {
fn call(&mut self, body: Value, cx: &mut Cx) -> anyhow::Result<Value> {
(**self).call(body, cx)
}
+
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ (**self).draw(view, frame)
+ }
+
+ fn rows(&mut self, view: &View, wanted: &RowsWanted) -> Vec<Vec<Item>> {
+ (**self).rows(view, wanted)
+ }
+
+ fn input(&mut self, view: &View, input: Input, cx: &mut Cx) {
+ (**self).input(view, input, cx)
+ }
+
+ fn closed(&mut self, view: &View) {
+ (**self).closed(view)
+ }
+}
+
+/// A panel of the plugin on show. The same plugin can be on show in
+/// several places at once -- two windows, a browser -- each a view of its
+/// own, with its own size. A panel's extended view is a view as well.
+#[derive(Debug, Clone, PartialEq)]
+pub struct View {
+ pub id: u64,
+ pub env: Env,
+ /// For an extended view, the panel it extends.
+ pub extends: Option<u64>,
+ /// For a panel, its extended view while one is on show: the panel is
+ /// drawn again when it comes and when it goes.
+ pub extension: Option<u64>,
+}
+
+impl View {
+ /// A panel of `env`'s size, numbered `id`.
+ pub fn new(id: u64, env: Env) -> Self {
+ Self {
+ id,
+ env,
+ extends: None,
+ extension: None,
+ }
+ }
+
+ /// Whether this is a panel's extended view.
+ pub fn extended(&self) -> bool {
+ self.extends.is_some()
+ }
+
+ /// The panel this view belongs to: itself, or the one it extends.
+ pub fn panel(&self) -> u64 {
+ self.extends.unwrap_or(self.id)
+ }
}
/// What a call does besides answering, all of it sent once the answer is.
#[derive(Debug, Default)]
pub struct Cx {
watch: bool,
+ redraw: bool,
events: Vec<Value>,
}
@@ -77,10 +198,17 @@ impl Cx {
self.events.push(event);
}
+ /// Every panel of the plugin on show is drawn again: what they show
+ /// changed.
+ pub fn redraw(&mut self) {
+ self.redraw = true;
+ }
+
/// What was asked for, for whatever runs the plugin to carry out.
pub fn finish(self) -> Effects {
Effects {
watch: self.watch,
+ redraw: self.redraw,
events: self.events,
}
}
@@ -89,20 +217,110 @@ impl Cx {
#[derive(Debug, Default, PartialEq)]
pub struct Effects {
pub watch: bool,
+ pub redraw: bool,
pub events: Vec<Value>,
}
-/// Sends events from outside a call: from a thread the plugin keeps to
-/// watch something, say.
+/// Reaches the plugin from outside a call: from a thread the plugin keeps
+/// to watch something, say.
#[derive(Debug, Clone)]
pub struct Emitter {
- _private: (),
+ wake: Sender<Wake>,
+ /// A redraw is asked for and not yet done: more asks fold into it.
+ redrawing: Arc<AtomicBool>,
+ asking: Arc<Asking>,
}
impl Emitter {
pub fn emit(&self, event: Value) -> io::Result<()> {
send(&FromPlugin::Event { body: event })
}
+
+ /// Has every panel of the plugin on show drawn again, on the plugin's
+ /// own thread, once it is done with what it is doing.
+ pub fn redraw(&self) {
+ if !self.redrawing.swap(true, Ordering::AcqRel) {
+ let _ = self.wake.send(Wake::Redraw);
+ }
+ }
+
+ /// Has ThinkTerm do `ask` on `machine`, the other machine the terminal
+ /// beside panel `view` runs on as its env names it
+ /// ([`Remote::machine`](panel::Remote::machine)), and waits at most
+ /// `wait` for what came of it. It fails once the terminal has moved to
+ /// another machine. Blocking: ask from a thread of the plugin's own
+ /// rather than while drawing, which waits for it.
+ pub fn ask(&self, view: u64, machine: &str, ask: &Ask, wait: Duration) -> Answer {
+ self.asking.ask(view, machine, ask, wait, send)
+ }
+}
+
+/// What the plugin asked ThinkTerm and waits for, by the id it was asked
+/// with. An answer is taken in on the thread reading the input, so one that
+/// comes while the plugin's own thread is busy still reaches its asker.
+#[derive(Debug, Default)]
+struct Asking {
+ last: AtomicU64,
+ waiting: Mutex<HashMap<u64, SyncSender<Answer>>>,
+}
+
+impl Asking {
+ fn ask(
+ &self,
+ view: u64,
+ machine: &str,
+ ask: &Ask,
+ wait: Duration,
+ out: impl FnOnce(&FromPlugin) -> io::Result<()>,
+ ) -> Answer {
+ let id = self.last.fetch_add(1, Ordering::Relaxed) + 1;
+ let (answered, answer) = mpsc::sync_channel(1);
+ self.waiting().insert(id, answered);
+ let asked = out(&FromPlugin::Ask {
+ view,
+ id,
+ machine: machine.to_string(),
+ ask: Raw::new(ask),
+ });
+ let answer = match asked {
+ Ok(()) => answer
+ .recv_timeout(wait)
+ .map_err(|_| Answer::failed(format!("ThinkTerm did not answer within {wait:?}"))),
+ Err(err) => Err(Answer::failed(format!("cannot ask ThinkTerm: {err}"))),
+ };
+ self.waiting().remove(&id);
+ answer.unwrap_or_else(|failed| failed)
+ }
+
+ /// Hands `answer` to whoever asked `id`, if anyone still waits.
+ fn answer(&self, id: u64, answer: Answer) {
+ if let Some(asker) = self.waiting().remove(&id) {
+ let _ = asker.try_send(answer);
+ }
+ }
+
+ /// Tells the asker of `line`, an answer this SDK cannot read -- from a
+ /// newer ThinkTerm, say -- that it failed. False for a line that is no
+ /// answer.
+ fn unreadable(&self, line: &[u8], err: &serde_json::Error) -> bool {
+ let Ok(message) = serde_json::from_slice::<Value>(line) else {
+ return false;
+ };
+ if message.get("type").and_then(Value::as_str) != Some("answer") {
+ return false;
+ }
+ if let Some(id) = message.get("id").and_then(Value::as_u64) {
+ let why = format!("ThinkTerm answered in a way this plugin does not know: {err}");
+ self.answer(id, Answer::failed(why));
+ }
+ true
+ }
+
+ fn waiting(&self) -> std::sync::MutexGuard<'_, HashMap<u64, SyncSender<Answer>>> {
+ self.waiting
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
}
fn send(message: &FromPlugin) -> io::Result<()> {
@@ -122,54 +340,371 @@ pub fn run(plugin: impl Plugin) -> io::Result<()> {
run_with(|_| plugin)
}
-/// [`run`], for a plugin that sends events of its own accord: `make` is
-/// handed what sends them.
+/// [`run`], for a plugin that sends events or redraws of its own accord:
+/// `make` is handed what does that.
pub fn run_with<P: Plugin>(make: impl FnOnce(Emitter) -> P) -> io::Result<()> {
- let mut plugin = make(Emitter { _private: () });
- send(&FromPlugin::Ready { api: protocol::API })?;
- serve(&mut plugin, &mut io::stdin().lock(), &mut |message| {
- send(message)
+ let (wake, woken) = mpsc::channel();
+ let redrawing = Arc::new(AtomicBool::new(false));
+ let asking = Arc::new(Asking::default());
+ let mut plugin = make(Emitter {
+ wake: wake.clone(),
+ redrawing: Arc::clone(&redrawing),
+ asking: Arc::clone(&asking),
+ });
+ let api = speaking(std::env::var("THINKTERM_PLUGIN_API").ok().as_deref());
+ send(&FromPlugin::Ready { api })?;
+ // Input is read on a thread of its own, so that a redraw asked for
+ // from elsewhere does not wait for the next line, nor an answer for the
+ // plugin's thread to be free.
+ let answers = Arc::clone(&asking);
+ std::thread::Builder::new()
+ .name("plugin-input".into())
+ .spawn(move || {
+ let mut input = io::stdin().lock();
+ let mut line = Vec::new();
+ let end = loop {
+ match protocol::read_line(&mut input, &mut line) {
+ Ok(true) => {
+ let woke = match serde_json::from_slice::<ToPlugin>(&line) {
+ Ok(ToPlugin::Answer { id, answer, .. }) => {
+ answers.answer(id, answer);
+ continue;
+ }
+ Ok(message) => Wake::Message(message),
+ Err(err) if answers.unreadable(&line, &err) => continue,
+ // Left for the plugin's thread to say it does
+ // not know.
+ Err(_) => Wake::Line(std::mem::take(&mut line)),
+ };
+ if wake.send(woke).is_err() {
+ return;
+ }
+ }
+ Ok(false) => break Ok(()),
+ Err(err) => break Err(err),
+ }
+ };
+ let _ = wake.send(Wake::End(end));
+ })?;
+ Runner::new(redrawing, asking).serve(&mut plugin, bursts(woken), &mut |message| send(message))
+}
+
+/// The plugin API to say `ready` with: this SDK's, or the one ThinkTerm
+/// says it speaks (`THINKTERM_PLUGIN_API`) when that is older, since a
+/// ThinkTerm takes none newer than its own. What this SDK sends reads the
+/// same in every version it speaks.
+fn speaking(host: Option<&str>) -> u32 {
+ host.and_then(|api| api.trim().parse::<u32>().ok())
+ .map_or(protocol::API, |api| api.clamp(1, protocol::API))
+}
+
+/// The most taken in one burst: whatever is drawn waits no longer than this
+/// many messages.
+const BURST_LIMIT: usize = 64;
+
+/// What wakes the plugin's thread, a burst at a time: the next to come,
+/// and what is waiting behind it already. A panel is drawn once a burst is
+/// through, so a window being resized, which sends a size for each step,
+/// has it drawn for the size it stopped at, not for each.
+fn bursts(woken: Receiver<Wake>) -> impl Iterator<Item = Vec<Wake>> {
+ std::iter::from_fn(move || {
+ let mut burst = vec![woken.recv().ok()?];
+ burst.extend(woken.try_iter().take(BURST_LIMIT - 1));
+ Some(burst)
})
}
-/// Answers what `input` asks until it ends or says stop.
-fn serve<P: Plugin>(
- plugin: &mut P,
- input: &mut impl BufRead,
- out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
-) -> io::Result<()> {
- let mut line = Vec::new();
- while protocol::read_line(input, &mut line)? {
+/// What the plugin's thread wakes for.
+#[derive(Debug)]
+enum Wake {
+ Message(ToPlugin),
+ /// A line that is not a message this plugin knows, or not read yet.
+ Line(Vec<u8>),
+ Redraw,
+ /// The input ended, or broke.
+ End(io::Result<()>),
+}
+
+/// A view, and the last frame sent for it.
+struct Shown {
+ view: View,
+ last: Option<Raw>,
+ /// To be drawn once the burst is through.
+ dirty: bool,
+}
+
+struct Runner {
+ views: BTreeMap<u64, Shown>,
+ redrawing: Arc<AtomicBool>,
+ asking: Arc<Asking>,
+}
+
+impl Runner {
+ fn new(redrawing: Arc<AtomicBool>, asking: Arc<Asking>) -> Self {
+ Self {
+ views: BTreeMap::new(),
+ redrawing,
+ asking,
+ }
+ }
+
+ /// Answers what comes in until the input ends or says stop, drawing
+ /// what is to be drawn after each burst.
+ fn serve<P: Plugin>(
+ &mut self,
+ plugin: &mut P,
+ woken: impl IntoIterator<Item = Vec<Wake>>,
+ out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
+ ) -> io::Result<()> {
+ for burst in woken {
+ for wake in burst {
+ if let Some(end) = self.take(plugin, wake, out)? {
+ return end;
+ }
+ }
+ self.draw_dirty(plugin, out)?;
+ }
+ Ok(())
+ }
+
+ /// Takes in one wake; `Some` with how the plugin ends when it is to.
+ fn take<P: Plugin>(
+ &mut self,
+ plugin: &mut P,
+ wake: Wake,
+ out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
+ ) -> io::Result<Option<io::Result<()>>> {
+ let line = match wake {
+ Wake::Message(message) => return self.handle(plugin, message, out),
+ Wake::Line(line) => line,
+ Wake::Redraw => {
+ self.redrawing.store(false, Ordering::Release);
+ self.dirty_all();
+ return Ok(None);
+ }
+ Wake::End(end) => return Ok(Some(end)),
+ };
if line.iter().all(u8::is_ascii_whitespace) {
- continue;
+ return Ok(None);
}
let message: ToPlugin = match serde_json::from_slice(&line) {
Ok(message) => message,
Err(err) => {
- // One from a newer ThinkTerm, say. Its caller is told when
- // it has one; anything else is let be.
- let id = serde_json::from_slice::<Value>(&line)
+ if self.asking.unreadable(&line, &err) {
+ return Ok(None);
+ }
+ // One from a newer ThinkTerm, say. A call's caller is told;
+ // anything else is let be, for an error answers a call.
+ let call = serde_json::from_slice::<Value>(&line)
.ok()
+ .filter(|message| message.get("type").and_then(Value::as_str) == Some("call"))
.and_then(|message| message.get("id")?.as_u64());
- if let Some(id) = id {
+ if let Some(id) = call {
out(&FromPlugin::Error {
id,
message: format!("not a message this plugin knows: {err}"),
})?;
}
- continue;
+ return Ok(None);
}
};
+ self.handle(plugin, message, out)
+ }
+
+ /// Answers one message; `Some` with how the plugin ends when it is to.
+ fn handle<P: Plugin>(
+ &mut self,
+ plugin: &mut P,
+ message: ToPlugin,
+ out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
+ ) -> io::Result<Option<io::Result<()>>> {
match message {
ToPlugin::Call { id, body } => {
let mut cx = Cx::new();
let answer = guard(|| plugin.call(body, &mut cx));
- answer_with(out, id, answer, cx)?;
+ if answer_with(out, id, answer, cx)? {
+ self.dirty_all();
+ }
+ }
+ ToPlugin::Open { view, env, extends } => {
+ // The panel an extended view extends knows it by.
+ if let Some(panel) = extends.and_then(|panel| self.views.get_mut(&panel)) {
+ panel.view.extension = Some(view);
+ panel.dirty = true;
+ }
+ let shown = Shown {
+ view: View {
+ extends,
+ ..View::new(view, env)
+ },
+ last: None,
+ dirty: true,
+ };
+ self.views.insert(view, shown);
+ }
+ ToPlugin::Env { view, env } => {
+ if let Some(shown) = self.views.get_mut(&view) {
+ shown.view.env = env;
+ shown.dirty = true;
+ }
+ }
+ ToPlugin::Input { view, input } => {
+ let Some(shown) = self.views.get(&view) else {
+ return Ok(None);
+ };
+ let panel = shown.view.panel();
+ let mut cx = Cx::new();
+ let handled = guard(|| {
+ plugin.input(&shown.view, input, &mut cx);
+ Ok(())
+ });
+ if let Err(err) = handled {
+ eprintln!("input in panel {view}: {err:#}");
+ }
+ // What one of a panel's views shows, the other may follow.
+ self.dirty_panel(panel);
+ let effects = cx.finish();
+ for body in effects.events {
+ out(&FromPlugin::Event { body })?;
+ }
+ if effects.redraw {
+ self.dirty_all();
+ }
+ }
+ ToPlugin::Rows { view, wanted } => {
+ // Rows come from a plugin that has drawn the view, and made
+ // whatever it keeps for one: asked for before that, on an
+ // opening, the view is drawn first.
+ if self
+ .views
+ .get(&view)
+ .is_some_and(|shown| shown.last.is_none())
+ {
+ self.draw(plugin, view, out)?;
+ }
+ let Some(shown) = self.views.get(&view) else {
+ return Ok(None);
+ };
+ let rows = guard(|| Ok(plugin.rows(&shown.view, &wanted)));
+ let mut rows = rows.unwrap_or_else(|err| {
+ eprintln!("rows of panel {view}: {err:#}");
+ Vec::new()
+ });
+ rows.truncate(wanted.to.saturating_sub(wanted.from) as usize);
+ let rows = Rows {
+ list: wanted.list,
+ key: wanted.key,
+ version: wanted.version,
+ layout: wanted.layout,
+ from: wanted.from,
+ rows,
+ };
+ out(&FromPlugin::Rows {
+ view,
+ rows: Raw::new(&rows),
+ })?;
+ }
+ ToPlugin::Close { view } => {
+ // A panel's extended view goes first: ThinkTerm closes it
+ // so, and it is done here for one that does not.
+ let extensions: Vec<u64> = self
+ .views
+ .values()
+ .filter(|shown| shown.view.extends == Some(view))
+ .map(|shown| shown.view.id)
+ .collect();
+ for extension in extensions {
+ self.close(plugin, extension);
+ }
+ self.close(plugin, view);
+ }
+ ToPlugin::Answer { id, answer, .. } => self.asking.answer(id, answer),
+ ToPlugin::Stop => return Ok(Some(Ok(()))),
+ }
+ Ok(None)
+ }
+
+ /// Lets view `view` go, telling the plugin; the panel it extended is
+ /// drawn again without it.
+ fn close<P: Plugin>(&mut self, plugin: &mut P, view: u64) {
+ let Some(shown) = self.views.remove(&view) else {
+ return;
+ };
+ if let Some(panel) = shown
+ .view
+ .extends
+ .and_then(|panel| self.views.get_mut(&panel))
+ .filter(|panel| panel.view.extension == Some(view))
+ {
+ panel.view.extension = None;
+ panel.dirty = true;
+ }
+ let _ = guard(|| {
+ plugin.closed(&shown.view);
+ Ok(())
+ });
+ }
+
+ fn dirty_all(&mut self) {
+ for shown in self.views.values_mut() {
+ shown.dirty = true;
+ }
+ }
+
+ /// Panel `panel` and its extended view are to be drawn again.
+ fn dirty_panel(&mut self, panel: u64) {
+ for shown in self.views.values_mut() {
+ if shown.view.panel() == panel {
+ shown.dirty = true;
}
- ToPlugin::Stop => break,
}
}
- Ok(())
+
+ fn draw_dirty<P: Plugin>(
+ &mut self,
+ plugin: &mut P,
+ out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
+ ) -> io::Result<()> {
+ let views: Vec<u64> = self
+ .views
+ .iter()
+ .filter(|(_, shown)| shown.dirty)
+ .map(|(view, _)| *view)
+ .collect();
+ for view in views {
+ self.draw(plugin, view, out)?;
+ }
+ Ok(())
+ }
+
+ /// Draws `view`, and sends the frame unless it is the one sent last.
+ fn draw<P: Plugin>(
+ &mut self,
+ plugin: &mut P,
+ view: u64,
+ out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
+ ) -> io::Result<()> {
+ let Some(shown) = self.views.get_mut(&view) else {
+ return Ok(());
+ };
+ shown.dirty = false;
+ let mut frame = Frame::default();
+ let drawn = guard(|| {
+ plugin.draw(&shown.view, &mut frame);
+ Ok(())
+ });
+ if let Err(err) = drawn {
+ // What was on show stays.
+ eprintln!("drawing panel {view}: {err:#}");
+ return Ok(());
+ }
+ let frame = Raw::new(&frame);
+ if shown.last.as_ref() == Some(&frame) {
+ return Ok(());
+ }
+ shown.last = Some(frame.clone());
+ out(&FromPlugin::Frame { view, frame })
+ }
}
/// A plugin that panics answers with an error and goes on serving; the
@@ -188,12 +723,14 @@ fn guard<T>(work: impl FnOnce() -> anyhow::Result<T>) -> anyhow::Result<T> {
}
}
+/// Sends the answer and the events after it; true when the panels are to
+/// be drawn again.
fn answer_with(
out: &mut impl FnMut(&FromPlugin) -> io::Result<()>,
id: u64,
answer: anyhow::Result<Value>,
cx: Cx,
-) -> io::Result<()> {
+) -> io::Result<bool> {
let effects = cx.finish();
match answer {
Ok(body) => out(&FromPlugin::Ok {
@@ -209,18 +746,21 @@ fn answer_with(
for body in effects.events {
out(&FromPlugin::Event { body })?;
}
- Ok(())
+ Ok(effects.redraw)
}
#[cfg(test)]
mod tests {
use super::*;
+ use panel::{Click, Hit, List, Text};
use serde_json::json;
- /// Counts calls, and lists as a watcher.
+ /// Counts calls, lists as a watcher, and draws the count in a panel
+ /// with a list of that many rows.
#[derive(Default)]
struct Counter {
calls: u64,
+ closed: Vec<u64>,
}
impl Plugin for Counter {
@@ -229,6 +769,7 @@ mod tests {
Some("add") => {
self.calls += 1;
cx.emit(json!({"event": "changed"}));
+ cx.redraw();
Ok(json!(self.calls))
}
Some("get") => {
@@ -239,19 +780,190 @@ mod tests {
_ => anyhow::bail!("unknown op"),
}
}
+
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ frame.push(Text::new(
+ 0.0,
+ 0.0,
+ view.env.width,
+ 20.0,
+ self.calls.to_string(),
+ ));
+ frame.push(Hit::new("add", 0.0, 0.0, view.env.width, 20.0));
+ let key = self.calls.to_string();
+ frame.push(List::new(
+ "rows",
+ 0.0,
+ 20.0,
+ view.env.width,
+ 100.0,
+ 1000,
+ 20.0,
+ key,
+ ));
+ }
+
+ fn rows(&mut self, _view: &View, wanted: &RowsWanted) -> Vec<Vec<Item>> {
+ (wanted.from..wanted.to + 5)
+ .map(|row| vec![Text::new(0.0, 0.0, 10.0, 20.0, row.to_string()).into()])
+ .collect()
+ }
+
+ fn input(&mut self, _view: &View, input: Input, _cx: &mut Cx) {
+ if matches!(input, Input::Click(Click { id, .. }) if id == "add") {
+ self.calls += 1;
+ }
+ }
+
+ fn closed(&mut self, view: &View) {
+ self.closed.push(view.id);
+ }
}
- fn serve_lines(input: &str) -> Vec<Value> {
- let mut plugin = Counter::default();
- let mut sent = Vec::new();
- serve(&mut plugin, &mut input.as_bytes(), &mut |message| {
- sent.push(serde_json::to_value(message).unwrap());
- Ok(())
+ fn env() -> Value {
+ json!({
+ "width": 300, "height": 500, "scale": 2, "dark": true,
+ "small": {"size": 11, "line": 15},
+ "body": {"size": 13, "line": 18},
+ "title": {"size": 15, "line": 20},
+ "mono": {"size": 12, "line": 17, "advance": 7}
})
- .unwrap();
+ }
+
+ /// Serves `woken` one at a time, each a burst of its own.
+ fn serve_all<P: Plugin>(plugin: &mut P, woken: Vec<Wake>) -> Vec<Value> {
+ serve_bursts(plugin, woken.into_iter().map(|wake| vec![wake]).collect())
+ }
+
+ fn serve_bursts<P: Plugin>(plugin: &mut P, bursts: Vec<Vec<Wake>>) -> Vec<Value> {
+ let mut sent = Vec::new();
+ Runner::new(Arc::default(), Arc::default())
+ .serve(plugin, bursts, &mut |message| {
+ sent.push(serde_json::to_value(message).unwrap());
+ Ok(())
+ })
+ .unwrap();
sent
}
+ fn lines(messages: &[Value]) -> Vec<Wake> {
+ messages
+ .iter()
+ .map(|message| Wake::Line(serde_json::to_vec(message).unwrap()))
+ .collect()
+ }
+
+ fn serve_lines(input: &str) -> Vec<Value> {
+ let woken = input
+ .lines()
+ .map(|line| Wake::Line(line.as_bytes().to_vec()))
+ .collect();
+ serve_all(&mut Counter::default(), woken)
+ }
+
+ #[test]
+ fn an_ask_waits_for_its_own_answer_and_no_longer_than_it_may() {
+ let asking = Arc::new(Asking::default());
+ let ask = Ask::Stat {
+ path: "/home/user/a".into(),
+ };
+ // ThinkTerm answers from the thread reading the input: here, one
+ // that sees what was sent.
+ let (sent, asked) = mpsc::channel();
+ let answering = {
+ let asking = Arc::clone(&asking);
+ std::thread::spawn(move || {
+ let (view, id) = asked.recv().unwrap();
+ asking.answer(id + 1, Answer::failed("not this one"));
+ asking.answer(id, Answer::Stat { entry: None });
+ view
+ })
+ };
+ let answer = asking.ask(3, "m1", &ask, Duration::from_secs(10), |message| {
+ let FromPlugin::Ask {
+ view,
+ id,
+ machine,
+ ask,
+ } = message
+ else {
+ panic!("{message:?}")
+ };
+ assert_eq!(machine, "m1", "names the machine it is for");
+ assert_eq!(
+ ask.read::<Ask>().unwrap(),
+ Ask::Stat {
+ path: "/home/user/a".into()
+ }
+ );
+ sent.send((*view, *id)).unwrap();
+ Ok(())
+ });
+ assert_eq!(answer, Answer::Stat { entry: None });
+ assert_eq!(answering.join().unwrap(), 3, "asked for the panel it names");
+ assert!(asking.waiting().is_empty());
+
+ let late = asking.ask(3, "m1", &ask, Duration::from_millis(20), |_| Ok(()));
+ assert!(
+ matches!(late, Answer::Failed { ref why, .. } if why.contains("did not answer")),
+ "{late:?}"
+ );
+ assert!(asking.waiting().is_empty(), "given up on, and let go");
+ // An answer after that finds nobody, and is dropped.
+ asking.answer(2, Answer::Stat { entry: None });
+ }
+
+ #[test]
+ fn an_answer_among_the_lines_reaches_its_asker_not_the_plugin() {
+ let asking = Arc::new(Asking::default());
+ let (answered, answer) = mpsc::sync_channel(1);
+ asking.waiting().insert(7, answered);
+ let line = json!({"type": "answer", "view": 1, "id": 7, "answer": {"result": "failed", "why": "gone"}});
+ let mut sent = Vec::new();
+ Runner::new(Arc::default(), Arc::clone(&asking))
+ .serve(
+ &mut Counter::default(),
+ vec![lines(&[line])],
+ &mut |message| {
+ sent.push(serde_json::to_value(message).unwrap());
+ Ok(())
+ },
+ )
+ .unwrap();
+ assert_eq!(answer.try_recv().unwrap(), Answer::failed("gone"));
+ assert!(sent.is_empty(), "nothing to say about it: {sent:?}");
+ }
+
+ #[test]
+ fn an_answer_it_cannot_read_still_reaches_its_asker_and_no_call() {
+ let asking = Arc::new(Asking::default());
+ let (answered, answer) = mpsc::sync_channel(1);
+ asking.waiting().insert(1, answered);
+ // A newer ThinkTerm's answer, and a message this SDK does not know
+ // that carries an id: neither is a call to answer with an error.
+ let lines = lines(&[
+ json!({"type": "answer", "view": 1, "id": 1, "answer": {"result": "someday"}}),
+ json!({"type": "someday", "id": 2}),
+ json!({"type": "call", "id": 3, "body": {"op": "get"}, "extra": 1}),
+ ]);
+ let mut sent = Vec::new();
+ Runner::new(Arc::default(), Arc::clone(&asking))
+ .serve(&mut Counter::default(), vec![lines], &mut |message| {
+ sent.push(serde_json::to_value(message).unwrap());
+ Ok(())
+ })
+ .unwrap();
+ let Answer::Failed { why, .. } = answer.try_recv().unwrap() else {
+ panic!("the asker is told")
+ };
+ assert!(why.contains("does not know"), "{why}");
+ assert_eq!(
+ sent,
+ [json!({"type": "ok", "id": 3, "body": 0, "watch": true})],
+ "only the call is answered"
+ );
+ }
+
#[test]
fn calls_are_answered_by_id_with_their_events_after() {
let sent = serve_lines(concat!(
@@ -281,13 +993,219 @@ mod tests {
"{\"type\":\"stop\"}\n",
"{\"type\":\"call\",\"id\":3,\"body\":{\"op\":\"get\"}}\n",
));
- assert_eq!(sent.len(), 2, "{sent:?}");
+ // A kind of message it does not know is let be, id or not: an
+ // error answers a call.
+ assert_eq!(sent.len(), 1, "{sent:?}");
assert_eq!(sent[0]["id"], 1);
assert!(sent[0]["message"]
.as_str()
.unwrap()
.contains("panicked: boom"));
- assert_eq!(sent[1]["type"], "error");
- assert_eq!(sent[1]["id"], 2);
+ }
+
+ #[test]
+ fn a_panel_is_drawn_when_it_opens_after_input_and_when_asked() {
+ let mut plugin = Counter::default();
+ let click = json!({"click": {"id": "add", "x": 1, "y": 1}});
+ let mut woken = lines(&[
+ json!({"type": "open", "view": 7, "env": env()}),
+ json!({"type": "rows", "view": 7, "wanted": {"list": "rows", "key": "0", "from": 0, "to": 3}}),
+ json!({"type": "input", "view": 7, "input": click}),
+ // Drawn the same as before: not sent again.
+ json!({"type": "env", "view": 7, "env": env()}),
+ ]);
+ woken.push(Wake::Redraw);
+ woken.extend(lines(&[
+ json!({"type": "call", "id": 1, "body": {"op": "add"}}),
+ json!({"type": "close", "view": 7}),
+ json!({"type": "input", "view": 7, "input": click}),
+ ]));
+ woken.push(Wake::End(Ok(())));
+ let sent = serve_all(&mut plugin, woken);
+ let kinds: Vec<&str> = sent.iter().map(|m| m["type"].as_str().unwrap()).collect();
+ assert_eq!(
+ kinds,
+ ["frame", "rows", "frame", "ok", "event", "frame"],
+ "{sent:?}"
+ );
+ assert_eq!(sent[0]["view"], 7);
+ assert_eq!(sent[0]["frame"]["items"][0]["text"]["text"], "0");
+ let rows = &sent[1]["rows"];
+ assert_eq!(rows["from"], 0);
+ assert_eq!(
+ rows["rows"].as_array().unwrap().len(),
+ 3,
+ "no more than asked for"
+ );
+ assert_eq!(
+ sent[2]["frame"]["items"][0]["text"]["text"], "1",
+ "the click counted"
+ );
+ assert_eq!(
+ sent[5]["frame"]["items"][0]["text"]["text"], "2",
+ "the call redrew"
+ );
+ assert_eq!(plugin.closed, [7]);
+ assert_eq!(plugin.calls, 2, "no input reaches a closed view");
+ }
+
+ #[test]
+ fn a_burst_is_drawn_once_it_is_through_and_rows_are_answered_at_once() {
+ let mut plugin = Counter::default();
+ let sized = |width: u32| {
+ let mut env = env();
+ env["width"] = json!(width);
+ json!({"type": "env", "view": 7, "env": env})
+ };
+ let wanted =
+ json!({"list": "rows", "key": "0", "version": 3, "layout": 2, "from": 0, "to": 2});
+ let sent = serve_bursts(
+ &mut plugin,
+ vec![
+ lines(&[json!({"type": "open", "view": 7, "env": env()})]),
+ lines(&[
+ sized(310),
+ sized(320),
+ json!({"type": "rows", "view": 7, "wanted": wanted}),
+ sized(330),
+ ]),
+ ],
+ );
+ let kinds: Vec<&str> = sent.iter().map(|m| m["type"].as_str().unwrap()).collect();
+ assert_eq!(kinds, ["frame", "rows", "frame"], "{sent:?}");
+ assert_eq!(
+ sent[2]["frame"]["items"][0]["text"]["w"], 330.0,
+ "drawn for the size it stopped at"
+ );
+ let rows = &sent[1]["rows"];
+ assert_eq!((&rows["version"], &rows["layout"]), (&json!(3), &json!(2)));
+ }
+
+ /// Says in each view which it is and how many clicks it has had, and
+ /// asks for an extended view from its panel.
+ #[derive(Default)]
+ struct Extending {
+ clicks: u32,
+ closed: Vec<u64>,
+ }
+
+ impl Plugin for Extending {
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ let which = match (view.extended(), view.extension) {
+ (true, _) => format!("extends {}", view.panel()),
+ (false, Some(extension)) => format!("extended by {extension}"),
+ (false, None) => "alone".to_string(),
+ };
+ let said = format!("{which}, {} clicks", self.clicks);
+ frame.push(Text::new(0.0, 0.0, 10.0, 10.0, said));
+ frame.extend(!view.extended());
+ }
+
+ fn input(&mut self, _view: &View, _input: Input, _cx: &mut Cx) {
+ self.clicks += 1;
+ }
+
+ fn closed(&mut self, view: &View) {
+ self.closed.push(view.id);
+ }
+ }
+
+ #[test]
+ fn an_extended_view_is_drawn_with_its_panel_and_goes_before_it() {
+ let mut plugin = Extending::default();
+ let click = json!({"click": {"id": "x", "x": 1, "y": 1}});
+ let woken = lines(&[
+ json!({"type": "open", "view": 1, "env": env()}),
+ json!({"type": "open", "view": 2, "env": env(), "extends": 1}),
+ json!({"type": "input", "view": 2, "input": click}),
+ json!({"type": "close", "view": 2}),
+ json!({"type": "open", "view": 3, "env": env(), "extends": 1}),
+ json!({"type": "close", "view": 1}),
+ ]);
+ let sent = serve_all(&mut plugin, woken);
+ let drawn: Vec<(u64, String)> = sent
+ .iter()
+ .map(|message| {
+ let text = &message["frame"]["items"][0]["text"]["text"];
+ (
+ message["view"].as_u64().unwrap(),
+ text.as_str().unwrap().to_string(),
+ )
+ })
+ .collect();
+ let expected = [
+ (1, "alone, 0 clicks"),
+ (1, "extended by 2, 0 clicks"),
+ (2, "extends 1, 0 clicks"),
+ // A click in either is drawn in both.
+ (1, "extended by 2, 1 clicks"),
+ (2, "extends 1, 1 clicks"),
+ (1, "alone, 1 clicks"),
+ (1, "extended by 3, 1 clicks"),
+ (3, "extends 1, 1 clicks"),
+ ];
+ let expected: Vec<(u64, String)> = expected
+ .iter()
+ .map(|(view, text)| (*view, text.to_string()))
+ .collect();
+ assert_eq!(drawn, expected);
+ assert_eq!(sent[0]["frame"]["extend"], true, "a panel asks");
+ assert!(
+ sent[2]["frame"].get("extend").is_none(),
+ "an extended view does not"
+ );
+ assert_eq!(plugin.closed, [2, 3, 1], "the extended view goes first");
+ }
+
+ /// Has rows only for a view it has drawn: what it keeps for one is made
+ /// in `draw`.
+ #[derive(Default)]
+ struct Lazy {
+ drawn: std::collections::HashSet<u64>,
+ }
+
+ impl Plugin for Lazy {
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ self.drawn.insert(view.id);
+ frame.push(List::new("rows", 0.0, 0.0, 100.0, 100.0, 10, 10.0, "k"));
+ }
+
+ fn rows(&mut self, view: &View, wanted: &RowsWanted) -> Vec<Vec<Item>> {
+ if !self.drawn.contains(&view.id) {
+ return Vec::new();
+ }
+ (wanted.from..wanted.to)
+ .map(|_| vec![Text::new(0.0, 0.0, 1.0, 1.0, "row").into()])
+ .collect()
+ }
+ }
+
+ #[test]
+ fn rows_asked_for_before_a_view_is_drawn_come_after_its_first_frame() {
+ let wanted = json!({"list": "rows", "key": "k", "from": 0, "to": 3});
+ let sent = serve_bursts(
+ &mut Lazy::default(),
+ vec![lines(&[
+ json!({"type": "open", "view": 5, "env": env()}),
+ json!({"type": "rows", "view": 5, "wanted": wanted}),
+ ])],
+ );
+ let kinds: Vec<&str> = sent.iter().map(|m| m["type"].as_str().unwrap()).collect();
+ assert_eq!(kinds, ["frame", "rows"], "{sent:?}");
+ assert_eq!(
+ sent[1]["rows"]["rows"].as_array().unwrap().len(),
+ 3,
+ "drawn first, so they are there"
+ );
+ }
+
+ #[test]
+ fn it_says_the_api_of_a_thinkterm_older_than_itself() {
+ assert_eq!(speaking(None), protocol::API);
+ assert_eq!(speaking(Some("1")), 1);
+ assert_eq!(speaking(Some(" 1\n")), 1);
+ assert_eq!(speaking(Some("99")), protocol::API);
+ assert_eq!(speaking(Some("0")), 1);
+ assert_eq!(speaking(Some("two")), protocol::API);
}
}
diff --git a/thinkterm-plugin-sdk/src/protocol.rs b/thinkterm-plugin-sdk/src/protocol.rs
index 59d26195..bb3ae57f 100644
--- a/thinkterm-plugin-sdk/src/protocol.rs
+++ b/thinkterm-plugin-sdk/src/protocol.rs
@@ -3,13 +3,21 @@
//! line of JSON. docs/thinkterm/plugins.md describes it for plugins written
//! in any language.
+use serde::de::Error as _;
use serde::{Deserialize, Serialize};
+use serde_json::value::RawValue;
use serde_json::Value;
+use std::borrow::Cow;
use std::io::{self, BufRead, Read, Write};
+use thinkterm_plugin_channel::wire::Raw;
+use thinkterm_plugin_panel::{Answer, Env, Input, RowsWanted};
/// The version of this protocol: a manifest's `api`, which the program's
-/// `ready` repeats.
-pub const API: u32 = 1;
+/// `ready` repeats. 2 added panels; a program speaking 1 still runs, and
+/// has none.
+pub const API: u32 = 2;
+/// The first version a panel is drawn in.
+pub const PANEL_API: u32 = 2;
/// The longest line either side sends or accepts, so that neither can make
/// the other hold an input without bound. The same as a client's frame.
@@ -25,12 +33,33 @@ pub enum ToPlugin {
#[serde(default)]
body: Value,
},
+ /// A panel of the plugin came on show, as `view`: to be drawn with a
+ /// `frame`. With `extends`, it is the extended view of that panel,
+ /// which asked for one; it is closed before the panel is.
+ Open {
+ view: u64,
+ env: Env,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ extends: Option<u64>,
+ },
+ /// Its size, fonts or theme changed.
+ Env { view: u64, env: Env },
+ /// The user did something in it.
+ Input { view: u64, input: Input },
+ /// Rows of one of its lists: answered with `rows`.
+ Rows { view: u64, wanted: RowsWanted },
+ /// It went off show.
+ Close { view: u64 },
+ /// What came of the plugin's `ask` `id` for panel `view`.
+ Answer { view: u64, id: u64, answer: Answer },
/// Exit now. Standard input closes after it.
Stop,
}
-/// What a plugin sends ThinkTerm.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+/// What a plugin sends ThinkTerm. A panel's frames and rows are carried
+/// as they were written, unread, for ThinkTerm passes them on to the
+/// client showing the panel: read a line with [`FromPlugin::read`].
+#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FromPlugin {
/// The first line: the program is ready, and speaks this protocol.
@@ -53,6 +82,93 @@ pub enum FromPlugin {
Event {
body: Value,
},
+ /// Panel `view` drawn anew: a `Frame`.
+ Frame {
+ view: u64,
+ frame: Raw,
+ },
+ /// Rows panel `view` asked for: a `Rows`.
+ Rows {
+ view: u64,
+ rows: Raw,
+ },
+ /// Something for ThinkTerm to do on `machine`, the one the terminal
+ /// beside panel `view` runs on (`Env::remote`): an `Ask`, answered
+ /// with an `answer` of the same `id`, which the plugin picks. Done only
+ /// while the terminal is still on that machine.
+ Ask {
+ view: u64,
+ id: u64,
+ machine: String,
+ ask: Raw,
+ },
+}
+
+/// The kinds of message a plugin sends, for the error naming them.
+const KINDS: &[&str] = &["ready", "ok", "error", "event", "frame", "rows", "ask"];
+
+impl FromPlugin {
+ /// Reads one line from a plugin, going over it once: a panel's frame,
+ /// rows or ask is kept as it was written, for ThinkTerm passes those on
+ /// unread, and a payload kept unread cannot be read through a tag.
+ pub fn read(line: &[u8]) -> serde_json::Result<Self> {
+ #[derive(Deserialize)]
+ struct Line<'a> {
+ #[serde(rename = "type", borrow)]
+ kind: Cow<'a, str>,
+ api: Option<u32>,
+ id: Option<u64>,
+ body: Option<Value>,
+ #[serde(default)]
+ watch: bool,
+ message: Option<String>,
+ view: Option<u64>,
+ #[serde(borrow)]
+ machine: Option<Cow<'a, str>>,
+ #[serde(borrow)]
+ frame: Option<&'a RawValue>,
+ #[serde(borrow)]
+ rows: Option<&'a RawValue>,
+ #[serde(borrow)]
+ ask: Option<&'a RawValue>,
+ }
+ fn given<T>(field: Option<T>, name: &'static str) -> serde_json::Result<T> {
+ field.ok_or_else(|| serde_json::Error::missing_field(name))
+ }
+ let line: Line = serde_json::from_slice(line)?;
+ Ok(match &*line.kind {
+ "ready" => Self::Ready {
+ api: given(line.api, "api")?,
+ },
+ "ok" => Self::Ok {
+ id: given(line.id, "id")?,
+ body: line.body.unwrap_or_default(),
+ watch: line.watch,
+ },
+ "error" => Self::Error {
+ id: given(line.id, "id")?,
+ message: given(line.message, "message")?,
+ },
+ "event" => Self::Event {
+ body: line.body.unwrap_or_default(),
+ },
+ "frame" => Self::Frame {
+ view: given(line.view, "view")?,
+ frame: Raw::copy_of(given(line.frame, "frame")?),
+ },
+ "rows" => Self::Rows {
+ view: given(line.view, "view")?,
+ rows: Raw::copy_of(given(line.rows, "rows")?),
+ },
+ "ask" => Self::Ask {
+ view: given(line.view, "view")?,
+ id: given(line.id, "id")?,
+ machine: given(line.machine, "machine")?.into_owned(),
+ ask: Raw::copy_of(given(line.ask, "ask")?),
+ },
+ other => return Err(serde_json::Error::unknown_variant(other, KINDS)),
+ })
+ }
}
/// Writes `message` as one line, in a single write, so lines written from
@@ -92,11 +208,15 @@ mod tests {
use super::*;
use serde_json::{json, to_value};
+ fn read(value: Value) -> serde_json::Result<FromPlugin> {
+ FromPlugin::read(&serde_json::to_vec(&value).unwrap())
+ }
+
#[test]
fn messages_are_json_tagged_by_type() {
assert_eq!(
to_value(FromPlugin::Ready { api: API }).unwrap(),
- json!({"type": "ready", "api": 1})
+ json!({"type": "ready", "api": 2})
);
assert_eq!(
to_value(FromPlugin::Ok {
@@ -107,7 +227,7 @@ mod tests {
.unwrap(),
json!({"type": "ok", "id": 1, "body": "hi"})
);
- let ok: FromPlugin = serde_json::from_value(json!({"type": "ok", "id": 2})).unwrap();
+ let ok = read(json!({"type": "ok", "id": 2})).unwrap();
assert_eq!(
ok,
FromPlugin::Ok {
@@ -128,9 +248,104 @@ mod tests {
);
assert_eq!(to_value(ToPlugin::Stop).unwrap(), json!({"type": "stop"}));
// What a plugin can no longer send is not a message.
+ assert!(read(json!({"type": "notify", "title": "x"})).is_err());
+ }
+
+ #[test]
+ fn a_frame_is_read_without_reading_what_it_draws() {
+ let line = br#"{"type":"frame","view":4,"frame":{"items":[{"rect": {"x":0}}]}}"#;
+ let FromPlugin::Frame { view, frame } = FromPlugin::read(line).unwrap() else {
+ panic!()
+ };
+ assert_eq!(view, 4);
+ assert_eq!(frame.get(), r#"{"items":[{"rect": {"x":0}}]}"#);
+ let mut wire = Vec::new();
+ write_message(&mut wire, &FromPlugin::Frame { view, frame }).unwrap();
+ assert_eq!(wire, [&line[..], b"\n"].concat(), "written as it came");
+
+ let rows = FromPlugin::read(br#"{"view":1,"rows":[],"type":"rows"}"#).unwrap();
+ assert!(matches!(rows, FromPlugin::Rows { view: 1, .. }), "{rows:?}");
+ assert!(FromPlugin::read(br#"{"type":"frame","view":1}"#).is_err());
+ assert!(
+ FromPlugin::read(br#"{"type":"error","id":1}"#).is_err(),
+ "no message"
+ );
+
+ let asked = br#"{"type":"ask","view":2,"id":5,"machine":"m1","ask":{"op":"read","path":"/a b","limit":9}}"#;
+ let FromPlugin::Ask {
+ view,
+ id,
+ machine,
+ ask,
+ } = FromPlugin::read(asked).unwrap()
+ else {
+ panic!()
+ };
+ assert_eq!((view, id, machine.as_str()), (2, 5, "m1"));
+ assert_eq!(
+ ask.get(),
+ r#"{"op":"read","path":"/a b","limit":9}"#,
+ "unread"
+ );
+ let mut wire = Vec::new();
+ write_message(
+ &mut wire,
+ &FromPlugin::Ask {
+ view,
+ id,
+ machine,
+ ask,
+ },
+ )
+ .unwrap();
+ assert_eq!(wire, [&asked[..], b"\n"].concat());
assert!(
- serde_json::from_value::<FromPlugin>(json!({"type": "notify", "title": "x"})).is_err()
+ FromPlugin::read(br#"{"type":"ask","view":2,"id":5,"ask":{"op":"stat","path":"/"}}"#)
+ .is_err(),
+ "an ask names the machine it is for"
);
+
+ let answer: ToPlugin = serde_json::from_value(json!({
+ "type": "answer", "view": 2, "id": 5,
+ "answer": {"result": "read", "bytes": "aGk=", "cut": false}
+ }))
+ .unwrap();
+ let ToPlugin::Answer {
+ answer: thinkterm_plugin_panel::Answer::Read { bytes, cut: false },
+ ..
+ } = answer
+ else {
+ panic!("{answer:?}")
+ };
+ assert_eq!(bytes.0, b"hi");
+
+ let open: ToPlugin = serde_json::from_value(json!({
+ "type": "open",
+ "view": 2,
+ "env": {
+ "width": 300, "height": 500, "scale": 2, "dark": true,
+ "small": {"size": 11, "line": 15},
+ "body": {"size": 13, "line": 18},
+ "title": {"size": 15, "line": 20},
+ "mono": {"size": 12, "line": 17, "advance": 7.2}
+ }
+ }))
+ .unwrap();
+ let ToPlugin::Open {
+ view: 2,
+ env,
+ extends: None,
+ } = open
+ else {
+ panic!("{open:?}")
+ };
+ assert_eq!(env.mono.advance, 7.2);
+ let extended = ToPlugin::Open {
+ view: 3,
+ env,
+ extends: Some(2),
+ };
+ assert_eq!(to_value(&extended).unwrap()["extends"], 2);
}
#[test]
@@ -142,7 +357,7 @@ mod tests {
let mut from = wire.as_slice();
let mut line = Vec::new();
assert!(read_line(&mut from, &mut line).unwrap());
- assert_eq!(line, br#"{"type":"ready","api":1}"#);
+ assert_eq!(line, br#"{"type":"ready","api":2}"#);
assert!(read_line(&mut from, &mut line).unwrap());
assert_eq!(line, br#"{"type":"stop"}"#);
assert!(read_line(&mut from, &mut line).unwrap());
diff --git a/thinkterm-plugin-server/src/host.rs b/thinkterm-plugin-server/src/host.rs
index 4aea28e6..9fcb0f8e 100644
--- a/thinkterm-plugin-server/src/host.rs
+++ b/thinkterm-plugin-server/src/host.rs
@@ -10,19 +10,38 @@
//! plugin holds up its own callers and nobody else. Calls addressed to
//! [`api::PLUGIN`] are the host's own: the list of plugins, their switches,
//! and reloading them.
+//!
+//! A panel a client shows is a view here, numbered for the plugin, routed
+//! to the client that opened it and closed when either side goes. Its
+//! frames go one at a time: while the client has not taken in the last,
+//! only the newest is kept back. A panel's extended view is a view of its
+//! own, linked to the panel's, and closed before it whenever it closes.
+//! What a plugin asks of the other machine a panel's terminal runs on goes
+//! to that panel's client, and the answer back; a panel that closes first
+//! leaves its plugin told that none is coming.
+//!
+//! Whether a plugin is used -- a panel on show, a client watching it, a
+//! call waiting -- is looked at after everything handled here, and a timer
+//! stops the programs gone unused for long enough ([`Registry::tidy`]).
+//! Clients that are ThinkTerm running on this machine say so (`keep`):
+//! while one is connected, the plugins that run always do.
-use crate::process::{Listener, Waiter};
-use crate::registry::{Fallout, Lookup, Message, Registry};
+use crate::process::{Listener, Waiter, STACK};
+use crate::registry::{Fallout, Lookup, Message, Refusal, Registry};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::net::Shutdown;
use std::path::PathBuf;
use std::sync::mpsc::{sync_channel, SyncSender, TrySendError};
-use std::sync::{Arc, Mutex, MutexGuard, Weak};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, Weak};
use std::time::{Duration, Instant};
use thinkterm_plugin_channel::registry as api;
-use thinkterm_plugin_channel::wire::{read_frame, write_frame, FromHost, ToHost, PROTOCOL};
+use thinkterm_plugin_channel::wire::{
+ frame_header, read_frame, write_frame, FromHost, PanelEvent, PanelRequest, Raw, ToHost,
+ PROTOCOL,
+};
+use thinkterm_plugin_sdk::panel::{Answer, Env, Input, RowsWanted};
use thinkterm_plugin_sdk::protocol::{FromPlugin, ToPlugin};
use thinkterm_plugin_sdk::Cx;
use wezterm_uds::UnixStream;
@@ -30,9 +49,9 @@ use wezterm_uds::UnixStream;
/// Frames that may wait for one client. A client this far behind is not
/// reading, and is disconnected.
const QUEUE: usize = 256;
-/// The threads here parse JSON and move bytes; a host with two clients has
-/// no use for megabytes of stack each.
-const STACK: usize = 256 * 1024;
+/// What one panel's plugin may have asked of its client and not heard back
+/// about. A plugin this far ahead is not waiting for its answers.
+const ASKS: usize = 64;
struct Client {
outbox: SyncSender<Vec<u8>>,
@@ -42,17 +61,49 @@ struct Client {
watching: HashSet<String>,
}
+/// A panel a client shows, by the number its plugin knows it by.
+struct Route {
+ client: u64,
+ /// The client's own number for it.
+ view: u64,
+ plugin: String,
+ /// The plugin's run it is open on.
+ generation: u64,
+ /// For an extended view, the number of the panel it extends.
+ extends: Option<u64>,
+ /// A frame is with the client, and it has not said it took it in.
+ in_flight: bool,
+ /// The newest frame drawn meanwhile.
+ held: Option<Raw>,
+ /// Pages of rows asked for and not answered: rows beyond these are
+ /// not the client's to be sent.
+ asked: u32,
+ /// The client said the panel's terminal runs on another machine
+ /// (`Env::remote`), which the plugin may ask things of.
+ remote: bool,
+ /// What the plugin asked of it that the client has not answered.
+ asks: HashSet<u64>,
+}
+
struct State {
registry: Registry,
clients: HashMap<u64, Client>,
next_client: u64,
+ views: HashMap<u64, Route>,
+ next_view: u64,
/// When the last client left, or the host started; `None` while anyone
/// is connected.
idle_since: Option<Instant>,
+ /// The clients that are ThinkTerm running on this machine.
+ keepers: HashSet<u64>,
+ /// When a program is next due to be stopped or started.
+ next_tidy: Option<Instant>,
}
pub struct Host {
state: Mutex<State>,
+ /// Wakes the timer when what it waits for changed.
+ wake: Condvar,
socket: PathBuf,
idle: Duration,
/// Itself, for what it starts from a program's threads to report to.
@@ -70,6 +121,8 @@ struct Out {
changed: bool,
/// Not told of the change: it asked for the list, and has it.
fresh: Option<u64>,
+ /// About panels, each for the client showing it.
+ panels: Vec<(u64, Vec<u8>)>,
}
impl Out {
@@ -87,6 +140,26 @@ impl Out {
}
self.changed |= fallout.changed;
}
+
+ /// False when `event` is too long for a frame: a plugin's line as long
+ /// as it may be is, with the view's number around it. It is dropped,
+ /// since sending it would cost the client its connection.
+ fn panel(&mut self, client: u64, view: u64, event: PanelEvent) -> bool {
+ let frame = FromHost::Panel { view, event }.encode();
+ if frame_header(frame.len()).is_none() {
+ log::warn!(
+ "dropped {} bytes drawn for a panel of client {client}: too long to send",
+ frame.len()
+ );
+ return false;
+ }
+ self.panels.push((client, frame));
+ true
+ }
+
+ fn closed(&mut self, client: u64, view: u64, reason: String, again: bool) {
+ self.panel(client, view, PanelEvent::Closed { reason, again });
+ }
}
impl Host {
@@ -96,8 +169,13 @@ impl Host {
registry,
clients: HashMap::new(),
next_client: 1,
+ views: HashMap::new(),
+ next_view: 0,
idle_since: Some(Instant::now()),
+ keepers: HashSet::new(),
+ next_tidy: None,
}),
+ wake: Condvar::new(),
socket,
idle,
me: me.clone(),
@@ -182,6 +260,7 @@ impl Host {
};
match ToHost::decode(&frame) {
Ok(ToHost::Call { id, plugin, body }) => self.call(client, id, &plugin, body),
+ Ok(ToHost::Panel { view, request }) => self.panel(client, view, request),
Ok(ToHost::Quit) => {
log::info!("asked to quit by a newer build");
// Once any call in progress has finished.
@@ -203,7 +282,7 @@ impl Host {
} else {
self.ask(&mut state, client, id, plugin, body, &mut out);
}
- send(&mut state, out);
+ self.send(&mut state, out);
}
/// A call to the host itself.
@@ -238,6 +317,22 @@ impl Host {
.registry
.set_enabled(&plugin, enabled, &mut fallout)
.map(|()| Value::Null),
+ api::Request::SetBackground {
+ id: plugin,
+ background,
+ } => state
+ .registry
+ .set_background(&plugin, background, &mut fallout)
+ .map(|()| Value::Null),
+ api::Request::Keep => {
+ // A keeper asks again when a plugin is installed that says
+ // it runs always: looked for, it is marked and started.
+ if state.keepers.insert(client) {
+ log::info!("client {client} is ThinkTerm running on this machine");
+ }
+ state.registry.scan(&mut fallout);
+ Ok(Value::Null)
+ }
api::Request::Reload { id: plugin } => state
.registry
.reload(plugin.as_deref(), &mut fallout)
@@ -307,38 +402,291 @@ impl Host {
}
}
+ /// Something about the client's panel `view`.
+ fn panel(self: &Arc<Self>, client: u64, view: u64, request: PanelRequest) {
+ let mut state = self.state();
+ let mut out = Out::default();
+ let mut fallout = Fallout::default();
+ if let PanelRequest::Open {
+ plugin,
+ env,
+ extends,
+ } = request
+ {
+ self.open_panel(&mut state, client, view, plugin, env, extends, &mut out);
+ return self.send(&mut state, out);
+ }
+ let Some(number) = route_of(&state.views, client, view) else {
+ // Closed already: the client hears so, or has.
+ return;
+ };
+ // As a plugin's drawing is, in `said`.
+ let drawing = matches!(request, PanelRequest::Shown | PanelRequest::Rows { .. });
+ let route = state.views.get_mut(&number).expect("just found");
+ let told = match request {
+ PanelRequest::Open { .. } => unreachable!("handled above"),
+ PanelRequest::Env { env } => match env.read::<Env>() {
+ Ok(env) => {
+ route.remote = env.remote.is_some();
+ Some(Told::Message(ToPlugin::Env { view: number, env }))
+ }
+ Err(err) => {
+ log::warn!("client {client} sent a panel size that does not read: {err}");
+ None
+ }
+ },
+ PanelRequest::Input { input } => match input.read::<Input>() {
+ Ok(input) => Some(Told::Message(ToPlugin::Input {
+ view: number,
+ input,
+ })),
+ Err(err) => {
+ log::warn!("client {client} sent input that does not read: {err}");
+ None
+ }
+ },
+ PanelRequest::Rows { wanted } => match wanted.read::<RowsWanted>() {
+ Ok(wanted) => {
+ route.asked += 1;
+ Some(Told::Message(ToPlugin::Rows {
+ view: number,
+ wanted,
+ }))
+ }
+ Err(err) => {
+ log::warn!("client {client} asked for rows in a way that does not read: {err}");
+ None
+ }
+ },
+ PanelRequest::Shown => {
+ route.in_flight = match route.held.take() {
+ Some(frame) => out.panel(client, view, PanelEvent::Frame { frame }),
+ None => false,
+ };
+ None
+ }
+ PanelRequest::Close => {
+ self.close_view(&mut state, number, &mut fallout, &mut out);
+ None
+ }
+ // One the plugin stopped waiting for, or never asked, goes no
+ // further.
+ PanelRequest::Answer { id, answer } => route
+ .asks
+ .remove(&id)
+ .then(|| Told::Line(answer_line(number, id, &answer))),
+ };
+ if let Some(told) = told {
+ let route = &state.views[&number];
+ let (plugin, generation) = (route.plugin.clone(), route.generation);
+ match told {
+ Told::Message(message) => {
+ state
+ .registry
+ .tell(&plugin, generation, &message, &mut fallout);
+ }
+ Told::Line(line) => {
+ state
+ .registry
+ .tell_line(&plugin, generation, line, &mut fallout);
+ }
+ }
+ }
+ out.fallout(fallout);
+ if drawing {
+ deliver_out(&mut state, out);
+ } else {
+ self.send(&mut state, out);
+ }
+ }
+
+ /// Opens plugin `plugin`'s panel as the client's `view`, replacing any
+ /// it had under that number: the extended view of the client's panel
+ /// `extends`, with one.
+ #[allow(clippy::too_many_arguments)]
+ fn open_panel(
+ self: &Arc<Self>,
+ state: &mut State,
+ client: u64,
+ view: u64,
+ plugin: String,
+ env: Raw,
+ extends: Option<u64>,
+ out: &mut Out,
+ ) {
+ let mut fallout = Fallout::default();
+ if let Some(number) = route_of(&state.views, client, view) {
+ self.close_view(state, number, &mut fallout, out);
+ }
+ let env = match env.read::<Env>() {
+ Ok(env) => env,
+ Err(err) => {
+ out.fallout(fallout);
+ return out.closed(client, view, format!("not a panel's size: {err}"), false);
+ }
+ };
+ let remote = env.remote.is_some();
+ // What an extended view extends is a panel of the same plugin that
+ // the client shows, and not an extended view itself.
+ let extends = match extends {
+ None => None,
+ Some(panel) => {
+ let found = route_of(&state.views, client, panel).filter(|number| {
+ let route = &state.views[number];
+ route.plugin == plugin && route.extends.is_none()
+ });
+ let Some(found) = found else {
+ out.fallout(fallout);
+ let why = format!("the client shows no panel {panel} of {plugin} to extend");
+ return out.closed(client, view, why, false);
+ };
+ // A panel has one extended view: a new one replaces it.
+ self.close_extension(state, found, "another took its place", &mut fallout, out);
+ Some(found)
+ }
+ };
+ let index = match state.registry.find(&plugin, &mut fallout) {
+ Lookup::Installed(index) => Some(index),
+ Lookup::Builtin(_) | Lookup::Missing => None,
+ };
+ state.next_view += 1;
+ let number = state.next_view;
+ let opened = match index {
+ Some(index) => {
+ let listener: Arc<dyn Listener> = Arc::clone(self) as Arc<dyn Listener>;
+ let message = ToPlugin::Open {
+ view: number,
+ env,
+ extends,
+ };
+ state
+ .registry
+ .open_panel(&plugin, index, &message, &listener, &mut fallout)
+ }
+ None => Err(Refusal {
+ reason: format!("there is no plugin named {plugin:?} with a panel"),
+ again: false,
+ }),
+ };
+ out.fallout(fallout);
+ match opened {
+ Ok(generation) => {
+ let route = Route {
+ client,
+ view,
+ plugin,
+ generation,
+ extends,
+ in_flight: false,
+ held: None,
+ asked: 0,
+ remote,
+ asks: HashSet::new(),
+ };
+ state.views.insert(number, route);
+ }
+ Err(Refusal { reason, again }) => out.closed(client, view, reason, again),
+ }
+ }
+
+ /// Lets go of the view numbered `number`, telling its plugin, and of
+ /// its extended view before it, telling the client as well.
+ fn close_view(&self, state: &mut State, number: u64, fallout: &mut Fallout, out: &mut Out) {
+ self.close_extension(state, number, "its panel closed", fallout, out);
+ if let Some(route) = state.views.remove(&number) {
+ unanswered(state, number, &route, fallout);
+ let message = ToPlugin::Close { view: number };
+ state
+ .registry
+ .tell(&route.plugin, route.generation, &message, fallout);
+ }
+ }
+
+ /// Lets go of the extended view of the panel numbered `panel`, if it has
+ /// one, telling its plugin and its client why.
+ fn close_extension(
+ &self,
+ state: &mut State,
+ panel: u64,
+ why: &str,
+ fallout: &mut Fallout,
+ out: &mut Out,
+ ) {
+ let extensions: Vec<u64> = state
+ .views
+ .iter()
+ .filter(|(_, route)| route.extends == Some(panel))
+ .map(|(extension, _)| *extension)
+ .collect();
+ for extension in extensions {
+ if let Some(route) = state.views.remove(&extension) {
+ unanswered(state, extension, &route, fallout);
+ let message = ToPlugin::Close { view: extension };
+ state
+ .registry
+ .tell(&route.plugin, route.generation, &message, fallout);
+ out.closed(route.client, route.view, why.into(), false);
+ }
+ }
+ }
+
fn leave(&self, client: u64) {
let mut state = self.state();
state.clients.remove(&client);
+ state.keepers.remove(&client);
// Nobody is left to answer: its calls free the plugins' slots.
state.registry.forget_client(client);
+ let views: Vec<u64> = state
+ .views
+ .iter()
+ .filter(|(_, route)| route.client == client)
+ .map(|(number, _)| *number)
+ .collect();
+ let mut fallout = Fallout::default();
+ let mut out = Out::default();
+ for number in views {
+ self.close_view(&mut state, number, &mut fallout, &mut out);
+ }
+ out.fallout(fallout);
+ self.send(&mut state, out);
if state.clients.is_empty() {
state.idle_since.get_or_insert_with(Instant::now);
}
}
- /// Exits once nobody has been connected for the idle time.
+ /// Stops the programs gone unused as they come due, and exits once
+ /// nobody has been connected for the idle time.
pub fn exit_when_idle(self: &Arc<Self>) {
let host = Arc::clone(self);
let reaper = std::thread::Builder::new()
.name("idle".into())
.stack_size(STACK)
- .spawn(move || loop {
- let wait = {
- // Decided with the table locked, so a client being
- // accepted either registers first or finds the socket
- // gone and starts a new host.
- let state = host.state();
- match state.idle_since {
- Some(since) if since.elapsed() >= host.idle => {
+ .spawn(move || {
+ // Decided with the table locked, so a client being accepted
+ // either registers first or finds the socket gone and starts
+ // a new host.
+ let mut state = host.state();
+ loop {
+ let now = Instant::now();
+ let idle_left = match state.idle_since {
+ Some(since) if now.saturating_duration_since(since) >= host.idle => {
log::info!("nobody connected for {:?}; exiting", host.idle);
host.exit(state);
}
- Some(since) => host.idle - since.elapsed(),
+ Some(since) => host.idle - now.saturating_duration_since(since),
None => host.idle,
+ };
+ if state.next_tidy.is_some_and(|due| due <= now) {
+ host.send(&mut state, Out::default());
}
- };
- std::thread::sleep(wait);
+ let wait = state.next_tidy.map_or(idle_left, |due| {
+ idle_left.min(due.saturating_duration_since(Instant::now()))
+ });
+ state = match host.wake.wait_timeout(state, wait) {
+ Ok((state, _)) => state,
+ Err(poisoned) => poisoned.into_inner().0,
+ };
+ }
});
if let Err(err) = reaper {
log::warn!("cannot watch for idleness, so this host stays up: {err}");
@@ -362,6 +710,9 @@ impl Listener for Host {
let mut out = Out::default();
let mut fallout = Fallout::default();
let running = state.registry.process(plugin, generation).is_some();
+ // A panel's drawing comes many times a second, and changes nothing
+ // about which plugins are used: it is sent on without a tidy.
+ let drawing = matches!(message, FromPlugin::Frame { .. } | FromPlugin::Rows { .. });
match message {
FromPlugin::Ready { api } => {
state.registry.ready(plugin, generation, api, &mut fallout)
@@ -389,9 +740,69 @@ impl Listener for Host {
}
FromPlugin::Event { body } if running => out.events.push((plugin.to_string(), body)),
FromPlugin::Event { .. } => {}
+ FromPlugin::Frame { view, frame } => {
+ if let Some(route) = routed(&mut state.views, view, plugin, generation) {
+ if route.in_flight {
+ route.held = Some(frame);
+ } else {
+ let (client, view) = (route.client, route.view);
+ route.in_flight = out.panel(client, view, PanelEvent::Frame { frame });
+ }
+ }
+ }
+ FromPlugin::Rows { view, rows } => {
+ if let Some(route) = routed(&mut state.views, view, plugin, generation) {
+ if route.asked > 0 {
+ route.asked -= 1;
+ let (client, view) = (route.client, route.view);
+ out.panel(client, view, PanelEvent::Rows { rows });
+ }
+ }
+ }
+ FromPlugin::Ask {
+ view,
+ id,
+ machine,
+ ask,
+ } => {
+ let refused = match routed(&mut state.views, view, plugin, generation) {
+ None => Some("the panel is closed"),
+ Some(route) if !route.remote => {
+ Some("the panel's terminal runs on this machine, which the plugin reaches itself")
+ }
+ Some(route) if route.asks.len() >= ASKS => {
+ Some("it asked too much at once")
+ }
+ Some(route) => {
+ route.asks.insert(id);
+ let (client, client_view) = (route.client, route.view);
+ let event = PanelEvent::Remote { id, machine, ask };
+ if out.panel(client, client_view, event) {
+ None
+ } else {
+ route.asks.remove(&id);
+ Some("what it asked is too long to send")
+ }
+ }
+ };
+ if let Some(why) = refused {
+ let message = ToPlugin::Answer {
+ view,
+ id,
+ answer: Answer::failed(why),
+ };
+ state
+ .registry
+ .tell(plugin, generation, &message, &mut fallout);
+ }
+ }
}
out.fallout(fallout);
- send(&mut state, out);
+ if drawing {
+ deliver_out(&mut state, out);
+ } else {
+ self.send(&mut state, out);
+ }
}
fn ended(&self, plugin: &str, generation: u64, why: String) {
@@ -400,12 +811,25 @@ impl Listener for Host {
};
let mut state = self.state();
let mut fallout = Fallout::default();
+ let mut out = Out::default();
+ // Its panels close with it; opened again, they start the plugin
+ // anew, or hear why it cannot be.
+ let ended: Vec<u64> = state
+ .views
+ .iter()
+ .filter(|(_, route)| route.plugin == plugin && route.generation == generation)
+ .map(|(number, _)| *number)
+ .collect();
+ for number in ended {
+ if let Some(route) = state.views.remove(&number) {
+ out.closed(route.client, route.view, why.clone(), true);
+ }
+ }
state
.registry
.ended(plugin, generation, why, &listener, &mut fallout);
- let mut out = Out::default();
out.fallout(fallout);
- send(&mut state, out);
+ self.send(&mut state, out);
}
fn late(&self, plugin: &str, generation: u64) {
@@ -414,12 +838,93 @@ impl Listener for Host {
state.registry.late(plugin, generation, &mut fallout);
let mut out = Out::default();
out.fallout(fallout);
- send(&mut state, out);
+ self.send(&mut state, out);
+ }
+}
+
+/// What a client said about a panel that goes on to its plugin.
+enum Told {
+ Message(ToPlugin),
+ /// Written out already: an answer, carried as the client wrote it.
+ Line(Vec<u8>),
+}
+
+/// The line telling a plugin what came of what it asked, `id`, of panel
+/// `view`: the client's `Answer`, unread, on one line as a message must be.
+fn answer_line(view: u64, id: u64, answer: &Raw) -> Vec<u8> {
+ let answer = answer.get();
+ let answer = if answer.contains('\n') {
+ serde_json::from_str::<Value>(answer)
+ .map(|answer| answer.to_string())
+ .unwrap_or_else(|_| "null".into())
+ } else {
+ answer.to_string()
+ };
+ format!("{{\"type\":\"answer\",\"view\":{view},\"id\":{id},\"answer\":{answer}}}\n")
+ .into_bytes()
+}
+
+/// Tells the plugin of the panel numbered `number`, `route`, gone, that
+/// what it asked of the panel's client will not be answered.
+fn unanswered(state: &mut State, number: u64, route: &Route, fallout: &mut Fallout) {
+ for id in &route.asks {
+ let message = ToPlugin::Answer {
+ view: number,
+ id: *id,
+ answer: Answer::failed("the panel closed"),
+ };
+ state
+ .registry
+ .tell(&route.plugin, route.generation, &message, fallout);
+ }
+}
+
+impl Host {
+ /// Sends what `out` holds, once the plugins' programs are stopped or
+ /// started as how they are used now says.
+ fn send(&self, state: &mut State, mut out: Out) {
+ self.tidy(state, &mut out);
+ deliver_out(state, out);
+ }
+
+ /// Stops the programs gone unused for long enough and starts the ones
+ /// that run always, and has the timer wait for the next one due.
+ fn tidy(&self, state: &mut State, out: &mut Out) {
+ let Some(listener) = self.listener() else {
+ return;
+ };
+ let mut fallout = Fallout::default();
+ let State {
+ registry,
+ clients,
+ views,
+ keepers,
+ next_tidy,
+ ..
+ } = state;
+ let used = |plugin: &str| {
+ views.values().any(|route| route.plugin == plugin)
+ || clients
+ .values()
+ .any(|client| client.watching.contains(plugin))
+ };
+ let next = registry.tidy(
+ Instant::now(),
+ !keepers.is_empty(),
+ used,
+ &listener,
+ &mut fallout,
+ );
+ out.fallout(fallout);
+ if next != *next_tidy {
+ *next_tidy = next;
+ self.wake.notify_all();
+ }
}
}
/// Sends what `out` holds.
-fn send(state: &mut State, out: Out) {
+fn deliver_out(state: &mut State, out: Out) {
for (client, plugin) in out.watch {
if let Some(watcher) = state.clients.get_mut(&client) {
watcher.watching.insert(plugin);
@@ -428,6 +933,9 @@ fn send(state: &mut State, out: Out) {
for (client, frame) in out.answers {
deliver(&mut state.clients, client, frame);
}
+ for (client, frame) in out.panels {
+ deliver(&mut state.clients, client, frame);
+ }
for (plugin, body) in out.events {
let frame = FromHost::Event {
plugin: plugin.clone(),
@@ -445,6 +953,27 @@ fn send(state: &mut State, out: Out) {
}
}
+/// The number of the client's panel `view`.
+fn route_of(views: &HashMap<u64, Route>, client: u64, view: u64) -> Option<u64> {
+ views
+ .iter()
+ .find(|(_, route)| route.client == client && route.view == view)
+ .map(|(number, _)| *number)
+}
+
+/// The view numbered `view`, if it is open on this run of `plugin`: what an
+/// earlier run drew is not the panel's any more.
+fn routed<'a>(
+ views: &'a mut HashMap<u64, Route>,
+ view: u64,
+ plugin: &str,
+ generation: u64,
+) -> Option<&'a mut Route> {
+ views
+ .get_mut(&view)
+ .filter(|route| route.plugin == plugin && route.generation == generation)
+}
+
fn registry_event(event: &api::Event) -> Vec<u8> {
FromHost::Event {
plugin: api::PLUGIN.to_string(),
diff --git a/thinkterm-plugin-server/src/main.rs b/thinkterm-plugin-server/src/main.rs
index c4a9b85b..cd988ba9 100644
--- a/thinkterm-plugin-server/src/main.rs
+++ b/thinkterm-plugin-server/src/main.rs
@@ -7,7 +7,9 @@
//!
//! The plugins built into it run inside it. An installed plugin runs as a
//! program of its own, which the host starts when the plugin is first used
-//! and stops when it exits (see registry and docs/thinkterm/plugins.md).
+//! -- or at once, for one that runs always while ThinkTerm keeps the host --
+//! and stops once it has gone unused for long enough, or when the host
+//! exits (see registry and docs/thinkterm/plugins.md).
// Started in the background, never from a console: no window of its own.
#![cfg_attr(windows, windows_subsystem = "windows")]
@@ -43,6 +45,8 @@ struct Args {
data_dir: PathBuf,
idle: Duration,
ready_within: Duration,
+ /// How long programs run unused; a test's are shorter.
+ limits: registry::Limits,
/// Serve this built-in plugin over standard input and output, as an
/// installed plugin's program does, instead of being the host.
serve_plugin: Option<String>,
@@ -55,6 +59,7 @@ fn parse_args() -> Result<Args, String> {
data_dir: paths::data_dir(),
idle: IDLE_EXIT,
ready_within: READY_WITHIN,
+ limits: registry::Limits::default(),
serve_plugin: None,
};
let seconds = |name: &str, value: &std::ffi::OsStr| {
@@ -76,6 +81,9 @@ fn parse_args() -> Result<Args, String> {
"--data-dir" => args.data_dir = value.into(),
"--idle-secs" => args.idle = seconds(&name, &value)?,
"--ready-secs" => args.ready_within = seconds(&name, &value)?,
+ "--briefly-secs" => args.limits.briefly = seconds(&name, &value)?,
+ "--never-secs" => args.limits.never = seconds(&name, &value)?,
+ "--pending-secs" => args.limits.pending = seconds(&name, &value)?,
"--serve-plugin" => args.serve_plugin = Some(value.to_string_lossy().into_owned()),
_ => return Err(format!("unknown argument {name}")),
}
@@ -161,6 +169,7 @@ fn run(args: Args) -> anyhow::Result<()> {
&args.data_dir,
builtins::all(&args.data_dir),
args.ready_within,
+ args.limits,
);
let host = host::Host::new(args.socket, args.idle, registry);
host.exit_when_idle();
diff --git a/thinkterm-plugin-server/src/manifest.rs b/thinkterm-plugin-server/src/manifest.rs
index 5f428a6d..94e65342 100644
--- a/thinkterm-plugin-server/src/manifest.rs
+++ b/thinkterm-plugin-server/src/manifest.rs
@@ -6,8 +6,8 @@ use serde::Deserialize;
use std::collections::BTreeMap;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
-use thinkterm_plugin_channel::registry;
-use thinkterm_plugin_sdk::protocol::API;
+use thinkterm_plugin_channel::registry::{self, Background, Panel};
+use thinkterm_plugin_sdk::protocol::{API, PANEL_API};
pub const FILE: &str = "plugin.toml";
/// The longest id: it names a directory, a switch, and every event.
@@ -29,15 +29,27 @@ struct Raw {
#[serde(default)]
run: Option<RawRun>,
#[serde(default)]
+ panel: Option<RawPanel>,
+ #[serde(default)]
locales: BTreeMap<String, RawLocale>,
}
+#[derive(Debug, Default, Deserialize)]
+struct RawPanel {
+ #[serde(default)]
+ icon: Option<String>,
+}
+
#[derive(Debug, Default, Deserialize)]
struct RawRun {
#[serde(default)]
program: Option<String>,
#[serde(default)]
args: Option<Vec<String>>,
+ /// How long the program runs unused: `[run]`'s own, the same on every
+ /// system.
+ #[serde(default)]
+ background: Option<Background>,
#[serde(default)]
macos: Option<Box<RawRun>>,
#[serde(default)]
@@ -61,6 +73,10 @@ pub struct Manifest {
pub version: String,
pub description: String,
pub platforms: Vec<String>,
+ /// The panel it adds to the right sidebar.
+ pub panel: Option<Panel>,
+ /// How long its program runs unused, unless the user chose otherwise.
+ pub background: Background,
/// The program for this system, and its arguments. None for a built-in
/// plugin, and for one that does not run on this system.
run: Option<(String, Vec<String>)>,
@@ -95,6 +111,9 @@ fn id_rule() -> String {
format!("a-z, 0-9 and \"-\", at most {ID_LIMIT} characters")
}
+/// The icon a panel that names none, or one no client has, gets.
+const PANEL_ICON: &str = thinkterm_plugin_sdk::panel::ICONS[0];
+
impl Manifest {
/// The manifest in an installed plugin's directory.
pub fn load(dir: &Path) -> Result<Self, String> {
@@ -146,6 +165,11 @@ impl Manifest {
.map(|platform| platform.to_ascii_lowercase())
.collect();
let supported = supports(&platforms);
+ let background = raw
+ .run
+ .as_ref()
+ .and_then(|run| run.background)
+ .unwrap_or_default();
let run = match (builtin, raw.run) {
(true, None) => None,
(true, Some(_)) => return Err("a built-in plugin runs no program".into()),
@@ -156,6 +180,19 @@ impl Manifest {
if !builtin && raw.version.trim().is_empty() {
return Err("the version is empty".into());
}
+ let panel = match raw.panel {
+ None => None,
+ Some(_) if builtin => return Err("a built-in plugin's panel is ThinkTerm's own".into()),
+ Some(_) if raw.api < PANEL_API => {
+ return Err(format!("a [panel] needs api = {PANEL_API} or later"))
+ }
+ Some(panel) => Some(Panel {
+ icon: panel
+ .icon
+ .filter(|icon| thinkterm_plugin_sdk::panel::ICONS.contains(&icon.as_str()))
+ .unwrap_or_else(|| PANEL_ICON.to_string()),
+ }),
+ };
let locales = raw
.locales
.into_iter()
@@ -173,6 +210,8 @@ impl Manifest {
version: raw.version,
description: raw.description,
platforms,
+ panel,
+ background,
run,
locales,
})
@@ -325,6 +364,24 @@ mod tests {
assert_eq!(manifest.localized("ja-JP").description, "デコード");
assert_eq!(manifest.localized("").name, "Text Tools");
assert_eq!(manifest.localized("de-DE").name, "Text Tools");
+ assert_eq!(manifest.background, Background::Briefly, "unless it says");
+ }
+
+ #[test]
+ fn a_manifest_says_how_long_its_program_runs_unused() {
+ let with =
+ |line: &str| Manifest::parse(&EXAMPLE.replacen("args = [\"--stdio\"]", line, 1), false);
+ assert_eq!(
+ with("background = \"always\"").unwrap().background,
+ Background::Always
+ );
+ assert_eq!(
+ with("background = \"never\"").unwrap().background,
+ Background::Never
+ );
+ assert!(with("background = \"sometimes\"")
+ .unwrap_err()
+ .contains("line"));
}
#[test]
@@ -335,7 +392,7 @@ mod tests {
};
assert!(broken("text-tools", "Text Tools").contains("is not a-z"));
assert!(broken("text-tools", "plugins").contains("ThinkTerm's own"));
- assert!(broken("api = 1", "api = 2").contains("newer ThinkTerm"));
+ assert!(broken("api = 1", "api = 3").contains("newer ThinkTerm"));
assert!(broken("api = 1", "api = 0").contains("api must be"));
assert!(broken("version = \"0.1.0\"", "").contains("version"));
let unreadable = broken("[run]", "[run");
@@ -345,6 +402,32 @@ mod tests {
.contains("runs no program"));
}
+ #[test]
+ fn a_panel_needs_the_api_that_draws_one() {
+ let with_panel = |api: u32, panel: &str| {
+ let text = EXAMPLE.replace("api = 1", &format!("api = {api}"));
+ Manifest::parse(&format!("{text}\n{panel}\n"), false)
+ };
+ let manifest = with_panel(2, "[panel]\nicon = \"git-compare\"").unwrap();
+ assert_eq!(manifest.panel.unwrap().icon, "git-compare");
+ let manifest = with_panel(2, "[panel]\nicon = \"Not An Icon\"").unwrap();
+ assert_eq!(manifest.panel.unwrap().icon, PANEL_ICON);
+ let manifest = with_panel(2, "[panel]\nicon = \"house\"").unwrap();
+ assert_eq!(
+ manifest.panel.unwrap().icon,
+ PANEL_ICON,
+ "a Lucide icon no client has"
+ );
+ assert_eq!(
+ with_panel(2, "[panel]").unwrap().panel.unwrap().icon,
+ PANEL_ICON
+ );
+ assert!(with_panel(2, "").unwrap().panel.is_none());
+ assert!(with_panel(1, "[panel]")
+ .unwrap_err()
+ .contains("needs api = 2"));
+ }
+
#[test]
fn an_error_says_the_line_it_is_on() {
// The second id starts its line.
@@ -402,4 +485,25 @@ mod tests {
assert!(!valid_id(id), "{id}");
}
}
+
+ #[test]
+ fn a_manifest_nested_as_deep_as_toml_goes_is_read_on_a_hosts_stack() {
+ // The parser takes 80 levels, and refuses more.
+ let deepest = |open: &str, close: &str| {
+ format!(
+ "id = \"a\"\nname = \"A\"\napi = 1\nx = {}1{}\n[run]\nprogram = \"a\"\n",
+ open.repeat(79),
+ close.repeat(79)
+ )
+ };
+ for text in [deepest("[", "]"), deepest("{a=", "}")] {
+ // Read or refused, as long as it is not the host aborted.
+ std::thread::Builder::new()
+ .stack_size(crate::process::STACK)
+ .spawn(move || Manifest::parse(&text, false).is_ok())
+ .unwrap()
+ .join()
+ .unwrap();
+ }
+ }
}
diff --git a/thinkterm-plugin-server/src/process.rs b/thinkterm-plugin-server/src/process.rs
index e6bfca81..563714e6 100644
--- a/thinkterm-plugin-server/src/process.rs
+++ b/thinkterm-plugin-server/src/process.rs
@@ -44,7 +44,17 @@ const ERRORS_LOGGED: usize = 4 * 1024 * 1024;
const ERROR_LINE: u64 = 4096;
/// What is left of [`ERRORS_LOGGED`].
static ERRORS_LEFT: AtomicUsize = AtomicUsize::new(ERRORS_LOGGED);
-const STACK: usize = 256 * 1024;
+/// The stack of the host's threads, here and in `host`. They parse JSON and
+/// move bytes, and any of them may read a manifest -- a scan, a tidy -- one
+/// nested as deep as the TOML parser goes (80 levels) taking 512 KiB in a
+/// release build and 2 MiB in a debug one, unoptimized: twice that here. A
+/// thread that runs out aborts the host; what it does not touch of its
+/// stack is only reserved.
+pub const STACK: usize = if cfg!(debug_assertions) {
+ 4 * 1024 * 1024
+} else {
+ 1024 * 1024
+};
/// What the host hears about a program, on the program's own threads.
pub trait Listener: Send + Sync + 'static {
@@ -200,7 +210,7 @@ impl Process {
Ok(false) => break None,
Err(err) => break Some(format!("{err}")),
}
- match serde_json::from_slice::<FromPlugin>(&line) {
+ match FromPlugin::read(&line) {
Ok(message) => listener.said(&id, generation, message),
Err(err) if noise < NOISE_LOGGED => {
noise += 1;
@@ -291,17 +301,47 @@ impl Process {
Ok(())
}
+ /// Sends a message no answer is waited for: one about a panel.
+ pub fn tell(&mut self, message: &ToPlugin) -> Result<(), Refused> {
+ let mut line = Vec::new();
+ protocol::write_message(&mut line, message)
+ .map_err(|err| Refused::Busy(format!("{err}")))?;
+ self.tell_line(line)
+ }
+
+ /// Sends a message already written out as a line, its end included.
+ pub fn tell_line(&mut self, line: Vec<u8>) -> Result<(), Refused> {
+ match self.outbox.try_send(line) {
+ Ok(()) => Ok(()),
+ Err(TrySendError::Full(_)) => {
+ Err(Refused::Gone("it is not reading what it is sent".into()))
+ }
+ Err(TrySendError::Disconnected(_)) => Err(Refused::Gone("its input is closed".into())),
+ }
+ }
+
+ /// Whether calls to it wait for their answers.
+ pub fn busy(&self) -> bool {
+ !self.pending.is_empty()
+ }
+
/// The client waiting for the answer to `id`, now that it came.
pub fn answered(&mut self, id: u64) -> Option<Waiter> {
self.pending.remove(&id).map(|(waiter, _)| waiter)
}
- /// Lets go of the calls made longer than [`PENDING_EXPIRY`] ago: whoever
- /// made them stopped waiting long since. Hands them back.
- pub fn expire(&mut self) -> Vec<Waiter> {
+ /// When the oldest call still waiting for its answer was made.
+ pub fn oldest_call(&self) -> Option<Instant> {
+ self.pending.values().map(|(_, made)| *made).min()
+ }
+
+ /// Lets go of the calls made longer than `limit` ago -- normally
+ /// [`PENDING_EXPIRY`]: whoever made them stopped waiting long since.
+ /// Hands them back.
+ pub fn expire(&mut self, limit: Duration) -> Vec<Waiter> {
let mut expired = Vec::new();
self.pending.retain(|_, (waiter, made)| {
- let keep = made.elapsed() < PENDING_EXPIRY;
+ let keep = made.elapsed() < limit;
if !keep {
expired.push(*waiter);
}
diff --git a/thinkterm-plugin-server/src/registry.rs b/thinkterm-plugin-server/src/registry.rs
index 71062055..07bd0c87 100644
--- a/thinkterm-plugin-server/src/registry.rs
+++ b/thinkterm-plugin-server/src/registry.rs
@@ -4,8 +4,10 @@
//!
//! The directory is looked at again whenever the list is asked for, and a
//! plugin's manifest and program whenever it is used, so installing,
-//! removing, editing and rebuilding a plugin need no restart. Nothing
-//! starts a plugin's program but a client using the plugin, and no program
+//! removing, editing and rebuilding a plugin need no restart. A plugin's
+//! program starts when a client uses the plugin -- or, for one that runs
+//! always, while ThinkTerm keeps the host -- and stops once it has gone
+//! unused for as long as the plugin may run so ([`Background`]). No program
//! starts while one that ran under the same id -- from whichever directory
//! -- is still on its way out: they share a data directory, and calls made
//! meanwhile wait for it to be gone.
@@ -17,18 +19,50 @@ use crate::switches::{self, Switches};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
-use thinkterm_plugin_channel::registry::{Info, State};
-use thinkterm_plugin_sdk::protocol::{ToPlugin, API};
+use thinkterm_plugin_channel::registry::{Background, Info, State, DIR_LIMIT};
+use thinkterm_plugin_sdk::protocol::{ToPlugin, API, PANEL_API};
use thinkterm_plugin_sdk::Plugin;
/// Crashes within [`CRASH_WINDOW`] that mark a plugin failed.
const CRASH_LIMIT: usize = 3;
const CRASH_WINDOW: Duration = Duration::from_secs(60);
-/// Directories looked at in the plugins directory; one with more than this
-/// is not a plugins directory someone keeps by hand.
-const DIR_LIMIT: usize = 256;
/// How long the programs still running when the host exits have to exit.
const EXIT_GRACE: Duration = Duration::from_secs(1);
+/// How long a plugin that runs always rests after it stopped by itself
+/// before it is started again.
+const RESTART_PAUSE: Duration = Duration::from_secs(2);
+
+/// How long programs run unused, by how long their plugins may, and how
+/// long a call waits for its answer: what [`Background`] and
+/// [`process::PENDING_EXPIRY`] say, but for a test's much shorter ones.
+#[derive(Debug, Clone, Copy)]
+pub struct Limits {
+ pub briefly: Duration,
+ pub never: Duration,
+ pub pending: Duration,
+}
+
+impl Default for Limits {
+ fn default() -> Self {
+ Self {
+ briefly: Background::BRIEFLY,
+ never: Background::NEVER,
+ pending: process::PENDING_EXPIRY,
+ }
+ }
+}
+
+impl Limits {
+ /// How long a plugin that runs `background` runs unused, `None` for as
+ /// long as the host is kept.
+ fn unused_for(&self, background: Background) -> Option<Duration> {
+ match background {
+ Background::Always => None,
+ Background::Briefly => Some(self.briefly),
+ Background::Never => Some(self.never),
+ }
+ }
+}
/// A plugin built into the host, which runs inside it.
pub struct Builtin {
@@ -70,6 +104,8 @@ struct Installed {
exiting: Vec<Exiting>,
/// The calls waiting for such a program to be gone.
queued: Vec<Queued>,
+ /// Since when its running program has gone unused.
+ unused_since: Option<Instant>,
}
enum Run {
@@ -97,6 +133,7 @@ impl Installed {
crashes: Vec::new(),
exiting: Vec::new(),
queued: Vec::new(),
+ unused_since: None,
};
installed.read_manifest();
installed
@@ -162,6 +199,12 @@ impl Fallout {
}
}
+/// Why a panel could not be opened, and whether opening it again may work.
+pub struct Refusal {
+ pub reason: String,
+ pub again: bool,
+}
+
/// Which plugin a call is for.
pub enum Lookup {
Builtin(usize),
@@ -180,10 +223,19 @@ pub struct Registry {
/// taken for another run's.
generation: u64,
ready_within: Duration,
+ limits: Limits,
+ /// Where the plugins that run always are written, and what was last.
+ always_file: PathBuf,
+ always_written: Option<Vec<String>>,
}
impl Registry {
- pub fn new(data_dir: &Path, builtins: Vec<Builtin>, ready_within: Duration) -> Self {
+ pub fn new(
+ data_dir: &Path,
+ builtins: Vec<Builtin>,
+ ready_within: Duration,
+ limits: Limits,
+ ) -> Self {
let mut registry = Self {
plugins_dir: thinkterm_plugin_channel::paths::plugins_dir_in(data_dir),
plugin_data: data_dir.join("plugin-data"),
@@ -192,6 +244,9 @@ impl Registry {
installed: Vec::new(),
generation: 0,
ready_within,
+ limits,
+ always_file: thinkterm_plugin_channel::paths::always_in(data_dir),
+ always_written: None,
};
// Nobody is connected yet to be told what it found.
registry.scan(&mut Fallout::default());
@@ -349,9 +404,20 @@ impl Registry {
dir: None,
enabled,
state: if enabled { State::Idle } else { State::Off },
+ panel: None,
+ background: Background::default(),
+ background_default: Background::default(),
}
}
+ /// How long a plugin with `manifest` runs unused: the user's choice,
+ /// else its manifest's.
+ fn background(&self, manifest: &Manifest) -> Background {
+ self.switches
+ .background(&manifest.id)
+ .unwrap_or(manifest.background)
+ }
+
fn installed_info(&self, installed: &Installed, locale: &str) -> Info {
let dir = Some(installed.dir.display().to_string());
let manifest = match &installed.manifest {
@@ -368,6 +434,9 @@ impl Registry {
state: State::Invalid {
reason: reason.clone(),
},
+ panel: None,
+ background: Background::default(),
+ background_default: Background::default(),
}
}
};
@@ -410,6 +479,9 @@ impl Registry {
dir,
enabled,
state,
+ panel: manifest.panel.clone(),
+ background: self.background(manifest),
+ background_default: manifest.background,
}
}
@@ -496,6 +568,185 @@ impl Registry {
Ok(())
}
+ /// Keeps the user's choice of how long plugin `id` runs unused, `None`
+ /// for its manifest's. Acted on at the next [`tidy`](Self::tidy).
+ pub fn set_background(
+ &mut self,
+ id: &str,
+ background: Option<Background>,
+ fallout: &mut Fallout,
+ ) -> Result<(), String> {
+ let known = self
+ .installed
+ .iter()
+ .any(|installed| installed.id() == Some(id));
+ if !known {
+ let why = if self
+ .builtins
+ .iter()
+ .any(|builtin| builtin.manifest.id == id)
+ {
+ format!("{id:?} runs inside ThinkTerm, not on its own")
+ } else {
+ format!("there is no plugin {id:?}")
+ };
+ return Err(why);
+ }
+ self.follow_switches(fallout);
+ let moved = self
+ .switches
+ .set_background(id, background)
+ .map_err(|err| format!("cannot save the choice: {err:#}"))?;
+ if moved {
+ log::info!("plugin {id} runs unused: {background:?}");
+ fallout.changed = true;
+ }
+ Ok(())
+ }
+
+ /// Stops the programs that have gone unused for as long as their
+ /// plugins may run so, and starts the ones that run always while
+ /// ThinkTerm `kept` the host -- restarting one that stopped by itself
+ /// after a pause, until it has stopped too often. `used` says whether a
+ /// plugin, by id, has a panel on show or a client watching it; a call
+ /// waiting for its answer counts as a use too. Hands back when the next
+ /// program is due to be stopped or started, if any is.
+ pub fn tidy(
+ &mut self,
+ now: Instant,
+ kept: bool,
+ used: impl Fn(&str) -> bool,
+ listener: &Arc<dyn Listener>,
+ fallout: &mut Fallout,
+ ) -> Option<Instant> {
+ self.mark_always();
+ let mut next: Option<Instant> = None;
+ let mut due = |at: Instant| next = Some(next.map_or(at, |next| next.min(at)));
+ // A call the program never answers is let go of in time, and stops
+ // counting as a use of it, though no other call comes to find it.
+ let pending = self.limits.pending;
+ for installed in &mut self.installed {
+ if let Run::Running(process) = &mut installed.run {
+ let expired = process.expire(pending);
+ if !expired.is_empty() {
+ fallout.lost(expired, "the plugin did not answer in time");
+ }
+ if let Some(made) = process.oldest_call() {
+ due(made + pending);
+ }
+ }
+ }
+ for index in 0..self.installed.len() {
+ let installed = &self.installed[index];
+ let Some(manifest) = installed
+ .manifest
+ .as_ref()
+ .ok()
+ .filter(|_| installed.shadowed.is_none())
+ else {
+ continue;
+ };
+ let id = manifest.id.clone();
+ let background = self.background(manifest);
+ // One that cannot run -- turned off, or not for this system --
+ // is not tried each time.
+ let always = kept
+ && background == Background::Always
+ && manifest.supported()
+ && self.switches.enabled(&id);
+ let in_use = |installed: &Installed| match &installed.run {
+ Run::Running(process) => {
+ always || process.busy() || !installed.queued.is_empty() || used(&id)
+ }
+ _ => false,
+ };
+ match &installed.run {
+ Run::Running(_) if in_use(installed) => {
+ self.installed[index].unused_since = None;
+ }
+ Run::Running(_) => {
+ // With nothing keeping ThinkTerm up, one that runs
+ // always runs as the others do.
+ let limit = self
+ .limits
+ .unused_for(background)
+ .unwrap_or(self.limits.briefly);
+ let installed = &mut self.installed[index];
+ let since = *installed.unused_since.get_or_insert(now);
+ if now.saturating_duration_since(since) >= limit {
+ installed.unused_since = None;
+ installed.stop(&format!("it went unused for {limit:?}"), fallout);
+ } else {
+ due(since + limit);
+ }
+ }
+ Run::Idle | Run::Crashed(_) if always => {
+ if let (Run::Crashed(_), Some(crashed)) =
+ (&installed.run, installed.crashes.last())
+ {
+ let again = *crashed + RESTART_PAUSE;
+ if now < again {
+ due(again);
+ continue;
+ }
+ }
+ if self.still_exiting(&id) {
+ // Started once it is gone: word of that runs this again.
+ continue;
+ }
+ let Ok(launch) = self.launchable(index, fallout) else {
+ continue;
+ };
+ if launch.id != id {
+ continue;
+ }
+ log::info!("starting plugin {id}: it runs always");
+ if let Err(why) = self.start(index, launch, listener, fallout) {
+ log::warn!("plugin {id} runs always, and cannot start: {why}");
+ }
+ }
+ _ => {}
+ }
+ }
+ next
+ }
+
+ /// Writes which plugins run always -- on, usable and not given up on --
+ /// where ThinkTerm looks to keep the host up for them, when that
+ /// changed; with none, there is no file. A write that fails is said
+ /// once, and tried again at the next change.
+ fn mark_always(&mut self) {
+ let mut always: Vec<String> = self
+ .installed
+ .iter()
+ .filter(|installed| installed.shadowed.is_none())
+ .filter(|installed| !matches!(installed.run, Run::Failed { .. }))
+ .filter_map(|installed| installed.manifest.as_ref().ok())
+ .filter(|manifest| {
+ manifest.supported()
+ && self.switches.enabled(&manifest.id)
+ && self.background(manifest) == Background::Always
+ })
+ .map(|manifest| manifest.id.clone())
+ .collect();
+ always.sort();
+ if self.always_written.as_ref() == Some(&always) {
+ return;
+ }
+ let written = if always.is_empty() {
+ match std::fs::remove_file(&self.always_file) {
+ Err(err) if err.kind() != std::io::ErrorKind::NotFound => Err(err.into()),
+ _ => Ok(()),
+ }
+ } else {
+ write_whole(&self.always_file, always.join("\n") + "\n")
+ };
+ if let Err(err) = written {
+ log::warn!("writing {}: {err:#}", self.always_file.display());
+ }
+ self.always_written = Some(always);
+ }
+
/// Stops a plugin, reads its manifest again and forgets that it failed:
/// every installed plugin when `id` is `None`, after looking for new and
/// removed ones.
@@ -574,6 +825,118 @@ impl Registry {
Ok(())
}
+ /// Sends the installed plugin at `index`, found answering to `id`, the
+ /// message opening a panel of it, starting its program if it is not
+ /// running -- and again if it was rebuilt. Hands back the run the panel
+ /// is open on. A program of the id still on its way out is not waited
+ /// for, as a call would: the client is to try again.
+ pub fn open_panel(
+ &mut self,
+ id: &str,
+ index: usize,
+ message: &ToPlugin,
+ listener: &Arc<dyn Listener>,
+ fallout: &mut Fallout,
+ ) -> Result<u64, Refusal> {
+ let for_good = |reason: String| Refusal {
+ reason,
+ again: false,
+ };
+ let launch = self.launchable(index, fallout).map_err(for_good)?;
+ if launch.id != id {
+ return Err(for_good(format!("there is no plugin named {id:?}")));
+ }
+ let installed = &mut self.installed[index];
+ let Ok(manifest) = &installed.manifest else {
+ return Err(for_good(format!("there is no plugin named {id:?}")));
+ };
+ if manifest.panel.is_none() {
+ return Err(for_good(format!("{} has no panel", manifest.name)));
+ }
+ if let Run::Running(process) = &installed.run {
+ if stamp(&process.program) != process.program_stamp {
+ installed.stop("its program changed, and it is started again", fallout);
+ }
+ }
+ if self.still_exiting(id) {
+ return Err(Refusal {
+ reason: "it is still stopping".into(),
+ again: true,
+ });
+ }
+ if !matches!(self.installed[index].run, Run::Running(_)) {
+ self.start(index, launch, listener, fallout)
+ .map_err(for_good)?;
+ }
+ let Run::Running(process) = &mut self.installed[index].run else {
+ unreachable!("just started");
+ };
+ let generation = process.generation;
+ match process.tell(message) {
+ Ok(()) => Ok(generation),
+ Err(Refused::Busy(reason)) => Err(Refusal {
+ reason,
+ again: true,
+ }),
+ Err(Refused::Gone(why)) => {
+ self.gave_up(id, generation, why.clone(), false, fallout);
+ Err(Refusal {
+ reason: why,
+ again: true,
+ })
+ }
+ }
+ }
+
+ /// Sends `message` to the program of plugin `id` if its run
+ /// `generation` is the one going on. False when it is not: the panels
+ /// open on it are closed by then, or about to be.
+ pub fn tell(
+ &mut self,
+ id: &str,
+ generation: u64,
+ message: &ToPlugin,
+ fallout: &mut Fallout,
+ ) -> bool {
+ let Some(process) = self.process(id, generation) else {
+ return false;
+ };
+ let told = process.tell(message);
+ self.told(id, generation, told, fallout)
+ }
+
+ /// [`tell`](Self::tell), with the message written out as a line already.
+ pub fn tell_line(
+ &mut self,
+ id: &str,
+ generation: u64,
+ line: Vec<u8>,
+ fallout: &mut Fallout,
+ ) -> bool {
+ let Some(process) = self.process(id, generation) else {
+ return false;
+ };
+ let told = process.tell_line(line);
+ self.told(id, generation, told, fallout)
+ }
+
+ fn told(
+ &mut self,
+ id: &str,
+ generation: u64,
+ told: Result<(), Refused>,
+ fallout: &mut Fallout,
+ ) -> bool {
+ match told {
+ Ok(()) => true,
+ Err(Refused::Busy(_)) => false,
+ Err(Refused::Gone(why)) => {
+ self.gave_up(id, generation, why, false, fallout);
+ false
+ }
+ }
+ }
+
/// Whether a program that ran under `id` is still on its way out, from
/// whichever directory: a new one would share its data directory.
fn still_exiting(&mut self, id: &str) -> bool {
@@ -670,10 +1033,11 @@ impl Registry {
return;
}
}
+ let pending = self.limits.pending;
let Run::Running(process) = &mut self.installed[index].run else {
unreachable!("just started");
};
- let expired = process.expire();
+ let expired = process.expire(pending);
fallout.lost(expired, "the plugin did not answer in time");
let mut gone = None;
let mut calls = calls.into_iter();
@@ -778,23 +1142,29 @@ impl Registry {
})
}
- /// The run's program said it is ready, speaking plugin API `api`.
+ /// The run's program said it is ready, speaking plugin API `api`: any
+ /// this ThinkTerm speaks, and one that draws a panel if it has one.
pub fn ready(&mut self, id: &str, generation: u64, api: u32, fallout: &mut Fallout) {
let Some(process) = self.process(id, generation) else {
return;
};
process.ready = true;
fallout.changed = true;
- if api == API {
+ let has_panel = self.installed.iter().any(|installed| {
+ installed.answers_to(id)
+ && installed
+ .manifest
+ .as_ref()
+ .is_ok_and(|manifest| manifest.panel.is_some())
+ });
+ let why = if !(1..=API).contains(&api) {
+ format!("it speaks plugin API {api}; this ThinkTerm speaks 1 to {API}")
+ } else if has_panel && api < PANEL_API {
+ format!("it speaks plugin API {api}, and its panel needs {PANEL_API}")
+ } else {
return;
- }
- self.gave_up(
- id,
- generation,
- format!("it speaks plugin API {api}; this ThinkTerm speaks {API}"),
- true,
- fallout,
- );
+ };
+ self.gave_up(id, generation, why, true, fallout);
}
/// The run's program has exited. One told to stop is gone at last: the
@@ -907,3 +1277,16 @@ impl Registry {
}
}
}
+
+/// Writes `text` to `path` whole, or not at all.
+fn write_whole(path: &Path, text: String) -> anyhow::Result<()> {
+ use std::io::Write;
+ let dir = path
+ .parent()
+ .ok_or_else(|| anyhow::anyhow!("{} has no directory", path.display()))?;
+ std::fs::create_dir_all(dir)?;
+ let mut file = tempfile::NamedTempFile::new_in(dir)?;
+ file.write_all(text.as_bytes())?;
+ file.persist(path)?;
+ Ok(())
+}
diff --git a/thinkterm-plugin-server/src/switches.rs b/thinkterm-plugin-server/src/switches.rs
index ada35393..ac8d5017 100644
--- a/thinkterm-plugin-server/src/switches.rs
+++ b/thinkterm-plugin-server/src/switches.rs
@@ -1,12 +1,16 @@
-//! Which plugins are turned off: `plugins.json` in the data directory. A
-//! plugin that is not in it is on. A switch stays when its plugin is
-//! removed, so a plugin installed again comes back as it was left.
+//! Which plugins are turned off, and how long the user lets each run
+//! unused: `plugins.json` in the data directory. A plugin that is not in it
+//! is on, and runs as its manifest says. A switch stays when its plugin is
+//! removed, so a plugin installed again comes back as it was left. Builds
+//! share the file: what one does not know is kept as another wrote it.
use crate::stamp::{stamp, Stamp};
use serde::{Deserialize, Serialize};
+use serde_json::Value;
use std::collections::BTreeMap;
use std::io::Write;
use std::path::PathBuf;
+use thinkterm_plugin_channel::registry::Background;
pub const FILE: &str = "plugins.json";
@@ -14,11 +18,36 @@ pub const FILE: &str = "plugins.json";
struct Stored {
#[serde(default)]
plugins: BTreeMap<String, Switch>,
+ /// What a newer build keeps here, as it wrote it.
+ #[serde(flatten)]
+ rest: BTreeMap<String, Value>,
}
-#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Switch {
+ #[serde(default = "on")]
enabled: bool,
+ /// The user's choice, as written; none, the manifest's. One this build
+ /// does not know counts as none, and is kept.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ background: Option<Value>,
+ /// What a newer build keeps here, as it wrote it.
+ #[serde(flatten)]
+ rest: BTreeMap<String, Value>,
+}
+
+impl Default for Switch {
+ fn default() -> Self {
+ Self {
+ enabled: true,
+ background: None,
+ rest: BTreeMap::new(),
+ }
+ }
+}
+
+fn on() -> bool {
+ true
}
pub struct Switches {
@@ -70,15 +99,44 @@ impl Switches {
.map_or(true, |switch| switch.enabled)
}
+ /// How long the user lets plugin `id` run unused, if they chose.
+ pub fn background(&self, id: &str) -> Option<Background> {
+ let chosen = self.stored.plugins.get(id)?.background.as_ref()?;
+ Background::deserialize(chosen).ok()
+ }
+
/// Turns a plugin on or off, on disk before it counts. The file is
/// written over as last read: [`refresh`](Self::refresh) first, and act
/// on what another host moved. False when it already was.
pub fn set(&mut self, id: &str, enabled: bool) -> anyhow::Result<bool> {
- if self.enabled(id) == enabled {
+ self.change(id, |switch| switch.enabled = enabled)
+ }
+
+ /// Keeps the user's choice of how long plugin `id` runs unused, `None`
+ /// for its manifest's, as [`set`](Self::set) keeps a switch.
+ pub fn set_background(
+ &mut self,
+ id: &str,
+ background: Option<Background>,
+ ) -> anyhow::Result<bool> {
+ let background = background.map(|background| {
+ serde_json::to_value(background).expect("a choice always serialises")
+ });
+ self.change(id, |switch| switch.background = background)
+ }
+
+ /// Changes plugin `id`'s entry and writes the file, if that moved it.
+ fn change(&mut self, id: &str, change: impl FnOnce(&mut Switch)) -> anyhow::Result<bool> {
+ let mut next = self.stored.clone();
+ let switch = next.plugins.entry(id.to_string()).or_default();
+ let before = switch.clone();
+ change(switch);
+ if *switch == before && self.stored.plugins.contains_key(id) {
+ return Ok(false);
+ }
+ if *switch == Switch::default() && !self.stored.plugins.contains_key(id) {
return Ok(false);
}
- let mut next = self.stored.clone();
- next.plugins.insert(id.to_string(), Switch { enabled });
let dir = self
.path
.parent()
@@ -117,6 +175,71 @@ mod tests {
assert!(!switches.refresh(), "nothing new");
}
+ #[test]
+ fn a_choice_of_background_is_kept_beside_the_switch() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(FILE);
+ let mut switches = Switches::load(path.clone());
+ assert_eq!(switches.background("a"), None, "the manifest's");
+ assert!(
+ !switches.set_background("a", None).unwrap(),
+ "nothing to keep"
+ );
+ assert!(switches
+ .set_background("a", Some(Background::Always))
+ .unwrap());
+ assert!(!switches
+ .set_background("a", Some(Background::Always))
+ .unwrap());
+ assert!(switches.enabled("a"), "still on");
+ let read = Switches::load(path.clone());
+ assert_eq!(read.background("a"), Some(Background::Always));
+ assert!(switches.set("a", false).unwrap());
+ assert_eq!(
+ Switches::load(path.clone()).background("a"),
+ Some(Background::Always)
+ );
+ assert!(switches.set_background("a", None).unwrap());
+ assert_eq!(Switches::load(path.clone()).background("a"), None);
+ assert!(!Switches::load(path.clone()).enabled("a"));
+ // A file from before there was a choice reads as it did.
+ std::fs::write(&path, r#"{"plugins": {"b": {"enabled": false}}}"#).unwrap();
+ let old = Switches::load(path);
+ assert!(!old.enabled("b"));
+ assert_eq!(old.background("b"), None);
+ }
+
+ #[test]
+ fn what_a_newer_build_wrote_is_kept_and_what_it_chose_counts_as_none() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(FILE);
+ let newer = serde_json::json!({
+ "plugins": {
+ "a": {"enabled": false, "background": "hourly", "pinned": true},
+ "b": {"background": "always"}
+ },
+ "order": ["b", "a"]
+ });
+ std::fs::write(&path, newer.to_string()).unwrap();
+ let mut switches = Switches::load(path.clone());
+ assert!(!switches.enabled("a"), "the rest of the file still reads");
+ assert_eq!(switches.background("a"), None, "a choice it does not know");
+ assert_eq!(switches.background("b"), Some(Background::Always));
+ assert!(switches.set("b", false).unwrap());
+ let written: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ assert_eq!(
+ written,
+ serde_json::json!({
+ "plugins": {
+ "a": {"enabled": false, "background": "hourly", "pinned": true},
+ "b": {"enabled": false, "background": "always"}
+ },
+ "order": ["b", "a"]
+ }),
+ "kept as the newer build wrote it"
+ );
+ }
+
#[test]
fn a_file_that_does_not_read_leaves_everything_on() {
let dir = tempfile::tempdir().unwrap();
diff --git a/thinkterm-plugin-server/tests/host.rs b/thinkterm-plugin-server/tests/host.rs
index 1d04e06b..bed1de65 100644
--- a/thinkterm-plugin-server/tests/host.rs
+++ b/thinkterm-plugin-server/tests/host.rs
@@ -227,7 +227,7 @@ fn a_session_follows_the_host_across_a_restart() {
let dir = tempfile::tempdir().unwrap();
let host = host_in(dir.path());
let (session, notices) = session(&host);
- next_notice(&notices, |n| matches!(n, Notice::Connected));
+ next_notice(&notices, |n| matches!(n, Notice::Connected { .. }));
let listed = ask(
&session,
Request::List {
@@ -257,7 +257,7 @@ fn a_session_follows_the_host_across_a_restart() {
// The host goes; the session starts another and says so.
stop(&host);
- next_notice(&notices, |n| matches!(n, Notice::Connected));
+ next_notice(&notices, |n| matches!(n, Notice::Connected { .. }));
let rows: Vec<Row> = serde_json::from_value(
ask(
&session,
@@ -312,7 +312,7 @@ fn a_call_to_a_host_that_hangs_is_given_up_on() {
let _ = tx.send(notice);
})
.unwrap();
- next_notice(&notices, |n| matches!(n, Notice::Connected));
+ next_notice(&notices, |n| matches!(n, Notice::Connected { .. }));
let started = Instant::now();
let why = ask(
&session,
diff --git a/thinkterm-plugin-server/tests/panels.rs b/thinkterm-plugin-server/tests/panels.rs
new file mode 100644
index 00000000..17ef4a4e
--- /dev/null
+++ b/thinkterm-plugin-server/tests/panels.rs
@@ -0,0 +1,519 @@
+//! Plugins' panels as clients see them: opened, drawn, clicked and scrolled
+//! through the host, sent one frame at a time, asking things of another
+//! machine through the client, and closed when the plugin or the client
+//! goes.
+
+#![cfg(unix)]
+
+mod common;
+
+use common::{host_in, next_notice, session, stop, wait_until};
+use serde_json::{json, Value};
+use std::os::unix::fs::PermissionsExt;
+use std::path::PathBuf;
+use std::sync::mpsc;
+use std::time::Duration;
+use thinkterm_plugin_channel::client::{Host, Notice, Session};
+use thinkterm_plugin_channel::registry as api;
+use thinkterm_plugin_channel::wire::{PanelEvent, PanelRequest, Raw};
+
+/// Draws "open" when a panel opens -- "extends" and the panel's number for
+/// an extended view -- or what is in the file `huge` in its data directory
+/// when there is one, and then, when there is a file `ask` there, asks what
+/// is at /x, by the view's number. A click draws five frames, one after
+/// another, numbered; rows are answered with one row, and then with one
+/// nobody asked for. Every view closed, and every answer, is written down.
+const PANEL: &str = r#"#!/bin/sh
+printf '%s\n' '{"type":"ready","api":2}'
+frame() {
+ printf '{"type":"frame","view":%s,"frame":{"items":[{"text":{"x":0,"y":0,"w":10,"h":10,"text":"%s"}}]}}\n' "$1" "$2"
+}
+while IFS= read -r line; do
+ view=$(printf '%s' "$line" | sed -n 's/.*"view":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"type":"stop"'*) exit 0 ;;
+ *'"type":"open"'*)
+ extends=$(printf '%s' "$line" | sed -n 's/.*"extends":\([0-9]*\).*/\1/p')
+ if [ -f "$THINKTERM_PLUGIN_DATA/huge" ]; then cat "$THINKTERM_PLUGIN_DATA/huge"
+ elif [ -n "$extends" ]; then frame "$view" "extends $extends"
+ else frame "$view" open; fi
+ if [ -f "$THINKTERM_PLUGIN_DATA/ask" ]; then
+ printf '{"type":"ask","view":%s,"id":%s,"machine":"m1","ask":{"op":"stat","path":"/x"}}\n' "$view" "$view"
+ fi ;;
+ *'"type":"answer"'*) printf '%s\n' "$line" >> "$THINKTERM_PLUGIN_DATA/answers" ;;
+ *'"type":"input"'*) for n in 1 2 3 4 5; do frame "$view" "$n"; done ;;
+ *'"type":"rows"'*)
+ printf '{"type":"rows","view":%s,"rows":{"list":"l","key":"k","from":0,"rows":[[]]}}\n' "$view"
+ printf '{"type":"rows","view":%s,"rows":{"list":"l","key":"k","from":9,"rows":[[]]}}\n' "$view" ;;
+ *'"type":"close"'*) printf '%s\n' "$view" >> "$THINKTERM_PLUGIN_DATA/closed" ;;
+ esac
+done
+"#;
+
+const MANIFEST: &str = r#"
+id = "panel"
+name = "Panel"
+version = "1"
+api = 2
+
+[run]
+program = "plugin.sh"
+
+[panel]
+icon = "chart-line"
+"#;
+
+fn install_panel(host: &Host) -> PathBuf {
+ let dir = host.data_dir.join("plugins").join("panel");
+ std::fs::create_dir_all(&dir).unwrap();
+ std::fs::write(dir.join("plugin.toml"), MANIFEST).unwrap();
+ let program = dir.join("plugin.sh");
+ std::fs::write(&program, PANEL).unwrap();
+ std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).unwrap();
+ dir
+}
+
+fn env() -> Raw {
+ Raw::new(&json!({
+ "width": 300, "height": 500, "scale": 2, "dark": true,
+ "small": {"size": 11, "line": 15},
+ "body": {"size": 13, "line": 18},
+ "title": {"size": 15, "line": 20},
+ "mono": {"size": 12, "line": 17, "advance": 7}
+ }))
+}
+
+/// [`env`], beside a terminal on another machine.
+fn remote_env() -> Raw {
+ let mut env: Value = env().read().unwrap();
+ env["remote"] = json!({"host": "server-a", "machine": "m1", "cwd": "/home/user"});
+ Raw::new(&env)
+}
+
+fn open(session: &Session, view: u64) {
+ session.panel(
+ view,
+ PanelRequest::Open {
+ plugin: "panel".into(),
+ env: env(),
+ extends: None,
+ },
+ );
+}
+
+/// Opens the extended view of the client's panel `panel` as `view`.
+fn extend(session: &Session, view: u64, panel: u64) {
+ session.panel(
+ view,
+ PanelRequest::Open {
+ plugin: "panel".into(),
+ env: env(),
+ extends: Some(panel),
+ },
+ );
+}
+
+fn click(session: &Session, view: u64) {
+ let input = Raw::new(&json!({"click": {"id": "a", "x": 1, "y": 1}}));
+ session.panel(view, PanelRequest::Input { input });
+}
+
+/// The next thing heard about panel `view`.
+fn heard(notices: &mpsc::Receiver<Notice>, view: u64) -> PanelEvent {
+ let notice = next_notice(
+ notices,
+ |notice| matches!(notice, Notice::Panel { view: of, .. } if *of == view),
+ );
+ let Notice::Panel { event, .. } = notice else {
+ unreachable!()
+ };
+ event
+}
+
+/// What a frame says: the text it draws.
+fn drawn(event: PanelEvent) -> String {
+ let PanelEvent::Frame { frame } = &event else {
+ panic!("not a frame: {event:?}")
+ };
+ let frame: Value = frame.read().unwrap();
+ frame["items"][0]["text"]["text"]
+ .as_str()
+ .unwrap()
+ .to_string()
+}
+
+/// Nothing more is heard about panel `view` for a while.
+fn quiet(notices: &mpsc::Receiver<Notice>, view: u64) {
+ let deadline = std::time::Instant::now() + Duration::from_millis(300);
+ while let Some(left) = deadline.checked_duration_since(std::time::Instant::now()) {
+ match notices.recv_timeout(left) {
+ Ok(Notice::Panel { view: of, event }) if of == view => {
+ panic!("heard {event:?}")
+ }
+ Ok(_) => {}
+ Err(_) => return,
+ }
+ }
+}
+
+fn closed_views(host: &Host) -> String {
+ std::fs::read_to_string(host.data_dir.join("plugin-data/panel/closed")).unwrap_or_default()
+}
+
+#[test]
+fn a_panel_is_listed_opened_drawn_and_closed() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let (session, notices) = session(&host);
+
+ let listed: Vec<api::Info> = {
+ let (tx, rx) = mpsc::channel();
+ let request = serde_json::to_value(api::Request::List {
+ locale: String::new(),
+ })
+ .unwrap();
+ session.call(api::PLUGIN, request, move |answer| {
+ let _ = tx.send(answer);
+ });
+ serde_json::from_value(rx.recv().unwrap().unwrap()).unwrap()
+ };
+ let panel = listed.iter().find(|info| info.id == "panel").unwrap();
+ assert_eq!(panel.panel.as_ref().unwrap().icon, "chart-line");
+ assert!(listed
+ .iter()
+ .find(|info| info.id == "snippets")
+ .unwrap()
+ .panel
+ .is_none());
+
+ open(&session, 41);
+ assert_eq!(drawn(heard(&notices, 41)), "open");
+ session.panel(41, PanelRequest::Shown);
+
+ let wanted = Raw::new(&json!({"list": "l", "key": "k", "from": 0, "to": 1}));
+ session.panel(41, PanelRequest::Rows { wanted });
+ let PanelEvent::Rows { rows } = heard(&notices, 41) else {
+ panic!()
+ };
+ assert_eq!(rows.read::<Value>().unwrap()["from"], 0);
+ quiet(&notices, 41);
+
+ session.panel(41, PanelRequest::Close);
+ wait_until("the plugin hears the panel closed", || {
+ closed_views(&host) == "1\n"
+ });
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn an_extended_view_knows_its_panel_and_closes_before_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let (session, notices) = session(&host);
+ open(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+ extend(&session, 2, 1);
+ // The plugin knows views by its own numbers: the panel is its first.
+ assert_eq!(drawn(heard(&notices, 2)), "extends 1");
+
+ // Nothing extends a panel the client does not show, or an extended
+ // view.
+ for (view, panel) in [(3, 9), (4, 2)] {
+ extend(&session, view, panel);
+ let PanelEvent::Closed { again, reason } = heard(&notices, view) else {
+ panic!()
+ };
+ assert!(!again && reason.contains("to extend"), "{reason}");
+ }
+
+ // The panel opened anew under its number: its extended view closed,
+ // and the client is told.
+ open(&session, 1);
+ let PanelEvent::Closed { again, .. } = heard(&notices, 2) else {
+ panic!()
+ };
+ assert!(!again);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+ extend(&session, 5, 1);
+ assert_eq!(drawn(heard(&notices, 5)), "extends 3");
+ // A panel has one: another takes its place.
+ extend(&session, 6, 1);
+ let PanelEvent::Closed { again, .. } = heard(&notices, 5) else {
+ panic!()
+ };
+ assert!(!again);
+ assert_eq!(drawn(heard(&notices, 6)), "extends 3");
+
+ session.panel(1, PanelRequest::Close);
+ let PanelEvent::Closed { .. } = heard(&notices, 6) else {
+ panic!()
+ };
+ wait_until("the plugin hears each extended view close first", || {
+ closed_views(&host) == "2\n1\n4\n5\n3\n"
+ });
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn a_client_is_sent_the_newest_frame_once_it_took_in_the_last() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let (session, notices) = session(&host);
+ open(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+ // Five frames drawn while "open" is not taken in yet: none is sent.
+ click(&session, 1);
+ quiet(&notices, 1);
+ session.panel(1, PanelRequest::Shown);
+ assert_eq!(drawn(heard(&notices, 1)), "5", "only the newest");
+ session.panel(1, PanelRequest::Shown);
+ quiet(&notices, 1);
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn a_frame_too_long_to_send_is_dropped_and_the_client_keeps_its_connection() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ // A line as long as a plugin may send: the view's number around it
+ // makes it longer than a client is sent.
+ let data = host.data_dir.join("plugin-data/panel");
+ std::fs::create_dir_all(&data).unwrap();
+ let start = r#"{"type":"frame","view":1,"frame":{"items":[],"pad":""#;
+ let end = r#""}}"#;
+ let pad = thinkterm_plugin_sdk::protocol::MAX_LINE - start.len() - end.len();
+ let line = format!("{start}{}{end}\n", "x".repeat(pad));
+ std::fs::write(data.join("huge"), line).unwrap();
+ let (session, notices) = session(&host);
+ open(&session, 1);
+ quiet(&notices, 1);
+ // Nothing was sent, so nothing waits to be taken in: the next frame
+ // goes at once, over the same connection.
+ click(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "1");
+ let log = std::fs::read_to_string(&host.log).unwrap();
+ assert!(log.contains("too long to send"), "{log}");
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn a_panel_closes_with_its_plugin_and_opens_again_unless_it_is_off() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let (session, notices) = session(&host);
+ let manage = |request: api::Request| {
+ let (tx, rx) = mpsc::channel();
+ session.call(
+ api::PLUGIN,
+ serde_json::to_value(request).unwrap(),
+ move |answer| {
+ let _ = tx.send(answer);
+ },
+ );
+ rx.recv().unwrap()
+ };
+ open(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+
+ manage(api::Request::Reload {
+ id: Some("panel".into()),
+ })
+ .unwrap();
+ let PanelEvent::Closed { again, .. } = heard(&notices, 1) else {
+ panic!()
+ };
+ assert!(again, "a reload is worth opening again after");
+ open(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "open", "on the new run");
+ // The old run's view was closed before it went; the new one opened
+ // as view 2.
+ session.panel(1, PanelRequest::Shown);
+
+ manage(api::Request::SetEnabled {
+ id: "panel".into(),
+ enabled: false,
+ })
+ .unwrap();
+ let PanelEvent::Closed { again, .. } = heard(&notices, 1) else {
+ panic!()
+ };
+ assert!(again);
+ open(&session, 1);
+ let PanelEvent::Closed { reason, again } = heard(&notices, 1) else {
+ panic!()
+ };
+ assert!(!again, "off, it stays closed: {reason}");
+ assert!(reason.contains("turned off"), "{reason}");
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn a_client_that_leaves_takes_its_panels_with_it() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let (session, notices) = session(&host);
+ open(&session, 1);
+ open(&session, 2);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+ assert_eq!(drawn(heard(&notices, 2)), "open");
+ // Another client keeps the host, and the plugin, up.
+ let (other, other_notices) = common::session(&host);
+ open(&other, 1);
+ assert_eq!(drawn(heard(&other_notices, 1)), "open");
+
+ drop(session);
+ wait_until("both of its panels close", || {
+ let closed = closed_views(&host);
+ closed.lines().count() == 2 && closed.contains("1\n") && closed.contains("2\n")
+ });
+ drop(other);
+ stop(&host);
+}
+
+#[test]
+fn a_panel_asked_for_before_the_host_was_reached_is_opened_once_it_is() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = host_in(dir.path());
+ install_panel(&real);
+ // A session whose host cannot be started: what it is asked about a
+ // panel meanwhile goes nowhere.
+ let unreachable = Host {
+ program: dir.path().join("no-such-program"),
+ ..real.clone()
+ };
+ let (tx, notices) = mpsc::channel();
+ let session = Session::start(unreachable, move |notice| {
+ let _ = tx.send(notice);
+ })
+ .unwrap();
+ next_notice(&notices, |notice| matches!(notice, Notice::Trouble(_)));
+ open(&session, 1);
+ // The host comes up after all: the owner is told to open its panels
+ // again, though it never had a connection to lose them with.
+ let mut server = common::spawn(&real, &[]);
+ let connected = next_notice(&notices, |notice| {
+ matches!(notice, Notice::Connected { .. })
+ });
+ assert!(
+ matches!(connected, Notice::Connected { again: true }),
+ "{connected:?}"
+ );
+ open(&session, 1);
+ assert_eq!(drawn(heard(&notices, 1)), "open");
+ drop(session);
+ stop(&real);
+ let _ = server.wait();
+}
+
+#[test]
+fn a_panel_of_a_plugin_without_one_is_closed_for_good() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ let (session, notices) = session(&host);
+ session.panel(
+ 3,
+ PanelRequest::Open {
+ plugin: "snippets".into(),
+ env: env(),
+ extends: None,
+ },
+ );
+ let PanelEvent::Closed { again, reason } = heard(&notices, 3) else {
+ panic!()
+ };
+ assert!(!again, "{reason}");
+ session.panel(
+ 4,
+ PanelRequest::Open {
+ plugin: "panel".into(),
+ env: Raw::new(&json!({"width": "wide"})),
+ extends: None,
+ },
+ );
+ let PanelEvent::Closed { again, reason } = heard(&notices, 4) else {
+ panic!()
+ };
+ assert!(!again && reason.contains("size"), "{reason}");
+ drop(session);
+ stop(&host);
+}
+
+#[test]
+fn what_a_plugin_asks_of_another_machine_goes_to_its_panels_client_and_back() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_panel(&host);
+ let data = host.data_dir.join("plugin-data/panel");
+ std::fs::create_dir_all(&data).unwrap();
+ std::fs::write(data.join("ask"), "").unwrap();
+ let answers = || std::fs::read_to_string(data.join("answers")).unwrap_or_default();
+ let (session, notices) = session(&host);
+ let open_remote = |view| {
+ session.panel(
+ view,
+ PanelRequest::Open {
+ plugin: "panel".into(),
+ env: remote_env(),
+ extends: None,
+ },
+ )
+ };
+
+ // Beside a terminal on another machine: the ask reaches the client
+ // showing the panel, and its answer the plugin.
+ open_remote(7);
+ assert_eq!(drawn(heard(&notices, 7)), "open");
+ let PanelEvent::Remote { id, machine, ask } = heard(&notices, 7) else {
+ panic!("no ask")
+ };
+ assert_eq!(machine, "m1", "the machine the plugin named");
+ assert_eq!(
+ ask.read::<Value>().unwrap(),
+ json!({"op": "stat", "path": "/x"})
+ );
+ let answer = Raw::new(&json!({"result": "stat", "entry": null}));
+ session.panel(7, PanelRequest::Answer { id, answer });
+ wait_until("the plugin hears the answer", || {
+ answers().contains(r#""result":"stat""#)
+ });
+ // An answer to nothing it asked goes nowhere.
+ let stray = Raw::new(&json!({"result": "stat", "entry": null}));
+ session.panel(
+ 7,
+ PanelRequest::Answer {
+ id: 99,
+ answer: stray,
+ },
+ );
+
+ // Beside one on this machine, the plugin reaches it itself: refused.
+ open(&session, 8);
+ assert_eq!(drawn(heard(&notices, 8)), "open");
+ wait_until("the refusal", || answers().contains("runs on this machine"));
+ quiet(&notices, 8);
+
+ // Closed before the client answered: the plugin hears none is coming.
+ open_remote(9);
+ assert_eq!(drawn(heard(&notices, 9)), "open");
+ let PanelEvent::Remote { .. } = heard(&notices, 9) else {
+ panic!("no ask")
+ };
+ session.panel(9, PanelRequest::Close);
+ wait_until("the plugin hears it goes unanswered", || {
+ answers().contains("the panel closed")
+ });
+ assert_eq!(answers().lines().count(), 3, "{}", answers());
+ drop(session);
+ stop(&host);
+}
diff --git a/thinkterm-plugin-server/tests/plugins.rs b/thinkterm-plugin-server/tests/plugins.rs
index 47d201c2..fee9306e 100644
--- a/thinkterm-plugin-server/tests/plugins.rs
+++ b/thinkterm-plugin-server/tests/plugins.rs
@@ -221,7 +221,7 @@ fn a_manifest_that_cannot_be_used_is_listed_with_why() {
"clash",
&copy.replace("\"snippets-copy\"", "\"snippets\""),
);
- install(&host, "future", &copy.replace("api = 1", "api = 2"));
+ install(&host, "future", &copy.replace("api = 1", "api = 99"));
std::fs::create_dir_all(host.data_dir.join("plugins/empty")).unwrap();
let (session, _notices) = session(&host);
@@ -287,6 +287,28 @@ fn plugins_have_no_commands_to_run() {
stop(&host);
}
+#[test]
+fn a_plugin_someone_watches_runs_on_unused() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install(&host, "copy", &snippets_copy(&host));
+ let mut child = spawn(&host, &["--briefly-secs", "1"]);
+ wait_until("the host to listen", || host.socket.exists());
+ let (session, _notices) = session(&host);
+ // Listing snippets watches them: the session hears when they change.
+ call(
+ &session,
+ "snippets-copy",
+ json!({"op": "list", "query": ""}),
+ )
+ .unwrap();
+ std::thread::sleep(Duration::from_millis(2500));
+ assert_eq!(info(&session, "snippets-copy").state, State::Running);
+ drop(session);
+ stop(&host);
+ wait_until("the host to quit", || child.try_wait().unwrap().is_some());
+}
+
#[test]
fn reloading_stops_a_plugin_and_the_next_call_starts_it() {
let dir = tempfile::tempdir().unwrap();
@@ -401,6 +423,209 @@ program = "plugin.sh"
stop(&host);
}
+ fn set_background(session: &Session, id: &str, background: Option<api::Background>) -> Answer {
+ manage(
+ session,
+ api::Request::SetBackground {
+ id: id.into(),
+ background,
+ },
+ )
+ }
+
+ #[test]
+ fn a_plugin_gone_unused_stops_after_as_long_as_it_may_run_so() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_script(&host, WELL_BEHAVED);
+ let mut child = spawn(&host, &["--briefly-secs", "2", "--never-secs", "1"]);
+ wait_until("the host to listen", || host.socket.exists());
+ let (session, _notices) = session(&host);
+ let shell = info(&session, "shell");
+ assert_eq!(
+ (shell.background, shell.background_default),
+ (api::Background::Briefly, api::Background::Briefly)
+ );
+
+ let first = pid(call(&session, "shell", json!({"op": "pid"})));
+ assert_eq!(info(&session, "shell").state, State::Running);
+ wait_until("the unused plugin to stop", || {
+ info(&session, "shell").state == State::Idle
+ });
+ // Used again, it starts again.
+ assert_ne!(pid(call(&session, "shell", json!({"op": "pid"}))), first);
+
+ assert_eq!(
+ set_background(&session, "shell", Some(api::Background::Never)),
+ Ok(Value::Null)
+ );
+ let shell = info(&session, "shell");
+ assert_eq!(
+ (shell.background, shell.background_default),
+ (api::Background::Never, api::Background::Briefly),
+ "the user's choice, shown against the manifest's"
+ );
+ wait_until("it to stop sooner", || {
+ info(&session, "shell").state == State::Idle
+ });
+ assert_eq!(set_background(&session, "shell", None), Ok(Value::Null));
+ assert_eq!(info(&session, "shell").background, api::Background::Briefly);
+ assert!(set_background(&session, "snippets", Some(api::Background::Never)).is_err());
+ assert!(set_background(&session, "nothing", None).is_err());
+ drop(session);
+ stop(&host);
+ wait_until("the host to quit", || child.try_wait().unwrap().is_some());
+ }
+
+ #[test]
+ fn a_call_never_answered_stops_counting_as_a_use_in_time() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ install_script(&host, WELL_BEHAVED);
+ let mut child = spawn(&host, &["--never-secs", "1", "--pending-secs", "2"]);
+ wait_until("the host to listen", || host.socket.exists());
+ let (session, _notices) = session(&host);
+ set_background(&session, "shell", Some(api::Background::Never)).unwrap();
+ // The client gives up at once; the host keeps the call waiting,
+ // and no other call comes after it.
+ session.call_within(
+ "shell",
+ json!({"op": "hang"}),
+ Duration::from_millis(100),
+ |_| {},
+ );
+ wait_until("it to start", || {
+ info(&session, "shell").state == State::Running
+ });
+ std::thread::sleep(Duration::from_millis(1500));
+ assert_eq!(
+ info(&session, "shell").state,
+ State::Running,
+ "used while the call waits"
+ );
+ wait_until("it to stop unused once the call is let go of", || {
+ info(&session, "shell").state == State::Idle
+ });
+ drop(session);
+ stop(&host);
+ wait_until("the host to quit", || child.try_wait().unwrap().is_some());
+ }
+
+ #[test]
+ fn a_plugin_that_runs_always_runs_while_thinkterm_keeps_the_host() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ let program = install_script(&host, WELL_BEHAVED);
+ let manifest = program.with_file_name("plugin.toml");
+ let text = std::fs::read_to_string(&manifest).unwrap();
+ std::fs::write(
+ &manifest,
+ text.replace(
+ "program = \"plugin.sh\"",
+ "program = \"plugin.sh\"\nbackground = \"always\"",
+ ),
+ )
+ .unwrap();
+ let mut child = spawn(&host, &["--briefly-secs", "1"]);
+ wait_until("the host to listen", || host.socket.exists());
+ let (session, _notices) = session(&host);
+ let shell = info(&session, "shell");
+ assert_eq!(shell.background_default, api::Background::Always);
+ assert_eq!(shell.state, State::Idle, "nothing keeps ThinkTerm up yet");
+ // Where ThinkTerm looks to know it is to keep the host up.
+ let always = thinkterm_plugin_channel::paths::always_in(&host.data_dir);
+ assert_eq!(std::fs::read_to_string(&always).unwrap(), "shell\n");
+
+ // ThinkTerm running on the machine connects, and says so.
+ let mut keeper = host.connect().unwrap();
+ keeper
+ .send(&ToHost::Call {
+ id: 1,
+ plugin: api::PLUGIN.into(),
+ body: json!({"op": "keep"}),
+ })
+ .unwrap();
+ wait_until("it to start by itself", || {
+ info(&session, "shell").state == State::Running
+ });
+ let first = pid(call(&session, "shell", json!({"op": "pid"})));
+ std::thread::sleep(Duration::from_millis(1500));
+ assert_eq!(
+ info(&session, "shell").state,
+ State::Running,
+ "unused, and kept"
+ );
+
+ // Stopped by itself, it is started again after a pause.
+ let why = call(&session, "shell", json!({"op": "crash"})).unwrap_err();
+ assert!(why.contains("exited with status 3"), "{why}");
+ wait_until("it to start again", || {
+ info(&session, "shell").state == State::Running
+ });
+ assert_ne!(pid(call(&session, "shell", json!({"op": "pid"}))), first);
+
+ // Once ThinkTerm is gone, it runs as the others do.
+ keeper.shutdown();
+ drop(keeper);
+ wait_until("it to stop unused", || {
+ info(&session, "shell").state == State::Idle
+ });
+ set_background(&session, "shell", Some(api::Background::Briefly)).unwrap();
+ assert!(
+ !always.exists(),
+ "none runs always: nothing to keep the host up for"
+ );
+ drop(session);
+ stop(&host);
+ wait_until("the host to quit", || child.try_wait().unwrap().is_some());
+ }
+
+ #[test]
+ fn a_plugin_installed_to_run_always_is_found_when_thinkterm_keeps_again() {
+ let dir = tempfile::tempdir().unwrap();
+ let host = host_in(dir.path());
+ let mut child = spawn(&host, &[]);
+ wait_until("the host to listen", || host.socket.exists());
+ let keep = |keeper: &mut thinkterm_plugin_channel::client::Connection| {
+ keeper
+ .send(&ToHost::Call {
+ id: 1,
+ plugin: api::PLUGIN.into(),
+ body: json!({"op": "keep"}),
+ })
+ .unwrap();
+ };
+ let mut keeper = host.connect().unwrap();
+ keep(&mut keeper);
+ let always = thinkterm_plugin_channel::paths::always_in(&host.data_dir);
+
+ // Installed while the host runs, and nothing asked for the list.
+ let program = install_script(&host, WELL_BEHAVED);
+ let manifest = program.with_file_name("plugin.toml");
+ let text = std::fs::read_to_string(&manifest).unwrap();
+ std::fs::write(
+ &manifest,
+ text.replace(
+ "program = \"plugin.sh\"",
+ "program = \"plugin.sh\"\nbackground = \"always\"",
+ ),
+ )
+ .unwrap();
+ keep(&mut keeper);
+ wait_until("it to be marked", || {
+ std::fs::read_to_string(&always).is_ok_and(|ids| ids == "shell\n")
+ });
+ let (session, _notices) = session(&host);
+ wait_until("it to start by itself", || {
+ info(&session, "shell").state == State::Running
+ });
+ drop(session);
+ keeper.shutdown();
+ drop(keeper);
+ stop(&host);
+ wait_until("the host to quit", || child.try_wait().unwrap().is_some());
+ }
+
#[test]
fn a_plugin_that_never_says_it_is_ready_is_given_up_on() {
let dir = tempfile::tempdir().unwrap();