1use crate::{
2 color::ColorU,
3 fonts::{FontCache, FontId, GlyphId},
4 geometry::rect::RectF,
5 scene, PaintContext,
6};
7use core_foundation::{
8 attributed_string::CFMutableAttributedString,
9 base::{CFRange, TCFType},
10 string::CFString,
11};
12use core_text::{font::CTFont, line::CTLine, string_attributes::kCTFontAttributeName};
13use ordered_float::OrderedFloat;
14use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
15use pathfinder_geometry::vector::{vec2f, Vector2F};
16use smallvec::SmallVec;
17use std::{
18 borrow::Borrow,
19 char,
20 collections::HashMap,
21 convert::TryFrom,
22 hash::{Hash, Hasher},
23 ops::Range,
24 sync::Arc,
25};
26
27pub struct TextLayoutCache {
28 prev_frame: Mutex<HashMap<CacheKeyValue, Arc<Line>>>,
29 curr_frame: RwLock<HashMap<CacheKeyValue, Arc<Line>>>,
30}
31
32impl TextLayoutCache {
33 pub fn new() -> Self {
34 Self {
35 prev_frame: Mutex::new(HashMap::new()),
36 curr_frame: RwLock::new(HashMap::new()),
37 }
38 }
39
40 pub fn finish_frame(&self) {
41 let mut prev_frame = self.prev_frame.lock();
42 let mut curr_frame = self.curr_frame.write();
43 std::mem::swap(&mut *prev_frame, &mut *curr_frame);
44 curr_frame.clear();
45 }
46
47 pub fn layout_str<'a>(
48 &'a self,
49 text: &'a str,
50 font_size: f32,
51 runs: &'a [(Range<usize>, FontId)],
52 font_cache: &'a FontCache,
53 ) -> Arc<Line> {
54 let key = &CacheKeyRef {
55 text,
56 font_size: OrderedFloat(font_size),
57 runs,
58 } as &dyn CacheKey;
59 let curr_frame = self.curr_frame.upgradable_read();
60 if let Some(line) = curr_frame.get(key) {
61 return line.clone();
62 }
63
64 let mut curr_frame = RwLockUpgradableReadGuard::upgrade(curr_frame);
65 if let Some((key, line)) = self.prev_frame.lock().remove_entry(key) {
66 curr_frame.insert(key, line.clone());
67 line.clone()
68 } else {
69 let line = Arc::new(layout_str(text, font_size, runs, font_cache));
70 let key = CacheKeyValue {
71 text: text.into(),
72 font_size: OrderedFloat(font_size),
73 runs: SmallVec::from(runs),
74 };
75 curr_frame.insert(key, line.clone());
76 line
77 }
78 }
79}
80
81trait CacheKey {
82 fn key<'a>(&'a self) -> CacheKeyRef<'a>;
83}
84
85impl<'a> PartialEq for (dyn CacheKey + 'a) {
86 fn eq(&self, other: &dyn CacheKey) -> bool {
87 self.key() == other.key()
88 }
89}
90
91impl<'a> Eq for (dyn CacheKey + 'a) {}
92
93impl<'a> Hash for (dyn CacheKey + 'a) {
94 fn hash<H: Hasher>(&self, state: &mut H) {
95 self.key().hash(state)
96 }
97}
98
99#[derive(Eq, PartialEq)]
100struct CacheKeyValue {
101 text: String,
102 font_size: OrderedFloat<f32>,
103 runs: SmallVec<[(Range<usize>, FontId); 1]>,
104}
105
106impl CacheKey for CacheKeyValue {
107 fn key<'a>(&'a self) -> CacheKeyRef<'a> {
108 CacheKeyRef {
109 text: &self.text.as_str(),
110 font_size: self.font_size,
111 runs: self.runs.as_slice(),
112 }
113 }
114}
115
116impl Hash for CacheKeyValue {
117 fn hash<H: Hasher>(&self, state: &mut H) {
118 self.key().hash(state);
119 }
120}
121
122impl<'a> Borrow<dyn CacheKey + 'a> for CacheKeyValue {
123 fn borrow(&self) -> &(dyn CacheKey + 'a) {
124 self as &dyn CacheKey
125 }
126}
127
128#[derive(Copy, Clone, PartialEq, Eq, Hash)]
129struct CacheKeyRef<'a> {
130 text: &'a str,
131 font_size: OrderedFloat<f32>,
132 runs: &'a [(Range<usize>, FontId)],
133}
134
135impl<'a> CacheKey for CacheKeyRef<'a> {
136 fn key<'b>(&'b self) -> CacheKeyRef<'b> {
137 *self
138 }
139}
140
141#[derive(Default)]
142pub struct Line {
143 pub width: f32,
144 pub runs: Vec<Run>,
145 pub len: usize,
146 font_size: f32,
147}
148
149#[derive(Debug)]
150pub struct Run {
151 pub font_id: FontId,
152 pub glyphs: Vec<Glyph>,
153}
154
155#[derive(Debug)]
156pub struct Glyph {
157 pub id: GlyphId,
158 pub position: Vector2F,
159 pub index: usize,
160}
161
162impl Line {
163 pub fn x_for_index(&self, index: usize) -> f32 {
164 for run in &self.runs {
165 for glyph in &run.glyphs {
166 if glyph.index == index {
167 return glyph.position.x();
168 }
169 }
170 }
171 self.width
172 }
173
174 pub fn index_for_x(&self, x: f32) -> Option<usize> {
175 if x >= self.width {
176 None
177 } else {
178 for run in self.runs.iter().rev() {
179 for glyph in run.glyphs.iter().rev() {
180 if glyph.position.x() <= x {
181 return Some(glyph.index);
182 }
183 }
184 }
185 Some(0)
186 }
187 }
188
189 pub fn paint(&self, bounds: RectF, colors: &[(Range<usize>, ColorU)], ctx: &mut PaintContext) {
190 let mut colors = colors.iter().peekable();
191 let mut color = ColorU::black();
192
193 for run in &self.runs {
194 let bounding_box = ctx.font_cache.bounding_box(run.font_id, self.font_size);
195 let ascent = ctx.font_cache.scale_metric(
196 ctx.font_cache.metric(run.font_id, |m| m.ascent),
197 run.font_id,
198 self.font_size,
199 );
200 let descent = ctx.font_cache.scale_metric(
201 ctx.font_cache.metric(run.font_id, |m| m.descent),
202 run.font_id,
203 self.font_size,
204 );
205
206 let max_glyph_width = bounding_box.x();
207 let font = ctx.font_cache.font(run.font_id);
208 let font_name = ctx.font_cache.font_name(run.font_id);
209 let is_emoji = ctx.font_cache.is_emoji(run.font_id);
210 for glyph in &run.glyphs {
211 let glyph_origin = bounds.origin() + glyph.position;
212 if glyph_origin.x() + max_glyph_width < bounds.origin().x() {
213 continue;
214 }
215 if glyph_origin.x() > bounds.upper_right().x() {
216 break;
217 }
218
219 while let Some((range, next_color)) = colors.peek() {
220 if glyph.index >= range.end {
221 colors.next();
222 } else {
223 color = *next_color;
224 break;
225 }
226 }
227
228 ctx.scene.push_glyph(scene::Glyph {
229 font_id: run.font_id,
230 font_size: self.font_size,
231 id: glyph.id,
232 origin: glyph_origin,
233 color,
234 });
235 }
236 }
237 }
238}
239
240pub fn layout_str(
241 text: &str,
242 font_size: f32,
243 runs: &[(Range<usize>, FontId)],
244 font_cache: &FontCache,
245) -> Line {
246 let mut string = CFMutableAttributedString::new();
247 string.replace_str(&CFString::new(text), CFRange::init(0, 0));
248
249 let mut utf16_lens = text.chars().map(|c| c.len_utf16());
250 let mut prev_char_ix = 0;
251 let mut prev_utf16_ix = 0;
252
253 for (range, font_id) in runs {
254 let utf16_start = prev_utf16_ix
255 + utf16_lens
256 .by_ref()
257 .take(range.start - prev_char_ix)
258 .sum::<usize>();
259 let utf16_end = utf16_start
260 + utf16_lens
261 .by_ref()
262 .take(range.end - range.start)
263 .sum::<usize>();
264 prev_char_ix = range.end;
265 prev_utf16_ix = utf16_end;
266
267 let cf_range = CFRange::init(utf16_start as isize, (utf16_end - utf16_start) as isize);
268 let native_font = font_cache.native_font(*font_id, font_size);
269 unsafe {
270 string.set_attribute(cf_range, kCTFontAttributeName, &native_font);
271 }
272 }
273
274 let line = CTLine::new_with_attributed_string(string.as_concrete_TypeRef());
275
276 let width = line.get_typographic_bounds().width as f32;
277
278 let mut utf16_chars = text.encode_utf16();
279 let mut char_ix = 0;
280 let mut prev_utf16_ix = 0;
281
282 let mut runs = Vec::new();
283 for run in line.glyph_runs().into_iter() {
284 let font_id = font_cache.font_id_for_native_font(unsafe {
285 run.attributes()
286 .unwrap()
287 .get(kCTFontAttributeName)
288 .downcast::<CTFont>()
289 .unwrap()
290 });
291
292 let mut glyphs = Vec::new();
293 for ((glyph_id, position), utf16_ix) in run
294 .glyphs()
295 .iter()
296 .zip(run.positions().iter())
297 .zip(run.string_indices().iter())
298 {
299 let utf16_ix = usize::try_from(*utf16_ix).unwrap();
300 char_ix +=
301 char::decode_utf16(utf16_chars.by_ref().take(utf16_ix - prev_utf16_ix)).count();
302 prev_utf16_ix = utf16_ix;
303
304 glyphs.push(Glyph {
305 id: *glyph_id as GlyphId,
306 position: vec2f(position.x as f32, position.y as f32),
307 index: char_ix,
308 });
309 }
310
311 runs.push(Run { font_id, glyphs })
312 }
313
314 Line {
315 width,
316 runs,
317 font_size,
318 len: char_ix + 1,
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325 use anyhow::Result;
326 use font_kit::properties::{
327 Properties as FontProperties, Style as FontStyle, Weight as FontWeight,
328 };
329
330 #[test]
331 fn test_layout_str() -> Result<()> {
332 let mut font_cache = FontCache::new();
333 let menlo = font_cache.load_family(&["Menlo"])?;
334 let menlo_regular = font_cache.select_font(menlo, &FontProperties::new())?;
335 let menlo_italic =
336 font_cache.select_font(menlo, &FontProperties::new().style(FontStyle::Italic))?;
337 let menlo_bold =
338 font_cache.select_font(menlo, &FontProperties::new().weight(FontWeight::BOLD))?;
339
340 let line = layout_str(
341 "hello world π",
342 16.0,
343 &[
344 (0..2, menlo_bold),
345 (2..6, menlo_italic),
346 (6..13, menlo_regular),
347 ],
348 &mut font_cache,
349 );
350
351 assert!(font_cache.is_emoji(line.runs.last().unwrap().font_id));
352
353 Ok(())
354 }
355
356 #[test]
357 fn test_char_indices() -> Result<()> {
358 let mut font_cache = FontCache::new();
359 let zapfino = font_cache.load_family(&["Zapfino"])?;
360 let zapfino_regular = font_cache.select_font(zapfino, &FontProperties::new())?;
361 let menlo = font_cache.load_family(&["Menlo"])?;
362 let menlo_regular = font_cache.select_font(menlo, &FontProperties::new())?;
363
364 let text = "This is, mπre πr less, Zapfino!π";
365 let line = layout_str(
366 text,
367 16.0,
368 &[
369 (0..9, zapfino_regular),
370 (11..22, menlo_regular),
371 (22..text.encode_utf16().count(), zapfino_regular),
372 ],
373 &mut font_cache,
374 );
375 assert_eq!(
376 line.runs
377 .iter()
378 .flat_map(|r| r.glyphs.iter())
379 .map(|g| g.index)
380 .collect::<Vec<_>>(),
381 vec![
382 0, 2, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
383 31, 32
384 ]
385 );
386 Ok(())
387 }
388}