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 the diff and stocks plugins

RoversX64cfe7b2ed9a
diff --git a/Cargo.lock b/Cargo.lock
index 96e5dcc2..50c0da78 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8590,6 +8590,15 @@ dependencies = [
"wezterm-uds",
]
+[[package]]
+name = "thinkterm-plugin-diff"
+version = "0.1.0"
+dependencies = [
+ "tempfile",
+ "thinkterm-plugin-sdk",
+ "unicode-width",
+]
+
[[package]]
name = "thinkterm-plugin-example"
version = "0.1.0"
@@ -8637,6 +8646,16 @@ dependencies = [
"wezterm-uds",
]
+[[package]]
+name = "thinkterm-plugin-stocks"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "http_req",
+ "serde_json",
+ "thinkterm-plugin-sdk",
+]
+
[[package]]
name = "thinkterm-proto"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 9e54c825..213a906a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,7 +18,9 @@ members = [
"thinkterm-plugin-panel",
"thinkterm-plugin-sdk",
"thinkterm-plugin-server",
+ "plugins/diff",
"plugins/example",
+ "plugins/stocks",
"thinkterm-session",
"thinkterm-snippets",
"thinkterm-web",
diff --git a/plugins/diff/Cargo.toml b/plugins/diff/Cargo.toml
new file mode 100644
index 00000000..c4b254f1
--- /dev/null
+++ b/plugins/diff/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "thinkterm-plugin-diff"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# A ThinkTerm plugin with a panel: the changes in the git repository of the
+# terminal beside it, shown the way GitHub Desktop shows them. Its
+# dependencies name their versions rather than the workspace's, so the
+# directory builds on its own once the SDK path below points at a checkout
+# of ThinkTerm.
+
+[dependencies]
+thinkterm-plugin-sdk = { path = "../../thinkterm-plugin-sdk" }
+unicode-width = "0.2"
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/plugins/diff/plugin.toml b/plugins/diff/plugin.toml
new file mode 100644
index 00000000..0f8a3a47
--- /dev/null
+++ b/plugins/diff/plugin.toml
@@ -0,0 +1,32 @@
+# The manifest ThinkTerm reads to find this plugin and its program.
+# docs/thinkterm/plugins.md describes every key.
+id = "diff"
+name = "Diff"
+version = "0.1.0"
+description = "Shows the changes in the git repository of the terminal beside it, the way GitHub Desktop does."
+api = 2
+
+[run]
+program = "thinkterm-plugin-diff"
+
+[run.windows]
+program = "thinkterm-plugin-diff.exe"
+
+[panel]
+icon = "git-compare"
+
+[locales.zh-CN]
+name = "Diff"
+description = "照 GitHub Desktop 的样子,显示旁边终端所在 git 仓库里的改动。"
+
+[locales.ja-JP]
+name = "Diff"
+description = "隣のターミナルがいる git リポジトリの変更を、GitHub Desktop のように表示します。"
+
+[locales.de-DE]
+name = "Diff"
+description = "Zeigt die Änderungen im git-Repository des Terminals daneben, wie GitHub Desktop."
+
+[locales.fr-FR]
+name = "Diff"
+description = "Montre les modifications du dépôt git du terminal voisin, comme GitHub Desktop."
diff --git a/plugins/diff/src/git.rs b/plugins/diff/src/git.rs
new file mode 100644
index 00000000..ded7378c
--- /dev/null
+++ b/plugins/diff/src/git.rs
@@ -0,0 +1,1260 @@
+//! What git says about a directory: the repository it is in, the files that
+//! changed there since the last commit, and how each one changed. Read from
+//! git's own output. The programs a repository's configuration can name --
+//! an fsmonitor, an external diff, a text converter -- are not run for it.
+//!
+//! Git runs, and the files are read, on the machine the directory is on
+//! ([`Machine`]): this one, or another that ThinkTerm reaches for the
+//! plugin. Paths are git's, with `/` between names on every system.
+
+use std::collections::{HashMap, HashSet};
+use std::io::{self, Read};
+use std::path::Path;
+use std::process::{Command, Stdio};
+use std::sync::mpsc;
+use std::time::{Duration, SystemTime};
+use unicode_width::UnicodeWidthChar;
+
+/// How long git may take to answer before it is given up on.
+const PATIENCE: Duration = Duration::from_secs(20);
+/// The most of a list git prints that is read.
+const LIST_BYTES: usize = 16 * 1024 * 1024;
+/// The most of one file's diff read: a file changed beyond it is shown in
+/// part.
+pub const DIFF_BYTES: usize = 8 * 1024 * 1024;
+/// The most lines of one file's diff kept.
+pub const DIFF_LINES: usize = 50_000;
+/// The most files listed.
+pub const FILES: usize = 2_000;
+/// The longest line kept, in characters: what a panel draws of one.
+const LINE_CHARS: usize = 2_000;
+/// An untracked file bigger than this is not read to count its lines.
+const COUNT_BYTES: u64 = 256 * 1024;
+/// The most untracked files read in one look to count their lines.
+const COUNT_READS: usize = 200;
+/// Columns from one tab stop to the next.
+const TAB: usize = 4;
+/// What git is run with before what is asked of it: no lock taken, a path a
+/// name and never a pattern, and none of the programs or colours a
+/// repository's configuration can name.
+pub const GIT_OPTIONS: [&str; 8] = [
+ "--no-optional-locks",
+ "--literal-pathspecs",
+ "-c",
+ "core.fsmonitor=false",
+ "-c",
+ "core.quotepath=false",
+ "-c",
+ "color.ui=false",
+];
+
+/// Where git runs and the files are read: this machine, or another.
+pub trait Machine {
+ /// Runs git in `dir` with `args`, keeping at most `limit` bytes of what
+ /// it prints: that, and whether there was more.
+ fn git(&self, dir: &str, args: &[&str], limit: usize) -> Result<(Vec<u8>, bool), Failure>;
+ /// What is at `path`, a link not followed: `None` when nothing is, or it
+ /// cannot be seen.
+ fn stat(&self, path: &str) -> Option<Meta>;
+ /// At most `limit` bytes of the file at `path`, and whether it has more.
+ fn read(&self, path: &str, limit: usize) -> Result<(Vec<u8>, bool), String>;
+ /// Whether each of those is a trip to another machine: then the lines
+ /// of new files are not counted, which would cost one a file every look.
+ fn far(&self) -> bool {
+ false
+ }
+}
+
+/// A file, as [`Machine::stat`] finds it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Meta {
+ pub len: u64,
+ /// When it last changed, as finely as the machine says: a change
+ /// within the second, to a file of the same size, is one too.
+ pub modified: Option<SystemTime>,
+ pub file: bool,
+ /// Where a link points.
+ pub link: Option<String>,
+}
+
+/// This machine: git run here, and the files read from its disks.
+pub struct Here;
+
+impl Machine for Here {
+ fn git(&self, dir: &str, args: &[&str], limit: usize) -> Result<(Vec<u8>, bool), Failure> {
+ git(Path::new(dir), args, limit)
+ }
+
+ fn stat(&self, path: &str) -> Option<Meta> {
+ let meta = std::fs::symlink_metadata(path).ok()?;
+ let link = meta
+ .file_type()
+ .is_symlink()
+ .then(|| std::fs::read_link(path).ok())
+ .flatten()
+ .map(|target| target.to_string_lossy().into_owned());
+ Some(Meta {
+ len: meta.len(),
+ modified: meta.modified().ok(),
+ file: meta.is_file(),
+ link,
+ })
+ }
+
+ fn read(&self, path: &str, limit: usize) -> Result<(Vec<u8>, bool), String> {
+ let failed = |err: io::Error| format!("{path}: {err}");
+ let file = std::fs::File::open(path).map_err(failed)?;
+ let mut bytes = Vec::new();
+ file.take(limit as u64 + 1)
+ .read_to_end(&mut bytes)
+ .map_err(failed)?;
+ let cut = bytes.len() > limit;
+ bytes.truncate(limit);
+ Ok((bytes, cut))
+ }
+}
+
+/// `path`, from the repository's root `root`.
+pub fn joined(root: &str, path: &str) -> String {
+ format!("{}/{path}", root.trim_end_matches('/'))
+}
+
+/// Why git gave no answer.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Failure {
+ /// There is no git to ask.
+ NoGit,
+ /// It ran, and said no.
+ Refused,
+ /// It could not be run, or took too long.
+ Failed(String),
+}
+
+/// A directory, as git sees it.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Found {
+ NoGit,
+ /// It is in no repository.
+ NotRepo,
+ Repo(Snapshot),
+}
+
+/// A repository's changes since its last commit, the working tree's and
+/// the index's alike.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Snapshot {
+ /// As git prints it.
+ pub root: String,
+ /// The branch checked out, or the short name of the commit when none is.
+ pub branch: String,
+ /// The branch has no commit yet: everything in it is new.
+ pub unborn: bool,
+ /// What the changes are counted from: `HEAD`, or the empty tree.
+ pub base: String,
+ pub files: Vec<Change>,
+ /// Files changed beyond those listed.
+ pub more: usize,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Change {
+ /// From the repository's root, `/` between names.
+ pub path: String,
+ /// Where a renamed or copied file was.
+ pub from: Option<String>,
+ pub status: Status,
+ /// Lines gained and lost; `None` for a binary file, or one not counted.
+ pub counts: Option<(u32, u32)>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Status {
+ Added,
+ Modified,
+ Deleted,
+ Renamed,
+ Copied,
+ /// New, and not yet added to the index.
+ Untracked,
+ /// Left in conflict by a merge.
+ Conflicted,
+}
+
+/// One file's changes, a line of the panel each.
+#[derive(Debug, Clone, PartialEq, Default)]
+pub struct FileDiff {
+ pub lines: Vec<Line>,
+ /// The widest line, in columns.
+ pub columns: usize,
+ /// The biggest line number.
+ pub biggest: u32,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Line {
+ pub kind: Kind,
+ pub old: Option<u32>,
+ pub new: Option<u32>,
+ /// With its tabs spread to their stops.
+ pub text: String,
+ /// The part of an edited line that changed, as a range of characters.
+ pub changed: Option<(usize, usize)>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Kind {
+ Hunk,
+ Context,
+ Added,
+ Removed,
+ Note(Note),
+}
+
+/// What a line says about the file instead of showing one of its lines.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Note {
+ Binary,
+ /// The line above ends the file without a newline.
+ NoNewline,
+ /// Only the file's mode changed.
+ Mode,
+ /// Renamed or copied, its content the same.
+ Unchanged,
+ /// The rest is too long to show.
+ Cut,
+ /// It could not be read; the line's text says why.
+ Failed,
+}
+
+/// What `dir` is in, on `machine`: a repository, and its changes. `counted`
+/// keeps the lines of untracked files from one look to the next, so a file
+/// is read again only when it changed; it is left with the files listed
+/// now.
+pub fn look(machine: &dyn Machine, dir: &str, counted: &mut Counted) -> Result<Found, String> {
+ let git = |dir: &str, args: &[&str], limit| machine.git(dir, args, limit);
+ let root = match git(dir, &["rev-parse", "--show-toplevel"], 64 * 1024) {
+ Ok((out, _)) => line_of(&out),
+ Err(Failure::NoGit) => return Ok(Found::NoGit),
+ Err(Failure::Refused) => return Ok(Found::NotRepo),
+ Err(Failure::Failed(why)) => return Err(why),
+ };
+ let unborn = git(&root, &["rev-parse", "--verify", "-q", "HEAD"], 1024).is_err();
+ let base = if unborn {
+ // Everything is new: counted from nothing.
+ let (out, _) = git(&root, &["hash-object", "-t", "tree", "--stdin"], 1024)
+ .map_err(|failure| failure.why())?;
+ line_of(&out)
+ } else {
+ "HEAD".to_string()
+ };
+ let branch = match git(&root, &["symbolic-ref", "--short", "-q", "HEAD"], 1024) {
+ Ok((out, _)) => line_of(&out),
+ Err(_) => git(&root, &["rev-parse", "--short", "HEAD"], 1024)
+ .map(|(out, _)| line_of(&out))
+ .unwrap_or_default(),
+ };
+ let diff = |what: &str| {
+ let args = [
+ "diff",
+ base.as_str(),
+ what,
+ "-z",
+ "-M",
+ "--no-ext-diff",
+ "--no-textconv",
+ ];
+ git(&root, &args, LIST_BYTES).map_err(|failure| failure.why())
+ };
+ let (statuses, _) = diff("--name-status")?;
+ let (counts, _) = diff("--numstat")?;
+ let (unmerged, _) = git(&root, &["ls-files", "--unmerged", "-z"], LIST_BYTES)
+ .map_err(|failure| failure.why())?;
+ let others = ["ls-files", "--others", "--exclude-standard", "-z"];
+ let (untracked, _) = git(&root, &others, LIST_BYTES).map_err(|failure| failure.why())?;
+
+ let mut files = changes(&statuses, &counts, &unmerged);
+ let listed: Vec<String> = split_z(&untracked)
+ .filter(|path| !path.is_empty())
+ .map(|path| path.into_owned())
+ .collect();
+ counted.keep_only(&root, &listed);
+ // A first look at many new files reads a few of them at a time.
+ let mut reads = if machine.far() { 0 } else { COUNT_READS };
+ for path in listed {
+ let counts = counted
+ .lines(machine, &joined(&root, &path), &mut reads)
+ .map(|lines| (lines, 0));
+ files.push(Change {
+ path,
+ from: None,
+ status: Status::Untracked,
+ counts,
+ });
+ }
+ files.sort_by(|a, b| a.path.cmp(&b.path));
+ let more = files.len().saturating_sub(FILES);
+ files.truncate(FILES);
+ Ok(Found::Repo(Snapshot {
+ root,
+ branch,
+ unborn,
+ base,
+ files,
+ more,
+ }))
+}
+
+/// How `change` changed, with its raw form: the same raw form is the same
+/// diff, so a look that finds it again need not read it anew.
+pub fn diff(
+ machine: &dyn Machine,
+ snapshot: &Snapshot,
+ change: &Change,
+) -> Result<(Vec<u8>, bool), String> {
+ if change.status == Status::Untracked {
+ return read_new(machine, &joined(&snapshot.root, &change.path));
+ }
+ let mut args = vec![
+ "diff",
+ snapshot.base.as_str(),
+ "-M",
+ "--no-color",
+ "--no-ext-diff",
+ "--no-textconv",
+ "-U3",
+ "--",
+ change.path.as_str(),
+ ];
+ // A rename is found only with both of its names in the pathspec.
+ if let Some(from) = &change.from {
+ args.push(from);
+ }
+ machine
+ .git(&snapshot.root, &args, DIFF_BYTES)
+ .map_err(|failure| failure.why())
+}
+
+/// The lines of the diff git printed, `cut` when it was longer than was
+/// read; for an untracked file, its content, every line of it new.
+pub fn lines(raw: &[u8], cut: bool, untracked: bool) -> FileDiff {
+ let mut diff = FileDiff::default();
+ if untracked {
+ read_whole(&mut diff, raw);
+ } else {
+ read_unified(&mut diff, raw);
+ }
+ if cut || diff.lines.len() > DIFF_LINES {
+ diff.lines.truncate(DIFF_LINES);
+ diff.lines.push(note(Note::Cut));
+ }
+ mark_changes(&mut diff.lines);
+ diff.columns = diff
+ .lines
+ .iter()
+ .filter(|line| !matches!(line.kind, Kind::Note(_)))
+ .map(|line| columns(&line.text))
+ .max()
+ .unwrap_or(0);
+ diff.biggest = diff
+ .lines
+ .iter()
+ .filter_map(|line| line.old.max(line.new))
+ .max()
+ .unwrap_or(0);
+ diff
+}
+
+/// Lines of untracked files, as last counted: read again only when a
+/// file's size or time changed.
+#[derive(Default)]
+pub struct Counted {
+ files: std::collections::HashMap<String, (u64, Option<SystemTime>, Option<u32>)>,
+}
+
+impl Counted {
+ /// Lines in the file at `path`: none for one too big to read, or
+ /// binary, or when `reads` has run out and it is not counted yet.
+ fn lines(&mut self, machine: &dyn Machine, path: &str, reads: &mut usize) -> Option<u32> {
+ if *reads == 0 && !self.files.contains_key(path) {
+ return None;
+ }
+ let meta = machine.stat(path)?;
+ // A link is where it points, as git keeps it: one line.
+ if meta.link.is_some() {
+ return Some(1);
+ }
+ let stamp = (meta.len, meta.modified);
+ if let Some((len, time, lines)) = self.files.get(path) {
+ if (*len, *time) == stamp {
+ return *lines;
+ }
+ }
+ if *reads == 0 {
+ return None;
+ }
+ *reads -= 1;
+ let lines = (meta.file && meta.len <= COUNT_BYTES)
+ .then(|| machine.read(path, COUNT_BYTES as usize).ok())
+ .flatten()
+ .map(|(bytes, _)| bytes)
+ .filter(|bytes| !binary(bytes))
+ .map(|bytes| count_lines(&bytes));
+ self.files
+ .insert(path.to_string(), (stamp.0, stamp.1, lines));
+ lines
+ }
+
+ /// Lets go of every file but those in `paths`, from `root`.
+ fn keep_only(&mut self, root: &str, paths: &[String]) {
+ let kept: std::collections::HashSet<String> =
+ paths.iter().map(|path| joined(root, path)).collect();
+ self.files.retain(|path, _| kept.contains(path));
+ }
+}
+
+/// Runs git in `dir` with `args`, keeping at most `limit` bytes of what it
+/// prints: that, and whether there was more. Given up on, and ended, when
+/// it takes longer than [`PATIENCE`].
+fn git(dir: &Path, args: &[&str], limit: usize) -> Result<(Vec<u8>, bool), Failure> {
+ let mut command = Command::new("git");
+ command
+ // A path given is a name: `*` or a leading `:` in one is no pattern.
+ .args(GIT_OPTIONS)
+ .arg("-C")
+ .arg(dir)
+ .args(args)
+ .env("GIT_TERMINAL_PROMPT", "0")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ // No console window flashing up for each look.
+ const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+ command.creation_flags(CREATE_NO_WINDOW);
+ }
+ let mut child = command.spawn().map_err(|err| match err.kind() {
+ io::ErrorKind::NotFound => Failure::NoGit,
+ _ => Failure::Failed(format!("git: {err}")),
+ })?;
+ let mut stdout = child.stdout.take().expect("piped above");
+ let (tx, rx) = mpsc::channel();
+ std::thread::spawn(move || {
+ let mut out = Vec::new();
+ let read = (&mut stdout).take(limit as u64 + 1).read_to_end(&mut out);
+ let _ = tx.send(read.map(|_| out));
+ });
+ let out = match rx.recv_timeout(PATIENCE) {
+ Ok(Ok(out)) => out,
+ Ok(Err(err)) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(Failure::Failed(format!("git: {err}")));
+ }
+ Err(_) => {
+ let _ = child.kill();
+ let _ = child.wait();
+ return Err(Failure::Failed("git took too long".into()));
+ }
+ };
+ if out.len() > limit {
+ // What it had left to say is not wanted.
+ let _ = child.kill();
+ let _ = child.wait();
+ let mut out = out;
+ out.truncate(limit);
+ return Ok((out, true));
+ }
+ let status = child
+ .wait()
+ .map_err(|err| Failure::Failed(format!("git: {err}")))?;
+ if status.success() {
+ Ok((out, false))
+ } else {
+ Err(Failure::Refused)
+ }
+}
+
+impl Failure {
+ pub fn why(self) -> String {
+ match self {
+ Failure::NoGit => "git is not installed".into(),
+ Failure::Refused => "git refused".into(),
+ Failure::Failed(why) => why,
+ }
+ }
+}
+
+/// The first line of `out`, without its end.
+fn line_of(out: &[u8]) -> String {
+ String::from_utf8_lossy(out)
+ .lines()
+ .next()
+ .unwrap_or_default()
+ .trim_end()
+ .to_string()
+}
+
+/// The fields of git's `-z` output. A name that is not UTF-8 is still a
+/// field, its odd bytes shown as U+FFFD: dropped, it would pair every name
+/// after it with the wrong status.
+fn split_z(out: &[u8]) -> impl Iterator<Item = std::borrow::Cow<'_, str>> {
+ out.split(|byte| *byte == 0).map(String::from_utf8_lossy)
+}
+
+/// The files `--name-status -z` and `--numstat -z` list, with their counts,
+/// and the index's conflicts, even when their content matches HEAD.
+fn changes(statuses: &[u8], counts: &[u8], unmerged: &[u8]) -> Vec<Change> {
+ let mut files = Vec::new();
+ let mut fields = split_z(statuses).filter(|field| !field.is_empty());
+ while let Some(letter) = fields.next() {
+ let status = match letter.as_bytes().first() {
+ Some(b'A') => Status::Added,
+ Some(b'D') => Status::Deleted,
+ Some(b'R') => Status::Renamed,
+ Some(b'C') => Status::Copied,
+ Some(b'U') => Status::Conflicted,
+ _ => Status::Modified,
+ };
+ let (from, path) = if matches!(status, Status::Renamed | Status::Copied) {
+ let from = fields.next().unwrap_or_default();
+ (Some(from.into_owned()), fields.next().unwrap_or_default())
+ } else {
+ (None, fields.next().unwrap_or_default())
+ };
+ if path.is_empty() {
+ break;
+ }
+ files.push(Change {
+ path: path.into_owned(),
+ from,
+ status,
+ counts: None,
+ });
+ }
+ // "added\tremoved\tpath", or "added\tremoved\t" then the two names of a
+ // rename as fields of their own; "-" for a binary file's counts.
+ let mut by_path: HashMap<_, _> = files
+ .iter_mut()
+ .map(|file| (file.path.as_str(), &mut file.counts))
+ .collect();
+ let mut fields = split_z(counts);
+ while let Some(field) = fields.next() {
+ let mut parts = field.splitn(3, '\t');
+ let (Some(added), Some(removed), Some(path)) = (parts.next(), parts.next(), parts.next())
+ else {
+ continue;
+ };
+ let path = if path.is_empty() {
+ let _from = fields.next();
+ fields.next().unwrap_or_default()
+ } else {
+ std::borrow::Cow::Borrowed(path)
+ };
+ let counts = added.parse().ok().zip(removed.parse().ok());
+ if let Some(found) = by_path.get_mut(path.as_ref()) {
+ **found = counts;
+ }
+ }
+ drop(by_path);
+ // ls-files emits one record per index stage, with the path after the
+ // first tab. A path can itself contain tabs or newlines.
+ let mut conflicts: HashSet<String> = split_z(unmerged)
+ .filter_map(|field| field.split_once('\t').map(|(_, path)| path.to_string()))
+ .collect();
+ for file in &mut files {
+ if conflicts.remove(&file.path) {
+ file.status = Status::Conflicted;
+ }
+ }
+ files.extend(conflicts.into_iter().map(|path| Change {
+ path,
+ from: None,
+ status: Status::Conflicted,
+ counts: None,
+ }));
+ files
+}
+
+/// An untracked file's content, as much as is read of it: for a link, where
+/// it points, as git would keep it, not what it points to.
+fn read_new(machine: &dyn Machine, path: &str) -> Result<(Vec<u8>, bool), String> {
+ let meta = machine
+ .stat(path)
+ .ok_or_else(|| format!("{path}: it is not there"))?;
+ if let Some(target) = meta.link {
+ return Ok((target.into_bytes(), false));
+ }
+ machine.read(path, DIFF_BYTES)
+}
+
+/// A new file's lines, all of them added.
+fn read_whole(diff: &mut FileDiff, raw: &[u8]) {
+ if binary(raw) {
+ diff.lines.push(note(Note::Binary));
+ return;
+ }
+ let text = String::from_utf8_lossy(raw);
+ let count = count_lines(raw);
+ if count == 0 {
+ return;
+ }
+ diff.lines.push(hunk(format!("@@ -0,0 +1,{count} @@")));
+ for (index, text) in text.lines().take(DIFF_LINES).enumerate() {
+ diff.lines.push(Line {
+ kind: Kind::Added,
+ old: None,
+ new: Some(index as u32 + 1),
+ text: shown(text),
+ changed: None,
+ });
+ }
+}
+
+/// The lines of a unified diff: its hunks, their lines, and what the
+/// headers say when there is no hunk.
+fn read_unified(diff: &mut FileDiff, raw: &[u8]) {
+ let text = String::from_utf8_lossy(raw);
+ let (mut old, mut new) = (0u32, 0u32);
+ let (mut hunks, mut binary, mut mode, mut header) = (false, false, false, true);
+ for text in text.lines() {
+ if diff.lines.len() > DIFF_LINES {
+ break;
+ }
+ if let Some(rest) = text.strip_prefix("@@ ") {
+ header = false;
+ hunks = true;
+ let (a, b) = hunk_starts(rest);
+ (old, new) = (a, b);
+ diff.lines.push(hunk(shown(text)));
+ continue;
+ }
+ if header || text.starts_with("diff --git ") {
+ header = true;
+ binary |= text.starts_with("Binary files ") || text == "GIT binary patch";
+ mode |= text.starts_with("old mode ") || text.starts_with("new mode ");
+ continue;
+ }
+ let (kind, body) = match text.as_bytes().first() {
+ Some(b'+') => (Kind::Added, &text[1..]),
+ Some(b'-') => (Kind::Removed, &text[1..]),
+ Some(b' ') => (Kind::Context, &text[1..]),
+ Some(b'\\') => {
+ diff.lines.push(note(Note::NoNewline));
+ continue;
+ }
+ // An empty context line, where the diff dropped the space.
+ None => (Kind::Context, ""),
+ Some(_) => continue,
+ };
+ let (at_old, at_new) = match kind {
+ Kind::Added => {
+ new += 1;
+ (None, Some(new - 1))
+ }
+ Kind::Removed => {
+ old += 1;
+ (Some(old - 1), None)
+ }
+ _ => {
+ old += 1;
+ new += 1;
+ (Some(old - 1), Some(new - 1))
+ }
+ };
+ diff.lines.push(Line {
+ kind,
+ old: at_old,
+ new: at_new,
+ text: shown(body),
+ changed: None,
+ });
+ }
+ if !hunks {
+ let said = if binary {
+ Note::Binary
+ } else if mode {
+ Note::Mode
+ } else {
+ Note::Unchanged
+ };
+ diff.lines.push(note(said));
+ }
+}
+
+/// Where a hunk starts in the old file and in the new: `-12,5 +12,7 @@`.
+fn hunk_starts(rest: &str) -> (u32, u32) {
+ let start = |mark: char| {
+ rest.split(' ')
+ .find_map(|part| part.strip_prefix(mark))
+ .and_then(|range| range.split(',').next())
+ .and_then(|line| line.parse::<u32>().ok())
+ .unwrap_or(0)
+ };
+ (start('-'), start('+'))
+}
+
+/// Marks what differs between each removed line and the added line that
+/// replaced it: what lies between their common start and their common
+/// end, when they have enough in common for that to read as an edit.
+fn mark_changes(lines: &mut [Line]) {
+ let mut at = 0;
+ while at < lines.len() {
+ if lines[at].kind != Kind::Removed {
+ at += 1;
+ continue;
+ }
+ let removed = at;
+ while at < lines.len() && lines[at].kind == Kind::Removed {
+ at += 1;
+ }
+ let added = at;
+ while at < lines.len() && lines[at].kind == Kind::Added {
+ at += 1;
+ }
+ let pairs = (added - removed).min(at - added);
+ for n in 0..pairs {
+ mark_change(lines, removed + n, added + n);
+ }
+ }
+}
+
+fn mark_change(lines: &mut [Line], old: usize, new: usize) {
+ let before: Vec<char> = lines[old].text.chars().collect();
+ let after: Vec<char> = lines[new].text.chars().collect();
+ let start = before
+ .iter()
+ .zip(&after)
+ .take_while(|(a, b)| a == b)
+ .count();
+ let room = before.len().min(after.len()) - start;
+ let end = before
+ .iter()
+ .rev()
+ .zip(after.iter().rev())
+ .take(room)
+ .take_while(|(a, b)| a == b)
+ .count();
+ // Lines with little in common were rewritten, not edited: marking all
+ // of each says nothing.
+ let longest = before.len().max(after.len());
+ if (start + end) * 5 < longest * 2 {
+ return;
+ }
+ if start < before.len() - end {
+ lines[old].changed = Some((start, before.len() - end));
+ }
+ if start < after.len() - end {
+ lines[new].changed = Some((start, after.len() - end));
+ }
+}
+
+/// A file whose diff could not be read, for `why`.
+pub fn failed(why: String) -> FileDiff {
+ FileDiff {
+ lines: vec![Line {
+ text: why,
+ ..note(Note::Failed)
+ }],
+ columns: 0,
+ biggest: 0,
+ }
+}
+
+fn hunk(text: String) -> Line {
+ Line {
+ kind: Kind::Hunk,
+ old: None,
+ new: None,
+ text,
+ changed: None,
+ }
+}
+
+fn note(note: Note) -> Line {
+ Line {
+ kind: Kind::Note(note),
+ old: None,
+ new: None,
+ text: String::new(),
+ changed: None,
+ }
+}
+
+/// A line as the panel shows it: tabs spread to their stops, what is not
+/// printable shown as such, and no longer than a panel draws.
+fn shown(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut column = 0;
+ for c in text.trim_end_matches('\r').chars().take(LINE_CHARS) {
+ match c {
+ '\t' => {
+ let stop = TAB - column % TAB;
+ out.extend(std::iter::repeat_n(' ', stop));
+ column += stop;
+ }
+ c if c.is_control() => {
+ out.push('\u{fffd}');
+ column += 1;
+ }
+ c => {
+ out.push(c);
+ column += c.width().unwrap_or(0);
+ }
+ }
+ }
+ out
+}
+
+/// How many columns `text` takes.
+pub fn columns(text: &str) -> usize {
+ text.chars().map(|c| c.width().unwrap_or(0)).sum()
+}
+
+/// A file git would call binary: one with a NUL near its start.
+fn binary(bytes: &[u8]) -> bool {
+ bytes.iter().take(8000).any(|byte| *byte == 0)
+}
+
+fn count_lines(bytes: &[u8]) -> u32 {
+ let newlines = bytes.iter().filter(|byte| **byte == b'\n').count();
+ let unended = bytes.last().is_some_and(|byte| *byte != b'\n');
+ (newlines + usize::from(unended)) as u32
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const DIFF: &str = "diff --git a/src/main.rs b/src/main.rs
+index 1111111..2222222 100644
+--- a/src/main.rs
++++ b/src/main.rs
+@@ -10,4 +10,5 @@ fn main() {
+ let panel = Panel::new();
+- let rows = panel.rows();
++ let rows = panel.visible_rows();
++ rows.sort();
+
+ \tprintln!(\"{rows:?}\");
+\\ No newline at end of file
+";
+
+ #[test]
+ fn a_unified_diff_reads_as_its_lines_with_their_numbers() {
+ let diff = lines(DIFF.as_bytes(), false, false);
+ let kinds: Vec<Kind> = diff.lines.iter().map(|line| line.kind).collect();
+ assert_eq!(
+ kinds,
+ [
+ Kind::Hunk,
+ Kind::Context,
+ Kind::Removed,
+ Kind::Added,
+ Kind::Added,
+ Kind::Context,
+ Kind::Context,
+ Kind::Note(Note::NoNewline),
+ ]
+ );
+ let numbers: Vec<(Option<u32>, Option<u32>)> =
+ diff.lines.iter().map(|line| (line.old, line.new)).collect();
+ assert_eq!(numbers[1], (Some(10), Some(10)));
+ assert_eq!(numbers[2], (Some(11), None));
+ assert_eq!(numbers[3], (None, Some(11)));
+ assert_eq!(numbers[4], (None, Some(12)));
+ assert_eq!(numbers[5], (Some(12), Some(13)), "an empty context line");
+ assert_eq!(
+ diff.lines[6].text, " println!(\"{rows:?}\");",
+ "a tab to its stop"
+ );
+ assert_eq!(diff.biggest, 14);
+ // The edit is marked where it differs -- nothing was taken out of
+ // the old line, `visible_` went into the new -- and the next new
+ // line has nothing to pair with.
+ assert_eq!(diff.lines[2].changed, None);
+ assert_eq!(diff.lines[3].changed, Some((21, 29)));
+ assert_eq!(diff.lines[4].changed, None);
+ }
+
+ #[test]
+ fn a_diff_without_hunks_says_what_changed() {
+ let binary = "diff --git a/logo.png b/logo.png\nindex 1..2 100644\nBinary files a/logo.png and b/logo.png differ\n";
+ assert_eq!(
+ lines(binary.as_bytes(), false, false).lines,
+ [note(Note::Binary)]
+ );
+ let mode = "diff --git a/run.sh b/run.sh\nold mode 100644\nnew mode 100755\n";
+ assert_eq!(
+ lines(mode.as_bytes(), false, false).lines,
+ [note(Note::Mode)]
+ );
+ let renamed =
+ "diff --git a/a.rs b/b.rs\nsimilarity index 100%\nrename from a.rs\nrename to b.rs\n";
+ assert_eq!(
+ lines(renamed.as_bytes(), false, false).lines,
+ [note(Note::Unchanged)]
+ );
+ }
+
+ #[test]
+ fn a_new_file_is_all_added_and_a_long_one_is_cut() {
+ let diff = lines(b"one\r\ntwo\n\x07three", false, true);
+ assert_eq!(diff.lines[0].text, "@@ -0,0 +1,3 @@");
+ let texts: Vec<&str> = diff.lines[1..]
+ .iter()
+ .map(|line| line.text.as_str())
+ .collect();
+ assert_eq!(texts, ["one", "two", "\u{fffd}three"]);
+ assert!(diff.lines[1..].iter().all(|line| line.kind == Kind::Added));
+ assert_eq!(lines(b"\x00\x01", false, true).lines, [note(Note::Binary)]);
+ let cut = lines(b"a\nb\n", true, true);
+ assert_eq!(cut.lines.last(), Some(&note(Note::Cut)));
+ }
+
+ #[test]
+ fn rewritten_lines_are_not_marked_as_edits() {
+ let text = "@@ -1,1 +1,1 @@\n-let frame = view.len();\n+return Ok(());\n";
+ let diff = lines(text.as_bytes(), false, false);
+ assert!(diff.lines.iter().all(|line| line.changed.is_none()));
+ }
+
+ #[test]
+ fn the_lists_git_prints_become_changes_with_counts() {
+ let statuses = b"M\0src/main.rs\0R087\0old/name.rs\0new/name.rs\0A\0logo.png\0";
+ let counts = b"3\t1\tsrc/main.rs\x002\t2\t\0old/name.rs\0new/name.rs\0-\t-\tlogo.png\0";
+ let files = changes(statuses, counts, b"");
+ assert_eq!(files.len(), 3);
+ assert_eq!(files[0].counts, Some((3, 1)));
+ assert_eq!(files[1].status, Status::Renamed);
+ assert_eq!(files[1].from.as_deref(), Some("old/name.rs"));
+ assert_eq!(files[1].path, "new/name.rs");
+ assert_eq!(files[1].counts, Some((2, 2)));
+ assert_eq!((files[2].status, files[2].counts), (Status::Added, None));
+
+ // A name that is not UTF-8 keeps its place, and every name after it.
+ let statuses = b"M\0caf\xe9.txt\0M\0src/a.rs\0";
+ let counts = b"1\t0\tcaf\xe9.txt\x002\t0\tsrc/a.rs\0";
+ let files = changes(statuses, counts, b"");
+ let paths: Vec<&str> = files.iter().map(|file| file.path.as_str()).collect();
+ assert_eq!(paths, ["caf\u{fffd}.txt", "src/a.rs"]);
+ assert_eq!(files[1].counts, Some((2, 0)));
+ }
+
+ #[test]
+ fn a_line_shows_wide_characters_as_two_columns() {
+ assert_eq!(columns("中文ab"), 6);
+ assert_eq!(shown("a\tb"), "a b");
+ assert_eq!(shown("ab\tc"), "ab c");
+ }
+
+ #[test]
+ fn conflicts_keep_their_paths_and_counts_without_repeating_stages() {
+ let files = changes(
+ b"M\0a\tb\nc.txt\0",
+ b"2\t1\ta\tb\nc.txt\0",
+ b"100644 abc 1\ta\tb\nc.txt\0\
+ 100644 def 2\ta\tb\nc.txt\0\
+ 100644 abc 1\tmissing.txt\0\
+ 100644 def 3\tmissing.txt\0",
+ );
+ assert_eq!(files.len(), 2);
+ assert_eq!(files[0].path, "a\tb\nc.txt");
+ assert_eq!(files[0].status, Status::Conflicted);
+ assert_eq!(files[0].counts, Some((2, 1)));
+ assert_eq!(files[1].path, "missing.txt");
+ assert_eq!(files[1].status, Status::Conflicted);
+ }
+
+ #[test]
+ fn a_large_list_pairs_counts_by_path_in_any_order() {
+ let count = FILES * 2;
+ let statuses: Vec<u8> = (0..count)
+ .flat_map(|n| format!("M\0file-{n:06}.txt\0").into_bytes())
+ .collect();
+ let counts: Vec<u8> = (0..count)
+ .rev()
+ .flat_map(|n| format!("{n}\t1\tfile-{n:06}.txt\0").into_bytes())
+ .collect();
+ let files = changes(&statuses, &counts, b"");
+ assert_eq!(files.len(), count);
+ for (n, file) in files.iter().enumerate() {
+ assert_eq!(file.path, format!("file-{n:06}.txt"));
+ assert_eq!(file.counts, Some((n as u32, 1)));
+ }
+ }
+
+ /// Runs git in `dir` as an example user, with no hooks or signing.
+ fn git_in(dir: &Path, args: &[&str]) -> Option<std::process::Output> {
+ Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args([
+ "-c",
+ "user.name=example",
+ "-c",
+ ])
+ .args([
+ "-c",
+ "commit.gpgsign=false",
+ "-c",
+ "core.hooksPath=/dev/null",
+ ])
+ .args(args)
+ .output()
+ .ok()
+ .filter(|out| out.status.success())
+ }
+
+ /// A repository in a temporary directory, with a commit and changes
+ /// since: when there is a git to make it with.
+ fn repository() -> Option<tempfile::TempDir> {
+ let dir = tempfile::tempdir().ok()?;
+ let run = |args: &[&str]| git_in(dir.path(), args);
+ run(&["init", "-q", "-b", "main"])?;
+ std::fs::write(dir.path().join("kept.txt"), "one\ntwo\nthree\n").ok()?;
+ std::fs::write(dir.path().join("gone.txt"), "bye\n").ok()?;
+ run(&["add", "."])?;
+ run(&["commit", "-q", "-m", "first"])?;
+ std::fs::write(dir.path().join("kept.txt"), "one\n2\nthree\nfour\n").ok()?;
+ std::fs::remove_file(dir.path().join("gone.txt")).ok()?;
+ std::fs::write(dir.path().join("new.txt"), "hello\nworld\n").ok()?;
+ Some(dir)
+ }
+
+ #[test]
+ fn a_repository_is_found_with_its_changes() {
+ let Some(dir) = repository() else {
+ eprintln!("no git here: skipped");
+ return;
+ };
+ let inner = dir.path().join("inside");
+ std::fs::create_dir(&inner).unwrap();
+ let inner = inner.to_str().unwrap();
+ let Ok(Found::Repo(snapshot)) = look(&Here, inner, &mut Counted::default()) else {
+ panic!("not found from a directory inside")
+ };
+ assert_eq!(snapshot.branch, "main");
+ assert!(!snapshot.unborn);
+ let seen: Vec<_> = snapshot
+ .files
+ .iter()
+ .map(|file| (file.path.as_str(), file.status, file.counts))
+ .collect();
+ assert_eq!(
+ seen,
+ [
+ ("gone.txt", Status::Deleted, Some((0, 1))),
+ ("kept.txt", Status::Modified, Some((2, 1))),
+ ("new.txt", Status::Untracked, Some((2, 0))),
+ ]
+ );
+ let (raw, cut) = diff(&Here, &snapshot, &snapshot.files[1]).unwrap();
+ let kept = lines(&raw, cut, false);
+ assert!(kept
+ .lines
+ .iter()
+ .any(|line| line.kind == Kind::Added && line.text == "four"));
+ let (raw, cut) = diff(&Here, &snapshot, &snapshot.files[2]).unwrap();
+ assert_eq!(
+ lines(&raw, cut, true).lines.len(),
+ 3,
+ "a hunk and two lines"
+ );
+
+ let outside = tempfile::tempdir().unwrap();
+ assert_eq!(
+ look(
+ &Here,
+ outside.path().to_str().unwrap(),
+ &mut Counted::default()
+ ),
+ Ok(Found::NotRepo)
+ );
+ }
+
+ #[test]
+ fn a_conflict_stays_listed_until_it_is_staged() {
+ let Some(dir) = repository() else {
+ eprintln!("no git here: skipped");
+ return;
+ };
+ let root = dir.path();
+ git_in(root, &["add", "."]).unwrap();
+ git_in(root, &["commit", "-q", "-m", "base"]).unwrap();
+ git_in(root, &["checkout", "-q", "-b", "other"]).unwrap();
+ std::fs::write(root.join("kept.txt"), "other\n").unwrap();
+ git_in(root, &["commit", "-qam", "other"]).unwrap();
+ git_in(root, &["checkout", "-q", "main"]).unwrap();
+ std::fs::write(root.join("kept.txt"), "ours\n").unwrap();
+ git_in(root, &["commit", "-qam", "ours"]).unwrap();
+ assert!(git_in(root, &["merge", "--no-edit", "other"]).is_none());
+ let listed = || {
+ let Ok(Found::Repo(snapshot)) =
+ look(&Here, root.to_str().unwrap(), &mut Counted::default())
+ else {
+ panic!("no repository")
+ };
+ snapshot.files
+ };
+ let conflicted = || {
+ let files = listed();
+ assert_eq!(files.len(), 1, "one file, not one for each index stage");
+ assert_eq!(files[0].path, "kept.txt");
+ assert_eq!(files[0].status, Status::Conflicted);
+ };
+ conflicted();
+ // The working tree matches HEAD, but the index is still unmerged.
+ std::fs::write(root.join("kept.txt"), "ours\n").unwrap();
+ assert_eq!(
+ git_in(root, &["status", "--porcelain"]).unwrap().stdout,
+ b"UU kept.txt\n"
+ );
+ conflicted();
+ std::fs::remove_file(root.join("kept.txt")).unwrap();
+ conflicted();
+ std::fs::write(root.join("kept.txt"), "ours\n").unwrap();
+ git_in(root, &["add", "kept.txt"]).unwrap();
+ assert!(listed().is_empty());
+ }
+
+ /// A name with a pattern's characters in it is only that name, and a
+ /// new link shows where it points, not what is there.
+ #[cfg(unix)]
+ #[test]
+ fn a_name_is_a_name_and_a_link_is_where_it_points() {
+ let Some(dir) = repository() else {
+ eprintln!("no git here: skipped");
+ return;
+ };
+ let root = dir.path();
+ std::fs::write(root.join("a*.txt"), "star\n").unwrap();
+ std::fs::write(root.join("ab.txt"), "plain\n").unwrap();
+ git_in(root, &["add", "."]).unwrap();
+ git_in(root, &["commit", "-q", "-m", "second"]).unwrap();
+ std::fs::write(root.join("a*.txt"), "star 2\n").unwrap();
+ std::fs::write(root.join("ab.txt"), "plain 2\n").unwrap();
+ let outside = tempfile::tempdir().unwrap();
+ let secret = outside.path().join("secret");
+ std::fs::write(&secret, "not to be shown\n").unwrap();
+ std::os::unix::fs::symlink(&secret, root.join("link")).unwrap();
+
+ let Ok(Found::Repo(snapshot)) =
+ look(&Here, root.to_str().unwrap(), &mut Counted::default())
+ else {
+ panic!("no repository")
+ };
+ let texts = |file: &Change, untracked: bool| -> Vec<String> {
+ let (raw, cut) = diff(&Here, &snapshot, file).unwrap();
+ lines(&raw, cut, untracked)
+ .lines
+ .into_iter()
+ .map(|line| line.text)
+ .collect()
+ };
+ let star = snapshot.files.iter().find(|file| file.path == "a*.txt");
+ let star = texts(star.unwrap(), false);
+ assert!(star.contains(&"star 2".to_string()), "{star:?}");
+ assert!(!star.iter().any(|text| text.contains("plain")), "{star:?}");
+
+ let link = snapshot.files.iter().find(|file| file.path == "link");
+ let link = link.unwrap();
+ assert_eq!(link.counts, Some((1, 0)));
+ let shown = texts(link, true);
+ assert_eq!(shown[1], secret.display().to_string());
+ assert!(!shown.iter().any(|text| text.contains("not to be shown")));
+ }
+
+ /// Another machine, as the plugin sees one: git answers from a table,
+ /// and every stat and read is counted.
+ struct Far {
+ asked: std::cell::RefCell<Vec<String>>,
+ }
+
+ impl Machine for Far {
+ fn git(&self, dir: &str, args: &[&str], _limit: usize) -> Result<(Vec<u8>, bool), Failure> {
+ self.asked
+ .borrow_mut()
+ .push(format!("git {dir} {}", args.join(" ")));
+ let out: &[u8] = match args {
+ ["rev-parse", "--show-toplevel"] => b"/srv/app\n",
+ ["rev-parse", "--verify", ..] => b"abc\n",
+ ["symbolic-ref", ..] => b"main\n",
+ ["diff", _, "--name-status", ..] => b"",
+ ["diff", _, "--numstat", ..] => b"",
+ ["ls-files", "--unmerged", ..] => b"",
+ ["ls-files", ..] => b"new.txt\0",
+ _ => return Err(Failure::Refused),
+ };
+ Ok((out.to_vec(), false))
+ }
+
+ fn stat(&self, path: &str) -> Option<Meta> {
+ self.asked.borrow_mut().push(format!("stat {path}"));
+ Some(Meta {
+ len: 3,
+ modified: None,
+ file: true,
+ link: None,
+ })
+ }
+
+ fn read(&self, path: &str, _limit: usize) -> Result<(Vec<u8>, bool), String> {
+ self.asked.borrow_mut().push(format!("read {path}"));
+ Ok((b"hi\n".to_vec(), false))
+ }
+
+ fn far(&self) -> bool {
+ true
+ }
+ }
+
+ #[test]
+ fn on_another_machine_new_files_are_listed_but_not_counted() {
+ let far = Far {
+ asked: Default::default(),
+ };
+ let Ok(Found::Repo(snapshot)) = look(&far, "/srv/app/src", &mut Counted::default()) else {
+ panic!("no repository")
+ };
+ assert_eq!(snapshot.root, "/srv/app");
+ assert_eq!(snapshot.files[0].path, "new.txt");
+ assert_eq!(snapshot.files[0].counts, None, "a trip a file, every look");
+ assert!(!far
+ .asked
+ .borrow()
+ .iter()
+ .any(|asked| !asked.starts_with("git")));
+ let (raw, _) = diff(&far, &snapshot, &snapshot.files[0]).unwrap();
+ assert_eq!(raw, b"hi\n");
+ assert_eq!(
+ far.asked.borrow()[far.asked.borrow().len() - 2..],
+ ["stat /srv/app/new.txt", "read /srv/app/new.txt"]
+ );
+ assert_eq!(joined("/", "a"), "/a");
+ }
+
+ #[test]
+ fn a_file_changed_within_the_second_to_the_same_size_is_counted_again() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("new.txt");
+ let path = path.to_str().unwrap();
+ let second = std::time::UNIX_EPOCH + Duration::from_secs(1_790_000_000);
+ let write = |text: &str, at: SystemTime| {
+ std::fs::write(path, text).unwrap();
+ let file = std::fs::File::options().write(true).open(path).unwrap();
+ file.set_modified(at).unwrap();
+ };
+ let mut counted = Counted::default();
+ write("a\nb\n", second);
+ assert_eq!(counted.lines(&Here, path, &mut 1), Some(2));
+ write("abcd", second + Duration::from_millis(300));
+ assert_eq!(
+ counted.lines(&Here, path, &mut 1),
+ Some(1),
+ "not the count from before"
+ );
+ }
+}
diff --git a/plugins/diff/src/main.rs b/plugins/diff/src/main.rs
new file mode 100644
index 00000000..aab86666
--- /dev/null
+++ b/plugins/diff/src/main.rs
@@ -0,0 +1,1175 @@
+//! A ThinkTerm plugin with a panel in the right sidebar: the changes in the
+//! git repository of the terminal beside it since its last commit, shown
+//! the way GitHub Desktop shows them -- the files in the panel, and the
+//! lines of the one picked in its extended view, the wide area beside the
+//! sidebar; or below the files, where a client has no room for one. It
+//! asks git again every two seconds while a panel is on show, and sends a
+//! file's lines only as they are asked for, so a file of ten thousand
+//! changed lines costs what shows. A terminal on another machine has git
+//! asked there, through ThinkTerm's connection to it.
+//!
+//! It draws by hand, with the SDK's items and nothing else.
+//! docs/thinkterm/plugins.md says how to install it.
+
+mod git;
+mod text;
+mod watch;
+
+use git::{Change, FileDiff, Kind, Line, Note, Status};
+use std::collections::hash_map::DefaultHasher;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+use text::Words;
+use thinkterm_plugin_sdk::panel::{
+ Align, Click, Env, Frame, Hit, Input, Item, List, Rect, RowsWanted, Size, Text, Token,
+};
+use thinkterm_plugin_sdk::{Cx, Plugin, View};
+use unicode_width::UnicodeWidthChar;
+use watch::{Dir, Place, Repo, Shared};
+
+/// Room at the panel's sides.
+const PAD: f32 = 12.0;
+/// Room at the extended view's sides, which has more to spare.
+const WIDE_PAD: f32 = 20.0;
+/// A status badge's side.
+const BADGE: f32 = 16.0;
+/// The corners of a file's row where it is picked, or the pointer is over
+/// it.
+const ROW_RADIUS: f32 = 6.0;
+/// Room kept at a list's right edge for its scrollbar.
+const THUMB_ROOM: f32 = 8.0;
+
+struct DiffPanel {
+ shared: Shared,
+}
+
+/// Where things go in a panel of one size, listing `files` rows: the
+/// picked file's lines below them when it shows those itself (`inside`),
+/// the files alone down to its foot when its extended view does.
+struct Layout {
+ width: f32,
+ header: f32,
+ file_row: f32,
+ files_height: f32,
+ /// Room at the file rows' right: for the scrollbar when they scroll.
+ files_room: f32,
+ diff_header_top: f32,
+ diff_header: f32,
+ diff_top: f32,
+}
+
+impl Layout {
+ fn of(env: &Env, files: usize, inside: bool) -> Self {
+ let header = 10.0 + env.title.line + env.small.line + 10.0;
+ let file_row = env.body.line + env.small.line + 12.0;
+ let wanted = files as f32 * file_row;
+ let room = (env.height - header).max(0.0);
+ let files_height = if inside {
+ wanted
+ .min((env.height * 0.38).max(file_row * 3.0))
+ .min(room)
+ } else {
+ room
+ };
+ let diff_header_top = header + files_height + 1.0;
+ let diff_header = env.body.line + 16.0;
+ let diff_top = diff_header_top + diff_header;
+ Self {
+ width: env.width,
+ header,
+ file_row,
+ files_height,
+ files_room: if wanted > files_height {
+ THUMB_ROOM
+ } else {
+ 0.0
+ },
+ diff_header_top,
+ diff_header,
+ diff_top,
+ }
+ }
+}
+
+/// Where a diff's columns go: its two line numbers, the mark, the text --
+/// spaced out more in the extended view (`wide`) than in the panel.
+struct Gutter {
+ advance: f32,
+ row: f32,
+ /// Room at the rows' sides.
+ pad: f32,
+ /// Where the first number's column starts.
+ left: f32,
+ gutter: f32,
+ marker_x: f32,
+ text_x: f32,
+}
+
+impl Gutter {
+ fn of(env: &Env, diff: &FileDiff, wide: bool) -> Self {
+ let advance = env.mono.advance.max(1.0);
+ let digits = diff.biggest.to_string().len().max(3) as f32;
+ let (pad, spare, lead) = if wide {
+ (WIDE_PAD, 12.0, 4.0)
+ } else {
+ (PAD, 8.0, 2.0)
+ };
+ let gutter = digits * advance + spare;
+ let left = pad / 2.0;
+ let marker_x = left + gutter * 2.0;
+ Self {
+ advance,
+ row: env.mono.line + lead,
+ pad,
+ left,
+ gutter,
+ marker_x,
+ text_x: marker_x + advance * 2.0,
+ }
+ }
+
+ /// How wide the rows are: as wide as the widest line, or the view.
+ fn width(&self, diff: &FileDiff, view: f32) -> f32 {
+ (self.text_x + diff.columns as f32 * self.advance + self.pad).max(view)
+ }
+}
+
+impl Plugin for DiffPanel {
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ if view.extended() {
+ return self.draw_extended(view, frame);
+ }
+ let env = &view.env;
+ let words = text::words(&env.locale);
+ let dir = Dir::of(env);
+ // A file's lines go in the extended view when there is one, or
+ // room for one; below the files when there is not.
+ let inside = view.extension.is_none() && !env.can_extend;
+ watch::place(&self.shared, view.id, dir.clone(), inside);
+ let Some(dir) = dir else {
+ say(frame, env, PAD, PAD, words.no_terminal, None);
+ return;
+ };
+ let state = watch::lock(&self.shared);
+ match state.places.get(&dir) {
+ None => say(frame, env, PAD, PAD, words.looking, None),
+ Some(Place::NoGit) => say(frame, env, PAD, PAD, words.no_git, None),
+ Some(Place::NotRepo) => {
+ let dir = dir.to_string();
+ say(frame, env, PAD, PAD, words.not_repo, Some(&dir));
+ }
+ Some(Place::Failed(why)) => say(frame, env, PAD, PAD, words.failed, Some(why)),
+ Some(Place::Repo(repo)) => {
+ frame.extend(state.picked(view.id, repo).is_some());
+ let shown = state.shown(view.id, repo);
+ draw_repo(frame, env, words, &dir, repo, shown, inside);
+ }
+ }
+ }
+
+ fn rows(&mut self, view: &View, wanted: &RowsWanted) -> Vec<Vec<Item>> {
+ let env = &view.env;
+ let words = text::words(&env.locale);
+ let panel = view.panel();
+ let state = watch::lock(&self.shared);
+ let Some(want) = state.views.get(&panel) else {
+ return Vec::new();
+ };
+ let Some(dir) = want.dir.clone() else {
+ return Vec::new();
+ };
+ let Some(Place::Repo(repo)) = state.places.get(&dir) else {
+ return Vec::new();
+ };
+ // What the panel marks and shows the lines of: in its extended
+ // view, only what was picked.
+ let shown = match view.extended() {
+ true => state.picked(panel, repo),
+ false => state.shown(panel, repo),
+ };
+ let (from, to) = (wanted.from as usize, wanted.to as usize);
+ match wanted.list.as_str() {
+ "files" if !view.extended() && wanted.key == files_key(&dir) => {
+ let files = &repo.snapshot.files;
+ let at = Layout::of(env, rows_of(repo), want.inside);
+ (from..to.min(rows_of(repo)))
+ .map(|row| match files.get(row) {
+ Some(file) => {
+ let marked = shown.is_some_and(|shown| shown.path == file.path);
+ file_row(env, &at, file, marked)
+ }
+ None => more_row(&at, words, repo.snapshot.more),
+ })
+ .collect()
+ }
+ "diff" => {
+ let Some(file) = shown.filter(|file| wanted.key == diff_key(&dir, &file.path))
+ else {
+ return Vec::new();
+ };
+ let Some(read) = repo.diffs.get(&file.path) else {
+ return Vec::new();
+ };
+ let diff = Arc::clone(&read.diff);
+ let at = Gutter::of(env, &diff, view.extended());
+ let lines = &diff.lines;
+ lines[from.min(lines.len())..to.min(lines.len())]
+ .iter()
+ .map(|line| diff_row(env, &at, words, line))
+ .collect()
+ }
+ _ => Vec::new(),
+ }
+ }
+
+ fn input(&mut self, view: &View, input: Input, _cx: &mut Cx) {
+ match input {
+ Input::Click(Click { id, .. }) => {
+ if let Some(path) = id.strip_prefix("file:") {
+ watch::pick(&self.shared, view.panel(), Some(path.to_string()));
+ }
+ }
+ // The extended view was closed: the file is put down, and the
+ // panel stops asking for it.
+ Input::Close => watch::pick(&self.shared, view.panel(), None),
+ }
+ }
+
+ fn closed(&mut self, view: &View) {
+ // The panel an extended view leaves keeps what it wants.
+ if !view.extended() {
+ watch::close(&self.shared, view.id);
+ }
+ }
+}
+
+impl DiffPanel {
+ /// The extended view: the lines of the file its panel picked.
+ fn draw_extended(&self, view: &View, frame: &mut Frame) {
+ let env = &view.env;
+ let words = text::words(&env.locale);
+ let panel = view.panel();
+ let state = watch::lock(&self.shared);
+ let Some(dir) = state.views.get(&panel).and_then(|want| want.dir.clone()) else {
+ return;
+ };
+ let Some(Place::Repo(repo)) = state.places.get(&dir) else {
+ return;
+ };
+ // Nothing picked: the panel no longer asks for it, and it goes.
+ if let Some(file) = state.picked(panel, repo) {
+ draw_file(frame, env, words, &dir, repo, file);
+ }
+ }
+}
+
+/// The key of the files list of the panels in `dir`.
+fn files_key(dir: &Dir) -> String {
+ dir.key()
+}
+
+/// The key of the list of `path`'s lines, in `dir`.
+fn diff_key(dir: &Dir, path: &str) -> String {
+ format!("{}\n{path}", dir.key())
+}
+
+/// Rows the files list has: one a file, and one saying how many more there
+/// are when not all are listed.
+fn rows_of(repo: &Repo) -> usize {
+ repo.snapshot.files.len() + usize::from(repo.snapshot.more > 0)
+}
+
+/// The repository's name, branch and changes, and the files: with the
+/// lines of the one `shown` below them, `inside` the panel.
+fn draw_repo(
+ frame: &mut Frame,
+ env: &Env,
+ words: &Words,
+ dir: &Dir,
+ repo: &Repo,
+ shown: Option<&Change>,
+ inside: bool,
+) {
+ let snapshot = &repo.snapshot;
+ let at = Layout::of(env, rows_of(repo), inside);
+ let name = snapshot
+ .root
+ .rsplit('/')
+ .find(|name| !name.is_empty())
+ .unwrap_or(&snapshot.root)
+ .to_string();
+ let (added, removed) = snapshot
+ .files
+ .iter()
+ .filter_map(|file| file.counts)
+ .fold((0, 0), |(a, r), (added, removed)| (a + added, r + removed));
+ let totals = counts_width(env, added, removed) + 8.0;
+ let title = Text::new(
+ PAD,
+ 10.0,
+ at.width - PAD * 2.0 - totals,
+ env.title.line,
+ name,
+ );
+ frame.push(title.size(Size::Title).bold());
+ counts(
+ &mut frame.items,
+ env,
+ added,
+ removed,
+ at.width - PAD,
+ 10.0,
+ env.title.line,
+ );
+ // A repository on another machine says which.
+ let mut about: Vec<String> = dir.host.iter().map(|host| host.name.clone()).collect();
+ about.push(snapshot.branch.clone());
+ if snapshot.unborn {
+ about.push(words.unborn.to_string());
+ }
+ about.push((words.files)(snapshot.files.len() + snapshot.more));
+ let about = Text::new(
+ PAD,
+ 10.0 + env.title.line,
+ at.width - PAD * 2.0,
+ env.small.line,
+ about.join(" \u{00b7} "),
+ );
+ frame.push(about.size(Size::Small).color(Token::TextMuted));
+ if snapshot.files.is_empty() {
+ say(frame, env, PAD, at.header, words.clean, None);
+ return;
+ }
+
+ let version = {
+ let mut hasher = DefaultHasher::new();
+ (repo.revision, shown.map(|file| &file.path), inside).hash(&mut hasher);
+ hasher.finish() as u32
+ };
+ let files = List::new(
+ "files",
+ 0.0,
+ at.header,
+ at.width,
+ at.files_height,
+ rows_of(repo) as u32,
+ at.file_row,
+ files_key(dir),
+ );
+ frame.push(files.version(version));
+ if !inside {
+ return;
+ }
+ frame.push(Rect::new(0.0, at.diff_header_top - 1.0, at.width, 1.0).fill(Token::Border));
+
+ let Some(file) = shown else {
+ return;
+ };
+ let top = at.diff_header_top;
+ frame.push(Rect::new(0.0, top, at.width, at.diff_header).fill(Token::BgRaised));
+ let room = file.counts.map_or(0.0, |(added, removed)| {
+ counts_width(env, added, removed) + 8.0
+ });
+ let path = Text::new(
+ PAD,
+ top,
+ at.width - PAD * 2.0 - room,
+ at.diff_header,
+ &file.path,
+ );
+ frame.push(path.bold());
+ if let Some((added, removed)) = file.counts {
+ counts(
+ &mut frame.items,
+ env,
+ added,
+ removed,
+ at.width - PAD,
+ top,
+ at.diff_header,
+ );
+ }
+ lines(frame, env, words, dir, repo, file, at.diff_top, false);
+}
+
+/// The extended view: the picked file's name, where it is and how much of
+/// it changed, and its lines, with room to spare. The name starts after the
+/// close button ThinkTerm draws at the top left, and lines up with it.
+fn draw_file(frame: &mut Frame, env: &Env, words: &Words, dir: &Dir, repo: &Repo, file: &Change) {
+ let width = env.width;
+ let (folder, name) = split_path(&file.path);
+ let below = match &file.from {
+ Some(from) => format!("{from} \u{2192} {folder}"),
+ None => folder.to_string(),
+ };
+ let (left, top) = match env.close {
+ Some(close) => (
+ close.x + close.size + 10.0,
+ close.y + (close.size - env.title.line) / 2.0,
+ ),
+ None => (WIDE_PAD, 14.0),
+ };
+ let tall = env.title.line
+ + if below.is_empty() {
+ 0.0
+ } else {
+ env.small.line
+ };
+ let clear = env.close.map_or(0.0, |close| close.y + close.size + 8.0);
+ let head = (top + tall + 12.0).max(clear);
+ let middle = top + env.title.line / 2.0;
+
+ let (letter, color) = status_mark(file.status);
+ let badge = BADGE + 2.0;
+ let badge_y = middle - badge / 2.0;
+ frame.push(
+ Rect::new(left, badge_y, badge, badge)
+ .border(color)
+ .radius(4.0),
+ );
+ let mark = Text::new(left, badge_y, badge, badge, letter)
+ .color(color)
+ .size(Size::Small)
+ .bold();
+ frame.push(mark.align(Align::Center));
+
+ let text_x = left + badge + 12.0;
+ let mut end = width - WIDE_PAD;
+ if let Some((added, removed)) = file.counts {
+ counts(
+ &mut frame.items,
+ env,
+ added,
+ removed,
+ end,
+ top,
+ env.title.line,
+ );
+ end -= counts_width(env, added, removed) + 16.0;
+ }
+ let title = Text::new(text_x, top, end - text_x, env.title.line, name);
+ frame.push(title.size(Size::Title).bold());
+ if !below.is_empty() {
+ let below = Text::new(
+ text_x,
+ top + env.title.line,
+ width - WIDE_PAD - text_x,
+ env.small.line,
+ below,
+ );
+ frame.push(below.size(Size::Small).color(Token::TextMuted));
+ }
+ frame.push(Rect::new(0.0, head - 1.0, width, 1.0).fill(Token::Border));
+ lines(frame, env, words, dir, repo, file, head, true);
+}
+
+/// `file`'s lines, from `top` to the foot of the view: laid out `wide` in
+/// the extended view.
+#[allow(clippy::too_many_arguments)]
+fn lines(
+ frame: &mut Frame,
+ env: &Env,
+ words: &Words,
+ dir: &Dir,
+ repo: &Repo,
+ file: &Change,
+ top: f32,
+ wide: bool,
+) {
+ let pad = if wide { WIDE_PAD } else { PAD };
+ let Some(read) = repo.diffs.get(&file.path) else {
+ say(frame, env, pad, top, words.reading, None);
+ return;
+ };
+ let gutter = Gutter::of(env, &read.diff, wide);
+ let list = List::new(
+ "diff",
+ 0.0,
+ top,
+ env.width,
+ (env.height - top).max(0.0),
+ read.diff.lines.len() as u32,
+ gutter.row,
+ diff_key(dir, &file.path),
+ );
+ let width = gutter.width(&read.diff, env.width);
+ frame.push(list.version(read.version).wide(width, gutter.text_x));
+}
+
+/// A path's folder, empty at the root, and its name.
+fn split_path(path: &str) -> (&str, &str) {
+ path.rsplit_once('/').unwrap_or(("", path))
+}
+
+/// A file's row: its status, name and directory, and how many lines it
+/// gained and lost. The whole row answers a click; the tint under the
+/// pointer and the mark of the one picked sit inside it, rounded alike.
+fn file_row(env: &Env, at: &Layout, file: &Change, picked: bool) -> Vec<Item> {
+ let row = at.file_row;
+ let id = format!("file:{}", file.path);
+ let (left, right) = (PAD / 2.0, at.width - PAD / 2.0 - at.files_room);
+ let (inset, height) = (2.0, row - 4.0);
+ let mut items: Vec<Item> = vec![Hit::new(&id, 0.0, 0.0, at.width, row).into()];
+ let tint = Hit::new(&id, left, inset, right - left, height);
+ items.push(tint.hover(Token::BgHover).radius(ROW_RADIUS).into());
+ if picked {
+ let pick = Rect::new(left, inset, right - left, height);
+ items.push(pick.fill(Token::BgSelected).radius(ROW_RADIUS).into());
+ }
+ let (letter, color) = status_mark(file.status);
+ let badge_y = (row - BADGE) / 2.0;
+ let badge = Rect::new(PAD, badge_y, BADGE, BADGE)
+ .border(color)
+ .radius(4.0);
+ items.push(badge.into());
+ let mark = Text::new(PAD, badge_y, BADGE, BADGE, letter)
+ .color(color)
+ .size(Size::Small)
+ .bold();
+ items.push(mark.align(Align::Center).into());
+
+ let (dir, name) = split_path(&file.path);
+ let text_x = PAD + BADGE + 10.0;
+ let below = match &file.from {
+ Some(from) => format!("{from} \u{2192} {dir}"),
+ None => dir.to_string(),
+ };
+ // A file at the root has no second line: its name sits in the middle.
+ let top = if below.is_empty() {
+ (row - env.body.line) / 2.0
+ } else {
+ (row - env.body.line - env.small.line) / 2.0
+ };
+ let counts_room = file.counts.map_or(0.0, |(added, removed)| {
+ counts_width(env, added, removed) + 8.0
+ });
+ let end = right - PAD / 2.0;
+ items.push(Text::new(text_x, top, end - text_x - counts_room, env.body.line, name).into());
+ if !below.is_empty() {
+ let below = Text::new(
+ text_x,
+ top + env.body.line,
+ end - text_x,
+ env.small.line,
+ below,
+ );
+ items.push(below.size(Size::Small).color(Token::TextMuted).into());
+ }
+ if let Some((added, removed)) = file.counts {
+ counts(&mut items, env, added, removed, end, top, env.body.line);
+ }
+ items
+}
+
+/// The row after the files listed, saying how many more changed.
+fn more_row(at: &Layout, words: &Words, more: usize) -> Vec<Item> {
+ let text = Text::new(
+ PAD,
+ 0.0,
+ at.width - PAD * 2.0,
+ at.file_row,
+ (words.more)(more),
+ );
+ vec![text.color(Token::TextMuted).into()]
+}
+
+/// A line of the diff: the hunk it starts, or a line with its numbers, its
+/// mark and what changed in it. What lies left of the text stays put while
+/// the lines scroll sideways.
+fn diff_row(env: &Env, at: &Gutter, words: &Words, line: &Line) -> Vec<Item> {
+ let width = env.width;
+ let height = at.row;
+ let mut row: Vec<Item> = Vec::new();
+ let marks = match line.kind {
+ Kind::Hunk => {
+ row.push(
+ Rect::new(0.0, 0.0, width, height)
+ .fill(Token::BgRaised)
+ .into(),
+ );
+ let text = Text::new(at.left, 0.0, width - at.pad, height, &line.text);
+ row.push(text.mono().color(Token::TextMuted).into());
+ return row;
+ }
+ Kind::Note(note) => {
+ let (said, x) = match note {
+ Note::NoNewline => (words.no_newline.to_string(), at.text_x),
+ Note::Binary => (words.binary.to_string(), at.pad),
+ Note::Mode => (words.mode.to_string(), at.pad),
+ Note::Unchanged => (words.unchanged.to_string(), at.pad),
+ Note::Cut => (words.cut.to_string(), at.pad),
+ Note::Failed => (format!("{}{}", words.failed, line.text), at.pad),
+ };
+ let text = Text::new(x, 0.0, width - x - at.left, height, said);
+ row.push(text.color(Token::TextFaint).size(Size::Small).into());
+ return row;
+ }
+ Kind::Added => Some((
+ Token::PositiveBg,
+ Token::PositiveBgStrong,
+ "+",
+ Token::Positive,
+ )),
+ Kind::Removed => Some((
+ Token::NegativeBg,
+ Token::NegativeBgStrong,
+ "-",
+ Token::Negative,
+ )),
+ Kind::Context => None,
+ };
+ if let Some((ground, _, _, _)) = marks {
+ row.push(Rect::new(0.0, 0.0, width, height).fill(ground).into());
+ }
+ for (number, x) in [(line.old, at.left), (line.new, at.left + at.gutter)] {
+ if let Some(number) = number {
+ let text = Text::new(x, 0.0, at.gutter - 8.0, height, number.to_string());
+ row.push(
+ text.mono()
+ .color(Token::TextFaint)
+ .align(Align::Right)
+ .into(),
+ );
+ }
+ }
+ let advance = at.advance;
+ if let Some((_, strong, mark, color)) = marks {
+ let mark = Text::new(at.marker_x, 0.0, advance * 2.0, height, mark);
+ row.push(mark.mono().color(color).into());
+ if let Some((start, end)) = line.changed {
+ let left = at.text_x + columns_of(line.text.chars().take(start)) * advance;
+ let right = at.text_x + columns_of(line.text.chars().take(end)) * advance;
+ if right > left {
+ let changed = Rect::new(left, 1.0, right - left, height - 2.0);
+ row.push(changed.fill(strong).radius(2.0).into());
+ }
+ }
+ }
+ if !line.text.is_empty() {
+ let wide = (git::columns(&line.text) + 1) as f32 * advance;
+ let text = Text::new(at.text_x, 0.0, wide, height, &line.text);
+ row.push(text.mono().into());
+ }
+ row
+}
+
+/// A message where the view's content goes, from `top`, `pad` in from its
+/// sides: `said`, broken into lines to fit, and `detail` faint on one line
+/// below.
+fn say(frame: &mut Frame, env: &Env, pad: f32, top: f32, said: &str, detail: Option<&str>) {
+ let room = (env.width - pad * 2.0).max(1.0);
+ let mut y = top + 8.0;
+ for line in wrap(said, room, env.body.size) {
+ let text = Text::new(pad, y, room, env.body.line, line);
+ frame.push(text.color(Token::TextMuted));
+ y += env.body.line;
+ }
+ if let Some(detail) = detail {
+ let text = Text::new(pad, y + 4.0, room, env.small.line, detail);
+ frame.push(text.size(Size::Small).color(Token::TextFaint));
+ }
+}
+
+/// `text` broken into lines no wider than `room`, as wide as a font of
+/// `size` is thought to set them: at spaces, or between two characters a
+/// language writes without them. The panel measures nothing for a plugin,
+/// so a character is taken to be half its size wide, twice that when wide.
+fn wrap(text: &str, room: f32, size: f32) -> Vec<String> {
+ let width = |c: char| match c.width() {
+ Some(2) => size,
+ _ => size * 0.55,
+ };
+ let mut lines = Vec::new();
+ let mut line = String::new();
+ let mut used = 0.0;
+ for piece in pieces(text) {
+ let wide: f32 = piece.chars().map(width).sum();
+ if used + wide > room && !line.trim().is_empty() {
+ lines.push(line.trim_end().to_string());
+ line = String::new();
+ used = 0.0;
+ if piece == " " {
+ continue;
+ }
+ }
+ line.push_str(piece);
+ used += wide;
+ }
+ if !line.trim().is_empty() {
+ lines.push(line.trim_end().to_string());
+ }
+ lines
+}
+
+/// `text` in the pieces a line may break between: words, the spaces
+/// between them, and each wide character on its own.
+fn pieces(text: &str) -> Vec<&str> {
+ let mut pieces = Vec::new();
+ let mut start = 0;
+ for (at, c) in text.char_indices() {
+ if c == ' ' || c.width() == Some(2) {
+ if start < at {
+ pieces.push(&text[start..at]);
+ }
+ pieces.push(&text[at..at + c.len_utf8()]);
+ start = at + c.len_utf8();
+ }
+ }
+ if start < text.len() {
+ pieces.push(&text[start..]);
+ }
+ pieces
+}
+
+fn status_mark(status: Status) -> (&'static str, Token) {
+ match status {
+ Status::Added | Status::Untracked => ("A", Token::Positive),
+ Status::Modified => ("M", Token::Warning),
+ Status::Deleted => ("D", Token::Negative),
+ Status::Renamed => ("R", Token::Accent),
+ Status::Copied => ("C", Token::Accent),
+ Status::Conflicted => ("!", Token::Negative),
+ }
+}
+
+/// "+12 -3" -- either left out when it is naught -- ending at `right`: in
+/// the monospaced font, whose widths are known, so the two can sit side by
+/// side.
+fn counts(
+ items: &mut Vec<Item>,
+ env: &Env,
+ added: u32,
+ removed: u32,
+ right: f32,
+ y: f32,
+ height: f32,
+) {
+ let advance = env.mono.advance;
+ let mut right = right;
+ if removed > 0 || added == 0 {
+ let minus = format!("-{removed}");
+ let width = minus.len() as f32 * advance;
+ let minus = Text::new(right - width, y, width + 1.0, height, minus);
+ items.push(minus.mono().color(Token::Negative).into());
+ right -= width + advance;
+ }
+ if added > 0 {
+ let plus = format!("+{added}");
+ let width = plus.len() as f32 * advance;
+ let plus = Text::new(right - width, y, width + 1.0, height, plus);
+ items.push(plus.mono().color(Token::Positive).into());
+ }
+}
+
+fn counts_width(env: &Env, added: u32, removed: u32) -> f32 {
+ let mut chars = 0;
+ if removed > 0 || added == 0 {
+ chars += format!("-{removed}").len();
+ }
+ if added > 0 {
+ chars += format!("+{added}").len() + usize::from(chars > 0);
+ }
+ chars as f32 * env.mono.advance
+}
+
+/// How many columns `chars` take in the monospaced font.
+fn columns_of(chars: impl Iterator<Item = char>) -> f32 {
+ chars.map(|c| c.width().unwrap_or(0)).sum::<usize>() as f32
+}
+
+fn main() -> std::io::Result<()> {
+ let shared = Shared::default();
+ thinkterm_plugin_sdk::run_with(|emitter| {
+ let fetching = Arc::clone(&shared);
+ let started = std::thread::Builder::new()
+ .name("git".into())
+ .spawn(move || watch::fetch(fetching, emitter));
+ if let Err(err) = started {
+ eprintln!("diff: cannot start looking: {err}");
+ }
+ DiffPanel { shared }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use git::Snapshot;
+ use thinkterm_plugin_sdk::panel::{
+ Button, CloseButton, Drawn, Mods, MonoMetrics, Player, TextMetrics,
+ };
+ use watch::{Read, Want};
+
+ const DIR: &str = "/home/user/project";
+
+ fn env() -> Env {
+ let text = |size, line| TextMetrics { size, line };
+ Env {
+ width: 320.0,
+ height: 800.0,
+ scale: 2.0,
+ dark: true,
+ small: text(11.0, 15.0),
+ body: text(13.0, 18.0),
+ title: text(15.0, 20.0),
+ mono: MonoMetrics {
+ size: 12.0,
+ line: 17.0,
+ advance: 7.0,
+ },
+ locale: "en-US".into(),
+ cwd: Some(DIR.into()),
+ remote: None,
+ can_extend: false,
+ close: None,
+ }
+ }
+
+ fn change(path: &str, status: Status) -> Change {
+ Change {
+ path: path.into(),
+ from: None,
+ status,
+ counts: Some((3, 1)),
+ }
+ }
+
+ /// A panel over a repository with three changed files, the second of
+ /// them ten thousand lines long, one of those far wider than a panel.
+ fn panel() -> DiffPanel {
+ let shared = Shared::default();
+ let mut long = String::from("@@ -1,10000 +1,10000 @@\n");
+ for n in 0..10_000 {
+ let text = if n == 3 {
+ "x".repeat(900)
+ } else {
+ format!("line {n}")
+ };
+ long.push_str(&format!(" {text}\n"));
+ }
+ let files = vec![
+ change("README.md", Status::Modified),
+ change("src/long.rs", Status::Modified),
+ change("src/new.rs", Status::Untracked),
+ ];
+ let diffs = [(
+ "src/long.rs".to_string(),
+ Read::new(git::lines(long.as_bytes(), false, false), 7),
+ )];
+ {
+ let mut state = watch::lock(&shared);
+ state.places.insert(
+ Dir {
+ host: None,
+ path: DIR.into(),
+ },
+ Place::Repo(Repo {
+ snapshot: Snapshot {
+ root: DIR.into(),
+ branch: "main".into(),
+ unborn: false,
+ base: "HEAD".into(),
+ files,
+ more: 0,
+ },
+ revision: 1,
+ diffs: diffs.into_iter().collect(),
+ }),
+ );
+ state.views.insert(1, Want::default());
+ }
+ DiffPanel { shared }
+ }
+
+ fn texts(player: &Player) -> Vec<String> {
+ player
+ .draw()
+ .iter()
+ .filter_map(|draw| match draw.what {
+ Drawn::Text(text) => Some(text.text.clone()),
+ _ => None,
+ })
+ .collect()
+ }
+
+ fn show(panel: &mut DiffPanel, view: &View, player: &mut Player) {
+ let mut frame = Frame::default();
+ panel.draw(view, &mut frame);
+ player.frame(frame);
+ for want in player.wanted() {
+ let rows = panel.rows(view, &want);
+ player.rows(thinkterm_plugin_sdk::panel::Rows {
+ list: want.list.clone(),
+ key: want.key.clone(),
+ version: want.version,
+ layout: want.layout,
+ from: want.from,
+ rows,
+ });
+ }
+ }
+
+ #[test]
+ fn a_panel_with_no_room_beside_it_shows_the_picked_file_below_a_page_at_a_time() {
+ let mut panel = panel();
+ let view = View::new(1, env());
+ let mut player = Player::new(env());
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player);
+ assert!(shown.contains(&"project".to_string()), "{shown:?}");
+ assert!(shown.contains(&"README.md".to_string()));
+ assert!(shown.contains(&"main \u{00b7} 3 changed files".to_string()));
+ assert!(
+ shown.contains(&"Reading the changes…".to_string()),
+ "README.md is not read yet"
+ );
+ assert!(!player.extend(), "nothing picked asks for nothing");
+
+ // Pick the long file by clicking its row, near the right edge.
+ let at = Layout::of(&env(), 3, true);
+ let y = at.header + at.file_row * 1.5;
+ let input = player
+ .click(300.0, y, Button::Left, 1, Mods::default())
+ .expect("the row answers across");
+ panel.input(&view, input, &mut Cx::new());
+ assert_eq!(
+ watch::lock(&panel.shared).views[&1].picked.as_deref(),
+ Some("src/long.rs")
+ );
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player);
+ assert!(shown.contains(&"line 0".to_string()), "{shown:?}");
+ assert!(player.rows_kept() < 1_000, "a page at a time");
+ assert!(
+ player.extend(),
+ "asked for, for a client that has room after all"
+ );
+ }
+
+ #[test]
+ fn a_repository_on_another_machine_says_which_and_is_its_own_place() {
+ let mut panel = panel();
+ let mut far = env();
+ far.cwd = None;
+ far.remote = Some(thinkterm_plugin_sdk::panel::Remote {
+ host: "server-a".into(),
+ machine: "m1".into(),
+ cwd: DIR.into(),
+ });
+ let view = View::new(1, far.clone());
+ let mut player = Player::new(far);
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player);
+ assert_eq!(
+ shown,
+ ["Looking for changes…"],
+ "the same path here is not the same place"
+ );
+ {
+ let mut state = watch::lock(&panel.shared);
+ let here = Dir {
+ host: None,
+ path: DIR.into(),
+ };
+ let Some(Place::Repo(repo)) = state.places.remove(&here) else {
+ panic!("no repository here")
+ };
+ let there = Dir {
+ host: Some(watch::Host {
+ name: "server-a".into(),
+ machine: "m1".into(),
+ }),
+ path: DIR.into(),
+ };
+ state.places.insert(there, Place::Repo(repo));
+ }
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player);
+ assert!(
+ shown.contains(&"server-a \u{00b7} main \u{00b7} 3 changed files".to_string()),
+ "{shown:?}"
+ );
+ }
+
+ #[test]
+ fn long_lines_scroll_sideways_under_still_numbers() {
+ let mut panel = panel();
+ let view = View::new(1, env());
+ let mut player = Player::new(env());
+ show(&mut panel, &view, &mut player);
+ watch::pick(&panel.shared, 1, Some("src/long.rs".into()));
+ show(&mut panel, &view, &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),
+ _ => None,
+ })
+ };
+ let at = Layout::of(&env(), 3, true);
+ let long = "x".repeat(900);
+ let (number, line) = (place(&player, "4").unwrap(), place(&player, &long).unwrap());
+ assert!(
+ player.wheel(100.0, at.diff_top + 20.0, 300.0, 0.0),
+ "across"
+ );
+ assert_eq!(place(&player, "4"), Some(number), "the numbers stay");
+ assert_eq!(place(&player, &long), Some(line - 300.0), "the lines move");
+ assert_eq!(
+ place(&player, "line 0"),
+ None,
+ "a short line went out of sight"
+ );
+ }
+
+ #[test]
+ fn the_hover_and_the_pick_are_one_rounded_shape() {
+ let at = Layout::of(&env(), 3, true);
+ let row = file_row(&env(), &at, &change("a", Status::Added), true);
+ let tint = row.iter().find_map(|item| match item {
+ Item::Hit(hit) if hit.hover.is_some() => Some(hit.clone()),
+ _ => None,
+ });
+ let pick = row.iter().find_map(|item| match item {
+ Item::Rect(rect) if rect.fill == Some(Token::BgSelected.into()) => Some(rect.clone()),
+ _ => None,
+ });
+ let (tint, pick) = (tint.unwrap(), pick.unwrap());
+ assert_eq!(
+ (tint.x, tint.y, tint.w, tint.h, tint.radius),
+ (pick.x, pick.y, pick.w, pick.h, pick.radius)
+ );
+ assert!(pick.x + pick.w <= at.width - PAD / 2.0);
+ }
+
+ #[test]
+ fn a_panel_without_a_terminal_here_says_so() {
+ let mut panel = panel();
+ let mut env = env();
+ env.cwd = None;
+ env.locale = "zh-CN".into();
+ let view = View::new(2, env.clone());
+ let mut player = Player::new(env);
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player).join("");
+ assert!(shown.contains("在本机的终端里打开一个目录"), "{shown}");
+ }
+
+ #[test]
+ fn a_panel_with_room_beside_it_lists_the_files_alone_and_asks_once_one_is_picked() {
+ let mut panel = panel();
+ let env = Env {
+ can_extend: true,
+ ..env()
+ };
+ let view = View::new(1, env.clone());
+ let mut player = Player::new(env.clone());
+ show(&mut panel, &view, &mut player);
+ let shown = texts(&player);
+ assert!(shown.contains(&"README.md".to_string()), "{shown:?}");
+ assert!(
+ !shown.contains(&"Reading the changes…".to_string()),
+ "no lines in the panel"
+ );
+ assert!(!player.extend(), "nothing picked asks for nothing");
+ let at = Layout::of(&env, 3, false);
+ assert_eq!(
+ at.header + at.files_height,
+ env.height,
+ "the files go down to the foot"
+ );
+
+ let y = at.header + at.file_row * 1.5;
+ let input = player
+ .click(100.0, y, Button::Left, 1, Mods::default())
+ .unwrap();
+ panel.input(&view, input, &mut Cx::new());
+ show(&mut panel, &view, &mut player);
+ assert!(player.extend(), "a pick asks for the extended view");
+ assert!(
+ !texts(&player).contains(&"line 0".to_string()),
+ "whose lines go there"
+ );
+ }
+
+ #[test]
+ fn the_extended_view_shows_the_picked_file_with_room_beside_thinkterms_close_button() {
+ let mut panel = panel();
+ let env = Env {
+ can_extend: true,
+ ..env()
+ };
+ let mut view = View::new(1, env.clone());
+ let mut player = Player::new(env.clone());
+ show(&mut panel, &view, &mut player);
+ watch::pick(&panel.shared, 1, Some("src/long.rs".into()));
+ // The client opens the extended view the panel asks for, its close
+ // button at the top left.
+ let close = CloseButton {
+ x: 5.0,
+ y: 2.0,
+ size: 22.0,
+ };
+ let wide = Env {
+ width: 640.0,
+ can_extend: false,
+ close: Some(close),
+ ..env.clone()
+ };
+ let extended = View {
+ extends: Some(1),
+ ..View::new(2, wide.clone())
+ };
+ view.extension = Some(2);
+ show(&mut panel, &view, &mut player);
+ let mut beside = Player::new(wide);
+ show(&mut panel, &extended, &mut beside);
+ let shown = texts(&beside);
+ for text in ["long.rs", "src", "+3", "-1", "line 0"] {
+ assert!(shown.contains(&text.to_string()), "{text}: {shown:?}");
+ }
+ assert!(!texts(&player).contains(&"line 0".to_string()));
+ let number = beside.draw().iter().find_map(|draw| match draw.what {
+ Drawn::Text(text) if text.text == "1" => Some(text.x + draw.dx),
+ _ => None,
+ });
+ assert_eq!(number, Some(WIDE_PAD / 2.0), "further in than the panel's");
+ // The name is beside the button and lined up with it; nothing is
+ // drawn over the button.
+ let name = beside.draw().iter().find_map(|draw| match draw.what {
+ Drawn::Text(text) if text.text == "long.rs" => Some(text.clone()),
+ _ => None,
+ });
+ let name = name.unwrap();
+ assert!(name.x > close.x + close.size);
+ assert_eq!(name.y + name.h / 2.0, close.y + close.size / 2.0);
+ let clear = |x: f32, y: f32| x >= close.x + close.size || y >= close.y + close.size;
+ assert!(beside.draw().iter().all(|draw| match draw.what {
+ Drawn::Rect(rect) => clear(rect.x + draw.dx, rect.y + draw.dy),
+ Drawn::Text(text) => clear(text.x + draw.dx, text.y + draw.dy),
+ _ => true,
+ }));
+
+ // Closed with it: the file is put down, and the panel stops asking.
+ panel.input(&extended, Input::Close, &mut Cx::new());
+ assert_eq!(watch::lock(&panel.shared).views[&1].picked, None);
+ show(&mut panel, &view, &mut player);
+ assert!(!player.extend(), "put down, it is let go");
+ panel.closed(&extended);
+ assert!(
+ watch::lock(&panel.shared).views.contains_key(&1),
+ "the panel keeps what it wants"
+ );
+ }
+
+ #[test]
+ fn a_message_breaks_into_lines_that_fit() {
+ let lines = wrap("Open a folder in a terminal on this computer", 100.0, 10.0);
+ assert!(lines.len() > 2, "{lines:?}");
+ assert!(lines
+ .iter()
+ .all(|line| line.chars().count() as f32 * 5.5 <= 100.0 + 0.01));
+ assert!(lines.iter().all(|line| !line.starts_with(' ')));
+ let chinese = wrap("在本机的终端里打开一个目录", 50.0, 10.0);
+ assert_eq!(chinese[0], "在本机的终");
+ }
+}
diff --git a/plugins/diff/src/text.rs b/plugins/diff/src/text.rs
new file mode 100644
index 00000000..135943f3
--- /dev/null
+++ b/plugins/diff/src/text.rs
@@ -0,0 +1,158 @@
+//! What the panel says, in the languages ThinkTerm speaks: the one it is
+//! told, else English.
+
+pub struct Words {
+ /// There is no terminal on this machine beside the panel.
+ pub no_terminal: &'static str,
+ pub looking: &'static str,
+ pub no_git: &'static str,
+ pub not_repo: &'static str,
+ /// Before why git could not be asked.
+ pub failed: &'static str,
+ pub clean: &'static str,
+ pub unborn: &'static str,
+ pub files: fn(usize) -> String,
+ pub more: fn(usize) -> String,
+ pub reading: &'static str,
+ pub binary: &'static str,
+ pub no_newline: &'static str,
+ pub mode: &'static str,
+ pub unchanged: &'static str,
+ pub cut: &'static str,
+}
+
+/// The words for `locale`, a tag such as `zh-CN`.
+pub fn words(locale: &str) -> &'static Words {
+ let language = locale.split(['-', '_']).next().unwrap_or_default();
+ match language {
+ "zh" => &CHINESE,
+ "ja" => &JAPANESE,
+ "de" => &GERMAN,
+ "fr" => &FRENCH,
+ _ => &ENGLISH,
+ }
+}
+
+static ENGLISH: Words = Words {
+ no_terminal: "Open a folder in a terminal on this computer to see its changes here.",
+ looking: "Looking for changes…",
+ no_git: "git is not installed.",
+ not_repo: "This folder is not in a git repository.",
+ failed: "The changes could not be read: ",
+ clean: "No changes.",
+ unborn: "no commits yet",
+ files: |n| match n {
+ 1 => "1 changed file".into(),
+ n => format!("{n} changed files"),
+ },
+ more: |n| match n {
+ 1 => "and 1 more file".into(),
+ n => format!("and {n} more files"),
+ },
+ reading: "Reading the changes…",
+ binary: "Binary file: not shown.",
+ no_newline: "No newline at end of file",
+ mode: "Only the file's mode changed.",
+ unchanged: "Renamed, without changes.",
+ cut: "Too long: the rest is not shown.",
+};
+
+static CHINESE: Words = Words {
+ no_terminal: "在本机的终端里打开一个目录,这里会显示它的改动。",
+ looking: "正在查看改动…",
+ no_git: "没有找到 git。",
+ not_repo: "这个目录不在 git 仓库里。",
+ failed: "读不到改动:",
+ clean: "没有改动。",
+ unborn: "还没有提交",
+ files: |n| format!("{n} 个文件有改动"),
+ more: |n| format!("还有 {n} 个文件没列出"),
+ reading: "正在读取改动…",
+ binary: "二进制文件,不显示内容。",
+ no_newline: "文件末尾没有换行",
+ mode: "只改了文件权限。",
+ unchanged: "只改了名字,内容没变。",
+ cut: "太长了,后面的不显示。",
+};
+
+static JAPANESE: Words = Words {
+ no_terminal: "このコンピュータのターミナルでフォルダを開くと、その変更がここに表示されます。",
+ looking: "変更を確認しています…",
+ no_git: "git が見つかりません。",
+ not_repo: "このフォルダは git リポジトリにありません。",
+ failed: "変更を読み取れませんでした: ",
+ clean: "変更はありません。",
+ unborn: "まだコミットがありません",
+ files: |n| format!("{n} 個のファイルに変更"),
+ more: |n| format!("ほかに {n} 個のファイル"),
+ reading: "変更を読み込んでいます…",
+ binary: "バイナリファイルのため表示しません。",
+ no_newline: "ファイルの末尾に改行がありません",
+ mode: "ファイルのモードだけが変わりました。",
+ unchanged: "名前だけが変わり、内容は同じです。",
+ cut: "長すぎるため、以降は表示しません。",
+};
+
+static GERMAN: Words = Words {
+ no_terminal: "Öffne einen Ordner in einem Terminal auf diesem Rechner, um hier seine Änderungen zu sehen.",
+ looking: "Änderungen werden gesucht …",
+ no_git: "git wurde nicht gefunden.",
+ not_repo: "Dieser Ordner liegt in keinem git-Repository.",
+ failed: "Die Änderungen konnten nicht gelesen werden: ",
+ clean: "Keine Änderungen.",
+ unborn: "noch keine Commits",
+ files: |n| match n {
+ 1 => "1 geänderte Datei".into(),
+ n => format!("{n} geänderte Dateien"),
+ },
+ more: |n| match n {
+ 1 => "und 1 weitere Datei".into(),
+ n => format!("und {n} weitere Dateien"),
+ },
+ reading: "Änderungen werden gelesen …",
+ binary: "Binärdatei, nicht angezeigt.",
+ no_newline: "Kein Zeilenumbruch am Dateiende",
+ mode: "Nur der Dateimodus wurde geändert.",
+ unchanged: "Umbenannt, ohne Änderungen.",
+ cut: "Zu lang: Der Rest wird nicht angezeigt.",
+};
+
+static FRENCH: Words = Words {
+ no_terminal:
+ "Ouvrez un dossier dans un terminal de cet ordinateur pour voir ici ses modifications.",
+ looking: "Recherche des modifications…",
+ no_git: "git est introuvable.",
+ not_repo: "Ce dossier n'est dans aucun dépôt git.",
+ failed: "Impossible de lire les modifications : ",
+ clean: "Aucune modification.",
+ unborn: "aucun commit",
+ files: |n| match n {
+ 1 => "1 fichier modifié".into(),
+ n => format!("{n} fichiers modifiés"),
+ },
+ more: |n| match n {
+ 1 => "et 1 autre fichier".into(),
+ n => format!("et {n} autres fichiers"),
+ },
+ reading: "Lecture des modifications…",
+ binary: "Fichier binaire, non affiché.",
+ no_newline: "Pas de retour à la ligne en fin de fichier",
+ mode: "Seul le mode du fichier a changé.",
+ unchanged: "Renommé sans modification.",
+ cut: "Trop long : la suite n'est pas affichée.",
+};
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_language_is_found_by_its_tag_and_english_stands_in() {
+ assert_eq!(words("zh-CN").clean, "没有改动。");
+ assert_eq!(words("de_DE").clean, "Keine Änderungen.");
+ assert_eq!(words("").clean, "No changes.");
+ assert_eq!(words("pt-BR").clean, "No changes.");
+ assert_eq!((words("en-US").files)(1), "1 changed file");
+ assert_eq!((words("fr-FR").more)(3), "et 3 autres fichiers");
+ }
+}
diff --git a/plugins/diff/src/watch.rs b/plugins/diff/src/watch.rs
new file mode 100644
index 00000000..259f5f6b
--- /dev/null
+++ b/plugins/diff/src/watch.rs
@@ -0,0 +1,864 @@
+//! The fetcher: git asked, on a thread of its own, about the directories the
+//! panels on show are in -- every [`EVERY`], or less often in a repository
+//! git takes a while over, and at once when a panel comes, moves or picks a
+//! file -- and the panels drawn again when what it says changed. Nothing is
+//! asked while no panel is on show. A directory on another machine is
+//! looked at there, through ThinkTerm ([`There`]).
+
+use crate::git::{
+ self, Change, Counted, Failure, FileDiff, Found, Machine, Meta, Snapshot, Status,
+};
+use std::collections::hash_map::DefaultHasher;
+use std::collections::{BTreeMap, HashMap};
+use std::fmt;
+use std::hash::{Hash, Hasher};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard};
+use std::time::{Duration, Instant};
+use thinkterm_plugin_sdk::panel::{Answer, Ask, Env, Remote};
+use thinkterm_plugin_sdk::Emitter;
+
+/// How often git is asked again while a panel is on show.
+pub const EVERY: Duration = Duration::from_secs(2);
+/// How long ThinkTerm is given to answer for another machine: git's own
+/// patience there, and the trip.
+const ASK_WAIT: Duration = Duration::from_secs(30);
+/// How many directories no panel is in any more keep what was found there.
+const KEPT: usize = 4;
+
+pub type Shared = Arc<(Mutex<State>, Condvar)>;
+
+/// A directory a terminal beside a panel is in: on this machine, or on the
+/// other one `host` is.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Dir {
+ pub host: Option<Host>,
+ pub path: String,
+}
+
+/// Another machine, as ThinkTerm names it: `name` to show, and `machine`
+/// to ask it by, which tells two accounts on one host apart.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub struct Host {
+ pub name: String,
+ pub machine: String,
+}
+
+impl Dir {
+ /// Where the terminal beside a panel of `env` is, if it says.
+ pub fn of(env: &Env) -> Option<Self> {
+ match (&env.cwd, &env.remote) {
+ (Some(cwd), _) => Some(Self {
+ host: None,
+ path: cwd.clone(),
+ }),
+ (None, Some(Remote { host, machine, cwd })) => Some(Self {
+ host: Some(Host {
+ name: host.clone(),
+ machine: machine.clone(),
+ }),
+ path: cwd.clone(),
+ }),
+ (None, None) => None,
+ }
+ }
+
+ /// What the panel's lists here are kept by: one for each place, which
+ /// two accounts on one host are too.
+ pub fn key(&self) -> String {
+ match &self.host {
+ Some(host) => format!("{}:{}", host.machine, self.path),
+ None => self.path.clone(),
+ }
+ }
+}
+
+impl fmt::Display for Dir {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match &self.host {
+ Some(host) => write!(f, "{}:{}", host.name, self.path),
+ None => f.write_str(&self.path),
+ }
+ }
+}
+
+#[derive(Default)]
+pub struct State {
+ /// What each panel on show wants, by its view: its extended view goes
+ /// by the panel's.
+ pub views: HashMap<u64, Want>,
+ /// What was found in each directory a panel is in, and in those in
+ /// [`State::left`].
+ pub places: HashMap<Dir, Place>,
+ /// The directories panels left last, the last last, at most [`KEPT`]:
+ /// what was found there is kept for as long as the program runs, so
+ /// that a panel back in one -- beside another tab's terminal, or shown
+ /// again after the sidebar went to another of its panels or closed --
+ /// shows it at once while it is looked at again, rather than looking
+ /// afresh. The program itself stops once unused for long enough.
+ left: Vec<Dir>,
+ /// The file picked last in each directory of [`State::places`]: a
+ /// panel back in one picks it again.
+ picked_in: HashMap<Dir, String>,
+ /// A look is wanted at once.
+ poked: bool,
+ /// The fetcher was handed something to look at since the last panel
+ /// went: what it keeps for that is still to be let go.
+ looking: bool,
+}
+
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct Want {
+ /// The directory of the terminal beside the panel.
+ pub dir: Option<Dir>,
+ /// The file it picked, from the repository's root: shown in its
+ /// extended view.
+ pub picked: Option<String>,
+ /// It shows a file's lines itself, below the files -- the first file's
+ /// while none is picked -- with no extended view to show them in.
+ pub inside: bool,
+}
+
+pub enum Place {
+ NoGit,
+ NotRepo,
+ Failed(String),
+ Repo(Repo),
+}
+
+pub struct Repo {
+ pub snapshot: Snapshot,
+ /// Changes whenever the files listed do.
+ pub revision: u32,
+ /// The picked files' diffs, by path, as last read.
+ pub diffs: HashMap<String, Read>,
+}
+
+pub struct Read {
+ pub diff: Arc<FileDiff>,
+ /// Changes whenever the diff does.
+ pub version: u32,
+ /// What git printed, hashed: the same again is the same diff.
+ raw: u64,
+}
+
+impl State {
+ /// Lets go of what was found in the directories no panel is in, but for
+ /// the [`KEPT`] left last.
+ fn keep_places(&mut self) {
+ let State {
+ views,
+ places,
+ left,
+ picked_in,
+ ..
+ } = self;
+ let wanted = |dir: &Dir| views.values().any(|want| want.dir.as_ref() == Some(dir));
+ left.retain(|dir| !wanted(dir));
+ for dir in places.keys() {
+ if !wanted(dir) && !left.contains(dir) {
+ left.push(dir.clone());
+ }
+ }
+ let over = left.len().saturating_sub(KEPT);
+ left.drain(..over);
+ places.retain(|dir, _| wanted(dir) || left.contains(dir));
+ picked_in.retain(|dir, _| places.contains_key(dir));
+ }
+
+ /// The file panel `panel` picked in `repo`, while that is changed still.
+ pub fn picked<'a>(&self, panel: u64, repo: &'a Repo) -> Option<&'a Change> {
+ let path = self.views.get(&panel)?.picked.as_ref()?;
+ repo.snapshot.files.iter().find(|file| &file.path == path)
+ }
+
+ /// The file whose lines panel `panel` shows, in itself or its extended
+ /// view: the one it picked, or the first of `repo`'s when it shows
+ /// them itself.
+ pub fn shown<'a>(&self, panel: u64, repo: &'a Repo) -> Option<&'a Change> {
+ let want = self.views.get(&panel)?;
+ let first = want.inside.then(|| repo.snapshot.files.first()).flatten();
+ self.picked(panel, repo).or(first)
+ }
+}
+
+impl Read {
+ #[cfg(test)]
+ pub fn new(diff: FileDiff, version: u32) -> Self {
+ Self {
+ diff: Arc::new(diff),
+ version,
+ raw: 0,
+ }
+ }
+}
+
+pub fn lock(shared: &Shared) -> MutexGuard<'_, State> {
+ shared
+ .0
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+/// Panel `panel` is beside a terminal in `dir`, and shows a file's lines
+/// itself or not: looked at at once when either is news. A panel that
+/// moves picks what was picked last where it is now, if anything was.
+pub fn place(shared: &Shared, panel: u64, dir: Option<Dir>, inside: bool) {
+ let mut state = lock(shared);
+ let State {
+ views, picked_in, ..
+ } = &mut *state;
+ let want = views.entry(panel).or_default();
+ if want.dir != dir || want.inside != inside {
+ let moved = want.dir != dir;
+ if moved {
+ want.picked = dir.as_ref().and_then(|dir| picked_in.get(dir).cloned());
+ }
+ want.dir = dir;
+ want.inside = inside;
+ // The directory left is kept as it is left, in turn.
+ if moved {
+ state.keep_places();
+ }
+ state.poked = true;
+ shared.1.notify_all();
+ }
+}
+
+/// Panel `panel` picked the file at `path`, or put it down: read at once,
+/// and picked again when a panel comes back to the directory.
+pub fn pick(shared: &Shared, panel: u64, path: Option<String>) {
+ let mut state = lock(shared);
+ let State {
+ views,
+ picked_in,
+ poked,
+ ..
+ } = &mut *state;
+ let want = views.entry(panel).or_default();
+ if want.picked != path {
+ if let Some(dir) = &want.dir {
+ match &path {
+ Some(path) => picked_in.insert(dir.clone(), path.clone()),
+ None => picked_in.remove(dir),
+ };
+ }
+ want.picked = path;
+ *poked = true;
+ shared.1.notify_all();
+ }
+}
+
+/// View `view` went: what was found for it alone is let go now, and what
+/// the fetcher keeps for it on its next turn.
+pub fn close(shared: &Shared, view: u64) {
+ let mut state = lock(shared);
+ state.views.remove(&view);
+ state.keep_places();
+ shared.1.notify_all();
+}
+
+/// Another machine, `machine`, reached through ThinkTerm: what is asked of
+/// it goes on panel `view`'s behalf, one of the panels beside a terminal
+/// there.
+pub struct There {
+ pub emitter: Emitter,
+ pub view: u64,
+ pub machine: String,
+}
+
+impl There {
+ fn ask(&self, ask: &Ask) -> Answer {
+ self.emitter.ask(self.view, &self.machine, ask, ASK_WAIT)
+ }
+}
+
+impl Machine for There {
+ fn git(&self, dir: &str, args: &[&str], limit: usize) -> Result<(Vec<u8>, bool), Failure> {
+ let run: Vec<String> = ["env", "GIT_TERMINAL_PROMPT=0", "git"]
+ .iter()
+ .chain(git::GIT_OPTIONS.iter())
+ .chain(["-C", dir].iter())
+ .chain(args)
+ .map(|arg| arg.to_string())
+ .collect();
+ ran(self.ask(&Ask::Run {
+ args: run,
+ cwd: dir.to_string(),
+ limit: limit as u64,
+ }))
+ }
+
+ fn stat(&self, path: &str) -> Option<Meta> {
+ let path = path.to_string();
+ match self.ask(&Ask::Stat { path }) {
+ Answer::Stat { entry: Some(entry) } => Some(Meta {
+ len: entry.len,
+ modified: entry
+ .modified
+ .map(|secs| std::time::UNIX_EPOCH + Duration::from_secs(secs)),
+ file: entry.kind == thinkterm_plugin_sdk::panel::EntryKind::File,
+ link: entry.target,
+ }),
+ _ => None,
+ }
+ }
+
+ fn read(&self, path: &str, limit: usize) -> Result<(Vec<u8>, bool), String> {
+ let path = path.to_string();
+ match self.ask(&Ask::Read {
+ path,
+ limit: limit as u64,
+ }) {
+ Answer::Read { bytes, cut } => Ok((bytes.0, cut)),
+ Answer::Failed { why, .. } => Err(why),
+ other => Err(format!("ThinkTerm answered something else: {other:?}")),
+ }
+ }
+
+ fn far(&self) -> bool {
+ true
+ }
+}
+
+/// What git run through ThinkTerm came to, as git run here comes to it:
+/// what it printed when it answered, and why not when it did not -- 127
+/// being a shell's word for a program it cannot find.
+fn ran(answer: Answer) -> Result<(Vec<u8>, bool), Failure> {
+ match answer {
+ Answer::Ran { out, cut: true, .. } => Ok((out.0, true)),
+ Answer::Ran {
+ status: Some(0),
+ out,
+ ..
+ } => Ok((out.0, false)),
+ Answer::Ran {
+ status: Some(127), ..
+ } => Err(Failure::NoGit),
+ Answer::Ran {
+ status: Some(_), ..
+ } => Err(Failure::Refused),
+ Answer::Ran { status: None, .. } => Err(Failure::Failed("git was stopped".into())),
+ Answer::Failed { why, .. } => Err(Failure::Failed(why)),
+ other => Err(Failure::Failed(format!(
+ "ThinkTerm answered something else: {other:?}"
+ ))),
+ }
+}
+
+/// A place to look at, and the panels there: what each wants of it, and
+/// their views, which what is asked of another machine goes on behalf of.
+struct Job {
+ views: Vec<u64>,
+ wants: Vec<Want>,
+}
+
+/// Looks for as long as the plugin runs, telling the panels to draw anew
+/// whenever something changed.
+pub fn fetch(shared: Shared, emitter: Emitter) {
+ let mut counted: HashMap<Dir, Counted> = HashMap::new();
+ let mut versions = 0u32;
+ let mut wait = EVERY;
+ loop {
+ let jobs = next_jobs(&shared, wait);
+ // What was counted in a directory left last goes with its place.
+ let left = lock(&shared).left.clone();
+ counted.retain(|dir, _| jobs.contains_key(dir) || left.contains(dir));
+ let started = Instant::now();
+ let mut changed = false;
+ for (dir, job) in jobs {
+ let machine: Box<dyn Machine> = match &dir.host {
+ None => Box::new(git::Here),
+ Some(host) => Box::new(There {
+ emitter: emitter.clone(),
+ view: job.views[0],
+ machine: host.machine.clone(),
+ }),
+ };
+ let found = git::look(
+ &*machine,
+ &dir.path,
+ counted.entry(dir.clone()).or_default(),
+ );
+ let place = match found {
+ Ok(Found::NoGit) => Place::NoGit,
+ Ok(Found::NotRepo) => Place::NotRepo,
+ Err(why) => Place::Failed(why),
+ Ok(Found::Repo(snapshot)) => {
+ let diffs = read_diffs(
+ &shared,
+ &*machine,
+ &dir,
+ &snapshot,
+ &job.wants,
+ &mut versions,
+ );
+ Place::Repo(Repo {
+ snapshot,
+ revision: 0,
+ diffs,
+ })
+ }
+ };
+ changed |= settle(&mut lock(&shared), dir, place, &mut versions);
+ }
+ // A repository git takes long over is looked at less often.
+ wait = EVERY.max(started.elapsed() * 4);
+ if changed {
+ emitter.redraw();
+ }
+ }
+}
+
+/// Waits for a panel to want a look, or for `wait` to pass while one is on
+/// show: then what to look at, each directory a panel is in with what the
+/// panels there want of it. The places no panel is in are let go but for
+/// those left last; once the last panel has gone, nothing is to be looked
+/// at, once, so that the fetcher lets go of what it keeps for the others
+/// too, before it waits.
+fn next_jobs(shared: &Shared, wait: Duration) -> BTreeMap<Dir, Job> {
+ let mut state = lock(shared);
+ loop {
+ if state.views.is_empty() {
+ if std::mem::take(&mut state.looking) {
+ state.keep_places();
+ return BTreeMap::new();
+ }
+ state = shared
+ .1
+ .wait(state)
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ continue;
+ }
+ if state.poked {
+ break;
+ }
+ let (next, timeout) = shared
+ .1
+ .wait_timeout(state, wait)
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ state = next;
+ if timeout.timed_out() && !state.views.is_empty() {
+ break;
+ }
+ }
+ state.poked = false;
+ state.looking = true;
+ let mut jobs: BTreeMap<Dir, Job> = BTreeMap::new();
+ for (view, want) in &state.views {
+ if let Some(dir) = &want.dir {
+ let job = jobs.entry(dir.clone()).or_insert_with(|| Job {
+ views: Vec::new(),
+ wants: Vec::new(),
+ });
+ job.views.push(*view);
+ job.wants.push(want.clone());
+ }
+ }
+ state.keep_places();
+ jobs
+}
+
+/// The diffs of the files the panels in `dir` show, as [`State::shown`]
+/// finds them, each read again and parsed only when git prints something
+/// new for it.
+fn read_diffs(
+ shared: &Shared,
+ machine: &dyn Machine,
+ dir: &Dir,
+ snapshot: &Snapshot,
+ wants: &[Want],
+ versions: &mut u32,
+) -> HashMap<String, Read> {
+ let mut shown: Vec<&Change> = Vec::new();
+ for want in wants {
+ let picked = want
+ .picked
+ .as_ref()
+ .and_then(|path| snapshot.files.iter().find(|file| &file.path == path));
+ let first = want.inside.then(|| snapshot.files.first()).flatten();
+ if let Some(file) = picked.or(first) {
+ if !shown.iter().any(|kept| kept.path == file.path) {
+ shown.push(file);
+ }
+ }
+ }
+ let mut diffs = HashMap::new();
+ for file in shown {
+ let raw = git::diff(machine, snapshot, file);
+ let hash = {
+ let mut hasher = DefaultHasher::new();
+ raw.hash(&mut hasher);
+ hasher.finish()
+ };
+ let known = match lock(shared).places.get(dir) {
+ Some(Place::Repo(repo)) => repo
+ .diffs
+ .get(&file.path)
+ .filter(|read| read.raw == hash)
+ .map(|read| (Arc::clone(&read.diff), read.version)),
+ _ => None,
+ };
+ let read = match known {
+ Some((diff, version)) => Read {
+ diff,
+ version,
+ raw: hash,
+ },
+ None => {
+ let diff = match raw {
+ Ok((bytes, cut)) => git::lines(&bytes, cut, file.status == Status::Untracked),
+ Err(why) => git::failed(why),
+ };
+ *versions = versions.wrapping_add(1);
+ Read {
+ diff: Arc::new(diff),
+ version: *versions,
+ raw: hash,
+ }
+ }
+ };
+ diffs.insert(file.path.clone(), read);
+ }
+ diffs
+}
+
+/// Takes in what was found in `dir`; true when it differs from what was.
+fn settle(state: &mut State, dir: Dir, mut place: Place, versions: &mut u32) -> bool {
+ let before = state.places.get(&dir);
+ let changed = match (before, &mut place) {
+ (Some(Place::Repo(before)), Place::Repo(repo)) => {
+ let same_files = before.snapshot == repo.snapshot;
+ repo.revision = if same_files {
+ before.revision
+ } else {
+ *versions = versions.wrapping_add(1);
+ *versions
+ };
+ let same_diffs = before.diffs.len() == repo.diffs.len()
+ && repo.diffs.iter().all(|(path, read)| {
+ before
+ .diffs
+ .get(path)
+ .is_some_and(|old| old.version == read.version)
+ });
+ !same_files || !same_diffs
+ }
+ (_, Place::Repo(repo)) => {
+ *versions = versions.wrapping_add(1);
+ repo.revision = *versions;
+ true
+ }
+ (Some(Place::NoGit), Place::NoGit) | (Some(Place::NotRepo), Place::NotRepo) => false,
+ (Some(Place::Failed(before)), Place::Failed(why)) => before != why,
+ _ => true,
+ };
+ // A directory no panel is in any more is not kept, unless it was left
+ // with what was found there.
+ let wanted = state
+ .views
+ .values()
+ .any(|want| want.dir.as_ref() == Some(&dir));
+ if wanted || state.left.contains(&dir) {
+ state.places.insert(dir, place);
+ }
+ changed
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn here(path: &str) -> Dir {
+ Dir {
+ host: None,
+ path: path.into(),
+ }
+ }
+
+ fn server_a() -> Host {
+ Host {
+ name: "server-a".into(),
+ machine: "m1".into(),
+ }
+ }
+
+ fn snapshot(paths: &[&str]) -> Snapshot {
+ Snapshot {
+ root: "/home/user/project".into(),
+ branch: "main".into(),
+ unborn: false,
+ base: "HEAD".into(),
+ files: paths
+ .iter()
+ .map(|path| Change {
+ path: path.to_string(),
+ from: None,
+ status: Status::Modified,
+ counts: Some((1, 1)),
+ })
+ .collect(),
+ more: 0,
+ }
+ }
+
+ fn repo(paths: &[&str], diffs: &[(&str, u32)]) -> Place {
+ Place::Repo(Repo {
+ snapshot: snapshot(paths),
+ revision: 0,
+ diffs: diffs
+ .iter()
+ .map(|(path, version)| (path.to_string(), Read::new(FileDiff::default(), *version)))
+ .collect(),
+ })
+ }
+
+ #[test]
+ fn what_is_found_again_the_same_changes_nothing() {
+ let dir = here("/home/user/project");
+ let mut state = State::default();
+ state.views.insert(
+ 1,
+ Want {
+ dir: Some(dir.clone()),
+ ..Want::default()
+ },
+ );
+ let mut versions = 0;
+ assert!(settle(
+ &mut state,
+ dir.clone(),
+ repo(&["a"], &[("a", 1)]),
+ &mut versions
+ ));
+ let revision = |state: &State| match state.places.get(&dir) {
+ Some(Place::Repo(repo)) => repo.revision,
+ _ => panic!("no repository"),
+ };
+ let first = revision(&state);
+ assert!(!settle(
+ &mut state,
+ dir.clone(),
+ repo(&["a"], &[("a", 1)]),
+ &mut versions
+ ));
+ assert_eq!(
+ revision(&state),
+ first,
+ "the same files keep their revision"
+ );
+ assert!(settle(
+ &mut state,
+ dir.clone(),
+ repo(&["a"], &[("a", 2)]),
+ &mut versions
+ ));
+ assert_eq!(revision(&state), first, "a file's diff is not the list");
+ assert!(settle(
+ &mut state,
+ dir.clone(),
+ repo(&["a", "b"], &[("a", 2)]),
+ &mut versions
+ ));
+ assert_ne!(revision(&state), first);
+ assert!(settle(
+ &mut state,
+ dir.clone(),
+ Place::NotRepo,
+ &mut versions
+ ));
+ assert!(!settle(
+ &mut state,
+ dir.clone(),
+ Place::NotRepo,
+ &mut versions
+ ));
+ }
+
+ #[test]
+ fn a_panel_shows_the_file_it_picked_while_that_is_changed_still() {
+ let Place::Repo(repo) = repo(&["a", "b"], &[]) else {
+ unreachable!()
+ };
+ let mut state = State::default();
+ let path = |file: Option<&Change>| file.map(|file| file.path.clone());
+ state.views.insert(1, Want::default());
+ assert_eq!(
+ path(state.shown(1, &repo)),
+ None,
+ "none picked, for an extended view to show"
+ );
+ state.views.get_mut(&1).unwrap().inside = true;
+ assert_eq!(
+ path(state.shown(1, &repo)).as_deref(),
+ Some("a"),
+ "the first, in the panel itself"
+ );
+ state.views.get_mut(&1).unwrap().picked = Some("b".into());
+ assert_eq!(path(state.picked(1, &repo)).as_deref(), Some("b"));
+ assert_eq!(path(state.shown(1, &repo)).as_deref(), Some("b"));
+ state.views.get_mut(&1).unwrap().picked = Some("committed".into());
+ assert_eq!(path(state.picked(1, &repo)), None);
+ assert_eq!(path(state.shown(1, &repo)).as_deref(), Some("a"));
+ }
+
+ #[test]
+ fn a_place_no_panel_is_in_is_not_kept() {
+ let mut state = State::default();
+ let mut versions = 0;
+ settle(
+ &mut state,
+ here("/home/user/gone"),
+ Place::NotRepo,
+ &mut versions,
+ );
+ assert!(state.places.is_empty());
+ }
+
+ #[test]
+ fn what_was_found_goes_with_the_panels_it_was_for() {
+ let shared = Shared::default();
+ let (here, there) = (
+ here("/home/user/project"),
+ Dir {
+ host: Some(server_a()),
+ path: "/home/user/project".into(),
+ },
+ );
+ place(&shared, 1, Some(here.clone()), false);
+ place(&shared, 2, Some(there.clone()), false);
+ let jobs = next_jobs(&shared, Duration::ZERO);
+ assert_eq!(jobs.len(), 2, "the same path on two machines is two places");
+ assert_eq!(jobs[&there].views, [2], "asked on the panel's behalf");
+ {
+ let mut state = lock(&shared);
+ state.places.insert(here, Place::NotRepo);
+ state.places.insert(there, Place::NotRepo);
+ }
+ close(&shared, 2);
+ assert_eq!(lock(&shared).places.len(), 2, "kept, left last");
+ assert_eq!(
+ next_jobs(&shared, Duration::ZERO).len(),
+ 1,
+ "and not looked at"
+ );
+ close(&shared, 1);
+ assert!(
+ next_jobs(&shared, Duration::ZERO).is_empty(),
+ "nothing is looked at once the last panel went"
+ );
+ let state = lock(&shared);
+ assert_eq!(state.places.len(), 2, "what was found is kept, though");
+ assert_eq!(state.left.len(), 2);
+ }
+
+ #[test]
+ fn a_panel_shown_again_shows_what_it_showed_with_the_file_it_picked() {
+ let shared = Shared::default();
+ let repo = here("/home/user/project");
+ place(&shared, 1, Some(repo.clone()), false);
+ lock(&shared).places.insert(repo.clone(), Place::NotRepo);
+ pick(&shared, 1, Some("src/main.rs".into()));
+ // Looked at while on show.
+ assert_eq!(next_jobs(&shared, Duration::ZERO).len(), 1);
+ // The sidebar goes to another of its panels, or closes: the view
+ // goes, and the fetcher is let go.
+ close(&shared, 1);
+ assert!(next_jobs(&shared, Duration::ZERO).is_empty());
+ // Shown again, as a new view.
+ place(&shared, 2, Some(repo.clone()), false);
+ let state = lock(&shared);
+ assert!(state.places.contains_key(&repo), "at once");
+ assert_eq!(
+ state.views[&2].picked.as_deref(),
+ Some("src/main.rs"),
+ "with the file it picked"
+ );
+ drop(state);
+ // Put down, it is not picked again.
+ pick(&shared, 2, None);
+ place(&shared, 2, Some(here("/home/user/other")), false);
+ place(&shared, 2, Some(repo), false);
+ assert_eq!(lock(&shared).views[&2].picked, None);
+ }
+
+ #[test]
+ fn a_panel_back_in_a_directory_it_left_shows_what_was_found_there() {
+ let shared = Shared::default();
+ let found = |state: &State, dir: &Dir| state.places.contains_key(dir);
+ // A tab in the repository, another in a directory of it: the
+ // panel follows the terminal from one to the other.
+ let (root, src) = (here("/home/user/project"), here("/home/user/project/src"));
+ place(&shared, 1, Some(root.clone()), false);
+ lock(&shared).places.insert(root.clone(), Place::NotRepo);
+ place(&shared, 1, Some(src.clone()), false);
+ next_jobs(&shared, Duration::ZERO);
+ assert!(found(&lock(&shared), &root), "kept while the panel is away");
+ lock(&shared).places.insert(src.clone(), Place::NotRepo);
+ place(&shared, 1, Some(root.clone()), false);
+ let jobs = next_jobs(&shared, Duration::ZERO);
+ let state = lock(&shared);
+ assert!(found(&state, &root), "there at once, and looked at again");
+ assert!(jobs.contains_key(&root) && !jobs.contains_key(&src));
+ assert!(found(&state, &src), "the one left is kept in turn");
+ drop(state);
+
+ // No more than a few are kept: the one left first goes.
+ for n in 0..KEPT + 1 {
+ let dir = here(&format!("/home/user/other{n}"));
+ place(&shared, 1, Some(dir.clone()), false);
+ lock(&shared).places.insert(dir, Place::NotRepo);
+ }
+ next_jobs(&shared, Duration::ZERO);
+ let state = lock(&shared);
+ assert_eq!(state.left.len(), KEPT);
+ assert!(!found(&state, &root) && !found(&state, &src), "left first");
+ assert_eq!(
+ state.places.len(),
+ KEPT + 1,
+ "those kept, and the one in use"
+ );
+ }
+
+ #[test]
+ fn git_run_elsewhere_comes_to_what_git_run_here_does() {
+ use thinkterm_plugin_sdk::panel::Bytes;
+ let run = |status, cut| Answer::Ran {
+ status,
+ out: Bytes(b"out".to_vec()),
+ cut,
+ };
+ assert_eq!(ran(run(Some(0), false)), Ok((b"out".to_vec(), false)));
+ assert_eq!(
+ ran(run(None, true)),
+ Ok((b"out".to_vec(), true)),
+ "cut short"
+ );
+ assert_eq!(ran(run(Some(127), false)), Err(Failure::NoGit));
+ assert_eq!(ran(run(Some(128), false)), Err(Failure::Refused));
+ assert!(matches!(ran(run(None, false)), Err(Failure::Failed(_))));
+ assert_eq!(
+ ran(Answer::failed("not connected")),
+ Err(Failure::Failed("not connected".into()))
+ );
+ }
+
+ #[test]
+ fn a_terminal_here_or_there_is_a_directory_named_so() {
+ let dir = Dir {
+ host: Some(server_a()),
+ path: "/srv/app".into(),
+ };
+ assert_eq!(dir.to_string(), "server-a:/srv/app");
+ assert_eq!(here("/srv/app").to_string(), "/srv/app");
+ let other_account = Dir {
+ host: Some(Host {
+ machine: "m2".into(),
+ ..server_a()
+ }),
+ path: "/srv/app".into(),
+ };
+ assert_ne!(dir, other_account, "another account on the host");
+ assert_ne!(dir.key(), other_account.key());
+ assert_eq!(dir.to_string(), other_account.to_string(), "shown alike");
+ }
+}
diff --git a/plugins/stocks/Cargo.toml b/plugins/stocks/Cargo.toml
new file mode 100644
index 00000000..2a3b1be6
--- /dev/null
+++ b/plugins/stocks/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "thinkterm-plugin-stocks"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+# An example ThinkTerm plugin with a panel: a watchlist of quotes from Yahoo
+# Finance, and a chart of the one picked. Its dependencies name their
+# versions rather than the workspace's, so the directory builds on its own
+# once the SDK path below points at a checkout of ThinkTerm.
+
+[dependencies]
+anyhow = "1.0"
+http_req = "0.11"
+serde_json = "1.0"
+thinkterm-plugin-sdk = { path = "../../thinkterm-plugin-sdk" }
diff --git a/plugins/stocks/plugin.toml b/plugins/stocks/plugin.toml
new file mode 100644
index 00000000..029fa2fb
--- /dev/null
+++ b/plugins/stocks/plugin.toml
@@ -0,0 +1,32 @@
+# The manifest ThinkTerm reads to find this plugin and its program.
+# docs/thinkterm/plugins.md describes every key.
+id = "stocks"
+name = "Stocks"
+version = "0.1.0"
+description = "A watchlist of quotes from Yahoo Finance, with a chart of the one picked."
+api = 2
+
+[run]
+program = "thinkterm-plugin-stocks"
+
+[run.windows]
+program = "thinkterm-plugin-stocks.exe"
+
+[panel]
+icon = "chart-line"
+
+[locales.zh-CN]
+name = "股票"
+description = "Yahoo Finance 的自选股行情,外加选中那只的走势图。"
+
+[locales.ja-JP]
+name = "株価"
+description = "Yahoo Finance のウォッチリストと、選んだ銘柄のチャート。"
+
+[locales.de-DE]
+name = "Aktien"
+description = "Eine Watchlist mit Kursen von Yahoo Finance und dem Chart der gewählten."
+
+[locales.fr-FR]
+name = "Bourse"
+description = "Une liste de cours de Yahoo Finance, avec le graphique de celui choisi."
diff --git a/plugins/stocks/src/main.rs b/plugins/stocks/src/main.rs
new file mode 100644
index 00000000..c1dc6d92
--- /dev/null
+++ b/plugins/stocks/src/main.rs
@@ -0,0 +1,701 @@
+//! An example ThinkTerm plugin with a panel in the right sidebar: a
+//! watchlist of quotes from Yahoo Finance, each with its day so far, and a
+//! chart of the one picked over the range picked. The quotes are fetched on
+//! a thread of the plugin's own while a panel is on show (`market`), and
+//! the panel is drawn anew as they come.
+//!
+//! The watchlist is kept in the plugin's data directory, one symbol a
+//! line, and changed with calls:
+//! `thinkterm plugin call stocks '{"op":"add","symbol":"TSM"}'`, and
+//! `"remove"` the same way. docs/thinkterm/plugins.md says how to install it.
+
+mod market;
+mod yahoo;
+
+use anyhow::{bail, Context as _};
+use market::{lock, Market, Shared, WATCHLIST_LIMIT};
+use serde_json::{json, Value};
+use std::collections::HashMap;
+use std::sync::{Arc, Condvar, Mutex};
+use thinkterm_plugin_sdk::panel::{
+ Align, Area, Click, Env, Frame, Hit, Input, Item, Line, Rect, Scroll, Size, Text, Token,
+};
+use thinkterm_plugin_sdk::{Cx, Plugin, View};
+use yahoo::{Chart, Day, Range};
+
+/// Room at the panel's sides.
+const PAD: f32 = 12.0;
+/// Where the chart's prices go, to its right.
+const SCALE_WIDTH: f32 = 56.0;
+
+/// What one panel on show has picked.
+#[derive(Clone, Copy)]
+struct Pick {
+ symbol: usize,
+ range: Range,
+}
+
+impl Default for Pick {
+ fn default() -> Self {
+ Self {
+ symbol: 0,
+ range: Range::Day,
+ }
+ }
+}
+
+struct Stocks {
+ market: Shared,
+ picks: HashMap<u64, Pick>,
+}
+
+impl Stocks {
+ /// Tells the fetcher which charts the panels on show have picked.
+ fn want(&self) {
+ let mut market = lock(&self.market);
+ let wanted = self
+ .picks
+ .values()
+ .filter_map(|pick| Some((market.symbols.get(pick.symbol)?.clone(), pick.range)))
+ .collect();
+ market.want(self.picks.len(), wanted);
+ self.market.1.notify_all();
+ }
+
+ fn change_watchlist(&mut self, body: &Value, add: bool) -> anyhow::Result<Value> {
+ let symbol = body["symbol"]
+ .as_str()
+ .map(|symbol| symbol.trim().to_ascii_uppercase())
+ .filter(|symbol| !symbol.is_empty() && symbol.len() <= 24)
+ .context("a \"symbol\" is needed, such as \"TSM\"")?;
+ let removed = {
+ let mut market = lock(&self.market);
+ let known = market.symbols.iter().position(|kept| *kept == symbol);
+ let removed = match (add, known) {
+ (true, Some(_)) | (false, None) => return Ok(json!(market.symbols)),
+ (true, None) if market.symbols.len() >= WATCHLIST_LIMIT => {
+ bail!("the watchlist holds at most {WATCHLIST_LIMIT} symbols")
+ }
+ (true, None) => {
+ market.symbols.push(symbol);
+ None
+ }
+ (false, Some(_)) => market.remove(&symbol),
+ };
+ market.save().context("saving the watchlist")?;
+ removed
+ };
+ // Each panel keeps the symbol it picked; one whose symbol went has
+ // the one after it, or the last.
+ let count = lock(&self.market).symbols.len();
+ for pick in self.picks.values_mut() {
+ if removed.is_some_and(|at| pick.symbol > at) {
+ pick.symbol -= 1;
+ }
+ pick.symbol = pick.symbol.min(count.saturating_sub(1));
+ }
+ self.want();
+ Ok(json!(lock(&self.market).symbols))
+ }
+}
+
+impl Plugin for Stocks {
+ fn call(&mut self, body: Value, cx: &mut Cx) -> anyhow::Result<Value> {
+ let answer = match body["op"].as_str() {
+ Some("list") => return Ok(json!(lock(&self.market).symbols)),
+ Some("add") => self.change_watchlist(&body, true)?,
+ Some("remove") => self.change_watchlist(&body, false)?,
+ _ => bail!("unknown op; this plugin knows \"list\", \"add\" and \"remove\""),
+ };
+ cx.redraw();
+ Ok(answer)
+ }
+
+ fn draw(&mut self, view: &View, frame: &mut Frame) {
+ if let std::collections::hash_map::Entry::Vacant(new) = self.picks.entry(view.id) {
+ new.insert(Pick::default());
+ self.want();
+ }
+ let pick = self.picks[&view.id];
+ let market = lock(&self.market);
+ draw(&market, pick, &view.env, frame);
+ }
+
+ fn input(&mut self, view: &View, input: Input, _cx: &mut Cx) {
+ let Input::Click(Click { id, .. }) = input else {
+ return;
+ };
+ let pick = self.picks.entry(view.id).or_default();
+ if let Some(symbol) = id.strip_prefix("quote:").and_then(|at| at.parse().ok()) {
+ pick.symbol = symbol;
+ } else if let Some(range) = id
+ .strip_prefix("range:")
+ .and_then(|label| Range::ALL.into_iter().find(|range| range.label() == label))
+ {
+ pick.range = range;
+ }
+ self.want();
+ }
+
+ fn closed(&mut self, view: &View) {
+ self.picks.remove(&view.id);
+ self.want();
+ }
+}
+
+/// The whole panel: the watchlist above, the picked symbol's chart below.
+fn draw(market: &Market, pick: Pick, env: &Env, frame: &mut Frame) {
+ let width = env.width;
+ let header = env.title.line + 20.0;
+ frame.push(
+ Text::new(PAD, 10.0, width * 0.5, env.title.line, "Watchlist")
+ .size(Size::Title)
+ .bold(),
+ );
+ let (status, color) = match &market.trouble {
+ Some(trouble) => (trouble.as_str(), Token::Negative),
+ None if market.days.is_empty() => ("Loading\u{2026}", Token::TextMuted),
+ None => ("Yahoo Finance", Token::TextFaint),
+ };
+ let status = Text::new(width * 0.4, 10.0, width * 0.6 - PAD, env.title.line, status);
+ frame.push(status.size(Size::Small).color(color).align(Align::Right));
+
+ let row = env.body.line + env.small.line + 14.0;
+ let count = market.symbols.len();
+ let list_height = (count as f32 * row)
+ .min(env.height * 0.5)
+ .max(row * 2.0)
+ .min((env.height - header).max(0.0));
+ let mut rows = Vec::new();
+ for (index, symbol) in market.symbols.iter().enumerate() {
+ quote_row(
+ &mut rows,
+ market,
+ env,
+ symbol,
+ index,
+ index == pick.symbol,
+ row,
+ );
+ }
+ frame.push(Scroll::new(
+ "quotes",
+ 0.0,
+ header,
+ width,
+ list_height,
+ count as f32 * row,
+ rows,
+ ));
+ let top = header + list_height;
+ frame.push(Rect::new(0.0, top, width, 1.0).fill(Token::Border));
+
+ let Some(symbol) = market.symbols.get(pick.symbol) else {
+ return;
+ };
+ detail(frame, market, env, symbol, pick.range, top + 1.0);
+}
+
+/// One symbol in the watchlist: its name, its day as a line, its price and
+/// how far that moved.
+fn quote_row(
+ items: &mut Vec<Item>,
+ market: &Market,
+ env: &Env,
+ symbol: &str,
+ index: usize,
+ picked: bool,
+ row: f32,
+) {
+ let width = env.width;
+ let y = index as f32 * row;
+ items.push(
+ Hit::new(format!("quote:{index}"), 0.0, y, width, row)
+ .hover(Token::BgHover)
+ .into(),
+ );
+ if picked {
+ let pick = Rect::new(PAD / 2.0, y + 2.0, width - PAD, row - 4.0);
+ items.push(pick.fill(Token::BgSelected).radius(6.0).into());
+ }
+ let top = y + (row - env.body.line - env.small.line) / 2.0;
+ let left = width * 0.36;
+ items.push(
+ Text::new(PAD, top, left - PAD, env.body.line, symbol)
+ .bold()
+ .into(),
+ );
+ let name = market
+ .names
+ .get(symbol)
+ .map(String::as_str)
+ .unwrap_or_default();
+ let name = Text::new(PAD, top + env.body.line, left - PAD, env.small.line, name);
+ items.push(name.size(Size::Small).color(Token::TextMuted).into());
+
+ let Some(day) = market.days.get(symbol) else {
+ return;
+ };
+ let rising = day.price >= day.previous;
+ let spark_left = left + 6.0;
+ let spark_right = width * 0.62;
+ if spark_right > spark_left + 8.0 {
+ let (top, bottom) = (y + 10.0, y + row - 10.0);
+ spark(items, day, spark_left, spark_right, top, bottom, rising);
+ }
+ let price = Text::new(
+ spark_right,
+ top,
+ width - PAD - spark_right,
+ env.body.line,
+ price(day.price),
+ );
+ items.push(price.align(Align::Right).into());
+ let change = percent(day.price, day.previous);
+ let pill_width = change.chars().count() as f32 * env.mono.advance + 10.0;
+ let pill_x = width - PAD - pill_width;
+ let pill_y = top + env.body.line + 1.0;
+ let pill_height = env.small.line;
+ let (ground, color) = if rising {
+ (Token::PositiveBg, Token::Positive)
+ } else {
+ (Token::NegativeBg, Token::Negative)
+ };
+ items.push(
+ Rect::new(pill_x, pill_y, pill_width, pill_height)
+ .fill(ground)
+ .radius(4.0)
+ .into(),
+ );
+ let change = Text::new(pill_x, pill_y, pill_width, pill_height, change);
+ items.push(change.mono().color(color).align(Align::Center).into());
+}
+
+/// The day's prices as a line from `left` to `right`, with where the day
+/// before closed as a faint level.
+fn spark(
+ items: &mut Vec<Item>,
+ day: &Day,
+ left: f32,
+ right: f32,
+ top: f32,
+ bottom: f32,
+ rising: bool,
+) {
+ let prices = &day.closes;
+ if prices.len() < 2 {
+ return;
+ }
+ let (low, high) = prices
+ .iter()
+ .chain([&day.previous])
+ .fold((f64::MAX, f64::MIN), |(low, high), price| {
+ (low.min(*price), high.max(*price))
+ });
+ let span = (high - low).max(f64::EPSILON);
+ let height = bottom - top;
+ let at = |price: f64| top + ((high - price) / span) as f32 * height;
+ let step = (right - left) / (prices.len() - 1) as f32;
+ let points = prices
+ .iter()
+ .enumerate()
+ .flat_map(|(n, price)| [left + n as f32 * step, at(*price)])
+ .collect();
+ let level = at(day.previous);
+ items.push(Line::new(vec![left, level, right, level], Token::TextFaint).into());
+ let color = if rising {
+ Token::Positive
+ } else {
+ Token::Negative
+ };
+ items.push(Line::new(points, color).width(1.5).into());
+}
+
+/// The picked symbol: its name, price and move, the ranges, and its chart.
+fn detail(frame: &mut Frame, market: &Market, env: &Env, symbol: &str, range: Range, top: f32) {
+ let width = env.width;
+ let chart = market.charts.get(&(symbol.to_string(), range));
+ let day = market.days.get(symbol);
+ let mut y = top + 12.0;
+ frame.push(
+ Text::new(PAD, y, width * 0.5, env.title.line, symbol)
+ .size(Size::Title)
+ .bold(),
+ );
+ let name = market
+ .names
+ .get(symbol)
+ .map(String::as_str)
+ .unwrap_or_default();
+ let name = Text::new(width * 0.35, y, width * 0.65 - PAD, env.title.line, name);
+ frame.push(
+ name.size(Size::Small)
+ .color(Token::TextMuted)
+ .align(Align::Right),
+ );
+ y += env.title.line + 4.0;
+
+ let latest = day.map(|day| (day.price, day.previous));
+ let latest = latest.or_else(|| chart.map(|chart| (chart.price, chart.previous)));
+ if let Some((now, before)) = latest {
+ frame.push(Text::new(PAD, y, width * 0.5, env.title.line, price(now)).size(Size::Title));
+ let moved = format!("{} ({})", signed(now - before, now), percent(now, before));
+ let color = if now >= before {
+ Token::Positive
+ } else {
+ Token::Negative
+ };
+ let moved = Text::new(width * 0.4, y, width * 0.6 - PAD, env.title.line, moved);
+ frame.push(moved.color(color).align(Align::Right));
+ }
+ y += env.title.line + 10.0;
+
+ // The ranges, as a row of pills.
+ let gap = 6.0;
+ let count = Range::ALL.len() as f32;
+ let pill = ((width - PAD * 2.0 - gap * (count - 1.0)) / count).max(1.0);
+ let pill_height = env.body.line + 8.0;
+ for (n, choice) in Range::ALL.into_iter().enumerate() {
+ let x = PAD + n as f32 * (pill + gap);
+ frame.push(
+ Hit::new(format!("range:{}", choice.label()), x, y, pill, pill_height)
+ .hover(Token::BgHover),
+ );
+ let shape = Rect::new(x, y, pill, pill_height).radius(6.0);
+ let (shape, color) = if choice == range {
+ (shape.fill(Token::BgSelected), Token::Text)
+ } else {
+ (shape.border(Token::Border), Token::TextMuted)
+ };
+ frame.push(shape);
+ let label = Text::new(x, y, pill, pill_height, choice.label()).size(Size::Small);
+ frame.push(label.color(color).align(Align::Center).bold());
+ }
+ y += pill_height + 14.0;
+
+ let bottom = env.height - env.small.line - 14.0;
+ let (left, right) = (PAD, width - PAD - SCALE_WIDTH);
+ if bottom - y < 24.0 || right - left < 24.0 {
+ return;
+ }
+ match chart {
+ Some(chart) if chart.closes.len() >= 2 => {
+ draw_chart(frame, env, chart, range, left, right, y, bottom)
+ }
+ _ => {
+ let waiting = Text::new(left, y, right - left, bottom - y, "Loading\u{2026}");
+ frame.push(waiting.color(Token::TextMuted).align(Align::Center));
+ }
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn draw_chart(
+ frame: &mut Frame,
+ env: &Env,
+ chart: &Chart,
+ range: Range,
+ left: f32,
+ right: f32,
+ top: f32,
+ bottom: f32,
+) {
+ let prices = &chart.closes;
+ let day = range == Range::Day;
+ let (mut low, mut high) = prices
+ .iter()
+ .fold((f64::MAX, f64::MIN), |(low, high), price| {
+ (low.min(*price), high.max(*price))
+ });
+ if day {
+ low = low.min(chart.previous);
+ high = high.max(chart.previous);
+ }
+ let span = (high - low).max(f64::EPSILON);
+ let height = bottom - top;
+ let at = |price: f64| top + ((high - price) / span) as f32 * height;
+ // By step rather than by time: nights and weekends take no room.
+ let step = (right - left) / (prices.len() - 1) as f32;
+ let points: Vec<f32> = prices
+ .iter()
+ .enumerate()
+ .flat_map(|(n, price)| [left + n as f32 * step, at(*price)])
+ .collect();
+ let rising = prices.last() >= Some(if day { &chart.previous } else { &prices[0] });
+ let (ground, color) = if rising {
+ (Token::PositiveBg, Token::Positive)
+ } else {
+ (Token::NegativeBg, Token::Negative)
+ };
+ frame.push(Rect::new(left, top, right - left, 1.0).fill(Token::Border));
+ frame.push(Rect::new(left, bottom, right - left, 1.0).fill(Token::Border));
+ if day {
+ let level = at(chart.previous);
+ frame.push(Line::new(vec![left, level, right, level], Token::TextFaint));
+ }
+ frame.push(Area::new(points.clone(), bottom, ground).fade());
+ frame.push(Line::new(points, color).width(1.5));
+
+ let scale_x = right + 6.0;
+ let label = |text: String, y: f32| {
+ Text::new(scale_x, y, SCALE_WIDTH - 6.0, env.small.line, text)
+ .size(Size::Small)
+ .color(Token::TextMuted)
+ };
+ frame.push(label(price(high), top - env.small.line / 2.0));
+ frame.push(label(price(low), bottom - env.small.line / 2.0));
+
+ let (first, last) = (chart.times.first(), chart.times.last());
+ if let (Some(first), Some(last)) = (first, last) {
+ let when = |time: i64| clock_or_date(time + chart.offset, day);
+ let under = bottom + 6.0;
+ let half = (right - left) / 2.0;
+ let start = Text::new(left, under, half, env.small.line, when(*first));
+ frame.push(start.size(Size::Small).color(Token::TextMuted));
+ let mut end = when(*last);
+ if day && !chart.zone.is_empty() {
+ end = format!("{end} {}", chart.zone);
+ }
+ let end = Text::new(left + half, under, half, env.small.line, end);
+ frame.push(
+ end.size(Size::Small)
+ .color(Token::TextMuted)
+ .align(Align::Right),
+ );
+ }
+}
+
+/// A price with the places a market quotes it to: four below ten, which
+/// is where currencies are.
+fn price(value: f64) -> String {
+ format!("{value:.*}", places(value))
+}
+
+fn places(value: f64) -> usize {
+ if value.abs() >= 10.0 {
+ 2
+ } else {
+ 4
+ }
+}
+
+/// A move of a price of `of`, with its sign and that price's places.
+fn signed(value: f64, of: f64) -> String {
+ let sign = if value < 0.0 { "-" } else { "+" };
+ format!("{sign}{:.*}", places(of), value.abs())
+}
+
+fn percent(now: f64, before: f64) -> String {
+ if before == 0.0 {
+ return "--".into();
+ }
+ let change = (now - before) / before * 100.0;
+ format!(
+ "{}{:.2}%",
+ if change < 0.0 { "-" } else { "+" },
+ change.abs()
+ )
+}
+
+/// "15:45" for a time in a day's chart, "Sep 28" or "Sep 2026" otherwise:
+/// `time` is seconds since the epoch, moved to the exchange's clock.
+fn clock_or_date(time: i64, day: bool) -> String {
+ let seconds = time.rem_euclid(86_400);
+ if day {
+ return format!("{:02}:{:02}", seconds / 3_600, seconds % 3_600 / 60);
+ }
+ const MONTHS: [&str; 12] = [
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
+ ];
+ let (year, month, date) = civil(time.div_euclid(86_400));
+ format!("{} {date} {year}", MONTHS[(month - 1) as usize])
+}
+
+/// The calendar date of a day counted from 1970-01-01 (Howard Hinnant's
+/// algorithm).
+fn civil(days: i64) -> (i64, i64, i64) {
+ let z = days + 719_468;
+ let era = z.div_euclid(146_097);
+ let doe = z.rem_euclid(146_097);
+ let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+ let mp = (5 * doy + 2) / 153;
+ let date = doy - (153 * mp + 2) / 5 + 1;
+ let month = if mp < 10 { mp + 3 } else { mp - 9 };
+ let year = yoe + era * 400 + i64::from(month <= 2);
+ (year, month, date)
+}
+
+fn main() -> std::io::Result<()> {
+ let file = thinkterm_plugin_sdk::data_dir().map(|dir| dir.join("watchlist.txt"));
+ let market: Shared = Arc::new((Mutex::new(Market::load(file)), Condvar::new()));
+ thinkterm_plugin_sdk::run_with(|emitter| {
+ let fetching = Arc::clone(&market);
+ let started = std::thread::Builder::new()
+ .name("fetch".into())
+ .spawn(move || market::fetch(fetching, emitter));
+ if let Err(err) = started {
+ eprintln!("stocks: cannot start fetching: {err}");
+ }
+ Stocks {
+ market,
+ picks: HashMap::new(),
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use thinkterm_plugin_sdk::panel::{MonoMetrics, Player, TextMetrics};
+
+ fn env() -> Env {
+ let text = |size, line| TextMetrics { size, line };
+ Env {
+ width: 320.0,
+ height: 800.0,
+ scale: 2.0,
+ dark: false,
+ small: text(11.0, 15.0),
+ body: text(13.0, 18.0),
+ title: text(15.0, 20.0),
+ mono: MonoMetrics {
+ size: 12.0,
+ line: 17.0,
+ advance: 7.0,
+ },
+ locale: String::new(),
+ cwd: None,
+ remote: None,
+ can_extend: false,
+ close: None,
+ }
+ }
+
+ #[test]
+ fn numbers_and_dates_read_as_a_market_writes_them() {
+ assert_eq!(price(341.071), "341.07");
+ assert_eq!(price(1.08765), "1.0877");
+ assert_eq!(percent(105.0, 100.0), "+5.00%");
+ assert_eq!(percent(95.0, 100.0), "-5.00%");
+ assert_eq!(signed(-1.5, 341.0), "-1.50");
+ assert_eq!(signed(0.0012, 1.08), "+0.0012");
+ assert_eq!(civil(0), (1970, 1, 1));
+ assert_eq!(civil(20_724), (2026, 9, 28));
+ assert_eq!(clock_or_date(15 * 3_600 + 45 * 60, true), "15:45");
+ assert_eq!(clock_or_date(20_724 * 86_400, false), "Sep 28 2026");
+ }
+
+ #[test]
+ fn a_click_picks_a_symbol_and_a_range() {
+ let mut market = Market::load(None);
+ market.days.insert(
+ "AAPL".into(),
+ Day {
+ symbol: "AAPL".into(),
+ price: 341.0,
+ previous: 335.0,
+ closes: vec![335.0, 338.0, 341.0],
+ },
+ );
+ let shared: Shared = Arc::new((Mutex::new(market), Condvar::new()));
+ let mut stocks = Stocks {
+ market: shared,
+ picks: HashMap::new(),
+ };
+ let view = View::new(3, env());
+ let mut frame = Frame::default();
+ stocks.draw(&view, &mut frame);
+ assert_eq!(
+ lock(&stocks.market).wanted,
+ [("AAPL".to_string(), Range::Day)]
+ );
+
+ let mut player = Player::new(env());
+ player.frame(frame);
+ // The second row of the watchlist.
+ let row = env().body.line + env().small.line + 14.0;
+ let y = env().title.line + 20.0 + row * 1.5;
+ let input = player
+ .click(40.0, y, Default::default(), 1, Default::default())
+ .unwrap();
+ stocks.input(&view, input, &mut Cx::new());
+ assert_eq!(lock(&stocks.market).wanted[0].0, "MSFT");
+
+ let mut frame = Frame::default();
+ stocks.draw(&view, &mut frame);
+ let range = frame
+ .items
+ .iter()
+ .find_map(|item| match item {
+ Item::Hit(hit) if hit.id == "range:1Y" => Some(hit.clone()),
+ _ => None,
+ })
+ .unwrap();
+ player.frame(frame);
+ let input = player
+ .click(
+ range.x + 2.0,
+ range.y + 2.0,
+ Default::default(),
+ 1,
+ Default::default(),
+ )
+ .unwrap();
+ stocks.input(&view, input, &mut Cx::new());
+ assert_eq!(
+ lock(&stocks.market).wanted,
+ [("MSFT".to_string(), Range::Year)]
+ );
+ stocks.closed(&view);
+ assert!(lock(&stocks.market).wanted.is_empty());
+ assert_eq!(lock(&stocks.market).panels, 0);
+ }
+
+ #[test]
+ fn a_symbol_taken_off_leaves_the_others_picked_and_nothing_of_itself() {
+ let mut market = Market::load(None);
+ market.symbols = vec!["A".into(), "B".into(), "C".into()];
+ market.names.insert("A".into(), "Alpha".into());
+ market.days.insert(
+ "A".into(),
+ Day {
+ symbol: "A".into(),
+ price: 1.0,
+ previous: 1.0,
+ closes: vec![1.0],
+ },
+ );
+ let shared: Shared = Arc::new((Mutex::new(market), Condvar::new()));
+ let mut stocks = Stocks {
+ market: shared,
+ picks: HashMap::new(),
+ };
+ // Two panels: one on B, one on C.
+ for (view, symbol) in [(1, 1), (2, 2)] {
+ stocks.picks.insert(
+ view,
+ Pick {
+ symbol,
+ ..Pick::default()
+ },
+ );
+ }
+ stocks
+ .change_watchlist(&json!({"symbol": "A"}), false)
+ .unwrap();
+ let symbols = lock(&stocks.market).symbols.clone();
+ let picked = |view: u64| symbols[stocks.picks[&view].symbol].clone();
+ assert_eq!((picked(1), picked(2)), ("B".to_string(), "C".to_string()));
+ let market = lock(&stocks.market);
+ assert!(!market.days.contains_key("A") && !market.names.contains_key("A"));
+ drop(market);
+
+ // The one picked going, the panel has the one after it, or the last.
+ stocks
+ .change_watchlist(&json!({"symbol": "C"}), false)
+ .unwrap();
+ assert_eq!(stocks.picks[&2].symbol, 0);
+ assert_eq!(lock(&stocks.market).symbols, ["B"]);
+ }
+}
diff --git a/plugins/stocks/src/market.rs b/plugins/stocks/src/market.rs
new file mode 100644
index 00000000..89ed2975
--- /dev/null
+++ b/plugins/stocks/src/market.rs
@@ -0,0 +1,283 @@
+//! What the panels show, and the thread that fetches it: the watchlist's
+//! quotes every [`QUOTES_EVERY`], the charts the panels have picked every
+//! [`CHARTS_EVERY`], and each symbol's name once. Nothing is fetched while
+//! no panel is on show.
+
+use crate::yahoo::{self, Chart, Day, Failure, Range};
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::{Arc, Condvar, Mutex, MutexGuard};
+use std::time::{Duration, Instant};
+use thinkterm_plugin_sdk::Emitter;
+
+const QUOTES_EVERY: Duration = Duration::from_secs(15);
+const CHARTS_EVERY: Duration = Duration::from_secs(60);
+/// How long to leave Yahoo alone once it says it was asked too often.
+const LIMITED_FOR: Duration = Duration::from_secs(120);
+/// What a watchlist starts with.
+const START: &[&str] = &[
+ "AAPL", "MSFT", "NVDA", "GOOGL", "AMZN", "META", "TSLA", "^GSPC", "^IXIC", "BTC-USD",
+ "EURUSD=X", "GC=F",
+];
+/// The longest watchlist kept.
+pub const WATCHLIST_LIMIT: usize = 50;
+
+#[derive(Default)]
+pub struct Market {
+ pub symbols: Vec<String>,
+ pub days: HashMap<String, Day>,
+ pub names: HashMap<String, String>,
+ /// Only the charts some panel has picked.
+ pub charts: HashMap<(String, Range), Chart>,
+ /// Why the last fetch failed, while it does.
+ pub trouble: Option<String>,
+ /// Panels on show, and the charts they picked.
+ pub panels: usize,
+ pub wanted: Vec<(String, Range)>,
+ /// Where the watchlist is kept.
+ file: Option<PathBuf>,
+}
+
+pub type Shared = Arc<(Mutex<Market>, Condvar)>;
+
+pub fn lock(shared: &Shared) -> MutexGuard<'_, Market> {
+ shared
+ .0
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
+
+impl Market {
+ /// The watchlist kept in `file`, or the one a watchlist starts with.
+ pub fn load(file: Option<PathBuf>) -> Self {
+ let kept = file
+ .as_ref()
+ .and_then(|file| std::fs::read_to_string(file).ok());
+ let symbols = match kept {
+ Some(text) => text
+ .lines()
+ .map(str::trim)
+ .filter(|symbol| !symbol.is_empty())
+ .take(WATCHLIST_LIMIT)
+ .map(str::to_string)
+ .collect(),
+ None => START.iter().map(|symbol| symbol.to_string()).collect(),
+ };
+ Self {
+ symbols,
+ file,
+ ..Self::default()
+ }
+ }
+
+ pub fn save(&self) -> std::io::Result<()> {
+ match &self.file {
+ Some(file) => std::fs::write(file, self.symbols.join("\n") + "\n"),
+ None => Ok(()),
+ }
+ }
+
+ /// Takes `symbol` off the watchlist, and lets go of what was fetched
+ /// for it: where it was, if it was there.
+ pub fn remove(&mut self, symbol: &str) -> Option<usize> {
+ let at = self.symbols.iter().position(|kept| kept == symbol)?;
+ self.symbols.remove(at);
+ self.days.remove(symbol);
+ self.names.remove(symbol);
+ Some(at)
+ }
+
+ /// Whether `symbol` is on the watchlist: what comes for one that was
+ /// taken off meanwhile is not kept.
+ fn watched(&self, symbol: &str) -> bool {
+ self.symbols.iter().any(|kept| kept == symbol)
+ }
+
+ /// The charts no panel wants any longer are let go.
+ pub fn want(&mut self, panels: usize, wanted: Vec<(String, Range)>) {
+ self.charts.retain(|picked, _| wanted.contains(picked));
+ self.panels = panels;
+ self.wanted = wanted;
+ }
+
+ /// The charts picked that are to be fetched at `now`: one not held --
+ /// never fetched, or let go while no panel wanted it -- at once, one
+ /// held once `due` says it was fetched [`CHARTS_EVERY`] ago.
+ fn charts_due(
+ &self,
+ due: &HashMap<(String, Range), Instant>,
+ now: Instant,
+ ) -> Vec<(String, Range)> {
+ self.wanted
+ .iter()
+ .filter(|picked| {
+ !self.charts.contains_key(*picked) || due.get(*picked).is_none_or(|at| *at <= now)
+ })
+ .cloned()
+ .collect()
+ }
+}
+
+/// Fetches for as long as the plugin runs, telling the panels to draw
+/// anew whenever something came.
+pub fn fetch(shared: Shared, emitter: Emitter) {
+ let mut quotes_due = Instant::now();
+ let mut charts_due: HashMap<(String, Range), Instant> = HashMap::new();
+ let mut quiet_until = Instant::now();
+ loop {
+ let (symbols, wanted, charts, unnamed) = {
+ let mut market = lock(&shared);
+ loop {
+ let now = Instant::now();
+ let chart_due = !market.charts_due(&charts_due, now).is_empty();
+ let unnamed = market
+ .symbols
+ .iter()
+ .any(|symbol| !market.names.contains_key(symbol));
+ let due = quotes_due <= now || chart_due || unnamed;
+ if market.panels > 0 && due && quiet_until <= now {
+ break;
+ }
+ let wait = if market.panels == 0 {
+ QUOTES_EVERY
+ } else {
+ let next = charts_due
+ .values()
+ .copied()
+ .chain([quotes_due, quiet_until])
+ .filter(|at| *at > now)
+ .min()
+ .unwrap_or(now + QUOTES_EVERY);
+ next - now
+ };
+ market = shared
+ .1
+ .wait_timeout(market, wait)
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .0;
+ }
+ let unnamed: Vec<String> = market
+ .symbols
+ .iter()
+ .filter(|symbol| !market.names.contains_key(*symbol))
+ .cloned()
+ .collect();
+ let charts = market.charts_due(&charts_due, Instant::now());
+ (
+ market.symbols.clone(),
+ market.wanted.clone(),
+ charts,
+ unnamed,
+ )
+ };
+
+ let now = Instant::now();
+ let mut failure = None;
+ if quotes_due <= now {
+ quotes_due = now + QUOTES_EVERY;
+ match yahoo::days(&symbols) {
+ Ok(days) => {
+ let mut market = lock(&shared);
+ for day in days {
+ if market.watched(&day.symbol) {
+ market.days.insert(day.symbol.clone(), day);
+ }
+ }
+ }
+ Err(err) => failure = Some(err),
+ }
+ }
+ for picked in &charts {
+ if failure.is_some() {
+ break;
+ }
+ charts_due.insert(picked.clone(), now + CHARTS_EVERY);
+ match yahoo::chart(&picked.0, picked.1) {
+ Ok(chart) => {
+ let mut market = lock(&shared);
+ if market.watched(&picked.0) {
+ market.names.insert(picked.0.clone(), chart.name.clone());
+ }
+ if market.wanted.contains(picked) {
+ market.charts.insert(picked.clone(), chart);
+ }
+ }
+ Err(err) => failure = Some(err),
+ }
+ }
+ charts_due.retain(|picked, _| wanted.contains(picked));
+ // A name comes with a chart: one symbol at a time, so a long
+ // watchlist does not ask for all of them at once.
+ if let (None, Some(symbol)) = (&failure, unnamed.first()) {
+ let named = |name: String| {
+ let mut market = lock(&shared);
+ if market.watched(symbol) {
+ market.names.insert(symbol.clone(), name);
+ }
+ };
+ match yahoo::chart(symbol, Range::Day) {
+ Ok(chart) => named(chart.name),
+ Err(Failure::Failed(why)) => {
+ // A symbol Yahoo does not know keeps its own name.
+ eprintln!("stocks: no name for {symbol}: {why}");
+ named(String::new());
+ }
+ Err(Failure::Limited) => failure = Some(Failure::Limited),
+ }
+ }
+ {
+ let mut market = lock(&shared);
+ market.trouble = match failure {
+ None => None,
+ Some(Failure::Limited) => {
+ quiet_until = Instant::now() + LIMITED_FOR;
+ Some("Yahoo Finance asks to wait a while".into())
+ }
+ Some(Failure::Failed(why)) => {
+ // Tried again with the next quotes, not at once.
+ quiet_until = Instant::now() + QUOTES_EVERY;
+ eprintln!("stocks: {why}");
+ Some("Cannot reach Yahoo Finance".into())
+ }
+ };
+ }
+ emitter.redraw();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn chart() -> Chart {
+ Chart {
+ name: "Apple Inc.".into(),
+ currency: "USD".into(),
+ zone: "EDT".into(),
+ price: 1.0,
+ previous: 1.0,
+ offset: 0,
+ time: None,
+ times: Vec::new(),
+ closes: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn a_chart_let_go_is_fetched_again_as_soon_as_it_is_picked() {
+ let picked = ("AAPL".to_string(), Range::Day);
+ let now = Instant::now();
+ let mut due = HashMap::new();
+ let mut market = Market::default();
+ market.want(1, vec![picked.clone()]);
+ assert_eq!(market.charts_due(&due, now), std::slice::from_ref(&picked));
+ // Fetched, it is not fetched again for a while.
+ due.insert(picked.clone(), now + CHARTS_EVERY);
+ market.charts.insert(picked.clone(), chart());
+ assert!(market.charts_due(&due, now).is_empty());
+ // The panel closes and opens again: what it showed was let go.
+ market.want(0, Vec::new());
+ market.want(1, vec![picked.clone()]);
+ assert_eq!(market.charts_due(&due, now), [picked]);
+ }
+}
diff --git a/plugins/stocks/src/yahoo.rs b/plugins/stocks/src/yahoo.rs
new file mode 100644
index 00000000..7e72c017
--- /dev/null
+++ b/plugins/stocks/src/yahoo.rs
@@ -0,0 +1,238 @@
+//! Quotes and charts from Yahoo Finance's chart API, which answers without
+//! a key. It is not an official API: it turns away a client that asks too
+//! often, and may change what it answers, so what is here reads it loosely
+//! and takes what it finds.
+
+use serde_json::Value;
+use std::time::Duration;
+
+const HOST: &str = "https://query1.finance.yahoo.com";
+/// Yahoo turns away a client that does not say it is a browser of sorts.
+const USER_AGENT: &str = "Mozilla/5.0 (compatible; ThinkTerm stocks plugin)";
+const TIMEOUT: Duration = Duration::from_secs(10);
+
+/// Why nothing came.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Failure {
+ /// Asked too often: wait longer before the next.
+ Limited,
+ Failed(String),
+}
+
+/// A symbol's day so far: its price, where it closed the day before, and
+/// its prices through the day.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Day {
+ pub symbol: String,
+ pub price: f64,
+ pub previous: f64,
+ pub closes: Vec<f64>,
+}
+
+/// A chart of a symbol over a range, with what is known of it besides.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Chart {
+ pub name: String,
+ pub currency: String,
+ /// The exchange's time zone, as it names it: "EDT".
+ pub zone: String,
+ pub price: f64,
+ pub previous: f64,
+ /// The exchange's offset from UTC, in seconds: times show as it has
+ /// them.
+ pub offset: i64,
+ /// When the price was last set, in seconds since the epoch.
+ pub time: Option<i64>,
+ pub times: Vec<i64>,
+ pub closes: Vec<f64>,
+}
+
+/// The ranges a chart can show, and the step Yahoo gives each.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Range {
+ Day,
+ Week,
+ Month,
+ HalfYear,
+ Year,
+ FiveYears,
+}
+
+impl Range {
+ pub const ALL: [Self; 6] = [
+ Self::Day,
+ Self::Week,
+ Self::Month,
+ Self::HalfYear,
+ Self::Year,
+ Self::FiveYears,
+ ];
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Self::Day => "1D",
+ Self::Week => "5D",
+ Self::Month => "1M",
+ Self::HalfYear => "6M",
+ Self::Year => "1Y",
+ Self::FiveYears => "5Y",
+ }
+ }
+
+ fn query(self) -> (&'static str, &'static str) {
+ match self {
+ Self::Day => ("1d", "5m"),
+ Self::Week => ("5d", "30m"),
+ Self::Month => ("1mo", "1d"),
+ Self::HalfYear => ("6mo", "1d"),
+ Self::Year => ("1y", "1d"),
+ Self::FiveYears => ("5y", "1wk"),
+ }
+ }
+}
+
+/// The day so far of each of `symbols`, in one request.
+pub fn days(symbols: &[String]) -> Result<Vec<Day>, Failure> {
+ let list: Vec<String> = symbols.iter().map(|symbol| encode(symbol)).collect();
+ let url = format!(
+ "{HOST}/v8/finance/spark?symbols={}&range=1d&interval=5m",
+ list.join(",")
+ );
+ let answer = get(&url)?;
+ Ok(symbols
+ .iter()
+ .filter_map(|symbol| day(symbol, answer.get(symbol)?))
+ .collect())
+}
+
+fn day(symbol: &str, found: &Value) -> Option<Day> {
+ let closes = numbers(&found["close"]);
+ let price = closes
+ .last()
+ .copied()
+ .or_else(|| found["fulldayPrice"].as_f64())?;
+ let previous = found["chartPreviousClose"]
+ .as_f64()
+ .or_else(|| found["previousClose"].as_f64())
+ .unwrap_or(price);
+ Some(Day {
+ symbol: symbol.to_string(),
+ price,
+ previous,
+ closes,
+ })
+}
+
+/// `symbol` over `range`.
+pub fn chart(symbol: &str, range: Range) -> Result<Chart, Failure> {
+ let (range, interval) = range.query();
+ let url = format!(
+ "{HOST}/v8/finance/chart/{}?range={range}&interval={interval}",
+ encode(symbol)
+ );
+ let answer = get(&url)?;
+ let result = &answer["chart"]["result"][0];
+ let meta = &result["meta"];
+ let times: Vec<Option<i64>> = match result["timestamp"].as_array() {
+ Some(times) => times.iter().map(Value::as_i64).collect(),
+ None => Vec::new(),
+ };
+ let closes = result["indicators"]["quote"][0]["close"].as_array();
+ // A step with no price -- a halt, a gap -- is left out, with its time.
+ let (times, closes): (Vec<i64>, Vec<f64>) = times
+ .iter()
+ .zip(closes.into_iter().flatten())
+ .filter_map(|(time, close)| Some(((*time)?, close.as_f64()?)))
+ .unzip();
+ let price = meta["regularMarketPrice"]
+ .as_f64()
+ .or_else(|| closes.last().copied())
+ .ok_or_else(|| Failure::Failed(format!("no price for {symbol}")))?;
+ let text = |key: &str| meta[key].as_str().unwrap_or_default().to_string();
+ let name = [text("shortName"), text("longName")]
+ .into_iter()
+ .find(|name| !name.is_empty())
+ .unwrap_or_else(|| symbol.to_string());
+ Ok(Chart {
+ name,
+ currency: text("currency"),
+ zone: text("timezone"),
+ price,
+ previous: meta["chartPreviousClose"]
+ .as_f64()
+ .or_else(|| meta["previousClose"].as_f64())
+ .unwrap_or(price),
+ offset: meta["gmtoffset"].as_i64().unwrap_or(0),
+ time: meta["regularMarketTime"].as_i64(),
+ times,
+ closes,
+ })
+}
+
+fn numbers(values: &Value) -> Vec<f64> {
+ values
+ .as_array()
+ .map(|values| values.iter().filter_map(Value::as_f64).collect())
+ .unwrap_or_default()
+}
+
+fn get(url: &str) -> Result<Value, Failure> {
+ use http_req::request::Request;
+ use http_req::uri::Uri;
+
+ let uri = Uri::try_from(url).map_err(|err| Failure::Failed(format!("{err}")))?;
+ let mut body = Vec::new();
+ let response = Request::new(&uri)
+ .header("User-Agent", USER_AGENT)
+ .header("Accept", "application/json")
+ .connect_timeout(Some(TIMEOUT))
+ .read_timeout(Some(TIMEOUT))
+ .timeout(TIMEOUT)
+ .send(&mut body)
+ .map_err(|err| Failure::Failed(format!("{err}")))?;
+ let status = response.status_code();
+ if u16::from(status) == 429 {
+ return Err(Failure::Limited);
+ }
+ if !status.is_success() {
+ return Err(Failure::Failed(format!("HTTP {status}")));
+ }
+ serde_json::from_slice(&body).map_err(|err| Failure::Failed(format!("{err}")))
+}
+
+/// `symbol` as it goes in a URL: "^GSPC" is "%5EGSPC".
+fn encode(symbol: &str) -> String {
+ let mut encoded = String::new();
+ for byte in symbol.bytes() {
+ if byte.is_ascii_alphanumeric() || b"-._".contains(&byte) {
+ encoded.push(byte as char);
+ } else {
+ encoded.push_str(&format!("%{byte:02X}"));
+ }
+ }
+ encoded
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn symbols_are_encoded_for_a_url() {
+ assert_eq!(encode("^GSPC"), "%5EGSPC");
+ assert_eq!(encode("EURUSD=X"), "EURUSD%3DX");
+ assert_eq!(encode("BTC-USD"), "BTC-USD");
+ }
+
+ #[test]
+ fn a_day_is_read_loosely() {
+ let found = json!({"close": [1.0, null, 2.5], "chartPreviousClose": 2.0});
+ let read = day("A", &found).unwrap();
+ assert_eq!((read.price, read.previous), (2.5, 2.0));
+ assert_eq!(read.closes, [1.0, 2.5], "the gap is left out");
+ let bare = day("A", &json!({"fulldayPrice": 7.0})).unwrap();
+ assert_eq!((bare.price, bare.previous), (7.0, 7.0));
+ assert!(day("B", &json!({})).is_none());
+ }
+}