mirror of
https://github.com/itsjunetime/tdf.git
synced 2026-06-01 23:51:46 -04:00
Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8d73a38c51 | |||
| 2fbf7b3ef2 | |||
| 7f07c21791 | |||
| 25579ad2c3 | |||
| 421401c7a7 | |||
| 7448fc73c5 | |||
| 1ed03e94fb | |||
| cf9d295d95 | |||
| 725c6c6bfd | |||
| fca61d55b5 | |||
| 59c0e2338b | |||
| 52994b8b89 | |||
| 2f957cdcbb | |||
| f2be5e39fb | |||
| 2d40444273 | |||
| 580af3668f | |||
| 577141e201 | |||
| 828db8aed3 | |||
| 39a4bdafb6 | |||
| 19030f7fd4 | |||
| d5d62c81a3 |
+95
-29
@@ -2,41 +2,107 @@ 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:
|
||||||
- name: Setup sccache
|
- uses: actions/checkout@v6
|
||||||
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
|
||||||
uses: mozilla-actions/sccache-action@v0.0.8
|
- name: Setup sccache
|
||||||
- name: Configure 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
|
||||||
run: |
|
- name: Configure sccache
|
||||||
echo "SCCACHE_GHA_ENABLED=true" >> $GITHUB_ENV
|
if: github.event_name != 'release' && github.event_name != 'workflow_dispatch'
|
||||||
echo "RUSTC_WRAPPER=sccache" >> $GITHUB_ENV
|
run: |
|
||||||
- name: Install build dependencies
|
echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
|
||||||
run: |
|
echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y libfontconfig1-dev libgoogle-perftools-dev google-perftools
|
- name: Setup rust cache action
|
||||||
- uses: actions/checkout@v4
|
uses: swatinem/rust-cache@v2
|
||||||
- name: Install clippy and fmt
|
with:
|
||||||
run: rustup component add clippy rustfmt
|
cache-on-failure: true
|
||||||
- name: Clippy
|
|
||||||
run: cargo clippy --locked -- -D warnings
|
- name: install build dependencies on ubuntu and cache
|
||||||
- name: Tests
|
if: contains(matrix.os, 'ubuntu')
|
||||||
run: cargo test --locked
|
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||||
- name: Check fmt
|
with:
|
||||||
run: cargo fmt -- --check
|
packages: libfontconfig1-dev libgoogle-perftools-dev google-perftools
|
||||||
- name: Run benchmarks as tests
|
version: latest # could be anything
|
||||||
run: cargo test --locked --benches -- adobe_example
|
|
||||||
- name: Build
|
- name: Install clippy and fmt
|
||||||
run: cargo build --locked
|
run: rustup component add clippy rustfmt
|
||||||
|
- name: Clippy
|
||||||
|
run: cargo clippy --locked -- -D warnings
|
||||||
|
- name: Tests
|
||||||
|
run: cargo test --locked
|
||||||
|
- name: Check fmt
|
||||||
|
run: cargo fmt -- --check
|
||||||
|
- name: Run benchmarks as tests
|
||||||
|
run: cargo test --locked --benches -- adobe_example
|
||||||
|
|
||||||
|
- 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,10 @@
|
|||||||
# 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
|
# v0.5.0
|
||||||
|
|
||||||
- Switched simd base64 crate for one that works on stable (from `vb64` to `base64_simd`)
|
- Switched simd base64 crate for one that works on stable (from `vb64` to `base64_simd`)
|
||||||
|
|||||||
Generated
+519
-883
File diff suppressed because it is too large
Load Diff
+13
-9
@@ -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,16 +34,18 @@ 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 = "1", 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 = { version = "0.1.1", features = ["crossterm-tokio", "image-crate", "log"] }
|
kittage = { version = "0.4.0", features = ["crossterm-tokio", "image-crate", "log"] }
|
||||||
memmap2 = "0"
|
memmap2 = "0"
|
||||||
csscolorparser = { version = "0.8.0", default-features = false }
|
csscolorparser = { version = "0.8.0", default-features = false }
|
||||||
|
debounce = "0.2.2"
|
||||||
|
smallvec = "1"
|
||||||
|
|
||||||
# logging
|
# logging
|
||||||
log = "0.4.27"
|
log = "0.4.27"
|
||||||
@@ -51,7 +53,9 @@ flexi_logger = "0.31"
|
|||||||
|
|
||||||
# for tracing with tokio-console
|
# for tracing with tokio-console
|
||||||
console-subscriber = { version = "0.5.0", optional = true }
|
console-subscriber = { version = "0.5.0", optional = true }
|
||||||
debounce = "0.2.2"
|
|
||||||
|
[patch.crates-io]
|
||||||
|
pathfinder_simd = { git = "https://github.com/itsjunetime/pathfinder.git", rev = "814671e162a1829e074521446317b915311d3d4d" }
|
||||||
|
|
||||||
[profile.production]
|
[profile.production]
|
||||||
inherits = "release"
|
inherits = "release"
|
||||||
@@ -64,7 +68,7 @@ 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]]
|
||||||
|
|||||||
@@ -34,7 +34,12 @@ fn for_all_combos(
|
|||||||
name: &'static str,
|
name: &'static str,
|
||||||
mut f: impl FnMut(&Runtime, BenchmarkId, &'static str, ProtocolType)
|
mut f: impl FnMut(&Runtime, BenchmarkId, &'static str, ProtocolType)
|
||||||
) {
|
) {
|
||||||
let rt = tokio::runtime::Runtime::new().unwrap();
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(3)
|
||||||
|
.enable_time()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
for proto in PROTOS {
|
for proto in PROTOS {
|
||||||
for file in FILES {
|
for file in FILES {
|
||||||
f(
|
f(
|
||||||
|
|||||||
+2
-2
@@ -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,
|
||||||
@@ -117,6 +116,7 @@ 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(proto);
|
picker.set_protocol_type(proto);
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule ratatui updated: 6a0b8ddf76...720ac2d0ca
+1
-1
Submodule ratatui-image updated: 9564ae6466...8ad154a219
@@ -5,10 +5,7 @@ pkgs.mkShell {
|
|||||||
nativeBuildInputs = [ pkgs.pkg-config ];
|
nativeBuildInputs = [ pkgs.pkg-config ];
|
||||||
|
|
||||||
buildInputs = [
|
buildInputs = [
|
||||||
pkgs.cargo
|
|
||||||
pkgs.rustc
|
|
||||||
pkgs.rustPlatform.bindgenHook
|
pkgs.rustPlatform.bindgenHook
|
||||||
pkgs.cairo
|
pkgs.cairo
|
||||||
pkgs.rust-analyzer
|
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
+34
-23
@@ -1,12 +1,13 @@
|
|||||||
use std::{
|
use std::{
|
||||||
num::NonZeroUsize,
|
io::Cursor,
|
||||||
|
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 as _;
|
use futures_util::stream::StreamExt as _;
|
||||||
use image::DynamicImage;
|
use image::{DynamicImage, codecs::pnm::PnmDecoder};
|
||||||
use kittage::{NumberOrId, action::NONZERO_ONE};
|
use kittage::NumberOrId;
|
||||||
use ratatui::layout::Rect;
|
use ratatui::layout::Rect;
|
||||||
use ratatui_image::{
|
use ratatui_image::{
|
||||||
Resize,
|
Resize,
|
||||||
@@ -111,22 +112,26 @@ 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}")))?;
|
})?;
|
||||||
|
|
||||||
match dyn_img {
|
// The image we get should always already be `ImageRgb8`, so this `into` shouldn't do any
|
||||||
DynamicImage::ImageRgb8(ref mut img) =>
|
// conversions or anything, but just in case some underlying detail of mupdf or image
|
||||||
for quad in &*page_info.result_rects {
|
// changes, we do the `into` instead of just `match + unreachable!()` to avoid panicking
|
||||||
img.par_enumerate_pixels_mut()
|
let mut dyn_img = DynamicImage::from_decoder(decoder)
|
||||||
.filter(|(x, y, _)| {
|
.map_err(|e| RenderError::Converting(format!("Can't load image: {e}")))?
|
||||||
*x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_y
|
.into_rgb8();
|
||||||
})
|
|
||||||
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
for quad in &*page_info.result_rects {
|
||||||
},
|
dyn_img
|
||||||
_ => unreachable!()
|
.par_enumerate_pixels_mut()
|
||||||
|
.filter(|(x, y, _)| {
|
||||||
|
*x > quad.ul_x && *x < quad.lr_x && *y > quad.ul_y && *y < quad.lr_y
|
||||||
|
})
|
||||||
|
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
let img_area = Rect {
|
let img_area = Rect {
|
||||||
@@ -136,6 +141,8 @@ 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()
|
||||||
@@ -144,16 +151,20 @@ pub async fn run_conversion_loop(
|
|||||||
.as_nanos() % 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)
|
||||||
};
|
};
|
||||||
|
|
||||||
// if ur pdf has 4 billion pages then you deserve to suffer
|
// if ur pdf has 4 billion pages then you deserve to suffer
|
||||||
img.num_or_id = NumberOrId::Id(NONZERO_ONE.saturating_add(page_num as u32));
|
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),
|
||||||
|
|||||||
+93
-40
@@ -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;
|
||||||
|
|
||||||
@@ -63,7 +65,7 @@ impl<W: Write> Write for DbgWriter<W> {
|
|||||||
pub async fn run_action<'es>(
|
pub async fn run_action<'es>(
|
||||||
action: Action<'_, '_>,
|
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<'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 mut err = None;
|
let new_z_index = last_z_index.wrapping_add_unsigned(1);
|
||||||
|
|
||||||
|
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(|_| ())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -42,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
|
||||||
|
|||||||
+69
-31
@@ -38,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}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -70,11 +72,18 @@ fn reset_term() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
fn main() -> Result<(), WrappedErr> {
|
||||||
async fn main() -> Result<(), WrappedErr> {
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
let result = inner_main().await;
|
.worker_threads(3)
|
||||||
reset_term();
|
.enable_time()
|
||||||
result
|
.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> {
|
||||||
@@ -128,21 +137,37 @@ 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
|
||||||
WrappedErr(
|
.as_deref()
|
||||||
format!("Couldn't parse black color: {e} - is it formatted like a CSS color?")
|
.map(|color| {
|
||||||
|
parse_color_to_i32(color).map_err(|e| {
|
||||||
|
WrappedErr(
|
||||||
|
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
|
||||||
WrappedErr(
|
.as_deref()
|
||||||
format!("Couldn't parse white color: {e} - is it formatted like a CSS color?")
|
.map(|color| {
|
||||||
|
parse_color_to_i32(color).map_err(|e| {
|
||||||
|
WrappedErr(
|
||||||
|
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.
|
||||||
@@ -193,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())
|
||||||
})?;
|
})?;
|
||||||
@@ -234,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()
|
||||||
)),
|
)),
|
||||||
@@ -250,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,
|
||||||
@@ -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))?;
|
||||||
|
|||||||
+65
-11
@@ -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) {
|
||||||
@@ -80,7 +89,7 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
|
|||||||
// 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.
|
||||||
#[expect(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)))?;
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -277,7 +306,7 @@ pub fn start_rendering(
|
|||||||
// we only want to continue if one of the following is met:
|
// we only want to continue if one of the following is met:
|
||||||
// 1. It failed to render last time (we want to retry)
|
// 1. It failed to render last time (we want to retry)
|
||||||
// 2. The `contained_term` is set to Unknown, meaning that we need to at least
|
// 2. The `contained_term` is set to Unknown, meaning that we need to at least
|
||||||
// check if it contains the current term to see if it needs a re-render
|
// check if it contains the current term to see if it needs a re-render
|
||||||
if rendered.successful && rendered.num_search_found.is_some() {
|
if rendered.successful && rendered.num_search_found.is_some() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -570,4 +613,15 @@ impl Iterator for PopOnNext<'_> {
|
|||||||
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()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+222
-165
@@ -9,10 +9,6 @@ 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},
|
||||||
@@ -102,6 +98,70 @@ impl Zoom {
|
|||||||
ZOOM_RATE_GRANULAR.powi(self.level.into())
|
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
|
||||||
@@ -288,7 +348,6 @@ impl Tui {
|
|||||||
}])
|
}])
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Make a way to fill the width of the screen with one page and scroll down to view it
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn render<'s>(
|
pub fn render<'s>(
|
||||||
&'s mut self,
|
&'s mut self,
|
||||||
@@ -637,160 +696,146 @@ impl Tui {
|
|||||||
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| {
|
||||||
if c == 'g' && self.is_kitty {
|
*page = (*page * 10) + input_num as usize;
|
||||||
self.update_zoom(|z| z.cell_pan_from_top = 0);
|
InputAction::Redraw
|
||||||
self.set_msg(MessageSetting::Pop);
|
}),
|
||||||
return Some(InputAction::Redraw);
|
KeyCode::Char(_)
|
||||||
}
|
if let BottomMessage::Input(InputCommand::GoToPage(_)) =
|
||||||
|
self.bottom_msg =>
|
||||||
return c.to_digit(10).map(|input_num| {
|
{
|
||||||
*page = (*page * 10) + input_num as usize;
|
self.set_msg(MessageSetting::Pop);
|
||||||
InputAction::Redraw
|
self.update_zoom(Zoom::pan_bottom)
|
||||||
});
|
}
|
||||||
|
KeyCode::Char(c) => match c {
|
||||||
|
'l' => self.change_page(PageChange::Next, ChangeAmount::Single),
|
||||||
|
'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
|
||||||
|
'h' => self.change_page(PageChange::Prev, ChangeAmount::Single),
|
||||||
|
'k' => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
|
||||||
|
'q' => Some(InputAction::QuitApp),
|
||||||
|
'g' => {
|
||||||
|
self.set_msg(MessageSetting::Some(BottomMessage::Input(
|
||||||
|
InputCommand::GoToPage(0)
|
||||||
|
)));
|
||||||
|
Some(InputAction::Redraw)
|
||||||
}
|
}
|
||||||
|
'/' => {
|
||||||
|
self.set_msg(MessageSetting::Some(BottomMessage::Input(
|
||||||
|
InputCommand::Search(String::new())
|
||||||
|
)));
|
||||||
|
Some(InputAction::Redraw)
|
||||||
|
}
|
||||||
|
'i' => Some(InputAction::Invert),
|
||||||
|
'?' => {
|
||||||
|
self.showing_help_msg = true;
|
||||||
|
Some(InputAction::Redraw)
|
||||||
|
}
|
||||||
|
'f' => Some(InputAction::Fullscreen),
|
||||||
|
// TODO: If we can't find one, then maybe like block until we've verified
|
||||||
|
// all the pages have been checked?
|
||||||
|
'n' if self.page < self.rendered.len() - 1 => self.rendered
|
||||||
|
[(self.page + 1)..]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.find_map(|(idx, p)| {
|
||||||
|
p.num_results
|
||||||
|
.is_some_and(|num| num > 0)
|
||||||
|
.then_some(self.page + 1 + idx)
|
||||||
|
})
|
||||||
|
.map(|next_page| {
|
||||||
|
jump_to_page(&mut self.page, &mut self.last_render.rect, next_page)
|
||||||
|
}),
|
||||||
|
'N' if self.page > 0 => self.rendered[..(self.page)]
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.enumerate()
|
||||||
|
.find_map(|(idx, p)| {
|
||||||
|
p.num_results
|
||||||
|
.is_some_and(|num| num > 0)
|
||||||
|
.then_some(self.page - (idx + 1))
|
||||||
|
})
|
||||||
|
.map(|prev_page| {
|
||||||
|
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
|
||||||
|
}),
|
||||||
|
'z' if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
||||||
|
// [todo] better error handling here?
|
||||||
|
|
||||||
match c {
|
let mut backend = stdout();
|
||||||
'l' => self.change_page(PageChange::Next, ChangeAmount::Single),
|
execute!(
|
||||||
'j' => self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
|
&mut backend,
|
||||||
'h' => self.change_page(PageChange::Prev, ChangeAmount::Single),
|
LeaveAlternateScreen,
|
||||||
'k' => self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
|
crossterm::cursor::Show,
|
||||||
'q' => Some(InputAction::QuitApp),
|
crossterm::event::DisableMouseCapture
|
||||||
'g' => {
|
)
|
||||||
self.set_msg(MessageSetting::Some(BottomMessage::Input(
|
.unwrap();
|
||||||
InputCommand::GoToPage(0)
|
disable_raw_mode().unwrap();
|
||||||
)));
|
|
||||||
Some(InputAction::Redraw)
|
|
||||||
}
|
|
||||||
'/' => {
|
|
||||||
self.set_msg(MessageSetting::Some(BottomMessage::Input(
|
|
||||||
InputCommand::Search(String::new())
|
|
||||||
)));
|
|
||||||
Some(InputAction::Redraw)
|
|
||||||
}
|
|
||||||
'i' => Some(InputAction::Invert),
|
|
||||||
'?' => {
|
|
||||||
self.showing_help_msg = true;
|
|
||||||
Some(InputAction::Redraw)
|
|
||||||
}
|
|
||||||
'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
|
|
||||||
// all the pages have been checked?
|
|
||||||
self.rendered[(self.page + 1)..]
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.find_map(|(idx, p)| {
|
|
||||||
p.num_results
|
|
||||||
.is_some_and(|num| num > 0)
|
|
||||||
.then_some(self.page + 1 + idx)
|
|
||||||
})
|
|
||||||
.map(|next_page| {
|
|
||||||
jump_to_page(
|
|
||||||
&mut self.page,
|
|
||||||
&mut self.last_render.rect,
|
|
||||||
next_page
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
'N' if self.page > 0 => self.rendered[..(self.page)]
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.enumerate()
|
|
||||||
.find_map(|(idx, p)| {
|
|
||||||
p.num_results
|
|
||||||
.is_some_and(|num| num > 0)
|
|
||||||
.then_some(self.page - (idx + 1))
|
|
||||||
})
|
|
||||||
.map(|prev_page| {
|
|
||||||
jump_to_page(
|
|
||||||
&mut self.page,
|
|
||||||
&mut self.last_render.rect,
|
|
||||||
prev_page
|
|
||||||
)
|
|
||||||
}),
|
|
||||||
'z' if key.modifiers.contains(KeyModifiers::CONTROL) => {
|
|
||||||
// [todo] better error handling here?
|
|
||||||
|
|
||||||
let mut backend = stdout();
|
|
||||||
execute!(
|
|
||||||
&mut backend,
|
|
||||||
LeaveAlternateScreen,
|
|
||||||
crossterm::cursor::Show,
|
|
||||||
crossterm::event::DisableMouseCapture
|
|
||||||
)
|
|
||||||
.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(),
|
||||||
enable_raw_mode().unwrap();
|
nix::sys::signal::Signal::SIGSTOP
|
||||||
execute!(
|
|
||||||
&mut backend,
|
|
||||||
EnterAlternateScreen,
|
|
||||||
crossterm::cursor::Hide,
|
|
||||||
crossterm::event::EnableMouseCapture
|
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
self.last_render.rect = Rect::default();
|
enable_raw_mode().unwrap();
|
||||||
Some(InputAction::Redraw)
|
execute!(
|
||||||
}
|
&mut backend,
|
||||||
'z' if self.is_kitty => {
|
EnterAlternateScreen,
|
||||||
let (zoom, f_or_f) = match self.zoom {
|
crossterm::cursor::Hide,
|
||||||
None => (Some(Zoom::default()), FitOrFill::Fill),
|
crossterm::event::EnableMouseCapture
|
||||||
Some(_) => (None, FitOrFill::Fit)
|
)
|
||||||
};
|
.unwrap();
|
||||||
self.zoom = zoom;
|
|
||||||
self.last_render.rect = Rect::default();
|
self.last_render.rect = Rect::default();
|
||||||
Some(InputAction::SwitchRenderZoom(f_or_f))
|
Some(InputAction::Redraw)
|
||||||
}
|
|
||||||
'o' if self.is_kitty =>
|
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_add(1)),
|
|
||||||
'O' if self.is_kitty =>
|
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
|
|
||||||
'L' if self.is_kitty => self.update_zoom(|z| {
|
|
||||||
z.cell_pan_from_left = z.cell_pan_from_left.saturating_add(1);
|
|
||||||
}),
|
|
||||||
'H' if self.is_kitty => self.update_zoom(|z| {
|
|
||||||
z.cell_pan_from_left = z.cell_pan_from_left.saturating_sub(1);
|
|
||||||
}),
|
|
||||||
'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);
|
|
||||||
}),
|
|
||||||
'G' if self.is_kitty =>
|
|
||||||
self.update_zoom(|z| z.cell_pan_from_top = u16::MAX),
|
|
||||||
_ => None
|
|
||||||
}
|
}
|
||||||
}
|
'z' if self.is_kitty => {
|
||||||
KeyCode::Backspace => {
|
let (zoom, f_or_f) = match self.zoom {
|
||||||
|
None => (Some(Zoom::default()), FitOrFill::Fill),
|
||||||
|
Some(_) => (None, FitOrFill::Fit)
|
||||||
|
};
|
||||||
|
self.zoom = zoom;
|
||||||
|
self.last_render.rect = Rect::default();
|
||||||
|
Some(InputAction::SwitchRenderZoom(f_or_f))
|
||||||
|
}
|
||||||
|
'o' if can_zoom => self.update_zoom(Zoom::step_in),
|
||||||
|
'O' if can_zoom => self.update_zoom(Zoom::step_out),
|
||||||
|
'L' if can_zoom => self.update_zoom(|z| z.pan(Direction::Right)),
|
||||||
|
'H' if can_zoom => self.update_zoom(|z| z.pan(Direction::Left)),
|
||||||
|
'J' if can_zoom => self.update_zoom(|z| z.pan(Direction::Down)),
|
||||||
|
'K' if can_zoom => self.update_zoom(|z| z.pan(Direction::Up)),
|
||||||
|
'G' if can_zoom => self.update_zoom(Zoom::pan_top),
|
||||||
|
'0' if can_zoom => self.update_zoom(Zoom::pan_left),
|
||||||
|
'$' if can_zoom => self.update_zoom(Zoom::pan_right),
|
||||||
|
'r' => Some(InputAction::Rotate),
|
||||||
|
_ => None
|
||||||
|
},
|
||||||
|
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 | KeyCode::PageDown =>
|
KeyCode::Down | KeyCode::PageDown =>
|
||||||
@@ -866,29 +911,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)),
|
_ => None
|
||||||
MouseEventKind::ScrollDown =>
|
}
|
||||||
self.update_zoom(|z| z.level = z.level.saturating_sub(1)),
|
} else {
|
||||||
_ => None
|
if mouse.modifiers.contains(KeyModifiers::SHIFT) {
|
||||||
}
|
direction = direction.flip_mouse_xy();
|
||||||
} else {
|
}
|
||||||
match mouse.kind {
|
self.update_zoom(|z| z.pan(direction))
|
||||||
MouseEventKind::ScrollRight =>
|
}
|
||||||
self.change_page(PageChange::Next, ChangeAmount::Single),
|
} else {
|
||||||
MouseEventKind::ScrollDown =>
|
let (change, amount) = match direction {
|
||||||
self.change_page(PageChange::Next, ChangeAmount::WholeScreen),
|
Direction::Right => (PageChange::Next, ChangeAmount::Single),
|
||||||
MouseEventKind::ScrollLeft =>
|
Direction::Down => (PageChange::Next, ChangeAmount::WholeScreen),
|
||||||
self.change_page(PageChange::Prev, ChangeAmount::Single),
|
Direction::Left => (PageChange::Prev, ChangeAmount::Single),
|
||||||
MouseEventKind::ScrollUp =>
|
Direction::Up => (PageChange::Prev, ChangeAmount::WholeScreen)
|
||||||
self.change_page(PageChange::Prev, ChangeAmount::WholeScreen),
|
};
|
||||||
_ => None
|
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),
|
||||||
@@ -1042,6 +1094,10 @@ gg/G (when on fill-screen):
|
|||||||
Scroll to top/bottom of page
|
Scroll to top/bottom of page
|
||||||
H, J, K, L (when zoomed in):
|
H, J, K, L (when zoomed in):
|
||||||
Pan direction around page
|
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 {
|
||||||
@@ -1050,6 +1106,7 @@ pub enum InputAction {
|
|||||||
Search(String),
|
Search(String),
|
||||||
QuitApp,
|
QuitApp,
|
||||||
Invert,
|
Invert,
|
||||||
|
Rotate,
|
||||||
Fullscreen,
|
Fullscreen,
|
||||||
SwitchRenderZoom(crate::FitOrFill)
|
SwitchRenderZoom(crate::FitOrFill)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user