├── .gitignore ├── .editorconfig ├── rust-toolchain.toml ├── example_scrt.png ├── benches ├── geotopo.pdf ├── adobe_example.pdf ├── example_dictionary.pdf ├── for_profiling.rs ├── utils.rs └── rendering.rs ├── .gitmodules ├── .rustfmt.toml ├── shell.nix ├── scripts └── build_most_optimized.sh ├── .github └── workflows │ └── rust.yml ├── src ├── lib.rs ├── skip.rs ├── kitty.rs ├── converter.rs ├── renderer.rs ├── main.rs └── tui.rs ├── README.md ├── CHANGELOG.md ├── Cargo.toml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | debug.log 3 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.rs] 2 | indent_style = tab 3 | -------------------------------------------------------------------------------- /rust-toolchain.toml: -------------------------------------------------------------------------------- 1 | [toolchain] 2 | channel = "nightly" 3 | -------------------------------------------------------------------------------- /example_scrt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsjunetime/tdf/HEAD/example_scrt.png -------------------------------------------------------------------------------- /benches/geotopo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsjunetime/tdf/HEAD/benches/geotopo.pdf -------------------------------------------------------------------------------- /benches/adobe_example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsjunetime/tdf/HEAD/benches/adobe_example.pdf -------------------------------------------------------------------------------- /benches/example_dictionary.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/itsjunetime/tdf/HEAD/benches/example_dictionary.pdf -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "ratatui"] 2 | path = ratatui 3 | url = https://github.com/itsjunetime/ratatui 4 | [submodule "ratatui-image"] 5 | path = ratatui-image 6 | url = https://github.com/itsjunetime/ratatui-image 7 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = true 2 | match_arm_blocks = false 3 | imports_granularity = "Crate" 4 | overflow_delimited_expr = true 5 | group_imports = "StdExternalCrate" 6 | trailing_comma = "Never" 7 | use_field_init_shorthand = true 8 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | { 2 | pkgs ? import { }, 3 | }: 4 | pkgs.mkShell { 5 | nativeBuildInputs = [ pkgs.pkg-config ]; 6 | 7 | buildInputs = [ 8 | pkgs.rustPlatform.bindgenHook 9 | pkgs.cairo 10 | ]; 11 | } 12 | -------------------------------------------------------------------------------- /scripts/build_most_optimized.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | RUSTFLAGS="-Cpanic=abort -Ccodegen-units=1 -Cembed-bitcode=yes -Zdylib-lto -Copt-level=s -Zlocation-detail=none -Cstrip=symbols -Ctarget-cpu=native" cargo -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort build --profile production --target "$(rustc -vV | grep host | cut -d " " -f2)" --bin tdf 3 | -------------------------------------------------------------------------------- /benches/for_profiling.rs: -------------------------------------------------------------------------------- 1 | use ratatui_image::picker::ProtocolType; 2 | 3 | mod utils; 4 | 5 | const BLACK: i32 = 0; 6 | const WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]); 7 | 8 | #[tokio::main] 9 | async fn main() { 10 | #[cfg(feature = "tracing")] 11 | console_subscriber::init(); 12 | 13 | let file = std::env::args() 14 | .nth(1) 15 | .expect("Please enter a file to profile"); 16 | 17 | utils::render_doc(file, None, BLACK, WHITE, ProtocolType::Kitty).await; 18 | } 19 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Setup sccache 19 | if: github.event_name != 'release' && github.event_name != 'workflow_dispatch' 20 | uses: mozilla-actions/sccache-action@v0.0.8 21 | - name: Configure sccache 22 | if: github.event_name != 'release' && github.event_name != 'workflow_dispatch' 23 | run: | 24 | echo "SCCACHE_GHA_ENABLED=true" >> $GITHUB_ENV 25 | echo "RUSTC_WRAPPER=sccache" >> $GITHUB_ENV 26 | - name: Install build dependencies 27 | run: | 28 | sudo apt-get update 29 | sudo apt-get install -y libfontconfig1-dev libgoogle-perftools-dev google-perftools 30 | - uses: actions/checkout@v4 31 | - name: Install clippy and fmt 32 | run: rustup component add clippy rustfmt 33 | - name: Clippy 34 | run: cargo clippy --locked -- -D warnings 35 | - name: Tests 36 | run: cargo test --locked 37 | - name: Check fmt 38 | run: cargo fmt -- --check 39 | - name: Run benchmarks as tests 40 | run: cargo test --locked --benches -- adobe_example 41 | - name: Build 42 | run: cargo build --locked 43 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use std::num::NonZeroUsize; 2 | 3 | #[global_allocator] 4 | static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc; 5 | 6 | #[derive(PartialEq)] 7 | pub enum PrerenderLimit { 8 | All, 9 | Limited(NonZeroUsize) 10 | } 11 | 12 | pub mod converter; 13 | pub mod kitty; 14 | pub mod renderer; 15 | pub mod skip; 16 | pub mod tui; 17 | 18 | #[derive(Copy, Clone, PartialEq, Debug)] 19 | pub enum FitOrFill { 20 | Fit, 21 | Fill 22 | } 23 | 24 | pub struct ScaledResult { 25 | width: f32, 26 | height: f32, 27 | scale_factor: f32 28 | } 29 | 30 | #[must_use] 31 | pub fn scale_img_for_area( 32 | (img_width, img_height): (f32, f32), 33 | (area_width, area_height): (f32, f32), 34 | fit_or_fill: FitOrFill 35 | ) -> ScaledResult { 36 | // and get its aspect ratio 37 | let img_aspect_ratio = img_width / img_height; 38 | 39 | // Then we get the full pixel dimensions of the area provided to us, and the aspect ratio 40 | // of that area 41 | let area_aspect_ratio = area_width / area_height; 42 | 43 | // and get the ratio that this page would have to be scaled by to fit perfectly within the 44 | // area provided to us. 45 | // we do this first by comparing the aspec ratio of the page with the aspect ratio of the 46 | // area to fit it within. If the aspect ratio of the page is larger, then we need to scale 47 | // the width of the page to fill perfectly within the height of the area. Otherwise, we 48 | // scale the height to fit perfectly. The dimension that _is not_ scaled to fit perfectly 49 | // is scaled by the same factor as the dimension that _is_ scaled perfectly. 50 | let scale_factor = match (img_aspect_ratio > area_aspect_ratio, fit_or_fill) { 51 | (true, FitOrFill::Fit) | (false, FitOrFill::Fill) => area_width / img_width, 52 | (false, FitOrFill::Fit) | (true, FitOrFill::Fill) => area_height / img_height 53 | }; 54 | 55 | ScaledResult { 56 | width: img_width * scale_factor, 57 | height: img_height * scale_factor, 58 | scale_factor 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `tdf` 2 | 3 | A terminal-based PDF viewer. 4 | 5 | Designed to be performant, very responsive, and work well with even very large PDFs. Built with [`ratatui`](https://github.com/ratatui-org/ratatui). 6 | 7 | ![What it looks like](./example_scrt.png) 8 | 9 | ## Features: 10 | - Asynchronous Rendering 11 | - Searching 12 | - Hot reloading 13 | - Responsive details about rendering/search progress 14 | - Reactive layout 15 | 16 | ## Installation 17 | 18 | 1. Get the rust toolchain from [rustup.rs](https://rustup.rs) 19 | 2. Run `cargo install --git https://github.com/itsjunetime/tdf.git` 20 | 21 | If you want to use this with `epub`s or `cbz`s, add `--features epub` or `--features cbz` to the command line (or `--features cbz,epub` for both) 22 | 23 | ## To Build 24 | First, you need to install the system dependencies. This will generally only include `libfontconfig` and `clang`. If you're on linux, these will probably show up in your package manager as something like `libfontconfig1-devel` or `libfontconfig-dev` and just `clang`. 25 | 26 | If it turns out that you're missing one of these, it will fail to compile and tell you what library you're missing. Find the development package for that library in your package manager, install it, and try to build again. Now, the important steps: 27 | 28 | 1. Get the rust toolchain from [rustup.rs](https://rustup.rs) 29 | 2. Clone the repo and `cd` into it 30 | 3. Run `cargo build --release` 31 | 32 | The binary should then be found at `./target/release/tdf`. 33 | 34 | You can also pull this in via [radicle](https://radicle.xyz) with `rad clone rad:zb11K1XGfQooopqEfwtCMyvbcyK1` 35 | 36 | ## Why in the world would you use this? 37 | 38 | I dunno. Just for fun, mostly. 39 | 40 | ## Can I contribute? 41 | 42 | Yeah, sure. Please do. 43 | 44 | Please note, though, that: 45 | 1. No AI-generated or AI-assisted or AI-viewed or AI-anythinged code will be accepted. "AI" is a plague upon this earth and I won't be caught dead pretending it's normal. 46 | 2. All contributions will be treated as licensed under MPL-2.0 :) 47 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Unreleased 2 | 3 | # v0.5.0 4 | 5 | - Switched simd base64 crate for one that works on stable (from `vb64` to `base64_simd`) 6 | - Allow boolean arguments to function as flags, without a `true` or `false` argument following the flag itself ([#109](https://github.com/itsjunetime/tdf/pull/109), thanks [@tatounee](https://github.com/tatounee)!) 7 | - Fix cropping issues when zooming out too much while using kitty protocol 8 | - Added `gg` and `G` keybindings for scrolling to the top and bottom of a page, respectively, when filling the width of the screen with kitty 9 | - Updated help page to only show kitty keybindings when you're actually using kitty 10 | - Map page-up and page-down keybindings to do the same thing as up-key and down-key ([#115](https://github.com/itsjunetime/tdf/pull/115), thanks [@maxdexh](https://github.com/maxdexh)!) 11 | - Vertically center pages within the available space if they are not constrained by the height ([#116](https://github.com/itsjunetime/tdf/pull/116), thanks [@maxdexh](https://github.com/maxdexh)!) 12 | - Fixed issue with cooked mode not being restored upon panic/error ([#118](https://github.com/itsjunetime/tdf/pull/118), thanks [@maxdexh](https://github.com/maxdexh)!) 13 | - Implemented a debounce for file reload updates to prevent some editors from paralyzing the app due to a flurry of reloads ([#117](https://github.com/itsjunetime/tdf/pull/117), thanks [@maxdexh](https://github.com/maxdexh)) 14 | - Fixed an overflow when zooming out of horizontal pdfs ([#119](https://github.com/itsjunetime/tdf/pull/119), thanks [@maxdexh](https://github.com/maxdexh)!) 15 | - Reworked zooming to allow for full zooming in and out and panning in both directions ([#121](https://github.com/itsjunetime/tdf/pull/121), thanks [@maxdexh](https://github.com/maxdexh)!) 16 | 17 | # v0.4.3 18 | 19 | - Fix issue with some terminals hanging on startup 20 | - Fix issues with some iterm2-backend terminals not displaying anything 21 | - Allow using ctrl+scroll to zoom in/out while zoomed using kitty backend 22 | - (Internal) run CI with `--locked` flag to ensure lockfile is always in-sync 23 | 24 | # v0.4.2 25 | 26 | - Add `--version` flag 27 | - Fix shms not working on macos ([#93](https://github.com/itsjunetime/tdf/pull/93)) 28 | 29 | # v0.4.1 30 | 31 | - Add instructions for using new zoom/pan features to help page 32 | 33 | # v0.4.0 34 | 35 | - Update to new `kittage` backend for kitty-protocol-supporting terminals (fixes many issues and improves performance significantly, see [the PR](https://github.com/itsjunetime/tdf/pull/74)) 36 | - Use new mupdf search API for slightly better performance 37 | - Update ratatui(-image) dependencies 38 | - Allow specification of default white and black colors for rendered pdfs 39 | - Pause rendering every once in a while while there's a search term to enable searching across the entire document more quickly 40 | - Fix an issue with missing search highlights 41 | 42 | # v0.3.0 43 | 44 | - Update ratatui(-image) dependencies 45 | - Enable Ctrl+Z/Suspend functionality 46 | - Rewrite with mupdf as the backend for much better performance and rendering quality 47 | - Support easy inversion of colors via `i` keypress 48 | - Support for filling all available space with `f` keypress 49 | - Change help text at bottom into full help page 50 | 51 | # v0.2.0 52 | 53 | - Add `--r-to-l` flag to support displaying pdfs that read from right to left 54 | - Add `--max-wide` flag to restrict amount of pages that can appear on the screen at a time 55 | - Small internal changes to accomodate a few more clippy lints 56 | - Update `ratatui` and `ratatui-image` git dependencies to latest upstream 57 | - Move `ratatui-image/vb64` support under `nightly` feature, enabled by default 58 | - Fixed a bug where jumping to a page out of range could result in weird `esc` key behavior 59 | - Added CI ([#31](https://github.com/itsjunetime/tdf/pull/31), thank you [@Kriejstal](https://github.com/Kreijstal)) 60 | - Changed global allocator to [`mimalloc`](https://github.com/purpleprotocol/mimalloc_rust) for slightly improved performance 61 | - Fixed issue with document reloading not working when files are intermedially deleted 62 | - Fixed a lot of weirdness with bottom message layering/updating 63 | 64 | # v0.1.0 65 | 66 | Initial tag :) 67 | -------------------------------------------------------------------------------- /src/skip.rs: -------------------------------------------------------------------------------- 1 | use std::num::NonZeroUsize; 2 | 3 | use ratatui::widgets::Widget; 4 | 5 | pub struct Skip { 6 | skip: bool 7 | } 8 | 9 | impl Skip { 10 | #[must_use] 11 | pub fn new(skip: bool) -> Self { 12 | Self { skip } 13 | } 14 | } 15 | 16 | impl Widget for Skip { 17 | fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) { 18 | for x in area.x..(area.x + area.width) { 19 | for y in area.y..(area.y + area.height) { 20 | buf[(x, y)].skip = self.skip; 21 | } 22 | } 23 | } 24 | } 25 | 26 | enum PlusOrMinus { 27 | Plus, 28 | Minus 29 | } 30 | 31 | pub struct InterleavedAroundWithMax { 32 | // starts at this number 33 | around: usize, 34 | inclusive_min: usize, 35 | // this iterator can only produce values in [0..max) 36 | exclusive_max: NonZeroUsize, 37 | // the next time we call `next()`, this value should be combined with `around` according to 38 | // `next_op`, then, after next_op is inverted, incremented if next_op was negative before being 39 | // inverted. 40 | next_change: usize, 41 | // How `next_change` should be applied to `around` next time `next()` is called 42 | next_op: PlusOrMinus 43 | } 44 | 45 | impl InterleavedAroundWithMax { 46 | /// the following must hold or else this is liable to panic or produce nonsense values: 47 | /// - inclusive_min < exclusive_max 48 | /// - inclusive_min <= around <= exclusive_max 49 | #[must_use] 50 | pub fn new(around: usize, inclusive_min: usize, exclusive_max: NonZeroUsize) -> Self { 51 | Self { 52 | around, 53 | inclusive_min, 54 | exclusive_max, 55 | next_change: 0, 56 | next_op: PlusOrMinus::Minus 57 | } 58 | } 59 | } 60 | 61 | impl Iterator for InterleavedAroundWithMax { 62 | type Item = usize; 63 | fn next(&mut self) -> Option { 64 | let actual_change = self.next_change % (self.exclusive_max.get() - self.inclusive_min); 65 | 66 | let to_return = match self.next_op { 67 | // If we're supposed to add them and we need it to wrap, then try to add them together 68 | // 'cause we need special behavior if it overflows usize's limits 69 | PlusOrMinus::Plus => match self.around.checked_add(actual_change) { 70 | // If we added it and it's within the range, we're chillin 71 | Some(next_val) if next_val < self.exclusive_max.get() => next_val, 72 | // If we added it and it's not within the range, do next_val % (self.max + 1), e.g. 73 | // if max is 20, we were at 15, and we added 7, we should get 1 (because +5 would 74 | // hit the max, then 0, then 1). So adding 1 before the modulo makes it hit the 75 | // right numbers. And we can be sure the + here doesn't overflow 'cause we already 76 | // checked the `usize::MAX` up above 77 | Some(next_val) => (next_val % self.exclusive_max.get()) + self.inclusive_min, 78 | // If we added them and it would've overflowed usize::MAX, then we see how much 79 | // of the change would be remaining after reaching `max` 80 | None => 81 | (actual_change - (self.exclusive_max.get() - actual_change)) 82 | + self.inclusive_min, 83 | }, 84 | PlusOrMinus::Minus => match self.around.checked_sub(actual_change) { 85 | // If we can just minus it, cool cool. All is good. 86 | Some(next_val) if next_val >= self.inclusive_min => next_val, 87 | // If we can minus it but it goes below our min, then see how much below it went 88 | // and just manually wrap it around 89 | Some(next_val) => self.exclusive_max.get() - (self.inclusive_min - next_val), 90 | // If we can't... 91 | None => { 92 | // then we see how much of the change would be remaining after hitting the 93 | // minimum 94 | let remaining = actual_change - (self.around - self.inclusive_min); 95 | 96 | // and then we take that away from the top! 97 | self.exclusive_max.get() - remaining 98 | } 99 | } 100 | }; 101 | 102 | self.next_op = match self.next_op { 103 | PlusOrMinus::Plus => PlusOrMinus::Minus, 104 | PlusOrMinus::Minus => { 105 | self.next_change = (self.next_change + 1) % self.exclusive_max.get(); 106 | PlusOrMinus::Plus 107 | } 108 | }; 109 | 110 | Some(to_return) 111 | } 112 | } 113 | 114 | #[cfg(test)] 115 | mod tests { 116 | use super::*; 117 | 118 | #[test] 119 | fn iter_works() { 120 | let got = InterleavedAroundWithMax::new(5, 2, NonZeroUsize::new(21).unwrap()) 121 | .take(30) 122 | .collect::>(); 123 | 124 | assert_eq!(got, vec![ 125 | 5, 6, 4, 7, 3, 8, 2, 9, 20, 10, 19, 11, 18, 12, 17, 13, 16, 14, 15, 15, 14, 16, 13, 17, 126 | 12, 18, 11, 19, 10, 20 127 | ]); 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/kitty.rs: -------------------------------------------------------------------------------- 1 | use std::{io::Write, num::NonZeroU32}; 2 | 3 | use crossterm::{ 4 | cursor::MoveTo, 5 | event::EventStream, 6 | execute, 7 | terminal::{disable_raw_mode, enable_raw_mode} 8 | }; 9 | use image::DynamicImage; 10 | use kittage::{ 11 | AsyncInputReader, ImageDimensions, ImageId, NumberOrId, PixelFormat, 12 | action::Action, 13 | delete::{ClearOrDelete, DeleteConfig, WhichToDelete}, 14 | display::{CursorMovementPolicy, DisplayConfig, DisplayLocation}, 15 | error::TransmitError, 16 | image::Image, 17 | medium::Medium 18 | }; 19 | use ratatui::layout::Position; 20 | 21 | use crate::converter::MaybeTransferred; 22 | 23 | pub struct KittyReadyToDisplay<'tui> { 24 | pub img: &'tui mut MaybeTransferred, 25 | pub page_num: usize, 26 | pub pos: Position, 27 | pub display_loc: DisplayLocation 28 | } 29 | 30 | pub enum KittyDisplay<'tui> { 31 | NoChange, 32 | ClearImages, 33 | DisplayImages(Vec>) 34 | } 35 | 36 | pub struct DbgWriter { 37 | w: W, 38 | #[cfg(debug_assertions)] 39 | buf: String 40 | } 41 | 42 | impl Write for DbgWriter { 43 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 44 | #[cfg(debug_assertions)] 45 | { 46 | if let Ok(s) = std::str::from_utf8(buf) { 47 | self.buf.push_str(s); 48 | } 49 | } 50 | self.w.write(buf) 51 | } 52 | 53 | fn flush(&mut self) -> std::io::Result<()> { 54 | #[cfg(debug_assertions)] 55 | { 56 | log::debug!("Writing to kitty: {:?}", self.buf); 57 | self.buf.clear(); 58 | } 59 | self.w.flush() 60 | } 61 | } 62 | 63 | pub async fn run_action<'es>( 64 | action: Action<'_, '_>, 65 | ev_stream: &'es mut EventStream 66 | ) -> Result::Error>> { 67 | let writer = DbgWriter { 68 | w: std::io::stdout().lock(), 69 | #[cfg(debug_assertions)] 70 | buf: String::new() 71 | }; 72 | action 73 | .execute_async(writer, ev_stream) 74 | .await 75 | .map(|(_, i)| i) 76 | } 77 | 78 | pub async fn do_shms_work(ev_stream: &mut EventStream) -> bool { 79 | let img = DynamicImage::new_rgb8(1, 1); 80 | let pid = std::process::id(); 81 | let Ok(mut k_img) = kittage::image::Image::shm_from(img, &format!("tdf_test_{pid}")) else { 82 | return false; 83 | }; 84 | 85 | // apparently the terminal won't respond to queries unless they have an Id instead of a number 86 | k_img.num_or_id = NumberOrId::Id(NonZeroU32::new(u32::MAX).unwrap()); 87 | 88 | enable_raw_mode().unwrap(); 89 | 90 | let res = run_action(Action::Query(&k_img), ev_stream).await; 91 | 92 | disable_raw_mode().unwrap(); 93 | 94 | res.is_ok() 95 | } 96 | 97 | pub async fn display_kitty_images<'es>( 98 | display: KittyDisplay<'_>, 99 | ev_stream: &'es mut EventStream 100 | ) -> Result< 101 | (), 102 | ( 103 | Vec, 104 | &'static str, 105 | TransmitError<<&'es mut EventStream as AsyncInputReader>::Error> 106 | ) 107 | > { 108 | let images = match display { 109 | KittyDisplay::NoChange => return Ok(()), 110 | KittyDisplay::DisplayImages(_) | KittyDisplay::ClearImages => { 111 | run_action( 112 | Action::Delete(DeleteConfig { 113 | effect: ClearOrDelete::Clear, 114 | which: WhichToDelete::All 115 | }), 116 | ev_stream 117 | ) 118 | .await 119 | .map_err(|e| (vec![], "Couldn't clear previous images", e))?; 120 | 121 | let KittyDisplay::DisplayImages(images) = display else { 122 | return Ok(()); 123 | }; 124 | 125 | images 126 | } 127 | }; 128 | 129 | let mut err = None; 130 | for KittyReadyToDisplay { 131 | img, 132 | page_num, 133 | pos, 134 | display_loc 135 | } in images 136 | { 137 | let config = DisplayConfig { 138 | location: display_loc, 139 | cursor_movement: CursorMovementPolicy::DontMove, 140 | ..DisplayConfig::default() 141 | }; 142 | 143 | execute!(std::io::stdout(), MoveTo(pos.x, pos.y)).unwrap(); 144 | 145 | log::debug!("going to display img {img:#?}"); 146 | log::debug!("displaying with config {config:#?}"); 147 | 148 | let this_err = match img { 149 | MaybeTransferred::NotYet(image) => { 150 | let mut fake_image = Image { 151 | num_or_id: image.num_or_id, 152 | format: PixelFormat::Rgb24( 153 | ImageDimensions { 154 | width: 0, 155 | height: 0 156 | }, 157 | None 158 | ), 159 | medium: Medium::Direct { 160 | chunk_size: None, 161 | data: (&[]).into() 162 | } 163 | }; 164 | std::mem::swap(image, &mut fake_image); 165 | 166 | let res = run_action( 167 | Action::TransmitAndDisplay { 168 | image: fake_image, 169 | config, 170 | placement_id: None 171 | }, 172 | ev_stream 173 | ) 174 | .await; 175 | 176 | match res { 177 | Ok(img_id) => { 178 | *img = MaybeTransferred::Transferred(img_id); 179 | Ok(()) 180 | } 181 | Err(e) => Err((page_num, e)) 182 | } 183 | } 184 | MaybeTransferred::Transferred(image_id) => run_action( 185 | Action::Display { 186 | image_id: *image_id, 187 | placement_id: *image_id, 188 | config 189 | }, 190 | ev_stream 191 | ) 192 | .await 193 | .map(|_| ()) 194 | .map_err(|e| (page_num, e)) 195 | }; 196 | 197 | log::debug!("this_err is {this_err:#?}"); 198 | 199 | if let Err((id, e)) = this_err { 200 | let e = err.get_or_insert_with(|| (vec![], e)); 201 | e.0.push(id); 202 | } 203 | } 204 | 205 | match err { 206 | Some((replace, e)) => Err((replace, "Couldn't transfer image to the terminal", e)), 207 | None => Ok(()) 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /benches/utils.rs: -------------------------------------------------------------------------------- 1 | use std::{hint::black_box, path::Path}; 2 | 3 | use crossterm::terminal::WindowSize; 4 | use flume::{Sender, r#async::RecvStream, unbounded}; 5 | use futures_util::stream::StreamExt as _; 6 | use ratatui::layout::Rect; 7 | use ratatui_image::picker::{Picker, ProtocolType}; 8 | use tdf::{ 9 | converter::{ConvertedPage, ConverterMsg, run_conversion_loop}, 10 | renderer::{RenderError, RenderInfo, RenderNotif, fill_default, start_rendering} 11 | }; 12 | 13 | pub fn handle_renderer_msg( 14 | msg: Result, 15 | pages: &mut Vec>, 16 | to_converter_tx: &Sender 17 | ) { 18 | match msg { 19 | Ok(RenderInfo::NumPages(num)) => { 20 | fill_default(pages, num); 21 | to_converter_tx.send(ConverterMsg::NumPages(num)).unwrap(); 22 | } 23 | Ok(RenderInfo::Page(info)) => to_converter_tx.send(ConverterMsg::AddImg(info)).unwrap(), 24 | // We can ignore the these variants 'cause they're only used to send info to the TUI 25 | Ok(RenderInfo::Reloaded | RenderInfo::SearchResults { .. }) => (), 26 | Err(e) => panic!("Got error from renderer: {e:?}") 27 | } 28 | } 29 | 30 | pub fn handle_converter_msg( 31 | msg: Result, 32 | pages: &mut [Option], 33 | to_converter_tx: &Sender 34 | ) { 35 | let page = msg.expect("Got error from converter"); 36 | let num = page.num; 37 | 38 | pages[num] = Some(page); 39 | 40 | let first_none = pages.iter().position(Option::is_none); 41 | 42 | // we have to tell it to jump to a certain page so that it will actually render it (since 43 | // it only renders fanning out from the page that we currently have selected) 44 | if let Some(first) = first_none { 45 | to_converter_tx.send(ConverterMsg::GoToPage(first)).unwrap(); 46 | } 47 | } 48 | 49 | pub struct RenderState { 50 | pub from_render_rx: RecvStream<'static, Result>, 51 | pub from_converter_rx: RecvStream<'static, Result>, 52 | pub pages: Vec>, 53 | pub to_converter_tx: Sender, 54 | pub to_render_tx: Sender 55 | } 56 | 57 | const FONT_SIZE: (u16, u16) = (8, 14); 58 | 59 | pub fn start_rendering_loop( 60 | path: impl AsRef, 61 | black: i32, 62 | white: i32 63 | ) -> ( 64 | RecvStream<'static, Result>, 65 | Sender 66 | ) { 67 | let pathbuf = path.as_ref().canonicalize().unwrap(); 68 | let str_path = pathbuf.into_os_string().to_string_lossy().to_string(); 69 | 70 | let (to_render_tx, from_main_rx) = unbounded(); 71 | let (to_main_tx, from_render_rx) = unbounded(); 72 | 73 | let (columns, rows) = (60, 180); 74 | 75 | let size = WindowSize { 76 | columns, 77 | rows, 78 | height: rows * FONT_SIZE.1, 79 | width: columns * FONT_SIZE.0 80 | }; 81 | 82 | let main_area = Rect { 83 | x: 0, 84 | y: 0, 85 | width: columns - 2, 86 | height: rows - 6 87 | }; 88 | to_render_tx.send(RenderNotif::Area(main_area)).unwrap(); 89 | 90 | let cell_height_px = size.height / size.rows; 91 | let cell_width_px = size.width / size.columns; 92 | std::thread::spawn(move || { 93 | start_rendering( 94 | &str_path, 95 | to_main_tx, 96 | from_main_rx, 97 | cell_height_px, 98 | cell_width_px, 99 | tdf::PrerenderLimit::All, 100 | black, 101 | white 102 | ) 103 | }); 104 | 105 | let from_render_rx = from_render_rx.into_stream(); 106 | (from_render_rx, to_render_tx) 107 | } 108 | 109 | #[must_use] 110 | pub fn start_converting_loop( 111 | proto: ProtocolType, 112 | prerender: usize 113 | ) -> ( 114 | RecvStream<'static, Result>, 115 | Sender 116 | ) { 117 | let (to_converter_tx, from_main_rx) = unbounded(); 118 | let (to_main_tx, from_converter_rx) = unbounded(); 119 | 120 | let mut picker = Picker::from_fontsize(FONT_SIZE); 121 | picker.set_protocol_type(proto); 122 | 123 | tokio::spawn(run_conversion_loop( 124 | to_main_tx, 125 | from_main_rx, 126 | picker, 127 | prerender, 128 | // just assume shms work for now, who cares 129 | true 130 | )); 131 | 132 | let from_converter_rx = from_converter_rx.into_stream(); 133 | (from_converter_rx, to_converter_tx) 134 | } 135 | 136 | pub fn start_all_rendering( 137 | path: impl AsRef, 138 | black: i32, 139 | white: i32, 140 | proto: ProtocolType 141 | ) -> RenderState { 142 | let (from_render_rx, to_render_tx) = start_rendering_loop(path, black, white); 143 | let (from_converter_rx, to_converter_tx) = start_converting_loop(proto, 20); 144 | 145 | let pages: Vec> = Vec::new(); 146 | 147 | RenderState { 148 | from_render_rx, 149 | from_converter_rx, 150 | pages, 151 | to_converter_tx, 152 | to_render_tx 153 | } 154 | } 155 | 156 | pub async fn render_doc( 157 | path: impl AsRef, 158 | search_term: Option<&str>, 159 | black: i32, 160 | white: i32, 161 | proto: ProtocolType 162 | ) { 163 | let RenderState { 164 | mut from_render_rx, 165 | mut from_converter_rx, 166 | mut pages, 167 | to_converter_tx, 168 | to_render_tx 169 | } = start_all_rendering(path, black, white, proto); 170 | 171 | if let Some(term) = search_term { 172 | to_render_tx 173 | .send(RenderNotif::Search(term.to_owned())) 174 | .unwrap(); 175 | } 176 | 177 | while pages.is_empty() || pages.iter().any(Option::is_none) { 178 | tokio::select! { 179 | Some(renderer_msg) = from_render_rx.next() => { 180 | handle_renderer_msg(renderer_msg, &mut pages, &to_converter_tx); 181 | }, 182 | Some(converter_msg) = from_converter_rx.next() => { 183 | handle_converter_msg(converter_msg, &mut pages, &to_converter_tx); 184 | } 185 | } 186 | } 187 | 188 | black_box(pages); 189 | // we want to make sure this is kept around until the end of this function, or else the other 190 | // thread will see that this is disconnected and think that we're done communicating with them 191 | drop(to_render_tx); 192 | } 193 | -------------------------------------------------------------------------------- /src/converter.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | num::NonZeroUsize, 3 | time::{SystemTime, UNIX_EPOCH} 4 | }; 5 | 6 | use flume::{Receiver, SendError, Sender, TryRecvError}; 7 | use futures_util::stream::StreamExt as _; 8 | use image::DynamicImage; 9 | use kittage::{NumberOrId, action::NONZERO_ONE}; 10 | use ratatui::layout::Rect; 11 | use ratatui_image::{ 12 | Resize, 13 | picker::{Picker, ProtocolType}, 14 | protocol::Protocol 15 | }; 16 | use rayon::iter::ParallelIterator as _; 17 | 18 | use crate::{ 19 | renderer::{PageInfo, RenderError, fill_default}, 20 | skip::InterleavedAroundWithMax 21 | }; 22 | 23 | #[derive(Debug)] 24 | pub enum MaybeTransferred { 25 | NotYet(kittage::image::Image<'static>), 26 | Transferred(kittage::ImageId) 27 | } 28 | 29 | #[derive(Debug)] 30 | pub enum ConvertedImage { 31 | Generic(Protocol), 32 | Kitty { 33 | img: MaybeTransferred, 34 | cell_w: u16, 35 | cell_h: u16 36 | } 37 | } 38 | 39 | impl ConvertedImage { 40 | #[must_use] 41 | pub fn w_h(&self) -> (u16, u16) { 42 | match self { 43 | Self::Generic(prot) => { 44 | let a = prot.area(); 45 | (a.width, a.height) 46 | } 47 | Self::Kitty { 48 | img: _, 49 | cell_w, 50 | cell_h 51 | } => (*cell_w, *cell_h) 52 | } 53 | } 54 | } 55 | 56 | pub struct ConvertedPage { 57 | pub page: ConvertedImage, 58 | pub num: usize, 59 | pub num_results: usize 60 | } 61 | 62 | pub enum ConverterMsg { 63 | NumPages(usize), 64 | GoToPage(usize), 65 | AddImg(PageInfo) 66 | } 67 | 68 | pub async fn run_conversion_loop( 69 | sender: Sender>, 70 | receiver: Receiver, 71 | picker: Picker, 72 | prerender: usize, 73 | shms_work: bool 74 | ) -> Result<(), SendError>> { 75 | let mut images = vec![]; 76 | let mut page: usize = 0; 77 | let pid = std::process::id(); 78 | 79 | fn next_page( 80 | images: &mut [Option], 81 | picker: &Picker, 82 | page: usize, 83 | iteration: &mut usize, 84 | prerender: usize, 85 | pid: u32, 86 | shms_work: bool 87 | ) -> Result, RenderError> { 88 | if images.is_empty() || *iteration >= prerender { 89 | return Ok(None); 90 | } 91 | 92 | // This kinda mimics the way the renderer alternates between going above and below the 93 | // current page (within the bounds of how many pages there are) until we've done 20 94 | let idx_start = page.saturating_sub(prerender / 2); 95 | let idx_end = idx_start.saturating_add(prerender).min(images.len()); 96 | 97 | // If there's none to render, then why bother. 98 | let Some(idx_end) = NonZeroUsize::new(idx_end) else { 99 | return Ok(None); 100 | }; 101 | 102 | // then we go through all the indices available to us and find the first one that has an 103 | // image available to steal 104 | let Some((page_info, new_iter, page_num)) = 105 | InterleavedAroundWithMax::new(page, idx_start, idx_end) 106 | .enumerate() 107 | .take(prerender) 108 | // .skip(*iteration) 109 | .find_map(|(i_idx, p_idx)| images[p_idx].take().map(|p| (p, i_idx, p_idx))) 110 | else { 111 | return Ok(None); 112 | }; 113 | 114 | let mut dyn_img = image::load_from_memory_with_format( 115 | &page_info.img_data.pixels, 116 | image::ImageFormat::Pnm 117 | ) 118 | .map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?; 119 | 120 | match dyn_img { 121 | DynamicImage::ImageRgb8(ref mut img) => 122 | for quad in &*page_info.result_rects { 123 | img.par_enumerate_pixels_mut() 124 | .filter(|(x, y, _)| { 125 | *x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_y 126 | }) 127 | .for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2)); 128 | }, 129 | _ => unreachable!() 130 | } 131 | 132 | let img_area = Rect { 133 | width: page_info.img_data.cell_w, 134 | height: page_info.img_data.cell_h, 135 | x: 0, 136 | y: 0 137 | }; 138 | 139 | let txt_img = match picker.protocol_type() { 140 | ProtocolType::Kitty => { 141 | let rn = SystemTime::now() 142 | .duration_since(UNIX_EPOCH) 143 | .unwrap_or_default() 144 | .as_nanos() % 1_000_000; 145 | 146 | let mut img = if shms_work { 147 | kittage::image::Image::shm_from(dyn_img, &format!("/tdf_{pid}_{rn}_{page_num}")) 148 | .map_err(|e| { 149 | RenderError::Converting(format!("Couldn't write to shm: {e:?}")) 150 | })? 151 | } else { 152 | kittage::image::Image::from(dyn_img) 153 | }; 154 | 155 | // if ur pdf has 4 billion pages then you deserve to suffer 156 | img.num_or_id = NumberOrId::Id(NONZERO_ONE.saturating_add(page_num as u32)); 157 | 158 | ConvertedImage::Kitty { 159 | img: MaybeTransferred::NotYet(img), 160 | cell_w: page_info.img_data.cell_w, 161 | cell_h: page_info.img_data.cell_h 162 | } 163 | } 164 | _ => ConvertedImage::Generic( 165 | picker 166 | .new_protocol(dyn_img, img_area, Resize::None) 167 | .map_err(|e| { 168 | RenderError::Converting(format!( 169 | "Couldn't convert DynamicImage to ratatui image: {e}" 170 | )) 171 | })? 172 | ) 173 | }; 174 | 175 | log::debug!( 176 | "got converted page for num {} with results {:?}", 177 | page_info.page_num, 178 | page_info.result_rects 179 | ); 180 | 181 | // update the iteration to the iteration that we stole this image from 182 | *iteration = new_iter; 183 | 184 | Ok(Some(ConvertedPage { 185 | page: txt_img, 186 | num: page_info.page_num, 187 | num_results: page_info.result_rects.len() 188 | })) 189 | } 190 | 191 | fn handle_notif(msg: ConverterMsg, images: &mut Vec>, page: &mut usize) { 192 | match msg { 193 | ConverterMsg::AddImg(img) => { 194 | let page_num = img.page_num; 195 | images[page_num] = Some(img); 196 | } 197 | ConverterMsg::NumPages(n_pages) => { 198 | fill_default(images, n_pages); 199 | *page = (*page).min(n_pages - 1); 200 | } 201 | ConverterMsg::GoToPage(new_page) => *page = new_page 202 | } 203 | } 204 | 205 | 'outer: loop { 206 | let mut iteration = 0; 207 | loop { 208 | match receiver.try_recv() { 209 | Ok(msg) => { 210 | handle_notif(msg, &mut images, &mut page); 211 | continue 'outer; 212 | } 213 | Err(TryRecvError::Empty) => (), 214 | // if it's disconnected, we're done. just return. 215 | Err(TryRecvError::Disconnected) => return Ok(()) 216 | } 217 | 218 | match next_page( 219 | &mut images, 220 | &picker, 221 | page, 222 | &mut iteration, 223 | prerender, 224 | pid, 225 | shms_work 226 | ) { 227 | Ok(None) => break, 228 | Ok(Some(img)) => sender.send(Ok(img))?, 229 | Err(e) => sender.send(Err(e))? 230 | } 231 | } 232 | 233 | let Some(msg) = receiver.stream().next().await else { 234 | break; 235 | }; 236 | 237 | handle_notif(msg, &mut images, &mut page); 238 | } 239 | 240 | Ok(()) 241 | } 242 | -------------------------------------------------------------------------------- /benches/rendering.rs: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | use std::{hint::black_box, path::Path}; 4 | 5 | use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main}; 6 | use futures_util::StreamExt as _; 7 | use ratatui_image::picker::ProtocolType; 8 | use tdf::{ 9 | converter::{ConvertedPage, ConverterMsg}, 10 | renderer::{PageInfo, RenderInfo, fill_default} 11 | }; 12 | use tokio::runtime::Runtime; 13 | use utils::{ 14 | RenderState, handle_converter_msg, handle_renderer_msg, render_doc, start_all_rendering, 15 | start_converting_loop, start_rendering_loop 16 | }; 17 | 18 | const FILES: [&str; 3] = [ 19 | "benches/adobe_example.pdf", 20 | "benches/example_dictionary.pdf", 21 | "benches/geotopo.pdf" 22 | ]; 23 | 24 | const PROTOS: [ProtocolType; 3] = [ 25 | ProtocolType::Kitty, 26 | ProtocolType::Sixel, 27 | ProtocolType::Iterm2 28 | ]; 29 | 30 | const BLACK: i32 = 0; 31 | const WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]); 32 | 33 | fn for_all_combos( 34 | name: &'static str, 35 | mut f: impl FnMut(&Runtime, BenchmarkId, &'static str, ProtocolType) 36 | ) { 37 | let rt = tokio::runtime::Runtime::new().unwrap(); 38 | for proto in PROTOS { 39 | for file in FILES { 40 | f( 41 | &rt, 42 | BenchmarkId::new(name, format!("{file},{proto:?}")), 43 | file, 44 | proto 45 | ); 46 | } 47 | } 48 | } 49 | 50 | fn render_full(c: &mut Criterion) { 51 | for_all_combos("render_full", |rt, id, file, proto| { 52 | _ = c.bench_with_input(id, &file, |b, &file| { 53 | b.to_async(rt) 54 | .iter(|| render_doc(file, None, BLACK, WHITE, proto)); 55 | }); 56 | }); 57 | } 58 | 59 | fn render_to_first_page(c: &mut Criterion) { 60 | for_all_combos("render_first_page", |rt, id, file, proto| { 61 | c.bench_with_input(id, &file, |b, &file| { 62 | b.to_async(rt) 63 | .iter(|| render_first_page(file, BLACK, WHITE, proto)); 64 | }); 65 | }); 66 | } 67 | 68 | fn only_converting(c: &mut Criterion) { 69 | for_all_combos("only_converting", |rt, id, file, proto| { 70 | let all_rendered = rt.block_on(render_all_files(file, BLACK, WHITE)); 71 | 72 | c.bench_with_input(id, &all_rendered, |b, rendered| { 73 | b.to_async(rt) 74 | .iter_with_setup(|| rendered.clone(), |f| convert_all_files(f, proto)); 75 | }); 76 | }); 77 | } 78 | 79 | /* 80 | fn search_short_common(c: &mut Criterion) { 81 | for_all_combos("search_short_common", |rt, id, file, proto| { 82 | c.bench_with_input(id, &file, |b, &file| { 83 | b.to_async(rt) 84 | .iter(|| render_doc(file, Some("an"), BLACK, WHITE, proto)) 85 | }); 86 | }); 87 | } 88 | 89 | fn search_long_rare(c: &mut Criterion) { 90 | for_all_combos("search_long_rare", |rt, id, file, proto| { 91 | c.bench_with_input(id, &file, |b, &file| { 92 | b.to_async(rt) 93 | .iter(|| render_doc(file, Some("this is long and rare"), BLACK, WHITE, proto)) 94 | }); 95 | }); 96 | } 97 | */ 98 | 99 | pub async fn render_first_page( 100 | path: impl AsRef, 101 | black: i32, 102 | white: i32, 103 | proto: ProtocolType 104 | ) { 105 | let RenderState { 106 | mut from_render_rx, 107 | mut from_converter_rx, 108 | mut pages, 109 | to_converter_tx, 110 | to_render_tx 111 | } = start_all_rendering(path, black, white, proto); 112 | 113 | // we only want to render until the first page is ready to be printed 114 | while pages.iter().all(Option::is_none) { 115 | tokio::select! { 116 | Some(renderer_msg) = from_render_rx.next() => { 117 | handle_renderer_msg(renderer_msg, &mut pages, &to_converter_tx); 118 | }, 119 | Some(converter_msg) = from_converter_rx.next() => { 120 | handle_converter_msg(converter_msg, &mut pages, &to_converter_tx); 121 | } 122 | } 123 | } 124 | 125 | black_box(pages); 126 | // we want to make sure this is kept around until the end of this function, or else the other 127 | // thread will see that this is disconnected and think that we're done communicating with them 128 | drop(to_render_tx); 129 | } 130 | 131 | async fn render_all_files(path: &'static str, black: i32, white: i32) -> Vec { 132 | let (mut from_render_rx, to_render_tx) = start_rendering_loop(path, black, white); 133 | let mut pages = Vec::>::new(); 134 | 135 | while let Some(info) = from_render_rx.next().await { 136 | match info.expect("Renderer ran into an error while rendering") { 137 | RenderInfo::Reloaded | RenderInfo::SearchResults { .. } => (), 138 | RenderInfo::NumPages(num) => fill_default(&mut pages, num), 139 | RenderInfo::Page(page) => { 140 | let num = page.page_num; 141 | pages[num] = Some(page); 142 | } 143 | } 144 | 145 | if pages.iter().all(Option::is_some) { 146 | break; 147 | } 148 | } 149 | 150 | drop(to_render_tx); 151 | pages.into_iter().flatten().collect() 152 | } 153 | 154 | async fn convert_all_files(files: Vec, proto: ProtocolType) { 155 | let num_files = files.len(); 156 | let (mut from_converter_rx, to_converter_tx) = start_converting_loop(proto, num_files); 157 | 158 | to_converter_tx 159 | .send(ConverterMsg::NumPages(num_files)) 160 | .unwrap(); 161 | 162 | let mut converted = Vec::>::new(); 163 | fill_default(&mut converted, num_files); 164 | 165 | for page in files { 166 | to_converter_tx.send(ConverterMsg::AddImg(page)).unwrap(); 167 | 168 | if !from_converter_rx.is_empty() { 169 | let page = from_converter_rx 170 | .next() 171 | .await 172 | .expect("Converter ended stream before expected") 173 | .expect("Converter ran into an error while converting page"); 174 | 175 | let num = page.num; 176 | converted[num] = Some(page); 177 | } 178 | } 179 | 180 | while converted.iter().any(Option::is_none) { 181 | let page = from_converter_rx 182 | .next() 183 | .await 184 | .expect("Converted ended stream before expected") 185 | .expect("Converted ran into an error while converting page"); 186 | 187 | let num = page.num; 188 | converted[num] = Some(page); 189 | } 190 | 191 | drop(to_converter_tx); 192 | black_box(converted); 193 | } 194 | 195 | /* 196 | struct CpuProfiler; 197 | 198 | impl criterion::profiler::Profiler for CpuProfiler { 199 | fn start_profiling(&mut self, benchmark_id: &str, _: &std::path::Path) { 200 | use std::time::{SystemTime, UNIX_EPOCH} 201 | let file = format!( 202 | "./{}-{}.profile", 203 | benchmark_id.replace('/', "-"), 204 | SystemTime::now() 205 | .duration_since(UNIX_EPOCH) 206 | .unwrap() 207 | .as_millis() 208 | ); 209 | 210 | cpuprofiler::PROFILER.lock().unwrap().start(file).unwrap() 211 | } 212 | fn stop_profiling(&mut self, _: &str, _: &std::path::Path) { 213 | cpuprofiler::PROFILER.lock().unwrap().stop().unwrap(); 214 | } 215 | } 216 | */ 217 | 218 | criterion_group!( 219 | name = benches; 220 | // config = Criterion::default().sample_size(40).with_profiler(CpuProfiler); 221 | config = Criterion::default().sample_size(40); 222 | // targets = render_full, render_to_first_page, only_converting, search_short_common, search_long_rare 223 | targets = render_full, render_to_first_page, only_converting 224 | ); 225 | criterion_main!(benches); 226 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tdf-viewer" 3 | version = "0.5.0" 4 | authors = ["June Welker "] 5 | edition = "2024" 6 | description = "A terminal viewer for PDFs" 7 | readme = "README.md" 8 | homepage = "https://github.com/itsjunetime/tdf" 9 | repository = "https://github.com/itsjunetime/tdf" 10 | license = "AGPL-3.0-only" 11 | keywords = ["pdf", "tui", "cli", "terminal"] 12 | categories = ["command-line-utilities", "text-processing", "visualization"] 13 | default-run = "tdf" 14 | rust-version = "1.86" 15 | 16 | [[bin]] 17 | name = "tdf" 18 | path = "src/main.rs" 19 | 20 | # lib only exists for benching 21 | [lib] 22 | name = "tdf" 23 | 24 | [dependencies] 25 | # we're using this branch because it has significant performance fixes that I'm waiting on responses from the upstream devs to get upstreamed. See https://github.com/ratatui-org/ratatui/issues/1116 26 | ratatui = { git = "https://github.com/itsjunetime/ratatui.git" } 27 | # ratatui = { path = "./ratatui/ratatui/" } 28 | # We're using this to have the vb64 feature (for faster base64 encoding, since that does take up a good bit of time when converting images to the `Protocol`. It also just includes a few more features that I'm waiting on main to upstream 29 | ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", branch = "vb64_on_personal", default-features = false } 30 | # ratatui-image = { path = "./ratatui-image", default-features = false } 31 | crossterm = { version = "0.29.0", features = ["event-stream"] } 32 | # crossterm = { path = "../crossterm", features = ["event-stream"] } 33 | image = { version = "0.25.1", features = ["pnm", "rayon", "png"], default-features = false } 34 | notify = { version = "8.0.0", features = ["crossbeam-channel"] } 35 | tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] } 36 | futures-util = { version = "0.3.30", default-features = false } 37 | flume = { version = "0.11.0", default-features = false, features = ["async"] } 38 | xflags = "0.4.0-pre.2" 39 | mimalloc = "0.1.43" 40 | nix = { version = "0.30.0", features = ["signal"] } 41 | mupdf = { git = "https://github.com/messense/mupdf-rs.git", rev = "2e0fae910fac8048c7008211fc4d3b9f5d227a07", default-features = false, features = ["svg", "system-fonts", "img"] } 42 | rayon = { version = "1", default-features = false } 43 | # kittage = { path = "../kittage/", features = ["crossterm-tokio", "image-crate", "log"] } 44 | kittage = { version = "0.1.1", features = ["crossterm-tokio", "image-crate", "log"] } 45 | memmap2 = "0" 46 | csscolorparser = { version = "0.8.0", default-features = false } 47 | 48 | # logging 49 | log = "0.4.27" 50 | flexi_logger = "0.31" 51 | 52 | # for tracing with tokio-console 53 | console-subscriber = { version = "0.5.0", optional = true } 54 | debounce = "0.2.2" 55 | 56 | [profile.production] 57 | inherits = "release" 58 | lto = "fat" 59 | 60 | [features] 61 | default = [] 62 | tracing = ["tokio/tracing", "dep:console-subscriber"] 63 | epub = ["mupdf/epub"] 64 | cbz = ["mupdf/cbz"] 65 | 66 | [dev-dependencies] 67 | criterion = { version = "0.7.0", features = ["async_tokio"] } 68 | cpuprofiler = "0.0.4" 69 | 70 | [[bench]] 71 | name = "rendering" 72 | harness = false 73 | 74 | [[bin]] 75 | name = "for_profiling" 76 | path = "./benches/for_profiling.rs" 77 | 78 | [lints.clippy] 79 | alloc_instead_of_core = "warn" 80 | allow_attributes = "warn" 81 | as_pointer_underscore = "warn" 82 | as_ptr_cast_mut = "warn" 83 | as_underscore = "warn" 84 | assigning_clones = "warn" 85 | assertions_on_result_states = "warn" 86 | bool_to_int_with_if = "warn" 87 | borrow_as_ptr = "warn" 88 | branches_sharing_code = "warn" 89 | cargo_common_metadata = "warn" 90 | case_sensitive_file_extension_comparisons = "warn" 91 | cast_lossless = "warn" 92 | cast_ptr_alignment = "warn" 93 | cfg_not_test = "warn" 94 | checked_conversions = "warn" 95 | clear_with_drain = "warn" 96 | cloned_instead_of_copied = "warn" 97 | coerce_container_to_any = "warn" 98 | comparison_chain = "warn" 99 | copy_iterator = "warn" 100 | create_dir = "warn" 101 | debug_assert_with_mut_call = "warn" 102 | decimal_literal_representation = "warn" 103 | default_trait_access = "warn" 104 | deref_by_slicing = "warn" 105 | doc_broken_link = "warn" 106 | doc_link_code = "warn" 107 | doc_link_with_quotes = "warn" 108 | elidable_lifetime_names = "warn" 109 | empty_drop = "warn" 110 | empty_enums = "warn" 111 | empty_enum_variants_with_brackets = "warn" 112 | empty_structs_with_brackets = "warn" 113 | equatable_if_let = "warn" 114 | error_impl_error = "warn" 115 | expl_impl_clone_on_copy = "warn" 116 | explicit_deref_methods = "warn" 117 | explicit_into_iter_loop = "warn" 118 | explicit_iter_loop = "warn" 119 | fallible_impl_from = "warn" 120 | filetype_is_file = "warn" 121 | filter_map_next = "warn" 122 | flat_map_option = "warn" 123 | fn_to_numeric_cast_any = "warn" 124 | fn_params_excessive_bools = "warn" 125 | format_collect = "warn" 126 | format_push_string = "warn" 127 | get_unwrap = "warn" 128 | if_then_some_else_none = "warn" 129 | ignore_without_reason = "warn" 130 | ignored_unit_patterns = "warn" 131 | implicit_clone = "warn" 132 | imprecise_flops = "warn" 133 | index_refutable_slice = "warn" 134 | indexing_slicing = "allow" # can't warn on this cause we basically have to do indexing for some ratatui apis 135 | infinite_loop = "warn" 136 | invalid_upcast_comparisons = "warn" 137 | ip_constant = "warn" 138 | iter_filter_is_ok = "warn" 139 | iter_filter_is_some = "warn" 140 | iter_not_returning_iterator = "warn" 141 | iter_on_empty_collections = "warn" 142 | iter_on_single_items = "warn" 143 | large_digit_groups = "warn" 144 | large_futures = "warn" 145 | large_include_file = "warn" 146 | large_stack_frames = "warn" 147 | large_types_passed_by_value = "warn" 148 | linkedlist = "warn" 149 | literal_string_with_formatting_args = "warn" 150 | lossy_float_literal = "warn" 151 | macro_use_imports = "warn" 152 | manual_assert = "warn" 153 | manual_instant_elapsed = "warn" 154 | manual_is_power_of_two = "warn" 155 | manual_is_variant_and = "warn" 156 | manual_let_else = "warn" 157 | manual_midpoint = "warn" 158 | manual_ok_or = "warn" 159 | many_single_char_names = "warn" 160 | map_err_ignore = "warn" 161 | map_unwrap_or = "warn" 162 | map_with_unused_argument_over_ranges = "warn" 163 | match_same_arms = "warn" 164 | match_wild_err_arm = "warn" 165 | match_wildcard_for_single_variants = "warn" 166 | maybe_infinite_iter = "warn" 167 | mem_forget = "warn" 168 | mismatching_type_param_order = "warn" 169 | missing_assert_message = "warn" 170 | missing_fields_in_debug = "warn" 171 | mixed_read_write_in_expression = "warn" 172 | multiple_unsafe_ops_per_block = "warn" 173 | must_use_candidate = "warn" 174 | mut_mut = "warn" 175 | mutex_atomic = "warn" 176 | mutex_integer = "warn" 177 | naive_bytecount = "warn" 178 | needless_bitwise_bool = "warn" 179 | needless_collect = "warn" 180 | needless_continue = "warn" 181 | needless_for_each = "warn" 182 | needless_pass_by_ref_mut = "warn" 183 | needless_pass_by_value = "warn" 184 | needless_raw_string_hashes = "warn" 185 | needless_raw_strings = "warn" 186 | negative_feature_names = "warn" 187 | no_effect_underscore_binding = "warn" 188 | no_mangle_with_rust_abi = "warn" 189 | non_send_fields_in_send_ty = "warn" 190 | non_std_lazy_statics = "warn" 191 | non_zero_suggestions = "warn" 192 | nonstandard_macro_braces = "warn" 193 | option_as_ref_cloned = "warn" 194 | option_option = "warn" 195 | or_fun_call = "warn" 196 | path_buf_push_overwrite = "warn" 197 | pathbuf_init_then_push = "warn" 198 | precedence_bits = "warn" 199 | ptr_as_ptr = "warn" 200 | ptr_cast_constness = "warn" 201 | pub_underscore_fields = "warn" 202 | pub_without_shorthand = "warn" 203 | range_minus_one = "warn" 204 | range_plus_one = "warn" 205 | rc_buffer = "warn" 206 | rc_mutex = "warn" 207 | read_zero_byte_vec = "warn" 208 | redundant_clone = "warn" 209 | redundant_closure_for_method_calls = "warn" 210 | redundant_else = "warn" 211 | redundant_pub_crate = "warn" 212 | redundant_test_prefix = "warn" 213 | ref_as_ptr = "warn" 214 | ref_binding_to_reference = "warn" 215 | ref_option = "warn" 216 | ref_option_ref = "warn" 217 | rest_pat_in_fully_bound_structs = "warn" 218 | return_self_not_must_use = "warn" 219 | same_functions_in_if_condition = "warn" 220 | self_named_module_files = "warn" 221 | semicolon_if_nothing_returned = "warn" 222 | semicolon_inside_block = "warn" 223 | should_panic_without_expect = "warn" 224 | significant_drop_in_scrutinee = "warn" # I thought this was fixed in the 2024 edition. watever 225 | significant_drop_tightening = "warn" 226 | single_char_pattern = "warn" 227 | single_option_map = "warn" 228 | stable_sort_primitive = "warn" 229 | str_split_at_newline = "warn" 230 | string_lit_as_bytes = "warn" 231 | string_lit_chars_any = "warn" 232 | string_slice = "warn" 233 | struct_excessive_bools = "warn" 234 | struct_field_names = "warn" 235 | suboptimal_flops = "warn" 236 | suspicious_operation_groupings = "warn" 237 | suspicious_xor_used_as_pow = "warn" 238 | tests_outside_test_module = "warn" 239 | trait_duplication_in_bounds = "warn" 240 | transmute_ptr_to_ptr = "warn" 241 | trivial_regex = "warn" 242 | trivially_copy_pass_by_ref = "warn" 243 | try_err = "warn" 244 | tuple_array_conversions = "warn" 245 | type_repetition_in_bounds = "warn" 246 | unchecked_time_subtraction = "warn" 247 | undocumented_unsafe_blocks = "warn" 248 | unicode_not_nfc = "warn" 249 | uninhabited_references = "warn" 250 | uninlined_format_args = "warn" 251 | unnecessary_box_returns = "warn" 252 | unnecessary_debug_formatting = "warn" 253 | unnecessary_join = "warn" 254 | unnecessary_literal_bound = "warn" 255 | unnecessary_safety_comment = "warn" 256 | unnecessary_safety_doc = "warn" 257 | unnecessary_self_imports = "warn" 258 | unnecessary_semicolon = "warn" 259 | unnecessary_struct_initialization = "warn" 260 | unnecessary_wraps = "warn" 261 | unnested_or_patterns = "warn" 262 | unreadable_literal = "warn" 263 | unsafe_derive_deserialize = "warn" 264 | unused_async = "warn" 265 | unused_peekable = "warn" 266 | unused_result_ok = "warn" 267 | unused_rounding = "warn" 268 | unused_self = "warn" 269 | unused_trait_names = "warn" 270 | use_self = "warn" 271 | used_underscore_binding = "warn" 272 | used_underscore_items = "warn" 273 | useless_let_if_seq = "warn" 274 | verbose_bit_mask = "warn" 275 | verbose_file_reads = "warn" 276 | volatile_composites = "warn" 277 | while_float = "warn" 278 | wildcard_dependencies = "warn" 279 | wildcard_imports = "warn" 280 | zero_sized_map_values = "warn" 281 | -------------------------------------------------------------------------------- /src/renderer.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::VecDeque, num::NonZeroUsize, thread::sleep, time::Duration}; 2 | 3 | use flume::{Receiver, SendError, Sender, TryRecvError}; 4 | use mupdf::{ 5 | Colorspace, Document, Matrix, Page, Pixmap, Quad, TextPageFlags, text_page::SearchHitResponse 6 | }; 7 | use ratatui::layout::Rect; 8 | 9 | use crate::{ 10 | FitOrFill, PrerenderLimit, ScaledResult, scale_img_for_area, skip::InterleavedAroundWithMax 11 | }; 12 | 13 | const KITTY_MAX_W_OR_H: f32 = 10_000.0; 14 | 15 | #[derive(Debug)] 16 | pub enum RenderNotif { 17 | Area(Rect), 18 | JumpToPage(usize), 19 | PageNeedsReRender(usize), 20 | Search(String), 21 | SwitchFitOrFill(FitOrFill), 22 | Reload, 23 | Invert 24 | } 25 | 26 | #[derive(Debug)] 27 | pub enum RenderError { 28 | Notify(notify::Error), 29 | Doc(mupdf::error::Error), 30 | Converting(String) 31 | } 32 | 33 | pub enum RenderInfo { 34 | NumPages(usize), 35 | Page(PageInfo), 36 | SearchResults { page_num: usize, num_results: usize }, 37 | Reloaded 38 | } 39 | 40 | #[derive(Clone)] 41 | pub struct PageInfo { 42 | pub img_data: ImageData, 43 | pub page_num: usize, 44 | pub result_rects: Vec 45 | } 46 | 47 | #[derive(Clone)] 48 | pub struct ImageData { 49 | pub pixels: Vec, 50 | pub cell_w: u16, 51 | pub cell_h: u16 52 | } 53 | 54 | #[derive(Default)] 55 | struct PrevRender { 56 | successful: bool, 57 | num_search_found: Option 58 | } 59 | 60 | const MUPDF_BLACK: i32 = 0; 61 | const MUPDF_WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]); 62 | 63 | #[inline] 64 | pub fn fill_default(vec: &mut Vec, size: usize) { 65 | vec.clear(); 66 | vec.resize_with(size, T::default); 67 | } 68 | 69 | // this function has to be sync (non-async) because the mupdf::Document needs to be held during 70 | // most of it, but that's basically just a wrapper around `*c_void` cause it's just a binding to C 71 | // code, so it's !Send and thus can't be held across await points. So we can't call any of the 72 | // async `send` or `recv` methods in this function body, since those create await points. Which 73 | // means we need to call blocking_(send|recv). Those functions panic if called in an async context. 74 | // So here we are. 75 | // Also we just kinda 'unwrap' all of the send/recv calls here 'cause if they return an error, that 76 | // means the other side's disconnected, which means that the main thread has panicked, which means 77 | // we're done. 78 | // We're allowing passing by value here because this is only called once, at the beginning of the 79 | // program, and the arguments that 'should' be passed by value (`receiver` and `size`) would 80 | // probably be more performant if accessed by-value instead of through a reference. Probably. 81 | #[expect(clippy::needless_pass_by_value, clippy::too_many_arguments)] 82 | pub fn start_rendering( 83 | path: &str, 84 | sender: Sender>, 85 | receiver: Receiver, 86 | col_h: u16, 87 | col_w: u16, 88 | prerender: PrerenderLimit, 89 | black: i32, 90 | white: i32 91 | ) -> Result<(), SendError>> { 92 | // We want this outside of 'reload so that if the doc reloads, the search term that somebody 93 | // set will still get highlighted in the reloaded doc 94 | let mut search_term = None; 95 | 96 | // And although the font size could theoretically change, we aren't accounting for that right 97 | // now, so we just use the values passed in. 98 | 99 | let mut stored_doc = None; 100 | let mut invert = false; 101 | let mut preserved_area = None; 102 | let mut fit_or_fill = FitOrFill::Fit; 103 | 104 | let mut need_rerender = VecDeque::new(); 105 | 106 | 'reload: loop { 107 | let doc = match Document::open(path) { 108 | Err(e) => { 109 | // if there's an error, tell the main loop 110 | sender.send(Err(RenderError::Doc(e)))?; 111 | 112 | match stored_doc { 113 | Some(ref d) => d, 114 | None => { 115 | // then wait for a reload notif (since what probably happened is that the file was 116 | // temporarily removed to facilitate a save or something like that) 117 | while let Ok(msg) = receiver.recv() { 118 | // and once that comes, just try to reload again 119 | if matches!(msg, RenderNotif::Reload) { 120 | continue 'reload; 121 | } 122 | } 123 | // if that while let Ok ever fails and we exit out of that loop, the main thread is 124 | // done, so we're fine to just return 125 | return Ok(()); 126 | } 127 | } 128 | } 129 | Ok(d) => { 130 | if stored_doc.is_some() { 131 | sender.send(Ok(RenderInfo::Reloaded))?; 132 | } 133 | &*stored_doc.insert(d) 134 | } 135 | }; 136 | 137 | let n_pages = match doc.page_count() { 138 | Ok(n) => match NonZeroUsize::new(n as usize) { 139 | Some(n) => n, 140 | None => { 141 | sleep(Duration::from_secs(1)); 142 | continue 'reload; 143 | } 144 | }, 145 | Err(e) => { 146 | sender.send(Err(RenderError::Doc(e)))?; 147 | // just basic backoff i think 148 | sleep(Duration::from_secs(1)); 149 | continue 'reload; 150 | } 151 | }; 152 | 153 | sender.send(Ok(RenderInfo::NumPages(n_pages.get())))?; 154 | 155 | // We're using this vec of bools to indicate which page numbers have already been rendered, 156 | // to support people jumping to specific pages and having quick rendering results. We 157 | // `split_at_mut` at 0 initially (which bascially makes `right == rendered && left == []`), 158 | // doing basically nothing, but if we get a notification that something has been jumped to, 159 | // then we can split at that page and render at both sides of it 160 | let mut rendered = Vec::new(); 161 | fill_default::(&mut rendered, n_pages.get()); 162 | let mut start_point = 0; 163 | 164 | // This is kinda a weird way of doing this, but if we get a notification that the area 165 | // changed, we want to start re-rending all of the pages, but we don't want to reload the 166 | // document. If there was a mechanism to say 'start this for-loop over' then I would do 167 | // that, but I don't think such a thing exists, so this is our attempt 168 | 'render_pages: loop { 169 | // next, we gotta wait 'til we get told what the current starting area is so that we can 170 | // set it to know what to render to 171 | let area = preserved_area.unwrap_or_else(|| { 172 | let new_area = loop { 173 | if let RenderNotif::Area(r) = receiver.recv().unwrap() { 174 | break r; 175 | } 176 | }; 177 | preserved_area = Some(new_area); 178 | new_area 179 | }); 180 | 181 | let area_w = f32::from(area.width) * f32::from(col_w); 182 | let area_h = f32::from(area.height) * f32::from(col_h); 183 | 184 | // what we do with a notif is the same regardless of if we're in the middle of 185 | // rendering the list of pages or we're all done 186 | macro_rules! handle_notif { 187 | ($notif:ident) => {{ 188 | match $notif { 189 | RenderNotif::Reload => continue 'reload, 190 | RenderNotif::Invert => { 191 | invert = !invert; 192 | for page in &mut rendered { 193 | page.successful = false; 194 | } 195 | continue 'render_pages; 196 | } 197 | RenderNotif::Area(new_area) => { 198 | preserved_area = Some(new_area); 199 | fill_default(&mut rendered, n_pages.get()); 200 | continue 'render_pages; 201 | } 202 | RenderNotif::SwitchFitOrFill(f_or_f) => 203 | if f_or_f != fit_or_fill { 204 | fit_or_fill = f_or_f; 205 | fill_default(&mut rendered, n_pages.get()); 206 | continue 'render_pages; 207 | }, 208 | RenderNotif::JumpToPage(page) => { 209 | start_point = page; 210 | continue 'render_pages; 211 | } 212 | RenderNotif::PageNeedsReRender(page) => { 213 | rendered[page].successful = false; 214 | need_rerender.push_back(page); 215 | continue 'render_pages; 216 | } 217 | RenderNotif::Search(term) => { 218 | if term.is_empty() { 219 | // If the term is set to nothing, then we don't need to re-render 220 | // the pages wherein there were already no search results. So this 221 | // is a little optimization to allow that. 222 | for page in &mut rendered { 223 | if page.num_search_found.is_some_and(|n| n > 0) { 224 | page.num_search_found = Some(0); 225 | page.successful = false; 226 | } 227 | } 228 | search_term = None; 229 | } else { 230 | // But if the term is set to something new, we need to reset all of 231 | // the 'contained_term' fields so that if they now contain the 232 | // term, we can render them with the term, but if they don't, we 233 | // don't need to re-render and send it over again. 234 | for page in &mut rendered { 235 | page.num_search_found = None; 236 | } 237 | search_term = Some(term); 238 | } 239 | continue 'render_pages; 240 | } 241 | } 242 | }}; 243 | } 244 | 245 | let any_not_searched = rendered.iter().any(|r| r.num_search_found.is_none()); 246 | 247 | // This is our iterator over all the pages we want to look at and render. It uses this 248 | // weird 'interleave' thing to render pages on *both sides* of the currently-displayed 249 | // page in case they device to go forward or backwards. 250 | let page_iter = PopOnNext { 251 | inner: &mut need_rerender 252 | } 253 | .chain(InterleavedAroundWithMax::new(start_point, 0, n_pages).take( 254 | match (&prerender, &search_term) { 255 | // If the user has limited the amount of pages they want to prerender, then we 256 | // just do what they ask. Nice and easy. 257 | (PrerenderLimit::Limited(l), _) => l.get(), 258 | // If they haven't limited it, but we don't have any search term that we're 259 | // currently looking for, just go for all of it 260 | (PrerenderLimit::All, None) => n_pages.get(), 261 | // If they haven't limited it, and we DO have a search term we need to look 262 | // for, just do 20 so that we don't dramatically slow down the search process 263 | // since they've specifically initiated that and so we want it to take priority 264 | (PrerenderLimit::All, Some(_)) => 265 | if any_not_searched { 266 | 20 267 | } else { 268 | n_pages.get() 269 | }, 270 | } 271 | )); 272 | 273 | // we go through each page 274 | for page_num in page_iter { 275 | let rendered = &mut rendered[page_num]; 276 | 277 | // we only want to continue if one of the following is met: 278 | // 1. It failed to render last time (we want to retry) 279 | // 2. The `contained_term` is set to Unknown, meaning that we need to at least 280 | // check if it contains the current term to see if it needs a re-render 281 | if rendered.successful && rendered.num_search_found.is_some() { 282 | continue; 283 | } 284 | 285 | // We know this is in range 'cause we're iterating over it but we still just want 286 | // to be safe 287 | let page = match doc.load_page(page_num as i32) { 288 | Err(e) => { 289 | sender.send(Err(RenderError::Doc(e)))?; 290 | continue; 291 | } 292 | Ok(p) => p 293 | }; 294 | 295 | // render the page 296 | match render_single_page_to_ctx( 297 | &page, 298 | search_term.as_deref(), 299 | rendered, 300 | invert, 301 | black, 302 | white, 303 | fit_or_fill, 304 | (area_w, area_h) 305 | ) { 306 | // If that fn returned Some, that means it needed to be re-rendered for some 307 | // reason or another, so we're sending it here 308 | Ok(ctx) => { 309 | let w = ctx.pixmap.width(); 310 | let h = ctx.pixmap.height(); 311 | let cap = (w * h * u32::from(ctx.pixmap.n())) as usize + 16; 312 | let mut pixels = Vec::with_capacity(cap); 313 | if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) { 314 | sender.send(Err(RenderError::Doc(e)))?; 315 | continue; 316 | } 317 | 318 | log::debug!("got pixmap for page {page_num} with WxH {w}x{h}"); 319 | 320 | rendered.num_search_found = Some(ctx.result_rects.len()); 321 | rendered.successful = true; 322 | 323 | sender.send(Ok(RenderInfo::Page(PageInfo { 324 | img_data: ImageData { 325 | pixels, 326 | cell_w: (ctx.surface_w / f32::from(col_w)) as u16, 327 | cell_h: (ctx.surface_h / f32::from(col_h)) as u16 328 | }, 329 | page_num, 330 | result_rects: ctx.result_rects 331 | })))?; 332 | } 333 | // And if we got an error, then obviously we need to propagate that 334 | Err(e) => sender.send(Err(RenderError::Doc(e)))? 335 | } 336 | 337 | // check if we've been told to change the area that we're rendering to, 338 | // or if we're told to rerender 339 | match receiver.try_recv() { 340 | // If it's disconnected, then the main loop is done, so we should just give up 341 | Err(TryRecvError::Disconnected) => return Ok(()), 342 | Ok(notif) => handle_notif!(notif), 343 | Err(TryRecvError::Empty) => () 344 | } 345 | } 346 | 347 | // Now, if we have a search term, we want to look through the rest of the document past 348 | // what we've just rendered (and looked at the search results of) 349 | if let Some(ref term) = search_term { 350 | let mut search_start = start_point; 351 | loop { 352 | // hmm maybe this would be nice to make configurable but whatever 353 | const SEARCH_AT_TIME: usize = 20; 354 | 355 | // So now we want to look through all the remaining pages, starting after this 356 | // current one (we don't do interleaving here 'cause I'm lazy 357 | let page_idx = rendered[search_start..] 358 | .iter_mut() 359 | .enumerate() 360 | // And we only want to take max SEARCH_AT_TIME of them since we don't want 361 | // to block on this for *too* long 362 | .take(SEARCH_AT_TIME) 363 | // And we only want the ones that we still don't know about... 364 | .filter(|(_, r)| r.num_search_found.is_none()) 365 | // And then adjust the index to be correct for the actual page number 366 | .map(|(idx, r)| (idx + search_start, r)); 367 | 368 | // then we go through each... 369 | for (page_num, rendered) in page_idx { 370 | // We get the number of results (using the function that specifically just 371 | // counts them instead of determining the quads of them all) 372 | let num_results = doc 373 | .load_page(page_num as i32) 374 | .and_then(|page| count_search_results(&page, term)) 375 | .unwrap(); 376 | 377 | // And mark that whatever else was rendered last is not relevant anymore if 378 | // there are results that need to be rendered 379 | if num_results > 0 { 380 | rendered.successful = false; 381 | } 382 | // Mark the `contained_term` field with this updated value... 383 | rendered.num_search_found = Some(num_results); 384 | 385 | // And send it over to the tui so that they can know and use it to 386 | // determine what next page to jump to 387 | sender.send(Ok(RenderInfo::SearchResults { 388 | page_num, 389 | num_results 390 | }))?; 391 | } 392 | 393 | // then once we're done with this iteration, we increment search_start to 394 | // prepare for the next iteration 395 | search_start += SEARCH_AT_TIME; 396 | 397 | // now, we want to check if we've gone past the end - if so, we go back to the 398 | // beginning so we can get the pages before the current one. 399 | if search_start > n_pages.get() { 400 | if start_point == 0 { 401 | break; 402 | } 403 | 404 | search_start = 0; 405 | } else if ((search_start - SEARCH_AT_TIME) + 1..search_start) 406 | .contains(&start_point) 407 | { 408 | // And if we are back at the place we started, we've looked through all the 409 | // pages. Quit. 410 | break; 411 | } 412 | 413 | match receiver.try_recv() { 414 | // If there are no messages left for us, just continue in this loop 415 | Err(TryRecvError::Empty) => (), 416 | Err(TryRecvError::Disconnected) => return Ok(()), 417 | Ok(msg) => handle_notif!(msg) 418 | } 419 | } 420 | } 421 | 422 | // So now we've just *searched* all the pages but not necessarily rendered all of them. 423 | // So if there are any we have yet to render, we need to loop back to the beginning of 424 | // this loop to continue rendering all of them 425 | if rendered.iter().any(|r| !r.successful) && prerender == PrerenderLimit::All { 426 | continue; 427 | } 428 | 429 | // Then once we've rendered all these pages, wait until we get another notification 430 | // that this doc needs to be reloaded 431 | // This once returned None despite the main thing being still connected (I think, at 432 | // least), so I'm just being safe here 433 | let Ok(msg) = receiver.recv() else { 434 | return Ok(()); 435 | }; 436 | 437 | handle_notif!(msg); 438 | } 439 | } 440 | } 441 | 442 | struct RenderedContext { 443 | pixmap: Pixmap, 444 | surface_w: f32, 445 | surface_h: f32, 446 | result_rects: Vec 447 | } 448 | 449 | #[expect(clippy::too_many_arguments)] 450 | fn render_single_page_to_ctx( 451 | page: &Page, 452 | search_term: Option<&str>, 453 | prev_render: &PrevRender, 454 | invert: bool, 455 | black: i32, 456 | white: i32, 457 | fit_or_fill: FitOrFill, 458 | (area_w, area_h): (f32, f32) 459 | ) -> Result { 460 | let result_rects = match prev_render.num_search_found { 461 | None => search_page(page, search_term, 0)?, 462 | Some(0) => Vec::new(), 463 | Some(count @ 1..) => search_page(page, search_term, count)? 464 | }; 465 | 466 | // then, get the size of the page 467 | let bounds = page.bounds()?; 468 | let page_dim = (bounds.x1 - bounds.x0, bounds.y1 - bounds.y0); 469 | 470 | let scaled = scale_img_for_area(page_dim, (area_w, area_h), fit_or_fill); 471 | let ScaledResult { 472 | width: mut surface_w, 473 | height: mut surface_h, 474 | mut scale_factor 475 | } = scaled; 476 | 477 | if surface_w > KITTY_MAX_W_OR_H || surface_h > KITTY_MAX_W_OR_H { 478 | let descale = (surface_w / KITTY_MAX_W_OR_H).max(surface_h / KITTY_MAX_W_OR_H); 479 | surface_w /= descale; 480 | surface_h /= descale; 481 | scale_factor /= descale; 482 | } 483 | 484 | let colorspace = Colorspace::device_rgb(); 485 | let matrix = Matrix::new_scale(scale_factor, scale_factor); 486 | 487 | let mut pixmap = page.to_pixmap(&matrix, &colorspace, false, false)?; 488 | if invert { 489 | pixmap.tint(white, black)?; 490 | } else if black != MUPDF_BLACK || white != MUPDF_WHITE { 491 | pixmap.tint(black, white)?; 492 | } 493 | 494 | let (x_res, y_res) = pixmap.resolution(); 495 | let new_x = (x_res as f32 * scale_factor) as i32; 496 | let new_y = (y_res as f32 * scale_factor) as i32; 497 | pixmap.set_resolution(new_x, new_y); 498 | 499 | let result_rects = result_rects 500 | .into_iter() 501 | .map(|quad| { 502 | let ul_x = (quad.ul.x * scale_factor) as u32; 503 | let ul_y = (quad.ul.y * scale_factor) as u32; 504 | let lr_x = (quad.lr.x * scale_factor) as u32; 505 | let lr_y = (quad.lr.y * scale_factor) as u32; 506 | HighlightRect { 507 | ul_x, 508 | ul_y, 509 | lr_x, 510 | lr_y 511 | } 512 | }) 513 | .collect::>(); 514 | 515 | Ok(RenderedContext { 516 | pixmap, 517 | surface_w, 518 | surface_h, 519 | result_rects 520 | }) 521 | } 522 | 523 | #[derive(Clone, Debug)] 524 | pub struct HighlightRect { 525 | pub ul_x: u32, 526 | pub ul_y: u32, 527 | pub lr_x: u32, 528 | pub lr_y: u32 529 | } 530 | 531 | #[inline] 532 | fn search_page( 533 | page: &Page, 534 | search_term: Option<&str>, 535 | trusted_search_results: usize 536 | ) -> Result, mupdf::error::Error> { 537 | search_term 538 | .map(|term| { 539 | page.to_text_page(TextPageFlags::empty()).and_then(|page| { 540 | let mut v = Vec::with_capacity(trusted_search_results); 541 | page.search_cb(term, &mut v, |v, results| { 542 | v.extend(results.iter().cloned()); 543 | SearchHitResponse::ContinueSearch 544 | }) 545 | .map(|_| v) 546 | }) 547 | }) 548 | .transpose() 549 | .map(Option::unwrap_or_default) 550 | } 551 | 552 | #[inline] 553 | fn count_search_results(page: &Page, search_term: &str) -> Result { 554 | page.to_text_page(TextPageFlags::empty()).and_then(|page| { 555 | let mut count = 0; 556 | page.search_cb(search_term, &mut count, |count, results| { 557 | *count += results.len(); 558 | SearchHitResponse::ContinueSearch 559 | })?; 560 | Ok(count) 561 | }) 562 | } 563 | 564 | struct PopOnNext<'a> { 565 | inner: &'a mut VecDeque 566 | } 567 | 568 | impl Iterator for PopOnNext<'_> { 569 | type Item = usize; 570 | fn next(&mut self) -> Option { 571 | self.inner.pop_front() 572 | } 573 | } 574 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use core::{ 2 | error::Error, 3 | num::{NonZeroU32, NonZeroUsize} 4 | }; 5 | use std::{ 6 | borrow::Cow, 7 | ffi::OsString, 8 | io::{BufReader, Read as _, Stdout, Write as _, stdout}, 9 | mem, 10 | path::PathBuf, 11 | sync::{Arc, Mutex}, 12 | time::Duration 13 | }; 14 | 15 | use crossterm::{ 16 | event::EventStream, 17 | execute, 18 | terminal::{ 19 | EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, 20 | enable_raw_mode, window_size 21 | } 22 | }; 23 | use debounce::EventDebouncer; 24 | use flexi_logger::FileSpec; 25 | use flume::{Sender, r#async::RecvStream}; 26 | use futures_util::{FutureExt as _, stream::StreamExt as _}; 27 | use kittage::{ 28 | action::Action, 29 | delete::{ClearOrDelete, DeleteConfig, WhichToDelete}, 30 | error::{TerminalError, TransmitError} 31 | }; 32 | use notify::{Event, EventKind, RecursiveMode, Watcher as _}; 33 | use ratatui::{Terminal, backend::CrosstermBackend}; 34 | use ratatui_image::{ 35 | FontSize, 36 | picker::{Picker, ProtocolType} 37 | }; 38 | use tdf::{ 39 | PrerenderLimit, 40 | converter::{ConvertedPage, ConverterMsg, run_conversion_loop}, 41 | kitty::{KittyDisplay, display_kitty_images, do_shms_work, run_action}, 42 | renderer::{self, RenderError, RenderInfo, RenderNotif}, 43 | tui::{BottomMessage, InputAction, MessageSetting, Tui} 44 | }; 45 | 46 | // Dummy struct for easy errors in main 47 | struct WrappedErr(Cow<'static, str>); 48 | 49 | impl std::fmt::Display for WrappedErr { 50 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 51 | write!(f, "{}", self.0) 52 | } 53 | } 54 | 55 | impl std::fmt::Debug for WrappedErr { 56 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 57 | std::fmt::Display::fmt(self, f) 58 | } 59 | } 60 | 61 | impl std::error::Error for WrappedErr {} 62 | 63 | fn reset_term() { 64 | _ = disable_raw_mode(); 65 | _ = execute!( 66 | std::io::stdout(), 67 | LeaveAlternateScreen, 68 | crossterm::cursor::Show, 69 | crossterm::event::DisableMouseCapture 70 | ); 71 | } 72 | 73 | #[tokio::main] 74 | async fn main() -> Result<(), WrappedErr> { 75 | let result = inner_main().await; 76 | reset_term(); 77 | result 78 | } 79 | 80 | async fn inner_main() -> Result<(), WrappedErr> { 81 | let hook = std::panic::take_hook(); 82 | std::panic::set_hook(Box::new(move |info| { 83 | reset_term(); 84 | hook(info); 85 | })); 86 | 87 | #[cfg(feature = "tracing")] 88 | console_subscriber::init(); 89 | 90 | const DEFAULT_DEBOUNCE_DELAY: Duration = Duration::from_millis(50); 91 | 92 | let flags = xflags::parse_or_exit! { 93 | /// Display the pdf with the pages starting at the right hand size and moving left and 94 | /// adjust input keys to match 95 | optional -r,--r-to-l 96 | /// The maximum number of pages to display together, horizontally, at a time 97 | optional -m,--max-wide max_wide: NonZeroUsize 98 | /// Fullscreen the pdf (hide document name, page count, etc) 99 | optional -f,--fullscreen 100 | /// The time to wait for the file to stop changing before reloading, in milliseconds. 101 | /// Defaults to 50ms. 102 | optional --reload-delay reload_delay: u64 103 | /// The number of pages to prerender surrounding the currently-shown page; 0 means no 104 | /// limit. By default, there is no limit. 105 | optional -p,--prerender prerender: usize 106 | /// Custom white color, specified in css format (e.g. "FFFFFF" or "rgb(255, 255, 255)") 107 | optional -w,--white-color white: String 108 | /// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)") 109 | optional -b,--black-color black: String 110 | /// Print the version and exit 111 | optional --version 112 | /// PDF file to read 113 | optional file: PathBuf 114 | }; 115 | 116 | if flags.version { 117 | println!("{}", env!("CARGO_PKG_VERSION")); 118 | return Ok(()); 119 | } 120 | 121 | let Some(file) = flags.file else { 122 | return Err(WrappedErr( 123 | "Please specify the file to open, e.g. `tdf ./my_example_pdf.pdf`".into() 124 | )); 125 | }; 126 | 127 | let path = file 128 | .canonicalize() 129 | .map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?; 130 | 131 | let black = 132 | parse_color_to_i32(flags.black_color.as_deref().unwrap_or("000000")).map_err(|e| { 133 | WrappedErr( 134 | format!("Couldn't parse black color: {e} - is it formatted like a CSS color?") 135 | .into() 136 | ) 137 | })?; 138 | 139 | let white = 140 | parse_color_to_i32(flags.white_color.as_deref().unwrap_or("FFFFFF")).map_err(|e| { 141 | WrappedErr( 142 | format!("Couldn't parse white color: {e} - is it formatted like a CSS color?") 143 | .into() 144 | ) 145 | })?; 146 | 147 | // need to keep it around throughout the lifetime of the program, but don't rly need to use it. 148 | // Just need to make sure it doesn't get dropped yet. 149 | let maybe_logger = if std::env::var("RUST_LOG").is_ok() { 150 | Some( 151 | flexi_logger::Logger::try_with_env() 152 | .map_err(|e| WrappedErr(format!("Couldn't create initial logger: {e}").into()))? 153 | .log_to_file(FileSpec::try_from("./debug.log").map_err(|e| { 154 | WrappedErr(format!("Couldn't create FileSpec for logger: {e}").into()) 155 | })?) 156 | .start() 157 | .map_err(|e| WrappedErr(format!("Can't start logger: {e}").into()))? 158 | ) 159 | } else { 160 | None 161 | }; 162 | 163 | let (watch_to_render_tx, render_rx) = flume::unbounded(); 164 | let to_renderer = watch_to_render_tx.clone(); 165 | 166 | let (render_tx, tui_rx) = flume::unbounded(); 167 | let watch_to_tui_tx = render_tx.clone(); 168 | 169 | let mut watcher = notify::recommended_watcher(on_notify_ev( 170 | watch_to_tui_tx, 171 | watch_to_render_tx, 172 | path.file_name() 173 | .ok_or_else(|| WrappedErr("Path does not have a last component??".into()))? 174 | .to_owned(), 175 | flags 176 | .reload_delay 177 | .map_or(DEFAULT_DEBOUNCE_DELAY, Duration::from_millis) 178 | )) 179 | .map_err(|e| WrappedErr(format!("Couldn't start watching the provided file: {e}").into()))?; 180 | 181 | // So we have to watch the parent directory of the file that we are interested in because the 182 | // `notify` library works on inodes, and if the file is deleted, that inode is gone as well, 183 | // and then the notify library just gives up on trying to watch for the file reappearing. Imo 184 | // they should start watching the parent directory if the file is deleted, and then wait for it 185 | // to reappear and then begin watching it again, but whatever. It seems they've made their 186 | // opinion on this clear 187 | // (https://github.com/notify-rs/notify/issues/113#issuecomment-281836995) so whatever, guess 188 | // we have to do this annoying workaround. 189 | watcher 190 | .watch( 191 | path.parent().expect("The root directory is not a PDF"), 192 | RecursiveMode::NonRecursive 193 | ) 194 | .map_err(|e| WrappedErr(format!("Can't watch the provided file: {e}").into()))?; 195 | 196 | // TODO: Handle non-utf8 file names? Maybe by constructing a CString and passing that in to the 197 | // mupdf stuff instead of a rust string? 198 | let file_path = path.clone().into_os_string().to_string_lossy().to_string(); 199 | 200 | let mut window_size = window_size().map_err(|e| { 201 | WrappedErr(format!("Can't get your current terminal window size: {e}").into()) 202 | })?; 203 | 204 | if window_size.width == 0 || window_size.height == 0 { 205 | let (w, h) = get_font_size_through_stdio()?; 206 | 207 | window_size.width = w; 208 | window_size.height = h; 209 | } 210 | 211 | let cell_height_px = window_size.height / window_size.rows; 212 | let cell_width_px = window_size.width / window_size.columns; 213 | 214 | execute!( 215 | std::io::stdout(), 216 | EnterAlternateScreen, 217 | crossterm::cursor::Hide, 218 | crossterm::event::EnableMouseCapture 219 | ) 220 | .map_err(|e| { 221 | WrappedErr( 222 | format!( 223 | "Couldn't enter the alternate screen and hide the cursor for proper presentation: {e}" 224 | ) 225 | .into() 226 | ) 227 | })?; 228 | 229 | // We need to create `picker` on this thread because if we create it on the `renderer` thread, 230 | // it messes up something with user input. Input never makes it to the crossterm thing 231 | let picker = Picker::from_query_stdio() 232 | .or_else(|e| match e { 233 | ratatui_image::errors::Errors::NoFontSize if 234 | window_size.width != 0 235 | && window_size.height != 0 236 | && window_size.columns != 0 237 | && window_size.rows != 0 238 | => Ok(Picker::from_fontsize((cell_width_px, cell_height_px))), 239 | ratatui_image::errors::Errors::NoFontSize => Err(WrappedErr( 240 | "Unable to detect your terminal's font size; this is an issue with your terminal emulator.\nPlease use a different terminal emulator or report this bug to tdf.".into() 241 | )), 242 | e => Err(WrappedErr(format!("Couldn't get the necessary information to set up images: {e}").into())) 243 | })?; 244 | 245 | // then we want to spawn off the rendering task 246 | // We need to use the thread::spawn API so that this exists in a thread not owned by tokio, 247 | // since the methods we call in `start_rendering` will panic if called in an async context 248 | let prerender = flags 249 | .prerender 250 | .and_then(NonZeroUsize::new) 251 | .map_or(PrerenderLimit::All, PrerenderLimit::Limited); 252 | 253 | std::thread::spawn(move || { 254 | renderer::start_rendering( 255 | &file_path, 256 | render_tx, 257 | render_rx, 258 | cell_height_px, 259 | cell_width_px, 260 | prerender, 261 | black, 262 | white 263 | ) 264 | }); 265 | 266 | let font_size = picker.font_size(); 267 | 268 | let mut ev_stream = crossterm::event::EventStream::new(); 269 | 270 | let (to_converter, from_main) = flume::unbounded(); 271 | let (to_main, from_converter) = flume::unbounded(); 272 | 273 | let is_kitty = picker.protocol_type() == ProtocolType::Kitty; 274 | 275 | let shms_work = is_kitty && do_shms_work(&mut ev_stream).await; 276 | 277 | tokio::spawn(run_conversion_loop( 278 | to_main, from_main, picker, 20, shms_work 279 | )); 280 | 281 | let file_name = path.file_name().map_or_else( 282 | || "Unknown file".into(), 283 | |n| n.to_string_lossy().to_string() 284 | ); 285 | let tui = Tui::new(file_name, flags.max_wide, flags.r_to_l, is_kitty); 286 | 287 | let backend = CrosstermBackend::new(std::io::stdout()); 288 | let mut term = Terminal::new(backend).map_err(|e| { 289 | WrappedErr(format!("Couldn't set up crossterm's terminal backend: {e}").into()) 290 | })?; 291 | term.skip_diff(true); 292 | 293 | enable_raw_mode().map_err(|e| { 294 | WrappedErr( 295 | format!("Can't enable raw mode, which is necessary to receive input: {e}").into() 296 | ) 297 | })?; 298 | 299 | if is_kitty { 300 | run_action( 301 | Action::Delete(DeleteConfig { 302 | effect: ClearOrDelete::Delete, 303 | which: WhichToDelete::IdRange(NonZeroU32::new(1).unwrap()..=NonZeroU32::MAX) 304 | }), 305 | &mut ev_stream 306 | ) 307 | .await 308 | .map_err(|e| { 309 | WrappedErr(format!("Couldn't delete all previous images from memory: {e}").into()) 310 | })?; 311 | } 312 | 313 | let fullscreen = flags.fullscreen; 314 | let main_area = Tui::main_layout(&term.get_frame(), fullscreen); 315 | to_renderer 316 | .send(RenderNotif::Area(main_area.page_area)) 317 | .map_err(|e| { 318 | WrappedErr( 319 | format!("Couldn't inform the rendering thread of the available area: {e}").into() 320 | ) 321 | })?; 322 | 323 | let tui_rx = tui_rx.into_stream(); 324 | let from_converter = from_converter.into_stream(); 325 | 326 | enter_redraw_loop( 327 | ev_stream, 328 | to_renderer, 329 | tui_rx, 330 | to_converter, 331 | from_converter, 332 | fullscreen, 333 | tui, 334 | &mut term, 335 | main_area, 336 | font_size 337 | ) 338 | .await 339 | .map_err(|e| { 340 | WrappedErr( 341 | format!( 342 | "An unexpected error occurred while communicating between different parts of tdf: {e}" 343 | ) 344 | .into() 345 | ) 346 | })?; 347 | 348 | drop(maybe_logger); 349 | Ok(()) 350 | } 351 | 352 | // oh shut up clippy who cares 353 | #[expect(clippy::too_many_arguments)] 354 | async fn enter_redraw_loop( 355 | mut ev_stream: EventStream, 356 | to_renderer: Sender, 357 | mut tui_rx: RecvStream<'_, Result>, 358 | to_converter: Sender, 359 | mut from_converter: RecvStream<'_, Result>, 360 | mut fullscreen: bool, 361 | mut tui: Tui, 362 | term: &mut Terminal>, 363 | mut main_area: tdf::tui::RenderLayout, 364 | font_size: FontSize 365 | ) -> Result<(), Box> { 366 | loop { 367 | let mut needs_redraw = true; 368 | let next_ev = ev_stream.next().fuse(); 369 | tokio::select! { 370 | // First we check if we have any keystrokes 371 | Some(ev) = next_ev => { 372 | // If we can't get user input, just crash. 373 | let ev = ev.expect("Couldn't get any user input"); 374 | 375 | match tui.handle_event(&ev) { 376 | None => needs_redraw = false, 377 | Some(action) => match action { 378 | InputAction::Redraw => (), 379 | InputAction::QuitApp => return Ok(()), 380 | InputAction::JumpingToPage(page) => { 381 | to_renderer.send(RenderNotif::JumpToPage(page))?; 382 | to_converter.send(ConverterMsg::GoToPage(page))?; 383 | }, 384 | InputAction::Search(term) => to_renderer.send(RenderNotif::Search(term))?, 385 | InputAction::Invert => to_renderer.send(RenderNotif::Invert)?, 386 | InputAction::Fullscreen => fullscreen = !fullscreen, 387 | InputAction::SwitchRenderZoom(f_or_f) => { 388 | to_renderer.send(RenderNotif::SwitchFitOrFill(f_or_f)).unwrap(); 389 | } 390 | } 391 | } 392 | }, 393 | Some(renderer_msg) = tui_rx.next() => { 394 | match renderer_msg { 395 | Ok(render_info) => match render_info { 396 | RenderInfo::NumPages(num) => { 397 | tui.set_n_pages(num); 398 | to_converter.send(ConverterMsg::NumPages(num))?; 399 | }, 400 | RenderInfo::Page(info) => { 401 | tui.got_num_results_on_page(info.page_num, info.result_rects.len()); 402 | to_converter.send(ConverterMsg::AddImg(info))?; 403 | }, 404 | RenderInfo::Reloaded => tui.set_msg(MessageSetting::Some(BottomMessage::Reloaded)), 405 | RenderInfo::SearchResults { page_num, num_results } => 406 | tui.got_num_results_on_page(page_num, num_results), 407 | }, 408 | Err(e) => tui.show_error(e), 409 | } 410 | } 411 | Some(img_res) = from_converter.next() => { 412 | match img_res { 413 | Ok(ConvertedPage { page, num, num_results }) => { 414 | tui.page_ready(page, num, num_results); 415 | if num == tui.page { 416 | needs_redraw = true; 417 | } 418 | }, 419 | Err(e) => tui.show_error(e), 420 | } 421 | }, 422 | }; 423 | 424 | let new_area = Tui::main_layout(&term.get_frame(), fullscreen); 425 | if new_area != main_area { 426 | main_area = new_area; 427 | to_renderer.send(RenderNotif::Area(main_area.page_area))?; 428 | needs_redraw = true; 429 | } 430 | 431 | if needs_redraw { 432 | let mut to_display = KittyDisplay::NoChange; 433 | term.draw(|f| { 434 | to_display = tui.render(f, &main_area, font_size); 435 | })?; 436 | 437 | let maybe_err = display_kitty_images(to_display, &mut ev_stream).await; 438 | 439 | if let Err((to_replace, err_desc, enum_err)) = maybe_err { 440 | match enum_err { 441 | // This is the error that kitty & ghostty provide us when they delete an 442 | // image due to memory constraints, so if we get it, we just fix it by 443 | // re-rendering so it don't display it to the user 444 | // 445 | // [TODO] maybe when we detect that an image was deleted, we probe the 446 | // terminal for the pages around it to see if they were deleted too and if 447 | // they were, we re-render them? idk 448 | TransmitError::Terminal(TerminalError::NoEntity(_)) => (), 449 | _ => tui.set_msg(MessageSetting::Some(BottomMessage::Error(format!( 450 | "{err_desc}: {enum_err}" 451 | )))) 452 | } 453 | 454 | for page_num in to_replace { 455 | tui.page_failed_display(page_num); 456 | // So that they get re-rendered and sent over again 457 | to_renderer.send(RenderNotif::PageNeedsReRender(page_num))?; 458 | } 459 | } 460 | 461 | execute!(stdout().lock(), EndSynchronizedUpdate)?; 462 | } 463 | } 464 | } 465 | 466 | fn on_notify_ev( 467 | to_tui_tx: flume::Sender>, 468 | to_render_tx: flume::Sender, 469 | file_name: OsString, 470 | debounce_delay: Duration 471 | ) -> impl Fn(notify::Result) { 472 | let last_event: Mutex> = Mutex::new(Ok(())); 473 | let last_event = Arc::new(last_event); 474 | 475 | let debouncer = EventDebouncer::new(debounce_delay, { 476 | let last_event = last_event.clone(); 477 | move |()| { 478 | let event = mem::replace(&mut *last_event.lock().unwrap(), Ok(())); 479 | match event { 480 | // This shouldn't fail to send unless the receiver gets disconnected. If that's 481 | // happened, then like the main thread has panicked or something, so it doesn't matter 482 | // we don't handle the error here. 483 | Ok(()) => to_render_tx.send(RenderNotif::Reload).unwrap(), 484 | // If we get an error here, and then an error sending, everything's going wrong. Just give 485 | // up lol. 486 | Err(e) => to_tui_tx.send(Err(e)).unwrap() 487 | } 488 | } 489 | }); 490 | 491 | move |res| { 492 | let event = match res { 493 | Err(e) => Err(RenderError::Notify(e)), 494 | 495 | // TODO: Should we match EventKind::Rename and propogate that so that the other parts of the 496 | // process know that too? Or should that be 497 | Ok(ev) => { 498 | // We only watch the parent directory (see the comment above `watcher.watch` in `fn 499 | // main`) so we need to filter out events to only ones that pertain to the single file 500 | // we care about 501 | if !ev 502 | .paths 503 | .iter() 504 | .any(|path| path.file_name().is_some_and(|f| f == file_name)) 505 | { 506 | return; 507 | } 508 | 509 | match ev.kind { 510 | EventKind::Access(_) => return, 511 | EventKind::Remove(_) => Err(RenderError::Converting("File was deleted".into())), 512 | EventKind::Other 513 | | EventKind::Any 514 | | EventKind::Create(_) 515 | | EventKind::Modify(_) => Ok(()) 516 | } 517 | } 518 | }; 519 | *last_event.lock().unwrap() = event; 520 | debouncer.put(()); 521 | } 522 | } 523 | 524 | fn parse_color_to_i32(cs: &str) -> Result { 525 | let color = csscolorparser::parse(cs)?; 526 | let [r, g, b, _] = color.to_rgba8(); 527 | Ok(i32::from_be_bytes([0, r, g, b])) 528 | } 529 | 530 | fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> { 531 | // send the command code to get the terminal window size 532 | print!("\x1b[14t"); 533 | std::io::stdout().flush().unwrap(); 534 | 535 | // we need to enable raw mode here since this bit of output won't print a newline; it'll 536 | // just print the info it wants to tell us. So we want to get all characters as they come 537 | enable_raw_mode().map_err(|e| { 538 | WrappedErr( 539 | format!("Can't enable raw mode, which is necessary to receive input: {e}").into() 540 | ) 541 | })?; 542 | 543 | // read in the returned size until we hit a 't' (which indicates to us it's done) 544 | let input_vec = BufReader::new(std::io::stdin()) 545 | .bytes() 546 | .filter_map(Result::ok) 547 | .take_while(|b| *b != b't') 548 | .collect::>(); 549 | 550 | // and then disable raw mode again in case we return an error in this next section 551 | disable_raw_mode().map_err(|e| { 552 | WrappedErr(format!("Can't put the terminal back into a normal input state: {e}").into()) 553 | })?; 554 | 555 | let input_line = String::from_utf8(input_vec).map_err(|e| { 556 | WrappedErr( 557 | format!( 558 | "The terminal responded to our request for its font size by providing non-utf8 data: {e}" 559 | ) 560 | .into() 561 | ) 562 | })?; 563 | let input_line = input_line 564 | .trim_start_matches("\x1b[4") 565 | .trim_start_matches(';'); 566 | 567 | // it should input it to us as `\e[4;;t`, so we need to split to get the h/w 568 | // ignore the first val 569 | let mut splits = input_line.split([';', 't']); 570 | 571 | let (Some(h), Some(w)) = (splits.next(), splits.next()) else { 572 | return Err(WrappedErr( 573 | format!("Terminal responded with unparseable size response '{input_line}'").into() 574 | )); 575 | }; 576 | 577 | let h = h.parse::().map_err(|e| { 578 | WrappedErr( 579 | format!( 580 | "Your terminal said its height is {h}, but that is not a 16-bit unsigned integer: {e}" 581 | ) 582 | .into() 583 | ) 584 | })?; 585 | let w = w.parse::().map_err(|e| { 586 | WrappedErr( 587 | format!( 588 | "Your terminal said its width is {w}, but that is not a 16-bit unsigned integer: {e}" 589 | ) 590 | .into() 591 | ) 592 | })?; 593 | 594 | Ok((w, h)) 595 | } 596 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /src/tui.rs: -------------------------------------------------------------------------------- 1 | use std::{borrow::Cow, io::stdout, num::NonZeroUsize}; 2 | 3 | use crossterm::{ 4 | event::{Event, KeyCode, KeyModifiers, MouseEventKind}, 5 | execute, 6 | terminal::{ 7 | BeginSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, 8 | enable_raw_mode 9 | } 10 | }; 11 | use kittage::display::DisplayLocation; 12 | use nix::{ 13 | sys::signal::{Signal::SIGSTOP, kill}, 14 | unistd::Pid 15 | }; 16 | use ratatui::{ 17 | Frame, 18 | layout::{Constraint, Flex, Layout, Position, Rect}, 19 | prelude::{Line, Text}, 20 | style::{Color, Style}, 21 | symbols::border, 22 | text::Span, 23 | widgets::{Block, Borders, Clear, Padding, Paragraph, Wrap} 24 | }; 25 | use ratatui_image::{FontSize, Image}; 26 | 27 | use crate::{ 28 | FitOrFill, 29 | converter::{ConvertedImage, MaybeTransferred}, 30 | kitty::{KittyDisplay, KittyReadyToDisplay}, 31 | renderer::{RenderError, fill_default}, 32 | skip::Skip 33 | }; 34 | 35 | pub struct Tui { 36 | name: String, 37 | pub page: usize, 38 | last_render: LastRender, 39 | bottom_msg: BottomMessage, 40 | // we use `prev_msg` to, for example, restore the 'search results' message on the bottom after 41 | // jumping to a specific page 42 | prev_msg: Option, 43 | rendered: Vec, 44 | page_constraints: PageConstraints, 45 | showing_help_msg: bool, 46 | is_kitty: bool, 47 | zoom: Option 48 | } 49 | 50 | #[derive(Default)] 51 | struct LastRender { 52 | // Used as a way to track if we need to draw the images, to save ratatui from doing a lot of 53 | // diffing work 54 | rect: Rect, 55 | pages_shown: usize, 56 | unused_width: u16 57 | } 58 | 59 | #[derive(Default)] 60 | pub enum BottomMessage { 61 | #[default] 62 | Help, 63 | SearchResults(String), 64 | Error(String), 65 | Input(InputCommand), 66 | Reloaded 67 | } 68 | 69 | pub enum InputCommand { 70 | GoToPage(usize), 71 | Search(String) 72 | } 73 | 74 | struct PageConstraints { 75 | max_wide: Option, 76 | r_to_l: bool 77 | } 78 | 79 | #[derive(Default, Debug)] 80 | struct Zoom { 81 | // just how much 'zoom' you have. 0 means it fills the screen (instead of fits), such 82 | // that one axis is fully on-screen 83 | level: i16, 84 | // how many terminal-cells worth of content overflow the left side of the screen (and are thus 85 | // not displayed) 86 | cell_pan_from_left: u16, 87 | // how many terminal-cells worth of content overflow the top side of the screen (and are thus 88 | // not displayed) 89 | cell_pan_from_top: u16 90 | } 91 | impl Zoom { 92 | /// Returns the zoom factor, where 1 is the default and means fill-screen 93 | fn factor(&self) -> f32 { 94 | // TODO: Make these configurable once we have a good way to set options after startup 95 | const ZOOM_RATE: f32 = 1.1; 96 | const ZOOM_RATE_GRANULAR: f32 = 1.05; 97 | 98 | if self.level > 0 { 99 | ZOOM_RATE.powi(self.level.into()) 100 | } else { 101 | // use a more granular zoom rate for the steps between fit-screen and fill-screen 102 | ZOOM_RATE_GRANULAR.powi(self.level.into()) 103 | } 104 | } 105 | 106 | fn step_in(&mut self) { 107 | self.level = self.level.saturating_add(1); 108 | } 109 | fn step_out(&mut self) { 110 | self.level = self.level.saturating_sub(1); 111 | } 112 | 113 | // TODO: Make this configurable, maybe allow fractional steps? 114 | // With fractional steps, it might also be a good idea to have these 115 | // have the same ratio as the font aspect ratio. 116 | const PAN_STEP_X: i16 = 2; 117 | const PAN_STEP_Y: i16 = 1; 118 | 119 | fn pan(&mut self, direction: Direction) { 120 | let (target, sign) = match direction { 121 | Direction::Up => (&mut self.cell_pan_from_top, -1), 122 | Direction::Down => (&mut self.cell_pan_from_top, 1), 123 | Direction::Left => (&mut self.cell_pan_from_left, -1), 124 | Direction::Right => (&mut self.cell_pan_from_left, 1) 125 | }; 126 | let step = if direction.is_vertical() { 127 | Self::PAN_STEP_Y 128 | } else { 129 | Self::PAN_STEP_X 130 | }; 131 | *target = target.saturating_add_signed(sign * step); 132 | } 133 | fn pan_bottom(&mut self) { 134 | self.cell_pan_from_top = 0; 135 | } 136 | fn pan_top(&mut self) { 137 | self.cell_pan_from_top = u16::MAX; 138 | } 139 | } 140 | #[derive(Clone, Copy, Debug)] 141 | enum Direction { 142 | Up, 143 | Down, 144 | Left, 145 | Right 146 | } 147 | impl Direction { 148 | /// Flips the directions for vertical and horizonal panning. 149 | fn flip_mouse_xy(self) -> Self { 150 | match self { 151 | Self::Up => Self::Left, 152 | Self::Left => Self::Up, 153 | Self::Down => Self::Right, 154 | Self::Right => Self::Down 155 | } 156 | } 157 | fn is_vertical(self) -> bool { 158 | match self { 159 | Self::Up | Self::Down => true, 160 | Self::Left | Self::Right => false 161 | } 162 | } 163 | } 164 | 165 | // This seems like a kinda weird struct because it holds two optionals but any representation 166 | // within it is valid; I think it's the best way to represent it 167 | #[derive(Default)] 168 | pub struct RenderedInfo { 169 | // The image, if it has been rendered by `Converter` to that struct 170 | img: Option, 171 | // The number of results for the current search term that have been found on this page. None if 172 | // we haven't checked this page yet 173 | // Also this isn't the most efficient representation of this value, but it's accurate, so like 174 | // whatever I guess 175 | num_results: Option 176 | } 177 | 178 | #[derive(PartialEq)] 179 | pub struct RenderLayout { 180 | pub page_area: Rect, 181 | pub top_and_bottom: Option<(Rect, Rect)> 182 | } 183 | 184 | impl Tui { 185 | #[must_use] 186 | pub fn new(name: String, max_wide: Option, r_to_l: bool, is_kitty: bool) -> Self { 187 | Self { 188 | name, 189 | page: 0, 190 | prev_msg: None, 191 | bottom_msg: BottomMessage::Help, 192 | last_render: LastRender::default(), 193 | rendered: vec![], 194 | page_constraints: PageConstraints { max_wide, r_to_l }, 195 | showing_help_msg: false, 196 | is_kitty, 197 | zoom: None 198 | } 199 | } 200 | 201 | #[must_use] 202 | pub fn main_layout(frame: &Frame<'_>, fullscreened: bool) -> RenderLayout { 203 | if fullscreened { 204 | RenderLayout { 205 | page_area: frame.area(), 206 | top_and_bottom: None 207 | } 208 | } else { 209 | let layout = Layout::default() 210 | .constraints([ 211 | Constraint::Length(3), 212 | Constraint::Fill(1), 213 | Constraint::Length(3) 214 | ]) 215 | .horizontal_margin(2) 216 | .vertical_margin(1) 217 | .split(frame.area()); 218 | 219 | RenderLayout { 220 | page_area: layout[1], 221 | top_and_bottom: Some((layout[0], layout[2])) 222 | } 223 | } 224 | } 225 | 226 | fn render_zoomed<'s>( 227 | // area of the 'fit-screen' page 228 | mut img_area: Rect, 229 | font_size: FontSize, 230 | zoom: &mut Zoom, 231 | img: &'s mut MaybeTransferred, 232 | page_num: usize, 233 | img_cell_w: u16, 234 | img_cell_h: u16 235 | ) -> KittyDisplay<'s> { 236 | log::debug!("zoom is {zoom:#?}"); 237 | log::debug!("page area is {img_area:#?}"); 238 | log::debug!("img dimensions are {img_cell_w}x{img_cell_h}"); 239 | 240 | // Dimensions of the section of the image to be displayed. 241 | // Kittage calls this the "image area to display". 242 | // We need to shrink this or the page area in order to zoom in or out, 243 | // respectively. 244 | let mut img_section_w = f32::from(img_cell_w); 245 | let mut img_section_h = f32::from(img_cell_h); 246 | 247 | let zoom_factor = zoom.factor(); 248 | 249 | if zoom_factor >= 1.0 { 250 | // Use a smaller section of the image. This efficively zooms into that section. 251 | img_section_w /= zoom_factor; 252 | img_section_h /= zoom_factor; 253 | } else { 254 | // Shrink the page area, such that the fill-screen conversion 255 | // will zoom out of the image. 256 | let initial_page_w = f32::from(img_area.width); 257 | let initial_page_h = f32::from(img_area.height); 258 | 259 | // how many pages the image is wide/high 260 | let img_page_w_ratio = img_section_w / initial_page_w; 261 | let img_page_h_ratio = img_section_h / initial_page_h; 262 | 263 | let shrink_move_page = |dim: &mut u16, pos: &mut u16, axis_zoom_factor: f32| { 264 | let old_dim = *dim; 265 | // The axis zoom factor tells us what portion of the axis 266 | // we need to show. 267 | *dim = (f32::from(*dim) * axis_zoom_factor) as u16; 268 | 269 | *pos += old_dim 270 | .checked_sub(*dim) 271 | .expect("zooming out should shrink the image") 272 | / 2; 273 | }; 274 | 275 | // TODO: Detect max zoom-out in zoom levels 276 | if img_page_w_ratio < img_page_h_ratio { 277 | // vertical scroll / tall image. zooming out means decreasing the width of the page area 278 | shrink_move_page( 279 | &mut img_area.width, 280 | &mut img_area.x, 281 | // disallow zooming out past fit-screen 282 | zoom_factor.max(1.0 / img_page_h_ratio) 283 | ); 284 | } else { 285 | // horizontal scroll / wide image. zooming out means decreasing the width of the page area 286 | shrink_move_page( 287 | &mut img_area.height, 288 | &mut img_area.y, 289 | // disallow zooming out past fit-screen 290 | zoom_factor.max(1.0 / img_page_w_ratio) 291 | ); 292 | } 293 | } 294 | log::debug!("after adjustment, page area is {img_area:#?}"); 295 | 296 | // Crop the image such that in the end, the aspect ratio of the section 297 | // is the same as that of the page area. This effectively performs the 298 | // conversion to fill-screen. 299 | // Note that this only works because cell_w, cell_h is in fit-screen 300 | // format, i.e. the cell size and the page area already share at 301 | // least one dimension. 302 | { 303 | let page_area_w = f32::from(img_area.width); 304 | let page_area_h = f32::from(img_area.height); 305 | 306 | // how many pages the image is wide/high 307 | // Note that this is not the same as during the 308 | // zoom-out calculation, since it changed the page 309 | // dimensions. 310 | let img_page_w_ratio = img_section_w / page_area_w; 311 | let img_page_h_ratio = img_section_h / page_area_h; 312 | 313 | if img_page_w_ratio < img_page_h_ratio { 314 | img_section_h = page_area_h * img_page_w_ratio; 315 | } else { 316 | img_section_w = page_area_w * img_page_h_ratio; 317 | } 318 | } 319 | 320 | let width = (img_section_w * f32::from(font_size.0)) as u32; 321 | let height = (img_section_h * f32::from(font_size.1)) as u32; 322 | 323 | zoom.cell_pan_from_left = zoom 324 | .cell_pan_from_left 325 | .min(img_cell_w.saturating_sub(img_section_w.ceil() as u16)); 326 | zoom.cell_pan_from_top = zoom 327 | .cell_pan_from_top 328 | .min(img_cell_h.saturating_sub(img_section_h.ceil() as u16)); 329 | 330 | KittyDisplay::DisplayImages(vec![KittyReadyToDisplay { 331 | img, 332 | page_num, 333 | pos: Position { 334 | x: img_area.x, 335 | y: img_area.y 336 | }, 337 | display_loc: DisplayLocation { 338 | x: u32::from(zoom.cell_pan_from_left) * u32::from(font_size.0), 339 | y: u32::from(zoom.cell_pan_from_top) * u32::from(font_size.1), 340 | width, 341 | height, 342 | columns: img_area.width, 343 | rows: img_area.height, 344 | ..DisplayLocation::default() 345 | } 346 | }]) 347 | } 348 | 349 | // TODO: Make a way to fill the width of the screen with one page and scroll down to view it 350 | #[must_use] 351 | pub fn render<'s>( 352 | &'s mut self, 353 | frame: &mut Frame<'_>, 354 | full_layout: &RenderLayout, 355 | font_size: FontSize 356 | ) -> KittyDisplay<'s> { 357 | if self.showing_help_msg { 358 | self.render_help_msg(frame); 359 | return KittyDisplay::ClearImages; 360 | } 361 | 362 | if let Some(t_and_b) = full_layout.top_and_bottom { 363 | Self::render_top_and_bottom( 364 | t_and_b, 365 | self.page, 366 | &self.rendered, 367 | &self.name, 368 | frame, 369 | &self.bottom_msg 370 | ); 371 | } 372 | 373 | let mut img_area = full_layout.page_area; 374 | 375 | let size = frame.area(); 376 | if size == self.last_render.rect { 377 | // If we haven't resized (and haven't used the Rect as a way to mark that we need to 378 | // resize this time), then go through every element in the buffer where any Image would 379 | // be written and set to skip it so that ratatui doesn't spend a lot of time diffing it 380 | // each re-render 381 | frame.render_widget(Skip::new(true), img_area); 382 | return KittyDisplay::NoChange; 383 | } 384 | 385 | if let Some(ref mut zoom) = self.zoom { 386 | // yes this is ugly and I hate it. it's due to the limitations that currently exist 387 | // in the borrow checker. Once `-Zpolonius=next` is stabilized, we can rework this 388 | // to look like what we expect. 389 | // See https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions 390 | // You can also rewrite this to just if an `if let` and run it under 391 | // `RUSTFLAGS="-Zpolonius=next"` and see that it works 392 | if self.rendered[self.page] 393 | .img 394 | .as_ref() 395 | .is_some_and(|c| matches!(c, ConvertedImage::Kitty { .. })) 396 | { 397 | let Some(ConvertedImage::Kitty { 398 | ref mut img, 399 | cell_w, 400 | cell_h 401 | }) = self.rendered[self.page].img 402 | else { 403 | unreachable!() 404 | }; 405 | 406 | self.last_render = LastRender { 407 | rect: size, 408 | pages_shown: 1, 409 | unused_width: 0 410 | }; 411 | return Self::render_zoomed( 412 | img_area, font_size, zoom, img, self.page, cell_w, cell_h 413 | ); 414 | } 415 | } 416 | 417 | // here we calculate how many pages can fit in the available area. 418 | let mut test_area_w = img_area.width; 419 | // go through our pages, starting at the first one we want to view 420 | let mut page_sizes = self.rendered[self.page..] 421 | .iter_mut() 422 | // and get this to represent a count of how many we're looking at so far to render 423 | .enumerate() 424 | // and only take as many as are ready to be rendered 425 | .take_while(|(idx, page)| { 426 | let mut take = page.img.is_some(); 427 | if let Some(max) = self.page_constraints.max_wide { 428 | take &= *idx < max.get(); 429 | } 430 | take 431 | }) 432 | // and map it to their width (in cells on the terminal, not pixels) 433 | .filter_map(|(_, page)| { 434 | page.img.as_mut().map(|img| { 435 | let (w, h) = img.w_h(); 436 | (w, h, img) 437 | }) 438 | }) 439 | // and then take them as long as they won't overflow the available area. 440 | .take_while(|(width, _, _)| match test_area_w.checked_sub(*width) { 441 | Some(new_val) => { 442 | test_area_w = new_val; 443 | true 444 | } 445 | None => false 446 | }) 447 | .collect::>(); 448 | 449 | if self.page_constraints.r_to_l { 450 | page_sizes.reverse(); 451 | } 452 | 453 | if page_sizes.is_empty() { 454 | // If none are ready to render, just show the loading thing 455 | Self::render_loading_in(frame, img_area); 456 | KittyDisplay::ClearImages 457 | } else { 458 | execute!(stdout(), BeginSynchronizedUpdate).unwrap(); 459 | 460 | let total_width = page_sizes.iter().map(|(w, _, _)| w).sum::(); 461 | 462 | self.last_render.pages_shown = page_sizes.len(); 463 | 464 | let unused_width = img_area.width - total_width; 465 | self.last_render.unused_width = unused_width; 466 | img_area.x += unused_width / 2; 467 | 468 | if let Some(total_height) = page_sizes.iter().map(|(_, h, _)| h).max() { 469 | // This subtraction might sporadicly fail while shrinking the window. 470 | if let Some(unused_height) = img_area.height.checked_sub(*total_height) { 471 | img_area.y += unused_height / 2; 472 | } 473 | } 474 | 475 | let to_display = page_sizes 476 | .into_iter() 477 | .enumerate() 478 | .filter_map(|(idx, (width, _, img))| { 479 | let maybe_img = 480 | Self::render_single_page(frame, img, Rect { width, ..img_area }); 481 | img_area.x += width; 482 | maybe_img.map(|(img, pos)| KittyReadyToDisplay { 483 | img, 484 | page_num: idx + self.page, 485 | pos, 486 | display_loc: DisplayLocation::default() 487 | }) 488 | }) 489 | .collect::>(); 490 | 491 | // we want to set this at the very end so it doesn't get set somewhere halfway through and 492 | // then the whole diffing thing messes it up 493 | self.last_render.rect = size; 494 | 495 | KittyDisplay::DisplayImages(to_display) 496 | } 497 | } 498 | 499 | fn render_single_page<'img>( 500 | frame: &mut Frame<'_>, 501 | page_img: &'img mut ConvertedImage, 502 | img_area: Rect 503 | ) -> Option<(&'img mut MaybeTransferred, Position)> { 504 | match page_img { 505 | ConvertedImage::Generic(page_img) => { 506 | frame.render_widget(Image::new(page_img), img_area); 507 | None 508 | } 509 | ConvertedImage::Kitty { 510 | img, 511 | cell_h: _, 512 | cell_w: _ 513 | } => Some((img, Position { 514 | x: img_area.x, 515 | y: img_area.y 516 | })) 517 | } 518 | } 519 | 520 | fn render_loading_in(frame: &mut Frame<'_>, area: Rect) { 521 | const LOADING_STR: &str = "Loading..."; 522 | let inner_space = 523 | Layout::horizontal([Constraint::Length(const { LOADING_STR.len() as u16 })]) 524 | .flex(Flex::Center) 525 | .split(area); 526 | 527 | let loading_span = Span::styled(LOADING_STR, Style::new().fg(Color::Cyan)); 528 | 529 | frame.render_widget(loading_span, inner_space[0]); 530 | } 531 | 532 | fn change_page(&mut self, mut change: PageChange, amt: ChangeAmount) -> Option { 533 | let diff = match amt { 534 | ChangeAmount::Single => 1, 535 | ChangeAmount::WholeScreen => self.last_render.pages_shown 536 | }; 537 | 538 | // This is a kinda weird way to switch around the controls for this sort of thing but it 539 | // allows it to be pretty centralized and avoids annoyingly duplicated match arms (since 540 | // we'd have to do `match key { 'h' if r_to_l | 'l' => {}}` and that doesn't play well with 541 | // `if` guards on match arms) 542 | if self.page_constraints.r_to_l { 543 | change = match change { 544 | PageChange::Next => PageChange::Prev, 545 | PageChange::Prev => PageChange::Next 546 | }; 547 | } 548 | 549 | let old = self.page; 550 | match change { 551 | PageChange::Next => 552 | self.set_page((self.page + diff).min(self.rendered.len().saturating_sub(1))), 553 | PageChange::Prev => self.set_page(self.page.saturating_sub(diff)) 554 | } 555 | 556 | // Yes these conversions could wrap around if you have > isize::MAX pages, but we already 557 | // decided that you deserve to suffer if you have more than u32::MAX pages, so that's fine. 558 | match self.page as isize - old as isize { 559 | 0 => None, 560 | _ => Some(InputAction::JumpingToPage(self.page)) 561 | } 562 | } 563 | 564 | pub fn set_n_pages(&mut self, n_pages: usize) { 565 | fill_default(&mut self.rendered, n_pages); 566 | self.page = self.page.min(n_pages - 1); 567 | } 568 | 569 | pub fn page_ready(&mut self, img: ConvertedImage, page_num: usize, num_results: usize) { 570 | // If this new image woulda fit within the available space on the last render AND it's 571 | // within the range where it might've been rendered with the last shown pages, then reset 572 | // the last rect marker so that all images are forced to redraw on next render and this one 573 | // is drawn with them 574 | if page_num >= self.page && page_num <= self.page + self.last_render.pages_shown { 575 | self.last_render.rect = Rect::default(); 576 | } else { 577 | let img_w = img.w_h().0; 578 | if img_w <= self.last_render.unused_width { 579 | let num_fit = self.last_render.unused_width / img_w; 580 | if page_num >= self.page && (self.page + num_fit as usize) >= page_num { 581 | self.last_render.rect = Rect::default(); 582 | } 583 | } 584 | } 585 | 586 | // We always just set this here because we handle reloading in the `set_n_pages` function. 587 | // If the document was reloaded, then It'll have the `set_n_pages` called to set the new 588 | // number of pages, so the vec will already be cleared 589 | self.rendered[page_num] = RenderedInfo { 590 | img: Some(img), 591 | num_results: Some(num_results) 592 | }; 593 | } 594 | 595 | pub fn page_failed_display(&mut self, page_num: usize) { 596 | self.rendered[page_num].img = None; 597 | } 598 | 599 | pub fn got_num_results_on_page(&mut self, page_num: usize, num_results: usize) { 600 | self.rendered[page_num].num_results = Some(num_results); 601 | } 602 | 603 | pub fn render_top_and_bottom( 604 | (top_area, bottom_area): (Rect, Rect), 605 | page_num: usize, 606 | rendered: &[RenderedInfo], 607 | doc_name: &str, 608 | frame: &mut Frame<'_>, 609 | bottom_msg: &BottomMessage 610 | ) { 611 | // use the extra space here to add some padding to the right side 612 | let page_nums_text = format!("{} / {} ", page_num + 1, rendered.len()); 613 | 614 | let top_block = Block::new() 615 | // use this first title to add a bit of padding to the left side 616 | .title_top(" ") 617 | .title_top(Span::styled(doc_name, Style::new().fg(Color::Cyan))) 618 | .title_top( 619 | Span::styled(&page_nums_text, Style::new().fg(Color::Cyan)) 620 | .into_right_aligned_line() 621 | ) 622 | .padding(Padding { 623 | bottom: 1, 624 | ..Padding::default() 625 | }) 626 | .borders(Borders::BOTTOM); 627 | 628 | frame.render_widget(top_block, top_area); 629 | 630 | let bottom_block = Block::new() 631 | .padding(Padding { 632 | top: 1, 633 | right: 2, 634 | left: 2, 635 | bottom: 0 636 | }) 637 | .borders(Borders::TOP); 638 | let bottom_inside_block = bottom_block.inner(bottom_area); 639 | 640 | frame.render_widget(bottom_block, bottom_area); 641 | 642 | let rendered_str = if !rendered.is_empty() { 643 | format!( 644 | "Rendered: {}%", 645 | (rendered.iter().filter(|i| i.img.is_some()).count() * 100) / rendered.len() 646 | ) 647 | } else { 648 | String::new() 649 | }; 650 | let bottom_layout = Layout::horizontal([ 651 | Constraint::Fill(1), 652 | Constraint::Length(rendered_str.len() as u16) 653 | ]) 654 | .split(bottom_inside_block); 655 | 656 | let rendered_span = Span::styled(&rendered_str, Style::new().fg(Color::Cyan)); 657 | frame.render_widget(rendered_span, bottom_layout[1]); 658 | 659 | let (msg_str, color): (Cow<'_, str>, _) = match bottom_msg { 660 | BottomMessage::Help => ("?: Show help page".into(), Color::Blue), 661 | BottomMessage::Error(e) => (e.as_str().into(), Color::Red), 662 | BottomMessage::Input(input_state) => ( 663 | match input_state { 664 | InputCommand::GoToPage(page) => format!("Go to: {page}"), 665 | InputCommand::Search(s) => format!("Search: {s}") 666 | } 667 | .into(), 668 | Color::Blue 669 | ), 670 | BottomMessage::SearchResults(term) => { 671 | let num_found = rendered.iter().filter_map(|r| r.num_results).sum::(); 672 | let num_searched = 673 | rendered.iter().filter(|r| r.num_results.is_some()).count() * 100; 674 | ( 675 | format!( 676 | "Results for '{term}': {num_found} (searched: {}%)", 677 | num_searched / rendered.len() 678 | ) 679 | .into(), 680 | Color::Blue 681 | ) 682 | } 683 | BottomMessage::Reloaded => ("Document was reloaded!".into(), Color::Blue) 684 | }; 685 | 686 | let span = Span::styled(msg_str, Style::new().fg(color)); 687 | frame.render_widget(span, bottom_layout[0]); 688 | } 689 | 690 | pub fn handle_event(&mut self, ev: &Event) -> Option { 691 | fn jump_to_page(page: &mut usize, rect: &mut Rect, new_page: usize) -> InputAction { 692 | *page = new_page; 693 | // Make sure we re-render 694 | *rect = Rect::default(); 695 | InputAction::JumpingToPage(new_page) 696 | } 697 | 698 | let can_zoom = self.is_kitty && self.zoom.is_some(); 699 | 700 | match ev { 701 | Event::Key(key) => { 702 | match key.code { 703 | KeyCode::Char(c) => { 704 | // TODO: refactor back to `if let` arm guards when those are stabilized 705 | if let BottomMessage::Input(InputCommand::Search(ref mut term)) = 706 | self.bottom_msg 707 | { 708 | term.push(c); 709 | return Some(InputAction::Redraw); 710 | } 711 | 712 | if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) = 713 | self.bottom_msg 714 | { 715 | if c == 'g' && self.is_kitty { 716 | self.update_zoom(Zoom::pan_bottom); 717 | self.set_msg(MessageSetting::Pop); 718 | return Some(InputAction::Redraw); 719 | } 720 | 721 | return c.to_digit(10).map(|input_num| { 722 | *page = (*page * 10) + input_num as usize; 723 | InputAction::Redraw 724 | }); 725 | } 726 | 727 | match c { 728 | 'l' => self.change_page(PageChange::Next, ChangeAmount::Single), 729 | 'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen), 730 | 'h' => self.change_page(PageChange::Prev, ChangeAmount::Single), 731 | 'k' => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), 732 | 'q' => Some(InputAction::QuitApp), 733 | 'g' => { 734 | self.set_msg(MessageSetting::Some(BottomMessage::Input( 735 | InputCommand::GoToPage(0) 736 | ))); 737 | Some(InputAction::Redraw) 738 | } 739 | '/' => { 740 | self.set_msg(MessageSetting::Some(BottomMessage::Input( 741 | InputCommand::Search(String::new()) 742 | ))); 743 | Some(InputAction::Redraw) 744 | } 745 | 'i' => Some(InputAction::Invert), 746 | '?' => { 747 | self.showing_help_msg = true; 748 | Some(InputAction::Redraw) 749 | } 750 | 'f' => Some(InputAction::Fullscreen), 751 | 'n' if self.page < self.rendered.len() - 1 => { 752 | // TODO: If we can't find one, then maybe like block until we've verified 753 | // all the pages have been checked? 754 | self.rendered[(self.page + 1)..] 755 | .iter() 756 | .enumerate() 757 | .find_map(|(idx, p)| { 758 | p.num_results 759 | .is_some_and(|num| num > 0) 760 | .then_some(self.page + 1 + idx) 761 | }) 762 | .map(|next_page| { 763 | jump_to_page( 764 | &mut self.page, 765 | &mut self.last_render.rect, 766 | next_page 767 | ) 768 | }) 769 | } 770 | 'N' if self.page > 0 => self.rendered[..(self.page)] 771 | .iter() 772 | .rev() 773 | .enumerate() 774 | .find_map(|(idx, p)| { 775 | p.num_results 776 | .is_some_and(|num| num > 0) 777 | .then_some(self.page - (idx + 1)) 778 | }) 779 | .map(|prev_page| { 780 | jump_to_page( 781 | &mut self.page, 782 | &mut self.last_render.rect, 783 | prev_page 784 | ) 785 | }), 786 | 'z' if key.modifiers.contains(KeyModifiers::CONTROL) => { 787 | // [todo] better error handling here? 788 | 789 | let mut backend = stdout(); 790 | execute!( 791 | &mut backend, 792 | LeaveAlternateScreen, 793 | crossterm::cursor::Show, 794 | crossterm::event::DisableMouseCapture 795 | ) 796 | .unwrap(); 797 | disable_raw_mode().unwrap(); 798 | 799 | // This process will hang after the SIGSTOP call until we get 800 | // foregrounded again by something else, at which point we need to 801 | // re-setup everything so that it all gets drawn again. 802 | kill(Pid::this(), SIGSTOP).unwrap(); 803 | 804 | enable_raw_mode().unwrap(); 805 | execute!( 806 | &mut backend, 807 | EnterAlternateScreen, 808 | crossterm::cursor::Hide, 809 | crossterm::event::EnableMouseCapture 810 | ) 811 | .unwrap(); 812 | 813 | self.last_render.rect = Rect::default(); 814 | Some(InputAction::Redraw) 815 | } 816 | 'z' if self.is_kitty => { 817 | let (zoom, f_or_f) = match self.zoom { 818 | None => (Some(Zoom::default()), FitOrFill::Fill), 819 | Some(_) => (None, FitOrFill::Fit) 820 | }; 821 | self.zoom = zoom; 822 | self.last_render.rect = Rect::default(); 823 | Some(InputAction::SwitchRenderZoom(f_or_f)) 824 | } 825 | 'o' if can_zoom => self.update_zoom(Zoom::step_in), 826 | 'O' if can_zoom => self.update_zoom(Zoom::step_out), 827 | 'L' if can_zoom => self.update_zoom(|z| z.pan(Direction::Right)), 828 | 'H' if can_zoom => self.update_zoom(|z| z.pan(Direction::Left)), 829 | 'J' if can_zoom => self.update_zoom(|z| z.pan(Direction::Down)), 830 | 'K' if can_zoom => self.update_zoom(|z| z.pan(Direction::Up)), 831 | 'G' if can_zoom => self.update_zoom(Zoom::pan_top), 832 | _ => None 833 | } 834 | } 835 | KeyCode::Backspace => { 836 | if let BottomMessage::Input(InputCommand::Search(ref mut term)) = 837 | self.bottom_msg 838 | { 839 | term.pop(); 840 | return Some(InputAction::Redraw); 841 | } 842 | None 843 | } 844 | KeyCode::Right => self.change_page(PageChange::Next, ChangeAmount::Single), 845 | KeyCode::Down | KeyCode::PageDown => 846 | self.change_page(PageChange::Next, ChangeAmount::WholeScreen), 847 | KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single), 848 | KeyCode::Up | KeyCode::PageUp => 849 | self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), 850 | KeyCode::Esc => match (self.showing_help_msg, &self.bottom_msg) { 851 | (false, BottomMessage::Help) => Some(InputAction::QuitApp), 852 | _ => { 853 | // When we hit escape, we just want to pop off the current message and 854 | // show the underlying one. 855 | self.set_msg(MessageSetting::Pop); 856 | Some(InputAction::Redraw) 857 | } 858 | }, 859 | KeyCode::Enter => { 860 | let mut default = BottomMessage::default(); 861 | std::mem::swap(&mut self.bottom_msg, &mut default); 862 | let BottomMessage::Input(ref cmd) = default else { 863 | std::mem::swap(&mut self.bottom_msg, &mut default); 864 | return None; 865 | }; 866 | 867 | match cmd { 868 | // Only forward the command if it's within range 869 | InputCommand::GoToPage(page) => { 870 | // We need to subtract 1 b/c they're tracked internally as 871 | // 0-indexed but input and displayed as 1-indexed 872 | let zero_page = page.saturating_sub(1); 873 | let rendered_len = self.rendered.len(); 874 | 875 | if zero_page < rendered_len { 876 | self.set_page(zero_page); 877 | Some(InputAction::JumpingToPage(zero_page)) 878 | } else { 879 | self.set_msg(MessageSetting::Some(BottomMessage::Error( 880 | format!( 881 | "Cannot jump to page {page}; there are only {rendered_len} pages in the document" 882 | ) 883 | ))); 884 | Some(InputAction::Redraw) 885 | } 886 | } 887 | InputCommand::Search(term) => { 888 | let term = term.clone(); 889 | 890 | // We only want to show search results if there would actually be 891 | // data to show 892 | if !term.is_empty() { 893 | self.set_msg(MessageSetting::Some( 894 | BottomMessage::SearchResults(term.clone()) 895 | )); 896 | } else { 897 | // else, if it's not empty, we just want to reset the bottom 898 | // area to show the default data; we don't want it to like show 899 | // the data from a previous search 900 | self.set_msg(MessageSetting::Reset); 901 | } 902 | 903 | // Reset all the search results 904 | for img in &mut self.rendered { 905 | img.num_results = None; 906 | } 907 | // but we still want to tell the rest of the system that we set the 908 | // search term to '' so that they can re-render the pages wthout 909 | // the highlighting 910 | Some(InputAction::Search(term)) 911 | } 912 | } 913 | } 914 | _ => None 915 | } 916 | } 917 | Event::Mouse(mouse) => { 918 | let mut handle_scroll = |mut direction: Direction| { 919 | if can_zoom { 920 | if mouse.modifiers.contains(KeyModifiers::CONTROL) { 921 | match direction { 922 | Direction::Up => self.update_zoom(Zoom::step_in), 923 | Direction::Down => self.update_zoom(Zoom::step_out), 924 | _ => None 925 | } 926 | } else { 927 | if mouse.modifiers.contains(KeyModifiers::SHIFT) { 928 | direction = direction.flip_mouse_xy(); 929 | } 930 | self.update_zoom(|z| z.pan(direction)) 931 | } 932 | } else { 933 | let (change, amount) = match direction { 934 | Direction::Right => (PageChange::Next, ChangeAmount::Single), 935 | Direction::Down => (PageChange::Next, ChangeAmount::WholeScreen), 936 | Direction::Left => (PageChange::Prev, ChangeAmount::Single), 937 | Direction::Up => (PageChange::Prev, ChangeAmount::WholeScreen) 938 | }; 939 | self.change_page(change, amount) 940 | } 941 | }; 942 | match mouse.kind { 943 | MouseEventKind::ScrollRight => handle_scroll(Direction::Right), 944 | MouseEventKind::ScrollDown => handle_scroll(Direction::Down), 945 | MouseEventKind::ScrollLeft => handle_scroll(Direction::Left), 946 | MouseEventKind::ScrollUp => handle_scroll(Direction::Up), 947 | _ => None 948 | } 949 | } 950 | Event::Resize(_, _) => Some(InputAction::Redraw), 951 | _ => None 952 | } 953 | } 954 | 955 | // I want this to always return an option 'cause I just use it to return from `Self::handle_event` 956 | #[expect(clippy::unnecessary_wraps)] 957 | fn update_zoom(&mut self, f: impl FnOnce(&mut Zoom)) -> Option { 958 | if let Some(z) = &mut self.zoom { 959 | f(z); 960 | } 961 | self.last_render.rect = Rect::default(); 962 | Some(InputAction::Redraw) 963 | } 964 | 965 | pub fn show_error(&mut self, err: RenderError) { 966 | self.set_msg(MessageSetting::Some(BottomMessage::Error(match err { 967 | RenderError::Notify(e) => format!("Auto-reload failed: {e}"), 968 | RenderError::Doc(e) => format!("Couldn't process document: {e}"), 969 | RenderError::Converting(e) => format!("Couldn't convert page after rendering: {e}") 970 | }))); 971 | } 972 | 973 | fn set_page(&mut self, page: usize) { 974 | if page != self.page { 975 | // mark that we need to re-render the images 976 | self.last_render.rect = Rect::default(); 977 | self.page = page; 978 | } 979 | } 980 | 981 | // We have `msg` as optional so that if they reset it to none, it'll replace it with 982 | // `prev_msg`, but if they reset it to something else, it'll put the current thing in prev_msg 983 | pub fn set_msg(&mut self, msg: MessageSetting) { 984 | match msg { 985 | MessageSetting::Some(mut msg) => { 986 | std::mem::swap(&mut self.bottom_msg, &mut msg); 987 | self.prev_msg = Some(msg); 988 | } 989 | MessageSetting::Default => self.set_msg(MessageSetting::Some(BottomMessage::default())), 990 | MessageSetting::Reset => { 991 | self.prev_msg = None; 992 | self.bottom_msg = BottomMessage::default(); 993 | } 994 | MessageSetting::Pop => 995 | if self.showing_help_msg { 996 | self.last_render.rect = Rect::default(); 997 | self.showing_help_msg = false; 998 | } else { 999 | self.bottom_msg = self.prev_msg.take().unwrap_or_default(); 1000 | }, 1001 | } 1002 | } 1003 | 1004 | pub fn render_help_msg(&self, frame: &mut Frame<'_>) { 1005 | let frame_area = frame.area(); 1006 | frame.render_widget(Clear, frame_area); 1007 | 1008 | let block = Block::new() 1009 | .title("Help") 1010 | .padding(Padding::proportional(1)) 1011 | .borders(Borders::ALL) 1012 | .border_set(border::ROUNDED) 1013 | .border_style(Color::Blue); 1014 | 1015 | let help_sections = [ 1016 | Text::from(HELP_PAGE), 1017 | // just some spacing 1018 | Text::from(""), 1019 | if self.is_kitty { 1020 | Text::from(KITTY_HELP) 1021 | } else { 1022 | Text::from("Not using kitty, kitty-specific keybindings hidden") 1023 | .style(Color::DarkGray) 1024 | } 1025 | ]; 1026 | 1027 | let max_w: u16 = help_sections 1028 | .iter() 1029 | .flat_map(|section| section.lines.as_slice()) 1030 | // We don't really need full unicode-width since we're using all ascii for the help 1031 | // pages, but this is the function they give us. 1032 | .map(Line::width) 1033 | .max() 1034 | .unwrap_or_default() 1035 | .try_into() 1036 | .expect("Every help text line must be shorter than u16::MAX"); 1037 | 1038 | let layout = Layout::horizontal([ 1039 | Constraint::Fill(1), 1040 | Constraint::Length(max_w + 6), 1041 | Constraint::Fill(1) 1042 | ]) 1043 | .split(frame_area); 1044 | 1045 | let block_area = Layout::vertical([ 1046 | Constraint::Fill(1), 1047 | Constraint::Length( 1048 | u16::try_from(help_sections.iter().map(|s| s.lines.len()).sum::()).unwrap() 1049 | + 4 1050 | ), 1051 | Constraint::Fill(1) 1052 | ]) 1053 | .split(layout[1]); 1054 | 1055 | let mut block_inner = block.inner(block_area[1]); 1056 | 1057 | frame.render_widget(block, block_area[1]); 1058 | 1059 | for section in help_sections { 1060 | let section_lines = section.lines.len(); 1061 | let span = Paragraph::new(section).wrap(Wrap { trim: false }); 1062 | frame.render_widget(span, block_inner); 1063 | block_inner.y += u16::try_from(section_lines).unwrap(); 1064 | } 1065 | } 1066 | } 1067 | 1068 | static HELP_PAGE: &str = "\ 1069 | l, h, left, right: 1070 | Go forward/backwards a single page 1071 | j, k, down, up: 1072 | Go forwards/backwards a screen's worth of pages 1073 | q, esc: 1074 | Quit 1075 | g: 1076 | Go to specific page (type numbers after 'g') 1077 | /: 1078 | Search 1079 | n, N: 1080 | Next/Previous search result 1081 | i: 1082 | Invert colors 1083 | f: 1084 | Remove borders/fullscreen 1085 | ?: 1086 | Show this page 1087 | ctrl+z: 1088 | Suspend & background tdf \ 1089 | "; 1090 | 1091 | static KITTY_HELP: &str = "\ 1092 | When using Kitty Protocol: 1093 | z: 1094 | Toggle between fill-screen and fit-screen 1095 | o/O (when on fill-screen): 1096 | Zoom in and out, respectively 1097 | gg/G (when on fill-screen): 1098 | Scroll to top/bottom of page 1099 | H, J, K, L (when zoomed in): 1100 | Pan direction around page 1101 | "; 1102 | 1103 | pub enum InputAction { 1104 | Redraw, 1105 | JumpingToPage(usize), 1106 | Search(String), 1107 | QuitApp, 1108 | Invert, 1109 | Fullscreen, 1110 | SwitchRenderZoom(crate::FitOrFill) 1111 | } 1112 | 1113 | #[derive(Copy, Clone)] 1114 | enum PageChange { 1115 | Prev, 1116 | Next 1117 | } 1118 | 1119 | #[derive(Copy, Clone)] 1120 | enum ChangeAmount { 1121 | WholeScreen, 1122 | Single 1123 | } 1124 | 1125 | pub enum MessageSetting { 1126 | Some(BottomMessage), 1127 | Default, 1128 | Reset, 1129 | Pop 1130 | } 1131 | --------------------------------------------------------------------------------