A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
feat(plugins): fields and keys in plugin panels
RoversX3f1d1fc67e1d
diff --git a/config/src/keyassignment.rs b/config/src/keyassignment.rsindex b919c26f..18a22932 100644--- a/config/src/keyassignment.rs+++ b/config/src/keyassignment.rs@@ -645,6 +645,10 @@ pub enum KeyAssignment {/// `OpenSshHosts`, which toggles the page: this one only ever opens.AddRemoteHost,ToggleLiveOverview,+ /// Open the right sidebar on this plugin's panel and give it the+ /// keyboard -- in its first field, if it has one. Pressed again while+ /// the panel has it, the keyboard goes back to the terminal.+ FocusPluginPanel(String),ActivateCommandPalette,/// Switch this window's color scheme. `None` reverts to the configured/// default. Applied through the window's config_overrides, the samediff --git a/plugins/diff/src/main.rs b/plugins/diff/src/main.rsindex 6f1600b8..b358bda7 100644--- a/plugins/diff/src/main.rs+++ b/plugins/diff/src/main.rs@@ -6,9 +6,12 @@//! asks git again every two seconds while a panel is on show, and sends a//! file's lines only as they are asked for, so a file of ten thousand//! changed lines costs what shows. A terminal on another machine has git-//! asked there, through ThinkTerm's connection to it.+//! asked there, through ThinkTerm's connection to it. Where a client has+//! fields, one above the files filters them by name; with the keyboard in+//! the panel, up and down pick the file before or after, and Return in+//! the filter the first it leaves.//!-//! It draws by hand, with the SDK's items and nothing else.+//! It draws by hand, with the SDK's items and one field.//! docs/thinkterm/plugins.md says how to install it.mod git;@@ -17,11 +20,13 @@ mod watch;use git::{Change, FileDiff, Kind, Line, Note, Status};use std::collections::hash_map::DefaultHasher;+use std::collections::HashMap;use std::hash::{Hash, Hasher};use std::sync::Arc;use text::Words;use thinkterm_plugin_sdk::panel::{- Align, Click, Env, Frame, Hit, Input, Item, List, Rect, RowsWanted, Size, Text, Token,+ feature, Align, Click, Env, FieldText, Frame, Hit, Input, Item, Jump, Key, List, Rect,+ RowsWanted, Size, Text, Token,};use thinkterm_plugin_sdk::{Cx, Plugin, View};use unicode_width::UnicodeWidthChar;@@ -38,16 +43,26 @@ const BADGE: f32 = 16.0;const ROW_RADIUS: f32 = 6.0;/// Room kept at a list's right edge for its scrollbar.const THUMB_ROOM: f32 = 8.0;+/// The field the files are filtered with.+const FILTER: &str = "filter";struct DiffPanel {shared: Shared,+ /// What each panel's filter holds, by the panel's view.+ filters: HashMap<u64, FieldText>,+ /// How many times each panel's file was picked with the keys: its list+ /// keeps the last in view, once for each.+ reveals: HashMap<u64, u32>,}/// Where things go in a panel of one size, listing `files` rows: the/// picked file's lines below them when it shows those itself (`inside`),-/// the files alone down to its foot when its extended view does.+/// the files alone down to its foot when its extended view does. A client+/// with fields has the filter above the files.struct Layout {width: f32,+ /// Where the filter goes, and how tall it is: none without fields.+ filter: Option<(f32, f32)>,header: f32,file_row: f32,files_height: f32,@@ -60,7 +75,13 @@ struct Layout {impl Layout {fn of(env: &Env, files: usize, inside: bool) -> Self {- let header = 10.0 + env.title.line + env.small.line + 10.0;+ let mut header = 10.0 + env.title.line + env.small.line + 10.0;+ let filter = env.has(feature::FIELDS).then(|| {+ let tall = env.body.line + 10.0;+ let top = header - 2.0;+ header += tall + 6.0;+ (top, tall)+ });let file_row = env.body.line + env.small.line + 12.0;let wanted = files as f32 * file_row;let room = (env.height - header).max(0.0);@@ -76,6 +97,7 @@ impl Layout {let diff_top = diff_header_top + diff_header;Self {width: env.width,+ filter,header,file_row,files_height,@@ -161,8 +183,13 @@ impl Plugin for DiffPanel {Some(Place::Failed(why)) => say(frame, env, PAD, PAD, words.failed, Some(why)),Some(Place::Repo(repo)) => {frame.extend(state.picked(view.id, repo).is_some());+ // Up and down pick the file before or after, while the+ // panel has the keyboard.+ frame.keys(&["ArrowUp", "ArrowDown"]);let shown = state.shown(view.id, repo);- draw_repo(frame, env, words, &dir, repo, shown, inside);+ let filter = self.filters.entry(view.id).or_default();+ let reveal = self.reveals.get(&view.id).copied();+ draw_repo(frame, env, words, &dir, repo, shown, inside, filter, reveal);}}}@@ -188,11 +215,13 @@ impl Plugin for DiffPanel {false => state.shown(panel, repo),};let (from, to) = (wanted.from as usize, wanted.to as usize);+ let filter = self.filters.get(&panel).map_or("", FieldText::text);match wanted.list.as_str() {- "files" if !view.extended() && wanted.key == files_key(&dir) => {- let files = &repo.snapshot.files;- let at = Layout::of(env, rows_of(repo), want.inside);- (from..to.min(rows_of(repo)))+ "files" if !view.extended() && wanted.key == files_key(&dir, filter) => {+ let files = listed(repo, filter);+ let count = rows_of(repo, filter);+ let at = Layout::of(env, count, want.inside);+ (from..to.min(count)).map(|row| match files.get(row) {Some(file) => {let marked = shown.is_some_and(|shown| shown.path == file.path);@@ -223,15 +252,38 @@ impl Plugin for DiffPanel {}fn input(&mut self, view: &View, input: Input, _cx: &mut Cx) {+ let panel = view.panel();match input {Input::Click(Click { id, .. }) => {if let Some(path) = id.strip_prefix("file:") {- watch::pick(&self.shared, view.panel(), Some(path.to_string()));+ watch::pick(&self.shared, panel, Some(path.to_string()));}}// The extended view was closed: the file is put down, and the// panel stops asking for it.- Input::Close => watch::pick(&self.shared, view.panel(), None),+ Input::Close => watch::pick(&self.shared, panel, None),+ Input::Text(typed) if typed.id == FILTER => {+ self.filters.entry(panel).or_default().heard(&typed);+ }+ // Return in the filter picks the first file it leaves.+ Input::Submit(typed) if typed.id == FILTER => {+ self.filters.entry(panel).or_default().heard(&typed);+ self.pick_listed(panel, |_, _| 0);+ *self.reveals.entry(panel).or_default() += 1;+ }+ Input::Key(Key { key, .. }) => {+ match key.as_str() {+ "ArrowUp" => {+ self.pick_listed(panel, |at, _| at.map_or(0, |at| at.saturating_sub(1)))+ }+ "ArrowDown" => self.pick_listed(panel, |at, count| {+ at.map_or(0, |at| (at + 1).min(count - 1))+ }),+ _ => return,+ }+ *self.reveals.entry(panel).or_default() += 1;+ }+ _ => {}}}@@ -239,11 +291,39 @@ impl Plugin for DiffPanel {// The panel an extended view leaves keeps what it wants.if !view.extended() {watch::close(&self.shared, view.id);+ self.filters.remove(&view.id);+ self.reveals.remove(&view.id);}}}impl DiffPanel {+ /// Picks the file of panel `panel`'s list -- as its filter leaves it --+ /// that `next` says, from where the one it shows is in it, if it is, and+ /// how many there are.+ fn pick_listed(&self, panel: u64, next: impl FnOnce(Option<usize>, usize) -> usize) {+ let path = {+ let state = watch::lock(&self.shared);+ let Some(dir) = state.views.get(&panel).and_then(|want| want.dir.clone()) else {+ return;+ };+ let Some(Place::Repo(repo)) = state.places.get(&dir) else {+ return;+ };+ let filter = self.filters.get(&panel).map_or("", FieldText::text);+ let files = listed(repo, filter);+ if files.is_empty() {+ return;+ }+ let shown = state.shown(panel, repo);+ let at = shown.and_then(|shown| files.iter().position(|file| file.path == shown.path));+ files[next(at, files.len()).min(files.len() - 1)]+ .path+ .clone()+ };+ watch::pick(&self.shared, panel, Some(path));+ }+/// The extended view: the lines of the file its panel picked.fn draw_extended(&self, view: &View, frame: &mut Frame) {let env = &view.env;@@ -263,9 +343,21 @@ impl DiffPanel {}}-/// The key of the files list of the panels in `dir`.-fn files_key(dir: &Dir) -> String {- dir.key()+/// The key of the files list of the panels in `dir`, filtered by `filter`:+/// another filter, other rows.+fn files_key(dir: &Dir, filter: &str) -> String {+ format!("{}\n{filter}", dir.key())+}++/// The files of `repo` whose paths have `filter` in them, whatever their+/// case: all of them for none.+fn listed<'a>(repo: &'a Repo, filter: &str) -> Vec<&'a Change> {+ let filter = filter.trim().to_lowercase();+ repo.snapshot+ .files+ .iter()+ .filter(|file| filter.is_empty() || file.path.to_lowercase().contains(&filter))+ .collect()}/// The key of the list of `path`'s lines, in `dir`.@@ -273,14 +365,16 @@ fn diff_key(dir: &Dir, path: &str) -> String {format!("{}\n{path}", dir.key())}-/// Rows the files list has: one a file, and one saying how many more there-/// are when not all are listed.-fn rows_of(repo: &Repo) -> usize {- repo.snapshot.files.len() + usize::from(repo.snapshot.more > 0)+/// Rows the files list has, as `filter` leaves it: one a file, and, with no+/// filter, one saying how many more there are when not all are listed.+fn rows_of(repo: &Repo, filter: &str) -> usize {+ let more = filter.trim().is_empty() && repo.snapshot.more > 0;+ listed(repo, filter).len() + usize::from(more)}-/// The repository's name, branch and changes, and the files: with the-/// lines of the one `shown` below them, `inside` the panel.+/// The repository's name, branch and changes, the filter, and the files:+/// with the lines of the one `shown` below them, `inside` the panel.+#[allow(clippy::too_many_arguments)]fn draw_repo(frame: &mut Frame,env: &Env,@@ -289,9 +383,12 @@ fn draw_repo(repo: &Repo,shown: Option<&Change>,inside: bool,+ filter: &FieldText,+ reveal: Option<u32>,) {let snapshot = &repo.snapshot;- let at = Layout::of(env, rows_of(repo), inside);+ let rows = rows_of(repo, filter.text());+ let at = Layout::of(env, rows, inside);let name = snapshot.root.rsplit('/')@@ -337,25 +434,45 @@ fn draw_repo();frame.push(about.size(Size::Small).color(Token::TextMuted));if snapshot.files.is_empty() {- say(frame, env, PAD, at.header, words.clean, None);+ // Where the filter would be: there is nothing to filter.+ let top = at.filter.map_or(at.header, |(top, _)| top);+ say(frame, env, PAD, top, words.clean, None);return;}+ if let Some((top, tall)) = at.filter {+ let field = filter.field(FILTER, PAD, top, at.width - PAD * 2.0, tall);+ frame.push(field.placeholder(words.filter).icon("search").clear());+ }+ let listed = listed(repo, filter.text());+ if listed.is_empty() {+ say(frame, env, PAD, at.header, words.no_match, None);+ }let version = {let mut hasher = DefaultHasher::new();(repo.revision, shown.map(|file| &file.path), inside).hash(&mut hasher);hasher.finish() as u32};- let files = List::new(+ let mut files = List::new("files",0.0,at.header,at.width,at.files_height,- rows_of(repo) as u32,+ rows as u32,at.file_row,- files_key(dir),+ files_key(dir, filter.text()),);+ // The file picked with the keys, kept in view.+ let picked = shown.and_then(|file| listed.iter().position(|row| row.path == file.path));+ if let (Some(seq), Some(at)) = (reveal, picked) {+ let at = at as f32;+ files = files.top(Jump {+ to: at,+ seq,+ through: Some(at + 1.0),+ });+ }frame.push(files.version(version));if !inside {return;@@ -787,7 +904,11 @@ fn main() -> std::io::Result<()> {if let Err(err) = started {eprintln!("diff: cannot start looking: {err}");}- DiffPanel { shared }+ DiffPanel {+ shared,+ filters: HashMap::new(),+ reveals: HashMap::new(),+ }})}@@ -822,6 +943,7 @@ mod tests {remote: None,can_extend: false,close: None,+ features: Vec::new(),}}@@ -882,7 +1004,11 @@ mod tests {);state.views.insert(1, Want::default());}- DiffPanel { shared }+ DiffPanel {+ shared,+ filters: HashMap::new(),+ reveals: HashMap::new(),+ }}fn texts(player: &Player) -> Vec<String> {@@ -950,6 +1076,79 @@ mod tests {);}+ #[test]+ fn the_filter_leaves_the_files_it_names_and_the_keys_pick_among_them() {+ let mut panel = panel();+ let with_fields = Env {+ features: vec![feature::FIELDS.into(), feature::KEYS.into()],+ ..env()+ };+ let view = View::new(1, with_fields.clone());+ let mut player = Player::new(with_fields);+ show(&mut panel, &view, &mut player);+ assert_eq!(player.fields().count(), 1, "the filter");+ let picked = |panel: &DiffPanel| watch::lock(&panel.shared).views[&1].picked.clone();+ let key = |name: &str| {+ Input::Key(Key {+ key: name.into(),+ mods: Mods::default(),+ })+ };+ // Down from the first shown below the files.+ panel.input(&view, key("ArrowDown"), &mut Cx::new());+ assert_eq!(picked(&panel).as_deref(), Some("src/long.rs"));+ panel.input(&view, key("ArrowDown"), &mut Cx::new());+ panel.input(&view, key("ArrowDown"), &mut Cx::new());+ assert_eq!(+ picked(&panel).as_deref(),+ Some("src/new.rs"),+ "no further than the last"+ );+ panel.input(&view, key("ArrowUp"), &mut Cx::new());+ assert_eq!(picked(&panel).as_deref(), Some("src/long.rs"));++ // The list follows the pick made with the keys.+ let mut frame = Frame::default();+ panel.draw(&view, &mut frame);+ let top = frame.items.iter().find_map(|item| match item {+ Item::List(list) if list.id == "files" => list.top,+ _ => None,+ });+ assert_eq!(+ top.and_then(|jump| jump.through),+ Some(2.0),+ "row 1, in view"+ );++ let typed = |text: &str| thinkterm_plugin_sdk::panel::Typed {+ id: FILTER.into(),+ text: text.into(),+ seq: 0,+ };+ panel.input(&view, Input::Text(typed("READ")), &mut Cx::new());+ show(&mut panel, &view, &mut player);+ let shown = texts(&player);+ assert!(shown.contains(&"README.md".to_string()), "{shown:?}");+ assert!(+ !shown.contains(&"new.rs".to_string()),+ "filtered out: {shown:?}"+ );+ panel.input(&view, Input::Submit(typed("READ")), &mut Cx::new());+ assert_eq!(+ picked(&panel).as_deref(),+ Some("README.md"),+ "the first it leaves"+ );+ // The client empties it with its button: a field that asks for one.+ assert!(player.fields().next().is_some_and(|field| field.clear));+ panel.input(&view, Input::Text(typed("zzz")), &mut Cx::new());+ show(&mut panel, &view, &mut player);+ let words = text::words("en-US");+ assert!(texts(&player).contains(&words.no_match.to_string()));+ panel.closed(&view);+ assert!(panel.filters.is_empty() && panel.reveals.is_empty());+ }+#[test]fn a_repository_on_another_machine_says_which_and_is_its_own_place() {let mut panel = panel();diff --git a/plugins/diff/src/text.rs b/plugins/diff/src/text.rsindex 135943f3..365013fc 100644--- a/plugins/diff/src/text.rs+++ b/plugins/diff/src/text.rs@@ -19,6 +19,10 @@ pub struct Words {pub mode: &'static str,pub unchanged: &'static str,pub cut: &'static str,+ /// What the empty filter says.+ pub filter: &'static str,+ /// No file's path has what the filter holds.+ pub no_match: &'static str,}/// The words for `locale`, a tag such as `zh-CN`.@@ -55,6 +59,8 @@ static ENGLISH: Words = Words {mode: "Only the file's mode changed.",unchanged: "Renamed, without changes.",cut: "Too long: the rest is not shown.",+ filter: "Filter files",+ no_match: "No file matches",};static CHINESE: Words = Words {@@ -73,6 +79,8 @@ static CHINESE: Words = Words {mode: "只改了文件权限。",unchanged: "只改了名字,内容没变。",cut: "太长了,后面的不显示。",+ filter: "筛选文件",+ no_match: "没有匹配的文件",};static JAPANESE: Words = Words {@@ -91,6 +99,8 @@ static JAPANESE: Words = Words {mode: "ファイルのモードだけが変わりました。",unchanged: "名前だけが変わり、内容は同じです。",cut: "長すぎるため、以降は表示しません。",+ filter: "ファイルを絞り込む",+ no_match: "一致するファイルはありません",};static GERMAN: Words = Words {@@ -115,6 +125,8 @@ static GERMAN: Words = Words {mode: "Nur der Dateimodus wurde geändert.",unchanged: "Umbenannt, ohne Änderungen.",cut: "Zu lang: Der Rest wird nicht angezeigt.",+ filter: "Dateien filtern",+ no_match: "Keine Datei passt",};static FRENCH: Words = Words {@@ -140,6 +152,8 @@ static FRENCH: Words = Words {mode: "Seul le mode du fichier a changé.",unchanged: "Renommé sans modification.",cut: "Trop long : la suite n'est pas affichée.",+ filter: "Filtrer les fichiers",+ no_match: "Aucun fichier ne correspond",};#[cfg(test)]diff --git a/plugins/stocks/src/main.rs b/plugins/stocks/src/main.rsindex c1dc6d92..7aa2437a 100644--- a/plugins/stocks/src/main.rs+++ b/plugins/stocks/src/main.rs@@ -5,9 +5,12 @@//! the panel is drawn anew as they come.//!//! The watchlist is kept in the plugin's data directory, one symbol a-//! line, and changed with calls:+//! line. A symbol is added by typing it in the field at the panel's top,+//! where a client has fields, or with a call://! `thinkterm plugin call stocks '{"op":"add","symbol":"TSM"}'`, and-//! `"remove"` the same way. docs/thinkterm/plugins.md says how to install it.+//! `"remove"` the same way. With the keyboard in the panel, up and down+//! pick the symbol before or after. docs/thinkterm/plugins.md says how to+//! install it.mod market;mod yahoo;@@ -18,21 +21,29 @@ use serde_json::{json, Value};use std::collections::HashMap;use std::sync::{Arc, Condvar, Mutex};use thinkterm_plugin_sdk::panel::{- Align, Area, Click, Env, Frame, Hit, Input, Item, Line, Rect, Scroll, Size, Text, Token,+ feature, Align, Area, Click, Env, FieldText, Frame, Hit, Input, Item, Jump, Key, Line, Rect,+ Scroll, Size, Text, Token,};use thinkterm_plugin_sdk::{Cx, Plugin, View};use yahoo::{Chart, Day, Range};/// Room at the panel's sides.const PAD: f32 = 12.0;+/// The field a symbol is typed in to add it.+const ADD: &str = "add";+/// The longest symbol a watchlist keeps.+const SYMBOL_LIMIT: u32 = 24;/// Where the chart's prices go, to its right.const SCALE_WIDTH: f32 = 56.0;-/// What one panel on show has picked.+/// What one panel on show has picked, and how many times its symbol was+/// picked with the keys: the watchlist keeps the last in view, once for+/// each.#[derive(Clone, Copy)]struct Pick {symbol: usize,range: Range,+ reveal: u32,}impl Default for Pick {@@ -40,6 +51,7 @@ impl Default for Pick {Self {symbol: 0,range: Range::Day,+ reveal: 0,}}}@@ -47,6 +59,16 @@ impl Default for Pick {struct Stocks {market: Shared,picks: HashMap<u64, Pick>,+ /// What each panel's field for adding a symbol holds.+ adding: HashMap<u64, Adding>,+}++/// A panel's field for adding a symbol, and why the last symbol typed+/// there was not added.+#[derive(Default)]+struct Adding {+ text: FieldText,+ refused: Option<String>,}impl Stocks {@@ -66,7 +88,7 @@ impl Stocks {let symbol = body["symbol"].as_str().map(|symbol| symbol.trim().to_ascii_uppercase())- .filter(|symbol| !symbol.is_empty() && symbol.len() <= 24)+ .filter(|symbol| !symbol.is_empty() && symbol.len() <= SYMBOL_LIMIT as usize).context("a \"symbol\" is needed, such as \"TSM\"")?;let removed = {let mut market = lock(&self.market);@@ -117,46 +139,111 @@ impl Plugin for Stocks {self.want();}let pick = self.picks[&view.id];+ let adding = view+ .env+ .has(feature::FIELDS)+ .then(|| self.adding.entry(view.id).or_default());let market = lock(&self.market);- draw(&market, pick, &view.env, frame);+ draw(&market, pick, adding.as_deref(), &view.env, frame);}- fn input(&mut self, view: &View, input: Input, _cx: &mut Cx) {- let Input::Click(Click { id, .. }) = input else {- return;- };- let pick = self.picks.entry(view.id).or_default();- if let Some(symbol) = id.strip_prefix("quote:").and_then(|at| at.parse().ok()) {- pick.symbol = symbol;- } else if let Some(range) = id- .strip_prefix("range:")- .and_then(|label| Range::ALL.into_iter().find(|range| range.label() == label))- {- pick.range = range;+ fn input(&mut self, view: &View, input: Input, cx: &mut Cx) {+ match input {+ Input::Click(Click { id, .. }) => {+ let pick = self.picks.entry(view.id).or_default();+ if let Some(symbol) = id.strip_prefix("quote:").and_then(|at| at.parse().ok()) {+ pick.symbol = symbol;+ } else if let Some(range) = id+ .strip_prefix("range:")+ .and_then(|label| Range::ALL.into_iter().find(|range| range.label() == label))+ {+ pick.range = range;+ }+ }+ Input::Text(typed) if typed.id == ADD => {+ let adding = self.adding.entry(view.id).or_default();+ if adding.text.heard(&typed) {+ adding.refused = None;+ }+ }+ Input::Submit(typed) if typed.id == ADD => {+ let added = self.change_watchlist(&json!({"symbol": typed.text}), true);+ let adding = self.adding.entry(view.id).or_default();+ match added {+ Ok(_) => {+ adding.text.clear();+ adding.refused = None;+ // The symbol typed is picked, and every panel shows it.+ let symbol = typed.text.trim().to_ascii_uppercase();+ let at = lock(&self.market)+ .symbols+ .iter()+ .position(|kept| *kept == symbol);+ if let Some(at) = at {+ self.picks.entry(view.id).or_default().symbol = at;+ }+ cx.redraw();+ }+ Err(err) => {+ adding.text.heard(&typed);+ adding.refused = Some(format!("{err:#}"));+ }+ }+ }+ Input::Key(Key { key, .. }) => {+ let count = lock(&self.market).symbols.len();+ let pick = self.picks.entry(view.id).or_default();+ match key.as_str() {+ "ArrowUp" => pick.symbol = pick.symbol.saturating_sub(1),+ "ArrowDown" => pick.symbol = (pick.symbol + 1).min(count.saturating_sub(1)),+ _ => return,+ }+ pick.reveal += 1;+ }+ _ => return,}self.want();}fn closed(&mut self, view: &View) {self.picks.remove(&view.id);+ self.adding.remove(&view.id);self.want();}}-/// The whole panel: the watchlist above, the picked symbol's chart below.-fn draw(market: &Market, pick: Pick, env: &Env, frame: &mut Frame) {+/// The whole panel: the watchlist above -- with, where the client has+/// fields, one to add a symbol with -- the picked symbol's chart below.+fn draw(market: &Market, pick: Pick, adding: Option<&Adding>, env: &Env, frame: &mut Frame) {let width = env.width;- let header = env.title.line + 20.0;+ let mut header = env.title.line + 20.0;frame.push(Text::new(PAD, 10.0, width * 0.5, env.title.line, "Watchlist").size(Size::Title).bold(),);- let (status, color) = match &market.trouble {- Some(trouble) => (trouble.as_str(), Token::Negative),- None if market.days.is_empty() => ("Loading\u{2026}", Token::TextMuted),- None => ("Yahoo Finance", Token::TextFaint),+ // Up and down pick the symbol before and after, while the panel has+ // the keyboard.+ frame.keys(&["ArrowUp", "ArrowDown"]);+ let refused = adding.and_then(|adding| adding.refused.as_deref());+ let (status, color) = match (refused, &market.trouble) {+ (Some(refused), _) => (refused, Token::Negative),+ (None, Some(trouble)) => (trouble.as_str(), Token::Negative),+ (None, None) if market.days.is_empty() => ("Loading\u{2026}", Token::TextMuted),+ (None, None) => ("Yahoo Finance", Token::TextFaint),};+ if let Some(adding) = adding {+ let tall = env.body.line + 12.0;+ let (x, y, w) = (PAD, header - 4.0, width - PAD * 2.0);+ let add = adding.text.field(ADD, x, y, w, tall);+ frame.push(+ add.placeholder("Add a symbol, such as TSM")+ .max(SYMBOL_LIMIT)+ .icon("plus")+ .clear(),+ );+ header += tall + 4.0;+ }let status = Text::new(width * 0.4, 10.0, width * 0.6 - PAD, env.title.line, status);frame.push(status.size(Size::Small).color(color).align(Align::Right));@@ -178,7 +265,7 @@ fn draw(market: &Market, pick: Pick, env: &Env, frame: &mut Frame) {row,);}- frame.push(Scroll::new(+ let mut quotes = Scroll::new("quotes",0.0,header,@@ -186,7 +273,17 @@ fn draw(market: &Market, pick: Pick, env: &Env, frame: &mut Frame) {list_height,count as f32 * row,rows,- ));+ );+ // The symbol picked with the keys, kept in view.+ if pick.reveal > 0 {+ let at = pick.symbol as f32 * row;+ quotes = quotes.top(Jump {+ to: at,+ seq: pick.reveal,+ through: Some(at + row),+ });+ }+ frame.push(quotes);let top = header + list_height;frame.push(Rect::new(0.0, top, width, 1.0).fill(Token::Border));@@ -540,6 +637,7 @@ fn main() -> std::io::Result<()> {Stocks {market,picks: HashMap::new(),+ adding: HashMap::new(),}})}@@ -569,6 +667,7 @@ mod tests {remote: None,can_extend: false,close: None,+ features: vec![feature::FIELDS.into(), feature::KEYS.into()],}}@@ -602,6 +701,7 @@ mod tests {let mut stocks = Stocks {market: shared,picks: HashMap::new(),+ adding: HashMap::new(),};let view = View::new(3, env());let mut frame = Frame::default();@@ -613,9 +713,10 @@ mod tests {let mut player = Player::new(env());player.frame(frame);- // The second row of the watchlist.+ // The second row of the watchlist, below the field to add one.let row = env().body.line + env().small.line + 14.0;- let y = env().title.line + 20.0 + row * 1.5;+ let field = env().body.line + 12.0 + 4.0;+ let y = env().title.line + 20.0 + field + row * 1.5;let input = player.click(40.0, y, Default::default(), 1, Default::default()).unwrap();@@ -652,6 +753,86 @@ mod tests {assert_eq!(lock(&stocks.market).panels, 0);}+ #[test]+ fn a_symbol_typed_and_submitted_is_added_and_picked_and_the_keys_move_the_pick() {+ let mut market = Market::load(None);+ market.symbols = vec!["A".into(), "B".into()];+ let shared: Shared = Arc::new((Mutex::new(market), Condvar::new()));+ let mut stocks = Stocks {+ market: shared,+ picks: HashMap::new(),+ adding: HashMap::new(),+ };+ let view = View::new(1, env());+ let mut frame = Frame::default();+ stocks.draw(&view, &mut frame);+ assert!(+ frame+ .items+ .iter()+ .any(|item| matches!(item, Item::Field(field) if field.id == ADD)),+ "a field to add one with"+ );+ let typed_over = |text: &str, seq: u32| thinkterm_plugin_sdk::panel::Typed {+ id: ADD.into(),+ text: text.into(),+ seq,+ };+ let typed = |text: &str| typed_over(text, 0);+ stocks.input(&view, Input::Text(typed("tsm")), &mut Cx::new());+ let mut cx = Cx::new();+ stocks.input(&view, Input::Submit(typed("tsm")), &mut cx);+ assert_eq!(lock(&stocks.market).symbols, ["A", "B", "TSM"]);+ assert_eq!(stocks.picks[&1].symbol, 2, "picked");+ assert!(cx.finish().redraw, "every panel shows it");+ let field = |stocks: &mut Stocks| {+ let mut frame = Frame::default();+ stocks.draw(&view, &mut frame);+ frame.items.into_iter().find_map(|item| match item {+ Item::Field(field) if field.id == ADD => Some(field),+ _ => None,+ })+ };+ let cleared = field(&mut stocks).expect("the field");+ assert_eq!(+ (cleared.value.as_str(), cleared.seq),+ ("", 1),+ "emptied, once"+ );+ assert!(cleared.clear, "with the client's button to empty it");+ // Typed over the text before it was emptied: the field takes the+ // empty one, and so does the plugin.+ stocks.input(&view, Input::Text(typed("tsmx")), &mut Cx::new());+ assert_eq!(field(&mut stocks).unwrap().value, "");+ stocks.input(&view, Input::Text(typed_over("ns", 1)), &mut Cx::new());+ assert_eq!(field(&mut stocks).unwrap().value, "ns");++ let key = |name: &str| {+ Input::Key(Key {+ key: name.into(),+ mods: Default::default(),+ })+ };+ stocks.input(&view, key("ArrowUp"), &mut Cx::new());+ assert_eq!(stocks.picks[&1].symbol, 1);+ stocks.input(&view, key("ArrowDown"), &mut Cx::new());+ stocks.input(&view, key("ArrowDown"), &mut Cx::new());+ assert_eq!(stocks.picks[&1].symbol, 2, "no further than the last");+ // The watchlist follows the pick made with the keys.+ let mut frame = Frame::default();+ stocks.draw(&view, &mut frame);+ let top = frame.items.iter().find_map(|item| match item {+ Item::Scroll(scroll) if scroll.id == "quotes" => scroll.top,+ _ => None,+ });+ assert!(top.is_some_and(|jump| jump.seq == 3 && jump.through.is_some()));++ stocks.input(&view, Input::Submit(typed("")), &mut Cx::new());+ assert!(stocks.adding[&1].refused.is_some(), "says why");+ stocks.closed(&view);+ assert!(stocks.adding.is_empty());+ }+#[test]fn a_symbol_taken_off_leaves_the_others_picked_and_nothing_of_itself() {let mut market = Market::load(None);@@ -670,6 +851,7 @@ mod tests {let mut stocks = Stocks {market: shared,picks: HashMap::new(),+ adding: HashMap::new(),};// Two panels: one on B, one on C.for (view, symbol) in [(1, 1), (2, 2)] {diff --git a/thinkterm-plugin-channel/src/wire.rs b/thinkterm-plugin-channel/src/wire.rsindex a6281b97..3404c216 100644--- a/thinkterm-plugin-channel/src/wire.rs+++ b/thinkterm-plugin-channel/src/wire.rs@@ -12,8 +12,8 @@ use std::io::{self, Read, Write};/// one that finds a newer host leaves it alone. 2 added the host's own API/// (`registry`) and installed plugins; 3 took commands and notifications/// out of it; 4 added plugins' panels; 5 what a panel's plugin asks of-/// another machine, and how long plugins run unused; 6 plugins that wait-/// for the user to let them run.+/// another machine, and how long plugins run unused; 6 what is typed and+/// pressed in a panel, and plugins that wait for the user to let them run.pub const PROTOCOL: u32 = 6;/// The largest frame either side sends or accepts, so a confused peerdiff --git a/thinkterm-plugin-panel/src/lib.rs b/thinkterm-plugin-panel/src/lib.rsindex 2aecded9..81e9bc66 100644--- a/thinkterm-plugin-panel/src/lib.rs+++ b/thinkterm-plugin-panel/src/lib.rs@@ -11,7 +11,10 @@//! it at once; a click is sent to the plugin, which answers with a new//! frame when it is ready. A long list is drawn a page of rows at a time,//! as the player asks for them, so a plugin with ten thousand rows sends-//! the few dozen that show.+//! the few dozen that show. Text is typed in a [`Field`], which the client+//! draws and edits itself, and the plugin is sent what it holds. A panel+//! has the keyboard only when the user gives it ([`Keyboard`]): then it is+//! sent the keys it takes, and nothing else.//!//! A panel whose frame asks for it (`Frame::extend`) gets an extended view//! as well: a wide area beside the sidebar, which the client opens as a@@ -44,12 +47,18 @@ pub const ICONS: [&str; 12] = ["list-todo",];-pub use player::{Draw, Drawn, Op, Painting, Player};+/// The Lucide icons a field can have at its start ([`Field::icon`]);+/// every client has these, and shows none for another.+///+/// [`Field::icon`]: scene::Field::icon+pub const FIELD_ICONS: [&str; 3] = ["search", "plus", "pencil"];++pub use player::{Draw, Drawn, FieldIcon, FieldPart, Keyboard, Op, Painting, Player};pub use scene::{- Align, Area, Bounds, Color, Cursor, Font, Frame, Hit, Item, Jump, Line, List, Rect, Scroll,- Size, Text, Token,+ Align, Area, Bounds, Color, Cursor, Field, FieldKind, FieldText, Font, Frame, Hit, Item, Jump,+ Line, List, Rect, Scroll, Size, Text, Token,};pub use wire::{- Answer, Ask, Button, Bytes, Click, CloseButton, Entry, EntryKind, Env, Input, Mods,- MonoMetrics, Remote, Rows, RowsWanted, TextMetrics,+ feature, Answer, Ask, Button, Bytes, Click, CloseButton, Entry, EntryKind, Env, Focus, Input,+ Key, Mods, MonoMetrics, Remote, Rows, RowsWanted, TextMetrics, Typed,};diff --git a/thinkterm-plugin-panel/src/player.rs b/thinkterm-plugin-panel/src/player.rsindex c958365b..225e2d25 100644--- a/thinkterm-plugin-panel/src/player.rs+++ b/thinkterm-plugin-panel/src/player.rs@@ -6,15 +6,26 @@//!//! A client paints what [`Player::draw`] gives it with its own renderer,//! and hands the pointer and the wheel in. What is to go to the plugin-//! comes back from [`Player::click`] and [`Player::wanted`].+//! comes back from [`Player::click`] and [`Player::wanted`], and from+//! [`Player::told`] for the keyboard.+//!+//! The keyboard is the terminal's until the user gives it to a panel: by+//! pressing in one of its fields, or with a key of their own that asks for+//! the panel ([`Player::focus_panel`]). A press anywhere else in the panel+//! leaves it where it is. While the panel has it, the keys the panel takes+//! go to its plugin and the rest go nowhere -- never to the terminal --+//! but for the app's own, with Ctrl, Alt or Command. Escape gives it back;+//! so does the panel going, and the client says so ([`Player::blur`]) when+//! the user puts it elsewhere. The plugin can move it between its own+//! fields, and give it back, but never take it.use crate::scene::{- Align, Area, Bounds, Color, Cursor, Font, Frame, Hit, Item, Line, List, Rect, Scroll, Size,- Text,+ Align, Area, Bounds, Color, Cursor, Field, FieldKind, Font, Frame, Hit, Item, Line, List, Rect,+ Scroll, Size, Text,};-use crate::wire::{Button, Click, Env, Input, Mods, Rows, RowsWanted};+use crate::wire::{Button, Click, Env, Focus, Input, Key, Mods, Rows, RowsWanted, Typed};use serde::Serialize;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet};/// Items a frame may hold, its scroll areas' included, and a page of rows;/// the rest are dropped. Far more than a panel shows.@@ -26,6 +37,23 @@ pub const ROW_LIMIT: usize = 2_048;pub const TEXT_LIMIT: usize = 2_000;/// The most numbers a line or an area is drawn through.pub const POINT_LIMIT: usize = 8_192;+/// The most characters a field holds.+pub const FIELD_LIMIT: usize = 16_384;+/// How far a field's text is kept from its box's sides, and -- in one of+/// lines -- from its top and bottom.+pub const FIELD_INSET: f32 = 10.0;+pub const FIELD_INSET_LINES: f32 = 5.0;+/// How wide a field's icon is, and the room between it and the text.+pub const FIELD_ICON: f32 = 14.0;+pub const FIELD_ICON_GAP: f32 = 6.0;+/// A field of lines' corners; one on one line is rounded at its ends.+pub const FIELD_RADIUS: f32 = 6.0;+/// The most keys a frame says its panel takes, and the longest name.+const KEY_LIMIT: usize = 64;+const KEY_NAME_LIMIT: usize = 32;+/// The most pieces of a field's box a painting says are covered: past+/// them, the client's own field takes the rest.+const COVERED_LIMIT: usize = 32;/// Pages of rows one list may be waiting for at once.const ASKING_LIMIT: usize = 3;/// Rows are asked for a screenful at a time, and never fewer than this.@@ -58,6 +86,31 @@ pub enum Drawn<'a> {/// The thumb of a scroll area or a list taller than it shows, in the/// panel's units already.Thumb(Bounds),+ /// A field, which the client draws itself, in two parts.+ Field(&'a Field, FieldPart),+}++/// What of a field a draw is.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FieldPart {+ /// Its box, with its icon: outlined in the accent while it has the+ /// keyboard, and as the sidebar's search is while the pointer is over+ /// it.+ Box { focused: bool, hovered: bool },+ /// What it holds -- its placeholder while that is empty -- the caret+ /// and what is selected, cut to inside the box ([`FIELD_INSET`]).+ Text,+}++/// Where the keyboard is, as far as one view knows.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Keyboard {+ /// Not with this view: with the terminal, or another part of ThinkTerm.+ Away,+ /// With this view, in none of its fields: the keys it takes go to it.+ Panel,+ /// In its field with this id.+ Field(String),}/// What [`Player::draw`] gives, as plain data in the panel's units: for a@@ -71,6 +124,8 @@ pub struct Painting {pub ops: Vec<Op>,/// Over what the pointer is, the cursor to show; none over the rest.pub cursor: Option<Cursor>,+ /// The panel has the keyboard, in none of its fields.+ pub focused: bool,}/// One thing to paint, in the panel's units, moved into place already.@@ -124,6 +179,48 @@ pub enum Op {w: f32,h: f32,},+ /// A field's box, for the client to put a field of its own over:+ /// `text` is what it holds as the player has it, to be taken whenever+ /// `revision` moves -- the plugin put text there -- and `limit` the+ /// most characters it takes. `inside` is where its text goes, as x, y,+ /// w, h -- after `icon`, if it shows one. `covered` is where what is+ /// drawn after it and answers a press -- a hit, a scroll area, a list --+ /// lies over it, as x, y, w, h: the client's own field leaves those to+ /// the painting, which shows there and is pressed there.+ Field {+ clip: usize,+ x: f32,+ y: f32,+ w: f32,+ h: f32,+ id: String,+ kind: FieldKind,+ placeholder: String,+ font: Font,+ limit: usize,+ focused: bool,+ text: String,+ revision: u32,+ inside: [f32; 4],+ #[serde(skip_serializing_if = "Option::is_none")]+ icon: Option<FieldIcon>,+ /// Where its button that empties it goes, which the client shows+ /// while it holds something.+ #[serde(skip_serializing_if = "Option::is_none")]+ clear: Option<FieldIcon>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ covered: Vec<[f32; 4]>,+ },+}++/// The icon a field shows, by name, and its square: `size` across, from+/// `x`, `y`, in the panel's units.+#[derive(Debug, Clone, PartialEq, Serialize)]+pub struct FieldIcon {+ pub name: String,+ pub x: f32,+ pub y: f32,+ pub size: f32,}/// Where a hit is: which item, and inside what.@@ -165,6 +262,21 @@ struct Kept {items: Vec<Item>,}+/// What a field holds, as the client edits it, and what it was given.+struct FieldState {+ /// The `seq` the plugin's text was last taken for; none once the+ /// plugin started again, whose next frame's text is taken whatever it+ /// says.+ seq: Option<u32>,+ text: String,+ /// Changes when the text was put there rather than typed: the plugin's+ /// taken, or what was typed cut to fit. A client that edits a copy of+ /// its own takes it again then.+ revision: u32,+ /// The last `focus` seen.+ focus: Option<u32>,+}+pub struct Player {env: Env,frame: Frame,@@ -178,8 +290,26 @@ pub struct Player {layout: u32,lists: HashMap<String, ListState>,scrolls: HashMap<String, ScrollState>,+ /// The fields of the frame, by id.+ fields: HashMap<String, FieldState>,+ /// Counts what a field's revision is set to, so that one gone and come+ /// back under its id is never taken for what it was.+ field_revisions: u32,+ keyboard: Keyboard,+ /// The last `release` the frames said.+ release: Option<u32>,+ /// The plugin's program has not drawn since it started: the `release`+ /// of its first frame asks nothing.+ fresh: bool,+ /// The keyboard was given before the panel was drawn: the first field+ /// of its first frame gets it.+ first_field: bool,+ /// What the player decided to tell the plugin, in order.+ told: Vec<Input>,pointer: Option<(f32, f32)>,hover: Option<Spot>,+ /// The field the pointer is over, where nothing over it answers a press.+ hover_field: Option<String>,wanted: Vec<RowsWanted>,}@@ -194,8 +324,16 @@ impl Player {layout: 0,lists: HashMap::new(),scrolls: HashMap::new(),+ fields: HashMap::new(),+ field_revisions: 0,+ keyboard: Keyboard::Away,+ release: None,+ fresh: true,+ first_field: false,+ told: Vec::new(),pointer: None,hover: None,+ hover_field: None,wanted: Vec::new(),}}@@ -244,6 +382,52 @@ impl Player {pub fn frame(&mut self, mut frame: Frame) {let mut budget = ITEM_LIMIT;keep(&mut frame.items, &mut budget, false);+ let mut ids = HashSet::new();+ frame.items.retain(|item| match item {+ Item::Field(field) => ids.insert(field.id.clone()),+ _ => true,+ });+ frame+ .keys+ .retain(|key| !key.is_empty() && key.chars().count() <= KEY_NAME_LIMIT);+ frame.keys.truncate(KEY_LIMIT);+ let mut fields = HashMap::new();+ for item in &frame.items {+ let Item::Field(field) = item else {+ continue;+ };+ let state = match self.fields.remove(&field.id) {+ Some(mut state) => {+ if state.seq != Some(field.seq) {+ state.seq = Some(field.seq);+ state.text = fit_field(field, &field.value);+ self.field_revisions += 1;+ state.revision = self.field_revisions;+ } else {+ // It may hold less than it did: on one line now, or+ // fewer characters.+ let fitted = fit_field(field, &state.text);+ if fitted != state.text {+ state.text = fitted;+ self.field_revisions += 1;+ state.revision = self.field_revisions;+ }+ }+ state+ }+ None => {+ self.field_revisions += 1;+ FieldState {+ seq: Some(field.seq),+ text: fit_field(field, &field.value),+ revision: self.field_revisions,+ focus: None,+ }+ }+ };+ fields.insert(field.id.clone(), state);+ }+ self.fields = fields;let mut lists = HashMap::new();let mut scrolls = HashMap::new();for item in &frame.items {@@ -268,7 +452,10 @@ impl Player {seq: None,});if let Some(jump) = scroll.top.filter(|jump| state.seq != Some(jump.seq)) {- state.offset = jump.to;+ state.offset = match jump.through {+ Some(through) => reveal(state.offset, jump.to, through, scroll.h),+ None => jump.to,+ };state.seq = Some(jump.seq);}scrolls.insert(scroll.id.clone(), state);@@ -278,11 +465,283 @@ impl Player {}self.lists = lists;self.scrolls = scrolls;+ let first = std::mem::take(&mut self.fresh);self.frame = frame;self.shown = true;+ self.follow_keyboard(first);self.settle();}+ /// Moves the keyboard as the new frame says: out of a field that went,+ /// back to the terminal for a new `release`, and to a field for a new+ /// `focus` -- or to the first field, given to the panel before it was+ /// drawn -- but only while the panel has it. The `release` of the+ /// program's first frame is only taken note of: one at the opening, or+ /// after a restart, asks nothing.+ fn follow_keyboard(&mut self, first: bool) {+ // Asked of a panel that had the keyboard as the frame came: the+ // field it was in may be the one the frame put another in place of.+ let had = self.keyboard != Keyboard::Away;+ let gone = matches!(&self.keyboard, Keyboard::Field(id) if !self.fields.contains_key(id));+ let mut released = false;+ if let Some(seq) = self.frame.release {+ if self.release != Some(seq) {+ self.release = Some(seq);+ released = !first;+ }+ }+ // The last one asked for wins.+ let mut asked = None;+ for item in &self.frame.items {+ let Item::Field(field) = item else {+ continue;+ };+ let Some(seq) = field.focus else {+ continue;+ };+ if let Some(state) = self.fields.get_mut(&field.id) {+ if state.focus != Some(seq) {+ state.focus = Some(seq);+ asked = Some(field.id.clone());+ }+ }+ }+ let first_field = std::mem::take(&mut self.first_field);+ if !had {+ return;+ }+ match asked {+ _ if released => self.set_keyboard(Keyboard::Away),+ Some(id) => self.set_keyboard(Keyboard::Field(id)),+ None if gone => self.set_keyboard(Keyboard::Away),+ None if first_field && self.keyboard == Keyboard::Panel => {+ if let Some(id) = self.first_field_id() {+ self.set_keyboard(Keyboard::Field(id));+ }+ }+ None => {}+ }+ }++ /// Puts the keyboard at `keyboard`, telling the plugin where it went.+ fn set_keyboard(&mut self, keyboard: Keyboard) {+ if self.keyboard == keyboard {+ return;+ }+ self.told.push(match &keyboard {+ Keyboard::Away => Input::Blur,+ Keyboard::Panel => Input::Focus(Focus { id: None }),+ Keyboard::Field(id) => Input::Focus(Focus {+ id: Some(id.clone()),+ }),+ });+ self.keyboard = keyboard;+ self.revision += 1;+ }++ fn first_field_id(&self) -> Option<String> {+ self.fields().next().map(|field| field.id.clone())+ }++ /// Where the keyboard is, as this view knows it.+ pub fn keyboard(&self) -> &Keyboard {+ &self.keyboard+ }++ pub fn has_keyboard(&self) -> bool {+ self.keyboard != Keyboard::Away+ }++ /// The field the keyboard is in, if it is in one.+ pub fn focused_field(&self) -> Option<&str> {+ match &self.keyboard {+ Keyboard::Field(id) => Some(id),+ Keyboard::Away | Keyboard::Panel => None,+ }+ }++ /// The user asked for the panel -- with a key of their own: it has the+ /// keyboard, in its first field if it has one. One not drawn yet puts+ /// it there once its first frame comes, and swallows the keys pressed+ /// meanwhile.+ pub fn focus_panel(&mut self) {+ match self.first_field_id() {+ Some(id) => self.set_keyboard(Keyboard::Field(id)),+ None => {+ self.first_field = !self.shown;+ self.set_keyboard(Keyboard::Panel);+ }+ }+ }++ /// The user pressed in field `id`: it has the keyboard. False when the+ /// frame has no such field.+ pub fn focus_field(&mut self, id: &str) -> bool {+ if !self.fields.contains_key(id) {+ return false;+ }+ self.set_keyboard(Keyboard::Field(id.to_string()));+ true+ }++ /// The keyboard went elsewhere: the user put it there, or the panel is+ /// going.+ pub fn blur(&mut self) {+ self.set_keyboard(Keyboard::Away);+ }++ /// A key pressed while the panel has the keyboard, which the field with+ /// it -- if one has it -- did not use, named as a browser names it:+ /// Escape gives the keyboard back, Tab -- Shift-Tab back -- moves it to+ /// the next field, and a key the frame says the panel takes is sent.+ /// True when the panel took it. False for any other -- one with Ctrl,+ /// Alt or Command, one the panel does not take, any while the keyboard+ /// is elsewhere -- which the client lets the app have, and never the+ /// terminal.+ pub fn key(&mut self, key: &str, mods: Mods) -> bool {+ if self.keyboard == Keyboard::Away || mods.ctrl || mods.alt || mods.cmd {+ return false;+ }+ match key {+ "Escape" => self.set_keyboard(Keyboard::Away),+ "Tab" => self.step_field(mods.shift),+ _ if self.frame.keys.iter().any(|taken| taken == key) => {+ let mods = Mods {+ shift: mods.shift,+ ..Mods::default()+ };+ self.told.push(Input::Key(Key {+ key: key.to_string(),+ mods,+ }));+ }+ _ => return false,+ }+ true+ }++ /// Moves the keyboard to the next field in the frame's order, or the+ /// one before, going round; from none, to the first or the last.+ fn step_field(&mut self, back: bool) {+ let ids: Vec<&str> = self.fields().map(|field| field.id.as_str()).collect();+ if ids.is_empty() {+ return;+ }+ let count = ids.len();+ let at = self+ .focused_field()+ .and_then(|focused| ids.iter().position(|id| *id == focused));+ let next = match (at, back) {+ (Some(at), false) => (at + 1) % count,+ (Some(at), true) => (at + count - 1) % count,+ (None, false) => 0,+ (None, true) => count - 1,+ };+ let id = ids[next].to_string();+ self.set_keyboard(Keyboard::Field(id));+ }++ /// The fields of the last frame, in its order.+ pub fn fields(&self) -> impl Iterator<Item = &Field> {+ self.frame.items.iter().filter_map(|item| match item {+ Item::Field(field) => Some(field),+ _ => None,+ })+ }++ /// The field `id` of the last frame.+ pub fn field(&self, id: &str) -> Option<&Field> {+ self.fields().find(|field| field.id == id)+ }++ /// The field at `x`, `y`, unless what else answers a press -- a hit, a+ /// scroll area, a list -- is drawn over it there: a button laid on a+ /// field's end is the button's.+ pub fn field_at(&self, x: f32, y: f32) -> Option<&Field> {+ if !self.panel().contains(x, y) {+ return None;+ }+ let top = self.frame.items.iter().rev().find(|item| {+ matches!(+ item,+ Item::Field(_) | Item::Hit(_) | Item::Scroll(_) | Item::List(_)+ ) && item.bounds().contains(x, y)+ });+ match top {+ Some(Item::Field(field)) => Some(field),+ _ => None,+ }+ }++ /// What field `id` holds, as the player has it, and its revision: a+ /// client that edits a copy of its own takes the text again whenever+ /// that moves.+ pub fn field_text(&self, id: &str) -> Option<(&str, u32)> {+ let state = self.fields.get(id)?;+ Some((&state.text, state.revision))+ }++ /// What the field with the keyboard, `id`, holds now the user edited+ /// it: kept to what it takes -- the text taken again, cut to fit, when+ /// that is less -- and sent to the plugin, unless the field is secret.+ /// An edit of any other is not the user's, and is let be.+ pub fn edit_field(&mut self, id: &str, text: &str) {+ if self.focused_field() != Some(id) {+ return;+ }+ let Some(field) = self.field(id) else {+ return;+ };+ let secret = field.kind == FieldKind::Secret;+ let fitted = fit_field(field, text);+ let drawn = field.seq;+ let Some(state) = self.fields.get_mut(id) else {+ return;+ };+ if fitted != text {+ // Cut to fit: the client takes it again, even when that is+ // what the field held already.+ self.field_revisions += 1;+ state.revision = self.field_revisions;+ self.revision += 1;+ }+ if fitted == state.text {+ return;+ }+ state.text = fitted;+ self.revision += 1;+ if !secret {+ self.told.push(Input::Text(Typed {+ id: id.to_string(),+ text: state.text.clone(),+ seq: state.seq.unwrap_or(drawn),+ }));+ }+ }++ /// The user submitted the field with the keyboard, `id`: what it holds+ /// goes to the plugin.+ pub fn submit(&mut self, id: &str) {+ if self.focused_field() != Some(id) {+ return;+ }+ let drawn = self.field(id).map_or(0, |field| field.seq);+ if let Some(state) = self.fields.get(id) {+ self.told.push(Input::Submit(Typed {+ id: id.to_string(),+ text: state.text.clone(),+ seq: state.seq.unwrap_or(drawn),+ }));+ }+ }++ /// What the player decided to tell the plugin -- where the keyboard+ /// went, what a field holds, a key -- in order: taken after every+ /// change a client makes, and after every frame.+ pub fn told(&mut self) -> Vec<Input> {+ std::mem::take(&mut self.told)+ }+/// Rows the plugin sent for a list: taken when they answer a page it/// waits for, drawn for the list and the panel as they are now. Rows/// it was asked for and left out are kept empty, so they are not asked@@ -336,13 +795,26 @@ impl Player {/// The plugin's program was started again: what the last one was asked/// will not be answered, and is asked again, and so are the rows on- /// show, which stay until the new ones come.+ /// show, which stay until the new ones come. The keyboard goes back to+ /// the terminal; the new program never had it, and is not told. Its+ /// fields take what its first frame puts in them -- it never heard what+ /// was typed for the last one -- and its `focus` and `release` count+ /// afresh.pub fn restarted(&mut self) {self.layout = self.layout.wrapping_add(1);for state in self.lists.values_mut() {state.asking.clear();}+ for state in self.fields.values_mut() {+ state.seq = None;+ state.focus = None;+ }+ self.release = None;+ self.fresh = true;self.wanted.clear();+ self.keyboard = Keyboard::Away;+ self.first_field = false;+ self.told.clear();self.settle();}@@ -358,9 +830,14 @@ impl Player {self.rehover()}- /// The cursor over what the pointer is on; `None` where nothing- /// answers a click.+ /// The cursor over what the pointer is on -- the I-beam over a field;+ /// `None` where nothing answers a click.pub fn cursor(&self) -> Option<Cursor> {+ if let Some((x, y)) = self.pointer {+ if self.field_at(x, y).is_some() {+ return Some(Cursor::Text);+ }+ }let (hit, ..) = self.hit(self.hover?)?;Some(hit.cursor)}@@ -412,7 +889,8 @@ impl Player {}/// A press at `x`, `y`: the plugin is to hear of it when it landed on a- /// hit.+ /// hit. One on a field is the field's, not a click+ /// ([`focus_field`](Self::focus_field)).pub fn click(&mut self,x: f32,@@ -423,6 +901,9 @@ impl Player {) -> Option<Input> {self.pointer = Some((x, y));self.rehover();+ if self.field_at(x, y).is_some() {+ return None;+ }let (hit, dx, dy) = self.hit(self.spot_at(x, y)?)?;Some(Input::Click(Click {id: hit.id.clone(),@@ -486,6 +967,28 @@ impl Player {push_thumb(&mut out, thumb, panel);}}+ Item::Field(field) => {+ if !item.bounds().touches(&panel) {+ continue;+ }+ let focused = self.focused_field() == Some(field.id.as_str());+ let hovered = self.hover_field.as_deref() == Some(field.id.as_str());+ out.push(Draw {+ what: Drawn::Field(field, FieldPart::Box { focused, hovered }),+ dx: 0.0,+ dy: 0.0,+ clip: panel,+ });+ let inside = field_inside(field).intersect(&panel);+ if !inside.is_empty() {+ out.push(Draw {+ what: Drawn::Field(field, FieldPart::Text),+ dx: 0.0,+ dy: 0.0,+ clip: inside,+ });+ }+ }_ => self.push(&mut out, item, Spot::Top(index), 0.0, 0.0, panel),}}@@ -497,6 +1000,11 @@ impl Player {let mut clips: Vec<[f32; 4]> = Vec::new();let mut ops = Vec::new();for draw in self.draw() {+ // A client that puts a field of its own over the box draws+ // what it holds itself.+ if let Drawn::Field(_, FieldPart::Text) = draw.what {+ continue;+ }let clip = [draw.clip.left,draw.clip.top,@@ -569,13 +1077,90 @@ impl Player {w: thumb.width(),h: thumb.height(),},+ Drawn::Field(field, part) => {+ let (text, revision) = self.field_text(&field.id).unwrap_or_default();+ Op::Field {+ clip,+ x: field.x + dx,+ y: field.y + dy,+ w: field.w,+ h: field.h,+ id: field.id.clone(),+ kind: field.kind,+ placeholder: field.placeholder.clone(),+ font: field.font,+ limit: field_limit(field),+ focused: matches!(part, FieldPart::Box { focused: true, .. }),+ text: text.to_string(),+ revision,+ inside: {+ let inside = field_inside(field);+ [+ inside.left + dx,+ inside.top + dy,+ inside.width(),+ inside.height(),+ ]+ },+ icon: field_icon(field).map(|name| FieldIcon {+ name: name.to_string(),+ x: field.x + FIELD_INSET + dx,+ y: field.y + (field.h - FIELD_ICON) / 2.0 + dy,+ size: FIELD_ICON,+ }),+ clear: field_clear_at(field).map(|(x, y, size)| FieldIcon {+ name: "x".to_string(),+ x: x + dx,+ y: y + dy,+ size,+ }),+ covered: self.covering(field),+ }+ }});}Painting {clips,ops,cursor: self.cursor(),+ focused: self.keyboard == Keyboard::Panel,+ }+ }++ /// Where what is drawn after field `field` and answers a press lies+ /// over it, in the panel -- there a press is not the field's+ /// ([`field_at`](Self::field_at)) -- in pieces that do not overlap.+ fn covering(&self, field: &Field) -> Vec<[f32; 4]> {+ let items = &self.frame.items;+ let Some(at) = items+ .iter()+ .position(|item| matches!(item, Item::Field(own) if own.id == field.id))+ else {+ return Vec::new();+ };+ let own = items[at].bounds().intersect(&self.panel());+ let mut covered: Vec<Bounds> = Vec::new();+ let over = items[at + 1..]+ .iter()+ .filter(|item| matches!(item, Item::Hit(_) | Item::Scroll(_) | Item::List(_)));+ for item in over {+ let mut pieces = vec![item.bounds().intersect(&own)];+ for done in &covered {+ pieces = pieces+ .into_iter()+ .flat_map(|piece| without(piece, done))+ .collect();+ }+ covered.extend(pieces.into_iter().filter(|piece| !piece.is_empty()));+ if covered.len() >= COVERED_LIMIT {+ covered.truncate(COVERED_LIMIT);+ break;+ }}+ covered+ .into_iter()+ .map(|piece| [piece.left, piece.top, piece.width(), piece.height()])+ .collect()}/// Rows a list keeps now, for looking at what the player holds.@@ -601,7 +1186,8 @@ impl Player {Item::Line(line) => Drawn::Line(line),Item::Area(area) => Drawn::Area(area),Item::Hit(hit) if hit.hover.is_some() && self.hover == Some(spot) => Drawn::Hover(hit),- Item::Hit(_) | Item::Scroll(_) | Item::List(_) => return,+ // A field is drawn where it is in the frame, by `draw`.+ Item::Hit(_) | Item::Scroll(_) | Item::List(_) | Item::Field(_) => return,};out.push(Draw { what, dx, dy, clip });}@@ -637,11 +1223,16 @@ impl Player {fn rehover(&mut self) -> bool {let hover = self.pointer.and_then(|(x, y)| self.spot_at(x, y));- let changed = hover != self.hover;+ let hover_field = self+ .pointer+ .and_then(|(x, y)| self.field_at(x, y))+ .map(|field| field.id.clone());+ let changed = hover != self.hover || hover_field != self.hover_field;if changed {self.revision += 1;}self.hover = hover;+ self.hover_field = hover_field;changed}@@ -747,7 +1338,12 @@ impl ListState {}self.count = list.count;if let Some(jump) = list.top.filter(|jump| self.seq != Some(jump.seq)) {- self.offset = jump.to * list.row;+ self.offset = match jump.through {+ Some(through) => {+ reveal(self.offset, jump.to * list.row, through * list.row, list.h)+ }+ None => jump.to * list.row,+ };self.seq = Some(jump.seq);}}@@ -912,7 +1508,7 @@ fn keep(items: &mut Vec<Item>, budget: &mut usize, nested: bool) {return false;}match item {- Item::Scroll(_) | Item::List(_) if nested => return false,+ Item::Scroll(_) | Item::List(_) | Item::Field(_) if nested => return false,Item::Scroll(scroll) => {*budget -= 1;keep(&mut scroll.items, budget, true);@@ -923,6 +1519,14 @@ fn keep(items: &mut Vec<Item>, budget: &mut usize, nested: bool) {text.text.truncate(cut);}}+ Item::Field(field) => {+ if let Some((cut, _)) = field.value.char_indices().nth(FIELD_LIMIT) {+ field.value.truncate(cut);+ }+ if let Some((cut, _)) = field.placeholder.char_indices().nth(TEXT_LIMIT) {+ field.placeholder.truncate(cut);+ }+ }Item::Line(Line { points, .. }) | Item::Area(Area { points, .. }) => {points.truncate(POINT_LIMIT);if points.len() % 2 == 1 {@@ -954,7 +1558,120 @@ fn drawable(item: &Item) -> bool {&& list.row >= 1.0&& list.top.is_none_or(|jump| jump.to.is_finite())}+ Item::Field(field) => finite(&[field.x, field.y, field.w, field.h]),+ }+}++/// What of `piece` lies outside `cut`: up to four pieces, none of them+/// overlapping.+fn without(piece: Bounds, cut: &Bounds) -> Vec<Bounds> {+ let inside = piece.intersect(cut);+ if inside.is_empty() {+ return vec![piece];}+ let band = |top: f32, bottom: f32, left: f32, right: f32| Bounds {+ left,+ top,+ right,+ bottom,+ };+ [+ band(piece.top, inside.top, piece.left, piece.right),+ band(inside.bottom, piece.bottom, piece.left, piece.right),+ band(inside.top, inside.bottom, piece.left, inside.left),+ band(inside.top, inside.bottom, inside.right, piece.right),+ ]+ .into_iter()+ .filter(|part| !part.is_empty())+ .collect()+}++/// The most characters `field` holds.+pub fn field_limit(field: &Field) -> usize {+ match field.max {+ 0 => FIELD_LIMIT,+ max => (max as usize).min(FIELD_LIMIT),+ }+}++/// What `field` holds of `text`: no more characters than it takes, and no+/// control characters but -- in one of lines -- line ends and tabs.+fn fit_field(field: &Field, text: &str) -> String {+ let lines = field.kind == FieldKind::Lines;+ text.chars()+ .filter(|ch| !ch.is_control() || (lines && (*ch == '\n' || *ch == '\t')))+ .take(field_limit(field))+ .collect()+}++/// Where in `field`'s box its text goes: after its icon, if it shows one.+pub fn field_inside(field: &Field) -> Bounds {+ let down = match field.kind {+ FieldKind::Lines => FIELD_INSET_LINES,+ FieldKind::Line | FieldKind::Secret => 0.0,+ };+ let lead = match field_icon(field) {+ Some(_) => FIELD_ICON + FIELD_ICON_GAP,+ None => 0.0,+ };+ let trail = match field_clear(field) {+ true => FIELD_ICON + FIELD_ICON_GAP,+ false => 0.0,+ };+ Bounds::new(+ field.x + FIELD_INSET + lead,+ field.y + down,+ field.w - FIELD_INSET * 2.0 - lead - trail,+ field.h - down * 2.0,+ )+}++/// Whether `field` has a button at its end that empties it: one on one+/// line that asks for it.+pub fn field_clear(field: &Field) -> bool {+ field.clear && field.kind != FieldKind::Lines+}++/// Where `field`'s button that empties it is, and its icon's: `size`+/// across from `x`, `y`, in its units.+pub fn field_clear_at(field: &Field) -> Option<(f32, f32, f32)> {+ field_clear(field).then(|| {+ (+ field.x + field.w - FIELD_INSET - FIELD_ICON,+ field.y + (field.h - FIELD_ICON) / 2.0,+ FIELD_ICON,+ )+ })+}++/// The offset of a region `room` tall that shows `from` to `to`, moved+/// from `offset` as little as it takes.+fn reveal(offset: f32, from: f32, to: f32, room: f32) -> f32 {+ if from < offset {+ from+ } else if to > offset + room {+ // Its start, at least, when it is taller than the room.+ (to - room).min(from)+ } else {+ offset+ }+}++/// The icon `field` shows: the one it names, if every client has it, on+/// one line.+pub fn field_icon(field: &Field) -> Option<&str> {+ let icon = field.icon.as_deref()?;+ (field.kind != FieldKind::Lines && crate::FIELD_ICONS.contains(&icon)).then_some(icon)+}++/// How round `field`'s corners are: wholly at the ends of one on one line,+/// as the sidebar's search is.+pub fn field_radius(field: &Field) -> f32 {+ match field.kind {+ FieldKind::Lines => FIELD_RADIUS.min(field.h / 2.0),+ FieldKind::Line | FieldKind::Secret => field.h / 2.0,+ }+ .max(0.0)}#[cfg(test)]@@ -962,6 +1679,7 @@ mod tests {use super::*;use crate::scene::{Color, Jump, Token};use crate::wire::{MonoMetrics, TextMetrics};+ use serde_json::json;fn env(width: f32, height: f32) -> Env {let text = TextMetrics {@@ -986,6 +1704,7 @@ mod tests {remote: None,can_extend: false,close: None,+ features: Vec::new(),}}@@ -1172,7 +1891,11 @@ mod tests {});assert!(texts(&player).is_empty());- let jump = Some(Jump { to: 500.0, seq: 1 });+ let jump = Some(Jump {+ to: 500.0,+ seq: 1,+ through: None,+ });player.frame(Frame {items: vec![list(1_000, "b", jump)],..Frame::default()@@ -1573,7 +2296,11 @@ mod tests {.filter(|draw| !matches!(draw.what, Drawn::Thumb(_))).all(|draw| draw.clip == Bounds::new(0.0, 50.0, 300.0, 100.0)));player.frame(Frame {- items: vec![Item::Scroll(scroll(Some(Jump { to: 0.0, seq: 7 })))],+ items: vec![Item::Scroll(scroll(Some(Jump {+ to: 0.0,+ seq: 7,+ through: None,+ })))],..Frame::default()});assert!(@@ -1723,9 +2450,511 @@ mod tests {player.frame(Frame {items: Vec::new(),extend: true,+ ..Frame::default()});assert!(player.extend());player.frame(Frame::default());assert!(!player.extend(), "a frame that does not ask lets it go");}++ fn fields(fields: Vec<Field>) -> Frame {+ Frame {+ items: fields.into_iter().map(Item::Field).collect(),+ ..Frame::default()+ }+ }++ fn field(id: &str, y: f32) -> Field {+ Field::new(id, 10.0, y, 200.0, 26.0)+ }++ fn focus(id: &str) -> Input {+ Input::Focus(Focus {+ id: Some(id.into()),+ })+ }++ #[test]+ fn only_the_user_gives_a_panel_the_keyboard_and_a_press_elsewhere_keeps_it_where_it_is() {+ let mut player = Player::new(env(300.0, 400.0));+ let mut frame = fields(vec![field("add", 10.0).focus(1)]);+ frame.items.push(hit("row", 0.0, 100.0, 300.0, 20.0));+ player.frame(frame);+ assert_eq!(player.keyboard(), &Keyboard::Away, "asked for, not given");+ assert!(player.told().is_empty());+ assert!(!player.key("ArrowDown", Mods::default()), "the terminal's");++ // A press on a hit is a click, and does not move the keyboard.+ assert!(player+ .click(5.0, 105.0, Button::Left, 1, Mods::default())+ .is_some());+ assert_eq!(player.keyboard(), &Keyboard::Away);+ // One on the field is not a click: it is the field's.+ assert_eq!(+ player.field_at(50.0, 20.0).map(|f| f.id.as_str()),+ Some("add")+ );+ assert_eq!(+ player.click(50.0, 20.0, Button::Left, 1, Mods::default()),+ None+ );+ assert!(player.focus_field("add"));+ assert_eq!(player.told(), [focus("add")]);+ player.click(5.0, 105.0, Button::Left, 1, Mods::default());+ assert_eq!(player.focused_field(), Some("add"), "still typing there");+ assert!(!player.focus_field("gone"));++ // With the keyboard in the panel, its plugin moves it between its+ // own fields, once for each new seq.+ let two = || fields(vec![field("add", 10.0).focus(1), field("b", 50.0).focus(1)]);+ player.frame(two());+ assert_eq!(player.told(), [focus("b")]);+ player.frame(two());+ assert!(player.told().is_empty(), "the same seq is not taken again");+ player.blur();+ assert_eq!(player.told(), [Input::Blur]);+ player.frame(fields(vec![field("add", 10.0).focus(2), field("b", 50.0)]));+ assert_eq!(+ player.keyboard(),+ &Keyboard::Away,+ "never from the terminal"+ );+ assert!(player.told().is_empty());+ }++ #[test]+ fn what_is_typed_is_sent_kept_to_what_the_field_takes_and_a_new_seq_replaces_it() {+ let mut player = Player::new(env(300.0, 400.0));+ let frame = |seq: u32, value: &str| {+ fields(vec![+ field("add", 10.0).max(3).value(value, seq),+ field("pass", 50.0).secret(),+ field("note", 90.0).lines(),+ ])+ };+ player.frame(frame(0, "x"));+ let (text, first) = player.field_text("add").unwrap();+ assert_eq!(text, "x");+ player.edit_field("add", "nope");+ assert_eq!(player.field_text("add").unwrap().0, "x", "not the user's");++ player.focus_field("add");+ player.told();+ player.edit_field("add", "TSMC");+ let (text, cut) = player.field_text("add").unwrap();+ assert_eq!(text, "TSM");+ assert_ne!(cut, first, "cut to fit: to be taken back");+ assert_eq!(+ player.told(),+ [Input::Text(Typed {+ id: "add".into(),+ text: "TSM".into(),+ seq: 0,+ })]+ );+ // Cut to what it holds already: nothing to tell, but the client+ // takes it back all the same.+ let shown = player.revision();+ player.edit_field("add", "TSMD");+ assert!(player.told().is_empty());+ assert_ne!(player.revision(), shown);+ let cut = player.field_text("add").unwrap().1;+ player.frame(frame(0, ""));+ assert_eq!(+ player.field_text("add").unwrap(),+ ("TSM", cut),+ "typed, kept"+ );+ player.frame(frame(1, ""));+ let (text, taken) = player.field_text("add").unwrap();+ assert_eq!(text, "", "a new seq puts the plugin's there");+ assert_ne!(taken, cut);+ player.edit_field("add", "a\nb");+ assert_eq!(player.field_text("add").unwrap().0, "ab", "one line");+ player.submit("add");+ assert_eq!(+ player.told().last(),+ Some(&Input::Submit(Typed {+ id: "add".into(),+ text: "ab".into(),+ seq: 1,+ })),+ "typed over the text of seq 1"+ );++ player.focus_field("pass");+ player.told();+ player.edit_field("pass", "hunter2");+ assert!(+ player.told().is_empty(),+ "a secret goes only when submitted"+ );+ player.submit("pass");+ assert_eq!(+ player.told(),+ [Input::Submit(Typed {+ id: "pass".into(),+ text: "hunter2".into(),+ seq: 0,+ })]+ );+ player.focus_field("note");+ player.edit_field("note", "a\n\tb\r");+ assert_eq!(player.field_text("note").unwrap().0, "a\n\tb");+ player.submit("add");+ assert!(+ !player+ .told()+ .iter()+ .any(|input| matches!(input, Input::Submit(_))),+ "only the field with the keyboard submits"+ );+ }++ #[test]+ fn keys_go_to_the_panel_only_as_it_takes_them() {+ let mut player = Player::new(env(300.0, 400.0));+ let mut frame = fields(vec![field("a", 10.0), field("b", 50.0)]);+ frame.keys(&["ArrowDown", "j"]);+ player.frame(frame);+ let plain = Mods::default();+ assert!(!player.key("ArrowDown", plain));+ player.focus_panel();+ assert_eq!(player.told(), [focus("a")], "in its first field");+ assert!(player.key("ArrowDown", plain));+ assert_eq!(+ player.told(),+ [Input::Key(Key {+ key: "ArrowDown".into(),+ mods: plain+ })]+ );+ assert!(+ !player.key("x", plain),+ "not the panel's: the client lets the app have it"+ );+ assert!(player.told().is_empty());+ let ctrl = Mods {+ ctrl: true,+ ..Mods::default()+ };+ assert!(!player.key("j", ctrl), "a chord is the app's");+ let shift = Mods {+ shift: true,+ ..Mods::default()+ };+ player.key("Tab", plain);+ assert_eq!(player.focused_field(), Some("b"));+ player.key("Tab", plain);+ assert_eq!(player.focused_field(), Some("a"), "round again");+ player.key("Tab", shift);+ assert_eq!(player.focused_field(), Some("b"));+ player.told();+ assert!(player.key("Escape", plain));+ assert_eq!(player.told(), [Input::Blur]);+ assert_eq!(player.keyboard(), &Keyboard::Away);+ }++ #[test]+ fn a_field_that_goes_takes_the_keyboard_and_a_release_gives_it_back() {+ let mut player = Player::new(env(300.0, 400.0));+ player.frame(fields(vec![field("a", 10.0)]));+ player.focus_field("a");+ player.told();+ player.frame(Frame::default());+ assert_eq!(player.told(), [Input::Blur]);++ player.focus_panel();+ assert_eq!(player.keyboard(), &Keyboard::Panel, "nothing to type in");+ let mut released = Frame::default();+ released.release(1);+ player.frame(released.clone());+ assert_eq!(player.keyboard(), &Keyboard::Away);+ player.focus_panel();+ player.frame(released);+ assert_eq!(player.keyboard(), &Keyboard::Panel, "once for each seq");++ // Asked for before the panel is drawn: its first field gets it,+ // and the release its first frame says asks nothing.+ let mut fresh = Player::new(env(300.0, 400.0));+ fresh.focus_panel();+ assert!(fresh.has_keyboard());+ let mut first = fields(vec![field("q", 10.0)]);+ first.release(0);+ fresh.frame(first);+ assert_eq!(fresh.focused_field(), Some("q"));+ assert_eq!(fresh.told(), [Input::Focus(Focus::default()), focus("q")]);++ // Started again, the plugin never had it.+ fresh.restarted();+ assert_eq!(fresh.keyboard(), &Keyboard::Away);+ assert!(fresh.told().is_empty());+ }++ #[test]+ fn a_field_put_in_place_of_the_one_typed_in_takes_the_keyboard() {+ let mut player = Player::new(env(300.0, 400.0));+ player.frame(fields(vec![field("add", 10.0)]));+ player.focus_field("add");+ player.told();+ player.frame(fields(vec![field("edit", 10.0).focus(1)]));+ assert_eq!(player.focused_field(), Some("edit"));+ assert_eq!(player.told(), [focus("edit")], "no blur between");++ // Gone with none in its place, or let go of in the same frame.+ player.frame(fields(vec![field("other", 10.0)]));+ assert_eq!(player.keyboard(), &Keyboard::Away);+ player.focus_field("other");+ let mut both = fields(vec![field("next", 10.0).focus(2)]);+ both.release(1);+ player.frame(both);+ assert_eq!(player.keyboard(), &Keyboard::Away, "the release wins");+ }++ #[test]+ fn a_jump_through_a_row_scrolls_only_as_far_as_it_takes_to_show_it() {+ let mut player = Player::new(env(300.0, 400.0));+ let to_row = |row: f32, seq: u32| {+ Some(Jump {+ to: row,+ seq,+ through: Some(row + 1.0),+ })+ };+ let mut show = |top: Option<Jump>| {+ player.frame(Frame {+ items: vec![list(1_000, "a", top)],+ ..Frame::default()+ });+ answer(&mut player);+ texts(&player)[0].clone()+ };+ assert_eq!(show(to_row(15.0, 1)), "row 6", "down, to show it last");+ assert_eq!(show(to_row(3.0, 2)), "row 3", "up, to show it first");+ assert_eq!(show(to_row(5.0, 3)), "row 3", "in view already");+ }++ #[test]+ fn a_clear_button_takes_room_at_the_end_of_a_field_on_one_line() {+ let plain = Field::new("q", 10.0, 0.0, 200.0, 30.0);+ let clear = plain.clone().clear();+ assert_eq!(+ field_inside(&clear).width(),+ field_inside(&plain).width() - FIELD_ICON - FIELD_ICON_GAP+ );+ assert_eq!(+ field_clear_at(&clear),+ Some((+ 10.0 + 200.0 - FIELD_INSET - FIELD_ICON,+ (30.0 - FIELD_ICON) / 2.0,+ FIELD_ICON+ ))+ );+ let lines = Field::new("n", 10.0, 0.0, 200.0, 80.0).lines().clear();+ assert!(!field_clear(&lines));+ assert_eq!(field_clear_at(&lines), None);+ }++ #[test]+ fn a_program_started_again_counts_its_focus_and_release_afresh() {+ let mut player = Player::new(env(300.0, 400.0));+ let plain = fields(vec![field("a", 10.0), field("b", 50.0)]);+ let mut to_b = plain.clone();+ if let Item::Field(b) = &mut to_b.items[1] {+ b.focus = Some(1);+ }+ let mut released = plain.clone();+ released.release(1);+ player.frame(plain.clone());+ player.focus_field("a");+ player.frame(to_b.clone());+ assert_eq!(player.focused_field(), Some("b"));+ player.frame(released.clone());+ assert_eq!(player.keyboard(), &Keyboard::Away);++ player.restarted();+ player.frame(plain.clone());+ player.focus_field("a");+ player.frame(to_b);+ assert_eq!(player.focused_field(), Some("b"), "its first ask");+ player.frame(released.clone());+ assert_eq!(player.keyboard(), &Keyboard::Away, "its first release");++ // Pressed in before it drew: the release it opens with asks nothing.+ player.restarted();+ player.focus_field("a");+ player.frame(released);+ assert_eq!(player.focused_field(), Some("a"));+ }++ #[test]+ fn a_hit_over_a_field_answers_and_what_was_typed_goes_with_the_program_that_heard_it() {+ let mut player = Player::new(env(300.0, 400.0));+ let mut frame = fields(vec![field("filter", 10.0)]);+ // A clear button over the field's right end.+ frame.items.push(hit("clear", 180.0, 10.0, 30.0, 26.0));+ player.frame(frame.clone());+ assert_eq!(+ player.field_at(50.0, 20.0).map(|f| f.id.as_str()),+ Some("filter")+ );+ assert!(+ player.field_at(190.0, 20.0).is_none(),+ "the button is over it"+ );+ // A client's own field over the painting leaves it to the button.+ let covered = |player: &Player| {+ player.painting().ops.into_iter().find_map(|op| match op {+ Op::Field { covered, .. } => Some(covered),+ _ => None,+ })+ };+ assert_eq!(covered(&player), Some(vec![[180.0, 10.0, 30.0, 26.0]]));+ // Two over the same end: in pieces that do not overlap.+ let mut twice = frame.clone();+ twice.items.push(hit("again", 160.0, 10.0, 30.0, 26.0));+ player.frame(twice);+ assert_eq!(+ covered(&player),+ Some(vec![[180.0, 10.0, 30.0, 26.0], [160.0, 10.0, 20.0, 26.0]])+ );+ let pressed = player.click(190.0, 20.0, Button::Left, 1, Mods::default());+ assert!(matches!(pressed, Some(Input::Click(Click { ref id, .. })) if id == "clear"));++ player.focus_field("filter");+ player.edit_field("filter", "src");+ // The program started again draws the field as it knows it: its text+ // is taken, though its seq is the one taken before.+ player.restarted();+ assert_eq!(+ player.field_text("filter").unwrap().0,+ "src",+ "until it draws"+ );+ player.frame(frame);+ assert_eq!(player.field_text("filter").unwrap().0, "");+ }++ #[test]+ fn a_field_is_drawn_in_its_place_and_painted_for_a_client_of_its_own() {+ let mut player = Player::new(env(300.0, 400.0));+ let mut frame = fields(vec![+ field("a", 10.0).value("hi", 0).placeholder("Symbol"),+ field("a", 50.0),+ ]);+ frame.items.push(Item::Scroll(Scroll {+ id: "s".into(),+ x: 0.0,+ y: 100.0,+ w: 300.0,+ h: 100.0,+ height: 300.0,+ items: vec![field("inner", 0.0).into()],+ top: None,+ }));+ player.frame(frame);+ assert_eq!(+ player.fields().count(),+ 1,+ "the first of an id, and none scrolled"+ );+ player.focus_field("a");+ let draws = player.draw();+ let parts: Vec<(FieldPart, Bounds)> = draws+ .iter()+ .filter_map(|draw| match draw.what {+ Drawn::Field(_, part) => Some((part, draw.clip)),+ _ => None,+ })+ .collect();+ assert_eq!(parts.len(), 2);+ assert_eq!(+ parts[0].0,+ FieldPart::Box {+ focused: true,+ hovered: false+ }+ );+ assert_eq!(+ parts[1],+ (FieldPart::Text, Bounds::new(20.0, 10.0, 180.0, 26.0))+ );+ assert!(player.pointer_moved(20.0, 20.0), "over the field now");+ assert_eq!(player.cursor(), Some(Cursor::Text));+ let hovered = player.draw().iter().any(|draw| {+ matches!(+ draw.what,+ Drawn::Field(_, FieldPart::Box { hovered: true, .. })+ )+ });+ assert!(hovered);++ let painting = player.painting();+ let fields: Vec<&Op> = painting+ .ops+ .iter()+ .filter(|op| matches!(op, Op::Field { .. }))+ .collect();+ assert_eq!(+ fields.len(),+ 1,+ "the box, which the client puts its own over"+ );+ let Op::Field {+ text,+ focused,+ limit,+ placeholder,+ ..+ } = fields[0]+ else {+ unreachable!()+ };+ assert_eq!(+ (text.as_str(), *focused, *limit, placeholder.as_str()),+ ("hi", true, FIELD_LIMIT, "Symbol")+ );+ let json = serde_json::to_value(fields[0]).unwrap();+ assert_eq!(+ (&json["op"], &json["kind"]),+ (&json!("field"), &json!("line"))+ );+ assert_eq!(json["inside"], json!([20.0, 10.0, 180.0, 26.0]));+ assert!(json.get("icon").is_none());+ }++ #[test]+ fn a_field_on_one_line_is_round_at_its_ends_with_room_for_an_icon_every_client_has() {+ let search = Field::new("q", 10.0, 0.0, 200.0, 30.0).icon("search");+ assert_eq!(field_icon(&search), Some("search"));+ let inside = field_inside(&search);+ let lead = FIELD_INSET + FIELD_ICON + FIELD_ICON_GAP;+ assert_eq!(+ (inside.left, inside.width()),+ (10.0 + lead, 200.0 - lead - FIELD_INSET)+ );+ assert_eq!(field_radius(&search), 15.0);++ // One no client has, or on a field of lines: none, and no room.+ let unknown = Field::new("q", 10.0, 0.0, 200.0, 30.0).icon("rocket");+ assert_eq!(field_icon(&unknown), None);+ assert_eq!(field_inside(&unknown).left, 10.0 + FIELD_INSET);+ let lines = Field::new("note", 10.0, 0.0, 200.0, 80.0)+ .lines()+ .icon("pencil");+ assert_eq!(field_icon(&lines), None);+ assert_eq!(field_radius(&lines), FIELD_RADIUS);++ let mut player = Player::new(env(300.0, 400.0));+ player.frame(fields(vec![field("a", 10.0).icon("plus")]));+ let icon = player.painting().ops.into_iter().find_map(|op| match op {+ Op::Field { icon, .. } => icon,+ _ => None,+ });+ let at = (10.0 + FIELD_INSET, 10.0 + (26.0 - FIELD_ICON) / 2.0);+ assert_eq!(+ icon.map(|icon| (icon.name, icon.x, icon.y, icon.size)),+ Some(("plus".to_string(), at.0, at.1, FIELD_ICON))+ );+ }}diff --git a/thinkterm-plugin-panel/src/scene.rs b/thinkterm-plugin-panel/src/scene.rsindex abc1bb89..6c1abc5e 100644--- a/thinkterm-plugin-panel/src/scene.rs+++ b/thinkterm-plugin-panel/src/scene.rs@@ -5,7 +5,9 @@//! There are no widgets. A button is a rounded rectangle, its label and a//! hit over both; the player draws what it is given and nothing else, so a//! panel looks the same wherever it is shown. Colours are ThinkTerm's own,-//! by name, so a panel follows the theme without being told of it.+//! by name, so a panel follows the theme without being told of it. The one+//! exception is a [`Field`]: text is edited where it is typed, without+//! waiting on the plugin, so the client draws the field itself.//!//! An item that does not read -- a coordinate a plugin wrote as `null`, a//! kind a newer ThinkTerm knows and this one does not -- is left out, and@@ -28,6 +30,19 @@ pub struct Frame {/// nothing.#[serde(default, skip_serializing_if = "is_default")]pub extend: bool,+ /// The keys the panel takes while it has the keyboard, named as a+ /// browser names them (`KeyboardEvent.key`): "ArrowDown", "Enter", "j".+ /// Only these are sent, and only without Ctrl, Alt or Command, which+ /// are the app's; Escape and Tab never are (see [`Input::Key`]).+ ///+ /// [`Input::Key`]: crate::wire::Input::Key+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub keys: Vec<String>,+ /// Lets go of the keyboard, once for each new seq: what the user types+ /// next goes nowhere until they press Escape, or somewhere -- never to+ /// the terminal.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub release: Option<u32>,}/// A list of items, keeping the ones that read. JSON only: an item is read@@ -50,6 +65,7 @@ pub enum Item {Hit(Hit),Scroll(Scroll),List(List),+ Field(Field),}/// A filled rectangle, with rounded corners and a one-unit border when@@ -181,11 +197,83 @@ pub struct List {/// Scrolls a region to `to` -- a row of a list, a height in a scroll area/// -- once for each new `seq`, so a plugin that sends it in every frame-/// does not keep pulling the region back.+/// does not keep pulling the region back. With `through`, it scrolls only+/// as far as it takes to show from `to` to there: a row picked with the+/// keys is kept in view.#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]pub struct Jump {pub to: f32,pub seq: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub through: Option<f32>,+}++/// A box the user types in, which the client draws -- the box, the text,+/// the caret and what is selected -- in its own font and colours. A click+/// in it gives it the keyboard. What it holds goes to the plugin as it+/// changes, and again when the user presses Return ([`Input::Text`],+/// [`Input::Submit`]).+///+/// What it holds is the client's while the field shows: `value` is taken+/// when it first comes, and again for each new `seq`, so the frames that+/// follow do not undo what is typed meanwhile -- a plugin empties it after+/// a submit by sending `""` with the next seq ([`FieldText`] keeps count).+/// `focus` moves the keyboard to it once for each new seq, but only while+/// its panel has the keyboard already: a plugin never takes it from the+/// terminal. A field does not go in a scroll area or a list's rows, and of+/// two with one id the first is kept. One on one line is drawn rounded at+/// its ends, as the sidebar's search is, with an icon before its text when+/// it names one.+///+/// [`Input::Text`]: crate::wire::Input::Text+/// [`Input::Submit`]: crate::wire::Input::Submit+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct Field {+ pub id: String,+ pub x: f32,+ pub y: f32,+ pub w: f32,+ pub h: f32,+ #[serde(default, skip_serializing_if = "is_default")]+ pub kind: FieldKind,+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub value: String,+ #[serde(default, skip_serializing_if = "is_default")]+ pub seq: u32,+ /// Shown, faint, while it is empty.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub placeholder: String,+ #[serde(default, skip_serializing_if = "is_default")]+ pub font: Font,+ /// The most characters it holds; 0 for as many as any field holds+ /// ([`FIELD_LIMIT`](crate::player::FIELD_LIMIT)).+ #[serde(default, skip_serializing_if = "is_default")]+ pub max: u32,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub focus: Option<u32>,+ /// Shown before its text, on one line: one of+ /// [`FIELD_ICONS`](crate::FIELD_ICONS) -- `search`, say -- by name.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub icon: Option<String>,+ /// A button at its end, on one line, that empties it while it holds+ /// something. The client draws it and empties the field itself, which+ /// the plugin hears as text like any other.+ #[serde(default, skip_serializing_if = "is_default")]+ pub clear: bool,+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum FieldKind {+ /// One line: Return submits it.+ #[default]+ Line,+ /// Lines: Return starts a new one, and Command-Return -- Ctrl+Return+ /// off a Mac -- submits them.+ Lines,+ /// One line shown as dots. The plugin is sent what it holds only when+ /// it is submitted, and nothing can be copied or cut out of it.+ Secret,}#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]@@ -224,6 +312,8 @@ pub enum Cursor {Pointer,/// The arrow: a region that answers clicks without looking like it.Arrow,+ /// The I-beam: text is typed there. A field has it.+ Text,}/// A colour: one of ThinkTerm's by name, which follow its theme, or a fixed@@ -386,6 +476,16 @@ impl Frame {pub fn extend(&mut self, extend: bool) {self.extend = extend;}++ /// The keys the panel takes while it has the keyboard.+ pub fn keys(&mut self, keys: &[&str]) {+ self.keys = keys.iter().map(|key| key.to_string()).collect();+ }++ /// Lets go of the keyboard: once for each new `seq`.+ pub fn release(&mut self, seq: u32) {+ self.release = Some(seq);+ }}impl Rect {@@ -597,6 +697,125 @@ impl List {}}+impl Field {+ pub fn new(id: impl Into<String>, x: f32, y: f32, w: f32, h: f32) -> Self {+ Self {+ id: id.into(),+ x,+ y,+ w,+ h,+ kind: FieldKind::Line,+ value: String::new(),+ seq: 0,+ placeholder: String::new(),+ font: Font::Ui,+ max: 0,+ focus: None,+ icon: None,+ clear: false,+ }+ }++ /// Lines rather than one.+ pub fn lines(mut self) -> Self {+ self.kind = FieldKind::Lines;+ self+ }++ /// Shown as dots, and sent only when submitted.+ pub fn secret(mut self) -> Self {+ self.kind = FieldKind::Secret;+ self+ }++ /// What it holds, taken once for each new `seq`.+ pub fn value(mut self, value: impl Into<String>, seq: u32) -> Self {+ self.value = value.into();+ self.seq = seq;+ self+ }++ pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {+ self.placeholder = placeholder.into();+ self+ }++ /// In the terminal's font.+ pub fn mono(mut self) -> Self {+ self.font = Font::Mono;+ self+ }++ pub fn max(mut self, max: u32) -> Self {+ self.max = max;+ self+ }++ /// Moves the keyboard here, once for each new `seq`, while the panel+ /// has it.+ pub fn focus(mut self, seq: u32) -> Self {+ self.focus = Some(seq);+ self+ }++ /// The icon before its text, on one line: one of+ /// [`FIELD_ICONS`](crate::FIELD_ICONS).+ pub fn icon(mut self, icon: impl Into<String>) -> Self {+ self.icon = Some(icon.into());+ self+ }++ /// A button at its end, on one line, that empties it.+ pub fn clear(mut self) -> Self {+ self.clear = true;+ self+ }+}++/// A field's text as its plugin keeps it: what the field last said it+/// holds, and how many times the plugin put text in it, which+/// [`field`](Self::field) sends as its `seq`. So what the plugin puts there+/// is taken once, and frames drawn while the user types do not undo it.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct FieldText {+ text: String,+ seq: u32,+}++impl FieldText {+ pub fn text(&self) -> &str {+ &self.text+ }++ /// What the field said it holds -- an `Input::Text`'s or an+ /// `Input::Submit`'s -- unless it was typed over text this has put+ /// there since: the field takes that text, and says what it holds+ /// again. True when it was taken.+ pub fn heard(&mut self, typed: &crate::wire::Typed) -> bool {+ if typed.seq != self.seq {+ return false;+ }+ self.text = typed.text.clone();+ true+ }++ /// Puts `text` in the field, over what was typed.+ pub fn set(&mut self, text: impl Into<String>) {+ self.text = text.into();+ self.seq = self.seq.wrapping_add(1);+ }++ pub fn clear(&mut self) {+ self.set(String::new());+ }++ /// The field holding it, at its place.+ pub fn field(&self, id: impl Into<String>, x: f32, y: f32, w: f32, h: f32) -> Field {+ Field::new(id, x, y, w, h).value(self.text.clone(), self.seq)+ }+}+macro_rules! into_item {($($kind:ident),*) => {$(impl From<$kind> for Item {@@ -607,7 +826,7 @@ macro_rules! into_item {};}-into_item!(Rect, Text, Line, Area, Hit, Scroll, List);+into_item!(Rect, Text, Line, Area, Hit, Scroll, List, Field);impl Color {pub const fn rgb(r: u8, g: u8, b: u8) -> Self {@@ -641,6 +860,7 @@ impl Item {Self::Hit(hit) => Bounds::new(hit.x, hit.y, hit.w, hit.h),Self::Scroll(scroll) => Bounds::new(scroll.x, scroll.y, scroll.w, scroll.h),Self::List(list) => Bounds::new(list.x, list.y, list.w, list.h),+ Self::Field(field) => Bounds::new(field.x, field.y, field.w, field.h),Self::Line(line) => points_bounds(&line.points, None).grow(line.width / 2.0),Self::Area(area) => points_bounds(&area.points, Some(area.base)),}@@ -815,6 +1035,67 @@ mod tests {assert_eq!(to_value(&extending).unwrap(), json!({"items": []}));}+ #[test]+ fn a_field_and_the_keys_a_frame_takes_are_json_too() {+ let frame = read(json!({+ "items": [+ {"field": {"id": "add", "x": 8, "y": 4, "w": 200, "h": 26, "placeholder": "Symbol", "icon": "plus"}},+ {"field": {"id": "note", "x": 8, "y": 40, "w": 200, "h": 80, "kind": "lines", "value": "a\nb", "seq": 2, "focus": 1}}+ ],+ "keys": ["ArrowDown", "j"],+ "release": 3+ }));+ let Item::Field(add) = &frame.items[0] else {+ panic!("{frame:?}")+ };+ assert_eq!(+ (add.kind, add.seq, add.font, add.max, add.focus),+ (FieldKind::Line, 0, Font::Ui, 0, None)+ );+ assert_eq!(add.icon.as_deref(), Some("plus"));+ let Item::Field(note) = &frame.items[1] else {+ panic!("{frame:?}")+ };+ assert_eq!(+ (note.kind, note.value.as_str(), note.seq, note.focus),+ (FieldKind::Lines, "a\nb", 2, Some(1))+ );+ assert_eq!(frame.keys, ["ArrowDown", "j"]);+ assert_eq!(frame.release, Some(3));+ assert_eq!(+ to_value(Field::new("pass", 0.0, 0.0, 10.0, 10.0).secret()).unwrap(),+ json!({"id": "pass", "x": 0.0, "y": 0.0, "w": 10.0, "h": 10.0, "kind": "secret"}),+ "what is the default is left out"+ );+ let mut plain = Frame::default();+ plain.keys(&[]);+ assert_eq!(to_value(&plain).unwrap(), json!({"items": []}));+ }++ #[test]+ fn a_field_s_text_is_sent_again_only_when_the_plugin_puts_some_there() {+ let mut text = FieldText::default();+ let first = text.field("add", 0.0, 0.0, 10.0, 10.0);+ let typed = |text: &str, seq: u32| crate::wire::Typed {+ id: "add".into(),+ text: text.into(),+ seq,+ };+ assert!(text.heard(&typed("TS", first.seq)));+ let shown = text.field("add", 0.0, 0.0, 10.0, 10.0);+ assert_eq!((shown.value.as_str(), shown.seq), ("TS", first.seq));+ text.clear();+ let cleared = text.field("add", 0.0, 0.0, 10.0, 10.0);+ assert_eq!((cleared.value.as_str(), cleared.seq), ("", first.seq + 1));+ assert_eq!(text.text(), "");+ // Typed over the text before it was emptied: the field takes the+ // empty one, so the plugin keeps it too.+ assert!(!text.heard(&typed("TSx", first.seq)));+ assert_eq!(text.text(), "");+ assert!(text.heard(&typed("x", first.seq + 1)));+ assert_eq!(text.text(), "x");+ }+#[test]fn colours_are_names_or_hex_and_the_unknown_is_text() {assert_eq!(Color::parse("negative-bg"), Color::Token(Token::NegativeBg));diff --git a/thinkterm-plugin-panel/src/wire.rs b/thinkterm-plugin-panel/src/wire.rsindex aa1cd02e..9d21cb68 100644--- a/thinkterm-plugin-panel/src/wire.rs+++ b/thinkterm-plugin-panel/src/wire.rs@@ -47,6 +47,28 @@ pub struct Env {/// row up with it.#[serde(default, skip_serializing_if = "Option::is_none")]pub close: Option<CloseButton>,+ /// What the client does besides drawing and sending clicks+ /// ([`feature`]): a plugin draws for what it has. One that does not+ /// say `fields` leaves fields out, and one that does not say `keys`+ /// never gives the panel the keyboard but through a field.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub features: Vec<String>,+}++/// The names of what a client can do, in [`Env::features`].+pub mod feature {+ /// It shows fields, and sends what is typed in them.+ pub const FIELDS: &str = "fields";+ /// It gives a panel the keyboard when the user asks, and sends the keys+ /// the panel takes.+ pub const KEYS: &str = "keys";+}++impl Env {+ /// Whether the client says it does `feature`.+ pub fn has(&self, feature: &str) -> bool {+ self.features.iter().any(|has| has == feature)+ }}/// The other machine the terminal beside a panel runs on.@@ -190,9 +212,11 @@ pub struct MonoMetrics {}/// Something the user did in the panel. Hovering and scrolling are not-/// among them: the player does both without asking.+/// among them: the player does both without asking. More may come: a+/// plugin lets be what it does not know.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]+#[non_exhaustive]pub enum Input {/// A press on a hit, at `x`, `y` within it.Click(Click),@@ -200,6 +224,54 @@ pub enum Input {/// whatever the plugin does, and its panel gets no other until its/// frames have stopped asking for one: this is for the plugin to stop.Close,+ /// What a field holds changed: typed, pasted or cut. Not sent for a+ /// secret field.+ Text(Typed),+ /// The user pressed Return in a field, Command-Return in one of lines:+ /// what it holds.+ Submit(Typed),+ /// The panel has the keyboard: in its field `id`, or in none of them.+ Focus(Focus),+ /// The keyboard went from the panel: where the user put it, or nowhere+ /// until they do.+ Blur,+ /// One of the keys the panel takes ([`Frame::keys`]), pressed while it+ /// has the keyboard. Escape gives the keyboard back, and Tab moves it+ /// between the panel's fields: neither is sent. Nor is a key pressed+ /// with Ctrl, Alt or Command, which are the app's, or what the field+ /// with the keyboard uses itself.+ ///+ /// [`Frame::keys`]: crate::scene::Frame::keys+ Key(Key),+}++/// A field, by its id, what it holds, and the `seq` of the text it was+/// typed over: one the plugin has put other text in since was typed over+/// what is gone ([`FieldText::heard`]).+///+/// [`FieldText::heard`]: crate::scene::FieldText::heard+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Typed {+ pub id: String,+ pub text: String,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub seq: u32,+}++/// Where in a panel with the keyboard it is: in the field `id`, or none.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Focus {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub id: Option<String>,+}++/// A key, named as a browser names it, and whether Shift was held -- the+/// one modifier sent with one.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Key {+ pub key: String,+ #[serde(default)]+ pub mods: Mods,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -333,6 +405,66 @@ mod tests {serde_json::from_value::<Input>(json!("close")).unwrap(),Input::Close);++ let typed = Typed {+ id: "add".into(),+ text: "TSM".into(),+ seq: 0,+ };+ assert_eq!(+ to_value(Input::Submit(typed.clone())).unwrap(),+ json!({"submit": {"id": "add", "text": "TSM"}})+ );+ let over = Typed {+ seq: 2,+ ..typed.clone()+ };+ assert_eq!(+ to_value(Input::Text(over)).unwrap(),+ json!({"text": {"id": "add", "text": "TSM", "seq": 2}}),+ "typed over the text the plugin put there the second time"+ );+ assert_eq!(+ to_value(Input::Text(typed)).unwrap(),+ json!({"text": {"id": "add", "text": "TSM"}})+ );+ assert_eq!(+ to_value(Input::Focus(Focus::default())).unwrap(),+ json!({"focus": {}}),+ "the panel, in none of its fields"+ );+ assert_eq!(to_value(Input::Blur).unwrap(), json!("blur"));+ let key: Input = serde_json::from_value(json!({"key": {"key": "ArrowDown"}})).unwrap();+ assert_eq!(+ key,+ Input::Key(Key {+ key: "ArrowDown".into(),+ mods: Mods::default()+ })+ );+ }++ #[test]+ fn an_env_says_what_its_client_does() {+ let env: Env = serde_json::from_value(json!({+ "width": 300, "height": 500, "scale": 2, "dark": true,+ "small": {"size": 11, "line": 15},+ "body": {"size": 13, "line": 18},+ "title": {"size": 15, "line": 20},+ "mono": {"size": 12, "line": 17, "advance": 7},+ "features": ["fields", "someday"]+ }))+ .unwrap();+ assert!(env.has(feature::FIELDS));+ assert!(!env.has(feature::KEYS));+ let older = Env {+ features: Vec::new(),+ ..env+ };+ assert!(+ to_value(&older).unwrap().get("features").is_none(),+ "a client that does none of it says nothing"+ );}#[test]diff --git a/thinkterm-plugin-sdk/src/lib.rs b/thinkterm-plugin-sdk/src/lib.rsindex 18e65577..41d21d9a 100644--- a/thinkterm-plugin-sdk/src/lib.rs+++ b/thinkterm-plugin-sdk/src/lib.rs@@ -43,6 +43,12 @@//! }//! ```//!+//! Text is typed in a [`Field`](panel::Field), which ThinkTerm draws and+//! edits itself: the plugin is sent what it holds as it changes, and when+//! the user presses Return, and keeps it with a+//! [`FieldText`](panel::FieldText). A panel the user gives the keyboard to+//! is sent the keys its frame says it takes ([`Frame::keys`](panel::Frame::keys())).+//!//! A panel with more to show than a sidebar has room for asks for its//! extended view, a wide area beside the sidebar that the user sizes, with//! [`Frame::extend`](panel::Frame::extend()). It comes as a view of its own,@@ -62,7 +68,7 @@ pub mod protocol;pub use thinkterm_plugin_panel as panel;use anyhow::anyhow;-use panel::{Answer, Ask, Env, Frame, Input, Item, Rows, RowsWanted};+use panel::{Answer, Ask, Env, Focus, Frame, Input, Item, Rows, RowsWanted};use protocol::{FromPlugin, ToPlugin};use serde_json::Value;use std::collections::{BTreeMap, HashMap};@@ -100,10 +106,11 @@ pub trait Plugin: Send {Vec::new()}- /// What the user did in `view`: a click, or, in an extended view, the- /// close button pressed -- the view goes, and the panel is to stop- /// asking for it. The panel is drawn again after it, and its extended- /// view with it.+ /// What the user did in `view`: a click; in an extended view, the close+ /// button pressed -- the view goes, and the panel is to stop asking for+ /// it; text typed in a field, or submitted; the keyboard coming or+ /// going (`view.focus` follows it); a key the panel takes. The panel is+ /// drawn again after it, and its extended view with it.fn input(&mut self, view: &View, input: Input, cx: &mut Cx) {let _ = (view, input, cx);}@@ -149,6 +156,10 @@ pub struct View {/// For a panel, its extended view while one is on show: the panel is/// drawn again when it comes and when it goes.pub extension: Option<u64>,+ /// Where the keyboard is in the view while it has it -- in which of+ /// its fields, if any -- as the last `Input::Focus` said; `None` while+ /// it is elsewhere.+ pub focus: Option<Focus>,}impl View {@@ -159,6 +170,7 @@ impl View {env,extends: None,extension: None,+ focus: None,}}@@ -549,9 +561,15 @@ impl Runner {}}ToPlugin::Input { view, input } => {- let Some(shown) = self.views.get(&view) else {+ let Some(shown) = self.views.get_mut(&view) else {return Ok(None);};+ match &input {+ Input::Focus(focus) => shown.view.focus = Some(focus.clone()),+ Input::Blur => shown.view.focus = None,+ _ => {}+ }+ let shown = &self.views[&view];let panel = shown.view.panel();let mut cx = Cx::new();let handled = guard(|| {@@ -1199,6 +1217,78 @@ mod tests {);}+ /// Keeps a field's text, and draws where the keyboard is in its view.+ #[derive(Default)]+ struct Typing {+ add: panel::FieldText,+ submitted: Vec<String>,+ }++ impl Plugin for Typing {+ fn draw(&mut self, view: &View, frame: &mut Frame) {+ let focus = match &view.focus {+ None => "away".to_string(),+ Some(Focus { id: None }) => "panel".to_string(),+ Some(Focus { id: Some(id) }) => id.clone(),+ };+ frame.push(Text::new(0.0, 0.0, 10.0, 10.0, focus));+ frame.push(self.add.field("add", 0.0, 20.0, 100.0, 24.0));+ }++ fn input(&mut self, _view: &View, input: Input, _cx: &mut Cx) {+ match input {+ Input::Text(typed) => {+ self.add.heard(&typed);+ }+ Input::Submit(typed) => {+ self.submitted.push(typed.text);+ self.add.clear();+ }+ _ => {}+ }+ }+ }++ #[test]+ fn a_view_knows_where_the_keyboard_is_and_a_submit_empties_its_field() {+ let mut plugin = Typing::default();+ let sent = serve_all(+ &mut plugin,+ lines(&[+ json!({"type": "open", "view": 1, "env": env()}),+ json!({"type": "input", "view": 1, "input": {"focus": {"id": "add"}}}),+ json!({"type": "input", "view": 1, "input": {"text": {"id": "add", "text": "TSM"}}}),+ json!({"type": "input", "view": 1, "input": {"submit": {"id": "add", "text": "TSM"}}}),+ json!({"type": "input", "view": 1, "input": "blur"}),+ ]),+ );+ let drawn: Vec<(String, String, u64)> = sent+ .iter()+ .map(|message| {+ let items = &message["frame"]["items"];+ (+ items[0]["text"]["text"].as_str().unwrap().to_string(),+ items[1]["field"]["value"]+ .as_str()+ .unwrap_or("")+ .to_string(),+ items[1]["field"]["seq"].as_u64().unwrap_or(0),+ )+ })+ .collect();+ assert_eq!(+ drawn,+ [+ ("away".to_string(), String::new(), 0),+ ("add".to_string(), String::new(), 0),+ ("add".to_string(), "TSM".to_string(), 0),+ ("add".to_string(), String::new(), 1),+ ("away".to_string(), String::new(), 1),+ ]+ );+ assert_eq!(plugin.submitted, ["TSM"]);+ }+#[test]fn it_says_the_api_of_a_thinkterm_older_than_itself() {assert_eq!(speaking(None), protocol::API);diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 41d7db0d..527794e8 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -4357,6 +4357,9 @@ impl<P: Platform, L: Link> App<P, L> {let inner = &mut *self.inner.borrow_mut();env.locale = thinkterm_i18n::current_locale().to_string();env.cwd = Self::focused_cwd(inner);+ // Its fields are the page's own; the keyboard comes to a panel+ // through them, and no key of the page's gives it.+ env.features = vec![thinkterm_plugin_panel::feature::FIELDS.to_string()];if extended {env.can_extend = false;inner.plugin_extended_env = Some(env.clone());@@ -4547,6 +4550,92 @@ impl<P: Platform, L: Link> App<P, L> {sent}+ /// Whether the plugin panel, or its extended view, has the keyboard: one+ /// of its fields is the page's field with it.+ pub fn plugin_panel_has_keyboard(&self, extended: bool) -> bool {+ Self::plugin_view(&self.inner.borrow(), extended).is_some_and(|panel| panel.has_keyboard())+ }++ /// The user put the keyboard in field `id` of the plugin panel, or its+ /// extended view: pressed in it, or tabbed to it. The other view lets go+ /// of it.+ pub fn plugin_panel_field_focus(self: &Rc<Self>, extended: bool, id: &str) {+ let (sends, others) = {+ let mut inner = self.inner.borrow_mut();+ let others = match Self::plugin_view_mut(&mut inner, !extended) {+ Some(other) if other.has_keyboard() => other.blur(),+ _ => Vec::new(),+ };+ let sends = match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.focus_field(id),+ None => Vec::new(),+ };+ (sends, others)+ };+ self.send_panel_frames(others, !extended);+ self.send_panel_frames(sends, extended);+ }++ /// What field `id` of the plugin panel, or its extended view, holds now+ /// the user edited it: what the page's field is to hold instead, when+ /// the panel's takes less.+ pub fn plugin_panel_field_text(self: &Rc<Self>, extended: bool, id: &str, text: &str) -> Option<String> {+ let (sends, held) = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.edit_field(id, text),+ None => return None,+ }+ };+ self.send_panel_frames(sends, extended);+ held+ }++ /// The user submitted field `id` of the plugin panel, or its extended+ /// view.+ pub fn plugin_panel_field_submit(self: &Rc<Self>, extended: bool, id: &str) {+ let sends = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.submit_field(id),+ None => return,+ }+ };+ self.send_panel_frames(sends, extended);+ }++ /// The keyboard went from the plugin panel, or its extended view.+ pub fn plugin_panel_blur(self: &Rc<Self>, extended: bool) {+ let sends = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) if panel.has_keyboard() => panel.blur(),+ _ => return,+ }+ };+ self.send_panel_frames(sends, extended);+ }++ /// A key the page's field with the keyboard does not use, in the plugin+ /// panel or its extended view, named as the browser names it: true when+ /// it was the panel's, for the page to keep it to itself.+ pub fn plugin_panel_key(+ self: &Rc<Self>,+ extended: bool,+ key: &str,+ mods: thinkterm_plugin_panel::Mods,+ ) -> bool {+ let (taken, sends) = {+ let mut inner = self.inner.borrow_mut();+ match Self::plugin_view_mut(&mut inner, extended) {+ Some(panel) => panel.key(key, mods),+ None => return false,+ }+ };+ self.send_panel_frames(sends, extended);+ taken+ }+/// The wheel over the plugin panel, or its extended view, `dy` of its/// units down. True when something in it scrolled, and the page is to/// paint it again.diff --git a/thinkterm-web/src/bridge.rs b/thinkterm-web/src/bridge.rsindex 5e7f146e..e874d2be 100644--- a/thinkterm-web/src/bridge.rs+++ b/thinkterm-web/src/bridge.rs@@ -212,6 +212,49 @@ impl Client {self.app.plugin_panel_wheel(extended, x, y, dx, dy)}+ /// Whether the plugin panel, or its extended view, has the keyboard.+ pub fn plugin_panel_has_keyboard(&self, extended: bool) -> bool {+ self.app.plugin_panel_has_keyboard(extended)+ }++ /// The page's field over the panel's field `id` got the keyboard.+ pub fn plugin_panel_field_focus(&self, extended: bool, id: String) {+ self.app.plugin_panel_field_focus(extended, &id);+ }++ /// What the page's field over the panel's field `id` holds now: what+ /// it is to hold instead, when the panel's takes less.+ pub fn plugin_panel_field_text(&self, extended: bool, id: String, text: String) -> Option<String> {+ self.app.plugin_panel_field_text(extended, &id, &text)+ }++ /// Return in the page's field over the panel's field `id`.+ pub fn plugin_panel_field_submit(&self, extended: bool, id: String) {+ self.app.plugin_panel_field_submit(extended, &id);+ }++ /// The keyboard went from the panel's fields to elsewhere on the page.+ pub fn plugin_panel_blur(&self, extended: bool) {+ self.app.plugin_panel_blur(extended);+ }++ /// A key the page's field with the keyboard does not use, as+ /// `KeyboardEvent.key` names it: true when it was the panel's, and the+ /// page is to keep it to itself.+ #[allow(clippy::too_many_arguments)]+ pub fn plugin_panel_key(+ &self,+ extended: bool,+ key: String,+ shift: bool,+ ctrl: bool,+ alt: bool,+ meta: bool,+ ) -> bool {+ let mods = thinkterm_plugin_panel::Mods { shift, ctrl, alt, cmd: meta };+ self.app.plugin_panel_key(extended, &key, mods)+ }+/// The Snippets tab: JSON `SnippetsView`.pub fn snippets(&self) -> String {json(&self.app.snippets_view())diff --git a/thinkterm-web/src/plugin_panel.rs b/thinkterm-web/src/plugin_panel.rsindex b220e3b8..d12aded8 100644--- a/thinkterm-web/src/plugin_panel.rs+++ b/thinkterm-web/src/plugin_panel.rs@@ -11,6 +11,11 @@//! A panel's extended view, beside the right panel, is a model of its own,//! opened as the extended view of the panel's opening: the app opens it//! while the panel's frames ask for one.+//!+//! The page puts a field of its own over each field the player paints,+//! which the browser edits; what it holds, and where the keyboard goes,+//! come back here for the player to decide what the plugin hears. A panel+//! has the keyboard through its fields only: the page offers no key for it.use serde::Serialize;use thinkterm_plugin_channel::wire::{PanelEvent, PanelRequest, Raw, ToHost};@@ -36,6 +41,9 @@ pub struct PanelView {pub message: Option<String>,/// What to paint; none before the plugin first drew.pub painting: Option<Painting>,+ /// Whether its fields take typing: its program drew it on this+ /// opening. What one starting again last drew takes none.+ pub live: bool,}#[derive(Debug, Clone, PartialEq)]@@ -168,6 +176,7 @@ impl PanelModel {state,message,painting: (state != "stopped" && self.player.shown()).then(|| self.player.painting()),+ live: self.status == Status::Open,}}@@ -222,6 +231,8 @@ impl PanelModel {}Err(err) => log::warn!("plugin panel {}: a frame that does not read: {err}", self.plugin),}+ // The keyboard may have moved with it, or gone with a field.+ sends.extend(self.told());}PanelEvent::Rows { rows } => match rows.read::<Rows>() {Ok(rows) => self.player.rows(rows),@@ -234,6 +245,7 @@ impl PanelModel {log::info!("plugin panel {}: {reason}", self.plugin);Status::Stopped(reason)};+ self.let_go_of_keyboard();}// The page never says its terminal runs on another machine: a// plugin asking of one anyway is told so.@@ -257,6 +269,7 @@ impl PanelModel {self.status = Status::Again(at);self.changed();}+ self.let_go_of_keyboard();}/// Something sent for it did not reach the host, for `why` -- one that@@ -274,6 +287,7 @@ impl PanelModel {let delay = 1000.0 * f64::from(1u32 << self.failures.min(5)).min(30.0);self.status = Status::Again(now + delay);self.trouble = Some(why.to_string());+ self.let_go_of_keyboard();self.changed();Some(delay)}@@ -327,6 +341,86 @@ impl PanelModel {vec![self.frame(PanelRequest::Input { input: Raw::new(&input) })]}+ /// Whether the panel has the keyboard: one of its fields is the page's+ /// field with it.+ pub fn has_keyboard(&self) -> bool {+ self.player.has_keyboard()+ }++ /// The user put the keyboard in field `id`, pressing in it or tabbing+ /// to it.+ pub fn focus_field(&mut self, id: &str) -> Sends {+ if self.status != Status::Open {+ return Vec::new();+ }+ self.player.focus_field(id);+ self.changed();+ self.told()+ }++ /// What field `id`, with the keyboard, holds now the user edited it:+ /// what the plugin is to hear, and what the field is to hold instead,+ /// when it takes less -- fewer characters, one line.+ pub fn edit_field(&mut self, id: &str, text: &str) -> (Sends, Option<String>) {+ if self.status != Status::Open {+ return (Vec::new(), None);+ }+ self.player.edit_field(id, text);+ self.changed();+ let held = self+ .player+ .field_text(id)+ .map(|(held, _)| held)+ .filter(|held| *held != text)+ .map(str::to_string);+ (self.told(), held)+ }++ /// The user submitted field `id`.+ pub fn submit_field(&mut self, id: &str) -> Sends {+ if self.status != Status::Open {+ return Vec::new();+ }+ self.player.submit(id);+ self.told()+ }++ /// The keyboard went from the panel: to the terminal, or elsewhere on+ /// the page.+ pub fn blur(&mut self) -> Sends {+ self.player.blur();+ self.changed();+ self.told()+ }++ /// A key the page's field with the keyboard does not use, named as the+ /// browser names it: whether it was the panel's, and what the plugin is+ /// to hear.+ pub fn key(&mut self, key: &str, mods: Mods) -> (bool, Sends) {+ if self.status != Status::Open {+ return (false, Vec::new());+ }+ let taken = self.player.key(key, mods);+ self.changed();+ (taken, self.told())+ }++ /// The panel is not served: the keyboard goes back, and the plugin,+ /// whose view is gone, is told nothing of it.+ fn let_go_of_keyboard(&mut self) {+ self.player.blur();+ self.player.told();+ }++ /// What the player decided the plugin is to hear, as frames.+ fn told(&mut self) -> Sends {+ self.player+ .told()+ .into_iter()+ .map(|input| self.frame(PanelRequest::Input { input: Raw::new(&input) }))+ .collect()+ }+/// The wheel turned: what scrolled is painted again, and the rows it/// brings near are asked for.pub fn wheel(&mut self, x: f32, y: f32, dx: f32, dy: f32) -> (bool, Sends) {@@ -386,6 +480,7 @@ mod tests {remote: None,can_extend: false,close: None,+ features: Vec::new(),}}@@ -511,6 +606,48 @@ mod tests {assert_eq!(panel.unsent(why, 0.0), None, "stopped stays stopped");}+ #[test]+ fn a_field_has_the_keyboard_only_as_the_user_gives_it_and_tells_the_plugin() {+ let (mut panel, _) = PanelModel::open("stocks", 1, None, env(), 0.0);+ let frame = json!({"items": [+ {"field": {"id": "add", "x": 8, "y": 8, "w": 200, "h": 26, "focus": 1}}+ ], "keys": ["ArrowDown"]});+ let sends = panel.heard(PanelEvent::Frame { frame: Raw::new(&frame) }, 0.0);+ assert!(!requests(&sends).iter().any(|asked| asked.get("input").is_some()), "not given");+ assert!(!panel.has_keyboard());+ let view = panel.view_json();+ let painted = serde_json::to_value(view.painting.unwrap()).unwrap();+ assert_eq!(painted["ops"][0]["op"], "field", "for the page to put its own over");++ let focused = requests(&panel.focus_field("add"));+ assert_eq!(focused[0]["input"]["input"], json!({"focus": {"id": "add"}}));+ let (typed, held) = panel.edit_field("add", "TSM");+ assert_eq!(held, None, "all of it taken");+ let typed = requests(&typed);+ assert_eq!(typed[0]["input"]["input"], json!({"text": {"id": "add", "text": "TSM"}}));+ let (taken, keyed) = panel.key("ArrowDown", Mods::default());+ assert!(taken);+ assert_eq!(requests(&keyed)[0]["input"]["input"]["key"]["key"], "ArrowDown");+ assert_eq!(panel.edit_field("add", "TS\tM").1.as_deref(), Some("TSM"), "one line");+ let submitted = requests(&panel.submit_field("add"));+ assert_eq!(submitted[0]["input"]["input"]["submit"]["text"], "TSM");+ let (_, escaped) = panel.key("Escape", Mods::default());+ assert_eq!(requests(&escaped)[0]["input"]["input"], json!("blur"));+ assert!(!panel.has_keyboard());++ // A panel the host lets go of lets go of the keyboard, saying nothing.+ panel.focus_field("add");+ panel.heard(PanelEvent::Closed { reason: "restarting".into(), again: true }, 0.0);+ assert!(!panel.has_keyboard());+ // What it last drew stays on show meanwhile, and takes no typing.+ let view = panel.view_json();+ assert!(view.painting.is_some() && !view.live);+ assert!(panel.focus_field("add").is_empty());+ assert!(!panel.has_keyboard());+ assert!(panel.edit_field("add", "x").0.is_empty());+ assert!(panel.submit_field("add").is_empty());+ }+#[test]fn sizes_are_told_at_most_every_little_while_and_rows_wait_for_them() {let (mut panel, _) = PanelModel::open("stocks", 1, None, env(), 0.0);diff --git a/thinkterm-web/ui/src/PluginPanel.svelte b/thinkterm-web/ui/src/PluginPanel.svelteindex c47fb740..1cb1e8dc 100644--- a/thinkterm-web/ui/src/PluginPanel.svelte+++ b/thinkterm-web/ui/src/PluginPanel.svelte@@ -5,12 +5,21 @@// plugin_panel.rs), painted on a canvas with the page's own fonts and// colours, as the desktop paints it with its own. The pointer and the// wheel go back to the wasm, which says whether to paint again; what the- // plugin draws anew arrives as a new revision.+ // plugin draws anew arrives as a new revision. Each of its fields is an+ // input of the page's own, which the browser edits, over the box the+ // canvas paints in order: see-through, and cut away where what answers a+ // press is drawn over it. What it holds and where the keyboard goes go+ // back to the wasm, whose player+ // decides what the plugin hears. The panel has the keyboard only through+ // them, and one that loses it without the user leaves it on the canvas,+ // never the terminal (`hold`).import { handle } from './client';import { refreshViews, s, views } from './client.svelte';import { canExtend } from './extended';- import { x as closeIcon } from './icons';+ import { iconByName, x as closeIcon } from './icons';+ import { focusTerminal } from './mobile.svelte';import type { PanelOp, PanelView, Painting } from './model';+ import { onMac } from './palette.svelte';let { extended = false }: { extended?: boolean } = $props();@@ -33,6 +42,12 @@const MONO_FACE = 'ThinkTerm Panel Mono';const MONO_FAMILY = `"${MONO_FACE}", ui-monospace, Menlo, monospace`;const ELLIPSIS = '...';+ // A field of lines' corners (thinkterm-plugin-panel `FIELD_RADIUS`); one+ // on one line is round at its ends, as the panel's search is.+ const FIELD_RADIUS = 6;+ // How long after an input method put its text in a Return marked 229 is+ // still its own, in milliseconds: Safari sends the one that ended it then.+ const ENDED_COMPOSING = 500;let host: HTMLDivElement;let canvas: HTMLCanvasElement;@@ -66,6 +81,11 @@warning: '--caution',thumb: '--muted',};+ // The page's own, for a field's box.+ const FIELD_SOURCES: Record<string, string> = {+ field: '--btn',+ 'field-border': '--btn-border',+ };function parse(css: string): Rgba {const m = css.match(/rgba?\(([^)]+)\)/);@@ -79,7 +99,7 @@probe.style.display = 'none';host.appendChild(probe);const out: Record<string, Rgba> = {};- for (const [name, variable] of Object.entries(SOURCES)) {+ for (const [name, variable] of Object.entries({ ...SOURCES, ...FIELD_SOURCES })) {probe.style.color = `var(${variable})`;out[name] = parse(getComputedStyle(probe).color);}@@ -275,9 +295,229 @@ctx.fill();return;}+ // The box, in order with what is drawn over it; the page's own+ // input over it, see-through, holds the text.+ case 'field': {+ if (op.w <= 0 || op.h <= 0) return;+ const radius = Math.min(fieldRadius(op), op.w / 2);+ ctx.fillStyle = css(rgba('field'));+ ctx.beginPath();+ ctx.roundRect(op.x, op.y, op.w, op.h, radius);+ ctx.fill();+ ctx.strokeStyle = css(rgba(op.focused ? 'accent' : 'field-border'));+ ctx.lineWidth = 1;+ ctx.beginPath();+ ctx.roundRect(op.x + 0.5, op.y + 0.5, op.w - 1, op.h - 1, Math.max(0, radius - 0.5));+ ctx.stroke();+ return;+ }}}+ type FieldOp = Extract<PanelOp, { op: 'field' }>;++ function fieldRadius(op: FieldOp): number {+ return Math.max(0, op.kind === 'lines' ? Math.min(FIELD_RADIUS, op.h / 2) : op.h / 2);+ }+ /** The panel's fields, each with an input of the page's own over it. */+ const fields = $derived(+ (view?.painting?.ops ?? []).filter((op): op is FieldOp => op.op === 'field'),+ );++ /** Whether a field of `kind` leaves `ev`'s key to the panel: Escape and+ Tab, the function keys, and on one line the keys that move up and+ down. A key it uses is the field's; one with Ctrl, Alt or Command is+ the field's, the page's or the browser's, never the panel's. */+ function leaves(kind: FieldOp['kind'], ev: KeyboardEvent): boolean {+ if (ev.ctrlKey || ev.altKey || ev.metaKey) return false;+ if (ev.key === 'Escape' || ev.key === 'Tab' || /^F\d{1,2}$/.test(ev.key)) return true;+ return kind !== 'lines' && ['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown'].includes(ev.key);+ }++ /** The keyboard left a field without the user -- the plugin let go of+ it, or the field went -- while they may be typing in it: what they+ type next was meant for the panel, and goes nowhere. It waits on the+ canvas, where Escape gives it to the terminal; a press anywhere puts+ it where it was pressed. */+ function hold() {+ if (canvas?.isConnected) canvas.focus({ preventScroll: true });+ else if (document.activeElement instanceof HTMLElement) document.activeElement.blur();+ }++ /** What of its box a field's input takes: all of it but where what+ answers a press -- a button at its end -- is drawn over it, which+ shows there, and is pressed there. */+ function uncovered(op: FieldOp): string {+ if (!op.covered?.length) return '';+ // The box one way round and the pieces, which do not overlap, the+ // other: they are left out.+ let path = `M0 0H${op.w}V${op.h}H0Z`;+ for (const [x, y, w, h] of op.covered) path += `M${x - op.x} ${y - op.y}v${h}h${w}v${-h}Z`;+ return `path('${path}')`;+ }++ function onCanvasKey(ev: KeyboardEvent) {+ if (ev.key !== 'Escape' || ev.ctrlKey || ev.altKey || ev.metaKey) return;+ ev.preventDefault();+ focusTerminal();+ }++ /** Keeps an input in step with the panel's field it is over: in its+ place, holding what the plugin last put there, and with the keyboard+ when the player says the field has it -- moved there by the plugin,+ or by Tab -- and not when it says it has not. */+ function field(node: HTMLInputElement | HTMLTextAreaElement, op: FieldOp) {+ let taken = -1;+ let current = op;+ // Its button that empties it, where it has one: shown while it holds+ // something, and never taking the keyboard from it.+ const clear = document.createElement('button');+ clear.type = 'button';+ clear.tabIndex = -1;+ clear.className = 'pclear';+ clear.innerHTML = closeIcon;+ node.after(clear);+ const showClear = () => {+ clear.hidden = !current.clear || node.value === '' || node.disabled;+ };+ // What the panel's field takes of what the page's holds: less, it+ // holds that instead.+ const tell = () => {+ const held = handle.client?.plugin_panel_field_text(extended, current.id, node.value);+ if (typeof held === 'string' && held !== node.value) node.value = held;+ showClear();+ };+ const follow = (op: FieldOp) => {+ current = op;+ node.style.left = `${op.x}px`;+ node.style.top = `${op.y}px`;+ node.style.width = `${op.w}px`;+ node.style.height = `${op.h}px`;+ const [ix, iy, iw, ih] = op.inside;+ node.style.padding = `${iy - op.y}px ${op.x + op.w - ix - iw}px ${op.y + op.h - iy - ih}px ${ix - op.x}px`;+ node.style.borderRadius = `${fieldRadius(op)}px`;+ node.style.clipPath = uncovered(op);+ // The browser counts in UTF-16 and the panel in characters, which+ // may be two of those: the panel's field cuts what is over.+ node.maxLength = op.limit * 2;+ node.placeholder = op.placeholder;+ node.dataset.font = op.font;+ if (op.revision !== taken) {+ taken = op.revision;+ if (node.value !== op.text) node.value = op.text;+ }+ if (op.clear) {+ clear.style.left = `${op.clear.x}px`;+ clear.style.top = `${op.clear.y}px`;+ clear.style.width = `${op.clear.size}px`;+ clear.style.height = `${op.clear.size}px`;+ }+ const live = view?.live ?? false;+ if (op.focused && live && document.activeElement !== node) {+ node.focus({ preventScroll: true });+ } else if (+ !op.focused &&+ document.activeElement === node &&+ // To another of its fields, which takes it as it follows.+ !handle.client?.plugin_panel_has_keyboard(extended)+ ) {+ hold();+ }+ // What a plugin starting again last drew takes no typing: nobody+ // would hear it.+ node.disabled = !live;+ showClear();+ };+ follow(op);+ // The canvas outlines the box with the keyboard.+ const onFocus = () => {+ handle.client?.plugin_panel_field_focus(extended, current.id);+ queueMicrotask(() => refresh());+ };+ const onBlur = (ev: FocusEvent) => {+ // To another of the panel's fields: the keyboard stays in it. Nor+ // does it go with the window: the browser gives this field it back.+ const to = ev.relatedTarget;+ if (to instanceof HTMLElement && to.classList.contains('pfield') && host.contains(to)) return;+ if (!document.hasFocus()) return;+ handle.client?.plugin_panel_blur(extended);+ queueMicrotask(() => refresh());+ };+ // What a field holds is told once composed: never the half of a word+ // an input method is still putting together.+ const onInput = (ev: Event) => {+ if ((ev as InputEvent).isComposing) return;+ tell();+ };+ // When an input method last put its text in.+ let composed = -Infinity;+ const onComposed = (ev: CompositionEvent) => {+ composed = ev.timeStamp;+ tell();+ };+ const onClearDown = (ev: MouseEvent) => ev.preventDefault();+ const onClear = () => {+ node.value = '';+ if (document.activeElement !== node) node.focus({ preventScroll: true });+ tell();+ };+ const onKey = (ev: KeyboardEvent) => {+ // Keys pressed while composing are the input method's: marked so, a+ // printable one marked 229 (Chrome on macOS), or the one that ended+ // a composition just now (Safari). An input method on but idle -- an+ // Android keyboard -- marks every key 229, and Return still submits.+ if (ev.isComposing) return;+ if (ev.keyCode === 229) {+ if (Array.from(ev.key).length === 1) return;+ if (ev.timeStamp - composed < ENDED_COMPOSING) {+ composed = -Infinity;+ return;+ }+ }+ // The terminal's keys are not this field's to hear.+ ev.stopPropagation();+ const command = onMac() ? ev.metaKey && !ev.ctrlKey : ev.ctrlKey && !ev.metaKey;+ if (ev.key === 'Enter' && !ev.altKey && (current.kind === 'lines' ? command : !ev.ctrlKey && !ev.metaKey)) {+ ev.preventDefault();+ handle.client?.plugin_panel_field_submit(extended, current.id);+ return;+ }+ if (!leaves(current.kind, ev)) return;+ const taken = handle.client?.plugin_panel_key(extended, ev.key, ev.shiftKey, ev.ctrlKey, ev.altKey, ev.metaKey);+ if (!taken) return;+ ev.preventDefault();+ // The keyboard may have moved to another field, or gone back.+ refresh();+ if (!handle.client?.plugin_panel_has_keyboard(extended) && document.activeElement === node) {+ node.blur();+ focusTerminal();+ }+ };+ // Typed as one element, for its events' types to be known.+ const el: HTMLElement = node;+ el.addEventListener('focus', onFocus);+ el.addEventListener('blur', onBlur);+ el.addEventListener('input', onInput);+ el.addEventListener('compositionend', onComposed);+ el.addEventListener('keydown', onKey);+ clear.addEventListener('mousedown', onClearDown);+ clear.addEventListener('click', onClear);+ return {+ update: follow,+ destroy() {+ if (document.activeElement === node) hold();+ el.removeEventListener('focus', onFocus);+ el.removeEventListener('blur', onBlur);+ el.removeEventListener('input', onInput);+ el.removeEventListener('compositionend', onComposed);+ el.removeEventListener('keydown', onKey);+ clear.removeEventListener('mousedown', onClearDown);+ clear.removeEventListener('click', onClear);+ clear.remove();+ },+ };+ }+/** Reads the panel as the wasm has it, and paints it: when it changedsince it was last painted, or `anew`, when the canvas was cleared orwhat it is painted with changed. */@@ -476,19 +716,25 @@function onMouseDown(ev: MouseEvent) {const { x, y } = local(ev);+ // A press on the panel leaves the keyboard where it is -- in one of its+ // fields, or the terminal -- but for keys held on the canvas, which the+ // terminal has again: a press is the user's.+ ev.preventDefault();+ if (document.activeElement === canvas) focusTerminal();const heard = handle.client?.plugin_panel_click(extended, x, y, ev.button, Math.max(1, ev.detail), ev.shiftKey, ev.ctrlKey, ev.altKey, ev.metaKey,);- if (heard) {- ev.preventDefault();- refresh();- }+ if (heard) refresh();}</script><div class="plugin" class:extended bind:this={host}>+ <!-- Focused only to hold the keyboard from the terminal (`hold`). -->+ <!-- svelte-ignore a11y_no_noninteractive_tabindex --><canvasbind:this={canvas}+ tabindex="-1"+ onkeydown={onCanvasKey}onpointerdown={onPointerDown}onpointermove={onPointerMove}onpointerup={onPointerUp}@@ -496,6 +742,16 @@onpointerleave={onPointerLeave}onmousedown={onMouseDown}></canvas>+ {#each fields as op (op.id)}+ {#if op.kind === 'lines'}+ <textarea class="pfield" spellcheck="false" use:field={op}></textarea>+ {:else}+ <input class="pfield" type={op.kind === 'secret' ? 'password' : 'text'} autocomplete="off" spellcheck="false" use:field={op} />+ {/if}+ {#if op.icon}+ <span class="picon" style="left: {op.icon.x}px; top: {op.icon.y}px; width: {op.icon.size}px; height: {op.icon.size}px">{@html iconByName(op.icon.name) ?? ''}</span>+ {/if}+ {/each}{#if view?.message}<div class="msg">{view.message}</div>{/if}diff --git a/thinkterm-web/ui/src/model.ts b/thinkterm-web/ui/src/model.tsindex 872af246..4c0aa48f 100644--- a/thinkterm-web/ui/src/model.ts+++ b/thinkterm-web/ui/src/model.ts@@ -287,13 +287,40 @@ export type PanelOp =}| { op: 'line'; clip: number; points: number[]; width: number; color: string }| { op: 'area'; clip: number; points: number[]; base: number; color: string; fade: boolean }- | { op: 'thumb'; clip: number; x: number; y: number; w: number; h: number };+ | { op: 'thumb'; clip: number; x: number; y: number; w: number; h: number }+ // A field's box: the page paints it, and puts a field of its own over+ // it, which takes `text` whenever `revision` moves -- the plugin put text+ // there -- and leaves `covered` (x, y, w, h) to the painting.+ | {+ op: 'field';+ clip: number;+ x: number;+ y: number;+ w: number;+ h: number;+ id: string;+ kind: 'line' | 'lines' | 'secret';+ placeholder: string;+ font: 'ui' | 'mono';+ limit: number;+ focused: boolean;+ text: string;+ revision: number;+ // Where its text goes, after its icon if it shows one.+ inside: [number, number, number, number];+ icon?: { name: string; x: number; y: number; size: number };+ // Its button that empties it, shown while it holds something.+ clear?: { name: string; x: number; y: number; size: number };+ covered?: [number, number, number, number][];+ };export type Painting = {/** Left, top, right, bottom. */clips: [number, number, number, number][];ops: PanelOp[];- cursor: 'pointer' | 'arrow' | null;+ cursor: 'pointer' | 'arrow' | 'text' | null;+ /** The panel has the keyboard, in none of its fields. */+ focused: boolean;};export type PanelView = {@@ -301,6 +328,9 @@ export type PanelView = {/** Said instead of a painting: starting, or why it stopped. */message: string | null;painting: Painting | null;+ /** Whether its fields take typing: what a plugin starting again last+ drew takes none. */+ live: boolean;};// The page's own preferences (thinkterm-web/src/settings.rs `WebSettings`),diff --git a/thinkterm-web/ui/src/palette.svelte.ts b/thinkterm-web/ui/src/palette.svelte.tsindex 64642d8a..f38ab6f4 100644--- a/thinkterm-web/ui/src/palette.svelte.ts+++ b/thinkterm-web/ui/src/palette.svelte.ts@@ -144,7 +144,7 @@ export function storedPicks(): string[] {/** Cmd on a Mac, Ctrl everywhere else. `navigator.platform` is deprecatedbut still the only thing every browser answers; the newer field winswhere there is one. */-function onMac(): boolean {+export function onMac(): boolean {const data = (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData;return /mac|iphone|ipad|ipod/i.test(data?.platform || navigator.platform || '');}diff --git a/thinkterm-web/ui/src/tokens.css b/thinkterm-web/ui/src/tokens.cssindex 1b03ec5d..6813b5bc 100644--- a/thinkterm-web/ui/src/tokens.css+++ b/thinkterm-web/ui/src/tokens.css@@ -267,7 +267,24 @@ body[data-side=off]:not([data-mobile]) #side .list { top: var(--tabs); }/* A plugin's panel: its canvas under the selector, to the panel's edges;the plugin draws its own margins. */#agents .plugin { position: absolute; inset: 86px 0 0 0; }-#agents .plugin canvas, #extended .plugin canvas { display: block; touch-action: none; }+#agents .plugin canvas, #extended .plugin canvas { display: block; touch-action: none; outline: none; }+/* A plugin's field: the page's own input over the canvas, as the sidebar's+ own fields look. */+#agents .plugin, #extended .plugin { overflow: hidden; }+/* See-through: the canvas paints the box under it, and what is drawn over it. */+.plugin .pfield { position: absolute; box-sizing: border-box; margin: 0; background: transparent; border: 1px solid transparent; color: var(--text); font: 400 14px var(--ui); outline: none; user-select: text; -webkit-user-select: text; }+.plugin textarea.pfield { line-height: 20px; resize: none; }+/* A field's icon, before its text: the player says where. */+.plugin .picon { position: absolute; display: flex; pointer-events: none; color: var(--muted); }+.plugin .picon svg { width: 100%; height: 100%; }+.plugin .pclear { position: absolute; display: flex; align-items: center; justify-content: center; margin: 0; padding: 0; border: 0; background: transparent; color: var(--muted); cursor: pointer; }+.plugin .pclear[hidden] { display: none; }+.plugin .pclear:hover { color: var(--text); }+.plugin .pclear svg { width: 100%; height: 100%; }+.plugin .pfield::placeholder { color: var(--muted); }+/* Taking no typing for the moment a plugin starts again: looking the same. */+.plugin .pfield:disabled { color: var(--text); -webkit-text-fill-color: var(--text); opacity: 1; }+.plugin .pfield[data-font="mono"] { font: 400 13px "ThinkTerm Panel Mono", ui-monospace, Menlo, monospace; }#agents .plugin .msg, #extended .plugin .msg { position: absolute; left: 12px; right: 12px; top: 8px; color: var(--muted); font-size: 13px; }/* A plugin panel's extended view (PluginExtended): the wide area left ofthe panel, the plugin's from its top, as the desktop's is. */diff --git a/wezterm-gui/src/commands.rs b/wezterm-gui/src/commands.rsindex 39e6dbbd..41bdb701 100644--- a/wezterm-gui/src/commands.rs+++ b/wezterm-gui/src/commands.rs@@ -2075,6 +2075,9 @@ pub fn derive_command_from_key_assignment(action: &KeyAssignment) -> Option<Commicon: None,},DisableDefaultAssignment => return None,+ // A plugin's panel shows in the sidebar and nowhere else: not in the+ // palette, whatever key the user gave it.+ FocusPluginPanel(_) => return None,SelectTextAtMouseCursor(mode) => CommandDef {brief: format!("Selects text at the mouse cursor \diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex c0253b36..14c33d57 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -3036,6 +3036,18 @@ pub struct TermWindow {right_sidebar_snippet_listing: thinkterm_snippets::view::Listing,/// The plugin panel on show in this window, while one is.pub(crate) right_sidebar_plugin: Option<ui::plugin_panel::PluginPanel>,+ /// The user's key asked for this plugin's panel to have the keyboard+ /// before the panel was open: it is given it as it opens, and holds+ /// the keyboard meanwhile.+ plugin_panel_focus_asked: Option<String>,+ /// The plugin panel lost the keyboard without the user while they may+ /// have been typing in it: what they press is nobody's -- never the+ /// terminal's -- until they press Escape or somewhere, or leave the+ /// window.+ plugin_panel_keys_held: bool,+ /// What the system was last shown of the plugin field with the+ /// keyboard, on a Mac.+ plugin_field_snapshot: Option<ui::plugin_panel::FieldSnapshot>,/// Whether each domain whose panes the plugin panel was beside runs/// them on this machine: `None` while a look off this thread finds out./// The answer is the domain's, so another pane of one looked at already@@ -4074,6 +4086,7 @@ impl TermWindow {self.clear_workspace_space_swipe_frame_transition();self.right_sidebar_note.native_text_input_snapshot_key = None;window.set_native_text_input_snapshot(None);+ self.plugin_panel_window_blurred();self.right_sidebar_note.freeze_live_source();self.save_right_sidebar_note_now();self.last_mouse_click = None;@@ -4597,6 +4610,9 @@ impl TermWindow {right_sidebar_snippet_scrollbar_visible_until: None,right_sidebar_snippet_listing: Default::default(),right_sidebar_plugin: None,+ plugin_panel_focus_asked: None,+ plugin_panel_keys_held: false,+ plugin_field_snapshot: None,plugin_panel_domains: Vec::new(),plugin_panel_reach: None,right_sidebar_snippet_saving: false,@@ -5181,6 +5197,8 @@ impl TermWindow {self.note_did_edit();}}+ } else {+ self.plugin_field_replace(token, revision, source_range, &text);}window.invalidate();Ok(true)@@ -10928,6 +10946,7 @@ impl TermWindow {OpenSettings => {crate::settings_window::show_from(self.mux_window_id);}+ FocusPluginPanel(plugin) => self.focus_plugin_panel(plugin),QuitAndStopSessionServer => {// The stop happens after the loop ends; the quit itself// goes through the same confirmation as any quit.diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 776aa139..552da6b5 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -1900,6 +1900,7 @@ impl super::TermWindow {pub fn mouse_event_impl(&mut self, event: MouseEvent, context: &dyn WindowOps) {log::trace!("{:?}", event);+ self.plugin_panel_saw_button(&event.kind);if self.recording_overlay_mouse(&event, context) {return;}diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex 742a4277..ee53340b 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -135,6 +135,17 @@ pub enum SvgIcon {}impl SvgIcon {+ /// The icon a plugin's field names: one of those+ /// `thinkterm_plugin_panel::FIELD_ICONS` lists.+ pub fn for_field(name: &str) -> Option<Self> {+ match name {+ "search" => Some(Self::Search),+ "plus" => Some(Self::Plus),+ "pencil" => Some(Self::Pencil),+ _ => None,+ }+ }+/// The icon a plugin's panel names: one of those/// `thinkterm_plugin_panel::ICONS` lists, else the puzzle piece.pub fn for_panel(name: &str) -> Self {diff --git a/wezterm-gui/src/termwindow/ui/plugin_panel.rs b/wezterm-gui/src/termwindow/ui/plugin_panel.rsindex 0fa0f90f..a0aef870 100644--- a/wezterm-gui/src/termwindow/ui/plugin_panel.rs+++ b/wezterm-gui/src/termwindow/ui/plugin_panel.rs@@ -24,6 +24,14 @@//! there: over the connection Files reaches that machine with, and only//! once the user has let ThinkTerm connect to it -- in Files, or with the//! button the panel shows in place of what the plugin drew until then.+//!+//! The panel's fields are edited here (`field`), and it has the keyboard+//! only when the user gives it: a press in one of its fields, or the key+//! the user chose for it (`FocusPluginPanel`).++mod field;++pub(crate) use field::FieldSnapshot;use crate::plugins::{self, PanelNews};use crate::quad::{HeapQuadAllocator, QuadClipRect, QuadTrait, TripleLayerQuadAllocator};@@ -37,7 +45,7 @@ use crate::termwindow::render::corners::{TOP_LEFT_ROUNDED_CORNER_OUTLINE, TOP_RIGHT_ROUNDED_CORNER_OUTLINE,};use crate::termwindow::{TermWindow, TermWindowNotif, UIItem, UIItemType};-use crate::ui::UiPalette;+use crate::ui::{SvgIcon, UiPalette};use crate::utilsprites::RenderMetrics;use crate::workspace_threads;use anyhow::Context;@@ -51,10 +59,13 @@ use std::rc::Rc;use std::sync::{Arc, OnceLock};use std::time::{Duration, Instant};use thinkterm_plugin_channel::wire::{PanelRequest, Raw};+use thinkterm_plugin_panel::player::{+ field_clear_at, field_icon, field_radius, FIELD_ICON, FIELD_INSET,+};use thinkterm_plugin_panel::{- Align, Answer, Area, Ask, Bounds, Button, Bytes, CloseButton, Color, Cursor, Draw, Drawn,- Entry, EntryKind, Env, Font, Input, Line, Mods, MonoMetrics, Player, Rect, Remote, Size, Text,- TextMetrics, Token,+ feature, Align, Answer, Area, Ask, Bounds, Button, Bytes, CloseButton, Color, Cursor, Draw,+ Drawn, Entry, EntryKind, Env, FieldPart, Font, Input, Line, Mods, MonoMetrics, Player, Rect,+ Remote, Size, Text, TextMetrics, Token,};use url::Url;use wezterm_font::LoadedFont;@@ -101,6 +112,9 @@ pub(crate) struct PluginPanel {/// The user closed the extended view with its close button: it is not/// opened again until the panel's frames have stopped asking for it.dismissed: bool,+ /// A field text is being selected in by dragging: in the extended view+ /// or the panel, and which.+ selecting: Option<(bool, String)>,}/// A view the host serves this window -- a panel, or its extended view --@@ -123,6 +137,11 @@ struct Shown {/// Its plugin asked something of the machine beside it, which ThinkTerm/// may not connect to yet: shown instead of what it drew.connect: Option<Connect>,+ /// Its fields as they are edited here, by id; one for each field the+ /// player has, and let go with it.+ editors: std::collections::HashMap<String, field::Editor>,+ /// Counts edits and caret moves, which what was recorded is painted for.+ edits: u64,}/// A machine a plugin needs ThinkTerm connected to, and the source Files@@ -172,6 +191,8 @@ impl Shown {env_told: Instant::now(),env_due: false,connect: None,+ editors: std::collections::HashMap::new(),+ edits: 0,}}@@ -198,6 +219,15 @@ impl PluginPanel {&& !self.dismissed&& !matches!(self.shown.status, Status::Stopped(_))}++ /// Whether the panel or its extended view has the keyboard.+ pub(crate) fn has_keyboard(&self) -> bool {+ self.shown.player.has_keyboard()+ || self+ .extended+ .as_ref()+ .is_some_and(|(extended, _)| extended.player.has_keyboard())+ }}/// A painting recorded as quads, a heap for each region it is cut to.@@ -210,6 +240,8 @@ struct Painted {#[derive(PartialEq)]struct PaintKey {revision: u64,+ /// What was typed, and where the caret is.+ edits: u64,origin: (f32, f32),scale: f32,window: (usize, usize),@@ -407,17 +439,19 @@ impl TermWindow {return Ok(());};let area = (content_x, content_top, content_width);- let painted = self.paint_plugin_view(- layers,- &mut panel.shown,- false,- area,- scale,- ui_font,- ui_metrics,- fonts,- &chrome,- );+ let painted = self+ .paint_plugin_view(+ layers,+ &mut panel.shown,+ false,+ area,+ scale,+ ui_font,+ ui_metrics,+ fonts,+ &chrome,+ )+ .and_then(|()| self.paint_plugin_view_ring(layers, &panel.shown, &chrome));self.right_sidebar_plugin = Some(panel);painted}@@ -473,9 +507,11 @@ impl TermWindow {};let area = (content_x, content_top, content_width);let painted = match panel.extended.as_mut() {- Some((extended, _)) => self.paint_plugin_view(- layers, extended, true, area, scale, ui_font, ui_metrics, fonts, &chrome,- ),+ Some((extended, _)) => self+ .paint_plugin_view(+ layers, extended, true, area, scale, ui_font, ui_metrics, fonts, &chrome,+ )+ .and_then(|()| self.paint_plugin_view_ring(layers, extended, &chrome)),None => Ok(()),};self.right_sidebar_plugin = Some(panel);@@ -604,12 +640,24 @@ impl TermWindow {/// changed, the last of those within [`ENV_EVERY`]; and opens a panel/// the host closed again once it is time.fn follow_plugin_panel(&mut self, plugin: &str, env: Env) {+ // The user's key asked for another plugin's panel, which is not on+ // show: that ask is gone.+ if self+ .plugin_panel_focus_asked+ .as_deref()+ .is_some_and(|asked| asked != plugin)+ {+ self.plugin_panel_focus_asked = None;+ }if self.right_sidebar_plugin.as_ref().is_some_and(|panel| panel.plugin != plugin){+ // Another plugin's: the ask for this one stays, for it to open with.+ let asked = self.plugin_panel_focus_asked.take();self.close_plugin_panel();+ self.plugin_panel_focus_asked = asked;}let Some(panel) = self.right_sidebar_plugin.as_mut() else {let Some(window) = self.window.clone() else {@@ -620,13 +668,21 @@ impl TermWindow {plugin,self.dimensions.dpi,);+ let mut shown = Shown::new(view, Player::new(env));+ // The user's key asked for it before it was open.+ if self.plugin_panel_focus_asked.as_deref() == Some(plugin) {+ self.plugin_panel_focus_asked = None;+ shown.player.focus_panel();+ shown.tell();+ }self.right_sidebar_plugin = Some(PluginPanel {plugin: plugin.to_string(),- shown: Shown::new(view, Player::new(env)),+ shown,opening: 0,extended: None,extended_width,dismissed: false,+ selecting: None,});return;};@@ -634,6 +690,9 @@ impl TermWindow {let shown = &mut panel.shown;if let Status::Again(at) = shown.status {if now >= at {+ // Given the keyboard meanwhile -- the user's key for it --+ // it loses it as it opens again, without the user.+ let lost = shown.player.has_keyboard();shown.player.set_env(env);shown.player.restarted();shown.status = Status::Opening;@@ -641,6 +700,9 @@ impl TermWindow {shown.env_due = false;panel.opening = panel.opening.wrapping_add(1);plugins::reopen_panel(shown.view, &panel.plugin, shown.player.env());+ if lost {+ self.hold_plugin_panel_keys();+ }} else {self.update_next_frame_time(Some(at));}@@ -663,6 +725,7 @@ impl TermWindow {return;};let opening = panel.opening;+ let mut lost = false;match panel.extended.as_mut() {Some((extended, on)) if *on == opening => {if let Some(due) = tell_env(extended, env, Instant::now()) {@@ -675,6 +738,7 @@ impl TermWindow {Some((stale, _)) => {plugins::close_panel(stale.view);let mut player = stale.player;+ lost = player.has_keyboard();player.set_env(env);player.restarted();player@@ -690,6 +754,9 @@ impl TermWindow {panel.extended = Some((Shown::new(view, player), opening));}}+ if lost {+ self.hold_plugin_panel_keys();+ }}/// Opens the right sidebar on plugin `plugin`'s panel, if the sidebar@@ -718,6 +785,8 @@ impl TermWindow {/// Lets go of the panel on show, if one is, and of its extended view:/// the plugin is told, and what they held is freed.pub(crate) fn close_plugin_panel(&mut self) {+ self.plugin_panel_focus_asked = None;+ self.forget_plugin_field_snapshot();if let Some(panel) = self.right_sidebar_plugin.take() {if let Some((extended, _)) = panel.extended {plugins::close_panel(extended.view);@@ -741,6 +810,7 @@ impl TermWindow {let input = Raw::new(&Input::Close);plugins::tell_panel(extended.view, PanelRequest::Input { input });plugins::close_panel(extended.view);+ self.forget_plugin_field_snapshot_of(extended.view);}if let Some(window) = self.window.as_ref() {window.invalidate();@@ -748,7 +818,8 @@ impl TermWindow {self.reflow_right_sidebar_if_width_changed(before);}- /// Lets go of the extended view of the panel on show, if it has one.+ /// Lets go of the extended view of the panel on show, if it has one:+ /// nothing asks for it, or there is no room for it.fn close_plugin_extended(&mut self) {let extended = self.right_sidebar_plugin@@ -756,6 +827,10 @@ impl TermWindow {.and_then(|panel| panel.extended.take());if let Some((extended, _)) = extended {plugins::close_panel(extended.view);+ self.forget_plugin_field_snapshot_of(extended.view);+ if extended.player.has_keyboard() {+ self.hold_plugin_panel_keys();+ }}}@@ -1031,8 +1106,17 @@ impl TermWindow {/// What the host said about the view `view`: the panel on show, or its/// extended view. The terminal is laid out again when the sidebar's- /// width changed with it.+ /// width changed with it. A view that lost the keyboard with it lost it+ /// without the user.pub(crate) fn plugin_panel_heard(&mut self, view: u64, news: PanelNews) {+ let had = self.plugin_panel_has_keyboard();+ self.plugin_panel_hear(view, news);+ if had && !self.plugin_panel_has_keyboard() {+ self.hold_plugin_panel_keys();+ }+ }++ fn plugin_panel_hear(&mut self, view: u64, news: PanelNews) {let news = match news {PanelNews::Remote { id, machine, ask } => {if self.plugin_view_numbered(view).is_none() {@@ -1090,6 +1174,10 @@ impl TermWindow {context: &dyn WindowOps,extended: bool,) {+ // A press in a field, or a drag selecting in one, is the field's.+ if self.plugin_field_mouse(&event, context, extended) {+ return;+ }let Some(shown) = self.plugin_view_mut(extended) else {context.set_cursor(Some(MouseCursor::Arrow));return;@@ -1121,11 +1209,17 @@ impl TermWindow {repaint = true;}}- let cursor = self- .plugin_view_mut(extended)- .and_then(|shown| shown.player.cursor());+ let (px, py) = (event.coords.x as f32, event.coords.y as f32);+ let cursor = self.plugin_view_mut(extended).and_then(|shown| {+ // The button at a field's end is a button.+ match shown.clear_under(px, py) {+ Some(_) => Some(Cursor::Pointer),+ None => shown.player.cursor(),+ }+ });context.set_cursor(Some(match cursor {Some(Cursor::Pointer) => MouseCursor::Hand,+ Some(Cursor::Text) => MouseCursor::Text,Some(Cursor::Arrow) | None => MouseCursor::Arrow,}));if repaint {@@ -1137,6 +1231,10 @@ impl TermWindow {/// its extended view, whichever the pointer is over. True when/// something in it scrolled.pub(crate) fn plugin_panel_wheel(&mut self, event: &MouseEvent, dx: f32, dy: f32) -> bool {+ // Over a field of lines, its lines scroll.+ if let Some(moved) = self.plugin_field_wheel(event, dy) {+ return moved;+ }let Some(panel) = self.right_sidebar_plugin.as_mut() else {return false;};@@ -1212,8 +1310,12 @@ impl TermWindow {fonts: &PanelFonts,chrome: &UiPalette,) -> anyhow::Result<()> {+ // The fields as the player has them now, before what they are+ // painted for is known.+ shown.sync_editors();let key = PaintKey {revision: shown.player.revision(),+ edits: shown.edits,origin: shown.origin,scale: shown.scale,window: (self.dimensions.pixel_width, self.dimensions.pixel_height),@@ -1230,6 +1332,7 @@ impl TermWindow {{// Let go of the last before the next is recorded.shown.painted = None;+ self.lay_out_plugin_fields(shown, fonts)?;let regions = self.record_plugin_panel(shown, fonts, chrome)?;shown.painted = Some(Painted { key, regions });}@@ -1237,6 +1340,9 @@ impl TermWindow {for (clip, heap) in &painted.regions {self.lay_plugin_panel_heap(layers, heap, shown, *clip)?;}+ // Blinking, and the text being composed: painted on top each time.+ self.paint_plugin_field_caret(layers, shown, fonts, chrome)?;+ self.sync_plugin_field_snapshot(shown);Ok(())}@@ -1359,8 +1465,13 @@ impl TermWindow {shown.origin.0 + draw.clip.right * scale,);let spent = match draw.what {- Drawn::Rect(_) | Drawn::Hover(_) | Drawn::Thumb(_) => spend(budget, 1),- Drawn::Text(_) | Drawn::Line(_) | Drawn::Area(_) => true,+ Drawn::Rect(_)+ | Drawn::Hover(_)+ | Drawn::Thumb(_)+ | Drawn::Field(_, FieldPart::Box { .. }) => spend(budget, 1),+ Drawn::Text(_) | Drawn::Line(_) | Drawn::Area(_) | Drawn::Field(_, FieldPart::Text) => {+ true+ }};if !spent {return Ok(());@@ -1454,6 +1565,45 @@ impl TermWindow {let radius = area.width().min(area.height()) / 2.0;self.paint_panel_rect(layers, area, Some(chrome.scrollbar_thumb), None, radius)}+ // A field looks as the sidebar's search does -- round at its+ // ends, its border and its icon before its text as that one's --+ // but for the accent outlining the one with the keyboard: where+ // typing goes must be plain to see.+ Drawn::Field(field, FieldPart::Box { focused, hovered }) => {+ let area = place(field.x, field.y, field.w, field.h);+ let border = if focused {+ chrome.accent+ } else if hovered {+ chrome.separator+ } else {+ chrome.control_border+ };+ let radius = field_radius(field) * scale;+ self.paint_panel_rect(layers, area, Some(chrome.control_bg), Some(border), radius)?;+ let square = |x: f32, y: f32, size: f32| {+ let at = place(x, y, size, size);+ (+ at.min_x().round().max(0.0) as usize,+ at.min_y().round().max(0.0) as usize,+ at.width().round().max(1.0) as usize,+ )+ };+ if let Some(icon) = field_icon(field).and_then(SvgIcon::for_field) {+ let y = field.y + (field.h - FIELD_ICON) / 2.0;+ let (x, y, side) = square(field.x + FIELD_INSET, y, FIELD_ICON);+ self.paint_sidebar_icon(layers, icon, x, y, side, chrome.secondary_text)?;+ }+ // The button that empties it, while it holds something.+ let holds = shown.editors_hold(&field.id);+ if let Some((x, y, size)) = field_clear_at(field).filter(|_| holds) {+ let (x, y, side) = square(x, y, size);+ self.paint_sidebar_icon(layers, SvgIcon::X, x, y, side, chrome.secondary_text)?;+ }+ Ok(())+ }+ Drawn::Field(field, FieldPart::Text) => {+ self.paint_plugin_field_text(layers, shown, field, fonts, chrome, budget)+ }}}@@ -1809,6 +1959,7 @@ fn panel_env(fonts: &PanelFonts, chrome: &UiPalette, width: f32, height: f32, scremote: None,can_extend: false,close: None,+ features: vec![feature::FIELDS.to_string(), feature::KEYS.to_string()],}}@@ -1854,6 +2005,8 @@ fn heard(shown: &mut Shown, plugin: &str, news: PanelNews) {shown.player.frame(frame);shown.status = Status::Open;plugins::tell_panel(shown.view, PanelRequest::Shown);+ // The keyboard may have moved with it, or left with a field.+ shown.tell();send_wanted(shown);}PanelNews::Rows(rows) => {@@ -1867,9 +2020,11 @@ fn heard(shown: &mut Shown, plugin: &str, news: PanelNews) {log::info!("plugin panel {plugin}: {reason}");Status::Stopped(reason)};+ shown.let_go_of_keyboard();}PanelNews::Unreachable(why) => {shown.status = Status::Lost(why);+ shown.let_go_of_keyboard();}// An extended view's: it goes with its panel, which is opened again.PanelNews::Reconnected => {}diff --git a/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs b/wezterm-gui/src/termwindow/ui/plugin_panel/field.rsnew file mode 100644index 00000000..02bb3fe7--- /dev/null+++ b/wezterm-gui/src/termwindow/ui/plugin_panel/field.rs@@ -0,0 +1,1847 @@+//! The fields of a plugin's panel, as this window edits them: what each+//! holds -- taken from the player, and handed back with every change --+//! where its text was laid out when last painted, and the keys, presses and+//! text that edit it. Editing never waits for the plugin.+//!+//! Where the keyboard is, the player decides (`thinkterm_plugin_panel`):+//! a panel has it only once the user pressed in one of its fields, or used+//! the key they chose for it, and gives it back on Escape, a press on the+//! terminal, or going off show. While it has it, what the field with it does+//! not use goes to the player, which sends on the keys the panel takes; the+//! rest are the app's, and never the terminal's. Lost without the user --+//! the plugin let go, the field went, the plugin stopped -- the keyboard+//! goes nowhere until they press Escape or somewhere: what they type next+//! was meant for the panel.++use super::{spend, PanelFonts, PluginPanel, Shown, Status, LAYER};+use crate::termwindow::{RightSidebarMode, TermWindow};+use crate::ui::{EditModifiers, TextInputState, UiPalette};+use crate::utilsprites::RenderMetrics;+use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource};+use std::borrow::Cow;+use std::rc::Rc;+use termwiz::input::{KeyCode as TermKeyCode, Modifiers as TermModifiers};+use thinkterm_plugin_channel::wire::{PanelRequest, Raw};+use thinkterm_plugin_panel::player::{field_clear_at, field_inside, field_limit, FIELD_ICON_GAP};+use thinkterm_plugin_panel::{Field, FieldKind, Font, Keyboard, Mods};+use wezterm_font::LoadedFont;+use window::{+ DeadKeyStatus, MouseButtons, MouseCursor, MouseEvent, MouseEventKind as WMEK, MousePress,+ Point, Rect, RectF, WindowOps,+};++/// Where the tokens of the text a field shows the system start: apart from+/// the Note editor's, so that an edit meant for one is never the other's.+static SNAPSHOT_TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1 << 63);+/// The caret's width, in the UI's units.+const CARET_WIDTH: f32 = 2.0;+/// How much of a field's text, about its caret, the system is shown.+const SNAPSHOT_BYTES: usize = 4096;+/// How thick the outline of a panel with the keyboard is, in the UI's units.+const RING_WIDTH: f32 = 2.0;++/// A field's text as it is edited in this window.+pub(super) struct Editor {+ /// The player's revision of the text this was taken from: taken again+ /// when that moves, the plugin having put text there.+ revision: u32,+ input: TextInputState,+ /// In window pixels: on one line, how far the text is scrolled across;+ /// in one of lines, how far down.+ scroll: f32,+ /// Whether the next layout scrolls the caret into view: after it moved,+ /// and not after the wheel moved the lines.+ follow: bool,+ /// The x a caret going up and down keeps to, from the lines' left.+ goal: Option<f32>,+ layout: Option<FieldLayout>,+}++impl Editor {+ fn new(text: &str, revision: u32) -> Self {+ let mut input = TextInputState::new();+ input.set_text_end(text.to_string());+ Self {+ revision,+ input,+ scroll: 0.0,+ follow: true,+ goal: None,+ layout: None,+ }+ }+}++/// Where a field's text went when it was last painted, in window pixels.+struct FieldLayout {+ /// Where a line's x of 0 is, and the first line's top: scrolled.+ left: f32,+ top: f32,+ line_height: f32,+ /// The box the text shows in.+ inner: RectF,+ lines: Vec<LaidLine>,+ /// Where each line of what the field holds starts, by character.+ starts: Vec<usize>,+}++/// A line as it is laid in the box: the characters it shows, by index in+/// what the field holds, which of the field's lines they are of, and where+/// each boundary from `start` to `end` is, from the line's left.+struct LaidLine {+ start: usize,+ end: usize,+ of: usize,+ xs: Vec<f32>,+}++impl Shown {+ /// Brings the editors in line with the player's fields: one for each,+ /// holding the player's text when the plugin put text there, and none+ /// for a field gone.+ pub(super) fn sync_editors(&mut self) {+ let Self {+ player,+ editors,+ edits,+ ..+ } = self;+ editors.retain(|id, _| player.field(id).is_some());+ for field in player.fields() {+ let Some((text, revision)) = player.field_text(&field.id) else {+ continue;+ };+ if editors+ .get(&field.id)+ .is_some_and(|editor| editor.revision == revision)+ {+ continue;+ }+ editors.insert(field.id.clone(), Editor::new(text, revision));+ *edits += 1;+ }+ }++ /// Tells the plugin what the player decided to: where the keyboard+ /// went, what a field holds, a key.+ pub(super) fn tell(&mut self) {+ for input in self.player.told() {+ let input = Raw::new(&input);+ super::plugins::tell_panel(self.view, PanelRequest::Input { input });+ }+ }++ /// The host no longer serves it: the keyboard goes back, and the plugin,+ /// whose view is gone, is told nothing of it.+ pub(super) fn let_go_of_keyboard(&mut self) {+ self.player.blur();+ self.player.told();+ }++ /// Where the pointer at `x`, `y` in window pixels is, in the view's units,+ /// even outside it.+ fn units(&self, x: f32, y: f32) -> (f32, f32) {+ (+ (x - self.origin.0) / self.scale,+ (y - self.origin.1) / self.scale,+ )+ }++ /// Whether field `id` holds something, as it is edited here.+ pub(super) fn editors_hold(&self, id: &str) -> bool {+ self.editors+ .get(id)+ .is_some_and(|editor| !editor.input.text().is_empty())+ }++ /// The field whose button that empties it is under the pointer at `x`,+ /// `y` in window pixels: the end of a field that has one and holds+ /// something, all of its height.+ pub(super) fn clear_under(&self, x: f32, y: f32) -> Option<String> {+ let (x, y) = self.units(x, y);+ let field = self.player.field_at(x, y)?;+ let (left, _, _) = field_clear_at(field)?;+ let over = x >= left - FIELD_ICON_GAP / 2.0 && x < field.x + field.w;+ (over && self.editors_hold(&field.id)).then(|| field.id.clone())+ }++ /// Where `field`'s text shows, in window pixels.+ fn inner(&self, field: &Field) -> RectF {+ let inside = field_inside(field);+ euclid::rect(+ self.origin.0 + inside.left * self.scale,+ self.origin.1 + inside.top * self.scale,+ inside.width() * self.scale,+ inside.height() * self.scale,+ )+ }+}++/// The text of the field with the keyboard as the system was last shown it+/// (`set_native_text_input_snapshot`), for its press-and-hold accents,+/// dictation and reconversion: whose it is, what it was made from -- the+/// view's edits, and where the text was laid out -- and the token the+/// system's edits of it come back with.+pub(crate) struct FieldSnapshot {+ view: u64,+ field: String,+ edits: u64,+ place: [u32; 7],+ token: u64,+}++impl PluginPanel {+ /// The panel, or its extended view.+ fn view_mut(&mut self, extended: bool) -> Option<&mut Shown> {+ if extended {+ self.extended.as_mut().map(|(extended, _)| extended)+ } else {+ Some(&mut self.shown)+ }+ }++ /// The view with the keyboard, and whether it is the extended one.+ fn keyboard_view(&mut self) -> Option<(&mut Shown, bool)> {+ let extended = self+ .extended+ .as_ref()+ .is_some_and(|(extended, _)| extended.player.has_keyboard());+ let shown = self.view_mut(extended)?;+ shown.player.has_keyboard().then_some((shown, extended))+ }+}++/// What a key did in a field.+enum Act {+ /// The caret or the selection moved.+ Moved,+ /// What the field holds changed.+ Edited,+ Submit,+ Copy,+ Cut,+ Paste,+ /// Not the field's: for the player, by name, when it has one.+ Key(Option<String>),+}++impl TermWindow {+ /// Whether a view of the plugin panel on show has the keyboard -- or is+ /// to have it, the user having asked for the panel with their key before+ /// it opened.+ pub(crate) fn plugin_panel_has_keyboard(&self) -> bool {+ let asked = self.plugin_panel_focus_asked.as_deref().is_some_and(|asked| {+ matches!(self.right_sidebar_mode, RightSidebarMode::Plugin(id) if id.as_str() == asked)+ });+ asked+ || self+ .right_sidebar_plugin+ .as_ref()+ .is_some_and(PluginPanel::has_keyboard)+ }++ /// The keyboard goes back from the plugin panel: the user put it+ /// elsewhere.+ pub(crate) fn release_plugin_panel_keyboard(&mut self) {+ self.plugin_panel_focus_asked = None;+ self.plugin_panel_keys_held = false;+ self.forget_plugin_field_snapshot();+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return;+ };+ panel.selecting = None;+ for extended in [false, true] {+ if let Some(shown) = panel.view_mut(extended) {+ if shown.player.has_keyboard() {+ shown.player.blur();+ shown.tell();+ }+ }+ }+ }++ /// The key the user chose for plugin `plugin`'s panel: the sidebar opens+ /// on it, and it has the keyboard -- in its first field, once it has one.+ /// Pressed again while it has it, the keyboard goes back.+ pub(crate) fn focus_plugin_panel(&mut self, plugin: &str) {+ self.plugin_panel_keys_held = false;+ let on_it = |mode: RightSidebarMode| matches!(mode, RightSidebarMode::Plugin(id) if id.as_str() == plugin);+ if on_it(self.right_sidebar_mode)+ && !self.right_sidebar_collapsed+ && self.plugin_panel_has_keyboard()+ {+ self.release_plugin_panel_keyboard();+ } else {+ self.show_plugin_panel(plugin);+ if !on_it(self.right_sidebar_mode) || self.right_sidebar_collapsed {+ return;+ }+ self.clear_right_sidebar_text_focus();+ match self+ .right_sidebar_plugin+ .as_mut()+ .filter(|panel| panel.plugin == plugin)+ {+ Some(panel) => {+ panel.shown.player.focus_panel();+ panel.shown.tell();+ }+ // Opened as the window paints next, and given it then.+ None => self.plugin_panel_focus_asked = Some(plugin.to_string()),+ }+ }+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ }++ /// The plugin panel lost the keyboard without the user: while this+ /// window has it, what they press next is held from the terminal.+ pub(crate) fn hold_plugin_panel_keys(&mut self) {+ if self.focused.is_some() {+ self.plugin_panel_keys_held = true;+ }+ }++ /// A key pressed while keys are held from the terminal: nobody's, but+ /// for the app's own chords. Escape lets the terminal have the next.+ pub(crate) fn plugin_panel_held_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {+ let plain = EditModifiers::from(mods).plain();+ if plain && key == TermKeyCode::Escape {+ self.plugin_panel_keys_held = false;+ }+ plain+ }++ /// The window lost the keyboard, and the system's view of a field's+ /// text with it: shown again once it is back. A drag ended, and no key+ /// is held any more.+ pub(crate) fn plugin_panel_window_blurred(&mut self) {+ self.plugin_field_snapshot = None;+ self.plugin_panel_keys_held = false;+ if let Some(panel) = self.right_sidebar_plugin.as_mut() {+ panel.selecting = None;+ }+ }++ /// Any press or release in the window, before it goes where it goes. A+ /// press is the user's, whose keys are held no longer; a drag selecting+ /// in a field ends where the button comes up, in the panel or not.+ pub(crate) fn plugin_panel_saw_button(&mut self, kind: &WMEK) {+ if matches!(kind, WMEK::Press(_)) {+ self.plugin_panel_keys_held = false;+ }+ if matches!(kind, WMEK::Press(_) | WMEK::Release(_)) {+ if let Some(panel) = self.right_sidebar_plugin.as_mut() {+ panel.selecting = None;+ }+ }+ }++ /// A key pressed while a view of the plugin panel has the keyboard: the+ /// field with it edits, and what it does not use goes to the player. True+ /// when the panel took it; false for one it did not, which the app's own+ /// keys may have, and the terminal never.+ pub(crate) fn plugin_panel_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {+ let Some(mut panel) = self.right_sidebar_plugin.take() else {+ // Asked for, and not open yet: what is pressed meanwhile is+ // nobody's, and Escape takes the ask back.+ if self.plugin_panel_focus_asked.is_none() {+ return false;+ }+ if key == TermKeyCode::Escape {+ self.plugin_panel_focus_asked = None;+ }+ return EditModifiers::from(mods).plain();+ };+ let handled = self.plugin_panel_key_in(&mut panel, key, mods);+ self.right_sidebar_plugin = Some(panel);+ handled+ }++ fn plugin_panel_key_in(+ &mut self,+ panel: &mut PluginPanel,+ key: TermKeyCode,+ mods: TermModifiers,+ ) -> bool {+ let Some((shown, _)) = panel.keyboard_view() else {+ return false;+ };+ shown.sync_editors();+ let to_player = player_mods(mods);+ let Some(id) = shown.player.focused_field().map(str::to_string) else {+ let taken = key_name(&key).is_some_and(|name| shown.player.key(&name, to_player));+ shown.tell();+ return taken;+ };+ let Some(field) = shown.player.field(&id) else {+ return false;+ };+ let kind = field.kind;+ let limit = field_limit(field);+ let lines = kind == FieldKind::Lines;+ let secret = kind == FieldKind::Secret;+ let Some(editor) = shown.editors.get_mut(&id) else {+ return false;+ };+ let edit = EditModifiers::from(mods);+ let shift = edit.shift;+ let macos = cfg!(target_os = "macos");+ let len = editor.input.char_len();+ // Up and down by a line or a page keep to the x they started from.+ let keeps_goal = lines+ && edit.plain()+ && matches!(+ key,+ TermKeyCode::UpArrow+ | TermKeyCode::DownArrow+ | TermKeyCode::PageUp+ | TermKeyCode::PageDown+ );++ let chord = if edit.command {+ match key {+ TermKeyCode::Char('a') | TermKeyCode::Char('A') => {+ editor.input.caret_select_all();+ Some(Act::Moved)+ }+ TermKeyCode::Char('c') | TermKeyCode::Char('C') => Some(Act::Copy),+ TermKeyCode::Char('x') | TermKeyCode::Char('X') => Some(Act::Cut),+ TermKeyCode::Char('v') | TermKeyCode::Char('V') => Some(Act::Paste),+ TermKeyCode::Enter if lines => Some(Act::Submit),+ // ⌘←, ⌘→ and ⌘⌫ are the line's start and end on a Mac, and+ // ⌘↑, ⌘↓ the whole text's; elsewhere Ctrl+Home and Ctrl+End.+ TermKeyCode::LeftArrow if macos => {+ line_home(editor, shift);+ Some(Act::Moved)+ }+ TermKeyCode::RightArrow if macos => {+ line_end(editor, shift);+ Some(Act::Moved)+ }+ TermKeyCode::UpArrow if macos && lines => {+ editor.input.caret_set(0, shift);+ Some(Act::Moved)+ }+ TermKeyCode::DownArrow if macos && lines => {+ editor.input.caret_set(len, shift);+ Some(Act::Moved)+ }+ TermKeyCode::Home if !macos => {+ editor.input.caret_set(0, shift);+ Some(Act::Moved)+ }+ TermKeyCode::End if !macos => {+ editor.input.caret_set(len, shift);+ Some(Act::Moved)+ }+ TermKeyCode::Backspace if macos => {+ delete_to_line_start(editor);+ Some(Act::Edited)+ }+ _ => None,+ }+ } else {+ None+ };+ // Word by word: ⌥ on a Mac, Ctrl elsewhere.+ let chord = chord.or_else(|| {+ if !edit.word {+ return None;+ }+ match key {+ TermKeyCode::LeftArrow => {+ editor.input.caret_word_left(shift);+ Some(Act::Moved)+ }+ TermKeyCode::RightArrow => {+ editor.input.caret_word_right(shift);+ Some(Act::Moved)+ }+ TermKeyCode::Backspace => {+ editor.input.caret_delete_word_back();+ Some(Act::Edited)+ }+ _ => None,+ }+ });+ let act = match chord {+ Some(act) => act,+ // Any chord the field does not use is the app's.+ None if !edit.plain() => return false,+ None => match key {+ TermKeyCode::LeftArrow => {+ editor.input.caret_move_left(shift);+ Act::Moved+ }+ TermKeyCode::RightArrow => {+ editor.input.caret_move_right(shift);+ Act::Moved+ }+ TermKeyCode::Home => {+ line_home(editor, shift);+ Act::Moved+ }+ TermKeyCode::End => {+ line_end(editor, shift);+ Act::Moved+ }+ TermKeyCode::UpArrow if lines => {+ vertical(editor, -1, shift);+ Act::Moved+ }+ TermKeyCode::DownArrow if lines => {+ vertical(editor, 1, shift);+ Act::Moved+ }+ TermKeyCode::PageUp if lines => {+ let rows = page_rows(editor);+ vertical(editor, -rows, shift);+ Act::Moved+ }+ TermKeyCode::PageDown if lines => {+ let rows = page_rows(editor);+ vertical(editor, rows, shift);+ Act::Moved+ }+ TermKeyCode::Delete => {+ editor.input.caret_delete_forward();+ Act::Edited+ }+ TermKeyCode::Backspace => {+ editor.input.caret_backspace();+ Act::Edited+ }+ TermKeyCode::Enter if lines => {+ insert(&mut editor.input, "\n", limit, lines);+ Act::Edited+ }+ TermKeyCode::Enter => Act::Submit,+ TermKeyCode::Char(ch) if !ch.is_control() => {+ insert(&mut editor.input, &ch.to_string(), limit, lines);+ Act::Edited+ }+ other => Act::Key(key_name(&other)),+ },+ };++ let taken = match act {+ Act::Moved | Act::Edited => {+ if !keeps_goal {+ editor.goal = None;+ }+ editor.follow = true;+ shown.edits += 1;+ if matches!(act, Act::Edited) {+ shown.player.edit_field(&id, editor.input.text());+ }+ true+ }+ Act::Submit => {+ shown.player.submit(&id);+ true+ }+ Act::Copy => {+ // Nothing leaves a secret field.+ if !secret {+ let text = copied(&editor.input);+ if !text.is_empty() {+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);+ }+ }+ true+ }+ Act::Cut => {+ if !secret {+ let text = match editor.input.caret_take_selected_text() {+ Some(text) => text,+ None => {+ let text = editor.input.text().to_string();+ editor.input.clear();+ text+ }+ };+ if !text.is_empty() {+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);+ }+ editor.follow = true;+ shown.edits += 1;+ shown.player.edit_field(&id, editor.input.text());+ }+ true+ }+ Act::Paste => {+ self.paste_into_right_sidebar_from_clipboard(ClipboardPasteSource::Clipboard);+ true+ }+ Act::Key(Some(name)) => shown.player.key(&name, to_player),+ Act::Key(None) => false,+ };+ shown.tell();+ taken+ }++ /// Text that arrived for the plugin panel with the keyboard -- composed,+ /// or pasted: put in the field with it. True when the panel has the+ /// keyboard, in a field or not: it goes nowhere else.+ pub(crate) fn plugin_panel_text(&mut self, text: &str) -> bool {+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return self.plugin_panel_focus_asked.is_some();+ };+ let Some((shown, _)) = panel.keyboard_view() else {+ return false;+ };+ shown.sync_editors();+ let Some(id) = shown.player.focused_field().map(str::to_string) else {+ return true;+ };+ let Some(field) = shown.player.field(&id) else {+ return true;+ };+ let (limit, lines) = (field_limit(field), field.kind == FieldKind::Lines);+ if let Some(editor) = shown.editors.get_mut(&id) {+ insert(&mut editor.input, text, limit, lines);+ editor.follow = true;+ editor.goal = None;+ shown.player.edit_field(&id, editor.input.text());+ shown.edits += 1;+ }+ shown.tell();+ true+ }++ /// Copies what is selected in the field with the keyboard, or all of+ /// it -- not out of a secret one.+ pub(crate) fn plugin_panel_copy(&mut self, destination: ClipboardCopyDestination) {+ let text = self.right_sidebar_plugin.as_mut().and_then(|panel| {+ let (shown, _) = panel.keyboard_view()?;+ let id = shown.player.focused_field()?;+ let field = shown.player.field(id)?;+ if field.kind == FieldKind::Secret {+ return None;+ }+ Some(copied(&shown.editors.get(id)?.input))+ });+ if let Some(text) = text.filter(|text| !text.is_empty()) {+ self.copy_to_clipboard(destination, text);+ }+ }++ /// The selection in the field with the keyboard goes.+ pub(crate) fn plugin_panel_clear_selection(&mut self) {+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return;+ };+ let Some((shown, _)) = panel.keyboard_view() else {+ return;+ };+ let Some(id) = shown.player.focused_field().map(str::to_string) else {+ return;+ };+ if let Some(editor) = shown.editors.get_mut(&id) {+ editor.input.clear_selection();+ shown.edits += 1;+ }+ }++ /// Shows the system the text of view `shown`'s field with the keyboard,+ /// on a Mac, for what it does with text -- press and hold for an accent,+ /// dictation -- when it changed; or takes back what it showed of the view+ /// once no field of it has the keyboard. A secret field's is never shown.+ pub(super) fn sync_plugin_field_snapshot(&mut self, shown: &Shown) {+ if !cfg!(target_os = "macos") {+ return;+ }+ let focused = shown.player.focused_field().and_then(|id| {+ let field = shown.player.field(id)?;+ let editor = shown.editors.get(id)?;+ let layout = editor.layout.as_ref()?;+ (field.kind != FieldKind::Secret).then_some((id, editor, layout))+ });+ let Some((id, editor, layout)) = focused else {+ if self+ .plugin_field_snapshot+ .as_ref()+ .is_some_and(|held| held.view == shown.view)+ {+ self.forget_plugin_field_snapshot();+ }+ return;+ };+ // Every change to what a field holds, its caret or its scroll counts+ // as an edit of the view; a move, a new width or a new font moves+ // its text.+ let inner = layout.inner;+ let place = [+ layout.left,+ layout.top,+ layout.line_height,+ inner.min_x(),+ inner.min_y(),+ inner.width(),+ inner.height(),+ ]+ .map(f32::to_bits);+ if self.plugin_field_snapshot.as_ref().is_some_and(|held| {+ held.view == shown.view+ && held.field == id+ && held.edits == shown.edits+ && held.place == place+ }) {+ return;+ }+ let text = editor.input.text();+ let byte_of = |at: usize| text.char_indices().nth(at).map_or(text.len(), |(at, _)| at);+ let (from, to) = editor+ .input+ .caret_selection_range()+ .unwrap_or((editor.input.cursor, editor.input.cursor));+ let caret = byte_of(editor.input.cursor);+ let (mut selection, mut start, mut end) = (byte_of(from)..byte_of(to), 0, text.len());+ // Only the text about the caret, as the Note editor shows it: what+ // the system does with text wants no more, and a field of lines+ // holds tens of kilobytes.+ if text.len() > SNAPSHOT_BYTES {+ start = caret.saturating_sub(SNAPSHOT_BYTES / 2);+ end = (start + SNAPSHOT_BYTES).min(text.len());+ start = end.saturating_sub(SNAPSHOT_BYTES);+ while start > 0 && !text.is_char_boundary(start) {+ start -= 1;+ }+ while end > start && !text.is_char_boundary(end) {+ end -= 1;+ }+ if selection.start < start || selection.end > end {+ selection = caret..caret;+ }+ }+ // Each character of it, where it was laid out.+ let first = text[..start].chars().count();+ let bytes: Vec<usize> = text[start..end]+ .char_indices()+ .map(|(at, _)| at)+ .chain([end - start])+ .collect();+ let mut hits = Vec::new();+ for (row, line) in layout.lines.iter().enumerate() {+ if line.end < first || line.start > first + bytes.len() {+ continue;+ }+ let top = layout.top + row as f32 * layout.line_height;+ for (at, x) in line.xs.iter().enumerate() {+ let Some(byte) = (line.start + at)+ .checked_sub(first)+ .and_then(|at| bytes.get(at))+ else {+ continue;+ };+ hits.push(window::NativeTextHit {+ rect: Rect::new(+ Point::new((layout.left + x) as isize, top as isize),+ window::Size::new(1, layout.line_height.max(1.0) as isize),+ ),+ byte: *byte,+ });+ }+ }+ let token = SNAPSHOT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ if let Some(window) = self.window.as_ref() {+ window.set_native_text_input_snapshot(Some(window::NativeTextInputSnapshot {+ token,+ revision: text_revision(text),+ source_base: start,+ text: text[start..end].to_string(),+ selection: selection.start - start..selection.end - start,+ hits,+ }));+ }+ self.plugin_field_snapshot = Some(FieldSnapshot {+ view: shown.view,+ field: id.to_string(),+ edits: shown.edits,+ place,+ token,+ });+ }++ /// Takes back the text of a field of view `view` the system was shown,+ /// if it was one of its: the view went.+ pub(crate) fn forget_plugin_field_snapshot_of(&mut self, view: u64) {+ if self+ .plugin_field_snapshot+ .as_ref()+ .is_some_and(|held| held.view == view)+ {+ self.forget_plugin_field_snapshot();+ }+ }++ /// Takes back the text of a plugin's field the system was shown.+ pub(crate) fn forget_plugin_field_snapshot(&mut self) {+ if self.plugin_field_snapshot.take().is_some() {+ if let Some(window) = self.window.as_ref() {+ window.set_native_text_input_snapshot(None);+ }+ }+ }++ /// The system edited the text of the field it was shown -- an accent+ /// held for, words dictated: bytes `range` of it, as it was at+ /// `revision`, are `text` now. One for a field without the keyboard+ /// since, or text since changed, is not taken. False when the edit is+ /// no field's.+ pub(crate) fn plugin_field_replace(+ &mut self,+ token: u64,+ revision: u64,+ range: std::ops::Range<usize>,+ text: &str,+ ) -> bool {+ let Some((view, shown_field)) = self+ .plugin_field_snapshot+ .as_ref()+ .filter(|held| held.token == token)+ .map(|held| (held.view, held.field.clone()))+ else {+ return false;+ };+ let Some(panel) = self.right_sidebar_plugin.as_mut() else {+ return true;+ };+ let shown = if panel.shown.view == view {+ &mut panel.shown+ } else {+ match panel+ .extended+ .as_mut()+ .filter(|(extended, _)| extended.view == view)+ {+ Some((extended, _)) => extended,+ None => return true,+ }+ };+ let Some(id) = shown+ .player+ .focused_field()+ .filter(|id| *id == shown_field)+ .map(str::to_string)+ else {+ return true;+ };+ let Some(field) = shown.player.field(&id) else {+ return true;+ };+ if field.kind == FieldKind::Secret {+ return true;+ }+ let (limit, lines) = (field_limit(field), field.kind == FieldKind::Lines);+ let Some(editor) = shown.editors.get_mut(&id) else {+ return true;+ };+ let now = editor.input.text();+ if text_revision(now) != revision+ || range.start > range.end+ || !now.is_char_boundary(range.start)+ || !now.is_char_boundary(range.end.min(now.len()))+ || range.end > now.len()+ {+ return true;+ }+ let from = now[..range.start].chars().count();+ let to = from + now[range].chars().count();+ editor.input.caret_set(from, false);+ editor.input.caret_set(to, true);+ insert(&mut editor.input, text, limit, lines);+ editor.follow = true;+ editor.goal = None;+ shown.player.edit_field(&id, editor.input.text());+ shown.edits += 1;+ shown.tell();+ if let Some(window) = self.window.as_ref() {+ window.invalidate();+ }+ true+ }++ /// A press in a field gives it the keyboard and puts the caret there --+ /// a second selects the word, a third the line -- and a drag from it+ /// selects. True when the event was a field's.+ pub(super) fn plugin_field_mouse(+ &mut self,+ event: &MouseEvent,+ context: &dyn WindowOps,+ extended: bool,+ ) -> bool {+ let Some(mut panel) = self.right_sidebar_plugin.take() else {+ return false;+ };+ let streak = match &self.last_mouse_click {+ Some(click) => click.streak,+ None => 1,+ };+ let taken = plugin_field_mouse_in(&mut panel, event, extended, streak);+ self.right_sidebar_plugin = Some(panel);+ if taken {+ context.set_cursor(Some(MouseCursor::Text));+ context.invalidate();+ }+ taken+ }++ /// The wheel over a field of lines with more than it shows scrolls its+ /// lines: whether they moved. `None` when it is not over one.+ pub(super) fn plugin_field_wheel(&mut self, event: &MouseEvent, dy: f32) -> Option<bool> {+ let panel = self.right_sidebar_plugin.as_mut()?;+ let (px, py) = (event.coords.x as f32, event.coords.y as f32);+ let over_extended = panel+ .extended+ .as_ref()+ .is_some_and(|(extended, _)| extended.under(px, py).is_some());+ let shown = panel.view_mut(over_extended)?;+ let (x, y) = shown.under(px, py)?;+ let field = shown.player.field_at(x, y)?;+ if field.kind != FieldKind::Lines {+ return None;+ }+ let id = field.id.clone();+ let editor = shown.editors.get_mut(&id)?;+ let layout = editor.layout.as_ref()?;+ let content = layout.lines.len() as f32 * layout.line_height;+ let room = (content - layout.inner.height()).max(0.0);+ if room <= 0.0 {+ return None;+ }+ let before = editor.scroll;+ editor.scroll = (before + dy).clamp(0.0, room);+ editor.follow = false;+ let moved = editor.scroll != before;+ if moved {+ shown.edits += 1;+ }+ Some(moved)+ }++ /// Lays out what each field of `shown` holds, where it is: one line+ /// scrolled across, or lines wrapped at the box's width and scrolled+ /// down, so the caret of the one with the keyboard shows.+ pub(super) fn lay_out_plugin_fields(+ &self,+ shown: &mut Shown,+ fonts: &PanelFonts,+ ) -> anyhow::Result<()> {+ shown.sync_editors();+ let focused = shown.player.focused_field().map(str::to_string);+ let ids: Vec<String> = shown+ .player+ .fields()+ .map(|field| field.id.clone())+ .collect();+ for id in ids {+ let Some(field) = shown.player.field(&id) else {+ continue;+ };+ let inner = shown.inner(field);+ let focused = focused.as_deref() == Some(id.as_str());+ let kind = field.kind;+ let font = font_of(fonts, field.font);+ let Some(editor) = shown.editors.get_mut(&id) else {+ continue;+ };+ let layout = self.lay_out_field(kind, editor, font, inner, focused)?;+ editor.layout = Some(layout);+ }+ Ok(())+ }++ fn lay_out_field(+ &self,+ kind: FieldKind,+ editor: &mut Editor,+ (font, metrics): &(Rc<LoadedFont>, RenderMetrics),+ inner: RectF,+ focused: bool,+ ) -> anyhow::Result<FieldLayout> {+ let line_height = metrics.cell_size.height as f32;+ let caret_width = self.ui_f32(CARET_WIDTH).max(1.0);+ let text = shown_text(kind, editor.input.text());+ let wrap = (kind == FieldKind::Lines).then(|| (inner.width() - caret_width).max(1.0));+ let mut lines = Vec::new();+ let mut starts = Vec::new();+ let mut base = 0;+ for (of, line) in text.split('\n').enumerate() {+ starts.push(base);+ let xs = self.boundaries(font, metrics, line)?;+ let count = xs.len() - 1;+ match wrap {+ Some(width) => wrap_line(&mut lines, line, &xs, base, of, width),+ None => lines.push(LaidLine {+ start: base,+ end: base + count,+ of,+ xs,+ }),+ }+ base += count + 1;+ }+ let (row, caret_x) = caret_at(&lines, editor.input.cursor);+ let follow = std::mem::take(&mut editor.follow) && focused;+ let (left, top) = if kind == FieldKind::Lines {+ let content = lines.len() as f32 * line_height;+ if follow {+ let caret_top = row as f32 * line_height;+ if caret_top < editor.scroll {+ editor.scroll = caret_top;+ }+ if caret_top + line_height > editor.scroll + inner.height() {+ editor.scroll = caret_top + line_height - inner.height();+ }+ }+ editor.scroll = editor+ .scroll+ .clamp(0.0, (content - inner.height()).max(0.0));+ (inner.min_x(), inner.min_y() - editor.scroll)+ } else {+ let wide = lines.first().and_then(|line| line.xs.last()).copied();+ let room = (inner.width() - caret_width).max(0.0);+ if !focused {+ editor.scroll = 0.0;+ } else if follow {+ if caret_x - editor.scroll > room {+ editor.scroll = caret_x - room;+ }+ if caret_x < editor.scroll {+ editor.scroll = caret_x;+ }+ }+ editor.scroll = editor+ .scroll+ .clamp(0.0, (wide.unwrap_or(0.0) - room).max(0.0));+ let top = inner.min_y() + ((inner.height() - line_height) / 2.0).round();+ (inner.min_x() - editor.scroll, top)+ };+ Ok(FieldLayout {+ left,+ top,+ line_height,+ inner,+ lines,+ starts,+ })+ }++ /// Where each boundary between the characters of `text` is when it is+ /// set on one line, from its left: as many as it has characters, and+ /// one. The characters inside a cluster -- a ligature's -- share the+ /// cluster's start.+ fn boundaries(+ &self,+ font: &Rc<LoadedFont>,+ metrics: &RenderMetrics,+ text: &str,+ ) -> anyhow::Result<Vec<f32>> {+ let starts: Vec<usize> = text.char_indices().map(|(at, _)| at).collect();+ let count = starts.len();+ let mut xs: Vec<Option<f32>> = vec![None; count + 1];+ xs[0] = Some(0.0);+ if count > 0 {+ let (shaped, _) = self.cached_ui_shape(font, metrics, text)?;+ let mut x = 0.0;+ for info in shaped.iter() {+ let at = starts.partition_point(|start| *start < info.cluster);+ if let Some(slot) = xs.get_mut(at).filter(|slot| slot.is_none()) {+ *slot = Some(x);+ }+ x += info.glyph.x_advance.get() as f32;+ }+ xs[count] = Some(x);+ }+ let mut last = 0.0;+ Ok(xs+ .into_iter()+ .map(|x| {+ last = x.unwrap_or(last).max(last);+ last+ })+ .collect())+ }++ /// What field `field` of `shown` holds -- or, empty and without the+ /// keyboard, its placeholder -- and what is selected, as laid out:+ /// recorded with the panel, cut to inside the box.+ pub(super) fn paint_plugin_field_text(+ &self,+ layers: &mut crate::quad::TripleLayerQuadAllocator,+ shown: &Shown,+ field: &Field,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ budget: &mut usize,+ ) -> anyhow::Result<()> {+ let Some(editor) = shown.editors.get(&field.id) else {+ return Ok(());+ };+ let Some(layout) = editor.layout.as_ref() else {+ return Ok(());+ };+ let (font, metrics) = font_of(fonts, field.font);+ let inner = layout.inner;+ let focused = shown.player.focused_field() == Some(field.id.as_str());+ let text = editor.input.text();+ if text.is_empty() {+ if focused || field.placeholder.is_empty() {+ return Ok(());+ }+ let placeholder = match field.font {+ Font::Ui => {+ self.ellipsize_ui_text(font, &field.placeholder, inner.width() as usize)?+ }+ Font::Mono => Cow::Borrowed(field.placeholder.as_str()),+ };+ let (shaped, _) = self.cached_ui_shape(font, metrics, &placeholder)?;+ if !spend(budget, shaped.len()) {+ return Ok(());+ }+ let faint = chrome.secondary_text.mul_alpha(0.72);+ self.paint_cached_ui_shape_pixel_clipped(+ layers,+ metrics,+ &shaped,+ inner.min_x(),+ layout.top,+ inner.min_x(),+ inner.max_x(),+ |_| faint,+ )?;+ return Ok(());+ }+ let shown_text = shown_text(field.kind, text);+ let pieces: Vec<&str> = shown_text.split('\n').collect();+ let selection = editor.input.caret_selection_range();+ let selected = chrome.selected_bg.mul_alpha(0.55);+ for (row, line) in layout.lines.iter().enumerate() {+ let top = layout.top + row as f32 * layout.line_height;+ if top + layout.line_height <= inner.min_y() || top >= inner.max_y() {+ continue;+ }+ if let Some((from, to)) = selection {+ let (a, b) = (from.max(line.start), to.min(line.end));+ // A selection going on past a line's end takes a little of+ // the line's end with it: the line break it selects.+ let on = layout+ .lines+ .get(row + 1)+ .is_some_and(|next| next.start > line.end)+ && to > line.end+ && from <= line.end;+ if a < b || on {+ let left = layout.left + line.xs[a.min(line.end) - line.start];+ let mut right = layout.left + line.xs[b.max(a).min(line.end) - line.start];+ if on {+ right += layout.line_height / 3.0;+ }+ let left = left.max(inner.min_x());+ let right = right.min(inner.max_x());+ if right > left && spend(budget, 1) {+ let area: RectF = euclid::rect(left, top, right - left, layout.line_height);+ self.filled_rectangle(layers, LAYER, area, selected)?;+ }+ }+ }+ if line.end == line.start {+ continue;+ }+ let piece = pieces.get(line.of).copied().unwrap_or_default();+ let (shaped, _) = self.cached_ui_shape(font, metrics, piece)?;+ let starts: Vec<usize> = piece.char_indices().map(|(at, _)| at).collect();+ let char_of = |cluster: usize| starts.partition_point(|start| *start < cluster);+ let base = layout.starts.get(line.of).copied().unwrap_or(0);+ let (from, to) = (line.start - base, line.end - base);+ let first = shaped.partition_point(|info| char_of(info.cluster) < from);+ let last = shaped.partition_point(|info| char_of(info.cluster) < to);+ let glyphs = &shaped[first..last.max(first)];+ if !spend(budget, glyphs.len()) {+ return Ok(());+ }+ self.paint_cached_ui_shape_pixel_clipped(+ layers,+ metrics,+ glyphs,+ layout.left,+ top,+ inner.min_x(),+ inner.max_x(),+ |_| chrome.text,+ )?;+ }+ Ok(())+ }++ /// The outline of a view with the keyboard in none of its fields --+ /// given it by the user's key -- over whatever it shows.+ pub(super) fn paint_plugin_view_ring(+ &self,+ layers: &mut crate::quad::TripleLayerQuadAllocator,+ shown: &Shown,+ chrome: &UiPalette,+ ) -> anyhow::Result<()> {+ if shown.player.keyboard() != &Keyboard::Panel {+ return Ok(());+ }+ let env = shown.player.env();+ let area: RectF = euclid::rect(+ shown.origin.0,+ shown.origin.1,+ env.width * shown.scale,+ env.height * shown.scale,+ );+ let ring = self.ui_f32(RING_WIDTH).max(1.0);+ self.stroke_panel_rect(layers, area, chrome.accent, 0.0, ring)+ }++ /// Over what was recorded, each time it is painted: the caret of the+ /// field with the keyboard, blinking, or the text being composed there,+ /// with the input method's candidates put by it.+ pub(super) fn paint_plugin_field_caret(+ &self,+ layers: &mut crate::quad::TripleLayerQuadAllocator,+ shown: &Shown,+ fonts: &PanelFonts,+ chrome: &UiPalette,+ ) -> anyhow::Result<()> {+ let Some(id) = shown.player.focused_field() else {+ return Ok(());+ };+ let (Some(field), Some(editor)) = (shown.player.field(id), shown.editors.get(id)) else {+ return Ok(());+ };+ let Some(layout) = editor.layout.as_ref() else {+ return Ok(());+ };+ let (font, metrics) = font_of(fonts, field.font);+ let inner = layout.inner;+ let caret_width = self.ui_f32(CARET_WIDTH).max(1.0);+ let (row, x) = caret_at(&layout.lines, editor.input.cursor);+ let left = (layout.left + x).clamp(+ inner.min_x(),+ (inner.max_x() - caret_width).max(inner.min_x()),+ );+ let top = layout.top + row as f32 * layout.line_height;+ if top + layout.line_height <= inner.min_y() || top >= inner.max_y() {+ return Ok(());+ }+ if let Some(window) = self.window.as_ref() {+ window.set_text_cursor_position(Rect::new(+ Point::new(left as isize, top as isize),+ metrics.cell_size,+ ));+ }+ if let DeadKeyStatus::Composing(composing) = &self.dead_key_status {+ // A secret field's shows as dots too, being composed.+ let composing = shown_text(field.kind, composing);+ let (shaped, _) = self.cached_ui_shape(font, metrics, &composing)?;+ let wide = self+ .paint_cached_ui_shape_pixel_clipped(+ layers,+ metrics,+ &shaped,+ left,+ top,+ left,+ inner.max_x(),+ |_| chrome.text,+ )?+ .min(inner.max_x() - left);+ if wide > 0.0 {+ let under: RectF = euclid::rect(left, top + layout.line_height - 1.0, wide, 1.0);+ self.filled_rectangle(layers, LAYER, under, chrome.text)?;+ }+ return Ok(());+ }+ if editor.input.caret_selection_range().is_some() || !self.right_sidebar_snippet_cursor_on()+ {+ return Ok(());+ }+ let visible_top = top.max(inner.min_y());+ let visible_bottom = (top + layout.line_height).min(inner.max_y());+ let caret: RectF =+ euclid::rect(left, visible_top, caret_width, visible_bottom - visible_top);+ self.filled_rectangle(layers, LAYER, caret, chrome.text)?;+ Ok(())+ }+}++/// [`TermWindow::plugin_field_mouse`], with the panel in hand.+fn plugin_field_mouse_in(+ panel: &mut PluginPanel,+ event: &MouseEvent,+ extended: bool,+ streak: usize,+) -> bool {+ let (px, py) = (event.coords.x as f32, event.coords.y as f32);+ match event.kind {+ WMEK::Press(MousePress::Left) => {+ let Some(shown) = panel.view_mut(extended) else {+ return false;+ };+ // What a program that stopped, or is starting again, last drew+ // takes no typing: there is nobody to hear it.+ if !matches!(shown.status, Status::Open) {+ return false;+ }+ let (x, y) = shown.units(px, py);+ let Some(id) = shown.player.field_at(x, y).map(|field| field.id.clone()) else {+ return false;+ };+ let clearing = shown.clear_under(px, py).is_some();+ // The keyboard comes to this view: the other lets go of it.+ if let Some(other) = panel.view_mut(!extended) {+ if other.player.has_keyboard() {+ other.player.blur();+ other.tell();+ }+ }+ let Some(shown) = panel.view_mut(extended) else {+ return false;+ };+ shown.sync_editors();+ let again = shown.player.focused_field() == Some(id.as_str());+ shown.player.focus_field(&id);+ // Its button empties it, and leaves the keyboard in it.+ if clearing {+ if let Some(editor) = shown.editors.get_mut(&id) {+ editor.input.clear();+ editor.goal = None;+ editor.follow = true;+ }+ shown.player.edit_field(&id, "");+ shown.edits += 1;+ shown.tell();+ return true;+ }+ let lines = shown+ .player+ .field(&id)+ .is_some_and(|field| field.kind == FieldKind::Lines);+ if let Some(editor) = shown.editors.get_mut(&id) {+ let at = editor+ .layout+ .as_ref()+ .map_or(editor.input.char_len(), |layout| index_at(layout, px, py));+ let extend = again && event.modifiers.contains(window::Modifiers::SHIFT);+ match streak {+ 0 | 1 => editor.input.caret_set(at, extend),+ 2 => {+ editor.input.caret_set(at, false);+ editor.input.caret_select_word();+ }+ _ => select_line(&mut editor.input, at, lines),+ }+ editor.goal = None;+ editor.follow = true;+ }+ shown.edits += 1;+ shown.tell();+ panel.selecting = Some((extended, id));+ true+ }+ WMEK::Move if event.mouse_buttons.contains(MouseButtons::LEFT) => {+ let Some((from, id)) = panel.selecting.clone() else {+ return false;+ };+ if from != extended {+ return false;+ }+ let Some(shown) = panel.view_mut(extended) else {+ return false;+ };+ let Some(editor) = shown.editors.get_mut(&id) else {+ return false;+ };+ let Some(layout) = editor.layout.as_ref() else {+ return true;+ };+ let at = index_at(layout, px, py);+ if at != editor.input.cursor || editor.input.selection_anchor.is_none() {+ editor.input.caret_set(at, true);+ editor.follow = true;+ shown.edits += 1;+ }+ true+ }+ WMEK::Release(MousePress::Left) => {+ panel.selecting = None;+ false+ }+ _ => false,+ }+}++/// The fonts a field is set in: the sidebar's, at the body size, or the+/// terminal's.+fn font_of(fonts: &PanelFonts, font: Font) -> &(Rc<LoadedFont>, RenderMetrics) {+ match font {+ Font::Ui => &fonts.body,+ Font::Mono => &fonts.mono,+ }+}++/// What a field of `kind` shows of `text`: a secret one, a dot for each+/// character.+fn shown_text(kind: FieldKind, text: &str) -> Cow<'_, str> {+ match kind {+ FieldKind::Secret => Cow::Owned("\u{2022}".repeat(text.chars().count())),+ FieldKind::Line | FieldKind::Lines => Cow::Borrowed(text),+ }+}++/// What a field's text is at, for the system's edits of it to be taken+/// only of the text they were made for.+fn text_revision(text: &str) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ text.hash(&mut hasher);+ hasher.finish()+}++/// What a copy takes: what is selected, or all of it.+fn copied(input: &TextInputState) -> String {+ input+ .caret_selected_text()+ .unwrap_or_else(|| input.text().to_string())+}++/// Puts `text` in at the caret, over what is selected: no more than the+/// field takes, and on one line unless it has `lines`.+fn insert(input: &mut TextInputState, text: &str, limit: usize, lines: bool) {+ let selected = input+ .caret_selection_range()+ .map_or(0, |(from, to)| to - from);+ let room = limit.saturating_sub(input.char_len().saturating_sub(selected));+ let text: String = text+ .chars()+ .filter(|ch| match ch {+ '\n' | '\t' => lines,+ ch => !ch.is_control(),+ })+ .take(room)+ .collect();+ input.caret_insert(&text, lines);+}++/// Lays `text`, one of a field's lines, whose boundaries are at `xs`, as+/// lines no wider than `width`: broken at the last place that keeps one+/// within it -- after a space, or between characters of a script written+/// without spaces -- or else where it overflows.+fn wrap_line(+ lines: &mut Vec<LaidLine>,+ text: &str,+ xs: &[f32],+ base: usize,+ of: usize,+ width: f32,+) {+ let chars: Vec<char> = text.chars().collect();+ let count = chars.len();+ if count == 0 {+ lines.push(LaidLine {+ start: base,+ end: base,+ of,+ xs: vec![0.0],+ });+ return;+ }+ let mut start = 0;+ while start < count {+ let mut end = start + 1;+ while end < count && xs[end + 1] - xs[start] <= width {+ end += 1;+ }+ if end < count {+ if let Some(at) = (start + 1..=end)+ .rev()+ .find(|at| breaks_before(&chars, *at))+ {+ end = at;+ }+ }+ let origin = xs[start];+ lines.push(LaidLine {+ start: base + start,+ end: base + end,+ of,+ xs: xs[start..=end].iter().map(|x| x - origin).collect(),+ });+ start = end;+ }+}++/// Whether a line may break before character `at` of `chars`: after a+/// space, or where the characters on either side are of a script written+/// without spaces -- but not before the punctuation that closes one.+fn breaks_before(chars: &[char], at: usize) -> bool {+ let (Some(before), Some(after)) = (chars.get(at.wrapping_sub(1)), chars.get(at)) else {+ return false;+ };+ if before.is_whitespace() {+ return true;+ }+ let closing = matches!(+ after,+ '、' | '。'+ | ','+ | '.'+ | ':'+ | ';'+ | '!'+ | '?'+ | ')'+ | '」'+ | '』'+ | '】'+ | '〉'+ | '》'+ | '〕'+ | 'ー'+ | '…'+ );+ (unspaced(*before) || unspaced(*after)) && !after.is_whitespace() && !closing+}++/// A character of a script written without spaces between its words:+/// Chinese, Japanese, Korean, and their punctuation.+fn unspaced(ch: char) -> bool {+ matches!(+ ch as u32,+ 0x2E80..=0x2FFF+ | 0x3000..=0x303F+ | 0x3040..=0x30FF+ | 0x3100..=0x31FF+ | 0x3400..=0x4DBF+ | 0x4E00..=0x9FFF+ | 0xAC00..=0xD7AF+ | 0xF900..=0xFAFF+ | 0xFF00..=0xFFEF+ | 0x20000..=0x3FFFF+ )+}++/// The laid line the caret before character `index` shows on, and where+/// across it: at a line wrapped onto the next, the caret at the break is+/// the next line's.+fn caret_at(lines: &[LaidLine], index: usize) -> (usize, f32) {+ for (row, line) in lines.iter().enumerate() {+ let wrapped = lines+ .get(row + 1)+ .is_some_and(|next| next.start == line.end);+ if index >= line.start && (index < line.end || (index == line.end && !wrapped)) {+ return (row, line.xs[index - line.start]);+ }+ }+ let last = lines.len().saturating_sub(1);+ let x = lines+ .last()+ .and_then(|line| line.xs.last())+ .copied()+ .unwrap_or(0.0);+ (last, x)+}++/// The character the pointer at `x`, `y` is nearest the start of.+fn index_at(layout: &FieldLayout, x: f32, y: f32) -> usize {+ let rows = layout.lines.len();+ if rows == 0 {+ return 0;+ }+ let row = (((y - layout.top) / layout.line_height).floor().max(0.0) as usize).min(rows - 1);+ nearest(&layout.lines, row, x - layout.left)+}++/// The boundary of laid line `row` nearest `x` across it: short of the+/// break of a line wrapped onto the next, where the caret would show on that.+fn nearest(lines: &[LaidLine], row: usize, x: f32) -> usize {+ let line = &lines[row];+ let at = line+ .xs+ .iter()+ .enumerate()+ .min_by(|(_, a), (_, b)| (*a - x).abs().total_cmp(&(*b - x).abs()))+ .map_or(0, |(at, _)| at);+ let index = line.start + at;+ let wrapped = lines+ .get(row + 1)+ .is_some_and(|next| next.start == line.end);+ if wrapped && index == line.end && line.end > line.start {+ index - 1+ } else {+ index+ }+}++/// Moves the caret `rows` laid lines down -- up, for fewer than none --+/// keeping to the x it went up and down from.+fn vertical(editor: &mut Editor, rows: isize, shift: bool) {+ let Some(layout) = editor.layout.as_ref() else {+ return;+ };+ let (row, x) = caret_at(&layout.lines, editor.input.cursor);+ let goal = editor.goal.unwrap_or(x);+ let target = row as isize + rows;+ let at = if target < 0 {+ 0+ } else if target as usize >= layout.lines.len() {+ editor.input.char_len()+ } else {+ nearest(&layout.lines, target as usize, goal)+ };+ editor.input.caret_set(at, shift);+ editor.goal = Some(goal);+}++/// How many laid lines a page up or down moves: what shows, less one.+fn page_rows(editor: &Editor) -> isize {+ editor.layout.as_ref().map_or(1, |layout| {+ ((layout.inner.height() / layout.line_height).floor() as isize - 1).max(1)+ })+}++/// The laid line the caret is on, as where it starts and where a caret at+/// its end goes.+fn laid_line(editor: &Editor) -> Option<(usize, usize)> {+ let layout = editor.layout.as_ref()?;+ let (row, _) = caret_at(&layout.lines, editor.input.cursor);+ let line = layout.lines.get(row)?;+ let wrapped = layout+ .lines+ .get(row + 1)+ .is_some_and(|next| next.start == line.end);+ let end = if wrapped && line.end > line.start {+ line.end - 1+ } else {+ line.end+ };+ Some((line.start, end))+}++fn line_home(editor: &mut Editor, shift: bool) {+ match laid_line(editor) {+ Some((start, _)) => editor.input.caret_set(start, shift),+ None => editor.input.caret_move_home(shift),+ }+}++fn line_end(editor: &mut Editor, shift: bool) {+ match laid_line(editor) {+ Some((_, end)) => editor.input.caret_set(end, shift),+ None => editor.input.caret_move_end(shift),+ }+}++/// Deletes from the start of the laid line the caret is on to the caret --+/// or what is selected.+fn delete_to_line_start(editor: &mut Editor) {+ if editor.input.caret_delete_selection() {+ return;+ }+ let start = laid_line(editor).map_or(0, |(start, _)| start);+ editor.input.clear_selection();+ editor.input.caret_set(start, true);+ editor.input.caret_delete_selection();+}++/// Selects the line character `at` is on, in a field of lines; all of a+/// field of one.+fn select_line(input: &mut TextInputState, at: usize, lines: bool) {+ if !lines {+ input.caret_select_all();+ return;+ }+ let chars: Vec<char> = input.text().chars().collect();+ let at = at.min(chars.len());+ let start = chars[..at]+ .iter()+ .rposition(|ch| *ch == '\n')+ .map_or(0, |newline| newline + 1);+ let end = chars[at..]+ .iter()+ .position(|ch| *ch == '\n')+ .map_or(chars.len(), |newline| at + newline);+ input.caret_set(start, false);+ input.caret_set(end, true);+}++/// The modifiers of a key, as the player is told them.+fn player_mods(mods: TermModifiers) -> Mods {+ Mods {+ shift: mods.contains(TermModifiers::SHIFT),+ ctrl: mods.contains(TermModifiers::CTRL),+ alt: mods.contains(TermModifiers::ALT),+ cmd: mods.contains(TermModifiers::SUPER),+ }+}++/// A key as a browser names it (`KeyboardEvent.key`), which is how a panel+/// says the keys it takes; `None` for one it has no name for.+fn key_name(key: &TermKeyCode) -> Option<String> {+ let name = match key {+ TermKeyCode::Char(ch) if !ch.is_control() => return Some(ch.to_string()),+ TermKeyCode::Enter => "Enter",+ TermKeyCode::Escape => "Escape",+ TermKeyCode::Tab => "Tab",+ TermKeyCode::Backspace => "Backspace",+ TermKeyCode::Delete => "Delete",+ TermKeyCode::Insert => "Insert",+ TermKeyCode::LeftArrow => "ArrowLeft",+ TermKeyCode::RightArrow => "ArrowRight",+ TermKeyCode::UpArrow => "ArrowUp",+ TermKeyCode::DownArrow => "ArrowDown",+ TermKeyCode::Home => "Home",+ TermKeyCode::End => "End",+ TermKeyCode::PageUp => "PageUp",+ TermKeyCode::PageDown => "PageDown",+ TermKeyCode::Function(n) => return Some(format!("F{n}")),+ _ => return None,+ };+ Some(name.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Lines laid as if every character were 10 wide.+ fn laid(text: &str, width: Option<f32>) -> Vec<LaidLine> {+ let mut lines = Vec::new();+ let mut base = 0;+ for (of, piece) in text.split('\n').enumerate() {+ let count = piece.chars().count();+ let xs: Vec<f32> = (0..=count).map(|n| n as f32 * 10.0).collect();+ match width {+ Some(width) => wrap_line(&mut lines, piece, &xs, base, of, width),+ None => lines.push(LaidLine {+ start: base,+ end: base + count,+ of,+ xs,+ }),+ }+ base += count + 1;+ }+ lines+ }++ fn spans(lines: &[LaidLine]) -> Vec<(usize, usize)> {+ lines.iter().map(|line| (line.start, line.end)).collect()+ }++ #[test]+ fn lines_wrap_after_a_space_or_where_they_overflow() {+ // "aaa bbb" at 50 wide: "aaa " then "bbb".+ assert_eq!(spans(&laid("aaa bbb", Some(50.0))), [(0, 4), (4, 7)]);+ // No space to break at: cut where it overflows.+ assert_eq!(+ spans(&laid("abcdefgh", Some(30.0))),+ [(0, 3), (3, 6), (6, 8)]+ );+ // A line break starts a line; an empty line is a line.+ assert_eq!(+ spans(&laid("ab\n\ncd", Some(50.0))),+ [(0, 2), (3, 3), (4, 6)]+ );+ // Never fewer than a character a line, however narrow.+ assert_eq!(spans(&laid("ab", Some(1.0))), [(0, 1), (1, 2)]);+ // Between Chinese characters, wherever it fills -- but never before+ // the punctuation that closes a phrase.+ assert_eq!(spans(&laid("ab 中文字", Some(50.0))), [(0, 5), (5, 6)]);+ assert_eq!(spans(&laid("中文字。好", Some(30.0))), [(0, 2), (2, 5)]);+ }++ #[test]+ fn the_caret_at_a_wrap_is_on_the_next_line_and_a_press_past_the_end_stays() {+ let lines = laid("aaa bbb", Some(50.0));+ assert_eq!(+ caret_at(&lines, 4),+ (1, 0.0),+ "the break is the next line's"+ );+ assert_eq!(caret_at(&lines, 3), (0, 30.0));+ assert_eq!(caret_at(&lines, 7), (1, 30.0));+ assert_eq!(nearest(&lines, 0, 100.0), 3, "short of the break");+ assert_eq!(nearest(&lines, 1, 100.0), 7);+ // At a line break the caret stays on its line.+ let lines = laid("ab\ncd", Some(50.0));+ assert_eq!(caret_at(&lines, 2), (0, 20.0));+ assert_eq!(caret_at(&lines, 3), (1, 0.0));+ }++ #[test]+ fn a_caret_goes_up_and_down_keeping_to_its_x() {+ let mut editor = Editor::new("abcdef\nab\nabcdef", 0);+ let lines = laid("abcdef\nab\nabcdef", None);+ editor.layout = Some(FieldLayout {+ left: 0.0,+ top: 0.0,+ line_height: 10.0,+ inner: euclid::rect(0.0, 0.0, 100.0, 30.0),+ lines,+ starts: vec![0, 7, 10],+ });+ editor.input.caret_set(5, false);+ vertical(&mut editor, 1, false);+ assert_eq!(editor.input.cursor, 9, "the short line's end");+ vertical(&mut editor, 1, false);+ assert_eq!(editor.input.cursor, 15, "back to where it was across");+ vertical(&mut editor, 1, false);+ assert_eq!(editor.input.cursor, 16, "below the last, the end");+ vertical(&mut editor, -9, true);+ assert_eq!(editor.input.cursor, 0);+ assert_eq!(editor.input.caret_selection_range(), Some((0, 16)));+ }++ #[test]+ fn what_is_put_in_is_kept_to_what_the_field_takes() {+ let mut input = TextInputState::new();+ insert(&mut input, "ab\ncd\u{7}", 3, false);+ assert_eq!(+ input.text(),+ "abc",+ "one line, no control characters, three at most"+ );+ input.caret_select_all();+ insert(&mut input, "xyzw", 3, false);+ assert_eq!(input.text(), "xyz", "over the selection");+ let mut lines = TextInputState::new();+ insert(&mut lines, "a\n\tb", 10, true);+ assert_eq!(lines.text(), "a\n\tb");+ }++ #[test]+ fn a_line_is_selected_within_its_breaks() {+ let mut input = TextInputState::new();+ input.set_text_end("one\ntwo\nthree".into());+ select_line(&mut input, 5, true);+ assert_eq!(input.caret_selected_text().as_deref(), Some("two"));+ select_line(&mut input, 5, false);+ assert_eq!(+ input.caret_selected_text().as_deref(),+ Some("one\ntwo\nthree")+ );+ }++ #[test]+ fn keys_are_named_as_a_browser_names_them() {+ assert_eq!(+ key_name(&TermKeyCode::DownArrow).as_deref(),+ Some("ArrowDown")+ );+ assert_eq!(key_name(&TermKeyCode::Char('j')).as_deref(), Some("j"));+ assert_eq!(key_name(&TermKeyCode::Char(' ')).as_deref(), Some(" "));+ assert_eq!(key_name(&TermKeyCode::Function(5)).as_deref(), Some("F5"));+ assert_eq!(key_name(&TermKeyCode::CapsLock), None);+ assert_eq!(+ shown_text(FieldKind::Secret, "ab中"),+ "\u{2022}\u{2022}\u{2022}"+ );+ }+}diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex 87df995d..af6f54d2 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -1906,7 +1906,8 @@ impl crate::TermWindow {// the docked panel collapsed must not stop the next reveal.|| (self.right_sidebar_hover.is_presented()&& (self.right_sidebar_focused_input().is_some()- || self.right_sidebar_note.view.focused));+ || self.right_sidebar_note.view.focused+ || self.plugin_panel_has_keyboard()));HoverInput {eligible,pointer,@@ -2395,15 +2396,23 @@ impl crate::TermWindow {}pub(crate) fn right_sidebar_has_text_focus(&self) -> bool {+ // Held from the terminal, whatever the sidebar shows now.+ if self.plugin_panel_keys_held {+ return true;+ }match self.right_sidebar_mode {RightSidebarMode::Chat => self.right_sidebar_file_focus.is_some(),RightSidebarMode::Snippets => self.right_sidebar_snippet_focus.is_some(),RightSidebarMode::Tasks => self.right_sidebar_note.view.focused,- RightSidebarMode::Agents | RightSidebarMode::Plugin(_) => false,+ // Given only by the user: a press in one of its fields, or+ // their key for it.+ RightSidebarMode::Plugin(_) => self.plugin_panel_has_keyboard(),+ RightSidebarMode::Agents => false,}}pub(crate) fn clear_right_sidebar_text_focus(&mut self) {+ self.release_plugin_panel_keyboard();let note_was_focused = self.right_sidebar_note.view.focused;self.right_sidebar_snippet_focus = None;self.right_sidebar_file_focus = None;@@ -2455,6 +2464,12 @@ impl crate::TermWindow {/// is. All four can be off at once -- that is how you get rid of the/// right sidebar -- and then there is nothing to move to, so we stay put.pub(crate) fn fall_back_to_an_enabled_panel(&mut self) {+ // The panel with the keyboard went from under the user.+ if matches!(self.right_sidebar_mode, RightSidebarMode::Plugin(_))+ && self.plugin_panel_has_keyboard()+ {+ self.hold_plugin_panel_keys();+ }if let Some(first) = RightSidebarMode::enabled_panels().first().copied() {self.right_sidebar_mode = first;}@@ -4357,7 +4372,13 @@ impl crate::TermWindow {});}- pub(crate) fn copy_right_sidebar_focused_input(&self, destination: ClipboardCopyDestination) {+ pub(crate) fn copy_right_sidebar_focused_input(+ &mut self,+ destination: ClipboardCopyDestination,+ ) {+ if let RightSidebarMode::Plugin(_) = self.right_sidebar_mode {+ return self.plugin_panel_copy(destination);+ }if self.right_sidebar_mode == RightSidebarMode::Tasks {let Some(session) = self.right_sidebar_note.session.as_ref() else {return;@@ -4962,6 +4983,9 @@ impl crate::TermWindow {}pub(crate) fn clear_right_sidebar_focused_input_selection(&mut self) {+ if let RightSidebarMode::Plugin(_) = self.right_sidebar_mode {+ return self.plugin_panel_clear_selection();+ }if self.right_sidebar_mode == RightSidebarMode::Tasks {let focus = self.right_sidebar_note.view.selection.focus;self.right_sidebar_note.view.selection = SourceSelection {@@ -4984,6 +5008,9 @@ impl crate::TermWindow {if !self.right_sidebar_has_text_focus() {return false;}+ if self.plugin_panel_keys_held {+ return self.plugin_panel_held_key(key, mods);+ }// Resolved once, platform-normalized: ⌘ on macOS, Ctrl on// Windows/Linux. Testing raw modifiers here is what left these inputs@@ -4995,6 +5022,9 @@ impl crate::TermWindow {if self.right_sidebar_mode == RightSidebarMode::Tasks {return self.handle_right_sidebar_note_key(key, mods);}+ if let RightSidebarMode::Plugin(_) = self.right_sidebar_mode {+ return self.plugin_panel_key(key, mods);+ }// Clipboard and select-all. Deliberately falls through rather than// returning on an unhandled key: off macOS the same Ctrl chord is also@@ -5206,6 +5236,12 @@ impl crate::TermWindow {}pub(crate) fn push_right_sidebar_text(&mut self, text: &str) -> bool {+ if self.plugin_panel_keys_held {+ return true;+ }+ if let RightSidebarMode::Plugin(_) = self.right_sidebar_mode {+ return self.plugin_panel_text(text);+ }if self.right_sidebar_mode == RightSidebarMode::Tasks {self.right_sidebar_note.begin_live_editing();let Some(session) = self.right_sidebar_note.session.clone() else {@@ -7205,7 +7241,7 @@ impl crate::TermWindow {.is_some_and(|until| until > Instant::now())}- fn right_sidebar_snippet_cursor_on(&self) -> bool {+ pub(crate) fn right_sidebar_snippet_cursor_on(&self) -> bool {let blink_ms = (self.config.cursor_blink_rate as u64).max(100);self.update_next_frame_time(Some(Instant::now() + Duration::from_millis(blink_ms)));let ms = std::time::SystemTime::now()diff --git a/wezterm-gui/src/ui/state.rs b/wezterm-gui/src/ui/state.rsindex b8de60eb..c9795e49 100644--- a/wezterm-gui/src/ui/state.rs+++ b/wezterm-gui/src/ui/state.rs@@ -402,6 +402,34 @@ impl TextInputState {idx}+ /// Selects the word the caret is in or before -- a run of characters+ /// that are not spaces -- or, between words, the spaces there, within+ /// its line.+ pub(crate) fn caret_select_word(&mut self) {+ let chars: Vec<char> = self.text.chars().collect();+ let at = self.cursor.min(chars.len());+ let probe = if at < chars.len() && chars[at] != '\n' {+ at+ } else if at > 0 && chars[at - 1] != '\n' {+ at - 1+ } else {+ return;+ };+ let space = chars[probe].is_whitespace();+ let alike = |ch: char| ch != '\n' && ch.is_whitespace() == space;+ let mut start = probe;+ while start > 0 && alike(chars[start - 1]) {+ start -= 1;+ }+ let mut end = probe + 1;+ while end < chars.len() && alike(chars[end]) {+ end += 1;+ }+ self.selection_anchor = Some(start);+ self.cursor = end;+ self.sync_selected_all();+ }+pub(crate) fn caret_word_left(&mut self, extend: bool) {let target = self.prev_word_boundary();self.caret_set(target, extend);@@ -691,6 +719,31 @@ mod text_input_tests {assert_eq!(i.cursor, 4);}+ #[test]+ fn a_word_is_selected_within_its_line() {+ let mut i = input("one two\nthree");+ i.caret_set(5, false);+ i.caret_select_word();+ assert_eq!(i.caret_selected_text().as_deref(), Some("two"));+ i.caret_set(3, false);+ i.caret_select_word();+ assert_eq!(+ i.caret_selected_text().as_deref(),+ Some(" "),+ "the spaces between"+ );+ i.caret_set(7, false);+ i.caret_select_word();+ assert_eq!(+ i.caret_selected_text().as_deref(),+ Some("two"),+ "not past the line"+ );+ let mut empty = input("");+ empty.caret_select_word();+ assert!(empty.caret_selection_range().is_none());+ }+#[test]fn caret_respects_multibyte_chars() {let mut i = input("aé中b");