From 756e533230aaa2ccccecf30c5a2b5aa670a218cf Mon Sep 17 00:00:00 2001 From: Deepanshu Mishra Date: Wed, 18 Nov 2026 23:25:38 +0530 Subject: [PATCH 1/2] fix(reader): Keep diagrams after quick resizes, and add width keys After several resizes in a row, Rex drops the uploaded kitty images, so placing the old ids again left an empty gap. A resize now frees and re-uploads every figure. `<` and `>` narrow or widen the reading column by 8 (down to 20), and `=` fits it to the screen or returns to the configured max_width. The pen and eraser share a row in the key list so `quit` still fits on 30 rows. Refs #46 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + README.md | 4 +- src/viewer.rs | 147 +++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 138 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eaf7fba..c364731 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - Configure the document reader's maximum width in `$XDG_CONFIG_HOME/leaf/config.toml` (default `~/.config/leaf/config.toml`). Omitted settings keep the 76-column layout. - Keep the reading position within PDF and EPUB pages when resizing in scroll mode. +- `<` and `>` narrow or widen the reading column, and `=` fits it to the screen, so wide diagrams can be read without quitting. +- Diagrams and images no longer vanish after the terminal or pane is resized several times in quick succession. ## 0.17.2 diff --git a/README.md b/README.md index a93e601..f13862e 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ ln -s "$PWD/completions/_leaf" ~/.zsh/completions/ fpath=(~/.zsh/completions $fpath) # in ~/.zshrc, before compinit ``` -Keys: `←/→` (or `h/l`, `p/n`) page, `j/k` scroll, `ctrl+d`/`u` half screen, `space/b` screen (turns the page at its end), `g/G` first/last, `t` (or `:`) go to page, `i` original/painted images, `?` all keys, `q` quit. +Keys: `←/→` (or `h/l`, `p/n`) page, `j/k` scroll, `ctrl+d`/`u` half screen, `space/b` screen (turns the page at its end), `g/G` first/last, `t` (or `:`) go to page, `i` original/painted images, `<`/`>` narrower/wider column, `=` fit the screen (again to go back), `?` all keys, `q` quit. On a picture file, `←/→` (or `h/l`, `p/n`) move to the previous or next picture in its folder instead, since a picture has only the one page. Names go in the order a file manager lists them, with numbers counted as numbers (`img2` before `img10`), and past the last picture the first comes round again. The footer shows where you are among them, like `2 / 12`. @@ -96,7 +96,7 @@ To change the maximum reading width, add: max_width = 100 ``` -`max_width` accepts integers from 1 through 65535 and defaults to 76. The column stays centered and fits within the terminal, retaining the existing four-column margin budget and minimum one-column layout. This changes wrapping, not the terminal font size. Images fit within the configured reading width; their row limit is unchanged. +`max_width` accepts integers from 1 through 65535 and defaults to 76. The column stays centered and fits within the terminal, retaining the existing four-column margin budget and minimum one-column layout. This changes wrapping, not the terminal font size. Images fit within the configured reading width; their row limit is unchanged. While reading, `<` and `>` narrow or widen the column by 8, and `=` fits it to the screen or returns to `max_width`. These last until you quit. Missing or empty files and omitted settings use defaults. Unknown keys, invalid values, and unreadable files stop document opening before fetching or converting the document, with an error identifying the file and cause. Reopen the reader after editing the file; picture navigation keeps the settings loaded at the start of the session. diff --git a/src/viewer.rs b/src/viewer.rs index e828418..639c2f0 100644 --- a/src/viewer.rs +++ b/src/viewer.rs @@ -49,6 +49,18 @@ use crate::usage; const SPEECH_SENTENCE_REWIND: usize = 76; /// Windows at least this big show one page per screen; smaller ones scroll. const PAGED_MIN_WIDTH: u16 = 100; +/// Columns `<` and `>` take from or add to the reading column. +const WIDTH_STEP: u16 = 8; +/// The narrowest column `<` goes to. +const MIN_WIDTH: u16 = 20; + +/// How wide the reading column is asked to be, before the screen limits it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ReadingWidth { + Columns(u16), + /// As wide as the screen allows. + Fit, +} const PAGED_MIN_HEIGHT: u16 = 24; /// The footer line with a blank row above and below it. const FOOTER_ROWS: u16 = 3; @@ -362,6 +374,8 @@ pub struct App { picker: Picker, /// Column width pages are laid out at. width: u16, + /// Starts at the configured width; `<`, `>` and `=` change it. + reading_width: ReadingWidth, laid: HashMap, bool)>, mode: Mode, /// The page being read: in paged mode the one shown, when scrolling the one at the top. @@ -517,6 +531,7 @@ impl App { ask: None, rex_command: None, bookmarks: options.bookmarks.clone(), + reading_width: ReadingWidth::Columns(options.max_text_width), doc, options, picker, @@ -1005,11 +1020,12 @@ impl App { pub fn draw(&mut self, f: &mut Frame) { let area = f.area(); - let width = self - .options - .max_text_width - .min(area.width.saturating_sub(4)) - .max(1); + let room = area.width.saturating_sub(4); + let width = match self.reading_width { + ReadingWidth::Columns(columns) => columns.min(room), + ReadingWidth::Fit => room, + } + .max(1); let mode = if self.doc.page_count.is_some() && area.width >= PAGED_MIN_WIDTH && area.height >= PAGED_MIN_HEIGHT @@ -1395,6 +1411,16 @@ impl App { self.pixels.retain(|key, _| pixels_used.contains(key)); } + /// The redraw after a resize clears the screen, and kitty's placements with + /// it. Rex and Ghostty drop the uploaded figures too, so placing the old + /// ids again shows nothing: every figure is uploaded afresh. + fn resized(&mut self) { + if let Some(kitty) = &mut self.kitty { + kitty.reset(); + } + self.retain_protocols(|_| false); + } + /// Keeps the drawn figures `keep` accepts, freeing the terminal's copy of the rest. fn retain_protocols(&mut self, keep: impl Fn(&ProtocolKey) -> bool) { let kitty = &mut self.kitty; @@ -1487,6 +1513,7 @@ impl App { ("[ ]", "read slower / faster"), (", .", "previous / next sentence aloud"), ("s", "pick a voice"), + ("< > =", "narrower / wider / fit column"), ]); rows.push(( "i", @@ -1501,8 +1528,7 @@ impl App { ("@ ^enter", "ask an agent about the selection (⇧⌘A in Rex)"), ("y", "highlight selection, or clear one"), ("1-6", "pick a color; paints the selection"), - ("d", "pen: drag to draw"), - ("e", "eraser: drag over ink"), + ("d e", "pen / eraser: drag to draw or erase"), ("v", "move tool: pick, move, resize ink"), ("!", "how to highlight and draw"), ("?", "this help"), @@ -2629,6 +2655,20 @@ impl App { Some('s') | Some('S') => self.open_voices(), Some('[') => self.change_speed(false), Some(']') => self.change_speed(true), + // From the width on screen, so a column the screen narrowed answers at once. + Some('<') => { + self.reading_width = + ReadingWidth::Columns(self.width.saturating_sub(WIDTH_STEP).max(MIN_WIDTH)) + } + Some('>') => { + self.reading_width = ReadingWidth::Columns(self.width.saturating_add(WIDTH_STEP)) + } + Some('=') => { + self.reading_width = match self.reading_width { + ReadingWidth::Fit => ReadingWidth::Columns(self.options.max_text_width), + ReadingWidth::Columns(_) => ReadingWidth::Fit, + } + } Some(',') => self.skip_sentence(Direction::Backward), Some('.') => self.skip_sentence(Direction::Forward), _ => match key.code { @@ -3340,12 +3380,7 @@ impl App { match event::read()? { Event::Key(key) => self.key(key), Event::Mouse(mouse) => self.mouse(mouse), - // The redraw after a resize clears the screen, and kitty's placements with it. - Event::Resize(..) => { - if let Some(kitty) = &mut self.kitty { - kitty.reset(); - } - } + Event::Resize(..) => self.resized(), _ => {} } if self.quit || !event::poll(Duration::ZERO)? { @@ -3715,6 +3750,92 @@ mod tests { ); } + /// A page with one figure that decodes to a solid square. + struct Pictured; + + impl crate::doc::Source for Pictured { + fn page(&self, _: usize) -> Rc { + "Before\n\n![](leaf-image:square)\n\nAfter".into() + } + fn image_size(&self, _: &str) -> Option<(u32, u32)> { + Some((160, 80)) + } + fn decode(&self, _: &str, _: u32) -> Option { + Some(RgbaImage::from_pixel( + 160, + 80, + image::Rgba([0, 0, 255, 255]), + )) + } + } + + fn figure_ids(s: &Screen) -> Vec { + s.app + .placements + .iter() + .filter(|(image, _)| image.layer == 0) + .map(|(image, _)| image.id) + .collect() + } + + #[test] + fn a_resize_uploads_figures_again_because_terminals_may_drop_them() { + let doc = Doc { + title: "Book".into(), + page_count: Some(1), + source: Box::new(Pictured), + }; + let mut s = Screen::new(doc, 120, 30, ViewerOptions::default()); + s.app.kitty = Some(Kitty::default()); + // The first frame drew it in half blocks, before kitty was there. + s.app.protocols.clear(); + s.draw(); + let before = figure_ids(&s); + assert_eq!(before.len(), 1); + // The column stays 76 wide, so nothing else would make the figure change. + s.app.resized(); + s.terminal.backend_mut().resize(118, 30); + s.draw(); + let after = figure_ids(&s); + assert_eq!(after.len(), 1); + assert_ne!( + before, after, + "the figure kept an id the terminal may have dropped" + ); + } + + #[test] + fn angle_brackets_narrow_and_widen_the_column_and_equals_fits_the_screen() { + let mut s = Screen::new( + Doc::whole("Notes", "A".repeat(300)), + 160, + 30, + ViewerOptions::default(), + ); + assert_eq!(s.app.column.width, 76); + s.press(KeyCode::Char('<')); + assert_eq!(s.app.column.width, 76 - WIDTH_STEP); + s.press(KeyCode::Char('>')); + s.press(KeyCode::Char('>')); + assert_eq!(s.app.column.width, 76 + WIDTH_STEP); + s.press(KeyCode::Char('=')); + assert_eq!(s.app.column.width, 156); + // Wider than the screen stays inside it, and narrowing starts from what's shown. + s.press(KeyCode::Char('>')); + assert_eq!(s.app.column.width, 156); + s.press(KeyCode::Char('<')); + assert_eq!(s.app.column.width, 156 - WIDTH_STEP); + s.press(KeyCode::Char('=')); + assert_eq!(s.app.column.width, 156); + // Fitting again goes back to the configured width. + s.press(KeyCode::Char('=')); + assert_eq!(s.app.column.width, 76); + for _ in 0..40 { + s.press(KeyCode::Char('<')); + } + assert_eq!(s.app.column.width, MIN_WIDTH); + } + #[test] fn a_figure_that_cant_be_decoded_is_tried_once_while_on_screen() { let tries = Rc::new(std::cell::Cell::new(0)); From 57109700c0fb6da855ffafe904825d074b18e2b2 Mon Sep 17 00:00:00 2001 From: Deepanshu Mishra Date: Wed, 18 Nov 2026 23:35:40 +0530 Subject: [PATCH 2/2] fix(reader): Re-upload ink on resize, and let queued width keys add up A resize now frees and re-uploads pen strokes as well as figures, since the terminal can drop both. `<` and `>` step from the width already asked for, clamped to the last frame's room, so presses before the next draw each count. The README says `<` stops at 20 columns and that images follow the current reading width. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/viewer.rs | 84 +++++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 75 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f13862e..8795856 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ To change the maximum reading width, add: max_width = 100 ``` -`max_width` accepts integers from 1 through 65535 and defaults to 76. The column stays centered and fits within the terminal, retaining the existing four-column margin budget and minimum one-column layout. This changes wrapping, not the terminal font size. Images fit within the configured reading width; their row limit is unchanged. While reading, `<` and `>` narrow or widen the column by 8, and `=` fits it to the screen or returns to `max_width`. These last until you quit. +`max_width` accepts integers from 1 through 65535 and defaults to 76. The column stays centered and fits within the terminal, retaining the existing four-column margin budget and minimum one-column layout. This changes wrapping, not the terminal font size. Images fit within the current reading width; their row limit is unchanged. While reading, `<` and `>` narrow or widen the column by 8, with `<` stopping at 20 columns, and `=` fits it to the screen or returns to `max_width`. These last until you quit. Missing or empty files and omitted settings use defaults. Unknown keys, invalid values, and unreadable files stop document opening before fetching or converting the document, with an error identifying the file and cause. Reopen the reader after editing the file; picture navigation keeps the settings loaded at the start of the session. diff --git a/src/viewer.rs b/src/viewer.rs index 639c2f0..394464d 100644 --- a/src/viewer.rs +++ b/src/viewer.rs @@ -61,6 +61,17 @@ enum ReadingWidth { /// As wide as the screen allows. Fit, } + +impl ReadingWidth { + /// The column width this asks for on a screen with `room` columns to spare. + fn within(self, room: u16) -> u16 { + match self { + ReadingWidth::Columns(columns) => columns.min(room), + ReadingWidth::Fit => room, + } + .max(1) + } +} const PAGED_MIN_HEIGHT: u16 = 24; /// The footer line with a blank row above and below it. const FOOTER_ROWS: u16 = 3; @@ -376,6 +387,8 @@ pub struct App { width: u16, /// Starts at the configured width; `<`, `>` and `=` change it. reading_width: ReadingWidth, + /// Columns the last frame left for the reading column; unbounded before it. + room: u16, laid: HashMap, bool)>, mode: Mode, /// The page being read: in paged mode the one shown, when scrolling the one at the top. @@ -532,6 +545,7 @@ impl App { rex_command: None, bookmarks: options.bookmarks.clone(), reading_width: ReadingWidth::Columns(options.max_text_width), + room: u16::MAX, doc, options, picker, @@ -1020,12 +1034,8 @@ impl App { pub fn draw(&mut self, f: &mut Frame) { let area = f.area(); - let room = area.width.saturating_sub(4); - let width = match self.reading_width { - ReadingWidth::Columns(columns) => columns.min(room), - ReadingWidth::Fit => room, - } - .max(1); + self.room = area.width.saturating_sub(4); + let width = self.reading_width.within(self.room); let mode = if self.doc.page_count.is_some() && area.width >= PAGED_MIN_WIDTH && area.height >= PAGED_MIN_HEIGHT @@ -1413,10 +1423,13 @@ impl App { /// The redraw after a resize clears the screen, and kitty's placements with /// it. Rex and Ghostty drop the uploaded figures too, so placing the old - /// ids again shows nothing: every figure is uploaded afresh. + /// ids again shows nothing: every figure and stroke is uploaded afresh. fn resized(&mut self) { if let Some(kitty) = &mut self.kitty { kitty.reset(); + for (_, image) in self.ink_drawn.drain() { + kitty.free(image); + } } self.retain_protocols(|_| false); } @@ -2655,13 +2668,16 @@ impl App { Some('s') | Some('S') => self.open_voices(), Some('[') => self.change_speed(false), Some(']') => self.change_speed(true), - // From the width on screen, so a column the screen narrowed answers at once. + // From the width the screen allows, so a column it narrowed answers at + // once, and from the one asked for, so presses before the next frame add up. Some('<') => { + let now = self.reading_width.within(self.room); self.reading_width = - ReadingWidth::Columns(self.width.saturating_sub(WIDTH_STEP).max(MIN_WIDTH)) + ReadingWidth::Columns(now.saturating_sub(WIDTH_STEP).max(MIN_WIDTH)) } Some('>') => { - self.reading_width = ReadingWidth::Columns(self.width.saturating_add(WIDTH_STEP)) + let now = self.reading_width.within(self.room); + self.reading_width = ReadingWidth::Columns(now.saturating_add(WIDTH_STEP)) } Some('=') => { self.reading_width = match self.reading_width { @@ -3804,6 +3820,54 @@ mod tests { ); } + #[test] + fn a_resize_uploads_ink_again_too() { + let (mut s, _, _) = with_a_line(); + let ink = |s: &Screen| -> Vec { + s.app + .placements + .iter() + .filter(|(image, _)| image.layer == INK_LAYER) + .map(|(image, _)| image.id) + .collect() + }; + let before = ink(&s); + assert_eq!(before.len(), 1); + s.app.resized(); + s.draw(); + let after = ink(&s); + assert_eq!(after.len(), 1); + assert_ne!( + before, after, + "the ink kept an id the terminal may have dropped" + ); + } + + #[test] + fn width_keys_pressed_before_the_next_frame_all_count() { + let mut s = Screen::new( + Doc::whole("Notes", "A".repeat(300)), + 160, + 30, + ViewerOptions::default(), + ); + let key = |code| KeyEvent { + code, + modifiers: KeyModifiers::NONE, + kind: KeyEventKind::Press, + state: KeyEventState::NONE, + }; + s.app.key(key(KeyCode::Char('<'))); + s.app.key(key(KeyCode::Char('<'))); + s.draw(); + assert_eq!(s.app.column.width, 76 - 2 * WIDTH_STEP); + s.app.key(key(KeyCode::Char('>'))); + s.app.key(key(KeyCode::Char('>'))); + s.app.key(key(KeyCode::Char('>'))); + s.draw(); + assert_eq!(s.app.column.width, 76 + WIDTH_STEP); + } + #[test] fn angle_brackets_narrow_and_widen_the_column_and_equals_fits_the_screen() { let mut s = Screen::new(