use cosmic_text::{Attrs, AttrsList, Buffer, Family, FontSystem, Metrics, SwashCache}; use image::{Rgba, RgbaImage}; use crate::{ layout::{TextureHandle, Textures, UiColor, Vec2}, util::HashMap, }; pub struct TextData { pub font_system: FontSystem, pub swash_cache: SwashCache, } impl Default for TextData { fn default() -> Self { Self { font_system: FontSystem::new(), swash_cache: SwashCache::new(), } } } #[derive(Clone, Copy)] pub struct TextAttrs { pub color: UiColor, pub font_size: f32, pub line_height: f32, pub family: Family<'static>, } impl TextAttrs { pub fn apply(&self, font_system: &mut FontSystem, buf: &mut Buffer) { buf.set_metrics(font_system, Metrics::new(self.font_size, self.line_height)); let attrs = Attrs::new().family(self.family); let list = AttrsList::new(&attrs); for line in &mut buf.lines { line.set_attrs_list(list.clone()); } } } pub type TextBuffer = Buffer; impl Default for TextAttrs { fn default() -> Self { let size = 14.0; Self { color: UiColor::WHITE, font_size: size, line_height: size * 1.2, family: Family::SansSerif, } } } impl TextData { pub fn draw( &mut self, buffer: &mut TextBuffer, attrs: &TextAttrs, textures: &mut Textures, ) -> (TextureHandle, TextOffset) { let mut pixels = HashMap::new(); let mut min_x = 0; let mut min_y = 0; let mut max_x = 0; let mut max_y = 0; let cosmic_color = { let c = attrs.color; cosmic_text::Color::rgba(c.r, c.g, c.b, c.a) }; let mut max_width = 0.0f32; for run in buffer.layout_runs() { for glyph in run.glyphs.iter() { let physical_glyph = glyph.physical((0., 0.), 1.0); let glyph_color = match glyph.color_opt { Some(some) => some, None => cosmic_color, }; self.swash_cache.with_pixels( &mut self.font_system, physical_glyph.cache_key, glyph_color, |x, y, color| { let x = physical_glyph.x + x; let y = run.line_y as i32 + physical_glyph.y + y; min_x = min_x.min(x); min_y = min_y.min(y); max_x = max_x.max(x); max_y = max_y.max(y); pixels.insert((x, y), Rgba(color.as_rgba())); }, ); } max_width = max_width.max(run.line_w); } let width = (max_x - min_x + 1) as u32; let height = (max_y - min_y + 1) as u32; let mut image = RgbaImage::new(width, height); for ((x, y), color) in pixels { let x = (x - min_x) as u32; let y = (y - min_y) as u32; image.put_pixel(x, y, color); } let lines = buffer.lines.len(); let offset = TextOffset { top_left: Vec2::new(min_x as f32, min_y as f32), bot_right: Vec2::new( max_width - max_x as f32, attrs.line_height * lines as f32 - max_y as f32, ), }; (textures.add(image), offset) } } #[derive(Clone, Copy)] pub struct TextOffset { pub top_left: Vec2, pub bot_right: Vec2, } impl TextOffset { pub fn size(&self, handle: &TextureHandle) -> Vec2 { handle.size() - self.top_left + self.bot_right } }