-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtext_context.rs
More file actions
201 lines (171 loc) · 7.41 KB
/
text_context.rs
File metadata and controls
201 lines (171 loc) · 7.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
use super::{Font, FontCache, TypesettingConfig};
use core::cell::RefCell;
use core_types::table::Table;
use glam::DVec2;
use hyphenation::{Hyphenator, Language, Load, Standard};
use parley::fontique::{Blob, FamilyId, FontInfo};
use parley::{AlignmentOptions, FontContext, Layout, LayoutContext, LineHeight, OverflowWrap, PositionedLayoutItem, StyleProperty};
use std::collections::HashMap;
use std::sync::OnceLock;
use vector_types::Vector;
use super::path_builder::PathBuilder;
thread_local! {
static THREAD_TEXT: RefCell<TextContext> = RefCell::new(TextContext::default());
}
static EN_US_DICT: OnceLock<Option<Standard>> = OnceLock::new();
fn get_dict_for_language(lang: Language) -> Option<&'static Standard> {
match lang {
Language::EnglishUS | Language::EnglishGB => EN_US_DICT
.get_or_init(|| {
Standard::from_embedded(Language::EnglishUS)
.map_err(|err| {
log::error!("Failed to load hyphenation dictionary: {err}");
err
})
.ok()
})
.as_ref(),
_ => None,
}
}
/// Unified thread-local text processing context that combines font and layout management
/// for efficient text rendering operations.
#[derive(Default)]
pub struct TextContext {
font_context: FontContext,
layout_context: LayoutContext<()>,
/// Cached font metadata for performance optimization
font_info_cache: HashMap<Font, (FamilyId, FontInfo)>,
}
impl TextContext {
/// Access the thread-local TextContext instance for text processing operations
pub fn with_thread_local<F, R>(f: F) -> R
where
F: FnOnce(&mut TextContext) -> R,
{
THREAD_TEXT.with_borrow_mut(f)
}
/// Resolve a font and return its data as a Blob if available
fn resolve_font_data<'a>(&self, font: &'a Font, font_cache: &'a FontCache) -> Option<(Blob<u8>, &'a Font)> {
font_cache.get_blob(font)
}
/// Get or cache font information for a given font
fn get_font_info(&mut self, font: &Font, font_data: &Blob<u8>) -> Option<(String, FontInfo)> {
// Check if we already have the font info cached
if let Some((family_id, font_info)) = self.font_info_cache.get(font)
&& let Some(family_name) = self.font_context.collection.family_name(*family_id)
{
return Some((family_name.to_string(), font_info.clone()));
}
// Register the font and cache the info
let families = self.font_context.collection.register_fonts(font_data.clone(), None);
families.first().and_then(|(family_id, fonts_info)| {
fonts_info.first().and_then(|font_info| {
self.font_context.collection.family_name(*family_id).map(|family_name| {
// Cache the font info for future use
self.font_info_cache.insert(font.clone(), (*family_id, font_info.clone()));
(family_name.to_string(), font_info.clone())
})
})
})
}
/// Create a text layout using the specified font and typesetting configuration
// TODO: Cache layout builder to avoid re-shaping text continuously.
fn layout_text(&mut self, text: &str, font: &Font, font_cache: &FontCache, typesetting: TypesettingConfig) -> Option<Layout<()>> {
// Note that the actual_font may not be the desired font if that font is not yet loaded.
// It is important not to cache the default font under the name of another font.
let (font_data, actual_font) = self.resolve_font_data(font, font_cache)?;
let (font_family, font_info) = self.get_font_info(actual_font, &font_data)?;
let injected: String;
let layout_text = if typesetting.hyphenate && typesetting.max_width.is_some() {
// TODO: pull language from typesetting config
injected = apply_hyphenation(text, Language::EnglishUS);
&injected
} else {
text
};
const DISPLAY_SCALE: f32 = 1.;
let mut builder = self.layout_context.ranged_builder(&mut self.font_context, layout_text, DISPLAY_SCALE, false);
builder.push_default(StyleProperty::FontSize(typesetting.font_size as f32));
builder.push_default(StyleProperty::LetterSpacing(typesetting.character_spacing as f32));
builder.push_default(StyleProperty::FontStack(parley::FontStack::Single(parley::FontFamily::Named(std::borrow::Cow::Owned(font_family)))));
builder.push_default(StyleProperty::FontWeight(font_info.weight()));
builder.push_default(StyleProperty::FontStyle(font_info.style()));
builder.push_default(StyleProperty::FontWidth(font_info.width()));
builder.push_default(LineHeight::FontSizeRelative(typesetting.line_height_ratio as f32));
builder.push_default(StyleProperty::OverflowWrap(OverflowWrap::BreakWord));
let mut layout = builder.build(layout_text);
layout.break_all_lines(typesetting.max_width.map(|mw| mw as f32));
layout.align(typesetting.max_width.map(|max_w| max_w as f32), typesetting.align.into(), AlignmentOptions::default());
Some(layout)
}
/// Convert text to vector paths using the specified font and typesetting configuration
pub fn to_path<Upstream: Default + 'static>(&mut self, text: &str, font: &Font, font_cache: &FontCache, typesetting: TypesettingConfig, per_glyph_instances: bool) -> Table<Vector<Upstream>> {
let Some(layout) = self.layout_text(text, font, font_cache, typesetting) else {
return Table::new_from_element(Vector::default());
};
let mut path_builder = PathBuilder::new(per_glyph_instances, layout.scale() as f64);
for line in layout.lines() {
for item in line.items() {
if let PositionedLayoutItem::GlyphRun(glyph_run) = item
&& typesetting.max_height.filter(|&max_height| glyph_run.baseline() > max_height as f32).is_none()
{
path_builder.render_glyph_run(&glyph_run, typesetting.tilt, per_glyph_instances);
}
}
}
path_builder.finalize()
}
/// Calculate the bounding box of text using the specified font and typesetting configuration
pub fn bounding_box(&mut self, text: &str, font: &Font, font_cache: &FontCache, typesetting: TypesettingConfig, for_clipping_test: bool) -> DVec2 {
let Some(layout) = self.layout_text(text, font, font_cache, typesetting) else {
return DVec2::ZERO;
};
let layout_width = layout.full_width() as f64;
let layout_height = layout.height() as f64;
if for_clipping_test {
return DVec2::new(layout_width, layout_height);
}
let width = typesetting.max_width.unwrap_or(layout_width);
let height = typesetting.max_height.unwrap_or(layout_height);
DVec2::new(width, height)
}
/// Check if text lines are being clipped due to height constraints
pub fn lines_clipping(&mut self, text: &str, font: &Font, font_cache: &FontCache, typesetting: TypesettingConfig) -> bool {
let Some(max_height) = typesetting.max_height else { return false };
let bounds = self.bounding_box(text, font, font_cache, typesetting, true);
max_height < bounds.y
}
}
/// Apply hyphenation to the given text.
fn apply_hyphenation(text: &str, lang: Language) -> String {
let Some(dict) = get_dict_for_language(lang) else {
return text.to_string();
};
let mut out = String::with_capacity(text.len() + text.len() / 8);
let mut word_start: Option<usize> = None;
fn push_hyphenated(out: &mut String, dict: &hyphenation::Standard, word: &str) {
const SOFT_HYPHEN: char = '\u{00AD}';
let mut segs = dict.hyphenate(word).into_iter().segments().peekable();
while let Some(seg) = segs.next() {
out.push_str(seg);
if segs.peek().is_some() {
out.push(SOFT_HYPHEN);
}
}
}
for (i, c) in text.char_indices() {
if c.is_alphabetic() {
word_start.get_or_insert(i);
} else {
if let Some(start) = word_start.take() {
push_hyphenated(&mut out, dict, &text[start..i]);
}
out.push(c);
}
}
if let Some(start) = word_start {
push_hyphenated(&mut out, dict, &text[start..]);
}
out
}