Skip to main content

aylis_core/
textcore.rs

1//! O texto igual em todos os renderizadores (item 10): o modo de texto de cada plataforma.
2//!
3//! - `native`: cada renderizador mede e desenha (Skia, DirectWrite, o navegador), como sempre;
4//! - `layout`: o núcleo mede (com as fontes do projeto e o `harfrust`) e decide as quebras e
5//!   os tamanhos; o renderizador só desenha cada linha no lugar que o núcleo deu;
6//! - `core`: o núcleo também desenha, letra por letra (o contorno de cada letra vira um
7//!   caminho preenchido): o mesmo desenho em toda parte.
8//!
9//! O núcleo só conhece as fontes registradas ([`crate::fonts`]: as do projeto). Um texto com
10//! um caractere que nenhuma delas tem (um emoji, sem uma fonte de emoji no projeto) fica com o
11//! renderizador, como no `native`.
12
13use crate::canvas::{Brush, Canvas, Shadow, Stroke, TextStyle};
14use crate::geometry::{PointF, RectF, SizeF};
15use crate::path::Path;
16use engine::{engine_face, line_metrics_of as line_metrics, line_width, outline};
17use crate::{TextAlign, Ui};
18
19/// Quem mede e desenha o texto (veja o módulo).
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21pub enum TextMode {
22    #[default]
23    Native,
24    Layout,
25    Core,
26}
27
28impl crate::prop::PropEnum for TextMode {
29    const NAMES: &'static [&'static str] = &["native", "layout", "core"];
30
31    fn from_index(index: usize) -> Option<Self> {
32        [TextMode::Native, TextMode::Layout, TextMode::Core].get(index).copied()
33    }
34
35    fn index(self) -> usize {
36        self as usize
37    }
38}
39
40/// Mede como o núcleo mede: `None` se o texto não fica com ele (sem fonte, letra que falta).
41pub fn measure(text: &str, style: &TextStyle, max_width: Option<f32>) -> Option<SizeF> {
42    let face = engine_face(text, &style.font)?;
43    let size = style.font.size;
44    let (line_height, _) = line_metrics(face, size);
45    let mut measure = |s: &str| line_width(face, s, size);
46    let lines: Vec<String> = match max_width {
47        Some(w) => crate::text::layout_lines(text, w, usize::MAX, true, crate::Trimming::None, &mut measure),
48        _ => text.split('\n').map(str::to_string).collect(),
49    };
50    let width = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
51    Some(SizeF::new(width, line_height * lines.len().max(1) as f32))
52}
53
54/// O canvas que põe o texto no modo do app: repassa tudo a `inner`, menos medir e desenhar
55/// texto (veja o módulo).
56pub(crate) struct TextCanvas<'a> {
57    pub(crate) inner: &'a mut dyn Canvas,
58    pub(crate) mode: TextMode,
59}
60
61impl TextCanvas<'_> {
62    /// Uma linha no lugar que o núcleo decidiu: o renderizador desenha (`layout`) ou o núcleo
63    /// desenha as letras (`core`).
64    fn draw_line(&mut self, face: usize, line: &str, x: f32, top: f32, line_height: f32, style: &TextStyle) {
65        let size = style.font.size;
66        let (width, baseline) = (line_width(face, line, size), line_metrics(face, size).1);
67        match self.mode {
68            TextMode::Core => {
69                let path = outline(face, line, size, x, top + baseline);
70                self.inner.fill_path(&path, &Brush::Solid(style.color));
71                crate::canvas::decorate_line(self.inner, &style.font, style.color, x, width, top, line_height);
72            }
73            _ => {
74                let mut one = style.clone();
75                one.h_align = TextAlign::Leading;
76                one.v_align = TextAlign::Center;
77                one.wrap = false;
78                one.trimming = crate::Trimming::None;
79                // Uma folga à direita: a medida do renderizador pode ser um pouco maior, e a
80                // linha não pode ganhar "…" nem quebrar.
81                self.inner.draw_text(line, RectF::new(x, top, width + size, line_height), &one);
82            }
83        }
84    }
85}
86
87impl Canvas for TextCanvas<'_> {
88    fn save(&mut self) {
89        self.inner.save();
90    }
91    fn restore(&mut self) {
92        self.inner.restore();
93    }
94    fn translate(&mut self, dx: f32, dy: f32) {
95        self.inner.translate(dx, dy);
96    }
97    fn scale(&mut self, sx: f32, sy: f32) {
98        self.inner.scale(sx, sy);
99    }
100    fn rotate(&mut self, degrees: f32) {
101        self.inner.rotate(degrees);
102    }
103    fn clip_rect(&mut self, rect: RectF) {
104        self.inner.clip_rect(rect);
105    }
106    fn save_layer(&mut self, opacity: f32) {
107        self.inner.save_layer(opacity);
108    }
109    fn save_layer_blend(&mut self, opacity: f32, mode: crate::BlendMode, bounds: RectF) {
110        self.inner.save_layer_blend(opacity, mode, bounds);
111    }
112    fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush) {
113        self.inner.fill_rect(rect, radius, brush);
114    }
115    fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke) {
116        self.inner.stroke_rect(rect, radius, stroke);
117    }
118    fn fill_ellipse(&mut self, rect: RectF, brush: &Brush) {
119        self.inner.fill_ellipse(rect, brush);
120    }
121    fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke) {
122        self.inner.stroke_ellipse(rect, stroke);
123    }
124    fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke) {
125        self.inner.draw_line(from, to, stroke);
126    }
127    fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle) {
128        if text.is_empty() || rect.width <= 0.0 {
129            return;
130        }
131        let Some(face) = (self.mode != TextMode::Native).then(|| engine_face(text, &style.font)).flatten() else {
132            self.inner.draw_text(text, rect, style);
133            return;
134        };
135        // A mesma regra de linhas dos renderizadores (quebra, reticências, alinhamento), com
136        // as medidas do núcleo.
137        let size = style.font.size;
138        let (line_height, _) = line_metrics(face, size);
139        let mut measure = |s: &str| line_width(face, s, size);
140        let lines = if !style.wrap && !text.contains('\n') {
141            let width = measure(text);
142            let line = if width > rect.width && style.trimming != crate::Trimming::None { crate::text::trim_line(text, rect.width, style.trimming, &mut measure) } else { text.to_string() };
143            vec![(line, true)]
144        } else {
145            let max_lines = ((rect.height + 1.0) / line_height).floor().max(1.0) as usize;
146            crate::text::layout_lines_marked(text, rect.width, max_lines, style.wrap, style.trimming, &mut measure)
147        };
148        let total = line_height * lines.len() as f32;
149        let top = match style.v_align {
150            TextAlign::Leading | TextAlign::Justify => rect.y,
151            TextAlign::Center => rect.y + (rect.height - total) / 2.0,
152            TextAlign::Trailing => rect.bottom() - total,
153        };
154        for (i, (line, end)) in lines.iter().enumerate() {
155            if line.is_empty() {
156                continue;
157            }
158            let y = top + line_height * i as f32;
159            let words = (style.h_align == TextAlign::Justify && !end).then(|| crate::text::justify_line(line, rect.width, &mut |s: &str| line_width(face, s, size))).flatten();
160            if let Some(words) = words {
161                for (x, word) in words {
162                    self.draw_line(face, &word, rect.x + x, y, line_height, style);
163                }
164                continue;
165            }
166            let width = line_width(face, line, size);
167            let x = match style.h_align {
168                TextAlign::Leading | TextAlign::Justify => rect.x,
169                TextAlign::Center => rect.x + (rect.width - width) / 2.0,
170                TextAlign::Trailing => rect.right() - width,
171            };
172            self.draw_line(face, line, x, y, line_height, style);
173        }
174    }
175    fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF {
176        if self.mode != TextMode::Native {
177            if let Some(size) = measure(text, style, None) {
178                return size;
179            }
180        }
181        self.inner.measure_text(text, style)
182    }
183    fn draw_image(&mut self, image: &crate::Image, src: RectF, dest: RectF, opacity: f32) {
184        self.inner.draw_image(image, src, dest, opacity);
185    }
186    fn image_size(&mut self, image: &crate::Image) -> Option<SizeF> {
187        self.inner.image_size(image)
188    }
189    fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
190        self.inner.clip_round_rect(rect, radius);
191    }
192    fn fill_path(&mut self, path: &Path, brush: &Brush) {
193        self.inner.fill_path(path, brush);
194    }
195    fn clip_path(&mut self, path: &Path, inverse: bool) {
196        self.inner.clip_path(path, inverse);
197    }
198    fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
199        self.inner.backdrop_blur(rect, radius, blur)
200    }
201    fn begin_masked(&mut self, inverse: bool) -> bool {
202        self.inner.begin_masked(inverse)
203    }
204    fn begin_mask(&mut self) {
205        self.inner.begin_mask();
206    }
207    fn end_mask(&mut self) {
208        self.inner.end_mask();
209    }
210    fn begin_cached(&mut self, key: u64, rect: RectF) -> bool {
211        self.inner.begin_cached(key, rect)
212    }
213    fn end_cached(&mut self) {
214        self.inner.end_cached();
215    }
216    fn forget_cached(&mut self, key: u64) {
217        self.inner.forget_cached(key);
218    }
219    fn stroke_path(&mut self, path: &Path, stroke: &Stroke) {
220        self.inner.stroke_path(path, stroke);
221    }
222    fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &Shadow) {
223        self.inner.draw_shadow(rect, radius, shadow);
224    }
225    fn device_scale(&self) -> f32 {
226        self.inner.device_scale()
227    }
228    fn gpu_device(&self) -> Option<crate::GpuDevice> {
229        self.inner.gpu_device()
230    }
231    fn draw_gpu_surface(&mut self, dest: RectF, surface: &crate::GpuSurface) -> bool {
232        self.inner.draw_gpu_surface(dest, surface)
233    }
234    fn gpu_state_changed(&mut self) {
235        self.inner.gpu_state_changed();
236    }
237}
238
239impl Ui {
240    /// O modo de texto do app (veja o módulo): o `text` do `.aylisproj` para a plataforma.
241    pub fn set_text_mode(&mut self, mode: TextMode) {
242        if self.text_mode != mode {
243            self.text_mode = mode;
244            self.invalidate();
245        }
246    }
247
248    pub fn text_mode(&self) -> TextMode {
249        self.text_mode
250    }
251}
252
253/// O peso no número das fontes (400 o normal, 700 o negrito).
254#[cfg(feature = "text-shaping")]
255fn weight_number(weight: crate::canvas::FontWeight) -> u16 {
256    use crate::canvas::FontWeight::*;
257    match weight {
258        Thin => 100,
259        Light => 300,
260        Normal => 400,
261        Medium => 500,
262        SemiBold => 600,
263        Bold => 700,
264        Black => 900,
265    }
266}
267
268/// As fontes do projeto abertas pelo núcleo (o `harfrust`: medir, formar e o contorno das
269/// letras). Só com a feature `text-shaping`: sem ela, nenhuma fonte fica com o núcleo e o texto
270/// é todo do renderizador, como sem fonte registrada (o `harfrust` e o `read-fonts` são ~520 KB
271/// de cada wasm; a IDE liga a feature no projeto que tem fontes em `assets/fonts`).
272#[cfg(feature = "text-shaping")]
273mod engine {
274    use std::cell::RefCell;
275    use std::collections::HashMap;
276
277    use super::weight_number;
278    use crate::canvas::FontSpec;
279    use crate::geometry::PointF;
280    use crate::path::{Path, PathCmd};
281    use harfrust::font::attribute::Style;
282    use harfrust::font::glyph::outline::{DrawMemory, DrawOptions, PathSink};
283    use harfrust::font::{Blob, Font};
284    use harfrust::GlyphId;
285
286    /// Uma fonte registrada, aberta para medir e desenhar (divide os bytes com o registro).
287    struct Face {
288        family: String,
289        weight: u16,
290        italic: bool,
291        /// Uma cópia de uma fonte variável em outro peso (não entra na escolha da família).
292        variant: bool,
293        font: Font,
294        units: f32,
295        ascender: f32,
296        descender: f32,
297        gap: f32,
298    }
299
300    #[derive(Default)]
301    struct Faces {
302        generation: u64,
303        list: Vec<Face>,
304        /// O contorno de cada letra, nas unidades da fonte (o desenho só escala e move).
305        outlines: HashMap<(usize, u32), Vec<PathCmd>>,
306        /// As cópias das fontes variáveis em outro peso: (a original, o peso) → a cópia.
307        variants: HashMap<(usize, u16), usize>,
308        /// O plano de formação de cada fonte, direção, escrita e idioma: montá-lo é a parte cara de
309        /// formar um texto (o `harfrust::shape` sem plano monta um a cada chamada).
310        plans: HashMap<PlanKey, harfrust::ShapePlan>,
311        /// As letras já formadas de cada texto, em unidades da fonte (servem em qualquer tamanho).
312        /// Formar a cada medida e a cada desenho custava 1,7 ms por texto em debug: a grade do menu
313        /// do ERP levava 400 ms por quadro (relatado pelo autor em 07/11). Esvazia ao passar de
314        /// `SHAPED_KEEP` textos.
315        shaped: HashMap<(usize, String), std::rc::Rc<Shaped>>,
316    }
317
318    type PlanKey = (usize, harfrust::Direction, Option<harfrust::Script>, Option<harfrust::Language>);
319
320    /// As letras de uma linha: (letra, avanço, deslocamento x, deslocamento y) e a soma dos
321    /// avanços, em unidades da fonte.
322    struct Shaped {
323        glyphs: Vec<(u32, f32, f32, f32)>,
324        advance: f32,
325    }
326
327    const SHAPED_KEEP: usize = 4096;
328
329    thread_local! {
330        static FACES: RefCell<Faces> = RefCell::new(Faces::default());
331    }
332
333    /// As fontes abertas, refeitas quando uma fonte nova é registrada.
334    fn with_faces<R>(f: impl FnOnce(&mut Faces) -> R) -> R {
335        FACES.with(|faces| {
336            let mut faces = faces.borrow_mut();
337            let generation = crate::fonts::generation();
338            if faces.generation != generation || (faces.list.is_empty() && generation > 0) {
339                faces.generation = generation;
340                faces.outlines.clear();
341                faces.variants.clear();
342                faces.plans.clear();
343                faces.shaped.clear();
344                faces.list = crate::fonts::registered()
345                    .into_iter()
346                    .flat_map(|file| {
347                        // Os bytes são os do registro (`Arc`): nada é copiado. Uma coleção (`.ttc`)
348                        // abre uma fonte por índice, até o primeiro que não existe.
349                        let data: std::sync::Arc<dyn AsRef<[u8]> + Send + Sync> = file.data.clone();
350                        let blob = Blob::from(data);
351                        let family = file.family.clone();
352                        (0u32..).map_while(move |index| Font::new(blob.clone(), index)).map(move |font| {
353                            let units = font.units_per_em() as f32;
354                            let attributes = font.default_attributes();
355                            // A linha como o `ttf-parser` dava: a tipográfica se o OS/2 pede, senão
356                            // a do `hhea`, a tipográfica ou a do Windows.
357                            let line = font.metrics().h_line().unwrap_or_default();
358                            Face {
359                                family: family.clone(),
360                                weight: attributes.weight.value().round().clamp(1.0, 1000.0) as u16,
361                                italic: attributes.style == Style::Italic,
362                                variant: false,
363                                ascender: line.ascender.to_f32(),
364                                descender: line.descender.to_f32(),
365                                gap: line.line_gap.to_f32(),
366                                units: if units > 0.0 { units } else { 1000.0 },
367                                font,
368                            }
369                        })
370                    })
371                    .collect();
372            }
373            f(&mut faces)
374        })
375    }
376
377    /// A família padrão do núcleo (a de um `FontSpec` sem família): a primeira registrada, que é a
378    /// do projeto.
379    fn default_family(faces: &Faces) -> Option<String> {
380        faces.list.first().map(|f| f.family.clone())
381    }
382
383    /// A fonte para `spec`: a família pedida (ou a padrão), com o peso e o itálico mais perto.
384    fn pick(faces: &mut Faces, spec: &FontSpec) -> Option<usize> {
385        let family = if spec.family.is_empty() { default_family(faces)? } else { spec.family.clone() };
386        let want = weight_number(spec.weight);
387        let best = faces
388            .list
389            .iter()
390            .enumerate()
391            .filter(|(_, f)| f.family.eq_ignore_ascii_case(&family) && !f.variant)
392            .min_by_key(|(_, f)| (f.italic != spec.italic, (f.weight as i32 - want as i32).abs()))
393            .map(|(i, _)| i)?;
394        // Uma fonte variável (a Inter do projeto) no peso pedido: uma cópia com o eixo `wght` posto.
395        let wght = harfrust::Tag::new(b"wght");
396        let variable = faces.list[best].font.axes().iter().any(|a| a.tag() == wght);
397        if !variable || faces.list[best].weight == want {
398            return Some(best);
399        }
400        if let Some(&i) = faces.variants.get(&(best, want)) {
401            return Some(i);
402        }
403        let base = &faces.list[best];
404        let font = base.font.instance_builder().variations([(wght, want as f32)]).build();
405        let face = Face {
406            family: base.family.clone(),
407            weight: want,
408            italic: base.italic,
409            variant: true,
410            font,
411            units: base.units,
412            ascender: base.ascender,
413            descender: base.descender,
414            gap: base.gap,
415        };
416        faces.list.push(face);
417        let i = faces.list.len() - 1;
418        faces.variants.insert((best, want), i);
419        Some(i)
420    }
421
422    /// A fonte (`spec`) tem todas as letras do texto? Sem isso, o texto fica com o renderizador.
423    fn covers(face: &Face, text: &str) -> bool {
424        let charmap = face.font.charmap();
425        text.chars().all(|c| c.is_control() || c == '\u{200d}' || c == '\u{fe0f}' || charmap.map_unicode(c).is_some())
426    }
427
428    /// As letras montadas de uma linha (da memória, ou formadas e guardadas), em unidades da fonte.
429    fn shaped(faces: &mut Faces, face: usize, text: &str) -> std::rc::Rc<Shaped> {
430        if let Some(found) = faces.shaped.get(&(face, text.to_string())) {
431            return found.clone();
432        }
433        let mut buffer = harfrust::Buffer::new();
434        buffer.push_str(text);
435        buffer.guess_segment_properties();
436        let key: PlanKey = (face, buffer.direction(), buffer.script(), buffer.language().cloned());
437        let font = &faces.list[face].font;
438        let plan = faces.plans.entry(key).or_insert_with(|| {
439            harfrust::ShapePlan::new(font, buffer.direction(), buffer.script(), buffer.language(), &[])
440        });
441        let shaper = harfrust::ShaperFont::new(font);
442        // Só falha com um plano de outra direção ou escrita, e a chave do plano é a do texto.
443        let shaped = harfrust::shape(&shaper, &mut buffer, harfrust::ShapeOptions::new().plan(Some(plan)));
444        let glyphs: Vec<(u32, f32, f32, f32)> = match shaped {
445            Ok(()) => buffer
446                .glyph_infos()
447                .iter()
448                .zip(buffer.glyph_positions())
449                .map(|(info, pos)| (info.glyph_id, pos.x_advance as f32, pos.x_offset as f32, pos.y_offset as f32))
450                .collect(),
451            Err(_) => Vec::new(),
452        };
453        let advance = glyphs.iter().map(|g| g.1).sum::<f32>();
454        let result = std::rc::Rc::new(Shaped { glyphs, advance });
455        if faces.shaped.len() >= SHAPED_KEEP {
456            faces.shaped.clear();
457        }
458        faces.shaped.insert((face, text.to_string()), result.clone());
459        result
460    }
461
462    /// A largura de uma linha formada, no tamanho.
463    fn width_of(faces: &mut Faces, face: usize, text: &str, size: f32) -> f32 {
464        let units = faces.list[face].units;
465        shaped(faces, face, text).advance * size / units
466    }
467
468    /// A altura de uma linha e a distância do topo à linha de base, no tamanho.
469    fn line_metrics(face: &Face, size: f32) -> (f32, f32) {
470        let scale = size / face.units;
471        let ascent = face.ascender * scale;
472        let height = (face.ascender - face.descender + face.gap) * scale;
473        (height.max(size), ascent + face.gap * scale / 2.0)
474    }
475
476    /// O texto todo pode ficar com o núcleo (há fonte registrada e ela tem todas as letras)?
477    pub(super) fn engine_face(text: &str, spec: &FontSpec) -> Option<usize> {
478        with_faces(|faces| pick(faces, spec).filter(|&i| covers(&faces.list[i], text)))
479    }
480
481    /// A largura de uma linha (sem quebra) pelo núcleo.
482    pub(super) fn line_width(face: usize, text: &str, size: f32) -> f32 {
483        with_faces(|faces| width_of(faces, face, text, size))
484    }
485
486    /// O contorno de uma linha de letras, já no tamanho e na posição (`x`, linha de base).
487    fn outline_line(faces: &mut Faces, face: usize, line: &str, size: f32, x: f32, baseline: f32) -> Path {
488        let glyphs = shaped(faces, face, line);
489        let scale = size / faces.list[face].units;
490        let mut cmds = Vec::new();
491        let mut pen = x;
492        for &(glyph, advance, dx, dy) in glyphs.glyphs.iter() {
493            let outline = faces.outlines.entry((face, glyph)).or_insert_with(|| {
494                let mut builder = Outline(Vec::new());
495                if let Some(outline) = faces.list[face].font.outline_glyphs().get(GlyphId::new(glyph)) {
496                    // Sem tamanho: nas unidades da fonte, como o `ttf-parser` dava. Uma letra que não
497                    // abre fica sem desenho, como antes.
498                    if outline.draw(&DrawOptions::default(), DrawMemory::Scratch, &mut builder).is_err() {
499                        builder.0.clear();
500                    }
501                }
502                builder.0
503            });
504            let ox = pen + dx * scale;
505            let oy = baseline - dy * scale;
506            let map = |p: PointF| PointF::new(ox + p.x * scale, oy - p.y * scale);
507            for cmd in outline.iter() {
508                cmds.push(match *cmd {
509                    PathCmd::MoveTo(p) => PathCmd::MoveTo(map(p)),
510                    PathCmd::LineTo(p) => PathCmd::LineTo(map(p)),
511                    PathCmd::QuadTo(a, b) => PathCmd::QuadTo(map(a), map(b)),
512                    PathCmd::CubicTo(a, b, c) => PathCmd::CubicTo(map(a), map(b), map(c)),
513                    PathCmd::Close => PathCmd::Close,
514                });
515            }
516            pen += advance * scale;
517        }
518        Path { cmds, even_odd: false }
519    }
520
521    /// Junta o contorno de uma letra (nas unidades da fonte).
522    struct Outline(Vec<PathCmd>);
523
524    impl PathSink for Outline {
525        fn move_to(&mut self, x: f32, y: f32) {
526            self.0.push(PathCmd::MoveTo(PointF::new(x, y)));
527        }
528        fn line_to(&mut self, x: f32, y: f32) {
529            self.0.push(PathCmd::LineTo(PointF::new(x, y)));
530        }
531        fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
532            self.0.push(PathCmd::QuadTo(PointF::new(x1, y1), PointF::new(x, y)));
533        }
534        fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
535            self.0.push(PathCmd::CubicTo(PointF::new(x1, y1), PointF::new(x2, y2), PointF::new(x, y)));
536        }
537        fn close(&mut self) {
538            self.0.push(PathCmd::Close);
539        }
540    }
541
542    /// A altura de uma linha e a distância do topo à linha de base, no tamanho.
543    pub(super) fn line_metrics_of(face: usize, size: f32) -> (f32, f32) {
544        with_faces(|faces| line_metrics(&faces.list[face], size))
545    }
546
547    /// O contorno de uma linha de letras, já no tamanho e na posição.
548    pub(super) fn outline(face: usize, line: &str, size: f32, x: f32, baseline: f32) -> Path {
549        with_faces(|faces| outline_line(faces, face, line, size, x, baseline))
550    }
551}
552
553/// Sem a feature `text-shaping`: o núcleo não abre fonte nenhuma (veja o de cima).
554#[cfg(not(feature = "text-shaping"))]
555mod engine {
556    use crate::canvas::FontSpec;
557    use crate::path::Path;
558
559    pub(super) fn engine_face(_text: &str, _spec: &FontSpec) -> Option<usize> {
560        None
561    }
562    pub(super) fn line_width(_face: usize, _text: &str, _size: f32) -> f32 {
563        0.0
564    }
565    pub(super) fn line_metrics_of(_face: usize, size: f32) -> (f32, f32) {
566        (size, size)
567    }
568    pub(super) fn outline(_face: usize, _line: &str, _size: f32, _x: f32, _baseline: f32) -> Path {
569        Path { cmds: Vec::new(), even_odd: false }
570    }
571}