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