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