cosmic_text/
render.rs

1//! Helpers for rendering buffers and editors
2
3use crate::{Color, PhysicalGlyph};
4#[cfg(feature = "swash")]
5use crate::{FontSystem, SwashCache};
6
7/// Custom renderer for buffers and editors
8pub trait Renderer {
9    /// Render a rectangle at x, y with size w, h and the provided [`Color`].
10    fn rectangle(&mut self, x: i32, y: i32, w: u32, h: u32, color: Color);
11
12    /// Render a [`PhysicalGlyph`] with the provided [`Color`].
13    /// For performance, consider using [`SwashCache`].
14    fn glyph(&mut self, physical_glyph: PhysicalGlyph, color: Color);
15}
16
17/// Helper to migrate from old renderer
18//TODO: remove in future version
19#[cfg(feature = "swash")]
20#[derive(Debug)]
21pub struct LegacyRenderer<'a, F: FnMut(i32, i32, u32, u32, Color)> {
22    pub font_system: &'a mut FontSystem,
23    pub cache: &'a mut SwashCache,
24    pub callback: F,
25}
26
27#[cfg(feature = "swash")]
28impl<'a, F: FnMut(i32, i32, u32, u32, Color)> Renderer for LegacyRenderer<'a, F> {
29    fn rectangle(&mut self, x: i32, y: i32, w: u32, h: u32, color: Color) {
30        (self.callback)(x, y, w, h, color);
31    }
32
33    fn glyph(&mut self, physical_glyph: PhysicalGlyph, color: Color) {
34        self.cache.with_pixels(
35            self.font_system,
36            physical_glyph.cache_key,
37            color,
38            |x, y, pixel_color| {
39                (self.callback)(
40                    physical_glyph.x + x,
41                    physical_glyph.y + y,
42                    1,
43                    1,
44                    pixel_color,
45                );
46            },
47        );
48    }
49}