mirror of
https://github.com/itsjunetime/tdf.git
synced 2026-06-01 23:51:46 -04:00
- Added more lints to Cargo.toml (for fun I guess)
- Extended benchmarking system to check all protocols, not just kitty - Updated deps
This commit is contained in:
+15
-12
@@ -1,19 +1,19 @@
|
||||
use std::{
|
||||
num::{NonZeroU32, NonZeroUsize},
|
||||
num::NonZeroUsize,
|
||||
time::{SystemTime, UNIX_EPOCH}
|
||||
};
|
||||
|
||||
use flume::{Receiver, SendError, Sender, TryRecvError};
|
||||
use futures_util::stream::StreamExt;
|
||||
use futures_util::stream::StreamExt as _;
|
||||
use image::DynamicImage;
|
||||
use kittage::NumberOrId;
|
||||
use kittage::{NumberOrId, action::NONZERO_ONE};
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui_image::{
|
||||
Resize,
|
||||
picker::{Picker, ProtocolType},
|
||||
protocol::Protocol
|
||||
};
|
||||
use rayon::iter::ParallelIterator;
|
||||
use rayon::iter::ParallelIterator as _;
|
||||
|
||||
use crate::{
|
||||
renderer::{PageInfo, RenderError, fill_default},
|
||||
@@ -37,6 +37,7 @@ pub enum ConvertedImage {
|
||||
}
|
||||
|
||||
impl ConvertedImage {
|
||||
#[must_use]
|
||||
pub fn w_h(&self) -> (u16, u16) {
|
||||
match self {
|
||||
Self::Generic(prot) => {
|
||||
@@ -67,7 +68,7 @@ pub enum ConverterMsg {
|
||||
pub async fn run_conversion_loop(
|
||||
sender: Sender<Result<ConvertedPage, RenderError>>,
|
||||
receiver: Receiver<ConverterMsg>,
|
||||
mut picker: Picker,
|
||||
picker: Picker,
|
||||
prerender: usize,
|
||||
shms_work: bool
|
||||
) -> Result<(), SendError<Result<ConvertedPage, RenderError>>> {
|
||||
@@ -77,7 +78,7 @@ pub async fn run_conversion_loop(
|
||||
|
||||
fn next_page(
|
||||
images: &mut [Option<PageInfo>],
|
||||
picker: &mut Picker,
|
||||
picker: &Picker,
|
||||
page: usize,
|
||||
iteration: &mut usize,
|
||||
prerender: usize,
|
||||
@@ -126,7 +127,7 @@ pub async fn run_conversion_loop(
|
||||
.for_each(|(_, _, px)| px.0[2] = px.0[2].saturating_sub(u8::MAX / 2));
|
||||
},
|
||||
_ => unreachable!()
|
||||
};
|
||||
}
|
||||
|
||||
let img_area = Rect {
|
||||
width: page_info.img_data.cell_w,
|
||||
@@ -140,18 +141,20 @@ pub async fn run_conversion_loop(
|
||||
let rn = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() % 1_000_000;
|
||||
.as_nanos() % 1_000_000;
|
||||
|
||||
let mut img = if shms_work {
|
||||
kittage::image::Image::shm_from(dyn_img, &format!("tdf_{pid}_{rn}_{page_num}"))
|
||||
kittage::image::Image::shm_from(dyn_img, &format!("/tdf_{pid}_{rn}_{page_num}"))
|
||||
.map_err(|e| {
|
||||
RenderError::Converting(format!("Couldn't write to shm: {e}"))
|
||||
RenderError::Converting(format!("Couldn't write to shm: {e:?}"))
|
||||
})?
|
||||
} else {
|
||||
kittage::image::Image::from(dyn_img)
|
||||
};
|
||||
|
||||
img.num_or_id = NumberOrId::Id(NonZeroU32::new(page_num as u32 + 1).unwrap());
|
||||
// if ur pdf has 4 billion pages then you deserve to suffer
|
||||
img.num_or_id = NumberOrId::Id(NONZERO_ONE.saturating_add(page_num as u32));
|
||||
|
||||
ConvertedImage::Kitty {
|
||||
img: MaybeTransferred::NotYet(img),
|
||||
cell_w: page_info.img_data.cell_w,
|
||||
@@ -214,7 +217,7 @@ pub async fn run_conversion_loop(
|
||||
|
||||
match next_page(
|
||||
&mut images,
|
||||
&mut picker,
|
||||
&picker,
|
||||
page,
|
||||
&mut iteration,
|
||||
prerender,
|
||||
|
||||
+2
-2
@@ -60,8 +60,8 @@ impl<W: Write> Write for DbgWriter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run_action<'image, 'data, 'es>(
|
||||
action: Action<'image, 'data>,
|
||||
pub async fn run_action<'es>(
|
||||
action: Action<'_, '_>,
|
||||
ev_stream: &'es mut EventStream
|
||||
) -> Result<ImageId, TransmitError<<&'es mut EventStream as AsyncInputReader>::Error>> {
|
||||
let writer = DbgWriter {
|
||||
|
||||
@@ -27,6 +27,7 @@ pub struct ScaledResult {
|
||||
scale_factor: f32
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn scale_img_for_area(
|
||||
(img_width, img_height): (f32, f32),
|
||||
(area_width, area_height): (f32, f32),
|
||||
|
||||
+19
-27
@@ -5,7 +5,7 @@ use core::{
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
ffi::OsString,
|
||||
io::{BufReader, Read, Stdout, Write, stdout},
|
||||
io::{BufReader, Read as _, Stdout, Write as _, stdout},
|
||||
path::PathBuf
|
||||
};
|
||||
|
||||
@@ -19,13 +19,13 @@ use crossterm::{
|
||||
};
|
||||
use flexi_logger::FileSpec;
|
||||
use flume::{Sender, r#async::RecvStream};
|
||||
use futures_util::{FutureExt, stream::StreamExt};
|
||||
use futures_util::{FutureExt as _, stream::StreamExt as _};
|
||||
use kittage::{
|
||||
action::Action,
|
||||
delete::{ClearOrDelete, DeleteConfig, WhichToDelete},
|
||||
error::{TerminalError, TransmitError}
|
||||
};
|
||||
use notify::{Event, EventKind, RecursiveMode, Watcher};
|
||||
use notify::{Event, EventKind, RecursiveMode, Watcher as _};
|
||||
use ratatui::{Terminal, backend::CrosstermBackend};
|
||||
use ratatui_image::{
|
||||
FontSize,
|
||||
@@ -57,23 +57,25 @@ impl std::fmt::Debug for WrappedErr {
|
||||
impl std::error::Error for WrappedErr {}
|
||||
|
||||
fn reset_term() {
|
||||
_ = disable_raw_mode();
|
||||
_ = execute!(
|
||||
std::io::stdout(),
|
||||
LeaveAlternateScreen,
|
||||
crossterm::cursor::Show,
|
||||
crossterm::event::DisableMouseCapture
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), WrappedErr> {
|
||||
inner_main().await.inspect_err(|_| reset_term())
|
||||
let result = inner_main().await;
|
||||
reset_term();
|
||||
result
|
||||
}
|
||||
|
||||
async fn inner_main() -> Result<(), WrappedErr> {
|
||||
let hook = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
_ = disable_raw_mode();
|
||||
reset_term();
|
||||
hook(info);
|
||||
}));
|
||||
@@ -135,10 +137,8 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
||||
|
||||
// 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.
|
||||
let mut maybe_logger = None;
|
||||
|
||||
if std::env::var("RUST_LOG").is_ok() {
|
||||
maybe_logger = Some(
|
||||
let maybe_logger = if std::env::var("RUST_LOG").is_ok() {
|
||||
Some(
|
||||
flexi_logger::Logger::try_with_env()
|
||||
.map_err(|e| WrappedErr(format!("Couldn't create initial logger: {e}").into()))?
|
||||
.log_to_file(FileSpec::try_from("./debug.log").map_err(|e| {
|
||||
@@ -146,8 +146,10 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
||||
})?)
|
||||
.start()
|
||||
.map_err(|e| WrappedErr(format!("Can't start logger: {e}").into()))?
|
||||
);
|
||||
}
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let (watch_to_render_tx, render_rx) = flume::unbounded();
|
||||
let to_renderer = watch_to_render_tx.clone();
|
||||
@@ -159,7 +161,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
||||
watch_to_tui_tx,
|
||||
watch_to_render_tx,
|
||||
path.file_name()
|
||||
.ok_or(WrappedErr("Path does not have a last component??".into()))?
|
||||
.ok_or_else(|| WrappedErr("Path does not have a last component??".into()))?
|
||||
.to_owned()
|
||||
))
|
||||
.map_err(|e| WrappedErr(format!("Couldn't start watching the provided file: {e}").into()))?;
|
||||
@@ -331,17 +333,7 @@ async fn inner_main() -> Result<(), WrappedErr> {
|
||||
)
|
||||
})?;
|
||||
|
||||
execute!(
|
||||
term.backend_mut(),
|
||||
LeaveAlternateScreen,
|
||||
crossterm::cursor::Show,
|
||||
crossterm::event::DisableMouseCapture
|
||||
)
|
||||
.unwrap();
|
||||
disable_raw_mode().unwrap();
|
||||
|
||||
drop(maybe_logger);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -550,18 +542,18 @@ fn get_font_size_through_stdio() -> Result<(u16, u16), WrappedErr> {
|
||||
));
|
||||
};
|
||||
|
||||
let h = h.parse::<u16>().map_err(|_| {
|
||||
let h = h.parse::<u16>().map_err(|e| {
|
||||
WrappedErr(
|
||||
format!(
|
||||
"Your terminal said its height is {h}, but that is not a 16-bit unsigned integer"
|
||||
"Your terminal said its height is {h}, but that is not a 16-bit unsigned integer: {e}"
|
||||
)
|
||||
.into()
|
||||
)
|
||||
})?;
|
||||
let w = w.parse::<u16>().map_err(|_| {
|
||||
let w = w.parse::<u16>().map_err(|e| {
|
||||
WrappedErr(
|
||||
format!(
|
||||
"Your terminal said its width is {w}, but that is not a 16-bit unsigned integer"
|
||||
"Your terminal said its width is {w}, but that is not a 16-bit unsigned integer: {e}"
|
||||
)
|
||||
.into()
|
||||
)
|
||||
|
||||
+6
-6
@@ -78,7 +78,7 @@ pub fn fill_default<T: Default>(vec: &mut Vec<T>, size: usize) {
|
||||
// We're allowing passing by value here because this is only called once, at the beginning of the
|
||||
// program, and the arguments that 'should' be passed by value (`receiver` and `size`) would
|
||||
// probably be more performant if accessed by-value instead of through a reference. Probably.
|
||||
#[allow(clippy::needless_pass_by_value, clippy::too_many_arguments)]
|
||||
#[expect(clippy::needless_pass_by_value, clippy::too_many_arguments)]
|
||||
pub fn start_rendering(
|
||||
path: &str,
|
||||
sender: Sender<Result<RenderInfo, RenderError>>,
|
||||
@@ -116,7 +116,7 @@ pub fn start_rendering(
|
||||
// temporarily removed to facilitate a save or something like that)
|
||||
while let Ok(msg) = receiver.recv() {
|
||||
// and once that comes, just try to reload again
|
||||
if let RenderNotif::Reload = msg {
|
||||
if matches!(msg, RenderNotif::Reload) {
|
||||
continue 'reload;
|
||||
}
|
||||
}
|
||||
@@ -313,7 +313,7 @@ pub fn start_rendering(
|
||||
if let Err(e) = ctx.pixmap.write_to(&mut pixels, mupdf::ImageFormat::PNM) {
|
||||
sender.send(Err(RenderError::Doc(e)))?;
|
||||
continue;
|
||||
};
|
||||
}
|
||||
|
||||
log::debug!("got pixmap for page {page_num} with WxH {w}x{h}");
|
||||
|
||||
@@ -341,7 +341,7 @@ pub fn start_rendering(
|
||||
Err(TryRecvError::Disconnected) => return Ok(()),
|
||||
Ok(notif) => handle_notif!(notif),
|
||||
Err(TryRecvError::Empty) => ()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Now, if we have a search term, we want to look through the rest of the document past
|
||||
@@ -434,7 +434,7 @@ pub fn start_rendering(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
handle_notif!(msg)
|
||||
handle_notif!(msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -565,7 +565,7 @@ struct PopOnNext<'a> {
|
||||
inner: &'a mut VecDeque<usize>
|
||||
}
|
||||
|
||||
impl<'a> Iterator for PopOnNext<'a> {
|
||||
impl Iterator for PopOnNext<'_> {
|
||||
type Item = usize;
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
self.inner.pop_front()
|
||||
|
||||
@@ -7,6 +7,7 @@ pub struct Skip {
|
||||
}
|
||||
|
||||
impl Skip {
|
||||
#[must_use]
|
||||
pub fn new(skip: bool) -> Self {
|
||||
Self { skip }
|
||||
}
|
||||
@@ -45,6 +46,7 @@ impl InterleavedAroundWithMax {
|
||||
/// the following must hold or else this is liable to panic or produce nonsense values:
|
||||
/// - inclusive_min < exclusive_max
|
||||
/// - inclusive_min <= around <= exclusive_max
|
||||
#[must_use]
|
||||
pub fn new(around: usize, inclusive_min: usize, exclusive_max: NonZeroUsize) -> Self {
|
||||
Self {
|
||||
around,
|
||||
|
||||
+47
-40
@@ -109,7 +109,8 @@ pub struct RenderLayout {
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool, is_kitty: bool) -> Tui {
|
||||
#[must_use]
|
||||
pub fn new(name: String, max_wide: Option<NonZeroUsize>, r_to_l: bool, is_kitty: bool) -> Self {
|
||||
Self {
|
||||
name,
|
||||
page: 0,
|
||||
@@ -124,6 +125,7 @@ impl Tui {
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn main_layout(frame: &Frame<'_>, fullscreened: bool) -> RenderLayout {
|
||||
if fullscreened {
|
||||
RenderLayout {
|
||||
@@ -276,7 +278,7 @@ impl Tui {
|
||||
}
|
||||
}]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// here we calculate how many pages can fit in the available area.
|
||||
let mut test_area_w = img_area.width;
|
||||
@@ -383,12 +385,13 @@ impl Tui {
|
||||
}
|
||||
|
||||
fn render_loading_in(frame: &mut Frame<'_>, area: Rect) {
|
||||
let loading_str = "Loading...";
|
||||
let inner_space = Layout::horizontal([Constraint::Length(loading_str.len() as u16)])
|
||||
.flex(Flex::Center)
|
||||
.split(area);
|
||||
const LOADING_STR: &str = "Loading...";
|
||||
let inner_space =
|
||||
Layout::horizontal([Constraint::Length(const { LOADING_STR.len() as u16 })])
|
||||
.flex(Flex::Center)
|
||||
.split(area);
|
||||
|
||||
let loading_span = Span::styled(loading_str, Style::new().fg(Color::Cyan));
|
||||
let loading_span = Span::styled(LOADING_STR, Style::new().fg(Color::Cyan));
|
||||
|
||||
frame.render_widget(loading_span, inner_space[0]);
|
||||
}
|
||||
@@ -417,6 +420,8 @@ impl Tui {
|
||||
PageChange::Prev => self.set_page(self.page.saturating_sub(diff))
|
||||
}
|
||||
|
||||
// Yes these conversions could wrap around if you have > isize::MAX pages, but we already
|
||||
// decided that you deserve to suffer if you have more than u32::MAX pages, so that's fine.
|
||||
match self.page as isize - old as isize {
|
||||
0 => None,
|
||||
_ => Some(InputAction::JumpingToPage(self.page))
|
||||
@@ -550,17 +555,11 @@ impl Tui {
|
||||
}
|
||||
|
||||
pub fn handle_event(&mut self, ev: &Event) -> Option<InputAction> {
|
||||
fn jump_to_page(
|
||||
page: &mut usize,
|
||||
rect: &mut Rect,
|
||||
new_page: Option<usize>
|
||||
) -> Option<InputAction> {
|
||||
new_page.map(|new_page| {
|
||||
*page = new_page;
|
||||
// Make sure we re-render
|
||||
*rect = Rect::default();
|
||||
InputAction::JumpingToPage(new_page)
|
||||
})
|
||||
fn jump_to_page(page: &mut usize, rect: &mut Rect, new_page: usize) -> InputAction {
|
||||
*page = new_page;
|
||||
// Make sure we re-render
|
||||
*rect = Rect::default();
|
||||
InputAction::JumpingToPage(new_page)
|
||||
}
|
||||
|
||||
match ev {
|
||||
@@ -617,30 +616,38 @@ impl Tui {
|
||||
'n' if self.page < self.rendered.len() - 1 => {
|
||||
// TODO: If we can't find one, then maybe like block until we've verified
|
||||
// all the pages have been checked?
|
||||
let next_page = self.rendered[(self.page + 1)..]
|
||||
self.rendered[(self.page + 1)..]
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find_map(|(idx, p)| {
|
||||
p.num_results
|
||||
.is_some_and(|num| num > 0)
|
||||
.then_some(self.page + 1 + idx)
|
||||
});
|
||||
|
||||
jump_to_page(&mut self.page, &mut self.last_render.rect, next_page)
|
||||
}
|
||||
'N' if self.page > 0 => {
|
||||
let prev_page = self.rendered[..(self.page)]
|
||||
.iter()
|
||||
.rev()
|
||||
.enumerate()
|
||||
.find_map(|(idx, p)| {
|
||||
p.num_results
|
||||
.is_some_and(|num| num > 0)
|
||||
.then_some(self.page - (idx + 1))
|
||||
});
|
||||
|
||||
jump_to_page(&mut self.page, &mut self.last_render.rect, prev_page)
|
||||
})
|
||||
.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?
|
||||
|
||||
@@ -686,16 +693,16 @@ impl Tui {
|
||||
'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)
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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),
|
||||
@@ -819,7 +826,7 @@ impl Tui {
|
||||
#[expect(clippy::unnecessary_wraps)]
|
||||
fn update_zoom(&mut self, f: impl FnOnce(&mut Zoom)) -> Option<InputAction> {
|
||||
if let Some(z) = &mut self.zoom {
|
||||
f(z)
|
||||
f(z);
|
||||
}
|
||||
self.last_render.rect = Rect::default();
|
||||
Some(InputAction::Redraw)
|
||||
|
||||
Reference in New Issue
Block a user