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_icons(&self) -> usize {
165 self.icons.cached()
166 }
167
168 #[cfg(test)]
170 pub(crate) fn rasterized_icons(&self) -> usize {
171 self.icons.rasterized()
172 }
173
174 pub fn forget_captures(&mut self, gone: &[u64]) {
178 self.icons.forget_captures(gone);
179 }
180
181 pub fn decode_off_thread(&mut self) {
194 self.icons.decode_off_thread();
195 }
196
197 pub fn decoding(&self) -> bool {
200 self.icons.decoding()
201 }
202
203 pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
207 self.icons.wake_when_decoded(Box::new(wake));
208 }
209
210 pub fn waits_for_pictures(&self) -> bool {
213 self.icons.waited()
214 }
215
216 pub fn take_decoded(&mut self) -> Vec<u64> {
222 self.icons.take_decoded()
223 }
224
225 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
230 self.icons.next_frame(now)
231 }
232
233 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
239 self.icons.advance(now)
240 }
241
242 #[cfg(test)]
244 pub(crate) fn decoded_off_thread(&self) -> usize {
245 self.icons.worker_work().0
246 }
247
248 #[cfg(test)]
250 pub(crate) fn decoder_running(&self) -> bool {
251 self.icons.worker_work().1
252 }
253
254 #[cfg(test)]
256 pub(crate) fn cached_captures(&self) -> usize {
257 self.icons.captures()
258 }
259
260 pub fn draw(
278 &mut self,
279 view: &WindowView<'_>,
280 damage: &[Rect],
281 text: &mut TextSystem,
282 history: &mut DamageHistory,
283 canvas: Canvas<'_>,
284 ) -> Result<Vec<PixelRect>, CanvasError> {
285 let Canvas {
286 pixels,
287 width,
288 height,
289 scale,
290 format,
291 age,
292 } = canvas;
293 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
294 || !(scale.is_finite() && scale > 0.0)
295 {
296 return Err(CanvasError {
297 width,
298 height,
299 scale,
300 bytes: pixels.len(),
301 });
302 }
303 self.icons.start_frame(history.id());
304 let plan = history.plan(damage, scale, width, height, age);
305 let mut tiles: Vec<(u32, u32)> = Vec::new();
306 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
307 for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
308 tiles
309 .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
310 }
311 }
312 tiles.sort_unstable();
313 tiles.dedup();
314 let mut casts = HashMap::new();
315 let mut fonts = text.font_system();
316 for &(row, column) in &tiles {
317 self.icons.start_tile((row, column));
318 let (x, y) = (column * TILE, row * TILE);
319 let size = (width.saturating_sub(x), height.saturating_sub(y));
320 let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
321 self.scratch.clear();
322 self.scratch.resize(area.area() as usize * 4, 0);
323 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
324 else {
325 continue;
326 };
327 let mut painter = Painter {
328 grid: Grid {
329 scale,
330 zoom: 1.0,
331 linear: Affine {
332 sx: 1.0,
333 ky: 0.0,
334 kx: 0.0,
335 sy: 1.0,
336 tx: 0.0,
337 ty: 0.0,
338 },
339 window: view.size(),
340 width,
341 height,
342 left: area.x as f32,
343 top: area.y as f32,
344 },
345 glyphs: &mut self.glyphs,
346 icons: &mut self.icons,
347 fonts: &mut fonts,
348 work: &mut self.work,
349 casts: &mut casts,
350 };
351 painter.node(&mut pixmap, view.root());
352 copy(&self.scratch, area, pixels, width, format);
353 }
354 self.icons.repainted(&tiles);
355 self.icons.end_frame();
356 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
357 self.glyphs.image_cache.clear();
358 self.glyphs.outline_command_cache.clear();
359 }
360 Ok(plan.report)
361 }
362}
363
364#[derive(Clone, Copy, Debug, PartialEq)]
367pub struct CanvasError {
368 pub width: u32,
370 pub height: u32,
372 pub scale: f32,
374 pub bytes: usize,
376}
377
378impl std::fmt::Display for CanvasError {
379 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380 write!(
381 f,
382 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
383 self.width,
384 self.height,
385 self.scale,
386 u64::from(self.width) * u64::from(self.height) * 4,
387 self.bytes
388 )
389 }
390}
391
392impl std::error::Error for CanvasError {}
393
394impl Default for Renderer {
395 fn default() -> Self {
396 Self::new()
397 }
398}
399
400fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
402 let stride = width as usize * 4;
403 let row_bytes = area.width as usize * 4;
404 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
405 let start = (area.y as usize + row) * stride + area.x as usize * 4;
406 let target = &mut pixels[start..start + row_bytes];
407 match format {
408 PixelFormat::Abgr8888 => target.copy_from_slice(source),
409 PixelFormat::Argb8888 => {
410 let (to, _) = target.as_chunks_mut::<4>();
411 let (from, _) = source.as_chunks::<4>();
412 for (to, from) in to.iter_mut().zip(from) {
415 let pixel = u32::from_le_bytes(*from);
416 *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
417 }
418 }
419 }
420 }
421}
422
423#[derive(Clone, Copy)]
425struct Grid {
426 scale: f32,
428 zoom: f32,
431 linear: Affine,
434 window: Size,
436 width: u32,
438 height: u32,
439 left: f32,
441 top: f32,
442}
443
444impl Grid {
445 fn x(&self, x: f32) -> f32 {
448 let pixel = if x >= self.window.width {
449 self.width as f32
450 } else {
451 (x * self.scale).round()
452 };
453 pixel - self.left
454 }
455
456 fn y(&self, y: f32) -> f32 {
458 let pixel = if y >= self.window.height {
459 self.height as f32
460 } else {
461 (y * self.scale).round()
462 };
463 pixel - self.top
464 }
465
466 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
470 if !(rect.width > 0.0 && rect.height > 0.0) {
471 return None;
472 }
473 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
475 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
476 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
477 let bottom =
478 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
479 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
480 }
481
482 fn moved(&self, x: u32, y: u32) -> Grid {
484 Grid {
485 left: self.left + x as f32,
486 top: self.top + y as f32,
487 ..*self
488 }
489 }
490
491 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
494 tiny_skia::Rect::from_ltrb(
495 self.x(rect.x),
496 self.y(rect.y),
497 self.x(rect.right()),
498 self.y(rect.bottom()),
499 )
500 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
501 }
502}
503
504struct Painter<'a> {
506 grid: Grid,
507 glyphs: &'a mut SwashCache,
508 icons: &'a mut Icons,
509 fonts: &'a mut FontSystem,
510 work: &'a mut Work,
511 casts: &'a mut HashMap<CastKey, effects::Cast>,
513}
514
515type CastKey = (String, i64, i64);
518
519impl Painter<'_> {
520 fn on(&mut self, grid: Grid) -> Painter<'_> {
522 Painter {
523 grid,
524 glyphs: &mut *self.glyphs,
525 icons: &mut *self.icons,
526 fonts: &mut *self.fonts,
527 work: &mut *self.work,
528 casts: &mut *self.casts,
529 }
530 }
531
532 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
537 let Some((x, y, width, height)) =
539 self
540 .grid
541 .cover(node.bounds(), pixmap.width(), pixmap.height())
542 else {
543 return;
544 };
545 let style = node.style();
546 let opacity = style.opacity.unwrap_or(1.0);
547 let opacity = if opacity.is_nan() {
548 1.0
549 } else {
550 opacity.clamp(0.0, 1.0)
551 };
552 if opacity == 0.0 {
553 return;
554 }
555 let shadow = effects::cast_by_content(&style);
556 if let Some(transform) = node.transform() {
557 self.transformed(pixmap, node, &style, transform, opacity);
558 } else if opacity < 1.0 || style.mask.is_some() || shadow.is_some() {
559 let Some(mut layer) = Pixmap::new(width, height) else {
561 return;
562 };
563 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
564 let mut inner = self.on(self.grid.moved(x, y));
565 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow);
566 let paint = PixmapPaint {
567 opacity,
568 ..PixmapPaint::default()
569 };
570 let (x, y) = (x as i32, y as i32);
571 pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
572 } else {
573 self.node_contents(pixmap, node, &style);
574 }
575 }
576
577 fn layer_contents(
581 &mut self,
582 layer: &mut PixmapMut<'_>,
583 node: NodeView<'_>,
584 style: &Style,
585 shadow: Option<Shadow>,
586 ) {
587 self.node_contents(layer, node, style);
588 if let Some(mask) = &style.mask {
589 self.mask(layer, node.rect(), mask);
590 }
591 if let Some(shadow) = shadow {
592 self.content_shadow(layer, node, &shadow);
593 }
594 }
595
596 fn transformed(
603 &mut self,
604 pixmap: &mut PixmapMut<'_>,
605 node: NodeView<'_>,
606 style: &Style,
607 transform: Affine,
608 opacity: f32,
609 ) {
610 let Affine {
611 sx,
612 ky,
613 kx,
614 sy,
615 tx,
616 ty,
617 } = transform;
618 let Grid {
619 scale, left, top, ..
620 } = self.grid;
621 let outer = self.grid.linear;
622 let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0)
623 .pre_concat(Transform::from_row(sx, ky, kx, sy, 0.0, 0.0));
624 let linear = Affine {
625 sx: linear.sx,
626 ky: linear.ky,
627 kx: linear.kx,
628 sy: linear.sy,
629 tx: 0.0,
630 ty: 0.0,
631 };
632 let zoom = linear.layer_zoom();
633 let layer_scale = scale / self.grid.zoom * zoom;
634 let device = Transform::from_scale(scale, scale)
636 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
637 .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
638 let to_pixmap = device.post_translate(-left, -top);
639 let Some(back) = to_pixmap.invert() else {
640 return;
641 };
642 let inner = node.inner_bounds();
643 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
644 .and_then(|rect| rect.transform(back));
645 let drawn = tiny_skia::Rect::from_xywh(
646 inner.x * layer_scale,
647 inner.y * layer_scale,
648 inner.width * layer_scale,
649 inner.height * layer_scale,
650 );
651 let Some(area) = shown
652 .zip(drawn)
653 .and_then(|(shown, drawn)| shown.intersect(&drawn))
654 .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
655 .and_then(|area| area.round_out())
656 else {
657 return;
658 };
659 let pixels = u64::from(area.width()) * u64::from(area.height());
660 if pixels > LAYER_LIMIT {
661 tracing::debug!(
662 "{} is transformed into a layer too large to draw",
663 node.path()
664 );
665 return;
666 }
667 let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
668 return;
669 };
670 self.work.layer_pixels += pixels;
671 let (x, y) = (area.x() as f32, area.y() as f32);
672 let (width, height) = if zoom == self.grid.zoom {
673 (self.grid.width, self.grid.height)
674 } else {
675 let window = self.grid.window;
677 (
678 (window.width * layer_scale).round() as u32,
679 (window.height * layer_scale).round() as u32,
680 )
681 };
682 let mut inner = self.on(Grid {
683 scale: layer_scale,
684 zoom,
685 linear,
686 width,
687 height,
688 left: x,
689 top: y,
690 ..self.grid
691 });
692 let shadow = effects::cast_by_content(style);
693 inner.layer_contents(&mut layer.as_mut(), node, style, shadow);
694 let paint = PixmapPaint {
695 opacity,
696 quality: FilterQuality::Bilinear,
697 ..PixmapPaint::default()
698 };
699 pixmap.draw_pixmap(
700 0,
701 0,
702 layer.as_ref(),
703 &paint,
704 to_pixmap.pre_translate(x, y),
705 None,
706 );
707 }
708
709 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
710 self.work.nodes += 1;
711 let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
714 if let Some(shadow) = style.shadow.filter(outside) {
715 self.shadow(pixmap, node.rect(), style, &shadow);
716 }
717 self.draw_box(pixmap, node.rect(), style);
718 match node.content() {
719 Content::Text(text) => {
720 self.selection(pixmap, &text.selection(), text.color());
721 self.text(pixmap, &text);
722 }
723 Content::Icon(icon) => self.icon(pixmap, &icon),
724 Content::Image(image) => self.image(pixmap, &image),
725 Content::Capture(capture) => self.capture(pixmap, &capture),
726 Content::Input(input) => self.input(pixmap, &input),
727 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
728 Content::None => {}
729 }
730 if node.clips() {
731 self.clipped_children(pixmap, node, style);
732 } else {
733 for child in node.children() {
734 self.node(pixmap, child);
735 }
736 }
737 }
738
739 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
744 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
745 return;
746 };
747 let width = self.border_width(style);
748 let Some(inside) = tiny_skia::Rect::from_ltrb(
749 area.left() + width,
750 area.top() + width,
751 area.right() - width,
752 area.bottom() - width,
753 ) else {
754 return;
755 };
756 let corners = inset(corners, width);
757 self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
758 for child in node.children() {
759 painter.node(layer, child);
760 }
761 for (handle, bar) in node.scroll_bars() {
763 painter.draw_box(layer, handle, &bar);
764 }
765 });
766 }
767
768 fn through_mask(
771 &mut self,
772 pixmap: &mut PixmapMut<'_>,
773 cover: Rect,
774 (shape, corners): (tiny_skia::Rect, Corners),
775 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
776 ) {
777 if !visible(pixmap, shape) {
778 return;
779 }
780 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
781 Mask::new(pixmap.width(), pixmap.height()),
782 self.grid.cover(cover, pixmap.width(), pixmap.height()),
783 ) else {
784 return;
785 };
786 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
787 return;
788 };
789 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
790 let mut inner = self.on(self.grid.moved(x, y));
791 draw(&mut inner, &mut layer.as_mut());
792 let mut path = PathBuilder::new();
793 rounded_rect(&mut path, shape, corners);
794 let Some(path) = path.finish() else {
795 return;
796 };
797 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
798 pixmap.draw_pixmap(
799 x as i32,
800 y as i32,
801 layer.as_ref(),
802 &PixmapPaint::default(),
803 Transform::identity(),
804 Some(&mask),
805 );
806 }
807
808 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
812 let area = self.grid.rect(rect)?;
813 let corners = style.radius.unwrap_or_default().corners();
814 let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
815 Some((area, corners))
816 }
817
818 fn border_width(&self, style: &Style) -> f32 {
821 let Some(border) = style.border else {
822 return 0.0;
823 };
824 let width = (border.width * self.grid.scale).floor();
825 if border.width > 0.0 {
826 width.max(1.0)
827 } else {
828 width.max(0.0)
829 }
830 }
831
832 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
835 let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
836 if style.background.is_none()
837 && style.gradient.is_none()
838 && style.border.is_none()
839 && inset_shadow.is_none()
840 {
841 return;
842 }
843 let Some((area, corners)) = self.box_shape(rect, style) else {
844 return;
845 };
846 if !visible(pixmap, area) {
847 return;
848 }
849
850 if let Some(color) = style.background
851 && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
852 {
853 let mut path = PathBuilder::new();
854 rounded_rect(&mut path, area, corners);
855 fill(pixmap, path, color, FillRule::Winding);
856 }
857 if let Some(gradient) = style.gradient {
858 let mut path = PathBuilder::new();
859 rounded_rect(&mut path, area, corners);
860 let size = (pixmap.width(), pixmap.height());
861 if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
862 ramp.fill(pixmap, &path);
863 }
864 }
865 if let Some(shadow) = inset_shadow {
866 self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
867 }
868 if let Some(border) = style.border {
869 let width = self.border_width(style);
870 let dashed = width >= 1.0
871 && style.border_dash.is_some_and(|dash| {
872 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
873 });
874
875 if width >= 1.0 && !dashed {
876 let mut path = PathBuilder::new();
878 rounded_rect(&mut path, area, corners);
879 if let Some(inner) = tiny_skia::Rect::from_ltrb(
880 area.left() + width,
881 area.top() + width,
882 area.right() - width,
883 area.bottom() - width,
884 ) {
885 rounded_rect(&mut path, inner, inset(corners, width));
886 }
887 fill(pixmap, path, border.color, FillRule::EvenOdd);
888 }
889 }
890 }
891
892 fn dashed_border(
898 &self,
899 pixmap: &mut PixmapMut<'_>,
900 (area, corners): (tiny_skia::Rect, Corners),
901 width: f32,
902 color: Color,
903 (on, off): (f32, f32),
904 ) -> bool {
905 let Grid {
906 scale, left, top, ..
907 } = self.grid;
908 let half = width / 2.0;
909 let Some(middle) = tiny_skia::Rect::from_ltrb(
910 area.left() + left + half,
911 area.top() + top + half,
912 area.right() + left - half,
913 area.bottom() + top - half,
914 ) else {
915 return false;
916 };
917 let corners = inset(corners, half);
918 let (on, off) = (on * scale, off * scale);
919 let mut all = PathBuilder::new();
920 let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
921 if square.is_empty() {
922 let rounding: f32 = corners
925 .iter()
926 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
927 .sum();
928 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
929 let mut path = PathBuilder::new();
930 rounded_rect(&mut path, middle, corners);
931 if !dash_into(&mut all, path, perimeter, on, off) {
932 return false;
933 }
934 } else {
935 for (at, &from) in square.iter().enumerate() {
938 let to = square[(at + 1) % square.len()];
939 let steps = (to + 4 - from - 1) % 4 + 1;
940 let [.., mut was] = corner(middle, corners, from);
941 let mut path = PathBuilder::new();
942 path.move_to(was.x, was.y);
943 let mut length = 0.0;
944 for index in (from + 1..=from + steps).map(|index| index % 4) {
945 let [start, one, two, end] = corner(middle, corners, index);
946 path.line_to(start.x, start.y);
947 length += was.distance(start);
948 if corners[index] > 0.0 {
949 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
950 length += std::f32::consts::FRAC_PI_2 * corners[index];
951 }
952 was = end;
953 }
954 if !dash_into(&mut all, path, length, on, off) {
955 return false;
956 }
957 }
958 if on > 0.0 {
962 const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
964 for &index in &square {
965 let [point, ..] = corner(middle, corners, index);
966 let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
967 all.move_to(point.x - half * ax, point.y - half * ay);
968 all.line_to(point.x, point.y);
969 all.line_to(point.x + half * bx, point.y + half * by);
970 }
971 }
972 }
973 let Some(dashes) = all.finish() else {
974 return true;
975 };
976 let reach = 2.0 * width + 1.0;
981 let near = [
982 left - reach,
983 top - reach,
984 left + pixmap.width() as f32 + reach,
985 top + pixmap.height() as f32 + reach,
986 ];
987 let mut kept = PathBuilder::new();
988 let mut contour = Vec::new();
989 for segment in dashes.segments() {
990 if matches!(segment, PathSegment::MoveTo(_)) {
991 keep_near(&mut kept, &contour, near);
992 contour.clear();
993 }
994 contour.push(segment);
995 }
996 keep_near(&mut kept, &contour, near);
997 let Some(kept) = kept.finish() else {
998 return true;
999 };
1000 let stroke = Stroke {
1001 width,
1002 line_cap: if on == 0.0 {
1004 LineCap::Round
1005 } else {
1006 LineCap::Butt
1007 },
1008 line_join: LineJoin::Miter,
1009 ..Stroke::default()
1010 };
1011 let mut paint = Paint::default();
1012 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1013 paint.anti_alias = true;
1014 let moved = Transform::from_translate(-left, -top);
1015 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1016 true
1017 }
1018
1019 fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1024 let Grid {
1025 scale, left, top, ..
1026 } = self.grid;
1027 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1028 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1029 return;
1030 }
1031 let Some((area, corners)) = self.box_shape(rect, style) else {
1032 return;
1033 };
1034 let spread = shadow.spread * scale;
1036 let Some(shape) = tiny_skia::Rect::from_ltrb(
1037 area.left() + left + shadow.x * scale - spread,
1038 area.top() + top + shadow.y * scale - spread,
1039 area.right() + left + shadow.x * scale + spread,
1040 area.bottom() + top + shadow.y * scale + spread,
1041 ) else {
1042 return;
1043 };
1044 let corners = fit(spread_corners(corners, spread), shape);
1045 let cut = if shadow.cut_out {
1047 self.box_mask(pixmap, rect, style)
1048 } else {
1049 None
1050 };
1051 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1053 if sigma < 0.25 {
1054 let mut path = PathBuilder::new();
1055 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1056 return;
1057 };
1058 rounded_rect(&mut path, shape, corners);
1059 let Some(path) = path.finish() else {
1060 return;
1061 };
1062 let mut paint = Paint::default();
1063 let color = shadow.color;
1064 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1065 paint.anti_alias = true;
1066 let outside = cut.map(|mut cut| {
1067 cut.invert();
1068 cut
1069 });
1070 let (rule, at) = (FillRule::Winding, Transform::identity());
1071 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1072 return;
1073 }
1074 let reach = 3.0 * sigma;
1075 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1076 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1077 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1078 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1079 if columns.is_empty() || rows.is_empty() {
1080 return;
1081 }
1082 let blurred = BlurredBox::new(shape, corners, sigma);
1083 let mut mask = Vec::with_capacity(columns.len() * rows.len());
1084 for row in rows.clone() {
1085 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1086 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1087 }
1088 if let Some(cut) = cut {
1089 let stride = pixmap.width() as usize;
1090 let under = rows.clone().flat_map(|row| {
1091 columns
1092 .clone()
1093 .map(move |column| row as usize * stride + column as usize)
1094 });
1095 for (alpha, at) in mask.iter_mut().zip(under) {
1096 *alpha = mul(*alpha, 255 - cut.data()[at]);
1097 }
1098 }
1099 let width = columns.len() as u32;
1100 let height = rows.len() as u32;
1101 let (x, y) = (columns.start as i32, rows.start as i32);
1102 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1103 }
1104
1105 fn inset_shadow(
1110 &self,
1111 pixmap: &mut PixmapMut<'_>,
1112 (area, corners): (tiny_skia::Rect, Corners),
1113 border: f32,
1114 shadow: &Shadow,
1115 ) {
1116 let Grid {
1117 scale, left, top, ..
1118 } = self.grid;
1119 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1120 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1121 return;
1122 }
1123 let Some(inside) = tiny_skia::Rect::from_ltrb(
1124 area.left() + border,
1125 area.top() + border,
1126 area.right() - border,
1127 area.bottom() - border,
1128 ) else {
1129 return;
1130 };
1131 let inside_corners = inset(corners, border);
1132 if !visible(pixmap, inside) {
1133 return;
1134 }
1135 let mut path = PathBuilder::new();
1136 rounded_rect(&mut path, inside, inside_corners);
1137 let Some(path) = path.finish() else {
1138 return;
1139 };
1140 let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1142 let hole = tiny_skia::Rect::from_ltrb(
1143 inside.left() + left + x + spread,
1144 inside.top() + top + y + spread,
1145 inside.right() + left + x - spread,
1146 inside.bottom() + top + y - spread,
1147 );
1148 let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1149 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1150 let color = shadow.color;
1151 if sigma < 0.25 {
1152 let mut outside = None;
1153 if let Some((hole, corners)) = hole {
1154 let mut cut = PathBuilder::new();
1155 let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1156 return;
1157 };
1158 rounded_rect(&mut cut, moved, corners);
1159 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1160 return;
1161 };
1162 let (rule, at) = (FillRule::Winding, Transform::identity());
1163 let Some(cut) = cut.finish() else {
1164 return;
1165 };
1166 mask.fill_path(&cut, rule, true, at);
1167 mask.invert();
1168 outside = Some(mask);
1169 }
1170 let mut paint = Paint::default();
1171 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1172 paint.anti_alias = true;
1173 let (rule, at) = (FillRule::Winding, Transform::identity());
1174 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1175 return;
1176 }
1177 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1180 return;
1181 };
1182 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1183 let columns = inside.left().floor().max(0.0) as u32
1184 ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1185 let rows = inside.top().floor().max(0.0) as u32
1186 ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1187 if columns.is_empty() || rows.is_empty() {
1188 return;
1189 }
1190 let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1191 let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1192 for row in rows.clone() {
1193 let start = alpha.len();
1194 match &blurred {
1195 Some(blurred) => {
1196 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1197 blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1198 }
1199 None => alpha.resize(start + columns.len(), 0),
1200 }
1201 let stride = pixmap.width() as usize;
1202 let row = &mask.data()[row as usize * stride..];
1203 let covered = &row[columns.start as usize..columns.end as usize];
1204 for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1205 *value = mul(255 - *value, covered);
1206 }
1207 }
1208 let (width, height) = (columns.len() as u32, rows.len() as u32);
1209 let (x, y) = (columns.start as i32, rows.start as i32);
1210 blend_mask(pixmap, x, y, width, height, &alpha, color);
1211 }
1212
1213 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1216 let (area, corners) = self.box_shape(rect, style)?;
1217 let mut path = PathBuilder::new();
1218 rounded_rect(&mut path, area, corners);
1219 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1220 let (rule, at) = (FillRule::Winding, Transform::identity());
1221 mask.fill_path(&path.finish()?, rule, true, at);
1222 Some(mask)
1223 }
1224
1225 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1230 let Grid {
1231 scale, left, top, ..
1232 } = self.grid;
1233 let origin = text.origin();
1234 let x = origin.x * scale - left;
1235 for run in text.runs() {
1236 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1238 if baseline + run.line_height * scale < 0.0
1239 || baseline - run.line_height * scale > pixmap.height() as f32
1240 {
1241 continue;
1242 }
1243 let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1245 true => text.link_hover_color().or(span.color),
1246 false => span.color,
1247 };
1248 for glyph in run.glyphs.iter() {
1249 let span = text.span(run.line_i, glyph);
1250 let color = span.and_then(|span| span_color(span, glyph));
1251 let color = color.unwrap_or(text.color());
1252 if color.a == 0 {
1253 continue;
1254 }
1255 let physical = glyph.physical((x, baseline), scale);
1256 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1257 continue;
1258 };
1259 let left = physical.x + image.placement.left;
1260 let top = physical.y - image.placement.top;
1261 let (width, height) = (image.placement.width, image.placement.height);
1262 match image.content {
1263 SwashContent::Mask => {
1264 blend_mask(pixmap, left, top, width, height, &image.data, color);
1265 }
1266 SwashContent::Color => {
1267 let premultiplied = is_color_outline(image);
1268 let rgba = (image.data.as_slice(), premultiplied);
1269 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1270 }
1271 SwashContent::SubpixelMask => {}
1273 }
1274 }
1275 let origin = text.origin().x;
1276 let own = (text.underline(), text.strikethrough());
1277 if own != (false, false) {
1278 self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1279 }
1280 let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1284 text.span(run.line_i, a),
1285 text.span(run.line_i, b),
1286 ) {
1287 (Some(a), Some(b)) => std::ptr::eq(a, b),
1288 (a, b) => a.is_none() && b.is_none(),
1289 };
1290 for glyphs in run.glyphs.chunk_by(same_span) {
1291 let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1292 continue;
1293 };
1294 let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1295 let lines = (span.underline || lit, span.strikethrough);
1296 if lines != (false, false) {
1297 let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1298 self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1299 }
1300 }
1301 }
1302 }
1303
1304 fn decorations(
1308 &mut self,
1309 pixmap: &mut PixmapMut<'_>,
1310 origin: f32,
1311 glyphs: &[LayoutGlyph],
1312 baseline: f32,
1313 lines: (bool, bool),
1314 color: Color,
1315 ) {
1316 let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1317 (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1318 };
1319 for glyphs in glyphs.chunk_by(same_font) {
1320 self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1321 }
1322 }
1323
1324 fn font_decorations(
1330 &mut self,
1331 pixmap: &mut PixmapMut<'_>,
1332 origin: f32,
1333 glyphs: &[LayoutGlyph],
1334 baseline: f32,
1335 (underline, strikethrough): (bool, bool),
1336 color: Color,
1337 ) {
1338 let Some(first) = glyphs.first() else {
1339 return;
1340 };
1341 let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1342 return;
1343 };
1344 let metrics = font.metrics();
1345 let em = f32::from(metrics.units_per_em);
1346 if em == 0.0 {
1347 return;
1348 }
1349 let Grid { scale, left, .. } = self.grid;
1350 let (start, end) = glyphs
1351 .iter()
1352 .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1353 (start.min(glyph.x), end.max(glyph.x + glyph.w))
1354 });
1355 let x0 = ((origin + start) * scale).round() - left;
1356 let x1 = ((origin + end) * scale).round() - left;
1357 let size = first.font_size * scale;
1358 let lines = [
1360 (underline, metrics.underline, -0.125),
1361 (strikethrough, metrics.strikeout, 0.3),
1362 ];
1363 for (on, decoration, offset) in lines {
1364 if !on {
1365 continue;
1366 }
1367 let (offset, thickness) =
1368 decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1369 let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1371 let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1372 if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1373 let mut path = PathBuilder::new();
1374 path.push_rect(area);
1375 fill(pixmap, path, color, FillRule::Winding);
1376 }
1377 }
1378 }
1379
1380 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1382 let Some(area) = self.grid.rect(input.area) else {
1383 return;
1384 };
1385 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1386 painter.input_contents(layer, input);
1387 });
1388 }
1389
1390 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1393 let color = input.text.color();
1394 self.selection(pixmap, input.selection, color);
1395 self.text(pixmap, &input.text);
1396 for line in input.underline {
1397 if let Some(area) = self.grid.rect(*line) {
1398 let mut path = PathBuilder::new();
1399 path.push_rect(area);
1400 fill(pixmap, path, color, FillRule::Winding);
1401 }
1402 }
1403 if let Some(caret) = input.caret {
1404 let left = self.grid.x(caret.x);
1406 let right = self.grid.x(caret.right()).max(left + 1.0);
1407 if let Some(area) = tiny_skia::Rect::from_ltrb(
1408 left,
1409 self.grid.y(caret.y),
1410 right,
1411 self.grid.y(caret.bottom()),
1412 ) {
1413 let mut path = PathBuilder::new();
1414 path.push_rect(area);
1415 fill(pixmap, path, color, FillRule::Winding);
1416 }
1417 }
1418 }
1419
1420 fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], color: Color) {
1422 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1423 for span in spans {
1424 if let Some(area) = self.grid.rect(*span) {
1425 let mut path = PathBuilder::new();
1426 path.push_rect(area);
1427 fill(pixmap, path, tint, FillRule::Winding);
1428 }
1429 }
1430 }
1431
1432 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1434 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1435 return;
1436 };
1437 match self.icons.image(image, (width, height), self.grid.scale) {
1438 Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1439 transition::blit(pixmap, (x, y), pixels);
1440 }
1441 Some(Drawn::One(pixels)) => {
1443 let paint = PixmapPaint {
1444 quality: FilterQuality::Bilinear,
1445 ..PixmapPaint::default()
1446 };
1447 let stretch = Transform::from_scale(
1448 width as f32 / pixels.width() as f32,
1449 height as f32 / pixels.height() as f32,
1450 )
1451 .post_translate(x as f32, y as f32);
1452 pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1453 }
1454 Some(Drawn::Two { from, to, t }) => {
1455 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1456 }
1457 None => {}
1458 }
1459 }
1460
1461 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1463 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1464 return;
1465 };
1466 let frame = capture.frame;
1467 if let Some(pixels) = self
1468 .icons
1469 .capture(capture.id, frame, width, height, capture.fit)
1470 {
1471 draw_at(pixmap, x, y, pixels);
1472 }
1473 }
1474
1475 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1480 let Grid {
1481 scale, left, top, ..
1482 } = self.grid;
1483 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1484 let (x, y) = (
1485 (rect.x * scale).round() - left,
1486 (rect.y * scale).round() - top,
1487 );
1488 if !(width >= 1.0 && height >= 1.0) {
1489 return None;
1490 }
1491 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1492 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1494 }
1495
1496 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1498 let Grid {
1499 scale, left, top, ..
1500 } = self.grid;
1501 let side = (icon.rect.width * scale).round();
1502 if side.is_nan() || side < 1.0 {
1503 return;
1504 }
1505 let x = (icon.rect.x * scale).round() - left;
1506 let y = (icon.rect.y * scale).round() - top;
1507 let size = icon.rect.width.round() as u32;
1509 let theme_scale = scale.ceil().max(1.0) as u32;
1510 let sizes = (side as u32, size, theme_scale);
1511 let source = match icon.fallback {
1513 Some(fallback) if self.icons.get(icon.source, sizes, icon.tint).is_none() => fallback,
1514 _ => icon.source,
1515 };
1516 if let Some(image) = self.icons.get(source, sizes, icon.tint) {
1517 pixmap.draw_pixmap(
1518 x as i32,
1519 y as i32,
1520 image.as_ref(),
1521 &PixmapPaint::default(),
1522 Transform::identity(),
1523 None,
1524 );
1525 }
1526 }
1527}
1528
1529fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1531 let paint = PixmapPaint::default();
1532 pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1533}
1534
1535fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1537 area.right() > 0.0
1538 && area.bottom() > 0.0
1539 && area.left() < pixmap.width() as f32
1540 && area.top() < pixmap.height() as f32
1541}
1542
1543fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1544 let Some(path) = path.finish() else {
1545 return;
1546 };
1547 let mut paint = Paint::default();
1548 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1549 paint.anti_alias = true;
1550 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1551}
1552
1553type Corners = [f32; 4];
1555
1556fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
1561 let Some((on, off)) = fit_dash(length, on, off) else {
1562 return false;
1563 };
1564 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
1565 return false;
1566 };
1567 if let Some(dashes) = path.dash(&dash, 1.0) {
1568 all.push_path(&dashes);
1569 }
1570 true
1571}
1572
1573fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1577 const KAPPA: f32 = 0.552_284_8;
1580 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1581 let radius = corners[index];
1582 let k = radius * (1.0 - KAPPA);
1583 let points = match index {
1584 0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
1585 1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
1586 2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
1587 _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
1588 };
1589 points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
1590}
1591
1592fn spread_corners(corners: Corners, spread: f32) -> Corners {
1596 corners.map(|radius| {
1597 if spread > 0.0 && radius < spread {
1598 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
1599 } else {
1600 (radius + spread).max(0.0)
1601 }
1602 })
1603}
1604
1605fn fit(
1607 [top_left, top_right, bottom_right, bottom_left]: Corners,
1608 area: tiny_skia::Rect,
1609) -> Corners {
1610 let radii = Radii {
1611 top_left,
1612 top_right,
1613 bottom_right,
1614 bottom_left,
1615 };
1616 radii.fit(area.width(), area.height()).corners()
1617}
1618
1619fn inset(corners: Corners, by: f32) -> Corners {
1621 corners.map(|radius| (radius - by).max(0.0))
1622}
1623
1624fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1627 if corners.iter().all(|&radius| radius <= 0.0) {
1628 path.push_rect(rect);
1629 return;
1630 }
1631 let [.., start] = corner(rect, corners, 0);
1632 path.move_to(start.x, start.y);
1633 for index in [1, 2, 3, 0] {
1634 let [start, one, two, end] = corner(rect, corners, index);
1635 path.line_to(start.x, start.y);
1636 if corners[index] > 0.0 {
1637 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1638 }
1639 }
1640 path.close();
1641}
1642
1643fn mul(a: u8, b: u8) -> u8 {
1645 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1646}
1647
1648fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1650 let rest = 255 - source[3];
1651 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1652 *channel = value.saturating_add(mul(*channel, rest));
1653 }
1654}
1655
1656fn overlap(
1660 pixmap: &PixmapMut<'_>,
1661 left: i32,
1662 top: i32,
1663 width: u32,
1664 height: u32,
1665) -> Option<(usize, usize, usize, usize)> {
1666 let column_start = (-i64::from(left)).max(0);
1667 let row_start = (-i64::from(top)).max(0);
1668 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1669 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1670 (column_start < column_end && row_start < row_end).then_some((
1671 column_start as usize,
1672 column_end as usize,
1673 row_start as usize,
1674 row_end as usize,
1675 ))
1676}
1677
1678fn blend_mask(
1680 pixmap: &mut PixmapMut<'_>,
1681 left: i32,
1682 top: i32,
1683 width: u32,
1684 height: u32,
1685 mask: &[u8],
1686 color: Color,
1687) {
1688 if mask.len() < width as usize * height as usize {
1689 return;
1690 }
1691 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1692 else {
1693 return;
1694 };
1695 let stride = pixmap.width() as usize;
1696 let data = pixmap.data_mut();
1697 for row in rows..rows_end {
1698 for column in columns..columns_end {
1699 let coverage = mask[row * width as usize + column];
1700 if coverage == 0 {
1701 continue;
1702 }
1703 let alpha = mul(color.a, coverage);
1704 let source = [
1705 mul(color.r, alpha),
1706 mul(color.g, alpha),
1707 mul(color.b, alpha),
1708 alpha,
1709 ];
1710 let x = (i64::from(left) + column as i64) as usize;
1711 let y = (i64::from(top) + row as i64) as usize;
1712 over(data, (y * stride + x) * 4, source);
1713 }
1714 }
1715}
1716
1717const SAMPLES: usize = 8;
1719
1720struct BlurredBox {
1727 middle: (f32, f32),
1728 half: (f32, f32),
1729 corners: Corners,
1730 largest: f32,
1731 sigma: f32,
1732 whole: f32,
1735}
1736
1737impl BlurredBox {
1738 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1739 let step = 6.0 * sigma / SAMPLES as f32;
1740 let whole = (0..SAMPLES)
1741 .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
1742 .sum();
1743 BlurredBox {
1744 whole,
1745 middle: (
1746 (shape.left() + shape.right()) / 2.0,
1747 (shape.top() + shape.bottom()) / 2.0,
1748 ),
1749 half: (shape.width() / 2.0, shape.height() / 2.0),
1750 corners,
1751 largest: corners.into_iter().fold(0.0, f32::max),
1752 sigma,
1753 }
1754 }
1755
1756 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1759 let y = y - self.middle.1;
1760 let (half_width, half_height) = self.half;
1761 let reach = 3.0 * self.sigma;
1762 let down = self.along(y, half_height);
1763 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1764 let rows = if clear_of_corners {
1765 [(0.0, 0.0, 0.0); SAMPLES]
1766 } else {
1767 self.rows_near(y)
1768 };
1769 for x in xs {
1770 let x = x - self.middle.0;
1771 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1772 self.along(x, half_width) * down
1773 } else {
1774 let sum: f32 = rows
1775 .iter()
1776 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1777 .sum();
1778 (sum / self.whole).clamp(0.0, 1.0)
1779 };
1780 mask.push((coverage * 255.0).round() as u8);
1781 }
1782 }
1783
1784 fn along(&self, p: f32, half: f32) -> f32 {
1786 self.between(p, half, half)
1787 }
1788
1789 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1792 let reach = 3.0 * self.sigma;
1793 if -(left - reach) <= p && p <= right - reach {
1794 return 1.0;
1795 }
1796 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1797 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1798 }
1799
1800 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1804 let (half_width, half_height) = self.half;
1805 let reach = 3.0 * self.sigma;
1806 let start = (y - half_height).clamp(-reach, reach);
1807 let end = (y + half_height).clamp(-reach, reach);
1808 let step = (end - start) / SAMPLES as f32;
1809 std::array::from_fn(|sample| {
1810 let offset = start + step * (sample as f32 + 0.5);
1811 let row = y - offset;
1814 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1815 let (left, right) = if row < 0.0 {
1816 (top_left, top_right)
1817 } else {
1818 (bottom_left, bottom_right)
1819 };
1820 let span = |radius: f32| {
1821 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1822 half_width - radius
1823 + (radius * radius - into_corner * into_corner)
1824 .max(0.0)
1825 .sqrt()
1826 };
1827 (span(left), span(right), gaussian(offset, self.sigma) * step)
1828 })
1829 }
1830}
1831
1832fn gaussian(x: f32, sigma: f32) -> f32 {
1834 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1835 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1836}
1837
1838fn erf(x: f32) -> f32 {
1841 let a = x.abs();
1842 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1843 let d = d * d;
1844 (1.0 - 1.0 / (d * d)).copysign(x)
1845}
1846
1847fn is_color_outline(image: &SwashImage) -> bool {
1854 format!("{:?}", image.source).starts_with("ColorOutline")
1855}
1856
1857fn blend_rgba(
1860 pixmap: &mut PixmapMut<'_>,
1861 left: i32,
1862 top: i32,
1863 width: u32,
1864 height: u32,
1865 (rgba, premultiplied): (&[u8], bool),
1866 opacity: u8,
1867) {
1868 if rgba.len() < width as usize * height as usize * 4 {
1869 return;
1870 }
1871 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1872 else {
1873 return;
1874 };
1875 let stride = pixmap.width() as usize;
1876 let data = pixmap.data_mut();
1877 for row in rows..rows_end {
1878 for column in columns..columns_end {
1879 let index = (row * width as usize + column) * 4;
1880 let alpha = mul(rgba[index + 3], opacity);
1881 if alpha == 0 {
1882 continue;
1883 }
1884 let factor = if premultiplied { opacity } else { alpha };
1887 let source = [
1888 mul(rgba[index], factor),
1889 mul(rgba[index + 1], factor),
1890 mul(rgba[index + 2], factor),
1891 alpha,
1892 ];
1893 let x = (i64::from(left) + column as i64) as usize;
1894 let y = (i64::from(top) + row as i64) as usize;
1895 over(data, (y * stride + x) * 4, source);
1896 }
1897 }
1898}
1899
1900fn keep_near(
1903 kept: &mut PathBuilder,
1904 contour: &[PathSegment],
1905 [left, top, right, bottom]: [f32; 4],
1906) {
1907 let (mut low, mut high) = (
1908 (f32::INFINITY, f32::INFINITY),
1909 (f32::NEG_INFINITY, f32::NEG_INFINITY),
1910 );
1911 let points = contour.iter().flat_map(|segment| match *segment {
1912 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1913 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1914 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1915 PathSegment::Close => [None; 3],
1916 });
1917 for point in points.flatten() {
1918 low = (low.0.min(point.x), low.1.min(point.y));
1919 high = (high.0.max(point.x), high.1.max(point.y));
1920 }
1921 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1922 return;
1923 }
1924 for segment in contour {
1925 match *segment {
1926 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1927 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1928 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1929 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1930 PathSegment::Close => kept.close(),
1931 }
1932 }
1933}
1934
1935pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1940 let period = on + off;
1941 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1942 return None;
1943 }
1944 let count = (perimeter / period).round().max(1.0);
1945 let stretch = perimeter / (count * period);
1946 Some((on * stretch, off * stretch))
1947}
1948
1949pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
1955 let edges = [area.left(), area.top(), area.right(), area.bottom()];
1956 if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
1957 return false;
1958 }
1959 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
1960 let [left, top, right, bottom] = [
1961 area.left().clamp(0.0, width),
1962 area.top().clamp(0.0, height),
1963 area.right().clamp(0.0, width),
1964 area.bottom().clamp(0.0, height),
1965 ]
1966 .map(|edge| edge as usize);
1967 let stride = pixmap.width() as usize * 4;
1968 let pixel = [color.r, color.g, color.b, 255];
1969 for row in pixmap
1970 .data_mut()
1971 .chunks_exact_mut(stride)
1972 .take(bottom)
1973 .skip(top)
1974 {
1975 row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
1976 }
1977 true
1978}