| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 1 | //! The session: a tree, a screen, and where the focus and the caret are. |
| 2 | //! |
| 3 | //! This is the whole backend minus the terminal. It paints into a grid, takes |
| 4 | //! keys and clicks by name, and answers events — so the entire widget layer, |
| 5 | //! keyboard navigation included, runs in a test with no TTY, no raw mode and no |
| 6 | //! display. `tui_headless` opens exactly this and nothing else. |
| 7 | //! |
| 8 | //! Keys arrive already named (`"ctrl+u"`, `"page-down"`, `"a"`); turning a |
| 9 | //! terminal's bytes into those names is [`crate::keys`]'s job, and a caller |
| 10 | //! synthesising one for a test writes the name directly. |
| 11 | |
| 12 | use crate::keys; |
| 13 | use crate::paint::{self, Painted}; |
| 14 | use crate::screen::Screen; |
| 15 | use crate::tree::{Tag, Tree, Value}; |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 16 | use std::collections::HashMap; |
| 17 | |
| 18 | /// Where one scroll area is, and whether it is following its own bottom. |
| 19 | /// |
| 20 | /// It lives here rather than in the tree because a re-render clears a node's |
| 21 | /// props: glimmer writes what the component said and nothing else, which is |
| 22 | /// right — the component's state is the truth — and it means a viewport that |
| 23 | /// kept its position in a prop loses it the moment anything above it changes. |
| 24 | /// A chat backlog changes on every message, which is exactly when a reader |
| 25 | /// cares where they were. |
| 26 | #[derive(Clone, Copy)] |
| 27 | struct Scrolled { |
| 28 | offset: u16, |
| 29 | /// Following the bottom. A `:stick-to-bottom` viewport starts this way, |
| 30 | /// stops when the reader scrolls up, and starts again when they come back |
| 31 | /// down — which is the behaviour that lets a new message arrive without |
| 32 | /// dragging the screen out from under someone reading history. |
| 33 | pinned: bool, |
| 34 | } |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 35 | |
| 36 | pub struct Ui { |
| 37 | pub tree: Tree, |
| 38 | pub screen: Screen, |
| 39 | /// The node the focus ring is on, 0 for none. |
| 40 | focus: u32, |
| 41 | /// The caret in the focused entry, in characters from the start. |
| 42 | caret: usize, |
| 43 | painted: Painted, |
| 44 | tick: u64, |
| 45 | quit: bool, |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 46 | /// Scroll positions by `:scroll-key`, across re-renders. |
| 47 | scrolls: HashMap<String, Scrolled>, |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 48 | } |
| 49 | |
| 50 | impl Ui { |
| 51 | pub fn new(width: u16, height: u16) -> Self { |
| 52 | Self { |
| 53 | tree: Tree::new(), |
| 54 | screen: Screen::new(width.max(1), height.max(1)), |
| 55 | focus: 0, |
| 56 | caret: 0, |
| 57 | painted: Painted::default(), |
| 58 | tick: 0, |
| 59 | quit: false, |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 60 | scrolls: HashMap::new(), |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 61 | } |
| 62 | } |
| 63 | |
| 64 | pub fn resize(&mut self, width: u16, height: u16) { |
| 65 | self.screen.resize(width.max(1), height.max(1)); |
| 66 | } |
| 67 | |
| 68 | pub fn should_close(&self) -> bool { |
| 69 | self.quit |
| 70 | } |
| 71 | |
| 72 | pub fn quit(&mut self) { |
| 73 | self.quit = true; |
| 74 | } |
| 75 | |
| 76 | pub fn focus(&self) -> u32 { |
| 77 | self.focus |
| 78 | } |
| 79 | |
| 80 | pub fn cursor(&self) -> Option<(u16, u16)> { |
| 81 | self.painted.cursor |
| 82 | } |
| 83 | |
| 84 | /// Paint one frame, then settle the things painting decided: what is |
| 85 | /// focusable now, and how far each scroll area really is. |
| 86 | pub fn frame(&mut self) { |
| 87 | self.tick = self.tick.wrapping_add(1); |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 88 | self.restore_scrolls(self.tree.root()); |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 89 | self.paint_once(); |
| 90 | if self.settle_focus() { |
| 91 | // Focus is decided by what the paint found, so the frame that |
| 92 | // gives it away has to be drawn again — otherwise the first frame |
| 93 | // of a screen shows nothing focused and the second one does. |
| 94 | self.paint_once(); |
| 95 | } |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 96 | for (node, offset, max) in self.painted.scrolled.clone() { |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 97 | // Painting clamps the viewport to the content; write the clamped |
| 98 | // value back so the caller's next `+1` starts from the truth. |
| 99 | if self.tree.props(node).cells("offset", 0) != offset { |
| 100 | self.tree.set(node, "offset", Value::Num(offset as f64)); |
| 101 | } |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 102 | // And remember it under its key, which is what survives the |
| 103 | // re-render that is about to clear the prop. Being at the bottom |
| 104 | // is what pins it there: a reader who scrolls back down has said |
| 105 | // they want to follow again, and never has to say so twice. |
| 106 | let key = self.scroll_key(node); |
| 107 | let sticky = self.tree.props(node).bool("stick-to-bottom", false); |
| 108 | self.scrolls.insert( |
| 109 | key, |
| 110 | Scrolled { |
| 111 | offset, |
| 112 | pinned: sticky && offset >= max, |
| 113 | }, |
| 114 | ); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// What a scroll area is remembered by. Its `:scroll-key` when it has one, |
| 119 | /// because that is a name the caller chose and means the same viewport |
| 120 | /// after a re-mount; its handle otherwise, which at least survives a |
| 121 | /// re-render that leaves the node where it was. |
| 122 | fn scroll_key(&self, node: u32) -> String { |
| 123 | let props = self.tree.props(node); |
| 124 | let key = props.str("scroll-key"); |
| 125 | if key.is_empty() { |
| 126 | format!("#{node}") |
| 127 | } else { |
| 128 | key.to_owned() |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Put every scroll area back where it was before the tree is painted. |
| 133 | /// |
| 134 | /// A pinned one is asked for an offset past the end and painting clamps it |
| 135 | /// to the bottom, which is how it follows content that grew since the last |
| 136 | /// frame without this having to measure anything. |
| 137 | fn restore_scrolls(&mut self, id: u32) { |
| 138 | if matches!(self.tree.tag(id), Tag::Scroll) { |
| 139 | let key = self.scroll_key(id); |
| 140 | let sticky = self.tree.props(id).bool("stick-to-bottom", false); |
| 141 | let to = match self.scrolls.get(&key) { |
| 142 | Some(state) if sticky && state.pinned => u16::MAX, |
| 143 | Some(state) => state.offset, |
| 144 | // Never seen: a sticky viewport opens at the bottom, which for |
| 145 | // a backlog is the message that just arrived. |
| 146 | None if sticky => u16::MAX, |
| 147 | None => return, |
| 148 | }; |
| 149 | self.tree.set(id, "offset", Value::Num(to as f64)); |
| 150 | } |
| 151 | for child in self.tree.children(id) { |
| 152 | self.restore_scrolls(child); |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 153 | } |
| 154 | } |
| 155 | |
| 156 | fn paint_once(&mut self) { |
| 157 | self.painted = paint::frame( |
| 158 | &self.tree, |
| 159 | &mut self.screen, |
| 160 | self.focus, |
| 161 | self.caret, |
| 162 | self.tick, |
| 163 | ); |
| 164 | } |
| 165 | |
| 166 | /// Put the focus somewhere real. Answers whether it moved. |
| 167 | fn settle_focus(&mut self) -> bool { |
| 168 | let was = self.focus; |
| 169 | // A focused widget that has since been unmounted — or dimmed — leaves |
| 170 | // the ring, and focus lands on the first thing that is still there |
| 171 | // rather than on nothing. |
| 172 | if self.focus != 0 && !self.painted.ring.contains(&self.focus) { |
| 173 | self.focus = 0; |
| 174 | } |
| 175 | if self.focus == 0 { |
| 176 | let wants = self |
| 177 | .painted |
| 178 | .ring |
| 179 | .iter() |
| 180 | .find(|id| self.tree.props(**id).bool("autofocus", false)) |
| 181 | .copied(); |
| 182 | if let Some(id) = wants.or_else(|| self.painted.ring.first().copied()) { |
| 183 | self.set_focus(id); |
| 184 | } |
| 185 | } |
| 186 | self.focus != was |
| 187 | } |
| 188 | |
| 189 | fn set_focus(&mut self, id: u32) { |
| 190 | if self.focus == id { |
| 191 | return; |
| 192 | } |
| 193 | self.focus = id; |
| 194 | // The caret goes to the end of whatever it just entered, which is where |
| 195 | // someone tabbing into a field with text in it expects to type. |
| 196 | self.caret = self.tree.props(id).str("text").chars().count(); |
| 197 | } |
| 198 | |
| 199 | fn move_focus(&mut self, forward: bool) { |
| 200 | if self.painted.ring.is_empty() { |
| 201 | return; |
| 202 | } |
| 203 | let ring = self.painted.ring.clone(); |
| 204 | let at = ring.iter().position(|id| *id == self.focus); |
| 205 | let next = match (at, forward) { |
| 206 | (Some(i), true) => (i + 1) % ring.len(), |
| 207 | (Some(i), false) => (i + ring.len() - 1) % ring.len(), |
| 208 | (None, true) => 0, |
| 209 | (None, false) => ring.len() - 1, |
| 210 | }; |
| 211 | self.set_focus(ring[next]); |
| 212 | } |
| 213 | |
| 214 | // ── keys ──────────────────────────────────────────────────────────────── |
| 215 | |
| 216 | /// Handle one key by name. Answers false when nothing here wanted it, in |
| 217 | /// which case it has been emitted as a `key` event for the caller to route. |
| 218 | pub fn key(&mut self, name: &str) -> bool { |
| 219 | if matches!(name, "ctrl+c" | "ctrl+q") { |
| 220 | self.quit = true; |
| 221 | return true; |
| 222 | } |
| 223 | match name { |
| 224 | "tab" => { |
| 225 | self.move_focus(true); |
| 226 | return true; |
| 227 | } |
| 228 | "shift+tab" | "backtab" => { |
| 229 | self.move_focus(false); |
| 230 | return true; |
| 231 | } |
| 232 | "esc" => { |
| 233 | // Esc belongs to the topmost overlay when there is one: that is |
| 234 | // what closes a modal everywhere else. |
| 235 | if let Some(overlay) = self.topmost_overlay() { |
| 236 | self.tree.emit(overlay, "close", String::new(), 0.0); |
| 237 | return true; |
| 238 | } |
| 239 | } |
| 240 | _ => {} |
| 241 | } |
| 242 | |
| 243 | let focus = self.focus; |
| 244 | let handled = match self.tree.tag(focus) { |
| 245 | Tag::Entry => self.entry_key(focus, name), |
| 246 | Tag::Button => self.activate_key(focus, name, "click"), |
| 247 | Tag::CheckButton => { |
| 248 | if matches!(name, "enter" | "space") { |
| 249 | self.toggle(focus); |
| 250 | true |
| 251 | } else { |
| 252 | false |
| 253 | } |
| 254 | } |
| 255 | Tag::Listbox => self.listbox_key(focus, name), |
| 256 | _ => false, |
| 257 | }; |
| 258 | if !handled { |
| 259 | // Unhandled keys go to the caller as an event on the focused node, |
| 260 | // or on the window when nothing has focus. glimmer bubbles from |
| 261 | // there; it holds the handlers and knows the tree. |
| 262 | let target = if focus != 0 { focus } else { self.tree.root() }; |
| 263 | self.tree.emit(target, "key", name.to_owned(), 0.0); |
| 264 | } |
| 265 | handled |
| 266 | } |
| 267 | |
| 268 | fn topmost_overlay(&self) -> Option<u32> { |
| 269 | fn walk(tree: &Tree, id: u32, found: &mut Option<u32>) { |
| 270 | if matches!(tree.tag(id), Tag::Overlay) { |
| 271 | *found = Some(id); |
| 272 | } |
| 273 | for child in tree.children(id) { |
| 274 | walk(tree, child, found); |
| 275 | } |
| 276 | } |
| 277 | let mut found = None; |
| 278 | walk(&self.tree, self.tree.root(), &mut found); |
| 279 | found |
| 280 | } |
| 281 | |
| 282 | fn activate_key(&mut self, node: u32, name: &str, event: &'static str) -> bool { |
| 283 | if matches!(name, "enter" | "space") { |
| 284 | self.tree.emit(node, event, String::new(), 0.0); |
| 285 | true |
| 286 | } else { |
| 287 | false |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | fn toggle(&mut self, node: u32) { |
| 292 | let now = !self.tree.props(node).bool("active", false); |
| 293 | // The widget does not own its value, but it does keep working when the |
| 294 | // caller ignores the event: the new state is written back here, and the |
| 295 | // next prop write from the reconciler is what settles it. |
| 296 | self.tree.set(node, "active", Value::Bool(now)); |
| 297 | self.tree |
| 298 | .emit(node, "toggled", String::new(), if now { 1.0 } else { 0.0 }); |
| 299 | } |
| 300 | |
| 301 | fn entry_key(&mut self, node: u32, name: &str) -> bool { |
| 302 | let mut text: Vec<char> = self.tree.props(node).str("text").chars().collect(); |
| 303 | let mut at = self.caret.min(text.len()); |
| 304 | let mut changed = false; |
| 305 | match name { |
| 306 | "enter" => { |
| 307 | let now: String = text.iter().collect(); |
| 308 | self.tree.emit(node, "activate", now, 0.0); |
| 309 | return true; |
| 310 | } |
| 311 | "left" | "ctrl+b" => at = at.saturating_sub(1), |
| 312 | "right" | "ctrl+f" => at = (at + 1).min(text.len()), |
| 313 | "home" | "ctrl+a" => at = 0, |
| 314 | "end" | "ctrl+e" => at = text.len(), |
| 315 | "alt+b" => at = keys::word_left(&text, at), |
| 316 | "alt+f" => at = keys::word_right(&text, at), |
| 317 | "backspace" => { |
| 318 | if at > 0 { |
| 319 | text.remove(at - 1); |
| 320 | at -= 1; |
| 321 | changed = true; |
| 322 | } |
| 323 | } |
| 324 | "delete" | "ctrl+d" => { |
| 325 | if at < text.len() { |
| 326 | text.remove(at); |
| 327 | changed = true; |
| 328 | } |
| 329 | } |
| 330 | "ctrl+w" | "alt+backspace" => { |
| 331 | let from = keys::word_left(&text, at); |
| 332 | if from < at { |
| 333 | text.drain(from..at); |
| 334 | at = from; |
| 335 | changed = true; |
| 336 | } |
| 337 | } |
| 338 | "ctrl+u" => { |
| 339 | if at > 0 { |
| 340 | text.drain(0..at); |
| 341 | at = 0; |
| 342 | changed = true; |
| 343 | } |
| 344 | } |
| 345 | "ctrl+k" => { |
| 346 | if at < text.len() { |
| 347 | text.truncate(at); |
| 348 | changed = true; |
| 349 | } |
| 350 | } |
| 351 | "space" => { |
| 352 | text.insert(at, ' '); |
| 353 | at += 1; |
| 354 | changed = true; |
| 355 | } |
| 356 | other => { |
| 357 | // A single character with no modifier on it is text. |
| 358 | let mut chars = other.chars(); |
| 359 | match (chars.next(), chars.next()) { |
| 360 | (Some(ch), None) if !ch.is_control() => { |
| 361 | text.insert(at, ch); |
| 362 | at += 1; |
| 363 | changed = true; |
| 364 | } |
| 365 | _ => return false, |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | self.caret = at; |
| 370 | if changed { |
| 371 | let now: String = text.iter().collect(); |
| 372 | self.tree.set(node, "text", Value::Str(now.clone())); |
| 373 | self.tree.emit(node, "change", now, 0.0); |
| 374 | } |
| 375 | true |
| 376 | } |
| 377 | |
| 378 | fn listbox_key(&mut self, node: u32, name: &str) -> bool { |
| 379 | let count = self.tree.child_count(node) as i64; |
| 380 | if count == 0 { |
| 381 | return false; |
| 382 | } |
| 383 | let page = self |
| 384 | .painted |
| 385 | .hits |
| 386 | .iter() |
| 387 | .find(|(id, _)| *id == node) |
| 388 | .map_or(1, |(_, rect)| rect.h.max(1) as i64); |
| 389 | let at = self.tree.props(node).num("selected", 0.0) as i64; |
| 390 | let to = match name { |
| 391 | "down" | "j" | "ctrl+n" => at + 1, |
| 392 | "up" | "k" | "ctrl+p" => at - 1, |
| 393 | "page-down" | "ctrl+d" => at + page, |
| 394 | "page-up" | "ctrl+u" => at - page, |
| 395 | "home" | "g" => 0, |
| 396 | "end" | "G" => count - 1, |
| 397 | "enter" | "space" => { |
| 398 | let index = at.clamp(0, count - 1); |
| 399 | let item = self.tree.child_at(node, index as usize); |
| 400 | let label = self.tree.props(item).label().to_owned(); |
| 401 | self.tree.emit(node, "activate", label, index as f64); |
| 402 | return true; |
| 403 | } |
| 404 | _ => return false, |
| 405 | }; |
| 406 | self.select(node, to.clamp(0, count - 1)); |
| 407 | true |
| 408 | } |
| 409 | |
| 410 | fn select(&mut self, node: u32, index: i64) { |
| 411 | if self.tree.props(node).num("selected", -1.0) as i64 == index { |
| 412 | return; |
| 413 | } |
| 414 | self.tree.set(node, "selected", Value::Num(index as f64)); |
| 415 | let item = self.tree.child_at(node, index as usize); |
| 416 | let label = self.tree.props(item).label().to_owned(); |
| 417 | self.tree.emit(node, "select", label, index as f64); |
| 418 | } |
| 419 | |
| 420 | // ── mouse ─────────────────────────────────────────────────────────────── |
| 421 | |
| 422 | /// A click at a cell. Focuses whatever is under it and activates it, which |
| 423 | /// is the whole of button 1 in a terminal: there is no press and release to |
| 424 | /// tell apart at this level. |
| 425 | pub fn click(&mut self, x: u16, y: u16) -> bool { |
| 426 | let Some((node, rect)) = self |
| 427 | .painted |
| 428 | .hits |
| 429 | .iter() |
| 430 | .find(|(_, rect)| rect.contains(x, y)) |
| 431 | .copied() |
| 432 | else { |
| 433 | return false; |
| 434 | }; |
| 435 | self.set_focus(node); |
| 436 | match self.tree.tag(node) { |
| 437 | Tag::Button => self.tree.emit(node, "click", String::new(), 0.0), |
| 438 | Tag::CheckButton => self.toggle(node), |
| 439 | Tag::Listbox => { |
| 440 | let row = (y - rect.y) as i64; |
| 441 | let count = self.tree.child_count(node) as i64; |
| 442 | if count > 0 { |
| 443 | self.select(node, row.clamp(0, count - 1)); |
| 444 | } |
| 445 | } |
| 446 | Tag::Entry => { |
| 447 | // Put the caret where it was clicked, not at the end. |
| 448 | let text = self.tree.props(node).str("text").chars().count(); |
| 449 | self.caret = ((x - rect.x) as usize).min(text); |
| 450 | } |
| 451 | _ => {} |
| 452 | } |
| 453 | true |
| 454 | } |
| 455 | |
| 456 | /// The wheel, `by` rows — negative is up. It moves the innermost `:scroll` |
| 457 | /// under the pointer, which is the one a reader means. |
| 458 | pub fn wheel(&mut self, x: u16, y: u16, by: i32) -> bool { |
| 459 | let Some(node) = self.scroll_at(self.tree.root(), x, y) else { |
| 460 | return false; |
| 461 | }; |
| 462 | let now = self.tree.props(node).cells("offset", 0) as i32; |
| 463 | let to = (now + by).max(0) as f64; |
| 464 | self.tree.set(node, "offset", Value::Num(to)); |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 465 | // Unpin on the way up, and let the next frame decide whether this put |
| 466 | // the reader back at the bottom — painting is what knows how far down |
| 467 | // that is. |
| 468 | let key = self.scroll_key(node); |
| 469 | self.scrolls.insert( |
| 470 | key, |
| 471 | Scrolled { |
| 472 | offset: to as u16, |
| 473 | pinned: false, |
| 474 | }, |
| 475 | ); |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 476 | self.tree.emit(node, "scroll", String::new(), to); |
| 477 | true |
| 478 | } |
| 479 | |
| 480 | /// The innermost `:scroll` whose painted area holds this cell. |
| 481 | fn scroll_at(&self, id: u32, x: u16, y: u16) -> Option<u32> { |
| 482 | for child in self.tree.children(id) { |
| 483 | if let Some(inner) = self.scroll_at(child, x, y) { |
| 484 | return Some(inner); |
| 485 | } |
| 486 | } |
| 487 | // Scroll areas take no focus, so they are not in the hit list; the |
| 488 | // frame records the ones it painted, which is enough for a wheel. |
| Let a backlog keep its place, and leave room for what is under it 68910bd nandi 18d ago | 489 | let painted = self.painted.scrolled.iter().any(|(n, _, _)| *n == id); |
| Paint the same tree into a terminal, for the machines with no window a7f6202 nandi 18d ago | 490 | if painted && matches!(self.tree.tag(id), Tag::Scroll) && self.screen.rect().contains(x, y) |
| 491 | { |
| 492 | return Some(id); |
| 493 | } |
| 494 | None |
| 495 | } |
| 496 | } |