From 0169874d69d575fcbe68cd84618349dd60590eec Mon Sep 17 00:00:00 2001 From: Francesc Date: Thu, 12 Nov 2026 20:19:24 +0100 Subject: [PATCH 1/3] feat: a terminal under the graph, with a shell that knows whose repository it is in There is a Terminal button at the end of the action bar and Ctrl+` does what it does: a panel opens under the graph, between the two side panels, with a shell in the repository's folder. Each tab has its own. The bar over it folds the panel, kills the shell or hides it and leaves the shell running; a shell that exits takes the panel with it. Whether it was open, and how tall, is remembered. How it behaves was read out of GitKraken's bundle before any of it was written -- the three states of the panel, what each button does to the shell, the context menu, Ctrl+C that copies when something is selected and interrupts when nothing is, the preferences and their limits. The preferences are the ones that could be made to act: font size, line height, cursor style, dimming when unfocused, and which shell. Three things are here that are not there. The shell is started with the name, the address and the key of the profile the repository is filed under, so a commit typed in it is signed the way one made with the button would be. A checkout on another machine gets a shell on that machine, over ssh, in its folder. And since nothing here watches the disk, the repository is looked at again once the shell has gone quiet, and reloaded only if something moved -- a commit typed in the panel turns up in the graph by itself. The emulator is alacritty_terminal, eleven crates. A terminal that is nearly right is one where vim and an interactive rebase are nearly usable, and this one also brings the Windows pty. What is drawn is drawn here: Fira Mono, bold by striking twice since there is only the regular weight, and the box-drawing and block characters by hand, as the font's own do not reach from one row to the next. Not there: GitKraken's autocomplete suggestions, a choice of typeface, and any letter the two bundled fonts lack. The profile is read when the shell starts, so changing it applies to the next shell. Run on Linux, on a virtual display. Read out of the code and not seen on macOS or Windows, and the shell on another machine has not been opened against one -- only the command it sends was tried, locally. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Francesc --- Cargo.lock | 119 ++- README.md | 52 +- crates/gitrust-core/src/lib.rs | 6 +- crates/gitrust-core/src/settings.rs | 202 +++- crates/gitrust-ui/Cargo.toml | 4 + crates/gitrust-ui/src/main.rs | 288 ++++- crates/gitrust-ui/src/prefs_view.rs | 102 +- crates/gitrust-ui/src/terminal.rs | 735 +++++++++++++ crates/gitrust-ui/src/terminal_view.rs | 1334 ++++++++++++++++++++++++ crates/gitrust-ui/src/theme.rs | 70 ++ 10 files changed, 2905 insertions(+), 7 deletions(-) create mode 100644 crates/gitrust-ui/src/terminal.rs create mode 100644 crates/gitrust-ui/src/terminal_view.rs diff --git a/Cargo.lock b/Cargo.lock index 423d0b8..175c946 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -129,6 +129,40 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "alacritty_terminal" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda177466b9524d59f1b12f0dd30b68696788e9992a7e959021c4a0ed96fcf59" +dependencies = [ + "base64", + "bitflags 2.13.2", + "home", + "libc", + "log", + "miow", + "parking_lot", + "piper", + "polling", + "regex-automata", + "rustix 1.1.6", + "rustix-openpty", + "serde", + "signal-hook", + "unicode-width 0.2.3", + "vte", + "windows-sys 0.59.0", +] + [[package]] name = "android-activity" version = "0.6.1" @@ -421,6 +455,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bit-set" version = "0.8.0" @@ -645,7 +685,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" dependencies = [ "termcolor", - "unicode-width", + "unicode-width 0.1.14", ] [[package]] @@ -1270,6 +1310,7 @@ dependencies = [ name = "gitrust-ui" version = "0.1.0-beta.1" dependencies = [ + "alacritty_terminal", "anyhow", "chrono", "eframe", @@ -1456,6 +1497,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -1888,6 +1938,15 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "miow" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "536bfad37a309d62069485248eeaba1e8d9853aaf951caaeaed0585a95346f08" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "moxcms" version = "0.8.1" @@ -2642,6 +2701,23 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "renderdoc-sys" version = "1.1.0" @@ -2719,6 +2795,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustix-openpty" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1de16c7c59892b870a6336f185dc10943517f1327447096bbb7bb32cd85e2393" +dependencies = [ + "errno", + "libc", + "rustix 1.1.6", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -2823,6 +2910,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -3274,6 +3371,12 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "unicode-xid" version = "0.2.6" @@ -3319,6 +3422,20 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "cursor-icon", + "log", + "memchr", + "serde", +] + [[package]] name = "walkdir" version = "2.5.0" diff --git a/README.md b/README.md index fb2c450..2f448c9 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,9 @@ cherry-pick and an undo all stop here instead of being thrown away. history the graph reads and whether it reads on, the tabs that come back, submodules kept at their recorded commit, conflicts seen coming, and a log of what happened +- [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 - [ ] Three-way editor with line-by-line picking - [ ] A screen for the submodules themselves, bisect, LFS, signing @@ -173,6 +176,8 @@ crates/ picker.rs choosing a repository, cloning one, starting one profiles_view.rs the profiles, and which one is in use 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 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 @@ -363,7 +368,52 @@ happened, opens **a log** of the things before it -- with what the window did by itself among them when the preferences ask for that. The screen has a row for forgetting every token the profiles hold, which asks first. -**The folder dialog:** the one dependency that was not part of the plan. +**The terminal:** a panel under the graph, between the branches and the +commit, opened from the end of the actions or with Control and the +backtick. **A shell per tab**, in that tab's repository, started the first +time the panel is opened on it; the panel itself -- open, folded to its +bar or put away, and how tall -- is one answer for the whole window and +comes back the way it was left. Putting it away leaves the shell running; +the bin ends it, and so does `exit`. **It works as the profile in use**: +the name on a commit typed there and the key a `git push` typed there +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 +same key. **The graph keeps up.** Nothing here watches the disk, so the +window looks when the shell goes quiet: 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 +message you were amending. Not on a remote checkout, where looking is a +round trip on the thread that paints. Control and C copies when something +is selected and interrupts when nothing is; pasting is Control, Shift and +V, since Control and V alone is the shell's. An address is a link. The +letters programs draw frames with are drawn, not set in the font, so a +frame is a frame at any line height. What is not there: the suggestions +GitKraken pops up as you type, which are a product of their own; a choice +of typeface, because this program ships the one it was designed around; +and letters Fira Mono and its fallbacks do not have, Chinese and Japanese +among them, which come out as boxes here as they do in a commit message. +Run on Linux; read out of the code and not seen on macOS or Windows, and +the shell on another machine has not been opened against one. + +**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, +scroll regions, eleven ways of naming a colour -- and a reader of them that +is nearly right is a terminal where `git log` works and `git rebase -i` +does not. The syntax colouring here is hand-made because being wrong about +a comment costs a few grey letters; being wrong about a cursor movement +costs the screen. So it is `alacritty_terminal`, the inside of Alacritty: +the reader, the grid with its history and selection, and the +pseudo-terminal itself on all three systems, which on Windows is a +subsystem of its own. Eleven crates. The painting, the keys and the mouse +are still this program's, in the fonts and the colours it already had: +red in the panel is the coral of the graph. + +**The folder dialog:** the one dependency that was not part of the plan +until the terminal made it the first of two. Opening a repository meant typing its path, and the obvious fix was to run `gdbus` and ask `xdg-desktop-portal`, the way `gh` is run to ask GitHub. It does not work, and the reason is not a bug anybody can fix: the portal's diff --git a/crates/gitrust-core/src/lib.rs b/crates/gitrust-core/src/lib.rs index b24be63..b07d18a 100644 --- a/crates/gitrust-core/src/lib.rs +++ b/crates/gitrust-core/src/lib.rs @@ -59,7 +59,11 @@ pub use reader::Reader; pub use remote_repo::RemoteRepo; pub use rewrite::{Plan, Step}; pub use repo::Repo; -pub use settings::{Appearance, General, Settings, FEWEST_COMMITS, LONGEST_FETCH_WAIT}; +pub use settings::{ + Appearance, Caret, General, Panel, Settings, FEWEST_COMMITS, LARGEST_TERMINAL_FONT, + LONGEST_FETCH_WAIT, LOOSEST_TERMINAL_LINE, SHORTEST_TERMINAL, SMALLEST_TERMINAL_FONT, + TALLEST_TERMINAL, TIGHTEST_TERMINAL_LINE, +}; pub use stash::StashEntry; pub use submodule::Sub; pub use status::{ChangeKind, FileChange, WorkingState}; diff --git a/crates/gitrust-core/src/settings.rs b/crates/gitrust-core/src/settings.rs index a0df20a..2b87df7 100644 --- a/crates/gitrust-core/src/settings.rs +++ b/crates/gitrust-core/src/settings.rs @@ -25,7 +25,8 @@ //! not a preference at all -- they are what was open when the window was //! last closed -- but they are kept here for the reason the remote //! checkouts are: one file that is about this computer is easier to reason -//! about, and to delete, than three. +//! about, and to delete, than three. The `terminal` lines are the same kind +//! of thing: how much of the terminal panel was showing, and how tall. //! //! A line it does not understand is skipped and a setting that is not in the //! file keeps its default, so a file written by a newer gitrust does not stop @@ -75,6 +76,101 @@ impl Appearance { } } +/// What marks the place in the terminal where the next letter goes. +/// +/// A bar until somebody says otherwise, as in an editor: a block sits on +/// top of the letter it is on, and in a panel a few lines tall that is one +/// letter fewer to read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Caret { + #[default] + Bar, + Block, + Underline, +} + +impl Caret { + /// Every one of them, in the order the preferences list them. + pub const ALL: [Self; 3] = [Self::Bar, Self::Block, Self::Underline]; + + fn parse(value: &str) -> Option { + match value.trim() { + "bar" => Some(Self::Bar), + "block" => Some(Self::Block), + "underline" => Some(Self::Underline), + _ => None, + } + } + + fn as_str(self) -> &'static str { + match self { + Self::Bar => "bar", + Self::Block => "block", + Self::Underline => "underline", + } + } + + /// What it is called where somebody chooses it. + pub fn label(self) -> &'static str { + match self { + Self::Bar => "Bar", + Self::Block => "Block", + Self::Underline => "Underline", + } + } +} + +/// How much of the terminal panel is on screen. +/// +/// Three, and the difference between the first two is the point of having +/// both: put away, the shell goes on running and nothing says it is there; +/// folded, its title bar stays at the bottom of the window to say so. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Panel { + /// Not on screen. Whatever was running in it still is. + #[default] + Hidden, + /// Its title bar and nothing else. + Minimized, + /// All of it. + Expanded, +} + +impl Panel { + fn parse(value: &str) -> Option { + match value.trim() { + "hidden" => Some(Self::Hidden), + "minimized" => Some(Self::Minimized), + "expanded" => Some(Self::Expanded), + _ => None, + } + } + + fn as_str(self) -> &'static str { + match self { + Self::Hidden => "hidden", + Self::Minimized => "minimized", + Self::Expanded => "expanded", + } + } +} + +/// The smallest and the largest the letters in the terminal get, in points. +/// Below the first they are not letters, and above the second a line of +/// them is four words. +pub const SMALLEST_TERMINAL_FONT: u32 = 8; +pub const LARGEST_TERMINAL_FONT: u32 = 72; + +/// How close together and how far apart its lines go, in hundredths of the +/// letter's own height: touching, and five times that. +pub const TIGHTEST_TERMINAL_LINE: u32 = 100; +pub const LOOSEST_TERMINAL_LINE: u32 = 500; + +/// The shortest and the tallest the terminal panel is remembered as, in +/// points. The window decides how much of the second it can have. +pub const SHORTEST_TERMINAL: u32 = 90; +pub const TALLEST_TERMINAL: u32 = 2_000; + /// The fewest commits the graph will be asked to start with. Below this the /// history stops before most people have scrolled once. pub const FEWEST_COMMITS: usize = 500; @@ -116,6 +212,19 @@ pub struct General { /// Whether the branch is checked, ahead of time, for conflicts with the /// branch it will be merged into. pub foresee_conflicts: bool, + /// How large the letters in the terminal are, in points. + pub terminal_font: u32, + /// How far apart its lines are, in hundredths of a letter's height. A + /// whole number, because two preferences have to be able to say they + /// are the same and 1.2 cannot be trusted to. + pub terminal_line: u32, + /// What marks where the next letter goes. + pub terminal_caret: Caret, + /// Whether the terminal goes quiet while the keyboard is somewhere else. + pub terminal_dim: bool, + /// The program the terminal runs. Empty is the shell this account logs + /// in with. + pub terminal_shell: String, } impl Default for General { @@ -134,6 +243,11 @@ impl Default for General { remember_tabs: true, extended_log: false, foresee_conflicts: true, + terminal_font: 12, + terminal_line: 120, + terminal_caret: Caret::default(), + terminal_dim: true, + terminal_shell: String::new(), } } } @@ -177,6 +291,27 @@ impl General { "remember-tabs" => self.remember_tabs = on, "extended-log" => self.extended_log = on, "foresee-conflicts" => self.foresee_conflicts = on, + "terminal-font" => { + if let Ok(points) = value.parse::() { + self.terminal_font = + points.clamp(SMALLEST_TERMINAL_FONT, LARGEST_TERMINAL_FONT); + } + } + "terminal-line-height" => { + if let Ok(hundredths) = value.parse::() { + self.terminal_line = + hundredths.clamp(TIGHTEST_TERMINAL_LINE, LOOSEST_TERMINAL_LINE); + } + } + "terminal-cursor" => { + if let Some(caret) = Caret::parse(value) { + self.terminal_caret = caret; + } + } + "terminal-dim" => self.terminal_dim = on, + // The rest of the line and not a word of it, as for a tab: a + // program can live in a folder with a space in its name. + "terminal-shell" => self.terminal_shell = value.to_string(), _ => return false, } true @@ -207,6 +342,16 @@ impl General { word(self.extended_log), word(self.foresee_conflicts), )); + text.push_str(&format!( + "terminal-font {}\nterminal-line-height {}\nterminal-cursor {}\nterminal-dim {}\n", + self.terminal_font, + self.terminal_line, + self.terminal_caret.as_str(), + word(self.terminal_dim), + )); + if !self.terminal_shell.trim().is_empty() { + text.push_str(&format!("terminal-shell {}\n", self.terminal_shell.trim())); + } text } } @@ -232,6 +377,12 @@ pub struct Settings { pub tabs: Vec, /// Which of them was in front. pub front: usize, + /// How much of the terminal panel is showing. One answer for the whole + /// window and not one per tab: it is where somebody likes their + /// terminal, not something about a repository. + pub terminal: Panel, + /// How tall it is when all of it is showing, in points. + pub terminal_height: u32, } impl Default for Settings { @@ -243,6 +394,8 @@ impl Default for Settings { general: General::default(), tabs: Vec::new(), front: 0, + terminal: Panel::default(), + terminal_height: 280, } } } @@ -289,6 +442,17 @@ impl Settings { Some(("front", value)) => { settings.front = value.trim().parse().unwrap_or(0); } + Some(("terminal", value)) => { + if let Some(panel) = Panel::parse(value) { + settings.terminal = panel; + } + } + Some(("terminal-height", value)) => { + if let Ok(points) = value.trim().parse::() { + settings.terminal_height = + points.clamp(SHORTEST_TERMINAL, TALLEST_TERMINAL); + } + } Some((name, value)) => { settings.general.take(name, value); } @@ -320,6 +484,11 @@ impl Settings { if !self.tabs.is_empty() { text.push_str(&format!("front {}\n", self.front)); } + text.push_str(&format!( + "terminal {}\nterminal-height {}\n", + self.terminal.as_str(), + self.terminal_height + )); text } @@ -424,6 +593,11 @@ mod tests { remember_tabs: false, extended_log: true, foresee_conflicts: false, + terminal_font: 15, + terminal_line: 140, + terminal_caret: Caret::Underline, + terminal_dim: false, + terminal_shell: "/opt/my shells/fish".to_string(), }; let settings = Settings { general, ..Settings::default() }; assert_eq!(Settings::parse(&settings.render()), settings); @@ -441,6 +615,32 @@ mod tests { assert_eq!(settings.general, General::default()); } + #[test] + fn the_terminal_is_kept_inside_what_can_be_read() { + let settings = Settings::parse( + "terminal-font 2\nterminal-line-height 9000\nterminal-height 5\n", + ); + assert_eq!(settings.general.terminal_font, SMALLEST_TERMINAL_FONT); + assert_eq!(settings.general.terminal_line, LOOSEST_TERMINAL_LINE); + assert_eq!(settings.terminal_height, SHORTEST_TERMINAL); + // A caret nobody has heard of leaves the one that was there. + let settings = Settings::parse("terminal-cursor wedge\n"); + assert_eq!(settings.general.terminal_caret, Caret::Bar); + } + + #[test] + fn the_terminal_panel_comes_back_the_way_it_was_left() { + // Put away until somebody asks for it: a window that opens a shell + // on a machine that never asked for one has started a program. + assert_eq!(Settings::default().terminal, Panel::Hidden); + for panel in [Panel::Hidden, Panel::Minimized, Panel::Expanded] { + let settings = Settings { terminal: panel, terminal_height: 412, ..Settings::default() }; + let back = Settings::parse(&settings.render()); + assert_eq!(back.terminal, panel); + assert_eq!(back.terminal_height, 412); + } + } + #[test] fn a_branch_name_with_a_space_in_it_is_not_taken() { let settings = Settings::parse("default-branch my branch\n"); diff --git a/crates/gitrust-ui/Cargo.toml b/crates/gitrust-ui/Cargo.toml index 06862cf..06d6b47 100644 --- a/crates/gitrust-ui/Cargo.toml +++ b/crates/gitrust-ui/Cargo.toml @@ -22,3 +22,7 @@ eframe = "0.31" egui = "0.31" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] } +# The inside of a terminal: the pseudo-terminal on all three systems, the +# reader of what a shell writes, and the grid that writing describes. The +# README says why this one is somebody else's. +alacritty_terminal = "0.26" diff --git a/crates/gitrust-ui/src/main.rs b/crates/gitrust-ui/src/main.rs index b33bef9..60a6948 100644 --- a/crates/gitrust-ui/src/main.rs +++ b/crates/gitrust-ui/src/main.rs @@ -29,6 +29,8 @@ mod refs_view; mod rewrite_view; mod ripple; mod syntax; +mod terminal; +mod terminal_view; mod theme; mod toast; @@ -36,7 +38,7 @@ 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, Profile, Profiles, PullMode, PullRequests, Reader, + Foreseen, General, Graph, HunkId, Join, Move, Oid, Panel, Profile, Profiles, PullMode, PullRequests, Reader, RefEntry, RefKind, RemoteRepo, Repo, Settings, StashEntry, Tracking, WorkingState, Worktree, Writer, }; @@ -1548,12 +1550,23 @@ impl eframe::App for App { self.adopt_profile(); self.hand_preferences(); self.auto_fetch(ctx); - for open in &mut self.open { + let mut ended = false; + for (which, open) in self.open.iter_mut().enumerate() { open.poll(ctx); open.poll_forge(ctx); open.poll_board(ctx); open.poll_fetch(ctx); open.poll_foresee(ctx); + ended |= open.poll_terminal(ctx) && which == self.at; + } + // A shell that has exited takes its panel with it: an open panel + // with nothing in it would only start another, and whoever typed + // `exit` did not ask for one. Only for the tab in front -- the panel + // is the window's, and another tab's shell ending is not a reason + // to take it from this one. + if ended && self.settings.terminal == Panel::Expanded { + self.settings.terminal = Panel::Hidden; + let _ = self.settings.save(); } self.note_tabs(); @@ -1745,6 +1758,10 @@ struct Open { /// The commit the submodules were last brought up to date at, so that a /// submodule that will not update is tried once and not on every reload. subs_tried: Option, + /// The shell in this tab's terminal, once its panel has been opened. + /// It outlives the panel being put away, and goes when it is killed, + /// when it exits, or when the tab does. + terminal: Option, } /// One line of the activity log. @@ -1997,6 +2014,7 @@ impl Open { head_at: None, looked: false, subs_tried: None, + terminal: None, }; app.load(); if let Ok(shot) = std::env::var("GITRUST_SHOT") { @@ -4546,6 +4564,11 @@ impl Open { // is seen through or thrown away. self.half_bar(ctx); + // Under whatever has the middle of the window, and between the two + // side panels rather than across them: it is the graph that gives + // up room to it, and the branches and the commit stay whole. + self.terminal_panel(ctx, settings); + if self.deciding.is_some() { let mut act = None; egui::CentralPanel::default() @@ -4922,6 +4945,261 @@ impl Open { } } +/// The terminal: a shell in this tab's folder, in a panel under the graph. +/// +/// The shell is the tab's and the panel is the window's. Each repository +/// has its own shell, started the first time the panel is opened on it and +/// left running when the panel is put away; whether the panel is open, and +/// how tall, is one answer for every tab, because it is about where +/// somebody likes their terminal and not about a repository. +impl Open { + /// The button for it, at the end of the actions. Says whether it was + /// pressed. + fn terminal_button(ui: &mut egui::Ui, settings: &Settings) -> bool { + theme::vrule(ui); + terminal_view::toggle(ui, settings.terminal == Panel::Expanded) + .on_hover_text("Show/Hide Terminal (Ctrl+`)") + .clicked() + } + + /// Opens the panel, or puts it away when it is open. Folded counts as + /// not open: pressing the button on a folded panel unfolds it. + fn toggle_terminal(&mut self, settings: &mut Settings) { + self.set_terminal( + settings, + match settings.terminal { + Panel::Expanded => Panel::Hidden, + _ => Panel::Expanded, + }, + ); + } + + /// Shows that much of the panel, and writes it down. + fn set_terminal(&mut self, settings: &mut Settings, panel: Panel) { + if panel == Panel::Expanded { + // Opened to be typed into, so the keyboard goes with it. + if let Some(session) = &mut self.terminal { + session.view.wants_focus = true; + } + } + if settings.terminal != panel { + settings.terminal = panel; + if let Err(err) = settings.save() { + self.note_error(format!("could not remember that: {err:#}")); + } + } + } + + /// Starts this tab's shell. + /// + /// In the repository's folder, as whoever this tab is working as: the + /// profile's name on what is committed from it and the profile's key + /// on what is fetched and pushed, for the reason the buttons use them. + /// Both are read when the shell starts. A profile changed afterwards + /// is taken on by the next shell, not by one already running, whose + /// environment is its own. + /// + /// For a checkout on another machine the shell is on that machine, in + /// that folder, reached with `ssh`. + fn start_terminal(&self, ctx: &egui::Context) -> std::io::Result { + let who = self.profile.as_ref().and_then(Profile::who); + let key = profile_key(self.profile.as_ref()); + let caret = self.general.terminal_caret; + let start = match &self.remote_descriptor { + Some(remote) => terminal::Start { + program: Some(terminal::remote_shell( + &remote.login.host, + &remote.login.user, + remote.login.port, + &remote.path, + key.as_deref(), + who, + )), + folder: None, + env: Vec::new(), + caret, + }, + None => { + let shell = self.general.terminal_shell.trim(); + terminal::Start { + program: (!shell.is_empty()).then(|| (shell.to_string(), Vec::new())), + folder: Some(std::path::PathBuf::from(&self.path)), + env: terminal::profile_env(who, key.as_deref()), + caret, + } + } + }; + terminal::Session::start(ctx, start) + } + + /// Hears the shell out, whether or not its panel is on screen. Says + /// whether the shell has just ended. + /// + /// Every tab's, every frame, like the rest of the polling: a program + /// in a terminal asks its terminal questions and waits for the answers, + /// and it does not stop asking because somebody is looking at another + /// tab. + fn poll_terminal(&mut self, ctx: &egui::Context) -> bool { + let Some(session) = &mut self.terminal else { + return false; + }; + session.pump(ctx); + if session.is_over() { + self.terminal = None; + return true; + } + match session.quiet() { + terminal::Quiet::Nothing => {} + terminal::Quiet::Wait(wait) => ctx.request_repaint_after(wait), + terminal::Quiet::Now { asked } => self.after_terminal(asked), + } + false + } + + /// Looks at the repository after the shell has had something to say. + /// + /// 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. + /// + /// 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 + /// message being amended and moves what is selected, and `ls` is not a + /// reason for either. + /// + /// Not for a checkout on another machine: looking there is a round + /// trip on the thread that paints, and one after every command would + /// be a window that stutters while somebody types. The reload button + /// is still where it was. + fn after_terminal(&mut self, asked: bool) { + if self.is_remote() || self.job.is_some() { + return; + } + let Ok(mut repo) = self.repo() else { + return; + }; + let refs = repo.references().unwrap_or_default(); + let same = refs.len() == self.refs.len() + && refs.iter().zip(&self.refs).all(|(now, then)| { + now.name == then.name + && now.kind == then.kind + && now.target == then.target + && now.is_head == then.is_head + }) + && repo.head_name() == self.head + && (!self.looked || repo.head_id() == self.head_at) + && repo.half_done() == self.half + && repo.stashes().map(|stashes| stashes.len()).unwrap_or(0) == self.stashes.len(); + drop(repo); + + match (same, asked) { + (false, _) => self.load(), + (true, true) => self.refresh(), + (true, false) => {} + } + } + + /// 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 + // keyboard is -- including in the terminal, which is where it is + // when somebody wants the panel out of the way. + if ctx.input_mut(|input| input.consume_key(egui::Modifiers::CTRL, egui::Key::Backtick)) { + self.toggle_terminal(settings); + } + + let title = self + .terminal + .as_ref() + .and_then(|session| session.title()) + .map(str::to_string); + let mut act = None; + + match settings.terminal { + Panel::Hidden => return, + Panel::Minimized => { + egui::TopBottomPanel::bottom("terminal-folded") + .exact_height(terminal_view::BAR) + .frame(egui::Frame::NONE.fill(theme::raised())) + .show(ctx, |ui| { + act = terminal_view::bar(ui, true, title.as_deref()); + }); + } + Panel::Expanded => { + if self.terminal.is_none() { + match self.start_terminal(ctx) { + Ok(mut session) => { + session.view.wants_focus = true; + self.terminal = Some(session); + } + // Put away as well as said: an open panel asks for + // a shell on every frame, and this one has just + // been refused. + Err(err) => { + self.note_error(format!("Failed to start shell process: {err}")); + settings.terminal = Panel::Hidden; + let _ = settings.save(); + return; + } + } + } + + // Never so tall that what it is under cannot be seen. + let shortest = gitrust_core::SHORTEST_TERMINAL as f32; + let tallest = (ctx.screen_rect().height() * 0.75).max(shortest + 1.0); + // One name for every tab, and not a tab's own: the height + // is the window's, like whether the panel is open at all. + let shown = egui::TopBottomPanel::bottom("terminal") + .resizable(true) + .default_height((settings.terminal_height as f32).clamp(shortest, tallest)) + .height_range(shortest..=tallest) + .frame(egui::Frame::NONE.fill(theme::terminal_ground())) + .show(ctx, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let band = egui::Rect::from_min_size( + ui.max_rect().min, + egui::vec2(ui.max_rect().width(), terminal_view::BAR), + ); + ui.painter().rect_filled(band, 0, theme::raised()); + act = terminal_view::bar(ui, false, title.as_deref()); + ui.push_id(self.salt, |ui| { + if let Some(session) = &mut self.terminal { + if let Some(asked) = terminal_view::show(ui, session, &self.general) { + act = Some(asked); + } + } + }); + }); + + // Written down once the dragging is over, and not sixty + // times a second while it is going on. + let height = shown.response.rect.height().round() as u32; + let dragging = ctx.input(|input| input.pointer.any_down()); + if height != settings.terminal_height && !dragging { + settings.terminal_height = height; + let _ = settings.save(); + } + } + } + + match act { + Some(terminal_view::Act::Minimize) => self.set_terminal(settings, Panel::Minimized), + Some(terminal_view::Act::Expand) => self.set_terminal(settings, Panel::Expanded), + Some(terminal_view::Act::Hide) => self.set_terminal(settings, Panel::Hidden), + // The shell is told to go by being let go of. + Some(terminal_view::Act::Kill) => { + self.terminal = None; + self.set_terminal(settings, Panel::Hidden); + } + Some(terminal_view::Act::Open(address)) => self.open_in_browser(&address), + None => {} + } + } +} + impl Open { fn top_bar(&mut self, ctx: &egui::Context, settings: &mut Settings) { if self.is_remote() { @@ -4963,6 +5241,7 @@ impl Open { self.job.is_some(), &mut self.draft, ); + let terminal = Self::terminal_button(ui, settings); let mut reload = false; // Taken out and put back rather than lent to the closure: @@ -4996,6 +5275,8 @@ impl Open { self.act(action); } else if reload { self.load(); + } else if terminal { + self.toggle_terminal(settings); } }); }); @@ -5047,6 +5328,7 @@ impl Open { self.job.is_some(), &mut self.draft, ); + let terminal = Self::terminal_button(ui, settings); let mut appearance_changed = false; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui @@ -5066,6 +5348,8 @@ impl Open { } if let Some(action) = action { self.act(action); + } else if terminal { + self.toggle_terminal(settings); } }) }); diff --git a/crates/gitrust-ui/src/prefs_view.rs b/crates/gitrust-ui/src/prefs_view.rs index 6479df2..70438e6 100644 --- a/crates/gitrust-ui/src/prefs_view.rs +++ b/crates/gitrust-ui/src/prefs_view.rs @@ -19,7 +19,10 @@ //! Like every other view here it touches nothing but what it is handed. use eframe::egui::{self, RichText}; -use gitrust_core::{start, General, FEWEST_COMMITS, LONGEST_FETCH_WAIT}; +use gitrust_core::{ + start, Caret, General, FEWEST_COMMITS, LARGEST_TERMINAL_FONT, LONGEST_FETCH_WAIT, + LOOSEST_TERMINAL_LINE, SMALLEST_TERMINAL_FONT, TIGHTEST_TERMINAL_LINE, +}; use crate::theme; @@ -42,6 +45,9 @@ pub struct Preferring { git_branch: String, /// Whether forgetting the tokens has been asked for and not confirmed. asking: bool, + /// The shell this account logs in with, read once when the screen + /// opens. It is what the empty box for the terminal's program shows. + login_shell: String, } impl Preferring { @@ -50,6 +56,8 @@ impl Preferring { branch: general.default_branch.clone(), git_branch: start::git_default_branch(), asking: false, + login_shell: std::env::var(if cfg!(windows) { "COMSPEC" } else { "SHELL" }) + .unwrap_or_default(), } } } @@ -313,6 +321,98 @@ pub fn show( ); }); + ui.add_space(8.0); + theme::rule(ui); + ui.add_space(12.0); + ui.horizontal(|ui| { + ui.add_space(28.0); + ui.label( + RichText::new("In-App Terminal").font(theme::strong(15.0)).color(theme::text()), + ); + }); + ui.add_space(18.0); + + row(ui, "Font Size", |ui| { + ui.add( + egui::DragValue::new(&mut general.terminal_font) + .range(SMALLEST_TERMINAL_FONT..=LARGEST_TERMINAL_FONT) + .speed(0.1), + ); + help( + ui, + &format!( + "In points, between {SMALLEST_TERMINAL_FONT} and {LARGEST_TERMINAL_FONT}. \ + The face is Fira Mono, the one the hashes and the dates are in." + ), + ); + }); + + row(ui, "Line Height", |ui| { + // Kept as hundredths so that two preferences can be told + // apart exactly, and shown as what everybody calls it. + let mut height = general.terminal_line as f32 / 100.0; + let (tightest, loosest) = ( + TIGHTEST_TERMINAL_LINE as f32 / 100.0, + LOOSEST_TERMINAL_LINE as f32 / 100.0, + ); + let dragged = ui.add( + egui::DragValue::new(&mut height) + .range(tightest..=loosest) + .speed(0.01) + .fixed_decimals(2), + ); + if dragged.changed() { + general.terminal_line = (height * 100.0).round() as u32; + } + help(ui, "How many times a letter's own height each line is given."); + }); + + row(ui, "Cursor Style", |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + for caret in Caret::ALL { + ui.selectable_value(&mut general.terminal_caret, caret, caret.label()); + } + }); + help( + ui, + "What marks where the next letter goes. A program that asks for a \ + caret of its own gets it.", + ); + }); + + row(ui, "Dim terminal when unfocused", |ui| { + ui.checkbox(&mut general.terminal_dim, ""); + help( + ui, + "The terminal goes quiet while the keyboard is somewhere else, so it is \ + plain where what you type will go.", + ); + }); + + row(ui, "Default In-App Terminal", |ui| { + let typed = ui.add( + egui::TextEdit::singleline(&mut general.terminal_shell) + .desired_width(320.0) + .margin(egui::vec2(8.0, 5.0)) + .font(theme::mono(11.5)) + .hint_text(RichText::new(&state.login_shell).color(theme::faint())), + ); + if typed.lost_focus() { + general.terminal_shell = general.terminal_shell.trim().to_string(); + } + help( + ui, + "The program a terminal runs. Empty is the shell this account logs in \ + with. A terminal already open keeps the one it started with.", + ); + warning( + ui, + "For a checkout on another machine the terminal is an ssh to that \ + machine, and the shell is the one the account has there.", + ); + }); + ui.add_space(24.0); }); diff --git a/crates/gitrust-ui/src/terminal.rs b/crates/gitrust-ui/src/terminal.rs new file mode 100644 index 0000000..ef8188d --- /dev/null +++ b/crates/gitrust-ui/src/terminal.rs @@ -0,0 +1,735 @@ +//! A shell running in the window, and everything about it that is not paint. +//! +//! Three things make a terminal and this file holds all three: a +//! pseudo-terminal with a shell on the far end of it, something that reads +//! what the shell writes and keeps the grid of letters that writing +//! describes, and the bytes a key turns into on its way back. The painting +//! is next door in `terminal_view`, and knows nothing about processes. +//! +//! The first two are `alacritty_terminal`, the inside of the terminal of +//! that name, and they are the one part of this program that is somebody +//! else's and was never going to be otherwise. What a shell writes is +//! escape sequences forty years deep -- the alternate screen `vim` draws +//! on, scroll regions, the eleven ways of saying a colour -- and a reader +//! of them that is nearly right is a terminal where `git log` works and +//! `git rebase -i` does not. It also brings the pseudo-terminal itself on +//! all three systems, which on Windows is not a small thing. +//! +//! One session per tab, started the first time its panel is opened and in +//! the folder of that tab's repository. Putting the panel away does not +//! stop it; killing it does, and so does the shell exiting. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::io; +use std::path::PathBuf; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use alacritty_terminal::event::{Event, EventListener, WindowSize}; +use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg}; +use alacritty_terminal::grid::{Dimensions, Scroll}; +use alacritty_terminal::sync::FairMutex; +use alacritty_terminal::term::{Config, Term, TermMode}; +use alacritty_terminal::tty; +use alacritty_terminal::vte::ansi::{CursorShape, CursorStyle, Rgb}; +use eframe::egui::{self, Color32, Key, Modifiers}; +use gitrust_core::Caret; + +use crate::theme; + +/// How many lines that have scrolled off the top are kept. +const HISTORY: usize = 5_000; + +/// How long the shell has to say nothing before it is taken to have +/// finished saying it. +const QUIET: Duration = Duration::from_millis(400); + +/// What a session is started with. +pub struct Start { + /// The program and what it is handed. `None` is the shell this account + /// logs in with. + pub program: Option<(String, Vec)>, + /// Where it starts. A folder that has gone is not an error: the shell + /// starts wherever the window was started. + pub folder: Option, + /// What is put in its environment on top of the window's own. + pub env: Vec<(String, String)>, + pub caret: Caret, +} + +/// Hands on what the terminal has to say to the window, and wakes the +/// window up to hear it. It is called from the thread that reads the shell. +#[derive(Clone)] +pub struct Proxy { + events: Sender, + ctx: egui::Context, +} + +impl EventListener for Proxy { + fn send_event(&self, event: Event) { + let _ = self.events.send(event); + self.ctx.request_repaint(); + } +} + +/// How many letters fit, which is all the grid wants to know of a size. +struct Room { + cols: usize, + rows: usize, +} + +impl Dimensions for Room { + fn total_lines(&self) -> usize { + self.rows + } + + fn screen_lines(&self) -> usize { + self.rows + } + + fn columns(&self) -> usize { + self.cols + } +} + +/// What the shell going quiet means for whoever is watching the repository. +#[derive(Debug, PartialEq, Eq)] +pub enum Quiet { + /// Nothing has happened since the last look. + Nothing, + /// Something is still being said. Ask again after this long. + Wait(Duration), + /// Something was said and it has stopped. `asked` is whether a line was + /// sent in before it: a command, as far as anybody outside can tell. + Now { asked: bool }, +} + +/// One shell, and the grid it has written. +pub struct Session { + term: Arc>>, + to_shell: EventLoopSender, + events: Receiver, + cols: usize, + rows: usize, + cell: (u16, u16), + caret: Caret, + title: Option, + over: bool, + /// A line went in and nobody has yet looked at what it did. + asked: bool, + /// The shell has said something since the last look. + stirred: bool, + /// When it last did. + heard: Instant, + /// What the painting keeps between frames. It is here because it is + /// about this shell and has to go when the shell does. + pub view: crate::terminal_view::Kept, +} + +impl Session { + /// Starts the shell. What comes back when it cannot is what the system + /// said, which is usually that the program is not there. + pub fn start(ctx: &egui::Context, start: Start) -> io::Result { + let (cols, rows) = (80, 30); + let size = WindowSize { num_cols: cols as u16, num_lines: rows as u16, cell_width: 8, cell_height: 16 }; + + // Said in the environment handed over rather than in the window's + // own: that one is read by every thread here and by every `git` and + // `gh` this program runs, none of which is drawing on a terminal. + let mut env: HashMap = HashMap::from([ + ("TERM".to_string(), "xterm-256color".to_string()), + ("COLORTERM".to_string(), "truecolor".to_string()), + ("TERM_PROGRAM".to_string(), "gitrust".to_string()), + ]); + env.extend(start.env); + + let options = tty::Options { + shell: start + .program + .map(|(program, args)| tty::Shell::new(program, args)), + working_directory: start.folder.filter(|folder| folder.is_dir()), + env, + ..tty::Options::default() + }; + let pty = tty::new(&options, size, 0)?; + + let (events, heard) = mpsc::channel(); + let proxy = Proxy { events, ctx: ctx.clone() }; + let config = Config { + scrolling_history: HISTORY, + default_cursor_style: style_of(start.caret), + ..Config::default() + }; + let term = Arc::new(FairMutex::new(Term::new(config, &Room { cols, rows }, proxy.clone()))); + + let reading = EventLoop::new(term.clone(), proxy, pty, false, false)?; + let to_shell = reading.channel(); + // Not kept: the thread ends when it is told to or when the shell + // does, and takes the pseudo-terminal with it either way. + let _ = reading.spawn(); + + Ok(Self { + term, + to_shell, + events: heard, + cols, + rows, + cell: (8, 16), + caret: start.caret, + title: None, + over: false, + asked: false, + stirred: false, + heard: Instant::now(), + view: crate::terminal_view::Kept::default(), + }) + } + + /// Hears what the terminal has had to say since the last frame. + /// + /// Most of it is the terminal asking for something only a window has: + /// the clipboard, a colour, its own size in pixels. A program that asks + /// and gets no answer waits for one, which is how `vim` comes to take a + /// second to open in a terminal that is nearly finished. + pub fn pump(&mut self, ctx: &egui::Context) { + let palette = Palette::current(); + while let Ok(event) = self.events.try_recv() { + match event { + Event::Wakeup => { + self.stirred = true; + self.heard = Instant::now(); + } + Event::PtyWrite(text) => self.send(text.into_bytes()), + Event::Title(title) => self.title = Some(title), + Event::ResetTitle => self.title = None, + Event::ClipboardStore(_, text) => ctx.copy_text(text), + Event::ColorRequest(index, answer) => { + let colour = self.term.lock().colors()[index] + .unwrap_or_else(|| rgb_of(palette.indexed(index))); + self.send(answer(colour).into_bytes()); + } + Event::TextAreaSizeRequest(answer) => { + self.send(answer(self.size()).into_bytes()); + } + Event::Exit | Event::ChildExit(_) => self.over = true, + // Reading the clipboard for a program that asks is off in + // the terminal's own settings, so this is never sent; a + // bell is a noise, and nobody asked the window for one. + Event::ClipboardLoad(..) + | Event::Bell + | Event::MouseCursorDirty + | Event::CursorBlinkingChange => {} + } + } + } + + /// Whether the shell has gone. There is nothing to do with a session + /// after that but let go of it. + pub fn is_over(&self) -> bool { + self.over + } + + /// What the shell calls itself just now, when it says. + pub fn title(&self) -> Option<&str> { + self.title.as_deref().filter(|title| !title.trim().is_empty()) + } + + /// Whether what the shell was saying has stopped, asked once per frame + /// by whoever wants to look at the repository afterwards. + /// + /// Nothing here knows when a command ends: a shell does not say. What it + /// does is write, and then stop writing, and a prompt is the last thing + /// it writes. So a burst that has been over for a moment is taken for a + /// finished command, which is wrong about `sleep 60` and costs one look + /// at a repository that has not changed. + pub fn quiet(&mut self) -> Quiet { + if !self.stirred && !self.asked { + return Quiet::Nothing; + } + let since = self.heard.elapsed(); + if since < QUIET { + return Quiet::Wait(QUIET - since); + } + let asked = std::mem::take(&mut self.asked); + self.stirred = false; + Quiet::Now { asked } + } + + /// Sends bytes to the shell as they are. + pub fn send(&self, bytes: impl Into>) { + let bytes = bytes.into(); + // Nothing at all is not nothing to the far end: it reads it as the + // end of the input. + if !bytes.is_empty() { + let _ = self.to_shell.send(Msg::Input(bytes)); + } + } + + /// Sends what somebody typed, which is the same bytes and two things + /// more: the view goes back to the bottom, where the typing is, and + /// what was selected is let go of, because it was selected in a screen + /// that is about to move. + pub fn type_in(&mut self, bytes: Vec) { + if bytes.is_empty() { + return; + } + if bytes.iter().any(|byte| *byte == b'\r' || *byte == b'\n') { + self.asked = true; + self.heard = Instant::now(); + } + { + let mut term = self.term.lock(); + term.scroll_display(Scroll::Bottom); + term.selection = None; + } + self.send(bytes); + } + + /// Pastes: the text, wrapped the way a program that asked to be told + /// has asked, so that a pasted paragraph is a paragraph to it and not + /// forty lines typed very fast. + pub fn paste(&mut self, text: &str) { + let bracketed = self.mode().contains(TermMode::BRACKETED_PASTE); + let bytes = match bracketed { + // The marks themselves are taken out of what is pasted. Text + // that carries the closing one would otherwise end the paste + // early and have the rest of itself run as typing. + true => { + let clean = text.replace("\x1b[200~", "").replace("\x1b[201~", ""); + format!("\x1b[200~{clean}\x1b[201~").into_bytes() + } + // A line ends with a carriage return when it is typed, and a + // paste nobody asked to be told about is typing. + false => text.replace("\r\n", "\r").replace('\n', "\r").into_bytes(), + }; + self.type_in(bytes); + } + + /// Tells the grid and the shell how many letters there is room for. + pub fn fit(&mut self, cols: usize, rows: usize, cell: (u16, u16)) { + if (cols, rows, cell) == (self.cols, self.rows, self.cell) { + return; + } + (self.cols, self.rows, self.cell) = (cols, rows, cell); + let _ = self.to_shell.send(Msg::Resize(self.size())); + self.term.lock().resize(Room { cols, rows }); + } + + fn size(&self) -> WindowSize { + WindowSize { + num_cols: self.cols as u16, + num_lines: self.rows as u16, + cell_width: self.cell.0, + cell_height: self.cell.1, + } + } + + /// Takes on the caret the preferences name, for a shell already open. + pub fn set_caret(&mut self, caret: Caret) { + if caret == self.caret { + return; + } + self.caret = caret; + self.term.lock().set_options(Config { + scrolling_history: HISTORY, + default_cursor_style: style_of(caret), + ..Config::default() + }); + } + + /// What the program in the terminal has asked of it: which keys it + /// wants spelt differently, whether it wants the mouse. + pub fn mode(&self) -> TermMode { + *self.term.lock().mode() + } + + /// The grid, held still for as long as what comes back is kept. + pub fn grid(&self) -> impl std::ops::DerefMut> + '_ { + self.term.lock() + } +} + +impl Drop for Session { + fn drop(&mut self) { + // The thread reading the shell owns the pseudo-terminal, and closes + // it on its way out; the shell is told to go when it does. + let _ = self.to_shell.send(Msg::Shutdown); + } +} + +fn style_of(caret: Caret) -> CursorStyle { + CursorStyle { + shape: match caret { + Caret::Bar => CursorShape::Beam, + Caret::Block => CursorShape::Block, + Caret::Underline => CursorShape::Underline, + }, + blinking: false, + } +} + +fn rgb_of(colour: Color32) -> Rgb { + Rgb { r: colour.r(), g: colour.g(), b: colour.b() } +} + +/// The colours a terminal is drawn in. +/// +/// Sixteen of them have names every program agrees on, and those come from +/// the theme. The other two hundred and forty are arithmetic: a cube of six +/// steps a side and a ramp of greys, the same in every terminal there is. +pub struct Palette { + /// What is behind the letters. + pub ground: Color32, + /// The letters, when a program has not said. + pub ink: Color32, + pub caret: Color32, + /// What is behind the letters somebody has selected. + pub selection: Color32, + ansi: [Color32; 16], +} + +impl Palette { + pub fn current() -> Self { + let ground = theme::terminal_ground(); + let lane = theme::lane(0); + Self { + ground, + ink: theme::text(), + caret: lane, + selection: mix(ground, lane, 0.32), + ansi: theme::terminal(), + } + } + + /// One of the two hundred and fifty-six, or what stands in for the few + /// named ones past them. + pub fn indexed(&self, index: usize) -> Color32 { + match index { + 0..=15 => self.ansi[index], + 16..=231 => { + let step = |n: usize| match n { + 0 => 0, + n => (55 + 40 * n) as u8, + }; + let index = index - 16; + Color32::from_rgb(step(index / 36), step(index / 6 % 6), step(index % 6)) + } + 232..=255 => { + let grey = (8 + 10 * (index - 232)) as u8; + Color32::from_rgb(grey, grey, grey) + } + // Foreground, background and the caret, in the order the + // terminal numbers them. + 256 => self.ink, + 257 => self.ground, + 258 => self.caret, + // The dim eight and the dim foreground: the colour itself, let + // down towards what is behind it. + 259..=266 => mix(self.ground, self.ansi[index - 259], 0.66), + 267 => self.ansi[15], + _ => mix(self.ground, self.ink, 0.66), + } + } +} + +/// `part` of the way from one colour to another. +pub fn mix(from: Color32, to: Color32, part: f32) -> Color32 { + let blend = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * part).round() as u8; + Color32::from_rgb(blend(from.r(), to.r()), blend(from.g(), to.g()), blend(from.b(), to.b())) +} + +/// What a key is to a shell. +/// +/// Only the keys that are not letters: a letter arrives as the text it +/// types, already through the keyboard layout, and is sent as that. What is +/// left is the keys with no letter of their own and the ones held with +/// Control, and each of those is a few bytes agreed on long before there +/// were windows. `None` is a key that says nothing by itself. +pub fn key_bytes(key: Key, held: Modifiers, mode: TermMode) -> Option> { + // What xterm adds to a key held with something: one, plus one for + // Shift, two for Alt and four for Control. + let extra = 1 + held.shift as u8 + 2 * held.alt as u8 + 4 * held.ctrl as u8; + let plain = extra == 1; + let app = mode.contains(TermMode::APP_CURSOR); + + // An arrow, Home or End: one letter, said three ways. + let lettered = |letter: char| match (plain, app) { + (true, true) => format!("\x1bO{letter}"), + (true, false) => format!("\x1b[{letter}"), + (false, _) => format!("\x1b[1;{extra}{letter}"), + }; + // A key that is a number and a tilde. + let numbered = |number: u8| match plain { + true => format!("\x1b[{number}~"), + false => format!("\x1b[{number};{extra}~"), + }; + // Alt before a key is Escape before its bytes. + let met = |bytes: &[u8]| { + let mut all = Vec::with_capacity(bytes.len() + 1); + if held.alt { + all.push(0x1b); + } + all.extend_from_slice(bytes); + all + }; + + let text = match key { + Key::ArrowUp => lettered('A'), + Key::ArrowDown => lettered('B'), + Key::ArrowRight => lettered('C'), + Key::ArrowLeft => lettered('D'), + Key::Home => lettered('H'), + Key::End => lettered('F'), + Key::Insert => numbered(2), + Key::Delete => numbered(3), + Key::PageUp => numbered(5), + Key::PageDown => numbered(6), + Key::F1 | Key::F2 | Key::F3 | Key::F4 => { + let letter = match key { + Key::F1 => 'P', + Key::F2 => 'Q', + Key::F3 => 'R', + _ => 'S', + }; + match plain { + true => format!("\x1bO{letter}"), + false => format!("\x1b[1;{extra}{letter}"), + } + } + Key::F5 => numbered(15), + Key::F6 => numbered(17), + Key::F7 => numbered(18), + Key::F8 => numbered(19), + Key::F9 => numbered(20), + Key::F10 => numbered(21), + Key::F11 => numbered(23), + Key::F12 => numbered(24), + + Key::Enter => return Some(met(b"\r")), + Key::Escape => return Some(met(b"\x1b")), + Key::Tab if held.shift => return Some(b"\x1b[Z".to_vec()), + Key::Tab => return Some(met(b"\t")), + // Rubout, which is what a terminal has sent for this key since + // the key stopped meaning "move left". With Control it is the + // older one, which shells read as "the whole word". + Key::Backspace if held.ctrl => return Some(met(b"\x08")), + Key::Backspace => return Some(met(b"\x7f")), + + // Held with Control, a key is itself with its top bits taken off: + // that is what Control was. A letter without it is text, and comes + // by the other road. + _ if held.ctrl => { + let byte = match key { + Key::Space | Key::Num2 => 0x00, + Key::OpenBracket | Key::Num3 => 0x1b, + Key::Backslash | Key::Num4 => 0x1c, + Key::CloseBracket | Key::Num5 => 0x1d, + Key::Num6 => 0x1e, + Key::Slash | Key::Minus | Key::Num7 => 0x1f, + Key::Num8 => 0x7f, + key => { + let name = key.name(); + match name.as_bytes() { + [letter @ b'A'..=b'Z'] => letter & 0x1f, + _ => return None, + } + } + }; + return Some(met(&[byte])); + } + _ => return None, + }; + Some(text.into_bytes()) +} + +/// A string as one word of a shell command, whatever is in it. +pub fn quoted(text: &str) -> String { + format!("'{}'", text.replace('\'', "'\\''")) +} + +/// The command that opens a shell in a checkout on another machine. +/// +/// It is `ssh`, the program, in a terminal on this machine, and not the +/// connection the tab already has. That one is a library's and is busy +/// being a Git client; this one has to be somebody typing, with their own +/// `known_hosts` and their own agent and a passphrase asked for where they +/// can answer it. The key is the profile's when it has one, and no other +/// is offered then: which key opens the door is which client you are. +pub fn remote_shell( + host: &str, + user: &str, + port: u16, + folder: &str, + key: Option<&std::path::Path>, + who: Option<(&str, &str)>, +) -> (String, Vec) { + let mut args = vec!["-t".to_string(), "-p".to_string(), port.to_string()]; + if let Some(key) = key { + args.extend(["-i".to_string(), key.display().to_string()]); + args.extend(["-o".to_string(), "IdentitiesOnly=yes".to_string()]); + } + args.push(format!("{user}@{host}")); + + // The name goes along the way it goes along with every Git command + // this program runs there: said for this one shell, and written into + // nothing on that machine. + let mut there = format!("cd -- {} && ", quoted(folder)); + if let Some((name, email)) = who { + for (variable, value) in [ + ("GIT_AUTHOR_NAME", name), + ("GIT_AUTHOR_EMAIL", email), + ("GIT_COMMITTER_NAME", name), + ("GIT_COMMITTER_EMAIL", email), + ] { + there.push_str(&format!("export {variable}={} && ", quoted(value))); + } + } + there.push_str("exec \"${SHELL:-/bin/sh}\" -l"); + args.push(there); + ("ssh".to_string(), args) +} + +/// What a profile puts in a shell's environment on this machine. +/// +/// The same two things it decides everywhere else. A commit made by typing +/// `git commit` in this terminal is made in this window, and one that went +/// out under another client's name because it was typed rather than +/// clicked would be the mistake profiles are here to stop. +pub fn profile_env( + who: Option<(&str, &str)>, + key: Option<&std::path::Path>, +) -> Vec<(String, String)> { + let mut env = Vec::new(); + if let Some((name, email)) = who { + for (variable, value) in [ + ("GIT_AUTHOR_NAME", name), + ("GIT_AUTHOR_EMAIL", email), + ("GIT_COMMITTER_NAME", name), + ("GIT_COMMITTER_EMAIL", email), + ] { + env.push((variable.to_string(), value.to_string())); + } + } + if let Some(key) = key { + env.push(( + "GIT_SSH_COMMAND".to_string(), + format!("ssh -i {} -o IdentitiesOnly=yes", quoted(&key.display().to_string())), + )); + } + env +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bytes(key: Key, held: Modifiers, mode: TermMode) -> Option { + key_bytes(key, held, mode).map(|bytes| String::from_utf8_lossy(&bytes).into_owned()) + } + + #[test] + fn an_arrow_is_spelt_the_way_the_program_asked() { + let none = TermMode::empty(); + assert_eq!(bytes(Key::ArrowUp, Modifiers::NONE, none).as_deref(), Some("\x1b[A")); + // `vim` and `less` ask for the other spelling, and move by nothing + // at all when they are sent the first. + assert_eq!( + bytes(Key::ArrowUp, Modifiers::NONE, TermMode::APP_CURSOR).as_deref(), + Some("\x1bOA") + ); + // Held with something, it is the long form whichever was asked for. + assert_eq!(bytes(Key::ArrowLeft, Modifiers::CTRL, none).as_deref(), Some("\x1b[1;5D")); + assert_eq!( + bytes(Key::ArrowRight, Modifiers::SHIFT | Modifiers::ALT, TermMode::APP_CURSOR) + .as_deref(), + Some("\x1b[1;4C") + ); + } + + #[test] + fn control_takes_the_top_off_a_letter() { + let none = TermMode::empty(); + assert_eq!(key_bytes(Key::D, Modifiers::CTRL, none), Some(vec![0x04])); + assert_eq!(key_bytes(Key::Z, Modifiers::CTRL, none), Some(vec![0x1a])); + assert_eq!(key_bytes(Key::Space, Modifiers::CTRL, none), Some(vec![0x00])); + // And Alt puts an Escape in front of whatever that came to. + assert_eq!( + key_bytes(Key::B, Modifiers::CTRL | Modifiers::ALT, none), + Some(vec![0x1b, 0x02]) + ); + // A letter on its own is text, and is not this function's to send. + assert_eq!(key_bytes(Key::D, Modifiers::NONE, none), None); + } + + #[test] + fn the_keys_with_no_letter_say_what_they_always_said() { + let none = TermMode::empty(); + assert_eq!(key_bytes(Key::Enter, Modifiers::NONE, none), Some(b"\r".to_vec())); + assert_eq!(key_bytes(Key::Backspace, Modifiers::NONE, none), Some(vec![0x7f])); + assert_eq!(key_bytes(Key::Backspace, Modifiers::ALT, none), Some(vec![0x1b, 0x7f])); + assert_eq!(key_bytes(Key::Tab, Modifiers::SHIFT, none), Some(b"\x1b[Z".to_vec())); + assert_eq!(bytes(Key::Delete, Modifiers::NONE, none).as_deref(), Some("\x1b[3~")); + assert_eq!(bytes(Key::PageDown, Modifiers::NONE, none).as_deref(), Some("\x1b[6~")); + assert_eq!(bytes(Key::F1, Modifiers::NONE, none).as_deref(), Some("\x1bOP")); + assert_eq!(bytes(Key::F5, Modifiers::NONE, none).as_deref(), Some("\x1b[15~")); + assert_eq!(bytes(Key::F5, Modifiers::SHIFT, none).as_deref(), Some("\x1b[15;2~")); + } + + #[test] + fn the_cube_and_the_greys_are_the_ones_every_terminal_has() { + let palette = Palette::current(); + assert_eq!(palette.indexed(16), Color32::from_rgb(0, 0, 0)); + assert_eq!(palette.indexed(196), Color32::from_rgb(255, 0, 0)); + assert_eq!(palette.indexed(231), Color32::from_rgb(255, 255, 255)); + assert_eq!(palette.indexed(232), Color32::from_rgb(8, 8, 8)); + assert_eq!(palette.indexed(255), Color32::from_rgb(238, 238, 238)); + } + + #[test] + fn a_folder_with_a_quote_in_it_is_still_one_word() { + assert_eq!(quoted("/srv/it's here"), "'/srv/it'\\''s here'"); + } + + #[test] + fn a_shell_on_another_machine_opens_in_the_checkout_as_the_profile() { + let key = std::path::Path::new("/home/someone/.ssh/acme"); + let (program, args) = remote_shell( + "host.example", + "dev", + 2222, + "/srv/my project", + Some(key), + Some(("Some One", "one@acme.example")), + ); + assert_eq!(program, "ssh"); + assert_eq!( + &args[..7], + ["-t", "-p", "2222", "-i", "/home/someone/.ssh/acme", "-o", "IdentitiesOnly=yes"] + ); + assert_eq!(args[7], "dev@host.example"); + assert!(args[8].starts_with("cd -- '/srv/my project' && ")); + assert!(args[8].contains("export GIT_AUTHOR_NAME='Some One' && ")); + assert!(args[8].ends_with("exec \"${SHELL:-/bin/sh}\" -l")); + + // With no profile there is nothing to say but where. + let (_, args) = remote_shell("host.example", "dev", 22, "/srv/p", None, None); + assert_eq!(args, ["-t", "-p", "22", "dev@host.example", "cd -- '/srv/p' && exec \"${SHELL:-/bin/sh}\" -l"]); + } + + #[test] + fn a_profile_is_who_a_typed_commit_is_from() { + let env = profile_env( + Some(("Some One", "one@acme.example")), + Some(std::path::Path::new("/keys/acme key")), + ); + assert!(env.contains(&("GIT_COMMITTER_EMAIL".to_string(), "one@acme.example".to_string()))); + assert!(env.contains(&( + "GIT_SSH_COMMAND".to_string(), + "ssh -i '/keys/acme key' -o IdentitiesOnly=yes".to_string() + ))); + // A profile that says neither leaves the shell as it would have been. + assert!(profile_env(None, None).is_empty()); + } +} diff --git a/crates/gitrust-ui/src/terminal_view.rs b/crates/gitrust-ui/src/terminal_view.rs new file mode 100644 index 0000000..a1111df --- /dev/null +++ b/crates/gitrust-ui/src/terminal_view.rs @@ -0,0 +1,1334 @@ +//! The terminal as it is seen and touched: the grid painted, the keyboard +//! and the mouse heard on the shell's behalf, and the bar above it. +//! +//! The grid is letters in boxes, and the boxes are the point. Text here is +//! not laid out, it is placed: a letter goes in the column the shell put +//! it in, whatever its neighbours are, because a program that draws a +//! table is counting columns and has no way to know how wide this window +//! thinks a letter is. So a run of letters that the mono face draws at its +//! own width is painted as one piece of text, and anything else -- a +//! symbol borrowed from another font, a letter two columns wide -- is +//! painted alone, in its own box, where it cannot push the rest along. +//! +//! Like every other view it changes nothing but what it is handed, which +//! here is the session: the keys go into it and the grid comes out of it. +//! What it cannot do itself -- fold the panel, end the shell, open a +//! browser -- it gives back as an [`Act`]. + +use std::collections::HashMap; +use std::ops::Range; + +use alacritty_terminal::grid::{Dimensions, Scroll}; +use alacritty_terminal::index::{Column, Line, Point, Side}; +use alacritty_terminal::selection::{Selection, SelectionType}; +use alacritty_terminal::term::cell::Flags; +use alacritty_terminal::term::TermMode; +use alacritty_terminal::vte::ansi::{Color, CursorShape}; +use eframe::egui::{ + self, + emath::GuiRounding, + text::{LayoutJob, TextFormat}, + Color32, Event, EventFilter, PointerButton, Sense, Stroke, +}; +use gitrust_core::General; + +use crate::terminal::{key_bytes, mix, Palette, Session}; +use crate::theme; + +/// What has been asked of the panel that the panel cannot do itself. +pub enum Act { + /// Fold it down to its bar. + Minimize, + /// Open it up again. + Expand, + /// End the shell and put the panel away. + Kill, + /// Put the panel away and leave the shell running. + Hide, + /// Open an address somebody clicked on. + Open(String), +} + +/// How tall the bar above the terminal is. +pub const BAR: f32 = 26.0; + +/// The room left between the edge of the panel and the letters. +const PAD: egui::Vec2 = egui::vec2(10.0, 6.0); + +/// How wide the handle for scrolling back is. +const SCROLLER: f32 = 9.0; + +/// How much of itself the terminal keeps while the keyboard is elsewhere. +const DIMMED: f32 = 0.55; + +/// How wide the menu behind a right click is. Told, not asked for, like +/// every other menu here. +const MENU: f32 = 210.0; + +/// What the painting remembers between frames about one shell. +#[derive(Default)] +pub struct Kept { + /// Take the keyboard on the next frame: the panel has just been opened, + /// and it was opened to be typed into. + pub wants_focus: bool, + had_focus: bool, + /// The part of a turn of the wheel that was less than a line. + wheel: f32, + /// Which letters the mono face draws at its own width, found out once + /// each, and the size they were asked about at. + plain: HashMap, + plain_size: f32, + /// The next paste to arrive was asked for from the menu, and is a + /// paste whatever is held down when it comes. + paste_next: bool, + /// The mouse button a program in the terminal is being told is down, + /// and the box the pointer was last reported in. + held: Option, + reported: Option<(usize, usize)>, +} + +/// Where everything is, worked out once a frame. +struct Layout { + origin: egui::Pos2, + cell: egui::Vec2, + cols: usize, + rows: usize, +} + +impl Layout { + /// The box a point on the screen is in, kept inside the grid, and + /// which half of the box. + fn at(&self, pos: egui::Pos2) -> (usize, usize, Side) { + let across = ((pos.x - self.origin.x) / self.cell.x).max(0.0); + let down = ((pos.y - self.origin.y) / self.cell.y).max(0.0); + let col = (across as usize).min(self.cols - 1); + let row = (down as usize).min(self.rows - 1); + let side = match across.fract() < 0.5 || across as usize >= self.cols { + true if (across as usize) < self.cols => Side::Left, + _ => Side::Right, + }; + (col, row, side) + } + + fn corner(&self, col: usize, row: usize) -> egui::Pos2 { + self.origin + egui::vec2(col as f32 * self.cell.x, row as f32 * self.cell.y) + } +} + +/// A run of boxes behind which something other than the ground is painted. +struct Band { + row: usize, + from: usize, + to: usize, + colour: Color32, +} + +/// A piece of text and where it starts. +struct Piece { + row: usize, + col: usize, + text: String, + /// How many boxes it covers, for the lines drawn under and through it. + wide: usize, + ink: Color32, + bold: bool, + italic: bool, + under: Option, + struck: bool, + /// What is behind it, for the letters that are drawn rather than set. + ground: Color32, +} + +/// Paints the terminal into whatever room is left and carries what is +/// typed and clicked into the session. +pub fn show(ui: &mut egui::Ui, session: &mut Session, general: &General) -> Option { + let mut act = None; + session.set_caret(general.terminal_caret); + + let palette = Palette::current(); + let size = general.terminal_font as f32; + let font = theme::mono(size); + let (letter, natural) = ui.fonts(|fonts| (fonts.glyph_width(&font, 'M'), fonts.row_height(&font))); + let cell = egui::vec2(letter, (natural * general.terminal_line as f32 / 100.0).ceil()); + + let (rect, response) = ui.allocate_exact_size(ui.available_size(), Sense::click_and_drag()); + let inner = rect.shrink2(PAD); + let layout = Layout { + origin: inner.min.round_to_pixels(ui.pixels_per_point()), + cell, + cols: (((inner.width() - SCROLLER) / cell.x).floor() as usize).max(2), + rows: ((inner.height() / cell.y).floor() as usize).max(1), + }; + // A panel on its way open is a few points tall for a frame, and telling + // the shell it has one line makes it redraw its prompt for one. + if inner.width() > cell.x * 12.0 && inner.height() >= cell.y * 2.0 { + session.fit(layout.cols, layout.rows, (cell.x.round() as u16, cell.y as u16)); + } + + if session.view.plain_size != size { + session.view.plain.clear(); + session.view.plain_size = size; + } + + // ── The keyboard ────────────────────────────────────────────────────── + let pressed = response.drag_started() + || (response.clicked() && ui.input(|input| input.pointer.any_released())); + if std::mem::take(&mut session.view.wants_focus) || pressed { + response.request_focus(); + } + let focused = response.has_focus() && ui.input(|input| input.focused); + let mode = session.mode(); + if focused { + // Tab, the arrows and Escape are keys to a shell before they are + // ways of moving round a window. + ui.memory_mut(|memory| { + memory.set_focus_lock_filter( + response.id, + EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: true }, + ); + }); + typing(ui, session, mode); + } + if focused != session.view.had_focus { + session.view.had_focus = focused; + session.grid().is_focused = focused; + // A program that asked to be told when it is being looked at. + if mode.contains(TermMode::FOCUS_IN_OUT) { + session.send(match focused { + true => b"\x1b[I".as_slice(), + false => b"\x1b[O".as_slice(), + }); + } + } + + // ── The mouse ───────────────────────────────────────────────────────── + // A program that asked for the mouse gets it, and Shift is how to keep + // it from that program: the way every terminal that does this does it. + let shift = ui.input(|input| input.modifiers.shift); + let reporting = mode.intersects(TermMode::MOUSE_MODE) && !shift; + let lines = wheel(ui, session, &response, cell.y); + if reporting { + report(ui, session, &response, &layout, mode, lines); + } else { + session.view.held = None; + scroll(session, mode, lines); + if let Some(address) = select(ui, session, &response, &layout) { + act = Some(Act::Open(address)); + } + response.context_menu(|ui| { + if let Some(chosen) = menu(ui, session) { + act = Some(chosen); + } + }); + } + + // ── The paint ───────────────────────────────────────────────────────── + let dim = general.terminal_dim && !focused; + let hover = response.hover_pos().filter(|_| !reporting); + let link = paint(ui, session, &layout, rect, &palette, &font, natural, focused, dim, hover); + if link { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } else if response.hovered() && !reporting { + ui.ctx().set_cursor_icon(egui::CursorIcon::Text); + } + scroller(ui, session, rect, response.hovered()); + + act +} + +/// Carries this frame's keys into the shell, and takes them out of the +/// frame: with the keyboard in the terminal, Control and F is the shell's, +/// and the search box over the graph is not to open because of it. +fn typing(ui: &mut egui::Ui, session: &mut Session, mode: TermMode) { + let mac = cfg!(target_os = "macos"); + let events = ui.input_mut(|input| { + let mut taken = Vec::new(); + input.events.retain(|event| { + let ours = matches!( + event, + Event::Key { .. } | Event::Text(_) | Event::Copy | Event::Cut | Event::Paste(_) + ); + if ours { + taken.push(event.clone()); + } + !ours + }); + taken + }); + let held = ui.input(|input| input.modifiers); + + for event in events { + match event { + // Alt and a letter is Escape and then the letter: what `bash` + // calls Meta. Not on a Mac, where that key types the letters + // the keyboard has no key for. + Event::Text(text) => { + let mut bytes = Vec::with_capacity(text.len() + 1); + if held.alt && !mac { + bytes.push(0x1b); + } + bytes.extend_from_slice(text.as_bytes()); + session.type_in(bytes); + } + Event::Key { key, pressed: true, modifiers, .. } => { + // Shift and a paging key is the window's and not the + // shell's: it is how to read back without a mouse. Not + // while a program has the whole screen, which has no back. + if modifiers.shift && !modifiers.ctrl && !mode.contains(TermMode::ALT_SCREEN) { + let turn = match key { + egui::Key::PageUp => Some(Scroll::PageUp), + egui::Key::PageDown => Some(Scroll::PageDown), + egui::Key::Home => Some(Scroll::Top), + egui::Key::End => Some(Scroll::Bottom), + _ => None, + }; + if let Some(turn) = turn { + session.grid().scroll_display(turn); + continue; + } + } + if let Some(bytes) = key_bytes(key, modifiers, mode) { + session.type_in(bytes); + } + } + // Control and C is two things, and which one is whether + // anything is selected: with a selection it is "copy", as in + // every window there is, and without one it is what it has + // always been to a shell. The selection goes once it is + // copied, so that the second press is the interrupt. + Event::Copy => { + let chosen = session.grid().selection_to_string().filter(|text| !text.is_empty()); + match chosen { + Some(text) => { + ui.ctx().copy_text(text); + session.grid().selection = None; + } + None if !held.shift && !mac => session.type_in(vec![0x03]), + None => {} + } + } + Event::Cut if !mac => session.type_in(vec![0x18]), + // Control and V on its own belongs to the shell too, where it + // means "the next key, as it is". Pasting is that with Shift, + // or Shift and Insert, or the menu. + Event::Paste(text) => { + let asked = std::mem::take(&mut session.view.paste_next); + match asked || held.shift || mac { + true => session.paste(&text), + false => session.type_in(vec![0x16]), + } + } + _ => {} + } + } +} + +/// How many whole lines the wheel has turned over the terminal this frame, +/// upwards positive. +fn wheel(ui: &egui::Ui, session: &mut Session, response: &egui::Response, line: f32) -> i32 { + if !response.contains_pointer() { + session.view.wheel = 0.0; + return 0; + } + session.view.wheel += ui.input(|input| input.smooth_scroll_delta.y) / line; + let whole = session.view.wheel.trunc(); + session.view.wheel -= whole; + whole as i32 +} + +/// What the wheel does when no program has asked for the mouse. +fn scroll(session: &mut Session, mode: TermMode, lines: i32) { + if lines == 0 { + return; + } + // A program with the whole screen has nothing above it to scroll back + // to, so the wheel is its arrow keys: that is how `less` and `man` + // scroll in a terminal without either knowing what a wheel is. + if mode.contains(TermMode::ALT_SCREEN) && mode.contains(TermMode::ALTERNATE_SCROLL) { + let key = match lines > 0 { + true => egui::Key::ArrowUp, + false => egui::Key::ArrowDown, + }; + if let Some(bytes) = key_bytes(key, egui::Modifiers::NONE, mode) { + session.send(bytes.repeat(lines.unsigned_abs() as usize)); + } + return; + } + session.grid().scroll_display(Scroll::Delta(lines)); +} + +/// Tells a program that asked for the mouse what the mouse is doing. +fn report( + ui: &egui::Ui, + session: &mut Session, + response: &egui::Response, + layout: &Layout, + mode: TermMode, + lines: i32, +) { + let held = ui.input(|input| input.modifiers); + let extra = 8 * held.alt as u8 + 16 * held.ctrl as u8; + let sgr = mode.contains(TermMode::SGR_MOUSE); + let say = |session: &Session, code: u8, col: usize, row: usize, down: bool| { + if sgr { + let end = if down { 'M' } else { 'm' }; + session.send(format!("\x1b[<{code};{};{}{end}", col + 1, row + 1).into_bytes()); + } else if col < 222 && row < 222 { + // The old way has no "up" for a button: there is one release, + // and it is button three. + let code = if down { code } else { 3 + extra }; + session.send(vec![0x1b, b'[', b'M', 32 + code, 33 + col as u8, 33 + row as u8]); + } + }; + + let over = response.contains_pointer(); + let events = ui.input(|input| input.events.clone()); + for event in events { + match event { + Event::PointerButton { pos, button, pressed, .. } => { + let code = match button { + PointerButton::Primary => 0, + PointerButton::Middle => 1, + PointerButton::Secondary => 2, + _ => continue, + }; + // A press counts where it lands; a release counts wherever + // it lands, or the program is left holding a button. + if (pressed && !over) || (!pressed && session.view.held != Some(code)) { + continue; + } + let (col, row, _) = layout.at(pos); + session.view.held = pressed.then_some(code); + session.view.reported = Some((col, row)); + say(session, code + extra, col, row, pressed); + } + Event::PointerMoved(pos) => { + let wanted = match session.view.held { + Some(_) => mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION), + None => over && mode.contains(TermMode::MOUSE_MOTION), + }; + let (col, row, _) = layout.at(pos); + if wanted && session.view.reported != Some((col, row)) { + session.view.reported = Some((col, row)); + say(session, 32 + session.view.held.unwrap_or(3) + extra, col, row, true); + } + } + _ => {} + } + } + + if lines != 0 { + if let Some(pos) = response.hover_pos() { + let (col, row, _) = layout.at(pos); + let code = if lines > 0 { 64 } else { 65 }; + for _ in 0..lines.unsigned_abs() { + say(session, code + extra, col, row, true); + } + } + } +} + +/// Selecting with the mouse, and the click that is not a selection. +/// +/// Gives back an address when what was clicked was one. +fn select( + ui: &egui::Ui, + session: &mut Session, + response: &egui::Response, + layout: &Layout, +) -> Option { + let mut term = session.grid(); + let back = term.grid().display_offset() as i32; + let spot = |pos: egui::Pos2| { + let (col, row, side) = layout.at(pos); + (Point::new(Line(row as i32 - back), Column(col)), side) + }; + let primary = PointerButton::Primary; + + if response.drag_started_by(primary) { + if let Some(pos) = ui.input(|input| input.pointer.press_origin()) { + let (point, side) = spot(pos); + // Held with Control it is a rectangle: a column out of a table. + let kind = match ui.input(|input| input.modifiers.ctrl) { + true => SelectionType::Block, + false => SelectionType::Simple, + }; + term.selection = Some(Selection::new(kind, point, side)); + } + } + if response.dragged_by(primary) { + if let Some(pos) = response.interact_pointer_pos() { + // Past the top or the bottom the view follows, a line a frame, + // so that a selection can be longer than the panel is tall. + let rect = response.rect; + if pos.y < rect.top() { + term.scroll_display(Scroll::Delta(1)); + ui.ctx().request_repaint(); + } else if pos.y > rect.bottom() { + term.scroll_display(Scroll::Delta(-1)); + ui.ctx().request_repaint(); + } + let back = term.grid().display_offset() as i32; + let (col, row, side) = layout.at(pos); + let point = Point::new(Line(row as i32 - back), Column(col)); + if let Some(selection) = &mut term.selection { + selection.update(point, side); + } + } + } + + // A key held down with the keyboard in here is also a "click", as far + // as the response can tell: that is how a focused button is pressed + // with Space. A real one let go of a button this frame. + let let_go = ui.input(|input| input.pointer.primary_released()); + let pos = response.interact_pointer_pos().filter(|_| let_go)?; + let (point, side) = spot(pos); + if response.triple_clicked() { + term.selection = Some(Selection::new(SelectionType::Lines, point, side)); + } else if response.double_clicked() { + term.selection = Some(Selection::new(SelectionType::Semantic, point, side)); + } else if response.clicked() { + term.selection = None; + return address_at(&term, point, layout.cols).map(|(address, _)| address); + } + None +} + +/// The address under a box, when there is one, and the columns it runs +/// across on that line. +/// +/// Two kinds. A program can say outright that a stretch of text is a link +/// and where it goes; failing that, text that starts like an address is +/// taken for one, up to the first thing an address cannot have in it. +fn address_at( + term: &alacritty_terminal::Term, + point: Point, + cols: usize, +) -> Option<(String, Range)> { + let row = &term.grid()[point.line]; + if let Some(link) = row[point.column].hyperlink() { + let same = |col: usize| row[Column(col)].hyperlink().as_ref() == Some(&link); + let from = (0..=point.column.0).rev().take_while(|col| same(*col)).last()?; + let to = (point.column.0..cols).take_while(|col| same(*col)).last()? + 1; + return Some((link.uri().to_string(), from..to)); + } + let letters: Vec = (0..cols).map(|col| row[Column(col)].c).collect(); + let span = address_in(&letters, point.column.0)?; + Some((letters[span.clone()].iter().collect(), span)) +} + +/// Where in a line of letters the web address covering `col` is. +fn address_in(letters: &[char], col: usize) -> Option> { + let starts = |at: usize, word: &str| { + letters[at..].iter().take(word.len()).copied().eq(word.chars()) + }; + let mut at = 0; + while at < letters.len() { + if !(starts(at, "https://") || starts(at, "http://")) { + at += 1; + continue; + } + let mut end = at; + while end < letters.len() + && !letters[end].is_whitespace() + && !matches!(letters[end], '\0' | '"' | '\'' | '<' | '>' | '`' | '│' | '|') + { + end += 1; + } + // What an address ends with in a sentence is the sentence's. + while end > at && matches!(letters[end - 1], '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}') { + end -= 1; + } + if (at..end).contains(&col) { + return Some(at..end); + } + at = end.max(at + 1); + } + None +} + +/// The menu behind a right click. +fn menu(ui: &mut egui::Ui, session: &mut Session) -> Option { + ui.set_width(MENU); + let mac = cfg!(target_os = "macos"); + let mut act = None; + let item = |ui: &mut egui::Ui, name: &str, keys: &str, enabled: bool| { + let button = egui::Button::new(name).shortcut_text( + egui::RichText::new(keys).font(theme::body(11.0)).color(theme::faint()), + ); + let pressed = ui.add_enabled(enabled, button).clicked(); + if pressed { + ui.close_menu(); + } + pressed + }; + + let chosen = session.grid().selection_to_string().filter(|text| !text.is_empty()); + if item(ui, "Copy", if mac { "Cmd+C" } else { "Ctrl+C" }, chosen.is_some()) { + if let Some(text) = chosen { + ui.ctx().copy_text(text); + } + } + if item(ui, "Paste", if mac { "Cmd+V" } else { "Ctrl+Shift+V" }, true) { + // The clipboard is the window's to read, and it hands over what it + // read as a paste on the next frame. + session.view.paste_next = true; + session.view.wants_focus = true; + ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste); + } + if item(ui, "Select All", "", true) { + let mut term = session.grid(); + let (top, bottom, last) = + (term.grid().topmost_line(), term.grid().bottommost_line(), term.grid().last_column()); + let mut all = Selection::new(SelectionType::Simple, Point::new(top, Column(0)), Side::Left); + all.update(Point::new(bottom, last), Side::Right); + term.selection = Some(all); + } + ui.separator(); + if item(ui, "Delete Line", "Ctrl+U", true) { + session.type_in(vec![0x15]); + } + if item(ui, "Clear", "Ctrl+L", true) { + // What has scrolled off goes too, which the key alone leaves. + session.grid().grid_mut().clear_history(); + session.type_in(vec![0x0c]); + } + ui.separator(); + if item(ui, "Minimize Terminal", "", true) { + act = Some(Act::Minimize); + } + if item(ui, "Kill Terminal", "", true) { + act = Some(Act::Kill); + } + if item(ui, "Hide Terminal", "", true) { + act = Some(Act::Hide); + } + act +} + +/// Paints the grid. Says whether the pointer is over an address. +#[allow(clippy::too_many_arguments)] +fn paint( + ui: &egui::Ui, + session: &mut Session, + layout: &Layout, + rect: egui::Rect, + palette: &Palette, + font: &egui::FontId, + natural: f32, + focused: bool, + dim: bool, + hover: Option, +) -> bool { + let painter = ui.painter_at(rect); + painter.rect_filled(rect, 0, palette.ground); + + // Taken out for the length of the painting and put back: the grid is + // borrowed from the session the whole time, and this is the session's. + let mut plain = std::mem::take(&mut session.view.plain); + let mut is_plain = |letter: char| match letter { + ' '..='~' => true, + // The frames and the blocks are drawn, each in its own box. + '\u{2500}'..='\u{259f}' => false, + _ => *plain.entry(letter).or_insert_with(|| { + let width = ui.fonts(|fonts| fonts.glyph_width(font, letter)); + (width - layout.cell.x).abs() < 0.01 + }), + }; + + let term = session.grid(); + let content = term.renderable_content(); + let back = content.display_offset as i32; + let quiet = |colour: Color32| match dim { + true => mix(palette.ground, colour, DIMMED), + false => colour, + }; + let named = |colour: Color, bold: bool| match colour { + Color::Spec(rgb) => Color32::from_rgb(rgb.r, rgb.g, rgb.b), + Color::Indexed(index) => match content.colors[index as usize] { + Some(rgb) => Color32::from_rgb(rgb.r, rgb.g, rgb.b), + None => palette.indexed(index as usize), + }, + Color::Named(name) => { + // Bold in one of the eight is the bright one of it, which is + // what bold was before there were bold faces to draw it in. + let name = match (bold, name as usize) { + (true, 0..=7) => name.to_bright(), + _ => name, + }; + match content.colors[name] { + Some(rgb) => Color32::from_rgb(rgb.r, rgb.g, rgb.b), + None => palette.indexed(name as usize), + } + } + }; + + // The address the pointer is over, found before the cells are walked so + // that they can be underlined as they go by. + let link = hover.and_then(|pos| { + let (col, row, _) = layout.at(pos); + let point = Point::new(Line(row as i32 - back), Column(col)); + let inside = layout.corner(0, 0).x <= pos.x + && pos.x < layout.corner(layout.cols, 0).x + && layout.corner(0, 0).y <= pos.y + && pos.y < layout.corner(0, layout.rows).y; + address_at(&term, point, layout.cols).filter(|_| inside).map(|(_, span)| (row, span)) + }); + + let mut bands: Vec = Vec::new(); + let mut pieces: Vec = Vec::new(); + // The run of plain letters being gathered, if one is. + let mut run: Option = None; + let end_run = |run: &mut Option, pieces: &mut Vec| { + if let Some(mut piece) = run.take() { + // Blank boxes at the end of a run are nothing to draw, unless + // there is a line under them. + if piece.under.is_none() && !piece.struck { + let kept = piece.text.trim_end().len(); + piece.text.truncate(kept); + piece.wide = piece.text.chars().count(); + } + if !piece.text.is_empty() { + pieces.push(piece); + } + } + }; + + for indexed in content.display_iter { + let row = indexed.point.line.0 + back; + if row < 0 || row as usize >= layout.rows || indexed.point.column.0 >= layout.cols { + continue; + } + let (row, col) = (row as usize, indexed.point.column.0); + let cell = indexed.cell; + let flags = cell.flags; + if col == 0 { + end_run(&mut run, &mut pieces); + } + // The second half of a letter two boxes wide: the first half + // painted it. + if flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) { + end_run(&mut run, &mut pieces); + continue; + } + + let bold = flags.contains(Flags::BOLD); + let mut ink = named(cell.fg, bold); + let mut ground = named(cell.bg, false); + if flags.contains(Flags::INVERSE) { + std::mem::swap(&mut ink, &mut ground); + } + if flags.contains(Flags::DIM) { + ink = mix(ground, ink, 0.66); + } + let chosen = content.selection.is_some_and(|range| range.contains(indexed.point)); + if chosen { + ground = palette.selection; + } + let wide = if flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 }; + + if ground != palette.ground { + let colour = if chosen { ground } else { quiet(ground) }; + match bands.last_mut() { + Some(band) if band.row == row && band.to == col && band.colour == colour => { + band.to = col + wide; + } + _ => bands.push(Band { row, from: col, to: col + wide, colour }), + } + } + + let linked = link.as_ref().is_some_and(|(at, span)| *at == row && span.contains(&col)); + let under = match (linked, flags.intersects(Flags::ALL_UNDERLINES)) { + (true, _) => Some(quiet(ink)), + (_, true) => Some(quiet(cell.underline_color().map_or(ink, |colour| named(colour, false)))), + _ => None, + }; + let struck = flags.contains(Flags::STRIKEOUT); + let italic = flags.contains(Flags::ITALIC); + let ink = quiet(ink); + let behind = match chosen { + true => ground, + false => quiet(ground), + }; + let letter = match flags.contains(Flags::HIDDEN) || cell.c == '\0' { + true => ' ', + false => cell.c, + }; + let marks = cell.zerowidth().filter(|marks| !marks.is_empty()); + + if marks.is_none() && wide == 1 && is_plain(letter) { + let fits = run.as_ref().is_some_and(|piece| { + piece.row == row + && piece.col + piece.wide == col + && piece.ink == ink + && piece.bold == bold + && piece.italic == italic + && piece.under == under + && piece.struck == struck + }); + if !fits { + end_run(&mut run, &mut pieces); + // A run does not begin with nothing. + if letter == ' ' && under.is_none() && !struck { + continue; + } + run = Some(Piece { + row, + col, + text: String::new(), + wide: 0, + ink, + bold, + italic, + under, + struck, + ground: behind, + }); + } + if let Some(piece) = &mut run { + piece.text.push(letter); + piece.wide += 1; + } + continue; + } + + // Anything else is painted alone in its own box. + end_run(&mut run, &mut pieces); + let mut text = String::from(letter); + text.extend(marks.into_iter().flatten()); + pieces.push(Piece { row, col, text, wide, ink, bold, italic, under, struck, ground: behind }); + } + end_run(&mut run, &mut pieces); + + let caret = content.cursor; + let caret_spot = { + let row = caret.point.line.0 + back; + (row >= 0 && (row as usize) < layout.rows && caret.point.column.0 < layout.cols) + .then(|| (caret.point.column.0, row as usize)) + }; + let under_caret = term.grid()[caret.point].c; + drop(term); + session.view.plain = plain; + + for band in &bands { + painter.rect_filled( + egui::Rect::from_min_max( + layout.corner(band.from, band.row), + layout.corner(band.to, band.row + 1), + ), + 0, + band.colour, + ); + } + + // One pixel of the screen, which is how far over the second striking + // of a bold letter goes: the mono face here comes in one weight. + let pixel = 1.0 / ui.ctx().pixels_per_point(); + let lift = ((layout.cell.y - natural) / 2.0).round(); + let write = |text: &str, col: usize, row: usize, ink: Color32, bold: bool, italic: bool| { + let format = TextFormat { font_id: font.clone(), color: ink, italics: italic, ..Default::default() }; + let galley = painter.layout_job(LayoutJob::single_section(text.to_string(), format)); + let at = layout.corner(col, row) + egui::vec2(0.0, lift); + if bold { + painter.galley(at + egui::vec2(pixel, 0.0), galley.clone(), ink); + } + painter.galley(at, galley, ink); + }; + for piece in &pieces { + let mut letters = piece.text.chars(); + let alone = letters.next().filter(|_| letters.next().is_none()); + let spot = egui::Rect::from_min_max( + layout.corner(piece.col, piece.row), + layout.corner(piece.col + 1, piece.row + 1), + ); + if alone.is_some_and(|letter| drawn(&painter, spot, letter, piece.ink, piece.ground)) { + continue; + } + write(&piece.text, piece.col, piece.row, piece.ink, piece.bold, piece.italic); + let (left, right) = ( + layout.corner(piece.col, piece.row).x, + layout.corner(piece.col + piece.wide, piece.row).x, + ); + let top = layout.corner(piece.col, piece.row).y; + if let Some(colour) = piece.under { + let y = (top + lift + natural - 1.5).min(top + layout.cell.y - 1.0).round() + 0.5; + painter.hline(left..=right, y, Stroke::new(1.0, colour)); + } + if piece.struck { + let y = (top + layout.cell.y / 2.0).round() + 0.5; + painter.hline(left..=right, y, Stroke::new(1.0, piece.ink)); + } + } + + // The caret, last, over whatever it is on. Without the keyboard it is + // an outline: the place is still marked, and nothing typed will go + // there. + if let Some((col, row)) = caret_spot { + let colour = quiet(palette.caret); + let spot = egui::Rect::from_min_max(layout.corner(col, row), layout.corner(col + 1, row + 1)); + let shape = match (caret.shape, focused) { + (CursorShape::Hidden, _) => CursorShape::Hidden, + (_, false) => CursorShape::HollowBlock, + (shape, true) => shape, + }; + match shape { + CursorShape::Block => { + painter.rect_filled(spot, 0, colour); + if under_caret != ' ' && under_caret != '\0' { + write(&under_caret.to_string(), col, row, palette.ground, false, false); + } + } + CursorShape::Beam => { + let width = (layout.cell.x * 0.16).clamp(1.0, 2.0); + painter.rect_filled(spot.with_max_x(spot.left() + width), 0, colour); + } + CursorShape::Underline => { + painter.rect_filled(spot.with_min_y(spot.bottom() - 2.0), 0, colour); + } + CursorShape::HollowBlock => { + painter.rect_stroke(spot, 0, Stroke::new(1.0, colour), egui::StrokeKind::Inside); + } + CursorShape::Hidden => {} + } + } + + link.is_some() +} + +// ── Lines and blocks ─────────────────────────────────────────────────────── +// The letters programs draw frames with are not letters, and are not +// painted as letters. A font draws `│` to fit its own line, and a terminal's +// line is taller than that by whatever the preferences say, so a frame set +// in the font is a column of dashes with gaps between them. Here each one +// is drawn to the edges of its box: arms out from the middle, as thick as +// the letter says, which is all any of them is. + +/// The arms of each letter from U+2500 to U+257F, in the order up, right, +/// down, left: nought for none, one for a light line, two for a heavy one +/// and three for a double. A dashed line is drawn whole, and a rounded +/// corner square: at this size the difference is a pixel. +#[rustfmt::skip] +const ARMS: [[u8; 4]; 128] = [ + [0, 1, 0, 1], [0, 2, 0, 2], [1, 0, 1, 0], [2, 0, 2, 0], [0, 1, 0, 1], [0, 2, 0, 2], [1, 0, 1, 0], [2, 0, 2, 0], // 2500 ─━│┃┄┅┆┇ + [0, 1, 0, 1], [0, 2, 0, 2], [1, 0, 1, 0], [2, 0, 2, 0], [0, 1, 1, 0], [0, 2, 1, 0], [0, 1, 2, 0], [0, 2, 2, 0], // 2508 ┈┉┊┋┌┍┎┏ + [0, 0, 1, 1], [0, 0, 1, 2], [0, 0, 2, 1], [0, 0, 2, 2], [1, 1, 0, 0], [1, 2, 0, 0], [2, 1, 0, 0], [2, 2, 0, 0], // 2510 ┐┑┒┓└┕┖┗ + [1, 0, 0, 1], [1, 0, 0, 2], [2, 0, 0, 1], [2, 0, 0, 2], [1, 1, 1, 0], [1, 2, 1, 0], [2, 1, 1, 0], [1, 1, 2, 0], // 2518 ┘┙┚┛├┝┞┟ + [2, 1, 2, 0], [2, 2, 1, 0], [1, 2, 2, 0], [2, 2, 2, 0], [1, 0, 1, 1], [1, 0, 1, 2], [2, 0, 1, 1], [1, 0, 2, 1], // 2520 ┠┡┢┣┤┥┦┧ + [2, 0, 2, 1], [2, 0, 1, 2], [1, 0, 2, 2], [2, 0, 2, 2], [0, 1, 1, 1], [0, 1, 1, 2], [0, 2, 1, 1], [0, 2, 1, 2], // 2528 ┨┩┪┫┬┭┮┯ + [0, 1, 2, 1], [0, 1, 2, 2], [0, 2, 2, 1], [0, 2, 2, 2], [1, 1, 0, 1], [1, 1, 0, 2], [1, 2, 0, 1], [1, 2, 0, 2], // 2530 ┰┱┲┳┴┵┶┷ + [2, 1, 0, 1], [2, 1, 0, 2], [2, 2, 0, 1], [2, 2, 0, 2], [1, 1, 1, 1], [1, 1, 1, 2], [1, 2, 1, 1], [1, 2, 1, 2], // 2538 ┸┹┺┻┼┽┾┿ + [2, 1, 1, 1], [1, 1, 2, 1], [2, 1, 2, 1], [2, 1, 1, 2], [2, 2, 1, 1], [1, 1, 2, 2], [1, 2, 2, 1], [2, 2, 1, 2], // 2540 ╀╁╂╃╄╅╆╇ + [1, 2, 2, 2], [2, 1, 2, 2], [2, 2, 2, 1], [2, 2, 2, 2], [0, 1, 0, 1], [0, 2, 0, 2], [1, 0, 1, 0], [2, 0, 2, 0], // 2548 ╈╉╊╋╌╍╎╏ + [0, 3, 0, 3], [3, 0, 3, 0], [0, 3, 1, 0], [0, 1, 3, 0], [0, 3, 3, 0], [0, 0, 1, 3], [0, 0, 3, 1], [0, 0, 3, 3], // 2550 ═║╒╓╔╕╖╗ + [1, 3, 0, 0], [3, 1, 0, 0], [3, 3, 0, 0], [1, 0, 0, 3], [3, 0, 0, 1], [3, 0, 0, 3], [1, 3, 1, 0], [3, 1, 3, 0], // 2558 ╘╙╚╛╜╝╞╟ + [3, 3, 3, 0], [1, 0, 1, 3], [3, 0, 3, 1], [3, 0, 3, 3], [0, 3, 1, 3], [0, 1, 3, 1], [0, 3, 3, 3], [1, 3, 0, 3], // 2560 ╠╡╢╣╤╥╦╧ + [3, 1, 0, 1], [3, 3, 0, 3], [1, 3, 1, 3], [3, 1, 3, 1], [3, 3, 3, 3], [0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1], // 2568 ╨╩╪╫╬╭╮╯ + [1, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], // 2570 ╰╱╲╳╴╵╶╷ + [0, 0, 0, 2], [2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 2, 0, 1], [1, 0, 2, 0], [0, 1, 0, 2], [2, 0, 1, 0], // 2578 ╸╹╺╻╼╽╾╿ +]; + +/// Paints a line-drawing or block letter into its box. Says whether it was +/// one: anything else is the font's to draw. +fn drawn( + painter: &egui::Painter, + spot: egui::Rect, + letter: char, + ink: Color32, + ground: Color32, +) -> bool { + let code = letter as u32; + if !(0x2500..=0x259f).contains(&code) { + return false; + } + // Everything lands on whole pixels, and a box ends where the next one + // begins: two boxes that each stop a third of a pixel short of the + // same edge leave a seam down every frame. + let scale = painter.pixels_per_point(); + let snap = |value: f32| (value * scale).round() / scale; + let (left, right) = (snap(spot.left()), snap(spot.right())); + let (top, bottom) = (snap(spot.top()), snap(spot.bottom())); + let fill = |x: (f32, f32), y: (f32, f32), colour: Color32| { + if x.1 > x.0 && y.1 > y.0 { + painter.rect_filled( + egui::Rect::from_min_max(egui::pos2(x.0, y.0), egui::pos2(x.1, y.1)), + 0, + colour, + ); + } + }; + let (wide, tall) = (right - left, bottom - top); + + if code >= 0x2580 { + // Part of the box, filled: `across` and `down` are the part, as + // fractions of it. + let part = |across: (f32, f32), down: (f32, f32), colour: Color32| { + fill( + (snap(left + wide * across.0), snap(left + wide * across.1)), + (snap(top + tall * down.0), snap(top + tall * down.1)), + colour, + ); + }; + let eighths = |count: u32| count as f32 / 8.0; + let quarter = |upper: bool, leftward: bool| { + let across = if leftward { (0.0, 0.5) } else { (0.5, 1.0) }; + let down = if upper { (0.0, 0.5) } else { (0.5, 1.0) }; + part(across, down, ink); + }; + match code { + 0x2580 => part((0.0, 1.0), (0.0, 0.5), ink), + 0x2581..=0x2588 => part((0.0, 1.0), (1.0 - eighths(code - 0x2580), 1.0), ink), + 0x2589..=0x258f => part((0.0, eighths(0x2590 - code)), (0.0, 1.0), ink), + 0x2590 => part((0.5, 1.0), (0.0, 1.0), ink), + // The three shades: the ink, a quarter, a half and three + // quarters of the way up from the ground. + 0x2591..=0x2593 => { + let depth = (code - 0x2590) as f32 * 0.25; + part((0.0, 1.0), (0.0, 1.0), mix(ground, ink, depth)); + } + 0x2594 => part((0.0, 1.0), (0.0, eighths(1)), ink), + 0x2595 => part((eighths(7), 1.0), (0.0, 1.0), ink), + _ => { + // The quarters, as four bits: upper left, upper right, + // lower left, lower right. + let which: u8 = match code { + 0x2596 => 0b0010, + 0x2597 => 0b0001, + 0x2598 => 0b1000, + 0x2599 => 0b1011, + 0x259a => 0b1001, + 0x259b => 0b1110, + 0x259c => 0b1101, + 0x259d => 0b0100, + 0x259e => 0b0110, + _ => 0b0111, + }; + for (bit, upper, leftward) in + [(8, true, true), (4, true, false), (2, false, true), (1, false, false)] + { + if which & bit != 0 { + quarter(upper, leftward); + } + } + } + } + return true; + } + + // A light line is a pixel at the size a terminal is usually read at, + // and grows with the letters. + let light = ((wide * scale / 7.0).round().max(1.0)) / scale; + let (cx, cy) = (snap(left + wide / 2.0 - light / 2.0) + light / 2.0, snap(top + tall / 2.0 - light / 2.0) + light / 2.0); + + // The diagonals are the three that are not arms. + if (0x2571..=0x2573).contains(&code) { + let stroke = Stroke::new(light, ink); + if code != 0x2572 { + painter.line_segment([egui::pos2(left, bottom), egui::pos2(right, top)], stroke); + } + if code != 0x2571 { + painter.line_segment([egui::pos2(left, top), egui::pos2(right, bottom)], stroke); + } + return true; + } + + let [up, east, down, west] = ARMS[(code - 0x2500) as usize]; + // One arm: a bar `half` either side of the middle line, from `near` + // the middle out to the edge of the box. + let arm = |which: usize, half: f32, near: f32, colour: Color32| match which { + 0 => fill((cx - half, cx + half), (top, cy + near), colour), + 1 => fill((cx - near, right), (cy - half, cy + half), colour), + 2 => fill((cx - half, cx + half), (cy - near, bottom), colour), + _ => fill((left, cx + near), (cy - half, cy + half), colour), + }; + let arms = [up, east, down, west]; + + // A double line is a thick one with its middle taken back out, which + // gets every corner and crossing of them right without a case for + // each: the outline of two thick bars meeting is two thin lines + // turning together. As thick as a heavy line, and what is taken out is + // a light one, so the two lines and the gap between them are a pixel + // each and all three sit on whole pixels. + let crossed = |which: usize| arms[(which + 1) % 4] == 3 || arms[(which + 3) % 4] == 3; + let (outer, inner) = (light * 1.5, light * 0.5); + for which in 0..4 { + if arms[which] == 3 { + arm(which, outer, if crossed(which) { outer } else { 0.0 }, ink); + } + } + for which in 0..4 { + if arms[which] == 3 { + arm(which, inner, if crossed(which) { inner } else { 0.0 }, ground); + } + } + for which in 0..4 { + let half = match arms[which] { + 1 => light / 2.0, + 2 => light * 1.5, + _ => continue, + }; + arm(which, half, half, ink); + } + true +} + +/// The handle down the right-hand edge for reading back. +/// +/// There only while there is something above to read, and faint until the +/// pointer is in the panel: the terminal is the one place in this window +/// where the edge of the text is the edge of somebody else's layout. +fn scroller(ui: &mut egui::Ui, session: &mut Session, rect: egui::Rect, near: bool) { + let (history, back, rows) = { + let term = session.grid(); + (term.grid().history_size(), term.grid().display_offset(), term.grid().screen_lines()) + }; + if history == 0 { + return; + } + let track = egui::Rect::from_min_max( + egui::pos2(rect.right() - SCROLLER, rect.top() + 2.0), + egui::pos2(rect.right() - 2.0, rect.bottom() - 2.0), + ); + let length = (track.height() * rows as f32 / (rows + history) as f32).max(22.0); + let travel = (track.height() - length).max(1.0); + let top = track.top() + travel * (1.0 - back as f32 / history as f32); + let thumb = egui::Rect::from_min_size(egui::pos2(track.left(), top), egui::vec2(track.width(), length)); + + let handle = ui.interact(track, ui.id().with("terminal-scroller"), Sense::click_and_drag()); + if let Some(pos) = handle.interact_pointer_pos().filter(|_| handle.dragged() || handle.clicked()) { + // Where the middle of the handle is asked to be, as lines back. + let part = 1.0 - ((pos.y - length / 2.0 - track.top()) / travel).clamp(0.0, 1.0); + let wanted = (part * history as f32).round() as i32; + session.grid().scroll_display(Scroll::Delta(wanted - back as i32)); + } + let live = handle.hovered() || handle.dragged(); + if live || near || back > 0 { + let colour = match live { + true => theme::muted(), + false => theme::tint(theme::muted(), if back > 0 { 110 } else { 60 }), + }; + ui.painter().rect_filled(thumb.shrink2(egui::vec2(1.0, 0.0)), 3, colour); + } +} + +/// The bar above the terminal: what it is on the left, and on the right +/// the three things that can be done to the panel. +/// +/// The bar is all there is of a folded panel, which is why it is a function +/// of its own: it is drawn whether or not there is a grid under it. +pub fn bar(ui: &mut egui::Ui, minimized: bool, title: Option<&str>) -> Option { + let mut act = None; + ui.allocate_ui_with_layout( + egui::vec2(ui.available_width(), BAR), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.add_space(10.0); + let (rect, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), Sense::hover()); + prompt(ui.painter(), rect, theme::muted()); + ui.label( + egui::RichText::new("Terminal").font(theme::medium(12.0)).color(theme::text()), + ); + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.add_space(6.0); + if icon(ui, Icon::Cross, "Hide Terminal") { + act = Some(Act::Hide); + } + if icon(ui, Icon::Bin, "Kill Terminal") { + act = Some(Act::Kill); + } + match minimized { + true => { + if icon(ui, Icon::Up, "Expand Terminal") { + act = Some(Act::Expand); + } + } + false => { + if icon(ui, Icon::Down, "Minimize Terminal") { + act = Some(Act::Minimize); + } + } + } + // What the shell calls itself -- usually who and where -- + // in whatever room is left, cut short rather than wrapped. + if let Some(title) = title { + ui.add_space(10.0); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.add_space(4.0); + ui.add( + egui::Label::new( + egui::RichText::new(title) + .font(theme::mono(10.5)) + .color(theme::faint()), + ) + .truncate(), + ); + }); + } + }); + }, + ); + act +} + +/// The button in a repository's bar that opens the panel and puts it away. +/// +/// Drawn rather than built out of a button and a label, for the prompt in +/// front of the word: the fonts here have a `>` and a `_`, but set side by +/// side as text they are two characters, and a prompt is one sign. +pub fn toggle(ui: &mut egui::Ui, on: bool) -> egui::Response { + let galley = ui.painter().layout_no_wrap( + "Terminal".to_string(), + theme::medium(12.5), + Color32::PLACEHOLDER, + ); + let pad = ui.spacing().button_padding; + let sign = 14.0; + let size = egui::vec2( + pad.x * 2.0 + sign + 6.0 + galley.size().x, + ui.spacing().interact_size.y.max(galley.size().y + pad.y * 2.0), + ); + let (rect, response) = ui.allocate_exact_size(size, Sense::click()); + let visuals = ui.style().interact_selectable(&response, on); + let painter = ui.painter(); + painter.rect( + rect, + visuals.corner_radius, + visuals.weak_bg_fill, + visuals.bg_stroke, + egui::StrokeKind::Inside, + ); + let ink = visuals.text_color(); + let at = egui::Rect::from_min_size( + egui::pos2(rect.left() + pad.x, rect.center().y - sign / 2.0), + egui::vec2(sign, sign), + ); + prompt(painter, at, ink); + painter.galley( + egui::pos2(at.right() + 6.0, rect.center().y - galley.size().y / 2.0), + galley, + ink, + ); + response +} + +/// A prompt: the angle a shell waits behind, and the line where the next +/// letter goes. +fn prompt(painter: &egui::Painter, rect: egui::Rect, colour: Color32) { + let stroke = Stroke::new(1.4, colour); + let (left, middle) = (rect.left() + 1.5, rect.center().y); + painter.line_segment([egui::pos2(left, middle - 3.6), egui::pos2(left + 4.0, middle)], stroke); + painter.line_segment([egui::pos2(left + 4.0, middle), egui::pos2(left, middle + 3.6)], stroke); + painter.line_segment( + [egui::pos2(left + 6.5, middle + 4.0), egui::pos2(rect.right() - 1.0, middle + 4.0)], + stroke, + ); +} + +/// The four little drawings in the bar. +#[derive(Clone, Copy)] +enum Icon { + Down, + Up, + Bin, + Cross, +} + +/// One of them, as something to press. Says whether it was. +fn icon(ui: &mut egui::Ui, which: Icon, hint: &str) -> bool { + let (rect, response) = ui.allocate_exact_size(egui::vec2(22.0, 20.0), Sense::click()); + let colour = match response.hovered() { + true => theme::text(), + false => theme::muted(), + }; + if response.hovered() { + ui.painter().rect_filled(rect, theme::RADIUS, theme::hover()); + } + let painter = ui.painter(); + let stroke = Stroke::new(1.3, colour); + let centre = rect.center(); + let line = |from: (f32, f32), to: (f32, f32)| { + painter.line_segment( + [centre + egui::vec2(from.0, from.1), centre + egui::vec2(to.0, to.1)], + stroke, + ); + }; + match which { + Icon::Down => { + line((-4.0, -2.0), (0.0, 2.2)); + line((0.0, 2.2), (4.0, -2.0)); + } + Icon::Up => { + line((-4.0, 2.0), (0.0, -2.2)); + line((0.0, -2.2), (4.0, 2.0)); + } + Icon::Cross => { + line((-3.6, -3.6), (3.6, 3.6)); + line((-3.6, 3.6), (3.6, -3.6)); + } + // A lid with its handle, and the can under it. + Icon::Bin => { + line((-4.6, -3.2), (4.6, -3.2)); + line((-1.6, -3.2), (-1.6, -5.0)); + line((-1.6, -5.0), (1.6, -5.0)); + line((1.6, -5.0), (1.6, -3.2)); + line((-3.4, -3.2), (-2.8, 5.0)); + line((-2.8, 5.0), (2.8, 5.0)); + line((2.8, 5.0), (3.4, -3.2)); + line((-1.0, -1.0), (-1.0, 3.0)); + line((1.0, -1.0), (1.0, 3.0)); + } + } + response.on_hover_text(hint).clicked() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn found(line: &str, col: usize) -> Option { + let letters: Vec = line.chars().collect(); + address_in(&letters, col).map(|span| letters[span].iter().collect()) + } + + #[test] + fn an_address_is_found_under_the_pointer_and_only_there() { + let line = "remote: see https://example.org/pull/7 for it"; + assert_eq!(found(line, 14).as_deref(), Some("https://example.org/pull/7")); + assert_eq!(found(line, 37).as_deref(), Some("https://example.org/pull/7")); + assert_eq!(found(line, 3), None); + assert_eq!(found(line, 40), None); + } + + #[test] + fn what_ends_a_sentence_is_not_part_of_the_address() { + assert_eq!( + found("(read http://example.org/a.html).", 10).as_deref(), + Some("http://example.org/a.html") + ); + assert_eq!(found("go to 'https://example.org' now", 9).as_deref(), Some("https://example.org")); + } + + #[test] + fn two_addresses_on_a_line_are_two_addresses() { + let line = "https://one.example https://two.example"; + assert_eq!(found(line, 2).as_deref(), Some("https://one.example")); + assert_eq!(found(line, 25).as_deref(), Some("https://two.example")); + assert_eq!(found(line, 19), None); + } + + #[test] + fn a_point_on_the_screen_is_a_box_in_the_grid() { + let layout = Layout { + origin: egui::pos2(10.0, 20.0), + cell: egui::vec2(8.0, 16.0), + cols: 80, + rows: 24, + }; + assert!(matches!(layout.at(egui::pos2(10.0, 20.0)), (0, 0, Side::Left))); + assert!(matches!(layout.at(egui::pos2(31.0, 37.0)), (2, 1, Side::Right))); + // Off the edges it is the nearest box, not no box. + assert!(matches!(layout.at(egui::pos2(-50.0, -50.0)), (0, 0, Side::Left))); + assert!(matches!(layout.at(egui::pos2(9_000.0, 9_000.0)), (79, 23, Side::Right))); + } +} diff --git a/crates/gitrust-ui/src/theme.rs b/crates/gitrust-ui/src/theme.rs index bbcfee1..45d1b48 100644 --- a/crates/gitrust-ui/src/theme.rs +++ b/crates/gitrust-ui/src/theme.rs @@ -81,6 +81,76 @@ pub fn lane(index: usize) -> Color32 { LANES[index % LANES.len()] } +// ── The terminal ─────────────────────────────────────────────────────────── +// The one place in the window that does not choose its own colours. A +// program says "red" by number and expects red, so there have to be sixteen +// answers, and eight of them have to be the eight a terminal has always +// had. They are the lanes: the same coral, jade, amber and azure the graph +// is drawn in, so that `git status` in the panel and the changes list +// beside it are the same red and the same green. The bright eight are the +// same eight a step lighter, which is all "bright" has meant since it +// stopped meaning "bold". +// +// On white the lanes are too pale to read as text, so the light table is +// the light theme's own darker set, and "white" there is a grey: a program +// that writes in white is asking to be read, not to be invisible. + +/// What is behind the letters in the terminal: the deepest surface there +/// is, so that the panel reads as a place set into the window. +pub fn terminal_ground() -> Color32 { + choose(sunken(), rgb(0xFF, 0xFF, 0xFF)) +} + +/// The sixteen colours a program in the terminal can ask for by name: +/// black, red, green, yellow, blue, magenta, cyan and white, and then the +/// same eight again, bright. +pub fn terminal() -> [Color32; 16] { + if is_light() { + return [ + rgb(0x1E, 0x1E, 0x1E), + rgb(0xB5, 0x35, 0x2B), + rgb(0x28, 0x7A, 0x45), + rgb(0xA4, 0x63, 0x00), + rgb(0x0B, 0x63, 0xC5), + rgb(0x7B, 0x3F, 0xF2), + rgb(0x00, 0x7C, 0x85), + rgb(0x5A, 0x5F, 0x66), + rgb(0x6F, 0x6F, 0x6F), + rgb(0xD8, 0x45, 0x3A), + rgb(0x2F, 0x96, 0x54), + rgb(0xC2, 0x7A, 0x0A), + rgb(0x2B, 0x7F, 0xE0), + rgb(0x95, 0x62, 0xF7), + rgb(0x00, 0x97, 0xA2), + rgb(0x8A, 0x8F, 0x98), + ]; + } + let lighter = |color: Color32| { + let lift = |channel: u8| channel + ((255 - channel) as f32 * 0.28) as u8; + rgb(lift(color.r()), lift(color.g()), lift(color.b())) + }; + let dull = [ + rgb(0x1B, 0x23, 0x26), + LANES[5], + LANES[1], + LANES[2], + LANES[0], + LANES[6], + LANES[4], + rgb(0xC3, 0xCD, 0xD0), + ]; + let mut all = [Color32::BLACK; 16]; + for (index, color) in dull.into_iter().enumerate() { + all[index] = color; + all[index + 8] = lighter(color); + } + // Bright black is the one that is not black a step lighter: it is what + // programs write their asides in, and has to be readable on the ground. + all[8] = rgb(0x5F, 0x70, 0x76); + all[15] = rgb(0xF2, 0xF6, 0xF7); + all +} + /// The same color let down to a background, for the branch chips. pub fn tint(color: Color32, alpha: u8) -> Color32 { Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), alpha) From c4c40131692a7998c02008b2988979517d344fb9 Mon Sep 17 00:00:00 2001 From: Francesc Date: Thu, 12 Nov 2026 21:59:42 +0100 Subject: [PATCH 2/3] feat: a remote checkout opens with the key file a server hands out A checkout on another machine could be reached with a password, with the profile's key or through the agent. A server that hands out a .pem is none of the three: the key is in a file of its own, belongs to no profile and has never been near the agent. The box for a remote checkout has a line for that file now, with the desktop's chooser beside it. With a key named, the secret next to it is that key's passphrase and the box says so; with none it is the password it always was. A key that was named is that key and nothing after it -- a profile's key falls back to the agent because nobody chose it for this server, and this one was chosen. Where the key is gets remembered beside the checkout, as a fifth field on its line in the settings, so Reconnect and the terminal knock with it too. The passphrase is remembered nowhere: a key that has one is reopened from the box, and in the terminal ssh asks for it itself. A checkout is now remembered by where it is and not by how it was reached, so opening it again with another key replaces the line instead of adding one. Two things said before they go wrong. A key file that is not there is reported before anything is asked of the network, in those words and not in libssh2's about the format of keys. And a key other people on the machine can read -- which is how a downloaded .pem arrives -- opens the checkout here but is refused by ssh in the terminal, so the box says which chmod it wants. Tried against an OpenSSH server in a container: an RSA key in the PEM envelope with a passphrase and one without, a wrong passphrase, none, a file that is not there; then in the window, on a virtual display, the box, the saved checkout, Reconnect and the shell on that machine. The test that goes with it starts its own sshd and so runs in CI and not on a desk without one; it has not run yet. The chooser button was not pressed -- it is the one the profiles already use. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Francesc --- README.md | 15 ++- crates/gitrust-core/src/profile.rs | 9 +- crates/gitrust-core/src/remote_repo.rs | 16 ++- crates/gitrust-core/src/settings.rs | 47 +++++++- crates/gitrust-core/src/ssh.rs | 114 ++++++++++++++++--- crates/gitrust-core/tests/remote_ssh.rs | 59 +++++++++- crates/gitrust-ui/src/main.rs | 51 ++++++--- crates/gitrust-ui/src/picker.rs | 144 ++++++++++++++++++++---- 8 files changed, 387 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 2f448c9..f71ccf6 100644 --- a/README.md +++ b/README.md @@ -331,7 +331,14 @@ taken back off. A checkout on another machine gets the same three things as far as they can honestly reach: the profile's key opens the connection, with the agent after it, and the profile's name goes along on the command line of each Git command there, so the commit is yours and the server's own -configuration is left exactly as it was. What does not cross is the token +configuration is left exactly as it was. A key can be named for the one +connection instead -- the `.pem` a server hands out, with its passphrase +if it has one -- and then it is that key and nothing after it. Where the +key is gets remembered beside the checkout, so reconnecting and the +terminal knock with it too; the passphrase is remembered nowhere, so a key +that has one is reopened from the screen it was opened from. Tried against +an OpenSSH server in a container, with a passphrase and without. What does +not cross is the token and the key: what that checkout fetches and pushes with stays the server's business. It writes nothing into `.gitconfig` or `~/.ssh/config`: a program that rewrites the files other @@ -380,7 +387,7 @@ 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 -same key. **The graph keeps up.** Nothing here watches the disk, so 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 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` @@ -395,8 +402,8 @@ GitKraken pops up as you type, which are a product of their own; a choice of typeface, because this program ships the one it was designed around; and letters Fira Mono and its fallbacks do not have, Chinese and Japanese among them, which come out as boxes here as they do in a commit message. -Run on Linux; read out of the code and not seen on macOS or Windows, and -the shell on another machine has not been opened against one. +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. **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 diff --git a/crates/gitrust-core/src/profile.rs b/crates/gitrust-core/src/profile.rs index 8ff35b7..a11e34a 100644 --- a/crates/gitrust-core/src/profile.rs +++ b/crates/gitrust-core/src/profile.rs @@ -250,14 +250,7 @@ impl Profile { /// A leading `~` is expanded here rather than left to libgit2, which does /// not expand it and would go looking for a folder called `~`. pub fn key_file(&self) -> Option { - let key = self.key.trim(); - if key.is_empty() { - return None; - } - let Some(rest) = key.strip_prefix("~/") else { - return Some(PathBuf::from(key)); - }; - Some(crate::home::folder()?.join(rest)) + crate::ssh::key_file(&self.key) } /// The public half of that key, beside it on the disk. diff --git a/crates/gitrust-core/src/remote_repo.rs b/crates/gitrust-core/src/remote_repo.rs index d6563ce..e1ed1dd 100644 --- a/crates/gitrust-core/src/remote_repo.rs +++ b/crates/gitrust-core/src/remote_repo.rs @@ -21,6 +21,10 @@ pub struct RemoteRepo { /// /// [`Repo::pruning`]: crate::Repo::pruning pub(crate) prune: bool, + /// The key that was named for this connection, as it was typed. Only + /// remembered here, for [`RemoteRepo::descriptor`] to hand on: the + /// session is already open and has no further use for it. + key: Option, } impl Writer for RemoteRepo { @@ -109,7 +113,13 @@ impl RemoteRepo { impl RemoteRepo { pub fn new(session: Session, path: String) -> Result { session.verify_checkout(&path)?; - Ok(Self { session, path, who: None, prune: false }) + Ok(Self { session, path, who: None, prune: false, key: None }) + } + + /// Notes which key this connection was made with, when one was named, + /// so that the next connection to the same checkout can use it too. + pub fn keyed(&mut self, key: Option) { + self.key = key.filter(|key| !key.trim().is_empty()); } /// Writes from here on as this person, or as whoever the server says. @@ -134,11 +144,13 @@ impl RemoteRepo { } /// Enough to reconnect later, with no password retained in memory or on - /// disk beyond the lifetime of the original authentication dialog. + /// disk beyond the lifetime of the original authentication dialog. The + /// path of a key that was named is not a secret, and is part of it. pub fn descriptor(&self) -> RemoteDescriptor { RemoteDescriptor { login: self.session.login().clone(), path: self.path.clone(), + key: self.key.clone(), } } diff --git a/crates/gitrust-core/src/settings.rs b/crates/gitrust-core/src/settings.rs index 2b87df7..a7e677c 100644 --- a/crates/gitrust-core/src/settings.rs +++ b/crates/gitrust-core/src/settings.rs @@ -368,7 +368,8 @@ pub struct Settings { /// The application's light, dark, or system appearance. pub appearance: Appearance, /// Remote checkouts previously selected by the user. This is strictly - /// connection metadata; authentication remains with SSH agent/password. + /// connection metadata: where each is and, when a key was named for + /// it, the path of that key. Passwords and passphrases are not here. pub remotes: Vec, /// What the preferences screen changes. pub general: General, @@ -419,8 +420,10 @@ impl Settings { } } Some(("remote", value)) => { + // Four fields, or five when a key was named for it. A + // line written before there was a fifth still reads. let fields: Vec<_> = value.split('\t').collect(); - if let [host, user, port, path] = fields.as_slice() { + if let [host, user, port, path, key @ ..] = fields.as_slice() { if let Ok(port) = port.parse() { if let Ok(login) = Login::new((*host).to_string(), (*user).to_string(), port) @@ -428,7 +431,7 @@ impl Settings { if let Ok(remote) = RemoteDescriptor::new(login, (*path).to_string()) { - settings.remotes.push(remote); + settings.remotes.push(remote.keyed(key.first().copied())); } } } @@ -473,9 +476,13 @@ impl Settings { }, self.appearance.as_str()); for remote in &self.remotes { text.push_str(&format!( - "remote {}\t{}\t{}\t{}\n", + "remote {}\t{}\t{}\t{}", remote.login.host, remote.login.user, remote.login.port, remote.path )); + if let Some(key) = &remote.key { + text.push_str(&format!("\t{key}")); + } + text.push('\n'); } text.push_str(&self.general.render()); for tab in &self.tabs { @@ -509,9 +516,11 @@ impl Settings { true } - /// Keeps a checkout descriptor once, replacing an older identical entry. + /// Keeps a checkout once, by where it is: opened again with another + /// key, or with none, it is the same checkout and the newer way in. pub fn remember_remote(&mut self, remote: RemoteDescriptor) { - self.remotes.retain(|known| known != &remote); + let place = remote.place(); + self.remotes.retain(|known| known.place() != place); self.remotes.insert(0, remote); } @@ -705,4 +714,30 @@ mod tests { assert!(!text.contains("password")); assert_eq!(Settings::parse(&text).remotes, vec![remote]); } + + #[test] + fn a_remote_checkout_remembers_the_key_it_was_opened_with() { + let plain = RemoteDescriptor::new( + Login::new("host.example".to_string(), "dev".to_string(), 2222).unwrap(), + "/srv/project".to_string(), + ) + .unwrap(); + let keyed = plain.clone().keyed(Some(" ~/keys/acme.pem ")); + assert_eq!(keyed.key.as_deref(), Some("~/keys/acme.pem")); + // The key is how it is reached and not where it is. + assert_eq!(keyed.place(), plain.place()); + assert_eq!(plain.clone().keyed(Some(" ")).key, None); + + let mut settings = Settings::default(); + settings.remember_remote(plain.clone()); + settings.remember_remote(keyed.clone()); + assert_eq!(settings.remotes, vec![keyed.clone()]); + let text = settings.render(); + assert!(text.contains("remote host.example\tdev\t2222\t/srv/project\t~/keys/acme.pem\n")); + assert_eq!(Settings::parse(&text).remotes, vec![keyed]); + + // Opened again with no key, it stops naming one. + settings.remember_remote(plain.clone()); + assert_eq!(settings.remotes, vec![plain]); + } } diff --git a/crates/gitrust-core/src/ssh.rs b/crates/gitrust-core/src/ssh.rs index 121f5c5..158ab87 100644 --- a/crates/gitrust-core/src/ssh.rs +++ b/crates/gitrust-core/src/ssh.rs @@ -2,7 +2,7 @@ use std::io::{Read, Write}; use std::net::TcpStream; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::{bail, Context, Result}; @@ -31,6 +31,15 @@ pub struct Login { pub struct RemoteDescriptor { pub login: Login, pub path: String, + /// The private key this checkout was opened with, when one was named + /// for it: a path, as it was typed, and never the key itself. + /// + /// It is what a server hands out as a `.pem` and expects back on every + /// connection. Kept beside the address so that reconnecting, and the + /// terminal, knock with the same key the first connection did -- a + /// server reached with a named key is very often one the agent has + /// never heard of. `None` is the profile's key and then the agent. + pub key: Option, } impl RemoteDescriptor { @@ -39,7 +48,21 @@ impl RemoteDescriptor { path.starts_with('/'), "the repository path must be absolute" ); - Ok(Self { login, path }) + Ok(Self { login, path, key: None }) + } + + /// The same checkout, reached with that key. A blank is no key. + pub fn keyed(mut self, key: Option<&str>) -> Self { + self.key = key + .map(str::trim) + .filter(|key| !key.is_empty()) + .map(str::to_string); + self + } + + /// Where that key is on this disk, with a leading `~/` undone. + pub fn key_file(&self) -> Option { + key_file(self.key.as_deref()?) } /// Where this checkout is, as one line: `ssh://user@host:port/path`. @@ -63,6 +86,32 @@ impl Login { } } +/// A key path as somebody writes one, made into a path on this disk: a +/// leading `~/` is the home folder, as it is for a profile's key. +pub fn key_file(written: &str) -> Option { + let written = written.trim(); + if written.is_empty() { + return None; + } + match written.strip_prefix("~/") { + Some(rest) => Some(crate::home::folder()?.join(rest)), + None => Some(PathBuf::from(written)), + } +} + +/// What a connection proves itself with. +enum How<'a> { + Password(&'a str), + /// A private key file. `then_agent` is whether the agent is asked when + /// the key is refused. + Key { + file: &'a Path, + passphrase: Option<&'a str>, + then_agent: bool, + }, + Agent, +} + /// An open, authenticated connection. It holds its TCP socket until dropped. pub struct Session { login: Login, @@ -73,7 +122,11 @@ impl Session { /// Connect using the supplied password, or the SSH agent when it is blank. /// The caller owns the password and can clear it as soon as this returns. pub fn connect(login: Login, password: Option<&str>, trust_new_host: bool) -> Result { - Self::connect_inner(login, password, None, false, trust_new_host, None) + let how = match password.filter(|password| !password.is_empty()) { + Some(password) => How::Password(password), + None => How::Agent, + }; + Self::connect_inner(login, how, trust_new_host, None) } /// Connect the way a profile would: with its key first, and the SSH @@ -86,17 +139,45 @@ impl Session { /// and a server that does not know this client's key is very often one /// that knows the key already in the agent. pub fn connect_as(login: Login, password: Option<&str>, key: Option<&Path>, trust_new_host: bool) -> Result { - Self::connect_inner(login, password, key, true, trust_new_host, None) + let how = match (password.filter(|password| !password.is_empty()), key) { + (Some(password), _) => How::Password(password), + (None, Some(file)) => How::Key { file, passphrase: None, then_agent: true }, + (None, None) => How::Agent, + }; + Self::connect_inner(login, how, trust_new_host, None) + } + + /// Connect with the key somebody named for this connection: the `.pem` + /// a server handed out, or any other private key file. + /// + /// That key and nothing after it. A profile's key falls back to the + /// agent because nobody chose it for this server; this one was chosen, + /// and a connection that quietly got in some other way would leave a + /// key written down beside the checkout that does not open it. + /// + /// The passphrase is for a key that has one, and like a password it is + /// the caller's to clear: it is used once, here, and kept nowhere. + pub fn connect_keyed(login: Login, key: &Path, passphrase: Option<&str>, trust_new_host: bool) -> Result { + let passphrase = passphrase.filter(|passphrase| !passphrase.is_empty()); + Self::connect_inner(login, How::Key { file: key, passphrase, then_agent: false }, trust_new_host, None) } /// Connect with an explicit private key and known-hosts file. This is /// useful for isolated transport tests without borrowing the user's SSH /// agent or their `known_hosts` file. - pub fn connect_with_key(login: Login, private_key: &Path, known_hosts: &Path, trust_new_host: bool) -> Result { - Self::connect_inner(login, None, Some(private_key), false, trust_new_host, Some(known_hosts)) + pub fn connect_with_key(login: Login, private_key: &Path, passphrase: Option<&str>, known_hosts: &Path, trust_new_host: bool) -> Result { + Self::connect_inner(login, How::Key { file: private_key, passphrase, then_agent: false }, trust_new_host, Some(known_hosts)) } - fn connect_inner(login: Login, password: Option<&str>, private_key: Option<&Path>, then_agent: bool, trust_new_host: bool, known_hosts: Option<&Path>) -> Result { + fn connect_inner(login: Login, how: How, trust_new_host: bool, known_hosts: Option<&Path>) -> Result { + // Said before anything is asked of the network: libssh2 answers a + // file that is not there with a line about the format of keys, and + // only once the server has been reached. Only for a key that was + // named -- a profile's has the agent after it, and that is the + // answer to its being gone. + if let How::Key { file, then_agent: false, .. } = &how { + anyhow::ensure!(file.is_file(), "there is no key at {}", file.display()); + } let tcp = TcpStream::connect((login.host.as_str(), login.port)) .with_context(|| format!("could not reach {}:{}", login.host, login.port))?; tcp.set_read_timeout(Some(Duration::from_secs(15))) @@ -108,27 +189,32 @@ impl Session { raw.handshake().context("the SSH handshake failed")?; verify_host(&raw, &login, trust_new_host, known_hosts)?; - match (password.filter(|password| !password.is_empty()), private_key) { - (Some(password), _) => raw + match how { + How::Password(password) => raw .userauth_password(&login.user, password) .context("the SSH password was refused")?, - (None, Some(private_key)) => { - let keyed = raw.userauth_pubkey_file(&login.user, None, private_key, None); + How::Key { file, passphrase, then_agent } => { + let keyed = raw.userauth_pubkey_file(&login.user, None, file, passphrase); match (keyed, then_agent) { (Ok(()), _) => {} - (Err(err), false) => return Err(err).context("the SSH key was refused"), + (Err(err), false) => { + return Err(err).with_context(|| match passphrase { + Some(_) => format!("{} was refused, or that is not its passphrase", file.display()), + None => format!("{} was refused, or it has a passphrase and none was given", file.display()), + }) + } // Both are named when both fail: "the agent refused" // alone would send somebody to look at the agent, when // the thing they set up and expected to work was the key. (Err(key), true) => raw.userauth_agent(&login.user).with_context(|| { format!( "{} was refused ({key}), and so was the SSH agent", - private_key.display() + file.display() ) })?, } } - (None, None) => raw + How::Agent => raw .userauth_agent(&login.user) .context("could not authenticate with the SSH agent")?, } diff --git a/crates/gitrust-core/tests/remote_ssh.rs b/crates/gitrust-core/tests/remote_ssh.rs index 7a44ad6..07c0cd0 100644 --- a/crates/gitrust-core/tests/remote_ssh.rs +++ b/crates/gitrust-core/tests/remote_ssh.rs @@ -43,7 +43,14 @@ struct IsolatedSshd { impl IsolatedSshd { fn start() -> Self { - let root = std::env::temp_dir().join(format!("gitrust-sshd-{}", std::process::id())); + // One folder per daemon and not per process: the tests in this + // file run side by side, in threads of the one process. + static STARTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let root = std::env::temp_dir().join(format!( + "gitrust-sshd-{}-{}", + std::process::id(), + STARTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); let _ = fs::remove_dir_all(&root); fs::create_dir_all(&root).unwrap(); let key = root.join("client-key"); @@ -107,6 +114,7 @@ impl IsolatedSshd { Session::connect_with_key( Login::new("127.0.0.1".to_string(), user, self.port).unwrap(), &self.key, + None, &self.known_hosts, true, ) @@ -114,6 +122,16 @@ impl IsolatedSshd { } } +impl IsolatedSshd { + fn login(&self) -> Login { + let user = String::from_utf8(Command::new("id").arg("-un").output().unwrap().stdout) + .unwrap() + .trim() + .to_string(); + Login::new("127.0.0.1".to_string(), user, self.port).unwrap() + } +} + impl Drop for IsolatedSshd { fn drop(&mut self) { let _ = self.child.kill(); @@ -296,3 +314,42 @@ fn resolves_continues_and_aborts_a_remote_merge() { // about, which is what keeps a command off the server after every pull. assert!(!remote.has_submodules()); } + +/// The key a server hands out: an RSA key in the old PEM envelope, which is +/// what a `.pem` from a cloud console is, here with a passphrase on it so +/// that both halves of naming a key for a connection are tried at once. +#[test] +#[ignore = "starts an isolated sshd; run with GITRUST_SSHD_INTEGRATION=1"] +fn a_pem_key_with_a_passphrase_opens_the_connection() { + if std::env::var_os("GITRUST_SSHD_INTEGRATION").is_none() { + return; + } + let sshd = IsolatedSshd::start(); + let pem = sshd.root.join("handed-out.pem"); + command( + "ssh-keygen", + &["-q", "-t", "rsa", "-b", "3072", "-m", "PEM", "-N", "open sesame", "-f", pem.to_str().unwrap()], + ); + let text = fs::read_to_string(&pem).unwrap(); + assert!(text.starts_with("-----BEGIN RSA PRIVATE KEY-----"), "not the PEM envelope: {text:.40}"); + // The daemon reads this file on every connection, so a key added after + // it started is a key it knows. + let mut allowed = fs::read_to_string(sshd.root.join("authorized_keys")).unwrap(); + allowed.push_str(&fs::read_to_string(pem.with_extension("pem.pub")).unwrap()); + fs::write(sshd.root.join("authorized_keys"), allowed).unwrap(); + + let session = Session::connect_with_key(sshd.login(), &pem, Some("open sesame"), &sshd.known_hosts, true).unwrap(); + assert!(session.folders("/").unwrap().iter().any(|folder| folder == "/tmp")); + drop(session); + + // The host is known by now, so these fail on the key and nothing else. + let wrong = Session::connect_with_key(sshd.login(), &pem, Some("open barley"), &sshd.known_hosts, false); + assert!(wrong.is_err(), "a wrong passphrase got in"); + let none = Session::connect_with_key(sshd.login(), &pem, None, &sshd.known_hosts, false); + let said = format!("{:#}", none.err().expect("no passphrase got in")); + assert!(said.contains("has a passphrase and none was given"), "{said}"); + + // And a key that is not there is said to be not there. + let gone = Session::connect_with_key(sshd.login(), &sshd.root.join("nothing.pem"), None, &sshd.known_hosts, false); + assert!(format!("{:#}", gone.err().unwrap()).contains("there is no key at")); +} diff --git a/crates/gitrust-ui/src/main.rs b/crates/gitrust-ui/src/main.rs index 60a6948..0312c6b 100644 --- a/crates/gitrust-ui/src/main.rs +++ b/crates/gitrust-ui/src/main.rs @@ -379,6 +379,8 @@ enum Browsing { Folder { beside: bool }, /// A private key for a profile. Key { which: usize }, + /// A private key for the remote checkout being connected to. + RemoteKey, } /// A repository being brought down, and where it is going. @@ -579,9 +581,10 @@ impl App { self.file_under_profile(); } - fn add_remote(&mut self, session: gitrust_core::ssh::Session, path: String) { + fn add_remote(&mut self, session: gitrust_core::ssh::Session, path: String, key: Option) { match RemoteRepo::new(session, path) { - Ok(repo) => { + Ok(mut repo) => { + repo.keyed(key); self.settings.remember_remote(repo.descriptor()); let saved = self.settings.save(); self.open.push(Open::new_remote(repo, self.opened, &self.settings.general)); @@ -648,7 +651,7 @@ impl App { fn act_on_pick(&mut self, act: picker::Act) { match act { picker::Act::Open(path) => self.open_tab(path), - picker::Act::OpenRemote { session, path } => self.add_remote(session, path), + picker::Act::OpenRemote { session, path, key } => self.add_remote(session, path, key), picker::Act::Start(path) => match gitrust_core::start::init( &path, Some(&self.settings.general.default_branch), @@ -670,6 +673,7 @@ impl App { } picker::Act::Close => self.picking = None, picker::Act::Browse { beside } => self.browse(Browsing::Folder { beside }), + picker::Act::BrowseKey => self.browse(Browsing::RemoteKey), } } @@ -690,7 +694,7 @@ impl App { std::thread::spawn(move || { let _ = send.send(match what { Browsing::Folder { .. } => chooser::folder("Choose a repository folder"), - Browsing::Key { .. } => chooser::file( + Browsing::Key { .. } | Browsing::RemoteKey => chooser::file( "Choose a private key", gitrust_core::home::folder().map(|home| home.join(".ssh")), ), @@ -719,6 +723,13 @@ impl App { self.keep_profiles(); } } + // And the other key goes into the box that asked: the + // connection is still to be made, by pressing Connect. + Ok(Some(path)) if matches!(what, Browsing::RemoteKey) => { + if let Some(state) = &mut self.picking { + state.take_key(&path); + } + } // Choosing a folder in a dialog called "choose a // repository folder" is the decision. Putting it in a box // and waiting for a second Open was a step that asked @@ -3254,19 +3265,27 @@ impl Open { } } - /// Re-authenticates deliberately, with the profile's key when it has - /// one and through the SSH agent after it. The descriptor has no - /// password, so a password-only server asks the user to reopen it from - /// the picker instead of retaining a secret for later. + /// Re-authenticates deliberately: with the key that was named for this + /// checkout when one was, and otherwise with the profile's key when it + /// has one and through the SSH agent after it. The descriptor has no + /// password and no passphrase, so a server that wants one asks the + /// user to reopen it from the picker instead of retaining a secret for + /// later. fn reconnect_remote(&mut self) { let Some(descriptor) = self.remote_descriptor.clone() else { return self.note_error("this tab has no remote connection details".to_string()); }; - let key = profile_key(self.profile.as_ref()); - match gitrust_core::ssh::Session::connect_as(descriptor.login.clone(), None, key.as_deref(), false) - .and_then(|session| RemoteRepo::new(session, descriptor.path.clone())) - { + let login = descriptor.login.clone(); + let session = match descriptor.key_file() { + Some(named) => gitrust_core::ssh::Session::connect_keyed(login, &named, None, false), + None => { + let key = profile_key(self.profile.as_ref()); + gitrust_core::ssh::Session::connect_as(login, None, key.as_deref(), false) + } + }; + match session.and_then(|session| RemoteRepo::new(session, descriptor.path.clone())) { Ok(mut repo) => { + repo.keyed(descriptor.key.clone()); repo.pruning(self.general.auto_prune); self.remote = Some(repo); self.name_the_remote(); @@ -5003,7 +5022,13 @@ impl Open { /// that folder, reached with `ssh`. fn start_terminal(&self, ctx: &egui::Context) -> std::io::Result { let who = self.profile.as_ref().and_then(Profile::who); - let key = profile_key(self.profile.as_ref()); + // The key that was named for a checkout on another machine goes + // before the profile's, as it does when the checkout is opened. + let key = self + .remote_descriptor + .as_ref() + .and_then(gitrust_core::ssh::RemoteDescriptor::key_file) + .or_else(|| profile_key(self.profile.as_ref())); let caret = self.general.terminal_caret; let start = match &self.remote_descriptor { Some(remote) => terminal::Start { diff --git a/crates/gitrust-ui/src/picker.rs b/crates/gitrust-ui/src/picker.rs index 647c6a1..d7a4d1c 100644 --- a/crates/gitrust-ui/src/picker.rs +++ b/crates/gitrust-ui/src/picker.rs @@ -22,7 +22,10 @@ pub enum Act { Open(PathBuf), /// Open the authenticated checkout without ever putting its path on this /// computer's known-repository list. - OpenRemote { session: ssh::Session, path: String }, + /// + /// `key` is the private key that was named for the connection, as it + /// was typed, so the checkout can be reached with it again. + OpenRemote { session: ssh::Session, path: String, key: Option }, /// Bring one down from an address into a folder. Clone { url: String, into: PathBuf }, /// Make an empty one there. @@ -36,6 +39,8 @@ pub enum Act { /// Ask the desktop for a folder, and put what comes back in a box. /// `beside` picks which: the one a clone lands in, or the one above it. Browse { beside: bool }, + /// Ask the desktop for a private key file, for the remote box. + BrowseKey, } /// Which box is open, when one is. @@ -83,6 +88,11 @@ struct Remote { host: String, user: String, port: String, + /// A private key file to connect with -- the `.pem` a server hands + /// out -- or blank for the profile's key and the agent. + key: String, + /// The password, or with a key named, that key's passphrase. Taken + /// out of here the moment Connect is pressed. password: String, path: String, folders: Vec, @@ -103,6 +113,7 @@ impl Default for Picker { host: String::new(), user: String::new(), port: "22".to_string(), + key: String::new(), password: String::new(), path: "/".to_string(), folders: Vec::new(), @@ -124,6 +135,14 @@ impl Picker { self.asking == Some(Asking::Start) } + /// Puts the key the desktop's dialog came back with into the remote + /// box. Whatever was connected is let go of: it got in some other way. + pub fn take_key(&mut self, key: &Path) { + self.remote.key = key.display().to_string(); + self.remote.session = None; + self.remote.note = None; + } + /// Where a clone typed in right now would go. fn landing(&self) -> Option { gitrust_core::start::folder_for(&self.draft, Path::new(self.beside.trim())) @@ -417,6 +436,7 @@ fn remote_picker( let mut open = None; let whom = connecting_as(profiles, remote); let key = crate::profile_key(whom); + let mut browse = false; ui.add_space(8.0); egui::Frame::NONE .fill(theme::raised()) @@ -434,8 +454,12 @@ fn remote_picker( remote.user = saved.login.user.clone(); remote.port = saved.login.port.to_string(); remote.path = saved.path.clone(); + remote.key = saved.key.clone().unwrap_or_default(); remote.session = None; - remote.note = Some(("Press Connect to authenticate again; no password was saved.".to_string(), false)); + remote.note = Some((match saved.key { + Some(_) => "Press Connect to authenticate again. Its key was remembered; a passphrase is not.", + None => "Press Connect to authenticate again; no password was saved.", + }.to_string(), false)); } } }); @@ -465,6 +489,7 @@ fn remote_picker( .unwrap_or_else(|| saved.alias.clone()); remote.user = saved.user.clone().unwrap_or_default(); remote.port = saved.port.unwrap_or(22).to_string(); + remote.key.clear(); remote.session = None; remote.note = None; } @@ -476,16 +501,44 @@ fn remote_picker( ui.add(egui::TextEdit::singleline(&mut remote.user).hint_text("user").desired_width(120.0)); ui.add(egui::TextEdit::singleline(&mut remote.host).hint_text("host").desired_width(190.0)); ui.add(egui::TextEdit::singleline(&mut remote.port).hint_text("port").desired_width(62.0)); - ui.add(egui::TextEdit::singleline(&mut remote.password).password(true).hint_text("password").desired_width(150.0)); + }); + ui.add_space(4.0); + // How to get in, on a line of its own: a key file, a password, + // or neither. With a key named the secret beside it is that + // key's, so the box says which of the two it is asking for. + let named = ssh::key_file(&remote.key); + ui.horizontal(|ui| { + ui.add( + egui::TextEdit::singleline(&mut remote.key) + .hint_text("private key file (.pem), if it has one") + .font(theme::mono(11.5)) + .desired_width(290.0), + ); + if ui + .small_button("\u{2026}") + .on_hover_text("Pick the key file") + .clicked() + { + browse = true; + } + let secret = match named { + Some(_) => "key passphrase, if any", + None => "password", + }; + ui.add(egui::TextEdit::singleline(&mut remote.password).password(true).hint_text(secret).desired_width(150.0)); let ready = !remote.user.trim().is_empty() && !remote.host.trim().is_empty(); if ui.add_enabled(ready, egui::Button::new("Connect").fill(theme::chosen())).clicked() { let port = remote.port.trim().parse().unwrap_or(22); let password = std::mem::take(&mut remote.password); + let secret = (!password.is_empty()).then_some(password.as_str()); // Trust is a confirmation for this one connection attempt, never // a broad setting that could accept a later, unrelated host. let trust_new_host = std::mem::replace(&mut remote.trust_new_host, false); match ssh::Login::new(remote.host.trim().to_string(), remote.user.trim().to_string(), port) - .and_then(|login| ssh::Session::connect_as(login, (!password.is_empty()).then_some(password.as_str()), key.as_deref(), trust_new_host)) { + .and_then(|login| match &named { + Some(file) => ssh::Session::connect_keyed(login, file, secret, trust_new_host), + None => ssh::Session::connect_as(login, secret, key.as_deref(), trust_new_host), + }) { Ok(session) => match session.folders("/") { Ok(folders) => { remote.session = Some(session); @@ -501,31 +554,62 @@ fn remote_picker( // Who is about to knock, said before the knocking: a connection // refused is easier to understand next to the key it was tried // with than next to nothing. - if let Some(profile) = whom { - let name = match profile.name.trim().is_empty() { - true => "(no name)", - false => profile.name.trim(), - }; - let line = match (&key, profile.key.trim().is_empty()) { - (Some(_), _) => format!( - "As {name}: {} first, then the SSH agent. A password typed here goes before both.", - profile.key.trim() - ), - (None, true) => format!("As {name}, which has no key of its own: the SSH agent."), - (None, false) => format!( - "As {name}, whose key {} is not there: the SSH agent.", - profile.key.trim() - ), - }; + // The key is named the way it was typed: that is the line + // somebody is checking against, and the short one. + let mut warning = None; + let line = match (&named, whom) { + (Some(file), _) => { + // The connection made here does not mind, and the + // terminal's will: `ssh` refuses a key that other + // people on this machine can read, which is how a + // downloaded .pem arrives. + if open_to_others(file) { + warning = Some(format!( + "Others on this machine can read that file. It opens the checkout as it is, \ + but ssh will refuse it in the terminal until: chmod 600 {}", + remote.key.trim() + )); + } + Some(format!( + "With {}, and nothing after it: not the profile's key, not the SSH agent.", + remote.key.trim() + )) + } + (None, Some(profile)) => { + let name = match profile.name.trim().is_empty() { + true => "(no name)", + false => profile.name.trim(), + }; + Some(match (&key, profile.key.trim().is_empty()) { + (Some(_), _) => format!( + "As {name}: {} first, then the SSH agent. A password typed here goes before both.", + profile.key.trim() + ), + (None, true) => format!("As {name}, which has no key of its own: the SSH agent."), + (None, false) => format!( + "As {name}, whose key {} is not there: the SSH agent.", + profile.key.trim() + ), + }) + } + (None, None) => None, + }; + if let Some(line) = line { ui.add_space(3.0); ui.label(RichText::new(line).font(theme::body(11.0)).color(theme::faint())); } + if let Some(warning) = warning { + ui.label(RichText::new(warning).font(theme::body(11.0)).color(theme::muted())); + } ui.checkbox(&mut remote.trust_new_host, "I verified this host key; trust and save it for this attempt"); if let Some((note, bad)) = &remote.note { ui.add_space(3.0); ui.label(RichText::new(note).font(theme::body(11.5)).color(if *bad { theme::removed() } else { theme::muted() })); } }); + if browse { + return Some(Act::BrowseKey); + } let Some(session) = remote.session.as_ref() else { return None; }; @@ -584,9 +668,11 @@ fn remote_picker( }); if use_folder { let session = remote.session.take().expect("session checked above"); + let key = remote.key.trim(); open = Some(Act::OpenRemote { session, path: remote.path.clone(), + key: (!key.is_empty()).then(|| key.to_string()), }); } open @@ -609,6 +695,24 @@ fn connecting_as<'a>(profiles: &'a Profiles, remote: &Remote) -> Option<&'a Prof .or(profiles.active()) } +/// Whether anybody but its owner can read that file. +/// +/// Only asked on Unix, where it is what `ssh` asks before it will use a +/// key. A file that cannot be looked at is not complained about here: the +/// connection will say what is wrong with it. +fn open_to_others(file: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(file).is_ok_and(|about| about.permissions().mode() & 0o077 != 0) + } + #[cfg(not(unix))] + { + let _ = file; + false + } +} + fn remote_list_row(ui: &mut egui::Ui, _kind: &str, label: &str, selected: bool) -> egui::Response { let (rect, response) = ui.allocate_exact_size( egui::vec2(ui.available_width(), theme::ROW_H), From 053ea3f09ba34482962bfc2b1f3bcbbba8800db3 Mon Sep 17 00:00:00 2001 From: Francesc Date: Thu, 12 Nov 2026 22:15:40 +0100 Subject: [PATCH 3/3] feat: the window keeps up with what other programs do to the repository 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 the window went on showing what was true when it last read until somebody pressed the reload button -- which takes knowing it is stale. GitKraken is told by the system: every folder of the working tree is watched, it waits two seconds for the events to stop and reads again the part they were about. That comes with three messages of its own, for a watcher that would not start, that ran out of watches, that 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, 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 looking is never more than a twentieth of the time. What a look gives is a pulse: two numbers, one for what Git keeps -- HEAD, the references, the stashes, what is half-done -- and one for the working tree, which is the list of changes and, beside each, when the file was written and which blob is staged, so a file saved a second time is not the same as the first. The tab keeps the pulse of what it is showing, read in the same walk as the list it shows. A look that matches it does nothing at all, which is every look that found nothing and every look that found what the window had just done itself. Otherwise only the half that moved is read again: a saved file is the list of changes and the message being written stays where it is; a branch that moved is the whole history, as the button would. No dependency, no limit to run out of, the same on all three systems. Only the repository in front -- the others are looked at when they are brought forward -- and not a checkout on another machine, where a look is a round trip on a connection the window is using. Run on Linux, on a virtual display: a commit, a new file and a branch made by another program each turned up without the window being touched, at about one part in a hundred of a processor while idle. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Francesc --- README.md | 32 +++- crates/gitrust-core/src/lib.rs | 2 +- crates/gitrust-core/src/repo.rs | 94 +++++++++- crates/gitrust-core/src/status.rs | 20 +++ crates/gitrust-core/tests/working_tree.rs | 53 ++++++ crates/gitrust-ui/src/main.rs | 98 ++++++++++- crates/gitrust-ui/src/watch.rs | 198 ++++++++++++++++++++++ 7 files changed, 485 insertions(+), 12 deletions(-) create mode 100644 crates/gitrust-ui/src/watch.rs 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); + } +}