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
54pub(crate) struct TextCanvas<'a> {
57 pub(crate) inner: &'a mut dyn Canvas,
58 pub(crate) mode: TextMode,
59}
60
61impl TextCanvas<'_> {
62 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 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 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 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#[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#[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 struct Face {
288 family: String,
289 weight: u16,
290 italic: bool,
291 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 outlines: HashMap<(usize, u32), Vec<PathCmd>>,
306 variants: HashMap<(usize, u16), usize>,
308 plans: HashMap<PlanKey, harfrust::ShapePlan>,
311 shaped: HashMap<(usize, String), std::rc::Rc<Shaped>>,
316 }
317
318 type PlanKey = (usize, harfrust::Direction, Option<harfrust::Script>, Option<harfrust::Language>);
319
320 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 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 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 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 fn default_family(faces: &Faces) -> Option<String> {
380 faces.list.first().map(|f| f.family.clone())
381 }
382
383 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 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 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 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 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 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 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 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 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 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 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 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 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 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#[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}