fix images not disappearing after terminal exits

This commit is contained in:
itsjunetime
2026-04-19 12:56:17 -05:00
parent bd00c7e913
commit a6a9471bef
4 changed files with 88 additions and 45 deletions
+1 -1
Submodule ratatui updated: 720ac2d0ca...abe7dcf234
+48 -15
View File
@@ -1,5 +1,8 @@
use core::fmt::Display; use core::fmt::Display;
use std::{io::Write, num::NonZeroU32}; use std::{
io::{StdoutLock, Write, stdout},
num::NonZeroU32
};
use crossterm::{ use crossterm::{
cursor::MoveTo, cursor::MoveTo,
@@ -63,28 +66,55 @@ impl<W: Write> Write for DbgWriter<W> {
} }
} }
pub enum MaybeTmuxWriter<W>
where
W: Write
{
Tmux(TmuxWriter<W>),
Normal(W)
}
impl<W: Write> MaybeTmuxWriter<W> {
pub fn new(w: W, is_tmux: bool) -> Self {
if is_tmux {
Self::Tmux(TmuxWriter::new(w))
} else {
Self::Normal(w)
}
}
}
impl<W: Write> Write for &mut MaybeTmuxWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match *self {
MaybeTmuxWriter::Tmux(t) => t.write(buf),
MaybeTmuxWriter::Normal(w) => w.write(buf)
}
}
fn flush(&mut self) -> std::io::Result<()> {
match *self {
MaybeTmuxWriter::Tmux(t) => t.flush(),
MaybeTmuxWriter::Normal(w) => w.flush()
}
}
}
pub async fn run_action<'es>( pub async fn run_action<'es>(
action: Action<'_, '_>, action: Action<'_, '_>,
is_tmux: bool, writer: &mut MaybeTmuxWriter<StdoutLock<'_>>,
ev_stream: &'es mut EventStream ev_stream: &'es mut EventStream
) -> Result<Option<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: writer,
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
buf: String::new() buf: String::new()
}; };
if is_tmux {
action
.execute_async(TmuxWriter::new(writer), ev_stream)
.await
.map(|(_, i)| i)
} else {
action action
.execute_async(writer, ev_stream) .execute_async(writer, ev_stream)
.await .await
.map(|(_, i)| i) .map(|(_, i)| i)
}
} }
pub async fn do_shms_work(is_tmux: bool, ev_stream: &mut EventStream) -> bool { pub async fn do_shms_work(is_tmux: bool, ev_stream: &mut EventStream) -> bool {
@@ -104,7 +134,8 @@ pub async fn do_shms_work(is_tmux: bool, ev_stream: &mut EventStream) -> bool {
enable_raw_mode().unwrap(); enable_raw_mode().unwrap();
let res = run_action(Action::Query(&k_img), is_tmux, ev_stream).await; let mut writer = MaybeTmuxWriter::new(stdout().lock(), is_tmux);
let res = run_action(Action::Query(&k_img), &mut writer, ev_stream).await;
disable_raw_mode().unwrap(); disable_raw_mode().unwrap();
@@ -153,6 +184,8 @@ pub async fn display_kitty_images<'es>(
ev_stream: &'es mut EventStream, ev_stream: &'es mut EventStream,
last_z_index: &mut i32 last_z_index: &mut i32
) -> Result<(), DisplayErr<'es>> { ) -> Result<(), DisplayErr<'es>> {
let mut writer = MaybeTmuxWriter::new(stdout().lock(), is_tmux);
let images = match display { let images = match display {
KittyDisplay::NoChange => return Ok(()), KittyDisplay::NoChange => return Ok(()),
KittyDisplay::ClearImages => KittyDisplay::ClearImages =>
@@ -161,7 +194,7 @@ pub async fn display_kitty_images<'es>(
effect: ClearOrDelete::Clear, effect: ClearOrDelete::Clear,
which: WhichToDelete::All which: WhichToDelete::All
}), }),
is_tmux, &mut writer,
ev_stream ev_stream
) )
.await .await
@@ -188,7 +221,7 @@ pub async fn display_kitty_images<'es>(
..DisplayConfig::default() ..DisplayConfig::default()
}; };
execute!(std::io::stdout(), MoveTo(pos.x, pos.y)).unwrap(); execute!(&mut writer, MoveTo(pos.x, pos.y)).unwrap();
log::debug!("going to display img {img:#?}"); log::debug!("going to display img {img:#?}");
log::debug!("displaying with config {config:#?}"); log::debug!("displaying with config {config:#?}");
@@ -217,7 +250,7 @@ pub async fn display_kitty_images<'es>(
config, config,
placement_id: None placement_id: None
}, },
is_tmux, &mut writer,
ev_stream ev_stream
) )
.await .await
@@ -234,7 +267,7 @@ pub async fn display_kitty_images<'es>(
placement_id: *image_id, placement_id: *image_id,
config config
}, },
is_tmux, &mut writer,
ev_stream ev_stream
) )
.await .await
+34 -24
View File
@@ -1,7 +1,4 @@
use core::{ use core::{error::Error, num::NonZeroUsize};
error::Error,
num::{NonZeroU32, NonZeroUsize}
};
use std::{ use std::{
borrow::Cow, borrow::Cow,
ffi::OsString, ffi::OsString,
@@ -16,8 +13,8 @@ use crossterm::{
event::EventStream, event::EventStream,
execute, execute,
terminal::{ terminal::{
EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, WindowSize,
enable_raw_mode, window_size disable_raw_mode, enable_raw_mode, window_size
} }
}; };
use debounce::EventDebouncer; use debounce::EventDebouncer;
@@ -39,7 +36,8 @@ use tdf::{
PrerenderLimit, PrerenderLimit,
converter::{ConvertedPage, ConverterMsg, run_conversion_loop}, converter::{ConvertedPage, ConverterMsg, run_conversion_loop},
kitty::{ kitty::{
DisplayErr, DisplayErrSource, KittyDisplay, display_kitty_images, do_shms_work, run_action DisplayErr, DisplayErrSource, KittyDisplay, MaybeTmuxWriter, display_kitty_images,
do_shms_work, run_action
}, },
renderer::{self, MUPDF_BLACK, MUPDF_WHITE, RenderError, RenderInfo, RenderNotif}, renderer::{self, MUPDF_BLACK, MUPDF_WHITE, RenderError, RenderInfo, RenderNotif},
tui::{BottomMessage, InputAction, MessageSetting, Tui} tui::{BottomMessage, InputAction, MessageSetting, Tui}
@@ -250,22 +248,20 @@ async fn inner_main() -> Result<(), WrappedErr> {
// We need to create `picker` on this thread because if we create it on the `renderer` thread, // We need to create `picker` on this thread because if we create it on the `renderer` thread,
// it messes up something with user input. Input never makes it to the crossterm thing // it messes up something with user input. Input never makes it to the crossterm thing
let picker = Picker::from_query_stdio() let picker = Picker::from_query_stdio()
.or_else(|e| match e { .or_else(|e| match (e, window_size) {
ratatui_image::errors::Errors::NoFontSize if (
window_size.width != 0 ratatui_image::errors::Errors::NoFontSize,
&& window_size.height != 0 WindowSize { width: 1.., height: 1.., columns: 1.., rows: 1.. }
&& window_size.columns != 0 ) => {
&& window_size.rows != 0 =>
{
// 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((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()
)), )),
e => Err(WrappedErr(format!("Couldn't get the necessary information to set up images: {e}").into())) (e, _) => Err(WrappedErr(format!("Couldn't get the necessary information to set up images: {e}").into()))
})?; })?;
// then we want to spawn off the rendering task // then we want to spawn off the rendering task
@@ -325,12 +321,13 @@ async fn inner_main() -> Result<(), WrappedErr> {
})?; })?;
if is_kitty { if is_kitty {
let mut writer = MaybeTmuxWriter::new(stdout().lock(), is_tmux);
run_action( run_action(
Action::Delete(DeleteConfig { Action::Delete(DeleteConfig {
effect: ClearOrDelete::Delete, effect: ClearOrDelete::Delete,
which: WhichToDelete::IdRange(NonZeroU32::new(1).unwrap()..=NonZeroU32::MAX) which: WhichToDelete::All
}), }),
is_tmux, &mut writer,
&mut ev_stream &mut ev_stream
) )
.await .await
@@ -352,8 +349,8 @@ async fn inner_main() -> Result<(), WrappedErr> {
let tui_rx = tui_rx.into_stream(); let tui_rx = tui_rx.into_stream();
let from_converter = from_converter.into_stream(); let from_converter = from_converter.into_stream();
enter_redraw_loop( let res = enter_redraw_loop(
ev_stream, &mut ev_stream,
to_renderer, to_renderer,
tui_rx, tui_rx,
to_converter, to_converter,
@@ -373,16 +370,29 @@ async fn inner_main() -> Result<(), WrappedErr> {
) )
.into() .into()
) )
})?; });
if is_kitty {
let mut writer = MaybeTmuxWriter::new(stdout().lock(), is_tmux);
_ = run_action(
Action::Delete(DeleteConfig {
effect: ClearOrDelete::Delete,
which: WhichToDelete::All
}),
&mut writer,
&mut ev_stream
)
.await;
}
drop(maybe_logger); drop(maybe_logger);
Ok(())
res
} }
// oh shut up clippy who cares // oh shut up clippy who cares
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
async fn enter_redraw_loop( async fn enter_redraw_loop(
mut ev_stream: EventStream, ev_stream: &mut EventStream,
to_renderer: Sender<RenderNotif>, to_renderer: Sender<RenderNotif>,
mut tui_rx: RecvStream<'_, Result<RenderInfo, RenderError>>, mut tui_rx: RecvStream<'_, Result<RenderInfo, RenderError>>,
to_converter: Sender<ConverterMsg>, to_converter: Sender<ConverterMsg>,
@@ -469,7 +479,7 @@ async fn enter_redraw_loop(
})?; })?;
let maybe_err = let maybe_err =
display_kitty_images(to_display, is_tmux, &mut ev_stream, &mut kitty_z_idx).await; display_kitty_images(to_display, is_tmux, ev_stream, &mut kitty_z_idx).await;
if let Err(DisplayErr { if let Err(DisplayErr {
failed_pages, failed_pages,