Compare commits

...

40 Commits

Author SHA1 Message Date
itsjunetime aed9e56e65 Release version 0.5.0 2025-12-02 21:05:51 -06:00
itsjunetime a4905b2ae5 Update CHANGELOG to link to PRs 2025-12-02 20:09:04 -06:00
Max 9b9796e718 Rewrite zooming (#121) 2025-12-02 19:59:38 -06:00
Max e5cf92221f Add dev utils (#120) 2025-11-27 17:33:46 -06:00
itsjunetime 3fcf3be65f Update changelog for PR 119 and mention radicle identity 2025-11-27 12:38:25 -06:00
Max 3dc5135a8b Fix overflow when zooming out of wide pdf (#119) 2025-11-27 12:33:50 -06:00
itsjunetime 065797ccf6 Update changelog for PR 117 and clarify stance on 'AI' code 2025-11-26 20:46:08 -06:00
Max 55e0c2b33f Implement debounce time for automatic reloading (#117) 2025-11-26 14:22:58 -06:00
itsjunetime 0a0112a7e1 - Update changelog for PR 118 2025-11-26 12:27:40 -06:00
itsjunetime 8f57cd02c3 - Added more lints to Cargo.toml (for fun I guess)
- Extended benchmarking system to check all protocols, not just kitty
- Updated deps
2025-11-26 12:25:56 -06:00
Max 74def1c0a8 Fix panic messages being printed in raw mode (#118) 2025-11-26 11:57:44 -06:00
itsjunetime 670251fdff Add more thanks to readme and mention vertical centering from pr 116 2025-11-24 16:06:20 -06:00
Max b7d1b78e98 Center pages vertically within the layout (#116) 2025-11-24 15:55:40 -06:00
itsjunetime fe8287bf7a Update changelog to reflect pr 115 2025-11-24 13:24:58 -06:00
Max 38b307d628 Make Page-Up and Page-Down behave like up and down (#115) 2025-11-24 13:14:55 -06:00
June 09a332f07e Update deps (#113) 2025-11-23 14:01:47 -06:00
June cde86b4f2c implement gg & G keybinds and better help page (#112)
* implement gg & G keybinds and better help page

* Update changelog
2025-11-16 17:54:18 -06:00
June 5a492599da Fix weird cropping when zooming out too much with kitty (#111)
* Fix weird cropping when zooming out too much with kitty

* Add changelog entry
2025-11-06 20:02:31 -06:00
June 7551c4dba3 Update deps and fmt (#110) 2025-11-06 18:50:19 -06:00
itsjunetime e61eb9b846 Fix r_to_l argument as well to just be a flag 2025-11-06 18:21:18 -06:00
tatounee 6b37976357 Made flags -f, --fullscreen not taking argument (#109)
Now, its presence alone is enough to activate the full-screen option.
2025-11-06 18:18:57 -06:00
June 3628d21c74 Switch to stable base64 simd library (#105) 2025-09-29 17:00:29 -05:00
itsjunetime f4f3b4f539 Actually update package Cargo.toml ugh 2025-09-15 10:05:20 -05:00
itsjunetime a79c534e97 Actually mark release on CHANGELOG 2025-09-07 20:33:43 -05:00
June 971393892a v0.4.3 release 2025-09-07 20:32:16 -05:00
June 440515a3db Actually query terminals and fix terminals if we fail initialization (#103) 2025-09-06 12:02:04 -05:00
itsjunetime 690489016c fmt 2025-09-05 11:15:58 -05:00
itsjunetime bd5554db27 Update mupdf to use git dependency so it works on windows 2025-09-05 10:34:46 -05:00
itsjunetime 45409bacd0 fix CI? 2025-09-05 10:15:49 -05:00
itsjunetime 0481c14c4d fix CI 2025-09-05 08:41:38 -05:00
itsjunetime a78ea5a08c Update deps for new kittage 2025-09-05 08:31:03 -05:00
June f7eabc9af2 Require CI to run with locked flag so lockfile is always in sync (#100) 2025-08-29 09:17:14 -05:00
itsjunetime 918c192047 Add changelog entry for ctrl+scroll zooming 2025-08-20 21:59:29 -05:00
Per Hurtig 8b03329bba Add ctrl+mousewheel zoom control for fill-screen mode (#94)
* Add ctrl+mousewheel zoom control for fill-screen mode

  Enables mouse-based zooming; Uses ctrl+scroll up/down to
  increase/decrease zoom level while in fill-screen mode, with proper
  mouse capture handling.

* removed unused include
2025-08-20 21:57:55 -05:00
itsjunetime 7064be32f2 Update deps including ratatui-image 2025-08-20 09:23:49 -05:00
itsjunetime 2a03294557 Release version 0.4.2 2025-08-18 10:18:26 -05:00
Per Hurtig 7c2c6484a6 Fix macOS shared memory filename length limit (fixes issue #92) (#93)
* Fix macOS shared memory filename length limit

Shorten shared memory object names from "__tdf_kittage_{pid}_page_{rn}_{page_num}"
to "tdf_{pid}_{rn}_{page_num}" and change timestamp from nanoseconds to
milliseconds % 1M to stay under macOS's 31-character limit for shm names.

Fixes "File name too long (os error 63)" error when rendering PDFs on macOS.

On macOS, SHM_NAME_MAX: 30

* Fix macOS shared memory filename length limit

Shorten shared memory object names from "__tdf_kittage_{pid}_page_{rn}_{page_num}"
to "tdf_{pid}_{rn}_{page_num}" and change timestamp from nanoseconds to
milliseconds % 1M to stay under macOS's 31-character limit for shm names.

Fixes "File name too long (os error 63)" error when rendering PDFs on macOS.

SHM_NAME_MAX: 30
2025-08-18 10:15:19 -05:00
itsjunetime e65472e571 Add --version flag 2025-08-15 09:43:52 -05:00
itsjunetime 4fd2237b69 Specify on README to use nightly when building even though it should be detected by rust-toolchain.toml 2025-08-11 21:26:17 -05:00
itsjunetime 69fd8ec7e8 Add instructions for zooming and such to help page 2025-08-09 15:58:56 -06:00
19 changed files with 1650 additions and 1277 deletions
+2
View File
@@ -0,0 +1,2 @@
[*.rs]
indent_style = tab
+5 -5
View File
@@ -31,12 +31,12 @@ jobs:
- name: Install clippy and fmt - name: Install clippy and fmt
run: rustup component add clippy rustfmt run: rustup component add clippy rustfmt
- name: Clippy - name: Clippy
run: cargo clippy -- -D warnings run: cargo clippy --locked -- -D warnings
- name: Tests - name: Tests
run: cargo test run: cargo test --locked
- name: Check fmt - name: Check fmt
run: cargo fmt -- --check run: cargo fmt -- --check
- name: Run tests - name: Run benchmarks as tests
run: cargo test --benches -- adobe_example run: cargo test --locked --benches -- adobe_example
- name: Build - name: Build
run: cargo build run: cargo build --locked
+30
View File
@@ -1,5 +1,35 @@
# Unreleased # Unreleased
# v0.5.0
- Switched simd base64 crate for one that works on stable (from `vb64` to `base64_simd`)
- 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)!)
- Fix cropping issues when zooming out too much while using kitty protocol
- 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
- Updated help page to only show kitty keybindings when you're actually using kitty
- 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)!)
- 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)!)
- 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)!)
- 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))
- Fixed an overflow when zooming out of horizontal pdfs ([#119](https://github.com/itsjunetime/tdf/pull/119), thanks [@maxdexh](https://github.com/maxdexh)!)
- 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)!)
# v0.4.3
- Fix issue with some terminals hanging on startup
- Fix issues with some iterm2-backend terminals not displaying anything
- Allow using ctrl+scroll to zoom in/out while zoomed using kitty backend
- (Internal) run CI with `--locked` flag to ensure lockfile is always in-sync
# v0.4.2
- Add `--version` flag
- Fix shms not working on macos ([#93](https://github.com/itsjunetime/tdf/pull/93))
# v0.4.1
- Add instructions for using new zoom/pan features to help page
# v0.4.0 # v0.4.0
- 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)) - 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))
Generated
+745 -807
View File
File diff suppressed because it is too large Load Diff
+141 -26
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "tdf-viewer" name = "tdf-viewer"
version = "0.3.0" version = "0.5.0"
authors = ["June Welker <junewelker@gmail.com>"] authors = ["June Welker <junewelker@gmail.com>"]
edition = "2024" edition = "2024"
description = "A terminal viewer for PDFs" description = "A terminal viewer for PDFs"
@@ -11,7 +11,7 @@ license = "AGPL-3.0-only"
keywords = ["pdf", "tui", "cli", "terminal"] keywords = ["pdf", "tui", "cli", "terminal"]
categories = ["command-line-utilities", "text-processing", "visualization"] categories = ["command-line-utilities", "text-processing", "visualization"]
default-run = "tdf" default-run = "tdf"
rust-version = "1.85" rust-version = "1.86"
[[bin]] [[bin]]
name = "tdf" name = "tdf"
@@ -38,27 +38,27 @@ flume = { version = "0.11.0", default-features = false, features = ["async"] }
xflags = "0.4.0-pre.2" xflags = "0.4.0-pre.2"
mimalloc = "0.1.43" mimalloc = "0.1.43"
nix = { version = "0.30.0", features = ["signal"] } nix = { version = "0.30.0", features = ["signal"] }
mupdf = { version = "0.5.0", default-features = false, features = ["svg", "system-fonts", "img"] } mupdf = { git = "https://github.com/messense/mupdf-rs.git", rev = "2e0fae910fac8048c7008211fc4d3b9f5d227a07", default-features = false, features = ["svg", "system-fonts", "img"] }
rayon = { version = "*", default-features = false } rayon = { version = "1", default-features = false }
# kittage = { path = "../kittage/", features = ["crossterm-tokio", "image-crate", "log"] } # kittage = { path = "../kittage/", features = ["crossterm-tokio", "image-crate", "log"] }
kittage = { git = "https://github.com/itsjunetime/kittage.git", features = ["crossterm-tokio", "image-crate", "log"] } kittage = { version = "0.1.1", features = ["crossterm-tokio", "image-crate", "log"] }
memmap2 = "*" memmap2 = "0"
csscolorparser = { version = "0.8.0", default-features = false }
# logging # logging
log = "0.4.27" log = "0.4.27"
flexi_logger = "0.31" flexi_logger = "0.31"
# for tracing with tokio-console # for tracing with tokio-console
console-subscriber = { version = "0.4.0", optional = true } console-subscriber = { version = "0.5.0", optional = true }
csscolorparser = { version = "0.7.0" } debounce = "0.2.2"
[profile.production] [profile.production]
inherits = "release" inherits = "release"
lto = "fat" lto = "fat"
[features] [features]
default = ["nightly"] default = []
nightly = ["ratatui-image/vb64"]
tracing = ["tokio/tracing", "dep:console-subscriber"] tracing = ["tokio/tracing", "dep:console-subscriber"]
epub = ["mupdf/epub"] epub = ["mupdf/epub"]
cbz = ["mupdf/cbz"] cbz = ["mupdf/cbz"]
@@ -76,90 +76,205 @@ name = "for_profiling"
path = "./benches/for_profiling.rs" path = "./benches/for_profiling.rs"
[lints.clippy] [lints.clippy]
uninlined_format_args = "warn" alloc_instead_of_core = "warn"
redundant_closure_for_method_calls = "warn" allow_attributes = "warn"
cast_lossless = "warn" as_pointer_underscore = "warn"
single_char_pattern = "warn" as_ptr_cast_mut = "warn"
manual_let_else = "warn" as_underscore = "warn"
ignored_unit_patterns = "warn"
range_plus_one = "warn"
unreadable_literal = "warn"
redundant_else = "warn"
assigning_clones = "warn" assigning_clones = "warn"
assertions_on_result_states = "warn"
bool_to_int_with_if = "warn" bool_to_int_with_if = "warn"
borrow_as_ptr = "warn" borrow_as_ptr = "warn"
branches_sharing_code = "warn"
cargo_common_metadata = "warn"
case_sensitive_file_extension_comparisons = "warn"
cast_lossless = "warn"
cast_ptr_alignment = "warn" cast_ptr_alignment = "warn"
cfg_not_test = "warn"
checked_conversions = "warn" checked_conversions = "warn"
clear_with_drain = "warn"
cloned_instead_of_copied = "warn"
coerce_container_to_any = "warn"
comparison_chain = "warn"
copy_iterator = "warn" copy_iterator = "warn"
create_dir = "warn"
debug_assert_with_mut_call = "warn"
decimal_literal_representation = "warn"
default_trait_access = "warn" default_trait_access = "warn"
deref_by_slicing = "warn"
doc_broken_link = "warn"
doc_link_code = "warn"
doc_link_with_quotes = "warn" doc_link_with_quotes = "warn"
empty_enum = "warn" elidable_lifetime_names = "warn"
empty_drop = "warn"
empty_enums = "warn"
empty_enum_variants_with_brackets = "warn"
empty_structs_with_brackets = "warn"
equatable_if_let = "warn"
error_impl_error = "warn"
expl_impl_clone_on_copy = "warn"
explicit_deref_methods = "warn"
explicit_into_iter_loop = "warn" explicit_into_iter_loop = "warn"
explicit_iter_loop = "warn" explicit_iter_loop = "warn"
fallible_impl_from = "warn"
filetype_is_file = "warn"
filter_map_next = "warn" filter_map_next = "warn"
flat_map_option = "warn" flat_map_option = "warn"
fn_to_numeric_cast_any = "warn"
fn_params_excessive_bools = "warn" fn_params_excessive_bools = "warn"
from_iter_instead_of_collect = "warn" format_collect = "warn"
format_push_string = "warn"
get_unwrap = "warn"
if_then_some_else_none = "warn"
ignore_without_reason = "warn"
ignored_unit_patterns = "warn"
implicit_clone = "warn" implicit_clone = "warn"
imprecise_flops = "warn"
index_refutable_slice = "warn" index_refutable_slice = "warn"
inefficient_to_string = "warn" indexing_slicing = "allow" # can't warn on this cause we basically have to do indexing for some ratatui apis
infinite_loop = "warn"
invalid_upcast_comparisons = "warn" invalid_upcast_comparisons = "warn"
ip_constant = "warn"
iter_filter_is_ok = "warn" iter_filter_is_ok = "warn"
iter_filter_is_some = "warn" iter_filter_is_some = "warn"
iter_not_returning_iterator = "warn" iter_not_returning_iterator = "warn"
iter_on_empty_collections = "warn"
iter_on_single_items = "warn"
large_digit_groups = "warn"
large_futures = "warn" large_futures = "warn"
large_stack_arrays = "warn" large_include_file = "warn"
large_stack_frames = "warn"
large_types_passed_by_value = "warn" large_types_passed_by_value = "warn"
linkedlist = "warn" linkedlist = "warn"
literal_string_with_formatting_args = "warn"
lossy_float_literal = "warn"
macro_use_imports = "warn" macro_use_imports = "warn"
manual_assert = "warn" manual_assert = "warn"
manual_instant_elapsed = "warn" manual_instant_elapsed = "warn"
manual_is_power_of_two = "warn" manual_is_power_of_two = "warn"
manual_is_variant_and = "warn" manual_is_variant_and = "warn"
manual_let_else = "warn"
manual_midpoint = "warn"
manual_ok_or = "warn" manual_ok_or = "warn"
manual_string_new = "warn"
many_single_char_names = "warn" many_single_char_names = "warn"
manual_unwrap_or = "warn" map_err_ignore = "warn"
map_unwrap_or = "warn"
map_with_unused_argument_over_ranges = "warn"
match_same_arms = "warn" match_same_arms = "warn"
match_wild_err_arm = "warn"
match_wildcard_for_single_variants = "warn" match_wildcard_for_single_variants = "warn"
maybe_infinite_iter = "warn" maybe_infinite_iter = "warn"
mem_forget = "warn"
mismatching_type_param_order = "warn" mismatching_type_param_order = "warn"
missing_assert_message = "warn"
missing_fields_in_debug = "warn" missing_fields_in_debug = "warn"
mixed_read_write_in_expression = "warn"
multiple_unsafe_ops_per_block = "warn"
must_use_candidate = "warn"
mut_mut = "warn" mut_mut = "warn"
mutex_atomic = "warn"
mutex_integer = "warn"
naive_bytecount = "warn"
needless_bitwise_bool = "warn" needless_bitwise_bool = "warn"
needless_collect = "warn"
needless_continue = "warn" needless_continue = "warn"
needless_for_each = "warn" needless_for_each = "warn"
needless_pass_by_ref_mut = "warn"
needless_pass_by_value = "warn" needless_pass_by_value = "warn"
needless_raw_string_hashes = "warn" needless_raw_string_hashes = "warn"
needless_raw_strings = "warn"
negative_feature_names = "warn"
no_effect_underscore_binding = "warn" no_effect_underscore_binding = "warn"
no_mangle_with_rust_abi = "warn" no_mangle_with_rust_abi = "warn"
non_send_fields_in_send_ty = "warn"
non_std_lazy_statics = "warn"
non_zero_suggestions = "warn"
nonstandard_macro_braces = "warn"
option_as_ref_cloned = "warn" option_as_ref_cloned = "warn"
option_option = "warn" option_option = "warn"
or_fun_call = "warn"
path_buf_push_overwrite = "warn"
pathbuf_init_then_push = "warn"
precedence_bits = "warn"
ptr_as_ptr = "warn" ptr_as_ptr = "warn"
ptr_cast_constness = "warn" ptr_cast_constness = "warn"
pub_underscore_fields = "warn"
pub_without_shorthand = "warn"
range_minus_one = "warn" range_minus_one = "warn"
range_plus_one = "warn"
rc_buffer = "warn"
rc_mutex = "warn"
read_zero_byte_vec = "warn"
redundant_clone = "warn"
redundant_closure_for_method_calls = "warn"
redundant_else = "warn"
redundant_pub_crate = "warn"
redundant_test_prefix = "warn"
ref_as_ptr = "warn" ref_as_ptr = "warn"
ref_binding_to_reference = "warn" ref_binding_to_reference = "warn"
ref_option = "warn" ref_option = "warn"
ref_option_ref = "warn" ref_option_ref = "warn"
rest_pat_in_fully_bound_structs = "warn"
return_self_not_must_use = "warn" return_self_not_must_use = "warn"
same_functions_in_if_condition = "warn" same_functions_in_if_condition = "warn"
self_named_module_files = "warn"
semicolon_if_nothing_returned = "warn"
semicolon_inside_block = "warn"
should_panic_without_expect = "warn" should_panic_without_expect = "warn"
similar_names = "warn" significant_drop_in_scrutinee = "warn" # I thought this was fixed in the 2024 edition. watever
significant_drop_tightening = "warn"
single_char_pattern = "warn"
single_option_map = "warn"
stable_sort_primitive = "warn" stable_sort_primitive = "warn"
str_split_at_newline = "warn" str_split_at_newline = "warn"
string_lit_as_bytes = "warn"
string_lit_chars_any = "warn"
string_slice = "warn"
struct_excessive_bools = "warn" struct_excessive_bools = "warn"
struct_field_names = "warn" struct_field_names = "warn"
suboptimal_flops = "warn"
suspicious_operation_groupings = "warn"
suspicious_xor_used_as_pow = "warn"
tests_outside_test_module = "warn"
trait_duplication_in_bounds = "warn"
transmute_ptr_to_ptr = "warn" transmute_ptr_to_ptr = "warn"
trivial_regex = "warn"
trivially_copy_pass_by_ref = "warn" trivially_copy_pass_by_ref = "warn"
try_err = "warn"
tuple_array_conversions = "warn"
type_repetition_in_bounds = "warn"
unchecked_time_subtraction = "warn"
undocumented_unsafe_blocks = "warn"
unicode_not_nfc = "warn" unicode_not_nfc = "warn"
uninhabited_references = "warn"
uninlined_format_args = "warn"
unnecessary_box_returns = "warn" unnecessary_box_returns = "warn"
unnecessary_debug_formatting = "warn"
unnecessary_join = "warn" unnecessary_join = "warn"
unnecessary_literal_bound = "warn" unnecessary_literal_bound = "warn"
unnecessary_safety_comment = "warn"
unnecessary_safety_doc = "warn"
unnecessary_self_imports = "warn"
unnecessary_semicolon = "warn"
unnecessary_struct_initialization = "warn"
unnecessary_wraps = "warn" unnecessary_wraps = "warn"
unnested_or_patterns = "warn" unnested_or_patterns = "warn"
unreadable_literal = "warn"
unsafe_derive_deserialize = "warn"
unused_async = "warn" unused_async = "warn"
unused_peekable = "warn"
unused_result_ok = "warn"
unused_rounding = "warn"
unused_self = "warn" unused_self = "warn"
unused_trait_names = "warn"
use_self = "warn"
used_underscore_binding = "warn" used_underscore_binding = "warn"
used_underscore_items = "warn" used_underscore_items = "warn"
useless_let_if_seq = "warn"
verbose_bit_mask = "warn"
verbose_file_reads = "warn"
volatile_composites = "warn"
while_float = "warn"
wildcard_dependencies = "warn"
wildcard_imports = "warn"
zero_sized_map_values = "warn" zero_sized_map_values = "warn"
+8 -2
View File
@@ -16,7 +16,9 @@ Designed to be performant, very responsive, and work well with even very large P
## Installation ## Installation
1. Get the rust toolchain from [rustup.rs](https://rustup.rs) 1. Get the rust toolchain from [rustup.rs](https://rustup.rs)
2. Run `rustup install nightly && cargo +nightly install --git https://github.com/itsjunetime/tdf.git` 2. Run `cargo install --git https://github.com/itsjunetime/tdf.git`
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)
## To Build ## To Build
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`. 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`.
@@ -29,6 +31,8 @@ If it turns out that you're missing one of these, it will fail to compile and te
The binary should then be found at `./target/release/tdf`. The binary should then be found at `./target/release/tdf`.
You can also pull this in via [radicle](https://radicle.xyz) with `rad clone rad:zb11K1XGfQooopqEfwtCMyvbcyK1`
## Why in the world would you use this? ## Why in the world would you use this?
I dunno. Just for fun, mostly. I dunno. Just for fun, mostly.
@@ -37,4 +41,6 @@ I dunno. Just for fun, mostly.
Yeah, sure. Please do. Yeah, sure. Please do.
Please note, though, that all contributions will be treated as licensed under MPL-2.0. Please note, though, that:
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.
2. All contributions will be treated as licensed under MPL-2.0 :)
+3 -1
View File
@@ -1,3 +1,5 @@
use ratatui_image::picker::ProtocolType;
mod utils; mod utils;
const BLACK: i32 = 0; const BLACK: i32 = 0;
@@ -12,5 +14,5 @@ async fn main() {
.nth(1) .nth(1)
.expect("Please enter a file to profile"); .expect("Please enter a file to profile");
utils::render_doc(file, None, BLACK, WHITE).await; utils::render_doc(file, None, BLACK, WHITE, ProtocolType::Kitty).await;
} }
+82 -66
View File
@@ -1,17 +1,15 @@
mod utils; mod utils;
use std::{ use std::{hint::black_box, path::Path};
hint::black_box,
path::Path,
time::{SystemTime, UNIX_EPOCH}
};
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main, profiler::Profiler}; use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use futures_util::StreamExt; use futures_util::StreamExt as _;
use ratatui_image::picker::ProtocolType;
use tdf::{ use tdf::{
converter::{ConvertedPage, ConverterMsg}, converter::{ConvertedPage, ConverterMsg},
renderer::{PageInfo, RenderInfo, fill_default} renderer::{PageInfo, RenderInfo, fill_default}
}; };
use tokio::runtime::Runtime;
use utils::{ use utils::{
RenderState, handle_converter_msg, handle_renderer_msg, render_doc, start_all_rendering, RenderState, handle_converter_msg, handle_renderer_msg, render_doc, start_all_rendering,
start_converting_loop, start_rendering_loop start_converting_loop, start_rendering_loop
@@ -23,90 +21,103 @@ const FILES: [&str; 3] = [
"benches/geotopo.pdf" "benches/geotopo.pdf"
]; ];
const PROTOS: [ProtocolType; 3] = [
ProtocolType::Kitty,
ProtocolType::Sixel,
ProtocolType::Iterm2
];
const BLACK: i32 = 0; const BLACK: i32 = 0;
const WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]); const WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]);
fn render_full(c: &mut Criterion) { fn for_all_combos(
for file in FILES { name: &'static str,
c.bench_with_input(BenchmarkId::new("render_full", file), &file, |b, &file| { mut f: impl FnMut(&Runtime, BenchmarkId, &'static str, ProtocolType)
b.to_async(tokio::runtime::Runtime::new().unwrap()) ) {
.iter(|| render_doc(file, None, BLACK, WHITE)) let rt = tokio::runtime::Runtime::new().unwrap();
}); for proto in PROTOS {
for file in FILES {
f(
&rt,
BenchmarkId::new(name, format!("{file},{proto:?}")),
file,
proto
);
}
} }
} }
fn render_full(c: &mut Criterion) {
for_all_combos("render_full", |rt, id, file, proto| {
_ = c.bench_with_input(id, &file, |b, &file| {
b.to_async(rt)
.iter(|| render_doc(file, None, BLACK, WHITE, proto));
});
});
}
fn render_to_first_page(c: &mut Criterion) { fn render_to_first_page(c: &mut Criterion) {
for file in FILES { for_all_combos("render_first_page", |rt, id, file, proto| {
c.bench_with_input( c.bench_with_input(id, &file, |b, &file| {
BenchmarkId::new("render_first_page", file), b.to_async(rt)
&file, .iter(|| render_first_page(file, BLACK, WHITE, proto));
|b, &file| { });
b.to_async(tokio::runtime::Runtime::new().unwrap()) });
.iter(|| render_first_page(file, BLACK, WHITE))
}
);
}
} }
fn only_converting(c: &mut Criterion) { fn only_converting(c: &mut Criterion) {
for file in FILES { for_all_combos("only_converting", |rt, id, file, proto| {
let runtime = tokio::runtime::Runtime::new().unwrap(); let all_rendered = rt.block_on(render_all_files(file, BLACK, WHITE));
let all_rendered = runtime.block_on(render_all_files(file, BLACK, WHITE));
c.bench_with_input( c.bench_with_input(id, &all_rendered, |b, rendered| {
BenchmarkId::new("only_converting", file), b.to_async(rt)
&(all_rendered, file), .iter_with_setup(|| rendered.clone(), |f| convert_all_files(f, proto));
|b, (rendered, _)| { });
b.to_async(tokio::runtime::Runtime::new().unwrap()) });
.iter_with_setup(|| rendered.clone(), convert_all_files)
}
);
}
} }
/*
fn search_short_common(c: &mut Criterion) { fn search_short_common(c: &mut Criterion) {
for file in FILES { for_all_combos("search_short_common", |rt, id, file, proto| {
c.bench_with_input( c.bench_with_input(id, &file, |b, &file| {
BenchmarkId::new("search_short_common", file), b.to_async(rt)
&file, .iter(|| render_doc(file, Some("an"), BLACK, WHITE, proto))
|b, &file| { });
b.to_async(tokio::runtime::Runtime::new().unwrap()) });
.iter(|| render_doc(file, Some("an"), BLACK, WHITE))
}
);
}
} }
fn search_long_rare(c: &mut Criterion) { fn search_long_rare(c: &mut Criterion) {
for file in FILES { for_all_combos("search_long_rare", |rt, id, file, proto| {
c.bench_with_input( c.bench_with_input(id, &file, |b, &file| {
BenchmarkId::new("search_long_rare", file), b.to_async(rt)
&file, .iter(|| render_doc(file, Some("this is long and rare"), BLACK, WHITE, proto))
|b, &file| { });
b.to_async(tokio::runtime::Runtime::new().unwrap()) });
.iter(|| render_doc(file, Some("this is long and rare"), BLACK, WHITE))
}
);
}
} }
*/
pub async fn render_first_page(path: impl AsRef<Path>, black: i32, white: i32) { pub async fn render_first_page(
path: impl AsRef<Path>,
black: i32,
white: i32,
proto: ProtocolType
) {
let RenderState { let RenderState {
mut from_render_rx, mut from_render_rx,
mut from_converter_rx, mut from_converter_rx,
mut pages, mut pages,
mut to_converter_tx, to_converter_tx,
to_render_tx to_render_tx
} = start_all_rendering(path, black, white); } = start_all_rendering(path, black, white, proto);
// we only want to render until the first page is ready to be printed // we only want to render until the first page is ready to be printed
while pages.iter().all(Option::is_none) { while pages.iter().all(Option::is_none) {
tokio::select! { tokio::select! {
Some(renderer_msg) = from_render_rx.next() => { Some(renderer_msg) = from_render_rx.next() => {
handle_renderer_msg(renderer_msg, &mut pages, &mut to_converter_tx); handle_renderer_msg(renderer_msg, &mut pages, &to_converter_tx);
}, },
Some(converter_msg) = from_converter_rx.next() => { Some(converter_msg) = from_converter_rx.next() => {
handle_converter_msg(converter_msg, &mut pages, &mut to_converter_tx); handle_converter_msg(converter_msg, &mut pages, &to_converter_tx);
} }
} }
} }
@@ -129,7 +140,7 @@ async fn render_all_files(path: &'static str, black: i32, white: i32) -> Vec<Pag
let num = page.page_num; let num = page.page_num;
pages[num] = Some(page); pages[num] = Some(page);
} }
}; }
if pages.iter().all(Option::is_some) { if pages.iter().all(Option::is_some) {
break; break;
@@ -140,9 +151,9 @@ async fn render_all_files(path: &'static str, black: i32, white: i32) -> Vec<Pag
pages.into_iter().flatten().collect() pages.into_iter().flatten().collect()
} }
async fn convert_all_files(files: Vec<PageInfo>) { async fn convert_all_files(files: Vec<PageInfo>, proto: ProtocolType) {
let num_files = files.len(); let num_files = files.len();
let (mut from_converter_rx, to_converter_tx) = start_converting_loop(num_files); let (mut from_converter_rx, to_converter_tx) = start_converting_loop(proto, num_files);
to_converter_tx to_converter_tx
.send(ConverterMsg::NumPages(num_files)) .send(ConverterMsg::NumPages(num_files))
@@ -181,10 +192,12 @@ async fn convert_all_files(files: Vec<PageInfo>) {
black_box(converted); black_box(converted);
} }
/*
struct CpuProfiler; struct CpuProfiler;
impl Profiler for CpuProfiler { impl criterion::profiler::Profiler for CpuProfiler {
fn start_profiling(&mut self, benchmark_id: &str, _: &std::path::Path) { fn start_profiling(&mut self, benchmark_id: &str, _: &std::path::Path) {
use std::time::{SystemTime, UNIX_EPOCH}
let file = format!( let file = format!(
"./{}-{}.profile", "./{}-{}.profile",
benchmark_id.replace('/', "-"), benchmark_id.replace('/', "-"),
@@ -200,10 +213,13 @@ impl Profiler for CpuProfiler {
cpuprofiler::PROFILER.lock().unwrap().stop().unwrap(); cpuprofiler::PROFILER.lock().unwrap().stop().unwrap();
} }
} }
*/
criterion_group!( criterion_group!(
name = benches; name = benches;
config = Criterion::default().sample_size(40).with_profiler(CpuProfiler); // config = Criterion::default().sample_size(40).with_profiler(CpuProfiler);
targets = render_full, render_to_first_page, only_converting, search_short_common, search_long_rare config = Criterion::default().sample_size(40);
// targets = render_full, render_to_first_page, only_converting, search_short_common, search_long_rare
targets = render_full, render_to_first_page, only_converting
); );
criterion_main!(benches); criterion_main!(benches);
+23 -10
View File
@@ -13,7 +13,7 @@ use tdf::{
pub fn handle_renderer_msg( pub fn handle_renderer_msg(
msg: Result<RenderInfo, RenderError>, msg: Result<RenderInfo, RenderError>,
pages: &mut Vec<Option<ConvertedPage>>, pages: &mut Vec<Option<ConvertedPage>>,
to_converter_tx: &mut Sender<tdf::converter::ConverterMsg> to_converter_tx: &Sender<tdf::converter::ConverterMsg>
) { ) {
match msg { match msg {
Ok(RenderInfo::NumPages(num)) => { Ok(RenderInfo::NumPages(num)) => {
@@ -30,7 +30,7 @@ pub fn handle_renderer_msg(
pub fn handle_converter_msg( pub fn handle_converter_msg(
msg: Result<ConvertedPage, RenderError>, msg: Result<ConvertedPage, RenderError>,
pages: &mut [Option<ConvertedPage>], pages: &mut [Option<ConvertedPage>],
to_converter_tx: &mut Sender<ConverterMsg> to_converter_tx: &Sender<ConverterMsg>
) { ) {
let page = msg.expect("Got error from converter"); let page = msg.expect("Got error from converter");
let num = page.num; let num = page.num;
@@ -106,7 +106,9 @@ pub fn start_rendering_loop(
(from_render_rx, to_render_tx) (from_render_rx, to_render_tx)
} }
#[must_use]
pub fn start_converting_loop( pub fn start_converting_loop(
proto: ProtocolType,
prerender: usize prerender: usize
) -> ( ) -> (
RecvStream<'static, Result<ConvertedPage, RenderError>>, RecvStream<'static, Result<ConvertedPage, RenderError>>,
@@ -116,7 +118,7 @@ pub fn start_converting_loop(
let (to_main_tx, from_converter_rx) = unbounded(); let (to_main_tx, from_converter_rx) = unbounded();
let mut picker = Picker::from_fontsize(FONT_SIZE); let mut picker = Picker::from_fontsize(FONT_SIZE);
picker.set_protocol_type(ProtocolType::Kitty); picker.set_protocol_type(proto);
tokio::spawn(run_conversion_loop( tokio::spawn(run_conversion_loop(
to_main_tx, to_main_tx,
@@ -131,9 +133,14 @@ pub fn start_converting_loop(
(from_converter_rx, to_converter_tx) (from_converter_rx, to_converter_tx)
} }
pub fn start_all_rendering(path: impl AsRef<Path>, black: i32, white: i32) -> RenderState { pub fn start_all_rendering(
path: impl AsRef<Path>,
black: i32,
white: i32,
proto: ProtocolType
) -> RenderState {
let (from_render_rx, to_render_tx) = start_rendering_loop(path, black, white); let (from_render_rx, to_render_tx) = start_rendering_loop(path, black, white);
let (from_converter_rx, to_converter_tx) = start_converting_loop(20); let (from_converter_rx, to_converter_tx) = start_converting_loop(proto, 20);
let pages: Vec<Option<ConvertedPage>> = Vec::new(); let pages: Vec<Option<ConvertedPage>> = Vec::new();
@@ -146,14 +153,20 @@ pub fn start_all_rendering(path: impl AsRef<Path>, black: i32, white: i32) -> Re
} }
} }
pub async fn render_doc(path: impl AsRef<Path>, search_term: Option<&str>, black: i32, white: i32) { pub async fn render_doc(
path: impl AsRef<Path>,
search_term: Option<&str>,
black: i32,
white: i32,
proto: ProtocolType
) {
let RenderState { let RenderState {
mut from_render_rx, mut from_render_rx,
mut from_converter_rx, mut from_converter_rx,
mut pages, mut pages,
mut to_converter_tx, to_converter_tx,
to_render_tx to_render_tx
} = start_all_rendering(path, black, white); } = start_all_rendering(path, black, white, proto);
if let Some(term) = search_term { if let Some(term) = search_term {
to_render_tx to_render_tx
@@ -164,10 +177,10 @@ pub async fn render_doc(path: impl AsRef<Path>, search_term: Option<&str>, black
while pages.is_empty() || pages.iter().any(Option::is_none) { while pages.is_empty() || pages.iter().any(Option::is_none) {
tokio::select! { tokio::select! {
Some(renderer_msg) = from_render_rx.next() => { Some(renderer_msg) = from_render_rx.next() => {
handle_renderer_msg(renderer_msg, &mut pages, &mut to_converter_tx); handle_renderer_msg(renderer_msg, &mut pages, &to_converter_tx);
}, },
Some(converter_msg) = from_converter_rx.next() => { Some(converter_msg) = from_converter_rx.next() => {
handle_converter_msg(converter_msg, &mut pages, &mut to_converter_tx); handle_converter_msg(converter_msg, &mut pages, &to_converter_tx);
} }
} }
} }
+1 -1
Submodule ratatui updated: 47c200fb7f...6a0b8ddf76
+14
View File
@@ -0,0 +1,14 @@
{
pkgs ? import <nixpkgs> { },
}:
pkgs.mkShell {
nativeBuildInputs = [ pkgs.pkg-config ];
buildInputs = [
pkgs.cargo
pkgs.rustc
pkgs.rustPlatform.bindgenHook
pkgs.cairo
pkgs.rust-analyzer
];
}
+24 -15
View File
@@ -1,19 +1,19 @@
use std::{ use std::{
num::{NonZeroU32, NonZeroUsize}, num::NonZeroUsize,
time::{SystemTime, UNIX_EPOCH} time::{SystemTime, UNIX_EPOCH}
}; };
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use futures_util::stream::StreamExt; use futures_util::stream::StreamExt as _;
use image::DynamicImage; use image::DynamicImage;
use kittage::NumberOrId; use kittage::{NumberOrId, action::NONZERO_ONE};
use ratatui::layout::Rect; use ratatui::layout::Rect;
use ratatui_image::{ use ratatui_image::{
Resize, Resize,
picker::{Picker, ProtocolType}, picker::{Picker, ProtocolType},
protocol::Protocol protocol::Protocol
}; };
use rayon::iter::ParallelIterator; use rayon::iter::ParallelIterator as _;
use crate::{ use crate::{
renderer::{PageInfo, RenderError, fill_default}, renderer::{PageInfo, RenderError, fill_default},
@@ -26,6 +26,7 @@ pub enum MaybeTransferred {
Transferred(kittage::ImageId) Transferred(kittage::ImageId)
} }
#[derive(Debug)]
pub enum ConvertedImage { pub enum ConvertedImage {
Generic(Protocol), Generic(Protocol),
Kitty { Kitty {
@@ -36,6 +37,7 @@ pub enum ConvertedImage {
} }
impl ConvertedImage { impl ConvertedImage {
#[must_use]
pub fn w_h(&self) -> (u16, u16) { pub fn w_h(&self) -> (u16, u16) {
match self { match self {
Self::Generic(prot) => { Self::Generic(prot) => {
@@ -66,7 +68,7 @@ pub enum ConverterMsg {
pub async fn run_conversion_loop( pub async fn run_conversion_loop(
sender: Sender<Result<ConvertedPage, RenderError>>, sender: Sender<Result<ConvertedPage, RenderError>>,
receiver: Receiver<ConverterMsg>, receiver: Receiver<ConverterMsg>,
mut picker: Picker, picker: Picker,
prerender: usize, prerender: usize,
shms_work: bool shms_work: bool
) -> Result<(), SendError<Result<ConvertedPage, RenderError>>> { ) -> Result<(), SendError<Result<ConvertedPage, RenderError>>> {
@@ -76,7 +78,7 @@ pub async fn run_conversion_loop(
fn next_page( fn next_page(
images: &mut [Option<PageInfo>], images: &mut [Option<PageInfo>],
picker: &mut Picker, picker: &Picker,
page: usize, page: usize,
iteration: &mut usize, iteration: &mut usize,
prerender: usize, prerender: usize,
@@ -125,7 +127,7 @@ pub async fn run_conversion_loop(
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2)); .for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
}, },
_ => unreachable!() _ => unreachable!()
}; }
let img_area = Rect { let img_area = Rect {
width: page_info.img_data.cell_w, width: page_info.img_data.cell_w,
@@ -139,19 +141,20 @@ pub async fn run_conversion_loop(
let rn = SystemTime::now() let rn = SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.unwrap_or_default() .unwrap_or_default()
.as_nanos(); .as_nanos() % 1_000_000;
let mut img = if shms_work { let mut img = if shms_work {
kittage::image::Image::shm_from( kittage::image::Image::shm_from(dyn_img, &format!("/tdf_{pid}_{rn}_{page_num}"))
dyn_img, .map_err(|e| {
&format!("__tdf_kittage_{pid}_page_{rn}_{page_num}") RenderError::Converting(format!("Couldn't write to shm: {e:?}"))
) })?
.map_err(|e| RenderError::Converting(format!("Couldn't write to shm: {e}")))?
} else { } else {
kittage::image::Image::from(dyn_img) kittage::image::Image::from(dyn_img)
}; };
img.num_or_id = NumberOrId::Id(NonZeroU32::new(page_num as u32 + 1).unwrap()); // if ur pdf has 4 billion pages then you deserve to suffer
img.num_or_id = NumberOrId::Id(NONZERO_ONE.saturating_add(page_num as u32));
ConvertedImage::Kitty { ConvertedImage::Kitty {
img: MaybeTransferred::NotYet(img), img: MaybeTransferred::NotYet(img),
cell_w: page_info.img_data.cell_w, cell_w: page_info.img_data.cell_w,
@@ -169,6 +172,12 @@ pub async fn run_conversion_loop(
) )
}; };
log::debug!(
"got converted page for num {} with results {:?}",
page_info.page_num,
page_info.result_rects
);
// update the iteration to the iteration that we stole this image from // update the iteration to the iteration that we stole this image from
*iteration = new_iter; *iteration = new_iter;
@@ -208,7 +217,7 @@ pub async fn run_conversion_loop(
match next_page( match next_page(
&mut images, &mut images,
&mut picker, &picker,
page, page,
&mut iteration, &mut iteration,
prerender, prerender,
+3 -4
View File
@@ -60,8 +60,8 @@ impl<W: Write> Write for DbgWriter<W> {
} }
} }
pub async fn run_action<'image, 'data, 'es>( pub async fn run_action<'es>(
action: Action<'image, 'data>, action: Action<'_, '_>,
ev_stream: &'es mut EventStream ev_stream: &'es mut EventStream
) -> Result<ImageId, TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>> { ) -> Result<ImageId, TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>> {
let writer = DbgWriter { let writer = DbgWriter {
@@ -78,8 +78,7 @@ pub async fn run_action<'image, 'data, 'es>(
pub async fn do_shms_work(ev_stream: &mut EventStream) -> bool { pub async fn do_shms_work(ev_stream: &mut EventStream) -> bool {
let img = DynamicImage::new_rgb8(1, 1); let img = DynamicImage::new_rgb8(1, 1);
let pid = std::process::id(); let pid = std::process::id();
let Ok(mut k_img) = kittage::image::Image::shm_from(img, &format!("__tdf_kittage_test_{pid}")) let Ok(mut k_img) = kittage::image::Image::shm_from(img, &format!("tdf_test_{pid}")) else {
else {
return false; return false;
}; };
+1
View File
@@ -27,6 +27,7 @@ pub struct ScaledResult {
scale_factor: f32 scale_factor: f32
} }
#[must_use]
pub fn scale_img_for_area( pub fn scale_img_for_area(
(img_width, img_height): (f32, f32), (img_width, img_height): (f32, f32),
(area_width, area_height): (f32, f32), (area_width, area_height): (f32, f32),
+152 -84
View File
@@ -1,10 +1,15 @@
use core::error::Error; use core::{
error::Error,
num::{NonZeroU32, NonZeroUsize}
};
use std::{ use std::{
borrow::Cow, borrow::Cow,
ffi::OsString, ffi::OsString,
io::{BufReader, Read, Stdout, stdout}, io::{BufReader, Read as _, Stdout, Write as _, stdout},
num::{NonZeroU32, NonZeroUsize}, mem,
path::PathBuf path::PathBuf,
sync::{Arc, Mutex},
time::Duration
}; };
use crossterm::{ use crossterm::{
@@ -15,15 +20,16 @@ use crossterm::{
enable_raw_mode, window_size enable_raw_mode, window_size
} }
}; };
use debounce::EventDebouncer;
use flexi_logger::FileSpec; use flexi_logger::FileSpec;
use flume::{Sender, r#async::RecvStream}; use flume::{Sender, r#async::RecvStream};
use futures_util::{FutureExt, stream::StreamExt}; use futures_util::{FutureExt as _, stream::StreamExt as _};
use kittage::{ use kittage::{
action::Action, action::Action,
delete::{ClearOrDelete, DeleteConfig, WhichToDelete}, delete::{ClearOrDelete, DeleteConfig, WhichToDelete},
error::{TerminalError, TransmitError} error::{TerminalError, TransmitError}
}; };
use notify::{Event, EventKind, RecursiveMode, Watcher}; use notify::{Event, EventKind, RecursiveMode, Watcher as _};
use ratatui::{Terminal, backend::CrosstermBackend}; use ratatui::{Terminal, backend::CrosstermBackend};
use ratatui_image::{ use ratatui_image::{
FontSize, FontSize,
@@ -54,19 +60,46 @@ impl std::fmt::Debug for WrappedErr {
impl std::error::Error for WrappedErr {} impl std::error::Error for WrappedErr {}
fn reset_term() {
_ = disable_raw_mode();
_ = execute!(
std::io::stdout(),
LeaveAlternateScreen,
crossterm::cursor::Show,
crossterm::event::DisableMouseCapture
);
}
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), WrappedErr> { async fn main() -> Result<(), WrappedErr> {
let result = inner_main().await;
reset_term();
result
}
async fn inner_main() -> Result<(), WrappedErr> {
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
reset_term();
hook(info);
}));
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
console_subscriber::init(); console_subscriber::init();
const DEFAULT_DEBOUNCE_DELAY: Duration = Duration::from_millis(50);
let flags = xflags::parse_or_exit! { let flags = xflags::parse_or_exit! {
/// Display the pdf with the pages starting at the right hand size and moving left and /// Display the pdf with the pages starting at the right hand size and moving left and
/// adjust input keys to match /// adjust input keys to match
optional -r,--r-to-l r_to_l: bool optional -r,--r-to-l
/// The maximum number of pages to display together, horizontally, at a time /// The maximum number of pages to display together, horizontally, at a time
optional -m,--max-wide max_wide: NonZeroUsize optional -m,--max-wide max_wide: NonZeroUsize
/// Fullscreen the pdf (hide document name, page count, etc) /// Fullscreen the pdf (hide document name, page count, etc)
optional -f,--fullscreen fullscreen: bool optional -f,--fullscreen
/// The time to wait for the file to stop changing before reloading, in milliseconds.
/// Defaults to 50ms.
optional --reload-delay reload_delay: u64
/// The number of pages to prerender surrounding the currently-shown page; 0 means no /// The number of pages to prerender surrounding the currently-shown page; 0 means no
/// limit. By default, there is no limit. /// limit. By default, there is no limit.
optional -p,--prerender prerender: usize optional -p,--prerender prerender: usize
@@ -74,12 +107,24 @@ async fn main() -> Result<(), WrappedErr> {
optional -w,--white-color white: String optional -w,--white-color white: String
/// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)") /// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)")
optional -b,--black-color black: String optional -b,--black-color black: String
/// Print the version and exit
optional --version
/// PDF file to read /// PDF file to read
required file: PathBuf optional file: PathBuf
}; };
let path = flags if flags.version {
.file println!("{}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
let Some(file) = flags.file else {
return Err(WrappedErr(
"Please specify the file to open, e.g. `tdf ./my_example_pdf.pdf`".into()
));
};
let path = file
.canonicalize() .canonicalize()
.map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?; .map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?;
@@ -101,10 +146,8 @@ async fn main() -> Result<(), WrappedErr> {
// need to keep it around throughout the lifetime of the program, but don't rly need to use it. // need to keep it around throughout the lifetime of the program, but don't rly need to use it.
// Just need to make sure it doesn't get dropped yet. // Just need to make sure it doesn't get dropped yet.
let mut maybe_logger = None; let maybe_logger = if std::env::var("RUST_LOG").is_ok() {
Some(
if std::env::var("RUST_LOG").is_ok() {
maybe_logger = Some(
flexi_logger::Logger::try_with_env() flexi_logger::Logger::try_with_env()
.map_err(|e| WrappedErr(format!("Couldn't create initial logger: {e}").into()))? .map_err(|e| WrappedErr(format!("Couldn't create initial logger: {e}").into()))?
.log_to_file(FileSpec::try_from("./debug.log").map_err(|e| { .log_to_file(FileSpec::try_from("./debug.log").map_err(|e| {
@@ -112,8 +155,10 @@ async fn main() -> Result<(), WrappedErr> {
})?) })?)
.start() .start()
.map_err(|e| WrappedErr(format!("Can't start logger: {e}").into()))? .map_err(|e| WrappedErr(format!("Can't start logger: {e}").into()))?
); )
} } else {
None
};
let (watch_to_render_tx, render_rx) = flume::unbounded(); let (watch_to_render_tx, render_rx) = flume::unbounded();
let to_renderer = watch_to_render_tx.clone(); let to_renderer = watch_to_render_tx.clone();
@@ -125,8 +170,11 @@ async fn main() -> Result<(), WrappedErr> {
watch_to_tui_tx, watch_to_tui_tx,
watch_to_render_tx, watch_to_render_tx,
path.file_name() path.file_name()
.ok_or(WrappedErr("Path does not have a last component??".into()))? .ok_or_else(|| WrappedErr("Path does not have a last component??".into()))?
.to_owned() .to_owned(),
flags
.reload_delay
.map_or(DEFAULT_DEBOUNCE_DELAY, Duration::from_millis)
)) ))
.map_err(|e| WrappedErr(format!("Couldn't start watching the provided file: {e}").into()))?; .map_err(|e| WrappedErr(format!("Couldn't start watching the provided file: {e}").into()))?;
@@ -160,14 +208,39 @@ async fn main() -> Result<(), WrappedErr> {
window_size.height = h; window_size.height = h;
} }
let cell_height_px = window_size.height / window_size.rows;
let cell_width_px = window_size.width / window_size.columns;
execute!(
std::io::stdout(),
EnterAlternateScreen,
crossterm::cursor::Hide,
crossterm::event::EnableMouseCapture
)
.map_err(|e| {
WrappedErr(
format!(
"Couldn't enter the alternate screen and hide the cursor for proper presentation: {e}"
)
.into()
)
})?;
// We need to create `picker` on this thread because if we create it on the `renderer` thread, // We need to create `picker` on this thread because if we create it on the `renderer` thread,
// it messes up something with user input. Input never makes it to the crossterm thing // it messes up something with user input. Input never makes it to the crossterm thing
let picker = Picker::from_query_stdio() let picker = Picker::from_query_stdio()
.map_err(|e| WrappedErr(match e { .or_else(|e| match e {
ratatui_image::errors::Errors::NoFontSize => ratatui_image::errors::Errors::NoFontSize if
"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(), window_size.width != 0
e => format!("Couldn't get the necessary information to set up images: {e}").into() && window_size.height != 0
}))?; && window_size.columns != 0
&& window_size.rows != 0
=> Ok(Picker::from_fontsize((cell_width_px, cell_height_px))),
ratatui_image::errors::Errors::NoFontSize => Err(WrappedErr(
"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()
)),
e => Err(WrappedErr(format!("Couldn't get the necessary information to set up images: {e}").into()))
})?;
// then we want to spawn off the rendering task // then we want to spawn off the rendering task
// We need to use the thread::spawn API so that this exists in a thread not owned by tokio, // We need to use the thread::spawn API so that this exists in a thread not owned by tokio,
@@ -177,8 +250,6 @@ async fn main() -> Result<(), WrappedErr> {
.and_then(NonZeroUsize::new) .and_then(NonZeroUsize::new)
.map_or(PrerenderLimit::All, PrerenderLimit::Limited); .map_or(PrerenderLimit::All, PrerenderLimit::Limited);
let cell_height_px = window_size.height / window_size.rows;
let cell_width_px = window_size.width / window_size.columns;
std::thread::spawn(move || { std::thread::spawn(move || {
renderer::start_rendering( renderer::start_rendering(
&file_path, &file_path,
@@ -211,12 +282,7 @@ async fn main() -> Result<(), WrappedErr> {
|| "Unknown file".into(), || "Unknown file".into(),
|n| n.to_string_lossy().to_string() |n| n.to_string_lossy().to_string()
); );
let tui = Tui::new( let tui = Tui::new(file_name, flags.max_wide, flags.r_to_l, is_kitty);
file_name,
flags.max_wide,
flags.r_to_l.unwrap_or_default(),
is_kitty
);
let backend = CrosstermBackend::new(std::io::stdout()); let backend = CrosstermBackend::new(std::io::stdout());
let mut term = Terminal::new(backend).map_err(|e| { let mut term = Terminal::new(backend).map_err(|e| {
@@ -224,19 +290,6 @@ async fn main() -> Result<(), WrappedErr> {
})?; })?;
term.skip_diff(true); term.skip_diff(true);
execute!(
term.backend_mut(),
EnterAlternateScreen,
crossterm::cursor::Hide
)
.map_err(|e| {
WrappedErr(
format!(
"Couldn't enter the alternate screen and hide the cursor for proper presentation: {e}"
)
.into()
)
})?;
enable_raw_mode().map_err(|e| { enable_raw_mode().map_err(|e| {
WrappedErr( WrappedErr(
format!("Can't enable raw mode, which is necessary to receive input: {e}").into() format!("Can't enable raw mode, which is necessary to receive input: {e}").into()
@@ -257,7 +310,7 @@ async fn main() -> Result<(), WrappedErr> {
})?; })?;
} }
let fullscreen = flags.fullscreen.unwrap_or_default(); let fullscreen = flags.fullscreen;
let main_area = Tui::main_layout(&term.get_frame(), fullscreen); let main_area = Tui::main_layout(&term.get_frame(), fullscreen);
to_renderer to_renderer
.send(RenderNotif::Area(main_area.page_area)) .send(RenderNotif::Area(main_area.page_area))
@@ -292,16 +345,7 @@ async fn main() -> Result<(), WrappedErr> {
) )
})?; })?;
execute!(
term.backend_mut(),
LeaveAlternateScreen,
crossterm::cursor::Show
)
.unwrap();
disable_raw_mode().unwrap();
drop(maybe_logger); drop(maybe_logger);
Ok(()) Ok(())
} }
@@ -422,38 +466,58 @@ async fn enter_redraw_loop(
fn on_notify_ev( fn on_notify_ev(
to_tui_tx: flume::Sender<Result<RenderInfo, RenderError>>, to_tui_tx: flume::Sender<Result<RenderInfo, RenderError>>,
to_render_tx: flume::Sender<RenderNotif>, to_render_tx: flume::Sender<RenderNotif>,
file_name: OsString file_name: OsString,
debounce_delay: Duration
) -> impl Fn(notify::Result<Event>) { ) -> impl Fn(notify::Result<Event>) {
move |res| match res { let last_event: Mutex<Result<(), RenderError>> = Mutex::new(Ok(()));
// If we get an error here, and then an error sending, everything's going wrong. Just give let last_event = Arc::new(last_event);
// up lol.
Err(e) => to_tui_tx.send(Err(RenderError::Notify(e))).unwrap(),
// TODO: Should we match EventKind::Rename and propogate that so that the other parts of the
// process know that too? Or should that be
Ok(ev) => {
// We only watch the parent directory (see the comment above `watcher.watch` in `fn
// main`) so we need to filter out events to only ones that pertain to the single file
// we care about
if !ev
.paths
.iter()
.any(|path| path.file_name().is_some_and(|f| f == file_name))
{
return;
}
match ev.kind { let debouncer = EventDebouncer::new(debounce_delay, {
EventKind::Access(_) => (), let last_event = last_event.clone();
EventKind::Remove(_) => to_tui_tx move |()| {
.send(Err(RenderError::Converting("File was deleted".into()))) let event = mem::replace(&mut *last_event.lock().unwrap(), Ok(()));
.unwrap(), match event {
// This shouldn't fail to send unless the receiver gets disconnected. If that's // This shouldn't fail to send unless the receiver gets disconnected. If that's
// happened, then like the main thread has panicked or something, so it doesn't matter // happened, then like the main thread has panicked or something, so it doesn't matter
// we don't handle the error here. // we don't handle the error here.
EventKind::Other | EventKind::Any | EventKind::Create(_) | EventKind::Modify(_) => Ok(()) => to_render_tx.send(RenderNotif::Reload).unwrap(),
to_render_tx.send(RenderNotif::Reload).unwrap(), // If we get an error here, and then an error sending, everything's going wrong. Just give
// up lol.
Err(e) => to_tui_tx.send(Err(e)).unwrap()
} }
} }
});
move |res| {
let event = match res {
Err(e) => Err(RenderError::Notify(e)),
// TODO: Should we match EventKind::Rename and propogate that so that the other parts of the
// process know that too? Or should that be
Ok(ev) => {
// We only watch the parent directory (see the comment above `watcher.watch` in `fn
// main`) so we need to filter out events to only ones that pertain to the single file
// we care about
if !ev
.paths
.iter()
.any(|path| path.file_name().is_some_and(|f| f == file_name))
{
return;
}
match ev.kind {
EventKind::Access(_) => return,
EventKind::Remove(_) => Err(RenderError::Converting("File was deleted".into())),
EventKind::Other
| EventKind::Any
| EventKind::Create(_)
| EventKind::Modify(_) => Ok(())
}
}
};
*last_event.lock().unwrap() = event;
debouncer.put(());
} }
} }
@@ -464,6 +528,10 @@ fn parse_color_to_i32(cs: &str) -> Result<i32, csscolorparser::ParseColorError>
} }
fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> { fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
// send the command code to get the terminal window size
print!("\x1b[14t");
std::io::stdout().flush().unwrap();
// we need to enable raw mode here since this bit of output won't print a newline; it'll // we need to enable raw mode here since this bit of output won't print a newline; it'll
// just print the info it wants to tell us. So we want to get all characters as they come // just print the info it wants to tell us. So we want to get all characters as they come
enable_raw_mode().map_err(|e| { enable_raw_mode().map_err(|e| {
@@ -506,18 +574,18 @@ fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
)); ));
}; };
let h = h.parse::<u16>().map_err(|_| { let h = h.parse::<u16>().map_err(|e| {
WrappedErr( WrappedErr(
format!( format!(
"Your terminal said its height is {h}, but that is not a 16-bit unsigned integer" "Your terminal said its height is {h}, but that is not a 16-bit unsigned integer: {e}"
) )
.into() .into()
) )
})?; })?;
let w = w.parse::<u16>().map_err(|_| { let w = w.parse::<u16>().map_err(|e| {
WrappedErr( WrappedErr(
format!( format!(
"Your terminal said its width is {w}, but that is not a 16-bit unsigned integer" "Your terminal said its width is {w}, but that is not a 16-bit unsigned integer: {e}"
) )
.into() .into()
) )
+23 -25
View File
@@ -2,7 +2,7 @@ use std::{collections::VecDeque, num::NonZeroUsize, thread::sleep, time::Duratio
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use mupdf::{ use mupdf::{
Colorspace, Document, Matrix, Page, Pixmap, Quad, TextPageOptions, text_page::SearchHitResponse Colorspace, Document, Matrix, Page, Pixmap, Quad, TextPageFlags, text_page::SearchHitResponse
}; };
use ratatui::layout::Rect; use ratatui::layout::Rect;
@@ -78,7 +78,7 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
// We're allowing passing by value here because this is only called once, at the beginning of the // We're allowing passing by value here because this is only called once, at the beginning of the
// program, and the arguments that 'should' be passed by value (`receiver` and `size`) would // program, and the arguments that 'should' be passed by value (`receiver` and `size`) would
// probably be more performant if accessed by-value instead of through a reference. Probably. // probably be more performant if accessed by-value instead of through a reference. Probably.
#[allow(clippy::needless_pass_by_value, clippy::too_many_arguments)] #[expect(clippy::needless_pass_by_value, clippy::too_many_arguments)]
pub fn start_rendering( pub fn start_rendering(
path: &str, path: &str,
sender: Sender<Result<RenderInfo, RenderError>>, sender: Sender<Result<RenderInfo, RenderError>>,
@@ -116,7 +116,7 @@ pub fn start_rendering(
// temporarily removed to facilitate a save or something like that) // temporarily removed to facilitate a save or something like that)
while let Ok(msg) = receiver.recv() { while let Ok(msg) = receiver.recv() {
// and once that comes, just try to reload again // and once that comes, just try to reload again
if let RenderNotif::Reload = msg { if matches!(msg, RenderNotif::Reload) {
continue 'reload; continue 'reload;
} }
} }
@@ -313,7 +313,7 @@ pub fn start_rendering(
if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) { if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) {
sender.send(Err(RenderError::Doc(e)))?; sender.send(Err(RenderError::Doc(e)))?;
continue; continue;
}; }
log::debug!("got pixmap for page {page_num} with WxH {w}x{h}"); log::debug!("got pixmap for page {page_num} with WxH {w}x{h}");
@@ -341,7 +341,7 @@ pub fn start_rendering(
Err(TryRecvError::Disconnected) => return Ok(()), Err(TryRecvError::Disconnected) => return Ok(()),
Ok(notif) => handle_notif!(notif), Ok(notif) => handle_notif!(notif),
Err(TryRecvError::Empty) => () Err(TryRecvError::Empty) => ()
}; }
} }
// Now, if we have a search term, we want to look through the rest of the document past // Now, if we have a search term, we want to look through the rest of the document past
@@ -434,7 +434,7 @@ pub fn start_rendering(
return Ok(()); return Ok(());
}; };
handle_notif!(msg) handle_notif!(msg);
} }
} }
} }
@@ -520,7 +520,7 @@ fn render_single_page_to_ctx(
}) })
} }
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct HighlightRect { pub struct HighlightRect {
pub ul_x: u32, pub ul_x: u32,
pub ul_y: u32, pub ul_y: u32,
@@ -536,15 +536,14 @@ fn search_page(
) -> Result<Vec<Quad>, mupdf::error::Error> { ) -> Result<Vec<Quad>, mupdf::error::Error> {
search_term search_term
.map(|term| { .map(|term| {
page.to_text_page(TextPageOptions::empty()) page.to_text_page(TextPageFlags::empty()).and_then(|page| {
.and_then(|page| { let mut v = Vec::with_capacity(trusted_search_results);
let mut v = Vec::with_capacity(trusted_search_results); page.search_cb(term, &mut v, |v, results| {
page.search_cb(term, &mut v, |v, results| { v.extend(results.iter().cloned());
v.extend(results.iter().cloned()); SearchHitResponse::ContinueSearch
SearchHitResponse::ContinueSearch
})
.map(|_| v)
}) })
.map(|_| v)
})
}) })
.transpose() .transpose()
.map(Option::unwrap_or_default) .map(Option::unwrap_or_default)
@@ -552,22 +551,21 @@ fn search_page(
#[inline] #[inline]
fn count_search_results(page: &Page, search_term: &str) -> Result<usize, mupdf::error::Error> { fn count_search_results(page: &Page, search_term: &str) -> Result<usize, mupdf::error::Error> {
page.to_text_page(TextPageOptions::empty()) page.to_text_page(TextPageFlags::empty()).and_then(|page| {
.and_then(|page| { let mut count = 0;
let mut count = 0; page.search_cb(search_term, &mut count, |count, results| {
page.search_cb(search_term, &mut count, |count, results| { *count += results.len();
*count += results.len(); SearchHitResponse::ContinueSearch
SearchHitResponse::ContinueSearch })?;
})?; Ok(count)
Ok(count) })
})
} }
struct PopOnNext<'a> { struct PopOnNext<'a> {
inner: &'a mut VecDeque<usize> inner: &'a mut VecDeque<usize>
} }
impl<'a> Iterator for PopOnNext<'a> { impl Iterator for PopOnNext<'_> {
type Item = usize; type Item = usize;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
self.inner.pop_front() self.inner.pop_front()
+2
View File
@@ -7,6 +7,7 @@ pub struct Skip {
} }
impl Skip { impl Skip {
#[must_use]
pub fn new(skip: bool) -> Self { pub fn new(skip: bool) -> Self {
Self { skip } Self { skip }
} }
@@ -45,6 +46,7 @@ impl InterleavedAroundWithMax {
/// the following must hold or else this is liable to panic or produce nonsense values: /// the following must hold or else this is liable to panic or produce nonsense values:
/// - inclusive_min < exclusive_max /// - inclusive_min < exclusive_max
/// - inclusive_min <= around <= exclusive_max /// - inclusive_min <= around <= exclusive_max
#[must_use]
pub fn new(around: usize, inclusive_min: usize, exclusive_max: NonZeroUsize) -> Self { pub fn new(around: usize, inclusive_min: usize, exclusive_max: NonZeroUsize) -> Self {
Self { Self {
around, around,
+390 -230
View File
@@ -16,10 +16,11 @@ use nix::{
use ratatui::{ use ratatui::{
Frame, Frame,
layout::{Constraint, Flex, Layout, Position, Rect}, layout::{Constraint, Flex, Layout, Position, Rect},
prelude::{Line, Text},
style::{Color, Style}, style::{Color, Style},
symbols::border, symbols::border,
text::{Span, Text}, text::Span,
widgets::{Block, Borders, Clear, Padding} widgets::{Block, Borders, Clear, Padding, Paragraph, Wrap}
}; };
use ratatui_image::{FontSize, Image}; use ratatui_image::{FontSize, Image};
@@ -77,8 +78,8 @@ struct PageConstraints {
#[derive(Default, Debug)] #[derive(Default, Debug)]
struct Zoom { struct Zoom {
// just how much 'zoom' you have. Doesn't relate to anything specific yet, except that 0 means // just how much 'zoom' you have. 0 means it fills the screen (instead of fits), such
// it fills the screen (instead of fits) // that one axis is fully on-screen
level: i16, level: i16,
// how many terminal-cells worth of content overflow the left side of the screen (and are thus // how many terminal-cells worth of content overflow the left side of the screen (and are thus
// not displayed) // not displayed)
@@ -87,6 +88,21 @@ struct Zoom {
// not displayed) // not displayed)
cell_pan_from_top: u16 cell_pan_from_top: u16
} }
impl Zoom {
/// Returns the zoom factor, where 1 is the default and means fill-screen
fn factor(&self) -> f32 {
// TODO: Make these configurable once we have a good way to set options after startup
const ZOOM_RATE: f32 = 1.1;
const ZOOM_RATE_GRANULAR: f32 = 1.05;
if self.level > 0 {
ZOOM_RATE.powi(self.level.into())
} else {
// use a more granular zoom rate for the steps between fit-screen and fill-screen
ZOOM_RATE_GRANULAR.powi(self.level.into())
}
}
}
// This seems like a kinda weird struct because it holds two optionals but any representation // This seems like a kinda weird struct because it holds two optionals but any representation
// within it is valid; I think it's the best way to represent it // within it is valid; I think it's the best way to represent it
@@ -108,7 +124,8 @@ pub struct RenderLayout {
} }
impl Tui { impl Tui {
pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool, is_kitty: bool) -> Tui { #[must_use]
pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool, is_kitty: bool) -> Self {
Self { Self {
name, name,
page: 0, page: 0,
@@ -123,6 +140,7 @@ impl Tui {
} }
} }
#[must_use]
pub fn main_layout(frame: &Frame<'_>, fullscreened: bool) -> RenderLayout { pub fn main_layout(frame: &Frame<'_>, fullscreened: bool) -> RenderLayout {
if fullscreened { if fullscreened {
RenderLayout { RenderLayout {
@@ -147,6 +165,129 @@ impl Tui {
} }
} }
fn render_zoomed<'s>(
// area of the 'fit-screen' page
mut img_area: Rect,
font_size: FontSize,
zoom: &mut Zoom,
img: &'s mut MaybeTransferred,
page_num: usize,
img_cell_w: u16,
img_cell_h: u16
) -> KittyDisplay<'s> {
log::debug!("zoom is {zoom:#?}");
log::debug!("page area is {img_area:#?}");
log::debug!("img dimensions are {img_cell_w}x{img_cell_h}");
// Dimensions of the section of the image to be displayed.
// Kittage calls this the "image area to display".
// We need to shrink this or the page area in order to zoom in or out,
// respectively.
let mut img_section_w = f32::from(img_cell_w);
let mut img_section_h = f32::from(img_cell_h);
let zoom_factor = zoom.factor();
if zoom_factor >= 1.0 {
// Use a smaller section of the image. This efficively zooms into that section.
img_section_w /= zoom_factor;
img_section_h /= zoom_factor;
} else {
// Shrink the page area, such that the fill-screen conversion
// will zoom out of the image.
let initial_page_w = f32::from(img_area.width);
let initial_page_h = f32::from(img_area.height);
// how many pages the image is wide/high
let img_page_w_ratio = img_section_w / initial_page_w;
let img_page_h_ratio = img_section_h / initial_page_h;
let shrink_move_page = |dim: &mut u16, pos: &mut u16, axis_zoom_factor: f32| {
let old_dim = *dim;
// The axis zoom factor tells us what portion of the axis
// we need to show.
*dim = (f32::from(*dim) * axis_zoom_factor) as u16;
*pos += old_dim
.checked_sub(*dim)
.expect("zooming out should shrink the image")
/ 2;
};
// TODO: Detect max zoom-out in zoom levels
if img_page_w_ratio < img_page_h_ratio {
// vertical scroll / tall image. zooming out means decreasing the width of the page area
shrink_move_page(
&mut img_area.width,
&mut img_area.x,
// disallow zooming out past fit-screen
zoom_factor.max(1.0 / img_page_h_ratio)
);
} else {
// horizontal scroll / wide image. zooming out means decreasing the width of the page area
shrink_move_page(
&mut img_area.height,
&mut img_area.y,
// disallow zooming out past fit-screen
zoom_factor.max(1.0 / img_page_w_ratio)
);
}
}
log::debug!("after adjustment, page area is {img_area:#?}");
// Crop the image such that in the end, the aspect ratio of the section
// is the same as that of the page area. This effectively performs the
// conversion to fill-screen.
// Note that this only works because cell_w, cell_h is in fit-screen
// format, i.e. the cell size and the page area already share at
// least one dimension.
{
let page_area_w = f32::from(img_area.width);
let page_area_h = f32::from(img_area.height);
// how many pages the image is wide/high
// Note that this is not the same as during the
// zoom-out calculation, since it changed the page
// dimensions.
let img_page_w_ratio = img_section_w / page_area_w;
let img_page_h_ratio = img_section_h / page_area_h;
if img_page_w_ratio < img_page_h_ratio {
img_section_h = page_area_h * img_page_w_ratio;
} else {
img_section_w = page_area_w * img_page_h_ratio;
}
}
let width = (img_section_w * f32::from(font_size.0)) as u32;
let height = (img_section_h * f32::from(font_size.1)) as u32;
zoom.cell_pan_from_left = zoom
.cell_pan_from_left
.min(img_cell_w.saturating_sub(img_section_w.ceil() as u16));
zoom.cell_pan_from_top = zoom
.cell_pan_from_top
.min(img_cell_h.saturating_sub(img_section_h.ceil() as u16));
KittyDisplay::DisplayImages(vec![KittyReadyToDisplay {
img,
page_num,
pos: Position {
x: img_area.x,
y: img_area.y
},
display_loc: DisplayLocation {
x: u32::from(zoom.cell_pan_from_left) * u32::from(font_size.0),
y: u32::from(zoom.cell_pan_from_top) * u32::from(font_size.1),
width,
height,
columns: img_area.width,
rows: img_area.height,
..DisplayLocation::default()
}
}])
}
// TODO: Make a way to fill the width of the screen with one page and scroll down to view it // TODO: Make a way to fill the width of the screen with one page and scroll down to view it
#[must_use] #[must_use]
pub fn render<'s>( pub fn render<'s>(
@@ -180,166 +321,120 @@ impl Tui {
// be written and set to skip it so that ratatui doesn't spend a lot of time diffing it // be written and set to skip it so that ratatui doesn't spend a lot of time diffing it
// each re-render // each re-render
frame.render_widget(Skip::new(true), img_area); frame.render_widget(Skip::new(true), img_area);
KittyDisplay::NoChange return KittyDisplay::NoChange;
} else { }
if let Some(ref mut zoom) = self.zoom {
// yes this is ugly and I hate it. it's due to the limitations that currently exist
// in the borrow checker. Once `-Zpolonius=next` is stabilized, we can rework this
// to look like what we expect.
// See https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions
// You can also rewrite this to just if an `if let` and run it under
// `RUSTFLAGS="-Zpolonius=next"` and see that it works
if self.rendered[self.page]
.img
.as_ref()
.is_some_and(|c| matches!(c, ConvertedImage::Kitty { .. }))
{
let Some(ConvertedImage::Kitty {
ref mut img,
cell_w,
cell_h
}) = self.rendered[self.page].img
else {
unreachable!()
};
log::debug!("zoom is now {zoom:#?}"); if let Some(ref mut zoom) = self.zoom {
log::debug!("img_area is {img_area:#?}"); // yes this is ugly and I hate it. it's due to the limitations that currently exist
// in the borrow checker. Once `-Zpolonius=next` is stabilized, we can rework this
// to look like what we expect.
// See https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions
// You can also rewrite this to just if an `if let` and run it under
// `RUSTFLAGS="-Zpolonius=next"` and see that it works
if self.rendered[self.page]
.img
.as_ref()
.is_some_and(|c| matches!(c, ConvertedImage::Kitty { .. }))
{
let Some(ConvertedImage::Kitty {
ref mut img,
cell_w,
cell_h
}) = self.rendered[self.page].img
else {
unreachable!()
};
if zoom.level < 0 { self.last_render = LastRender {
img_area = Rect { rect: size,
width: img_area pages_shown: 1,
.width unused_width: 0
.saturating_sub((zoom.level * 2).unsigned_abs()) };
.max(1), return Self::render_zoomed(
x: img_area.x + (zoom.level.unsigned_abs().min(img_area.width / 2)), img_area, font_size, zoom, img, self.page, cell_w, cell_h
..img_area );
} }
} }
log::debug!("after adjustment, img_area is {img_area:#?}"); // here we calculate how many pages can fit in the available area.
let mut test_area_w = img_area.width;
// Ugh I don't like this logic. I wish we could simplify it. // go through our pages, starting at the first one we want to view
let img_width = f32::from(cell_w); let mut page_sizes = self.rendered[self.page..]
let img_height = f32::from(cell_h); .iter_mut()
let img_area_width = f32::from(img_area.width); // and get this to represent a count of how many we're looking at so far to render
let img_area_height = f32::from(img_area.height); .enumerate()
let available_to_real_width_ratio = img_area_width / img_width; // and only take as many as are ready to be rendered
let available_to_real_height_ratio = img_area_height / img_height; .take_while(|(idx, page)| {
let mut take = page.img.is_some();
let (new_cell_width, new_cell_height) = if let Some(max) = self.page_constraints.max_wide {
if available_to_real_width_ratio > available_to_real_height_ratio { take &= *idx < max.get();
(img_width, img_area_height / available_to_real_width_ratio)
} else {
(img_area_width / available_to_real_height_ratio, img_height)
};
log::debug!("new_cell stuff is {new_cell_width}x{new_cell_height}");
let width = (new_cell_width * f32::from(font_size.0)) as u32;
let height = (new_cell_height * f32::from(font_size.1)) as u32;
self.last_render = LastRender {
rect: size,
pages_shown: 1,
unused_width: 0
};
zoom.cell_pan_from_left = zoom
.cell_pan_from_left
.min(cell_w.saturating_sub(new_cell_width as u16));
zoom.cell_pan_from_top = zoom
.cell_pan_from_top
.min(cell_h.saturating_sub(new_cell_height as u16));
return KittyDisplay::DisplayImages(vec![KittyReadyToDisplay {
img,
page_num: self.page,
pos: Position {
x: img_area.x,
y: img_area.y
},
display_loc: DisplayLocation {
x: u32::from(zoom.cell_pan_from_left) * u32::from(font_size.0),
y: u32::from(zoom.cell_pan_from_top) * u32::from(font_size.1),
width,
height,
columns: img_area.width,
rows: img_area.height,
..DisplayLocation::default()
}
}]);
} }
}; take
})
// here we calculate how many pages can fit in the available area. // and map it to their width (in cells on the terminal, not pixels)
let mut test_area_w = img_area.width; .filter_map(|(_, page)| {
// go through our pages, starting at the first one we want to view page.img.as_mut().map(|img| {
let mut page_widths = self.rendered[self.page..] let (w, h) = img.w_h();
.iter_mut() (w, h, img)
// and get this to represent a count of how many we're looking at so far to render
.enumerate()
// and only take as many as are ready to be rendered
.take_while(|(idx, page)| {
let mut take = page.img.is_some();
if let Some(max) = self.page_constraints.max_wide {
take &= *idx < max.get();
}
take
}) })
// and map it to their width (in cells on the terminal, not pixels) })
.filter_map(|(_, page)| page.img.as_mut().map(|img| (img.w_h().0, img))) // and then take them as long as they won't overflow the available area.
// and then take them as long as they won't overflow the available area. .take_while(|(width, _, _)| match test_area_w.checked_sub(*width) {
.take_while(|(width, _)| match test_area_w.checked_sub(*width) { Some(new_val) => {
Some(new_val) => { test_area_w = new_val;
test_area_w = new_val; true
true }
} None => false
None => false })
.collect::<Vec<_>>();
if self.page_constraints.r_to_l {
page_sizes.reverse();
}
if page_sizes.is_empty() {
// If none are ready to render, just show the loading thing
Self::render_loading_in(frame, img_area);
KittyDisplay::ClearImages
} else {
execute!(stdout(), BeginSynchronizedUpdate).unwrap();
let total_width = page_sizes.iter().map(|(w, _, _)| w).sum::<u16>();
self.last_render.pages_shown = page_sizes.len();
let unused_width = img_area.width - total_width;
self.last_render.unused_width = unused_width;
img_area.x += unused_width / 2;
if let Some(total_height) = page_sizes.iter().map(|(_, h, _)| h).max() {
// This subtraction might sporadicly fail while shrinking the window.
if let Some(unused_height) = img_area.height.checked_sub(*total_height) {
img_area.y += unused_height / 2;
}
}
let to_display = page_sizes
.into_iter()
.enumerate()
.filter_map(|(idx, (width, _, img))| {
let maybe_img =
Self::render_single_page(frame, img, Rect { width, ..img_area });
img_area.x += width;
maybe_img.map(|(img, pos)| KittyReadyToDisplay {
img,
page_num: idx + self.page,
pos,
display_loc: DisplayLocation::default()
})
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if self.page_constraints.r_to_l { // we want to set this at the very end so it doesn't get set somewhere halfway through and
page_widths.reverse(); // then the whole diffing thing messes it up
} self.last_render.rect = size;
if page_widths.is_empty() { KittyDisplay::DisplayImages(to_display)
// If none are ready to render, just show the loading thing
Self::render_loading_in(frame, img_area);
KittyDisplay::ClearImages
} else {
execute!(stdout(), BeginSynchronizedUpdate).unwrap();
let total_width = page_widths.iter().map(|(w, _)| w).sum::<u16>();
self.last_render.pages_shown = page_widths.len();
let unused_width = img_area.width - total_width;
self.last_render.unused_width = unused_width;
img_area.x += unused_width / 2;
let to_display = page_widths
.into_iter()
.enumerate()
.filter_map(|(idx, (width, img))| {
let maybe_img =
Self::render_single_page(frame, img, Rect { width, ..img_area });
img_area.x += width;
maybe_img.map(|(img, pos)| KittyReadyToDisplay {
img,
page_num: idx + self.page,
pos,
display_loc: DisplayLocation::default()
})
})
.collect::<Vec<_>>();
// we want to set this at the very end so it doesn't get set somewhere halfway through and
// then the whole diffing thing messes it up
self.last_render.rect = size;
KittyDisplay::DisplayImages(to_display)
}
} }
} }
@@ -365,12 +460,13 @@ impl Tui {
} }
fn render_loading_in(frame: &mut Frame<'_>, area: Rect) { fn render_loading_in(frame: &mut Frame<'_>, area: Rect) {
let loading_str = "Loading..."; const LOADING_STR: &str = "Loading...";
let inner_space = Layout::horizontal([Constraint::Length(loading_str.len() as u16)]) let inner_space =
.flex(Flex::Center) Layout::horizontal([Constraint::Length(const { LOADING_STR.len() as u16 })])
.split(area); .flex(Flex::Center)
.split(area);
let loading_span = Span::styled(loading_str, Style::new().fg(Color::Cyan)); let loading_span = Span::styled(LOADING_STR, Style::new().fg(Color::Cyan));
frame.render_widget(loading_span, inner_space[0]); frame.render_widget(loading_span, inner_space[0]);
} }
@@ -399,6 +495,8 @@ impl Tui {
PageChange::Prev => self.set_page(self.page.saturating_sub(diff)) PageChange::Prev => self.set_page(self.page.saturating_sub(diff))
} }
// Yes these conversions could wrap around if you have > isize::MAX pages, but we already
// decided that you deserve to suffer if you have more than u32::MAX pages, so that's fine.
match self.page as isize - old as isize { match self.page as isize - old as isize {
0 => None, 0 => None,
_ => Some(InputAction::JumpingToPage(self.page)) _ => Some(InputAction::JumpingToPage(self.page))
@@ -532,17 +630,11 @@ impl Tui {
} }
pub fn handle_event(&mut self, ev: &Event) -> Option<InputAction> { pub fn handle_event(&mut self, ev: &Event) -> Option<InputAction> {
fn jump_to_page( fn jump_to_page(page: &mut usize, rect: &mut Rect, new_page: usize) -> InputAction {
page: &mut usize, *page = new_page;
rect: &mut Rect, // Make sure we re-render
new_page: Option<usize> *rect = Rect::default();
) -> Option<InputAction> { InputAction::JumpingToPage(new_page)
new_page.map(|new_page| {
*page = new_page;
// Make sure we re-render
*rect = Rect::default();
InputAction::JumpingToPage(new_page)
})
} }
match ev { match ev {
@@ -560,6 +652,12 @@ impl Tui {
if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) = if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) =
self.bottom_msg self.bottom_msg
{ {
if c == 'g' && self.is_kitty {
self.update_zoom(|z| z.cell_pan_from_top = 0);
self.set_msg(MessageSetting::Pop);
return Some(InputAction::Redraw);
}
return c.to_digit(10).map(|input_num| { return c.to_digit(10).map(|input_num| {
*page = (*page * 10) + input_num as usize; *page = (*page * 10) + input_num as usize;
InputAction::Redraw InputAction::Redraw
@@ -593,30 +691,38 @@ impl Tui {
'n' if self.page < self.rendered.len() - 1 => { 'n' if self.page < self.rendered.len() - 1 => {
// TODO: If we can't find one, then maybe like block until we've verified // TODO: If we can't find one, then maybe like block until we've verified
// all the pages have been checked? // all the pages have been checked?
let next_page = self.rendered[(self.page + 1)..] self.rendered[(self.page + 1)..]
.iter() .iter()
.enumerate() .enumerate()
.find_map(|(idx, p)| { .find_map(|(idx, p)| {
p.num_results p.num_results
.is_some_and(|num| num > 0) .is_some_and(|num| num > 0)
.then_some(self.page + 1 + idx) .then_some(self.page + 1 + idx)
}); })
.map(|next_page| {
jump_to_page(&mut self.page, &mut self.last_render.rect, next_page) jump_to_page(
} &mut self.page,
'N' if self.page > 0 => { &mut self.last_render.rect,
let prev_page = self.rendered[..(self.page)] next_page
.iter() )
.rev() })
.enumerate()
.find_map(|(idx, p)| {
p.num_results
.is_some_and(|num| num > 0)
.then_some(self.page - (idx + 1))
});
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
} }
'N' if self.page > 0 => self.rendered[..(self.page)]
.iter()
.rev()
.enumerate()
.find_map(|(idx, p)| {
p.num_results
.is_some_and(|num| num > 0)
.then_some(self.page - (idx + 1))
})
.map(|prev_page| {
jump_to_page(
&mut self.page,
&mut self.last_render.rect,
prev_page
)
}),
'z' if key.modifiers.contains(KeyModifiers::CONTROL) => { 'z' if key.modifiers.contains(KeyModifiers::CONTROL) => {
// [todo] better error handling here? // [todo] better error handling here?
@@ -624,7 +730,8 @@ impl Tui {
execute!( execute!(
&mut backend, &mut backend,
LeaveAlternateScreen, LeaveAlternateScreen,
crossterm::cursor::Show crossterm::cursor::Show,
crossterm::event::DisableMouseCapture
) )
.unwrap(); .unwrap();
disable_raw_mode().unwrap(); disable_raw_mode().unwrap();
@@ -638,7 +745,8 @@ impl Tui {
execute!( execute!(
&mut backend, &mut backend,
EnterAlternateScreen, EnterAlternateScreen,
crossterm::cursor::Hide crossterm::cursor::Hide,
crossterm::event::EnableMouseCapture
) )
.unwrap(); .unwrap();
@@ -654,23 +762,24 @@ impl Tui {
self.last_render.rect = Rect::default(); self.last_render.rect = Rect::default();
Some(InputAction::SwitchRenderZoom(f_or_f)) Some(InputAction::SwitchRenderZoom(f_or_f))
} }
'o' if self.is_kitty => self.update_zoom(|z| 'o' if self.is_kitty =>
// TODO: for now, we don't let people zoom in past fill-screen self.update_zoom(|z| z.level = z.level.saturating_add(1)),
z.level = z.level.saturating_add(1).min(0)),
'O' if self.is_kitty => 'O' if self.is_kitty =>
self.update_zoom(|z| z.level = z.level.saturating_sub(1)), self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
'L' if self.is_kitty => self.update_zoom(|z| { 'L' if self.is_kitty => self.update_zoom(|z| {
z.cell_pan_from_left = z.cell_pan_from_left.saturating_add(1) z.cell_pan_from_left = z.cell_pan_from_left.saturating_add(1);
}), }),
'H' if self.is_kitty => self.update_zoom(|z| { 'H' if self.is_kitty => self.update_zoom(|z| {
z.cell_pan_from_left = z.cell_pan_from_left.saturating_sub(1) z.cell_pan_from_left = z.cell_pan_from_left.saturating_sub(1);
}), }),
'J' if self.is_kitty => self.update_zoom(|z| { 'J' if self.is_kitty => self.update_zoom(|z| {
z.cell_pan_from_top = z.cell_pan_from_top.saturating_add(1) z.cell_pan_from_top = z.cell_pan_from_top.saturating_add(1);
}), }),
'K' if self.is_kitty => self.update_zoom(|z| { 'K' if self.is_kitty => self.update_zoom(|z| {
z.cell_pan_from_top = z.cell_pan_from_top.saturating_sub(1) z.cell_pan_from_top = z.cell_pan_from_top.saturating_sub(1);
}), }),
'G' if self.is_kitty =>
self.update_zoom(|z| z.cell_pan_from_top = u16::MAX),
_ => None _ => None
} }
} }
@@ -684,9 +793,11 @@ impl Tui {
None None
} }
KeyCode::Right => self.change_page(PageChange::Next, ChangeAmount::Single), KeyCode::Right => self.change_page(PageChange::Next, ChangeAmount::Single),
KeyCode::Down => self.change_page(PageChange::Next, ChangeAmount::WholeScreen), KeyCode::Down | KeyCode::PageDown =>
self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single), KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single),
KeyCode::Up => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), KeyCode::Up | KeyCode::PageUp =>
self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
KeyCode::Esc => match (self.showing_help_msg, &self.bottom_msg) { KeyCode::Esc => match (self.showing_help_msg, &self.bottom_msg) {
(false, BottomMessage::Help) => Some(InputAction::QuitApp), (false, BottomMessage::Help) => Some(InputAction::QuitApp),
_ => { _ => {
@@ -754,27 +865,42 @@ impl Tui {
_ => None _ => None
} }
} }
Event::Mouse(mouse) => match mouse.kind { Event::Mouse(mouse) => {
MouseEventKind::ScrollRight => if mouse.modifiers.contains(KeyModifiers::CONTROL)
self.change_page(PageChange::Next, ChangeAmount::Single), && self.is_kitty
MouseEventKind::ScrollDown => && self.zoom.is_some()
self.change_page(PageChange::Next, ChangeAmount::WholeScreen), {
MouseEventKind::ScrollLeft => match mouse.kind {
self.change_page(PageChange::Prev, ChangeAmount::Single), MouseEventKind::ScrollUp =>
MouseEventKind::ScrollUp => self.update_zoom(|z| z.level = z.level.saturating_add(1).min(0)),
self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), MouseEventKind::ScrollDown =>
_ => None self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
}, _ => None
}
} else {
match mouse.kind {
MouseEventKind::ScrollRight =>
self.change_page(PageChange::Next, ChangeAmount::Single),
MouseEventKind::ScrollDown =>
self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
MouseEventKind::ScrollLeft =>
self.change_page(PageChange::Prev, ChangeAmount::Single),
MouseEventKind::ScrollUp =>
self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
_ => None
}
}
}
Event::Resize(_, _) => Some(InputAction::Redraw), Event::Resize(_, _) => Some(InputAction::Redraw),
_ => None _ => None
} }
} }
// I want this to always return 0 'cause I just use it to return from `Self::handle_event`] // I want this to always return an option 'cause I just use it to return from `Self::handle_event`
#[expect(clippy::unnecessary_wraps)] #[expect(clippy::unnecessary_wraps)]
fn update_zoom(&mut self, f: impl FnOnce(&mut Zoom)) -> Option<InputAction> { fn update_zoom(&mut self, f: impl FnOnce(&mut Zoom)) -> Option<InputAction> {
if let Some(z) = &mut self.zoom { if let Some(z) = &mut self.zoom {
f(z) f(z);
} }
self.last_render.rect = Rect::default(); self.last_render.rect = Rect::default();
Some(InputAction::Redraw) Some(InputAction::Redraw)
@@ -830,11 +956,24 @@ impl Tui {
.border_set(border::ROUNDED) .border_set(border::ROUNDED)
.border_style(Color::Blue); .border_style(Color::Blue);
let help_span = Text::raw(HELP_PAGE); let help_sections = [
Text::from(HELP_PAGE),
// just some spacing
Text::from(""),
if self.is_kitty {
Text::from(KITTY_HELP)
} else {
Text::from("Not using kitty, kitty-specific keybindings hidden")
.style(Color::DarkGray)
}
];
let max_w: u16 = HELP_PAGE let max_w: u16 = help_sections
.lines() .iter()
.map(str::len) .flat_map(|section| section.lines.as_slice())
// We don't really need full unicode-width since we're using all ascii for the help
// pages, but this is the function they give us.
.map(Line::width)
.max() .max()
.unwrap_or_default() .unwrap_or_default()
.try_into() .try_into()
@@ -849,39 +988,60 @@ impl Tui {
let block_area = Layout::vertical([ let block_area = Layout::vertical([
Constraint::Fill(1), Constraint::Fill(1),
Constraint::Length(u16::try_from(HELP_PAGE.lines().count()).unwrap() + 4), Constraint::Length(
u16::try_from(help_sections.iter().map(|s| s.lines.len()).sum::<usize>()).unwrap()
+ 4
),
Constraint::Fill(1) Constraint::Fill(1)
]) ])
.split(layout[1]); .split(layout[1]);
let block_inner = block.inner(block_area[1]); let mut block_inner = block.inner(block_area[1]);
frame.render_widget(block, block_area[1]); frame.render_widget(block, block_area[1]);
frame.render_widget(help_span, block_inner);
for section in help_sections {
let section_lines = section.lines.len();
let span = Paragraph::new(section).wrap(Wrap { trim: false });
frame.render_widget(span, block_inner);
block_inner.y += u16::try_from(section_lines).unwrap();
}
} }
} }
static HELP_PAGE: &str = "\ static HELP_PAGE: &str = "\
l, h, left, right: l, h, left, right:
Go forward/backwards a single page Go forward/backwards a single page
j, k, down, up: j, k, down, up:
Go forwards/backwards a screen's worth of pages Go forwards/backwards a screen's worth of pages
q, esc: q, esc:
Quit Quit
g: g:
Go to specific page (type numbers after 'g') Go to specific page (type numbers after 'g')
/: /:
Search Search
n, N: n, N:
Next/Previous search result Next/Previous search result
i: i:
Invert colors Invert colors
f: f:
Remove borders/fullscreen Remove borders/fullscreen
?: ?:
Show this page Show this page
ctrl+z: ctrl+z:
Suspend & background tdf \ Suspend & background tdf \
";
static KITTY_HELP: &str = "\
When using Kitty Protocol:
z:
Toggle between fill-screen and fit-screen
o/O (when on fill-screen):
Zoom in and out, respectively
gg/G (when on fill-screen):
Scroll to top/bottom of page
H, J, K, L (when zoomed in):
Pan direction around page
"; ";
pub enum InputAction { pub enum InputAction {