Skip to main content

eternal_ui_skia/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Skia rendering for [eternal-ui](eternal_ui).
6//!
7//! Two types implement the toolkit's backend traits: [`SkiaFonts`] measures
8//! text (the [`Fonts`] trait) and [`SkiaRenderer`] draws one frame onto a
9//! Skia `Canvas` (the [`Renderer`] trait). Where the canvas comes from is up
10//! to the application: a CPU raster surface, or a GPU surface through one
11//! of skia-safe's `gl`, `metal` or `vulkan` features.
12//!
13//! ```
14//! use eternal_ui::{ui, Element, Size, Ui};
15//! use eternal_ui_skia::{SkiaFonts, SkiaRenderer};
16//!
17//! let mut ui: Ui<()> = Ui::new();
18//! ui.set_root(ui! { <panel><button>"Hello"</button></panel> });
19//!
20//! let fonts = SkiaFonts::new();
21//! let mut surface = skia_safe::surfaces::raster_n32_premul((200, 100)).unwrap();
22//! ui.layout(Size::new(200.0, 100.0), &fonts);
23//! let mut renderer = SkiaRenderer::new(surface.canvas(), &fonts);
24//! ui.paint(&mut renderer);
25//! ```
26//!
27//! Shapes are drawn without anti-aliasing and text without subpixel
28//! positioning, so 1px borders and pixel fonts stay crisp. Call
29//! [`SkiaFonts::set_smooth`] for the ordinary anti-aliased look.
30//!
31//! Fonts come from the system by default. Load your own, such as a pixel
32//! font shipped with the application, with [`SkiaFonts::load_font_file`]
33//! or [`SkiaFonts::load_font`], and name them in the stylesheet's
34//! `font-family`.
35
36use std::cell::RefCell;
37use std::collections::HashMap;
38use std::fmt;
39use std::path::Path;
40
41use eternal_ui::styler::{Color, Corners, FontStyle, Sides};
42use eternal_ui::{FontSpec, Fonts, Point, Rect, Renderer, TextMetrics};
43use skia_safe::font::Edging;
44use skia_safe::font_style::{Slant, Weight, Width};
45use skia_safe::{
46    Canvas, ClipOp, Color4f, Data, Font, FontHinting, FontMgr, Paint, PaintStyle, RRect, Typeface,
47    Vector,
48};
49
50/// Finds fonts and measures text with Skia.
51///
52/// Typefaces are looked up by the CSS family names in a style, first match
53/// wins: fonts loaded with [`load_font`](Self::load_font) and its
54/// relatives are checked first, then the system font manager. The generic
55/// families `monospace`, `sans-serif`, `serif`, `system-ui` and
56/// `ui-monospace` map to common system fonts; anything unknown falls back
57/// to the default typeface.
58///
59/// ```no_run
60/// use eternal_ui_skia::SkiaFonts;
61///
62/// let mut fonts = SkiaFonts::new();
63/// // Registered under the family name inside the file...
64/// let family = fonts.load_font_file("assets/PixelOperator.ttf")?;
65/// // ...or under a name of your choosing, so the stylesheet can say
66/// // `font-family: pixel` without caring which file provides it.
67/// fonts.load_font_file_as("pixel", "assets/PixelOperator.ttf")?;
68/// # Ok::<(), eternal_ui_skia::FontError>(())
69/// ```
70pub struct SkiaFonts {
71    font_mgr: FontMgr,
72    custom: Vec<CustomFont>,
73    typefaces: RefCell<HashMap<TypefaceKey, Typeface>>,
74    smooth: bool,
75}
76
77/// A font loaded from data rather than found on the system.
78struct CustomFont {
79    /// The name the stylesheet uses, lower-cased for matching.
80    family: String,
81    weight: i32,
82    italic: bool,
83    typeface: Typeface,
84}
85
86#[derive(Clone, PartialEq, Eq, Hash)]
87struct TypefaceKey {
88    families: Vec<String>,
89    weight: i32,
90    italic: bool,
91}
92
93impl Default for SkiaFonts {
94    fn default() -> Self {
95        Self::new()
96    }
97}
98
99impl SkiaFonts {
100    pub fn new() -> Self {
101        Self {
102            font_mgr: FontMgr::new(),
103            custom: Vec::new(),
104            typefaces: RefCell::new(HashMap::new()),
105            smooth: false,
106        }
107    }
108
109    /// Loads a font from the bytes of a TrueType, OpenType or WOFF file and
110    /// registers it under the family name the file declares, which is
111    /// returned. Several weights and styles of one family can be loaded
112    /// one file at a time; the closest match to a style's weight and slant
113    /// is used.
114    pub fn load_font(&mut self, bytes: &[u8]) -> Result<String, FontError> {
115        let typeface = self.typeface_from_bytes(bytes)?;
116        let family = typeface.family_name();
117        self.register(family.clone(), typeface);
118        Ok(family)
119    }
120
121    /// Like [`load_font`](Self::load_font), but registers the font under
122    /// `family` instead of the name in the file, so a stylesheet can refer
123    /// to it as `font-family: pixel` whatever the file says.
124    pub fn load_font_as(&mut self, family: &str, bytes: &[u8]) -> Result<(), FontError> {
125        let typeface = self.typeface_from_bytes(bytes)?;
126        self.register(family.to_owned(), typeface);
127        Ok(())
128    }
129
130    /// [`load_font`](Self::load_font) for a file on disk.
131    pub fn load_font_file(&mut self, path: impl AsRef<Path>) -> Result<String, FontError> {
132        let bytes = read_font_file(path.as_ref())?;
133        self.load_font(&bytes)
134            .map_err(|error| error.at(path.as_ref()))
135    }
136
137    /// [`load_font_as`](Self::load_font_as) for a file on disk.
138    pub fn load_font_file_as(
139        &mut self,
140        family: &str,
141        path: impl AsRef<Path>,
142    ) -> Result<(), FontError> {
143        let bytes = read_font_file(path.as_ref())?;
144        self.load_font_as(family, &bytes)
145            .map_err(|error| error.at(path.as_ref()))
146    }
147
148    /// The family names of the fonts loaded so far, in load order, as they
149    /// were registered.
150    pub fn loaded_families(&self) -> impl Iterator<Item = &str> {
151        self.custom.iter().map(|font| font.family.as_str())
152    }
153
154    fn typeface_from_bytes(&self, bytes: &[u8]) -> Result<Typeface, FontError> {
155        self.font_mgr
156            .new_from_data(Data::new_copy(bytes), None)
157            .ok_or(FontError::Unreadable { path: None })
158    }
159
160    fn register(&mut self, family: String, typeface: Typeface) {
161        let style = typeface.font_style();
162        self.custom.push(CustomFont {
163            family: family.to_ascii_lowercase(),
164            weight: *style.weight(),
165            italic: style.slant() != Slant::Upright,
166            typeface,
167        });
168        // A family that fell back to a system font before may resolve to
169        // the new font now.
170        self.typefaces.borrow_mut().clear();
171    }
172
173    /// The loaded font closest in weight and slant to what was asked for,
174    /// among those registered under `family`.
175    fn custom_typeface(&self, family: &str, weight: i32, italic: bool) -> Option<Typeface> {
176        self.custom
177            .iter()
178            .filter(|font| font.family.eq_ignore_ascii_case(family))
179            .min_by_key(|font| {
180                (font.weight - weight).abs() + if font.italic == italic { 0 } else { 1000 }
181            })
182            .map(|font| font.typeface.clone())
183    }
184
185    /// Whether to anti-alias text and shapes. Off by default for a pixel
186    /// look.
187    pub fn set_smooth(&mut self, smooth: bool) {
188        self.smooth = smooth;
189    }
190
191    pub fn smooth(&self) -> bool {
192        self.smooth
193    }
194
195    /// The Skia font for a style's font spec, ready to draw with.
196    pub fn font(&self, spec: &FontSpec) -> Font {
197        let mut font = Font::new(self.typeface(spec), spec.size);
198        if self.smooth {
199            font.set_edging(Edging::AntiAlias);
200            font.set_subpixel(true);
201        } else {
202            font.set_edging(Edging::Alias);
203            font.set_subpixel(false);
204            font.set_hinting(FontHinting::Full);
205        }
206        font
207    }
208
209    fn typeface(&self, spec: &FontSpec) -> Typeface {
210        let key = TypefaceKey {
211            families: spec.family.names().to_vec(),
212            weight: spec.weight.value().round() as i32,
213            italic: spec.style != FontStyle::Normal,
214        };
215        if let Some(typeface) = self.typefaces.borrow().get(&key) {
216            return typeface.clone();
217        }
218        let slant = match spec.style {
219            FontStyle::Normal => Slant::Upright,
220            FontStyle::Italic => Slant::Italic,
221            FontStyle::Oblique => Slant::Oblique,
222        };
223        let style = skia_safe::FontStyle::new(Weight::from(key.weight), Width::NORMAL, slant);
224        let typeface = key
225            .families
226            .iter()
227            .find_map(|family| {
228                self.custom_typeface(family, key.weight, key.italic)
229                    .or_else(|| {
230                        candidates(family)
231                            .into_iter()
232                            .find_map(|name| self.font_mgr.match_family_style(name, style))
233                    })
234            })
235            .or_else(|| self.font_mgr.legacy_make_typeface(None, style))
236            .expect("Skia has a default typeface");
237        self.typefaces.borrow_mut().insert(key, typeface.clone());
238        typeface
239    }
240}
241
242fn read_font_file(path: &Path) -> Result<Vec<u8>, FontError> {
243    std::fs::read(path).map_err(|source| FontError::Io {
244        path: path.display().to_string(),
245        source,
246    })
247}
248
249/// A font could not be loaded.
250#[derive(Debug)]
251pub enum FontError {
252    /// The file could not be read.
253    Io {
254        path: String,
255        source: std::io::Error,
256    },
257    /// Skia did not recognise the data as a font.
258    Unreadable {
259        /// The file it came from, when it came from one.
260        path: Option<String>,
261    },
262}
263
264impl FontError {
265    fn at(self, path: &Path) -> Self {
266        match self {
267            Self::Unreadable { path: None } => Self::Unreadable {
268                path: Some(path.display().to_string()),
269            },
270            other => other,
271        }
272    }
273}
274
275impl fmt::Display for FontError {
276    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277        match self {
278            Self::Io { path, source } => write!(f, "{path}: {source}"),
279            Self::Unreadable { path: Some(path) } => write!(f, "{path}: not a font Skia can read"),
280            Self::Unreadable { path: None } => f.write_str("not a font Skia can read"),
281        }
282    }
283}
284
285impl std::error::Error for FontError {
286    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
287        match self {
288            Self::Io { source, .. } => Some(source),
289            Self::Unreadable { .. } => None,
290        }
291    }
292}
293
294/// System font names to try for a CSS family name, generic ones expanded.
295fn candidates(family: &str) -> Vec<&str> {
296    match family {
297        "monospace" | "ui-monospace" => vec![
298            "Menlo",
299            "SF Mono",
300            "Consolas",
301            "Cascadia Mono",
302            "DejaVu Sans Mono",
303            "Liberation Mono",
304            "Courier New",
305            "monospace",
306        ],
307        "sans-serif" | "system-ui" | "ui-sans-serif" => vec![
308            "Helvetica Neue",
309            "Segoe UI",
310            "DejaVu Sans",
311            "Liberation Sans",
312            "Arial",
313            "sans-serif",
314        ],
315        "serif" | "ui-serif" => vec![
316            "Georgia",
317            "Times New Roman",
318            "DejaVu Serif",
319            "Liberation Serif",
320            "serif",
321        ],
322        other => vec![other],
323    }
324}
325
326impl Fonts for SkiaFonts {
327    fn measure(&self, text: &str, spec: &FontSpec) -> TextMetrics {
328        let font = self.font(spec);
329        let (_, metrics) = font.metrics();
330        let ascent = -metrics.ascent;
331        let descent = metrics.descent;
332        let natural = (ascent + descent + metrics.leading).ceil();
333        TextMetrics {
334            width: font.measure_str(text, None).0,
335            ascent,
336            descent,
337            line_height: spec.line_height.unwrap_or(natural),
338        }
339    }
340}
341
342/// Draws one frame of a [`Ui`](eternal_ui::Ui) onto a Skia canvas.
343pub struct SkiaRenderer<'a> {
344    canvas: &'a Canvas,
345    fonts: &'a SkiaFonts,
346}
347
348impl<'a> SkiaRenderer<'a> {
349    pub fn new(canvas: &'a Canvas, fonts: &'a SkiaFonts) -> Self {
350        Self { canvas, fonts }
351    }
352
353    fn paint(&self, color: Color) -> Paint {
354        let mut paint = Paint::new(Color4f::new(color.r, color.g, color.b, color.a), None);
355        paint.set_anti_alias(self.fonts.smooth);
356        paint
357    }
358}
359
360fn skia_rect(rect: Rect) -> skia_safe::Rect {
361    skia_safe::Rect::from_xywh(rect.x, rect.y, rect.width, rect.height)
362}
363
364fn rounded(rect: Rect, radius: Corners<f32>) -> Option<RRect> {
365    let radii = [
366        radius.top_left,
367        radius.top_right,
368        radius.bottom_right,
369        radius.bottom_left,
370    ];
371    if radii.iter().all(|&r| r <= 0.0) {
372        return None;
373    }
374    Some(RRect::new_rect_radii(
375        skia_rect(rect),
376        &radii.map(|r| Vector::new(r, r)),
377    ))
378}
379
380impl Renderer for SkiaRenderer<'_> {
381    fn fill_rect(&mut self, rect: Rect, radius: Corners<f32>, color: Color) {
382        let paint = self.paint(color);
383        match rounded(rect, radius) {
384            Some(rrect) => self.canvas.draw_rrect(rrect, &paint),
385            None => self.canvas.draw_rect(skia_rect(rect), &paint),
386        };
387    }
388
389    fn border(
390        &mut self,
391        rect: Rect,
392        widths: Sides<f32>,
393        colors: Sides<Color>,
394        radius: Corners<f32>,
395    ) {
396        if let Some(outer) = rounded(rect, radius) {
397            // Rounded borders are stroked with one width and colour; the
398            // theme is expected to keep the sides alike when it rounds.
399            let width = widths
400                .top
401                .max(widths.right)
402                .max(widths.bottom)
403                .max(widths.left);
404            let mut paint = self.paint(colors.top);
405            paint.set_style(PaintStyle::Stroke);
406            paint.set_stroke_width(width);
407            let inset = width / 2.0;
408            let mut inner = outer;
409            inner.inset((inset, inset));
410            self.canvas.draw_rrect(inner, &paint);
411            return;
412        }
413        let strips = [
414            (
415                Rect::new(rect.x, rect.y, rect.width, widths.top),
416                colors.top,
417            ),
418            (
419                Rect::new(
420                    rect.x,
421                    rect.bottom() - widths.bottom,
422                    rect.width,
423                    widths.bottom,
424                ),
425                colors.bottom,
426            ),
427            (
428                Rect::new(
429                    rect.x,
430                    rect.y + widths.top,
431                    widths.left,
432                    rect.height - widths.top - widths.bottom,
433                ),
434                colors.left,
435            ),
436            (
437                Rect::new(
438                    rect.right() - widths.right,
439                    rect.y + widths.top,
440                    widths.right,
441                    rect.height - widths.top - widths.bottom,
442                ),
443                colors.right,
444            ),
445        ];
446        for (strip, color) in strips {
447            if strip.width > 0.0 && strip.height > 0.0 && color.a > 0.0 {
448                self.canvas.draw_rect(skia_rect(strip), &self.paint(color));
449            }
450        }
451    }
452
453    fn text(&mut self, text: &str, spec: &FontSpec, top_left: Point, color: Color) {
454        let font = self.fonts.font(spec);
455        let metrics = self.fonts.measure("", spec);
456        // Centre the glyph box inside the line box, then drop to the baseline.
457        let baseline = top_left.y
458            + ((metrics.line_height - (metrics.ascent + metrics.descent)) / 2.0).max(0.0)
459            + metrics.ascent;
460        let mut paint = self.paint(color);
461        paint.set_anti_alias(true);
462        self.canvas.draw_str(
463            text,
464            skia_safe::Point::new(top_left.x, baseline.round()),
465            &font,
466            &paint,
467        );
468    }
469
470    fn push_clip(&mut self, rect: Rect) {
471        self.canvas.save();
472        self.canvas
473            .clip_rect(skia_rect(rect), ClipOp::Intersect, false);
474    }
475
476    fn pop_clip(&mut self) {
477        self.canvas.restore();
478    }
479
480    fn push_opacity(&mut self, opacity: f32) {
481        self.canvas.save_layer_alpha_f(None, opacity);
482    }
483
484    fn pop_opacity(&mut self) {
485        self.canvas.restore();
486    }
487}