1use std::collections::HashMap;
10
11use cosmic_text::{FontSystem, LayoutGlyph, SwashCache, SwashContent, SwashImage};
12use crabshell_ui::{
13 Affine, CaptureView, Color, Content, IconView, ImageView, InputView, NodeView, Radii, Rect,
14 Shadow, Size, Span, Style, TextSystem, TextView, WindowView,
15};
16use tiny_skia::{
17 FillRule, FilterQuality, LineCap, LineJoin, Mask, Paint, PathBuilder, PathSegment, Pixmap,
18 PixmapMut, PixmapPaint, Stroke, StrokeDash, Transform,
19};
20
21use crate::damage::{BufferAge, DamageHistory, PixelRect};
22use crate::icons::{Drawn, Icons};
23use crate::theme::IconLookup;
24
25mod canvas;
26mod effects;
27mod gradient;
28mod transition;
29
30const TILE: u32 = 64;
35
36const GLYPH_CACHE_LIMIT: usize = 2048;
39
40const LAYER_LIMIT: u64 = 1 << 22;
44
45const LAYER_MARGIN: f32 = 2.0;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum PixelFormat {
53 Argb8888,
55 Abgr8888,
57}
58
59pub struct Canvas<'a> {
61 pub pixels: &'a mut [u8],
63 pub width: u32,
67 pub height: u32,
69 pub scale: f32,
71 pub format: PixelFormat,
73 pub age: &'a mut BufferAge,
75}
76
77pub struct Renderer {
80 glyphs: SwashCache,
81 icons: Icons,
82 scratch: Vec<u8>,
85 work: Work,
86}
87
88#[derive(Default)]
91#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
92struct Work {
93 layer_pixels: u64,
95 nodes: u64,
97 blurred: u64,
99 gradient_pixels: std::cell::Cell<u64>,
102}
103
104impl Renderer {
105 pub fn new() -> Renderer {
108 Renderer {
109 glyphs: SwashCache::new(),
110 icons: Icons::new(),
111 scratch: Vec::new(),
112 work: Work::default(),
113 }
114 }
115
116 #[cfg(test)]
118 pub(crate) fn image_lookups(&self) -> usize {
119 self.icons.lookups()
120 }
121
122 #[cfg(test)]
124 pub(crate) fn cached_glyphs(&self) -> usize {
125 self.glyphs.image_cache.len()
126 }
127
128 #[cfg(test)]
131 pub(crate) fn work(&self) -> (u64, u64, u64) {
132 (self.work.layer_pixels, self.work.nodes, self.work.blurred)
133 }
134
135 #[cfg(test)]
137 pub(crate) fn gradient_pixels(&self) -> u64 {
138 self.work.gradient_pixels.get()
139 }
140
141 #[cfg(test)]
144 pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
145 Renderer {
146 icons: Icons::with_themes(crate::theme::Themes::new(bases)),
147 ..Renderer::new()
148 }
149 }
150
151 pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
153 self.icons.set_theme(theme.into());
154 }
155
156 pub fn icon_lookup(&self) -> IconLookup {
159 self.icons.lookup()
160 }
161
162 #[cfg(test)]
164 pub(crate) fn cached_bytes(&self) -> usize {
165 self.icons.cached_bytes()
166 }
167
168 #[cfg(test)]
170 pub(crate) fn cached_icons(&self) -> usize {
171 self.icons.cached()
172 }
173
174 #[cfg(test)]
176 pub(crate) fn rasterized_icons(&self) -> usize {
177 self.icons.rasterized()
178 }
179
180 pub fn forget_captures(&mut self, gone: &[u64]) {
184 self.icons.forget_captures(gone);
185 }
186
187 pub fn decode_off_thread(&mut self) {
200 self.icons.decode_off_thread();
201 }
202
203 pub fn load_images(&mut self, view: &WindowView<'_>, scale: f32) {
210 self.icons.load_unseen(&view.loading_images(), scale);
211 }
212
213 pub fn decoding(&self) -> bool {
216 self.icons.decoding()
217 }
218
219 pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
223 self.icons.wake_when_decoded(Box::new(wake));
224 }
225
226 pub fn waits_for_pictures(&self) -> bool {
229 self.icons.waited()
230 }
231
232 pub fn take_decoded(&mut self) -> Vec<u64> {
238 self.icons.take_decoded()
239 }
240
241 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
246 self.icons.next_frame(now)
247 }
248
249 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
255 self.icons.advance(now)
256 }
257
258 #[cfg(test)]
260 pub(crate) fn decoded_off_thread(&self) -> usize {
261 self.icons.worker_work().0
262 }
263
264 #[cfg(test)]
266 pub(crate) fn decoder_running(&self) -> bool {
267 self.icons.worker_work().1
268 }
269
270 #[cfg(test)]
272 pub(crate) fn cached_captures(&self) -> usize {
273 self.icons.captures()
274 }
275
276 pub fn draw(
294 &mut self,
295 view: &WindowView<'_>,
296 damage: &[Rect],
297 text: &mut TextSystem,
298 history: &mut DamageHistory,
299 canvas: Canvas<'_>,
300 ) -> Result<Vec<PixelRect>, CanvasError> {
301 let Canvas {
302 pixels,
303 width,
304 height,
305 scale,
306 format,
307 age,
308 } = canvas;
309 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
310 || !(scale.is_finite() && scale > 0.0)
311 {
312 return Err(CanvasError {
313 width,
314 height,
315 scale,
316 bytes: pixels.len(),
317 });
318 }
319 self.icons.start_frame(history.id());
320 let plan = history.plan(damage, scale, width, height, age);
321 let mut tiles: Vec<(u32, u32)> = Vec::new();
322 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
323 for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
324 tiles
325 .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
326 }
327 }
328 tiles.sort_unstable();
329 tiles.dedup();
330 let mut casts = HashMap::new();
331 let mut fonts = text.font_system();
332 for &(row, column) in &tiles {
333 self.icons.start_tile((row, column));
334 let (x, y) = (column * TILE, row * TILE);
335 let size = (width.saturating_sub(x), height.saturating_sub(y));
336 let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
337 self.scratch.clear();
338 self.scratch.resize(area.area() as usize * 4, 0);
339 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
340 else {
341 continue;
342 };
343 let mut painter = Painter {
344 grid: Grid {
345 scale,
346 zoom: 1.0,
347 linear: Affine {
348 sx: 1.0,
349 ky: 0.0,
350 kx: 0.0,
351 sy: 1.0,
352 tx: 0.0,
353 ty: 0.0,
354 },
355 window: view.size(),
356 width,
357 height,
358 left: area.x as f32,
359 top: area.y as f32,
360 },
361 glyphs: &mut self.glyphs,
362 icons: &mut self.icons,
363 fonts: &mut fonts,
364 work: &mut self.work,
365 casts: &mut casts,
366 };
367 painter.node(&mut pixmap, view.root());
368 copy(&self.scratch, area, pixels, width, format);
369 }
370 self.icons.repainted(&tiles);
371 self.icons.end_frame();
372 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
373 self.glyphs.image_cache.clear();
374 self.glyphs.outline_command_cache.clear();
375 }
376 Ok(plan.report)
377 }
378}
379
380#[derive(Clone, Copy, Debug, PartialEq)]
383pub struct CanvasError {
384 pub width: u32,
386 pub height: u32,
388 pub scale: f32,
390 pub bytes: usize,
392}
393
394impl std::fmt::Display for CanvasError {
395 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396 write!(
397 f,
398 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
399 self.width,
400 self.height,
401 self.scale,
402 u64::from(self.width) * u64::from(self.height) * 4,
403 self.bytes
404 )
405 }
406}
407
408impl std::error::Error for CanvasError {}
409
410impl Default for Renderer {
411 fn default() -> Self {
412 Self::new()
413 }
414}
415
416fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
418 let stride = width as usize * 4;
419 let row_bytes = area.width as usize * 4;
420 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
421 let start = (area.y as usize + row) * stride + area.x as usize * 4;
422 let target = &mut pixels[start..start + row_bytes];
423 match format {
424 PixelFormat::Abgr8888 => target.copy_from_slice(source),
425 PixelFormat::Argb8888 => {
426 let (to, _) = target.as_chunks_mut::<4>();
427 let (from, _) = source.as_chunks::<4>();
428 for (to, from) in to.iter_mut().zip(from) {
431 let pixel = u32::from_le_bytes(*from);
432 *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
433 }
434 }
435 }
436 }
437}
438
439#[derive(Clone, Copy)]
441struct Grid {
442 scale: f32,
444 zoom: f32,
447 linear: Affine,
450 window: Size,
452 width: u32,
454 height: u32,
455 left: f32,
457 top: f32,
458}
459
460impl Grid {
461 fn x(&self, x: f32) -> f32 {
464 let pixel = if x >= self.window.width {
465 self.width as f32
466 } else {
467 (x * self.scale).round()
468 };
469 pixel - self.left
470 }
471
472 fn y(&self, y: f32) -> f32 {
474 let pixel = if y >= self.window.height {
475 self.height as f32
476 } else {
477 (y * self.scale).round()
478 };
479 pixel - self.top
480 }
481
482 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
486 if !(rect.width > 0.0 && rect.height > 0.0) {
487 return None;
488 }
489 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
491 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
492 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
493 let bottom =
494 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
495 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
496 }
497
498 fn moved(&self, x: u32, y: u32) -> Grid {
500 Grid {
501 left: self.left + x as f32,
502 top: self.top + y as f32,
503 ..*self
504 }
505 }
506
507 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
510 tiny_skia::Rect::from_ltrb(
511 self.x(rect.x),
512 self.y(rect.y),
513 self.x(rect.right()),
514 self.y(rect.bottom()),
515 )
516 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
517 }
518}
519
520struct Painter<'a> {
522 grid: Grid,
523 glyphs: &'a mut SwashCache,
524 icons: &'a mut Icons,
525 fonts: &'a mut FontSystem,
526 work: &'a mut Work,
527 casts: &'a mut HashMap<CastKey, effects::Cast>,
529}
530
531type CastKey = (String, i64, i64);
534
535impl Painter<'_> {
536 fn on(&mut self, grid: Grid) -> Painter<'_> {
538 Painter {
539 grid,
540 glyphs: &mut *self.glyphs,
541 icons: &mut *self.icons,
542 fonts: &mut *self.fonts,
543 work: &mut *self.work,
544 casts: &mut *self.casts,
545 }
546 }
547
548 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
553 let Some((x, y, width, height)) =
555 self
556 .grid
557 .cover(node.bounds(), pixmap.width(), pixmap.height())
558 else {
559 return;
560 };
561 let style = node.style();
562 let opacity = style.opacity.unwrap_or(1.0);
563 let opacity = if opacity.is_nan() {
564 1.0
565 } else {
566 opacity.clamp(0.0, 1.0)
567 };
568 if opacity == 0.0 {
569 return;
570 }
571 let shadow = effects::cast_by_content(&style);
572 let region = node
575 .mask_region()
576 .filter(|_| node.transform().is_none() && shadow.is_none())
577 .map(|region| {
578 let inner = self.on(self.grid.moved(x, y));
579 inner.region_cover(width, height, node.rect(), region)
580 });
581 if matches!(region, Some(effects::Cover::Clear)) {
582 return;
583 }
584 if let Some(transform) = node.transform() {
585 self.transformed(pixmap, node, &style, transform, opacity);
586 } else if opacity < 1.0
587 || style.mask.is_some()
588 || matches!(region, Some(effects::Cover::Part(_)))
589 || shadow.is_some()
590 {
591 let Some(mut layer) = Pixmap::new(width, height) else {
593 return;
594 };
595 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
596 let mut inner = self.on(self.grid.moved(x, y));
597 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow, region);
598 let paint = PixmapPaint {
599 opacity,
600 ..PixmapPaint::default()
601 };
602 let (x, y) = (x as i32, y as i32);
603 pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
604 } else {
605 self.node_contents(pixmap, node, &style);
606 }
607 }
608
609 fn layer_contents(
614 &mut self,
615 layer: &mut PixmapMut<'_>,
616 node: NodeView<'_>,
617 style: &Style,
618 shadow: Option<Shadow>,
619 cover: Option<effects::Cover>,
620 ) {
621 self.node_contents(layer, node, style);
622 if let Some(mask) = &style.mask {
623 self.mask(layer, node.rect(), mask);
624 }
625 let (width, height) = (layer.width(), layer.height());
626 let cover = cover.or_else(|| {
627 let region = node.mask_region()?;
628 Some(self.region_cover(width, height, node.rect(), region))
629 });
630 match cover {
631 Some(effects::Cover::Clear) => layer.fill(tiny_skia::Color::TRANSPARENT),
632 Some(effects::Cover::Part(cut)) => layer.apply_mask(&cut),
633 Some(effects::Cover::Whole) | None => {}
634 }
635 if let Some(shadow) = shadow {
636 self.content_shadow(layer, node, &shadow);
637 }
638 }
639
640 fn transformed(
647 &mut self,
648 pixmap: &mut PixmapMut<'_>,
649 node: NodeView<'_>,
650 style: &Style,
651 transform: Affine,
652 opacity: f32,
653 ) {
654 let Affine {
655 sx,
656 ky,
657 kx,
658 sy,
659 tx,
660 ty,
661 } = transform;
662 let Grid {
663 scale, left, top, ..
664 } = self.grid;
665 let outer = self.grid.linear;
666 let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0)
667 .pre_concat(Transform::from_row(sx, ky, kx, sy, 0.0, 0.0));
668 let linear = Affine {
669 sx: linear.sx,
670 ky: linear.ky,
671 kx: linear.kx,
672 sy: linear.sy,
673 tx: 0.0,
674 ty: 0.0,
675 };
676 let zoom = linear.layer_zoom();
677 let layer_scale = scale / self.grid.zoom * zoom;
678 let device = Transform::from_scale(scale, scale)
680 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
681 .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
682 let to_pixmap = device.post_translate(-left, -top);
683 let Some(back) = to_pixmap.invert() else {
684 return;
685 };
686 let inner = node.inner_bounds();
687 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
688 .and_then(|rect| rect.transform(back));
689 let drawn = tiny_skia::Rect::from_xywh(
690 inner.x * layer_scale,
691 inner.y * layer_scale,
692 inner.width * layer_scale,
693 inner.height * layer_scale,
694 );
695 let Some(area) = shown
696 .zip(drawn)
697 .and_then(|(shown, drawn)| shown.intersect(&drawn))
698 .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
699 .and_then(|area| area.round_out())
700 else {
701 return;
702 };
703 let pixels = u64::from(area.width()) * u64::from(area.height());
704 if pixels > LAYER_LIMIT {
705 tracing::debug!(
706 "{} is transformed into a layer too large to draw",
707 node.path()
708 );
709 return;
710 }
711 let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
712 return;
713 };
714 self.work.layer_pixels += pixels;
715 let (x, y) = (area.x() as f32, area.y() as f32);
716 let (width, height) = if zoom == self.grid.zoom {
717 (self.grid.width, self.grid.height)
718 } else {
719 let window = self.grid.window;
721 (
722 (window.width * layer_scale).round() as u32,
723 (window.height * layer_scale).round() as u32,
724 )
725 };
726 let mut inner = self.on(Grid {
727 scale: layer_scale,
728 zoom,
729 linear,
730 width,
731 height,
732 left: x,
733 top: y,
734 ..self.grid
735 });
736 let shadow = effects::cast_by_content(style);
737 inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
738 let paint = PixmapPaint {
739 opacity,
740 quality: FilterQuality::Bilinear,
741 ..PixmapPaint::default()
742 };
743 pixmap.draw_pixmap(
744 0,
745 0,
746 layer.as_ref(),
747 &paint,
748 to_pixmap.pre_translate(x, y),
749 None,
750 );
751 }
752
753 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
754 self.work.nodes += 1;
755 let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
758 if let Some(shadow) = style.shadow.filter(outside) {
759 self.shadow(pixmap, node.rect(), style, &shadow);
760 }
761 self.draw_box(pixmap, node.rect(), style);
762 match node.content() {
763 Content::Text(text) => {
764 let color = text.color();
765 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
766 self.selection(pixmap, &text.selection(), tint);
767 self.text(pixmap, &text);
768 }
769 Content::Icon(icon) => self.icon(pixmap, &icon),
770 Content::Image(image) => self.image(pixmap, &image),
771 Content::Capture(capture) => self.capture(pixmap, &capture),
772 Content::Input(input) => self.input(pixmap, &input),
773 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
774 Content::None => {}
775 }
776 if node.clips() {
777 self.clipped_children(pixmap, node, style);
778 } else {
779 for child in node.children() {
780 self.node(pixmap, child);
781 }
782 }
783 }
784
785 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
790 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
791 return;
792 };
793 let width = self.border_width(style);
794 let Some(inside) = tiny_skia::Rect::from_ltrb(
795 area.left() + width,
796 area.top() + width,
797 area.right() - width,
798 area.bottom() - width,
799 ) else {
800 return;
801 };
802 let corners = inset(corners, width);
803 self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
804 for child in node.children() {
805 painter.node(layer, child);
806 }
807 for (handle, bar) in node.scroll_bars() {
809 painter.draw_box(layer, handle, &bar);
810 }
811 });
812 }
813
814 fn through_mask(
817 &mut self,
818 pixmap: &mut PixmapMut<'_>,
819 cover: Rect,
820 (shape, corners): (tiny_skia::Rect, Corners),
821 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
822 ) {
823 if !visible(pixmap, shape) {
824 return;
825 }
826 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
827 Mask::new(pixmap.width(), pixmap.height()),
828 self.grid.cover(cover, pixmap.width(), pixmap.height()),
829 ) else {
830 return;
831 };
832 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
833 return;
834 };
835 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
836 let mut inner = self.on(self.grid.moved(x, y));
837 draw(&mut inner, &mut layer.as_mut());
838 let mut path = PathBuilder::new();
839 rounded_rect(&mut path, shape, corners);
840 let Some(path) = path.finish() else {
841 return;
842 };
843 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
844 pixmap.draw_pixmap(
845 x as i32,
846 y as i32,
847 layer.as_ref(),
848 &PixmapPaint::default(),
849 Transform::identity(),
850 Some(&mask),
851 );
852 }
853
854 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
858 let area = self.grid.rect(rect)?;
859 let corners = style.radius.unwrap_or_default().corners();
860 let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
861 Some((area, corners))
862 }
863
864 fn border_width(&self, style: &Style) -> f32 {
867 let Some(border) = style.border else {
868 return 0.0;
869 };
870 let width = (border.width * self.grid.scale).floor();
871 if border.width > 0.0 {
872 width.max(1.0)
873 } else {
874 width.max(0.0)
875 }
876 }
877
878 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
881 let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
882 if style.background.is_none()
883 && style.gradient.is_none()
884 && style.border.is_none()
885 && inset_shadow.is_none()
886 {
887 return;
888 }
889 let Some((area, corners)) = self.box_shape(rect, style) else {
890 return;
891 };
892 if !visible(pixmap, area) {
893 return;
894 }
895
896 if let Some(color) = style.background
897 && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
898 {
899 let mut path = PathBuilder::new();
900 rounded_rect(&mut path, area, corners);
901 fill(pixmap, path, color, FillRule::Winding);
902 }
903 if let Some(gradient) = style.gradient {
904 let mut path = PathBuilder::new();
905 rounded_rect(&mut path, area, corners);
906 let size = (pixmap.width(), pixmap.height());
907 if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
908 ramp.fill(pixmap, &path);
909 }
910 }
911 if let Some(shadow) = inset_shadow {
912 self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
913 }
914 if let Some(border) = style.border {
915 let width = self.border_width(style);
916 let dashed = width >= 1.0
917 && style.border_dash.is_some_and(|dash| {
918 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
919 });
920
921 if width >= 1.0 && !dashed {
922 let mut path = PathBuilder::new();
924 rounded_rect(&mut path, area, corners);
925 if let Some(inner) = tiny_skia::Rect::from_ltrb(
926 area.left() + width,
927 area.top() + width,
928 area.right() - width,
929 area.bottom() - width,
930 ) {
931 rounded_rect(&mut path, inner, inset(corners, width));
932 }
933 fill(pixmap, path, border.color, FillRule::EvenOdd);
934 }
935 }
936 }
937
938 fn dashed_border(
944 &self,
945 pixmap: &mut PixmapMut<'_>,
946 (area, corners): (tiny_skia::Rect, Corners),
947 width: f32,
948 color: Color,
949 (on, off): (f32, f32),
950 ) -> bool {
951 let Grid {
952 scale, left, top, ..
953 } = self.grid;
954 let half = width / 2.0;
955 let Some(middle) = tiny_skia::Rect::from_ltrb(
956 area.left() + left + half,
957 area.top() + top + half,
958 area.right() + left - half,
959 area.bottom() + top - half,
960 ) else {
961 return false;
962 };
963 let corners = inset(corners, half);
964 let (on, off) = (on * scale, off * scale);
965 let mut all = PathBuilder::new();
966 let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
967 if square.is_empty() {
968 let rounding: f32 = corners
971 .iter()
972 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
973 .sum();
974 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
975 let mut path = PathBuilder::new();
976 rounded_rect(&mut path, middle, corners);
977 if !dash_into(&mut all, path, perimeter, on, off) {
978 return false;
979 }
980 } else {
981 for (at, &from) in square.iter().enumerate() {
984 let to = square[(at + 1) % square.len()];
985 let steps = (to + 4 - from - 1) % 4 + 1;
986 let [.., mut was] = corner(middle, corners, from);
987 let mut path = PathBuilder::new();
988 path.move_to(was.x, was.y);
989 let mut length = 0.0;
990 for index in (from + 1..=from + steps).map(|index| index % 4) {
991 let [start, one, two, end] = corner(middle, corners, index);
992 path.line_to(start.x, start.y);
993 length += was.distance(start);
994 if corners[index] > 0.0 {
995 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
996 length += std::f32::consts::FRAC_PI_2 * corners[index];
997 }
998 was = end;
999 }
1000 if !dash_into(&mut all, path, length, on, off) {
1001 return false;
1002 }
1003 }
1004 if on > 0.0 {
1008 const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
1010 for &index in &square {
1011 let [point, ..] = corner(middle, corners, index);
1012 let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
1013 all.move_to(point.x - half * ax, point.y - half * ay);
1014 all.line_to(point.x, point.y);
1015 all.line_to(point.x + half * bx, point.y + half * by);
1016 }
1017 }
1018 }
1019 let Some(dashes) = all.finish() else {
1020 return true;
1021 };
1022 let reach = 2.0 * width + 1.0;
1027 let near = [
1028 left - reach,
1029 top - reach,
1030 left + pixmap.width() as f32 + reach,
1031 top + pixmap.height() as f32 + reach,
1032 ];
1033 let mut kept = PathBuilder::new();
1034 let mut contour = Vec::new();
1035 for segment in dashes.segments() {
1036 if matches!(segment, PathSegment::MoveTo(_)) {
1037 keep_near(&mut kept, &contour, near);
1038 contour.clear();
1039 }
1040 contour.push(segment);
1041 }
1042 keep_near(&mut kept, &contour, near);
1043 let Some(kept) = kept.finish() else {
1044 return true;
1045 };
1046 let stroke = Stroke {
1047 width,
1048 line_cap: if on == 0.0 {
1050 LineCap::Round
1051 } else {
1052 LineCap::Butt
1053 },
1054 line_join: LineJoin::Miter,
1055 ..Stroke::default()
1056 };
1057 let mut paint = Paint::default();
1058 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1059 paint.anti_alias = true;
1060 let moved = Transform::from_translate(-left, -top);
1061 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1062 true
1063 }
1064
1065 fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1070 let Grid {
1071 scale, left, top, ..
1072 } = self.grid;
1073 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1074 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1075 return;
1076 }
1077 let Some((area, corners)) = self.box_shape(rect, style) else {
1078 return;
1079 };
1080 let spread = shadow.spread * scale;
1082 let Some(shape) = tiny_skia::Rect::from_ltrb(
1083 area.left() + left + shadow.x * scale - spread,
1084 area.top() + top + shadow.y * scale - spread,
1085 area.right() + left + shadow.x * scale + spread,
1086 area.bottom() + top + shadow.y * scale + spread,
1087 ) else {
1088 return;
1089 };
1090 let corners = fit(spread_corners(corners, spread), shape);
1091 let cut = if shadow.cut_out {
1093 self.box_mask(pixmap, rect, style)
1094 } else {
1095 None
1096 };
1097 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1099 if sigma < 0.25 {
1100 let mut path = PathBuilder::new();
1101 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1102 return;
1103 };
1104 rounded_rect(&mut path, shape, corners);
1105 let Some(path) = path.finish() else {
1106 return;
1107 };
1108 let mut paint = Paint::default();
1109 let color = shadow.color;
1110 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1111 paint.anti_alias = true;
1112 let outside = cut.map(|mut cut| {
1113 cut.invert();
1114 cut
1115 });
1116 let (rule, at) = (FillRule::Winding, Transform::identity());
1117 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1118 return;
1119 }
1120 let reach = 3.0 * sigma;
1121 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1122 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1123 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1124 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1125 if columns.is_empty() || rows.is_empty() {
1126 return;
1127 }
1128 let blurred = BlurredBox::new(shape, corners, sigma);
1129 let mut mask = Vec::with_capacity(columns.len() * rows.len());
1130 for row in rows.clone() {
1131 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1132 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1133 }
1134 if let Some(cut) = cut {
1135 let stride = pixmap.width() as usize;
1136 let under = rows.clone().flat_map(|row| {
1137 columns
1138 .clone()
1139 .map(move |column| row as usize * stride + column as usize)
1140 });
1141 for (alpha, at) in mask.iter_mut().zip(under) {
1142 *alpha = mul(*alpha, 255 - cut.data()[at]);
1143 }
1144 }
1145 let width = columns.len() as u32;
1146 let height = rows.len() as u32;
1147 let (x, y) = (columns.start as i32, rows.start as i32);
1148 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1149 }
1150
1151 fn inset_shadow(
1156 &self,
1157 pixmap: &mut PixmapMut<'_>,
1158 (area, corners): (tiny_skia::Rect, Corners),
1159 border: f32,
1160 shadow: &Shadow,
1161 ) {
1162 let Grid {
1163 scale, left, top, ..
1164 } = self.grid;
1165 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1166 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1167 return;
1168 }
1169 let Some(inside) = tiny_skia::Rect::from_ltrb(
1170 area.left() + border,
1171 area.top() + border,
1172 area.right() - border,
1173 area.bottom() - border,
1174 ) else {
1175 return;
1176 };
1177 let inside_corners = inset(corners, border);
1178 if !visible(pixmap, inside) {
1179 return;
1180 }
1181 let mut path = PathBuilder::new();
1182 rounded_rect(&mut path, inside, inside_corners);
1183 let Some(path) = path.finish() else {
1184 return;
1185 };
1186 let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1188 let hole = tiny_skia::Rect::from_ltrb(
1189 inside.left() + left + x + spread,
1190 inside.top() + top + y + spread,
1191 inside.right() + left + x - spread,
1192 inside.bottom() + top + y - spread,
1193 );
1194 let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1195 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1196 let color = shadow.color;
1197 if sigma < 0.25 {
1198 let mut outside = None;
1199 if let Some((hole, corners)) = hole {
1200 let mut cut = PathBuilder::new();
1201 let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1202 return;
1203 };
1204 rounded_rect(&mut cut, moved, corners);
1205 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1206 return;
1207 };
1208 let (rule, at) = (FillRule::Winding, Transform::identity());
1209 let Some(cut) = cut.finish() else {
1210 return;
1211 };
1212 mask.fill_path(&cut, rule, true, at);
1213 mask.invert();
1214 outside = Some(mask);
1215 }
1216 let mut paint = Paint::default();
1217 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1218 paint.anti_alias = true;
1219 let (rule, at) = (FillRule::Winding, Transform::identity());
1220 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1221 return;
1222 }
1223 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1226 return;
1227 };
1228 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1229 let columns = inside.left().floor().max(0.0) as u32
1230 ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1231 let rows = inside.top().floor().max(0.0) as u32
1232 ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1233 if columns.is_empty() || rows.is_empty() {
1234 return;
1235 }
1236 let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1237 let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1238 for row in rows.clone() {
1239 let start = alpha.len();
1240 match &blurred {
1241 Some(blurred) => {
1242 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1243 blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1244 }
1245 None => alpha.resize(start + columns.len(), 0),
1246 }
1247 let stride = pixmap.width() as usize;
1248 let row = &mask.data()[row as usize * stride..];
1249 let covered = &row[columns.start as usize..columns.end as usize];
1250 for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1251 *value = mul(255 - *value, covered);
1252 }
1253 }
1254 let (width, height) = (columns.len() as u32, rows.len() as u32);
1255 let (x, y) = (columns.start as i32, rows.start as i32);
1256 blend_mask(pixmap, x, y, width, height, &alpha, color);
1257 }
1258
1259 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1262 let (area, corners) = self.box_shape(rect, style)?;
1263 let mut path = PathBuilder::new();
1264 rounded_rect(&mut path, area, corners);
1265 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1266 let (rule, at) = (FillRule::Winding, Transform::identity());
1267 mask.fill_path(&path.finish()?, rule, true, at);
1268 Some(mask)
1269 }
1270
1271 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1276 let Grid {
1277 scale, left, top, ..
1278 } = self.grid;
1279 let origin = text.origin();
1280 let x = origin.x * scale - left;
1281 for run in text.runs() {
1282 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1284 if baseline + run.line_height * scale < 0.0
1285 || baseline - run.line_height * scale > pixmap.height() as f32
1286 {
1287 continue;
1288 }
1289 let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1291 true => text.link_hover_color().or(span.color),
1292 false => span.color,
1293 };
1294 for glyph in run.glyphs.iter() {
1295 let span = text.span(run.line_i, glyph);
1296 let color = text.selected_color(run.line_i, glyph);
1297 let color = color.or_else(|| span.and_then(|span| span_color(span, glyph)));
1298 let color = color.unwrap_or(text.color());
1299 if color.a == 0 {
1300 continue;
1301 }
1302 let physical = glyph.physical((x, baseline), scale);
1303 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1304 continue;
1305 };
1306 let left = physical.x + image.placement.left;
1307 let top = physical.y - image.placement.top;
1308 let (width, height) = (image.placement.width, image.placement.height);
1309 match image.content {
1310 SwashContent::Mask => {
1311 blend_mask(pixmap, left, top, width, height, &image.data, color);
1312 }
1313 SwashContent::Color => {
1314 let premultiplied = is_color_outline(image);
1315 let rgba = (image.data.as_slice(), premultiplied);
1316 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1317 }
1318 SwashContent::SubpixelMask => {}
1320 }
1321 }
1322 let origin = text.origin().x;
1323 let own = (text.underline(), text.strikethrough());
1324 if own != (false, false) {
1325 self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1326 }
1327 let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1331 text.span(run.line_i, a),
1332 text.span(run.line_i, b),
1333 ) {
1334 (Some(a), Some(b)) => std::ptr::eq(a, b),
1335 (a, b) => a.is_none() && b.is_none(),
1336 };
1337 for glyphs in run.glyphs.chunk_by(same_span) {
1338 let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1339 continue;
1340 };
1341 let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1342 let lines = (span.underline || lit, span.strikethrough);
1343 if lines != (false, false) {
1344 let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1345 self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1346 }
1347 }
1348 }
1349 }
1350
1351 fn decorations(
1355 &mut self,
1356 pixmap: &mut PixmapMut<'_>,
1357 origin: f32,
1358 glyphs: &[LayoutGlyph],
1359 baseline: f32,
1360 lines: (bool, bool),
1361 color: Color,
1362 ) {
1363 let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1364 (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1365 };
1366 for glyphs in glyphs.chunk_by(same_font) {
1367 self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1368 }
1369 }
1370
1371 fn font_decorations(
1377 &mut self,
1378 pixmap: &mut PixmapMut<'_>,
1379 origin: f32,
1380 glyphs: &[LayoutGlyph],
1381 baseline: f32,
1382 (underline, strikethrough): (bool, bool),
1383 color: Color,
1384 ) {
1385 let Some(first) = glyphs.first() else {
1386 return;
1387 };
1388 let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1389 return;
1390 };
1391 let metrics = font.metrics();
1392 let em = f32::from(metrics.units_per_em);
1393 if em == 0.0 {
1394 return;
1395 }
1396 let Grid { scale, left, .. } = self.grid;
1397 let (start, end) = glyphs
1398 .iter()
1399 .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1400 (start.min(glyph.x), end.max(glyph.x + glyph.w))
1401 });
1402 let x0 = ((origin + start) * scale).round() - left;
1403 let x1 = ((origin + end) * scale).round() - left;
1404 let size = first.font_size * scale;
1405 let lines = [
1407 (underline, metrics.underline, -0.125),
1408 (strikethrough, metrics.strikeout, 0.3),
1409 ];
1410 for (on, decoration, offset) in lines {
1411 if !on {
1412 continue;
1413 }
1414 let (offset, thickness) =
1415 decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1416 let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1418 let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1419 if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1420 let mut path = PathBuilder::new();
1421 path.push_rect(area);
1422 fill(pixmap, path, color, FillRule::Winding);
1423 }
1424 }
1425 }
1426
1427 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1429 let Some(area) = self.grid.rect(input.area) else {
1430 return;
1431 };
1432 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1433 painter.input_contents(layer, input);
1434 });
1435 }
1436
1437 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1440 let color = input.text.color();
1441 self.selection(pixmap, input.selection, input.selection_color);
1442 self.text(pixmap, &input.text);
1443 for line in input.underline {
1444 if let Some(area) = self.grid.rect(*line) {
1445 let mut path = PathBuilder::new();
1446 path.push_rect(area);
1447 fill(pixmap, path, color, FillRule::Winding);
1448 }
1449 }
1450 if let Some(caret) = input.caret {
1451 let left = self.grid.x(caret.x);
1453 let right = self.grid.x(caret.right()).max(left + 1.0);
1454 if let Some(area) = tiny_skia::Rect::from_ltrb(
1455 left,
1456 self.grid.y(caret.y),
1457 right,
1458 self.grid.y(caret.bottom()),
1459 ) {
1460 let mut path = PathBuilder::new();
1461 path.push_rect(area);
1462 fill(pixmap, path, color, FillRule::Winding);
1463 }
1464 }
1465 }
1466
1467 fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], tint: Color) {
1469 for span in spans {
1470 if let Some(area) = self.grid.rect(*span) {
1471 let mut path = PathBuilder::new();
1472 path.push_rect(area);
1473 fill(pixmap, path, tint, FillRule::Winding);
1474 }
1475 }
1476 }
1477
1478 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1480 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1481 return;
1482 };
1483 match self.icons.image(image, (width, height), self.grid.scale) {
1484 Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1485 transition::blit(pixmap, (x, y), pixels);
1486 }
1487 Some(Drawn::One(pixels)) => {
1489 let paint = PixmapPaint {
1490 quality: FilterQuality::Bilinear,
1491 ..PixmapPaint::default()
1492 };
1493 let stretch = Transform::from_scale(
1494 width as f32 / pixels.width() as f32,
1495 height as f32 / pixels.height() as f32,
1496 )
1497 .post_translate(x as f32, y as f32);
1498 pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1499 }
1500 Some(Drawn::Two { from, to, t }) => {
1501 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1502 }
1503 None => {}
1504 }
1505 }
1506
1507 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1509 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1510 return;
1511 };
1512 let frame = capture.frame;
1513 let Some([left, top, part_width, part_height]) = frame.drawn_part(capture.crop) else {
1516 return;
1517 };
1518 let crop = capture.crop.and_then(|_| {
1519 let sides = [left, top, part_width, part_height].map(|side| side as i32);
1521 tiny_skia::IntRect::from_xywh(sides[0], sides[1], part_width, part_height)
1522 });
1523 let size = (width, height);
1524 if let Some(pixels) = self
1525 .icons
1526 .capture(capture.id, frame, size, capture.fit, crop)
1527 {
1528 draw_at(pixmap, x, y, pixels);
1529 }
1530 }
1531
1532 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1537 let Grid {
1538 scale, left, top, ..
1539 } = self.grid;
1540 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1541 let (x, y) = (
1542 (rect.x * scale).round() - left,
1543 (rect.y * scale).round() - top,
1544 );
1545 if !(width >= 1.0 && height >= 1.0) {
1546 return None;
1547 }
1548 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1549 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1551 }
1552
1553 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1555 let Grid {
1556 scale, left, top, ..
1557 } = self.grid;
1558 let side = (icon.rect.width * scale).round();
1559 if side.is_nan() || side < 1.0 {
1560 return;
1561 }
1562 let x = (icon.rect.x * scale).round() - left;
1563 let y = (icon.rect.y * scale).round() - top;
1564 let size = icon.rect.width.round() as u32;
1566 let theme_scale = scale.ceil().max(1.0) as u32;
1567 let sizes = (side as u32, size, theme_scale);
1568 let source = match icon.fallback {
1570 Some(fallback) if self.icons.get(icon.source, sizes, icon.tint).is_none() => fallback,
1571 _ => icon.source,
1572 };
1573 if let Some(image) = self.icons.get(source, sizes, icon.tint) {
1574 pixmap.draw_pixmap(
1575 x as i32,
1576 y as i32,
1577 image.as_ref(),
1578 &PixmapPaint::default(),
1579 Transform::identity(),
1580 None,
1581 );
1582 }
1583 }
1584}
1585
1586fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1588 let paint = PixmapPaint::default();
1589 pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1590}
1591
1592fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1594 area.right() > 0.0
1595 && area.bottom() > 0.0
1596 && area.left() < pixmap.width() as f32
1597 && area.top() < pixmap.height() as f32
1598}
1599
1600fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1601 let Some(path) = path.finish() else {
1602 return;
1603 };
1604 let mut paint = Paint::default();
1605 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1606 paint.anti_alias = true;
1607 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1608}
1609
1610type Corners = [f32; 4];
1612
1613fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
1618 let Some((on, off)) = fit_dash(length, on, off) else {
1619 return false;
1620 };
1621 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
1622 return false;
1623 };
1624 if let Some(dashes) = path.dash(&dash, 1.0) {
1625 all.push_path(&dashes);
1626 }
1627 true
1628}
1629
1630fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1634 const KAPPA: f32 = 0.552_284_8;
1637 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1638 let radius = corners[index];
1639 let k = radius * (1.0 - KAPPA);
1640 let points = match index {
1641 0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
1642 1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
1643 2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
1644 _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
1645 };
1646 points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
1647}
1648
1649fn spread_corners(corners: Corners, spread: f32) -> Corners {
1653 corners.map(|radius| {
1654 if spread > 0.0 && radius < spread {
1655 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
1656 } else {
1657 (radius + spread).max(0.0)
1658 }
1659 })
1660}
1661
1662fn fit(
1664 [top_left, top_right, bottom_right, bottom_left]: Corners,
1665 area: tiny_skia::Rect,
1666) -> Corners {
1667 let radii = Radii {
1668 top_left,
1669 top_right,
1670 bottom_right,
1671 bottom_left,
1672 };
1673 radii.fit(area.width(), area.height()).corners()
1674}
1675
1676fn inset(corners: Corners, by: f32) -> Corners {
1678 corners.map(|radius| (radius - by).max(0.0))
1679}
1680
1681fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1684 if corners.iter().all(|&radius| radius <= 0.0) {
1685 path.push_rect(rect);
1686 return;
1687 }
1688 let [.., start] = corner(rect, corners, 0);
1689 path.move_to(start.x, start.y);
1690 for index in [1, 2, 3, 0] {
1691 let [start, one, two, end] = corner(rect, corners, index);
1692 path.line_to(start.x, start.y);
1693 if corners[index] > 0.0 {
1694 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1695 }
1696 }
1697 path.close();
1698}
1699
1700fn mul(a: u8, b: u8) -> u8 {
1702 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1703}
1704
1705fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1707 let rest = 255 - source[3];
1708 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1709 *channel = value.saturating_add(mul(*channel, rest));
1710 }
1711}
1712
1713fn overlap(
1717 pixmap: &PixmapMut<'_>,
1718 left: i32,
1719 top: i32,
1720 width: u32,
1721 height: u32,
1722) -> Option<(usize, usize, usize, usize)> {
1723 let column_start = (-i64::from(left)).max(0);
1724 let row_start = (-i64::from(top)).max(0);
1725 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1726 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1727 (column_start < column_end && row_start < row_end).then_some((
1728 column_start as usize,
1729 column_end as usize,
1730 row_start as usize,
1731 row_end as usize,
1732 ))
1733}
1734
1735fn blend_mask(
1737 pixmap: &mut PixmapMut<'_>,
1738 left: i32,
1739 top: i32,
1740 width: u32,
1741 height: u32,
1742 mask: &[u8],
1743 color: Color,
1744) {
1745 if mask.len() < width as usize * height as usize {
1746 return;
1747 }
1748 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1749 else {
1750 return;
1751 };
1752 let stride = pixmap.width() as usize;
1753 let data = pixmap.data_mut();
1754 for row in rows..rows_end {
1755 for column in columns..columns_end {
1756 let coverage = mask[row * width as usize + column];
1757 if coverage == 0 {
1758 continue;
1759 }
1760 let alpha = mul(color.a, coverage);
1761 let source = [
1762 mul(color.r, alpha),
1763 mul(color.g, alpha),
1764 mul(color.b, alpha),
1765 alpha,
1766 ];
1767 let x = (i64::from(left) + column as i64) as usize;
1768 let y = (i64::from(top) + row as i64) as usize;
1769 over(data, (y * stride + x) * 4, source);
1770 }
1771 }
1772}
1773
1774const SAMPLES: usize = 8;
1776
1777struct BlurredBox {
1784 middle: (f32, f32),
1785 half: (f32, f32),
1786 corners: Corners,
1787 largest: f32,
1788 sigma: f32,
1789 whole: f32,
1792}
1793
1794impl BlurredBox {
1795 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1796 let step = 6.0 * sigma / SAMPLES as f32;
1797 let whole = (0..SAMPLES)
1798 .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
1799 .sum();
1800 BlurredBox {
1801 whole,
1802 middle: (
1803 (shape.left() + shape.right()) / 2.0,
1804 (shape.top() + shape.bottom()) / 2.0,
1805 ),
1806 half: (shape.width() / 2.0, shape.height() / 2.0),
1807 corners,
1808 largest: corners.into_iter().fold(0.0, f32::max),
1809 sigma,
1810 }
1811 }
1812
1813 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1816 let y = y - self.middle.1;
1817 let (half_width, half_height) = self.half;
1818 let reach = 3.0 * self.sigma;
1819 let down = self.along(y, half_height);
1820 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1821 let rows = if clear_of_corners {
1822 [(0.0, 0.0, 0.0); SAMPLES]
1823 } else {
1824 self.rows_near(y)
1825 };
1826 for x in xs {
1827 let x = x - self.middle.0;
1828 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1829 self.along(x, half_width) * down
1830 } else {
1831 let sum: f32 = rows
1832 .iter()
1833 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1834 .sum();
1835 (sum / self.whole).clamp(0.0, 1.0)
1836 };
1837 mask.push((coverage * 255.0).round() as u8);
1838 }
1839 }
1840
1841 fn along(&self, p: f32, half: f32) -> f32 {
1843 self.between(p, half, half)
1844 }
1845
1846 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1849 let reach = 3.0 * self.sigma;
1850 if -(left - reach) <= p && p <= right - reach {
1851 return 1.0;
1852 }
1853 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1854 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1855 }
1856
1857 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1861 let (half_width, half_height) = self.half;
1862 let reach = 3.0 * self.sigma;
1863 let start = (y - half_height).clamp(-reach, reach);
1864 let end = (y + half_height).clamp(-reach, reach);
1865 let step = (end - start) / SAMPLES as f32;
1866 std::array::from_fn(|sample| {
1867 let offset = start + step * (sample as f32 + 0.5);
1868 let row = y - offset;
1871 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1872 let (left, right) = if row < 0.0 {
1873 (top_left, top_right)
1874 } else {
1875 (bottom_left, bottom_right)
1876 };
1877 let span = |radius: f32| {
1878 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1879 half_width - radius
1880 + (radius * radius - into_corner * into_corner)
1881 .max(0.0)
1882 .sqrt()
1883 };
1884 (span(left), span(right), gaussian(offset, self.sigma) * step)
1885 })
1886 }
1887}
1888
1889fn gaussian(x: f32, sigma: f32) -> f32 {
1891 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1892 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1893}
1894
1895fn erf(x: f32) -> f32 {
1898 let a = x.abs();
1899 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1900 let d = d * d;
1901 (1.0 - 1.0 / (d * d)).copysign(x)
1902}
1903
1904fn is_color_outline(image: &SwashImage) -> bool {
1911 format!("{:?}", image.source).starts_with("ColorOutline")
1912}
1913
1914fn blend_rgba(
1917 pixmap: &mut PixmapMut<'_>,
1918 left: i32,
1919 top: i32,
1920 width: u32,
1921 height: u32,
1922 (rgba, premultiplied): (&[u8], bool),
1923 opacity: u8,
1924) {
1925 if rgba.len() < width as usize * height as usize * 4 {
1926 return;
1927 }
1928 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1929 else {
1930 return;
1931 };
1932 let stride = pixmap.width() as usize;
1933 let data = pixmap.data_mut();
1934 for row in rows..rows_end {
1935 for column in columns..columns_end {
1936 let index = (row * width as usize + column) * 4;
1937 let alpha = mul(rgba[index + 3], opacity);
1938 if alpha == 0 {
1939 continue;
1940 }
1941 let factor = if premultiplied { opacity } else { alpha };
1944 let source = [
1945 mul(rgba[index], factor),
1946 mul(rgba[index + 1], factor),
1947 mul(rgba[index + 2], factor),
1948 alpha,
1949 ];
1950 let x = (i64::from(left) + column as i64) as usize;
1951 let y = (i64::from(top) + row as i64) as usize;
1952 over(data, (y * stride + x) * 4, source);
1953 }
1954 }
1955}
1956
1957fn keep_near(
1960 kept: &mut PathBuilder,
1961 contour: &[PathSegment],
1962 [left, top, right, bottom]: [f32; 4],
1963) {
1964 let (mut low, mut high) = (
1965 (f32::INFINITY, f32::INFINITY),
1966 (f32::NEG_INFINITY, f32::NEG_INFINITY),
1967 );
1968 let points = contour.iter().flat_map(|segment| match *segment {
1969 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1970 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1971 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1972 PathSegment::Close => [None; 3],
1973 });
1974 for point in points.flatten() {
1975 low = (low.0.min(point.x), low.1.min(point.y));
1976 high = (high.0.max(point.x), high.1.max(point.y));
1977 }
1978 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1979 return;
1980 }
1981 for segment in contour {
1982 match *segment {
1983 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1984 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1985 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1986 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1987 PathSegment::Close => kept.close(),
1988 }
1989 }
1990}
1991
1992pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1997 let period = on + off;
1998 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1999 return None;
2000 }
2001 let count = (perimeter / period).round().max(1.0);
2002 let stretch = perimeter / (count * period);
2003 Some((on * stretch, off * stretch))
2004}
2005
2006pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
2012 let edges = [area.left(), area.top(), area.right(), area.bottom()];
2013 if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
2014 return false;
2015 }
2016 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2017 let [left, top, right, bottom] = [
2018 area.left().clamp(0.0, width),
2019 area.top().clamp(0.0, height),
2020 area.right().clamp(0.0, width),
2021 area.bottom().clamp(0.0, height),
2022 ]
2023 .map(|edge| edge as usize);
2024 let stride = pixmap.width() as usize * 4;
2025 let pixel = [color.r, color.g, color.b, 255];
2026 for row in pixmap
2027 .data_mut()
2028 .chunks_exact_mut(stride)
2029 .take(bottom)
2030 .skip(top)
2031 {
2032 row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
2033 }
2034 true
2035}