1use std::collections::HashMap;
10use std::sync::Arc;
11use std::sync::atomic::AtomicU64;
12
13use cosmic_text::{FontSystem, LayoutGlyph, SwashCache, SwashContent, SwashImage};
14use crabshell_ui::{
15 Affine, CaptureView, Color, Content, IconView, ImageView, InputView, NodeView, Radii, Rect,
16 Shadow, Size, Span, Style, TextSystem, TextView, WindowView,
17};
18use tiny_skia::{
19 FillRule, FilterQuality, LineCap, LineJoin, Mask, Paint, PathBuilder, PathSegment, Pixmap,
20 PixmapMut, PixmapPaint, Stroke, StrokeDash, Transform,
21};
22
23use crate::damage::{BufferAge, DamageHistory, PixelRect};
24use crate::icons::{Drawn, Icons};
25use crate::theme::IconLookup;
26
27mod canvas;
28mod effects;
29mod gradient;
30mod kept;
31mod patched;
32mod transition;
33
34pub(crate) use kept::Kept;
35use kept::{Area, Layer, Seen, Want};
36#[cfg(test)]
37pub(crate) use kept::{KEPT_LIMIT, PATCHES};
38
39const TILE: u32 = 64;
44
45#[cfg(test)]
46thread_local! {
47 pub(crate) static TILE_SIDE: std::cell::Cell<u32> = const { std::cell::Cell::new(TILE) };
50}
51
52fn tile_side() -> u32 {
54 #[cfg(test)]
55 return TILE_SIDE.get();
56 #[cfg(not(test))]
57 TILE
58}
59
60const GLYPH_CACHE_LIMIT: usize = 2048;
63
64const LAYER_LIMIT: u64 = 1 << 22;
68
69const LAYER_MARGIN: f32 = 2.0;
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum PixelFormat {
77 Argb8888,
79 Abgr8888,
81}
82
83pub struct Canvas<'a> {
85 pub pixels: &'a mut [u8],
87 pub width: u32,
91 pub height: u32,
93 pub scale: f32,
95 pub format: PixelFormat,
97 pub age: &'a mut BufferAge,
99}
100
101pub struct Renderer {
104 glyphs: SwashCache,
105 icons: Icons,
106 scratch: Vec<u8>,
109 work: Work,
110 kept: Arc<AtomicU64>,
113 theme: u64,
115}
116
117#[derive(Default)]
120#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
121struct Work {
122 layer_pixels: u64,
124 nodes: u64,
126 skipped: u64,
128 blurred: u64,
130 gradient_pixels: std::cell::Cell<u64>,
133}
134
135impl Renderer {
136 pub fn new() -> Renderer {
139 Renderer {
140 glyphs: SwashCache::new(),
141 icons: Icons::new(),
142 scratch: Vec::new(),
143 work: Work::default(),
144 kept: Arc::default(),
145 theme: 0,
146 }
147 }
148
149 #[cfg(test)]
151 pub(crate) fn kept_bytes(&self) -> u64 {
152 self.kept.load(std::sync::atomic::Ordering::Relaxed)
153 }
154
155 #[cfg(test)]
157 pub(crate) fn spend_kept(&self, bytes: u64) {
158 self
159 .kept
160 .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
161 }
162
163 #[cfg(test)]
165 pub(crate) fn image_lookups(&self) -> usize {
166 self.icons.lookups()
167 }
168
169 #[cfg(test)]
171 pub(crate) fn cached_glyphs(&self) -> usize {
172 self.glyphs.image_cache.len()
173 }
174
175 #[cfg(test)]
178 pub(crate) fn work(&self) -> (u64, u64, u64) {
179 (self.work.layer_pixels, self.work.nodes, self.work.blurred)
180 }
181
182 #[cfg(test)]
184 pub(crate) fn skipped_nodes(&self) -> u64 {
185 self.work.skipped
186 }
187
188 #[cfg(test)]
190 pub(crate) fn gradient_pixels(&self) -> u64 {
191 self.work.gradient_pixels.get()
192 }
193
194 #[cfg(test)]
197 pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
198 Renderer {
199 icons: Icons::with_themes(crate::theme::Themes::new(bases)),
200 ..Renderer::new()
201 }
202 }
203
204 pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
207 self.icons.set_theme(theme.into());
208 self.theme += 1;
209 }
210
211 pub fn icon_lookup(&self) -> IconLookup {
214 self.icons.lookup()
215 }
216
217 #[cfg(test)]
219 pub(crate) fn cached_bytes(&self) -> usize {
220 self.icons.cached_bytes()
221 }
222
223 #[cfg(test)]
225 pub(crate) fn cached_icons(&self) -> usize {
226 self.icons.cached()
227 }
228
229 #[cfg(test)]
231 pub(crate) fn rasterized_icons(&self) -> usize {
232 self.icons.rasterized()
233 }
234
235 pub fn forget_captures(&mut self, gone: &[u64]) {
239 self.icons.forget_captures(gone);
240 }
241
242 pub fn decode_off_thread(&mut self) {
255 self.icons.decode_off_thread();
256 }
257
258 pub fn load_images(&mut self, view: &WindowView<'_>, scale: f32) {
265 self.icons.load_unseen(&view.loading_images(), scale);
266 }
267
268 pub fn decoding(&self) -> bool {
271 self.icons.decoding()
272 }
273
274 pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
278 self.icons.wake_when_decoded(Box::new(wake));
279 }
280
281 pub fn waits_for_pictures(&self) -> bool {
284 self.icons.waited()
285 }
286
287 pub fn take_decoded(&mut self) -> Vec<u64> {
293 self.icons.take_decoded()
294 }
295
296 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
301 self.icons.next_frame(now)
302 }
303
304 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
310 self.icons.advance(now)
311 }
312
313 #[cfg(test)]
315 pub(crate) fn decoded_off_thread(&self) -> usize {
316 self.icons.worker_work().0
317 }
318
319 #[cfg(test)]
321 pub(crate) fn decoder_running(&self) -> bool {
322 self.icons.worker_work().1
323 }
324
325 #[cfg(test)]
327 pub(crate) fn cached_captures(&self) -> usize {
328 self.icons.captures()
329 }
330
331 pub fn draw(
352 &mut self,
353 view: &WindowView<'_>,
354 damage: &[Rect],
355 text: &mut TextSystem,
356 history: &mut DamageHistory,
357 canvas: Canvas<'_>,
358 ) -> Result<Vec<PixelRect>, CanvasError> {
359 let Canvas {
360 pixels,
361 width,
362 height,
363 scale,
364 format,
365 age,
366 } = canvas;
367 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
368 || !(scale.is_finite() && scale > 0.0)
369 {
370 return Err(CanvasError {
371 width,
372 height,
373 scale,
374 bytes: pixels.len(),
375 });
376 }
377 self.icons.start_frame(history.id(), view.has_images());
378 let plan = history.plan(damage, scale, width, height, age);
379 history.kept.start(&self.kept, self.theme);
380 let tile = tile_side();
381 let mut tiles: Vec<(u32, u32)> = Vec::new();
382 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
383 for row in area.y / tile..=(area.y + area.height - 1) / tile {
384 tiles
385 .extend((area.x / tile..=(area.x + area.width - 1) / tile).map(|column| (row, column)));
386 }
387 }
388 tiles.sort_unstable();
389 tiles.dedup();
390 let mut casts = HashMap::new();
391 let mut fonts = text.font_system();
392 for &(row, column) in &tiles {
393 self.icons.start_tile((row, column));
394 let (x, y) = (column * tile, row * tile);
395 let size = (width.saturating_sub(x), height.saturating_sub(y));
396 let area = PixelRect::new(x, y, tile.min(size.0), tile.min(size.1));
397 self.scratch.clear();
398 self.scratch.resize(area.area() as usize * 4, 0);
399 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
400 else {
401 continue;
402 };
403 let mut painter = Painter {
404 grid: Grid {
405 scale,
406 zoom: 1.0,
407 linear: Affine {
408 sx: 1.0,
409 ky: 0.0,
410 kx: 0.0,
411 sy: 1.0,
412 tx: 0.0,
413 ty: 0.0,
414 },
415 window: view.size(),
416 width,
417 height,
418 left: area.x as f32,
419 top: area.y as f32,
420 },
421 glyphs: &mut self.glyphs,
422 icons: &mut self.icons,
423 fonts: &mut fonts,
424 work: &mut self.work,
425 casts: &mut casts,
426 kept: &mut history.kept,
427 clip: Some(Rect::new(0.0, 0.0, view.size().width, view.size().height)),
428 extent: [0, 0, width, height],
429 };
430 painter.node(&mut pixmap, view.root());
431 copy(&self.scratch, area, pixels, width, format);
432 }
433 history.kept.end();
434 self.icons.repainted(&tiles);
435 self.icons.end_frame();
436 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
437 self.glyphs.image_cache.clear();
438 self.glyphs.outline_command_cache.clear();
439 }
440 Ok(plan.report)
441 }
442}
443
444#[derive(Clone, Copy, Debug, PartialEq)]
447pub struct CanvasError {
448 pub width: u32,
450 pub height: u32,
452 pub scale: f32,
454 pub bytes: usize,
456}
457
458impl std::fmt::Display for CanvasError {
459 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
460 write!(
461 f,
462 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
463 self.width,
464 self.height,
465 self.scale,
466 u64::from(self.width) * u64::from(self.height) * 4,
467 self.bytes
468 )
469 }
470}
471
472impl std::error::Error for CanvasError {}
473
474impl Default for Renderer {
475 fn default() -> Self {
476 Self::new()
477 }
478}
479
480fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
482 let stride = width as usize * 4;
483 let row_bytes = area.width as usize * 4;
484 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
485 let start = (area.y as usize + row) * stride + area.x as usize * 4;
486 let target = &mut pixels[start..start + row_bytes];
487 match format {
488 PixelFormat::Abgr8888 => target.copy_from_slice(source),
489 PixelFormat::Argb8888 => {
490 let (to, _) = target.as_chunks_mut::<4>();
491 let (from, _) = source.as_chunks::<4>();
492 for (to, from) in to.iter_mut().zip(from) {
495 let pixel = u32::from_le_bytes(*from);
496 *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
497 }
498 }
499 }
500 }
501}
502
503#[derive(Clone, Copy)]
505struct Grid {
506 scale: f32,
508 zoom: f32,
511 linear: Affine,
514 window: Size,
516 width: u32,
518 height: u32,
519 left: f32,
521 top: f32,
522}
523
524impl Grid {
525 fn x(&self, x: f32) -> f32 {
528 let pixel = if x >= self.window.width {
529 self.width as f32
530 } else {
531 (x * self.scale).round()
532 };
533 pixel - self.left
534 }
535
536 fn y(&self, y: f32) -> f32 {
538 let pixel = if y >= self.window.height {
539 self.height as f32
540 } else {
541 (y * self.scale).round()
542 };
543 pixel - self.top
544 }
545
546 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
550 if !(rect.width > 0.0 && rect.height > 0.0) {
551 return None;
552 }
553 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
555 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
556 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
557 let bottom =
558 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
559 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
560 }
561
562 fn through(&self, transform: Affine) -> (Affine, f32, f32) {
565 let (outer, inner) = (self.linear, transform);
566 let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0).pre_concat(
567 Transform::from_row(inner.sx, inner.ky, inner.kx, inner.sy, 0.0, 0.0),
568 );
569 let linear = Affine {
570 sx: linear.sx,
571 ky: linear.ky,
572 kx: linear.kx,
573 sy: linear.sy,
574 tx: 0.0,
575 ty: 0.0,
576 };
577 let zoom = linear.layer_zoom();
578 (linear, zoom, self.scale / self.zoom * zoom)
579 }
580
581 fn moved(&self, x: u32, y: u32) -> Grid {
583 Grid {
584 left: self.left + x as f32,
585 top: self.top + y as f32,
586 ..*self
587 }
588 }
589
590 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
593 tiny_skia::Rect::from_ltrb(
594 self.x(rect.x),
595 self.y(rect.y),
596 self.x(rect.right()),
597 self.y(rect.bottom()),
598 )
599 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
600 }
601}
602
603struct Painter<'a> {
605 grid: Grid,
606 glyphs: &'a mut SwashCache,
607 icons: &'a mut Icons,
608 fonts: &'a mut FontSystem,
609 work: &'a mut Work,
610 casts: &'a mut HashMap<CastKey, effects::Cast>,
612 kept: &'a mut Kept,
614 clip: Option<Rect>,
618 extent: [u32; 4],
622}
623
624type CastKey = (String, i64, i64);
627
628impl Painter<'_> {
629 fn on(&mut self, grid: Grid) -> Painter<'_> {
631 Painter {
632 grid,
633 glyphs: &mut *self.glyphs,
634 icons: &mut *self.icons,
635 fonts: &mut *self.fonts,
636 work: &mut *self.work,
637 casts: &mut *self.casts,
638 kept: &mut *self.kept,
639 clip: self.clip,
640 extent: self.extent,
641 }
642 }
643
644 fn narrowed(&self, rect: Rect) -> [u32; 4] {
646 let window = Grid {
647 left: 0.0,
648 top: 0.0,
649 ..self.grid
650 };
651 let [left, top, right, bottom] = self.extent;
652 match window.cover(rect, window.width, window.height) {
653 Some((x, y, width, height)) => [
654 left.max(x),
655 top.max(y),
656 right.min(x + width),
657 bottom.min(y + height),
658 ],
659 None => [0; 4],
660 }
661 }
662
663 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
668 let Some((x, y, width, height)) =
670 self
671 .grid
672 .cover(node.bounds(), pixmap.width(), pixmap.height())
673 else {
674 return;
675 };
676 let style = node.style();
677 let opacity = style.opacity.unwrap_or(1.0);
678 let opacity = if opacity.is_nan() {
679 1.0
680 } else {
681 opacity.clamp(0.0, 1.0)
682 };
683 if opacity == 0.0 {
684 self.skip(node);
685 return;
686 }
687 let shadow = effects::cast_by_content(&style);
688 let region = node
691 .mask_region()
692 .filter(|_| node.transform().is_none() && shadow.is_none())
693 .map(|region| {
694 let inner = self.on(self.grid.moved(x, y));
695 inner.region_cover(width, height, node.rect(), region)
696 });
697 if matches!(region, Some(effects::Cover::Clear)) {
698 self.skip(node);
699 return;
700 }
701 if let Some(transform) = node.transform() {
702 self.transformed(pixmap, node, &style, transform, opacity);
703 } else if opacity < 1.0
704 || style.mask.is_some()
705 || matches!(region, Some(effects::Cover::Part(_)))
706 || shadow.is_some()
707 {
708 if opacity < 1.0 && self.kept_fade(pixmap, node, &style, shadow, opacity) {
709 return;
710 }
711 let Some(mut layer) = Pixmap::new(width, height) else {
713 return;
714 };
715 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
716 let mut inner = self.on(self.grid.moved(x, y));
717 inner.extent = inner.narrowed(node.bounds());
718 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow, region);
719 composite(pixmap, (x as i32, y as i32), &layer, opacity, None);
720 } else {
721 self.node_contents(pixmap, node, &style);
722 }
723 }
724
725 fn skip(&mut self, node: NodeView<'_>) {
732 if self.icons.look_through(node.path()) {
733 let (grid, clip) = (self.grid, self.clip);
734 self.skipped(node, grid, clip, false);
735 }
736 }
737
738 fn keep_inside(&mut self, node: NodeView<'_>) {
741 if self.icons.keep_through(node.path()) {
742 let (grid, clip) = (self.grid, self.clip);
743 self.skipped(node, grid, clip, true);
744 }
745 }
746
747 fn skipped(
751 &mut self,
752 node: NodeView<'_>,
753 mut grid: Grid,
754 mut clip: Option<Rect>,
755 captures: bool,
756 ) {
757 self.work.skipped += 1;
758 if let Some(transform) = node.transform() {
759 (grid.linear, grid.zoom, grid.scale) = grid.through(transform);
760 clip = None;
763 }
764 let shows =
765 |clip: Option<Rect>, rect: Rect| clip.is_none_or(|clip| !clip.intersect(rect).is_empty());
766 match node.content() {
767 Content::Image(image) if shows(clip, image.rect) => {
768 let (width, height) = (
769 (image.rect.width * grid.scale).round(),
770 (image.rect.height * grid.scale).round(),
771 );
772 if width >= 1.0 && height >= 1.0 {
773 let size = (width as u32, height as u32);
775 self.icons.skipped(&image, size, grid.scale);
776 }
777 }
778 Content::Capture(capture) if captures && shows(clip, capture.rect) => {
779 self.icons.keep_capture(capture.id);
780 }
781 _ => {}
782 }
783 if node.clips() {
784 let rect = node.rect();
785 clip = Some(clip.map_or(rect, |clip| clip.intersect(rect)));
786 }
787 for child in node.children() {
788 if shows(clip, child.bounds()) {
789 self.skipped(child, grid, clip, captures);
790 }
791 }
792 }
793
794 fn keeps(
801 &mut self,
802 node: NodeView<'_>,
803 (opacity, transform): (f32, Option<Affine>),
804 want: Want,
805 fill: impl FnOnce(&mut Painter<'_>, Area) -> Option<Pixmap>,
806 ) -> bool {
807 let frame = self.kept.frame;
808 if let Some(seen) = self.kept.seen.get(node.path())
809 && seen.frame == frame
810 {
811 return seen.layer.is_some();
812 }
813 let seen = self.kept.seen.remove(node.path());
814 let revision = node.revision();
815 let keep = seen.as_ref().is_some_and(|seen| {
819 seen.revision == revision
820 && match transform {
821 Some(_) => seen.transform != transform,
822 None => seen.opacity != opacity,
823 }
824 });
825 let Want { needed, whole, at } = want;
826 let fits = |layer: &Layer| layer.area.holds(&needed) && layer.at == at;
827 let mut layer = seen
828 .and_then(|seen| seen.layer)
829 .filter(|layer| keep && fits(layer));
830 let pixels = |area: &Area| u64::from(area.width) * u64::from(area.height);
831 let area = [whole, needed]
834 .into_iter()
835 .find(|area| pixels(area) <= LAYER_LIMIT);
836 if keep
837 && layer.is_none()
838 && let Some(area) = area
839 {
840 let (nested, playing) = self.inside(node);
842 let refused = playing || nested && transform.is_some();
843 let held = (!refused).then(|| self.kept.hold(pixels(&area) * 4));
844 if let Some(held) = held.flatten()
845 && let Some(pixmap) = fill(self, area)
846 {
847 layer = Some(Layer {
848 pixmap,
849 area,
850 at,
851 _held: held,
852 });
853 }
854 }
855 let kept = layer.is_some();
856 self.kept.seen.insert(
857 node.path().to_owned(),
858 Seen {
859 frame,
860 revision,
861 opacity,
862 transform,
863 layer,
864 },
865 );
866 kept
867 }
868
869 fn inside(&self, node: NodeView<'_>) -> (bool, bool) {
873 let active = matches!(
874 node.content(),
875 Content::Image(image) if self.icons.animates(image.id) || image.leaving.is_some()
876 );
877 node
878 .children()
879 .fold((false, active), |(nested, playing), child| {
880 let (deeper, plays) = self.inside(child);
881 (
882 nested || deeper || child.transform().is_some(),
883 playing || plays,
884 )
885 })
886 }
887
888 fn kept_fade(
892 &mut self,
893 pixmap: &mut PixmapMut<'_>,
894 node: NodeView<'_>,
895 style: &Style,
896 shadow: Option<Shadow>,
897 opacity: f32,
898 ) -> bool {
899 let Some(clip) = self.clip else {
900 return false;
901 };
902 let window = Grid {
903 left: 0.0,
904 top: 0.0,
905 ..self.grid
906 };
907 let Some((x, y, width, height)) =
908 window.cover(node.bounds().intersect(clip), window.width, window.height)
909 else {
910 return false;
911 };
912 let area = Area {
913 x: x as i32,
914 y: y as i32,
915 width,
916 height,
917 };
918 let want = Want {
919 needed: area,
920 whole: area,
921 at: (window.scale, window.zoom),
922 };
923 let fill = |painter: &mut Painter<'_>, _: Area| {
924 let mut kept = Pixmap::new(width, height)?;
925 let side = tile_side();
926 for row in y / side..=(y + height - 1) / side {
927 for column in x / side..=(x + width - 1) / side {
928 let [ex, ey, ex1, ey1] = painter.extent;
931 let (left, top) = ((column * side).max(ex), (row * side).max(ey));
932 let right = ((column + 1) * side).min(window.width).min(ex1);
933 let bottom = ((row + 1) * side).min(window.height).min(ey1);
934 if left >= right || top >= bottom {
935 continue;
936 }
937 let tile = window.moved(left, top);
938 let size = (right - left, bottom - top);
939 let Some((dx, dy, w, h)) = tile.cover(node.bounds(), size.0, size.1) else {
940 continue;
941 };
942 let mut layer = Pixmap::new(w, h)?;
943 painter.work.layer_pixels += u64::from(w) * u64::from(h);
944 let extent = painter.narrowed(node.bounds());
945 let mut inner = painter.on(tile.moved(dx, dy));
946 inner.extent = extent;
947 inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
948 let at = ((left + dx) as i32 - area.x, (top + dy) as i32 - area.y);
949 transition::blit(&mut kept.as_mut(), at, &layer);
950 }
951 }
952 Some(kept)
953 };
954 if !self.keeps(node, (opacity, None), want, fill) {
955 return false;
956 }
957 self.keep_inside(node);
958 let Some(layer) = self.kept.layer(node.path()) else {
959 return false;
960 };
961 let at = (
963 layer.area.x - self.grid.left as i32,
964 layer.area.y - self.grid.top as i32,
965 );
966 composite(pixmap, at, &layer.pixmap, opacity, None);
967 true
968 }
969
970 fn layer_contents(
975 &mut self,
976 layer: &mut PixmapMut<'_>,
977 node: NodeView<'_>,
978 style: &Style,
979 shadow: Option<Shadow>,
980 cover: Option<effects::Cover>,
981 ) {
982 self.node_contents(layer, node, style);
983 if let Some(mask) = &style.mask {
984 self.mask(layer, node.rect(), mask);
985 }
986 let (width, height) = (layer.width(), layer.height());
987 let cover = cover.or_else(|| {
988 let region = node.mask_region()?;
989 Some(self.region_cover(width, height, node.rect(), region))
990 });
991 match cover {
992 Some(effects::Cover::Clear) => layer.fill(tiny_skia::Color::TRANSPARENT),
993 Some(effects::Cover::Part(cut)) => layer.apply_mask(&cut),
994 Some(effects::Cover::Whole) | None => {}
995 }
996 if let Some(shadow) = shadow {
997 self.content_shadow(layer, node, &shadow);
998 }
999 }
1000
1001 fn transformed(
1008 &mut self,
1009 pixmap: &mut PixmapMut<'_>,
1010 node: NodeView<'_>,
1011 style: &Style,
1012 transform: Affine,
1013 opacity: f32,
1014 ) {
1015 let Affine {
1016 sx,
1017 ky,
1018 kx,
1019 sy,
1020 tx,
1021 ty,
1022 } = transform;
1023 let Grid {
1024 scale, left, top, ..
1025 } = self.grid;
1026 let zoomed = self.grid.through(transform);
1027 let layer_scale = zoomed.2;
1028 let device = Transform::from_scale(scale, scale)
1030 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
1031 .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
1032 let to_pixmap = device.post_translate(-left, -top);
1033 if let Some(clip) = self.clip {
1034 let shown = tiny_skia::Rect::from_ltrb(
1036 (clip.x * scale).floor(),
1037 (clip.y * scale).floor(),
1038 (clip.right() * scale).ceil(),
1039 (clip.bottom() * scale).ceil(),
1040 );
1041 let needed = shown.and_then(|shown| layer_area(node, device, Some(shown), layer_scale));
1042 let whole = layer_area(node, device, None, layer_scale);
1043 if let (Some(needed), Some(whole)) = (needed, whole) {
1044 let want = Want {
1045 needed,
1046 whole,
1047 at: (layer_scale, zoomed.1),
1048 };
1049 let fill =
1050 |painter: &mut Painter<'_>, area| painter.transformed_layer(node, style, area, zoomed);
1051 if self.keeps(node, (opacity, Some(transform)), want, fill) {
1052 self.keep_inside(node);
1053 if let Some(layer) = self.kept.layer(node.path()) {
1054 let corner = (layer.area.x as f32, layer.area.y as f32);
1055 let at = to_pixmap.pre_translate(corner.0, corner.1);
1056 blend_transformed(pixmap, &layer.pixmap, at, opacity);
1057 return;
1058 }
1059 }
1060 }
1061 }
1062 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32);
1063 let Some(area) = shown.and_then(|shown| layer_area(node, to_pixmap, Some(shown), layer_scale))
1064 else {
1065 return;
1066 };
1067 let pixels = u64::from(area.width) * u64::from(area.height);
1068 if pixels > LAYER_LIMIT {
1069 tracing::debug!(
1070 "{} is transformed into a layer too large to draw",
1071 node.path()
1072 );
1073 return;
1074 }
1075 let Some(layer) = self.transformed_layer(node, style, area, zoomed) else {
1076 return;
1077 };
1078 let at = to_pixmap.pre_translate(area.x as f32, area.y as f32);
1079 blend_transformed(pixmap, &layer, at, opacity);
1080 }
1081
1082 fn transformed_layer(
1085 &mut self,
1086 node: NodeView<'_>,
1087 style: &Style,
1088 area: Area,
1089 (linear, zoom, layer_scale): (Affine, f32, f32),
1090 ) -> Option<Pixmap> {
1091 let mut layer = Pixmap::new(area.width, area.height)?;
1092 self.work.layer_pixels += u64::from(area.width) * u64::from(area.height);
1093 let (width, height) = if zoom == self.grid.zoom {
1094 (self.grid.width, self.grid.height)
1095 } else {
1096 let window = self.grid.window;
1098 (
1099 (window.width * layer_scale).round() as u32,
1100 (window.height * layer_scale).round() as u32,
1101 )
1102 };
1103 let mut inner = self.on(Grid {
1104 scale: layer_scale,
1105 zoom,
1106 linear,
1107 width,
1108 height,
1109 left: area.x as f32,
1110 top: area.y as f32,
1111 ..self.grid
1112 });
1113 inner.clip = None;
1114 let shadow = effects::cast_by_content(style);
1115 inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
1116 Some(layer)
1117 }
1118
1119 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
1120 self.work.nodes += 1;
1121 let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
1124 if let Some(shadow) = style.shadow.filter(outside) {
1125 self.shadow(pixmap, node.rect(), style, &shadow);
1126 }
1127 self.draw_box(pixmap, node.rect(), style);
1128 match node.content() {
1129 Content::Text(text) => {
1130 let color = text.color();
1131 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1132 self.selection(pixmap, &text.selection(), tint);
1133 self.text(pixmap, &text);
1134 }
1135 Content::Icon(icon) => self.icon(pixmap, &icon),
1136 Content::Image(image) => self.image(pixmap, &image),
1137 Content::Capture(capture) => self.capture(pixmap, &capture),
1138 Content::Input(input) => self.input(pixmap, &input),
1139 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
1140 Content::None => {}
1141 }
1142 if node.clips() {
1143 self.clipped_children(pixmap, node, style);
1144 } else {
1145 for child in node.children() {
1146 self.node(pixmap, child);
1147 }
1148 }
1149 }
1150
1151 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
1156 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
1157 return;
1158 };
1159 let width = self.border_width(style);
1160 let Some(inside) = tiny_skia::Rect::from_ltrb(
1161 area.left() + width,
1162 area.top() + width,
1163 area.right() - width,
1164 area.bottom() - width,
1165 ) else {
1166 return;
1167 };
1168 let corners = inset(corners, width);
1169 let rect = node.rect();
1170 self.through_mask(pixmap, rect, (inside, corners), |painter, layer| {
1171 painter.clip = painter.clip.map(|clip| clip.intersect(rect));
1172 for child in node.children() {
1173 painter.node(layer, child);
1174 }
1175 for (handle, bar) in node.scroll_bars() {
1177 painter.draw_box(layer, handle, &bar);
1178 }
1179 });
1180 }
1181
1182 fn through_mask(
1185 &mut self,
1186 pixmap: &mut PixmapMut<'_>,
1187 cover: Rect,
1188 (shape, corners): (tiny_skia::Rect, Corners),
1189 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
1190 ) {
1191 if !visible(pixmap, shape) {
1192 return;
1193 }
1194 let extent = self.narrowed(cover);
1195 if covers(pixmap, shape, corners) {
1196 let grid = self.grid;
1198 let mut inner = self.on(grid);
1199 inner.extent = extent;
1200 draw(&mut inner, pixmap);
1201 return;
1202 }
1203 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
1204 Mask::new(pixmap.width(), pixmap.height()),
1205 self.grid.cover(cover, pixmap.width(), pixmap.height()),
1206 ) else {
1207 return;
1208 };
1209 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
1210 return;
1211 };
1212 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
1213 let mut inner = self.on(self.grid.moved(x, y));
1214 inner.extent = extent;
1215 draw(&mut inner, &mut layer.as_mut());
1216 let mut path = PathBuilder::new();
1217 rounded_rect(&mut path, shape, corners);
1218 let Some(path) = path.finish() else {
1219 return;
1220 };
1221 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1222 composite(pixmap, (x as i32, y as i32), &layer, 1.0, Some(&mask));
1223 }
1224
1225 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
1229 let area = self.grid.rect(rect)?;
1230 let corners = style.radius.unwrap_or_default().corners();
1231 let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
1232 Some((area, corners))
1233 }
1234
1235 fn border_width(&self, style: &Style) -> f32 {
1238 let Some(border) = style.border else {
1239 return 0.0;
1240 };
1241 let width = (border.width * self.grid.scale).floor();
1242 if border.width > 0.0 {
1243 width.max(1.0)
1244 } else {
1245 width.max(0.0)
1246 }
1247 }
1248
1249 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
1252 let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
1253 if style.background.is_none()
1254 && style.gradient.is_none()
1255 && style.border.is_none()
1256 && inset_shadow.is_none()
1257 {
1258 return;
1259 }
1260 let Some((area, corners)) = self.box_shape(rect, style) else {
1261 return;
1262 };
1263 if !visible(pixmap, area) {
1264 return;
1265 }
1266
1267 if let Some(color) = style.background
1268 && !(covers(pixmap, area, corners) && fill_all(pixmap, color))
1269 && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
1270 {
1271 let mut path = PathBuilder::new();
1272 rounded_rect(&mut path, area, corners);
1273 fill(pixmap, path, color, FillRule::Winding);
1274 }
1275 if let Some(gradient) = style.gradient {
1276 let mut path = PathBuilder::new();
1277 rounded_rect(&mut path, area, corners);
1278 let size = (pixmap.width(), pixmap.height());
1279 if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
1280 ramp.fill(pixmap, &path);
1281 }
1282 }
1283 if let Some(shadow) = inset_shadow {
1284 self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
1285 }
1286 if let Some(border) = style.border {
1287 let width = self.border_width(style);
1288 let inner = tiny_skia::Rect::from_ltrb(
1289 area.left() + width,
1290 area.top() + width,
1291 area.right() - width,
1292 area.bottom() - width,
1293 );
1294 if inner.is_some_and(|inner| covers(pixmap, inner, inset(corners, width))) {
1296 return;
1297 }
1298 let dashed = width >= 1.0
1299 && style.border_dash.is_some_and(|dash| {
1300 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
1301 });
1302
1303 if width >= 1.0 && !dashed {
1304 let mut path = PathBuilder::new();
1306 rounded_rect(&mut path, area, corners);
1307 if let Some(inner) = inner {
1308 rounded_rect(&mut path, inner, inset(corners, width));
1309 }
1310 fill(pixmap, path, border.color, FillRule::EvenOdd);
1311 }
1312 }
1313 }
1314
1315 fn dashed_border(
1321 &self,
1322 pixmap: &mut PixmapMut<'_>,
1323 (area, corners): (tiny_skia::Rect, Corners),
1324 width: f32,
1325 color: Color,
1326 (on, off): (f32, f32),
1327 ) -> bool {
1328 let Grid {
1329 scale, left, top, ..
1330 } = self.grid;
1331 let half = width / 2.0;
1332 let Some(middle) = tiny_skia::Rect::from_ltrb(
1333 area.left() + left + half,
1334 area.top() + top + half,
1335 area.right() + left - half,
1336 area.bottom() + top - half,
1337 ) else {
1338 return false;
1339 };
1340 let corners = inset(corners, half);
1341 let (on, off) = (on * scale, off * scale);
1342 let mut all = PathBuilder::new();
1343 let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
1344 if square.is_empty() {
1345 let rounding: f32 = corners
1348 .iter()
1349 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
1350 .sum();
1351 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
1352 let mut path = PathBuilder::new();
1353 rounded_rect(&mut path, middle, corners);
1354 if !dash_into(&mut all, path, perimeter, on, off) {
1355 return false;
1356 }
1357 } else {
1358 for (at, &from) in square.iter().enumerate() {
1361 let to = square[(at + 1) % square.len()];
1362 let steps = (to + 4 - from - 1) % 4 + 1;
1363 let [.., mut was] = corner(middle, corners, from);
1364 let mut path = PathBuilder::new();
1365 path.move_to(was.x, was.y);
1366 let mut length = 0.0;
1367 for index in (from + 1..=from + steps).map(|index| index % 4) {
1368 let [start, one, two, end] = corner(middle, corners, index);
1369 path.line_to(start.x, start.y);
1370 length += was.distance(start);
1371 if corners[index] > 0.0 {
1372 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1373 length += std::f32::consts::FRAC_PI_2 * corners[index];
1374 }
1375 was = end;
1376 }
1377 if !dash_into(&mut all, path, length, on, off) {
1378 return false;
1379 }
1380 }
1381 if on > 0.0 {
1385 const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
1387 for &index in &square {
1388 let [point, ..] = corner(middle, corners, index);
1389 let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
1390 all.move_to(point.x - half * ax, point.y - half * ay);
1391 all.line_to(point.x, point.y);
1392 all.line_to(point.x + half * bx, point.y + half * by);
1393 }
1394 }
1395 }
1396 let Some(dashes) = all.finish() else {
1397 return true;
1398 };
1399 let reach = 2.0 * width + 1.0;
1404 let near = [
1405 left - reach,
1406 top - reach,
1407 left + pixmap.width() as f32 + reach,
1408 top + pixmap.height() as f32 + reach,
1409 ];
1410 let mut kept = PathBuilder::new();
1411 let mut contour = Vec::new();
1412 for segment in dashes.segments() {
1413 if matches!(segment, PathSegment::MoveTo(_)) {
1414 keep_near(&mut kept, &contour, near);
1415 contour.clear();
1416 }
1417 contour.push(segment);
1418 }
1419 keep_near(&mut kept, &contour, near);
1420 let Some(kept) = kept.finish() else {
1421 return true;
1422 };
1423 let stroke = Stroke {
1424 width,
1425 line_cap: if on == 0.0 {
1427 LineCap::Round
1428 } else {
1429 LineCap::Butt
1430 },
1431 line_join: LineJoin::Miter,
1432 ..Stroke::default()
1433 };
1434 let mut paint = Paint::default();
1435 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1436 paint.anti_alias = true;
1437 let moved = Transform::from_translate(-left, -top);
1438 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1439 true
1440 }
1441
1442 fn shadow(&mut self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1449 let Grid {
1450 scale, left, top, ..
1451 } = self.grid;
1452 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1453 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1454 return;
1455 }
1456 let Some((area, corners)) = self.box_shape(rect, style) else {
1457 return;
1458 };
1459 if shadow.cut_out && covers(pixmap, area, corners) {
1460 return;
1461 }
1462 let spread = shadow.spread * scale;
1464 let Some(shape) = tiny_skia::Rect::from_ltrb(
1465 area.left() + left + shadow.x * scale - spread,
1466 area.top() + top + shadow.y * scale - spread,
1467 area.right() + left + shadow.x * scale + spread,
1468 area.bottom() + top + shadow.y * scale + spread,
1469 ) else {
1470 return;
1471 };
1472 let corners = fit(spread_corners(corners, spread), shape);
1473 let cut = if shadow.cut_out {
1475 self.box_mask(pixmap, rect, style)
1476 } else {
1477 None
1478 };
1479 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1481 if sigma < 0.25 {
1482 let mut path = PathBuilder::new();
1483 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1484 return;
1485 };
1486 rounded_rect(&mut path, shape, corners);
1487 let Some(path) = path.finish() else {
1488 return;
1489 };
1490 let mut paint = Paint::default();
1491 let color = shadow.color;
1492 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1493 paint.anti_alias = true;
1494 let outside = cut.map(|mut cut| {
1495 cut.invert();
1496 cut
1497 });
1498 let (rule, at) = (FillRule::Winding, Transform::identity());
1499 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1500 return;
1501 }
1502 let reach = 3.0 * sigma;
1503 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1504 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1505 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1506 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1507 if columns.is_empty() || rows.is_empty() {
1508 return;
1509 }
1510 let patch = patched::Patch::key(shape, corners, sigma).and_then(|key| self.kept.patch(key));
1511 let blurred = patch
1512 .is_none()
1513 .then(|| BlurredBox::new(shape, corners, sigma));
1514 let stride = pixmap.width() as usize;
1515 let clear = |column: u32| {
1518 cut.as_ref().is_some_and(|cut| {
1519 let at = |row: u32| row as usize * stride + column as usize;
1520 rows.clone().all(|row| cut.data()[at(row)] == 255)
1521 })
1522 };
1523 let mut start = columns.start;
1524 while start < columns.end {
1525 if clear(start) {
1526 start += 1;
1527 continue;
1528 }
1529 let end = (start + 1..columns.end)
1530 .find(|&column| clear(column))
1531 .unwrap_or(columns.end);
1532 let run = start..end;
1533 start = end;
1534 let mut mask = Vec::with_capacity(run.len() * rows.len());
1535 for row in rows.clone() {
1536 match (patch, &blurred) {
1537 (Some(patch), _) => {
1538 let columns = run.clone().map(|column| left as i64 + i64::from(column));
1540 patch.row(shape, top as i64 + i64::from(row), columns, &mut mask);
1541 }
1542 (None, Some(blurred)) => {
1543 let xs = run.clone().map(|column| left + column as f32 + 0.5);
1544 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1545 }
1546 (None, None) => {}
1547 }
1548 }
1549 if let Some(cut) = &cut {
1550 let under = rows.clone().flat_map(|row| {
1551 run
1552 .clone()
1553 .map(move |column| row as usize * stride + column as usize)
1554 });
1555 for (alpha, at) in mask.iter_mut().zip(under) {
1556 *alpha = mul(*alpha, 255 - cut.data()[at]);
1557 }
1558 }
1559 let width = run.len() as u32;
1560 let height = rows.len() as u32;
1561 let (x, y) = (run.start as i32, rows.start as i32);
1562 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1563 }
1564 }
1565
1566 fn inset_shadow(
1571 &self,
1572 pixmap: &mut PixmapMut<'_>,
1573 (area, corners): (tiny_skia::Rect, Corners),
1574 border: f32,
1575 shadow: &Shadow,
1576 ) {
1577 let Grid {
1578 scale, left, top, ..
1579 } = self.grid;
1580 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1581 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1582 return;
1583 }
1584 let Some(inside) = tiny_skia::Rect::from_ltrb(
1585 area.left() + border,
1586 area.top() + border,
1587 area.right() - border,
1588 area.bottom() - border,
1589 ) else {
1590 return;
1591 };
1592 let inside_corners = inset(corners, border);
1593 if !visible(pixmap, inside) {
1594 return;
1595 }
1596 let mut path = PathBuilder::new();
1597 rounded_rect(&mut path, inside, inside_corners);
1598 let Some(path) = path.finish() else {
1599 return;
1600 };
1601 let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1603 let hole = tiny_skia::Rect::from_ltrb(
1604 inside.left() + left + x + spread,
1605 inside.top() + top + y + spread,
1606 inside.right() + left + x - spread,
1607 inside.bottom() + top + y - spread,
1608 );
1609 let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1610 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1611 let color = shadow.color;
1612 if sigma < 0.25 {
1613 let mut outside = None;
1614 if let Some((hole, corners)) = hole {
1615 let mut cut = PathBuilder::new();
1616 let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1617 return;
1618 };
1619 rounded_rect(&mut cut, moved, corners);
1620 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1621 return;
1622 };
1623 let (rule, at) = (FillRule::Winding, Transform::identity());
1624 let Some(cut) = cut.finish() else {
1625 return;
1626 };
1627 mask.fill_path(&cut, rule, true, at);
1628 mask.invert();
1629 outside = Some(mask);
1630 }
1631 let mut paint = Paint::default();
1632 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1633 paint.anti_alias = true;
1634 let (rule, at) = (FillRule::Winding, Transform::identity());
1635 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1636 return;
1637 }
1638 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1641 return;
1642 };
1643 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1644 let columns = inside.left().floor().max(0.0) as u32
1645 ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1646 let rows = inside.top().floor().max(0.0) as u32
1647 ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1648 if columns.is_empty() || rows.is_empty() {
1649 return;
1650 }
1651 let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1652 let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1653 for row in rows.clone() {
1654 let start = alpha.len();
1655 match &blurred {
1656 Some(blurred) => {
1657 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1658 blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1659 }
1660 None => alpha.resize(start + columns.len(), 0),
1661 }
1662 let stride = pixmap.width() as usize;
1663 let row = &mask.data()[row as usize * stride..];
1664 let covered = &row[columns.start as usize..columns.end as usize];
1665 for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1666 *value = mul(255 - *value, covered);
1667 }
1668 }
1669 let (width, height) = (columns.len() as u32, rows.len() as u32);
1670 let (x, y) = (columns.start as i32, rows.start as i32);
1671 blend_mask(pixmap, x, y, width, height, &alpha, color);
1672 }
1673
1674 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1677 let (area, corners) = self.box_shape(rect, style)?;
1678 let mut path = PathBuilder::new();
1679 rounded_rect(&mut path, area, corners);
1680 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1681 let (rule, at) = (FillRule::Winding, Transform::identity());
1682 mask.fill_path(&path.finish()?, rule, true, at);
1683 Some(mask)
1684 }
1685
1686 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1691 let Grid {
1692 scale, left, top, ..
1693 } = self.grid;
1694 let origin = text.origin();
1695 let x = origin.x * scale - left;
1696 for run in text.runs() {
1697 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1699 if baseline + run.line_height * scale < 0.0
1700 || baseline - run.line_height * scale > pixmap.height() as f32
1701 {
1702 continue;
1703 }
1704 let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1706 true => text.link_hover_color().or(span.color),
1707 false => span.color,
1708 };
1709 for glyph in run.glyphs.iter() {
1710 let span = text.span(run.line_i, glyph);
1711 let color = text.selected_color(run.line_i, glyph);
1712 let color = color.or_else(|| span.and_then(|span| span_color(span, glyph)));
1713 let color = color.unwrap_or(text.color());
1714 if color.a == 0 {
1715 continue;
1716 }
1717 let physical = glyph.physical((x, baseline), scale);
1718 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1719 continue;
1720 };
1721 let left = physical.x + image.placement.left;
1722 let top = physical.y - image.placement.top;
1723 let (width, height) = (image.placement.width, image.placement.height);
1724 match image.content {
1725 SwashContent::Mask => {
1726 blend_mask(pixmap, left, top, width, height, &image.data, color);
1727 }
1728 SwashContent::Color => {
1729 let premultiplied = is_color_outline(image);
1730 let rgba = (image.data.as_slice(), premultiplied);
1731 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1732 }
1733 SwashContent::SubpixelMask => {}
1735 }
1736 }
1737 let origin = text.origin().x;
1738 let own = (text.underline(), text.strikethrough());
1739 if own != (false, false) {
1740 self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1741 }
1742 let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1746 text.span(run.line_i, a),
1747 text.span(run.line_i, b),
1748 ) {
1749 (Some(a), Some(b)) => std::ptr::eq(a, b),
1750 (a, b) => a.is_none() && b.is_none(),
1751 };
1752 for glyphs in run.glyphs.chunk_by(same_span) {
1753 let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1754 continue;
1755 };
1756 let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1757 let lines = (span.underline || lit, span.strikethrough);
1758 if lines != (false, false) {
1759 let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1760 self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1761 }
1762 }
1763 }
1764 }
1765
1766 fn decorations(
1770 &mut self,
1771 pixmap: &mut PixmapMut<'_>,
1772 origin: f32,
1773 glyphs: &[LayoutGlyph],
1774 baseline: f32,
1775 lines: (bool, bool),
1776 color: Color,
1777 ) {
1778 let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1779 (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1780 };
1781 for glyphs in glyphs.chunk_by(same_font) {
1782 self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1783 }
1784 }
1785
1786 fn font_decorations(
1792 &mut self,
1793 pixmap: &mut PixmapMut<'_>,
1794 origin: f32,
1795 glyphs: &[LayoutGlyph],
1796 baseline: f32,
1797 (underline, strikethrough): (bool, bool),
1798 color: Color,
1799 ) {
1800 let Some(first) = glyphs.first() else {
1801 return;
1802 };
1803 let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1804 return;
1805 };
1806 let metrics = font.metrics();
1807 let em = f32::from(metrics.units_per_em);
1808 if em == 0.0 {
1809 return;
1810 }
1811 let Grid { scale, left, .. } = self.grid;
1812 let (start, end) = glyphs
1813 .iter()
1814 .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1815 (start.min(glyph.x), end.max(glyph.x + glyph.w))
1816 });
1817 let x0 = ((origin + start) * scale).round() - left;
1818 let x1 = ((origin + end) * scale).round() - left;
1819 let size = first.font_size * scale;
1820 let lines = [
1822 (underline, metrics.underline, -0.125),
1823 (strikethrough, metrics.strikeout, 0.3),
1824 ];
1825 for (on, decoration, offset) in lines {
1826 if !on {
1827 continue;
1828 }
1829 let (offset, thickness) =
1830 decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1831 let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1833 let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1834 if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1835 let mut path = PathBuilder::new();
1836 path.push_rect(area);
1837 fill(pixmap, path, color, FillRule::Winding);
1838 }
1839 }
1840 }
1841
1842 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1844 let Some(area) = self.grid.rect(input.area) else {
1845 return;
1846 };
1847 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1848 painter.input_contents(layer, input);
1849 });
1850 }
1851
1852 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1855 let color = input.text.color();
1856 self.selection(pixmap, input.selection, input.selection_color);
1857 self.text(pixmap, &input.text);
1858 for line in input.underline {
1859 if let Some(area) = self.grid.rect(*line) {
1860 let mut path = PathBuilder::new();
1861 path.push_rect(area);
1862 fill(pixmap, path, color, FillRule::Winding);
1863 }
1864 }
1865 if let Some(caret) = input.caret {
1866 let left = self.grid.x(caret.x);
1868 let right = self.grid.x(caret.right()).max(left + 1.0);
1869 if let Some(area) = tiny_skia::Rect::from_ltrb(
1870 left,
1871 self.grid.y(caret.y),
1872 right,
1873 self.grid.y(caret.bottom()),
1874 ) {
1875 let mut path = PathBuilder::new();
1876 path.push_rect(area);
1877 fill(pixmap, path, color, FillRule::Winding);
1878 }
1879 }
1880 }
1881
1882 fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], tint: Color) {
1884 for span in spans {
1885 if let Some(area) = self.grid.rect(*span) {
1886 let mut path = PathBuilder::new();
1887 path.push_rect(area);
1888 fill(pixmap, path, tint, FillRule::Winding);
1889 }
1890 }
1891 }
1892
1893 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1895 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1896 return;
1897 };
1898 match self.icons.image(image, (width, height), self.grid.scale) {
1899 Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1900 transition::blit(pixmap, (x, y), pixels);
1901 }
1902 Some(Drawn::One(pixels)) => {
1904 let paint = PixmapPaint {
1905 quality: FilterQuality::Bilinear,
1906 ..PixmapPaint::default()
1907 };
1908 let stretch = Transform::from_scale(
1909 width as f32 / pixels.width() as f32,
1910 height as f32 / pixels.height() as f32,
1911 )
1912 .post_translate(x as f32, y as f32);
1913 pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1914 }
1915 Some(Drawn::Two { from, to, t }) => {
1916 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1917 }
1918 None => {}
1919 }
1920 }
1921
1922 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1924 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1925 return;
1926 };
1927 let frame = capture.frame;
1928 let Some([left, top, part_width, part_height]) = frame.drawn_part(capture.crop) else {
1931 return;
1932 };
1933 let crop = capture.crop.and_then(|_| {
1934 let sides = [left, top, part_width, part_height].map(|side| side as i32);
1936 tiny_skia::IntRect::from_xywh(sides[0], sides[1], part_width, part_height)
1937 });
1938 let size = (width, height);
1939 if let Some(pixels) = self
1940 .icons
1941 .capture(capture.id, frame, size, capture.fit, crop)
1942 {
1943 transition::blit(pixmap, (x, y), pixels);
1944 }
1945 }
1946
1947 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1952 let Grid {
1953 scale, left, top, ..
1954 } = self.grid;
1955 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1956 let (x, y) = (
1957 (rect.x * scale).round() - left,
1958 (rect.y * scale).round() - top,
1959 );
1960 if !(width >= 1.0 && height >= 1.0) {
1961 return None;
1962 }
1963 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1964 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1966 }
1967
1968 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1970 let Grid {
1971 scale, left, top, ..
1972 } = self.grid;
1973 let side = (icon.rect.width * scale).round();
1974 if side.is_nan() || side < 1.0 {
1975 return;
1976 }
1977 let x = (icon.rect.x * scale).round() - left;
1978 let y = (icon.rect.y * scale).round() - top;
1979 let size = icon.rect.width.round() as u32;
1981 let theme_scale = scale.ceil().max(1.0) as u32;
1982 let sizes = (side as u32, size, theme_scale);
1983 let source = match icon.fallback {
1985 Some(fallback) if self.icons.get(icon.source, sizes, icon.tint).is_none() => fallback,
1986 _ => icon.source,
1987 };
1988 if let Some(image) = self.icons.get(source, sizes, icon.tint) {
1989 transition::blit(pixmap, (x as i32, y as i32), image);
1991 }
1992 }
1993}
1994
1995fn covers(pixmap: &PixmapMut<'_>, shape: tiny_skia::Rect, corners: Corners) -> bool {
1999 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2000 let (left, top, right, bottom) = (shape.left(), shape.top(), shape.right(), shape.bottom());
2001 if !(left <= 0.0 && top <= 0.0 && right >= width && bottom >= height) {
2002 return false;
2003 }
2004 corners.iter().enumerate().all(|(index, &radius)| {
2006 let x = if matches!(index, 0 | 3) {
2007 left
2008 } else {
2009 right - radius
2010 };
2011 let y = if index < 2 { top } else { bottom - radius };
2012 radius <= 0.0 || x + radius <= 0.0 || x >= width || y + radius <= 0.0 || y >= height
2013 })
2014}
2015
2016fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
2018 area.right() > 0.0
2019 && area.bottom() > 0.0
2020 && area.left() < pixmap.width() as f32
2021 && area.top() < pixmap.height() as f32
2022}
2023
2024fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
2025 let Some(path) = path.finish() else {
2026 return;
2027 };
2028 let mut paint = Paint::default();
2029 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
2030 paint.anti_alias = true;
2031 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
2032}
2033
2034type Corners = [f32; 4];
2036
2037fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
2042 let Some((on, off)) = fit_dash(length, on, off) else {
2043 return false;
2044 };
2045 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
2046 return false;
2047 };
2048 if let Some(dashes) = path.dash(&dash, 1.0) {
2049 all.push_path(&dashes);
2050 }
2051 true
2052}
2053
2054fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
2058 const KAPPA: f32 = 0.552_284_8;
2061 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
2062 let radius = corners[index];
2063 let k = radius * (1.0 - KAPPA);
2064 let points = match index {
2065 0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
2066 1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
2067 2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
2068 _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
2069 };
2070 points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
2071}
2072
2073fn spread_corners(corners: Corners, spread: f32) -> Corners {
2077 corners.map(|radius| {
2078 if spread > 0.0 && radius < spread {
2079 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
2080 } else {
2081 (radius + spread).max(0.0)
2082 }
2083 })
2084}
2085
2086fn fit(
2088 [top_left, top_right, bottom_right, bottom_left]: Corners,
2089 area: tiny_skia::Rect,
2090) -> Corners {
2091 let radii = Radii {
2092 top_left,
2093 top_right,
2094 bottom_right,
2095 bottom_left,
2096 };
2097 radii.fit(area.width(), area.height()).corners()
2098}
2099
2100fn inset(corners: Corners, by: f32) -> Corners {
2102 corners.map(|radius| (radius - by).max(0.0))
2103}
2104
2105fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
2108 if corners.iter().all(|&radius| radius <= 0.0) {
2109 path.push_rect(rect);
2110 return;
2111 }
2112 let [.., start] = corner(rect, corners, 0);
2113 path.move_to(start.x, start.y);
2114 for index in [1, 2, 3, 0] {
2115 let [start, one, two, end] = corner(rect, corners, index);
2116 path.line_to(start.x, start.y);
2117 if corners[index] > 0.0 {
2118 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
2119 }
2120 }
2121 path.close();
2122}
2123
2124fn mul(a: u8, b: u8) -> u8 {
2126 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
2127}
2128
2129fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
2131 let rest = 255 - source[3];
2132 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
2133 *channel = value.saturating_add(mul(*channel, rest));
2134 }
2135}
2136
2137fn layer_area(
2142 node: NodeView<'_>,
2143 to_target: Transform,
2144 shown: Option<tiny_skia::Rect>,
2145 layer_scale: f32,
2146) -> Option<Area> {
2147 let inner = node.inner_bounds();
2148 let drawn = tiny_skia::Rect::from_xywh(
2149 inner.x * layer_scale,
2150 inner.y * layer_scale,
2151 inner.width * layer_scale,
2152 inner.height * layer_scale,
2153 )?;
2154 let drawn = match shown {
2155 Some(shown) => shown.transform(to_target.invert()?)?.intersect(&drawn)?,
2156 None => drawn,
2157 };
2158 let area = drawn.outset(LAYER_MARGIN, LAYER_MARGIN)?.round_out()?;
2159 Some(Area {
2160 x: area.x(),
2161 y: area.y(),
2162 width: area.width(),
2163 height: area.height(),
2164 })
2165}
2166
2167pub(crate) fn blend_transformed(
2170 pixmap: &mut PixmapMut<'_>,
2171 layer: &Pixmap,
2172 at: Transform,
2173 opacity: f32,
2174) {
2175 if at.is_identity() || at.is_translate() {
2176 let offset = ((at.tx - 0.5).ceil(), (at.ty - 0.5).ceil());
2179 composite(
2181 pixmap,
2182 (offset.0 as i32, offset.1 as i32),
2183 layer,
2184 opacity,
2185 None,
2186 );
2187 return;
2188 }
2189 if at.kx == 0.0 && at.ky == 0.0 && at.sx > 0.0 && at.sy > 0.0 {
2190 blend_scaled(pixmap, layer, at, opacity);
2191 return;
2192 }
2193 let paint = PixmapPaint {
2194 opacity,
2195 quality: FilterQuality::Bilinear,
2196 ..PixmapPaint::default()
2197 };
2198 pixmap.draw_pixmap(0, 0, layer.as_ref(), &paint, at, None);
2199}
2200
2201fn blend_scaled(pixmap: &mut PixmapMut<'_>, layer: &Pixmap, at: Transform, opacity: f32) {
2208 let taps = |scale: f32, offset: f32, length: u32, limit: u32| {
2211 let start = (offset - 0.5).ceil().max(0.0);
2212 let end = (offset + length as f32 * scale - 0.5)
2213 .ceil()
2214 .min(limit as f32);
2215 let last = length as usize - 1;
2216 let taps: Vec<(usize, usize, f32)> = (start as u32..end.max(start) as u32)
2218 .map(|pixel| {
2219 let x = (pixel as f32 + 0.5 - offset) / scale - 0.5;
2220 let floor = x.floor();
2221 let index = |at: f32| (at.max(0.0) as usize).min(last);
2222 (index(floor), index(floor + 1.0), x - floor)
2223 })
2224 .collect();
2225 (start as usize, taps)
2226 };
2227 let (x0, columns) = taps(at.sx, at.tx, layer.width(), pixmap.width());
2228 let (y0, rows) = taps(at.sy, at.ty, layer.height(), pixmap.height());
2229 if columns.is_empty() || rows.is_empty() {
2230 return;
2231 }
2232 let opacity = opacity.clamp(0.0, 1.0);
2233 let stride = pixmap.width() as usize;
2234 let width = layer.width() as usize;
2235 let source = layer.data().as_chunks::<4>().0;
2236 let data = pixmap.data_mut().as_chunks_mut::<4>().0;
2237 let across = |index: usize, mixed: &mut Vec<[f32; 4]>| {
2239 let row = &source[index * width..(index + 1) * width];
2240 mixed.clear();
2241 mixed.extend(columns.iter().map(|&(left, right, t)| {
2242 let (a, b) = (row[left], row[right]);
2243 std::array::from_fn(|channel| {
2244 let (a, b) = (f32::from(a[channel]), f32::from(b[channel]));
2245 a + (b - a) * t
2246 })
2247 }));
2248 };
2249 let (mut upper, mut lower) = (Vec::new(), Vec::new());
2250 let (mut upper_row, mut lower_row) = (usize::MAX, usize::MAX);
2251 for (y, &(top, bottom, down)) in rows.iter().enumerate() {
2252 if upper_row != top {
2253 if lower_row == top {
2254 std::mem::swap(&mut upper, &mut lower);
2255 std::mem::swap(&mut upper_row, &mut lower_row);
2256 } else {
2257 across(top, &mut upper);
2258 upper_row = top;
2259 }
2260 }
2261 if lower_row != bottom {
2262 across(bottom, &mut lower);
2263 lower_row = bottom;
2264 }
2265 let (near, far) = ((1.0 - down) * opacity, down * opacity);
2266 let start = (y0 + y) * stride + x0;
2267 let target = &mut data[start..start + columns.len()];
2268 for ((to, a), b) in target.iter_mut().zip(&upper).zip(&lower) {
2269 let mixed: [f32; 4] = std::array::from_fn(|channel| a[channel] * near + b[channel] * far);
2270 let rest = 1.0 - mixed[3] * (1.0 / 255.0);
2272 *to = std::array::from_fn(|channel| {
2273 (mixed[channel] + f32::from(to[channel]) * rest + 0.5).min(255.0) as u8
2275 });
2276 }
2277 }
2278}
2279
2280pub(crate) fn composite(
2286 pixmap: &mut PixmapMut<'_>,
2287 (left, top): (i32, i32),
2288 layer: &Pixmap,
2289 opacity: f32,
2290 mask: Option<&Mask>,
2291) {
2292 if opacity >= 1.0 && mask.is_none() {
2293 transition::blit(pixmap, (left, top), layer);
2294 return;
2295 }
2296 let width = layer.width() as usize;
2297 let Some((x0, x1, y0, y1)) = overlap(pixmap, left, top, layer.width(), layer.height()) else {
2298 return;
2299 };
2300 let scale = (opacity.clamp(0.0, 1.0) * 65536.0).round() as u32;
2302 let stride = pixmap.width() as usize;
2303 let mask = mask.map(Mask::data);
2304 let data = pixmap.data_mut();
2305 let source = layer.data();
2306 let fade = |pixel: [u8; 4], coverage: u8| {
2309 pixel.map(|channel| mul(((u32::from(channel) * scale + 32768) >> 16) as u8, coverage))
2310 };
2311 let blend = |to: &mut [u8; 4], from: [u8; 4]| {
2312 let rest = 255 - from[3];
2313 *to = std::array::from_fn(|channel| from[channel].saturating_add(mul(to[channel], rest)));
2314 };
2315 for y in y0..y1 {
2316 let start =
2318 (i64::from(top) + y as i64) as usize * stride + (i64::from(left) + x0 as i64) as usize;
2319 let end = start + (x1 - x0);
2320 let row = source[(y * width + x0) * 4..(y * width + x1) * 4]
2321 .as_chunks::<4>()
2322 .0;
2323 let target = data[start * 4..end * 4].as_chunks_mut::<4>().0;
2324 match mask {
2325 Some(mask) => {
2326 for ((to, from), &coverage) in target.iter_mut().zip(row).zip(&mask[start..end]) {
2327 blend(to, fade(*from, coverage));
2328 }
2329 }
2330 None => {
2331 for (to, from) in target.iter_mut().zip(row) {
2332 blend(to, fade(*from, 255));
2333 }
2334 }
2335 }
2336 }
2337}
2338
2339fn overlap(
2343 pixmap: &PixmapMut<'_>,
2344 left: i32,
2345 top: i32,
2346 width: u32,
2347 height: u32,
2348) -> Option<(usize, usize, usize, usize)> {
2349 let column_start = (-i64::from(left)).max(0);
2350 let row_start = (-i64::from(top)).max(0);
2351 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
2352 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
2353 (column_start < column_end && row_start < row_end).then_some((
2354 column_start as usize,
2355 column_end as usize,
2356 row_start as usize,
2357 row_end as usize,
2358 ))
2359}
2360
2361fn blend_mask(
2363 pixmap: &mut PixmapMut<'_>,
2364 left: i32,
2365 top: i32,
2366 width: u32,
2367 height: u32,
2368 mask: &[u8],
2369 color: Color,
2370) {
2371 if mask.len() < width as usize * height as usize {
2372 return;
2373 }
2374 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
2375 else {
2376 return;
2377 };
2378 let stride = pixmap.width() as usize;
2379 let data = pixmap.data_mut();
2380 for row in rows..rows_end {
2381 for column in columns..columns_end {
2382 let coverage = mask[row * width as usize + column];
2383 if coverage == 0 {
2384 continue;
2385 }
2386 let alpha = mul(color.a, coverage);
2387 let source = [
2388 mul(color.r, alpha),
2389 mul(color.g, alpha),
2390 mul(color.b, alpha),
2391 alpha,
2392 ];
2393 let x = (i64::from(left) + column as i64) as usize;
2394 let y = (i64::from(top) + row as i64) as usize;
2395 over(data, (y * stride + x) * 4, source);
2396 }
2397 }
2398}
2399
2400const SAMPLES: usize = 8;
2402
2403struct BlurredBox {
2410 middle: (f32, f32),
2411 half: (f32, f32),
2412 corners: Corners,
2413 largest: f32,
2414 sigma: f32,
2415 whole: f32,
2418}
2419
2420impl BlurredBox {
2421 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
2422 let step = 6.0 * sigma / SAMPLES as f32;
2423 let whole = (0..SAMPLES)
2424 .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
2425 .sum();
2426 BlurredBox {
2427 whole,
2428 middle: (
2429 (shape.left() + shape.right()) / 2.0,
2430 (shape.top() + shape.bottom()) / 2.0,
2431 ),
2432 half: (shape.width() / 2.0, shape.height() / 2.0),
2433 corners,
2434 largest: corners.into_iter().fold(0.0, f32::max),
2435 sigma,
2436 }
2437 }
2438
2439 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
2442 let y = y - self.middle.1;
2443 let (half_width, half_height) = self.half;
2444 let reach = 3.0 * self.sigma;
2445 let down = self.along(y, half_height);
2446 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
2447 let rows = if clear_of_corners {
2448 [(0.0, 0.0, 0.0); SAMPLES]
2449 } else {
2450 self.rows_near(y)
2451 };
2452 for x in xs {
2453 let x = x - self.middle.0;
2454 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
2455 self.along(x, half_width) * down
2456 } else {
2457 let sum: f32 = rows
2458 .iter()
2459 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
2460 .sum();
2461 (sum / self.whole).clamp(0.0, 1.0)
2462 };
2463 mask.push((coverage * 255.0).round() as u8);
2464 }
2465 }
2466
2467 fn along(&self, p: f32, half: f32) -> f32 {
2469 self.between(p, half, half)
2470 }
2471
2472 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
2475 let reach = 3.0 * self.sigma;
2476 if -(left - reach) <= p && p <= right - reach {
2477 return 1.0;
2478 }
2479 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
2480 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
2481 }
2482
2483 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
2487 let (half_width, half_height) = self.half;
2488 let reach = 3.0 * self.sigma;
2489 let start = (y - half_height).clamp(-reach, reach);
2490 let end = (y + half_height).clamp(-reach, reach);
2491 let step = (end - start) / SAMPLES as f32;
2492 std::array::from_fn(|sample| {
2493 let offset = start + step * (sample as f32 + 0.5);
2494 let row = y - offset;
2497 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
2498 let (left, right) = if row < 0.0 {
2499 (top_left, top_right)
2500 } else {
2501 (bottom_left, bottom_right)
2502 };
2503 let span = |radius: f32| {
2504 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
2505 half_width - radius
2506 + (radius * radius - into_corner * into_corner)
2507 .max(0.0)
2508 .sqrt()
2509 };
2510 (span(left), span(right), gaussian(offset, self.sigma) * step)
2511 })
2512 }
2513}
2514
2515fn gaussian(x: f32, sigma: f32) -> f32 {
2517 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
2518 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
2519}
2520
2521fn erf(x: f32) -> f32 {
2524 let a = x.abs();
2525 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
2526 let d = d * d;
2527 (1.0 - 1.0 / (d * d)).copysign(x)
2528}
2529
2530fn is_color_outline(image: &SwashImage) -> bool {
2537 format!("{:?}", image.source).starts_with("ColorOutline")
2538}
2539
2540fn blend_rgba(
2543 pixmap: &mut PixmapMut<'_>,
2544 left: i32,
2545 top: i32,
2546 width: u32,
2547 height: u32,
2548 (rgba, premultiplied): (&[u8], bool),
2549 opacity: u8,
2550) {
2551 if rgba.len() < width as usize * height as usize * 4 {
2552 return;
2553 }
2554 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
2555 else {
2556 return;
2557 };
2558 let stride = pixmap.width() as usize;
2559 let data = pixmap.data_mut();
2560 for row in rows..rows_end {
2561 for column in columns..columns_end {
2562 let index = (row * width as usize + column) * 4;
2563 let alpha = mul(rgba[index + 3], opacity);
2564 if alpha == 0 {
2565 continue;
2566 }
2567 let factor = if premultiplied { opacity } else { alpha };
2570 let source = [
2571 mul(rgba[index], factor),
2572 mul(rgba[index + 1], factor),
2573 mul(rgba[index + 2], factor),
2574 alpha,
2575 ];
2576 let x = (i64::from(left) + column as i64) as usize;
2577 let y = (i64::from(top) + row as i64) as usize;
2578 over(data, (y * stride + x) * 4, source);
2579 }
2580 }
2581}
2582
2583fn keep_near(
2586 kept: &mut PathBuilder,
2587 contour: &[PathSegment],
2588 [left, top, right, bottom]: [f32; 4],
2589) {
2590 let (mut low, mut high) = (
2591 (f32::INFINITY, f32::INFINITY),
2592 (f32::NEG_INFINITY, f32::NEG_INFINITY),
2593 );
2594 let points = contour.iter().flat_map(|segment| match *segment {
2595 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
2596 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
2597 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
2598 PathSegment::Close => [None; 3],
2599 });
2600 for point in points.flatten() {
2601 low = (low.0.min(point.x), low.1.min(point.y));
2602 high = (high.0.max(point.x), high.1.max(point.y));
2603 }
2604 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
2605 return;
2606 }
2607 for segment in contour {
2608 match *segment {
2609 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
2610 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
2611 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
2612 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
2613 PathSegment::Close => kept.close(),
2614 }
2615 }
2616}
2617
2618pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
2623 let period = on + off;
2624 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
2625 return None;
2626 }
2627 let count = (perimeter / period).round().max(1.0);
2628 let stretch = perimeter / (count * period);
2629 Some((on * stretch, off * stretch))
2630}
2631
2632pub(crate) fn fill_all(pixmap: &mut PixmapMut<'_>, color: Color) -> bool {
2637 let alpha = color.a;
2638 let source = [
2639 mul(color.r, alpha),
2640 mul(color.g, alpha),
2641 mul(color.b, alpha),
2642 alpha,
2643 ];
2644 let pixels = pixmap.data_mut().as_chunks_mut::<4>().0;
2645 match alpha {
2646 0 => {}
2647 255 => pixels.fill(source),
2648 _ => {
2649 let rest = 255 - alpha;
2650 for pixel in pixels {
2651 *pixel =
2652 std::array::from_fn(|channel| source[channel].saturating_add(mul(pixel[channel], rest)));
2653 }
2654 }
2655 }
2656 true
2657}
2658
2659pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
2665 let edges = [area.left(), area.top(), area.right(), area.bottom()];
2666 if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
2667 return false;
2668 }
2669 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2670 let [left, top, right, bottom] = [
2671 area.left().clamp(0.0, width),
2672 area.top().clamp(0.0, height),
2673 area.right().clamp(0.0, width),
2674 area.bottom().clamp(0.0, height),
2675 ]
2676 .map(|edge| edge as usize);
2677 let stride = pixmap.width() as usize * 4;
2678 let pixel = [color.r, color.g, color.b, 255];
2679 for row in pixmap
2680 .data_mut()
2681 .chunks_exact_mut(stride)
2682 .take(bottom)
2683 .skip(top)
2684 {
2685 row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
2686 }
2687 true
2688}