1use 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#[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
40pub 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
54fn core_handles(style: &TextStyle) -> bool {
57 style.letter_spacing == 0.0 && style.color_glyphs
58}
59
60pub(crate) struct TextCanvas<'a> {
63 pub(crate) inner: &'a mut dyn Canvas,
64 pub(crate) mode: TextMode,
65}
66
67impl TextCanvas<'_> {
68 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 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 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 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#[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#[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 struct Face {
305 family: String,
306 weight: u16,
307 italic: bool,
308 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 outlines: HashMap<(usize, u32), Vec<PathCmd>>,
323 variants: HashMap<(usize, u16), usize>,
325 plans: HashMap<PlanKey, harfrust::ShapePlan>,
328 shaped: HashMap<(usize, String), std::rc::Rc<Shaped>>,
333 }
334
335 type PlanKey = (usize, harfrust::Direction, Option<harfrust::Script>, Option<harfrust::Language>);
336
337 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 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 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 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 fn default_family(faces: &Faces) -> Option<String> {
397 faces.list.first().map(|f| f.family.clone())
398 }
399
400 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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}