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 fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush) {
110 self.inner.fill_rect(rect, radius, brush);
111 }
112 fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke) {
113 self.inner.stroke_rect(rect, radius, stroke);
114 }
115 fn fill_ellipse(&mut self, rect: RectF, brush: &Brush) {
116 self.inner.fill_ellipse(rect, brush);
117 }
118 fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke) {
119 self.inner.stroke_ellipse(rect, stroke);
120 }
121 fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke) {
122 self.inner.draw_line(from, to, stroke);
123 }
124 fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle) {
125 if text.is_empty() || rect.width <= 0.0 {
126 return;
127 }
128 let Some(face) = (self.mode != TextMode::Native).then(|| engine_face(text, &style.font)).flatten() else {
129 self.inner.draw_text(text, rect, style);
130 return;
131 };
132 let size = style.font.size;
135 let (line_height, _) = line_metrics(face, size);
136 let mut measure = |s: &str| line_width(face, s, size);
137 let lines = if !style.wrap && !text.contains('\n') {
138 let width = measure(text);
139 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() };
140 vec![(line, true)]
141 } else {
142 let max_lines = ((rect.height + 1.0) / line_height).floor().max(1.0) as usize;
143 crate::text::layout_lines_marked(text, rect.width, max_lines, style.wrap, style.trimming, &mut measure)
144 };
145 let total = line_height * lines.len() as f32;
146 let top = match style.v_align {
147 TextAlign::Leading | TextAlign::Justify => rect.y,
148 TextAlign::Center => rect.y + (rect.height - total) / 2.0,
149 TextAlign::Trailing => rect.bottom() - total,
150 };
151 for (i, (line, end)) in lines.iter().enumerate() {
152 if line.is_empty() {
153 continue;
154 }
155 let y = top + line_height * i as f32;
156 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();
157 if let Some(words) = words {
158 for (x, word) in words {
159 self.draw_line(face, &word, rect.x + x, y, line_height, style);
160 }
161 continue;
162 }
163 let width = line_width(face, line, size);
164 let x = match style.h_align {
165 TextAlign::Leading | TextAlign::Justify => rect.x,
166 TextAlign::Center => rect.x + (rect.width - width) / 2.0,
167 TextAlign::Trailing => rect.right() - width,
168 };
169 self.draw_line(face, line, x, y, line_height, style);
170 }
171 }
172 fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF {
173 if self.mode != TextMode::Native {
174 if let Some(size) = measure(text, style, None) {
175 return size;
176 }
177 }
178 self.inner.measure_text(text, style)
179 }
180 fn draw_image(&mut self, image: &crate::Image, src: RectF, dest: RectF, opacity: f32) {
181 self.inner.draw_image(image, src, dest, opacity);
182 }
183 fn image_size(&mut self, image: &crate::Image) -> Option<SizeF> {
184 self.inner.image_size(image)
185 }
186 fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
187 self.inner.clip_round_rect(rect, radius);
188 }
189 fn fill_path(&mut self, path: &Path, brush: &Brush) {
190 self.inner.fill_path(path, brush);
191 }
192 fn clip_path(&mut self, path: &Path, inverse: bool) {
193 self.inner.clip_path(path, inverse);
194 }
195 fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
196 self.inner.backdrop_blur(rect, radius, blur)
197 }
198 fn begin_masked(&mut self, inverse: bool) -> bool {
199 self.inner.begin_masked(inverse)
200 }
201 fn begin_mask(&mut self) {
202 self.inner.begin_mask();
203 }
204 fn end_mask(&mut self) {
205 self.inner.end_mask();
206 }
207 fn begin_cached(&mut self, key: u64, rect: RectF) -> bool {
208 self.inner.begin_cached(key, rect)
209 }
210 fn end_cached(&mut self) {
211 self.inner.end_cached();
212 }
213 fn forget_cached(&mut self, key: u64) {
214 self.inner.forget_cached(key);
215 }
216 fn stroke_path(&mut self, path: &Path, stroke: &Stroke) {
217 self.inner.stroke_path(path, stroke);
218 }
219 fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &Shadow) {
220 self.inner.draw_shadow(rect, radius, shadow);
221 }
222 fn device_scale(&self) -> f32 {
223 self.inner.device_scale()
224 }
225 fn gpu_device(&self) -> Option<crate::GpuDevice> {
226 self.inner.gpu_device()
227 }
228 fn draw_gpu_surface(&mut self, dest: RectF, surface: &crate::GpuSurface) -> bool {
229 self.inner.draw_gpu_surface(dest, surface)
230 }
231 fn gpu_state_changed(&mut self) {
232 self.inner.gpu_state_changed();
233 }
234}
235
236impl Ui {
237 pub fn set_text_mode(&mut self, mode: TextMode) {
239 if self.text_mode != mode {
240 self.text_mode = mode;
241 self.invalidate();
242 }
243 }
244
245 pub fn text_mode(&self) -> TextMode {
246 self.text_mode
247 }
248}
249
250#[cfg(feature = "text-shaping")]
252fn weight_number(weight: crate::canvas::FontWeight) -> u16 {
253 use crate::canvas::FontWeight::*;
254 match weight {
255 Thin => 100,
256 Light => 300,
257 Normal => 400,
258 Medium => 500,
259 SemiBold => 600,
260 Bold => 700,
261 Black => 900,
262 }
263}
264
265#[cfg(feature = "text-shaping")]
270mod engine {
271 use std::cell::RefCell;
272 use std::collections::HashMap;
273
274 use super::weight_number;
275 use crate::canvas::FontSpec;
276 use crate::geometry::PointF;
277 use crate::path::{Path, PathCmd};
278 use harfrust::font::attribute::Style;
279 use harfrust::font::glyph::outline::{DrawMemory, DrawOptions, PathSink};
280 use harfrust::font::{Blob, Font};
281 use harfrust::GlyphId;
282
283 struct Face {
285 family: String,
286 weight: u16,
287 italic: bool,
288 variant: bool,
290 font: Font,
291 units: f32,
292 ascender: f32,
293 descender: f32,
294 gap: f32,
295 }
296
297 #[derive(Default)]
298 struct Faces {
299 generation: u64,
300 list: Vec<Face>,
301 outlines: HashMap<(usize, u32), Vec<PathCmd>>,
303 variants: HashMap<(usize, u16), usize>,
305 plans: HashMap<PlanKey, harfrust::ShapePlan>,
308 shaped: HashMap<(usize, String), std::rc::Rc<Shaped>>,
313 }
314
315 type PlanKey = (usize, harfrust::Direction, Option<harfrust::Script>, Option<harfrust::Language>);
316
317 struct Shaped {
320 glyphs: Vec<(u32, f32, f32, f32)>,
321 advance: f32,
322 }
323
324 const SHAPED_KEEP: usize = 4096;
325
326 thread_local! {
327 static FACES: RefCell<Faces> = RefCell::new(Faces::default());
328 }
329
330 fn with_faces<R>(f: impl FnOnce(&mut Faces) -> R) -> R {
332 FACES.with(|faces| {
333 let mut faces = faces.borrow_mut();
334 let generation = crate::fonts::generation();
335 if faces.generation != generation || (faces.list.is_empty() && generation > 0) {
336 faces.generation = generation;
337 faces.outlines.clear();
338 faces.variants.clear();
339 faces.plans.clear();
340 faces.shaped.clear();
341 faces.list = crate::fonts::registered()
342 .into_iter()
343 .flat_map(|file| {
344 let data: std::sync::Arc<dyn AsRef<[u8]> + Send + Sync> = file.data.clone();
347 let blob = Blob::from(data);
348 let family = file.family.clone();
349 (0u32..).map_while(move |index| Font::new(blob.clone(), index)).map(move |font| {
350 let units = font.units_per_em() as f32;
351 let attributes = font.default_attributes();
352 let line = font.metrics().h_line().unwrap_or_default();
355 Face {
356 family: family.clone(),
357 weight: attributes.weight.value().round().clamp(1.0, 1000.0) as u16,
358 italic: attributes.style == Style::Italic,
359 variant: false,
360 ascender: line.ascender.to_f32(),
361 descender: line.descender.to_f32(),
362 gap: line.line_gap.to_f32(),
363 units: if units > 0.0 { units } else { 1000.0 },
364 font,
365 }
366 })
367 })
368 .collect();
369 }
370 f(&mut faces)
371 })
372 }
373
374 fn default_family(faces: &Faces) -> Option<String> {
377 faces.list.first().map(|f| f.family.clone())
378 }
379
380 fn pick(faces: &mut Faces, spec: &FontSpec) -> Option<usize> {
382 let family = if spec.family.is_empty() { default_family(faces)? } else { spec.family.clone() };
383 let want = weight_number(spec.weight);
384 let best = faces
385 .list
386 .iter()
387 .enumerate()
388 .filter(|(_, f)| f.family.eq_ignore_ascii_case(&family) && !f.variant)
389 .min_by_key(|(_, f)| (f.italic != spec.italic, (f.weight as i32 - want as i32).abs()))
390 .map(|(i, _)| i)?;
391 let wght = harfrust::Tag::new(b"wght");
393 let variable = faces.list[best].font.axes().iter().any(|a| a.tag() == wght);
394 if !variable || faces.list[best].weight == want {
395 return Some(best);
396 }
397 if let Some(&i) = faces.variants.get(&(best, want)) {
398 return Some(i);
399 }
400 let base = &faces.list[best];
401 let font = base.font.instance_builder().variations([(wght, want as f32)]).build();
402 let face = Face {
403 family: base.family.clone(),
404 weight: want,
405 italic: base.italic,
406 variant: true,
407 font,
408 units: base.units,
409 ascender: base.ascender,
410 descender: base.descender,
411 gap: base.gap,
412 };
413 faces.list.push(face);
414 let i = faces.list.len() - 1;
415 faces.variants.insert((best, want), i);
416 Some(i)
417 }
418
419 fn covers(face: &Face, text: &str) -> bool {
421 let charmap = face.font.charmap();
422 text.chars().all(|c| c.is_control() || c == '\u{200d}' || c == '\u{fe0f}' || charmap.map_unicode(c).is_some())
423 }
424
425 fn shaped(faces: &mut Faces, face: usize, text: &str) -> std::rc::Rc<Shaped> {
427 if let Some(found) = faces.shaped.get(&(face, text.to_string())) {
428 return found.clone();
429 }
430 let mut buffer = harfrust::Buffer::new();
431 buffer.push_str(text);
432 buffer.guess_segment_properties();
433 let key: PlanKey = (face, buffer.direction(), buffer.script(), buffer.language().cloned());
434 let font = &faces.list[face].font;
435 let plan = faces.plans.entry(key).or_insert_with(|| {
436 harfrust::ShapePlan::new(font, buffer.direction(), buffer.script(), buffer.language(), &[])
437 });
438 let shaper = harfrust::ShaperFont::new(font);
439 let shaped = harfrust::shape(&shaper, &mut buffer, harfrust::ShapeOptions::new().plan(Some(plan)));
441 let glyphs: Vec<(u32, f32, f32, f32)> = match shaped {
442 Ok(()) => buffer
443 .glyph_infos()
444 .iter()
445 .zip(buffer.glyph_positions())
446 .map(|(info, pos)| (info.glyph_id, pos.x_advance as f32, pos.x_offset as f32, pos.y_offset as f32))
447 .collect(),
448 Err(_) => Vec::new(),
449 };
450 let advance = glyphs.iter().map(|g| g.1).sum::<f32>();
451 let result = std::rc::Rc::new(Shaped { glyphs, advance });
452 if faces.shaped.len() >= SHAPED_KEEP {
453 faces.shaped.clear();
454 }
455 faces.shaped.insert((face, text.to_string()), result.clone());
456 result
457 }
458
459 fn width_of(faces: &mut Faces, face: usize, text: &str, size: f32) -> f32 {
461 let units = faces.list[face].units;
462 shaped(faces, face, text).advance * size / units
463 }
464
465 fn line_metrics(face: &Face, size: f32) -> (f32, f32) {
467 let scale = size / face.units;
468 let ascent = face.ascender * scale;
469 let height = (face.ascender - face.descender + face.gap) * scale;
470 (height.max(size), ascent + face.gap * scale / 2.0)
471 }
472
473 pub(super) fn engine_face(text: &str, spec: &FontSpec) -> Option<usize> {
475 with_faces(|faces| pick(faces, spec).filter(|&i| covers(&faces.list[i], text)))
476 }
477
478 pub(super) fn line_width(face: usize, text: &str, size: f32) -> f32 {
480 with_faces(|faces| width_of(faces, face, text, size))
481 }
482
483 fn outline_line(faces: &mut Faces, face: usize, line: &str, size: f32, x: f32, baseline: f32) -> Path {
485 let glyphs = shaped(faces, face, line);
486 let scale = size / faces.list[face].units;
487 let mut cmds = Vec::new();
488 let mut pen = x;
489 for &(glyph, advance, dx, dy) in glyphs.glyphs.iter() {
490 let outline = faces.outlines.entry((face, glyph)).or_insert_with(|| {
491 let mut builder = Outline(Vec::new());
492 if let Some(outline) = faces.list[face].font.outline_glyphs().get(GlyphId::new(glyph)) {
493 if outline.draw(&DrawOptions::default(), DrawMemory::Scratch, &mut builder).is_err() {
496 builder.0.clear();
497 }
498 }
499 builder.0
500 });
501 let ox = pen + dx * scale;
502 let oy = baseline - dy * scale;
503 let map = |p: PointF| PointF::new(ox + p.x * scale, oy - p.y * scale);
504 for cmd in outline.iter() {
505 cmds.push(match *cmd {
506 PathCmd::MoveTo(p) => PathCmd::MoveTo(map(p)),
507 PathCmd::LineTo(p) => PathCmd::LineTo(map(p)),
508 PathCmd::QuadTo(a, b) => PathCmd::QuadTo(map(a), map(b)),
509 PathCmd::CubicTo(a, b, c) => PathCmd::CubicTo(map(a), map(b), map(c)),
510 PathCmd::Close => PathCmd::Close,
511 });
512 }
513 pen += advance * scale;
514 }
515 Path { cmds, even_odd: false }
516 }
517
518 struct Outline(Vec<PathCmd>);
520
521 impl PathSink for Outline {
522 fn move_to(&mut self, x: f32, y: f32) {
523 self.0.push(PathCmd::MoveTo(PointF::new(x, y)));
524 }
525 fn line_to(&mut self, x: f32, y: f32) {
526 self.0.push(PathCmd::LineTo(PointF::new(x, y)));
527 }
528 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
529 self.0.push(PathCmd::QuadTo(PointF::new(x1, y1), PointF::new(x, y)));
530 }
531 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
532 self.0.push(PathCmd::CubicTo(PointF::new(x1, y1), PointF::new(x2, y2), PointF::new(x, y)));
533 }
534 fn close(&mut self) {
535 self.0.push(PathCmd::Close);
536 }
537 }
538
539 pub(super) fn line_metrics_of(face: usize, size: f32) -> (f32, f32) {
541 with_faces(|faces| line_metrics(&faces.list[face], size))
542 }
543
544 pub(super) fn outline(face: usize, line: &str, size: f32, x: f32, baseline: f32) -> Path {
546 with_faces(|faces| outline_line(faces, face, line, size, x, baseline))
547 }
548}
549
550#[cfg(not(feature = "text-shaping"))]
552mod engine {
553 use crate::canvas::FontSpec;
554 use crate::path::Path;
555
556 pub(super) fn engine_face(_text: &str, _spec: &FontSpec) -> Option<usize> {
557 None
558 }
559 pub(super) fn line_width(_face: usize, _text: &str, _size: f32) -> f32 {
560 0.0
561 }
562 pub(super) fn line_metrics_of(_face: usize, size: f32) -> (f32, f32) {
563 (size, size)
564 }
565 pub(super) fn outline(_face: usize, _line: &str, _size: f32, _x: f32, _baseline: f32) -> Path {
566 Path { cmds: Vec::new(), even_odd: false }
567 }
568}