1use crate::parser::OptionLog;
5use skrifa::DrawMemory;
6use skrifa::font::glyph::color::{Brush, ColorStop, CompositeMode, Extend, PaintSink};
7use skrifa::font::glyph::outline::{DrawOptions, PathSink};
8use skrifa::raw::types::{BoundingBox, GlyphId, Matrix, Point};
9use std::fmt::Write as _;
10use svgtypes::Color;
11
12struct Builder<'a> {
13 path: &'a mut String,
14 min_x: f32,
15 min_y: f32,
16 max_x: f32,
17 max_y: f32,
18}
19
20impl<'a> Builder<'a> {
21 fn new(path: &'a mut String) -> Self {
22 Self {
23 path,
24 min_x: f32::MAX,
25 min_y: f32::MAX,
26 max_x: f32::MIN,
27 max_y: f32::MIN,
28 }
29 }
30
31 fn add_point(&mut self, x: f32, y: f32) {
32 self.min_x = self.min_x.min(x);
33 self.min_y = self.min_y.min(y);
34 self.max_x = self.max_x.max(x);
35 self.max_y = self.max_y.max(y);
36 }
37
38 fn bounds(&self) -> Option<tiny_skia_path::Rect> {
42 if self.min_x <= self.max_x && self.min_y <= self.max_y {
43 tiny_skia_path::Rect::from_ltrb(self.min_x, self.min_y, self.max_x, self.max_y)
44 } else {
45 None
46 }
47 }
48
49 fn finish(&mut self) {
50 if !self.path.is_empty() {
51 self.path.pop(); }
53 }
54}
55
56impl PathSink for Builder<'_> {
57 fn move_to(&mut self, x: f32, y: f32) {
58 self.add_point(x, y);
59 write!(self.path, "M {} {} ", x, y).unwrap();
60 }
61
62 fn line_to(&mut self, x: f32, y: f32) {
63 self.add_point(x, y);
64 write!(self.path, "L {} {} ", x, y).unwrap();
65 }
66
67 fn quad_to(&mut self, cx0: f32, cy0: f32, x: f32, y: f32) {
68 self.add_point(cx0, cy0);
69 self.add_point(x, y);
70 write!(self.path, "Q {} {} {} {} ", cx0, cy0, x, y).unwrap();
71 }
72
73 fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
74 self.add_point(cx0, cy0);
75 self.add_point(cx1, cy1);
76 self.add_point(x, y);
77 write!(self.path, "C {} {} {} {} {} {} ", cx0, cy0, cx1, cy1, x, y).unwrap();
78 }
79
80 fn close(&mut self) {
81 self.path.push_str("Z ");
82 }
83}
84
85trait XmlWriterExt {
86 fn write_color_attribute(&mut self, name: &str, ts: Color);
87 fn write_transform_attribute(&mut self, name: &str, ts: Matrix<f32>);
88 fn write_spread_method_attribute(&mut self, method: Extend);
89}
90
91impl XmlWriterExt for xmlwriter::XmlWriter {
92 fn write_color_attribute(&mut self, name: &str, color: Color) {
93 self.write_attribute_fmt(
94 name,
95 format_args!("rgb({}, {}, {})", color.red, color.green, color.blue),
96 );
97 }
98
99 fn write_transform_attribute(&mut self, name: &str, ts: Matrix<f32>) {
100 if ts == Matrix::default() {
101 return;
102 }
103
104 self.write_attribute_fmt(
105 name,
106 format_args!(
107 "matrix({} {} {} {} {} {})",
108 ts.xx, ts.yx, ts.xy, ts.yy, ts.dx, ts.dy
109 ),
110 );
111 }
112
113 fn write_spread_method_attribute(&mut self, extend: Extend) {
114 self.write_attribute(
115 "spreadMethod",
116 match extend {
117 Extend::Pad => "pad",
118 Extend::Repeat => "repeat",
119 Extend::Reflect => "reflect",
120 Extend::Unknown => return,
121 },
122 );
123 }
124}
125
126pub(crate) struct GlyphPainter<'a> {
128 pub(crate) font: &'a skrifa::Font,
129 pub(crate) svg: &'a mut xmlwriter::XmlWriter,
130 pub(crate) path_buf: &'a mut String,
131 pub(crate) gradient_index: usize,
132 pub(crate) clip_path_index: usize,
133 pub(crate) foreground_color: Color,
134 pub(crate) transform: Matrix<f32>,
135 pub(crate) outline_transform: Matrix<f32>,
136 pub(crate) transforms_stack: Vec<Matrix<f32>>,
137 pub(crate) clip_stack: Vec<Option<tiny_skia_path::Rect>>,
140}
141
142impl<'a> GlyphPainter<'a> {
143 fn write_gradient_stops(&mut self, stops: &[ColorStop]) {
144 for stop in stops {
145 let color = self.palette_index_to_color(stop.palette_index, stop.alpha);
146 self.svg.start_element("stop");
147 self.svg.write_attribute("offset", &stop.offset);
148 self.svg.write_color_attribute("stop-color", color);
149 let opacity = f32::from(color.alpha) / 255.0;
150 self.svg.write_attribute("stop-opacity", &opacity);
151 self.svg.end_element();
152 }
153 }
154
155 fn paint_solid(&mut self, color: Color) {
156 self.svg.start_element("path");
157 self.svg.write_color_attribute("fill", color);
158 let opacity = f32::from(color.alpha) / 255.0;
159 self.svg.write_attribute("fill-opacity", &opacity);
160 self.svg
161 .write_transform_attribute("transform", self.outline_transform);
162 self.svg.write_attribute("d", self.path_buf);
163 self.svg.end_element();
164 }
165
166 fn paint_linear_gradient(
167 &mut self,
168 p0: Point<f32>,
169 p1: Point<f32>,
170 color_stops: &[ColorStop],
171 extend: Extend,
172 ) {
173 let gradient_id = format!("lg{}", self.gradient_index);
174 self.gradient_index += 1;
175
176 let gradient_transform = paint_transform(self.outline_transform, self.transform);
177
178 self.svg.start_element("linearGradient");
179 self.svg.write_attribute("id", &gradient_id);
180 self.svg.write_attribute("x1", &p0.x);
181 self.svg.write_attribute("y1", &p0.y);
182 self.svg.write_attribute("x2", &p1.x);
183 self.svg.write_attribute("y2", &p1.y);
184 self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
185 self.svg.write_spread_method_attribute(extend);
186 self.svg
187 .write_transform_attribute("gradientTransform", gradient_transform);
188 self.write_gradient_stops(color_stops);
189 self.svg.end_element();
190
191 self.svg.start_element("path");
192 self.svg
193 .write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));
194 self.svg
195 .write_transform_attribute("transform", self.outline_transform);
196 self.svg.write_attribute("d", self.path_buf);
197 self.svg.end_element();
198 }
199
200 fn paint_radial_gradient(
201 &mut self,
202 c0: Point<f32>,
203 r0: f32,
204 c1: Point<f32>,
205 r1: f32,
206 color_stops: &[ColorStop],
207 extend: Extend,
208 ) {
209 let gradient_id = format!("rg{}", self.gradient_index);
210 self.gradient_index += 1;
211
212 let gradient_transform = paint_transform(self.outline_transform, self.transform);
213
214 self.svg.start_element("radialGradient");
220 self.svg.write_attribute("id", &gradient_id);
221 self.svg.write_attribute("cx", &c1.x);
222 self.svg.write_attribute("cy", &c1.y);
223 self.svg.write_attribute("r", &r1);
224 self.svg.write_attribute("fr", &r0);
225 self.svg.write_attribute("fx", &c0.x);
226 self.svg.write_attribute("fy", &c0.y);
227 self.svg.write_attribute("gradientUnits", &"userSpaceOnUse");
228 self.svg.write_spread_method_attribute(extend);
229 self.svg
230 .write_transform_attribute("gradientTransform", gradient_transform);
231 self.write_gradient_stops(color_stops);
232 self.svg.end_element();
233
234 self.svg.start_element("path");
235 self.svg
236 .write_attribute_fmt("fill", format_args!("url(#{})", gradient_id));
237 self.svg
238 .write_transform_attribute("transform", self.outline_transform);
239 self.svg.write_attribute("d", self.path_buf);
240 self.svg.end_element();
241 }
242
243 fn paint_sweep_gradient(
244 &mut self,
245 _c0: Point<f32>,
246 _start_angle: f32,
247 _end_angle: f32,
248 _color_stops: &[ColorStop],
249 _extend: Extend,
250 ) {
251 }
254}
255
256fn to_tsp_transform(ts: Matrix<f32>) -> tiny_skia_path::Transform {
257 let [sx, ky, kx, sy, tx, ty] = ts.elements();
258 tiny_skia_path::Transform::from_row(sx, ky, kx, sy, tx, ty)
259}
260
261fn paint_transform(outline_transform: Matrix<f32>, transform: Matrix<f32>) -> Matrix<f32> {
262 let outline_transform = to_tsp_transform(outline_transform);
263 let gradient_transform = to_tsp_transform(transform);
264
265 let ts = outline_transform
266 .invert()
267 .log_none(|| log::warn!("Failed to calculate transform for gradient in glyph."))
268 .unwrap_or_default()
269 .pre_concat(gradient_transform);
270
271 Matrix::from_elements([ts.sx, ts.ky, ts.kx, ts.sy, ts.tx, ts.ty])
272}
273
274fn map_rect(
276 rect: tiny_skia_path::Rect,
277 ts: tiny_skia_path::Transform,
278) -> Option<tiny_skia_path::Rect> {
279 let mut points = [
280 tiny_skia_path::Point::from_xy(rect.left(), rect.top()),
281 tiny_skia_path::Point::from_xy(rect.right(), rect.top()),
282 tiny_skia_path::Point::from_xy(rect.left(), rect.bottom()),
283 tiny_skia_path::Point::from_xy(rect.right(), rect.bottom()),
284 ];
285 ts.map_points(&mut points);
286 let min_x = points.iter().map(|p| p.x).fold(f32::MAX, f32::min);
287 let min_y = points.iter().map(|p| p.y).fold(f32::MAX, f32::min);
288 let max_x = points.iter().map(|p| p.x).fold(f32::MIN, f32::max);
289 let max_y = points.iter().map(|p| p.y).fold(f32::MIN, f32::max);
290 tiny_skia_path::Rect::from_ltrb(min_x, min_y, max_x, max_y)
291}
292
293fn intersect_rects(
295 a: tiny_skia_path::Rect,
296 b: tiny_skia_path::Rect,
297) -> Option<tiny_skia_path::Rect> {
298 tiny_skia_path::Rect::from_ltrb(
299 a.left().max(b.left()),
300 a.top().max(b.top()),
301 a.right().min(b.right()),
302 a.bottom().min(b.bottom()),
303 )
304}
305
306impl GlyphPainter<'_> {
307 fn clip_with_path(&mut self, path: &str) {
308 let clip_id = format!("cp{}", self.clip_path_index);
309 self.clip_path_index += 1;
310
311 self.svg.start_element("clipPath");
312 self.svg.write_attribute("id", &clip_id);
313 self.svg.start_element("path");
314 self.svg
315 .write_transform_attribute("transform", self.outline_transform);
316 self.svg.write_attribute("d", &path);
317 self.svg.end_element();
318 self.svg.end_element();
319
320 self.svg.start_element("g");
321 self.svg
322 .write_attribute_fmt("clip-path", format_args!("url(#{})", clip_id));
323 }
324
325 fn outline_glyph(&mut self, glyph_id: GlyphId) -> Option<tiny_skia_path::Rect> {
330 self.path_buf.clear();
331
332 let mut bounds = None;
333 let outlined = if let Some(outliner) = self.font.outline_glyphs().get(glyph_id) {
334 let mut builder = Builder::new(self.path_buf);
335 let ok = outliner
336 .draw(&DrawOptions::default(), DrawMemory::Scratch, &mut builder)
337 .is_ok();
338 if ok {
339 builder.finish();
340 bounds = builder.bounds();
341 }
342 ok
343 } else {
344 false
345 };
346 if !outlined {
347 self.path_buf.clear();
349 }
350
351 self.outline_transform = self.transform;
353
354 bounds
355 }
356
357 fn paint_brush(&mut self, brush: Brush<'_>) {
359 match brush {
360 Brush::Solid {
361 palette_index,
362 alpha,
363 } => {
364 let color = self.palette_index_to_color(palette_index, alpha);
365 self.paint_solid(color);
366 }
367 Brush::LinearGradient {
368 p0,
369 p1,
370 color_stops,
371 extend,
372 } => self.paint_linear_gradient(p0, p1, color_stops, extend),
373 Brush::RadialGradient {
374 c0,
375 r0,
376 c1,
377 r1,
378 color_stops,
379 extend,
380 } => self.paint_radial_gradient(c0, r0, c1, r1, color_stops, extend),
381
382 Brush::SweepGradient {
383 c0,
384 start_angle,
385 end_angle,
386 color_stops,
387 extend,
388 } => self.paint_sweep_gradient(c0, start_angle, end_angle, color_stops, extend),
389 }
390 }
391
392 fn palette_index_to_color(&self, palette_index: u16, alpha: f32) -> Color {
393 let lookup = || -> Option<Color> {
394 let palettes = self.font.palettes();
397 let palette = palettes.get(0)?;
398 let color = palette.colors().get(palette_index as usize)?;
399 Some(Color {
400 red: color.red,
401 blue: color.blue,
402 green: color.green,
403 alpha: color.alpha,
404 })
405 };
406
407 let mut color = if palette_index == u16::MAX {
408 self.foreground_color
409 } else {
410 lookup().unwrap_or(self.foreground_color)
411 };
412
413 color.alpha = ((color.alpha as f32) * alpha) as u8;
415
416 color
417 }
418}
419
420impl PaintSink for GlyphPainter<'_> {
421 fn push_transform(&mut self, transform: Matrix<f32>) {
422 self.transforms_stack.push(self.transform);
423 self.transform = self.transform * transform;
424 }
425
426 fn pop_transform(&mut self) {
427 if let Some(ts) = self.transforms_stack.pop() {
428 self.transform = ts;
429 }
430 }
431
432 fn fill_glyph(
433 &mut self,
434 glyph_id: GlyphId,
435 brush_transform: Option<Matrix<f32>>,
436 brush: Brush<'_>,
437 ) {
438 self.outline_glyph(glyph_id);
442
443 if let Some(brush_transform) = brush_transform {
444 self.push_transform(brush_transform);
445 self.paint_brush(brush);
446 self.pop_transform();
447 } else {
448 self.paint_brush(brush);
449 }
450 }
451
452 fn push_clip_glyph(&mut self, glyph_id: GlyphId) {
453 let bounds = self.outline_glyph(glyph_id);
454
455 let path = self.path_buf.clone();
459 self.clip_with_path(&path);
460
461 let root_bounds =
462 bounds.and_then(|b| map_rect(b, to_tsp_transform(self.outline_transform)));
463 self.clip_stack.push(root_bounds);
464 }
465
466 fn push_clip_box(&mut self, clip_box: BoundingBox<f32>) {
467 let x_min = clip_box.x_min;
468 let x_max = clip_box.x_max;
469 let y_min = clip_box.y_min;
470 let y_max = clip_box.y_max;
471
472 let clip_path = format!(
473 "M {} {} L {} {} L {} {} L {} {} Z",
474 x_min, y_min, x_max, y_min, x_max, y_max, x_min, y_max
475 );
476
477 self.outline_transform = self.transform;
479 self.clip_with_path(&clip_path);
480
481 let bounds = tiny_skia_path::Rect::from_ltrb(x_min, y_min, x_max, y_max)
482 .and_then(|b| map_rect(b, to_tsp_transform(self.outline_transform)));
483 self.clip_stack.push(bounds);
484 }
485
486 fn pop_clip(&mut self) {
487 self.svg.end_element();
488 self.clip_stack.pop();
489 }
490
491 fn fill(&mut self, brush: Brush<'_>) {
492 if self.clip_stack.is_empty() {
496 log::warn!("Unclipped COLR fills are not supported.");
497 return;
498 }
499
500 let mut region: Option<tiny_skia_path::Rect> = None;
501 for bounds in &self.clip_stack {
502 let Some(bounds) = bounds else { return };
504 region = Some(match region {
505 Some(region) => match intersect_rects(region, *bounds) {
506 Some(r) => r,
507 None => return,
509 },
510 None => *bounds,
511 });
512 }
513 let Some(region) = region else { return };
514
515 self.path_buf.clear();
516 write!(
517 self.path_buf,
518 "M {} {} L {} {} L {} {} L {} {} Z",
519 region.left(),
520 region.top(),
521 region.right(),
522 region.top(),
523 region.right(),
524 region.bottom(),
525 region.left(),
526 region.bottom()
527 )
528 .unwrap();
529
530 self.outline_transform = Matrix::default();
532
533 self.paint_brush(brush);
534 }
535
536 fn push_layer(&mut self, composite_mode: CompositeMode) {
537 let composite_mode = match composite_mode {
539 CompositeMode::SrcOver => "normal",
540 CompositeMode::Screen => "screen",
541 CompositeMode::Overlay => "overlay",
542 CompositeMode::Darken => "darken",
543 CompositeMode::Lighten => "lighten",
544 CompositeMode::ColorDodge => "color-dodge",
545 CompositeMode::ColorBurn => "color-burn",
546 CompositeMode::HardLight => "hard-light",
547 CompositeMode::SoftLight => "soft-light",
548 CompositeMode::Difference => "difference",
549 CompositeMode::Exclusion => "exclusion",
550 CompositeMode::Multiply => "multiply",
551 CompositeMode::HslHue => "hue",
552 CompositeMode::HslSaturation => "saturation",
553 CompositeMode::HslColor => "color",
554 CompositeMode::HslLuminosity => "luminosity",
555 _ => {
556 "normal"
560 }
561 };
562
563 self.svg.start_element("g");
564 self.svg.write_attribute_fmt(
565 "style",
566 format_args!("mix-blend-mode: {}; isolation: isolate", composite_mode),
567 );
568 }
569
570 fn pop_layer(&mut self) {
571 self.svg.end_element();
572 }
573}