Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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 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.

Expand Down
211 changes: 198 additions & 13 deletions src/viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,29 @@ 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,
}

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;
Expand Down Expand Up @@ -362,6 +385,10 @@ 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,
/// Columns the last frame left for the reading column; unbounded before it.
room: u16,
laid: HashMap<usize, (Rc<Laid>, bool)>,
mode: Mode,
/// The page being read: in paged mode the one shown, when scrolling the one at the top.
Expand Down Expand Up @@ -517,6 +544,8 @@ impl App {
ask: None,
rex_command: None,
bookmarks: options.bookmarks.clone(),
reading_width: ReadingWidth::Columns(options.max_text_width),
room: u16::MAX,
doc,
options,
picker,
Expand Down Expand Up @@ -1005,11 +1034,8 @@ 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);
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
Expand Down Expand Up @@ -1395,6 +1421,19 @@ 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 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);
}
}
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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;
Expand Down Expand Up @@ -1487,6 +1526,7 @@ impl App {
("[ ]", "read slower / faster"),
(", .", "previous / next sentence aloud"),
("s", "pick a voice"),
("< > =", "narrower / wider / fit column"),
]);
rows.push((
"i",
Expand All @@ -1501,8 +1541,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"),
Expand Down Expand Up @@ -2629,6 +2668,23 @@ impl App {
Some('s') | Some('S') => self.open_voices(),
Some('[') => self.change_speed(false),
Some(']') => self.change_speed(true),
// 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(now.saturating_sub(WIDTH_STEP).max(MIN_WIDTH))
}
Some('>') => {
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 {
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 {
Expand Down Expand Up @@ -3340,12 +3396,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)? {
Expand Down Expand Up @@ -3715,6 +3766,140 @@ 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<str> {
"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<RgbaImage> {
Some(RgbaImage::from_pixel(
160,
80,
image::Rgba([0, 0, 255, 255]),
))
}
}

fn figure_ids(s: &Screen) -> Vec<u32> {
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 a_resize_uploads_ink_again_too() {
let (mut s, _, _) = with_a_line();
let ink = |s: &Screen| -> Vec<u32> {
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(
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));
Expand Down