From c5cb0ef66d64c1ccd65f147ef2f971c4bb22ad1e Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 11 Mar 2021 00:29:24 -0800 Subject: [PATCH] Added support for animated gifs and pngs This is first draft; the animation rate is currently tied to the cursor_blink_rate setting, so if the gif has frames that are intended to display more frequently than that, they will animate more slowly. Animation is only carried out while the window has focus. Animation increases the load on the GPU and thus uses more power. It's kinda fun to stick one of these animated pixel gifs in the background: https://imgur.com/gallery/F9DAH --- docs/changelog.md | 1 + wezterm-gui/src/glyphcache.rs | 133 +++++++++++++++++++++++---- wezterm-gui/src/termwindow/mod.rs | 9 +- wezterm-gui/src/termwindow/render.rs | 15 ++- 4 files changed, 138 insertions(+), 20 deletions(-) diff --git a/docs/changelog.md b/docs/changelog.md index 3280e5f8f..4ac1c75e5 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -49,6 +49,7 @@ brief notes about them may accumulate here. * New: [window:set_right_status](config/lua/window/set_right_status.md) allows setting additional status information in the tab bar. [#500](https://github.com/wez/wezterm/issues/500) * Changed the default [font_size](config/lua/config/font_size.md) to 12 points. [#517](https://github.com/wez/wezterm/discussions/517) * Window: fixed "Open WezTerm Here" context menu in explorer when used on the root of a drive (eg: `C:\`). Thanks to [@flyxyz123](https://github.com/flyxyz123)! [#526](https://github.com/wez/wezterm/issues/526) [#451](https://github.com/wez/wezterm/issues/451) +* New: animated gif and png images displayed via the `wezterm imgcat` (the iTerm2 image protocol), or attached to the window background via [window_background_image](config/appearance.html#window-background-image) will now animate while the window has focus. ### 20210203-095643-70a364eb diff --git a/wezterm-gui/src/glyphcache.rs b/wezterm-gui/src/glyphcache.rs index 4e7b9c0ab..f9cde8c7d 100644 --- a/wezterm-gui/src/glyphcache.rs +++ b/wezterm-gui/src/glyphcache.rs @@ -13,6 +13,7 @@ use std::collections::HashMap; use std::ops::Range; use std::rc::Rc; use std::sync::Arc; +use std::time::{Duration, Instant}; use termwiz::image::ImageData; use wezterm_font::units::*; use wezterm_font::{FontConfiguration, GlyphInfo}; @@ -215,11 +216,83 @@ impl BlockKey { } } +struct ImageFrame { + duration: Duration, + image: ::window::bitmaps::Image, +} + +struct DecodedImage { + frame_start: Instant, + current_frame: usize, + frames: Vec, +} + +impl DecodedImage { + fn with_frames(frames: Vec) -> Self { + let frames = frames + .into_iter() + .map(|frame| { + let duration: Duration = frame.delay().into(); + let image = image::DynamicImage::ImageRgba8(frame.into_buffer()).to_bgra8(); + let (w, h) = image.dimensions(); + let width = w as usize; + let height = h as usize; + let image = ::window::bitmaps::Image::from_raw(width, height, image.into_vec()); + ImageFrame { duration, image } + }) + .collect(); + Self { + frame_start: Instant::now(), + current_frame: 1, + frames, + } + } + + fn with_single(image_data: &Arc) -> anyhow::Result { + let image = image::load_from_memory(image_data.data())?.to_bgra8(); + let (width, height) = image.dimensions(); + let width = width as usize; + let height = height as usize; + let image = ::window::bitmaps::Image::from_raw(width, height, image.into_vec()); + Ok(Self { + frame_start: Instant::now(), + current_frame: 1, + frames: vec![ImageFrame { + duration: Default::default(), + image, + }], + }) + } + + fn load(image_data: &Arc) -> anyhow::Result { + use image::{AnimationDecoder, ImageFormat}; + let format = image::guess_format(image_data.data())?; + match format { + ImageFormat::Gif => { + let decoder = image::gif::GifDecoder::new(image_data.data())?; + let frames = decoder.into_frames().collect_frames()?; + Ok(Self::with_frames(frames)) + } + ImageFormat::Png => { + let decoder = image::png::PngDecoder::new(image_data.data())?; + if decoder.is_apng() { + let frames = decoder.apng().into_frames().collect_frames()?; + Ok(Self::with_frames(frames)) + } else { + Self::with_single(image_data) + } + } + _ => Self::with_single(image_data), + } + } +} + pub struct GlyphCache { glyph_cache: HashMap>>, pub atlas: Atlas, fonts: Rc, - image_cache: HashMap>, + image_cache: HashMap, + frame_cache: HashMap<(usize, usize), Sprite>, line_glyphs: HashMap>, block_glyphs: HashMap>, metrics: RenderMetrics, @@ -239,6 +312,7 @@ impl GlyphCache { fonts: Rc::clone(fonts), glyph_cache: HashMap::new(), image_cache: HashMap::new(), + frame_cache: HashMap::new(), atlas, metrics: metrics.clone(), line_glyphs: HashMap::new(), @@ -267,6 +341,7 @@ impl GlyphCache { fonts: Rc::clone(fonts), glyph_cache: HashMap::new(), image_cache: HashMap::new(), + frame_cache: HashMap::new(), atlas, metrics: metrics.clone(), line_glyphs: HashMap::new(), @@ -276,7 +351,8 @@ impl GlyphCache { pub fn clear(&mut self) { self.atlas.clear(); - self.image_cache.clear(); + // self.image_cache.clear(); - relatively expensive to re-populate + self.frame_cache.clear(); self.glyph_cache.clear(); self.line_glyphs.clear(); self.block_glyphs.clear(); @@ -425,24 +501,47 @@ impl GlyphCache { &mut self, image_data: &Arc, padding: Option, - ) -> anyhow::Result> { - if let Some(sprite) = self.image_cache.get(&image_data.id()) { - return Ok(sprite.clone()); + ) -> anyhow::Result<(Sprite, usize)> { + let id = image_data.id(); + if let Some(decoded) = self.image_cache.get_mut(&id) { + if decoded.frames.len() > 1 { + let now = Instant::now(); + if now.duration_since(decoded.frame_start) + >= decoded.frames[decoded.current_frame].duration + { + // Advance to next frame + decoded.current_frame += 1; + if decoded.current_frame == decoded.frames.len() { + decoded.current_frame = 0; + } + decoded.frame_start = now; + } + } + + if let Some(sprite) = self.frame_cache.get(&(id, decoded.current_frame)) { + return Ok((sprite.clone(), decoded.frames.len())); + } + + let sprite = self + .atlas + .allocate_with_padding(&decoded.frames[decoded.current_frame].image, padding)?; + + self.frame_cache + .insert((id, decoded.current_frame), sprite.clone()); + + return Ok((sprite, decoded.frames.len())); } - let decoded_image = image::load_from_memory(image_data.data())?.to_bgra8(); - let (width, height) = decoded_image.dimensions(); - let image = ::window::bitmaps::Image::from_raw( - width as usize, - height as usize, - decoded_image.to_vec(), - ); + let decoded = DecodedImage::load(image_data)?; + let num_frames = decoded.frames.len(); + let sprite = self + .atlas + .allocate_with_padding(&decoded.frames[0].image, padding)?; + self.frame_cache + .insert((id, decoded.current_frame), sprite.clone()); + self.image_cache.insert(id, decoded); - let sprite = self.atlas.allocate_with_padding(&image, padding)?; - - self.image_cache.insert(image_data.id(), sprite.clone()); - - Ok(sprite) + Ok((sprite, num_frames)) } fn block_sprite(&mut self, block: BlockKey) -> anyhow::Result> { diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 1059a562d..0e59eef34 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -161,6 +161,7 @@ pub struct TermWindow { palette: Option, event_states: HashMap, + has_animation: RefCell, } impl WindowCallbacks for TermWindow { @@ -299,6 +300,7 @@ impl WindowCallbacks for TermWindow { last_blink_paint: Instant::now(), last_status_call: Instant::now(), event_states: HashMap::new(), + has_animation: RefCell::new(false), }); prior_window.close(); @@ -519,6 +521,7 @@ impl TermWindow { last_blink_paint: Instant::now(), last_status_call: Instant::now(), event_states: HashMap::new(), + has_animation: RefCell::new(false), }), Some(&crate::window_config::ConfigInstance::new(config)), )?; @@ -727,12 +730,16 @@ impl TermWindow { // This is pretty heavyweight: it would be nice to only invalidate // the line on which the cursor resides, and then only if the cursor // is within the viewport. + // + // If self.has_animation is true, then the last render detected + // image attachments with multiple frames, so we also need to + // invalidate the viewport. if self.config.cursor_blink_rate != 0 && pos.is_active && self.focused.is_some() { let shape = self .config .default_cursor_style .effective_shape(pos.pane.get_cursor_position().shape); - if shape.is_blinking() { + if shape.is_blinking() || *self.has_animation.borrow() { if now.duration_since(self.last_blink_paint) > Duration::from_millis(self.config.cursor_blink_rate) { diff --git a/wezterm-gui/src/termwindow/render.rs b/wezterm-gui/src/termwindow/render.rs index 6e94ef317..dbb5e3b41 100644 --- a/wezterm-gui/src/termwindow/render.rs +++ b/wezterm-gui/src/termwindow/render.rs @@ -64,6 +64,10 @@ pub struct ComputeCellFgBgResult { impl super::TermWindow { pub fn paint_impl(&mut self, frame: &mut glium::Frame) { + // If nothing on screen needs animating, then we can avoid + // invalidating as frequently + *self.has_animation.borrow_mut() = false; + self.check_for_config_reload(); let start = std::time::Instant::now(); @@ -230,7 +234,11 @@ impl super::TermWindow { let color = rgbcolor_alpha_to_window_color(palette.background, background_image_alpha); if let Some(im) = self.window_background.as_ref() { - let sprite = gl_state.glyph_cache.borrow_mut().cached_image(im, None)?; + let (sprite, num_frames) = + gl_state.glyph_cache.borrow_mut().cached_image(im, None)?; + if num_frames > 1 { + *self.has_animation.borrow_mut() = true; + } quad.set_texture(sprite.texture_coords()); quad.set_is_background_image(); } else { @@ -985,10 +993,13 @@ impl super::TermWindow { padding.next_power_of_two() }; - let sprite = gl_state + let (sprite, num_frames) = gl_state .glyph_cache .borrow_mut() .cached_image(image.image_data(), Some(padding))?; + if num_frames > 1 { + *self.has_animation.borrow_mut() = true; + } let width = sprite.coords.size.width; let height = sprite.coords.size.height;