diff --git a/src/font/fontloader_and_freetype.rs b/src/font/fontloader_and_freetype.rs index 3078bd849..87196586a 100644 --- a/src/font/fontloader_and_freetype.rs +++ b/src/font/fontloader_and_freetype.rs @@ -90,7 +90,7 @@ impl NamedFont for NamedFontImpl { } fn shape(&mut self, s: &str) -> Result, Error> { - let mut shaped = Vec::new(); + let mut shaped = Vec::with_capacity(s.len()); let mut cluster = 0; for c in s.chars() { diff --git a/src/font/ftfont.rs b/src/font/ftfont.rs index 8bf175289..52a3d09e2 100644 --- a/src/font/ftfont.rs +++ b/src/font/ftfont.rs @@ -2,6 +2,7 @@ use crate::font::system::GlyphInfo; use crate::font::{ftwrap, Font, FontMetrics, RasterizedGlyph}; use failure::Error; use std::cell::RefCell; +use std::collections::HashMap; use std::mem; use std::slice; @@ -17,6 +18,7 @@ pub struct FreeTypeFontImpl { cell_height: f64, /// nominal monospace cell width cell_width: f64, + glyph_cache: RefCell>, } impl FreeTypeFontImpl { @@ -74,12 +76,20 @@ impl FreeTypeFontImpl { font: RefCell::new(font), cell_height, cell_width, + glyph_cache: RefCell::new(HashMap::new()), }) } pub fn single_glyph_info(&self, codepoint: char) -> Result { + // Memoize this, as we are called frequently during shaping + { + let cache = self.glyph_cache.borrow_mut(); + if let Some(info) = cache.get(&codepoint) { + return Ok(info.clone()); + } + } let (glyph_pos, metrics) = self.face.borrow_mut().load_codepoint(codepoint)?; - Ok(GlyphInfo { + let info = GlyphInfo { #[cfg(debug_assertions)] text: codepoint.to_string(), cluster: 0, @@ -90,7 +100,13 @@ impl FreeTypeFontImpl { x_offset: 0.0, //(metrics.horiBearingX as f64 / 64.0).into(), y_advance: 0.0, y_offset: 0.0, - }) + }; + + self.glyph_cache + .borrow_mut() + .insert(codepoint, info.clone()); + + Ok(info) } }