Compare commits

...

32 Commits

Author SHA1 Message Date
itsjunetime 134ba601fa Final adjustments to conform to mupdf changes 2025-02-19 09:39:51 -07:00
itsjunetime 3a264a0ddb perftools in ci 2025-02-19 09:27:12 -07:00
itsjunetime 85857890ed fontconfig in CI 2025-02-19 09:19:28 -07:00
itsjunetime c1c410ebe6 Remove unnecessary CI steps? 2025-02-19 09:15:20 -07:00
itsjunetime 34047ca106 Fix searching hehe 2025-02-19 09:13:54 -07:00
itsjunetime 3452294f59 Update deps 2025-02-16 17:13:01 -07:00
itsjunetime d22aa4596d Switch to git dependency for my fixes 2025-02-14 12:31:15 -07:00
itsjunetime 6e5bb0bdc5 Make features more modular and call search more easily 2025-02-09 15:20:51 -07:00
itsjunetime 7b68fe6b33 Remove some more dead code 2025-02-07 13:03:06 -07:00
itsjunetime a44dba20a7 Change back to no resizing and don't include alpha channel in conversion 2025-02-07 10:24:08 -07:00
itsjunetime d6102de3c6 Initial implementation of attempted mupdf rewrite 2025-02-06 11:14:47 -07:00
itsjunetime e123351079 Implement Ctrl+Z functionality to suspend for job control 2025-01-16 14:12:21 -07:00
itsjunetime 490b66b273 Update ratatui dependencies 2025-01-01 16:53:29 -07:00
itsjunetime a2b728fae3 Update deps and release 0.2.0 2024-12-03 21:25:18 -07:00
itsjunetime 0129c498c2 Fix document reloading with delete-then-write editors and redo BottomMessage updating to work better 2024-12-01 13:19:18 -07:00
June b9a12650c6 Relicense to GPLv3 (#30)
* Relicense to GPLv3 since poppler is GPL and we must not violate that license

* Add note to README that contributions will be licensed as MPL-2.0
2024-12-01 11:30:33 -07:00
itsjunetime 65e1f1a205 Switch to mimalloc 2024-11-27 18:57:39 -07:00
itsjunetime cc46791627 Update Changelog to reflect contribution from Kriejstal 2024-11-20 09:32:52 -07:00
June 9cf4a8e0d8 Misc Fixes (#36)
* - Update deps
- Explicitly run benches in CI, specifically only adobe_example pdf to make it quicker
- Render bottom message from Cow to avoid extra allocations
- Fix issue with hitting esc after jumping around pdf

* Install perftools to get criterion compiling

* Install libunwind-dev to get perftools installing

* Build with poppler 23.10 instead of .12 to maybe prevent segfault in CI

* Go back down to 23_7 poppler?

* Maybe more apt installs will get CI to work

* Build *with* boost?
2024-11-20 09:31:26 -07:00
June 25d98c3776 Merge pull request #31 from Kreijstal/main
some CI checks
2024-11-19 21:23:39 -07:00
June 03c2f381d9 Add format check and elevate clippy warnings to errors 2024-11-19 21:23:21 -07:00
June eb5ee99eec Add build step back to ensure linking works 2024-11-19 21:22:57 -07:00
Kreijstal 34b42cb1b2 Update .github/workflows/rust.yml
change build for clippy

Co-authored-by: June <61218022+itsjunetime@users.noreply.github.com>
2024-11-17 09:12:08 +01:00
Kreijstal e3ccb26d66 Update .github/workflows/rust.yml
Removing verbose it's okay, I'm not sure if cargo test tests linking the same binary as cargo build. So I'm not sure if it should be tested, furthermore maybe it makes sense to test in release mode rather than debug mode?

Co-authored-by: June <61218022+itsjunetime@users.noreply.github.com>
2024-11-17 07:46:37 +01:00
itsjunetime 1aa26b8e8c Manually enable opinionated set of clippy lints 2024-11-16 22:03:31 -07:00
Kreijstal 1402db3eba only libpoppler 23 is supported which doesn't come with ubuntu 2024-11-16 12:12:04 +01:00
Kreijstal 2d43c1e513 Create rust.yml
Adding sccache for speedup
2024-11-16 11:27:55 +01:00
itsjunetime 40d46f1e2d Make tdf run on stable with --no-default-features 2024-11-15 14:14:54 -07:00
itsjunetime 927a9cb587 Update ratatui deps 2024-11-13 10:16:05 -07:00
itsjunetime e51e9d3464 Add --r-to-l and --max-wide flags to cli args 2024-11-03 16:41:58 -07:00
itsjunetime 7c13054383 Fix a few more small clippy issues 2024-10-26 15:45:20 -06:00
itsjunetime b1e26bc96b Add fields to Cargo.toml and add CHANGELOG.md 2024-10-26 15:34:11 -06:00
16 changed files with 3256 additions and 1258 deletions
+38
View File
@@ -0,0 +1,38 @@
name: Rust
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Setup sccache
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
uses: mozilla-actions/sccache-action@v0.0.6
- name: Configure sccache
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
run: |
echo "SCCACHE_GHA_ENABLED=true" >> $GITHUB_ENV
echo "RUSTC_WRAPPER=sccache" >> $GITHUB_ENV
- name: Install build dependencies
run: |
sudo apt-get update
sudo apt-get install -y libfontconfig1-dev libgoogle-perftools-dev google-perftools
- uses: actions/checkout@v4
- name: Clippy
run: cargo clippy -- -D warnings
- name: Check fmt
run: cargo fmt -- --check
- name: Run tests
run: cargo test --benches -- adobe_example
- name: Build
run: cargo build
+22
View File
@@ -0,0 +1,22 @@
# Unreleased
- Update ratatui(-image) dependencies
- Enable Ctrl+Z/Suspend functionality
- Rewrite with mupdf as the backend for much better performance and rendering quality
# v0.2.0
- Add `--r-to-l` flag to support displaying pdfs that read from right to left
- Add `--max-wide` flag to restrict amount of pages that can appear on the screen at a time
- Small internal changes to accomodate a few more clippy lints
- Update `ratatui` and `ratatui-image` git dependencies to latest upstream
- Move `ratatui-image/vb64` support under `nightly` feature, enabled by default
- Fixed a bug where jumping to a page out of range could result in weird `esc` key behavior
- Added CI ([#31](https://github.com/itsjunetime/tdf/pull/31), thank you [@Kriejstal](https://github.com/Kreijstal))
- Changed global allocator to [`mimalloc`](https://github.com/purpleprotocol/mimalloc_rust) for slightly improved performance
- Fixed issue with document reloading not working when files are intermedially deleted
- Fixed a lot of weirdness with bottom message layering/updating
# v0.1.0
Initial tag :)
Generated
+1898 -458
View File
File diff suppressed because it is too large Load Diff
+119 -13
View File
@@ -1,34 +1,44 @@
[package] [package]
name = "tdf" name = "tdf-viewer"
version = "0.1.0" version = "0.2.0"
authors = ["June Welker <junewelker@gmail.com>"]
edition = "2021" edition = "2021"
license = "MPL-2.0" description = "A terminal viewer for PDFs"
readme = "README.md"
homepage = "https://github.com/itsjunetime/tdf"
repository = "https://github.com/itsjunetime/tdf"
license = "AGPL-3.0-only"
keywords = ["pdf", "tui", "cli", "terminal"]
categories = ["command-line-utilities", "text-processing", "visualization"]
default-run = "tdf" default-run = "tdf"
[[bin]] [[bin]]
name = "tdf" name = "tdf"
path = "src/main.rs"
# lib only exists for benching # lib only exists for benching
[lib] [lib]
name = "tdf" name = "tdf"
[dependencies] [dependencies]
poppler-rs = { version = "0.24.1", default-features = false, features = ["v23_7"] }
cairo-rs = { version = "0.20.0", default-features = false, features = ["png"] }
# 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 # 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
ratatui = { git = "https://github.com/itsjunetime/ratatui.git" } ratatui = { git = "https://github.com/itsjunetime/ratatui.git" }
# ratatui = { path = "./ratatui" } # ratatui = { path = "./ratatui/ratatui" }
# 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 Box<dyn ratatui_image::Protocol>. It also just includes a few more features that I'm waiting on main to upstream # 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
ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", branch = "vb64_on_personal", features = ["rustix", "vb64"], default-features = false } ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", branch = "vb64_on_personal", default-features = false }
# ratatui-image = { path = "./ratatui-image", features = ["rustix", "vb64"], default-features = false } # ratatui-image = { path = "./ratatui-image", features = ["vb64"], default-features = false }
crossterm = { version = "0.28.1", features = ["event-stream"] } crossterm = { version = "0.28.1", features = ["event-stream"] }
image = { version = "0.25.1", features = ["png", "rayon"], default-features = false } image = { version = "0.25.1", features = ["pnm", "rayon"], default-features = false }
notify = { version = "7.0.0", features = ["crossbeam-channel"] } notify = { version = "8.0.0", features = ["crossbeam-channel"] }
tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] }
futures-util = { version = "0.3.30", default-features = false } futures-util = { version = "0.3.30", default-features = false }
glib = "0.20.0"
itertools = "*" itertools = "*"
flume = { version = "0.11.0", default-features = false, features = ["async"] } flume = { version = "0.11.0", default-features = false, features = ["async"] }
xflags = "0.4.0-pre.2"
mimalloc = "0.1.43"
nix = { version = "0.29.0", features = ["signal"] }
mupdf = { git = "https://github.com/itsjunetime/mupdf-rs", branch = "remove_debug_print", default-features = false, features = ["svg", "system-fonts", "img"] }
rayon = { version = "*", default-features = false }
# for tracing with tokio-console # for tracing with tokio-console
console-subscriber = { version = "0.4.0", optional = true } console-subscriber = { version = "0.4.0", optional = true }
@@ -38,8 +48,11 @@ inherits = "release"
lto = "fat" lto = "fat"
[features] [features]
default = [] default = ["nightly"]
nightly = ["ratatui-image/vb64"]
tracing = ["tokio/tracing", "dep:console-subscriber"] tracing = ["tokio/tracing", "dep:console-subscriber"]
epub = ["mupdf/epub"]
cbz = ["mupdf/cbz"]
[dev-dependencies] [dev-dependencies]
criterion = { version = "0.5.1", features = ["async_tokio"] } criterion = { version = "0.5.1", features = ["async_tokio"] }
@@ -52,3 +65,96 @@ harness = false
[[bin]] [[bin]]
name = "for_profiling" name = "for_profiling"
path = "./benches/for_profiling.rs" path = "./benches/for_profiling.rs"
[lints.clippy]
uninlined_format_args = "warn"
redundant_closure_for_method_calls = "warn"
cast_lossless = "warn"
single_char_pattern = "warn"
manual_let_else = "warn"
ignored_unit_patterns = "warn"
range_plus_one = "warn"
unreadable_literal = "warn"
redundant_else = "warn"
assigning_clones = "warn"
bool_to_int_with_if = "warn"
borrow_as_ptr = "warn"
cast_ptr_alignment = "warn"
checked_conversions = "warn"
copy_iterator = "warn"
default_trait_access = "warn"
doc_link_with_quotes = "warn"
empty_enum = "warn"
explicit_into_iter_loop = "warn"
explicit_iter_loop = "warn"
filter_map_next = "warn"
flat_map_option = "warn"
fn_params_excessive_bools = "warn"
from_iter_instead_of_collect = "warn"
implicit_clone = "warn"
index_refutable_slice = "warn"
inefficient_to_string = "warn"
invalid_upcast_comparisons = "warn"
iter_filter_is_ok = "warn"
iter_filter_is_some = "warn"
iter_not_returning_iterator = "warn"
large_futures = "warn"
large_stack_arrays = "warn"
large_types_passed_by_value = "warn"
linkedlist = "warn"
macro_use_imports = "warn"
manual_assert = "warn"
manual_instant_elapsed = "warn"
manual_is_power_of_two = "warn"
manual_is_variant_and = "warn"
manual_ok_or = "warn"
manual_string_new = "warn"
many_single_char_names = "warn"
manual_unwrap_or = "warn"
match_on_vec_items = "warn"
match_same_arms = "warn"
match_wildcard_for_single_variants = "warn"
maybe_infinite_iter = "warn"
mismatching_type_param_order = "warn"
missing_fields_in_debug = "warn"
mut_mut = "warn"
needless_bitwise_bool = "warn"
needless_continue = "warn"
needless_for_each = "warn"
needless_pass_by_value = "warn"
needless_raw_string_hashes = "warn"
no_effect_underscore_binding = "warn"
no_mangle_with_rust_abi = "warn"
option_as_ref_cloned = "warn"
option_option = "warn"
ptr_as_ptr = "warn"
ptr_cast_constness = "warn"
range_minus_one = "warn"
ref_as_ptr = "warn"
ref_binding_to_reference = "warn"
ref_option = "warn"
ref_option_ref = "warn"
return_self_not_must_use = "warn"
same_functions_in_if_condition = "warn"
should_panic_without_expect = "warn"
similar_names = "warn"
stable_sort_primitive = "warn"
str_split_at_newline = "warn"
struct_excessive_bools = "warn"
struct_field_names = "warn"
transmute_ptr_to_ptr = "warn"
trivially_copy_pass_by_ref = "warn"
unicode_not_nfc = "warn"
unnecessary_box_returns = "warn"
unnecessary_join = "warn"
unnecessary_literal_bound = "warn"
unnecessary_wraps = "warn"
unnested_or_patterns = "warn"
unused_async = "warn"
unused_self = "warn"
used_underscore_binding = "warn"
used_underscore_items = "warn"
zero_sized_map_values = "warn"
[patch.crates-io]
pathfinder_simd = { git = "https://github.com/itsjunetime/pathfinder.git" }
+661 -373
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -14,7 +14,7 @@ Designed to be performant, very responsive, and work well with even very large P
- Reactive layout - Reactive layout
## To Build ## To Build
First, you need to install the system dependencies. This includes packages such as (but not limited to) `cairo`, `gtk`, and `poppler`. If you're on linux, these will probably show up in your package manager as something like `libcairo-devel` or `cairo-dev`. First, you need to install the system dependencies. This will generally only include `libfontconfig`. If you're on linux, these will probably show up in your package manager as something like `libfontconfig1-devel` or `libfontconfig-dev`.
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: 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:
@@ -29,3 +29,5 @@ I dunno. Just for fun, mostly.
## Can I contribute? ## Can I contribute?
Yeah, sure. Please do. Yeah, sure. Please do.
Please note, though, that all contributions will be treated as licensed under MPL-2.0.
+6 -5
View File
@@ -71,7 +71,7 @@ pub async fn render_first_page(path: impl AsRef<Path>) {
} = start_all_rendering(path); } = start_all_rendering(path);
// 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(|p| p.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, &mut to_converter_tx);
@@ -94,14 +94,15 @@ async fn render_all_files(path: &'static str) -> Vec<PageInfo> {
while let Some(info) = from_render_rx.next().await { while let Some(info) = from_render_rx.next().await {
match info.expect("Renderer ran into an error while rendering") { match info.expect("Renderer ran into an error while rendering") {
RenderInfo::Reloaded => (),
RenderInfo::NumPages(num) => fill_default(&mut pages, num), RenderInfo::NumPages(num) => fill_default(&mut pages, num),
RenderInfo::Page(page) => { RenderInfo::Page(page) => {
let num = page.page; let num = page.page_num;
pages[num] = Some(page); pages[num] = Some(page);
} }
}; };
if pages.iter().all(|p| p.is_some()) { if pages.iter().all(Option::is_some) {
break; break;
} }
} }
@@ -136,7 +137,7 @@ async fn convert_all_files(files: Vec<PageInfo>) {
} }
} }
while converted.iter().any(|p| p.is_none()) { while converted.iter().any(Option::is_none) {
let page = from_converter_rx let page = from_converter_rx
.next() .next()
.await .await
@@ -157,7 +158,7 @@ impl 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) {
let file = format!( let file = format!(
"./{}-{}.profile", "./{}-{}.profile",
benchmark_id.replace("/", "-"), benchmark_id.replace('/', "-"),
SystemTime::now() SystemTime::now()
.duration_since(UNIX_EPOCH) .duration_since(UNIX_EPOCH)
.unwrap() .unwrap()
+7 -5
View File
@@ -21,6 +21,8 @@ pub fn handle_renderer_msg(
to_converter_tx.send(ConverterMsg::NumPages(num)).unwrap(); to_converter_tx.send(ConverterMsg::NumPages(num)).unwrap();
} }
Ok(RenderInfo::Page(info)) => to_converter_tx.send(ConverterMsg::AddImg(info)).unwrap(), Ok(RenderInfo::Page(info)) => to_converter_tx.send(ConverterMsg::AddImg(info)).unwrap(),
// We can ignore the `Reloaded` variant 'cause that's only used to send info to the TUI
Ok(RenderInfo::Reloaded) => (),
Err(e) => panic!("Got error from renderer: {e:?}") Err(e) => panic!("Got error from renderer: {e:?}")
} }
} }
@@ -61,7 +63,7 @@ pub fn start_rendering_loop(
Sender<RenderNotif> Sender<RenderNotif>
) { ) {
let pathbuf = path.as_ref().canonicalize().unwrap(); let pathbuf = path.as_ref().canonicalize().unwrap();
let str_path = format!("file://{}", pathbuf.into_os_string().to_string_lossy()); let str_path = pathbuf.into_os_string().to_string_lossy().to_string();
let (to_render_tx, from_main_rx) = unbounded(); let (to_render_tx, from_main_rx) = unbounded();
let (to_main_tx, from_render_rx) = unbounded(); let (to_main_tx, from_render_rx) = unbounded();
@@ -75,7 +77,7 @@ pub fn start_rendering_loop(
width: columns * FONT_SIZE.0 width: columns * FONT_SIZE.0
}; };
std::thread::spawn(move || start_rendering(str_path, to_main_tx, from_main_rx, size)); std::thread::spawn(move || start_rendering(&str_path, to_main_tx, from_main_rx, size));
let main_area = Rect { let main_area = Rect {
x: 0, x: 0,
@@ -98,8 +100,8 @@ pub fn start_converting_loop(
let (to_converter_tx, from_main_rx) = unbounded(); let (to_converter_tx, from_main_rx) = unbounded();
let (to_main_tx, from_converter_rx) = unbounded(); let (to_main_tx, from_converter_rx) = unbounded();
let mut picker = Picker::new(FONT_SIZE); let mut picker = Picker::from_fontsize(FONT_SIZE);
picker.protocol_type = ProtocolType::Kitty; picker.set_protocol_type(ProtocolType::Kitty);
tokio::spawn(run_conversion_loop( tokio::spawn(run_conversion_loop(
to_main_tx, to_main_tx,
@@ -136,7 +138,7 @@ pub async fn render_doc(path: impl AsRef<Path>) {
to_render_tx to_render_tx
} = start_all_rendering(path); } = start_all_rendering(path);
while pages.is_empty() || pages.iter().any(|p| p.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, &mut to_converter_tx);
+1 -1
Submodule ratatui updated: a3fd887eaa...1166bebf44
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env bash
# 1. Pull the git source of poppler
# 2. cd poppler
# 3. git checkout poppler-23.07.0
# 4. mkdir build
# 5. cd build
# 6. cmake .. -DENABLE_GPGME=OFF -DENABLE_QT5=OFF -DENABLE_QT6=OFF -DENABLE_BOOST=OFF -DBUILD_SHARED_LIBS=OFF
# 7. cmake --build . --parallel $(nproc)
env SYSTEM_DEPS_POPPLER_GLIB_LINK=static \
SYSTEM_DEPS_POPPLER_GLIB_NO_PKG_CONFIG=1 \
SYSTEM_DEPS_POPPLER_GLIB_SEARCH_NATIVE=/path/to/poppler/build/glib \
SYSTEM_DEPS_POPPLER_GLIB_LIB=poppler-glib \
cargo perf --bin for_profiling --
+25 -12
View File
@@ -1,13 +1,14 @@
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use futures_util::stream::StreamExt; use futures_util::stream::StreamExt;
use image::ImageFormat; use image::DynamicImage;
use itertools::Itertools; use itertools::Itertools;
use ratatui_image::{picker::Picker, protocol::Protocol, Resize}; use ratatui_image::{picker::Picker, protocol::Protocol, Resize};
use rayon::iter::ParallelIterator;
use crate::renderer::{fill_default, PageInfo, RenderError}; use crate::renderer::{fill_default, PageInfo, RenderError};
pub struct ConvertedPage { pub struct ConvertedPage {
pub page: Box<dyn Protocol>, pub page: Protocol,
pub num: usize, pub num: usize,
pub num_results: usize pub num_results: usize
} }
@@ -54,13 +55,25 @@ pub async fn run_conversion_loop(
return Ok(None); return Ok(None);
}; };
let img_area = page_info.img_data.area; let mut dyn_img = image::load_from_memory_with_format(
&page_info.img_data.pixels,
image::ImageFormat::Pnm
)
.map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?;
let dyn_img = match dyn_img {
image::load_from_memory_with_format(&page_info.img_data.data, ImageFormat::Png) DynamicImage::ImageRgb8(ref mut img) =>
.map_err(|e| { for quad in &*page_info.result_rects {
RenderError::Render(format!("Couldn't convert Vec<u8> to DynamicImage: {e}")) img.par_enumerate_pixels_mut()
})?; .filter(|(x, y, _)| {
*x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_y
})
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
},
_ => unreachable!()
};
let img_area = page_info.img_data.cell_area;
// We don't actually want to Crop this image, but we've already // We don't actually want to Crop this image, but we've already
// verified (with the ImageSurface stuff) that the image is the correct // verified (with the ImageSurface stuff) that the image is the correct
@@ -69,7 +82,7 @@ pub async fn run_conversion_loop(
let txt_img = picker let txt_img = picker
.new_protocol(dyn_img, img_area, Resize::None) .new_protocol(dyn_img, img_area, Resize::None)
.map_err(|e| { .map_err(|e| {
RenderError::Render(format!( RenderError::Converting(format!(
"Couldn't convert DynamicImage to ratatui image: {e}" "Couldn't convert DynamicImage to ratatui image: {e}"
)) ))
})?; })?;
@@ -79,15 +92,15 @@ pub async fn run_conversion_loop(
Ok(Some(ConvertedPage { Ok(Some(ConvertedPage {
page: txt_img, page: txt_img,
num: page_info.page, num: page_info.page_num,
num_results: page_info.search_results num_results: page_info.result_rects.len()
})) }))
} }
fn handle_notif(msg: ConverterMsg, images: &mut Vec<Option<PageInfo>>, page: &mut usize) { fn handle_notif(msg: ConverterMsg, images: &mut Vec<Option<PageInfo>>, page: &mut usize) {
match msg { match msg {
ConverterMsg::AddImg(img) => { ConverterMsg::AddImg(img) => {
let page_num = img.page; let page_num = img.page_num;
images[page_num] = Some(img); images[page_num] = Some(img);
} }
ConverterMsg::NumPages(n_pages) => { ConverterMsg::NumPages(n_pages) => {
+2 -1
View File
@@ -1,4 +1,5 @@
#![feature(if_let_guard)] #[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
pub mod converter; pub mod converter;
pub mod renderer; pub mod renderer;
+110 -94
View File
@@ -1,12 +1,10 @@
#![feature(if_let_guard)]
use std::{ use std::{
ffi::OsString,
io::{stdout, Read, Write}, io::{stdout, Read, Write},
path::PathBuf, num::NonZeroUsize,
str::FromStr path::PathBuf
}; };
use converter::{run_conversion_loop, ConvertedPage, ConverterMsg};
use crossterm::{ use crossterm::{
execute, execute,
terminal::{ terminal::{
@@ -15,17 +13,14 @@ use crossterm::{
} }
}; };
use futures_util::{stream::StreamExt, FutureExt}; use futures_util::{stream::StreamExt, FutureExt};
use glib::{LogField, LogLevel, LogWriterOutput};
use notify::{Event, EventKind, RecursiveMode, Watcher}; use notify::{Event, EventKind, RecursiveMode, Watcher};
use ratatui::{backend::CrosstermBackend, Terminal}; use ratatui::{backend::CrosstermBackend, Terminal};
use ratatui_image::picker::Picker; use ratatui_image::picker::Picker;
use renderer::{RenderError, RenderInfo, RenderNotif}; use tdf::{
use tui::{InputAction, Tui}; converter::{run_conversion_loop, ConvertedPage, ConverterMsg},
renderer::{self, RenderError, RenderInfo, RenderNotif},
mod converter; tui::{BottomMessage, InputAction, MessageSetting, Tui}
mod renderer; };
mod skip;
mod tui;
// Dummy struct for easy errors in main // Dummy struct for easy errors in main
#[derive(Debug)] #[derive(Debug)]
@@ -44,43 +39,48 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(feature = "tracing")] #[cfg(feature = "tracing")]
console_subscriber::init(); console_subscriber::init();
let file = std::env::args() let flags = xflags::parse_or_exit! {
.nth(1) /// Display the pdf with the pages starting at the right hand size and moving left and
.ok_or("Program requires a file to process")?; /// adjust input keys to match
let path = PathBuf::from_str(&file)?.canonicalize()?; optional -r,--r-to-l r_to_l: bool
/// The maximum number of pages to display together, horizontally, at a time
optional -m,--max-wide max_wide: NonZeroUsize
/// PDF file to read
required file: PathBuf
};
let (watch_tx, render_rx) = flume::unbounded(); let path = flags.file.canonicalize()?;
let tui_tx = watch_tx.clone();
let (watch_to_render_tx, render_rx) = flume::unbounded();
let tui_tx = watch_to_render_tx.clone();
let (render_tx, tui_rx) = flume::unbounded(); let (render_tx, tui_rx) = flume::unbounded();
let watch_to_tui_tx = render_tx.clone(); let watch_to_tui_tx = render_tx.clone();
// we need to call this outside the recommended_watcher call because if we call it inside, that let mut watcher = notify::recommended_watcher(on_notify_ev(
// will be calling it from a thread not owned by the tokio runtime (since it's created by watch_to_tui_tx,
// calling thread::spawn) and that will cause a panic watch_to_render_tx,
let mut watcher = notify::recommended_watcher(move |res: notify::Result<Event>| match res { path.file_name()
// If we get an error here, and then an error sending, everything's going wrong. Just give .ok_or("Path does not have a last component??")?
// up lol. .to_owned()
Err(e) => watch_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) => match ev.kind {
EventKind::Access(_) => (),
EventKind::Remove(_) =>
drop(watch_to_tui_tx.send(Err(RenderError::Render("File was deleted".into())))),
// 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
// we don't handle the error here.
EventKind::Other | EventKind::Any | EventKind::Create(_) | EventKind::Modify(_) =>
drop(watch_tx.send(renderer::RenderNotif::Reload)),
}
})?;
// We're making this nonrecursive 'cause we're just watching a single file, so there's nothing // So we have to watch the parent directory of the file that we are interested in because the
// to recurse into // `notify` library works on inodes, and if the file is deleted, that inode is gone as well,
watcher.watch(&path, RecursiveMode::NonRecursive)?; // and then the notify library just gives up on trying to watch for the file reappearing. Imo
// they should start watching the parent directory if the file is deleted, and then wait for it
// to reappear and then begin watching it again, but whatever. It seems they've made their
// opinion on this clear
// (https://github.com/notify-rs/notify/issues/113#issuecomment-281836995) so whatever, guess
// we have to do this annoying workaround.
watcher.watch(
path.parent().expect("The root directory is not a PDF"),
RecursiveMode::NonRecursive
)?;
let file_path = format!("file://{}", path.clone().into_os_string().to_string_lossy()); // TODO: Handle non-utf8 file names? Maybe by constructing a CString and passing that in to the
// mupdf stuff instead of a rust string?
let file_path = path.clone().into_os_string().to_string_lossy().to_string();
let mut window_size = window_size()?; let mut window_size = window_size()?;
@@ -96,7 +96,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// read in the returned size until we hit a 't' (which indicates to us it's done) // read in the returned size until we hit a 't' (which indicates to us it's done)
let input_vec = std::io::stdin() let input_vec = std::io::stdin()
.bytes() .bytes()
.flat_map(|b| b.ok()) .filter_map(Result::ok)
.take_while(|b| *b != b't') .take_while(|b| *b != b't')
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@@ -134,17 +134,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 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 mut picker = Picker::new(( let picker = Picker::from_query_stdio()?;
window_size.width / window_size.columns,
window_size.height / window_size.rows
));
picker.guess_protocol();
// 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,
// since the methods we call in `start_rendering` will panic if called in an async context // since the methods we call in `start_rendering` will panic if called in an async context
std::thread::spawn(move || { std::thread::spawn(move || {
renderer::start_rendering(file_path, render_tx, render_rx, window_size) renderer::start_rendering(&file_path, render_tx, render_rx, window_size)
}); });
let mut ev_stream = crossterm::event::EventStream::new(); let mut ev_stream = crossterm::event::EventStream::new();
@@ -154,22 +150,16 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
tokio::spawn(run_conversion_loop(to_main, from_main, picker, 20)); tokio::spawn(run_conversion_loop(to_main, from_main, picker, 20));
let file_name = path let file_name = path.file_name().map_or_else(
.file_name() || "Unknown file".into(),
.map(|n| n.to_string_lossy()) |n| n.to_string_lossy().to_string()
.unwrap_or_else(|| "Unknown file".into()) );
.to_string(); let mut tui = Tui::new(file_name, flags.max_wide, flags.r_to_l.unwrap_or_default());
let mut tui = tui::Tui::new(file_name);
let backend = CrosstermBackend::new(std::io::stdout()); let backend = CrosstermBackend::new(std::io::stdout());
let mut term = Terminal::new(backend)?; let mut term = Terminal::new(backend)?;
term.skip_diff(true); term.skip_diff(true);
// poppler has some annoying logging (e.g. if you request a page index out-of-bounds of a
// document's pages, then it will return `None`, but still log to stderr with CRITICAL level),
// so we want to just ignore all logging since this is a tui app.
glib::log_set_writer_func(noop);
execute!( execute!(
term.backend_mut(), term.backend_mut(),
EnterAlternateScreen, EnterAlternateScreen,
@@ -177,62 +167,54 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)?; )?;
enable_raw_mode()?; enable_raw_mode()?;
let mut main_area = tui::Tui::main_layout(&term.get_frame()); let mut main_area = Tui::main_layout(&term.get_frame());
tui_tx.send(RenderNotif::Area(main_area[1]))?; tui_tx.send(RenderNotif::Area(main_area[1]))?;
let mut tui_rx = tui_rx.into_stream(); let mut tui_rx = tui_rx.into_stream();
let mut from_converter = from_converter.into_stream(); let mut from_converter = from_converter.into_stream();
loop { loop {
let mut needs_redraw = tokio::select! { let mut needs_redraw = true;
tokio::select! {
// First we check if we have any keystrokes // First we check if we have any keystrokes
Some(ev) = ev_stream.next().fuse() => { Some(ev) = ev_stream.next().fuse() => {
// If we can't get user input, just crash. // If we can't get user input, just crash.
let ev = ev.expect("Couldn't get any user input"); let ev = ev.expect("Couldn't get any user input");
match tui.handle_event(ev) { match tui.handle_event(&ev) {
None => false, None => needs_redraw = false,
Some(action) => { Some(action) => match action {
match action { InputAction::Redraw => (),
InputAction::Redraw => (), InputAction::QuitApp => break,
InputAction::QuitApp => break, InputAction::JumpingToPage(page) => {
InputAction::JumpingToPage(page) => { tui_tx.send(RenderNotif::JumpToPage(page))?;
tui_tx.send(RenderNotif::JumpToPage(page))?; to_converter.send(ConverterMsg::GoToPage(page))?;
to_converter.send(ConverterMsg::GoToPage(page))?; },
}, InputAction::Search(term) => tui_tx.send(RenderNotif::Search(term))?,
InputAction::Search(term) => tui_tx.send(RenderNotif::Search(term))?,
};
true
} }
} }
}, },
Some(renderer_msg) = tui_rx.next() => { Some(renderer_msg) = tui_rx.next() => {
match renderer_msg { match renderer_msg {
// if an Ok comes through, we know the error has been resolved ('cause it kinda Ok(render_info) => match render_info {
// bails whenever we run into an error) so just clear it RenderInfo::NumPages(num) => {
Ok(render_info) => { tui.set_n_pages(num);
match render_info { to_converter.send(ConverterMsg::NumPages(num))?;
RenderInfo::NumPages(num) => { },
tui.set_n_pages(num); RenderInfo::Page(info) => {
to_converter.send(ConverterMsg::NumPages(num))?; tui.got_num_results_on_page(info.page_num, info.result_rects.len());
}, to_converter.send(ConverterMsg::AddImg(info))?;
RenderInfo::Page(info) => { },
tui.got_num_results_on_page(info.page, info.search_results); RenderInfo::Reloaded => tui.set_msg(MessageSetting::Some(BottomMessage::Reloaded)),
to_converter.send(ConverterMsg::AddImg(info))?;
},
}
tui.set_bottom_msg(None);
}, },
Err(e) => tui.show_error(e), Err(e) => tui.show_error(e),
} }
true
} }
Some(img_res) = from_converter.next() => { Some(img_res) = from_converter.next() => {
match img_res { match img_res {
Ok(ConvertedPage { page, num, num_results }) => tui.page_ready(page, num, num_results), Ok(ConvertedPage { page, num, num_results }) => tui.page_ready(page, num, num_results),
Err(e) => tui.show_error(e), Err(e) => tui.show_error(e),
} }
true
}, },
}; };
@@ -261,6 +243,40 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(()) Ok(())
} }
fn noop(_: LogLevel, _: &[LogField<'_>]) -> LogWriterOutput { fn on_notify_ev(
LogWriterOutput::Handled to_tui_tx: flume::Sender<Result<RenderInfo, RenderError>>,
to_render_tx: flume::Sender<RenderNotif>,
file_name: OsString
) -> impl Fn(notify::Result<Event>) {
move |res| match res {
// 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(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 {
EventKind::Access(_) => (),
EventKind::Remove(_) => to_tui_tx
.send(Err(RenderError::Converting("File was deleted".into())))
.unwrap(),
// 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
// we don't handle the error here.
EventKind::Other | EventKind::Any | EventKind::Create(_) | EventKind::Modify(_) =>
to_render_tx.send(RenderNotif::Reload).unwrap(),
}
}
}
} }
+153 -165
View File
@@ -1,10 +1,9 @@
use std::thread; use std::{thread::sleep, time::Duration};
use cairo::{Antialias, Context, Format, Surface};
use crossterm::terminal::WindowSize; use crossterm::terminal::WindowSize;
use flume::{Receiver, SendError, Sender, TryRecvError}; use flume::{Receiver, SendError, Sender, TryRecvError};
use itertools::Itertools; use itertools::Itertools;
use poppler::{Color, Document, FindFlags, Page, Rectangle, SelectionStyle}; use mupdf::{Colorspace, Document, Matrix, Page, Pixmap};
use ratatui::layout::Rect; use ratatui::layout::Rect;
pub enum RenderNotif { pub enum RenderNotif {
@@ -17,28 +16,27 @@ pub enum RenderNotif {
#[derive(Debug)] #[derive(Debug)]
pub enum RenderError { pub enum RenderError {
Notify(notify::Error), Notify(notify::Error),
Doc(glib::Error), Doc(mupdf::error::Error),
// Don't like storing an error as a string but it needs to be Send to send to the main thread, Converting(String)
// and it's just going to be shown to the user, so whatever
Render(String)
} }
pub enum RenderInfo { pub enum RenderInfo {
NumPages(usize), NumPages(usize),
Page(PageInfo) Page(PageInfo),
Reloaded
} }
#[derive(Clone)] #[derive(Clone)]
pub struct PageInfo { pub struct PageInfo {
pub img_data: ImageData, pub img_data: ImageData,
pub page: usize, pub page_num: usize,
pub search_results: usize pub result_rects: Vec<HighlightRect>
} }
#[derive(Clone)] #[derive(Clone)]
pub struct ImageData { pub struct ImageData {
pub data: Vec<u8>, pub pixels: Vec<u8>,
pub area: Rect pub cell_area: Rect
} }
#[derive(Default)] #[derive(Default)]
@@ -55,7 +53,7 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
} }
} }
// this function has to be sync (non-async) because the poppler::Document needs to be held during // this function has to be sync (non-async) because the mupdf::Document needs to be held during
// most of it, but that's basically just a wrapper around `*c_void` cause it's just a binding to C // most of it, but that's basically just a wrapper around `*c_void` cause it's just a binding to C
// code, so it's !Send and thus can't be held across await points. So we can't call any of the // code, so it's !Send and thus can't be held across await points. So we can't call any of the
// async `send` or `recv` methods in this function body, since those create await points. Which // async `send` or `recv` methods in this function body, since those create await points. Which
@@ -64,21 +62,23 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
// Also we just kinda 'unwrap' all of the send/recv calls here 'cause if they return an error, that // Also we just kinda 'unwrap' all of the send/recv calls here 'cause if they return an error, that
// means the other side's disconnected, which means that the main thread has panicked, which means // means the other side's disconnected, which means that the main thread has panicked, which means
// we're done. // we're done.
// 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
// probably be more performant if accessed by-value instead of through a reference. Probably.
#[allow(clippy::needless_pass_by_value)]
pub fn start_rendering( pub fn start_rendering(
path: String, path: &str,
mut sender: Sender<Result<RenderInfo, RenderError>>, sender: Sender<Result<RenderInfo, RenderError>>,
receiver: Receiver<RenderNotif>, receiver: Receiver<RenderNotif>,
size: WindowSize size: WindowSize
) -> Result<(), SendError<Result<RenderInfo, RenderError>>> { ) -> Result<(), SendError<Result<RenderInfo, RenderError>>> {
// first, wait 'til we get told what the current starting area is so that we can set it to // first, wait 'til we get told what the current starting area is so that we can set it to
// know what to render to // know what to render to
let mut area; let mut area = loop {
loop {
if let RenderNotif::Area(r) = receiver.recv().unwrap() { if let RenderNotif::Area(r) = receiver.recv().unwrap() {
area = r; break r;
break;
} }
} };
// We want this outside of 'reload so that if the doc reloads, the search term that somebody // We want this outside of 'reload so that if the doc reloads, the search term that somebody
// set will still get highlighted in the reloaded doc // set will still get highlighted in the reloaded doc
@@ -89,27 +89,49 @@ pub fn start_rendering(
let col_w = size.width / size.columns; let col_w = size.width / size.columns;
let col_h = size.height / size.rows; let col_h = size.height / size.rows;
let mut stored_doc = None;
'reload: loop { 'reload: loop {
let doc = match Document::from_file(&path, None) { let doc = match Document::open(path) {
Err(e) => { Err(e) => {
// if there's an error, tell the main loop // if there's an error, tell the main loop
sender.send(Err(RenderError::Doc(e)))?; sender.send(Err(RenderError::Doc(e)))?;
// then wait for a reload notif (since what probably happened is that the file was
// temporarily removed to facilitate a save or something like that) match stored_doc {
while let Ok(msg) = receiver.recv() { Some(ref d) => d,
// and once that comes, just try to reload again None => {
if let RenderNotif::Reload = msg { // then wait for a reload notif (since what probably happened is that the file was
continue 'reload; // temporarily removed to facilitate a save or something like that)
while let Ok(msg) = receiver.recv() {
// and once that comes, just try to reload again
if let RenderNotif::Reload = msg {
continue 'reload;
}
}
// if that while let Ok ever fails and we exit out of that loop, the main thread is
// done, so we're fine to just return
return Ok(());
} }
} }
// if that while let Ok ever fails and we exit out of that loop, the main thread is
// done, so we're fine to just return
return Ok(());
} }
Ok(d) => d Ok(d) => {
if stored_doc.is_some() {
sender.send(Ok(RenderInfo::Reloaded))?;
}
&*stored_doc.insert(d)
}
};
let n_pages = match doc.page_count() {
Ok(n) => n as usize,
Err(e) => {
sender.send(Err(RenderError::Doc(e)))?;
// just basic backoff i think
sleep(Duration::from_secs(1));
continue 'reload;
}
}; };
let n_pages = doc.n_pages() as usize;
sender.send(Ok(RenderInfo::NumPages(n_pages)))?; sender.send(Ok(RenderInfo::NumPages(n_pages)))?;
// We're using this vec of bools to indicate which page numbers have already been rendered, // We're using this vec of bools to indicate which page numbers have already been rendered,
@@ -189,16 +211,16 @@ pub fn start_rendering(
.map(|(idx, p)| (start_point - (idx + 1), p)) .map(|(idx, p)| (start_point - (idx + 1), p))
); );
let area_w = area.width as f64 * col_w as f64; let area_w = f32::from(area.width) * f32::from(col_w);
let area_h = area.height as f64 * col_h as f64; let area_h = f32::from(area.height) * f32::from(col_h);
// we go through each page // we go through each page
for (num, rendered) in page_iter { for (num, rendered) in page_iter {
// we only want to continue if one of the following is met: // we only want to continue if one of the following is met:
// 1. It failed to render last time (we want to retry) // 1. It failed to render last time (we want to retry)
// 2. The `contained_term` is set to None (representing 'Unknown'), meaning that we // 2. The `contained_term` is set to None (representing 'Unknown'), meaning that we
// need to at least check if it contains the current term to see if it needs a // need to at least check if it contains the current term to see if it needs a
// re-render // re-render
if rendered.successful && rendered.contained_term.is_some() { if rendered.successful && rendered.contained_term.is_some() {
continue; continue;
} }
@@ -214,12 +236,12 @@ pub fn start_rendering(
// We know this is in range 'cause we're iterating over it but we still just want // We know this is in range 'cause we're iterating over it but we still just want
// to be safe // to be safe
let Some(page) = doc.page(num as i32) else { let page = match doc.load_page(num as i32) {
sender.send(Err(RenderError::Render(format!( Err(e) => {
"Couldn't get page {num} ({}) of doc?", sender.send(Err(RenderError::Doc(e)))?;
num as i32 continue;
))))?; }
continue; Ok(p) => p
}; };
let rendered_with_no_results = let rendered_with_no_results =
@@ -227,8 +249,8 @@ pub fn start_rendering(
// render the page // render the page
match render_single_page_to_ctx( match render_single_page_to_ctx(
page, &page,
&search_term, search_term.as_deref(),
rendered_with_no_results, rendered_with_no_results,
(area_w, area_h) (area_w, area_h)
) { ) {
@@ -241,26 +263,34 @@ pub fn start_rendering(
// we make a potentially incorrect assumption here that writing the context // we make a potentially incorrect assumption here that writing the context
// to a png won't fail, and mark that it all rendered correctly here before // to a png won't fail, and mark that it all rendered correctly here before
// spawning off the thread to do so and send it. // spawning off the thread to do so and send it.
rendered.contained_term = Some(ctx.num_results > 0); rendered.contained_term = Some(ctx.result_rects.is_empty());
rendered.successful = true; rendered.successful = true;
// if this is the page that the user is currently trying to look at, don't let cap = (ctx.pixmap.width()
// bother spawning off a thread to render it to a png - it'll only slow * ctx.pixmap.height() * u32::from(ctx.pixmap.n()))
// down the time til the user can see it (due to the overhead of creating a as usize;
// thread), but we still want to spawn threads to render the other pages let mut pixels = Vec::with_capacity(cap);
// since the effects of parallelizing that will be noticeable if the user if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) {
// tries to move through pages more quickly sender.send(Err(RenderError::Doc(e)))?;
if num == start_point { continue;
render_ctx_to_png(ctx, &mut sender, (col_w, col_h), num)?; };
} else {
let mut sender = sender.clone(); sender.send(Ok(RenderInfo::Page(PageInfo {
thread::spawn(move || { img_data: ImageData {
render_ctx_to_png(ctx, &mut sender, (col_w, col_h), num) pixels,
}); cell_area: Rect {
} x: 0,
y: 0,
width: (ctx.surface_w / f32::from(col_w)) as u16,
height: (ctx.surface_h / f32::from(col_h)) as u16
}
},
page_num: num,
result_rects: ctx.result_rects
})))?;
} }
// And if we got an error, then obviously we need to propagate that // And if we got an error, then obviously we need to propagate that
Err(e) => sender.send(Err(RenderError::Render(e)))? Err(e) => sender.send(Err(RenderError::Doc(e)))?
} }
} }
@@ -279,34 +309,37 @@ pub fn start_rendering(
} }
struct RenderedContext { struct RenderedContext {
surface: Surface, pixmap: Pixmap,
num_results: usize, surface_w: f32,
surface_width: f64, surface_h: f32,
surface_height: f64 result_rects: Vec<HighlightRect>
} }
/// SAFETY: I think this is safe because, although the backing struct for `Surface` does contain
/// pointers to like the cairo_backend_t struct that all the cairo stuff is using, that struct is
/// basically just a vtable, so accessing it from multiple threads *should* be safe since we're
/// just calling the same functions with different data. The only other thing it holds reference to
/// is a `cairo_device_t`, but that seems to be thread-safe because it's managed through ref counts
/// and a mutex. Also, as far as I can tell from reading the source code, write_to_png_stream (the
/// only function we call on this struct) doesn't access the device at all, so we should be fine
/// there.
/// We want this to be Send so that we can delegate the png writing to a separate thread (since
/// that's the thing that takes the most time, by far, in this app).
unsafe impl Send for RenderedContext {}
fn render_single_page_to_ctx( fn render_single_page_to_ctx(
page: Page, page: &Page,
search_term: &Option<String>, search_term: Option<&str>,
already_rendered_no_results: bool, already_rendered_no_results: bool,
(area_w, area_h): (f64, f64) (area_w, area_h): (f32, f32)
) -> Result<Option<RenderedContext>, String> { ) -> Result<Option<RenderedContext>, mupdf::error::Error> {
let mut result_rects = search_term let mut max_hits = 10;
.as_ref() let result_rects = loop {
.map(|term| page.find_text_with_options(term, FindFlags::DEFAULT | FindFlags::MULTILINE)) let rects = search_term
.unwrap_or_default(); .as_ref()
// mupdf allocates a buffer of the size we give it to try to fill it with results. If we
// pass in u32::MAX, it allocates too much memory to function. If we pass too small of a
// number in, we may miss out on some of the results. Ideally, we'd like to make a better
// interface than this, but we're stuck with this kinda ugly looping until we make sure
// that we've found every instance of it on this page.
.map(|term| page.search(term, max_hits))
.transpose()?
.unwrap_or_default();
if rects.len() < (max_hits as usize) {
break rects;
}
max_hits *= 2;
};
// If there are no search terms on this page, and we've already rendered it with no search // If there are no search terms on this page, and we've already rendered it with no search
// terms, then just return none to avoid this computation // terms, then just return none to avoid this computation
@@ -315,7 +348,8 @@ fn render_single_page_to_ctx(
} }
// then, get the size of the page // then, get the size of the page
let (p_width, p_height) = page.size(); let bounds = page.bounds()?;
let (p_width, p_height) = (bounds.x1 - bounds.x0, bounds.y1 - bounds.y0);
// and get its aspect ratio // and get its aspect ratio
let p_aspect_ratio = p_width / p_height; let p_aspect_ratio = p_width / p_height;
@@ -337,93 +371,47 @@ fn render_single_page_to_ctx(
area_h / p_height area_h / p_height
}; };
let surface_width = p_width * scale_factor; let surface_w = p_width * scale_factor;
let surface_height = p_height * scale_factor; let surface_h = p_height * scale_factor;
let surface = cairo::ImageSurface::create( let colorspace = Colorspace::device_rgb();
Format::Rgb16_565, let matrix = Matrix::new_scale(scale_factor, scale_factor);
// No matter how big you make these arguments, the image will be drawn at the same
// size. So if you make them really big, the image will be drawn on a quarter of it. If
// you make them really small, the image will cover more than all of the surface.
//
// However, that only stands as long as you don't scale the context that you place this
// surface into. If you scale the dimensions of this image by n, then scale the context
// by that same amount, then it'll still fit perfectly into the context, but be
// rendered at higher quality.
surface_width as i32,
surface_height as i32
)
.map_err(|e| format!("Couldn't create ImageSurface: {e}"))?;
surface.set_device_scale(scale_factor, scale_factor);
let ctx = Context::new(surface).map_err(|e| format!("Couldn't create Context: {e}"))?; let mut pixmap = page.to_pixmap(&matrix, &colorspace, 0.0, false)?;
// The default background color of PDFs (at least, I think) is white, so we need to set let (x_res, y_res) = pixmap.resolution();
// that as the background color, then paint, then render. let new_x = (x_res as f32 * scale_factor) as i32;
ctx.set_source_rgba(1.0, 1.0, 1.0, 1.0); let new_y = (y_res as f32 * scale_factor) as i32;
pixmap.set_resolution(new_x, new_y);
ctx.set_antialias(Antialias::None); let result_rects = result_rects
ctx.paint() .into_iter()
.map_err(|e| format!("Couldn't paint Context: {e}"))?; .map(|quad| {
page.render(&ctx); let ul_x = (quad.ul.x * scale_factor) as u32;
let ul_y = (quad.ul.y * scale_factor) as u32;
let num_results = result_rects.len(); let lr_x = (quad.lr.x * scale_factor) as u32;
let lr_y = (quad.lr.y * scale_factor) as u32;
if !result_rects.is_empty() { HighlightRect {
let mut highlight_color = Color::new(); ul_x,
highlight_color.set_red((u16::MAX / 5) * 4); ul_y,
highlight_color.set_green((u16::MAX / 5) * 4); lr_x,
lr_y
let mut old_rect = Rectangle::new(); }
for rect in result_rects.iter_mut() { })
// According to https://gitlab.freedesktop.org/poppler/poppler/-/issues/763, these rects .collect::<Vec<_>>();
// need to be corrected since they use different references as the y-coordinate base
rect.set_y1(p_height - rect.y1());
rect.set_y2(p_height - rect.y2());
page.render_selection(
&ctx,
rect,
&mut old_rect,
SelectionStyle::Glyph,
&mut Color::new(),
&mut highlight_color
);
}
}
Ok(Some(RenderedContext { Ok(Some(RenderedContext {
surface: ctx.target(), pixmap,
num_results, surface_w,
surface_width, surface_h,
surface_height result_rects
})) }))
} }
fn render_ctx_to_png( #[derive(Clone)]
ctx: RenderedContext, pub struct HighlightRect {
sender: &mut Sender<Result<RenderInfo, RenderError>>, pub ul_x: u32,
(col_w, col_h): (u16, u16), pub ul_y: u32,
page: usize pub lr_x: u32,
) -> Result<(), SendError<Result<RenderInfo, RenderError>>> { pub lr_y: u32
let mut img_data = Vec::with_capacity((ctx.surface_height * ctx.surface_width) as usize);
match ctx.surface.write_to_png(&mut img_data) {
Err(e) => sender.send(Err(RenderError::Render(format!(
"Couldn't write surface to png: {e}"
)))),
Ok(()) => sender.send(Ok(RenderInfo::Page(PageInfo {
img_data: ImageData {
data: img_data,
area: Rect {
width: ctx.surface_width as u16 / col_w,
height: ctx.surface_height as u16 / col_h,
x: 0,
y: 0
}
},
page,
search_results: ctx.num_results
})))
}
} }
+210 -116
View File
@@ -1,9 +1,16 @@
use std::{io::stdout, rc::Rc}; use std::{borrow::Cow, io::stdout, num::NonZeroUsize, rc::Rc};
use crossterm::{ use crossterm::{
event::{Event, KeyCode, MouseEventKind}, event::{Event, KeyCode, KeyModifiers, MouseEventKind},
execute, execute,
terminal::BeginSynchronizedUpdate terminal::{
disable_raw_mode, enable_raw_mode, BeginSynchronizedUpdate, EnterAlternateScreen,
LeaveAlternateScreen
}
};
use nix::{
sys::signal::{kill, Signal::SIGSTOP},
unistd::Pid
}; };
use ratatui::{ use ratatui::{
layout::{Constraint, Flex, Layout, Rect}, layout::{Constraint, Flex, Layout, Rect},
@@ -24,7 +31,8 @@ pub struct Tui {
// we use `prev_msg` to, for example, restore the 'search results' message on the bottom after // we use `prev_msg` to, for example, restore the 'search results' message on the bottom after
// jumping to a specific page // jumping to a specific page
prev_msg: Option<BottomMessage>, prev_msg: Option<BottomMessage>,
rendered: Vec<RenderedInfo> rendered: Vec<RenderedInfo>,
page_constraints: PageConstraints
} }
#[derive(Default, Debug)] #[derive(Default, Debug)]
@@ -42,7 +50,8 @@ pub enum BottomMessage {
Help, Help,
SearchResults(String), SearchResults(String),
Error(String), Error(String),
Input(InputCommand) Input(InputCommand),
Reloaded
} }
pub enum InputCommand { pub enum InputCommand {
@@ -50,12 +59,17 @@ pub enum InputCommand {
Search(String) Search(String)
} }
struct PageConstraints {
max_wide: Option<NonZeroUsize>,
r_to_l: bool
}
// 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
#[derive(Default)] #[derive(Default)]
struct RenderedInfo { struct RenderedInfo {
// The image, if it has been rendered by `Converter` to that struct // The image, if it has been rendered by `Converter` to that struct
img: Option<Box<dyn Protocol>>, img: Option<Protocol>,
// The number of results for the current search term that have been found on this page. None if // The number of results for the current search term that have been found on this page. None if
// we haven't checked this page yet // we haven't checked this page yet
// Also this isn't the most efficient representation of this value, but it's accurate, so like // Also this isn't the most efficient representation of this value, but it's accurate, so like
@@ -64,14 +78,15 @@ struct RenderedInfo {
} }
impl Tui { impl Tui {
pub fn new(name: String) -> Tui { pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool) -> Tui {
Self { Self {
name, name,
page: 0, page: 0,
prev_msg: None, prev_msg: None,
bottom_msg: BottomMessage::Help, bottom_msg: BottomMessage::Help,
last_render: LastRender::default(), last_render: LastRender::default(),
rendered: vec![] rendered: vec![],
page_constraints: PageConstraints { max_wide, r_to_l }
} }
} }
@@ -145,18 +160,18 @@ impl Tui {
let rendered_span = Span::styled(&rendered_str, Style::new().fg(Color::Cyan)); let rendered_span = Span::styled(&rendered_str, Style::new().fg(Color::Cyan));
frame.render_widget(rendered_span, bottom_layout[1]); frame.render_widget(rendered_span, bottom_layout[1]);
let (msg_str, color) = match self.bottom_msg { let (msg_str, color): (Cow<'_, str>, _) = match self.bottom_msg {
BottomMessage::Help => ( BottomMessage::Help => (
"/: Search, g: Go To Page, n: Next Search Result, N: Previous Search Result" "/: Search, g: Go To Page, n: Next Search Result, N: Previous Search Result".into(),
.to_string(),
Color::Blue Color::Blue
), ),
BottomMessage::Error(ref e) => (format!("Couldn't render a page: {e}"), Color::Red), BottomMessage::Error(ref e) => (e.as_str().into(), Color::Red),
BottomMessage::Input(ref input_state) => ( BottomMessage::Input(ref input_state) => (
match input_state { match input_state {
InputCommand::GoToPage(page) => format!("Go to: {page}"), InputCommand::GoToPage(page) => format!("Go to: {page}"),
InputCommand::Search(s) => format!("Search: {s}") InputCommand::Search(s) => format!("Search: {s}")
}, }
.into(),
Color::Blue Color::Blue
), ),
BottomMessage::SearchResults(ref term) => { BottomMessage::SearchResults(ref term) => {
@@ -174,10 +189,12 @@ impl Tui {
format!( format!(
"Results for '{term}': {num_found} (searched: {}%)", "Results for '{term}': {num_found} (searched: {}%)",
num_searched / self.rendered.len() num_searched / self.rendered.len()
), )
.into(),
Color::Blue Color::Blue
) )
} }
BottomMessage::Reloaded => ("Document was reloaded!".into(), Color::Blue)
}; };
let span = Span::styled(msg_str, Style::new().fg(color)); let span = Span::styled(msg_str, Style::new().fg(color));
@@ -196,15 +213,21 @@ impl Tui {
// here we calculate how many pages can fit in the available area. // here we calculate how many pages can fit in the available area.
let mut test_area_w = img_area.width; let mut test_area_w = img_area.width;
// go through our pages, starting at the first one we want to view // go through our pages, starting at the first one we want to view
let page_widths = self.rendered[self.page..] let mut page_widths = self.rendered[self.page..]
.iter() .iter()
// and get their indices (I know it's offset, we fix it down below when we actually // and get their indices (I know it's offset, we fix it down below when we actually
// render each page) // render each page)
.enumerate() .enumerate()
// and only take as many as are ready to be rendered // and only take as many as are ready to be rendered
.take_while(|(_, page)| page.img.is_some()) .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) // and map it to their width (in cells on the terminal, not pixels)
.flat_map(|(idx, page)| page.img.as_ref().map(|img| (idx, img.rect().width))) .filter_map(|(idx, page)| page.img.as_ref().map(|img| (idx, img.rect().width)))
// 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) => {
@@ -215,6 +238,10 @@ impl Tui {
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if self.page_constraints.r_to_l {
page_widths.reverse();
}
if page_widths.is_empty() { if page_widths.is_empty() {
// If none are ready to render, just show the loading thing // If none are ready to render, just show the loading thing
Self::render_loading_in(frame, img_area); Self::render_loading_in(frame, img_area);
@@ -252,7 +279,7 @@ impl Tui {
fn render_single_page(&mut self, frame: &mut Frame<'_>, page_idx: usize, img_area: Rect) { fn render_single_page(&mut self, frame: &mut Frame<'_>, page_idx: usize, img_area: Rect) {
match self.rendered[page_idx].img { match self.rendered[page_idx].img {
Some(ref page_img) => frame.render_widget(Image::new(&**page_img), img_area), Some(ref mut page_img) => frame.render_widget(Image::new(page_img), img_area),
None => Self::render_loading_in(frame, img_area) None => Self::render_loading_in(frame, img_area)
}; };
} }
@@ -268,12 +295,23 @@ impl Tui {
frame.render_widget(loading_span, inner_space[0]); frame.render_widget(loading_span, inner_space[0]);
} }
fn change_page(&mut self, change: PageChange, amt: ChangeAmount) -> Option<InputAction> { fn change_page(&mut self, mut change: PageChange, amt: ChangeAmount) -> Option<InputAction> {
let diff = match amt { let diff = match amt {
ChangeAmount::Single => 1, ChangeAmount::Single => 1,
ChangeAmount::WholeScreen => self.last_render.pages_shown ChangeAmount::WholeScreen => self.last_render.pages_shown
}; };
// This is a kinda weird way to switch around the controls for this sort of thing but it
// allows it to be pretty centralized and avoids annoyingly duplicated match arms (since
// we'd have to do `match key { 'h' if r_to_l | 'l' => {}}` and that doesn't play well with
// `if` guards on match arms)
if self.page_constraints.r_to_l {
change = match change {
PageChange::Next => PageChange::Prev,
PageChange::Prev => PageChange::Next
};
}
let old = self.page; let old = self.page;
match change { match change {
PageChange::Next => self.set_page((self.page + diff).min(self.rendered.len() - 1)), PageChange::Next => self.set_page((self.page + diff).min(self.rendered.len() - 1)),
@@ -293,7 +331,7 @@ impl Tui {
self.page = self.page.min(n_pages - 1); self.page = self.page.min(n_pages - 1);
} }
pub fn page_ready(&mut self, img: Box<dyn Protocol>, page_num: usize, num_results: usize) { pub fn page_ready(&mut self, img: Protocol, page_num: usize, num_results: usize) {
// If this new image woulda fit within the available space on the last render AND it's // If this new image woulda fit within the available space on the last render AND it's
// within the range where it might've been rendered with the last shown pages, then reset // within the range where it might've been rendered with the last shown pages, then reset
// the last rect marker so that all images are forced to redraw on next render and this one // the last rect marker so that all images are forced to redraw on next render and this one
@@ -323,7 +361,7 @@ impl Tui {
self.rendered[page_num].num_results = Some(num_results); self.rendered[page_num].num_results = Some(num_results);
} }
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, page: &mut usize,
rect: &mut Rect, rect: &mut Rect,
@@ -340,101 +378,147 @@ impl Tui {
match ev { match ev {
Event::Key(key) => { Event::Key(key) => {
match key.code { match key.code {
KeyCode::Char(c) KeyCode::Char(c) => {
// TODO: refactor back to `if let` arm guards when those are stabilized
if let BottomMessage::Input(InputCommand::Search(ref mut term)) = if let BottomMessage::Input(InputCommand::Search(ref mut term)) =
self.bottom_msg => self.bottom_msg
{ {
term.push(c); term.push(c);
Some(InputAction::Redraw) return Some(InputAction::Redraw);
} }
KeyCode::Backspace
if let BottomMessage::Input(InputCommand::Search(ref mut term)) =
self.bottom_msg =>
{
term.pop();
Some(InputAction::Redraw)
}
KeyCode::Char(c)
if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) = if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) =
self.bottom_msg => self.bottom_msg
c.to_digit(10).map(|input_num| { {
*page = (*page * 10) + input_num as usize; return c.to_digit(10).map(|input_num| {
InputAction::Redraw *page = (*page * 10) + input_num as usize;
}), InputAction::Redraw
KeyCode::Right | KeyCode::Char('l') => });
self.change_page(PageChange::Next, ChangeAmount::Single), }
KeyCode::Down | KeyCode::Char('j') =>
self.change_page(PageChange::Next, ChangeAmount::WholeScreen), match c {
KeyCode::Left | KeyCode::Char('h') => 'l' => self.change_page(PageChange::Next, ChangeAmount::Single),
self.change_page(PageChange::Prev, ChangeAmount::Single), 'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
KeyCode::Up | KeyCode::Char('k') => 'h' => self.change_page(PageChange::Prev, ChangeAmount::Single),
self.change_page(PageChange::Prev, ChangeAmount::WholeScreen), 'k' => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
'q' => Some(InputAction::QuitApp),
'g' => {
self.set_msg(MessageSetting::Some(BottomMessage::Input(
InputCommand::GoToPage(0)
)));
Some(InputAction::Redraw)
}
'/' => {
self.set_msg(MessageSetting::Some(BottomMessage::Input(
InputCommand::Search(String::new())
)));
Some(InputAction::Redraw)
}
'n' if self.page < self.rendered.len() - 1 => {
// TODO: If we can't find one, then maybe like block until we've verified
// all the pages have been checked?
let next_page = self.rendered[(self.page + 1)..]
.iter()
.enumerate()
.find_map(|(idx, p)| {
p.num_results
.is_some_and(|num| num > 0)
.then_some(self.page + 1 + idx)
});
jump_to_page(&mut self.page, &mut self.last_render.rect, next_page)
}
'N' if self.page > 0 => {
let prev_page = 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))
});
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
}
'z' if key.modifiers.contains(KeyModifiers::CONTROL) => {
// [todo] better error handling here?
let mut backend = stdout();
execute!(
&mut backend,
LeaveAlternateScreen,
crossterm::cursor::Show
)
.unwrap();
disable_raw_mode().unwrap();
// This process will hang after the SIGSTOP call until we get
// foregrounded again by something else, at which point we need to
// re-setup everything so that it all gets drawn again.
kill(Pid::this(), SIGSTOP).unwrap();
enable_raw_mode().unwrap();
execute!(
&mut backend,
EnterAlternateScreen,
crossterm::cursor::Hide
)
.unwrap();
self.last_render.rect = Rect::default();
Some(InputAction::Redraw)
}
_ => None
}
}
KeyCode::Backspace => {
if let BottomMessage::Input(InputCommand::Search(ref mut term)) =
self.bottom_msg
{
term.pop();
return Some(InputAction::Redraw);
}
None
}
KeyCode::Right => self.change_page(PageChange::Next, ChangeAmount::Single),
KeyCode::Down => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
KeyCode::Left => self.change_page(PageChange::Prev, ChangeAmount::Single),
KeyCode::Up => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
KeyCode::Esc => match self.bottom_msg { KeyCode::Esc => match self.bottom_msg {
BottomMessage::Input(_) => { BottomMessage::Help => Some(InputAction::QuitApp),
self.set_bottom_msg(None); _ => {
// When we hit escape, we just want to pop off the current message and
// show the underlying one.
self.set_msg(MessageSetting::Pop);
Some(InputAction::Redraw) Some(InputAction::Redraw)
} }
_ => Some(InputAction::QuitApp)
}, },
KeyCode::Char('q') => Some(InputAction::QuitApp),
KeyCode::Char('g') => {
self.set_bottom_msg(Some(BottomMessage::Input(InputCommand::GoToPage(0))));
Some(InputAction::Redraw)
}
KeyCode::Char('/') => {
self.set_bottom_msg(Some(BottomMessage::Input(InputCommand::Search(
String::new()
))));
Some(InputAction::Redraw)
}
KeyCode::Char('n') if self.page < self.rendered.len() - 1 => {
// TODO: If we can't find one, then maybe like block until we've verified
// all the pages have been checked?
let next_page = self.rendered[(self.page + 1)..]
.iter()
.enumerate()
.find_map(|(idx, p)| {
p.num_results
.is_some_and(|num| num > 0)
.then_some(self.page + 1 + idx)
});
jump_to_page(&mut self.page, &mut self.last_render.rect, next_page)
}
KeyCode::Char('N') if self.page > 0 => {
let prev_page = 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))
});
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
}
KeyCode::Enter => { KeyCode::Enter => {
let BottomMessage::Input(_) = self.bottom_msg else { let mut default = BottomMessage::default();
std::mem::swap(&mut self.bottom_msg, &mut default);
let BottomMessage::Input(ref cmd) = default else {
std::mem::swap(&mut self.bottom_msg, &mut default);
return None; return None;
}; };
self.set_bottom_msg(None);
let Some(BottomMessage::Input(ref cmd)) = self.prev_msg else {
// We need to verify it's an input msg currently, and only then take it
// and replace it by a default Help message. Don't exactly know how to
// do this otherwise.
unreachable!();
};
match cmd { match cmd {
// Only forward the command if it's within range // Only forward the command if it's within range
InputCommand::GoToPage(page) => { InputCommand::GoToPage(page) => {
let page = *page; // We need to subtract 1 b/c they're tracked internally as
(page < self.rendered.len()).then(|| { // 0-indexed but input and displayed as 1-indexed
self.set_page(page); let zero_page = page.saturating_sub(1);
InputAction::JumpingToPage(page) let rendered_len = self.rendered.len();
})
if zero_page < rendered_len {
self.set_page(zero_page);
Some(InputAction::JumpingToPage(zero_page))
} else {
self.set_msg(MessageSetting::Some(BottomMessage::Error(
format!("Cannot jump to page {page}; there are only {rendered_len} pages in the document")
)));
Some(InputAction::Redraw)
}
} }
InputCommand::Search(term) => { InputCommand::Search(term) => {
let term = term.clone(); let term = term.clone();
@@ -442,14 +526,14 @@ impl Tui {
// We only want to show search results if there would actually be // We only want to show search results if there would actually be
// data to show // data to show
if !term.is_empty() { if !term.is_empty() {
self.set_bottom_msg(Some(BottomMessage::SearchResults( self.set_msg(MessageSetting::Some(
term.clone() BottomMessage::SearchResults(term.clone())
))); ));
} else { } else {
// else, if it's not empty, we just want to reset the bottom // else, if it's not empty, we just want to reset the bottom
// area to show the default data; we don't want it to like show // area to show the default data; we don't want it to like show
// the data from a previous search // the data from a previous search
self.set_bottom_msg(Some(BottomMessage::Help)); self.set_msg(MessageSetting::Reset);
} }
// Reset all the search results // Reset all the search results
@@ -483,10 +567,10 @@ impl Tui {
} }
pub fn show_error(&mut self, err: RenderError) { pub fn show_error(&mut self, err: RenderError) {
self.set_bottom_msg(Some(BottomMessage::Error(match err { self.set_msg(MessageSetting::Some(BottomMessage::Error(match err {
RenderError::Notify(e) => format!("Auto-reload failed: {e}"), RenderError::Notify(e) => format!("Auto-reload failed: {e}"),
RenderError::Doc(e) => format!("Couldn't open document: {e}"), RenderError::Doc(e) => format!("Couldn't process document: {e}"),
RenderError::Render(e) => format!("Couldn't render page: {e}") RenderError::Converting(e) => format!("Couldn't convert page after rendering: {e}")
}))); })));
} }
@@ -500,17 +584,18 @@ impl Tui {
// We have `msg` as optional so that if they reset it to none, it'll replace it with // We have `msg` as optional so that if they reset it to none, it'll replace it with
// `prev_msg`, but if they reset it to something else, it'll put the current thing in prev_msg // `prev_msg`, but if they reset it to something else, it'll put the current thing in prev_msg
pub fn set_bottom_msg(&mut self, msg: Option<BottomMessage>) { pub fn set_msg(&mut self, msg: MessageSetting) {
match msg { match msg {
Some(mut msg) => { MessageSetting::Some(mut msg) => {
std::mem::swap(&mut self.bottom_msg, &mut msg); std::mem::swap(&mut self.bottom_msg, &mut msg);
self.prev_msg = Some(msg); self.prev_msg = Some(msg);
} }
None => { MessageSetting::Default => self.set_msg(MessageSetting::Some(BottomMessage::default())),
let mut new_bottom = self.prev_msg.take().unwrap_or_default(); MessageSetting::Reset => {
std::mem::swap(&mut self.bottom_msg, &mut new_bottom); self.prev_msg = None;
self.prev_msg = Some(new_bottom); self.bottom_msg = BottomMessage::default();
} }
MessageSetting::Pop => self.bottom_msg = self.prev_msg.take().unwrap_or_default()
} }
} }
} }
@@ -522,12 +607,21 @@ pub enum InputAction {
QuitApp QuitApp
} }
#[derive(Copy, Clone)]
enum PageChange { enum PageChange {
Prev, Prev,
Next Next
} }
#[derive(Copy, Clone)]
enum ChangeAmount { enum ChangeAmount {
WholeScreen, WholeScreen,
Single Single
} }
pub enum MessageSetting {
Some(BottomMessage),
Default,
Reset,
Pop
}