mirror of
https://github.com/itsjunetime/tdf.git
synced 2026-06-02 08:01:47 -04:00
Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3b130af6df | |||
| 95c24206ca | |||
| 5e4fbff9cd | |||
| 421401c7a7 | |||
| 7448fc73c5 | |||
| 1ed03e94fb | |||
| cf9d295d95 | |||
| 725c6c6bfd | |||
| fca61d55b5 | |||
| 59c0e2338b | |||
| 52994b8b89 | |||
| 2f957cdcbb | |||
| f2be5e39fb | |||
| 2d40444273 | |||
| 580af3668f | |||
| 577141e201 | |||
| 828db8aed3 | |||
| 39a4bdafb6 | |||
| 19030f7fd4 | |||
| d5d62c81a3 | |||
| 7b9e1462da | |||
| a4905b2ae5 | |||
| 9b9796e718 | |||
| e5cf92221f | |||
| 3fcf3be65f | |||
| 3dc5135a8b | |||
| 065797ccf6 | |||
| 55e0c2b33f | |||
| 0a0112a7e1 | |||
| 8f57cd02c3 | |||
| 74def1c0a8 | |||
| 670251fdff | |||
| b7d1b78e98 | |||
| fe8287bf7a | |||
| 38b307d628 | |||
| 09a332f07e | |||
| cde86b4f2c | |||
| 5a492599da | |||
| 7551c4dba3 | |||
| e61eb9b846 | |||
| 6b37976357 | |||
| 3628d21c74 | |||
| f4f3b4f539 | |||
| a79c534e97 | |||
| 971393892a |
@@ -0,0 +1,2 @@
|
|||||||
|
[*.rs]
|
||||||
|
indent_style = tab
|
||||||
+77
-11
@@ -3,31 +3,56 @@ name: Rust
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: ["main"]
|
branches: ["main"]
|
||||||
|
tags: ["v*.*.*"]
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: ["main"]
|
branches: ["main"]
|
||||||
|
workflow_dispatch:
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
CARGO_TERM_COLOR: always
|
CARGO_TERM_COLOR: always
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
test-build:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- { os: "macos-latest", target: "aarch64-apple-darwin" }
|
||||||
|
- { os: "ubuntu-latest", target: "x86_64-unknown-linux-gnu" }
|
||||||
|
- {
|
||||||
|
os: "windows-latest",
|
||||||
|
target: "x86_64-pc-windows-msvc",
|
||||||
|
ext: ".exe",
|
||||||
|
}
|
||||||
|
- { os: "ubuntu-24.04-arm", target: "aarch64-unknown-linux-gnu" }
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Setup sccache
|
- name: Setup sccache
|
||||||
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
||||||
uses: mozilla-actions/sccache-action@v0.0.8
|
uses: mozilla-actions/sccache-action@v0.0.8
|
||||||
- name: Configure sccache
|
- name: Configure sccache
|
||||||
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
||||||
run: |
|
run: |
|
||||||
echo "SCCACHE_GHA_ENABLED=true" >> $GITHUB_ENV
|
echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
|
||||||
echo "RUSTC_WRAPPER=sccache" >> $GITHUB_ENV
|
echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"
|
||||||
- name: Install build dependencies
|
|
||||||
run: |
|
- name: Setup rust cache action
|
||||||
sudo apt-get update
|
uses: swatinem/rust-cache@v2
|
||||||
sudo apt-get install -y libfontconfig1-dev libgoogle-perftools-dev google-perftools
|
with:
|
||||||
- uses: actions/checkout@v4
|
cache-on-failure: true
|
||||||
|
|
||||||
|
- name: install build dependencies on ubuntu and cache
|
||||||
|
if: contains(matrix.os, 'ubuntu')
|
||||||
|
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||||
|
with:
|
||||||
|
packages: libfontconfig1-dev libgoogle-perftools-dev google-perftools
|
||||||
|
version: latest # could be anything
|
||||||
|
|
||||||
- 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
|
||||||
@@ -38,5 +63,46 @@ jobs:
|
|||||||
run: cargo fmt -- --check
|
run: cargo fmt -- --check
|
||||||
- name: Run benchmarks as tests
|
- name: Run benchmarks as tests
|
||||||
run: cargo test --locked --benches -- adobe_example
|
run: cargo test --locked --benches -- adobe_example
|
||||||
- name: Build
|
|
||||||
run: cargo build --locked
|
- name: Set build mode
|
||||||
|
shell: bash
|
||||||
|
run: if [ "${{github.ref_type}}" == "tag" ] || [ ${{ github.event_name == 'push' && github.ref_name == 'main' }} ]; then echo "BMODE=production">>"$GITHUB_ENV"; fi
|
||||||
|
|
||||||
|
- name: Build in ${{env.BMODE || 'debug'}} mode
|
||||||
|
run: cargo build --verbose --locked --profile ${{env.BMODE || 'dev'}}
|
||||||
|
|
||||||
|
- name: Prepare artifact
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p dist
|
||||||
|
cp "target/${{env.BMODE || 'debug'}}/tdf${{ matrix.ext }}" dist/tdf-${{ matrix.target }}${{ matrix.ext }}
|
||||||
|
tree dist || ls -la dist
|
||||||
|
|
||||||
|
- name: Upload artifacts
|
||||||
|
uses: actions/upload-artifact@v5
|
||||||
|
with:
|
||||||
|
name: tdf-${{ matrix.target }}
|
||||||
|
path: dist/tdf*
|
||||||
|
|
||||||
|
tag-release:
|
||||||
|
name: Release on tag push
|
||||||
|
runs-on: ubuntu-slim
|
||||||
|
if: github.ref_type == 'tag'
|
||||||
|
needs: test-build
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v6
|
||||||
|
with:
|
||||||
|
pattern: "**/tdf-*"
|
||||||
|
path: release-artifacts
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: What's up?
|
||||||
|
run: tree release-artifacts # beautiful!
|
||||||
|
|
||||||
|
- name: Create a GitHub release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
draft: true
|
||||||
|
generate_release_notes: true
|
||||||
|
files: release-artifacts/*
|
||||||
|
prerelease: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') || contains(github.ref, 'rc') }}
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
/target
|
/target
|
||||||
debug.log
|
debug.log
|
||||||
|
/.envrc
|
||||||
|
/.direnv/
|
||||||
|
|||||||
@@ -1,5 +1,26 @@
|
|||||||
# Unreleased
|
# Unreleased
|
||||||
|
|
||||||
|
- Added windows support! (thank you to [@jarjk](https://github.com/jarjk) for helping out!)
|
||||||
|
- Added keybindings (`0`/`$`) to scroll to left or right side of zoomed-in image ([#131](https://github.com/itsjunetime/tdf/pull/131), thank you [@IshDeshpa](https://github.com/IshDeshpa)!)
|
||||||
|
- Fixed issue with images clearing/flashing after displaying a certain number on kitty
|
||||||
|
- (Internal) decreased runtime footprint of tokio runtime
|
||||||
|
|
||||||
|
# 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 issue with some terminals hanging on startup
|
||||||
- Fix issues with some iterm2-backend terminals not displaying anything
|
- Fix issues with some iterm2-backend terminals not displaying anything
|
||||||
- Allow using ctrl+scroll to zoom in/out while zoomed using kitty backend
|
- Allow using ctrl+scroll to zoom in/out while zoomed using kitty backend
|
||||||
|
|||||||
Generated
+836
-1283
File diff suppressed because it is too large
Load Diff
+150
-31
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tdf-viewer"
|
name = "tdf-viewer"
|
||||||
version = "0.4.2"
|
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.86"
|
rust-version = "1.95"
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "tdf"
|
name = "tdf"
|
||||||
@@ -23,10 +23,10 @@ name = "tdf"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# 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", rev = "720ac2d0cad1ac6424364fea74856fec9c100cb1", default-features = false, features = [ "crossterm", "layout-cache" ] }
|
||||||
# ratatui = { path = "./ratatui/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 `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", default-features = false }
|
ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", rev = "a276a87cb8e2976442c6cc59db831db81551da89", default-features = false }
|
||||||
# ratatui-image = { path = "./ratatui-image", default-features = false }
|
# ratatui-image = { path = "./ratatui-image", default-features = false }
|
||||||
crossterm = { version = "0.29.0", features = ["event-stream"] }
|
crossterm = { version = "0.29.0", features = ["event-stream"] }
|
||||||
# crossterm = { path = "../crossterm", features = ["event-stream"] }
|
# crossterm = { path = "../crossterm", features = ["event-stream"] }
|
||||||
@@ -34,37 +34,41 @@ image = { version = "0.25.1", features = ["pnm", "rayon", "png"], default-featur
|
|||||||
notify = { version = "8.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 }
|
||||||
flume = { version = "0.11.0", default-features = false, features = ["async"] }
|
flume = { version = "0.12.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.31.0", features = ["signal"] }
|
||||||
mupdf = { git = "https://github.com/messense/mupdf-rs.git", rev = "2e0fae910fac8048c7008211fc4d3b9f5d227a07", default-features = false, features = ["svg", "system-fonts", "img"] }
|
mupdf = { git = "https://github.com/messense/mupdf-rs.git", rev = "d7441b9998c92135e329559c0aa71d9dc92cf4de", 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.4.0", features = ["crossterm-tokio", "image-crate", "log"] }
|
||||||
memmap2 = "*"
|
memmap2 = "0"
|
||||||
|
csscolorparser = { version = "0.8.0", default-features = false }
|
||||||
|
debounce = "0.2.2"
|
||||||
|
smallvec = "1"
|
||||||
|
|
||||||
# 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" }
|
|
||||||
|
[patch.crates-io]
|
||||||
|
pathfinder_simd = { git = "https://github.com/itsjunetime/pathfinder.git", rev = "814671e162a1829e074521446317b915311d3d4d" }
|
||||||
|
|
||||||
[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"]
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
criterion = { version = "0.7.0", features = ["async_tokio"] }
|
criterion = { version = "0.8.0", features = ["async_tokio"] }
|
||||||
cpuprofiler = "0.0.4"
|
cpuprofiler = "0.0.4"
|
||||||
|
|
||||||
[[bench]]
|
[[bench]]
|
||||||
@@ -76,90 +80,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"
|
||||||
|
|||||||
@@ -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`.
|
||||||
@@ -25,10 +27,12 @@ If it turns out that you're missing one of these, it will fail to compile and te
|
|||||||
|
|
||||||
1. Get the rust toolchain from [rustup.rs](https://rustup.rs)
|
1. Get the rust toolchain from [rustup.rs](https://rustup.rs)
|
||||||
2. Clone the repo and `cd` into it
|
2. Clone the repo and `cd` into it
|
||||||
3. Run `cargo +nightly build --release`
|
3. Run `cargo build --release`
|
||||||
|
|
||||||
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 :)
|
||||||
|
|||||||
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
+86
-65
@@ -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,108 @@ 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(
|
||||||
|
name: &'static str,
|
||||||
|
mut f: impl FnMut(&Runtime, BenchmarkId, &'static str, ProtocolType)
|
||||||
|
) {
|
||||||
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(3)
|
||||||
|
.enable_time()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
for proto in PROTOS {
|
||||||
for file in FILES {
|
for file in FILES {
|
||||||
c.bench_with_input(BenchmarkId::new("render_full", file), &file, |b, &file| {
|
f(
|
||||||
b.to_async(tokio::runtime::Runtime::new().unwrap())
|
&rt,
|
||||||
.iter(|| render_doc(file, None, BLACK, WHITE))
|
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 +145,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 +156,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 +197,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 +218,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);
|
||||||
|
|||||||
+25
-12
@@ -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;
|
||||||
@@ -65,7 +65,6 @@ 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 = 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();
|
||||||
@@ -91,7 +90,7 @@ pub fn start_rendering_loop(
|
|||||||
let cell_width_px = size.width / size.columns;
|
let cell_width_px = size.width / size.columns;
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
start_rendering(
|
start_rendering(
|
||||||
&str_path,
|
&pathbuf,
|
||||||
to_main_tx,
|
to_main_tx,
|
||||||
from_main_rx,
|
from_main_rx,
|
||||||
cell_height_px,
|
cell_height_px,
|
||||||
@@ -106,7 +105,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>>,
|
||||||
@@ -115,8 +116,9 @@ 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();
|
||||||
|
|
||||||
|
#[expect(deprecated)]
|
||||||
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...720ac2d0ca
+1
-1
Submodule ratatui-image updated: fe3d0b992b...8ad154a219
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
pkgs ? import <nixpkgs> { },
|
||||||
|
}:
|
||||||
|
pkgs.mkShell {
|
||||||
|
nativeBuildInputs = [ pkgs.pkg-config ];
|
||||||
|
|
||||||
|
buildInputs = [
|
||||||
|
pkgs.rustPlatform.bindgenHook
|
||||||
|
pkgs.cairo
|
||||||
|
];
|
||||||
|
}
|
||||||
+36
-22
@@ -1,11 +1,12 @@
|
|||||||
use std::{
|
use std::{
|
||||||
|
io::Cursor,
|
||||||
num::{NonZeroU32, NonZeroUsize},
|
num::{NonZeroU32, 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, codecs::pnm::PnmDecoder};
|
||||||
use kittage::NumberOrId;
|
use kittage::NumberOrId;
|
||||||
use ratatui::layout::Rect;
|
use ratatui::layout::Rect;
|
||||||
use ratatui_image::{
|
use ratatui_image::{
|
||||||
@@ -13,7 +14,7 @@ use ratatui_image::{
|
|||||||
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},
|
||||||
@@ -37,6 +38,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) => {
|
||||||
@@ -67,7 +69,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>>> {
|
||||||
@@ -77,7 +79,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,
|
||||||
@@ -110,23 +112,27 @@ pub async fn run_conversion_loop(
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut dyn_img = image::load_from_memory_with_format(
|
let decoder = PnmDecoder::new(Cursor::new(&page_info.img_data.pixels)).map_err(|e| {
|
||||||
&page_info.img_data.pixels,
|
RenderError::Converting(format!(
|
||||||
image::ImageFormat::Pnm
|
"The image data provided from mupdf was not in pnm format ({e}); don't know how to convert"
|
||||||
)
|
))
|
||||||
.map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?;
|
})?;
|
||||||
|
|
||||||
|
// The image we get should always already be `ImageRgb8`, so this `into` shouldn't do any
|
||||||
|
// conversions or anything, but just in case some underlying detail of mupdf or image
|
||||||
|
// changes, we do the `into` instead of just `match + unreachable!()` to avoid panicking
|
||||||
|
let mut dyn_img = DynamicImage::from_decoder(decoder)
|
||||||
|
.map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?
|
||||||
|
.into_rgb8();
|
||||||
|
|
||||||
match dyn_img {
|
|
||||||
DynamicImage::ImageRgb8(ref mut img) =>
|
|
||||||
for quad in &*page_info.result_rects {
|
for quad in &*page_info.result_rects {
|
||||||
img.par_enumerate_pixels_mut()
|
dyn_img
|
||||||
|
.par_enumerate_pixels_mut()
|
||||||
.filter(|(x, y, _)| {
|
.filter(|(x, y, _)| {
|
||||||
*x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_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));
|
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
||||||
},
|
}
|
||||||
_ => unreachable!()
|
|
||||||
};
|
|
||||||
|
|
||||||
let img_area = Rect {
|
let img_area = Rect {
|
||||||
width: page_info.img_data.cell_w,
|
width: page_info.img_data.cell_w,
|
||||||
@@ -135,23 +141,31 @@ pub async fn run_conversion_loop(
|
|||||||
y: 0
|
y: 0
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let dyn_img = DynamicImage::ImageRgb8(dyn_img);
|
||||||
|
|
||||||
let txt_img = match picker.protocol_type() {
|
let txt_img = match picker.protocol_type() {
|
||||||
ProtocolType::Kitty => {
|
ProtocolType::Kitty => {
|
||||||
let rn = SystemTime::now()
|
let rn = SystemTime::now()
|
||||||
.duration_since(UNIX_EPOCH)
|
.duration_since(UNIX_EPOCH)
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
.as_millis() % 1_000_000;
|
.as_nanos() % 1_000_000;
|
||||||
|
|
||||||
let mut img = if shms_work {
|
let mut img = if shms_work {
|
||||||
kittage::image::Image::shm_from(dyn_img, &format!("tdf_{pid}_{rn}_{page_num}"))
|
let shm_name = format!("/tdf_{pid}_{rn}_{page_num}");
|
||||||
.map_err(|e| {
|
|
||||||
RenderError::Converting(format!("Couldn't write to shm: {e}"))
|
#[cfg(unix)]
|
||||||
|
let shm_name = &*shm_name;
|
||||||
|
|
||||||
|
kittage::image::Image::shm_from(dyn_img, shm_name).map_err(|e| {
|
||||||
|
RenderError::Converting(format!("Couldn't create 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(NonZeroU32::MIN.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,
|
||||||
@@ -214,7 +228,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,
|
||||||
|
|||||||
+94
-41
@@ -1,3 +1,4 @@
|
|||||||
|
use core::fmt::Display;
|
||||||
use std::{io::Write, num::NonZeroU32};
|
use std::{io::Write, num::NonZeroU32};
|
||||||
|
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
@@ -17,6 +18,7 @@ use kittage::{
|
|||||||
medium::Medium
|
medium::Medium
|
||||||
};
|
};
|
||||||
use ratatui::layout::Position;
|
use ratatui::layout::Position;
|
||||||
|
use smallvec::SmallVec;
|
||||||
|
|
||||||
use crate::converter::MaybeTransferred;
|
use crate::converter::MaybeTransferred;
|
||||||
|
|
||||||
@@ -60,10 +62,10 @@ 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<Option<ImageId>, TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>> {
|
||||||
let writer = DbgWriter {
|
let writer = DbgWriter {
|
||||||
w: std::io::stdout().lock(),
|
w: std::io::stdout().lock(),
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
@@ -78,7 +80,12 @@ 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_test_{pid}")) else {
|
let shm_name = format!("tdf_test_{pid}");
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
let shm_name = &*shm_name;
|
||||||
|
|
||||||
|
let Ok(mut k_img) = kittage::image::Image::shm_from(img, shm_name) else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -94,21 +101,51 @@ pub async fn do_shms_work(ev_stream: &mut EventStream) -> bool {
|
|||||||
res.is_ok()
|
res.is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ESTransErr<'es> = TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>;
|
||||||
|
|
||||||
|
pub struct DisplayErr<'es> {
|
||||||
|
pub failed_pages: SmallVec<[usize; 2]>,
|
||||||
|
pub user_facing_err: &'static str,
|
||||||
|
pub source: DisplayErrSource<'es>
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'es> DisplayErr<'es> {
|
||||||
|
fn empty(user_facing_err: &'static str, source: ESTransErr<'es>) -> Self {
|
||||||
|
Self {
|
||||||
|
failed_pages: SmallVec::new(),
|
||||||
|
user_facing_err,
|
||||||
|
source: DisplayErrSource::Transmission(source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum DisplayErrSource<'es> {
|
||||||
|
KittageReturnedNoId,
|
||||||
|
Transmission(ESTransErr<'es>)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for DisplayErrSource<'_> {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::KittageReturnedNoId => write!(
|
||||||
|
f,
|
||||||
|
"Kittage returned no ID when we asked it to display an image. This is a bug in kittage, please report it."
|
||||||
|
),
|
||||||
|
Self::Transmission(t) => write!(f, "Error with talking to the terminal: {t}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn display_kitty_images<'es>(
|
pub async fn display_kitty_images<'es>(
|
||||||
display: KittyDisplay<'_>,
|
display: KittyDisplay<'_>,
|
||||||
ev_stream: &'es mut EventStream
|
ev_stream: &'es mut EventStream,
|
||||||
) -> Result<
|
last_z_index: &mut i32
|
||||||
(),
|
) -> Result<(), DisplayErr<'es>> {
|
||||||
(
|
|
||||||
Vec<usize>,
|
|
||||||
&'static str,
|
|
||||||
TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>
|
|
||||||
)
|
|
||||||
> {
|
|
||||||
let images = match display {
|
let images = match display {
|
||||||
KittyDisplay::NoChange => return Ok(()),
|
KittyDisplay::NoChange => return Ok(()),
|
||||||
KittyDisplay::DisplayImages(_) | KittyDisplay::ClearImages => {
|
KittyDisplay::ClearImages =>
|
||||||
run_action(
|
return run_action(
|
||||||
Action::Delete(DeleteConfig {
|
Action::Delete(DeleteConfig {
|
||||||
effect: ClearOrDelete::Clear,
|
effect: ClearOrDelete::Clear,
|
||||||
which: WhichToDelete::All
|
which: WhichToDelete::All
|
||||||
@@ -116,24 +153,23 @@ pub async fn display_kitty_images<'es>(
|
|||||||
ev_stream
|
ev_stream
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| (vec![], "Couldn't clear previous images", e))?;
|
.map_err(|e| DisplayErr::empty("Couldn't clear previous images", e))
|
||||||
|
.map(|_: Option<ImageId>| ()),
|
||||||
let KittyDisplay::DisplayImages(images) = display else {
|
KittyDisplay::DisplayImages(imgs) => imgs
|
||||||
return Ok(());
|
|
||||||
};
|
};
|
||||||
|
|
||||||
images
|
let new_z_index = last_z_index.wrapping_add_unsigned(1);
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut err = None;
|
let mut err = Ok::<(), (SmallVec<[usize; 2]>, DisplayErrSource<'es>)>(());
|
||||||
for KittyReadyToDisplay {
|
for KittyReadyToDisplay {
|
||||||
img,
|
img,
|
||||||
page_num,
|
page_num,
|
||||||
pos,
|
pos,
|
||||||
display_loc
|
mut display_loc
|
||||||
} in images
|
} in images
|
||||||
{
|
{
|
||||||
|
display_loc.z_index = new_z_index;
|
||||||
|
|
||||||
let config = DisplayConfig {
|
let config = DisplayConfig {
|
||||||
location: display_loc,
|
location: display_loc,
|
||||||
cursor_movement: CursorMovementPolicy::DontMove,
|
cursor_movement: CursorMovementPolicy::DontMove,
|
||||||
@@ -163,7 +199,7 @@ pub async fn display_kitty_images<'es>(
|
|||||||
};
|
};
|
||||||
std::mem::swap(image, &mut fake_image);
|
std::mem::swap(image, &mut fake_image);
|
||||||
|
|
||||||
let res = run_action(
|
run_action(
|
||||||
Action::TransmitAndDisplay {
|
Action::TransmitAndDisplay {
|
||||||
image: fake_image,
|
image: fake_image,
|
||||||
config,
|
config,
|
||||||
@@ -171,15 +207,13 @@ pub async fn display_kitty_images<'es>(
|
|||||||
},
|
},
|
||||||
ev_stream
|
ev_stream
|
||||||
)
|
)
|
||||||
.await;
|
.await
|
||||||
|
.map_err(DisplayErrSource::Transmission)
|
||||||
match res {
|
.and_then(|img_id| {
|
||||||
Ok(img_id) => {
|
img_id
|
||||||
*img = MaybeTransferred::Transferred(img_id);
|
.map(|id| *img = MaybeTransferred::Transferred(id))
|
||||||
Ok(())
|
.ok_or(DisplayErrSource::KittageReturnedNoId)
|
||||||
}
|
})
|
||||||
Err(e) => Err((page_num, e))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
MaybeTransferred::Transferred(image_id) => run_action(
|
MaybeTransferred::Transferred(image_id) => run_action(
|
||||||
Action::Display {
|
Action::Display {
|
||||||
@@ -190,20 +224,39 @@ pub async fn display_kitty_images<'es>(
|
|||||||
ev_stream
|
ev_stream
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
// don't need the return id 'cause we already know it
|
||||||
.map_err(|e| (page_num, e))
|
.map(|_: Option<ImageId>| ())
|
||||||
|
.map_err(DisplayErrSource::Transmission)
|
||||||
};
|
};
|
||||||
|
|
||||||
log::debug!("this_err is {this_err:#?}");
|
log::debug!("this_err is {this_err:#?}");
|
||||||
|
|
||||||
if let Err((id, e)) = this_err {
|
if let Err(e) = this_err {
|
||||||
let e = err.get_or_insert_with(|| (vec![], e));
|
match err.as_mut() {
|
||||||
e.0.push(id);
|
Ok(()) => err = Err((SmallVec::from([page_num].as_slice()), e)),
|
||||||
|
Err((v, _)) => v.push(page_num)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let z_idxes_to_remove = *last_z_index;
|
||||||
|
*last_z_index = new_z_index;
|
||||||
|
|
||||||
match err {
|
match err {
|
||||||
Some((replace, e)) => Err((replace, "Couldn't transfer image to the terminal", e)),
|
Err((failed_pages, source)) => Err(DisplayErr {
|
||||||
None => Ok(())
|
failed_pages,
|
||||||
|
user_facing_err: "Couldn't transfer image to the terminal",
|
||||||
|
source
|
||||||
|
}),
|
||||||
|
Ok(()) => run_action(
|
||||||
|
Action::Delete(DeleteConfig {
|
||||||
|
effect: ClearOrDelete::Clear,
|
||||||
|
which: WhichToDelete::PlacementsWithZIndex(z_idxes_to_remove)
|
||||||
|
}),
|
||||||
|
ev_stream
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|e| DisplayErr::empty("Couldn't clear previously-sent images", e))
|
||||||
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-1
@@ -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),
|
||||||
@@ -41,7 +42,7 @@ pub fn scale_img_for_area(
|
|||||||
|
|
||||||
// and get the ratio that this page would have to be scaled by to fit perfectly within the
|
// and get the ratio that this page would have to be scaled by to fit perfectly within the
|
||||||
// area provided to us.
|
// area provided to us.
|
||||||
// we do this first by comparing the aspec ratio of the page with the aspect ratio of the
|
// we do this first by comparing the aspect ratio of the page with the aspect ratio of the
|
||||||
// area to fit it within. If the aspect ratio of the page is larger, then we need to scale
|
// area to fit it within. If the aspect ratio of the page is larger, then we need to scale
|
||||||
// the width of the page to fill perfectly within the height of the area. Otherwise, we
|
// the width of the page to fill perfectly within the height of the area. Otherwise, we
|
||||||
// scale the height to fit perfectly. The dimension that _is not_ scaled to fit perfectly
|
// scale the height to fit perfectly. The dimension that _is not_ scaled to fit perfectly
|
||||||
|
|||||||
+131
-73
@@ -5,8 +5,11 @@ use core::{
|
|||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
ffi::OsString,
|
ffi::OsString,
|
||||||
io::{BufReader, Read, Stdout, Write, stdout},
|
io::{BufReader, Read as _, Stdout, Write as _, stdout},
|
||||||
path::PathBuf
|
mem,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::Duration
|
||||||
};
|
};
|
||||||
|
|
||||||
use crossterm::{
|
use crossterm::{
|
||||||
@@ -17,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,
|
||||||
@@ -34,8 +38,10 @@ use ratatui_image::{
|
|||||||
use tdf::{
|
use tdf::{
|
||||||
PrerenderLimit,
|
PrerenderLimit,
|
||||||
converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
|
converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
|
||||||
kitty::{KittyDisplay, display_kitty_images, do_shms_work, run_action},
|
kitty::{
|
||||||
renderer::{self, RenderError, RenderInfo, RenderNotif},
|
DisplayErr, DisplayErrSource, KittyDisplay, display_kitty_images, do_shms_work, run_action
|
||||||
|
},
|
||||||
|
renderer::{self, MUPDF_BLACK, MUPDF_WHITE, RenderError, RenderInfo, RenderNotif},
|
||||||
tui::{BottomMessage, InputAction, MessageSetting, Tui}
|
tui::{BottomMessage, InputAction, MessageSetting, Tui}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -57,17 +63,27 @@ impl std::fmt::Debug for WrappedErr {
|
|||||||
impl std::error::Error for WrappedErr {}
|
impl std::error::Error for WrappedErr {}
|
||||||
|
|
||||||
fn reset_term() {
|
fn reset_term() {
|
||||||
|
_ = disable_raw_mode();
|
||||||
_ = execute!(
|
_ = execute!(
|
||||||
std::io::stdout(),
|
std::io::stdout(),
|
||||||
LeaveAlternateScreen,
|
LeaveAlternateScreen,
|
||||||
crossterm::cursor::Show,
|
crossterm::cursor::Show,
|
||||||
crossterm::event::DisableMouseCapture
|
crossterm::event::DisableMouseCapture
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
fn main() -> Result<(), WrappedErr> {
|
||||||
async fn main() -> Result<(), WrappedErr> {
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
inner_main().await.inspect_err(|_| reset_term())
|
.worker_threads(3)
|
||||||
|
.enable_time()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
rt.block_on(async move {
|
||||||
|
let result = inner_main().await;
|
||||||
|
reset_term();
|
||||||
|
result
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn inner_main() -> Result<(), WrappedErr> {
|
async fn inner_main() -> Result<(), WrappedErr> {
|
||||||
@@ -80,14 +96,19 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
#[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
|
||||||
@@ -116,28 +137,42 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
.canonicalize()
|
.canonicalize()
|
||||||
.map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?;
|
.map_err(|e| WrappedErr(format!("Cannot canonicalize provided file: {e}").into()))?;
|
||||||
|
|
||||||
let black =
|
let black = flags
|
||||||
parse_color_to_i32(flags.black_color.as_deref().unwrap_or("000000")).map_err(|e| {
|
.black_color
|
||||||
|
.as_deref()
|
||||||
|
.map(|color| {
|
||||||
|
parse_color_to_i32(color).map_err(|e| {
|
||||||
WrappedErr(
|
WrappedErr(
|
||||||
format!("Couldn't parse black color: {e} - is it formatted like a CSS color?")
|
format!(
|
||||||
|
"Couldn't parse black color {color:?}: {e} - is it formatted like a CSS color?"
|
||||||
|
)
|
||||||
.into()
|
.into()
|
||||||
)
|
)
|
||||||
})?;
|
})
|
||||||
|
})
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or(MUPDF_BLACK);
|
||||||
|
|
||||||
let white =
|
let white = flags
|
||||||
parse_color_to_i32(flags.white_color.as_deref().unwrap_or("FFFFFF")).map_err(|e| {
|
.white_color
|
||||||
|
.as_deref()
|
||||||
|
.map(|color| {
|
||||||
|
parse_color_to_i32(color).map_err(|e| {
|
||||||
WrappedErr(
|
WrappedErr(
|
||||||
format!("Couldn't parse white color: {e} - is it formatted like a CSS color?")
|
format!(
|
||||||
|
"Couldn't parse white color {color:?}: {e} - is it formatted like a CSS color?"
|
||||||
|
)
|
||||||
.into()
|
.into()
|
||||||
)
|
)
|
||||||
})?;
|
})
|
||||||
|
})
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or(MUPDF_WHITE);
|
||||||
|
|
||||||
// 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| {
|
||||||
@@ -145,8 +180,10 @@ async fn inner_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();
|
||||||
@@ -158,8 +195,11 @@ async fn inner_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()))?;
|
||||||
|
|
||||||
@@ -178,10 +218,6 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
)
|
)
|
||||||
.map_err(|e| WrappedErr(format!("Can't watch the provided file: {e}").into()))?;
|
.map_err(|e| WrappedErr(format!("Can't watch the provided file: {e}").into()))?;
|
||||||
|
|
||||||
// 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().map_err(|e| {
|
let mut window_size = window_size().map_err(|e| {
|
||||||
WrappedErr(format!("Can't get your current terminal window size: {e}").into())
|
WrappedErr(format!("Can't get your current terminal window size: {e}").into())
|
||||||
})?;
|
})?;
|
||||||
@@ -219,8 +255,13 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
window_size.width != 0
|
window_size.width != 0
|
||||||
&& window_size.height != 0
|
&& window_size.height != 0
|
||||||
&& window_size.columns != 0
|
&& window_size.columns != 0
|
||||||
&& window_size.rows != 0
|
&& window_size.rows != 0 =>
|
||||||
=> Ok(Picker::from_fontsize((cell_width_px, cell_height_px))),
|
{
|
||||||
|
// the 'equivalent' that is suggested instead is not the same. We need to keep
|
||||||
|
// calling this.
|
||||||
|
#[expect(deprecated)]
|
||||||
|
Ok(Picker::from_fontsize((cell_width_px, cell_height_px)))
|
||||||
|
},
|
||||||
ratatui_image::errors::Errors::NoFontSize => Err(WrappedErr(
|
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()
|
"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()
|
||||||
)),
|
)),
|
||||||
@@ -235,6 +276,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
.and_then(NonZeroUsize::new)
|
.and_then(NonZeroUsize::new)
|
||||||
.map_or(PrerenderLimit::All, PrerenderLimit::Limited);
|
.map_or(PrerenderLimit::All, PrerenderLimit::Limited);
|
||||||
|
|
||||||
|
let file_path = path.clone();
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
renderer::start_rendering(
|
renderer::start_rendering(
|
||||||
&file_path,
|
&file_path,
|
||||||
@@ -267,12 +309,7 @@ async fn inner_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| {
|
||||||
@@ -300,7 +337,7 @@ async fn inner_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))
|
||||||
@@ -335,17 +372,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
execute!(
|
|
||||||
term.backend_mut(),
|
|
||||||
LeaveAlternateScreen,
|
|
||||||
crossterm::cursor::Show,
|
|
||||||
crossterm::event::DisableMouseCapture
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
disable_raw_mode().unwrap();
|
|
||||||
|
|
||||||
drop(maybe_logger);
|
drop(maybe_logger);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -363,6 +390,8 @@ async fn enter_redraw_loop(
|
|||||||
mut main_area: tdf::tui::RenderLayout,
|
mut main_area: tdf::tui::RenderLayout,
|
||||||
font_size: FontSize
|
font_size: FontSize
|
||||||
) -> Result<(), Box<dyn Error>> {
|
) -> Result<(), Box<dyn Error>> {
|
||||||
|
let mut kitty_z_idx = i32::MIN;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let mut needs_redraw = true;
|
let mut needs_redraw = true;
|
||||||
let next_ev = ev_stream.next().fuse();
|
let next_ev = ev_stream.next().fuse();
|
||||||
@@ -383,6 +412,7 @@ async fn enter_redraw_loop(
|
|||||||
},
|
},
|
||||||
InputAction::Search(term) => to_renderer.send(RenderNotif::Search(term))?,
|
InputAction::Search(term) => to_renderer.send(RenderNotif::Search(term))?,
|
||||||
InputAction::Invert => to_renderer.send(RenderNotif::Invert)?,
|
InputAction::Invert => to_renderer.send(RenderNotif::Invert)?,
|
||||||
|
InputAction::Rotate => to_renderer.send(RenderNotif::Rotate)?,
|
||||||
InputAction::Fullscreen => fullscreen = !fullscreen,
|
InputAction::Fullscreen => fullscreen = !fullscreen,
|
||||||
InputAction::SwitchRenderZoom(f_or_f) => {
|
InputAction::SwitchRenderZoom(f_or_f) => {
|
||||||
to_renderer.send(RenderNotif::SwitchFitOrFill(f_or_f)).unwrap();
|
to_renderer.send(RenderNotif::SwitchFitOrFill(f_or_f)).unwrap();
|
||||||
@@ -434,10 +464,16 @@ async fn enter_redraw_loop(
|
|||||||
to_display = tui.render(f, &main_area, font_size);
|
to_display = tui.render(f, &main_area, font_size);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let maybe_err = display_kitty_images(to_display, &mut ev_stream).await;
|
let maybe_err =
|
||||||
|
display_kitty_images(to_display, &mut ev_stream, &mut kitty_z_idx).await;
|
||||||
|
|
||||||
if let Err((to_replace, err_desc, enum_err)) = maybe_err {
|
if let Err(DisplayErr {
|
||||||
match enum_err {
|
failed_pages,
|
||||||
|
user_facing_err,
|
||||||
|
source
|
||||||
|
}) = maybe_err
|
||||||
|
{
|
||||||
|
match source {
|
||||||
// This is the error that kitty & ghostty provide us when they delete an
|
// This is the error that kitty & ghostty provide us when they delete an
|
||||||
// image due to memory constraints, so if we get it, we just fix it by
|
// image due to memory constraints, so if we get it, we just fix it by
|
||||||
// re-rendering so it don't display it to the user
|
// re-rendering so it don't display it to the user
|
||||||
@@ -445,13 +481,15 @@ async fn enter_redraw_loop(
|
|||||||
// [TODO] maybe when we detect that an image was deleted, we probe the
|
// [TODO] maybe when we detect that an image was deleted, we probe the
|
||||||
// terminal for the pages around it to see if they were deleted too and if
|
// terminal for the pages around it to see if they were deleted too and if
|
||||||
// they were, we re-render them? idk
|
// they were, we re-render them? idk
|
||||||
TransmitError::Terminal(TerminalError::NoEntity(_)) => (),
|
DisplayErrSource::Transmission(TransmitError::Terminal(
|
||||||
|
TerminalError::NoEntity(_)
|
||||||
|
)) => (),
|
||||||
_ => tui.set_msg(MessageSetting::Some(BottomMessage::Error(format!(
|
_ => tui.set_msg(MessageSetting::Some(BottomMessage::Error(format!(
|
||||||
"{err_desc}: {enum_err}"
|
"{user_facing_err}: {source}"
|
||||||
))))
|
))))
|
||||||
}
|
}
|
||||||
|
|
||||||
for page_num in to_replace {
|
for page_num in failed_pages {
|
||||||
tui.page_failed_display(page_num);
|
tui.page_failed_display(page_num);
|
||||||
// So that they get re-rendered and sent over again
|
// So that they get re-rendered and sent over again
|
||||||
to_renderer.send(RenderNotif::PageNeedsReRender(page_num))?;
|
to_renderer.send(RenderNotif::PageNeedsReRender(page_num))?;
|
||||||
@@ -466,12 +504,32 @@ 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(()));
|
||||||
|
let last_event = Arc::new(last_event);
|
||||||
|
|
||||||
|
let debouncer = EventDebouncer::new(debounce_delay, {
|
||||||
|
let last_event = last_event.clone();
|
||||||
|
move |()| {
|
||||||
|
let event = mem::replace(&mut *last_event.lock().unwrap(), Ok(()));
|
||||||
|
match event {
|
||||||
|
// 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.
|
||||||
|
Ok(()) => to_render_tx.send(RenderNotif::Reload).unwrap(),
|
||||||
// If we get an error here, and then an error sending, everything's going wrong. Just give
|
// If we get an error here, and then an error sending, everything's going wrong. Just give
|
||||||
// up lol.
|
// up lol.
|
||||||
Err(e) => to_tui_tx.send(Err(RenderError::Notify(e))).unwrap(),
|
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
|
// TODO: Should we match EventKind::Rename and propogate that so that the other parts of the
|
||||||
// process know that too? Or should that be
|
// process know that too? Or should that be
|
||||||
Ok(ev) => {
|
Ok(ev) => {
|
||||||
@@ -487,17 +545,17 @@ fn on_notify_ev(
|
|||||||
}
|
}
|
||||||
|
|
||||||
match ev.kind {
|
match ev.kind {
|
||||||
EventKind::Access(_) => (),
|
EventKind::Access(_) => return,
|
||||||
EventKind::Remove(_) => to_tui_tx
|
EventKind::Remove(_) => Err(RenderError::Converting("File was deleted".into())),
|
||||||
.send(Err(RenderError::Converting("File was deleted".into())))
|
EventKind::Other
|
||||||
.unwrap(),
|
| EventKind::Any
|
||||||
// This shouldn't fail to send unless the receiver gets disconnected. If that's
|
| EventKind::Create(_)
|
||||||
// happened, then like the main thread has panicked or something, so it doesn't matter
|
| EventKind::Modify(_) => Ok(())
|
||||||
// we don't handle the error here.
|
|
||||||
EventKind::Other | EventKind::Any | EventKind::Create(_) | EventKind::Modify(_) =>
|
|
||||||
to_render_tx.send(RenderNotif::Reload).unwrap(),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
*last_event.lock().unwrap() = event;
|
||||||
|
debouncer.put(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -554,18 +612,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()
|
||||||
)
|
)
|
||||||
|
|||||||
+70
-16
@@ -1,4 +1,4 @@
|
|||||||
use std::{collections::VecDeque, num::NonZeroUsize, thread::sleep, time::Duration};
|
use std::{collections::VecDeque, num::NonZeroUsize, path::Path, thread::sleep, time::Duration};
|
||||||
|
|
||||||
use flume::{Receiver, SendError, Sender, TryRecvError};
|
use flume::{Receiver, SendError, Sender, TryRecvError};
|
||||||
use mupdf::{
|
use mupdf::{
|
||||||
@@ -20,7 +20,8 @@ pub enum RenderNotif {
|
|||||||
Search(String),
|
Search(String),
|
||||||
SwitchFitOrFill(FitOrFill),
|
SwitchFitOrFill(FitOrFill),
|
||||||
Reload,
|
Reload,
|
||||||
Invert
|
Invert,
|
||||||
|
Rotate
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -37,6 +38,14 @@ pub enum RenderInfo {
|
|||||||
Reloaded
|
Reloaded
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone)]
|
||||||
|
pub enum RotateDirection {
|
||||||
|
Deg0,
|
||||||
|
Deg90,
|
||||||
|
Deg180,
|
||||||
|
Deg270
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PageInfo {
|
pub struct PageInfo {
|
||||||
pub img_data: ImageData,
|
pub img_data: ImageData,
|
||||||
@@ -57,8 +66,8 @@ struct PrevRender {
|
|||||||
num_search_found: Option<usize>
|
num_search_found: Option<usize>
|
||||||
}
|
}
|
||||||
|
|
||||||
const MUPDF_BLACK: i32 = 0;
|
pub const MUPDF_BLACK: i32 = 0;
|
||||||
const MUPDF_WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]);
|
pub const MUPDF_WHITE: i32 = i32::from_be_bytes([0, 0xff, 0xff, 0xff]);
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
|
pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
|
||||||
@@ -78,9 +87,9 @@ 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: &Path,
|
||||||
sender: Sender<Result<RenderInfo, RenderError>>,
|
sender: Sender<Result<RenderInfo, RenderError>>,
|
||||||
receiver: Receiver<RenderNotif>,
|
receiver: Receiver<RenderNotif>,
|
||||||
col_h: u16,
|
col_h: u16,
|
||||||
@@ -98,13 +107,21 @@ pub fn start_rendering(
|
|||||||
|
|
||||||
let mut stored_doc = None;
|
let mut stored_doc = None;
|
||||||
let mut invert = false;
|
let mut invert = false;
|
||||||
|
let mut rotate = RotateDirection::Deg0;
|
||||||
let mut preserved_area = None;
|
let mut preserved_area = None;
|
||||||
let mut fit_or_fill = FitOrFill::Fit;
|
let mut fit_or_fill = FitOrFill::Fit;
|
||||||
|
|
||||||
let mut need_rerender = VecDeque::new();
|
let mut need_rerender = VecDeque::new();
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
let path = path.to_string_lossy();
|
||||||
|
|
||||||
'reload: loop {
|
'reload: loop {
|
||||||
let doc = match Document::open(path) {
|
// Need to do this weird borrow thing so that we convert `Cow<'_, str>` -> `&str` on windows
|
||||||
|
// and keep unix a `&Path` -> `&Path` 'cause there are different requirements within mupdf
|
||||||
|
// about file paths per-platform
|
||||||
|
#[cfg_attr(unix, expect(clippy::borrow_deref_ref))]
|
||||||
|
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)))?;
|
||||||
@@ -116,7 +133,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -152,8 +169,8 @@ pub fn start_rendering(
|
|||||||
|
|
||||||
sender.send(Ok(RenderInfo::NumPages(n_pages.get())))?;
|
sender.send(Ok(RenderInfo::NumPages(n_pages.get())))?;
|
||||||
|
|
||||||
// We're using this vec of bools to indicate which page numbers have already been rendered,
|
// We're using this vec to indicate which page numbers have already been rendered, to
|
||||||
// to support people jumping to specific pages and having quick rendering results. We
|
// support people jumping to specific pages and having quick rendering results. We
|
||||||
// `split_at_mut` at 0 initially (which bascially makes `right == rendered && left == []`),
|
// `split_at_mut` at 0 initially (which bascially makes `right == rendered && left == []`),
|
||||||
// doing basically nothing, but if we get a notification that something has been jumped to,
|
// doing basically nothing, but if we get a notification that something has been jumped to,
|
||||||
// then we can split at that page and render at both sides of it
|
// then we can split at that page and render at both sides of it
|
||||||
@@ -238,6 +255,18 @@ pub fn start_rendering(
|
|||||||
}
|
}
|
||||||
continue 'render_pages;
|
continue 'render_pages;
|
||||||
}
|
}
|
||||||
|
RenderNotif::Rotate => {
|
||||||
|
rotate = match rotate {
|
||||||
|
RotateDirection::Deg0 => RotateDirection::Deg90,
|
||||||
|
RotateDirection::Deg90 => RotateDirection::Deg180,
|
||||||
|
RotateDirection::Deg180 => RotateDirection::Deg270,
|
||||||
|
RotateDirection::Deg270 => RotateDirection::Deg0
|
||||||
|
};
|
||||||
|
for page in &mut rendered {
|
||||||
|
page.successful = false;
|
||||||
|
}
|
||||||
|
continue 'render_pages;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -301,6 +330,7 @@ pub fn start_rendering(
|
|||||||
black,
|
black,
|
||||||
white,
|
white,
|
||||||
fit_or_fill,
|
fit_or_fill,
|
||||||
|
rotate,
|
||||||
(area_w, area_h)
|
(area_w, area_h)
|
||||||
) {
|
) {
|
||||||
// If that fn returned Some, that means it needed to be re-rendered for some
|
// If that fn returned Some, that means it needed to be re-rendered for some
|
||||||
@@ -313,7 +343,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 +371,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 +464,7 @@ pub fn start_rendering(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
handle_notif!(msg)
|
handle_notif!(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -455,6 +485,7 @@ fn render_single_page_to_ctx(
|
|||||||
black: i32,
|
black: i32,
|
||||||
white: i32,
|
white: i32,
|
||||||
fit_or_fill: FitOrFill,
|
fit_or_fill: FitOrFill,
|
||||||
|
rotate: RotateDirection,
|
||||||
(area_w, area_h): (f32, f32)
|
(area_w, area_h): (f32, f32)
|
||||||
) -> Result<RenderedContext, mupdf::error::Error> {
|
) -> Result<RenderedContext, mupdf::error::Error> {
|
||||||
let result_rects = match prev_render.num_search_found {
|
let result_rects = match prev_render.num_search_found {
|
||||||
@@ -465,7 +496,12 @@ fn render_single_page_to_ctx(
|
|||||||
|
|
||||||
// then, get the size of the page
|
// then, get the size of the page
|
||||||
let bounds = page.bounds()?;
|
let bounds = page.bounds()?;
|
||||||
let page_dim = (bounds.x1 - bounds.x0, bounds.y1 - bounds.y0);
|
let page_dim = match rotate {
|
||||||
|
RotateDirection::Deg0 | RotateDirection::Deg180 =>
|
||||||
|
(bounds.x1 - bounds.x0, bounds.y1 - bounds.y0),
|
||||||
|
RotateDirection::Deg90 | RotateDirection::Deg270 =>
|
||||||
|
(bounds.y1 - bounds.y0, bounds.x1 - bounds.x0),
|
||||||
|
};
|
||||||
|
|
||||||
let scaled = scale_img_for_area(page_dim, (area_w, area_h), fit_or_fill);
|
let scaled = scale_img_for_area(page_dim, (area_w, area_h), fit_or_fill);
|
||||||
let ScaledResult {
|
let ScaledResult {
|
||||||
@@ -482,7 +518,13 @@ fn render_single_page_to_ctx(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let colorspace = Colorspace::device_rgb();
|
let colorspace = Colorspace::device_rgb();
|
||||||
let matrix = Matrix::new_scale(scale_factor, scale_factor);
|
let mut matrix = Matrix::new_scale(scale_factor, scale_factor);
|
||||||
|
match rotate {
|
||||||
|
RotateDirection::Deg0 => matrix.rotate(0.0),
|
||||||
|
RotateDirection::Deg90 => matrix.rotate(90.0),
|
||||||
|
RotateDirection::Deg180 => matrix.rotate(180.0),
|
||||||
|
RotateDirection::Deg270 => matrix.rotate(270.0)
|
||||||
|
};
|
||||||
|
|
||||||
let mut pixmap = page.to_pixmap(&matrix, &colorspace, false, false)?;
|
let mut pixmap = page.to_pixmap(&matrix, &colorspace, false, false)?;
|
||||||
if invert {
|
if invert {
|
||||||
@@ -494,6 +536,7 @@ fn render_single_page_to_ctx(
|
|||||||
let (x_res, y_res) = pixmap.resolution();
|
let (x_res, y_res) = pixmap.resolution();
|
||||||
let new_x = (x_res as f32 * scale_factor) as i32;
|
let new_x = (x_res as f32 * scale_factor) as i32;
|
||||||
let new_y = (y_res as f32 * scale_factor) as i32;
|
let new_y = (y_res as f32 * scale_factor) as i32;
|
||||||
|
|
||||||
pixmap.set_resolution(new_x, new_y);
|
pixmap.set_resolution(new_x, new_y);
|
||||||
|
|
||||||
let result_rects = result_rects
|
let result_rects = result_rects
|
||||||
@@ -565,9 +608,20 @@ 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||||
|
let l = self.len();
|
||||||
|
(l, Some(l))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ExactSizeIterator for PopOnNext<'_> {
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
self.inner.len()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
+398
-174
@@ -9,13 +9,10 @@ use crossterm::{
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
use kittage::display::DisplayLocation;
|
use kittage::display::DisplayLocation;
|
||||||
use nix::{
|
|
||||||
sys::signal::{Signal::SIGSTOP, kill},
|
|
||||||
unistd::Pid
|
|
||||||
};
|
|
||||||
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::Span,
|
||||||
@@ -75,10 +72,10 @@ struct PageConstraints {
|
|||||||
r_to_l: bool
|
r_to_l: bool
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default, Debug)]
|
#[derive(Default, Debug, Clone, Copy)]
|
||||||
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 +84,85 @@ 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_in(&mut self) {
|
||||||
|
self.level = self.level.saturating_add(1);
|
||||||
|
}
|
||||||
|
fn step_out(&mut self) {
|
||||||
|
self.level = self.level.saturating_sub(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Make this configurable, maybe allow fractional steps?
|
||||||
|
// With fractional steps, it might also be a good idea to have these
|
||||||
|
// have the same ratio as the font aspect ratio.
|
||||||
|
const PAN_STEP_X: i16 = 2;
|
||||||
|
const PAN_STEP_Y: i16 = 1;
|
||||||
|
|
||||||
|
fn pan(&mut self, direction: Direction) {
|
||||||
|
let (target, sign) = match direction {
|
||||||
|
Direction::Up => (&mut self.cell_pan_from_top, -1),
|
||||||
|
Direction::Down => (&mut self.cell_pan_from_top, 1),
|
||||||
|
Direction::Left => (&mut self.cell_pan_from_left, -1),
|
||||||
|
Direction::Right => (&mut self.cell_pan_from_left, 1)
|
||||||
|
};
|
||||||
|
let step = if direction.is_vertical() {
|
||||||
|
Self::PAN_STEP_Y
|
||||||
|
} else {
|
||||||
|
Self::PAN_STEP_X
|
||||||
|
};
|
||||||
|
*target = target.saturating_add_signed(sign * step);
|
||||||
|
}
|
||||||
|
fn pan_bottom(&mut self) {
|
||||||
|
self.cell_pan_from_top = 0;
|
||||||
|
}
|
||||||
|
fn pan_top(&mut self) {
|
||||||
|
self.cell_pan_from_top = u16::MAX;
|
||||||
|
}
|
||||||
|
fn pan_left(&mut self) {
|
||||||
|
self.cell_pan_from_left = 0;
|
||||||
|
}
|
||||||
|
fn pan_right(&mut self) {
|
||||||
|
self.cell_pan_from_left = u16::MAX;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
enum Direction {
|
||||||
|
Up,
|
||||||
|
Down,
|
||||||
|
Left,
|
||||||
|
Right
|
||||||
|
}
|
||||||
|
impl Direction {
|
||||||
|
/// Flips the directions for vertical and horizonal panning.
|
||||||
|
fn flip_mouse_xy(self) -> Self {
|
||||||
|
match self {
|
||||||
|
Self::Up => Self::Left,
|
||||||
|
Self::Left => Self::Up,
|
||||||
|
Self::Down => Self::Right,
|
||||||
|
Self::Right => Self::Down
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn is_vertical(self) -> bool {
|
||||||
|
match self {
|
||||||
|
Self::Up | Self::Down => true,
|
||||||
|
Self::Left | Self::Right => false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 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 +184,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 +200,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,7 +225,159 @@ impl Tui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Make a way to fill the width of the screen with one page and scroll down to view it
|
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;
|
||||||
|
|
||||||
|
fn 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shrink_move_two_pass(
|
||||||
|
zoom: &mut Zoom,
|
||||||
|
dim: &mut u16,
|
||||||
|
pos: &mut u16,
|
||||||
|
zoom_factor: f32,
|
||||||
|
axis_zoom_factor: f32
|
||||||
|
) {
|
||||||
|
// To detect if we're already at fit-screen, we perform a first
|
||||||
|
// pass on `img_area` that emulates the last call to
|
||||||
|
// `render_zoomed` by subtracting from the `zoom`'s level. This
|
||||||
|
// holds because the `img_area` that gets passed is always the
|
||||||
|
// same.
|
||||||
|
let mut first_pass_dim = *dim;
|
||||||
|
let mut first_pass_pos = *pos;
|
||||||
|
let mut first_pass_zoom = *zoom;
|
||||||
|
|
||||||
|
if first_pass_zoom.level.is_negative() {
|
||||||
|
first_pass_zoom.step_in();
|
||||||
|
}
|
||||||
|
let first_pass_zoom_factor = first_pass_zoom.factor();
|
||||||
|
shrink_move_page(
|
||||||
|
&mut first_pass_dim,
|
||||||
|
&mut first_pass_pos,
|
||||||
|
first_pass_zoom_factor.max(1.0 / axis_zoom_factor)
|
||||||
|
);
|
||||||
|
|
||||||
|
log::debug!("first_pass_dim: {first_pass_dim}, first_pass_pos: {first_pass_pos}");
|
||||||
|
// vertical scroll / tall image. zooming out means decreasing
|
||||||
|
// the width of the page area
|
||||||
|
// use `max` to disallow zooming out past fit-screen
|
||||||
|
shrink_move_page(dim, pos, zoom_factor.max(1.0 / axis_zoom_factor));
|
||||||
|
|
||||||
|
log::debug!("new dim: {dim}, new pos: {pos}");
|
||||||
|
// The moment the image area is left unmodified, we've hit
|
||||||
|
// fit-screen and the zoom level ought be normalized.
|
||||||
|
if first_pass_dim == *dim && first_pass_pos == *pos {
|
||||||
|
zoom.step_in();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (dim, pos, axis_zoom_factor) = if img_page_w_ratio < img_page_h_ratio {
|
||||||
|
(&mut img_area.width, &mut img_area.x, img_page_h_ratio)
|
||||||
|
} else {
|
||||||
|
// horizontal scroll / wide image. zooming out means decreasing
|
||||||
|
// the height of the page area
|
||||||
|
(&mut img_area.height, &mut img_area.y, img_page_w_ratio)
|
||||||
|
};
|
||||||
|
shrink_move_two_pass(zoom, dim, pos, zoom_factor, axis_zoom_factor);
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}])
|
||||||
|
}
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn render<'s>(
|
pub fn render<'s>(
|
||||||
&'s mut self,
|
&'s mut self,
|
||||||
@@ -180,8 +410,9 @@ 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 {
|
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
|
// 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
|
// in the borrow checker. Once `-Zpolonius=next` is stabilized, we can rework this
|
||||||
@@ -203,79 +434,21 @@ impl Tui {
|
|||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
|
|
||||||
log::debug!("zoom is now {zoom:#?}");
|
|
||||||
log::debug!("img_area is {img_area:#?}");
|
|
||||||
|
|
||||||
if zoom.level < 0 {
|
|
||||||
img_area = Rect {
|
|
||||||
width: img_area
|
|
||||||
.width
|
|
||||||
.saturating_sub((zoom.level * 2).unsigned_abs())
|
|
||||||
.max(1),
|
|
||||||
x: img_area.x + (zoom.level.unsigned_abs().min(img_area.width / 2)),
|
|
||||||
..img_area
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log::debug!("after adjustment, img_area is {img_area:#?}");
|
|
||||||
|
|
||||||
// Ugh I don't like this logic. I wish we could simplify it.
|
|
||||||
let img_width = f32::from(cell_w);
|
|
||||||
let img_height = f32::from(cell_h);
|
|
||||||
let img_area_width = f32::from(img_area.width);
|
|
||||||
let img_area_height = f32::from(img_area.height);
|
|
||||||
let available_to_real_width_ratio = img_area_width / img_width;
|
|
||||||
let available_to_real_height_ratio = img_area_height / img_height;
|
|
||||||
|
|
||||||
let (new_cell_width, new_cell_height) =
|
|
||||||
if available_to_real_width_ratio > available_to_real_height_ratio {
|
|
||||||
(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 {
|
self.last_render = LastRender {
|
||||||
rect: size,
|
rect: size,
|
||||||
pages_shown: 1,
|
pages_shown: 1,
|
||||||
unused_width: 0
|
unused_width: 0
|
||||||
};
|
};
|
||||||
|
return Self::render_zoomed(
|
||||||
zoom.cell_pan_from_left = zoom
|
img_area, font_size, zoom, img, self.page, cell_w, cell_h
|
||||||
.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()
|
|
||||||
}
|
}
|
||||||
}]);
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
// 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 mut page_widths = self.rendered[self.page..]
|
let mut page_sizes = self.rendered[self.page..]
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
// and get this to represent a count of how many we're looking at so far to render
|
// and get this to represent a count of how many we're looking at so far to render
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -288,9 +461,14 @@ impl Tui {
|
|||||||
take
|
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)
|
||||||
.filter_map(|(_, page)| page.img.as_mut().map(|img| (img.w_h().0, img)))
|
.filter_map(|(_, page)| {
|
||||||
|
page.img.as_mut().map(|img| {
|
||||||
|
let (w, h) = img.w_h();
|
||||||
|
(w, h, 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
|
||||||
@@ -300,28 +478,35 @@ impl Tui {
|
|||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
if self.page_constraints.r_to_l {
|
if self.page_constraints.r_to_l {
|
||||||
page_widths.reverse();
|
page_sizes.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
if page_widths.is_empty() {
|
if page_sizes.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);
|
||||||
KittyDisplay::ClearImages
|
KittyDisplay::ClearImages
|
||||||
} else {
|
} else {
|
||||||
execute!(stdout(), BeginSynchronizedUpdate).unwrap();
|
execute!(stdout(), BeginSynchronizedUpdate).unwrap();
|
||||||
|
|
||||||
let total_width = page_widths.iter().map(|(w, _)| w).sum::<u16>();
|
let total_width = page_sizes.iter().map(|(w, _, _)| w).sum::<u16>();
|
||||||
|
|
||||||
self.last_render.pages_shown = page_widths.len();
|
self.last_render.pages_shown = page_sizes.len();
|
||||||
|
|
||||||
let unused_width = img_area.width - total_width;
|
let unused_width = img_area.width - total_width;
|
||||||
self.last_render.unused_width = unused_width;
|
self.last_render.unused_width = unused_width;
|
||||||
img_area.x += unused_width / 2;
|
img_area.x += unused_width / 2;
|
||||||
|
|
||||||
let to_display = page_widths
|
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()
|
.into_iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
.filter_map(|(idx, (width, img))| {
|
.filter_map(|(idx, (width, _, img))| {
|
||||||
let maybe_img =
|
let maybe_img =
|
||||||
Self::render_single_page(frame, img, Rect { width, ..img_area });
|
Self::render_single_page(frame, img, Rect { width, ..img_area });
|
||||||
img_area.x += width;
|
img_area.x += width;
|
||||||
@@ -341,7 +526,6 @@ impl Tui {
|
|||||||
KittyDisplay::DisplayImages(to_display)
|
KittyDisplay::DisplayImages(to_display)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
fn render_single_page<'img>(
|
fn render_single_page<'img>(
|
||||||
frame: &mut Frame<'_>,
|
frame: &mut Frame<'_>,
|
||||||
@@ -365,12 +549,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 =
|
||||||
|
Layout::horizontal([Constraint::Length(const { LOADING_STR.len() as u16 })])
|
||||||
.flex(Flex::Center)
|
.flex(Flex::Center)
|
||||||
.split(area);
|
.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 +584,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,41 +719,40 @@ 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,
|
|
||||||
rect: &mut Rect,
|
|
||||||
new_page: Option<usize>
|
|
||||||
) -> Option<InputAction> {
|
|
||||||
new_page.map(|new_page| {
|
|
||||||
*page = new_page;
|
*page = new_page;
|
||||||
// Make sure we re-render
|
// Make sure we re-render
|
||||||
*rect = Rect::default();
|
*rect = Rect::default();
|
||||||
InputAction::JumpingToPage(new_page)
|
InputAction::JumpingToPage(new_page)
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let can_zoom = self.is_kitty && self.zoom.is_some();
|
||||||
|
|
||||||
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);
|
||||||
return Some(InputAction::Redraw);
|
InputAction::Redraw.into()
|
||||||
}
|
}
|
||||||
|
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 && matches!(c, 'g' if self.is_kitty) =>
|
||||||
{
|
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
|
||||||
});
|
}),
|
||||||
|
KeyCode::Char(_)
|
||||||
|
if let BottomMessage::Input(InputCommand::GoToPage(_)) =
|
||||||
|
self.bottom_msg =>
|
||||||
|
{
|
||||||
|
self.set_msg(MessageSetting::Pop);
|
||||||
|
self.update_zoom(Zoom::pan_bottom)
|
||||||
}
|
}
|
||||||
|
KeyCode::Char(c) => match c {
|
||||||
match c {
|
|
||||||
'l' => self.change_page(PageChange::Next, ChangeAmount::Single),
|
'l' => self.change_page(PageChange::Next, ChangeAmount::Single),
|
||||||
'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
|
'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
|
||||||
'h' => self.change_page(PageChange::Prev, ChangeAmount::Single),
|
'h' => self.change_page(PageChange::Prev, ChangeAmount::Single),
|
||||||
@@ -590,22 +776,21 @@ impl Tui {
|
|||||||
Some(InputAction::Redraw)
|
Some(InputAction::Redraw)
|
||||||
}
|
}
|
||||||
'f' => Some(InputAction::Fullscreen),
|
'f' => Some(InputAction::Fullscreen),
|
||||||
'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)..]
|
'n' if self.page < self.rendered.len() - 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, &mut self.last_render.rect, next_page)
|
||||||
}
|
}),
|
||||||
'N' if self.page > 0 => {
|
'N' if self.page > 0 => self.rendered[..(self.page)]
|
||||||
let prev_page = self.rendered[..(self.page)]
|
|
||||||
.iter()
|
.iter()
|
||||||
.rev()
|
.rev()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -613,10 +798,10 @@ impl Tui {
|
|||||||
p.num_results
|
p.num_results
|
||||||
.is_some_and(|num| num > 0)
|
.is_some_and(|num| num > 0)
|
||||||
.then_some(self.page - (idx + 1))
|
.then_some(self.page - (idx + 1))
|
||||||
});
|
})
|
||||||
|
.map(|prev_page| {
|
||||||
jump_to_page(&mut self.page, &mut self.last_render.rect, 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?
|
||||||
|
|
||||||
@@ -630,10 +815,17 @@ impl Tui {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
disable_raw_mode().unwrap();
|
disable_raw_mode().unwrap();
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
// This process will hang after the SIGSTOP call until we get
|
// This process will hang after the SIGSTOP call until we get
|
||||||
// foregrounded again by something else, at which point we need to
|
// foregrounded again by something else, at which point we need to
|
||||||
// re-setup everything so that it all gets drawn again.
|
// re-setup everything so that it all gets drawn again.
|
||||||
kill(Pid::this(), SIGSTOP).unwrap();
|
nix::sys::signal::kill(
|
||||||
|
nix::unistd::Pid::this(),
|
||||||
|
nix::sys::signal::Signal::SIGSTOP
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
enable_raw_mode().unwrap();
|
enable_raw_mode().unwrap();
|
||||||
execute!(
|
execute!(
|
||||||
@@ -656,39 +848,31 @@ 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 can_zoom => self.update_zoom(Zoom::step_in),
|
||||||
// TODO: for now, we don't let people zoom in past fill-screen
|
'O' if can_zoom => self.update_zoom(Zoom::step_out),
|
||||||
z.level = z.level.saturating_add(1).min(0)),
|
'L' if can_zoom => self.update_zoom(|z| z.pan(Direction::Right)),
|
||||||
'O' if self.is_kitty =>
|
'H' if can_zoom => self.update_zoom(|z| z.pan(Direction::Left)),
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
|
'J' if can_zoom => self.update_zoom(|z| z.pan(Direction::Down)),
|
||||||
'L' if self.is_kitty => self.update_zoom(|z| {
|
'K' if can_zoom => self.update_zoom(|z| z.pan(Direction::Up)),
|
||||||
z.cell_pan_from_left = z.cell_pan_from_left.saturating_add(1)
|
'G' if can_zoom => self.update_zoom(Zoom::pan_top),
|
||||||
}),
|
'0' if can_zoom => self.update_zoom(Zoom::pan_left),
|
||||||
'H' if self.is_kitty => self.update_zoom(|z| {
|
'$' if can_zoom => self.update_zoom(Zoom::pan_right),
|
||||||
z.cell_pan_from_left = z.cell_pan_from_left.saturating_sub(1)
|
'r' => Some(InputAction::Rotate),
|
||||||
}),
|
|
||||||
'J' if self.is_kitty => self.update_zoom(|z| {
|
|
||||||
z.cell_pan_from_top = z.cell_pan_from_top.saturating_add(1)
|
|
||||||
}),
|
|
||||||
'K' if self.is_kitty => self.update_zoom(|z| {
|
|
||||||
z.cell_pan_from_top = z.cell_pan_from_top.saturating_sub(1)
|
|
||||||
}),
|
|
||||||
_ => None
|
_ => None
|
||||||
}
|
},
|
||||||
}
|
KeyCode::Backspace
|
||||||
KeyCode::Backspace => {
|
|
||||||
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.pop();
|
term.pop();
|
||||||
return Some(InputAction::Redraw);
|
InputAction::Redraw.into()
|
||||||
}
|
|
||||||
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),
|
||||||
_ => {
|
_ => {
|
||||||
@@ -757,29 +941,36 @@ impl Tui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Event::Mouse(mouse) => {
|
Event::Mouse(mouse) => {
|
||||||
if mouse.modifiers.contains(KeyModifiers::CONTROL)
|
let mut handle_scroll = |mut direction: Direction| {
|
||||||
&& self.is_kitty
|
if can_zoom {
|
||||||
&& self.zoom.is_some()
|
if mouse.modifiers.contains(KeyModifiers::CONTROL) {
|
||||||
{
|
match direction {
|
||||||
match mouse.kind {
|
Direction::Up => self.update_zoom(Zoom::step_in),
|
||||||
MouseEventKind::ScrollUp =>
|
Direction::Down => self.update_zoom(Zoom::step_out),
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_add(1).min(0)),
|
|
||||||
MouseEventKind::ScrollDown =>
|
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
|
|
||||||
_ => None
|
_ => None
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
match mouse.kind {
|
if mouse.modifiers.contains(KeyModifiers::SHIFT) {
|
||||||
MouseEventKind::ScrollRight =>
|
direction = direction.flip_mouse_xy();
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
self.update_zoom(|z| z.pan(direction))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let (change, amount) = match direction {
|
||||||
|
Direction::Right => (PageChange::Next, ChangeAmount::Single),
|
||||||
|
Direction::Down => (PageChange::Next, ChangeAmount::WholeScreen),
|
||||||
|
Direction::Left => (PageChange::Prev, ChangeAmount::Single),
|
||||||
|
Direction::Up => (PageChange::Prev, ChangeAmount::WholeScreen)
|
||||||
|
};
|
||||||
|
self.change_page(change, amount)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match mouse.kind {
|
||||||
|
MouseEventKind::ScrollRight => handle_scroll(Direction::Right),
|
||||||
|
MouseEventKind::ScrollDown => handle_scroll(Direction::Down),
|
||||||
|
MouseEventKind::ScrollLeft => handle_scroll(Direction::Left),
|
||||||
|
MouseEventKind::ScrollUp => handle_scroll(Direction::Up),
|
||||||
|
_ => None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Event::Resize(_, _) => Some(InputAction::Redraw),
|
Event::Resize(_, _) => Some(InputAction::Redraw),
|
||||||
@@ -787,11 +978,11 @@ impl Tui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
||||||
@@ -847,11 +1038,24 @@ impl Tui {
|
|||||||
.border_set(border::ROUNDED)
|
.border_set(border::ROUNDED)
|
||||||
.border_style(Color::Blue);
|
.border_style(Color::Blue);
|
||||||
|
|
||||||
let help_span = Paragraph::new(HELP_PAGE).wrap(Wrap { trim: false });
|
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()
|
||||||
@@ -866,15 +1070,24 @@ 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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -895,24 +1108,35 @@ i:
|
|||||||
Invert colors
|
Invert colors
|
||||||
f:
|
f:
|
||||||
Remove borders/fullscreen
|
Remove borders/fullscreen
|
||||||
z (when using kitty protocol):
|
|
||||||
Toggle between fill-screen and fit-screen
|
|
||||||
o/O (when on fill-screen):
|
|
||||||
zoom in and out, respectively
|
|
||||||
H, J, K, L (when zoomed in):
|
|
||||||
pan direction around page
|
|
||||||
?:
|
?:
|
||||||
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
|
||||||
|
0/$ (when on fill-screen):
|
||||||
|
Scroll to left/right side of page
|
||||||
|
r:
|
||||||
|
Rotate by 90 degrees
|
||||||
|
";
|
||||||
|
|
||||||
pub enum InputAction {
|
pub enum InputAction {
|
||||||
Redraw,
|
Redraw,
|
||||||
JumpingToPage(usize),
|
JumpingToPage(usize),
|
||||||
Search(String),
|
Search(String),
|
||||||
QuitApp,
|
QuitApp,
|
||||||
Invert,
|
Invert,
|
||||||
|
Rotate,
|
||||||
Fullscreen,
|
Fullscreen,
|
||||||
SwitchRenderZoom(crate::FitOrFill)
|
SwitchRenderZoom(crate::FitOrFill)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user