Skip to main content

crabshell_render/
draw.rs

1//! Drawing a window's view into a buffer.
2//!
3//! The areas to repaint are drawn from scratch, one tile of a fixed grid at
4//! a time, into an RGBA pixmap of the tile's size, then copied into the
5//! buffer. The pixmap clips the drawing to the tile, and the copy converts
6//! the pixels to the buffer's byte order, so tiny-skia, glyph masks, resvg
7//! and PNG decoding all work in the RGBA order they share.
8
9use 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
30/// The side of a tile, in buffer pixels. tiny-skia cuts a curve where it
31/// leaves the pixmap, which changes the antialiasing beside the cut, so
32/// every pixel is drawn in the same tile whatever the damage, and a repaint
33/// matches drawing everything.
34const TILE: u32 = 64;
35
36/// How many glyph images cosmic-text's cache may hold after a draw before
37/// it is cleared. A bar needs a few hundred; the cache never shrinks itself.
38const GLYPH_CACHE_LIMIT: usize = 2048;
39
40/// The most pixels a transformed layer may hold, 16 MiB. Only a widget
41/// shrunk to a sliver of its size, so that a tile shows much of it, comes
42/// near; past this it isn't drawn.
43const LAYER_LIMIT: u64 = 1 << 22;
44
45/// Buffer pixels a transformed layer reaches past what it samples, so the
46/// edges where tiny-skia cuts its curves stay out of the picture.
47const LAYER_MARGIN: f32 = 2.0;
48
49/// How a buffer stores each pixel, as `wl_shm` names the formats. Both are
50/// 32 bits per pixel with premultiplied alpha.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum PixelFormat {
53  /// Bytes B, G, R, A in memory. Every compositor supports it.
54  Argb8888,
55  /// Bytes R, G, B, A in memory, as tiny-skia draws. Copied as is.
56  Abgr8888,
57}
58
59/// A buffer to draw a window into.
60pub struct Canvas<'a> {
61  /// The buffer's memory: `width * height` pixels of 4 bytes, row by row.
62  pub pixels: &'a mut [u8],
63  /// The width in pixels: the window's logical width times `scale`,
64  /// rounded halfway away from zero, as `wp_fractional_scale_v1` says.
65  /// The window's edge is drawn at the buffer's edge either way.
66  pub width: u32,
67  /// The height in pixels, likewise.
68  pub height: u32,
69  /// Physical pixels per logical pixel.
70  pub scale: f32,
71  /// How the buffer stores pixels.
72  pub format: PixelFormat,
73  /// The frame the buffer last held, updated by the draw.
74  pub age: &'a mut BufferAge,
75}
76
77/// Draws windows. One serves every window; it holds the glyph and icon
78/// caches.
79pub struct Renderer {
80  glyphs: SwashCache,
81  icons: Icons,
82  /// Where each tile is drawn before it is copied into the buffer, kept
83  /// between frames.
84  scratch: Vec<u8>,
85  work: Work,
86}
87
88/// What drawing has cost so far, for tests to check that a draw stays
89/// small.
90#[derive(Default)]
91#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
92struct Work {
93  /// Pixels of opacity, clip and transform layers allocated.
94  layer_pixels: u64,
95  /// Nodes drawn.
96  nodes: u64,
97  /// Nodes looked through for images a draw skips.
98  skipped: u64,
99  /// Pixels of alpha content shadows were blurred over.
100  blurred: u64,
101  /// Pixels gradients were worked out for. A `Cell`, since a ramp is
102  /// worked out while painting reads the rest.
103  gradient_pixels: std::cell::Cell<u64>,
104}
105
106impl Renderer {
107  /// A renderer with empty caches, looking icons up in the `hicolor`
108  /// theme.
109  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  /// How many times an image's file was looked up, for tests.
119  #[cfg(test)]
120  pub(crate) fn image_lookups(&self) -> usize {
121    self.icons.lookups()
122  }
123
124  /// The number of glyph images cached, for tests.
125  #[cfg(test)]
126  pub(crate) fn cached_glyphs(&self) -> usize {
127    self.glyphs.image_cache.len()
128  }
129
130  /// The pixels of opacity layers allocated and the nodes drawn so far,
131  /// for tests.
132  #[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  /// The nodes looked through for images a draw skips so far, for tests.
138  #[cfg(test)]
139  pub(crate) fn skipped_nodes(&self) -> u64 {
140    self.work.skipped
141  }
142
143  /// The pixels gradients were worked out for so far, for tests.
144  #[cfg(test)]
145  pub(crate) fn gradient_pixels(&self) -> u64 {
146    self.work.gradient_pixels.get()
147  }
148
149  /// A renderer that looks icon names up in `bases` instead of the
150  /// environment's directories, for tests.
151  #[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  /// Sets the icon theme names are looked up in.
160  pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
161    self.icons.set_theme(theme.into());
162  }
163
164  /// The lookup icon names go through, which follows
165  /// [`set_icon_theme`](Renderer::set_icon_theme).
166  pub fn icon_lookup(&self) -> IconLookup {
167    self.icons.lookup()
168  }
169
170  /// The bytes the icon cache keeps, for tests.
171  #[cfg(test)]
172  pub(crate) fn cached_bytes(&self) -> usize {
173    self.icons.cached_bytes()
174  }
175
176  /// The number of rasterized icons cached, for tests.
177  #[cfg(test)]
178  pub(crate) fn cached_icons(&self) -> usize {
179    self.icons.cached()
180  }
181
182  /// The number of times an icon was rasterized, for tests.
183  #[cfg(test)]
184  pub(crate) fn rasterized_icons(&self) -> usize {
185    self.icons.rasterized()
186  }
187
188  /// Drops the scaled frames kept for screencopy views `gone`, at once:
189  /// each is as large as its view, and an idle shell may draw nothing
190  /// for a long while.
191  pub fn forget_captures(&mut self, gone: &[u64]) {
192    self.icons.forget_captures(gone);
193  }
194
195  /// From now on, decodes image files on a worker thread, which starts
196  /// with the first and ends once none is left: a GIF's frames, a blurred
197  /// picture, and any file past 64 KiB or drawn past 256 by 256 pixels.
198  /// Until its picture comes in, an image draws the picture its
199  /// transition leaves, or the one it drew before at its size, or
200  /// nothing. Without this, as for a snapshot, each is decoded as it is
201  /// first drawn.
202  ///
203  /// The platform then follows [`decoding`](Self::decoding), and while it
204  /// holds asks to be woken with
205  /// [`wake_when_decoded`](Self::wake_when_decoded) and calls
206  /// [`take_decoded`](Self::take_decoded) when it is.
207  pub fn decode_off_thread(&mut self) {
208    self.icons.decode_off_thread();
209  }
210
211  /// Loads the images of `view` whose status still waits, drawn or not,
212  /// at their laid-out size at `scale`, or one pixel without one, and
213  /// tells each status: at once, or when the worker is done with it. The
214  /// platform calls it for every window, drawn or not, whenever
215  /// [`image_sources_changed`](crabshell_ui::image_sources_changed) says
216  /// a source changed.
217  pub fn load_images(&mut self, view: &WindowView<'_>, scale: f32) {
218    self.icons.load_unseen(&view.loading_images(), scale);
219  }
220
221  /// Whether pictures are being decoded for images drawn, or came in and
222  /// weren't taken with [`take_decoded`](Self::take_decoded) yet.
223  pub fn decoding(&self) -> bool {
224    self.icons.decoding()
225  }
226
227  /// Calls `wake` once, from the worker thread, when a picture is
228  /// decoded, or at once if one waits to be taken. It replaces a `wake`
229  /// given before.
230  pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
231    self.icons.wake_when_decoded(Box::new(wake));
232  }
233
234  /// Whether the last draw drew an image whose picture is still being
235  /// decoded, so the platform can hold a window's first frame for it.
236  pub fn waits_for_pictures(&self) -> bool {
237    self.icons.waited()
238  }
239
240  /// Caches the pictures decoded since the last call, logging each
241  /// failure once, and returns the ids of the images that wait for them,
242  /// for the platform to repaint with
243  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image) in
244  /// every window.
245  pub fn take_decoded(&mut self) -> Vec<u64> {
246    self.icons.take_decoded()
247  }
248
249  /// When the next frame of an animated GIF is due, counting from `now`
250  /// for one drawn since the last call. `None` while no GIF drawn plays.
251  /// The platform wakes then and calls
252  /// [`advance_images`](Self::advance_images).
253  pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
254    self.icons.next_frame(now)
255  }
256
257  /// Moves each GIF whose next frame is due by `now` on to it, and returns
258  /// their image ids for the platform to repaint with
259  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image). A
260  /// GIF waits for its next frame only once that one is drawn, so one no
261  /// longer shown wakes nothing more.
262  pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
263    self.icons.advance(now)
264  }
265
266  /// How many jobs the decoding thread did, for tests.
267  #[cfg(test)]
268  pub(crate) fn decoded_off_thread(&self) -> usize {
269    self.icons.worker_work().0
270  }
271
272  /// Whether the decoding thread runs, for tests.
273  #[cfg(test)]
274  pub(crate) fn decoder_running(&self) -> bool {
275    self.icons.worker_work().1
276  }
277
278  /// The number of screencopy frames kept scaled, for tests.
279  #[cfg(test)]
280  pub(crate) fn cached_captures(&self) -> usize {
281    self.icons.captures()
282  }
283
284  /// Draws the laid-out window `view` into `canvas` and returns the areas
285  /// to report with `wl_surface.damage_buffer`.
286  ///
287  /// `damage` is what the window reported since the last draw, from
288  /// [`Window::take_damage`](crabshell_ui::Window::take_damage). The draw
289  /// repaints that, plus what changed in frames this buffer missed
290  /// according to `history`, or the whole buffer when that is more than
291  /// half of it or the buffer is new. Text and glyphs come from `text`.
292  /// An image in that area it skips, at opacity 0 or cut out by its mask
293  /// region, still has its picture loaded at the size drawing it would
294  /// give, once a draw, so revealing it draws it on its first frame.
295  ///
296  /// Commit the buffer after every successful draw, in order: the history
297  /// counts each one as a frame the compositor showed.
298  ///
299  /// # Errors
300  ///
301  /// If `canvas` holds the wrong number of bytes for its size, or its
302  /// scale isn't a positive number. Nothing is drawn and the history
303  /// doesn't advance.
304  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/// A canvas whose bytes don't fit its size, or whose scale isn't a positive
393/// number.
394#[derive(Clone, Copy, Debug, PartialEq)]
395pub struct CanvasError {
396  /// The canvas's width in pixels.
397  pub width: u32,
398  /// The canvas's height in pixels.
399  pub height: u32,
400  /// The canvas's scale.
401  pub scale: f32,
402  /// How many bytes the canvas held.
403  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
428/// Copies an area drawn in RGBA into the buffer, converting byte order.
429fn 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        // Red and blue swapped in a whole word, which vectorizes, unlike
441        // moving the bytes one by one.
442        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/// Turns logical coordinates into pixels of the area being drawn.
452#[derive(Clone, Copy)]
453struct Grid {
454  /// Pixels a logical pixel: the output's scale times `zoom`.
455  scale: f32,
456  /// How many times its own resolution a transformed layer is drawn at,
457  /// from [`Affine::layer_zoom`]; 1 outside one.
458  zoom: f32,
459  /// The transforms around what is drawn, from its coordinates to the
460  /// window's, without their moves.
461  linear: Affine,
462  /// The window's logical size.
463  window: Size,
464  /// The buffer's size in pixels.
465  width: u32,
466  height: u32,
467  /// Where the area being drawn starts in the buffer.
468  left: f32,
469  top: f32,
470}
471
472impl Grid {
473  /// A logical x coordinate on the pixel grid. The window's right edge is
474  /// the buffer's, even where rounding would leave a column out.
475  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  /// A logical y coordinate on the pixel grid, likewise.
485  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  /// The pixels of a `width` by `height` area that `rect`, in logical
495  /// pixels, touches: rounded outward, a pixel added around for
496  /// antialiasing, and cut to the area. `None` if it misses the area.
497  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    // `as` saturates, so huge or negative values stay in range.
502    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  /// The transforms around a node moved by `transform`, without their
511  /// moves, and the zoom and scale its layer is drawn at.
512  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  /// This grid for a pixmap placed at `x`, `y` within this one.
530  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  /// A logical rectangle on the pixel grid, or `None` if it covers no
539  /// pixel.
540  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
551/// What drawing needs besides the pixmap.
552struct 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  /// The cells of content shadows cast in this draw.
559  casts: &'a mut HashMap<CastKey, effects::Cast>,
560  /// Where the clipping widgets around what is drawn and the window's
561  /// edges let anything show, in logical pixels; `None` inside a
562  /// transform, whose coordinates are its own.
563  clip: Option<Rect>,
564}
565
566/// A cell of a content shadow cast in a draw: its widget's path, and the
567/// cell's column and row.
568type CastKey = (String, i64, i64);
569
570impl Painter<'_> {
571  /// A painter for a pixmap on `grid`, in the same space.
572  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  /// Draws `node` and everything inside it. With an opacity below 1, a
585  /// mask, a mask region or a content shadow, they are drawn into one layer first, which
586  /// is masked, given its shadow and blended in at that opacity, so
587  /// overlapping children don't show through each other.
588  fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
589    // Nothing the node or its descendants paint reaches this area.
590    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    // A region that covers this area whole or not at all needs no layer;
610    // a content shadow may still fall where it is clear.
611    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      // The layer covers only what the subtree paints in this area.
630      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  /// Loads the pictures of the images in `node` and everything inside it
648  /// that a reveal would draw, which this draw skips, at the size drawing
649  /// them would give, so the reveal draws them on its first frame. Each
650  /// node skipped is looked through once a draw, and none in a window
651  /// without images.
652  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  /// [`skip`](Self::skip)'s walk of `node` on `grid`, loading the images
660  /// that show within `clip`.
661  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      // shortcut: the clip isn't carried into a transform's coordinates, so
666      // a transformed subtree loads what clips cut away; map it if that costs.
667      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        // `as` saturates, so a huge box stays in range.
680        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  /// What `node_contents` draws into a fresh `layer`, kept only where the
696  /// style's mask is opaque and inside the node's mask region, which
697  /// `cover` holds when it was worked out over this layer already, with
698  /// `shadow` cast by what is left put under it.
699  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  /// Draws `node` and everything inside it into a layer in its own
727  /// coordinates, then blends that in through its `transform`, filtered
728  /// bilinearly, at `opacity`: one layer for both. The layer covers only
729  /// what lands in this pixmap, in the node's own buffer pixels times the
730  /// zoom of every transform around it, so what they scale up stays
731  /// sharp, and a pixel is always drawn the same way in the same tile.
732  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    // From the node's own pixels, zoomed, to its parent's.
753    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      // `as` saturates; the window's edge is past any layer drawn.
794      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    // A content shadow is cast by the layer this is drawn into, and an
831    // inset one inside the box.
832    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  /// `node`'s children, drawn into a layer that is blended in through a
861  /// mask of the inside of the node's border. The mask is drawn in the
862  /// area's own pixels, on the same fixed grid as everything else, so a
863  /// repaint cuts every edge exactly as a full draw does.
864  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      // A scroll view always clips; its bar is cut to its corners too.
885      for (handle, bar) in node.scroll_bars() {
886        painter.draw_box(layer, handle, &bar);
887      }
888    });
889  }
890
891  /// What `draw` paints within `cover`, a logical rectangle, blended in
892  /// through a mask of `shape`, a pixel rectangle with rounded corners.
893  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  /// A widget's rectangle on the pixel grid and each corner's radius in
932  /// pixels, fitted to it as CSS does, so two on one side never overlap.
933  /// `None` if it covers no pixel.
934  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  /// The border's width in pixels: as in CSS, rounded down to whole
942  /// pixels, but at least one. 0 without a border.
943  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  /// The background, an inset shadow and the border of a widget's
956  /// rectangle.
957  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        // A ring: the outer shape with the inner one cut out.
1000        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  /// A border `width` pixels wide inside `area`, dashed by `on` and `off`
1016  /// logical pixels along its middle line, so the dashes follow the
1017  /// corners. The line is laid out and dashed in buffer pixels and moved
1018  /// onto the pixmap, so tiles cut the dashes in the same places. `false`
1019  /// when the pattern or the box can't take dashes, to draw it solid.
1020  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      // Each corner trades two radii of straight line for a quarter
1046      // circle.
1047      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      // As browsers do, each run from one square corner to the next gets
1059      // its own whole number of dashes, centered on both corners.
1060      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      // The two half dashes meeting at a square corner end on its middle
1082      // line, so the outer quarter of the corner is filled by a piece
1083      // joined there with a miter. A dot is round there as anywhere.
1084      if on > 0.0 {
1085        // Each corner's incoming direction, clockwise from the top left.
1086        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    // Every tile the border crosses would stroke every dash, so only the
1100    // dashes near this one are kept. A closed outline that misses the
1101    // tile adds nothing inside it, so the pixels are the same. A miter
1102    // reaches at most twice the width past its line.
1103    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      // A dash of 0 is a dot.
1126      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  /// `shadow` of the box `rect` with `style`'s corners. A sharp one is a
1143  /// filled shape; a blurred one is worked out pixel by pixel in buffer
1144  /// pixels, so every tile agrees, and only within one and a half blurs
1145  /// of its shape, past which it fades below a 255th.
1146  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    // The shape in buffer pixels.
1158    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    // A cut-out shadow leaves clear what the box's background covers.
1169    let cut = if shadow.cut_out {
1170      self.box_mask(pixmap, rect, style)
1171    } else {
1172      None
1173    };
1174    // CSS draws a blur as a Gaussian of half its length.
1175    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  /// An inset `shadow` inside `area` with `corners`, within a border
1229  /// `border` pixels wide: the inside of the border, but for a hole of its
1230  /// shape moved, shrunk by the spread and blurred, as CSS draws one. Like
1231  /// an outer shadow, it is worked out in buffer pixels, so tiles agree.
1232  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    // The hole in buffer pixels; a spread that swallows it leaves none.
1264    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    // The inside of the border covers these pixels, and the shadow shows
1301    // where the blurred hole doesn't.
1302    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  /// How much of each of this pixmap's pixels the box `rect` with
1337  /// `style`'s corners covers, as its background fills it.
1338  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  /// Glyphs, drawn as masks in their span's color or else the text's,
1349  /// then any underline and strikethrough. The baseline sits on a whole
1350  /// pixel so horizontal strokes stay sharp; glyphs keep their sub-pixel
1351  /// horizontal position.
1352  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      // Rounded in buffer coordinates, so every area drawn agrees.
1360      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      // A lit link takes the hover color, if the text has one.
1367      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          // Not requested: there is no subpixel antialiasing.
1396          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      // A span's own lines run across its glyphs on the line, each in its
1405      // color. cosmic-text's decoration spans join two decorated spans
1406      // across the text between them, so they aren't used.
1407      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  /// The underline and strikethrough across `glyphs`, each run of
1429  /// glyphs from one font at the place and thickness that font gives, so
1430  /// a fallback glyph's line sits where its own font puts it.
1431  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  /// The underline and strikethrough across `glyphs`, all from one font,
1449  /// at the place and thickness it gives, as cosmic-text draws them.
1450  /// Edges snap to whole pixels in the buffer, so every tile agrees, and
1451  /// each line is at least a pixel thick. A line is kept within half an
1452  /// em of the baseline, which the text's painted area covers.
1453  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    // cosmic-text's defaults for a font that gives none.
1483    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      // The offset is to the line's top, upward from the baseline.
1494      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  /// A text field, cut to its content box.
1505  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  /// A field's selection in its color, the text, and a caret in the
1515  /// text's color.
1516  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      // At least one pixel wide whatever the scale.
1529      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  /// A selection, behind text, in `tint`.
1545  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  /// An image, scaled to its box in pixels.
1556  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      // A picture of another size, while this one is decoded.
1565      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  /// A screencopy view's frame, scaled to its box in pixels.
1585  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    // The same test `shown` makes, so a view that draws nothing isn't
1591    // shown.
1592    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      // Within the frame, which is at most 8192 pixels a side.
1597      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  /// Where a picture in `rect` goes in the pixmap, and its size in
1610  /// pixels; `None` if it covers no pixel of it. Placed and sized apart,
1611  /// as an icon is, so a picture past the window's edge is cut there
1612  /// instead of squeezed inside it.
1613  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    // `as` saturates, so a huge box stays in range.
1627    visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1628  }
1629
1630  /// An icon, rasterized at its size in pixels.
1631  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    // Theme directories come in whole scales; 1.5 looks for @2 icons.
1642    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    // Asked twice when there is a fallback; the second is a cache hit.
1646    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
1663/// Draws `pixels` unscaled with its corner at `x`, `y`.
1664fn 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
1669/// Whether any of `area` lies inside the pixmap.
1670fn 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
1687/// Each corner's radius in pixels, from the top left clockwise.
1688type Corners = [f32; 4];
1689
1690/// Dashes `path`, `length` pixels long, by `on` and `off` stretched so a
1691/// whole number of them fits, each centered on a multiple of the period
1692/// from its start, and adds them to `all`. `false` when the pattern can't
1693/// be drawn.
1694fn 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
1707/// Where corner `index` of `rect`, from the top left clockwise, starts
1708/// and ends going clockwise, with its quarter circle's control points
1709/// between: `[start, one, two, end]`, all one point for a square corner.
1710fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1711  // How far a cubic curve's control points sit along the tangents to
1712  // follow a quarter circle closely.
1713  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
1726/// `corners` for a shadow's shape grown by `spread` pixels, or shrunk by
1727/// a negative one. As in CSS, a corner smaller than the spread grows by
1728/// less, so a square box keeps square corners.
1729fn 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
1739/// `corners` fitted to `area` as CSS fits them ([`Radii::fit`]).
1740fn 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
1753/// `corners` for a shape `by` pixels inside the edge.
1754fn inset(corners: Corners, by: f32) -> Corners {
1755  corners.map(|radius| (radius - by).max(0.0))
1756}
1757
1758/// Adds a rectangle with circular `corners` to `path`, clockwise from
1759/// the end of its top-left one.
1760fn 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
1777/// `a * b / 255`, rounded.
1778fn mul(a: u8, b: u8) -> u8 {
1779  ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1780}
1781
1782/// Blends a premultiplied `source` over the pixel at `index` (in bytes).
1783fn 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
1790/// The part of a `width` by `height` image placed at `left`, `top` that
1791/// lies inside the pixmap: the first and last column and row, as image
1792/// coordinates.
1793fn 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
1812/// Blends a glyph's coverage mask in `color`.
1813fn 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
1851/// How many rows a point near a corner sums.
1852const SAMPLES: usize = 8;
1853
1854/// A rectangle with rounded corners blurred by a Gaussian: how much of it
1855/// covers each point. Away from the corners it is a plain rectangle,
1856/// whose blur is the product of each axis's, from the error function.
1857/// Near a corner, each row's span is blurred across and the rows are
1858/// summed over eight samples of the Gaussian down. Each corner has its
1859/// own radius; the largest says where the corners' rows begin.
1860struct BlurredBox {
1861  middle: (f32, f32),
1862  half: (f32, f32),
1863  corners: Corners,
1864  largest: f32,
1865  sigma: f32,
1866  /// What the samples sum to where the shape covers them all, a little
1867  /// under 1, so a point the shape covers whole is covered whole.
1868  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  /// Pushes the coverage at each of `xs` on the row at `y`, out of 255,
1891  /// onto `mask`.
1892  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  /// The blur of the span from `-half` to `half` at `p`.
1919  fn along(&self, p: f32, half: f32) -> f32 {
1920    self.between(p, half, half)
1921  }
1922
1923  /// The blur of the span from `-left` to `right` at `p`. One the blur
1924  /// stays inside of is covered whole.
1925  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  /// The rows of the shape a point at height `y` near a corner sums: for
1935  /// each sample within the shape and the Gaussian's reach, how far the
1936  /// row reaches left and right of the middle, and its weight.
1937  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      // How far into a corner's rows this one is, and how much it
1946      // narrows there.
1947      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
1966/// The normal distribution's density at `x`, for a deviation of `sigma`.
1967fn 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
1972/// The error function, within 5e-4, an eighth of a color level, by
1973/// Abramowitz and Stegun's 7.1.27, which needs no exponential.
1974fn 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
1981/// Whether a color glyph came from vector color layers (COLR), which swash
1982/// renders premultiplied, rather than an embedded bitmap, which it hands
1983/// over as stored: straight alpha.
1984///
1985/// cosmic-text doesn't re-export swash's `Source`, and swash isn't a
1986/// dependency of this crate, so the variant is read from its name.
1987fn is_color_outline(image: &SwashImage) -> bool {
1988  format!("{:?}", image.source).starts_with("ColorOutline")
1989}
1990
1991/// Blends a color glyph's RGBA pixels at `opacity` out of 255. `rgba` says
1992/// whether they are premultiplied already.
1993fn 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      // Premultiplied colors only need the opacity; straight ones need
2019      // their own alpha too.
2020      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
2034/// Adds `contour` to `kept` when the box around its points reaches into
2035/// `near`, given as left, top, right and bottom.
2036fn 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
2069/// A dash of `on` pixels and a gap of `off`, stretched or squeezed so a
2070/// whole number of them goes around `perimeter`, at least one. `None` for
2071/// a pattern that can't be drawn: a number that isn't finite or is
2072/// negative, no gap, or a period shorter than a pixel.
2073pub(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
2083/// Fills `area` with the opaque `color` straight into the pixels, as
2084/// tiny-skia's path fill gives it, without its raster pipeline: a
2085/// window's background under a picture was half of a 1080p repaint.
2086/// `false`, drawing nothing, unless `color` is opaque and every edge is on
2087/// a whole pixel.
2088pub(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}