1use super::{
2 FontBudgetResource, FontError, FontFace, ShapedGlyph, ShapedLine, TextDirection,
3 TextLayoutBudget, TextStyle, check, represent, reserve,
4};
5
6#[derive(Debug, Clone, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum ShapedLineError {
11 FontMismatch,
13 StyleMismatch,
15 Font(FontError),
17}
18
19impl std::fmt::Display for ShapedLineError {
20 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 Self::FontMismatch => formatter.write_str("prepared text belongs to another font face"),
23 Self::StyleMismatch => formatter.write_str("prepared text uses another text style"),
24 Self::Font(error) => write!(formatter, "prepared text: {error}"),
25 }
26 }
27}
28
29impl std::error::Error for ShapedLineError {
30 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
31 match self {
32 Self::Font(error) => Some(error),
33 _ => None,
34 }
35 }
36}
37
38impl From<FontError> for ShapedLineError {
39 fn from(error: FontError) -> Self {
40 Self::Font(error)
41 }
42}
43
44#[derive(PartialEq)]
45struct PlanKey {
46 script: rustybuzz::Script,
47 direction: rustybuzz::Direction,
48 language: Option<rustybuzz::Language>,
49}
50
51pub struct TextShapingSession<'font> {
83 font: &'font FontFace,
84 face: rustybuzz::Face<'font>,
85 style: TextStyle,
86 budget: TextLayoutBudget,
87 input: rustybuzz::UnicodeBuffer,
88 plan: Option<(PlanKey, rustybuzz::ShapePlan)>,
89 glyphs: Vec<ShapedGlyph>,
90 text: String,
91 factor: f64,
92 ascent: f32,
93 descent: f32,
94 line_height: f32,
95}
96
97impl<'font> TextShapingSession<'font> {
98 pub fn new(
101 font: &'font FontFace,
102 style: TextStyle,
103 budget: TextLayoutBudget,
104 ) -> Result<Self, FontError> {
105 let face =
106 rustybuzz::Face::from_slice(font.font_data(), 0).ok_or(FontError::InvalidFont)?;
107 let factor = f64::from(style.logical_em_size().get()) / f64::from(face.units_per_em());
108 let ascent = represent(f64::from(face.ascender()) * factor)?;
109 let descent = represent(f64::from(face.descender()) * factor)?;
110 let line_height = represent(
111 (f64::from(face.ascender()) - f64::from(face.descender()) + f64::from(face.line_gap()))
112 * factor,
113 )?;
114 if line_height <= 0.0 {
115 return Err(FontError::InvalidFont);
116 }
117 Ok(Self {
118 font,
119 face,
120 style,
121 budget,
122 input: rustybuzz::UnicodeBuffer::new(),
123 plan: None,
124 glyphs: Vec::new(),
125 text: String::new(),
126 factor,
127 ascent,
128 descent,
129 line_height,
130 })
131 }
132
133 pub const fn style(&self) -> &TextStyle {
135 &self.style
136 }
137
138 pub const fn budget(&self) -> TextLayoutBudget {
140 self.budget
141 }
142
143 pub fn shape_line(&mut self, text: &str) -> Result<ShapedLine, FontError> {
146 let advance = self.shape_to_scratch(text)?;
147 Ok(ShapedLine {
148 font: self.font.clone(),
149 style: self.style,
150 text: std::mem::take(&mut self.text),
151 glyphs: std::mem::take(&mut self.glyphs),
152 advance,
153 ascent: self.ascent,
154 descent: self.descent,
155 line_height: self.line_height,
156 })
157 }
158
159 pub fn update_line(
168 &mut self,
169 line: &mut ShapedLine,
170 text: &str,
171 ) -> Result<bool, ShapedLineError> {
172 line.validate_for(self.font, &self.style, &self.budget)?;
173 check(
174 FontBudgetResource::TextBytes,
175 line.text.capacity(),
176 self.budget.max_text_bytes(),
177 )?;
178 check(
179 FontBudgetResource::ShapedGlyphs,
180 line.glyphs.capacity(),
181 self.budget.max_shaped_glyphs(),
182 )?;
183 if line.text == text {
184 return Ok(false);
185 }
186 let advance = self.shape_to_scratch(text)?;
187 std::mem::swap(&mut line.text, &mut self.text);
188 std::mem::swap(&mut line.glyphs, &mut self.glyphs);
189 line.advance = advance;
190 Ok(true)
191 }
192
193 pub fn allocation_bytes(&self) -> usize {
196 self.glyphs
197 .capacity()
198 .saturating_mul(std::mem::size_of::<ShapedGlyph>())
199 .saturating_add(self.text.capacity())
200 }
201
202 pub fn cached_plan_count(&self) -> usize {
204 usize::from(self.plan.is_some())
205 }
206
207 pub fn clear_scratch(&mut self) {
210 self.input = rustybuzz::UnicodeBuffer::new();
211 self.plan = None;
212 self.glyphs = Vec::new();
213 self.text = String::new();
214 }
215
216 fn shape_to_scratch(&mut self, text: &str) -> Result<f32, FontError> {
217 validate_text(text, self.budget)?;
218 self.input.clear();
219 self.input.push_str(text);
220 match self.style.direction() {
221 TextDirection::Auto => {}
222 TextDirection::Ltr => self.input.set_direction(rustybuzz::Direction::LeftToRight),
223 TextDirection::Rtl => self.input.set_direction(rustybuzz::Direction::RightToLeft),
224 }
225 self.input.guess_segment_properties();
226 let key = PlanKey {
227 script: self.input.script(),
228 direction: self.input.direction(),
229 language: self.input.language(),
230 };
231 if self
232 .plan
233 .as_ref()
234 .is_none_or(|(previous, _)| *previous != key)
235 {
236 let plan = rustybuzz::ShapePlan::new(
237 &self.face,
238 key.direction,
239 Some(key.script),
240 key.language.as_ref(),
241 &[],
242 );
243 self.plan = Some((key, plan));
244 }
245 let Some((_, plan)) = &self.plan else {
246 return Err(FontError::InvalidFont);
247 };
248 let output = rustybuzz::shape_with_plan(&self.face, plan, std::mem::take(&mut self.input));
249 let result = self.copy_output(text, &output);
250 if result.is_ok() {
252 self.input = output.clear();
253 }
254 result
255 }
256
257 fn copy_output(
258 &mut self,
259 text: &str,
260 output: &rustybuzz::GlyphBuffer,
261 ) -> Result<f32, FontError> {
262 check(
263 FontBudgetResource::ShapedGlyphs,
264 output.len(),
265 self.budget.max_shaped_glyphs(),
266 )?;
267 self.glyphs.clear();
268 reserve(&mut self.glyphs, output.len())?;
269 let mut pen_x = 0.0f64;
270 let mut pen_y = 0.0f64;
271 for (information, position) in output.glyph_infos().iter().zip(output.glyph_positions()) {
272 if information.glyph_id == 0 {
273 return Err(FontError::MissingGlyph {
274 byte_index: information.cluster as usize,
275 });
276 }
277 self.glyphs.push(ShapedGlyph {
278 glyph_id: u16::try_from(information.glyph_id)
279 .map_err(|_| FontError::InvalidGeometry)?,
280 logical_x: represent((pen_x + f64::from(position.x_offset)) * self.factor)?,
281 logical_y: represent(-(pen_y + f64::from(position.y_offset)) * self.factor)?,
282 cluster: information.cluster as usize,
283 });
284 pen_x += f64::from(position.x_advance);
285 pen_y += f64::from(position.y_advance);
286 }
287 let advance = represent(pen_x * self.factor)?;
288 self.text.clear();
289 self.text
290 .try_reserve_exact(text.len())
291 .map_err(|_| FontError::AllocationFailed {
292 requested_bytes: text.len(),
293 })?;
294 self.text.push_str(text);
295 Ok(advance)
296 }
297}
298
299fn validate_text(text: &str, budget: TextLayoutBudget) -> Result<(), FontError> {
300 check(
301 FontBudgetResource::TextBytes,
302 text.len(),
303 budget.max_text_bytes().min(u32::MAX as usize),
304 )?;
305 for (byte_index, character) in text.char_indices() {
306 if character.is_control() || matches!(character, '\u{2028}' | '\u{2029}') {
307 return Err(FontError::UnsupportedText { byte_index });
308 }
309 }
310 Ok(())
311}