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};
23
24mod canvas;
25mod effects;
26mod gradient;
27mod transition;
28
29const TILE: u32 = 64;
34
35const GLYPH_CACHE_LIMIT: usize = 2048;
38
39const LAYER_LIMIT: u64 = 1 << 22;
43
44const LAYER_MARGIN: f32 = 2.0;
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum PixelFormat {
52 Argb8888,
54 Abgr8888,
56}
57
58pub struct Canvas<'a> {
60 pub pixels: &'a mut [u8],
62 pub width: u32,
66 pub height: u32,
68 pub scale: f32,
70 pub format: PixelFormat,
72 pub age: &'a mut BufferAge,
74}
75
76pub struct Renderer {
79 glyphs: SwashCache,
80 icons: Icons,
81 scratch: Vec<u8>,
84 work: Work,
85}
86
87#[derive(Default)]
90#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
91struct Work {
92 layer_pixels: u64,
94 nodes: u64,
96 blurred: u64,
98 gradient_pixels: std::cell::Cell<u64>,
101}
102
103impl Renderer {
104 pub fn new() -> Renderer {
107 Renderer {
108 glyphs: SwashCache::new(),
109 icons: Icons::new(),
110 scratch: Vec::new(),
111 work: Work::default(),
112 }
113 }
114
115 #[cfg(test)]
117 pub(crate) fn image_lookups(&self) -> usize {
118 self.icons.lookups()
119 }
120
121 #[cfg(test)]
123 pub(crate) fn cached_glyphs(&self) -> usize {
124 self.glyphs.image_cache.len()
125 }
126
127 #[cfg(test)]
130 pub(crate) fn work(&self) -> (u64, u64, u64) {
131 (self.work.layer_pixels, self.work.nodes, self.work.blurred)
132 }
133
134 #[cfg(test)]
136 pub(crate) fn gradient_pixels(&self) -> u64 {
137 self.work.gradient_pixels.get()
138 }
139
140 #[cfg(test)]
143 pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
144 Renderer {
145 icons: Icons::with_themes(crate::theme::Themes::new(bases)),
146 ..Renderer::new()
147 }
148 }
149
150 pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
152 self.icons.set_theme(theme.into());
153 }
154
155 #[cfg(test)]
157 pub(crate) fn cached_icons(&self) -> usize {
158 self.icons.cached()
159 }
160
161 #[cfg(test)]
163 pub(crate) fn rasterized_icons(&self) -> usize {
164 self.icons.rasterized()
165 }
166
167 pub fn forget_captures(&mut self, gone: &[u64]) {
171 self.icons.forget_captures(gone);
172 }
173
174 pub fn decode_off_thread(&mut self) {
187 self.icons.decode_off_thread();
188 }
189
190 pub fn decoding(&self) -> bool {
193 self.icons.decoding()
194 }
195
196 pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
200 self.icons.wake_when_decoded(Box::new(wake));
201 }
202
203 pub fn waits_for_pictures(&self) -> bool {
206 self.icons.waited()
207 }
208
209 pub fn take_decoded(&mut self) -> Vec<u64> {
215 self.icons.take_decoded()
216 }
217
218 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
223 self.icons.next_frame(now)
224 }
225
226 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
232 self.icons.advance(now)
233 }
234
235 #[cfg(test)]
237 pub(crate) fn decoded_off_thread(&self) -> usize {
238 self.icons.worker_work().0
239 }
240
241 #[cfg(test)]
243 pub(crate) fn decoder_running(&self) -> bool {
244 self.icons.worker_work().1
245 }
246
247 #[cfg(test)]
249 pub(crate) fn cached_captures(&self) -> usize {
250 self.icons.captures()
251 }
252
253 pub fn draw(
271 &mut self,
272 view: &WindowView<'_>,
273 damage: &[Rect],
274 text: &mut TextSystem,
275 history: &mut DamageHistory,
276 canvas: Canvas<'_>,
277 ) -> Result<Vec<PixelRect>, CanvasError> {
278 let Canvas {
279 pixels,
280 width,
281 height,
282 scale,
283 format,
284 age,
285 } = canvas;
286 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
287 || !(scale.is_finite() && scale > 0.0)
288 {
289 return Err(CanvasError {
290 width,
291 height,
292 scale,
293 bytes: pixels.len(),
294 });
295 }
296 self.icons.start_frame(history.id());
297 let plan = history.plan(damage, scale, width, height, age);
298 let mut tiles: Vec<(u32, u32)> = Vec::new();
299 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
300 for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
301 tiles
302 .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
303 }
304 }
305 tiles.sort_unstable();
306 tiles.dedup();
307 let mut casts = HashMap::new();
308 let mut fonts = text.font_system();
309 for &(row, column) in &tiles {
310 self.icons.start_tile((row, column));
311 let (x, y) = (column * TILE, row * TILE);
312 let size = (width.saturating_sub(x), height.saturating_sub(y));
313 let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
314 self.scratch.clear();
315 self.scratch.resize(area.area() as usize * 4, 0);
316 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
317 else {
318 continue;
319 };
320 let mut painter = Painter {
321 grid: Grid {
322 scale,
323 zoom: 1.0,
324 linear: Affine {
325 sx: 1.0,
326 ky: 0.0,
327 kx: 0.0,
328 sy: 1.0,
329 tx: 0.0,
330 ty: 0.0,
331 },
332 window: view.size(),
333 width,
334 height,
335 left: area.x as f32,
336 top: area.y as f32,
337 },
338 glyphs: &mut self.glyphs,
339 icons: &mut self.icons,
340 fonts: &mut fonts,
341 work: &mut self.work,
342 casts: &mut casts,
343 };
344 painter.node(&mut pixmap, view.root());
345 copy(&self.scratch, area, pixels, width, format);
346 }
347 self.icons.repainted(&tiles);
348 self.icons.end_frame();
349 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
350 self.glyphs.image_cache.clear();
351 self.glyphs.outline_command_cache.clear();
352 }
353 Ok(plan.report)
354 }
355}
356
357#[derive(Clone, Copy, Debug, PartialEq)]
360pub struct CanvasError {
361 pub width: u32,
363 pub height: u32,
365 pub scale: f32,
367 pub bytes: usize,
369}
370
371impl std::fmt::Display for CanvasError {
372 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373 write!(
374 f,
375 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
376 self.width,
377 self.height,
378 self.scale,
379 u64::from(self.width) * u64::from(self.height) * 4,
380 self.bytes
381 )
382 }
383}
384
385impl std::error::Error for CanvasError {}
386
387impl Default for Renderer {
388 fn default() -> Self {
389 Self::new()
390 }
391}
392
393fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
395 let stride = width as usize * 4;
396 let row_bytes = area.width as usize * 4;
397 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
398 let start = (area.y as usize + row) * stride + area.x as usize * 4;
399 let target = &mut pixels[start..start + row_bytes];
400 match format {
401 PixelFormat::Abgr8888 => target.copy_from_slice(source),
402 PixelFormat::Argb8888 => {
403 let (to, _) = target.as_chunks_mut::<4>();
404 let (from, _) = source.as_chunks::<4>();
405 for (to, from) in to.iter_mut().zip(from) {
408 let pixel = u32::from_le_bytes(*from);
409 *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
410 }
411 }
412 }
413 }
414}
415
416#[derive(Clone, Copy)]
418struct Grid {
419 scale: f32,
421 zoom: f32,
424 linear: Affine,
427 window: Size,
429 width: u32,
431 height: u32,
432 left: f32,
434 top: f32,
435}
436
437impl Grid {
438 fn x(&self, x: f32) -> f32 {
441 let pixel = if x >= self.window.width {
442 self.width as f32
443 } else {
444 (x * self.scale).round()
445 };
446 pixel - self.left
447 }
448
449 fn y(&self, y: f32) -> f32 {
451 let pixel = if y >= self.window.height {
452 self.height as f32
453 } else {
454 (y * self.scale).round()
455 };
456 pixel - self.top
457 }
458
459 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
463 if !(rect.width > 0.0 && rect.height > 0.0) {
464 return None;
465 }
466 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
468 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
469 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
470 let bottom =
471 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
472 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
473 }
474
475 fn moved(&self, x: u32, y: u32) -> Grid {
477 Grid {
478 left: self.left + x as f32,
479 top: self.top + y as f32,
480 ..*self
481 }
482 }
483
484 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
487 tiny_skia::Rect::from_ltrb(
488 self.x(rect.x),
489 self.y(rect.y),
490 self.x(rect.right()),
491 self.y(rect.bottom()),
492 )
493 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
494 }
495}
496
497struct Painter<'a> {
499 grid: Grid,
500 glyphs: &'a mut SwashCache,
501 icons: &'a mut Icons,
502 fonts: &'a mut FontSystem,
503 work: &'a mut Work,
504 casts: &'a mut HashMap<CastKey, effects::Cast>,
506}
507
508type CastKey = (String, i64, i64);
511
512impl Painter<'_> {
513 fn on(&mut self, grid: Grid) -> Painter<'_> {
515 Painter {
516 grid,
517 glyphs: &mut *self.glyphs,
518 icons: &mut *self.icons,
519 fonts: &mut *self.fonts,
520 work: &mut *self.work,
521 casts: &mut *self.casts,
522 }
523 }
524
525 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
530 let Some((x, y, width, height)) =
532 self
533 .grid
534 .cover(node.bounds(), pixmap.width(), pixmap.height())
535 else {
536 return;
537 };
538 let style = node.style();
539 let opacity = style.opacity.unwrap_or(1.0);
540 let opacity = if opacity.is_nan() {
541 1.0
542 } else {
543 opacity.clamp(0.0, 1.0)
544 };
545 if opacity == 0.0 {
546 return;
547 }
548 let shadow = effects::cast_by_content(&style);
549 if let Some(transform) = node.transform() {
550 self.transformed(pixmap, node, &style, transform, opacity);
551 } else if opacity < 1.0 || style.mask.is_some() || shadow.is_some() {
552 let Some(mut layer) = Pixmap::new(width, height) else {
554 return;
555 };
556 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
557 let mut inner = self.on(self.grid.moved(x, y));
558 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow);
559 let paint = PixmapPaint {
560 opacity,
561 ..PixmapPaint::default()
562 };
563 let (x, y) = (x as i32, y as i32);
564 pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
565 } else {
566 self.node_contents(pixmap, node, &style);
567 }
568 }
569
570 fn layer_contents(
574 &mut self,
575 layer: &mut PixmapMut<'_>,
576 node: NodeView<'_>,
577 style: &Style,
578 shadow: Option<Shadow>,
579 ) {
580 self.node_contents(layer, node, style);
581 if let Some(mask) = &style.mask {
582 self.mask(layer, node.rect(), mask);
583 }
584 if let Some(shadow) = shadow {
585 self.content_shadow(layer, node, &shadow);
586 }
587 }
588
589 fn transformed(
596 &mut self,
597 pixmap: &mut PixmapMut<'_>,
598 node: NodeView<'_>,
599 style: &Style,
600 transform: Affine,
601 opacity: f32,
602 ) {
603 let Affine {
604 sx,
605 ky,
606 kx,
607 sy,
608 tx,
609 ty,
610 } = transform;
611 let Grid {
612 scale, left, top, ..
613 } = self.grid;
614 let outer = self.grid.linear;
615 let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0)
616 .pre_concat(Transform::from_row(sx, ky, kx, sy, 0.0, 0.0));
617 let linear = Affine {
618 sx: linear.sx,
619 ky: linear.ky,
620 kx: linear.kx,
621 sy: linear.sy,
622 tx: 0.0,
623 ty: 0.0,
624 };
625 let zoom = linear.layer_zoom();
626 let layer_scale = scale / self.grid.zoom * zoom;
627 let device = Transform::from_scale(scale, scale)
629 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
630 .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
631 let to_pixmap = device.post_translate(-left, -top);
632 let Some(back) = to_pixmap.invert() else {
633 return;
634 };
635 let inner = node.inner_bounds();
636 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
637 .and_then(|rect| rect.transform(back));
638 let drawn = tiny_skia::Rect::from_xywh(
639 inner.x * layer_scale,
640 inner.y * layer_scale,
641 inner.width * layer_scale,
642 inner.height * layer_scale,
643 );
644 let Some(area) = shown
645 .zip(drawn)
646 .and_then(|(shown, drawn)| shown.intersect(&drawn))
647 .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
648 .and_then(|area| area.round_out())
649 else {
650 return;
651 };
652 let pixels = u64::from(area.width()) * u64::from(area.height());
653 if pixels > LAYER_LIMIT {
654 tracing::debug!(
655 "{} is transformed into a layer too large to draw",
656 node.path()
657 );
658 return;
659 }
660 let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
661 return;
662 };
663 self.work.layer_pixels += pixels;
664 let (x, y) = (area.x() as f32, area.y() as f32);
665 let (width, height) = if zoom == self.grid.zoom {
666 (self.grid.width, self.grid.height)
667 } else {
668 let window = self.grid.window;
670 (
671 (window.width * layer_scale).round() as u32,
672 (window.height * layer_scale).round() as u32,
673 )
674 };
675 let mut inner = self.on(Grid {
676 scale: layer_scale,
677 zoom,
678 linear,
679 width,
680 height,
681 left: x,
682 top: y,
683 ..self.grid
684 });
685 let shadow = effects::cast_by_content(style);
686 inner.layer_contents(&mut layer.as_mut(), node, style, shadow);
687 let paint = PixmapPaint {
688 opacity,
689 quality: FilterQuality::Bilinear,
690 ..PixmapPaint::default()
691 };
692 pixmap.draw_pixmap(
693 0,
694 0,
695 layer.as_ref(),
696 &paint,
697 to_pixmap.pre_translate(x, y),
698 None,
699 );
700 }
701
702 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
703 self.work.nodes += 1;
704 let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
707 if let Some(shadow) = style.shadow.filter(outside) {
708 self.shadow(pixmap, node.rect(), style, &shadow);
709 }
710 self.draw_box(pixmap, node.rect(), style);
711 match node.content() {
712 Content::Text(text) => {
713 self.selection(pixmap, &text.selection(), text.color());
714 self.text(pixmap, &text);
715 }
716 Content::Icon(icon) => self.icon(pixmap, &icon),
717 Content::Image(image) => self.image(pixmap, &image),
718 Content::Capture(capture) => self.capture(pixmap, &capture),
719 Content::Input(input) => self.input(pixmap, &input),
720 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
721 Content::None => {}
722 }
723 if node.clips() {
724 self.clipped_children(pixmap, node, style);
725 } else {
726 for child in node.children() {
727 self.node(pixmap, child);
728 }
729 }
730 }
731
732 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
737 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
738 return;
739 };
740 let width = self.border_width(style);
741 let Some(inside) = tiny_skia::Rect::from_ltrb(
742 area.left() + width,
743 area.top() + width,
744 area.right() - width,
745 area.bottom() - width,
746 ) else {
747 return;
748 };
749 let corners = inset(corners, width);
750 self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
751 for child in node.children() {
752 painter.node(layer, child);
753 }
754 for (handle, bar) in node.scroll_bars() {
756 painter.draw_box(layer, handle, &bar);
757 }
758 });
759 }
760
761 fn through_mask(
764 &mut self,
765 pixmap: &mut PixmapMut<'_>,
766 cover: Rect,
767 (shape, corners): (tiny_skia::Rect, Corners),
768 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
769 ) {
770 if !visible(pixmap, shape) {
771 return;
772 }
773 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
774 Mask::new(pixmap.width(), pixmap.height()),
775 self.grid.cover(cover, pixmap.width(), pixmap.height()),
776 ) else {
777 return;
778 };
779 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
780 return;
781 };
782 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
783 let mut inner = self.on(self.grid.moved(x, y));
784 draw(&mut inner, &mut layer.as_mut());
785 let mut path = PathBuilder::new();
786 rounded_rect(&mut path, shape, corners);
787 let Some(path) = path.finish() else {
788 return;
789 };
790 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
791 pixmap.draw_pixmap(
792 x as i32,
793 y as i32,
794 layer.as_ref(),
795 &PixmapPaint::default(),
796 Transform::identity(),
797 Some(&mask),
798 );
799 }
800
801 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
805 let area = self.grid.rect(rect)?;
806 let corners = style.radius.unwrap_or_default().corners();
807 let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
808 Some((area, corners))
809 }
810
811 fn border_width(&self, style: &Style) -> f32 {
814 let Some(border) = style.border else {
815 return 0.0;
816 };
817 let width = (border.width * self.grid.scale).floor();
818 if border.width > 0.0 {
819 width.max(1.0)
820 } else {
821 width.max(0.0)
822 }
823 }
824
825 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
828 let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
829 if style.background.is_none()
830 && style.gradient.is_none()
831 && style.border.is_none()
832 && inset_shadow.is_none()
833 {
834 return;
835 }
836 let Some((area, corners)) = self.box_shape(rect, style) else {
837 return;
838 };
839 if !visible(pixmap, area) {
840 return;
841 }
842
843 if let Some(color) = style.background
844 && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
845 {
846 let mut path = PathBuilder::new();
847 rounded_rect(&mut path, area, corners);
848 fill(pixmap, path, color, FillRule::Winding);
849 }
850 if let Some(gradient) = style.gradient {
851 let mut path = PathBuilder::new();
852 rounded_rect(&mut path, area, corners);
853 let size = (pixmap.width(), pixmap.height());
854 if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
855 ramp.fill(pixmap, &path);
856 }
857 }
858 if let Some(shadow) = inset_shadow {
859 self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
860 }
861 if let Some(border) = style.border {
862 let width = self.border_width(style);
863 let dashed = width >= 1.0
864 && style.border_dash.is_some_and(|dash| {
865 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
866 });
867
868 if width >= 1.0 && !dashed {
869 let mut path = PathBuilder::new();
871 rounded_rect(&mut path, area, corners);
872 if let Some(inner) = tiny_skia::Rect::from_ltrb(
873 area.left() + width,
874 area.top() + width,
875 area.right() - width,
876 area.bottom() - width,
877 ) {
878 rounded_rect(&mut path, inner, inset(corners, width));
879 }
880 fill(pixmap, path, border.color, FillRule::EvenOdd);
881 }
882 }
883 }
884
885 fn dashed_border(
891 &self,
892 pixmap: &mut PixmapMut<'_>,
893 (area, corners): (tiny_skia::Rect, Corners),
894 width: f32,
895 color: Color,
896 (on, off): (f32, f32),
897 ) -> bool {
898 let Grid {
899 scale, left, top, ..
900 } = self.grid;
901 let half = width / 2.0;
902 let Some(middle) = tiny_skia::Rect::from_ltrb(
903 area.left() + left + half,
904 area.top() + top + half,
905 area.right() + left - half,
906 area.bottom() + top - half,
907 ) else {
908 return false;
909 };
910 let corners = inset(corners, half);
911 let (on, off) = (on * scale, off * scale);
912 let mut all = PathBuilder::new();
913 let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
914 if square.is_empty() {
915 let rounding: f32 = corners
918 .iter()
919 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
920 .sum();
921 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
922 let mut path = PathBuilder::new();
923 rounded_rect(&mut path, middle, corners);
924 if !dash_into(&mut all, path, perimeter, on, off) {
925 return false;
926 }
927 } else {
928 for (at, &from) in square.iter().enumerate() {
931 let to = square[(at + 1) % square.len()];
932 let steps = (to + 4 - from - 1) % 4 + 1;
933 let [.., mut was] = corner(middle, corners, from);
934 let mut path = PathBuilder::new();
935 path.move_to(was.x, was.y);
936 let mut length = 0.0;
937 for index in (from + 1..=from + steps).map(|index| index % 4) {
938 let [start, one, two, end] = corner(middle, corners, index);
939 path.line_to(start.x, start.y);
940 length += was.distance(start);
941 if corners[index] > 0.0 {
942 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
943 length += std::f32::consts::FRAC_PI_2 * corners[index];
944 }
945 was = end;
946 }
947 if !dash_into(&mut all, path, length, on, off) {
948 return false;
949 }
950 }
951 if on > 0.0 {
955 const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
957 for &index in &square {
958 let [point, ..] = corner(middle, corners, index);
959 let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
960 all.move_to(point.x - half * ax, point.y - half * ay);
961 all.line_to(point.x, point.y);
962 all.line_to(point.x + half * bx, point.y + half * by);
963 }
964 }
965 }
966 let Some(dashes) = all.finish() else {
967 return true;
968 };
969 let reach = 2.0 * width + 1.0;
974 let near = [
975 left - reach,
976 top - reach,
977 left + pixmap.width() as f32 + reach,
978 top + pixmap.height() as f32 + reach,
979 ];
980 let mut kept = PathBuilder::new();
981 let mut contour = Vec::new();
982 for segment in dashes.segments() {
983 if matches!(segment, PathSegment::MoveTo(_)) {
984 keep_near(&mut kept, &contour, near);
985 contour.clear();
986 }
987 contour.push(segment);
988 }
989 keep_near(&mut kept, &contour, near);
990 let Some(kept) = kept.finish() else {
991 return true;
992 };
993 let stroke = Stroke {
994 width,
995 line_cap: if on == 0.0 {
997 LineCap::Round
998 } else {
999 LineCap::Butt
1000 },
1001 line_join: LineJoin::Miter,
1002 ..Stroke::default()
1003 };
1004 let mut paint = Paint::default();
1005 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1006 paint.anti_alias = true;
1007 let moved = Transform::from_translate(-left, -top);
1008 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1009 true
1010 }
1011
1012 fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1017 let Grid {
1018 scale, left, top, ..
1019 } = self.grid;
1020 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1021 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1022 return;
1023 }
1024 let Some((area, corners)) = self.box_shape(rect, style) else {
1025 return;
1026 };
1027 let spread = shadow.spread * scale;
1029 let Some(shape) = tiny_skia::Rect::from_ltrb(
1030 area.left() + left + shadow.x * scale - spread,
1031 area.top() + top + shadow.y * scale - spread,
1032 area.right() + left + shadow.x * scale + spread,
1033 area.bottom() + top + shadow.y * scale + spread,
1034 ) else {
1035 return;
1036 };
1037 let corners = fit(spread_corners(corners, spread), shape);
1038 let cut = if shadow.cut_out {
1040 self.box_mask(pixmap, rect, style)
1041 } else {
1042 None
1043 };
1044 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1046 if sigma < 0.25 {
1047 let mut path = PathBuilder::new();
1048 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1049 return;
1050 };
1051 rounded_rect(&mut path, shape, corners);
1052 let Some(path) = path.finish() else {
1053 return;
1054 };
1055 let mut paint = Paint::default();
1056 let color = shadow.color;
1057 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1058 paint.anti_alias = true;
1059 let outside = cut.map(|mut cut| {
1060 cut.invert();
1061 cut
1062 });
1063 let (rule, at) = (FillRule::Winding, Transform::identity());
1064 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1065 return;
1066 }
1067 let reach = 3.0 * sigma;
1068 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1069 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1070 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1071 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1072 if columns.is_empty() || rows.is_empty() {
1073 return;
1074 }
1075 let blurred = BlurredBox::new(shape, corners, sigma);
1076 let mut mask = Vec::with_capacity(columns.len() * rows.len());
1077 for row in rows.clone() {
1078 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1079 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1080 }
1081 if let Some(cut) = cut {
1082 let stride = pixmap.width() as usize;
1083 let under = rows.clone().flat_map(|row| {
1084 columns
1085 .clone()
1086 .map(move |column| row as usize * stride + column as usize)
1087 });
1088 for (alpha, at) in mask.iter_mut().zip(under) {
1089 *alpha = mul(*alpha, 255 - cut.data()[at]);
1090 }
1091 }
1092 let width = columns.len() as u32;
1093 let height = rows.len() as u32;
1094 let (x, y) = (columns.start as i32, rows.start as i32);
1095 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1096 }
1097
1098 fn inset_shadow(
1103 &self,
1104 pixmap: &mut PixmapMut<'_>,
1105 (area, corners): (tiny_skia::Rect, Corners),
1106 border: f32,
1107 shadow: &Shadow,
1108 ) {
1109 let Grid {
1110 scale, left, top, ..
1111 } = self.grid;
1112 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1113 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1114 return;
1115 }
1116 let Some(inside) = tiny_skia::Rect::from_ltrb(
1117 area.left() + border,
1118 area.top() + border,
1119 area.right() - border,
1120 area.bottom() - border,
1121 ) else {
1122 return;
1123 };
1124 let inside_corners = inset(corners, border);
1125 if !visible(pixmap, inside) {
1126 return;
1127 }
1128 let mut path = PathBuilder::new();
1129 rounded_rect(&mut path, inside, inside_corners);
1130 let Some(path) = path.finish() else {
1131 return;
1132 };
1133 let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1135 let hole = tiny_skia::Rect::from_ltrb(
1136 inside.left() + left + x + spread,
1137 inside.top() + top + y + spread,
1138 inside.right() + left + x - spread,
1139 inside.bottom() + top + y - spread,
1140 );
1141 let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1142 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1143 let color = shadow.color;
1144 if sigma < 0.25 {
1145 let mut outside = None;
1146 if let Some((hole, corners)) = hole {
1147 let mut cut = PathBuilder::new();
1148 let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1149 return;
1150 };
1151 rounded_rect(&mut cut, moved, corners);
1152 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1153 return;
1154 };
1155 let (rule, at) = (FillRule::Winding, Transform::identity());
1156 let Some(cut) = cut.finish() else {
1157 return;
1158 };
1159 mask.fill_path(&cut, rule, true, at);
1160 mask.invert();
1161 outside = Some(mask);
1162 }
1163 let mut paint = Paint::default();
1164 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1165 paint.anti_alias = true;
1166 let (rule, at) = (FillRule::Winding, Transform::identity());
1167 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1168 return;
1169 }
1170 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1173 return;
1174 };
1175 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1176 let columns = inside.left().floor().max(0.0) as u32
1177 ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1178 let rows = inside.top().floor().max(0.0) as u32
1179 ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1180 if columns.is_empty() || rows.is_empty() {
1181 return;
1182 }
1183 let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1184 let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1185 for row in rows.clone() {
1186 let start = alpha.len();
1187 match &blurred {
1188 Some(blurred) => {
1189 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1190 blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1191 }
1192 None => alpha.resize(start + columns.len(), 0),
1193 }
1194 let stride = pixmap.width() as usize;
1195 let row = &mask.data()[row as usize * stride..];
1196 let covered = &row[columns.start as usize..columns.end as usize];
1197 for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1198 *value = mul(255 - *value, covered);
1199 }
1200 }
1201 let (width, height) = (columns.len() as u32, rows.len() as u32);
1202 let (x, y) = (columns.start as i32, rows.start as i32);
1203 blend_mask(pixmap, x, y, width, height, &alpha, color);
1204 }
1205
1206 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1209 let (area, corners) = self.box_shape(rect, style)?;
1210 let mut path = PathBuilder::new();
1211 rounded_rect(&mut path, area, corners);
1212 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1213 let (rule, at) = (FillRule::Winding, Transform::identity());
1214 mask.fill_path(&path.finish()?, rule, true, at);
1215 Some(mask)
1216 }
1217
1218 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1223 let Grid {
1224 scale, left, top, ..
1225 } = self.grid;
1226 let origin = text.origin();
1227 let x = origin.x * scale - left;
1228 for run in text.runs() {
1229 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1231 if baseline + run.line_height * scale < 0.0
1232 || baseline - run.line_height * scale > pixmap.height() as f32
1233 {
1234 continue;
1235 }
1236 let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1238 true => text.link_hover_color().or(span.color),
1239 false => span.color,
1240 };
1241 for glyph in run.glyphs.iter() {
1242 let span = text.span(run.line_i, glyph);
1243 let color = span.and_then(|span| span_color(span, glyph));
1244 let color = color.unwrap_or(text.color());
1245 if color.a == 0 {
1246 continue;
1247 }
1248 let physical = glyph.physical((x, baseline), scale);
1249 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1250 continue;
1251 };
1252 let left = physical.x + image.placement.left;
1253 let top = physical.y - image.placement.top;
1254 let (width, height) = (image.placement.width, image.placement.height);
1255 match image.content {
1256 SwashContent::Mask => {
1257 blend_mask(pixmap, left, top, width, height, &image.data, color);
1258 }
1259 SwashContent::Color => {
1260 let premultiplied = is_color_outline(image);
1261 let rgba = (image.data.as_slice(), premultiplied);
1262 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1263 }
1264 SwashContent::SubpixelMask => {}
1266 }
1267 }
1268 let origin = text.origin().x;
1269 let own = (text.underline(), text.strikethrough());
1270 if own != (false, false) {
1271 self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1272 }
1273 let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1277 text.span(run.line_i, a),
1278 text.span(run.line_i, b),
1279 ) {
1280 (Some(a), Some(b)) => std::ptr::eq(a, b),
1281 (a, b) => a.is_none() && b.is_none(),
1282 };
1283 for glyphs in run.glyphs.chunk_by(same_span) {
1284 let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1285 continue;
1286 };
1287 let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1288 let lines = (span.underline || lit, span.strikethrough);
1289 if lines != (false, false) {
1290 let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1291 self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1292 }
1293 }
1294 }
1295 }
1296
1297 fn decorations(
1301 &mut self,
1302 pixmap: &mut PixmapMut<'_>,
1303 origin: f32,
1304 glyphs: &[LayoutGlyph],
1305 baseline: f32,
1306 lines: (bool, bool),
1307 color: Color,
1308 ) {
1309 let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1310 (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1311 };
1312 for glyphs in glyphs.chunk_by(same_font) {
1313 self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1314 }
1315 }
1316
1317 fn font_decorations(
1323 &mut self,
1324 pixmap: &mut PixmapMut<'_>,
1325 origin: f32,
1326 glyphs: &[LayoutGlyph],
1327 baseline: f32,
1328 (underline, strikethrough): (bool, bool),
1329 color: Color,
1330 ) {
1331 let Some(first) = glyphs.first() else {
1332 return;
1333 };
1334 let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1335 return;
1336 };
1337 let metrics = font.metrics();
1338 let em = f32::from(metrics.units_per_em);
1339 if em == 0.0 {
1340 return;
1341 }
1342 let Grid { scale, left, .. } = self.grid;
1343 let (start, end) = glyphs
1344 .iter()
1345 .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1346 (start.min(glyph.x), end.max(glyph.x + glyph.w))
1347 });
1348 let x0 = ((origin + start) * scale).round() - left;
1349 let x1 = ((origin + end) * scale).round() - left;
1350 let size = first.font_size * scale;
1351 let lines = [
1353 (underline, metrics.underline, -0.125),
1354 (strikethrough, metrics.strikeout, 0.3),
1355 ];
1356 for (on, decoration, offset) in lines {
1357 if !on {
1358 continue;
1359 }
1360 let (offset, thickness) =
1361 decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1362 let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1364 let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1365 if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1366 let mut path = PathBuilder::new();
1367 path.push_rect(area);
1368 fill(pixmap, path, color, FillRule::Winding);
1369 }
1370 }
1371 }
1372
1373 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1375 let Some(area) = self.grid.rect(input.area) else {
1376 return;
1377 };
1378 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1379 painter.input_contents(layer, input);
1380 });
1381 }
1382
1383 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1386 let color = input.text.color();
1387 self.selection(pixmap, input.selection, color);
1388 self.text(pixmap, &input.text);
1389 for line in input.underline {
1390 if let Some(area) = self.grid.rect(*line) {
1391 let mut path = PathBuilder::new();
1392 path.push_rect(area);
1393 fill(pixmap, path, color, FillRule::Winding);
1394 }
1395 }
1396 if let Some(caret) = input.caret {
1397 let left = self.grid.x(caret.x);
1399 let right = self.grid.x(caret.right()).max(left + 1.0);
1400 if let Some(area) = tiny_skia::Rect::from_ltrb(
1401 left,
1402 self.grid.y(caret.y),
1403 right,
1404 self.grid.y(caret.bottom()),
1405 ) {
1406 let mut path = PathBuilder::new();
1407 path.push_rect(area);
1408 fill(pixmap, path, color, FillRule::Winding);
1409 }
1410 }
1411 }
1412
1413 fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], color: Color) {
1415 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1416 for span in spans {
1417 if let Some(area) = self.grid.rect(*span) {
1418 let mut path = PathBuilder::new();
1419 path.push_rect(area);
1420 fill(pixmap, path, tint, FillRule::Winding);
1421 }
1422 }
1423 }
1424
1425 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1427 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1428 return;
1429 };
1430 match self.icons.image(image, (width, height), self.grid.scale) {
1431 Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1432 transition::blit(pixmap, (x, y), pixels);
1433 }
1434 Some(Drawn::One(pixels)) => {
1436 let paint = PixmapPaint {
1437 quality: FilterQuality::Bilinear,
1438 ..PixmapPaint::default()
1439 };
1440 let stretch = Transform::from_scale(
1441 width as f32 / pixels.width() as f32,
1442 height as f32 / pixels.height() as f32,
1443 )
1444 .post_translate(x as f32, y as f32);
1445 pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1446 }
1447 Some(Drawn::Two { from, to, t }) => {
1448 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1449 }
1450 None => {}
1451 }
1452 }
1453
1454 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1456 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1457 return;
1458 };
1459 let frame = capture.frame;
1460 if let Some(pixels) = self
1461 .icons
1462 .capture(capture.id, frame, width, height, capture.fit)
1463 {
1464 draw_at(pixmap, x, y, pixels);
1465 }
1466 }
1467
1468 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1473 let Grid {
1474 scale, left, top, ..
1475 } = self.grid;
1476 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1477 let (x, y) = (
1478 (rect.x * scale).round() - left,
1479 (rect.y * scale).round() - top,
1480 );
1481 if !(width >= 1.0 && height >= 1.0) {
1482 return None;
1483 }
1484 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1485 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1487 }
1488
1489 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1491 let Grid {
1492 scale, left, top, ..
1493 } = self.grid;
1494 let side = (icon.rect.width * scale).round();
1495 if side.is_nan() || side < 1.0 {
1496 return;
1497 }
1498 let x = (icon.rect.x * scale).round() - left;
1499 let y = (icon.rect.y * scale).round() - top;
1500 let size = icon.rect.width.round() as u32;
1502 let theme_scale = scale.ceil().max(1.0) as u32;
1503 let sizes = (side as u32, size, theme_scale);
1504 if let Some(image) = self.icons.get(icon.source, sizes, icon.tint) {
1505 pixmap.draw_pixmap(
1506 x as i32,
1507 y as i32,
1508 image.as_ref(),
1509 &PixmapPaint::default(),
1510 Transform::identity(),
1511 None,
1512 );
1513 }
1514 }
1515}
1516
1517fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1519 let paint = PixmapPaint::default();
1520 pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1521}
1522
1523fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1525 area.right() > 0.0
1526 && area.bottom() > 0.0
1527 && area.left() < pixmap.width() as f32
1528 && area.top() < pixmap.height() as f32
1529}
1530
1531fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1532 let Some(path) = path.finish() else {
1533 return;
1534 };
1535 let mut paint = Paint::default();
1536 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1537 paint.anti_alias = true;
1538 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1539}
1540
1541type Corners = [f32; 4];
1543
1544fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
1549 let Some((on, off)) = fit_dash(length, on, off) else {
1550 return false;
1551 };
1552 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
1553 return false;
1554 };
1555 if let Some(dashes) = path.dash(&dash, 1.0) {
1556 all.push_path(&dashes);
1557 }
1558 true
1559}
1560
1561fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1565 const KAPPA: f32 = 0.552_284_8;
1568 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1569 let radius = corners[index];
1570 let k = radius * (1.0 - KAPPA);
1571 let points = match index {
1572 0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
1573 1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
1574 2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
1575 _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
1576 };
1577 points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
1578}
1579
1580fn spread_corners(corners: Corners, spread: f32) -> Corners {
1584 corners.map(|radius| {
1585 if spread > 0.0 && radius < spread {
1586 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
1587 } else {
1588 (radius + spread).max(0.0)
1589 }
1590 })
1591}
1592
1593fn fit(
1595 [top_left, top_right, bottom_right, bottom_left]: Corners,
1596 area: tiny_skia::Rect,
1597) -> Corners {
1598 let radii = Radii {
1599 top_left,
1600 top_right,
1601 bottom_right,
1602 bottom_left,
1603 };
1604 radii.fit(area.width(), area.height()).corners()
1605}
1606
1607fn inset(corners: Corners, by: f32) -> Corners {
1609 corners.map(|radius| (radius - by).max(0.0))
1610}
1611
1612fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1615 if corners.iter().all(|&radius| radius <= 0.0) {
1616 path.push_rect(rect);
1617 return;
1618 }
1619 let [.., start] = corner(rect, corners, 0);
1620 path.move_to(start.x, start.y);
1621 for index in [1, 2, 3, 0] {
1622 let [start, one, two, end] = corner(rect, corners, index);
1623 path.line_to(start.x, start.y);
1624 if corners[index] > 0.0 {
1625 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1626 }
1627 }
1628 path.close();
1629}
1630
1631fn mul(a: u8, b: u8) -> u8 {
1633 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1634}
1635
1636fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1638 let rest = 255 - source[3];
1639 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1640 *channel = value.saturating_add(mul(*channel, rest));
1641 }
1642}
1643
1644fn overlap(
1648 pixmap: &PixmapMut<'_>,
1649 left: i32,
1650 top: i32,
1651 width: u32,
1652 height: u32,
1653) -> Option<(usize, usize, usize, usize)> {
1654 let column_start = (-i64::from(left)).max(0);
1655 let row_start = (-i64::from(top)).max(0);
1656 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1657 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1658 (column_start < column_end && row_start < row_end).then_some((
1659 column_start as usize,
1660 column_end as usize,
1661 row_start as usize,
1662 row_end as usize,
1663 ))
1664}
1665
1666fn blend_mask(
1668 pixmap: &mut PixmapMut<'_>,
1669 left: i32,
1670 top: i32,
1671 width: u32,
1672 height: u32,
1673 mask: &[u8],
1674 color: Color,
1675) {
1676 if mask.len() < width as usize * height as usize {
1677 return;
1678 }
1679 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1680 else {
1681 return;
1682 };
1683 let stride = pixmap.width() as usize;
1684 let data = pixmap.data_mut();
1685 for row in rows..rows_end {
1686 for column in columns..columns_end {
1687 let coverage = mask[row * width as usize + column];
1688 if coverage == 0 {
1689 continue;
1690 }
1691 let alpha = mul(color.a, coverage);
1692 let source = [
1693 mul(color.r, alpha),
1694 mul(color.g, alpha),
1695 mul(color.b, alpha),
1696 alpha,
1697 ];
1698 let x = (i64::from(left) + column as i64) as usize;
1699 let y = (i64::from(top) + row as i64) as usize;
1700 over(data, (y * stride + x) * 4, source);
1701 }
1702 }
1703}
1704
1705const SAMPLES: usize = 8;
1707
1708struct BlurredBox {
1715 middle: (f32, f32),
1716 half: (f32, f32),
1717 corners: Corners,
1718 largest: f32,
1719 sigma: f32,
1720 whole: f32,
1723}
1724
1725impl BlurredBox {
1726 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1727 let step = 6.0 * sigma / SAMPLES as f32;
1728 let whole = (0..SAMPLES)
1729 .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
1730 .sum();
1731 BlurredBox {
1732 whole,
1733 middle: (
1734 (shape.left() + shape.right()) / 2.0,
1735 (shape.top() + shape.bottom()) / 2.0,
1736 ),
1737 half: (shape.width() / 2.0, shape.height() / 2.0),
1738 corners,
1739 largest: corners.into_iter().fold(0.0, f32::max),
1740 sigma,
1741 }
1742 }
1743
1744 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1747 let y = y - self.middle.1;
1748 let (half_width, half_height) = self.half;
1749 let reach = 3.0 * self.sigma;
1750 let down = self.along(y, half_height);
1751 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1752 let rows = if clear_of_corners {
1753 [(0.0, 0.0, 0.0); SAMPLES]
1754 } else {
1755 self.rows_near(y)
1756 };
1757 for x in xs {
1758 let x = x - self.middle.0;
1759 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1760 self.along(x, half_width) * down
1761 } else {
1762 let sum: f32 = rows
1763 .iter()
1764 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1765 .sum();
1766 (sum / self.whole).clamp(0.0, 1.0)
1767 };
1768 mask.push((coverage * 255.0).round() as u8);
1769 }
1770 }
1771
1772 fn along(&self, p: f32, half: f32) -> f32 {
1774 self.between(p, half, half)
1775 }
1776
1777 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1780 let reach = 3.0 * self.sigma;
1781 if -(left - reach) <= p && p <= right - reach {
1782 return 1.0;
1783 }
1784 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1785 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1786 }
1787
1788 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1792 let (half_width, half_height) = self.half;
1793 let reach = 3.0 * self.sigma;
1794 let start = (y - half_height).clamp(-reach, reach);
1795 let end = (y + half_height).clamp(-reach, reach);
1796 let step = (end - start) / SAMPLES as f32;
1797 std::array::from_fn(|sample| {
1798 let offset = start + step * (sample as f32 + 0.5);
1799 let row = y - offset;
1802 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1803 let (left, right) = if row < 0.0 {
1804 (top_left, top_right)
1805 } else {
1806 (bottom_left, bottom_right)
1807 };
1808 let span = |radius: f32| {
1809 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1810 half_width - radius
1811 + (radius * radius - into_corner * into_corner)
1812 .max(0.0)
1813 .sqrt()
1814 };
1815 (span(left), span(right), gaussian(offset, self.sigma) * step)
1816 })
1817 }
1818}
1819
1820fn gaussian(x: f32, sigma: f32) -> f32 {
1822 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1823 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1824}
1825
1826fn erf(x: f32) -> f32 {
1829 let a = x.abs();
1830 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1831 let d = d * d;
1832 (1.0 - 1.0 / (d * d)).copysign(x)
1833}
1834
1835fn is_color_outline(image: &SwashImage) -> bool {
1842 format!("{:?}", image.source).starts_with("ColorOutline")
1843}
1844
1845fn blend_rgba(
1848 pixmap: &mut PixmapMut<'_>,
1849 left: i32,
1850 top: i32,
1851 width: u32,
1852 height: u32,
1853 (rgba, premultiplied): (&[u8], bool),
1854 opacity: u8,
1855) {
1856 if rgba.len() < width as usize * height as usize * 4 {
1857 return;
1858 }
1859 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1860 else {
1861 return;
1862 };
1863 let stride = pixmap.width() as usize;
1864 let data = pixmap.data_mut();
1865 for row in rows..rows_end {
1866 for column in columns..columns_end {
1867 let index = (row * width as usize + column) * 4;
1868 let alpha = mul(rgba[index + 3], opacity);
1869 if alpha == 0 {
1870 continue;
1871 }
1872 let factor = if premultiplied { opacity } else { alpha };
1875 let source = [
1876 mul(rgba[index], factor),
1877 mul(rgba[index + 1], factor),
1878 mul(rgba[index + 2], factor),
1879 alpha,
1880 ];
1881 let x = (i64::from(left) + column as i64) as usize;
1882 let y = (i64::from(top) + row as i64) as usize;
1883 over(data, (y * stride + x) * 4, source);
1884 }
1885 }
1886}
1887
1888fn keep_near(
1891 kept: &mut PathBuilder,
1892 contour: &[PathSegment],
1893 [left, top, right, bottom]: [f32; 4],
1894) {
1895 let (mut low, mut high) = (
1896 (f32::INFINITY, f32::INFINITY),
1897 (f32::NEG_INFINITY, f32::NEG_INFINITY),
1898 );
1899 let points = contour.iter().flat_map(|segment| match *segment {
1900 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1901 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1902 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1903 PathSegment::Close => [None; 3],
1904 });
1905 for point in points.flatten() {
1906 low = (low.0.min(point.x), low.1.min(point.y));
1907 high = (high.0.max(point.x), high.1.max(point.y));
1908 }
1909 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1910 return;
1911 }
1912 for segment in contour {
1913 match *segment {
1914 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1915 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1916 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1917 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1918 PathSegment::Close => kept.close(),
1919 }
1920 }
1921}
1922
1923pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1928 let period = on + off;
1929 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1930 return None;
1931 }
1932 let count = (perimeter / period).round().max(1.0);
1933 let stretch = perimeter / (count * period);
1934 Some((on * stretch, off * stretch))
1935}
1936
1937pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
1943 let edges = [area.left(), area.top(), area.right(), area.bottom()];
1944 if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
1945 return false;
1946 }
1947 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
1948 let [left, top, right, bottom] = [
1949 area.left().clamp(0.0, width),
1950 area.top().clamp(0.0, height),
1951 area.right().clamp(0.0, width),
1952 area.bottom().clamp(0.0, height),
1953 ]
1954 .map(|edge| edge as usize);
1955 let stride = pixmap.width() as usize * 4;
1956 let pixel = [color.r, color.g, color.b, 255];
1957 for row in pixmap
1958 .data_mut()
1959 .chunks_exact_mut(stride)
1960 .take(bottom)
1961 .skip(top)
1962 {
1963 row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
1964 }
1965 true
1966}