mirror of
https://github.com/itsjunetime/tdf.git
synced 2026-08-25 20:54:30 -04:00
Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| de0050499e | |||
| fd275acecb | |||
| c2117daaf5 | |||
| 06f737b1fe | |||
| 95c24206ca | |||
| 5e4fbff9cd |
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
- Added windows support! (thank you to [@jarjk](https://github.com/jarjk) for helping out!)
|
- 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)!)
|
- 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)!)
|
||||||
|
- Added `-t` flag to use terminal foreground/background colors in pdf rendering ([#138](https://github.com/itsjunetime/tdf/pull/138), thank you [@unorsk](https://github.com/unorsk)!
|
||||||
|
- Fixed issue with images clearing/flashing after displaying a certain number on kitty
|
||||||
- (Internal) decreased runtime footprint of tokio runtime
|
- (Internal) decreased runtime footprint of tokio runtime
|
||||||
|
|
||||||
# v0.5.0
|
# v0.5.0
|
||||||
|
|||||||
Generated
+731
-396
File diff suppressed because it is too large
Load Diff
+3
-11
@@ -22,21 +22,16 @@ path = "src/main.rs"
|
|||||||
name = "tdf"
|
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
|
ratatui = { version = "^0.30.1", default-features = false, features = [ "crossterm", "layout-cache" ] }
|
||||||
ratatui = { git = "https://github.com/itsjunetime/ratatui.git", rev = "720ac2d0cad1ac6424364fea74856fec9c100cb1", default-features = false, features = [ "crossterm", "layout-cache" ] }
|
ratatui-image = { version = "11.0", default-features = false }
|
||||||
# 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
|
|
||||||
ratatui-image = { git = "https://github.com/itsjunetime/ratatui-image.git", rev = "a276a87cb8e2976442c6cc59db831db81551da89", 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"] }
|
|
||||||
image = { version = "0.25.1", features = ["pnm", "rayon", "png"], default-features = false }
|
image = { version = "0.25.1", features = ["pnm", "rayon", "png"], default-features = false }
|
||||||
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.12.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 = { git = "https://github.com/itsjunetime/mimalloc_rust.git", rev = "1094dbf3afdc0a57215e925a05f2e3160e59575b", features = [ "debug_in_debug" ] }
|
||||||
nix = { version = "0.31.0", features = ["signal"] }
|
nix = { version = "0.31.0", features = ["signal"] }
|
||||||
mupdf = { git = "https://github.com/messense/mupdf-rs.git", rev = "d7441b9998c92135e329559c0aa71d9dc92cf4de", 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 }
|
||||||
@@ -54,9 +49,6 @@ 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 }
|
||||||
|
|
||||||
[patch.crates-io]
|
|
||||||
pathfinder_simd = { git = "https://github.com/itsjunetime/pathfinder.git", branch = "fix_nightly_arm_simd" }
|
|
||||||
|
|
||||||
[profile.production]
|
[profile.production]
|
||||||
inherits = "release"
|
inherits = "release"
|
||||||
lto = "fat"
|
lto = "fat"
|
||||||
|
|||||||
+10
-4
@@ -4,7 +4,10 @@ use crossterm::terminal::WindowSize;
|
|||||||
use flume::{Sender, r#async::RecvStream, unbounded};
|
use flume::{Sender, r#async::RecvStream, unbounded};
|
||||||
use futures_util::stream::StreamExt as _;
|
use futures_util::stream::StreamExt as _;
|
||||||
use ratatui::layout::Rect;
|
use ratatui::layout::Rect;
|
||||||
use ratatui_image::picker::{Picker, ProtocolType};
|
use ratatui_image::{
|
||||||
|
FontSize,
|
||||||
|
picker::{Picker, ProtocolType}
|
||||||
|
};
|
||||||
use tdf::{
|
use tdf::{
|
||||||
converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
|
converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
|
||||||
renderer::{RenderError, RenderInfo, RenderNotif, fill_default, start_rendering}
|
renderer::{RenderError, RenderInfo, RenderNotif, fill_default, start_rendering}
|
||||||
@@ -54,7 +57,10 @@ pub struct RenderState {
|
|||||||
pub to_render_tx: Sender<RenderNotif>
|
pub to_render_tx: Sender<RenderNotif>
|
||||||
}
|
}
|
||||||
|
|
||||||
const FONT_SIZE: (u16, u16) = (8, 14);
|
const FONT_SIZE: FontSize = FontSize {
|
||||||
|
width: 8,
|
||||||
|
height: 14
|
||||||
|
};
|
||||||
|
|
||||||
pub fn start_rendering_loop(
|
pub fn start_rendering_loop(
|
||||||
path: impl AsRef<Path>,
|
path: impl AsRef<Path>,
|
||||||
@@ -74,8 +80,8 @@ pub fn start_rendering_loop(
|
|||||||
let size = WindowSize {
|
let size = WindowSize {
|
||||||
columns,
|
columns,
|
||||||
rows,
|
rows,
|
||||||
height: rows * FONT_SIZE.1,
|
height: rows * FONT_SIZE.height,
|
||||||
width: columns * FONT_SIZE.0
|
width: columns * FONT_SIZE.width
|
||||||
};
|
};
|
||||||
|
|
||||||
let main_area = Rect {
|
let main_area = Rect {
|
||||||
|
|||||||
+8
-10
@@ -8,7 +8,7 @@ use flume::{Receiver, SendError, Sender, TryRecvError};
|
|||||||
use futures_util::stream::StreamExt as _;
|
use futures_util::stream::StreamExt as _;
|
||||||
use image::{DynamicImage, codecs::pnm::PnmDecoder};
|
use image::{DynamicImage, codecs::pnm::PnmDecoder};
|
||||||
use kittage::NumberOrId;
|
use kittage::NumberOrId;
|
||||||
use ratatui::layout::Rect;
|
use ratatui::prelude::Size;
|
||||||
use ratatui_image::{
|
use ratatui_image::{
|
||||||
Resize,
|
Resize,
|
||||||
picker::{Picker, ProtocolType},
|
picker::{Picker, ProtocolType},
|
||||||
@@ -27,7 +27,7 @@ pub enum MaybeTransferred {
|
|||||||
Transferred(kittage::ImageId)
|
Transferred(kittage::ImageId)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
// #[derive(Debug)]
|
||||||
pub enum ConvertedImage {
|
pub enum ConvertedImage {
|
||||||
Generic(Protocol),
|
Generic(Protocol),
|
||||||
Kitty {
|
Kitty {
|
||||||
@@ -42,8 +42,8 @@ impl ConvertedImage {
|
|||||||
pub fn w_h(&self) -> (u16, u16) {
|
pub fn w_h(&self) -> (u16, u16) {
|
||||||
match self {
|
match self {
|
||||||
Self::Generic(prot) => {
|
Self::Generic(prot) => {
|
||||||
let a = prot.area();
|
let Size { width, height } = prot.size();
|
||||||
(a.width, a.height)
|
(width, height)
|
||||||
}
|
}
|
||||||
Self::Kitty {
|
Self::Kitty {
|
||||||
img: _,
|
img: _,
|
||||||
@@ -72,7 +72,7 @@ pub async fn run_conversion_loop(
|
|||||||
picker: Picker,
|
picker: Picker,
|
||||||
prerender: usize,
|
prerender: usize,
|
||||||
shms_work: bool
|
shms_work: bool
|
||||||
) -> Result<(), SendError<Result<ConvertedPage, RenderError>>> {
|
) -> Result<(), Box<SendError<Result<ConvertedPage, RenderError>>>> {
|
||||||
let mut images = vec![];
|
let mut images = vec![];
|
||||||
let mut page: usize = 0;
|
let mut page: usize = 0;
|
||||||
let pid = std::process::id();
|
let pid = std::process::id();
|
||||||
@@ -134,11 +134,9 @@ pub async fn run_conversion_loop(
|
|||||||
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
let img_area = Rect {
|
let img_size = Size {
|
||||||
width: page_info.img_data.cell_w,
|
width: page_info.img_data.cell_w,
|
||||||
height: page_info.img_data.cell_h,
|
height: page_info.img_data.cell_h
|
||||||
x: 0,
|
|
||||||
y: 0
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let dyn_img = DynamicImage::ImageRgb8(dyn_img);
|
let dyn_img = DynamicImage::ImageRgb8(dyn_img);
|
||||||
@@ -174,7 +172,7 @@ pub async fn run_conversion_loop(
|
|||||||
}
|
}
|
||||||
_ => ConvertedImage::Generic(
|
_ => ConvertedImage::Generic(
|
||||||
picker
|
picker
|
||||||
.new_protocol(dyn_img, img_area, Resize::None)
|
.new_protocol(dyn_img, img_size, Resize::Crop(None))
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
RenderError::Converting(format!(
|
RenderError::Converting(format!(
|
||||||
"Couldn't convert DynamicImage to ratatui image: {e}"
|
"Couldn't convert DynamicImage to ratatui image: {e}"
|
||||||
|
|||||||
+44
-32
@@ -139,12 +139,13 @@ impl Display for DisplayErrSource<'_> {
|
|||||||
|
|
||||||
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,
|
||||||
|
last_z_index: &mut i32
|
||||||
) -> Result<(), DisplayErr<'es>> {
|
) -> Result<(), DisplayErr<'es>> {
|
||||||
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
|
||||||
@@ -152,24 +153,23 @@ pub async fn display_kitty_images<'es>(
|
|||||||
ev_stream
|
ev_stream
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| DisplayErr::empty("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 = Ok::<(), (SmallVec<[usize; 2]>, DisplayErrSource<'es>)>(());
|
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,
|
||||||
@@ -199,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,
|
||||||
@@ -207,16 +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(Some(img_id)) => {
|
img_id
|
||||||
*img = MaybeTransferred::Transferred(img_id);
|
.map(|id| *img = MaybeTransferred::Transferred(id))
|
||||||
Ok(())
|
.ok_or(DisplayErrSource::KittageReturnedNoId)
|
||||||
}
|
})
|
||||||
Ok(None) => Err((page_num, DisplayErrSource::KittageReturnedNoId)),
|
|
||||||
Err(e) => Err((page_num, DisplayErrSource::Transmission(e)))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
MaybeTransferred::Transferred(image_id) => run_action(
|
MaybeTransferred::Transferred(image_id) => run_action(
|
||||||
Action::Display {
|
Action::Display {
|
||||||
@@ -229,22 +226,37 @@ pub async fn display_kitty_images<'es>(
|
|||||||
.await
|
.await
|
||||||
// don't need the return id 'cause we already know it
|
// don't need the return id 'cause we already know it
|
||||||
.map(|_: Option<ImageId>| ())
|
.map(|_: Option<ImageId>| ())
|
||||||
.map_err(|e| (page_num, DisplayErrSource::Transmission(e)))
|
.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 {
|
||||||
match err.as_mut() {
|
match err.as_mut() {
|
||||||
Ok(()) => err = Err((SmallVec::from([id].as_slice()), e)),
|
Ok(()) => err = Err((SmallVec::from([page_num].as_slice()), e)),
|
||||||
Err((v, _)) => v.push(id)
|
Err((v, _)) => v.push(page_num)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err.map_err(|(failed_pages, source)| DisplayErr {
|
let z_idxes_to_remove = *last_z_index;
|
||||||
failed_pages,
|
*last_z_index = new_z_index;
|
||||||
user_facing_err: "Couldn't transfer image to the terminal",
|
|
||||||
source
|
match err {
|
||||||
})
|
Err((failed_pages, source)) => Err(DisplayErr {
|
||||||
|
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(|_| ())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+148
-32
@@ -5,7 +5,7 @@ use core::{
|
|||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
ffi::OsString,
|
ffi::OsString,
|
||||||
io::{BufReader, Read as _, Stdout, Write as _, stdout},
|
io::{BufReader, IsTerminal as _, Read as _, Stdout, Write as _, stdout},
|
||||||
mem,
|
mem,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, Mutex},
|
sync::{Arc, Mutex},
|
||||||
@@ -116,6 +116,8 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
optional -w,--white-color white: String
|
optional -w,--white-color white: String
|
||||||
/// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)")
|
/// Custom black color, specified in css format (e.g "000000" or "rgb(0, 0, 0)")
|
||||||
optional -b,--black-color black: String
|
optional -b,--black-color black: String
|
||||||
|
/// Use terminal foreground/background colors for the PDF
|
||||||
|
optional -t,--terminal-colors
|
||||||
/// Print the version and exit
|
/// Print the version and exit
|
||||||
optional --version
|
optional --version
|
||||||
/// PDF file to read
|
/// PDF file to read
|
||||||
@@ -137,37 +139,49 @@ 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 = flags
|
if flags.terminal_colors && (flags.black_color.is_some() || flags.white_color.is_some()) {
|
||||||
.black_color
|
return Err(WrappedErr(
|
||||||
.as_deref()
|
"--terminal-colors cannot be combined with --black-color or --white-color".into()
|
||||||
.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()
|
|
||||||
)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.transpose()?
|
|
||||||
.unwrap_or(MUPDF_BLACK);
|
|
||||||
|
|
||||||
let white = flags
|
let (black, white) = if flags.terminal_colors {
|
||||||
.white_color
|
query_terminal_colors()
|
||||||
.as_deref()
|
} else {
|
||||||
.map(|color| {
|
let black = flags
|
||||||
parse_color_to_i32(color).map_err(|e| {
|
.black_color
|
||||||
WrappedErr(
|
.as_deref()
|
||||||
format!(
|
.map(|color| {
|
||||||
"Couldn't parse white color {color:?}: {e} - is it formatted like a CSS 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()?
|
||||||
.transpose()?
|
.unwrap_or(MUPDF_BLACK);
|
||||||
.unwrap_or(MUPDF_WHITE);
|
|
||||||
|
let white = flags
|
||||||
|
.white_color
|
||||||
|
.as_deref()
|
||||||
|
.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()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.transpose()?
|
||||||
|
.unwrap_or(MUPDF_WHITE);
|
||||||
|
|
||||||
|
(black, 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.
|
||||||
@@ -260,7 +274,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
// the 'equivalent' that is suggested instead is not the same. We need to keep
|
// the 'equivalent' that is suggested instead is not the same. We need to keep
|
||||||
// calling this.
|
// calling this.
|
||||||
#[expect(deprecated)]
|
#[expect(deprecated)]
|
||||||
Ok(Picker::from_fontsize((cell_width_px, cell_height_px)))
|
Ok(Picker::from_fontsize(FontSize { width: cell_width_px, height: 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()
|
||||||
@@ -315,7 +329,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
|||||||
let mut term = Terminal::new(backend).map_err(|e| {
|
let mut term = Terminal::new(backend).map_err(|e| {
|
||||||
WrappedErr(format!("Couldn't set up crossterm's terminal backend: {e}").into())
|
WrappedErr(format!("Couldn't set up crossterm's terminal backend: {e}").into())
|
||||||
})?;
|
})?;
|
||||||
term.skip_diff(true);
|
// term.skip_diff(true);
|
||||||
|
|
||||||
enable_raw_mode().map_err(|e| {
|
enable_raw_mode().map_err(|e| {
|
||||||
WrappedErr(
|
WrappedErr(
|
||||||
@@ -390,6 +404,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();
|
||||||
@@ -462,7 +478,8 @@ 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(DisplayErr {
|
if let Err(DisplayErr {
|
||||||
failed_pages,
|
failed_pages,
|
||||||
@@ -562,6 +579,89 @@ fn parse_color_to_i32(cs: &str) -> Result<i32, csscolorparser::ParseColorError>
|
|||||||
Ok(i32::from_be_bytes([0, r, g, b]))
|
Ok(i32::from_be_bytes([0, r, g, b]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn query_terminal_colors() -> (i32, i32) {
|
||||||
|
if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
|
||||||
|
return (MUPDF_BLACK, MUPDF_WHITE);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(()) = enable_raw_mode() else {
|
||||||
|
return (MUPDF_BLACK, MUPDF_WHITE);
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RawModeGuard;
|
||||||
|
impl Drop for RawModeGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = disable_raw_mode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _guard = RawModeGuard;
|
||||||
|
|
||||||
|
let stdin = std::io::stdin();
|
||||||
|
let mut handle = stdin.lock();
|
||||||
|
|
||||||
|
let fg = query_osc_color(10, &mut handle);
|
||||||
|
let bg = query_osc_color(11, &mut handle);
|
||||||
|
drop(handle);
|
||||||
|
|
||||||
|
(fg.unwrap_or(MUPDF_BLACK), bg.unwrap_or(MUPDF_WHITE))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn query_osc_color(osc: u8, handle: &mut std::io::StdinLock<'_>) -> Option<i32> {
|
||||||
|
print!("\x1b]{osc};?\x1b\\");
|
||||||
|
std::io::stdout().flush().ok()?;
|
||||||
|
|
||||||
|
// response looks like "\u{1b}]10;rgb:rrrr/bbbb/gggg\u{1b}\\" or "\u{1b}]10;rgb:rr/bb/gg\u{1b}\\"
|
||||||
|
// or if osc is 11, "\u{1b}]11;rgb:rrrr/bbbb/gggg\u{1b}\\" or "\u{1b}]11;rgb:rr/bb/gg\u{1b}\\"
|
||||||
|
|
||||||
|
// We expect the response to be either 19 or 25 bytes.
|
||||||
|
let mut response_buf = [0u8; 25];
|
||||||
|
|
||||||
|
handle.read_exact(&mut response_buf[..19])
|
||||||
|
.inspect_err(|e| eprintln!("Couldn't get a response from your terminal for querying OSC {osc}; please file a bug with tdf with your terminal emulator (underlying err: {e})"))
|
||||||
|
.ok()?;
|
||||||
|
|
||||||
|
let two_digit_colors = response_buf[11] == b'/';
|
||||||
|
|
||||||
|
if !two_digit_colors {
|
||||||
|
handle.read_exact(&mut response_buf[19..])
|
||||||
|
.inspect_err(|e| eprintln!("Couldn't get a response from your terminal for querying OSC {osc}; please file a bug with tdf with your terminal emulator (underlying err: {e})"))
|
||||||
|
.ok()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
osc_response_buf_to_color(response_buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn osc_response_buf_to_color(response_buf: [u8; 25]) -> Option<i32> {
|
||||||
|
fn parse(ascii_hex_bytes: &[u8]) -> Option<u8> {
|
||||||
|
let mut color = 0;
|
||||||
|
|
||||||
|
for byte in ascii_hex_bytes {
|
||||||
|
color = (color << 4)
|
||||||
|
+ (match byte {
|
||||||
|
b'0'..=b'9' => byte - b'0',
|
||||||
|
b'A'..=b'F' => byte - (b'A' - 10),
|
||||||
|
b'a'..=b'f' => byte - (b'a' - 10),
|
||||||
|
_ => return None
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(color)
|
||||||
|
}
|
||||||
|
|
||||||
|
let two_digit_colors = response_buf[11] == b'/';
|
||||||
|
|
||||||
|
// this is minimimal validation.
|
||||||
|
// the response either has `rrrr/gggg/bbbb` or `rr/gg/bb` starting at byte 9.
|
||||||
|
// So we grab the first two digits out of the r, g, and b sections (since we can only support
|
||||||
|
// 8-bit colors with mupdf; we can't do the 16-bits that the terminal might respond with), we
|
||||||
|
// parse them, and we return it as an i32.
|
||||||
|
let r = parse(&response_buf[9..11])?;
|
||||||
|
let g = parse(&response_buf[if two_digit_colors { 12..14 } else { 14..16 }])?;
|
||||||
|
let b = parse(&response_buf[if two_digit_colors { 15..17 } else { 19..21 }])?;
|
||||||
|
|
||||||
|
Some(i32::from_be_bytes([0, r, g, b]))
|
||||||
|
}
|
||||||
|
|
||||||
fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
|
fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
|
||||||
// send the command code to get the terminal window size
|
// send the command code to get the terminal window size
|
||||||
print!("\x1b[14t");
|
print!("\x1b[14t");
|
||||||
@@ -628,3 +728,19 @@ fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
|
|||||||
|
|
||||||
Ok((w, h))
|
Ok((w, h))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn osc_response_parsing() {
|
||||||
|
fn eq(bytes: [u8; 25], r: u8, g: u8, b: u8) {
|
||||||
|
let resp = osc_response_buf_to_color(bytes);
|
||||||
|
assert_eq!(resp, Some(i32::from_be_bytes([0, r, g, b])));
|
||||||
|
}
|
||||||
|
|
||||||
|
eq(*b"\x1b]10;rgb:11/22/33\x1b\\000000", 0x11, 0x22, 0x33);
|
||||||
|
eq(*b"\x1b]11;rgb:aa11/23bf/fff0\x1b1", 0xaa, 0x23, 0xff);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+3
-12
@@ -1,23 +1,14 @@
|
|||||||
use std::num::NonZeroUsize;
|
use std::num::NonZeroUsize;
|
||||||
|
|
||||||
use ratatui::widgets::Widget;
|
use ratatui::{prelude::buffer::CellDiffOption, widgets::Widget};
|
||||||
|
|
||||||
pub struct Skip {
|
pub struct Skip;
|
||||||
skip: bool
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Skip {
|
|
||||||
#[must_use]
|
|
||||||
pub fn new(skip: bool) -> Self {
|
|
||||||
Self { skip }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Widget for Skip {
|
impl Widget for Skip {
|
||||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
|
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer) {
|
||||||
for x in area.x..(area.x + area.width) {
|
for x in area.x..(area.x + area.width) {
|
||||||
for y in area.y..(area.y + area.height) {
|
for y in area.y..(area.y + area.height) {
|
||||||
buf[(x, y)].skip = self.skip;
|
buf[(x, y)].diff_option = CellDiffOption::Skip;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+65
-35
@@ -72,7 +72,7 @@ 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. 0 means it fills the screen (instead of fits), such
|
// just how much 'zoom' you have. 0 means it fills the screen (instead of fits), such
|
||||||
// that one axis is fully on-screen
|
// that one axis is fully on-screen
|
||||||
@@ -86,7 +86,7 @@ struct Zoom {
|
|||||||
}
|
}
|
||||||
impl Zoom {
|
impl Zoom {
|
||||||
/// Returns the zoom factor, where 1 is the default and means fill-screen
|
/// Returns the zoom factor, where 1 is the default and means fill-screen
|
||||||
fn factor(&self) -> f32 {
|
fn factor(self) -> f32 {
|
||||||
// TODO: Make these configurable once we have a good way to set options after startup
|
// TODO: Make these configurable once we have a good way to set options after startup
|
||||||
const ZOOM_RATE: f32 = 1.1;
|
const ZOOM_RATE: f32 = 1.1;
|
||||||
const ZOOM_RATE_GRANULAR: f32 = 1.05;
|
const ZOOM_RATE_GRANULAR: f32 = 1.05;
|
||||||
@@ -262,7 +262,7 @@ impl Tui {
|
|||||||
let img_page_w_ratio = img_section_w / initial_page_w;
|
let img_page_w_ratio = img_section_w / initial_page_w;
|
||||||
let img_page_h_ratio = img_section_h / initial_page_h;
|
let img_page_h_ratio = img_section_h / initial_page_h;
|
||||||
|
|
||||||
let shrink_move_page = |dim: &mut u16, pos: &mut u16, axis_zoom_factor: f32| {
|
fn shrink_move_page(dim: &mut u16, pos: &mut u16, axis_zoom_factor: f32) {
|
||||||
let old_dim = *dim;
|
let old_dim = *dim;
|
||||||
// The axis zoom factor tells us what portion of the axis
|
// The axis zoom factor tells us what portion of the axis
|
||||||
// we need to show.
|
// we need to show.
|
||||||
@@ -272,26 +272,56 @@ impl Tui {
|
|||||||
.checked_sub(*dim)
|
.checked_sub(*dim)
|
||||||
.expect("zooming out should shrink the image")
|
.expect("zooming out should shrink the image")
|
||||||
/ 2;
|
/ 2;
|
||||||
};
|
|
||||||
|
|
||||||
// TODO: Detect max zoom-out in zoom levels
|
|
||||||
if img_page_w_ratio < img_page_h_ratio {
|
|
||||||
// vertical scroll / tall image. zooming out means decreasing the width of the page area
|
|
||||||
shrink_move_page(
|
|
||||||
&mut img_area.width,
|
|
||||||
&mut img_area.x,
|
|
||||||
// disallow zooming out past fit-screen
|
|
||||||
zoom_factor.max(1.0 / img_page_h_ratio)
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// horizontal scroll / wide image. zooming out means decreasing the width of the page area
|
|
||||||
shrink_move_page(
|
|
||||||
&mut img_area.height,
|
|
||||||
&mut img_area.y,
|
|
||||||
// disallow zooming out past fit-screen
|
|
||||||
zoom_factor.max(1.0 / img_page_w_ratio)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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:#?}");
|
log::debug!("after adjustment, page area is {img_area:#?}");
|
||||||
|
|
||||||
@@ -319,8 +349,8 @@ impl Tui {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let width = (img_section_w * f32::from(font_size.0)) as u32;
|
let width = (img_section_w * f32::from(font_size.width)) as u32;
|
||||||
let height = (img_section_h * f32::from(font_size.1)) as u32;
|
let height = (img_section_h * f32::from(font_size.height)) as u32;
|
||||||
|
|
||||||
zoom.cell_pan_from_left = zoom
|
zoom.cell_pan_from_left = zoom
|
||||||
.cell_pan_from_left
|
.cell_pan_from_left
|
||||||
@@ -337,8 +367,8 @@ impl Tui {
|
|||||||
y: img_area.y
|
y: img_area.y
|
||||||
},
|
},
|
||||||
display_loc: DisplayLocation {
|
display_loc: DisplayLocation {
|
||||||
x: u32::from(zoom.cell_pan_from_left) * u32::from(font_size.0),
|
x: u32::from(zoom.cell_pan_from_left) * u32::from(font_size.width),
|
||||||
y: u32::from(zoom.cell_pan_from_top) * u32::from(font_size.1),
|
y: u32::from(zoom.cell_pan_from_top) * u32::from(font_size.height),
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
columns: img_area.width,
|
columns: img_area.width,
|
||||||
@@ -379,7 +409,7 @@ impl Tui {
|
|||||||
// resize this time), then go through every element in the buffer where any Image would
|
// resize this time), then go through every element in the buffer where any Image would
|
||||||
// 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, img_area);
|
||||||
return KittyDisplay::NoChange;
|
return KittyDisplay::NoChange;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -709,19 +739,19 @@ impl Tui {
|
|||||||
InputAction::Redraw.into()
|
InputAction::Redraw.into()
|
||||||
}
|
}
|
||||||
KeyCode::Char(c)
|
KeyCode::Char(c)
|
||||||
if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) =
|
|
||||||
self.bottom_msg && matches!(c, 'g' if self.is_kitty) =>
|
|
||||||
c.to_digit(10).map(|input_num| {
|
|
||||||
*page = (*page * 10) + input_num as usize;
|
|
||||||
InputAction::Redraw
|
|
||||||
}),
|
|
||||||
KeyCode::Char(_)
|
|
||||||
if let BottomMessage::Input(InputCommand::GoToPage(_)) =
|
if let BottomMessage::Input(InputCommand::GoToPage(_)) =
|
||||||
self.bottom_msg =>
|
self.bottom_msg && matches!(c, 'g' if self.is_kitty) =>
|
||||||
{
|
{
|
||||||
self.set_msg(MessageSetting::Pop);
|
self.set_msg(MessageSetting::Pop);
|
||||||
self.update_zoom(Zoom::pan_bottom)
|
self.update_zoom(Zoom::pan_bottom)
|
||||||
}
|
}
|
||||||
|
KeyCode::Char(c)
|
||||||
|
if let BottomMessage::Input(InputCommand::GoToPage(ref mut page)) =
|
||||||
|
self.bottom_msg =>
|
||||||
|
c.to_digit(10).map(|input_num| {
|
||||||
|
*page = (*page * 10) + input_num as usize;
|
||||||
|
InputAction::Redraw
|
||||||
|
}),
|
||||||
KeyCode::Char(c) => match c {
|
KeyCode::Char(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),
|
||||||
|
|||||||
Reference in New Issue
Block a user