diff --git a/README.md b/README.md index b19f1d4..4808b81 100644 --- a/README.md +++ b/README.md @@ -584,6 +584,18 @@ Text shows the first 128 KiB of the file, cut at the end of a line, and Markdown formatted. A file with a zero byte in its first 8,000 bytes isn't text. Page Up, Page Down, Home, End, Shift+Up, Shift+Down and the mouse wheel scroll it. +Dragging over text selects it, a double click takes a word and a third the line, Ctrl+A takes +all of it, and Ctrl+C copies. To select from the keyboard, F7 turns on caret mode, with a caret +at the start of the text in view. The arrows move it by a character or a line, Ctrl+Left and +Ctrl+Right by a word, Home and End to the ends of the line, and Ctrl+Home and Ctrl+End to the +ends of the text. Shift with any of them selects, Shift+Up and Shift+Down by lines, and a click +moves the caret. While caret mode is on, the arrows don't go to other files and Shift+Up and +Shift+Down don't scroll. Page Up, Page Down and the wheel still scroll without moving the +caret, as in a browser's caret browsing, and the next arrow brings it back into view. F7 or +Escape turns caret mode off, leaving the window open. The caret doesn't blink, so nothing runs +while it's on. A screen reader hears caret mode go on and off, and the line the caret is on as +it moves. + PDFs show their pages one under another, each drawn by poppler's `pdftoppm` as it scrolls into view, and scroll like text. A locked or damaged PDF says so. diff --git a/crates/app/src/a11y.rs b/crates/app/src/a11y.rs index 2eeced5..0670ed1 100644 --- a/crates/app/src/a11y.rs +++ b/crates/app/src/a11y.rs @@ -59,6 +59,8 @@ pub const PREVIEW_SHOWS: u64 = 53; pub const PREVIEW_PREVIOUS: u64 = 54; pub const PREVIEW_NEXT: u64 = 55; pub const PREVIEW_CLOSE: u64 = 56; +/// The line of a document the caret is on, in caret mode. +pub const PREVIEW_CARET_LINE: u64 = 57; // The Open With window. Its apps and headings are numbered from `OPEN_WITH_ROW0`, each keeping // its number while the window is open. pub const OPEN_WITH_SEARCH: u64 = 60; @@ -127,6 +129,9 @@ pub enum Role { Heading, /// What the preview window shows. Document, + /// A line of a document that can be read and selected from, not typed in: the caret's in + /// caret mode. Its text is the node's `field`. + Paragraph, /// The file list, whose rows are table rows of cells. Table, ColumnHeader, @@ -551,6 +556,8 @@ pub struct News { pub name_refused: (u64, String), /// How many times the folder showing has gone, and what was said the last time. pub gone_said: (u64, String), + /// Whether the preview window's caret mode is on. + pub caret_mode: bool, } /// A job as the panel shows it. @@ -598,6 +605,10 @@ impl Snapshot { if is.gone_said.0 > was.gone_said.0 { out.push((is.gone_said.1.clone(), false)); } + // Caret mode going on or off, whatever turned it: F7, Escape, or another file. + if is.caret_mode != was.caret_mode { + out.push((if is.caret_mode { "Caret mode on" } else { "Caret mode off" }.to_string(), false)); + } out } /// Whether a part is behind the menu or dialog that's open, so it can't be used. What's in @@ -1004,9 +1015,13 @@ impl Link { /// The preview window: the file's name, its kind and what's shown of it, and buttons to /// walk its folder and close it. fn build_viewer(&mut self, app: &App) -> Snapshot { - let s = app.a11y_preview(); + let mut s = app.a11y_preview(); + let (caret, area) = (s.caret.take(), s.area); + // In caret mode the arrows and Escape move the caret and leave the mode, so they aren't + // the buttons' keys then. + let keys = |k: &'static str| if caret.is_some() { "" } else { k }; let r = Rect::new(0, 0, app.w, app.h); - let fixed = vec![ + let mut fixed = vec![ Node::new(FRAME, Role::Frame, if s.name.is_empty() { "Preview".to_string() } else { format!("{} - Preview", s.name) }, r, 0).with_children(vec![PREVIEW, PREVIEW_PREVIOUS, PREVIEW_NEXT, PREVIEW_CLOSE]), // What has the keyboard, so moving to another file reads out its name, and the rest // is there to be read. @@ -1015,11 +1030,24 @@ impl Link { Node::new(PREVIEW_KIND, Role::Label, s.kind, s.area, PREVIEW), Node::new(PREVIEW_SHOWS, Role::Label, s.shows, s.foot, PREVIEW), // Placed as the keys that do the same: there are no buttons on screen. - Node::new(PREVIEW_PREVIOUS, Role::PushButton, "Previous file", Rect::default(), FRAME).enabled(s.can_step.0).doing(click("Show the previous file in the folder", "Left")), - Node::new(PREVIEW_NEXT, Role::PushButton, "Next file", Rect::default(), FRAME).enabled(s.can_step.1).doing(click("Show the next file in the folder", "Right")), - Node::new(PREVIEW_CLOSE, Role::PushButton, "Close", Rect::default(), FRAME).doing(click("Close the preview", "Escape")), + Node::new(PREVIEW_PREVIOUS, Role::PushButton, "Previous file", Rect::default(), FRAME).enabled(s.can_step.0).doing(click("Show the previous file in the folder", keys("Left"))), + Node::new(PREVIEW_NEXT, Role::PushButton, "Next file", Rect::default(), FRAME).enabled(s.can_step.1).doing(click("Show the next file in the folder", keys("Right"))), + Node::new(PREVIEW_CLOSE, Role::PushButton, "Close", Rect::default(), FRAME).doing(click("Close the preview", keys("Escape"))), ]; - Snapshot { fixed, rows: self.no_rows(), focus: Focus::Node(PREVIEW), window_focused: app.has_keyboard, dir: self.dir.clone(), text_geometry: Vec::new(), edit_gen: 0, news: News::default(), modal: None } + // In caret mode the keyboard is on the caret's line, which a screen reader reads as the + // caret moves. Each line is a new one, not an edit of the last (`edit_gen`): its caret is + // said to move, and the line is read from there. + let (mut focus, mut edit_gen) = (Focus::Node(PREVIEW), 0); + if let Some(c) = caret { + fixed[1].children.push(PREVIEW_CARET_LINE); + let mut n = Node::new(PREVIEW_CARET_LINE, Role::Paragraph, "", c.rect.intersect(area), PREVIEW); + n.field = Some(c.field); + fixed.push(n); + focus = Focus::Node(PREVIEW_CARET_LINE); + edit_gen = c.line.wrapping_add(1); + } + let news = News { caret_mode: focus != Focus::Node(PREVIEW), ..News::default() }; + Snapshot { fixed, rows: self.no_rows(), focus, window_focused: app.has_keyboard, dir: self.dir.clone(), text_geometry: Vec::new(), edit_gen, news, modal: None } } } @@ -1035,6 +1063,17 @@ pub struct PreviewText { pub foot: Rect, /// Whether there's a file before it and after it. pub can_step: (bool, bool), + /// In caret mode, the line the caret is on. + pub caret: Option, +} + +/// The line of a document the caret is on, its caret and selection, as a field has them. +pub struct CaretLine { + pub field: Field, + /// Which line of which layout it is, so moving to another, or the same laid out again, is a + /// new line, not an edit. + pub line: u64, + pub rect: Rect, } /// The menu open, if one is: its parts, the menu first, and the part with the keyboard. That's @@ -1350,7 +1389,7 @@ fn panel(app: &App, l: &Layout) -> (Node, Vec, News) { parts.push(Node::new(DISMISS0 + i as u64, Role::PushButton, "Dismiss", close(first + i), NOTICES).described(text.clone()).showing(shown).doing(click("Dismiss the notice", ""))); } let panel = Node::new(NOTICES, Role::Panel, "Notices", l.notices, FRAME).showing(l.notices.h > 0).with_children(parts.iter().map(|n| n.id).collect()); - let news = News { posted: app.notices_posted, notices: app.notices.clone(), info: app.info_notices.clone(), jobs, ended: app.jobs_ended.clone(), name_refused: app.name_refused.clone(), gone_said: app.gone_said.clone() }; + let news = News { posted: app.notices_posted, notices: app.notices.clone(), info: app.info_notices.clone(), jobs, ended: app.jobs_ended.clone(), name_refused: app.name_refused.clone(), gone_said: app.gone_said.clone(), caret_mode: false }; (panel, parts, news) } diff --git a/crates/app/src/a11y_atspi.rs b/crates/app/src/a11y_atspi.rs index 5e4864f..e4beaf8 100644 --- a/crates/app/src/a11y_atspi.rs +++ b/crates/app/src/a11y_atspi.rs @@ -244,6 +244,7 @@ fn role_of(r: Role) -> (u32, &'static str) { Role::Label => (29, "label"), Role::Heading => (83, "heading"), Role::Document => (82, "document frame"), + Role::Paragraph => (73, "paragraph"), Role::Table => (55, "table"), Role::ColumnHeader => (10, "column header"), Role::Link => (88, "link"), @@ -479,6 +480,14 @@ impl Ctx { _ => {} } } + // A document's line in caret mode is only read: the keys move its caret and select, and + // Ctrl+C copies. A screen reader asking to move them, or to edit it, is told no. + if let Target::Fixed(n) = &target + && n.role == Role::Paragraph + && (request || iface == EDITABLE_TEXT) + { + return self.reply(&h, &(false,)); + } match (iface, member.as_str()) { (PROPS, "Get") => { let Ok((i, name)) = body.deserialize::<(String, String)>() else { return self.error(&h, "org.freedesktop.DBus.Error.InvalidArgs", "") }; @@ -606,6 +615,7 @@ impl Ctx { Role::PasswordText => on.extend([STATE_FOCUSABLE, STATE_EDITABLE, STATE_SINGLE_LINE]), Role::MenuItem => on.extend([STATE_SELECTABLE, STATE_FOCUSABLE]), Role::Document => on.extend([STATE_FOCUSABLE, STATE_READ_ONLY]), + Role::Paragraph => on.extend([STATE_FOCUSABLE, STATE_READ_ONLY, STATE_SINGLE_LINE, STATE_SELECTABLE_TEXT]), Role::Table => on.extend([STATE_FOCUSABLE, STATE_MULTISELECTABLE, STATE_MANAGES_DESCENDANTS]), Role::ProgressBar if snap.news.jobs.iter().any(|j| a11y::JOB0 + j.id == n.id && j.percent.is_none()) => on.push(STATE_INDETERMINATE), Role::List => on.push(STATE_FOCUSABLE), @@ -772,8 +782,11 @@ impl Ctx { Target::Fixed(n) if n.role == Role::ProgressBar => v.push(VALUE), _ => {} } - if matches!(target, Target::Fixed(n) if n.field.is_some()) { - v.extend([TEXT, EDITABLE_TEXT]); + match target { + // A document's line is read, not typed in. + Target::Fixed(n) if n.field.is_some() && n.role == Role::Paragraph => v.push(TEXT), + Target::Fixed(n) if n.field.is_some() => v.extend([TEXT, EDITABLE_TEXT]), + _ => {} } self.reply(h, &(v,)) } @@ -1326,6 +1339,13 @@ impl Ctx { // new field under the same id, not an edit of the last. if old.edit_gen == new.edit_gen { self.emit_text_changes(&path, of, nf); + } else if n.role == Role::Paragraph { + // The caret went to another line of a document: its text isn't an edit, so + // only the caret is said to move, and a screen reader reads the line there. + self.event(&path, OBJECT_EVENT, "TextCaretMoved", ("", nf.chars_before(nf.caret) as i32), Variant::from(0i32)); + if of.has_selection() || nf.has_selection() { + self.event(&path, OBJECT_EVENT, "TextSelectionChanged", ("", 0), Variant::from(0i32)); + } } } // Whether it can be used: a menu or dialog opening over it, or closing, changes that. diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index acbd218..116c9ba 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -11327,6 +11327,274 @@ mod tests { assert_eq!(copied(&mut r), None, "what was selected isn't in what's showing now"); } + fn press(r: &mut Rig, sym: u32, ctrl: bool, shift: bool) { + r.app.key(sym, "", Mods { ctrl, shift, ..Mods::default() }); + } + + fn caret_at(r: &Rig) -> Option { + r.app.preview.as_ref().and_then(|p| p.caret).map(|c| c.caret.at) + } + + #[test] + fn caret_mode_selects_part_of_a_line_from_the_keyboard() { + let Some(mut r) = doc_rig("caret-keys", "DB_HOST=localhost\nDB_PASS=hunter2\n", false) else { return }; + assert_eq!(caret_at(&r), None, "off until F7"); + press(&mut r, k::KEY_F7, false, false); + assert_eq!(caret_at(&r), Some(0), "at the start of the visible text"); + press(&mut r, k::KEY_Right, true, false); + assert_eq!(caret_at(&r), Some(7), "past DB_HOST"); + press(&mut r, k::KEY_End, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("=localhost"), "Shift+End selects to the line's end"); + // Down without Shift lets the selection go, and keeps to the column over a shorter line. + press(&mut r, k::KEY_Down, false, false); + assert_eq!(copied(&mut r), None); + assert_eq!(caret_at(&r), Some(18 + 15), "the end of the shorter line"); + press(&mut r, k::KEY_Left, true, true); + assert_eq!(copied(&mut r).as_deref(), Some("hunter2"), "Ctrl+Shift+Left takes the word before"); + press(&mut r, k::KEY_Left, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("=hunter2"), "and Shift+Left grows it from where it started"); + press(&mut r, k::KEY_Home, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("DB_PASS=hunter2")); + press(&mut r, k::KEY_Up, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("DB_HOST=localhost\nDB_PASS=hunter2"), "a line up, from the same start"); + press(&mut r, k::KEY_End, true, false); + assert_eq!(caret_at(&r), Some(34), "Ctrl+End: the end, past the last break"); + press(&mut r, k::KEY_Home, true, true); + assert_eq!(copied(&mut r).as_deref(), Some("DB_HOST=localhost\nDB_PASS=hunter2\n"), "Ctrl+Shift+Home: all of it"); + // Escape turns caret mode off and leaves the window open; the next one closes it. + r.app.cmds.clear(); + r.key(k::KEY_Escape, ""); + assert!(caret_at(&r).is_none() && !r.app.cmds.iter().any(|c| matches!(c, Cmd::Quit))); + assert_eq!(copied(&mut r).as_deref(), Some("DB_HOST=localhost\nDB_PASS=hunter2\n"), "what's selected stays selected"); + press(&mut r, k::KEY_F7, false, false); + press(&mut r, k::KEY_F7, false, false); + assert!(caret_at(&r).is_none(), "F7 turns it off too"); + assert!(!r.app.cmds.iter().any(|c| matches!(c, Cmd::Quit))); + r.key(k::KEY_Escape, ""); + assert!(matches!(r.app.cmds.last(), Some(Cmd::Quit)), "closed"); + } + + #[test] + fn caret_mode_repaints_only_the_caret_lines_and_only_on_a_change() { + let text: String = (0..200).map(|i| format!("line {i}\n")).collect(); + let Some(mut r) = doc_rig("caret-paint", &text, false) else { return }; + let area = r.app.doc_area(); + press(&mut r, k::KEY_F7, false, false); + paint_all(&mut r); + r.app.dirty = Rect::default(); + press(&mut r, k::KEY_Left, false, false); + press(&mut r, k::KEY_Up, false, false); + press(&mut r, k::KEY_Home, false, false); + assert!(r.app.dirty.is_empty(), "nothing moved, nothing painted: {:?}", r.app.dirty); + press(&mut r, k::KEY_Down, false, false); + let h = r.app.preview.as_ref().unwrap().doc_layout.as_ref().unwrap().lines[0].h; + assert!(!r.app.dirty.is_empty() && r.app.dirty.h <= h * 2, "the two lines: {:?}", r.app.dirty); + // Off the bottom, the view scrolls to keep it in sight. + press(&mut r, k::KEY_End, true, false); + let p = r.app.preview.as_ref().unwrap(); + let (layout, line) = (p.doc_layout.as_ref().unwrap(), p.caret.unwrap().caret.line); + let l = &layout.lines[line]; + assert!(p.scroll > 0.0 && l.y as f64 >= p.scroll && (l.y + l.h) as f64 <= p.scroll + area.h as f64, "in view: {} at {}", l.y, p.scroll); + // Back to the top with Ctrl+Home. + press(&mut r, k::KEY_Home, true, false); + assert_eq!((caret_at(&r), r.app.preview.as_ref().unwrap().scroll), (Some(0), 0.0)); + } + + /// The colour painted at a point of the window. + fn pixel_at(r: &mut Rig, x: i32, y: i32) -> u32 { + let (w, h) = (r.app.w, r.app.h); + let mut pixels = vec![0u32; (w * h) as usize]; + let mut canvas = crate::canvas::Canvas::new(&mut pixels, w, h); + canvas.set_clip(Rect::new(0, 0, w, h)); + r.app.paint(&mut canvas); + pixels[(y * w + x) as usize] & 0xffffff + } + + #[test] + fn the_caret_is_drawn_only_in_caret_mode_and_a_click_moves_it() { + let Some(mut r) = doc_rig("caret-draw", " spaced\nnext\n", false) else { return }; + let (x, y) = doc_point(&mut r, 0, 0.0); + let (x, y) = (x as i32 - 1, y as i32); + let (base, text) = (r.app.colors.base, r.app.colors.foreground); + assert_eq!(pixel_at(&mut r, x, y), base, "no caret while it's off"); + press(&mut r, k::KEY_F7, false, false); + assert_eq!(pixel_at(&mut r, x, y), text, "the caret, in the text's colour"); + // At the start of a selection, the half over it is in the selection's text colour. + press(&mut r, k::KEY_Right, false, false); + press(&mut r, k::KEY_Left, false, true); + assert_eq!(caret_at(&r), Some(0)); + let (selection, on_selection) = (r.app.colors.selection, r.app.colors.on_selection); + assert_eq!(pixel_at(&mut r, x, y), on_selection, "over the selection, in its text colour"); + assert_eq!(pixel_at(&mut r, x - 1, y), text, "beside it, in the text's colour"); + assert_eq!(pixel_at(&mut r, x + 3, y), selection); + // A click puts the caret where it was. + let at = doc_point(&mut r, 1, 2.0); + click_at(&mut r, at); + let p = r.app.preview.as_ref().unwrap(); + assert_eq!(p.caret.map(|c| (c.caret.at, c.caret.line)), Some((11 + 2, 1))); + press(&mut r, k::KEY_End, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("xt")); + } + + #[test] + fn a_word_or_line_clicked_in_caret_mode_grows_from_its_start_with_shift() { + let Some(mut r) = doc_rig("caret-click-word", "DB_PASS=hunter2 more\nnext line\n", false) else { return }; + press(&mut r, k::KEY_F7, false, false); + // A double click in the middle of hunter2. + let on = doc_point(&mut r, 0, 11.0); + click_at(&mut r, on); + click_at(&mut r, on); + assert_eq!(copied(&mut r).as_deref(), Some("hunter2")); + assert_eq!(caret_at(&r), Some(15), "the caret at the word's end"); + press(&mut r, k::KEY_Right, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("hunter2 "), "Shift+Right takes one more"); + let line = a11y_snapshot(&mut r.app).get(crate::a11y::PREVIEW_CARET_LINE).unwrap().field.clone().unwrap(); + assert_eq!((line.caret, line.anchor), (16, 8), "a screen reader has the same ends"); + // A third click takes the line, and Shift+Left gives back its last character. + std::thread::sleep(Duration::from_millis(450)); + click_at(&mut r, on); + click_at(&mut r, on); + click_at(&mut r, on); + assert_eq!(caret_at(&r), Some(20)); + press(&mut r, k::KEY_Left, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("DB_PASS=hunter2 mor")); + } + + #[test] + fn escape_held_in_caret_mode_leaves_it_without_closing_the_window() { + let Some(mut r) = doc_rig("caret-escape-repeat", "some text\n", false) else { return }; + press(&mut r, k::KEY_F7, false, false); + r.app.cmds.clear(); + r.key(k::KEY_Escape, ""); + assert_eq!(caret_at(&r), None); + r.app.key_is_repeat = true; + for _ in 0..5 { + r.key(k::KEY_Escape, ""); + } + r.app.key_is_repeat = false; + assert!(!r.app.cmds.iter().any(|c| matches!(c, Cmd::Quit)), "the repeats are swallowed"); + r.key(k::KEY_Escape, ""); + assert!(matches!(r.app.cmds.last(), Some(Cmd::Quit)), "a second press closes it"); + // Escape repeating without having just left caret mode still closes, as it did. + let Some(mut r) = doc_rig("caret-escape-plain", "some text\n", false) else { return }; + r.app.key_is_repeat = true; + r.key(k::KEY_Escape, ""); + assert!(matches!(r.app.cmds.last(), Some(Cmd::Quit))); + } + + #[test] + fn ctrl_a_in_caret_mode_puts_the_caret_at_the_end_to_grow_back_from() { + let Some(mut r) = doc_rig("caret-ctrl-a", "one two\nthree\n", false) else { return }; + press(&mut r, k::KEY_F7, false, false); + press(&mut r, k::KEY_Right, false, false); + r.ctrl(k::KEY_a); + assert_eq!(caret_at(&r), Some(14)); + assert_eq!(r.app.preview.as_ref().unwrap().scroll, 0.0); + press(&mut r, k::KEY_Left, false, true); + assert_eq!(copied(&mut r).as_deref(), Some("one two\nthree"), "Shift+Left gives back the last break"); + } + + #[test] + fn ctrl_a_in_caret_mode_leaves_the_view_where_it_is() { + let text: String = (0..300).map(|i| format!("line {i}\n")).collect(); + let Some(mut r) = doc_rig("caret-ctrl-a-view", &text, false) else { return }; + press(&mut r, k::KEY_F7, false, false); + r.ctrl(k::KEY_a); + let p = r.app.preview.as_ref().unwrap(); + assert_eq!((caret_at(&r), p.scroll), (Some(p.doc_layout.as_ref().unwrap().total), 0.0), "the caret at the end, the view at the top"); + press(&mut r, k::KEY_Left, false, true); + assert!(r.app.preview.as_ref().unwrap().scroll > 0.0, "the next arrow goes to the caret"); + } + + #[test] + fn a_resize_leaves_a_caret_scrolled_away_where_it_is() { + let text: String = (0..300).map(|i| format!("line {i}\n")).collect(); + let Some(mut r) = doc_rig("caret-relayout-away", &text, false) else { return }; + press(&mut r, k::KEY_F7, false, false); + // The wheel takes the view well past the caret, on the first line. + r.app.preview_scroll(60.0, 0.0); + let scrolled = r.app.preview.as_ref().unwrap().scroll; + assert!(scrolled > 1000.0); + let (w, h) = (r.app.w, r.app.h); + r.app.resized(w - 40, h, 1.0); + paint_all(&mut r); + let p = r.app.preview.as_ref().unwrap(); + assert_eq!(p.caret.unwrap().caret.at, 0); + assert!(p.scroll > 1000.0, "not snapped back to the caret: {}", p.scroll); + } + + #[test] + fn caret_mode_takes_the_arrows_and_escape_off_the_preview_buttons() { + use crate::a11y::{PREVIEW_CLOSE, PREVIEW_NEXT, PREVIEW_PREVIOUS}; + let Some(mut r) = doc_rig("caret-hints", "text\n", false) else { return }; + let keys = |s: &crate::a11y::Snapshot| [PREVIEW_PREVIOUS, PREVIEW_NEXT, PREVIEW_CLOSE].map(|id| s.get(id).unwrap().action.unwrap().keys); + assert_eq!(keys(&a11y_snapshot(&mut r.app)), ["Left", "Right", "Escape"]); + press(&mut r, k::KEY_F7, false, false); + assert_eq!(keys(&a11y_snapshot(&mut r.app)), ["", "", ""]); + } + + #[test] + fn a_resize_keeps_the_caret_at_a_wrapped_lines_end_in_view_and_tells_a_new_line() { + let text = format!("{}\n{}", "word ".repeat(80), "line\n".repeat(300)); + let Some(mut r) = doc_rig("caret-relayout", &text, false) else { return }; + press(&mut r, k::KEY_F7, false, false); + press(&mut r, k::KEY_End, false, false); + let end = r.app.preview.as_ref().unwrap().caret.unwrap().caret; + assert_eq!(end.line, 0, "the end of the first wrapped line"); + let before = a11y_snapshot(&mut r.app); + let (w, h) = (r.app.w, r.app.h); + // A pixel narrower: laid out again, with the same number of columns. + r.app.resized(w - 1, h, 1.0); + paint_all(&mut r); + let p = r.app.preview.as_ref().unwrap(); + let (layout, c) = (p.doc_layout.as_ref().unwrap(), p.caret.unwrap().caret); + let l = &layout.lines[c.line]; + assert_eq!(c.at, end.at, "the same place in the text"); + assert!(l.end == crate::docview::End::Wrap && l.at + l.len() == c.at, "still drawn at a line's end"); + // Down at the bottom, then a resize: still in view. + press(&mut r, k::KEY_End, true, false); + r.app.resized(w / 2, h, 1.0); + paint_all(&mut r); + let p = r.app.preview.as_ref().unwrap(); + let (layout, c) = (p.doc_layout.as_ref().unwrap(), p.caret.unwrap().caret); + let l = &layout.lines[c.line]; + let area = r.app.doc_area(); + assert!(l.y as f64 >= p.scroll && (l.y + l.h) as f64 <= p.scroll + area.h as f64, "in view after the resize"); + assert_ne!(a11y_snapshot(&mut r.app).edit_gen, before.edit_gen); + // The first: laid out again at the same index, still a new line to a screen reader. + press(&mut r, k::KEY_Home, true, false); + let s = a11y_snapshot(&mut r.app); + r.app.resized(w, h, 1.0); + paint_all(&mut r); + assert_ne!(a11y_snapshot(&mut r.app).edit_gen, s.edit_gen, "laid out again, so not an edit"); + } + + #[test] + fn a_screen_reader_hears_caret_mode_and_the_line_the_caret_is_on() { + use crate::a11y::{Focus, PREVIEW, PREVIEW_CARET_LINE}; + let Some(mut r) = doc_rig("caret-a11y", "first line\n\n| A | B |\n|---|---|\n| x | y |\n", true) else { return }; + let off = a11y_snapshot(&mut r.app); + assert!(off.get(PREVIEW_CARET_LINE).is_none() && off.focus == Focus::Node(PREVIEW)); + press(&mut r, k::KEY_F7, false, false); + let on = a11y_snapshot(&mut r.app); + let line = on.get(PREVIEW_CARET_LINE).expect("the caret's line"); + assert_eq!(on.focus, Focus::Node(PREVIEW_CARET_LINE), "it has the keyboard"); + assert_eq!((line.field.as_ref().unwrap().text.as_str(), line.field.as_ref().unwrap().caret), ("first line", 0)); + assert!(on.get(PREVIEW).unwrap().children.contains(&PREVIEW_CARET_LINE)); + assert_eq!(on.news_since(&off), [("Caret mode on".to_string(), false)]); + // Down to the table's header, then Shift+Right: the line, its caret and selection. + press(&mut r, k::KEY_Down, false, false); + press(&mut r, k::KEY_Right, false, true); + let moved = a11y_snapshot(&mut r.app); + let f = moved.get(PREVIEW_CARET_LINE).unwrap().field.clone().unwrap(); + assert_eq!((f.text.as_str(), f.caret, f.anchor), ("A B", 1, 0)); + assert_ne!(moved.edit_gen, on.edit_gen, "another line, not an edit of the first"); + press(&mut r, k::KEY_F7, false, false); + let back = a11y_snapshot(&mut r.app); + assert!(back.get(PREVIEW_CARET_LINE).is_none() && back.focus == Focus::Node(PREVIEW)); + assert_eq!(back.news_since(&moved), [("Caret mode off".to_string(), false)]); + } + #[test] fn a_scroll_before_the_first_layout_isnt_lost() { use crate::preview::{Event, Found, Info}; diff --git a/crates/app/src/docview.rs b/crates/app/src/docview.rs index a377976..400ecb0 100644 --- a/crates/app/src/docview.rs +++ b/crates/app/src/docview.rs @@ -309,6 +309,11 @@ impl Layout { return 0; } let Some(line) = self.lines.get(self.line_at(y)) else { return self.total }; + Self::along(line, x, fonts, nearest) + } + + /// The offset in a line nearest `x`, or before the character under it. + fn along(line: &Line, x: f32, fonts: &mut Fonts, nearest: bool) -> usize { let mut at = line.at; for p in &line.pieces { if x < p.x { @@ -339,7 +344,7 @@ impl Layout { let end = start + p.text.len(); if at < end || (at == end && std::ptr::eq(p, line.pieces.last().unwrap_or(p))) { let i = floor_char(&p.text, at - start); - let word = |c: char| c.is_alphanumeric() || c == '_'; + let word = is_word; let after = p.text[i..].chars().next(); if !after.is_some_and(word) { // Past a word's end, at a space or the line's end, it's that word. @@ -373,6 +378,179 @@ impl Layout { (self.lines[first].at, l.at + l.len()) } + /// The character just after an offset and the offset after it. A line break is a `'\n'`, one + /// place long; where a line wraps, its end is the next line's start, so it's that line's + /// first character. Nothing at the end. + pub fn char_after(&self, at: usize) -> Option<(char, usize)> { + let mut i = self.line_of(at); + while let Some(l) = self.lines.get(i) { + let end = l.at + l.len(); + if at < end { + let mut start = l.at; + for p in &l.pieces { + if at < start + p.text.len() { + let k = floor_char(&p.text, at.max(start) - start); + let c = p.text[k..].chars().next()?; + return Some((c, start + k + c.len_utf8())); + } + start += p.text.len(); + } + return None; + } + if l.end.units() > 0 { + return (at == end).then_some(('\n', end + 1)); + } + i += 1; + } + None + } + + /// The character just before an offset and the offset before it, as `char_after` has them. + pub fn char_before(&self, at: usize) -> Option<(char, usize)> { + // The last line that starts before it: past a wrap, that's the line it ends. + let i = self.lines.partition_point(|l| l.at < at).checked_sub(1)?; + let l = &self.lines[i]; + let end = l.at + l.len(); + if at > end { + return Some(('\n', end)); + } + let mut start = l.at; + for p in &l.pieces { + if at <= start + p.text.len() && at > start { + let k = floor_char(&p.text, at - start); + let (b, c) = p.text[..k].char_indices().next_back()?; + return Some((c, start + b)); + } + start += p.text.len(); + } + None + } + + /// The line a caret at an offset is drawn on: `hint` while the offset is on it, so the end + /// of a wrapped line stays at that end; otherwise the last line starting at or before it, + /// which puts it at the start of the next line. Never a rule, which has no text. + pub fn caret_line(&self, at: usize, hint: Option) -> usize { + let on = |i: usize| self.lines.get(i).is_some_and(|l| l.mark != Mark::Rule && l.at <= at && at <= l.at + l.len()); + if let Some(i) = hint.filter(|&i| on(i)) { + return i; + } + let last = self.lines.partition_point(|l| l.at <= at).saturating_sub(1); + (0..=last).rev().find(|&i| self.lines[i].mark != Mark::Rule).unwrap_or(last) + } + + /// Where a caret goes on its line, in the layout's pixels, and the face of what's there. At + /// a place between two pieces, it's at the start of the second. + pub fn caret_x(&self, c: Caret, fonts: &mut Fonts) -> (f32, Face) { + let Some(line) = self.lines.get(c.line) else { return (fonts.px(spacing::DOC_MARGIN) as f32, Face::Body) }; + let mut start = line.at; + let n = line.pieces.len(); + for (k, p) in line.pieces.iter().enumerate() { + let end = start + p.text.len(); + if c.at < end || k + 1 == n { + let byte = floor_char(&p.text, c.at.clamp(start, end) - start); + let x = stops(p, fonts).iter().find(|s| s.0 == byte).map_or(0.0, |s| s.1); + return (p.x + x, p.face); + } + start = end; + } + // A line with no text: an empty table row, an item with nothing in it, or an empty line of + // a code block or quote. It's where its text would start. + let x = match (&line.mark, &line.marker) { + (Mark::Table { left, .. }, _) => (left + fonts.px(spacing::SPACE_10)) as f32, + (_, Some((x, marker))) => x + fonts.get(Face::Body).measure(marker) + fonts.px(spacing::SPACE_8) as f32, + (Mark::Code(left, _), _) => (left + fonts.px(spacing::SPACE_10)) as f32, + _ => (fonts.px(spacing::DOC_MARGIN) + line.quote as i32 * fonts.px(spacing::DOC_QUOTE)) as f32, + }; + (x, Face::Body) + } + + /// The caret moved one character left or right, over a line break as one. + pub fn caret_step(&self, c: Caret, right: bool) -> Caret { + let next = if right { self.char_after(c.at) } else { self.char_before(c.at) }; + next.map_or(c, |(_, at)| Caret { at, line: self.caret_line(at, Some(c.line)) }) + } + + /// The caret moved by a word: right to the end of the next word, left to the start of the + /// one before, as a text field moves. A word is letters, digits and `_`, as a double click + /// finds one. + pub fn caret_word(&self, c: Caret, right: bool) -> Caret { + let step = |at: usize| if right { self.char_after(at) } else { self.char_before(at) }; + let mut at = c.at; + while let Some((_, next)) = step(at).filter(|(ch, _)| !is_word(*ch)) { + at = next; + } + while let Some((_, next)) = step(at).filter(|(ch, _)| is_word(*ch)) { + at = next; + } + Caret { at, line: self.caret_line(at, Some(c.line)) } + } + + /// The caret moved a line up or down, as near `x` as that line has a place, past rules. + /// From the first line up, it goes to the start; from the last down, to the end. + pub fn caret_vertical(&self, c: Caret, down: bool, x: f32, fonts: &mut Fonts) -> Caret { + let mut i = c.line; + loop { + let next = if down { i.checked_add(1).filter(|&n| n < self.lines.len()) } else { i.checked_sub(1) }; + let Some(n) = next else { + return if down { self.line_end(c.line) } else { self.line_start(0) }; + }; + i = n; + if self.lines[i].mark != Mark::Rule { + break; + } + } + Caret { at: Self::along(&self.lines[i], x, fonts, true), line: i } + } + + /// The caret at the start of a line as it's shown: Home. + pub fn line_start(&self, line: usize) -> Caret { + let line = self.caret_line(self.lines.get(line).map_or(0, |l| l.at), Some(line)); + Caret { at: self.lines.get(line).map_or(0, |l| l.at), line } + } + + /// The caret at the end of a line as it's shown, before its break: End. + pub fn line_end(&self, line: usize) -> Caret { + match self.lines.get(line) { + Some(l) => Caret { at: l.at + l.len(), line }, + None => Caret { at: self.total, line: self.caret_line(self.total, None) }, + } + } + + /// A line's text for a screen reader, with a space between table cells that have none, and + /// where a caret at `at` and the selection's other end (see `CaretMode::other_end`) fall in + /// it, as bytes. An offset before the line is its start, and one after it its end. + pub fn line_for_reading(&self, line: usize, at: usize, other: Option) -> (String, usize, usize) { + let Some(l) = self.lines.get(line) else { return (String::new(), 0, 0) }; + let mut text = String::new(); + // Where each piece starts among the offsets and in the text, and how long it is. + let mut places: Vec<(usize, usize, usize)> = Vec::new(); + let mut start = l.at; + for (k, p) in l.pieces.iter().enumerate() { + if k > 0 && p.col != l.pieces[k - 1].col && !text.ends_with(char::is_whitespace) && !text.is_empty() { + text.push(' '); + } + places.push((start, text.len(), p.text.len())); + text.push_str(&p.text); + start += p.text.len(); + } + let end = start; + let place = |off: usize| -> usize { + if off <= l.at { + return 0; + } + if off >= end { + return text.len(); + } + // Between two cells, it's at the end of the first. + let &(from, to, _) = places.iter().find(|(from, _, len)| off <= from + len).unwrap_or(&(l.at, 0, 0)); + to + off.saturating_sub(from) + }; + let caret = place(at); + let caret = floor_char(&text, caret); + let anchor = other.map_or(caret, |o| floor_char(&text, place(o))); + (text, caret, anchor) + } + /// The text between two offsets, as copying gives it. pub fn text(&self, from: usize, to: usize) -> String { let (from, to) = (from.min(to), from.max(to)); @@ -425,6 +603,19 @@ impl Layout { } } +/// Caret mode's caret: an offset among the text's (see `Layout::text`), and the line it's drawn +/// on, as the end of a wrapped line and the start of the next are the same offset. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Caret { + pub at: usize, + pub line: usize, +} + +/// What a word is made of, to the caret and a double click. +fn is_word(c: char) -> bool { + c.is_alphanumeric() || c == '_' +} + /// The last character boundary at or before `i`. fn floor_char(s: &str, i: usize) -> usize { let mut i = i.min(s.len()); @@ -847,8 +1038,9 @@ pub struct Ink { } /// Draws the lines in view, `scroll` pixels down, inside `area`. `selected` is a range of -/// offsets, drawn in the selection's colours. -pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &mut Fonts, ink: Ink, selected: Option<(usize, usize)>) { +/// offsets, drawn in the selection's colours, and `caret` caret mode's caret. +#[allow(clippy::too_many_arguments)] +pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &mut Fonts, ink: Ink, selected: Option<(usize, usize)>, caret: Option) { let selected = selected.filter(|(a, b)| a < b); let bar = fonts.px(size::QUOTE_BAR).max(1); let pad = fonts.px(spacing::DOC_MARGIN); @@ -967,6 +1159,9 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m c.fill(Rect::new(ends_at.floor() as i32, y, fonts.px(size::LINE_END_MARK).max(2), line.h), ink.selection); } } + if let Some(at) = caret { + paint_caret(c, area, scroll, layout, fonts, ink, selected, at); + } // Where in the document this is, when there's more of it than fits. if layout.height > area.h && area.h > 0 { let track = area.h - fonts.px(spacing::SPACE_8); @@ -978,6 +1173,31 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m } } +/// The caret: a bar as tall as the text where it is, in the text's colour on the background and +/// in the selection's text colour on the selection. At an edge of the selection it's half in +/// each, so each half stands out from what it's on (see the `doc-caret` token). +#[allow(clippy::too_many_arguments)] +fn paint_caret(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &mut Fonts, ink: Ink, selected: Option<(usize, usize)>, caret: Caret) { + let Some(line) = layout.lines.get(caret.line) else { return }; + let (x, face) = layout.caret_x(caret, fonts); + let t = fonts.get(face); + let y = area.y - scroll + line.y; + let top = (y + line.baseline - t.ascent.round() as i32).max(y); + let h = (t.line_height().ceil() as i32).min(y + line.h - top); + let w = fonts.px(size::DOC_CARET).max(2); + let x = (area.x as f32 + x).round() as i32; + // Whether the selection is drawn just left of it on this line, and just right of it: a + // character, or the mark past the line's end for its break. + let end = line.at + line.len(); + let (at, sel) = (caret.at, selected.filter(|(a, b)| a < b)); + let on_left = sel.is_some_and(|(a, b)| a < at && at <= b && at > line.at); + let on_right = sel.is_some_and(|(a, b)| a <= at && at < b && (at < end || line.end.units() > 0)); + let (left, right) = (Rect::new(x - w / 2, top, w / 2, h), Rect::new(x, top, w - w / 2, h)); + let colour = |selected: bool| if selected { ink.on_selection } else { ink.text }; + c.fill(left, colour(on_left)); + c.fill(right, colour(on_right)); +} + #[cfg(test)] mod tests { use super::*; @@ -1246,6 +1466,141 @@ mod tests { assert_eq!(layout.lines.len(), 3, "two tables, the first of two rows"); } + /// Where a caret ends up after each of `steps` from `c`, as offsets. + fn walk(layout: &Layout, mut c: Caret, steps: usize, step: impl Fn(&Layout, Caret) -> Caret) -> Vec { + (0..steps) + .map(|_| { + c = step(layout, c); + c.at + }) + .collect() + } + + #[test] + fn the_caret_steps_by_characters_over_line_breaks_and_wide_ones() { + let Some(mut fonts) = fonts() else { return }; + let layout = lay_out(&doc::plain("ab\né\n".into(), false), 800, &mut fonts); + let start = layout.line_start(0); + assert_eq!(walk(&layout, start, 6, |l, c| l.caret_step(c, true)), [1, 2, 3, 5, 6, 6], "é is two bytes, a break one place, and the end stays put"); + let end = Caret { at: layout.total, line: layout.caret_line(layout.total, None) }; + assert_eq!(walk(&layout, end, 6, |l, c| l.caret_step(c, false)), [5, 3, 2, 1, 0, 0]); + // Across the break, the caret goes to the next line's start. + let c = layout.caret_step(Caret { at: 2, line: 0 }, true); + assert_eq!(c, Caret { at: 3, line: 1 }); + assert_eq!(layout.text(0, 5), "ab\né", "what the steps cover copies as the file has it"); + } + + #[test] + fn the_caret_moves_by_words_to_their_ends_right_and_starts_left() { + let Some(mut fonts) = fonts() else { return }; + let text = "one two_x, three\nfour"; + let layout = lay_out(&doc::plain(text.into(), false), 800, &mut fonts); + let start = layout.line_start(0); + assert_eq!(walk(&layout, start, 5, |l, c| l.caret_word(c, true)), [3, 9, 16, 21, 21], "_ is part of a word, and the break is passed over"); + let end = Caret { at: layout.total, line: 1 }; + assert_eq!(walk(&layout, end, 5, |l, c| l.caret_word(c, false)), [17, 11, 4, 0, 0]); + let c = layout.caret_word(start, true); + assert_eq!(layout.text(0, c.at), "one"); + } + + #[test] + fn up_and_down_keep_to_a_column_over_shorter_lines() { + let Some(mut fonts) = fonts() else { return }; + let layout = lay_out(&doc::plain("a long line here\nab\nanother line\n".into(), false), 800, &mut fonts); + let c = Caret { at: 10, line: 0 }; + let (x, _) = layout.caret_x(c, &mut fonts); + let down = layout.caret_vertical(c, true, x, &mut fonts); + assert_eq!(down, layout.line_end(1), "a short line's end"); + let again = layout.caret_vertical(down, true, x, &mut fonts); + assert_eq!(again, Caret { at: layout.lines[2].at + 10, line: 2 }, "back to the column it started in"); + let up = layout.caret_vertical(layout.caret_vertical(again, false, x, &mut fonts), false, x, &mut fonts); + assert_eq!(up, c); + // Past the first line it goes to the start, and past the last to the end. + assert_eq!(layout.caret_vertical(c, false, x, &mut fonts), layout.line_start(0)); + let last = layout.lines.len() - 1; + assert_eq!(layout.caret_vertical(Caret { at: layout.lines[last].at, line: last }, true, x, &mut fonts), layout.line_end(last)); + } + + #[test] + fn home_and_end_go_to_the_ends_of_the_line_as_its_shown() { + let Some(mut fonts) = fonts() else { return }; + let text = format!("{}\nnext\n", "word ".repeat(60)); + let layout = lay_out(&doc::plain(text, false), 300, &mut fonts); + assert!(layout.lines.len() > 3 && layout.lines[0].end == End::Wrap, "it wrapped"); + let end = layout.line_end(0); + assert_eq!(end.at, layout.lines[1].at, "the end of a wrapped line is the next one's start"); + assert_eq!(end.line, 0, "but it's drawn at the end of its own line"); + assert!(layout.caret_x(end, &mut fonts).0 > layout.caret_x(layout.line_start(1), &mut fonts).0); + assert_eq!(layout.line_start(1), Caret { at: layout.lines[1].at, line: 1 }); + // Right from the end of a wrapped line goes past the next line's first character, and + // left from there back to that line's start. + let right = layout.caret_step(end, true); + assert_eq!(right, Caret { at: layout.lines[1].at + 1, line: 1 }); + assert_eq!(layout.caret_step(right, false), layout.line_start(1)); + // Down from a line's start keeps to the left. + assert_eq!(layout.caret_vertical(layout.line_start(0), true, layout.caret_x(layout.line_start(0), &mut fonts).0, &mut fonts), layout.line_start(1)); + // Home and End on the whole wrapped line, selected with Shift, copy it as one. + let last = layout.lines.iter().position(|l| l.end != End::Wrap).unwrap(); + assert_eq!(layout.text(layout.line_start(0).at, layout.line_end(last).at), "word ".repeat(60)); + } + + #[test] + fn a_tab_is_one_step_and_its_columns_count_for_up_and_down() { + let Some(mut fonts) = fonts() else { return }; + let layout = lay_out(&doc::plain("\tx\nabcdefgh\n".into(), false), 800, &mut fonts); + let advance = fonts.get(Face::Mono).measure("0"); + let after_tab = layout.caret_step(layout.line_start(0), true); + assert_eq!(after_tab.at, 1, "the tab is one character"); + let (x, _) = layout.caret_x(after_tab, &mut fonts); + assert!((x - (layout.lines[0].pieces[0].x + advance * 4.0)).abs() < 0.5, "drawn at the tab's stop"); + let down = layout.caret_vertical(after_tab, true, x, &mut fonts); + assert_eq!(down.at - layout.lines[1].at, 4, "the fifth column below it"); + assert_eq!(layout.caret_vertical(down, false, x, &mut fonts), after_tab); + assert_eq!(layout.text(0, 1), "\t", "it copies as a tab"); + } + + #[test] + fn the_caret_walks_a_markdown_table_cell_by_cell_and_passes_rules() { + let Some(mut fonts) = fonts() else { return }; + let layout = lay_out(&doc::markdown("Above.\n\n---\n\n| Key | Value |\n|---|---|\n| a | 1 |\n", false), 800, &mut fonts); + let rule = layout.lines.iter().position(|l| l.mark == Mark::Rule).unwrap(); + let x = layout.caret_x(layout.line_start(0), &mut fonts).0; + let below = layout.caret_vertical(layout.line_start(0), true, x, &mut fonts); + assert_eq!(below.line, rule + 1, "the rule is passed over"); + assert_eq!(layout.caret_vertical(below, false, x, &mut fonts).line, 0); + let row = layout.lines.len() - 1; + let start = layout.line_start(row); + // a, then 1: the step from a's end is past the next cell's first character. + assert_eq!(walk(&layout, start, 3, |l, c| l.caret_step(c, true)).iter().map(|&at| at - start.at).collect::>(), [1, 2, 3]); + let end = layout.line_end(row); + assert_eq!(layout.text(start.at, end.at), "a\t1", "a row selected from Home to End copies cell by cell"); + assert!(layout.caret_x(end, &mut fonts).0 > layout.caret_x(Caret { at: start.at + 1, line: row }, &mut fonts).0, "1 is to the right of a"); + // Down from the header's start lands on the row's first cell. + let header = row - 1; + let x = layout.caret_x(layout.line_start(header), &mut fonts).0; + assert_eq!(layout.caret_vertical(layout.line_start(header), true, x, &mut fonts), start); + assert_eq!(layout.text(layout.line_start(header).at, end.at), "Key\tValue\na\t1"); + // A screen reader reads the row with its cells apart. + assert_eq!(layout.line_for_reading(row, start.at + 1, Some(start.at)), ("a 1".to_string(), 1, 0)); + assert_eq!(layout.line_for_reading(row, end.at, None), ("a 1".to_string(), 3, 3)); + } + + #[test] + fn on_an_empty_item_or_quote_line_the_caret_is_where_its_text_would_be() { + let Some(mut fonts) = fonts() else { return }; + let layout = lay_out(&doc::markdown("- one\n-\n\n> quoted\n", false), 800, &mut fonts); + let item = layout.lines.iter().position(|l| l.pieces.is_empty() && l.marker.is_some()).expect("the empty item"); + let one = layout.caret_x(layout.line_start(0), &mut fonts).0; + assert!((layout.caret_x(layout.line_start(item), &mut fonts).0 - one).abs() < 1.0, "under the first item's text"); + // An empty line in a quote, made as a quote's line with its words taken out. + let quoted = layout.lines.iter().position(|l| l.quote > 0).unwrap(); + let q = &layout.lines[quoted]; + let empty = Line { y: q.y, h: q.h, baseline: q.baseline, quote: q.quote, mark: Mark::None, marker: None, pieces: Vec::new(), at: 0, end: q.end }; + let alone = Layout { width: 800, generation: 0, height: 100, lines: vec![empty], total: 0 }; + let inside = layout.caret_x(layout.line_start(quoted), &mut fonts).0; + assert!((alone.caret_x(Caret { at: 0, line: 0 }, &mut fonts).0 - inside).abs() < 1.0, "inside the quote"); + } + #[test] fn words_keep_their_spaces_and_breaks() { let got: Vec<&str> = words("one two three\nfour").collect(); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index e4084c7..786dca8 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1123,7 +1123,7 @@ mod bench { }; let doc = match (&p.content, &p.doc_layout) { (Content::Doc { doc, .. }, layout) => format!( - "{{\"blocks\":{},\"cut\":{},\"lines\":{},\"scroll\":{:.0},\"height\":{},\"width\":{},\"table_lines\":{},\"table_right\":{},\"text\":{},\"selected\":{},\"line_starts\":[{}]}}", + "{{\"blocks\":{},\"cut\":{},\"lines\":{},\"scroll\":{:.0},\"height\":{},\"width\":{},\"table_lines\":{},\"table_right\":{},\"text\":{},\"selected\":{},\"caret\":{},\"line_starts\":[{}]}}", doc.blocks.len(), doc.cut, layout.as_ref().map_or(0, |l| l.lines.len()), @@ -1134,6 +1134,8 @@ mod bench { layout.as_ref().and_then(|l| l.lines.iter().find_map(|l| match l.mark { crate::docview::Mark::Table { right, .. } => Some(right), _ => None })).unwrap_or(0), esc(&doc.blocks.iter().take(3).flat_map(|b| b.spans.iter().map(|s| s.text.as_str())).collect::().chars().take(200).collect::()), esc(&layout.as_ref().zip(p.text_sel).map(|(l, s)| l.text(s.range.0, s.range.1)).unwrap_or_default()), + // Caret mode's caret, as its offset and line. + p.caret.map_or("null".to_string(), |c| format!("[{},{}]", c.caret.at, c.caret.line)), // Where the first lines' text starts, in the window's pixels at their middle. layout.as_ref().map_or(String::new(), |l| { let area = a.doc_text_area(); diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rs index b9f1cc1..096e01d 100644 --- a/crates/app/src/preview.rs +++ b/crates/app/src/preview.rs @@ -975,6 +975,26 @@ pub struct TextSel { held: bool, } +/// Caret mode: a caret moved through a document's text from the keyboard, to select part of it. +/// It doesn't blink, so nothing runs while it's on, and nothing of it is kept while it's off. +#[derive(Clone, Copy, Debug)] +pub struct CaretMode { + pub caret: docview::Caret, + /// Where Up and Down aim, in the layout's pixels, kept over lines too short to reach it. + goal_x: Option, + /// Where a selection made with Shift started. + anchor: Option, +} + +impl CaretMode { + /// The end of a selection the caret isn't at, which Shift grows the selection from: where + /// one made with Shift started, or else the far end of what's selected. + pub fn other_end(&self, selected: Option<(usize, usize)>) -> Option { + let (a, b) = selected.filter(|(a, b)| a < b)?; + Some(self.anchor.filter(|&x| x == a || x == b).unwrap_or(if self.caret.at <= a { b } else { a })) + } +} + /// Clicks this close together, in time and place, count as one double or triple click. const CLICK_TIME: Duration = motion::DOUBLE_CLICK; const CLICK_NEAR: i32 = 4; @@ -1035,6 +1055,13 @@ pub struct Preview { /// Text selected in a document, and the last press there: when, where and how many. pub text_sel: Option, text_clicks: Option<(Instant, (i32, i32), u8)>, + /// Caret mode, while it's on (F7). + pub caret: Option, + /// Escape just turned caret mode off, so that key repeating doesn't close the window. + caret_escaped: bool, + /// How many times the document has been laid out, so a screen reader is told a line laid + /// out again is a new one. + pub layouts: u64, } impl Drop for Preview { @@ -1170,6 +1197,9 @@ impl App { scrub: None, text_sel: None, text_clicks: None, + caret: None, + caret_escaped: false, + layouts: 0, }); if !settle { self.preview_start_job(); @@ -1362,8 +1392,9 @@ impl App { } Found::Doc { doc, info } => { p.content = Content::Doc { doc, info }; - // The file was read again: what was selected may not be there now. + // The file was read again: what was selected may not be there now, nor the caret. p.text_sel = None; + p.caret = None; p.loading_at = None; p.job = None; if self.doc_fonts.is_none() { @@ -1560,6 +1591,9 @@ impl App { if m.alt { return; } + if self.preview_caret_key(sym, m) { + return; + } if m.ctrl && !m.shift && self.preview_text_key(sym) { return; } @@ -1792,6 +1826,13 @@ impl App { self.doc_select_to(x, y); return true; } + // In caret mode, the caret goes where the press was. + if p.caret.is_some() + && let Some(at) = self.doc_offset(x, y, Unit::Char) + { + self.caret_to_point(at, y); + } + let Some(p) = self.preview.as_mut() else { return false }; let count = match p.text_clicks { Some((t, (px, py), n)) if now.duration_since(t) < CLICK_TIME && (px - x).abs() <= CLICK_NEAR && (py - y).abs() <= CLICK_NEAR => n % 3 + 1, _ => 1, @@ -1803,6 +1844,16 @@ impl App { if let Some(p) = self.preview.as_mut() { p.text_sel = Some(TextSel { anchor, unit, range: anchor, held: true }); } + // A word or line taken in caret mode: the caret goes to its end, and Shift grows it from + // its start. + if unit != Unit::Char && self.preview.as_ref().is_some_and(|p| p.caret.is_some()) { + self.caret_to_point(anchor.1, y); + if let Some(cm) = self.preview.as_mut().and_then(|p| p.caret.as_mut()) { + cm.anchor = Some(anchor.0); + } + // A line that wraps on below the window brings its end into view. + self.scroll_to_caret(); + } self.invalidate(self.preview_rect()); true } @@ -1827,6 +1878,26 @@ impl App { s.range = range; self.invalidate(self.preview_rect()); } + // In caret mode the caret follows the pointer, at the end of the selection that moves. + if self.preview.as_ref().is_some_and(|p| p.caret.is_some()) { + self.caret_to_point(if from < sel.anchor.0 { range.0 } else { range.1 }, y); + } + } + + /// Puts caret mode's caret at an offset the pointer found, on the line under `y` (in the + /// window) when the offset is on it. + fn caret_to_point(&mut self, at: usize, y: i32) { + let area = self.preview_geometry().area; + let Some(p) = self.preview.as_mut() else { return }; + let Some(layout) = p.doc_layout.as_ref() else { return }; + let under = layout.line_at(y - area.y + p.scroll as i32).min(layout.lines.len().saturating_sub(1)); + let caret = docview::Caret { at, line: layout.caret_line(at, Some(under)) }; + let Some(cm) = p.caret.as_mut() else { return }; + let old = cm.caret; + *cm = CaretMode { caret, goal_x: None, anchor: None }; + if old != caret { + self.invalidate_caret_lines(&[old, caret]); + } } /// Ctrl+A selects all of a document's text, and Ctrl+C copies what's selected. Returns @@ -1838,6 +1909,12 @@ impl App { k::KEY_a | k::KEY_A => { // Anchored at the start, so a Shift+click after it can take less. p.text_sel = Some(TextSel { anchor: (0, 0), unit: Unit::Char, range: (0, layout.total), held: false }); + // In caret mode the caret goes to the end, and Shift grows it from the start. The + // view stays where it is, as Page Down leaves it; the next arrow goes to the caret. + let end = docview::Caret { at: layout.total, line: layout.caret_line(layout.total, None) }; + if let Some(cm) = p.caret.as_mut() { + *cm = CaretMode { caret: end, goal_x: None, anchor: Some(0) }; + } self.invalidate(self.preview_rect()); } k::KEY_c | k::KEY_C | k::KEY_Insert => { @@ -1851,6 +1928,131 @@ impl App { true } + /// F7 turns caret mode on and off in a document, and Escape turns it off without closing + /// the window. While it's on, the arrows move the caret by a character or a line, with Ctrl + /// Left and Right by a word, and Home and End to the ends of the line, or with Ctrl of the + /// document. Shift with any of them selects from where it started. Returns whether the key + /// was one of those. + fn preview_caret_key(&mut self, sym: u32, m: Mods) -> bool { + let repeat = self.key_is_repeat; + let Some(p) = self.preview.as_mut() else { return false }; + // Escape held after it turned caret mode off goes on turning it off, not closing the + // window. Any other key, or Escape pressed again, is itself. + let escaped = std::mem::take(&mut p.caret_escaped); + if sym == k::KEY_Escape && repeat && escaped { + p.caret_escaped = true; + return true; + } + if !matches!(p.content, Content::Doc { .. }) || p.doc_layout.as_ref().is_none_or(|l| l.lines.is_empty()) { + return false; + } + let on = p.caret.is_some(); + match sym { + k::KEY_F7 if !m.ctrl && !m.shift => { + if !repeat { + self.set_caret_mode(!on); + } + } + k::KEY_Escape if on => { + self.set_caret_mode(false); + if let Some(p) = self.preview.as_mut() { + p.caret_escaped = true; + } + } + k::KEY_Left | k::KEY_Right | k::KEY_Up | k::KEY_Down | k::KEY_Home | k::KEY_End if on => self.caret_key(sym, m), + _ => return false, + } + true + } + + /// Turns caret mode on, with the caret at the start of the first line wholly in view, or off. + /// Whatever is selected stays selected. + fn set_caret_mode(&mut self, on: bool) { + let area = self.preview_geometry().area; + let Some(p) = self.preview.as_mut() else { return }; + let Some(layout) = p.doc_layout.as_ref() else { return }; + let old = p.caret.map(|c| c.caret); + if !on { + p.caret = None; + } else if p.caret.is_none() { + let (top, bottom) = (p.scroll as i32, p.scroll as i32 + area.h); + let first = layout.line_at(top).min(layout.lines.len().saturating_sub(1)); + let line = (first..layout.lines.len()).take_while(|&i| layout.lines[i].y < bottom).find(|&i| layout.lines[i].y >= top && layout.lines[i].mark != docview::Mark::Rule).unwrap_or(first); + p.caret = Some(CaretMode { caret: layout.line_start(line), goal_x: None, anchor: None }); + } + let new = p.caret.map(|c| c.caret); + if old != new { + let lines: Vec = old.into_iter().chain(new).collect(); + self.invalidate_caret_lines(&lines); + self.scroll_to_caret(); + } + } + + /// Moves the caret for an arrow, Home or End, selecting with Shift, and repaints only what + /// changed: the caret's lines, or the document when the selection or the scroll did. + fn caret_key(&mut self, sym: u32, m: Mods) { + let Some(fonts) = self.doc_fonts.as_mut() else { return }; + let Some(p) = self.preview.as_mut() else { return }; + let (Some(layout), Some(cm)) = (p.doc_layout.as_ref(), p.caret) else { return }; + // The line it's on can be from before the window was resized. + let c = docview::Caret { at: cm.caret.at.min(layout.total), line: layout.caret_line(cm.caret.at.min(layout.total), Some(cm.caret.line)) }; + let mut goal_x = None; + let next = match (sym, m.ctrl) { + (k::KEY_Left | k::KEY_Right, false) => layout.caret_step(c, sym == k::KEY_Right), + (k::KEY_Left | k::KEY_Right, true) => layout.caret_word(c, sym == k::KEY_Right), + (k::KEY_Up | k::KEY_Down, _) => { + let x = cm.goal_x.unwrap_or_else(|| layout.caret_x(c, fonts).0); + goal_x = Some(x); + layout.caret_vertical(c, sym == k::KEY_Down, x, fonts) + } + (k::KEY_Home, false) => layout.line_start(c.line), + (k::KEY_End, false) => layout.line_end(c.line), + (k::KEY_Home, true) => layout.line_start(0), + (_, _) => docview::Caret { at: layout.total, line: layout.caret_line(layout.total, None) }, + }; + let old_sel = p.text_sel.map(|s| s.range).filter(|(a, b)| a < b); + let anchor = if m.shift { + // From where the selection started: the end of one already there that the caret + // isn't at, or the caret. + let from = cm.anchor.filter(|_| old_sel.is_none()).or_else(|| CaretMode { caret: c, ..cm }.other_end(old_sel)).unwrap_or(c.at); + let range = (from.min(next.at), from.max(next.at)); + p.text_sel = Some(TextSel { anchor: (from, from), unit: Unit::Char, range, held: false }); + Some(from) + } else { + p.text_sel = None; + None + }; + p.caret = Some(CaretMode { caret: next, goal_x, anchor }); + let new_sel = p.text_sel.map(|s| s.range).filter(|(a, b)| a < b); + if new_sel != old_sel { + self.invalidate(self.preview_geometry().area); + } else if next != cm.caret { + self.invalidate_caret_lines(&[cm.caret, next]); + } + self.scroll_to_caret(); + } + + /// Repaints the lines these carets are on. + fn invalidate_caret_lines(&mut self, carets: &[docview::Caret]) { + let area = self.preview_geometry().area; + let Some(p) = self.preview.as_ref() else { return }; + let Some(layout) = p.doc_layout.as_ref() else { return }; + let rects: Vec = carets.iter().filter_map(|c| layout.lines.get(c.line)).map(|l| Rect::new(area.x, area.y + l.y - p.scroll as i32, area.w, l.h).intersect(area)).collect(); + for r in rects { + self.invalidate(r); + } + } + + /// Scrolls the document so the caret's line is in view, if it isn't. + fn scroll_to_caret(&mut self) { + let area = self.preview_geometry().area; + let Some(p) = self.preview.as_ref() else { return }; + let (Some(layout), Some(cm)) = (p.doc_layout.as_ref(), p.caret) else { return }; + if let Some(by) = caret_scroll(layout, cm.caret, p.scroll, area.h) { + self.doc_scroll_by(by); + } + } + /// Where a document is drawn, for tests to aim at. #[cfg(test)] pub fn doc_area(&self) -> Rect { @@ -1985,10 +2187,25 @@ impl App { // Keeps the same part of it in view, as near as can be. // A scroll from before the first layout stands, and is cut to fit below. let along = p.doc_layout.as_ref().map(|l| p.scroll / l.height.max(1) as f64); + // Whether the caret was in view, so it's kept there; one scrolled away stays away. + let caret_shown = p.doc_layout.as_ref().zip(p.caret).is_some_and(|(l, cm)| l.lines.get(cm.caret.line).is_some_and(|line| line.y + line.h > p.scroll as i32 && (line.y as f64) < p.scroll + area.h as f64)); let layout = docview::lay_out(doc, area.w, fonts); if let Some(along) = along { p.scroll = along * layout.height as f64; } + // The caret keeps its place in the text, on whichever line that is now: at the end + // of a wrapped line still, if it was, and in view if it was. + if let Some(cm) = p.caret.as_mut() { + let at = cm.caret.at.min(layout.total); + let was_wrap_end = p.doc_layout.as_ref().and_then(|l| l.lines.get(cm.caret.line)).is_some_and(|l| l.end == docview::End::Wrap && l.at + l.len() == at); + let wrap_end = layout.lines.iter().position(|l| l.end == docview::End::Wrap && l.at + l.len() == at && l.mark != docview::Mark::Rule).filter(|_| was_wrap_end); + let caret = docview::Caret { at, line: layout.caret_line(at, wrap_end) }; + *cm = CaretMode { caret, goal_x: None, anchor: cm.anchor }; + if caret_shown && let Some(by) = caret_scroll(&layout, caret, p.scroll, area.h) { + p.scroll += by; + } + } + p.layouts += 1; p.doc_layout = Some(layout); } let Some(layout) = &p.doc_layout else { return }; @@ -1996,7 +2213,8 @@ impl App { let co = self.colors; let ink = docview::Ink { text: co.foreground, muted: co.muted, link: co.link, code: co.surface, rule: co.border, selection: co.selection, on_selection: co.on_selection }; let selected = p.text_sel.map(|s| s.range); - App::with_clip(c, area, |c| docview::paint(c, area, p.scroll as i32, layout, fonts, ink, selected)); + let caret = p.caret.map(|c| c.caret); + App::with_clip(c, area, |c| docview::paint(c, area, p.scroll as i32, layout, fonts, ink, selected, caret)); } /// Scrolls a document by this much, if one's showing. @@ -2135,6 +2353,25 @@ impl App { } } +/// How far to scroll a document, `scroll` pixels down in a view `h` tall, to bring the caret's +/// line into view: on the first line or the last all the way, margin and all, and a line taller +/// than the view to its top. Nothing when it's in view. +fn caret_scroll(layout: &docview::Layout, caret: docview::Caret, scroll: f64, h: i32) -> Option { + let line = layout.lines.get(caret.line)?; + let (top, bottom) = (scroll, scroll + h as f64); + if caret.line == 0 { + Some(-top).filter(|&by| by != 0.0) + } else if caret.line + 1 == layout.lines.len() { + Some(layout.height as f64 - bottom).filter(|&by| by != 0.0) + } else if (line.y as f64) < top { + Some(line.y as f64 - top) + } else if (line.y + line.h) as f64 > bottom { + Some(((line.y + line.h) as f64 - bottom).min(line.y as f64 - top)) + } else { + None + } +} + /// What the footer says about what's shown, a part at a time. fn foot_parts(p: &Preview, view: Option<&View>, pdf_shown: Option<(usize, usize)>) -> Vec { match (&p.content, view) { @@ -2166,7 +2403,7 @@ impl App { let g = self.preview_geometry(); let (title, foot) = (Rect::new(0, 0, g.rect.w, g.area.y), Rect::new(0, g.area.bottom(), g.rect.w, (g.rect.bottom() - g.area.bottom()).max(0))); let can_step = (self.cursor > 0 && !self.rows.is_empty(), self.cursor + 1 < self.rows.len()); - let Some(p) = self.preview.as_ref() else { return crate::a11y::PreviewText { name: String::new(), kind: String::new(), shows: String::new(), title, area: g.area, foot, can_step } }; + let Some(p) = self.preview.as_ref() else { return crate::a11y::PreviewText { name: String::new(), kind: String::new(), shows: String::new(), title, area: g.area, foot, can_step, caret: None } }; let (kind, mut shows) = match &p.content { Content::Waiting => (String::new(), if p.loading_shown { vec!["Loading…".to_string()] } else { Vec::new() }), // What's said here is said again whenever it changes, so it leaves out what changes @@ -2199,7 +2436,16 @@ impl App { if let Some(n) = self.notices.last() { shows.push(n.clone()); } - crate::a11y::PreviewText { name: display_name(&p.path), kind, shows: shows.join(", "), title, area: g.area, foot, can_step } + // In caret mode, the line the caret is on, which is what a screen reader reads as it moves. + let caret = p.caret.zip(p.doc_layout.as_ref()).and_then(|(cm, layout)| { + let line = layout.lines.get(cm.caret.line)?; + let (text, caret, anchor) = layout.line_for_reading(cm.caret.line, cm.caret.at, cm.other_end(p.text_sel.map(|s| s.range))); + let rect = Rect::new(g.area.x, g.area.y + line.y - p.scroll as i32, g.area.w, line.h); + // A line laid out again, as the window is resized, is a new one too. + let line = (p.layouts << 32) | cm.caret.line as u64; + Some(crate::a11y::CaretLine { field: crate::field::Field { text, caret, anchor, error: None }, line, rect }) + }); + crate::a11y::PreviewText { name: display_name(&p.path), kind, shows: shows.join(", "), title, area: g.area, foot, can_step, caret } } } diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index 06c2374..c1ffcab 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -1218,6 +1218,9 @@ pub mod size { /// Quick View's text: how far a selection reaches past a line's end to show it takes the line break, at least 2 device pixels. pub const LINE_END_MARK: f32 = 6.0; + /// Quick View's caret in caret mode (F7), at least 2 device pixels: it doesn't blink, so it's twice a text field's caret to be found at a glance. Drawn in foreground on the background and in on-selection on the selection; at the selection's edge, half in each, so each half has its own background's contrast. + pub const DOC_CARET: f32 = 2.0; + /// Quick View's documents: the scroll bar's width, at least 2 device pixels. pub const DOC_SCROLLBAR: f32 = 4.0; diff --git a/design/tokens.json b/design/tokens.json index df0637d..5a59906 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -1152,6 +1152,11 @@ "value": "6px", "usage": "Quick View's text: how far a selection reaches past a line's end to show it takes the line break, at least 2 device pixels." }, + { + "name": "doc-caret", + "value": "2px", + "usage": "Quick View's caret in caret mode (F7), at least 2 device pixels: it doesn't blink, so it's twice a text field's caret to be found at a glance. Drawn in foreground on the background and in on-selection on the selection; at the selection's edge, half in each, so each half has its own background's contrast." + }, { "name": "doc-scrollbar", "value": "4px", @@ -1622,6 +1627,30 @@ "bg": "surface", "min": 4.5, "usage": "A link on the bars." + }, + { + "fg": "foreground", + "bg": "base", + "min": 3, + "usage": "Quick View's caret (doc-caret) on a document's text." + }, + { + "fg": "foreground", + "bg": "surface", + "min": 3, + "usage": "Quick View's caret in a code block or on a table's header." + }, + { + "fg": "foreground", + "bg": "border", + "min": 3, + "usage": "Quick View's caret on inline code in a table's header, whose box is in border." + }, + { + "fg": "on-selection", + "bg": "selection", + "min": 3, + "usage": "Quick View's caret over the selection: inside it, or the half on its side where the caret is at its edge (the other half is in foreground, on the background)." } ] } diff --git a/tests/a11y_client.py b/tests/a11y_client.py index 66cc275..c671354 100644 --- a/tests/a11y_client.py +++ b/tests/a11y_client.py @@ -34,6 +34,7 @@ caret NAME AT moves the caret through the Text interface select_text NAME A B selects from A to B word NAME AT the word at a character's place, as Orca reads one: [text, start, end] + caret_line WINDOW the line a preview's caret is on in caret mode, as for a field, or null at X Y the name of the window's part at a point, as pointing at it finds events the events heard since last asked, an announcement with what it said A field is found by its name, or the start of its name. @@ -343,6 +344,13 @@ def run(cmd, arg): name, at = arg.split(" ") r = Atspi.Text.get_string_at_offset(field(name), int(at), Atspi.TextGranularity.WORD) return [r.content, r.start_offset, r.end_offset] + if cmd == "caret_line": + def find(o): + if o.get_role_name() == "paragraph": + return o + return next((f for f in map(find, children(o)) if f is not None), None) + f = find(window(arg)) + return None if f is None else describe(f) if cmd == "events": out = list(events) events.clear() diff --git a/tests/e2e.py b/tests/e2e.py index 4721f82..777bda2 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -3058,6 +3058,22 @@ def a_screen_reader_can_read_and_walk_the_preview_window(h): w = sr.until("dump [\"Preview\"]", lambda w: w["name"] == "b.txt - Preview" and "3 lines" in (a11y_find(w, "b.txt", "document frame") or {}).get("description", ""), "the next file") assert a11y_focus(w) == ["b.txt"], a11y_focus(w) heard = sr.until("events", lambda e: any(x["type"] == "object:property-change:accessible-name" and x["source"] == "b.txt" for x in e), "the new name heard where the keyboard is") + # F7 in a text: caret mode is announced, and the keyboard goes to the caret's line, + # which is read as the caret moves. + sr.ask("events") + a.key("F7") + heard = sr.until("events", lambda e: any(x.get("said") == "Caret mode on" for x in e), "caret mode on heard") + line = sr.ask("caret_line Preview") + assert line and (line["role"], line["text"], line["caret"], line["focused"], line["editable"]) == ("paragraph", "one", 0, True, False), line + a.key("Down") + a.key("Right", mods=["shift"]) + heard = sr.until("events", lambda e: any(x["type"] == "object:text-selection-changed" for x in e), "the selection heard") + assert any(x["type"] == "object:text-caret-moved" for x in heard), heard + line = sr.ask("caret_line Preview") + assert (line["text"], line["caret"], line["selections"]) == ("two", 1, [[0, 1]]), line + a.key("F7") + sr.until("events", lambda e: any(x.get("said") == "Caret mode off" for x in e), "caret mode off heard") + assert sr.ask("caret_line Preview") is None sr.ask("do [\"Preview\", \"Next file\"]") w = sr.until("dump [\"Preview\"]", lambda w: w["name"] == "c.md - Preview", "the last file") assert "enabled" not in a11y_find(w, "Next file")["states"], w @@ -4475,6 +4491,68 @@ def pasted(): a.close() +@check +def caret_mode_selects_part_of_a_line_from_the_keyboard(h): + fs = fresh_fs() + (fs / "a.env").write_text("DB_HOST=localhost\nDB_PASS=hunter2\n\tindented\n") + (fs / "b-notes.md").write_text("# Notes\n\n| Key | Value |\n|---|---|\n| host | db1 |\n") + + def run(theme): + a = App(h, fs, extra_env={"LANG": "C.UTF-8"}) + s = a.wait(lambda s: s["count"] == 2, "listing") + assert (s["base"] == 0xfafafa) == (theme == "light"), f"{theme}: {s['base']:06x}" + a.key("space") + a.wait(lambda s: preview_of(s).get("name") == "a.env" and len(doc_of(s).get("line_starts", [])) > 2, "the .env, laid out") + + def pasted(): + a.key("c", mods=["ctrl"]) + time.sleep(0.2) + return wl_tool(a, ["wl-paste", "-n", "-t", "text/plain;charset=utf-8"]).stdout.decode() + + # F7 puts the caret at the start; the keys take it to the password, and Shift+End + # selects it. + a.key("F7") + a.wait(lambda s: doc_of(s).get("caret") == [0, 0], "the caret at the start") + a.shot(f"preview-caret-{theme}") + a.key("Down") + a.key("Right", mods=["ctrl"]) + a.key("Right") + a.key("End", mods=["shift"]) + a.wait(lambda s: doc_of(s).get("selected") == "hunter2", "the password selected from the keyboard") + a.shot(f"preview-caret-selected-{theme}") + got = pasted() + assert got == "hunter2", repr(got) + # Escape turns caret mode off, and the window stays. + a.key("Escape") + s = a.wait(lambda s: doc_of(s).get("caret") is None, "caret mode off") + assert preview_of(s).get("name") == "a.env" and doc_of(s)["selected"] == "hunter2", s["preview"] + # In a Markdown table, a row from Home to End copies cell by cell. + a.key("Down") + a.wait(lambda s: preview_of(s).get("name") == "b-notes.md" and doc_of(s).get("lines", 0) > 0, "the Markdown") + a.key("F7") + a.wait(lambda s: (doc_of(s).get("caret") or [None])[0] == 0, "the caret at the heading") + a.key("Down") + a.key("Down") + a.key("End", mods=["shift"]) + a.wait(lambda s: doc_of(s).get("selected") == "host\tdb1", "the row") + a.shot(f"preview-caret-table-{theme}") + got = pasted() + assert got == "host\tdb1", repr(got) + assert a.alive() + a.close() + + # The built-in themes, light then dark, whatever theme an earlier check left. + shutil.rmtree(SCRATCH / "client/home/.local/state/aliasos", ignore_errors=True) + run("light") + gtk = SCRATCH / "client/config/gtk-4.0" + gtk.mkdir(parents=True, exist_ok=True) + try: + (gtk / "settings.ini").write_text("[Settings]\ngtk-application-prefer-dark-theme=1\n") + run("dark") + finally: + shutil.rmtree(gtk) + + @check def markdown_tables_show_as_tables(h): fs = fresh_fs()