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