diff --git a/README.md b/README.md index f71ccf6..c8e518d 100644 --- a/README.md +++ b/README.md @@ -132,6 +132,8 @@ cherry-pick and an undo all stop here instead of being thrown away. - [x] A terminal under the graph: a shell per tab, in the repository's folder and as the profile in use, and the graph keeps up with what is typed into it +- [x] The window keeps up by itself with what an editor, a terminal or an + agent does to the repository in front, with no button to press - [ ] Three-way editor with line-by-line picking - [ ] A screen for the submodules themselves, bisect, LFS, signing @@ -178,6 +180,7 @@ crates/ prefs_view.rs the preferences: one column of rows, and no Save button terminal.rs a shell per tab: the pseudo-terminal, the keys, the colours terminal_view.rs the grid painted, the mouse heard, and the bar above it + watch.rs looking at the repository in front, off the painting thread chooser.rs asking the desktop for its own folder dialog graph_view.rs painting the graph and the references column board_view.rs the branches laid out in columns @@ -387,8 +390,8 @@ goes out with are the profile's, read when the shell starts, because a commit that went out under another client's name for having been typed instead of clicked is the mistake profiles exist to stop. On a checkout on another machine the shell is on that machine, reached with `ssh` and the -key the checkout was opened with. **The graph keeps up.** Nothing here watches the disk, so the -window looks when the shell goes quiet: at the branches and HEAD every +key the checkout was opened with. **The graph keeps up** sooner than the rest of the window does: it +looks when the shell goes quiet, without waiting for the next look: at the branches and HEAD every time, at the working tree after a line has been sent in, and it reads everything again only when one of them has actually moved -- `git commit` in the panel puts a commit in the graph, and `ls` does not take away the @@ -405,6 +408,31 @@ among them, which come out as boxes here as they do in a commit message. Run on Linux, the shell on another machine against a server in a container; read out of the code and not seen on macOS or Windows. +**Keeping up:** a repository is not only changed from here. An editor +saves a file, a terminal makes a commit, an agent does both for an hour, +and a window still showing what was true when it last read has to be told +to look by somebody who knows it is stale. GitKraken is told by the +system: it has every folder of the working tree watched, waits two seconds +for the events to stop, and reads again the part they were about -- which +comes with its three messages for when the watcher would not start, ran +out of watches or heard nothing. This looks instead. A thread that is not +the one that paints walks the repository in front the way `git status` +does, every two seconds while the window is the one in use and every five +while it is not, and at once when the window or a tab is come back to; a +walk that takes long is made less often, so that looking is never more +than a twentieth of the time. What it finds is two numbers, one for what +Git keeps and one for the working tree, and the window reads again only +the half that is not the one it is showing: a saved file is the list of +changes and nothing else, so the message being written stays where it is, +and a branch that moved is the whole history. A look that finds nothing +costs the window nothing, and what the window has just done itself is not +news to it. No dependency, no limit to run out of, and the same on all +three systems -- against two seconds' wait where a watcher would have +waited two seconds anyway. Only the repository in front; the others are +looked at when they are brought forward. Not a checkout on another +machine, where every look is a round trip on a connection the window is +using: its reload button is where it was. Run on Linux. + **The emulator:** the second dependency that was not part of the plan, and the one there was never going to be a way round. What a shell writes is forty years of escape sequences -- the second screen `vim` draws on, diff --git a/crates/gitrust-core/src/lib.rs b/crates/gitrust-core/src/lib.rs index b07d18a..628c379 100644 --- a/crates/gitrust-core/src/lib.rs +++ b/crates/gitrust-core/src/lib.rs @@ -66,6 +66,6 @@ pub use settings::{ }; pub use stash::StashEntry; pub use submodule::Sub; -pub use status::{ChangeKind, FileChange, WorkingState}; +pub use status::{ChangeKind, FileChange, Pulse, WorkingState}; pub use worktree::Worktree; pub use writer::Writer; diff --git a/crates/gitrust-core/src/repo.rs b/crates/gitrust-core/src/repo.rs index 366014f..2ecd409 100644 --- a/crates/gitrust-core/src/repo.rs +++ b/crates/gitrust-core/src/repo.rs @@ -1,6 +1,8 @@ //! Opening the repository, reading commits, and working on the index. +use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; +use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; @@ -12,7 +14,7 @@ use git2::{ use crate::detail::{CommitDetail, CommitFile, RefEntry}; use crate::diff::{DiffLine, FileDiff, Hunk, HunkId}; use crate::model::{Commit, RefKind, RefLabel}; -use crate::status::{staged_kind, unstaged_kind, ChangeKind, FileChange, WorkingState}; +use crate::status::{staged_kind, unstaged_kind, ChangeKind, FileChange, Pulse, WorkingState}; pub struct Repo { pub(crate) inner: Repository, @@ -194,6 +196,36 @@ impl Repo { /// The changed files, split between index and working tree. One file can /// show up on both sides if it is half staged. pub fn status(&self) -> Result { + Ok(self.work()?.0) + } + + /// The changed files, and the pulse they were read at. + /// + /// For whoever shows them: the pulse kept beside the list is what a + /// later look is compared with, and it has to be of this reading and + /// not of one made a moment afterwards. + pub fn status_and_pulse(&self) -> Result<(WorkingState, Pulse)> { + let (state, tree) = self.work()?; + Ok((state, Pulse { git: self.git_pulse(), tree })) + } + + /// Two numbers that stay the same for as long as the repository does. + /// + /// What a window is compared with to know whether it is out of date, + /// without reading the history to find out. See [`Pulse`]. + pub fn pulse(&self) -> Result { + Ok(self.status_and_pulse()?.1) + } + + /// One walk through the working tree for both: the list, and a number + /// made out of it. + /// + /// The number is more than the list. A file that was modified and is + /// modified again is the same line in the list and a different diff + /// behind it, so what goes in beside each path is when the file was + /// last written and how long it is, and for the index's side which + /// blob is staged. + fn work(&self) -> Result<(WorkingState, u64)> { let mut options = StatusOptions::new(); options .include_untracked(true) @@ -204,24 +236,82 @@ impl Repo { let statuses = self.inner.statuses(Some(&mut options))?; let mut state = WorkingState::default(); + let mut pulse = DefaultHasher::new(); + let folder = self.inner.workdir(); for entry in statuses.iter() { let Some(path) = entry.path() else { continue; }; let status = entry.status(); + path.hash(&mut pulse); + status.bits().hash(&mut pulse); if let Some(kind) = staged_kind(status) { state.staged.push(FileChange { path: path.to_string(), kind, staged: true }); + if let Some(staged) = entry.head_to_index() { + staged.new_file().id().as_bytes().hash(&mut pulse); + } } if let Some(kind) = unstaged_kind(status) { state.unstaged.push(FileChange { path: path.to_string(), kind, staged: false }); + // A file that cannot be asked -- it has just gone -- says + // nothing, and the next look says the rest. + if let Some(about) = folder.and_then(|folder| std::fs::symlink_metadata(folder.join(path)).ok()) { + about.len().hash(&mut pulse); + about.modified().ok().hash(&mut pulse); + } } } state.staged.sort_by(|a, b| a.path.cmp(&b.path)); state.unstaged.sort_by(|a, b| a.path.cmp(&b.path)); - Ok(state) + Ok((state, pulse.finish())) + } + + /// A number made of everything Git itself keeps: where HEAD is, every + /// reference and what it points at, the stashes, and what is half-done. + /// + /// The references are put in order first. `git pack-refs` moves them + /// from one file to another and changes nothing, and it should not look + /// like something happened. + /// + /// Cheap beside the other half, which walks the working tree, and so + /// it can be asked for on its own by whoever only needs to know + /// whether the history has to be read again. + pub fn git_pulse(&self) -> u64 { + let mut pulse = DefaultHasher::new(); + self.head_name().hash(&mut pulse); + self.head_id().map(|oid| oid.as_bytes().to_vec()).hash(&mut pulse); + (self.inner.state() as u32).hash(&mut pulse); + + let mut references: Vec<(Vec, Vec)> = self + .inner + .references() + .map(|references| { + references + .flatten() + .map(|reference| { + let target = match reference.target() { + Some(oid) => oid.as_bytes().to_vec(), + None => reference.symbolic_target_bytes().unwrap_or_default().to_vec(), + }; + (reference.name_bytes().to_vec(), target) + }) + .collect() + }) + .unwrap_or_default(); + references.sort(); + references.hash(&mut pulse); + + // Dropping a stash from the middle leaves `refs/stash` where it + // was. How many there are is in its log. + self.inner + .reflog("refs/stash") + .map(|log| log.len()) + .unwrap_or(0) + .hash(&mut pulse); + pulse.finish() } /// A file's diff. With `staged` it compares HEAD against the index; without diff --git a/crates/gitrust-core/src/status.rs b/crates/gitrust-core/src/status.rs index c56fbfe..8d7ad43 100644 --- a/crates/gitrust-core/src/status.rs +++ b/crates/gitrust-core/src/status.rs @@ -49,6 +49,26 @@ impl WorkingState { } } +/// Two numbers that stay the same for as long as a repository does. +/// +/// Nothing here is told when a file changes, so the window finds out by +/// looking, and what it compares is this: a number for what Git keeps and +/// a number for the working tree. They mean nothing in themselves and are +/// not kept from one run to the next -- two of them are only ever asked +/// whether they are equal. +/// +/// Two, because they are answered differently. A branch that has moved is +/// the history read again. A file that was saved is the list of changes +/// read again and nothing else, and somebody halfway through a commit +/// message should not lose their place for having saved a file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Pulse { + /// HEAD, the references, the stashes and what is half-done. + pub git: u64, + /// What has changed in the working tree and the index, and when. + pub tree: u64, +} + /// A change recorded in the index against HEAD. pub(crate) fn staged_kind(status: Status) -> Option { if status.contains(Status::INDEX_NEW) { diff --git a/crates/gitrust-core/tests/working_tree.rs b/crates/gitrust-core/tests/working_tree.rs index b9c34b2..2cf9117 100644 --- a/crates/gitrust-core/tests/working_tree.rs +++ b/crates/gitrust-core/tests/working_tree.rs @@ -550,3 +550,56 @@ fn discarding_a_hunk_of_a_new_file_says_to_discard_it_whole() { .to_string(); assert!(err.contains("discard it whole"), "{err}"); } + +/// What the window compares to know it is out of date: it moves when the +/// repository does, in the half that moved, and not otherwise. +#[test] +fn the_pulse_moves_with_the_repository_and_only_then() { + let temp = TempRepo::new("pulse"); + temp.write("a.txt", "one\n"); + let repo = temp.open(); + repo.stage("a.txt").unwrap(); + repo.commit("first").unwrap(); + + let clean = repo.pulse().unwrap(); + // Looking changes nothing, and neither does another program's look. + assert_eq!(repo.pulse().unwrap(), clean); + assert_eq!(temp.open().pulse().unwrap(), clean); + let (state, read_at) = repo.status_and_pulse().unwrap(); + assert!(state.is_clean()); + assert_eq!(read_at, clean); + + // A file saved by something else: the working tree's half and no other. + temp.write("a.txt", "one\ntwo\n"); + let edited = temp.open().pulse().unwrap(); + assert_eq!(edited.git, clean.git); + assert_ne!(edited.tree, clean.tree); + + // Saved again: the same line in the list of changes, another diff + // behind it, and the pulse knows the difference. + temp.write("a.txt", "one\ntwo\nthree\n"); + let again = repo.pulse().unwrap(); + assert_eq!(repo.status().unwrap().unstaged.len(), 1); + assert_ne!(again.tree, edited.tree); + + // Staged: still the working tree's half. + repo.stage("a.txt").unwrap(); + let staged = repo.pulse().unwrap(); + assert_eq!(staged.git, clean.git); + assert_ne!(staged.tree, again.tree); + + // Committed from somewhere else: Git's half, and the tree is as clean + // as it was to begin with. + temp.open().commit("second").unwrap(); + let committed = repo.pulse().unwrap(); + assert_ne!(committed.git, clean.git); + assert_eq!(committed.tree, clean.tree); + + // A branch made by another program is a reference that was not there. + let other = git2::Repository::open(temp.path()).unwrap(); + let head = other.head().unwrap().peel_to_commit().unwrap(); + other.branch("topic", &head, false).unwrap(); + let branched = repo.pulse().unwrap(); + assert_ne!(branched.git, committed.git); + assert_eq!(branched.tree, committed.tree); +} diff --git a/crates/gitrust-ui/src/main.rs b/crates/gitrust-ui/src/main.rs index 0312c6b..87964a6 100644 --- a/crates/gitrust-ui/src/main.rs +++ b/crates/gitrust-ui/src/main.rs @@ -33,13 +33,14 @@ mod terminal; mod terminal_view; mod theme; mod toast; +mod watch; use anyhow::Result; use eframe::egui; use gitrust_core::{ compose, layout, layout_with_working, likely_target, Appearance, Backlog, Board, CommitDetail, FileDiff, Foreseen, General, Graph, HunkId, Join, Move, Oid, Panel, Profile, Profiles, PullMode, PullRequests, Reader, - RefEntry, RefKind, RemoteRepo, Repo, Settings, StashEntry, Tracking, WorkingState, Worktree, Writer, + Pulse, RefEntry, RefKind, RemoteRepo, Repo, Settings, StashEntry, Tracking, WorkingState, Worktree, Writer, }; /// How wide the repository menu is, measured inside its frame. @@ -303,6 +304,10 @@ struct App { /// the moment it opened would be a window that asks for a passphrase /// before it has drawn anything. fetched: std::time::Instant, + /// What looks at the repository in front while nobody is pressing + /// anything. Started with the first frame, which is the first time + /// there is a window to wake. + watch: Option, /// What one of the screens that is not a repository has to say. A tab's /// own bottom bar cannot say it: the tab is not on screen. note: Option, @@ -407,6 +412,7 @@ impl App { managing: None, preferring: None, fetched: std::time::Instant::now(), + watch: None, note: None, }; app.come_back(asked); @@ -539,6 +545,39 @@ impl App { ctx.request_repaint_after(every); } + /// Keeps the repository in front up to date with what other programs + /// do to it: an editor, a terminal, an agent. + /// + /// The looking is done off this thread, by [`watch::Watch`], which + /// says so when the repository is not as it last found it. What it + /// says goes to the tab the folder belongs to, and the tab decides + /// whether that is news. + /// + /// Only the one in front, like the fetch nobody asked for and for the + /// same reason. The others are looked at the moment they are brought + /// forward, which is the moment being out of date starts to matter. + /// Not a checkout on another machine, and not a window that has been + /// put away, which has nobody to be up to date for. + fn keep_up(&mut self, ctx: &egui::Context) { + let (near, away) = ctx.input(|input| (input.focused, input.viewport().minimized == Some(true))); + let front = self + .open + .get(self.at) + .filter(|open| !open.is_remote() && !away) + .map(|open| std::path::PathBuf::from(&open.path)); + let watch = self.watch.get_or_insert_with(|| watch::Watch::start(ctx.clone())); + watch.look_at(front.as_deref(), near); + for (folder, seen) in watch.heard() { + let found = self + .open + .iter_mut() + .find(|open| !open.is_remote() && std::path::Path::new(&open.path) == folder); + if let Some(open) = found { + open.heard(seen); + } + } + } + /// Hands every tab the preferences, once the screen for them is away. /// /// Not while it is up: a number being dragged is forty numbers on the @@ -1580,6 +1619,7 @@ impl eframe::App for App { let _ = self.settings.save(); } self.note_tabs(); + self.keep_up(ctx); // Always, even with one repository open: the plus lives in it, and a // strip that appears only once you have two tabs is a way of opening @@ -1721,6 +1761,11 @@ struct Open { // The working tree. work: WorkingState, + /// The repository's pulse as of what is on screen: read in the same + /// walk as `work`, every time `work` is. What a look from outside is + /// compared with, to know whether it found anything this tab has not + /// already shown. + pulse: Option, selected: Option<(String, bool)>, diff: Option, subject: String, @@ -2003,6 +2048,7 @@ impl Open { detail_file: None, detail_diff: None, work: WorkingState::default(), + pulse: None, selected: None, diff: None, subject: String::new(), @@ -2785,8 +2831,11 @@ impl Open { } fn read_work(&mut self, repo: &Repo) { - match repo.status() { - Ok(work) => self.work = work, + match repo.status_and_pulse() { + Ok((work, pulse)) => { + self.work = work; + self.pulse = Some(pulse); + } Err(err) => return self.note_error(format!("could not read the status: {err}")), } @@ -5085,10 +5134,12 @@ impl Open { /// /// What is typed into a terminal changes the repository behind the /// window's back, and a graph that still shows the commit `git reset` - /// has just taken away is worse than no graph. Nothing watches the - /// disk here, so the window looks when the shell goes quiet: at the - /// branches and HEAD every time, which is cheap, and at the working - /// tree only after a line was sent in, which is a walk through it. + /// has just taken away is worse than no graph. The window would find + /// out by itself within a couple of seconds, from the thread that + /// looks; this is so that it does not take a couple of seconds. It + /// looks when the shell goes quiet: at the branches and HEAD every + /// time, which is cheap, and at the working tree only after a line + /// was sent in, which is a walk through it. /// /// Everything is read again only when a branch, HEAD, the stashes or /// what is half-done has actually changed. A reload puts away a commit @@ -5127,6 +5178,39 @@ impl Open { } } + /// Is told what the repository looked like a moment ago, by the thread + /// that looks while nobody is pressing anything. + /// + /// The same as what is on screen is the usual answer, and nothing + /// happens: that is every look that found nothing, and every look that + /// found what this tab has just done itself. + /// + /// Otherwise something else has been at the repository. What is read + /// again is decided here and now and not by what was seen: a look is + /// a moment old by the time it arrives, and a commit made from this + /// window in that moment would otherwise look like one made behind its + /// back. So Git's half is asked again, which is cheap. When it has + /// moved, everything is read, as the reload button would; when it has + /// not, only the working tree is, and a commit message being written + /// stays where it is. + /// + /// Not while something slow is running, which reads everything itself + /// when it ends, and not for a checkout on another machine. + fn heard(&mut self, seen: Pulse) { + if self.is_remote() || self.job.is_some() || self.pulse == Some(seen) { + return; + } + let Ok(repo) = self.repo() else { + return; + }; + let moved = self.pulse.map(|shown| shown.git) != Some(repo.git_pulse()); + drop(repo); + match moved { + true => self.load(), + false => self.refresh(), + } + } + /// The panel itself: its bar, and under it the grid. fn terminal_panel(&mut self, ctx: &egui::Context, settings: &mut Settings) { // The key GitKraken and most editors answer to, wherever the diff --git a/crates/gitrust-ui/src/watch.rs b/crates/gitrust-ui/src/watch.rs new file mode 100644 index 0000000..0983ea9 --- /dev/null +++ b/crates/gitrust-ui/src/watch.rs @@ -0,0 +1,198 @@ +//! Keeping the window up to date with what other programs do. +//! +//! A repository is not only changed from here. An editor saves a file, a +//! terminal makes a commit, an agent does both for an hour, and a window +//! that goes on showing what was true when it last read is one that has +//! to be told to look -- with a button, by somebody who has to know it +//! is stale to press it. +//! +//! GitKraken is told. It asks the system to watch the working tree and +//! `.git`, waits two seconds for the events to stop, and reads again +//! whichever part they were about. That is a watch on every folder in +//! the tree, the ignored ones included, and it comes with the three +//! messages GitKraken has for when it does not work: the watcher would +//! not start, the system ran out of watches, the events never arrived. +//! +//! This looks instead. Off the thread that paints, it reads the +//! repository's [`Pulse`] -- the walk `git status` makes, and a list of +//! the references -- and says so when it is not the one it read last. +//! The window compares that with the pulse of what it is showing and +//! reads again only the half that moved, so a look that finds nothing +//! costs the window nothing at all, and what the window itself has just +//! done is not news to it. +//! +//! The same two seconds, while the window is the one being typed into; +//! five when it is not, and at once when it becomes so or another tab is +//! brought to the front. A walk that takes long is made less often, so +//! that looking is never more than a twentieth of the time. +//! +//! Only the repository in front, and only one on this machine. A +//! checkout on another machine is a round trip per look over a +//! connection the window is using; its reload button is where it was. + +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::time::{Duration, Instant}; + +use eframe::egui; +use gitrust_core::{Pulse, Repo}; + +/// How long between looks while the window is the one in use. +const NEAR: Duration = Duration::from_secs(2); +/// And while it is not, but may be in sight beside whatever is. +const FAR: Duration = Duration::from_secs(5); +/// However long the walk takes, it is looked at this often at least. +const SLOWEST: Duration = Duration::from_secs(60); + +/// What the watcher was last told: where to look, and how closely. +#[derive(Clone, PartialEq, Eq, Default)] +struct Told { + /// `None` is nowhere: no repository in front, or the window put away. + path: Option, + near: bool, +} + +/// The thread that looks, and the two ends of talking to it. +pub struct Watch { + tell: Sender, + heard: Receiver<(PathBuf, Pulse)>, + told: Told, +} + +impl Watch { + /// Starts looking at nothing. `ctx` is how the window is woken when + /// there is something to hear: it sleeps while nothing moves. + pub fn start(ctx: egui::Context) -> Self { + let (tell, told) = mpsc::channel(); + let (say, heard) = mpsc::channel(); + std::thread::spawn(move || run(told, say, ctx)); + Self { tell, heard, told: Told::default() } + } + + /// Says where to look from now on. Said every frame and passed on + /// only when it is not what was said before -- and then looked at + /// straight away, which is what makes coming back to the window or + /// to a tab find it current. + pub fn look_at(&mut self, path: Option<&Path>, near: bool) { + let told = Told { path: path.map(Path::to_path_buf), near }; + if told != self.told { + self.told = told.clone(); + let _ = self.tell.send(told); + } + } + + /// What has been seen since this was last asked. + pub fn heard(&self) -> Vec<(PathBuf, Pulse)> { + self.heard.try_iter().collect() + } +} + +/// How long to wait before the next look, after one that took `cost`. +pub fn pace(cost: Duration, near: bool) -> Duration { + let wanted = if near { NEAR } else { FAR }; + wanted.max(cost * 20).min(SLOWEST) +} + +fn run(told: Receiver, say: Sender<(PathBuf, Pulse)>, ctx: egui::Context) { + let mut now = Told::default(); + let mut last: Option<(PathBuf, Pulse)> = None; + let mut wait = NEAR; + loop { + // With nowhere to look there is nothing to wake up for. + let news = match now.path { + Some(_) => told.recv_timeout(wait), + None => told.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + match news { + Ok(next) => now = next, + Err(RecvTimeoutError::Timeout) => {} + // The window has gone. + Err(RecvTimeoutError::Disconnected) => return, + } + // Only the last thing said counts. + while let Ok(next) = told.try_recv() { + now = next; + } + let Some(path) = now.path.clone() else { + continue; + }; + + // Opened each time. It costs next to nothing beside the walk, and + // a repository held open is one more thing that can disagree with + // the disk. + let started = Instant::now(); + let pulse = Repo::open(&path).and_then(|repo| repo.pulse()); + wait = pace(started.elapsed(), now.near); + + // A repository that cannot be read just now -- another program is + // halfway through writing it -- is looked at again next time. + let Ok(pulse) = pulse else { + continue; + }; + if last.as_ref() != Some(&(path.clone(), pulse)) { + last = Some((path.clone(), pulse)); + if say.send((path, pulse)).is_err() { + return; + } + ctx.request_repaint(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_quick_look_is_made_every_two_seconds_and_a_slow_one_less_often() { + assert_eq!(pace(Duration::from_millis(3), true), NEAR); + assert_eq!(pace(Duration::from_millis(3), false), FAR); + // Half a second of walking is ten seconds of leaving it alone. + assert_eq!(pace(Duration::from_millis(500), true), Duration::from_secs(10)); + assert_eq!(pace(Duration::from_millis(500), false), Duration::from_secs(10)); + // And nothing is left unlooked-at for more than a minute. + assert_eq!(pace(Duration::from_secs(30), true), SLOWEST); + } + + #[test] + fn a_change_made_by_something_else_is_heard_once() { + let folder = std::env::temp_dir().join(format!("gitrust-watch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + gitrust_core::start::init(&folder, None).unwrap(); + + let mut watch = Watch::start(egui::Context::default()); + watch.look_at(Some(&folder), true); + let hear = |watch: &Watch| { + for _ in 0..200 { + let heard = watch.heard(); + if !heard.is_empty() { + return heard; + } + std::thread::sleep(Duration::from_millis(25)); + } + Vec::new() + }; + + // The first look is said, whatever it finds: the window is the one + // that knows what it is showing. + let first = hear(&watch); + assert_eq!(first.len(), 1); + assert_eq!(first[0].0, folder); + + std::fs::write(folder.join("note.txt"), "written by something else\n").unwrap(); + let second = hear(&watch); + assert_eq!(second.len(), 1, "the change was not heard"); + assert_eq!(second[0].1.git, first[0].1.git); + assert_ne!(second[0].1.tree, first[0].1.tree); + + // Told to look nowhere, it says nothing more, whatever happens. + watch.look_at(None, true); + std::thread::sleep(Duration::from_millis(100)); + let _ = watch.heard(); + std::fs::write(folder.join("note.txt"), "and again\n").unwrap(); + std::thread::sleep(Duration::from_millis(300)); + assert!(watch.heard().is_empty()); + + let _ = std::fs::remove_dir_all(&folder); + } +}