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)