From 9732f9ee2b1795d79ec7be1788045a3961fb55fd Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sun, 28 Aug 2022 10:27:50 -0700 Subject: [PATCH] Adjust render caching; switch to LFU caches from LRU --- Cargo.lock | 13 +- termwiz/Cargo.toml | 1 + termwiz/src/cell.rs | 26 ++- termwiz/src/color.rs | 2 +- termwiz/src/hyperlink.rs | 10 ++ termwiz/src/image.rs | 16 +- termwiz/src/surface/line/cellref.rs | 6 + termwiz/src/surface/line/line.rs | 22 ++- wezterm-gui/Cargo.toml | 3 +- wezterm-gui/src/cache.rs | 162 ++++++++++++++++--- wezterm-gui/src/glyphcache.rs | 14 +- wezterm-gui/src/shapecache.rs | 9 +- wezterm-gui/src/termwindow/mod.rs | 36 +++-- wezterm-gui/src/termwindow/render.rs | 229 ++++++++++++++------------- 14 files changed, 380 insertions(+), 169 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6be838cc9..7c1397bfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -434,6 +434,15 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" +[[package]] +name = "cache-advisor" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656c75db54b59b714d3f30a5006160f9fbe329ca2fd6520a65910552f2d37664" +dependencies = [ + "crossbeam-queue", +] + [[package]] name = "cache-padded" version = "1.2.0" @@ -4562,6 +4571,7 @@ dependencies = [ "serde", "sha2", "signal-hook 0.1.17", + "siphasher", "terminfo", "termios 0.3.3", "thiserror", @@ -5405,6 +5415,7 @@ dependencies = [ "anyhow", "benchmarking", "bitflags", + "cache-advisor", "cc", "chrono", "clap 3.2.17", @@ -5419,6 +5430,7 @@ dependencies = [ "euclid", "fastrand", "filedescriptor", + "fnv", "futures", "fuzzy-matcher", "hdrhistogram", @@ -5428,7 +5440,6 @@ dependencies = [ "lazy_static", "libc", "log", - "lru", "luahelper", "metrics", "mlua", diff --git a/termwiz/Cargo.toml b/termwiz/Cargo.toml index 793880ef3..8c427bb82 100644 --- a/termwiz/Cargo.toml +++ b/termwiz/Cargo.toml @@ -34,6 +34,7 @@ phf = "0.10" regex = "1" semver = "0.11" serde = {version="1.0", features = ["rc", "derive"], optional=true} +siphasher = "0.3" sha2 = "0.9" terminfo = "0.7" thiserror = "1.0" diff --git a/termwiz/src/cell.rs b/termwiz/src/cell.rs index 0c1887d81..b4cb1d7b0 100644 --- a/termwiz/src/cell.rs +++ b/termwiz/src/cell.rs @@ -7,12 +7,13 @@ use crate::image::ImageCell; use crate::widechar_width::WcWidth; #[cfg(feature = "use_serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::hash::{Hash, Hasher}; use std::mem; use std::sync::Arc; use wezterm_dynamic::{FromDynamic, ToDynamic}; #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Copy, Eq, PartialEq)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] enum SmallColor { Default, PaletteIndex(PaletteIndex), @@ -87,6 +88,20 @@ struct FatAttributes { background: ColorAttribute, } +impl FatAttributes { + pub fn compute_shape_hash(&self, hasher: &mut H) { + if let Some(link) = &self.hyperlink { + link.compute_shape_hash(hasher); + } + for cell in &self.image { + cell.compute_shape_hash(hasher); + } + self.underline_color.hash(hasher); + self.foreground.hash(hasher); + self.background.hash(hasher); + } +} + /// Define getter and setter for the attributes bitfield. /// The first form is for a simple boolean value stored in /// a single bit. The $bitnum parameter specifies which bit. @@ -267,6 +282,15 @@ impl CellAttributes { self.attributes == other.attributes } + pub fn compute_shape_hash(&self, hasher: &mut H) { + self.attributes.hash(hasher); + self.foreground.hash(hasher); + self.background.hash(hasher); + if let Some(fat) = &self.fat { + fat.compute_shape_hash(hasher); + } + } + /// Set the foreground color for the cell to that specified pub fn set_foreground>(&mut self, foreground: C) -> &mut Self { let foreground: ColorAttribute = foreground.into(); diff --git a/termwiz/src/color.rs b/termwiz/src/color.rs index f8cae95f6..51dbb0afd 100644 --- a/termwiz/src/color.rs +++ b/termwiz/src/color.rs @@ -262,7 +262,7 @@ impl From for ColorSpec { /// TrueColor value, allowing a fallback to a more traditional palette /// index if TrueColor is not available. #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Copy, Eq, PartialEq, FromDynamic, ToDynamic)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, FromDynamic, ToDynamic, Hash)] pub enum ColorAttribute { /// Use RgbColor when supported, falling back to the specified PaletteIndex. TrueColorWithPaletteFallback(SrgbaTuple, PaletteIndex), diff --git a/termwiz/src/hyperlink.rs b/termwiz/src/hyperlink.rs index 6feb4c024..d513ff35a 100644 --- a/termwiz/src/hyperlink.rs +++ b/termwiz/src/hyperlink.rs @@ -10,6 +10,7 @@ use regex::{Captures, Regex}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::collections::HashMap; use std::fmt::{Display, Error as FmtError, Formatter}; +use std::hash::{Hash, Hasher}; use std::ops::Range; use std::sync::Arc; use wezterm_dynamic::{FromDynamic, FromDynamicOptions, ToDynamic, Value}; @@ -29,6 +30,15 @@ impl Hyperlink { &self.uri } + pub fn compute_shape_hash(&self, hasher: &mut H) { + self.uri.hash(hasher); + for (k, v) in &self.params { + k.hash(hasher); + v.hash(hasher); + } + self.implicit.hash(hasher); + } + pub fn params(&self) -> &HashMap { &self.params } diff --git a/termwiz/src/image.rs b/termwiz/src/image.rs index 88d537e00..3bfc69410 100644 --- a/termwiz/src/image.rs +++ b/termwiz/src/image.rs @@ -14,6 +14,7 @@ use ordered_float::NotNan; #[cfg(feature = "use_serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; @@ -36,7 +37,7 @@ where } #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TextureCoordinate { #[cfg_attr( feature = "use_serde", @@ -105,6 +106,19 @@ impl ImageCell { Self::with_z_index(top_left, bottom_right, data, 0, 0, 0, 0, 0, None, None) } + pub fn compute_shape_hash(&self, hasher: &mut H) { + self.top_left.hash(hasher); + self.bottom_right.hash(hasher); + self.data.hash.hash(hasher); + self.z_index.hash(hasher); + self.padding_left.hash(hasher); + self.padding_top.hash(hasher); + self.padding_right.hash(hasher); + self.padding_bottom.hash(hasher); + self.image_id.hash(hasher); + self.placement_id.hash(hasher); + } + pub fn with_z_index( top_left: TextureCoordinate, bottom_right: TextureCoordinate, diff --git a/termwiz/src/surface/line/cellref.rs b/termwiz/src/surface/line/cellref.rs index 31fd8b03b..10355146b 100644 --- a/termwiz/src/surface/line/cellref.rs +++ b/termwiz/src/surface/line/cellref.rs @@ -1,5 +1,6 @@ use crate::cell::{Cell, CellAttributes}; use crate::emoji::Presentation; +use std::hash::{Hash, Hasher}; #[derive(Debug)] pub enum CellRef<'a> { @@ -65,4 +66,9 @@ impl<'a> CellRef<'a> { pub fn same_contents(&self, other: &Self) -> bool { self.str() == other.str() && self.width() == other.width() && self.attrs() == other.attrs() } + + pub fn compute_shape_hash(&self, hasher: &mut H) { + self.str().hash(hasher); + self.attrs().compute_shape_hash(hasher); + } } diff --git a/termwiz/src/surface/line/line.rs b/termwiz/src/surface/line/line.rs index 63a383270..9583a55e6 100644 --- a/termwiz/src/surface/line/line.rs +++ b/termwiz/src/surface/line/line.rs @@ -9,8 +9,10 @@ use crate::surface::line::vecstorage::{VecStorage, VecStorageIter}; use crate::surface::{Change, SequenceNo, SEQ_ZERO}; #[cfg(feature = "use_serde")] use serde::{Deserialize, Serialize}; +use siphasher::sip128::{Hasher128, SipHasher}; use std::any::Any; use std::borrow::Cow; +use std::hash::Hash; use std::ops::Range; use std::sync::{Arc, Mutex, Weak}; use unicode_segmentation::UnicodeSegmentation; @@ -97,6 +99,23 @@ impl Line { } } + /// Computes a hash over the line that will change if the way that + /// the line contents are shaped would change. + /// This is independent of the seqno and is based purely on the + /// content of the line. + /// + /// Line doesn't implement Hash in terms of this function as compute_shape_hash + /// doesn't every possible bit of internal state, and we don't want to + /// encourage using Line directly as a hash key. + pub fn compute_shape_hash(&self) -> [u8; 16] { + let mut hasher = SipHasher::new(); + self.bits.bits().hash(&mut hasher); + for cell in self.visible_cells() { + cell.compute_shape_hash(&mut hasher); + } + hasher.finish128().as_bytes() + } + pub fn with_width(width: usize, seqno: SequenceNo) -> Self { let mut cells = Vec::with_capacity(width); cells.resize_with(width, Cell::blank); @@ -216,7 +235,8 @@ impl Line { /// and not for use by "middleware" crates. /// A Weak reference is stored. /// `get_appdata` is used to retrieve a previously stored reference. - pub fn set_appdata(&self, appdata: Arc) { + pub fn set_appdata(&self, appdata: Arc) { + let appdata: Arc = appdata; self.appdata .lock() .unwrap() diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml index 86ce0acc7..254bda571 100644 --- a/wezterm-gui/Cargo.toml +++ b/wezterm-gui/Cargo.toml @@ -23,6 +23,7 @@ cc = "1.0" [dependencies] anyhow = "1.0" bitflags = "1.3" +cache-advisor = "1.0" chrono = {version="0.4", features=["unstable-locales"]} clap = {version="3.1", features=["derive"]} codec = { path = "../codec" } @@ -34,6 +35,7 @@ env-bootstrap = { path = "../env-bootstrap" } euclid = "0.22" fastrand = "1.6" filedescriptor = { version="0.8", path = "../filedescriptor" } +fnv = "1.0" futures = "0.3" fuzzy-matcher = "0.3" hdrhistogram = "7.1" @@ -42,7 +44,6 @@ image = "0.24" lazy_static = "1.4" libc = "0.2" log = "0.4" -lru = "0.7" luahelper = { path = "../luahelper" } metrics = { version="0.17", features=["std"]} mlua = {version="0.8.3", features=["send"]} diff --git a/wezterm-gui/src/cache.rs b/wezterm-gui/src/cache.rs index d11bc8dd6..b84cd0279 100644 --- a/wezterm-gui/src/cache.rs +++ b/wezterm-gui/src/cache.rs @@ -1,45 +1,159 @@ -pub struct LruCache { +#![allow(dead_code)] +use cache_advisor::CacheAdvisor; +use fnv::FnvHashMap; +use std::borrow::Borrow; +use std::cmp::Eq; +use std::collections::HashMap; +use std::hash::Hash; + +/// Use ENTRY_PERCENT of the capacity as the "temporary cache"; entries +/// are evicted from the temporary cache before the main cache. +/// Frequently used items are promoted from temporary to main cache. +const ENTRY_PERCENT: u8 = 20; + +/// A cache using a Least-Frequently-Used eviction policy. +/// If K is u64 you should use LfuCacheU64 instead as it has +/// less overhead. +pub struct LfuCache { hit: &'static str, miss: &'static str, - cache: lru::LruCache, + key_to_id: HashMap, + map: FnvHashMap, + next_id: u64, + advisor: CacheAdvisor, + cap: usize, } -impl LruCache { +impl LfuCache { pub fn new(hit: &'static str, miss: &'static str, cap: usize) -> Self { Self { hit, miss, - cache: lru::LruCache::new(cap), + key_to_id: HashMap::with_capacity(cap), + map: FnvHashMap::default(), + advisor: CacheAdvisor::new(cap, ENTRY_PERCENT), + next_id: 0, + cap, + } + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn clear(&mut self) { + self.map.clear(); + self.advisor = CacheAdvisor::new(self.cap, ENTRY_PERCENT); + } + + fn process_evictions(&mut self, evict: &[(u64, usize)]) { + for (evict_id, _cost) in evict { + if let Some((evict_key, _v)) = self.map.remove(&evict_id) { + self.key_to_id.remove(&evict_key); + } } } pub fn get<'a, Q: ?Sized>(&'a mut self, k: &Q) -> Option<&'a V> where - lru::KeyRef: std::borrow::Borrow, - Q: std::hash::Hash + Eq, + K: Borrow, + Q: Hash + Eq, { - let result = self.cache.get(k); - metrics::histogram!( - if result.is_some() { - self.hit - } else { - self.miss - }, - 1. - ); - result + let id = match self.key_to_id.get(k) { + Some(id) => *id, + None => { + metrics::histogram!(self.miss, 1.0); + return None; + } + }; + + let evict = self.advisor.accessed(id, 1); + self.process_evictions(&evict); + + metrics::histogram!(self.hit, 1.); + + self.map.get(&id).map(|(_k, v)| v) + } + + pub fn put(&mut self, k: K, v: V) -> Option { + let id = match self.key_to_id.get(&k) { + Some(id) => *id, + None => { + let id = self.next_id; + self.next_id += 1; + self.key_to_id.insert(k.clone(), id); + id + } + }; + + let evict = self.advisor.accessed(id, 1); + self.process_evictions(&evict); + + self.map.insert(id, (k, v)).map(|(_k, v)| v) } } -impl std::ops::Deref for LruCache { - type Target = lru::LruCache; - fn deref(&self) -> &lru::LruCache { - &self.cache - } +/// A cache using a Least-Frequently-Used eviction policy, where the cache keys +/// are u64 +pub struct LfuCacheU64 { + hit: &'static str, + miss: &'static str, + map: FnvHashMap, + advisor: CacheAdvisor, + cap: usize, } -impl std::ops::DerefMut for LruCache { - fn deref_mut(&mut self) -> &mut lru::LruCache { - &mut self.cache +impl LfuCacheU64 { + pub fn new(hit: &'static str, miss: &'static str, cap: usize) -> Self { + Self { + hit, + miss, + map: FnvHashMap::default(), + advisor: CacheAdvisor::new(cap, ENTRY_PERCENT), + cap, + } + } + + pub fn len(&self) -> usize { + self.map.len() + } + + pub fn clear(&mut self) { + self.map.clear(); + self.advisor = CacheAdvisor::new(self.cap, ENTRY_PERCENT); + } + + fn process_evictions(&mut self, evict: &[(u64, usize)]) { + for (evict_id, _cost) in evict { + self.map.remove(&evict_id); + } + } + + pub fn get(&mut self, id: &u64) -> Option<&V> { + if !self.map.contains_key(&id) { + metrics::histogram!(self.miss, 1.0); + return None; + } + let evict = self.advisor.accessed(*id, 1); + self.process_evictions(&evict); + metrics::histogram!(self.hit, 1.); + self.map.get(&id) + } + + pub fn get_mut(&mut self, id: &u64) -> Option<&mut V> { + if !self.map.contains_key(&id) { + metrics::histogram!(self.miss, 1.0); + return None; + } + let evict = self.advisor.accessed(*id, 1); + self.process_evictions(&evict); + metrics::histogram!(self.hit, 1.); + self.map.get_mut(&id) + } + + pub fn put(&mut self, id: u64, v: V) -> Option { + let evict = self.advisor.accessed(id, 1); + self.process_evictions(&evict); + self.map.insert(id, v) } } diff --git a/wezterm-gui/src/glyphcache.rs b/wezterm-gui/src/glyphcache.rs index 7c5dd2a03..25bf95b3a 100644 --- a/wezterm-gui/src/glyphcache.rs +++ b/wezterm-gui/src/glyphcache.rs @@ -1,5 +1,5 @@ use super::utilsprites::RenderMetrics; -use crate::cache::LruCache; +use crate::cache::LfuCacheU64; use crate::customglyph::*; use ::window::bitmaps::atlas::{Atlas, OutOfTextureSpace, Sprite}; #[cfg(test)] @@ -249,7 +249,7 @@ pub struct GlyphCache { glyph_cache: HashMap>>, pub atlas: Atlas, fonts: Rc, - pub image_cache: LruCache, + pub image_cache: LfuCacheU64, frame_cache: HashMap<[u8; 32], Sprite>, line_glyphs: HashMap>, pub block_glyphs: HashMap>, @@ -266,10 +266,10 @@ impl GlyphCache { Ok(Self { fonts: Rc::clone(fonts), glyph_cache: HashMap::new(), - image_cache: LruCache::new( + image_cache: LfuCacheU64::new( "glyph_cache.image_cache.hit.rate", "glyph_cache.image_cache.miss.rate", - 16, + 256, ), frame_cache: HashMap::new(), atlas, @@ -316,10 +316,10 @@ impl GlyphCache { Ok(Self { fonts: Rc::clone(fonts), glyph_cache: HashMap::new(), - image_cache: LruCache::new( + image_cache: LfuCacheU64::new( "glyph_cache.image_cache.hit.rate", "glyph_cache.image_cache.miss.rate", - 64, // FIXME: make configurable + 256, // FIXME: make configurable ), frame_cache: HashMap::new(), atlas, @@ -644,7 +644,7 @@ impl GlyphCache { image_data: &Arc, padding: Option, ) -> anyhow::Result<(Sprite, Option)> { - let id = image_data.id(); + let id = image_data.id() as u64; if let Some(decoded) = self.image_cache.get_mut(&id) { Self::cached_image_impl(&mut self.frame_cache, &mut self.atlas, decoded, padding) diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rs index 0d03b04a1..c7ae3bfad 100644 --- a/wezterm-gui/src/shapecache.rs +++ b/wezterm-gui/src/shapecache.rs @@ -5,7 +5,7 @@ use std::rc::Rc; use wezterm_font::shaper::GlyphInfo; use wezterm_font::units::*; -#[derive(PartialEq, Eq, Hash)] +#[derive(PartialEq, Eq, Hash, Clone)] pub struct ShapeCacheKey { pub style: TextStyle, pub text: String, @@ -104,13 +104,6 @@ impl<'a> std::borrow::Borrow for ShapeCacheKey { } } -impl<'a> std::borrow::Borrow for lru::KeyRef { - fn borrow(&self) -> &(dyn ShapeCacheKeyTrait + 'a) { - let k: &ShapeCacheKey = self.borrow(); - k - } -} - impl<'a> PartialEq for (dyn ShapeCacheKeyTrait + 'a) { fn eq(&self, other: &Self) -> bool { self.key().eq(&other.key()) diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs index 0bfa130d1..50e64d583 100644 --- a/wezterm-gui/src/termwindow/mod.rs +++ b/wezterm-gui/src/termwindow/mod.rs @@ -1,7 +1,7 @@ #![cfg_attr(feature = "cargo-clippy", allow(clippy::range_plus_one))] use super::renderstate::*; use super::utilsprites::RenderMetrics; -use crate::cache::LruCache; +use crate::cache::*; use crate::colorease::ColorEase; use crate::frontend::{front_end, try_front_end}; use crate::glium::texture::SrgbTexture2d; @@ -22,7 +22,10 @@ use crate::termwindow::background::{ }; use crate::termwindow::keyevent::{KeyTableArgs, KeyTableState}; use crate::termwindow::modal::Modal; -use crate::termwindow::render::LineToElementShapeItem; +use crate::termwindow::render::{ + CachedLineState, LineQuadCacheKey, LineQuadCacheValue, LineToEleShapeCacheKey, + LineToElementShapeItem, +}; use ::wezterm_term::input::{ClickPosition, MouseButton as TMB}; use ::window::*; use anyhow::{anyhow, ensure, Context}; @@ -45,7 +48,6 @@ use mux::window::WindowId as MuxWindowId; use mux::{Mux, MuxNotification}; use smol::channel::Sender; use smol::Timer; -use std::any::Any; use std::cell::{RefCell, RefMut}; use std::collections::HashMap; use std::ops::Add; @@ -400,10 +402,13 @@ pub struct TermWindow { quad_generation: usize, shape_generation: usize, shape_cache: - RefCell>>>>>, - line_to_ele_shape_cache: RefCell>, - line_render_cache: RefCell>>, - next_line_render_cache_id: usize, + RefCell>>>>>, + line_to_ele_shape_cache: RefCell>, + + line_state_cache: RefCell>>, + next_line_state_id: u64, + + line_quad_cache: RefCell>, last_status_call: Instant, cursor_blink_state: RefCell, @@ -694,18 +699,23 @@ impl TermWindow { current_highlight: None, quad_generation: 0, shape_generation: 0, - shape_cache: RefCell::new(LruCache::new( + shape_cache: RefCell::new(LfuCache::new( "shape_cache.hit.rate", "shape_cache.miss.rate", 1024, )), - next_line_render_cache_id: 0, - line_render_cache: RefCell::new(LruCache::new( - "line_render_cache.hit.rate", - "line_render_cache.miss.rate", + line_state_cache: RefCell::new(LfuCacheU64::new( + "line_state_cache.hit.rate", + "line_state_cache.miss.rate", 1024, )), - line_to_ele_shape_cache: RefCell::new(LruCache::new( + next_line_state_id: 0, + line_quad_cache: RefCell::new(LfuCache::new( + "line_quad_cache.hit.rate", + "line_quad_cache.miss.rate", + 1024, + )), + line_to_ele_shape_cache: RefCell::new(LfuCache::new( "line_to_ele_shape_cache.hit.rate", "line_to_ele_shape_cache.miss.rate", 1024, diff --git a/wezterm-gui/src/termwindow/render.rs b/wezterm-gui/src/termwindow/render.rs index 49ee9be77..d00ca64e5 100644 --- a/wezterm-gui/src/termwindow/render.rs +++ b/wezterm-gui/src/termwindow/render.rs @@ -31,8 +31,8 @@ use euclid::num::Zero; use mux::pane::{Pane, WithPaneLines}; use mux::renderable::{RenderableDimensions, StableCursorPosition}; use mux::tab::{PositionedPane, PositionedSplit, SplitDirection}; +use ordered_float::NotNan; use smol::Timer; -use std::any::Any; use std::ops::Range; use std::rc::Rc; use std::sync::Arc; @@ -143,26 +143,35 @@ const PLUS_BUTTON: &[Poly] = &[ }, ]; +/// The data that we associate with a line; we use this to cache it shape hash #[derive(Debug)] -pub struct LineRenderCache { +pub struct CachedLineState { + pub id: u64, + pub seqno: SequenceNo, + pub shape_hash: [u8; 16], +} + +#[derive(Debug, Hash, Clone, PartialEq, Eq)] +pub struct LineQuadCacheKey { pub config_generation: usize, pub shape_generation: usize, pub quad_generation: usize, - pub seqno: SequenceNo, /// Only set if cursor.y == stable_row /// Tuple is (cursor_x, compose-text) pub composing: Option, pub selection: Range, - - pub id: usize, - pub expires: Option, - pub top_pixel_y: f32, - pub left_pixel_x: f32, + pub shape_hash: [u8; 16], + pub top_pixel_y: NotNan, + pub left_pixel_x: NotNan, pub phys_line_idx: usize, pub cursor_x: Option, pub reverse_video: bool, +} - // Value portion +pub struct LineQuadCacheValue { + /// For resolving hash collisions + pub line: Line, + pub expires: Option, pub layers: HeapQuadAllocator, } @@ -174,16 +183,12 @@ pub struct LineToElementParams<'a> { pub window_is_transparent: bool, pub cursor: &'a StableCursorPosition, pub reverse_video: bool, - pub shape_id: Option, + pub shape_key: &'a Option, } -#[derive(Hash, PartialEq, Eq, Clone)] -pub struct LineToElementShapeKey { - pub shape_id: Option, - pub seqno: SequenceNo, - pub stable_line_idx: StableRowIndex, - /// Only set if cursor.y == stable_row - /// Tuple is (cursor_x, compose-text) +#[derive(Debug, Hash, PartialEq, Eq, Clone)] +pub struct LineToEleShapeCacheKey { + pub shape_hash: [u8; 16], pub composing: Option<(usize, String)>, } @@ -248,7 +253,7 @@ pub struct RenderScreenLineOpenGLParams<'a> { pub use_pixel_positioning: bool, pub render_metrics: RenderMetrics, - pub shape_id: Option, + pub shape_key: Option, } pub struct ComputeCellFgBgParams<'a> { @@ -1107,7 +1112,7 @@ impl super::TermWindow { font: None, use_pixel_positioning: self.config.experimental_pixel_positioning, render_metrics: self.render_metrics, - shape_id: None, + shape_key: None, }, layers, )?; @@ -1682,55 +1687,56 @@ impl super::TermWindow { None }; - let mut shape_id = None; + let shape_hash = self.term_window.shape_hash_for_line(line); - if let Some(cached_arc) = line.get_appdata() { - if let Some(cached) = cached_arc.downcast_ref::() { - let expired = - cached.expires.map(|i| Instant::now() >= i).unwrap_or(false); - let shape_consistent = cached.config_generation - == self.term_window.config.generation() - && cached.shape_generation == self.term_window.shape_generation - && cached.seqno == line.current_seqno() - && cached.reverse_video == self.dims.reverse_video - && cached.composing == composing; - let quad_consistent = cached.selection == selrange - && cached.top_pixel_y == self.top_pixel_y - && cached.left_pixel_x == self.left_pixel_x - && cached.cursor_x == cursor_x - && cached.quad_generation == self.term_window.quad_generation - && cached.phys_line_idx == line_idx; + let quad_key = LineQuadCacheKey { + config_generation: self.term_window.config.generation(), + shape_generation: self.term_window.shape_generation, + quad_generation: self.term_window.quad_generation, + composing: composing.clone(), + selection: selrange.clone(), + cursor_x, + shape_hash, + top_pixel_y: NotNan::new(self.top_pixel_y).unwrap(), + left_pixel_x: NotNan::new(self.left_pixel_x).unwrap(), + phys_line_idx: line_idx, + reverse_video: self.dims.reverse_video, + }; - if shape_consistent && quad_consistent && !expired { - cached.layers.apply_to(&mut TripleLayerQuadAllocator::Heap( - &mut self.layers, - ))?; - self.term_window.update_next_frame_time(cached.expires); - // Touch it in the LRU - self.term_window - .line_render_cache - .borrow_mut() - .put(cached.id, cached_arc); - return Ok(()); - } - - shape_id = if shape_consistent && !expired { - Some(cached.id) - } else { - None - }; + if let Some(cached_quad) = + self.term_window.line_quad_cache.borrow_mut().get(&quad_key) + { + let expired = cached_quad + .expires + .map(|i| Instant::now() >= i) + .unwrap_or(false); + if !expired { + cached_quad + .layers + .apply_to(&mut TripleLayerQuadAllocator::Heap(&mut self.layers))?; + self.term_window.update_next_frame_time(cached_quad.expires); + return Ok(()); } } - let shape_id = shape_id.unwrap_or_else(|| { - let id = self.term_window.next_line_render_cache_id; - self.term_window.next_line_render_cache_id += 1; - id - }); - let mut buf = HeapQuadAllocator::default(); let next_due = self.term_window.has_animation.borrow_mut().take(); + let shape_key = LineToEleShapeCacheKey { + shape_hash, + composing: if self.cursor.y == stable_row { + if let DeadKeyStatus::Composing(composing) = + &self.term_window.dead_key_status + { + Some((self.cursor.x, composing.to_string())) + } else { + None + } + } else { + None + }, + }; + self.term_window.render_screen_line_opengl( RenderScreenLineOpenGLParams { top_pixel_y: self.top_pixel_y @@ -1766,7 +1772,7 @@ impl super::TermWindow { .config .experimental_pixel_positioning, render_metrics: self.term_window.render_metrics, - shape_id: Some(shape_id), + shape_key: Some(shape_key), }, &mut TripleLayerQuadAllocator::Heap(&mut buf), )?; @@ -1776,32 +1782,16 @@ impl super::TermWindow { buf.apply_to(&mut TripleLayerQuadAllocator::Heap(&mut self.layers))?; - let id = self.term_window.next_line_render_cache_id; - self.term_window.next_line_render_cache_id += 1; - - let cached: Arc = Arc::new(LineRenderCache { - config_generation: self.term_window.config.generation(), - shape_generation: self.term_window.shape_generation, - quad_generation: self.term_window.quad_generation, - seqno: line.current_seqno(), - composing, - selection: selrange, - cursor_x, - id: shape_id, - top_pixel_y: self.top_pixel_y, - left_pixel_x: self.left_pixel_x, - phys_line_idx: line_idx, + let quad_value = LineQuadCacheValue { layers: buf, - reverse_video: self.dims.reverse_video, expires, - }); - - line.set_appdata(Arc::clone(&cached)); + line: (*line).clone(), + }; self.term_window - .line_render_cache + .line_quad_cache .borrow_mut() - .put(id, cached); + .put(quad_key, quad_value); Ok(()) } @@ -2170,7 +2160,6 @@ impl super::TermWindow { fn build_line_element_shape( &self, params: LineToElementParams, - shape_key: LineToElementShapeKey, ) -> anyhow::Result>> { let (bidi_enabled, bidi_direction) = params.line.bidi_info(); let bidi_hint = if bidi_enabled { @@ -2178,15 +2167,13 @@ impl super::TermWindow { } else { None }; - let cell_clusters = if let Some((cursor_x, composing)) = &shape_key.composing { + let cell_clusters = if let Some((cursor_x, composing)) = + params.shape_key.as_ref().and_then(|k| k.composing.as_ref()) + { // Create an updated line with the composition overlaid let mut line = params.line.clone(); - line.overlay_text_with_attribute( - *cursor_x, - &composing, - CellAttributes::blank(), - shape_key.seqno, - ); + let seqno = line.current_seqno(); + line.overlay_text_with_attribute(*cursor_x, &composing, CellAttributes::blank(), seqno); line.cluster(bidi_hint) } else { params.line.cluster(bidi_hint) @@ -2336,9 +2323,9 @@ impl super::TermWindow { let shaped = Rc::new(shaped); - if let Some(shape_id) = shape_key.shape_id { + if let Some(shape_key) = params.shape_key { self.line_to_ele_shape_cache.borrow_mut().put( - shape_id, + shape_key.clone(), LineToElementShapeItem { expires, shaped: Rc::clone(&shaped), @@ -2442,8 +2429,9 @@ impl super::TermWindow { ..params.left_pixel_x + cursor_range.end as f32 * cell_width; let mut shaped = None; - if let Some(shape_id) = params.shape_id { - if let Some(entry) = self.line_to_ele_shape_cache.borrow_mut().get(&shape_id) { + if let Some(shape_key) = ¶ms.shape_key { + let mut cache = self.line_to_ele_shape_cache.borrow_mut(); + if let Some(entry) = cache.get(shape_key) { let expired = entry.expires.map(|i| Instant::now() >= i).unwrap_or(false); if !expired { @@ -2464,25 +2452,10 @@ impl super::TermWindow { stable_line_idx: params.stable_line_idx.unwrap_or(0), window_is_transparent: params.window_is_transparent, reverse_video: params.dims.reverse_video, - shape_id: params.shape_id, + shape_key: ¶ms.shape_key, }; - let shape_key = LineToElementShapeKey { - shape_id: params.shape_id, - seqno: params.line.current_seqno(), - stable_line_idx: params.stable_line_idx, - composing: if params.cursor.y == params.stable_line_idx { - if let DeadKeyStatus::Composing(composing) = &self.dead_key_status { - Some((params.cursor.x, composing.to_string())) - } else { - None - } - } else { - None - }, - }; - - self.build_line_element_shape(params, shape_key)? + self.build_line_element_shape(params)? }; let bounding_rect = euclid::rect( @@ -3432,6 +3405,40 @@ impl super::TermWindow { } Ok(()) } + + fn shape_hash_for_line(&mut self, line: &Line) -> [u8; 16] { + let seqno = line.current_seqno(); + let mut id = None; + if let Some(cached_arc) = line.get_appdata() { + if let Some(line_state) = cached_arc.downcast_ref::() { + if line_state.seqno == seqno { + // Touch the LRU + self.line_state_cache.borrow_mut().get(&line_state.id); + return line_state.shape_hash; + } + id.replace(line_state.id); + } + } + + let id = id.unwrap_or_else(|| { + let id = self.next_line_state_id; + self.next_line_state_id += 1; + id + }); + + let shape_hash = line.compute_shape_hash(); + + let state = Arc::new(CachedLineState { + id, + seqno, + shape_hash, + }); + + line.set_appdata(Arc::clone(&state)); + + self.line_state_cache.borrow_mut().put(id, state); + shape_hash + } } pub fn rgbcolor_to_window_color(color: RgbColor) -> LinearRgba {