1use std::collections::HashMap;
10
11use cosmic_text::{FontSystem, LayoutGlyph, SwashCache, SwashContent, SwashImage};
12use crabshell_ui::{
13 Affine, CaptureView, Color, Content, IconView, ImageView, InputView, NodeView, Radii, Rect,
14 Shadow, Size, Span, Style, TextSystem, TextView, WindowView,
15};
16use tiny_skia::{
17 FillRule, FilterQuality, LineCap, LineJoin, Mask, Paint, PathBuilder, PathSegment, Pixmap,
18 PixmapMut, PixmapPaint, Stroke, StrokeDash, Transform,
19};
20
21use crate::damage::{BufferAge, DamageHistory, PixelRect};
22use crate::icons::{Drawn, Icons};
23use crate::theme::IconLookup;
24
25mod canvas;
26mod effects;
27mod gradient;
28mod transition;
29
30const TILE: u32 = 64;
35
36const GLYPH_CACHE_LIMIT: usize = 2048;
39
40const LAYER_LIMIT: u64 = 1 << 22;
44
45const LAYER_MARGIN: f32 = 2.0;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum PixelFormat {
53 Argb8888,
55 Abgr8888,
57}
58
59pub struct Canvas<'a> {
61 pub pixels: &'a mut [u8],
63 pub width: u32,
67 pub height: u32,
69 pub scale: f32,
71 pub format: PixelFormat,
73 pub age: &'a mut BufferAge,
75}
76
77pub struct Renderer {
80 glyphs: SwashCache,
81 icons: Icons,
82 scratch: Vec<u8>,
85 work: Work,
86}
87
88#[derive(Default)]
91#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
92struct Work {
93 layer_pixels: u64,
95 nodes: u64,
97 skipped: u64,
99 blurred: u64,
101 gradient_pixels: std::cell::Cell<u64>,
104}
105
106impl Renderer {
107 pub fn new() -> Renderer {
110 Renderer {
111 glyphs: SwashCache::new(),
112 icons: Icons::new(),
113 scratch: Vec::new(),
114 work: Work::default(),
115 }
116 }
117
118 #[cfg(test)]
120 pub(crate) fn image_lookups(&self) -> usize {
121 self.icons.lookups()
122 }
123
124 #[cfg(test)]
126 pub(crate) fn cached_glyphs(&self) -> usize {
127 self.glyphs.image_cache.len()
128 }
129
130 #[cfg(test)]
133 pub(crate) fn work(&self) -> (u64, u64, u64) {
134 (self.work.layer_pixels, self.work.nodes, self.work.blurred)
135 }
136
137 #[cfg(test)]
139 pub(crate) fn skipped_nodes(&self) -> u64 {
140 self.work.skipped
141 }
142
143 #[cfg(test)]
145 pub(crate) fn gradient_pixels(&self) -> u64 {
146 self.work.gradient_pixels.get()
147 }
148
149 #[cfg(test)]
152 pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
153 Renderer {
154 icons: Icons::with_themes(crate::theme::Themes::new(bases)),
155 ..Renderer::new()
156 }
157 }
158
159 pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
161 self.icons.set_theme(theme.into());
162 }
163
164 pub fn icon_lookup(&self) -> IconLookup {
167 self.icons.lookup()
168 }
169
170 #[cfg(test)]
172 pub(crate) fn cached_bytes(&self) -> usize {
173 self.icons.cached_bytes()
174 }
175
176 #[cfg(test)]
178 pub(crate) fn cached_icons(&self) -> usize {
179 self.icons.cached()
180 }
181
182 #[cfg(test)]
184 pub(crate) fn rasterized_icons(&self) -> usize {
185 self.icons.rasterized()
186 }
187
188 pub fn forget_captures(&mut self, gone: &[u64]) {
192 self.icons.forget_captures(gone);
193 }
194
195 pub fn decode_off_thread(&mut self) {
208 self.icons.decode_off_thread();
209 }
210
211 pub fn load_images(&mut self, view: &WindowView<'_>, scale: f32) {
218 self.icons.load_unseen(&view.loading_images(), scale);
219 }
220
221 pub fn decoding(&self) -> bool {
224 self.icons.decoding()
225 }
226
227 pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
231 self.icons.wake_when_decoded(Box::new(wake));
232 }
233
234 pub fn waits_for_pictures(&self) -> bool {
237 self.icons.waited()
238 }
239
240 pub fn take_decoded(&mut self) -> Vec<u64> {
246 self.icons.take_decoded()
247 }
248
249 pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
254 self.icons.next_frame(now)
255 }
256
257 pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
263 self.icons.advance(now)
264 }
265
266 #[cfg(test)]
268 pub(crate) fn decoded_off_thread(&self) -> usize {
269 self.icons.worker_work().0
270 }
271
272 #[cfg(test)]
274 pub(crate) fn decoder_running(&self) -> bool {
275 self.icons.worker_work().1
276 }
277
278 #[cfg(test)]
280 pub(crate) fn cached_captures(&self) -> usize {
281 self.icons.captures()
282 }
283
284 pub fn draw(
305 &mut self,
306 view: &WindowView<'_>,
307 damage: &[Rect],
308 text: &mut TextSystem,
309 history: &mut DamageHistory,
310 canvas: Canvas<'_>,
311 ) -> Result<Vec<PixelRect>, CanvasError> {
312 let Canvas {
313 pixels,
314 width,
315 height,
316 scale,
317 format,
318 age,
319 } = canvas;
320 if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
321 || !(scale.is_finite() && scale > 0.0)
322 {
323 return Err(CanvasError {
324 width,
325 height,
326 scale,
327 bytes: pixels.len(),
328 });
329 }
330 self.icons.start_frame(history.id(), view.has_images());
331 let plan = history.plan(damage, scale, width, height, age);
332 let mut tiles: Vec<(u32, u32)> = Vec::new();
333 for area in plan.repaint.iter().filter(|area| area.area() > 0) {
334 for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
335 tiles
336 .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
337 }
338 }
339 tiles.sort_unstable();
340 tiles.dedup();
341 let mut casts = HashMap::new();
342 let mut fonts = text.font_system();
343 for &(row, column) in &tiles {
344 self.icons.start_tile((row, column));
345 let (x, y) = (column * TILE, row * TILE);
346 let size = (width.saturating_sub(x), height.saturating_sub(y));
347 let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
348 self.scratch.clear();
349 self.scratch.resize(area.area() as usize * 4, 0);
350 let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
351 else {
352 continue;
353 };
354 let mut painter = Painter {
355 grid: Grid {
356 scale,
357 zoom: 1.0,
358 linear: Affine {
359 sx: 1.0,
360 ky: 0.0,
361 kx: 0.0,
362 sy: 1.0,
363 tx: 0.0,
364 ty: 0.0,
365 },
366 window: view.size(),
367 width,
368 height,
369 left: area.x as f32,
370 top: area.y as f32,
371 },
372 glyphs: &mut self.glyphs,
373 icons: &mut self.icons,
374 fonts: &mut fonts,
375 work: &mut self.work,
376 casts: &mut casts,
377 clip: Some(Rect::new(0.0, 0.0, view.size().width, view.size().height)),
378 };
379 painter.node(&mut pixmap, view.root());
380 copy(&self.scratch, area, pixels, width, format);
381 }
382 self.icons.repainted(&tiles);
383 self.icons.end_frame();
384 if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
385 self.glyphs.image_cache.clear();
386 self.glyphs.outline_command_cache.clear();
387 }
388 Ok(plan.report)
389 }
390}
391
392#[derive(Clone, Copy, Debug, PartialEq)]
395pub struct CanvasError {
396 pub width: u32,
398 pub height: u32,
400 pub scale: f32,
402 pub bytes: usize,
404}
405
406impl std::fmt::Display for CanvasError {
407 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408 write!(
409 f,
410 "a {}x{} canvas at scale {} needs {} bytes, but has {}",
411 self.width,
412 self.height,
413 self.scale,
414 u64::from(self.width) * u64::from(self.height) * 4,
415 self.bytes
416 )
417 }
418}
419
420impl std::error::Error for CanvasError {}
421
422impl Default for Renderer {
423 fn default() -> Self {
424 Self::new()
425 }
426}
427
428fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
430 let stride = width as usize * 4;
431 let row_bytes = area.width as usize * 4;
432 for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
433 let start = (area.y as usize + row) * stride + area.x as usize * 4;
434 let target = &mut pixels[start..start + row_bytes];
435 match format {
436 PixelFormat::Abgr8888 => target.copy_from_slice(source),
437 PixelFormat::Argb8888 => {
438 let (to, _) = target.as_chunks_mut::<4>();
439 let (from, _) = source.as_chunks::<4>();
440 for (to, from) in to.iter_mut().zip(from) {
443 let pixel = u32::from_le_bytes(*from);
444 *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
445 }
446 }
447 }
448 }
449}
450
451#[derive(Clone, Copy)]
453struct Grid {
454 scale: f32,
456 zoom: f32,
459 linear: Affine,
462 window: Size,
464 width: u32,
466 height: u32,
467 left: f32,
469 top: f32,
470}
471
472impl Grid {
473 fn x(&self, x: f32) -> f32 {
476 let pixel = if x >= self.window.width {
477 self.width as f32
478 } else {
479 (x * self.scale).round()
480 };
481 pixel - self.left
482 }
483
484 fn y(&self, y: f32) -> f32 {
486 let pixel = if y >= self.window.height {
487 self.height as f32
488 } else {
489 (y * self.scale).round()
490 };
491 pixel - self.top
492 }
493
494 fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
498 if !(rect.width > 0.0 && rect.height > 0.0) {
499 return None;
500 }
501 let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
503 let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
504 let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
505 let bottom =
506 (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
507 (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
508 }
509
510 fn through(&self, transform: Affine) -> (Affine, f32, f32) {
513 let (outer, inner) = (self.linear, transform);
514 let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0).pre_concat(
515 Transform::from_row(inner.sx, inner.ky, inner.kx, inner.sy, 0.0, 0.0),
516 );
517 let linear = Affine {
518 sx: linear.sx,
519 ky: linear.ky,
520 kx: linear.kx,
521 sy: linear.sy,
522 tx: 0.0,
523 ty: 0.0,
524 };
525 let zoom = linear.layer_zoom();
526 (linear, zoom, self.scale / self.zoom * zoom)
527 }
528
529 fn moved(&self, x: u32, y: u32) -> Grid {
531 Grid {
532 left: self.left + x as f32,
533 top: self.top + y as f32,
534 ..*self
535 }
536 }
537
538 fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
541 tiny_skia::Rect::from_ltrb(
542 self.x(rect.x),
543 self.y(rect.y),
544 self.x(rect.right()),
545 self.y(rect.bottom()),
546 )
547 .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
548 }
549}
550
551struct Painter<'a> {
553 grid: Grid,
554 glyphs: &'a mut SwashCache,
555 icons: &'a mut Icons,
556 fonts: &'a mut FontSystem,
557 work: &'a mut Work,
558 casts: &'a mut HashMap<CastKey, effects::Cast>,
560 clip: Option<Rect>,
564}
565
566type CastKey = (String, i64, i64);
569
570impl Painter<'_> {
571 fn on(&mut self, grid: Grid) -> Painter<'_> {
573 Painter {
574 grid,
575 glyphs: &mut *self.glyphs,
576 icons: &mut *self.icons,
577 fonts: &mut *self.fonts,
578 work: &mut *self.work,
579 casts: &mut *self.casts,
580 clip: self.clip,
581 }
582 }
583
584 fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
589 let Some((x, y, width, height)) =
591 self
592 .grid
593 .cover(node.bounds(), pixmap.width(), pixmap.height())
594 else {
595 return;
596 };
597 let style = node.style();
598 let opacity = style.opacity.unwrap_or(1.0);
599 let opacity = if opacity.is_nan() {
600 1.0
601 } else {
602 opacity.clamp(0.0, 1.0)
603 };
604 if opacity == 0.0 {
605 self.skip(node);
606 return;
607 }
608 let shadow = effects::cast_by_content(&style);
609 let region = node
612 .mask_region()
613 .filter(|_| node.transform().is_none() && shadow.is_none())
614 .map(|region| {
615 let inner = self.on(self.grid.moved(x, y));
616 inner.region_cover(width, height, node.rect(), region)
617 });
618 if matches!(region, Some(effects::Cover::Clear)) {
619 self.skip(node);
620 return;
621 }
622 if let Some(transform) = node.transform() {
623 self.transformed(pixmap, node, &style, transform, opacity);
624 } else if opacity < 1.0
625 || style.mask.is_some()
626 || matches!(region, Some(effects::Cover::Part(_)))
627 || shadow.is_some()
628 {
629 let Some(mut layer) = Pixmap::new(width, height) else {
631 return;
632 };
633 self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
634 let mut inner = self.on(self.grid.moved(x, y));
635 inner.layer_contents(&mut layer.as_mut(), node, &style, shadow, region);
636 let paint = PixmapPaint {
637 opacity,
638 ..PixmapPaint::default()
639 };
640 let (x, y) = (x as i32, y as i32);
641 pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
642 } else {
643 self.node_contents(pixmap, node, &style);
644 }
645 }
646
647 fn skip(&mut self, node: NodeView<'_>) {
653 if self.icons.look_through(node.path()) {
654 let (grid, clip) = (self.grid, self.clip);
655 self.skipped(node, grid, clip);
656 }
657 }
658
659 fn skipped(&mut self, node: NodeView<'_>, mut grid: Grid, mut clip: Option<Rect>) {
662 self.work.skipped += 1;
663 if let Some(transform) = node.transform() {
664 (grid.linear, grid.zoom, grid.scale) = grid.through(transform);
665 clip = None;
668 }
669 let shows =
670 |clip: Option<Rect>, rect: Rect| clip.is_none_or(|clip| !clip.intersect(rect).is_empty());
671 if let Content::Image(image) = node.content()
672 && shows(clip, image.rect)
673 {
674 let (width, height) = (
675 (image.rect.width * grid.scale).round(),
676 (image.rect.height * grid.scale).round(),
677 );
678 if width >= 1.0 && height >= 1.0 {
679 let size = (width as u32, height as u32);
681 self.icons.skipped(&image, size, grid.scale);
682 }
683 }
684 if node.clips() {
685 let rect = node.rect();
686 clip = Some(clip.map_or(rect, |clip| clip.intersect(rect)));
687 }
688 for child in node.children() {
689 if shows(clip, child.bounds()) {
690 self.skipped(child, grid, clip);
691 }
692 }
693 }
694
695 fn layer_contents(
700 &mut self,
701 layer: &mut PixmapMut<'_>,
702 node: NodeView<'_>,
703 style: &Style,
704 shadow: Option<Shadow>,
705 cover: Option<effects::Cover>,
706 ) {
707 self.node_contents(layer, node, style);
708 if let Some(mask) = &style.mask {
709 self.mask(layer, node.rect(), mask);
710 }
711 let (width, height) = (layer.width(), layer.height());
712 let cover = cover.or_else(|| {
713 let region = node.mask_region()?;
714 Some(self.region_cover(width, height, node.rect(), region))
715 });
716 match cover {
717 Some(effects::Cover::Clear) => layer.fill(tiny_skia::Color::TRANSPARENT),
718 Some(effects::Cover::Part(cut)) => layer.apply_mask(&cut),
719 Some(effects::Cover::Whole) | None => {}
720 }
721 if let Some(shadow) = shadow {
722 self.content_shadow(layer, node, &shadow);
723 }
724 }
725
726 fn transformed(
733 &mut self,
734 pixmap: &mut PixmapMut<'_>,
735 node: NodeView<'_>,
736 style: &Style,
737 transform: Affine,
738 opacity: f32,
739 ) {
740 let Affine {
741 sx,
742 ky,
743 kx,
744 sy,
745 tx,
746 ty,
747 } = transform;
748 let Grid {
749 scale, left, top, ..
750 } = self.grid;
751 let (linear, zoom, layer_scale) = self.grid.through(transform);
752 let device = Transform::from_scale(scale, scale)
754 .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
755 .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
756 let to_pixmap = device.post_translate(-left, -top);
757 let Some(back) = to_pixmap.invert() else {
758 return;
759 };
760 let inner = node.inner_bounds();
761 let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
762 .and_then(|rect| rect.transform(back));
763 let drawn = tiny_skia::Rect::from_xywh(
764 inner.x * layer_scale,
765 inner.y * layer_scale,
766 inner.width * layer_scale,
767 inner.height * layer_scale,
768 );
769 let Some(area) = shown
770 .zip(drawn)
771 .and_then(|(shown, drawn)| shown.intersect(&drawn))
772 .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
773 .and_then(|area| area.round_out())
774 else {
775 return;
776 };
777 let pixels = u64::from(area.width()) * u64::from(area.height());
778 if pixels > LAYER_LIMIT {
779 tracing::debug!(
780 "{} is transformed into a layer too large to draw",
781 node.path()
782 );
783 return;
784 }
785 let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
786 return;
787 };
788 self.work.layer_pixels += pixels;
789 let (x, y) = (area.x() as f32, area.y() as f32);
790 let (width, height) = if zoom == self.grid.zoom {
791 (self.grid.width, self.grid.height)
792 } else {
793 let window = self.grid.window;
795 (
796 (window.width * layer_scale).round() as u32,
797 (window.height * layer_scale).round() as u32,
798 )
799 };
800 let mut inner = self.on(Grid {
801 scale: layer_scale,
802 zoom,
803 linear,
804 width,
805 height,
806 left: x,
807 top: y,
808 ..self.grid
809 });
810 inner.clip = None;
811 let shadow = effects::cast_by_content(style);
812 inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
813 let paint = PixmapPaint {
814 opacity,
815 quality: FilterQuality::Bilinear,
816 ..PixmapPaint::default()
817 };
818 pixmap.draw_pixmap(
819 0,
820 0,
821 layer.as_ref(),
822 &paint,
823 to_pixmap.pre_translate(x, y),
824 None,
825 );
826 }
827
828 fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
829 self.work.nodes += 1;
830 let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
833 if let Some(shadow) = style.shadow.filter(outside) {
834 self.shadow(pixmap, node.rect(), style, &shadow);
835 }
836 self.draw_box(pixmap, node.rect(), style);
837 match node.content() {
838 Content::Text(text) => {
839 let color = text.color();
840 let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
841 self.selection(pixmap, &text.selection(), tint);
842 self.text(pixmap, &text);
843 }
844 Content::Icon(icon) => self.icon(pixmap, &icon),
845 Content::Image(image) => self.image(pixmap, &image),
846 Content::Capture(capture) => self.capture(pixmap, &capture),
847 Content::Input(input) => self.input(pixmap, &input),
848 Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
849 Content::None => {}
850 }
851 if node.clips() {
852 self.clipped_children(pixmap, node, style);
853 } else {
854 for child in node.children() {
855 self.node(pixmap, child);
856 }
857 }
858 }
859
860 fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
865 let Some((area, corners)) = self.box_shape(node.rect(), style) else {
866 return;
867 };
868 let width = self.border_width(style);
869 let Some(inside) = tiny_skia::Rect::from_ltrb(
870 area.left() + width,
871 area.top() + width,
872 area.right() - width,
873 area.bottom() - width,
874 ) else {
875 return;
876 };
877 let corners = inset(corners, width);
878 let rect = node.rect();
879 self.through_mask(pixmap, rect, (inside, corners), |painter, layer| {
880 painter.clip = painter.clip.map(|clip| clip.intersect(rect));
881 for child in node.children() {
882 painter.node(layer, child);
883 }
884 for (handle, bar) in node.scroll_bars() {
886 painter.draw_box(layer, handle, &bar);
887 }
888 });
889 }
890
891 fn through_mask(
894 &mut self,
895 pixmap: &mut PixmapMut<'_>,
896 cover: Rect,
897 (shape, corners): (tiny_skia::Rect, Corners),
898 draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
899 ) {
900 if !visible(pixmap, shape) {
901 return;
902 }
903 let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
904 Mask::new(pixmap.width(), pixmap.height()),
905 self.grid.cover(cover, pixmap.width(), pixmap.height()),
906 ) else {
907 return;
908 };
909 let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
910 return;
911 };
912 self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
913 let mut inner = self.on(self.grid.moved(x, y));
914 draw(&mut inner, &mut layer.as_mut());
915 let mut path = PathBuilder::new();
916 rounded_rect(&mut path, shape, corners);
917 let Some(path) = path.finish() else {
918 return;
919 };
920 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
921 pixmap.draw_pixmap(
922 x as i32,
923 y as i32,
924 layer.as_ref(),
925 &PixmapPaint::default(),
926 Transform::identity(),
927 Some(&mask),
928 );
929 }
930
931 fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
935 let area = self.grid.rect(rect)?;
936 let corners = style.radius.unwrap_or_default().corners();
937 let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
938 Some((area, corners))
939 }
940
941 fn border_width(&self, style: &Style) -> f32 {
944 let Some(border) = style.border else {
945 return 0.0;
946 };
947 let width = (border.width * self.grid.scale).floor();
948 if border.width > 0.0 {
949 width.max(1.0)
950 } else {
951 width.max(0.0)
952 }
953 }
954
955 fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
958 let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
959 if style.background.is_none()
960 && style.gradient.is_none()
961 && style.border.is_none()
962 && inset_shadow.is_none()
963 {
964 return;
965 }
966 let Some((area, corners)) = self.box_shape(rect, style) else {
967 return;
968 };
969 if !visible(pixmap, area) {
970 return;
971 }
972
973 if let Some(color) = style.background
974 && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
975 {
976 let mut path = PathBuilder::new();
977 rounded_rect(&mut path, area, corners);
978 fill(pixmap, path, color, FillRule::Winding);
979 }
980 if let Some(gradient) = style.gradient {
981 let mut path = PathBuilder::new();
982 rounded_rect(&mut path, area, corners);
983 let size = (pixmap.width(), pixmap.height());
984 if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
985 ramp.fill(pixmap, &path);
986 }
987 }
988 if let Some(shadow) = inset_shadow {
989 self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
990 }
991 if let Some(border) = style.border {
992 let width = self.border_width(style);
993 let dashed = width >= 1.0
994 && style.border_dash.is_some_and(|dash| {
995 self.dashed_border(pixmap, (area, corners), width, border.color, dash)
996 });
997
998 if width >= 1.0 && !dashed {
999 let mut path = PathBuilder::new();
1001 rounded_rect(&mut path, area, corners);
1002 if let Some(inner) = tiny_skia::Rect::from_ltrb(
1003 area.left() + width,
1004 area.top() + width,
1005 area.right() - width,
1006 area.bottom() - width,
1007 ) {
1008 rounded_rect(&mut path, inner, inset(corners, width));
1009 }
1010 fill(pixmap, path, border.color, FillRule::EvenOdd);
1011 }
1012 }
1013 }
1014
1015 fn dashed_border(
1021 &self,
1022 pixmap: &mut PixmapMut<'_>,
1023 (area, corners): (tiny_skia::Rect, Corners),
1024 width: f32,
1025 color: Color,
1026 (on, off): (f32, f32),
1027 ) -> bool {
1028 let Grid {
1029 scale, left, top, ..
1030 } = self.grid;
1031 let half = width / 2.0;
1032 let Some(middle) = tiny_skia::Rect::from_ltrb(
1033 area.left() + left + half,
1034 area.top() + top + half,
1035 area.right() + left - half,
1036 area.bottom() + top - half,
1037 ) else {
1038 return false;
1039 };
1040 let corners = inset(corners, half);
1041 let (on, off) = (on * scale, off * scale);
1042 let mut all = PathBuilder::new();
1043 let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
1044 if square.is_empty() {
1045 let rounding: f32 = corners
1048 .iter()
1049 .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
1050 .sum();
1051 let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
1052 let mut path = PathBuilder::new();
1053 rounded_rect(&mut path, middle, corners);
1054 if !dash_into(&mut all, path, perimeter, on, off) {
1055 return false;
1056 }
1057 } else {
1058 for (at, &from) in square.iter().enumerate() {
1061 let to = square[(at + 1) % square.len()];
1062 let steps = (to + 4 - from - 1) % 4 + 1;
1063 let [.., mut was] = corner(middle, corners, from);
1064 let mut path = PathBuilder::new();
1065 path.move_to(was.x, was.y);
1066 let mut length = 0.0;
1067 for index in (from + 1..=from + steps).map(|index| index % 4) {
1068 let [start, one, two, end] = corner(middle, corners, index);
1069 path.line_to(start.x, start.y);
1070 length += was.distance(start);
1071 if corners[index] > 0.0 {
1072 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1073 length += std::f32::consts::FRAC_PI_2 * corners[index];
1074 }
1075 was = end;
1076 }
1077 if !dash_into(&mut all, path, length, on, off) {
1078 return false;
1079 }
1080 }
1081 if on > 0.0 {
1085 const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
1087 for &index in &square {
1088 let [point, ..] = corner(middle, corners, index);
1089 let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
1090 all.move_to(point.x - half * ax, point.y - half * ay);
1091 all.line_to(point.x, point.y);
1092 all.line_to(point.x + half * bx, point.y + half * by);
1093 }
1094 }
1095 }
1096 let Some(dashes) = all.finish() else {
1097 return true;
1098 };
1099 let reach = 2.0 * width + 1.0;
1104 let near = [
1105 left - reach,
1106 top - reach,
1107 left + pixmap.width() as f32 + reach,
1108 top + pixmap.height() as f32 + reach,
1109 ];
1110 let mut kept = PathBuilder::new();
1111 let mut contour = Vec::new();
1112 for segment in dashes.segments() {
1113 if matches!(segment, PathSegment::MoveTo(_)) {
1114 keep_near(&mut kept, &contour, near);
1115 contour.clear();
1116 }
1117 contour.push(segment);
1118 }
1119 keep_near(&mut kept, &contour, near);
1120 let Some(kept) = kept.finish() else {
1121 return true;
1122 };
1123 let stroke = Stroke {
1124 width,
1125 line_cap: if on == 0.0 {
1127 LineCap::Round
1128 } else {
1129 LineCap::Butt
1130 },
1131 line_join: LineJoin::Miter,
1132 ..Stroke::default()
1133 };
1134 let mut paint = Paint::default();
1135 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1136 paint.anti_alias = true;
1137 let moved = Transform::from_translate(-left, -top);
1138 pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1139 true
1140 }
1141
1142 fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1147 let Grid {
1148 scale, left, top, ..
1149 } = self.grid;
1150 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1151 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1152 return;
1153 }
1154 let Some((area, corners)) = self.box_shape(rect, style) else {
1155 return;
1156 };
1157 let spread = shadow.spread * scale;
1159 let Some(shape) = tiny_skia::Rect::from_ltrb(
1160 area.left() + left + shadow.x * scale - spread,
1161 area.top() + top + shadow.y * scale - spread,
1162 area.right() + left + shadow.x * scale + spread,
1163 area.bottom() + top + shadow.y * scale + spread,
1164 ) else {
1165 return;
1166 };
1167 let corners = fit(spread_corners(corners, spread), shape);
1168 let cut = if shadow.cut_out {
1170 self.box_mask(pixmap, rect, style)
1171 } else {
1172 None
1173 };
1174 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1176 if sigma < 0.25 {
1177 let mut path = PathBuilder::new();
1178 let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1179 return;
1180 };
1181 rounded_rect(&mut path, shape, corners);
1182 let Some(path) = path.finish() else {
1183 return;
1184 };
1185 let mut paint = Paint::default();
1186 let color = shadow.color;
1187 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1188 paint.anti_alias = true;
1189 let outside = cut.map(|mut cut| {
1190 cut.invert();
1191 cut
1192 });
1193 let (rule, at) = (FillRule::Winding, Transform::identity());
1194 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1195 return;
1196 }
1197 let reach = 3.0 * sigma;
1198 let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1199 ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1200 let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1201 ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1202 if columns.is_empty() || rows.is_empty() {
1203 return;
1204 }
1205 let blurred = BlurredBox::new(shape, corners, sigma);
1206 let mut mask = Vec::with_capacity(columns.len() * rows.len());
1207 for row in rows.clone() {
1208 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1209 blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1210 }
1211 if let Some(cut) = cut {
1212 let stride = pixmap.width() as usize;
1213 let under = rows.clone().flat_map(|row| {
1214 columns
1215 .clone()
1216 .map(move |column| row as usize * stride + column as usize)
1217 });
1218 for (alpha, at) in mask.iter_mut().zip(under) {
1219 *alpha = mul(*alpha, 255 - cut.data()[at]);
1220 }
1221 }
1222 let width = columns.len() as u32;
1223 let height = rows.len() as u32;
1224 let (x, y) = (columns.start as i32, rows.start as i32);
1225 blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1226 }
1227
1228 fn inset_shadow(
1233 &self,
1234 pixmap: &mut PixmapMut<'_>,
1235 (area, corners): (tiny_skia::Rect, Corners),
1236 border: f32,
1237 shadow: &Shadow,
1238 ) {
1239 let Grid {
1240 scale, left, top, ..
1241 } = self.grid;
1242 let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1243 if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1244 return;
1245 }
1246 let Some(inside) = tiny_skia::Rect::from_ltrb(
1247 area.left() + border,
1248 area.top() + border,
1249 area.right() - border,
1250 area.bottom() - border,
1251 ) else {
1252 return;
1253 };
1254 let inside_corners = inset(corners, border);
1255 if !visible(pixmap, inside) {
1256 return;
1257 }
1258 let mut path = PathBuilder::new();
1259 rounded_rect(&mut path, inside, inside_corners);
1260 let Some(path) = path.finish() else {
1261 return;
1262 };
1263 let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1265 let hole = tiny_skia::Rect::from_ltrb(
1266 inside.left() + left + x + spread,
1267 inside.top() + top + y + spread,
1268 inside.right() + left + x - spread,
1269 inside.bottom() + top + y - spread,
1270 );
1271 let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1272 let sigma = shadow.blur.max(0.0) * scale / 2.0;
1273 let color = shadow.color;
1274 if sigma < 0.25 {
1275 let mut outside = None;
1276 if let Some((hole, corners)) = hole {
1277 let mut cut = PathBuilder::new();
1278 let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1279 return;
1280 };
1281 rounded_rect(&mut cut, moved, corners);
1282 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1283 return;
1284 };
1285 let (rule, at) = (FillRule::Winding, Transform::identity());
1286 let Some(cut) = cut.finish() else {
1287 return;
1288 };
1289 mask.fill_path(&cut, rule, true, at);
1290 mask.invert();
1291 outside = Some(mask);
1292 }
1293 let mut paint = Paint::default();
1294 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1295 paint.anti_alias = true;
1296 let (rule, at) = (FillRule::Winding, Transform::identity());
1297 pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1298 return;
1299 }
1300 let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1303 return;
1304 };
1305 mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1306 let columns = inside.left().floor().max(0.0) as u32
1307 ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1308 let rows = inside.top().floor().max(0.0) as u32
1309 ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1310 if columns.is_empty() || rows.is_empty() {
1311 return;
1312 }
1313 let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1314 let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1315 for row in rows.clone() {
1316 let start = alpha.len();
1317 match &blurred {
1318 Some(blurred) => {
1319 let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1320 blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1321 }
1322 None => alpha.resize(start + columns.len(), 0),
1323 }
1324 let stride = pixmap.width() as usize;
1325 let row = &mask.data()[row as usize * stride..];
1326 let covered = &row[columns.start as usize..columns.end as usize];
1327 for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1328 *value = mul(255 - *value, covered);
1329 }
1330 }
1331 let (width, height) = (columns.len() as u32, rows.len() as u32);
1332 let (x, y) = (columns.start as i32, rows.start as i32);
1333 blend_mask(pixmap, x, y, width, height, &alpha, color);
1334 }
1335
1336 fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1339 let (area, corners) = self.box_shape(rect, style)?;
1340 let mut path = PathBuilder::new();
1341 rounded_rect(&mut path, area, corners);
1342 let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1343 let (rule, at) = (FillRule::Winding, Transform::identity());
1344 mask.fill_path(&path.finish()?, rule, true, at);
1345 Some(mask)
1346 }
1347
1348 fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1353 let Grid {
1354 scale, left, top, ..
1355 } = self.grid;
1356 let origin = text.origin();
1357 let x = origin.x * scale - left;
1358 for run in text.runs() {
1359 let baseline = ((origin.y + run.line_y) * scale).round() - top;
1361 if baseline + run.line_height * scale < 0.0
1362 || baseline - run.line_height * scale > pixmap.height() as f32
1363 {
1364 continue;
1365 }
1366 let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1368 true => text.link_hover_color().or(span.color),
1369 false => span.color,
1370 };
1371 for glyph in run.glyphs.iter() {
1372 let span = text.span(run.line_i, glyph);
1373 let color = text.selected_color(run.line_i, glyph);
1374 let color = color.or_else(|| span.and_then(|span| span_color(span, glyph)));
1375 let color = color.unwrap_or(text.color());
1376 if color.a == 0 {
1377 continue;
1378 }
1379 let physical = glyph.physical((x, baseline), scale);
1380 let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1381 continue;
1382 };
1383 let left = physical.x + image.placement.left;
1384 let top = physical.y - image.placement.top;
1385 let (width, height) = (image.placement.width, image.placement.height);
1386 match image.content {
1387 SwashContent::Mask => {
1388 blend_mask(pixmap, left, top, width, height, &image.data, color);
1389 }
1390 SwashContent::Color => {
1391 let premultiplied = is_color_outline(image);
1392 let rgba = (image.data.as_slice(), premultiplied);
1393 blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1394 }
1395 SwashContent::SubpixelMask => {}
1397 }
1398 }
1399 let origin = text.origin().x;
1400 let own = (text.underline(), text.strikethrough());
1401 if own != (false, false) {
1402 self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1403 }
1404 let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1408 text.span(run.line_i, a),
1409 text.span(run.line_i, b),
1410 ) {
1411 (Some(a), Some(b)) => std::ptr::eq(a, b),
1412 (a, b) => a.is_none() && b.is_none(),
1413 };
1414 for glyphs in run.glyphs.chunk_by(same_span) {
1415 let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1416 continue;
1417 };
1418 let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1419 let lines = (span.underline || lit, span.strikethrough);
1420 if lines != (false, false) {
1421 let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1422 self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1423 }
1424 }
1425 }
1426 }
1427
1428 fn decorations(
1432 &mut self,
1433 pixmap: &mut PixmapMut<'_>,
1434 origin: f32,
1435 glyphs: &[LayoutGlyph],
1436 baseline: f32,
1437 lines: (bool, bool),
1438 color: Color,
1439 ) {
1440 let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1441 (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1442 };
1443 for glyphs in glyphs.chunk_by(same_font) {
1444 self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1445 }
1446 }
1447
1448 fn font_decorations(
1454 &mut self,
1455 pixmap: &mut PixmapMut<'_>,
1456 origin: f32,
1457 glyphs: &[LayoutGlyph],
1458 baseline: f32,
1459 (underline, strikethrough): (bool, bool),
1460 color: Color,
1461 ) {
1462 let Some(first) = glyphs.first() else {
1463 return;
1464 };
1465 let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1466 return;
1467 };
1468 let metrics = font.metrics();
1469 let em = f32::from(metrics.units_per_em);
1470 if em == 0.0 {
1471 return;
1472 }
1473 let Grid { scale, left, .. } = self.grid;
1474 let (start, end) = glyphs
1475 .iter()
1476 .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1477 (start.min(glyph.x), end.max(glyph.x + glyph.w))
1478 });
1479 let x0 = ((origin + start) * scale).round() - left;
1480 let x1 = ((origin + end) * scale).round() - left;
1481 let size = first.font_size * scale;
1482 let lines = [
1484 (underline, metrics.underline, -0.125),
1485 (strikethrough, metrics.strikeout, 0.3),
1486 ];
1487 for (on, decoration, offset) in lines {
1488 if !on {
1489 continue;
1490 }
1491 let (offset, thickness) =
1492 decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1493 let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1495 let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1496 if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1497 let mut path = PathBuilder::new();
1498 path.push_rect(area);
1499 fill(pixmap, path, color, FillRule::Winding);
1500 }
1501 }
1502 }
1503
1504 fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1506 let Some(area) = self.grid.rect(input.area) else {
1507 return;
1508 };
1509 self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1510 painter.input_contents(layer, input);
1511 });
1512 }
1513
1514 fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1517 let color = input.text.color();
1518 self.selection(pixmap, input.selection, input.selection_color);
1519 self.text(pixmap, &input.text);
1520 for line in input.underline {
1521 if let Some(area) = self.grid.rect(*line) {
1522 let mut path = PathBuilder::new();
1523 path.push_rect(area);
1524 fill(pixmap, path, color, FillRule::Winding);
1525 }
1526 }
1527 if let Some(caret) = input.caret {
1528 let left = self.grid.x(caret.x);
1530 let right = self.grid.x(caret.right()).max(left + 1.0);
1531 if let Some(area) = tiny_skia::Rect::from_ltrb(
1532 left,
1533 self.grid.y(caret.y),
1534 right,
1535 self.grid.y(caret.bottom()),
1536 ) {
1537 let mut path = PathBuilder::new();
1538 path.push_rect(area);
1539 fill(pixmap, path, color, FillRule::Winding);
1540 }
1541 }
1542 }
1543
1544 fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], tint: Color) {
1546 for span in spans {
1547 if let Some(area) = self.grid.rect(*span) {
1548 let mut path = PathBuilder::new();
1549 path.push_rect(area);
1550 fill(pixmap, path, tint, FillRule::Winding);
1551 }
1552 }
1553 }
1554
1555 fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1557 let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1558 return;
1559 };
1560 match self.icons.image(image, (width, height), self.grid.scale) {
1561 Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1562 transition::blit(pixmap, (x, y), pixels);
1563 }
1564 Some(Drawn::One(pixels)) => {
1566 let paint = PixmapPaint {
1567 quality: FilterQuality::Bilinear,
1568 ..PixmapPaint::default()
1569 };
1570 let stretch = Transform::from_scale(
1571 width as f32 / pixels.width() as f32,
1572 height as f32 / pixels.height() as f32,
1573 )
1574 .post_translate(x as f32, y as f32);
1575 pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1576 }
1577 Some(Drawn::Two { from, to, t }) => {
1578 transition::draw(pixmap, (x, y), from, to, t, image.transition);
1579 }
1580 None => {}
1581 }
1582 }
1583
1584 fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1586 let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1587 return;
1588 };
1589 let frame = capture.frame;
1590 let Some([left, top, part_width, part_height]) = frame.drawn_part(capture.crop) else {
1593 return;
1594 };
1595 let crop = capture.crop.and_then(|_| {
1596 let sides = [left, top, part_width, part_height].map(|side| side as i32);
1598 tiny_skia::IntRect::from_xywh(sides[0], sides[1], part_width, part_height)
1599 });
1600 let size = (width, height);
1601 if let Some(pixels) = self
1602 .icons
1603 .capture(capture.id, frame, size, capture.fit, crop)
1604 {
1605 draw_at(pixmap, x, y, pixels);
1606 }
1607 }
1608
1609 fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1614 let Grid {
1615 scale, left, top, ..
1616 } = self.grid;
1617 let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1618 let (x, y) = (
1619 (rect.x * scale).round() - left,
1620 (rect.y * scale).round() - top,
1621 );
1622 if !(width >= 1.0 && height >= 1.0) {
1623 return None;
1624 }
1625 let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1626 visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1628 }
1629
1630 fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1632 let Grid {
1633 scale, left, top, ..
1634 } = self.grid;
1635 let side = (icon.rect.width * scale).round();
1636 if side.is_nan() || side < 1.0 {
1637 return;
1638 }
1639 let x = (icon.rect.x * scale).round() - left;
1640 let y = (icon.rect.y * scale).round() - top;
1641 let size = icon.rect.width.round() as u32;
1643 let theme_scale = scale.ceil().max(1.0) as u32;
1644 let sizes = (side as u32, size, theme_scale);
1645 let source = match icon.fallback {
1647 Some(fallback) if self.icons.get(icon.source, sizes, icon.tint).is_none() => fallback,
1648 _ => icon.source,
1649 };
1650 if let Some(image) = self.icons.get(source, sizes, icon.tint) {
1651 pixmap.draw_pixmap(
1652 x as i32,
1653 y as i32,
1654 image.as_ref(),
1655 &PixmapPaint::default(),
1656 Transform::identity(),
1657 None,
1658 );
1659 }
1660 }
1661}
1662
1663fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1665 let paint = PixmapPaint::default();
1666 pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1667}
1668
1669fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1671 area.right() > 0.0
1672 && area.bottom() > 0.0
1673 && area.left() < pixmap.width() as f32
1674 && area.top() < pixmap.height() as f32
1675}
1676
1677fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1678 let Some(path) = path.finish() else {
1679 return;
1680 };
1681 let mut paint = Paint::default();
1682 paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1683 paint.anti_alias = true;
1684 pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1685}
1686
1687type Corners = [f32; 4];
1689
1690fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
1695 let Some((on, off)) = fit_dash(length, on, off) else {
1696 return false;
1697 };
1698 let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
1699 return false;
1700 };
1701 if let Some(dashes) = path.dash(&dash, 1.0) {
1702 all.push_path(&dashes);
1703 }
1704 true
1705}
1706
1707fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1711 const KAPPA: f32 = 0.552_284_8;
1714 let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1715 let radius = corners[index];
1716 let k = radius * (1.0 - KAPPA);
1717 let points = match index {
1718 0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
1719 1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
1720 2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
1721 _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
1722 };
1723 points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
1724}
1725
1726fn spread_corners(corners: Corners, spread: f32) -> Corners {
1730 corners.map(|radius| {
1731 if spread > 0.0 && radius < spread {
1732 radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
1733 } else {
1734 (radius + spread).max(0.0)
1735 }
1736 })
1737}
1738
1739fn fit(
1741 [top_left, top_right, bottom_right, bottom_left]: Corners,
1742 area: tiny_skia::Rect,
1743) -> Corners {
1744 let radii = Radii {
1745 top_left,
1746 top_right,
1747 bottom_right,
1748 bottom_left,
1749 };
1750 radii.fit(area.width(), area.height()).corners()
1751}
1752
1753fn inset(corners: Corners, by: f32) -> Corners {
1755 corners.map(|radius| (radius - by).max(0.0))
1756}
1757
1758fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1761 if corners.iter().all(|&radius| radius <= 0.0) {
1762 path.push_rect(rect);
1763 return;
1764 }
1765 let [.., start] = corner(rect, corners, 0);
1766 path.move_to(start.x, start.y);
1767 for index in [1, 2, 3, 0] {
1768 let [start, one, two, end] = corner(rect, corners, index);
1769 path.line_to(start.x, start.y);
1770 if corners[index] > 0.0 {
1771 path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1772 }
1773 }
1774 path.close();
1775}
1776
1777fn mul(a: u8, b: u8) -> u8 {
1779 ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1780}
1781
1782fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1784 let rest = 255 - source[3];
1785 for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1786 *channel = value.saturating_add(mul(*channel, rest));
1787 }
1788}
1789
1790fn overlap(
1794 pixmap: &PixmapMut<'_>,
1795 left: i32,
1796 top: i32,
1797 width: u32,
1798 height: u32,
1799) -> Option<(usize, usize, usize, usize)> {
1800 let column_start = (-i64::from(left)).max(0);
1801 let row_start = (-i64::from(top)).max(0);
1802 let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1803 let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1804 (column_start < column_end && row_start < row_end).then_some((
1805 column_start as usize,
1806 column_end as usize,
1807 row_start as usize,
1808 row_end as usize,
1809 ))
1810}
1811
1812fn blend_mask(
1814 pixmap: &mut PixmapMut<'_>,
1815 left: i32,
1816 top: i32,
1817 width: u32,
1818 height: u32,
1819 mask: &[u8],
1820 color: Color,
1821) {
1822 if mask.len() < width as usize * height as usize {
1823 return;
1824 }
1825 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1826 else {
1827 return;
1828 };
1829 let stride = pixmap.width() as usize;
1830 let data = pixmap.data_mut();
1831 for row in rows..rows_end {
1832 for column in columns..columns_end {
1833 let coverage = mask[row * width as usize + column];
1834 if coverage == 0 {
1835 continue;
1836 }
1837 let alpha = mul(color.a, coverage);
1838 let source = [
1839 mul(color.r, alpha),
1840 mul(color.g, alpha),
1841 mul(color.b, alpha),
1842 alpha,
1843 ];
1844 let x = (i64::from(left) + column as i64) as usize;
1845 let y = (i64::from(top) + row as i64) as usize;
1846 over(data, (y * stride + x) * 4, source);
1847 }
1848 }
1849}
1850
1851const SAMPLES: usize = 8;
1853
1854struct BlurredBox {
1861 middle: (f32, f32),
1862 half: (f32, f32),
1863 corners: Corners,
1864 largest: f32,
1865 sigma: f32,
1866 whole: f32,
1869}
1870
1871impl BlurredBox {
1872 fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1873 let step = 6.0 * sigma / SAMPLES as f32;
1874 let whole = (0..SAMPLES)
1875 .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
1876 .sum();
1877 BlurredBox {
1878 whole,
1879 middle: (
1880 (shape.left() + shape.right()) / 2.0,
1881 (shape.top() + shape.bottom()) / 2.0,
1882 ),
1883 half: (shape.width() / 2.0, shape.height() / 2.0),
1884 corners,
1885 largest: corners.into_iter().fold(0.0, f32::max),
1886 sigma,
1887 }
1888 }
1889
1890 fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1893 let y = y - self.middle.1;
1894 let (half_width, half_height) = self.half;
1895 let reach = 3.0 * self.sigma;
1896 let down = self.along(y, half_height);
1897 let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1898 let rows = if clear_of_corners {
1899 [(0.0, 0.0, 0.0); SAMPLES]
1900 } else {
1901 self.rows_near(y)
1902 };
1903 for x in xs {
1904 let x = x - self.middle.0;
1905 let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1906 self.along(x, half_width) * down
1907 } else {
1908 let sum: f32 = rows
1909 .iter()
1910 .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1911 .sum();
1912 (sum / self.whole).clamp(0.0, 1.0)
1913 };
1914 mask.push((coverage * 255.0).round() as u8);
1915 }
1916 }
1917
1918 fn along(&self, p: f32, half: f32) -> f32 {
1920 self.between(p, half, half)
1921 }
1922
1923 fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1926 let reach = 3.0 * self.sigma;
1927 if -(left - reach) <= p && p <= right - reach {
1928 return 1.0;
1929 }
1930 let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1931 0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1932 }
1933
1934 fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1938 let (half_width, half_height) = self.half;
1939 let reach = 3.0 * self.sigma;
1940 let start = (y - half_height).clamp(-reach, reach);
1941 let end = (y + half_height).clamp(-reach, reach);
1942 let step = (end - start) / SAMPLES as f32;
1943 std::array::from_fn(|sample| {
1944 let offset = start + step * (sample as f32 + 0.5);
1945 let row = y - offset;
1948 let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1949 let (left, right) = if row < 0.0 {
1950 (top_left, top_right)
1951 } else {
1952 (bottom_left, bottom_right)
1953 };
1954 let span = |radius: f32| {
1955 let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1956 half_width - radius
1957 + (radius * radius - into_corner * into_corner)
1958 .max(0.0)
1959 .sqrt()
1960 };
1961 (span(left), span(right), gaussian(offset, self.sigma) * step)
1962 })
1963 }
1964}
1965
1966fn gaussian(x: f32, sigma: f32) -> f32 {
1968 let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1969 (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1970}
1971
1972fn erf(x: f32) -> f32 {
1975 let a = x.abs();
1976 let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1977 let d = d * d;
1978 (1.0 - 1.0 / (d * d)).copysign(x)
1979}
1980
1981fn is_color_outline(image: &SwashImage) -> bool {
1988 format!("{:?}", image.source).starts_with("ColorOutline")
1989}
1990
1991fn blend_rgba(
1994 pixmap: &mut PixmapMut<'_>,
1995 left: i32,
1996 top: i32,
1997 width: u32,
1998 height: u32,
1999 (rgba, premultiplied): (&[u8], bool),
2000 opacity: u8,
2001) {
2002 if rgba.len() < width as usize * height as usize * 4 {
2003 return;
2004 }
2005 let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
2006 else {
2007 return;
2008 };
2009 let stride = pixmap.width() as usize;
2010 let data = pixmap.data_mut();
2011 for row in rows..rows_end {
2012 for column in columns..columns_end {
2013 let index = (row * width as usize + column) * 4;
2014 let alpha = mul(rgba[index + 3], opacity);
2015 if alpha == 0 {
2016 continue;
2017 }
2018 let factor = if premultiplied { opacity } else { alpha };
2021 let source = [
2022 mul(rgba[index], factor),
2023 mul(rgba[index + 1], factor),
2024 mul(rgba[index + 2], factor),
2025 alpha,
2026 ];
2027 let x = (i64::from(left) + column as i64) as usize;
2028 let y = (i64::from(top) + row as i64) as usize;
2029 over(data, (y * stride + x) * 4, source);
2030 }
2031 }
2032}
2033
2034fn keep_near(
2037 kept: &mut PathBuilder,
2038 contour: &[PathSegment],
2039 [left, top, right, bottom]: [f32; 4],
2040) {
2041 let (mut low, mut high) = (
2042 (f32::INFINITY, f32::INFINITY),
2043 (f32::NEG_INFINITY, f32::NEG_INFINITY),
2044 );
2045 let points = contour.iter().flat_map(|segment| match *segment {
2046 PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
2047 PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
2048 PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
2049 PathSegment::Close => [None; 3],
2050 });
2051 for point in points.flatten() {
2052 low = (low.0.min(point.x), low.1.min(point.y));
2053 high = (high.0.max(point.x), high.1.max(point.y));
2054 }
2055 if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
2056 return;
2057 }
2058 for segment in contour {
2059 match *segment {
2060 PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
2061 PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
2062 PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
2063 PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
2064 PathSegment::Close => kept.close(),
2065 }
2066 }
2067}
2068
2069pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
2074 let period = on + off;
2075 if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
2076 return None;
2077 }
2078 let count = (perimeter / period).round().max(1.0);
2079 let stretch = perimeter / (count * period);
2080 Some((on * stretch, off * stretch))
2081}
2082
2083pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
2089 let edges = [area.left(), area.top(), area.right(), area.bottom()];
2090 if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
2091 return false;
2092 }
2093 let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2094 let [left, top, right, bottom] = [
2095 area.left().clamp(0.0, width),
2096 area.top().clamp(0.0, height),
2097 area.right().clamp(0.0, width),
2098 area.bottom().clamp(0.0, height),
2099 ]
2100 .map(|edge| edge as usize);
2101 let stride = pixmap.width() as usize * 4;
2102 let pixel = [color.r, color.g, color.b, 255];
2103 for row in pixmap
2104 .data_mut()
2105 .chunks_exact_mut(stride)
2106 .take(bottom)
2107 .skip(top)
2108 {
2109 row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
2110 }
2111 true
2112}