1use std::collections::HashMap;
10
11use cosmic_text::{FontSystem, SwashCache, SwashContent, SwashImage};
12use crabshell_ui::{
13 Affine, CaptureView, Color, Content, Gradient, GradientShape, IconView, ImageView, InputView,
14 NodeView, Rect, Shadow, Size, Style, TextSystem, TextView, WindowView,
15};
16use tiny_skia::{
17 FillRule, FilterQuality, GradientStop, LineCap, LineJoin, LinearGradient, Mask, Paint,
18 PathBuilder, PathSegment, Pixmap, PixmapMut, PixmapPaint, RadialGradient, Shader, SpreadMode,
19 Stroke, StrokeDash, SweepGradient, Transform,
20};
21
22use crate::damage::{BufferAge, DamageHistory, PixelRect};
23use crate::icons::{Drawn, Icons};
24
25mod canvas;
26mod effects;
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(Clone, Copy, 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}
99
100impl Renderer {
101 pub fn new() -> Renderer {
104 Renderer {
105 glyphs: SwashCache::new(),
106 icons: Icons::new(),
107 scratch: Vec::new(),
108 work: Work::default(),
109 }
110 }
111
112 #[cfg(test)]
114 pub(crate) fn cached_glyphs(&self) -> usize {
115 self.glyphs.image_cache.len()
116 }
117
118 #[cfg(test)]
121 pub(crate) fn work(&self) -> (u64, u64, u64) {
122 (self.work.layer_pixels, self.work.nodes, self.work.blurred)
123 }
124
125 #[cfg(test)]
128 pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
129 Renderer {
130 icons: Icons::with_themes(crate::theme::Themes::new(bases)),
131 ..Renderer::new()
132 }
133 }
134
135 pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
137 self.icons.set_theme(theme.into());
138 }
139
140 #[cfg(test)]
142 pub(crate) fn cached_icons(&self) -> usize {
143 self.icons.cached()
144 }
145
146 #[cfg(test)]
148 pub(crate) fn rasterized_icons(&self) -> usize {
149 self.icons.rasterized()
150 }
151
152 pub fn forget_captures(&mut self, gone: &[u64]) {
156 self.icons.forget_captures(gone);
157 }
158
159 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
164 self.icons.next_frame(now)
165 }
166
167 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
173 self.icons.advance(now)
174 }
175
176 #[cfg(test)]
178 pub(crate) fn cached_captures(&self) -> usize {
179 self.icons.captures()
180 }
181
182 pub fn draw(
200 &mut self,
201 view: &WindowView<'_>,
202 damage: &[Rect],
203 text: &mut TextSystem,
204 history: &mut DamageHistory,
205 canvas: Canvas<'_>,
206 ) -> Result<Vec<PixelRect>, CanvasError> {
207 let Canvas {
208 pixels,
209 width,
210 height,
211 scale,
212 format,
213 age,
214 } = canvas;
215 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
216 || !(scale.is_finite() && scale > 0.0)
217 {
218 return Err(CanvasError {
219 width,
220 height,
221 scale,
222 bytes: pixels.len(),
223 });
224 }
225 self.icons.start_frame(history.id());
226 let plan = history.plan(damage, scale, width, height, age);
227 let mut tiles: Vec<(u32, u32)> = Vec::new();
228 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
229 for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
230 tiles
231 .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
232 }
233 }
234 tiles.sort_unstable();
235 tiles.dedup();
236 let mut casts = HashMap::new();
237 for (row, column) in tiles {
238 let (x, y) = (column * TILE, row * TILE);
239 let size = (width.saturating_sub(x), height.saturating_sub(y));
240 let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
241 self.scratch.clear();
242 self.scratch.resize(area.area() as usize * 4, 0);
243 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
244 else {
245 continue;
246 };
247 let mut painter = Painter {
248 grid: Grid {
249 scale,
250 window: view.size(),
251 width,
252 height,
253 left: area.x as f32,
254 top: area.y as f32,
255 },
256 glyphs: &mut self.glyphs,
257 icons: &mut self.icons,
258 fonts: text.font_system(),
259 work: &mut self.work,
260 casts: &mut casts,
261 };
262 painter.node(&mut pixmap, view.root());
263 copy(&self.scratch, area, pixels, width, format);
264 }
265 self.icons.end_frame();
266 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
267 self.glyphs.image_cache.clear();
268 self.glyphs.outline_command_cache.clear();
269 }
270 Ok(plan.report)
271 }
272}
273
274#[derive(Clone, Copy, Debug, PartialEq)]
277pub struct CanvasError {
278 pub width: u32,
280 pub height: u32,
282 pub scale: f32,
284 pub bytes: usize,
286}
287
288impl std::fmt::Display for CanvasError {
289 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290 write!(
291 f,
292 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
293 self.width,
294 self.height,
295 self.scale,
296 u64::from(self.width) * u64::from(self.height) * 4,
297 self.bytes
298 )
299 }
300}
301
302impl std::error::Error for CanvasError {}
303
304impl Default for Renderer {
305 fn default() -> Self {
306 Self::new()
307 }
308}
309
310fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
312 let stride = width as usize * 4;
313 let row_bytes = area.width as usize * 4;
314 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
315 let start = (area.y as usize + row) * stride + area.x as usize * 4;
316 let target = &mut pixels[start..start + row_bytes];
317 match format {
318 PixelFormat::Abgr8888 => target.copy_from_slice(source),
319 PixelFormat::Argb8888 => {
320 let (to, _) = target.as_chunks_mut::<4>();
321 let (from, _) = source.as_chunks::<4>();
322 for (to, from) in to.iter_mut().zip(from) {
323 *to = [from[2], from[1], from[0], from[3]];
324 }
325 }
326 }
327 }
328}
329
330#[derive(Clone, Copy)]
332struct Grid {
333 scale: f32,
334 window: Size,
336 width: u32,
338 height: u32,
339 left: f32,
341 top: f32,
342}
343
344impl Grid {
345 fn x(&self, x: f32) -> f32 {
348 let pixel = if x >= self.window.width {
349 self.width as f32
350 } else {
351 (x * self.scale).round()
352 };
353 pixel - self.left
354 }
355
356 fn y(&self, y: f32) -> f32 {
358 let pixel = if y >= self.window.height {
359 self.height as f32
360 } else {
361 (y * self.scale).round()
362 };
363 pixel - self.top
364 }
365
366 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
370 if !(rect.width > 0.0 && rect.height > 0.0) {
371 return None;
372 }
373 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
375 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
376 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
377 let bottom =
378 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
379 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
380 }
381
382 fn moved(&self, x: u32, y: u32) -> Grid {
384 Grid {
385 left: self.left + x as f32,
386 top: self.top + y as f32,
387 ..*self
388 }
389 }
390
391 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
394 tiny_skia::Rect::from_ltrb(
395 self.x(rect.x),
396 self.y(rect.y),
397 self.x(rect.right()),
398 self.y(rect.bottom()),
399 )
400 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
401 }
402}
403
404struct Painter<'a> {
406 grid: Grid,
407 glyphs: &'a mut SwashCache,
408 icons: &'a mut Icons,
409 fonts: &'a mut FontSystem,
410 work: &'a mut Work,
411 casts: &'a mut HashMap<CastKey, effects::Cast>,
413}
414
415type CastKey = (String, i64, i64);
418
419impl Painter<'_> {
420 fn on(&mut self, grid: Grid) -> Painter<'_> {
422 Painter {
423 grid,
424 glyphs: &mut *self.glyphs,
425 icons: &mut *self.icons,
426 fonts: &mut *self.fonts,
427 work: &mut *self.work,
428 casts: &mut *self.casts,
429 }
430 }
431
432 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
437 let Some((x, y, width, height)) =
439 self
440 .grid
441 .cover(node.bounds(), pixmap.width(), pixmap.height())
442 else {
443 return;
444 };
445 let style = node.style();
446 let opacity = style.opacity.unwrap_or(1.0);
447 let opacity = if opacity.is_nan() {
448 1.0
449 } else {
450 opacity.clamp(0.0, 1.0)
451 };
452 if opacity == 0.0 {
453 return;
454 }
455 let shadow = effects::cast_by_content(&style);
456 if let Some(transform) = node.transform() {
457 self.transformed(pixmap, node, &style, transform, opacity);
458 } else if opacity < 1.0 || style.mask.is_some() || shadow.is_some() {
459 let Some(mut layer) = Pixmap::new(width, height) else {
461 return;
462 };
463 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
464 let mut inner = self.on(self.grid.moved(x, y));
465 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow);
466 let paint = PixmapPaint {
467 opacity,
468 ..PixmapPaint::default()
469 };
470 let (x, y) = (x as i32, y as i32);
471 pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
472 } else {
473 self.node_contents(pixmap, node, &style);
474 }
475 }
476
477 fn layer_contents(
481 &mut self,
482 layer: &mut PixmapMut<'_>,
483 node: NodeView<'_>,
484 style: &Style,
485 shadow: Option<Shadow>,
486 ) {
487 self.node_contents(layer, node, style);
488 if let Some(mask) = &style.mask {
489 self.mask(layer, node.rect(), mask);
490 }
491 if let Some(shadow) = shadow {
492 self.content_shadow(layer, node, &shadow);
493 }
494 }
495
496 fn transformed(
502 &mut self,
503 pixmap: &mut PixmapMut<'_>,
504 node: NodeView<'_>,
505 style: &Style,
506 transform: Affine,
507 opacity: f32,
508 ) {
509 let Affine {
510 sx,
511 ky,
512 kx,
513 sy,
514 tx,
515 ty,
516 } = transform;
517 let Grid {
518 scale, left, top, ..
519 } = self.grid;
520 let device = Transform::from_scale(scale, scale)
522 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
523 .pre_scale(1.0 / scale, 1.0 / scale);
524 let to_pixmap = device.post_translate(-left, -top);
525 let Some(back) = to_pixmap.invert() else {
526 return;
527 };
528 let inner = node.inner_bounds();
529 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
530 .and_then(|rect| rect.transform(back));
531 let drawn = tiny_skia::Rect::from_xywh(
532 inner.x * scale,
533 inner.y * scale,
534 inner.width * scale,
535 inner.height * scale,
536 );
537 let Some(area) = shown
538 .zip(drawn)
539 .and_then(|(shown, drawn)| shown.intersect(&drawn))
540 .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
541 .and_then(|area| area.round_out())
542 else {
543 return;
544 };
545 let pixels = u64::from(area.width()) * u64::from(area.height());
546 if pixels > LAYER_LIMIT {
547 tracing::debug!(
548 "{} is transformed into a layer too large to draw",
549 node.path()
550 );
551 return;
552 }
553 let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
554 return;
555 };
556 self.work.layer_pixels += pixels;
557 let (x, y) = (area.x() as f32, area.y() as f32);
558 let mut inner = self.on(Grid {
559 left: x,
560 top: y,
561 ..self.grid
562 });
563 let shadow = effects::cast_by_content(style);
564 inner.layer_contents(&mut layer.as_mut(), node, style, shadow);
565 let paint = PixmapPaint {
566 opacity,
567 quality: FilterQuality::Bilinear,
568 ..PixmapPaint::default()
569 };
570 pixmap.draw_pixmap(
571 0,
572 0,
573 layer.as_ref(),
574 &paint,
575 to_pixmap.pre_translate(x, y),
576 None,
577 );
578 }
579
580 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
581 self.work.nodes += 1;
582 if let Some(shadow) = style.shadow.filter(|shadow| !shadow.follow_content) {
584 self.shadow(pixmap, node.rect(), style, &shadow);
585 }
586 self.draw_box(pixmap, node.rect(), style);
587 match node.content() {
588 Content::Text(text) => self.text(pixmap, &text),
589 Content::Icon(icon) => self.icon(pixmap, &icon),
590 Content::Image(image) => self.image(pixmap, &image),
591 Content::Capture(capture) => self.capture(pixmap, &capture),
592 Content::Input(input) => self.input(pixmap, &input),
593 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
594 Content::None => {}
595 }
596 if node.clips() {
597 self.clipped_children(pixmap, node, style);
598 } else {
599 for child in node.children() {
600 self.node(pixmap, child);
601 }
602 }
603 }
604
605 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
610 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
611 return;
612 };
613 let width = self.border_width(style);
614 let Some(inside) = tiny_skia::Rect::from_ltrb(
615 area.left() + width,
616 area.top() + width,
617 area.right() - width,
618 area.bottom() - width,
619 ) else {
620 return;
621 };
622 let corners = inset(corners, width);
623 self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
624 for child in node.children() {
625 painter.node(layer, child);
626 }
627 if let Some((handle, bar)) = node.scroll_bar() {
629 painter.draw_box(layer, handle, &bar);
630 }
631 });
632 }
633
634 fn through_mask(
637 &mut self,
638 pixmap: &mut PixmapMut<'_>,
639 cover: Rect,
640 (shape, corners): (tiny_skia::Rect, Corners),
641 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
642 ) {
643 if !visible(pixmap, shape) {
644 return;
645 }
646 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
647 Mask::new(pixmap.width(), pixmap.height()),
648 self.grid.cover(cover, pixmap.width(), pixmap.height()),
649 ) else {
650 return;
651 };
652 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
653 return;
654 };
655 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
656 let mut inner = self.on(self.grid.moved(x, y));
657 draw(&mut inner, &mut layer.as_mut());
658 let mut path = PathBuilder::new();
659 rounded_rect(&mut path, shape, corners);
660 let Some(path) = path.finish() else {
661 return;
662 };
663 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
664 pixmap.draw_pixmap(
665 x as i32,
666 y as i32,
667 layer.as_ref(),
668 &PixmapPaint::default(),
669 Transform::identity(),
670 Some(&mask),
671 );
672 }
673
674 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
678 let area = self.grid.rect(rect)?;
679 let most = area.width().min(area.height()) / 2.0;
680 let corners = style.radius.unwrap_or_default().corners().map(|radius| {
681 let radius = (radius * self.grid.scale).clamp(0.0, most);
682 if radius.is_nan() { 0.0 } else { radius }
683 });
684 Some((area, corners))
685 }
686
687 fn border_width(&self, style: &Style) -> f32 {
690 let Some(border) = style.border else {
691 return 0.0;
692 };
693 let width = (border.width * self.grid.scale).floor();
694 if border.width > 0.0 {
695 width.max(1.0)
696 } else {
697 width.max(0.0)
698 }
699 }
700
701 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
703 if style.background.is_none() && style.gradient.is_none() && style.border.is_none() {
704 return;
705 }
706 let Some((area, corners)) = self.box_shape(rect, style) else {
707 return;
708 };
709 if !visible(pixmap, area) {
710 return;
711 }
712
713 if let Some(color) = style.background {
714 let mut path = PathBuilder::new();
715 rounded_rect(&mut path, area, corners);
716 fill(pixmap, path, color, FillRule::Winding);
717 }
718 if let Some(gradient) = style.gradient {
719 let mut path = PathBuilder::new();
720 rounded_rect(&mut path, area, corners);
721 if let (Some(path), Some(shader)) = (path.finish(), self.shader(&gradient, area)) {
722 let paint = Paint {
723 shader,
724 anti_alias: true,
725 ..Paint::default()
726 };
727 pixmap.fill_path(
728 &path,
729 &paint,
730 FillRule::Winding,
731 Transform::identity(),
732 None,
733 );
734 }
735 }
736 if let Some(border) = style.border {
737 let width = self.border_width(style);
738 let dashed = width >= 1.0
739 && style.border_dash.is_some_and(|dash| {
740 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
741 });
742
743 if width >= 1.0 && !dashed {
744 let mut path = PathBuilder::new();
746 rounded_rect(&mut path, area, corners);
747 if let Some(inner) = tiny_skia::Rect::from_ltrb(
748 area.left() + width,
749 area.top() + width,
750 area.right() - width,
751 area.bottom() - width,
752 ) {
753 rounded_rect(&mut path, inner, inset(corners, width));
754 }
755 fill(pixmap, path, border.color, FillRule::EvenOdd);
756 }
757 }
758 }
759
760 fn dashed_border(
766 &self,
767 pixmap: &mut PixmapMut<'_>,
768 (area, corners): (tiny_skia::Rect, Corners),
769 width: f32,
770 color: Color,
771 (on, off): (f32, f32),
772 ) -> bool {
773 let Grid {
774 scale, left, top, ..
775 } = self.grid;
776 let half = width / 2.0;
777 let Some(middle) = tiny_skia::Rect::from_ltrb(
778 area.left() + left + half,
779 area.top() + top + half,
780 area.right() + left - half,
781 area.bottom() + top - half,
782 ) else {
783 return false;
784 };
785 let corners = inset(corners, half);
786 let rounding: f32 = corners
788 .iter()
789 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
790 .sum();
791 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
792 let Some((on, off)) = fit_dash(perimeter, on * scale, off * scale) else {
793 return false;
794 };
795 let mut path = PathBuilder::new();
796 rounded_rect(&mut path, middle, corners);
797 let phase = on / 2.0;
801 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], phase)) else {
802 return false;
803 };
804 let Some(dashes) = path.dash(&dash, 1.0) else {
805 return true;
806 };
807 let reach = 2.0 * width + 1.0;
812 let near = [
813 left - reach,
814 top - reach,
815 left + pixmap.width() as f32 + reach,
816 top + pixmap.height() as f32 + reach,
817 ];
818 let mut kept = PathBuilder::new();
819 let mut contour = Vec::new();
820 for segment in dashes.segments() {
821 if matches!(segment, PathSegment::MoveTo(_)) {
822 keep_near(&mut kept, &contour, near);
823 contour.clear();
824 }
825 contour.push(segment);
826 }
827 keep_near(&mut kept, &contour, near);
828 let Some(kept) = kept.finish() else {
829 return true;
830 };
831 let stroke = Stroke {
832 width,
833 line_cap: if on == 0.0 {
835 LineCap::Round
836 } else {
837 LineCap::Butt
838 },
839 line_join: LineJoin::Miter,
840 ..Stroke::default()
841 };
842 let mut paint = Paint::default();
843 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
844 paint.anti_alias = true;
845 let moved = Transform::from_translate(-left, -top);
846 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
847 true
848 }
849
850 fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
855 let Grid {
856 scale, left, top, ..
857 } = self.grid;
858 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
859 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
860 return;
861 }
862 let Some((area, corners)) = self.box_shape(rect, style) else {
863 return;
864 };
865 let spread = shadow.spread * scale;
867 let Some(shape) = tiny_skia::Rect::from_ltrb(
868 area.left() + left + shadow.x * scale - spread,
869 area.top() + top + shadow.y * scale - spread,
870 area.right() + left + shadow.x * scale + spread,
871 area.bottom() + top + shadow.y * scale + spread,
872 ) else {
873 return;
874 };
875 let most = shape.width().min(shape.height()) / 2.0;
878 let corners = corners.map(|radius| {
879 let radius = if spread > 0.0 && radius < spread {
880 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
881 } else {
882 radius + spread
883 };
884 radius.clamp(0.0, most)
885 });
886 let cut = if shadow.cut_out {
888 self.box_mask(pixmap, rect, style)
889 } else {
890 None
891 };
892 let sigma = shadow.blur.max(0.0) * scale / 2.0;
894 if sigma < 0.25 {
895 let mut path = PathBuilder::new();
896 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
897 return;
898 };
899 rounded_rect(&mut path, shape, corners);
900 let Some(path) = path.finish() else {
901 return;
902 };
903 let mut paint = Paint::default();
904 let color = shadow.color;
905 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
906 paint.anti_alias = true;
907 let outside = cut.map(|mut cut| {
908 cut.invert();
909 cut
910 });
911 let (rule, at) = (FillRule::Winding, Transform::identity());
912 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
913 return;
914 }
915 let reach = 3.0 * sigma;
916 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
917 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
918 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
919 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
920 if columns.is_empty() || rows.is_empty() {
921 return;
922 }
923 let blurred = BlurredBox::new(shape, corners, sigma);
924 let mut mask = Vec::with_capacity(columns.len() * rows.len());
925 for row in rows.clone() {
926 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
927 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
928 }
929 if let Some(cut) = cut {
930 let stride = pixmap.width() as usize;
931 let under = rows.clone().flat_map(|row| {
932 columns
933 .clone()
934 .map(move |column| row as usize * stride + column as usize)
935 });
936 for (alpha, at) in mask.iter_mut().zip(under) {
937 *alpha = mul(*alpha, 255 - cut.data()[at]);
938 }
939 }
940 let width = columns.len() as u32;
941 let height = rows.len() as u32;
942 let (x, y) = (columns.start as i32, rows.start as i32);
943 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
944 }
945
946 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
949 let (area, corners) = self.box_shape(rect, style)?;
950 let mut path = PathBuilder::new();
951 rounded_rect(&mut path, area, corners);
952 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
953 let (rule, at) = (FillRule::Winding, Transform::identity());
954 mask.fill_path(&path.finish()?, rule, true, at);
955 Some(mask)
956 }
957
958 fn shader(&self, gradient: &Gradient, area: tiny_skia::Rect) -> Option<Shader<'static>> {
962 let (left, top) = (area.left() + self.grid.left, area.top() + self.grid.top);
963 let (width, height) = (area.width(), area.height());
964 let middle = tiny_skia::Point::from_xy(left + width / 2.0, top + height / 2.0);
965 let given = gradient.stops();
966 let mut stops = Vec::with_capacity(given.len() * 2);
967 let stop = |at: f32, color: Color, alpha: u8| {
968 GradientStop::new(
969 at,
970 tiny_skia::Color::from_rgba8(color.r, color.g, color.b, alpha),
971 )
972 };
973 for (index, &(at, color)) in given.iter().enumerate() {
974 if color.a > 0 {
975 stops.push(stop(at, color, color.a));
976 continue;
977 }
978 for neighbor in [index.checked_sub(1), Some(index + 1)]
982 .into_iter()
983 .flatten()
984 {
985 if let Some(&(_, near)) = given.get(neighbor) {
986 stops.push(stop(at, near, 0));
987 }
988 }
989 }
990 let moved = Transform::from_translate(-self.grid.left, -self.grid.top);
991 match gradient.shape {
992 GradientShape::Linear(angle) => {
993 let (sin, cos) = angle.to_radians().sin_cos();
996 let half = (width * sin.abs() + height * cos.abs()) / 2.0;
997 let (dx, dy) = (sin * half, -cos * half);
998 let start = tiny_skia::Point::from_xy(middle.x - dx, middle.y - dy);
999 let end = tiny_skia::Point::from_xy(middle.x + dx, middle.y + dy);
1000 LinearGradient::new(start, end, stops, SpreadMode::Pad, moved)
1001 }
1002 GradientShape::Radial => {
1003 let reach = (width * width + height * height).sqrt() / 2.0;
1004 RadialGradient::new(middle, 0.0, middle, reach, stops, SpreadMode::Pad, moved)
1005 }
1006 GradientShape::Sweep(angle) => {
1007 let turn = Transform::from_rotate_at(angle - 90.0, middle.x, middle.y);
1011 let at = moved.pre_concat(turn);
1012 SweepGradient::new(middle, 0.0, 360.0, stops, SpreadMode::Pad, at)
1013 }
1014 }
1015 }
1016
1017 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1021 let color = text.color();
1022 if color.a == 0 {
1023 return;
1024 }
1025 let Grid {
1026 scale, left, top, ..
1027 } = self.grid;
1028 let origin = text.origin();
1029 let x = origin.x * scale - left;
1030 for run in text.runs() {
1031 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1033 if baseline + run.line_height * scale < 0.0
1034 || baseline - run.line_height * scale > pixmap.height() as f32
1035 {
1036 continue;
1037 }
1038 for glyph in run.glyphs {
1039 let physical = glyph.physical((x, baseline), scale);
1040 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1041 continue;
1042 };
1043 let left = physical.x + image.placement.left;
1044 let top = physical.y - image.placement.top;
1045 let (width, height) = (image.placement.width, image.placement.height);
1046 match image.content {
1047 SwashContent::Mask => {
1048 blend_mask(pixmap, left, top, width, height, &image.data, color);
1049 }
1050 SwashContent::Color => {
1051 let premultiplied = is_color_outline(image);
1052 let rgba = (image.data.as_slice(), premultiplied);
1053 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1054 }
1055 SwashContent::SubpixelMask => {}
1057 }
1058 }
1059 }
1060 }
1061
1062 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1064 let Some(area) = self.grid.rect(input.area) else {
1065 return;
1066 };
1067 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1068 painter.input_contents(layer, input);
1069 });
1070 }
1071
1072 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1075 let color = input.text.color();
1076 for selection in input.selection {
1077 let Some(area) = self.grid.rect(*selection) else {
1078 continue;
1079 };
1080 let mut path = PathBuilder::new();
1081 path.push_rect(area);
1082 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1083 fill(pixmap, path, tint, FillRule::Winding);
1084 }
1085 self.text(pixmap, &input.text);
1086 for line in input.underline {
1087 if let Some(area) = self.grid.rect(*line) {
1088 let mut path = PathBuilder::new();
1089 path.push_rect(area);
1090 fill(pixmap, path, color, FillRule::Winding);
1091 }
1092 }
1093 if let Some(caret) = input.caret {
1094 let left = self.grid.x(caret.x);
1096 let right = self.grid.x(caret.right()).max(left + 1.0);
1097 if let Some(area) = tiny_skia::Rect::from_ltrb(
1098 left,
1099 self.grid.y(caret.y),
1100 right,
1101 self.grid.y(caret.bottom()),
1102 ) {
1103 let mut path = PathBuilder::new();
1104 path.push_rect(area);
1105 fill(pixmap, path, color, FillRule::Winding);
1106 }
1107 }
1108 }
1109
1110 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1112 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1113 return;
1114 };
1115 match self.icons.image(image, (width, height), self.grid.scale) {
1116 Some(Drawn::One(pixels)) => transition::blit(pixmap, (x, y), pixels),
1117 Some(Drawn::Two { from, to, t }) => {
1118 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1119 }
1120 None => {}
1121 }
1122 }
1123
1124 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1126 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1127 return;
1128 };
1129 let frame = capture.frame;
1130 if let Some(pixels) = self
1131 .icons
1132 .capture(capture.id, frame, width, height, capture.fit)
1133 {
1134 draw_at(pixmap, x, y, pixels);
1135 }
1136 }
1137
1138 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1143 let Grid {
1144 scale, left, top, ..
1145 } = self.grid;
1146 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1147 let (x, y) = (
1148 (rect.x * scale).round() - left,
1149 (rect.y * scale).round() - top,
1150 );
1151 if !(width >= 1.0 && height >= 1.0) {
1152 return None;
1153 }
1154 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1155 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1157 }
1158
1159 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1161 let Grid {
1162 scale, left, top, ..
1163 } = self.grid;
1164 let side = (icon.rect.width * scale).round();
1165 if side.is_nan() || side < 1.0 {
1166 return;
1167 }
1168 let x = (icon.rect.x * scale).round() - left;
1169 let y = (icon.rect.y * scale).round() - top;
1170 let size = icon.rect.width.round() as u32;
1172 let theme_scale = scale.ceil().max(1.0) as u32;
1173 let sizes = (side as u32, size, theme_scale);
1174 if let Some(image) = self.icons.get(icon.source, sizes, icon.tint) {
1175 pixmap.draw_pixmap(
1176 x as i32,
1177 y as i32,
1178 image.as_ref(),
1179 &PixmapPaint::default(),
1180 Transform::identity(),
1181 None,
1182 );
1183 }
1184 }
1185}
1186
1187fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1189 let paint = PixmapPaint::default();
1190 pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1191}
1192
1193fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1195 area.right() > 0.0
1196 && area.bottom() > 0.0
1197 && area.left() < pixmap.width() as f32
1198 && area.top() < pixmap.height() as f32
1199}
1200
1201fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1202 let Some(path) = path.finish() else {
1203 return;
1204 };
1205 let mut paint = Paint::default();
1206 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1207 paint.anti_alias = true;
1208 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1209}
1210
1211type Corners = [f32; 4];
1213
1214fn inset(corners: Corners, by: f32) -> Corners {
1216 corners.map(|radius| (radius - by).max(0.0))
1217}
1218
1219fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1222 if corners.iter().all(|&radius| radius <= 0.0) {
1223 path.push_rect(rect);
1224 return;
1225 }
1226 const KAPPA: f32 = 0.552_284_8;
1229 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1230 let [top_left, top_right, bottom_right, bottom_left] = corners;
1231 let k = |radius: f32| radius * (1.0 - KAPPA);
1232 path.move_to(l + top_left, t);
1233 path.line_to(r - top_right, t);
1234 if top_right > 0.0 {
1235 let k = k(top_right);
1236 path.cubic_to(r - k, t, r, t + k, r, t + top_right);
1237 }
1238 path.line_to(r, b - bottom_right);
1239 if bottom_right > 0.0 {
1240 let k = k(bottom_right);
1241 path.cubic_to(r, b - k, r - k, b, r - bottom_right, b);
1242 }
1243 path.line_to(l + bottom_left, b);
1244 if bottom_left > 0.0 {
1245 let k = k(bottom_left);
1246 path.cubic_to(l + k, b, l, b - k, l, b - bottom_left);
1247 }
1248 path.line_to(l, t + top_left);
1249 if top_left > 0.0 {
1250 let k = k(top_left);
1251 path.cubic_to(l, t + k, l + k, t, l + top_left, t);
1252 }
1253 path.close();
1254}
1255
1256fn mul(a: u8, b: u8) -> u8 {
1258 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1259}
1260
1261fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1263 let rest = 255 - source[3];
1264 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1265 *channel = value.saturating_add(mul(*channel, rest));
1266 }
1267}
1268
1269fn overlap(
1273 pixmap: &PixmapMut<'_>,
1274 left: i32,
1275 top: i32,
1276 width: u32,
1277 height: u32,
1278) -> Option<(usize, usize, usize, usize)> {
1279 let column_start = (-i64::from(left)).max(0);
1280 let row_start = (-i64::from(top)).max(0);
1281 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1282 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1283 (column_start < column_end && row_start < row_end).then_some((
1284 column_start as usize,
1285 column_end as usize,
1286 row_start as usize,
1287 row_end as usize,
1288 ))
1289}
1290
1291fn blend_mask(
1293 pixmap: &mut PixmapMut<'_>,
1294 left: i32,
1295 top: i32,
1296 width: u32,
1297 height: u32,
1298 mask: &[u8],
1299 color: Color,
1300) {
1301 if mask.len() < width as usize * height as usize {
1302 return;
1303 }
1304 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1305 else {
1306 return;
1307 };
1308 let stride = pixmap.width() as usize;
1309 let data = pixmap.data_mut();
1310 for row in rows..rows_end {
1311 for column in columns..columns_end {
1312 let coverage = mask[row * width as usize + column];
1313 if coverage == 0 {
1314 continue;
1315 }
1316 let alpha = mul(color.a, coverage);
1317 let source = [
1318 mul(color.r, alpha),
1319 mul(color.g, alpha),
1320 mul(color.b, alpha),
1321 alpha,
1322 ];
1323 let x = (i64::from(left) + column as i64) as usize;
1324 let y = (i64::from(top) + row as i64) as usize;
1325 over(data, (y * stride + x) * 4, source);
1326 }
1327 }
1328}
1329
1330const SAMPLES: usize = 8;
1332
1333struct BlurredBox {
1340 middle: (f32, f32),
1341 half: (f32, f32),
1342 corners: Corners,
1343 largest: f32,
1344 sigma: f32,
1345}
1346
1347impl BlurredBox {
1348 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1349 BlurredBox {
1350 middle: (
1351 (shape.left() + shape.right()) / 2.0,
1352 (shape.top() + shape.bottom()) / 2.0,
1353 ),
1354 half: (shape.width() / 2.0, shape.height() / 2.0),
1355 corners,
1356 largest: corners.into_iter().fold(0.0, f32::max),
1357 sigma,
1358 }
1359 }
1360
1361 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1364 let y = y - self.middle.1;
1365 let (half_width, half_height) = self.half;
1366 let reach = 3.0 * self.sigma;
1367 let down = self.along(y, half_height);
1368 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1369 let rows = if clear_of_corners {
1370 [(0.0, 0.0, 0.0); SAMPLES]
1371 } else {
1372 self.rows_near(y)
1373 };
1374 for x in xs {
1375 let x = x - self.middle.0;
1376 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1377 self.along(x, half_width) * down
1378 } else {
1379 let sum: f32 = rows
1380 .iter()
1381 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1382 .sum();
1383 sum.clamp(0.0, 1.0)
1384 };
1385 mask.push((coverage * 255.0).round() as u8);
1386 }
1387 }
1388
1389 fn along(&self, p: f32, half: f32) -> f32 {
1391 self.between(p, half, half)
1392 }
1393
1394 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1397 let reach = 3.0 * self.sigma;
1398 if -(left - reach) <= p && p <= right - reach {
1399 return 1.0;
1400 }
1401 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1402 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1403 }
1404
1405 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1409 let (half_width, half_height) = self.half;
1410 let reach = 3.0 * self.sigma;
1411 let start = (y - half_height).clamp(-reach, reach);
1412 let end = (y + half_height).clamp(-reach, reach);
1413 let step = (end - start) / SAMPLES as f32;
1414 std::array::from_fn(|sample| {
1415 let offset = start + step * (sample as f32 + 0.5);
1416 let row = y - offset;
1419 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1420 let (left, right) = if row < 0.0 {
1421 (top_left, top_right)
1422 } else {
1423 (bottom_left, bottom_right)
1424 };
1425 let span = |radius: f32| {
1426 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1427 half_width - radius
1428 + (radius * radius - into_corner * into_corner)
1429 .max(0.0)
1430 .sqrt()
1431 };
1432 (span(left), span(right), gaussian(offset, self.sigma) * step)
1433 })
1434 }
1435}
1436
1437fn gaussian(x: f32, sigma: f32) -> f32 {
1439 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1440 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1441}
1442
1443fn erf(x: f32) -> f32 {
1446 let a = x.abs();
1447 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1448 let d = d * d;
1449 (1.0 - 1.0 / (d * d)).copysign(x)
1450}
1451
1452fn is_color_outline(image: &SwashImage) -> bool {
1459 format!("{:?}", image.source).starts_with("ColorOutline")
1460}
1461
1462fn blend_rgba(
1465 pixmap: &mut PixmapMut<'_>,
1466 left: i32,
1467 top: i32,
1468 width: u32,
1469 height: u32,
1470 (rgba, premultiplied): (&[u8], bool),
1471 opacity: u8,
1472) {
1473 if rgba.len() < width as usize * height as usize * 4 {
1474 return;
1475 }
1476 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1477 else {
1478 return;
1479 };
1480 let stride = pixmap.width() as usize;
1481 let data = pixmap.data_mut();
1482 for row in rows..rows_end {
1483 for column in columns..columns_end {
1484 let index = (row * width as usize + column) * 4;
1485 let alpha = mul(rgba[index + 3], opacity);
1486 if alpha == 0 {
1487 continue;
1488 }
1489 let factor = if premultiplied { opacity } else { alpha };
1492 let source = [
1493 mul(rgba[index], factor),
1494 mul(rgba[index + 1], factor),
1495 mul(rgba[index + 2], factor),
1496 alpha,
1497 ];
1498 let x = (i64::from(left) + column as i64) as usize;
1499 let y = (i64::from(top) + row as i64) as usize;
1500 over(data, (y * stride + x) * 4, source);
1501 }
1502 }
1503}
1504
1505fn keep_near(
1508 kept: &mut PathBuilder,
1509 contour: &[PathSegment],
1510 [left, top, right, bottom]: [f32; 4],
1511) {
1512 let (mut low, mut high) = (
1513 (f32::INFINITY, f32::INFINITY),
1514 (f32::NEG_INFINITY, f32::NEG_INFINITY),
1515 );
1516 let points = contour.iter().flat_map(|segment| match *segment {
1517 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1518 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1519 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1520 PathSegment::Close => [None; 3],
1521 });
1522 for point in points.flatten() {
1523 low = (low.0.min(point.x), low.1.min(point.y));
1524 high = (high.0.max(point.x), high.1.max(point.y));
1525 }
1526 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1527 return;
1528 }
1529 for segment in contour {
1530 match *segment {
1531 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1532 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1533 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1534 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1535 PathSegment::Close => kept.close(),
1536 }
1537 }
1538}
1539
1540pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1545 let period = on + off;
1546 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1547 return None;
1548 }
1549 let count = (perimeter / period).round().max(1.0);
1550 let stretch = perimeter / (count * period);
1551 Some((on * stretch, off * stretch))
1552}