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;
10use std::sync::Arc;
11use std::sync::atomic::AtomicU64;
12
13use cosmic_text::{FontSystem, LayoutGlyph, SwashCache, SwashContent, SwashImage};
14use crabshell_ui::{
15  Affine, CaptureView, Color, Content, IconView, ImageView, InputView, NodeView, Radii, Rect,
16  Shadow, Size, Span, Style, TextSystem, TextView, WindowView,
17};
18use tiny_skia::{
19  FillRule, FilterQuality, LineCap, LineJoin, Mask, Paint, PathBuilder, PathSegment, Pixmap,
20  PixmapMut, PixmapPaint, Stroke, StrokeDash, Transform,
21};
22
23use crate::damage::{BufferAge, DamageHistory, PixelRect};
24use crate::icons::{Drawn, Icons};
25use crate::theme::IconLookup;
26
27mod canvas;
28mod effects;
29mod gradient;
30mod kept;
31mod patched;
32mod transition;
33
34pub(crate) use kept::Kept;
35use kept::{Area, Layer, Seen, Want};
36#[cfg(test)]
37pub(crate) use kept::{KEPT_LIMIT, PATCHES};
38
39/// The side of a tile, in buffer pixels. tiny-skia cuts a curve where it
40/// leaves the pixmap, which changes the antialiasing beside the cut, so
41/// every pixel is drawn in the same tile whatever the damage, and a repaint
42/// matches drawing everything.
43const TILE: u32 = 64;
44
45#[cfg(test)]
46thread_local! {
47  /// The tile side for this thread's draws, which a test sets larger to
48  /// draw a reference with no seams.
49  pub(crate) static TILE_SIDE: std::cell::Cell<u32> = const { std::cell::Cell::new(TILE) };
50}
51
52/// The side of a tile: [`TILE`], or what a test set.
53fn tile_side() -> u32 {
54  #[cfg(test)]
55  return TILE_SIDE.get();
56  #[cfg(not(test))]
57  TILE
58}
59
60/// How many glyph images cosmic-text's cache may hold after a draw before
61/// it is cleared. A bar needs a few hundred; the cache never shrinks itself.
62const GLYPH_CACHE_LIMIT: usize = 2048;
63
64/// The most pixels a transformed layer may hold, 16 MiB. Only a widget
65/// shrunk to a sliver of its size, so that a tile shows much of it, comes
66/// near; past this it isn't drawn.
67const LAYER_LIMIT: u64 = 1 << 22;
68
69/// Buffer pixels a transformed layer reaches past what it samples, so the
70/// edges where tiny-skia cuts its curves stay out of the picture.
71const LAYER_MARGIN: f32 = 2.0;
72
73/// How a buffer stores each pixel, as `wl_shm` names the formats. Both are
74/// 32 bits per pixel with premultiplied alpha.
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum PixelFormat {
77  /// Bytes B, G, R, A in memory. Every compositor supports it.
78  Argb8888,
79  /// Bytes R, G, B, A in memory, as tiny-skia draws. Copied as is.
80  Abgr8888,
81}
82
83/// A buffer to draw a window into.
84pub struct Canvas<'a> {
85  /// The buffer's memory: `width * height` pixels of 4 bytes, row by row.
86  pub pixels: &'a mut [u8],
87  /// The width in pixels: the window's logical width times `scale`,
88  /// rounded halfway away from zero, as `wp_fractional_scale_v1` says.
89  /// The window's edge is drawn at the buffer's edge either way.
90  pub width: u32,
91  /// The height in pixels, likewise.
92  pub height: u32,
93  /// Physical pixels per logical pixel.
94  pub scale: f32,
95  /// How the buffer stores pixels.
96  pub format: PixelFormat,
97  /// The frame the buffer last held, updated by the draw.
98  pub age: &'a mut BufferAge,
99}
100
101/// Draws windows. One serves every window; it holds the glyph and icon
102/// caches.
103pub struct Renderer {
104  glyphs: SwashCache,
105  icons: Icons,
106  /// Where each tile is drawn before it is copied into the buffer, kept
107  /// between frames.
108  scratch: Vec<u8>,
109  work: Work,
110  /// The bytes every window's kept layers hold, against
111  /// [`kept::KEPT_LIMIT`].
112  kept: Arc<AtomicU64>,
113  /// Counts icon theme changes, which no kept layer outlives.
114  theme: u64,
115}
116
117/// What drawing has cost so far, for tests to check that a draw stays
118/// small.
119#[derive(Default)]
120#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
121struct Work {
122  /// Pixels of opacity, clip and transform layers allocated.
123  layer_pixels: u64,
124  /// Nodes drawn.
125  nodes: u64,
126  /// Nodes looked through for images a draw skips.
127  skipped: u64,
128  /// Pixels of alpha content shadows were blurred over.
129  blurred: u64,
130  /// Pixels gradients were worked out for. A `Cell`, since a ramp is
131  /// worked out while painting reads the rest.
132  gradient_pixels: std::cell::Cell<u64>,
133}
134
135impl Renderer {
136  /// A renderer with empty caches, looking icons up in the `hicolor`
137  /// theme.
138  pub fn new() -> Renderer {
139    Renderer {
140      glyphs: SwashCache::new(),
141      icons: Icons::new(),
142      scratch: Vec::new(),
143      work: Work::default(),
144      kept: Arc::default(),
145      theme: 0,
146    }
147  }
148
149  /// The bytes kept layers hold for every window, for tests.
150  #[cfg(test)]
151  pub(crate) fn kept_bytes(&self) -> u64 {
152    self.kept.load(std::sync::atomic::Ordering::Relaxed)
153  }
154
155  /// Counts `bytes` as kept, for tests of the budget.
156  #[cfg(test)]
157  pub(crate) fn spend_kept(&self, bytes: u64) {
158    self
159      .kept
160      .fetch_add(bytes, std::sync::atomic::Ordering::Relaxed);
161  }
162
163  /// How many times an image's file was looked up, for tests.
164  #[cfg(test)]
165  pub(crate) fn image_lookups(&self) -> usize {
166    self.icons.lookups()
167  }
168
169  /// The number of glyph images cached, for tests.
170  #[cfg(test)]
171  pub(crate) fn cached_glyphs(&self) -> usize {
172    self.glyphs.image_cache.len()
173  }
174
175  /// The pixels of opacity layers allocated and the nodes drawn so far,
176  /// for tests.
177  #[cfg(test)]
178  pub(crate) fn work(&self) -> (u64, u64, u64) {
179    (self.work.layer_pixels, self.work.nodes, self.work.blurred)
180  }
181
182  /// The nodes looked through for images a draw skips so far, for tests.
183  #[cfg(test)]
184  pub(crate) fn skipped_nodes(&self) -> u64 {
185    self.work.skipped
186  }
187
188  /// The pixels gradients were worked out for so far, for tests.
189  #[cfg(test)]
190  pub(crate) fn gradient_pixels(&self) -> u64 {
191    self.work.gradient_pixels.get()
192  }
193
194  /// A renderer that looks icon names up in `bases` instead of the
195  /// environment's directories, for tests.
196  #[cfg(test)]
197  pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
198    Renderer {
199      icons: Icons::with_themes(crate::theme::Themes::new(bases)),
200      ..Renderer::new()
201    }
202  }
203
204  /// Sets the icon theme names are looked up in. Every window's kept
205  /// layers are dropped at its next draw, so a fade shows the new icons.
206  pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
207    self.icons.set_theme(theme.into());
208    self.theme += 1;
209  }
210
211  /// The lookup icon names go through, which follows
212  /// [`set_icon_theme`](Renderer::set_icon_theme).
213  pub fn icon_lookup(&self) -> IconLookup {
214    self.icons.lookup()
215  }
216
217  /// The bytes the icon cache keeps, for tests.
218  #[cfg(test)]
219  pub(crate) fn cached_bytes(&self) -> usize {
220    self.icons.cached_bytes()
221  }
222
223  /// The number of rasterized icons cached, for tests.
224  #[cfg(test)]
225  pub(crate) fn cached_icons(&self) -> usize {
226    self.icons.cached()
227  }
228
229  /// The number of times an icon was rasterized, for tests.
230  #[cfg(test)]
231  pub(crate) fn rasterized_icons(&self) -> usize {
232    self.icons.rasterized()
233  }
234
235  /// Drops the scaled frames kept for screencopy views `gone`, at once:
236  /// each is as large as its view, and an idle shell may draw nothing
237  /// for a long while.
238  pub fn forget_captures(&mut self, gone: &[u64]) {
239    self.icons.forget_captures(gone);
240  }
241
242  /// From now on, decodes image files on a worker thread, which starts
243  /// with the first and ends once none is left: a GIF's frames, a blurred
244  /// picture, and any file past 64 KiB or drawn past 256 by 256 pixels.
245  /// Until its picture comes in, an image draws the picture its
246  /// transition leaves, or the one it drew before at its size, or
247  /// nothing. Without this, as for a snapshot, each is decoded as it is
248  /// first drawn.
249  ///
250  /// The platform then follows [`decoding`](Self::decoding), and while it
251  /// holds asks to be woken with
252  /// [`wake_when_decoded`](Self::wake_when_decoded) and calls
253  /// [`take_decoded`](Self::take_decoded) when it is.
254  pub fn decode_off_thread(&mut self) {
255    self.icons.decode_off_thread();
256  }
257
258  /// Loads the images of `view` whose status still waits, drawn or not,
259  /// at their laid-out size at `scale`, or one pixel without one, and
260  /// tells each status: at once, or when the worker is done with it. The
261  /// platform calls it for every window, drawn or not, whenever
262  /// [`image_sources_changed`](crabshell_ui::image_sources_changed) says
263  /// a source changed.
264  pub fn load_images(&mut self, view: &WindowView<'_>, scale: f32) {
265    self.icons.load_unseen(&view.loading_images(), scale);
266  }
267
268  /// Whether pictures are being decoded for images drawn, or came in and
269  /// weren't taken with [`take_decoded`](Self::take_decoded) yet.
270  pub fn decoding(&self) -> bool {
271    self.icons.decoding()
272  }
273
274  /// Calls `wake` once, from the worker thread, when a picture is
275  /// decoded, or at once if one waits to be taken. It replaces a `wake`
276  /// given before.
277  pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
278    self.icons.wake_when_decoded(Box::new(wake));
279  }
280
281  /// Whether the last draw drew an image whose picture is still being
282  /// decoded, so the platform can hold a window's first frame for it.
283  pub fn waits_for_pictures(&self) -> bool {
284    self.icons.waited()
285  }
286
287  /// Caches the pictures decoded since the last call, logging each
288  /// failure once, and returns the ids of the images that wait for them,
289  /// for the platform to repaint with
290  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image) in
291  /// every window.
292  pub fn take_decoded(&mut self) -> Vec<u64> {
293    self.icons.take_decoded()
294  }
295
296  /// When the next frame of an animated GIF is due, counting from `now`
297  /// for one drawn since the last call. `None` while no GIF drawn plays.
298  /// The platform wakes then and calls
299  /// [`advance_images`](Self::advance_images).
300  pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
301    self.icons.next_frame(now)
302  }
303
304  /// Moves each GIF whose next frame is due by `now` on to it, and returns
305  /// their image ids for the platform to repaint with
306  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image). A
307  /// GIF waits for its next frame only once that one is drawn, so one no
308  /// longer shown wakes nothing more.
309  pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
310    self.icons.advance(now)
311  }
312
313  /// How many jobs the decoding thread did, for tests.
314  #[cfg(test)]
315  pub(crate) fn decoded_off_thread(&self) -> usize {
316    self.icons.worker_work().0
317  }
318
319  /// Whether the decoding thread runs, for tests.
320  #[cfg(test)]
321  pub(crate) fn decoder_running(&self) -> bool {
322    self.icons.worker_work().1
323  }
324
325  /// The number of screencopy frames kept scaled, for tests.
326  #[cfg(test)]
327  pub(crate) fn cached_captures(&self) -> usize {
328    self.icons.captures()
329  }
330
331  /// Draws the laid-out window `view` into `canvas` and returns the areas
332  /// to report with `wl_surface.damage_buffer`.
333  ///
334  /// `damage` is what the window reported since the last draw, from
335  /// [`Window::take_damage`](crabshell_ui::Window::take_damage). The draw
336  /// repaints that, plus what changed in frames this buffer missed
337  /// according to `history`, or the whole buffer when that is more than
338  /// half of it or the buffer is new. Text and glyphs come from `text`.
339  /// An image in that area it skips, at opacity 0 or cut out by its mask
340  /// region, still has its picture loaded at the size drawing it would
341  /// give, once a draw, so revealing it draws it on its first frame.
342  ///
343  /// Commit the buffer after every successful draw, in order: the history
344  /// counts each one as a frame the compositor showed.
345  ///
346  /// # Errors
347  ///
348  /// If `canvas` holds the wrong number of bytes for its size, or its
349  /// scale isn't a positive number. Nothing is drawn and the history
350  /// doesn't advance.
351  pub fn draw(
352    &mut self,
353    view: &WindowView<'_>,
354    damage: &[Rect],
355    text: &mut TextSystem,
356    history: &mut DamageHistory,
357    canvas: Canvas<'_>,
358  ) -> Result<Vec<PixelRect>, CanvasError> {
359    let Canvas {
360      pixels,
361      width,
362      height,
363      scale,
364      format,
365      age,
366    } = canvas;
367    if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
368      || !(scale.is_finite() && scale > 0.0)
369    {
370      return Err(CanvasError {
371        width,
372        height,
373        scale,
374        bytes: pixels.len(),
375      });
376    }
377    self.icons.start_frame(history.id(), view.has_images());
378    let plan = history.plan(damage, scale, width, height, age);
379    history.kept.start(&self.kept, self.theme);
380    let tile = tile_side();
381    let mut tiles: Vec<(u32, u32)> = Vec::new();
382    for area in plan.repaint.iter().filter(|area| area.area() > 0) {
383      for row in area.y / tile..=(area.y + area.height - 1) / tile {
384        tiles
385          .extend((area.x / tile..=(area.x + area.width - 1) / tile).map(|column| (row, column)));
386      }
387    }
388    tiles.sort_unstable();
389    tiles.dedup();
390    let mut casts = HashMap::new();
391    let mut fonts = text.font_system();
392    for &(row, column) in &tiles {
393      self.icons.start_tile((row, column));
394      let (x, y) = (column * tile, row * tile);
395      let size = (width.saturating_sub(x), height.saturating_sub(y));
396      let area = PixelRect::new(x, y, tile.min(size.0), tile.min(size.1));
397      self.scratch.clear();
398      self.scratch.resize(area.area() as usize * 4, 0);
399      let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
400      else {
401        continue;
402      };
403      let mut painter = Painter {
404        grid: Grid {
405          scale,
406          zoom: 1.0,
407          linear: Affine {
408            sx: 1.0,
409            ky: 0.0,
410            kx: 0.0,
411            sy: 1.0,
412            tx: 0.0,
413            ty: 0.0,
414          },
415          window: view.size(),
416          width,
417          height,
418          left: area.x as f32,
419          top: area.y as f32,
420        },
421        glyphs: &mut self.glyphs,
422        icons: &mut self.icons,
423        fonts: &mut fonts,
424        work: &mut self.work,
425        casts: &mut casts,
426        kept: &mut history.kept,
427        clip: Some(Rect::new(0.0, 0.0, view.size().width, view.size().height)),
428        extent: [0, 0, width, height],
429      };
430      painter.node(&mut pixmap, view.root());
431      copy(&self.scratch, area, pixels, width, format);
432    }
433    history.kept.end();
434    self.icons.repainted(&tiles);
435    self.icons.end_frame();
436    if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
437      self.glyphs.image_cache.clear();
438      self.glyphs.outline_command_cache.clear();
439    }
440    Ok(plan.report)
441  }
442}
443
444/// A canvas whose bytes don't fit its size, or whose scale isn't a positive
445/// number.
446#[derive(Clone, Copy, Debug, PartialEq)]
447pub struct CanvasError {
448  /// The canvas's width in pixels.
449  pub width: u32,
450  /// The canvas's height in pixels.
451  pub height: u32,
452  /// The canvas's scale.
453  pub scale: f32,
454  /// How many bytes the canvas held.
455  pub bytes: usize,
456}
457
458impl std::fmt::Display for CanvasError {
459  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
460    write!(
461      f,
462      "a {}x{} canvas at scale {} needs {} bytes, but has {}",
463      self.width,
464      self.height,
465      self.scale,
466      u64::from(self.width) * u64::from(self.height) * 4,
467      self.bytes
468    )
469  }
470}
471
472impl std::error::Error for CanvasError {}
473
474impl Default for Renderer {
475  fn default() -> Self {
476    Self::new()
477  }
478}
479
480/// Copies an area drawn in RGBA into the buffer, converting byte order.
481fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
482  let stride = width as usize * 4;
483  let row_bytes = area.width as usize * 4;
484  for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
485    let start = (area.y as usize + row) * stride + area.x as usize * 4;
486    let target = &mut pixels[start..start + row_bytes];
487    match format {
488      PixelFormat::Abgr8888 => target.copy_from_slice(source),
489      PixelFormat::Argb8888 => {
490        let (to, _) = target.as_chunks_mut::<4>();
491        let (from, _) = source.as_chunks::<4>();
492        // Red and blue swapped in a whole word, which vectorizes, unlike
493        // moving the bytes one by one.
494        for (to, from) in to.iter_mut().zip(from) {
495          let pixel = u32::from_le_bytes(*from);
496          *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
497        }
498      }
499    }
500  }
501}
502
503/// Turns logical coordinates into pixels of the area being drawn.
504#[derive(Clone, Copy)]
505struct Grid {
506  /// Pixels a logical pixel: the output's scale times `zoom`.
507  scale: f32,
508  /// How many times its own resolution a transformed layer is drawn at,
509  /// from [`Affine::layer_zoom`]; 1 outside one.
510  zoom: f32,
511  /// The transforms around what is drawn, from its coordinates to the
512  /// window's, without their moves.
513  linear: Affine,
514  /// The window's logical size.
515  window: Size,
516  /// The buffer's size in pixels.
517  width: u32,
518  height: u32,
519  /// Where the area being drawn starts in the buffer.
520  left: f32,
521  top: f32,
522}
523
524impl Grid {
525  /// A logical x coordinate on the pixel grid. The window's right edge is
526  /// the buffer's, even where rounding would leave a column out.
527  fn x(&self, x: f32) -> f32 {
528    let pixel = if x >= self.window.width {
529      self.width as f32
530    } else {
531      (x * self.scale).round()
532    };
533    pixel - self.left
534  }
535
536  /// A logical y coordinate on the pixel grid, likewise.
537  fn y(&self, y: f32) -> f32 {
538    let pixel = if y >= self.window.height {
539      self.height as f32
540    } else {
541      (y * self.scale).round()
542    };
543    pixel - self.top
544  }
545
546  /// The pixels of a `width` by `height` area that `rect`, in logical
547  /// pixels, touches: rounded outward, a pixel added around for
548  /// antialiasing, and cut to the area. `None` if it misses the area.
549  fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
550    if !(rect.width > 0.0 && rect.height > 0.0) {
551      return None;
552    }
553    // `as` saturates, so huge or negative values stay in range.
554    let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
555    let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
556    let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
557    let bottom =
558      (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
559    (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
560  }
561
562  /// The transforms around a node moved by `transform`, without their
563  /// moves, and the zoom and scale its layer is drawn at.
564  fn through(&self, transform: Affine) -> (Affine, f32, f32) {
565    let (outer, inner) = (self.linear, transform);
566    let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0).pre_concat(
567      Transform::from_row(inner.sx, inner.ky, inner.kx, inner.sy, 0.0, 0.0),
568    );
569    let linear = Affine {
570      sx: linear.sx,
571      ky: linear.ky,
572      kx: linear.kx,
573      sy: linear.sy,
574      tx: 0.0,
575      ty: 0.0,
576    };
577    let zoom = linear.layer_zoom();
578    (linear, zoom, self.scale / self.zoom * zoom)
579  }
580
581  /// This grid for a pixmap placed at `x`, `y` within this one.
582  fn moved(&self, x: u32, y: u32) -> Grid {
583    Grid {
584      left: self.left + x as f32,
585      top: self.top + y as f32,
586      ..*self
587    }
588  }
589
590  /// A logical rectangle on the pixel grid, or `None` if it covers no
591  /// pixel.
592  fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
593    tiny_skia::Rect::from_ltrb(
594      self.x(rect.x),
595      self.y(rect.y),
596      self.x(rect.right()),
597      self.y(rect.bottom()),
598    )
599    .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
600  }
601}
602
603/// What drawing needs besides the pixmap.
604struct Painter<'a> {
605  grid: Grid,
606  glyphs: &'a mut SwashCache,
607  icons: &'a mut Icons,
608  fonts: &'a mut FontSystem,
609  work: &'a mut Work,
610  /// The cells of content shadows cast in this draw.
611  casts: &'a mut HashMap<CastKey, effects::Cast>,
612  /// The window's layers kept from its last draw, for this one.
613  kept: &'a mut Kept,
614  /// Where the clipping widgets around what is drawn and the window's
615  /// edges let anything show, in logical pixels; `None` inside a
616  /// transform, whose coordinates are its own.
617  clip: Option<Rect>,
618  /// Outside a transform, the buffer pixels the layers being drawn into
619  /// may hold, left, top, right and bottom, whatever the tile: a kept
620  /// layer is cut where they are.
621  extent: [u32; 4],
622}
623
624/// A cell of a content shadow cast in a draw: its widget's path, and the
625/// cell's column and row.
626type CastKey = (String, i64, i64);
627
628impl Painter<'_> {
629  /// A painter for a pixmap on `grid`, in the same space.
630  fn on(&mut self, grid: Grid) -> Painter<'_> {
631    Painter {
632      grid,
633      glyphs: &mut *self.glyphs,
634      icons: &mut *self.icons,
635      fonts: &mut *self.fonts,
636      work: &mut *self.work,
637      casts: &mut *self.casts,
638      kept: &mut *self.kept,
639      clip: self.clip,
640      extent: self.extent,
641    }
642  }
643
644  /// The extent within a layer that holds what lands in `rect`.
645  fn narrowed(&self, rect: Rect) -> [u32; 4] {
646    let window = Grid {
647      left: 0.0,
648      top: 0.0,
649      ..self.grid
650    };
651    let [left, top, right, bottom] = self.extent;
652    match window.cover(rect, window.width, window.height) {
653      Some((x, y, width, height)) => [
654        left.max(x),
655        top.max(y),
656        right.min(x + width),
657        bottom.min(y + height),
658      ],
659      None => [0; 4],
660    }
661  }
662
663  /// Draws `node` and everything inside it. With an opacity below 1, a
664  /// mask, a mask region or a content shadow, they are drawn into one layer first, which
665  /// is masked, given its shadow and blended in at that opacity, so
666  /// overlapping children don't show through each other.
667  fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
668    // Nothing the node or its descendants paint reaches this area.
669    let Some((x, y, width, height)) =
670      self
671        .grid
672        .cover(node.bounds(), pixmap.width(), pixmap.height())
673    else {
674      return;
675    };
676    let style = node.style();
677    let opacity = style.opacity.unwrap_or(1.0);
678    let opacity = if opacity.is_nan() {
679      1.0
680    } else {
681      opacity.clamp(0.0, 1.0)
682    };
683    if opacity == 0.0 {
684      self.skip(node);
685      return;
686    }
687    let shadow = effects::cast_by_content(&style);
688    // A region that covers this area whole or not at all needs no layer;
689    // a content shadow may still fall where it is clear.
690    let region = node
691      .mask_region()
692      .filter(|_| node.transform().is_none() && shadow.is_none())
693      .map(|region| {
694        let inner = self.on(self.grid.moved(x, y));
695        inner.region_cover(width, height, node.rect(), region)
696      });
697    if matches!(region, Some(effects::Cover::Clear)) {
698      self.skip(node);
699      return;
700    }
701    if let Some(transform) = node.transform() {
702      self.transformed(pixmap, node, &style, transform, opacity);
703    } else if opacity < 1.0
704      || style.mask.is_some()
705      || matches!(region, Some(effects::Cover::Part(_)))
706      || shadow.is_some()
707    {
708      if opacity < 1.0 && self.kept_fade(pixmap, node, &style, shadow, opacity) {
709        return;
710      }
711      // The layer covers only what the subtree paints in this area.
712      let Some(mut layer) = Pixmap::new(width, height) else {
713        return;
714      };
715      self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
716      let mut inner = self.on(self.grid.moved(x, y));
717      inner.extent = inner.narrowed(node.bounds());
718      inner.layer_contents(&mut layer.as_mut(), node, &style, shadow, region);
719      composite(pixmap, (x as i32, y as i32), &layer, opacity, None);
720    } else {
721      self.node_contents(pixmap, node, &style);
722    }
723  }
724
725  /// Loads the pictures of the images in `node` and everything inside it
726  /// that a reveal would draw, which this draw skips, at the size drawing
727  /// them would give, so the reveal draws them on its first frame, and a
728  /// kept layer keeps them cached while it blends in. Each
729  /// node skipped is looked through once a draw, and none in a window
730  /// without images.
731  fn skip(&mut self, node: NodeView<'_>) {
732    if self.icons.look_through(node.path()) {
733      let (grid, clip) = (self.grid, self.clip);
734      self.skipped(node, grid, clip, false);
735    }
736  }
737
738  /// Keeps the cached pictures and scaled captures inside a kept layer
739  /// marked used for this draw, once a draw.
740  fn keep_inside(&mut self, node: NodeView<'_>) {
741    if self.icons.keep_through(node.path()) {
742      let (grid, clip) = (self.grid, self.clip);
743      self.skipped(node, grid, clip, true);
744    }
745  }
746
747  /// [`skip`](Self::skip)'s walk of `node` on `grid`, loading the images
748  /// that show within `clip`, and with `captures` marking scaled captures
749  /// used too.
750  fn skipped(
751    &mut self,
752    node: NodeView<'_>,
753    mut grid: Grid,
754    mut clip: Option<Rect>,
755    captures: bool,
756  ) {
757    self.work.skipped += 1;
758    if let Some(transform) = node.transform() {
759      (grid.linear, grid.zoom, grid.scale) = grid.through(transform);
760      // shortcut: the clip isn't carried into a transform's coordinates, so
761      // a transformed subtree loads what clips cut away; map it if that costs.
762      clip = None;
763    }
764    let shows =
765      |clip: Option<Rect>, rect: Rect| clip.is_none_or(|clip| !clip.intersect(rect).is_empty());
766    match node.content() {
767      Content::Image(image) if shows(clip, image.rect) => {
768        let (width, height) = (
769          (image.rect.width * grid.scale).round(),
770          (image.rect.height * grid.scale).round(),
771        );
772        if width >= 1.0 && height >= 1.0 {
773          // `as` saturates, so a huge box stays in range.
774          let size = (width as u32, height as u32);
775          self.icons.skipped(&image, size, grid.scale);
776        }
777      }
778      Content::Capture(capture) if captures && shows(clip, capture.rect) => {
779        self.icons.keep_capture(capture.id);
780      }
781      _ => {}
782    }
783    if node.clips() {
784      let rect = node.rect();
785      clip = Some(clip.map_or(rect, |clip| clip.intersect(rect)));
786    }
787    for child in node.children() {
788      if shows(clip, child.bounds()) {
789        self.skipped(child, grid, clip, captures);
790      }
791    }
792  }
793
794  /// Whether this draw blends `node`'s layer from the last instead of
795  /// drawing it, which is decided on the node's first visit: only when
796  /// the last draw drew it through a layer too, nothing inside it changed
797  /// since, and its own `transform` did, or without one its `opacity`.
798  /// Outside a transform, where `want` says where the layer goes now;
799  /// `fill` draws it over an area.
800  fn keeps(
801    &mut self,
802    node: NodeView<'_>,
803    (opacity, transform): (f32, Option<Affine>),
804    want: Want,
805    fill: impl FnOnce(&mut Painter<'_>, Area) -> Option<Pixmap>,
806  ) -> bool {
807    let frame = self.kept.frame;
808    if let Some(seen) = self.kept.seen.get(node.path())
809      && seen.frame == frame
810    {
811      return seen.layer.is_some();
812    }
813    let seen = self.kept.seen.remove(node.path());
814    let revision = node.revision();
815    // A transformed layer kept is drawn whole, without the seams of one
816    // cut to each tile, so it is kept only while the transform moves,
817    // when those seams move too; a still one fading draws as before.
818    let keep = seen.as_ref().is_some_and(|seen| {
819      seen.revision == revision
820        && match transform {
821          Some(_) => seen.transform != transform,
822          None => seen.opacity != opacity,
823        }
824    });
825    let Want { needed, whole, at } = want;
826    let fits = |layer: &Layer| layer.area.holds(&needed) && layer.at == at;
827    let mut layer = seen
828      .and_then(|seen| seen.layer)
829      .filter(|layer| keep && fits(layer));
830    let pixels = |area: &Area| u64::from(area.width) * u64::from(area.height);
831    // All of it when it fits, so a layer that moves into view needn't be
832    // drawn again.
833    let area = [whole, needed]
834      .into_iter()
835      .find(|area| pixels(area) <= LAYER_LIMIT);
836    if keep
837      && layer.is_none()
838      && let Some(area) = area
839    {
840      // A transform inside takes its zoom from the one moving around it.
841      let (nested, playing) = self.inside(node);
842      let refused = playing || nested && transform.is_some();
843      let held = (!refused).then(|| self.kept.hold(pixels(&area) * 4));
844      if let Some(held) = held.flatten()
845        && let Some(pixmap) = fill(self, area)
846      {
847        layer = Some(Layer {
848          pixmap,
849          area,
850          at,
851          _held: held,
852        });
853      }
854    }
855    let kept = layer.is_some();
856    self.kept.seen.insert(
857      node.path().to_owned(),
858      Seen {
859        frame,
860        revision,
861        opacity,
862        transform,
863        layer,
864      },
865    );
866    kept
867  }
868
869  /// Whether anything inside `node` has a transform of its own, and
870  /// whether `node` or anything inside it is a playing GIF or a
871  /// transitioning image, which a kept layer would stop or evict.
872  fn inside(&self, node: NodeView<'_>) -> (bool, bool) {
873    let active = matches!(
874      node.content(),
875      Content::Image(image) if self.icons.animates(image.id) || image.leaving.is_some()
876    );
877    node
878      .children()
879      .fold((false, active), |(nested, playing), child| {
880        let (deeper, plays) = self.inside(child);
881        (
882          nested || deeper || child.transform().is_some(),
883          playing || plays,
884        )
885      })
886  }
887
888  /// Blends `node`'s kept layer in at `opacity`, if this draw keeps one,
889  /// drawn over all of the window it can show in a tile at a time as
890  /// each tile's own layer is, so the pixels match.
891  fn kept_fade(
892    &mut self,
893    pixmap: &mut PixmapMut<'_>,
894    node: NodeView<'_>,
895    style: &Style,
896    shadow: Option<Shadow>,
897    opacity: f32,
898  ) -> bool {
899    let Some(clip) = self.clip else {
900      return false;
901    };
902    let window = Grid {
903      left: 0.0,
904      top: 0.0,
905      ..self.grid
906    };
907    let Some((x, y, width, height)) =
908      window.cover(node.bounds().intersect(clip), window.width, window.height)
909    else {
910      return false;
911    };
912    let area = Area {
913      x: x as i32,
914      y: y as i32,
915      width,
916      height,
917    };
918    let want = Want {
919      needed: area,
920      whole: area,
921      at: (window.scale, window.zoom),
922    };
923    let fill = |painter: &mut Painter<'_>, _: Area| {
924      let mut kept = Pixmap::new(width, height)?;
925      let side = tile_side();
926      for row in y / side..=(y + height - 1) / side {
927        for column in x / side..=(x + width - 1) / side {
928          // What the tile's own layer holds: the tile, cut where the
929          // layers around are.
930          let [ex, ey, ex1, ey1] = painter.extent;
931          let (left, top) = ((column * side).max(ex), (row * side).max(ey));
932          let right = ((column + 1) * side).min(window.width).min(ex1);
933          let bottom = ((row + 1) * side).min(window.height).min(ey1);
934          if left >= right || top >= bottom {
935            continue;
936          }
937          let tile = window.moved(left, top);
938          let size = (right - left, bottom - top);
939          let Some((dx, dy, w, h)) = tile.cover(node.bounds(), size.0, size.1) else {
940            continue;
941          };
942          let mut layer = Pixmap::new(w, h)?;
943          painter.work.layer_pixels += u64::from(w) * u64::from(h);
944          let extent = painter.narrowed(node.bounds());
945          let mut inner = painter.on(tile.moved(dx, dy));
946          inner.extent = extent;
947          inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
948          let at = ((left + dx) as i32 - area.x, (top + dy) as i32 - area.y);
949          transition::blit(&mut kept.as_mut(), at, &layer);
950        }
951      }
952      Some(kept)
953    };
954    if !self.keeps(node, (opacity, None), want, fill) {
955      return false;
956    }
957    self.keep_inside(node);
958    let Some(layer) = self.kept.layer(node.path()) else {
959      return false;
960    };
961    // The grid's corner is a whole pixel.
962    let at = (
963      layer.area.x - self.grid.left as i32,
964      layer.area.y - self.grid.top as i32,
965    );
966    composite(pixmap, at, &layer.pixmap, opacity, None);
967    true
968  }
969
970  /// What `node_contents` draws into a fresh `layer`, kept only where the
971  /// style's mask is opaque and inside the node's mask region, which
972  /// `cover` holds when it was worked out over this layer already, with
973  /// `shadow` cast by what is left put under it.
974  fn layer_contents(
975    &mut self,
976    layer: &mut PixmapMut<'_>,
977    node: NodeView<'_>,
978    style: &Style,
979    shadow: Option<Shadow>,
980    cover: Option<effects::Cover>,
981  ) {
982    self.node_contents(layer, node, style);
983    if let Some(mask) = &style.mask {
984      self.mask(layer, node.rect(), mask);
985    }
986    let (width, height) = (layer.width(), layer.height());
987    let cover = cover.or_else(|| {
988      let region = node.mask_region()?;
989      Some(self.region_cover(width, height, node.rect(), region))
990    });
991    match cover {
992      Some(effects::Cover::Clear) => layer.fill(tiny_skia::Color::TRANSPARENT),
993      Some(effects::Cover::Part(cut)) => layer.apply_mask(&cut),
994      Some(effects::Cover::Whole) | None => {}
995    }
996    if let Some(shadow) = shadow {
997      self.content_shadow(layer, node, &shadow);
998    }
999  }
1000
1001  /// Draws `node` and everything inside it into a layer in its own
1002  /// coordinates, then blends that in through its `transform`, filtered
1003  /// bilinearly, at `opacity`: one layer for both. The layer covers only
1004  /// what lands in this pixmap, in the node's own buffer pixels times the
1005  /// zoom of every transform around it, so what they scale up stays
1006  /// sharp, and a pixel is always drawn the same way in the same tile.
1007  fn transformed(
1008    &mut self,
1009    pixmap: &mut PixmapMut<'_>,
1010    node: NodeView<'_>,
1011    style: &Style,
1012    transform: Affine,
1013    opacity: f32,
1014  ) {
1015    let Affine {
1016      sx,
1017      ky,
1018      kx,
1019      sy,
1020      tx,
1021      ty,
1022    } = transform;
1023    let Grid {
1024      scale, left, top, ..
1025    } = self.grid;
1026    let zoomed = self.grid.through(transform);
1027    let layer_scale = zoomed.2;
1028    // From the node's own pixels, zoomed, to its parent's.
1029    let device = Transform::from_scale(scale, scale)
1030      .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
1031      .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
1032    let to_pixmap = device.post_translate(-left, -top);
1033    if let Some(clip) = self.clip {
1034      // All of the window it can show in, for a layer kept.
1035      let shown = tiny_skia::Rect::from_ltrb(
1036        (clip.x * scale).floor(),
1037        (clip.y * scale).floor(),
1038        (clip.right() * scale).ceil(),
1039        (clip.bottom() * scale).ceil(),
1040      );
1041      let needed = shown.and_then(|shown| layer_area(node, device, Some(shown), layer_scale));
1042      let whole = layer_area(node, device, None, layer_scale);
1043      if let (Some(needed), Some(whole)) = (needed, whole) {
1044        let want = Want {
1045          needed,
1046          whole,
1047          at: (layer_scale, zoomed.1),
1048        };
1049        let fill =
1050          |painter: &mut Painter<'_>, area| painter.transformed_layer(node, style, area, zoomed);
1051        if self.keeps(node, (opacity, Some(transform)), want, fill) {
1052          self.keep_inside(node);
1053          if let Some(layer) = self.kept.layer(node.path()) {
1054            let corner = (layer.area.x as f32, layer.area.y as f32);
1055            let at = to_pixmap.pre_translate(corner.0, corner.1);
1056            blend_transformed(pixmap, &layer.pixmap, at, opacity);
1057            return;
1058          }
1059        }
1060      }
1061    }
1062    let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32);
1063    let Some(area) = shown.and_then(|shown| layer_area(node, to_pixmap, Some(shown), layer_scale))
1064    else {
1065      return;
1066    };
1067    let pixels = u64::from(area.width) * u64::from(area.height);
1068    if pixels > LAYER_LIMIT {
1069      tracing::debug!(
1070        "{} is transformed into a layer too large to draw",
1071        node.path()
1072      );
1073      return;
1074    }
1075    let Some(layer) = self.transformed_layer(node, style, area, zoomed) else {
1076      return;
1077    };
1078    let at = to_pixmap.pre_translate(area.x as f32, area.y as f32);
1079    blend_transformed(pixmap, &layer, at, opacity);
1080  }
1081
1082  /// `node`'s layer over `area`, in its own pixels at the scale and zoom
1083  /// `through` worked out, with the transforms around it.
1084  fn transformed_layer(
1085    &mut self,
1086    node: NodeView<'_>,
1087    style: &Style,
1088    area: Area,
1089    (linear, zoom, layer_scale): (Affine, f32, f32),
1090  ) -> Option<Pixmap> {
1091    let mut layer = Pixmap::new(area.width, area.height)?;
1092    self.work.layer_pixels += u64::from(area.width) * u64::from(area.height);
1093    let (width, height) = if zoom == self.grid.zoom {
1094      (self.grid.width, self.grid.height)
1095    } else {
1096      // `as` saturates; the window's edge is past any layer drawn.
1097      let window = self.grid.window;
1098      (
1099        (window.width * layer_scale).round() as u32,
1100        (window.height * layer_scale).round() as u32,
1101      )
1102    };
1103    let mut inner = self.on(Grid {
1104      scale: layer_scale,
1105      zoom,
1106      linear,
1107      width,
1108      height,
1109      left: area.x as f32,
1110      top: area.y as f32,
1111      ..self.grid
1112    });
1113    inner.clip = None;
1114    let shadow = effects::cast_by_content(style);
1115    inner.layer_contents(&mut layer.as_mut(), node, style, shadow, None);
1116    Some(layer)
1117  }
1118
1119  fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
1120    self.work.nodes += 1;
1121    // A content shadow is cast by the layer this is drawn into, and an
1122    // inset one inside the box.
1123    let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
1124    if let Some(shadow) = style.shadow.filter(outside) {
1125      self.shadow(pixmap, node.rect(), style, &shadow);
1126    }
1127    self.draw_box(pixmap, node.rect(), style);
1128    match node.content() {
1129      Content::Text(text) => {
1130        let color = text.color();
1131        let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1132        self.selection(pixmap, &text.selection(), tint);
1133        self.text(pixmap, &text);
1134      }
1135      Content::Icon(icon) => self.icon(pixmap, &icon),
1136      Content::Image(image) => self.image(pixmap, &image),
1137      Content::Capture(capture) => self.capture(pixmap, &capture),
1138      Content::Input(input) => self.input(pixmap, &input),
1139      Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
1140      Content::None => {}
1141    }
1142    if node.clips() {
1143      self.clipped_children(pixmap, node, style);
1144    } else {
1145      for child in node.children() {
1146        self.node(pixmap, child);
1147      }
1148    }
1149  }
1150
1151  /// `node`'s children, drawn into a layer that is blended in through a
1152  /// mask of the inside of the node's border. The mask is drawn in the
1153  /// area's own pixels, on the same fixed grid as everything else, so a
1154  /// repaint cuts every edge exactly as a full draw does.
1155  fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
1156    let Some((area, corners)) = self.box_shape(node.rect(), style) else {
1157      return;
1158    };
1159    let width = self.border_width(style);
1160    let Some(inside) = tiny_skia::Rect::from_ltrb(
1161      area.left() + width,
1162      area.top() + width,
1163      area.right() - width,
1164      area.bottom() - width,
1165    ) else {
1166      return;
1167    };
1168    let corners = inset(corners, width);
1169    let rect = node.rect();
1170    self.through_mask(pixmap, rect, (inside, corners), |painter, layer| {
1171      painter.clip = painter.clip.map(|clip| clip.intersect(rect));
1172      for child in node.children() {
1173        painter.node(layer, child);
1174      }
1175      // A scroll view always clips; its bar is cut to its corners too.
1176      for (handle, bar) in node.scroll_bars() {
1177        painter.draw_box(layer, handle, &bar);
1178      }
1179    });
1180  }
1181
1182  /// What `draw` paints within `cover`, a logical rectangle, blended in
1183  /// through a mask of `shape`, a pixel rectangle with rounded corners.
1184  fn through_mask(
1185    &mut self,
1186    pixmap: &mut PixmapMut<'_>,
1187    cover: Rect,
1188    (shape, corners): (tiny_skia::Rect, Corners),
1189    draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
1190  ) {
1191    if !visible(pixmap, shape) {
1192      return;
1193    }
1194    let extent = self.narrowed(cover);
1195    if covers(pixmap, shape, corners) {
1196      // The mask would keep everything, so the layer adds nothing.
1197      let grid = self.grid;
1198      let mut inner = self.on(grid);
1199      inner.extent = extent;
1200      draw(&mut inner, pixmap);
1201      return;
1202    }
1203    let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
1204      Mask::new(pixmap.width(), pixmap.height()),
1205      self.grid.cover(cover, pixmap.width(), pixmap.height()),
1206    ) else {
1207      return;
1208    };
1209    let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
1210      return;
1211    };
1212    self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
1213    let mut inner = self.on(self.grid.moved(x, y));
1214    inner.extent = extent;
1215    draw(&mut inner, &mut layer.as_mut());
1216    let mut path = PathBuilder::new();
1217    rounded_rect(&mut path, shape, corners);
1218    let Some(path) = path.finish() else {
1219      return;
1220    };
1221    mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1222    composite(pixmap, (x as i32, y as i32), &layer, 1.0, Some(&mask));
1223  }
1224
1225  /// A widget's rectangle on the pixel grid and each corner's radius in
1226  /// pixels, fitted to it as CSS does, so two on one side never overlap.
1227  /// `None` if it covers no pixel.
1228  fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
1229    let area = self.grid.rect(rect)?;
1230    let corners = style.radius.unwrap_or_default().corners();
1231    let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
1232    Some((area, corners))
1233  }
1234
1235  /// The border's width in pixels: as in CSS, rounded down to whole
1236  /// pixels, but at least one. 0 without a border.
1237  fn border_width(&self, style: &Style) -> f32 {
1238    let Some(border) = style.border else {
1239      return 0.0;
1240    };
1241    let width = (border.width * self.grid.scale).floor();
1242    if border.width > 0.0 {
1243      width.max(1.0)
1244    } else {
1245      width.max(0.0)
1246    }
1247  }
1248
1249  /// The background, an inset shadow and the border of a widget's
1250  /// rectangle.
1251  fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
1252    let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
1253    if style.background.is_none()
1254      && style.gradient.is_none()
1255      && style.border.is_none()
1256      && inset_shadow.is_none()
1257    {
1258      return;
1259    }
1260    let Some((area, corners)) = self.box_shape(rect, style) else {
1261      return;
1262    };
1263    if !visible(pixmap, area) {
1264      return;
1265    }
1266
1267    if let Some(color) = style.background
1268      && !(covers(pixmap, area, corners) && fill_all(pixmap, color))
1269      && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
1270    {
1271      let mut path = PathBuilder::new();
1272      rounded_rect(&mut path, area, corners);
1273      fill(pixmap, path, color, FillRule::Winding);
1274    }
1275    if let Some(gradient) = style.gradient {
1276      let mut path = PathBuilder::new();
1277      rounded_rect(&mut path, area, corners);
1278      let size = (pixmap.width(), pixmap.height());
1279      if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
1280        ramp.fill(pixmap, &path);
1281      }
1282    }
1283    if let Some(shadow) = inset_shadow {
1284      self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
1285    }
1286    if let Some(border) = style.border {
1287      let width = self.border_width(style);
1288      let inner = tiny_skia::Rect::from_ltrb(
1289        area.left() + width,
1290        area.top() + width,
1291        area.right() - width,
1292        area.bottom() - width,
1293      );
1294      // A ring whose hole covers the pixmap has nothing in it.
1295      if inner.is_some_and(|inner| covers(pixmap, inner, inset(corners, width))) {
1296        return;
1297      }
1298      let dashed = width >= 1.0
1299        && style.border_dash.is_some_and(|dash| {
1300          self.dashed_border(pixmap, (area, corners), width, border.color, dash)
1301        });
1302
1303      if width >= 1.0 && !dashed {
1304        // A ring: the outer shape with the inner one cut out.
1305        let mut path = PathBuilder::new();
1306        rounded_rect(&mut path, area, corners);
1307        if let Some(inner) = inner {
1308          rounded_rect(&mut path, inner, inset(corners, width));
1309        }
1310        fill(pixmap, path, border.color, FillRule::EvenOdd);
1311      }
1312    }
1313  }
1314
1315  /// A border `width` pixels wide inside `area`, dashed by `on` and `off`
1316  /// logical pixels along its middle line, so the dashes follow the
1317  /// corners. The line is laid out and dashed in buffer pixels and moved
1318  /// onto the pixmap, so tiles cut the dashes in the same places. `false`
1319  /// when the pattern or the box can't take dashes, to draw it solid.
1320  fn dashed_border(
1321    &self,
1322    pixmap: &mut PixmapMut<'_>,
1323    (area, corners): (tiny_skia::Rect, Corners),
1324    width: f32,
1325    color: Color,
1326    (on, off): (f32, f32),
1327  ) -> bool {
1328    let Grid {
1329      scale, left, top, ..
1330    } = self.grid;
1331    let half = width / 2.0;
1332    let Some(middle) = tiny_skia::Rect::from_ltrb(
1333      area.left() + left + half,
1334      area.top() + top + half,
1335      area.right() + left - half,
1336      area.bottom() + top - half,
1337    ) else {
1338      return false;
1339    };
1340    let corners = inset(corners, half);
1341    let (on, off) = (on * scale, off * scale);
1342    let mut all = PathBuilder::new();
1343    let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
1344    if square.is_empty() {
1345      // Each corner trades two radii of straight line for a quarter
1346      // circle.
1347      let rounding: f32 = corners
1348        .iter()
1349        .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
1350        .sum();
1351      let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
1352      let mut path = PathBuilder::new();
1353      rounded_rect(&mut path, middle, corners);
1354      if !dash_into(&mut all, path, perimeter, on, off) {
1355        return false;
1356      }
1357    } else {
1358      // As browsers do, each run from one square corner to the next gets
1359      // its own whole number of dashes, centered on both corners.
1360      for (at, &from) in square.iter().enumerate() {
1361        let to = square[(at + 1) % square.len()];
1362        let steps = (to + 4 - from - 1) % 4 + 1;
1363        let [.., mut was] = corner(middle, corners, from);
1364        let mut path = PathBuilder::new();
1365        path.move_to(was.x, was.y);
1366        let mut length = 0.0;
1367        for index in (from + 1..=from + steps).map(|index| index % 4) {
1368          let [start, one, two, end] = corner(middle, corners, index);
1369          path.line_to(start.x, start.y);
1370          length += was.distance(start);
1371          if corners[index] > 0.0 {
1372            path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1373            length += std::f32::consts::FRAC_PI_2 * corners[index];
1374          }
1375          was = end;
1376        }
1377        if !dash_into(&mut all, path, length, on, off) {
1378          return false;
1379        }
1380      }
1381      // The two half dashes meeting at a square corner end on its middle
1382      // line, so the outer quarter of the corner is filled by a piece
1383      // joined there with a miter. A dot is round there as anywhere.
1384      if on > 0.0 {
1385        // Each corner's incoming direction, clockwise from the top left.
1386        const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
1387        for &index in &square {
1388          let [point, ..] = corner(middle, corners, index);
1389          let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
1390          all.move_to(point.x - half * ax, point.y - half * ay);
1391          all.line_to(point.x, point.y);
1392          all.line_to(point.x + half * bx, point.y + half * by);
1393        }
1394      }
1395    }
1396    let Some(dashes) = all.finish() else {
1397      return true;
1398    };
1399    // Every tile the border crosses would stroke every dash, so only the
1400    // dashes near this one are kept. A closed outline that misses the
1401    // tile adds nothing inside it, so the pixels are the same. A miter
1402    // reaches at most twice the width past its line.
1403    let reach = 2.0 * width + 1.0;
1404    let near = [
1405      left - reach,
1406      top - reach,
1407      left + pixmap.width() as f32 + reach,
1408      top + pixmap.height() as f32 + reach,
1409    ];
1410    let mut kept = PathBuilder::new();
1411    let mut contour = Vec::new();
1412    for segment in dashes.segments() {
1413      if matches!(segment, PathSegment::MoveTo(_)) {
1414        keep_near(&mut kept, &contour, near);
1415        contour.clear();
1416      }
1417      contour.push(segment);
1418    }
1419    keep_near(&mut kept, &contour, near);
1420    let Some(kept) = kept.finish() else {
1421      return true;
1422    };
1423    let stroke = Stroke {
1424      width,
1425      // A dash of 0 is a dot.
1426      line_cap: if on == 0.0 {
1427        LineCap::Round
1428      } else {
1429        LineCap::Butt
1430      },
1431      line_join: LineJoin::Miter,
1432      ..Stroke::default()
1433    };
1434    let mut paint = Paint::default();
1435    paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1436    paint.anti_alias = true;
1437    let moved = Transform::from_translate(-left, -top);
1438    pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1439    true
1440  }
1441
1442  /// `shadow` of the box `rect` with `style`'s corners. A sharp one is a
1443  /// filled shape; a blurred one is worked out pixel by pixel in buffer
1444  /// pixels, so every tile agrees, and only within one and a half blurs
1445  /// of its shape, past which it fades below a 255th. A large one is
1446  /// drawn from a small one of its corners, blur and place within a pixel,
1447  /// worked out once while drawing keeps using it.
1448  fn shadow(&mut self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1449    let Grid {
1450      scale, left, top, ..
1451    } = self.grid;
1452    let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1453    if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1454      return;
1455    }
1456    let Some((area, corners)) = self.box_shape(rect, style) else {
1457      return;
1458    };
1459    if shadow.cut_out && covers(pixmap, area, corners) {
1460      return;
1461    }
1462    // The shape in buffer pixels.
1463    let spread = shadow.spread * scale;
1464    let Some(shape) = tiny_skia::Rect::from_ltrb(
1465      area.left() + left + shadow.x * scale - spread,
1466      area.top() + top + shadow.y * scale - spread,
1467      area.right() + left + shadow.x * scale + spread,
1468      area.bottom() + top + shadow.y * scale + spread,
1469    ) else {
1470      return;
1471    };
1472    let corners = fit(spread_corners(corners, spread), shape);
1473    // A cut-out shadow leaves clear what the box's background covers.
1474    let cut = if shadow.cut_out {
1475      self.box_mask(pixmap, rect, style)
1476    } else {
1477      None
1478    };
1479    // CSS draws a blur as a Gaussian of half its length.
1480    let sigma = shadow.blur.max(0.0) * scale / 2.0;
1481    if sigma < 0.25 {
1482      let mut path = PathBuilder::new();
1483      let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1484        return;
1485      };
1486      rounded_rect(&mut path, shape, corners);
1487      let Some(path) = path.finish() else {
1488        return;
1489      };
1490      let mut paint = Paint::default();
1491      let color = shadow.color;
1492      paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1493      paint.anti_alias = true;
1494      let outside = cut.map(|mut cut| {
1495        cut.invert();
1496        cut
1497      });
1498      let (rule, at) = (FillRule::Winding, Transform::identity());
1499      pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1500      return;
1501    }
1502    let reach = 3.0 * sigma;
1503    let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1504      ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1505    let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1506      ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1507    if columns.is_empty() || rows.is_empty() {
1508      return;
1509    }
1510    let patch = patched::Patch::key(shape, corners, sigma).and_then(|key| self.kept.patch(key));
1511    let blurred = patch
1512      .is_none()
1513      .then(|| BlurredBox::new(shape, corners, sigma));
1514    let stride = pixmap.width() as usize;
1515    // A cut-out shadow leaves a column the box covers in every row clear,
1516    // so only the runs of columns between them are worked out.
1517    let clear = |column: u32| {
1518      cut.as_ref().is_some_and(|cut| {
1519        let at = |row: u32| row as usize * stride + column as usize;
1520        rows.clone().all(|row| cut.data()[at(row)] == 255)
1521      })
1522    };
1523    let mut start = columns.start;
1524    while start < columns.end {
1525      if clear(start) {
1526        start += 1;
1527        continue;
1528      }
1529      let end = (start + 1..columns.end)
1530        .find(|&column| clear(column))
1531        .unwrap_or(columns.end);
1532      let run = start..end;
1533      start = end;
1534      let mut mask = Vec::with_capacity(run.len() * rows.len());
1535      for row in rows.clone() {
1536        match (patch, &blurred) {
1537          (Some(patch), _) => {
1538            // The grid's corner is a whole pixel.
1539            let columns = run.clone().map(|column| left as i64 + i64::from(column));
1540            patch.row(shape, top as i64 + i64::from(row), columns, &mut mask);
1541          }
1542          (None, Some(blurred)) => {
1543            let xs = run.clone().map(|column| left + column as f32 + 0.5);
1544            blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1545          }
1546          (None, None) => {}
1547        }
1548      }
1549      if let Some(cut) = &cut {
1550        let under = rows.clone().flat_map(|row| {
1551          run
1552            .clone()
1553            .map(move |column| row as usize * stride + column as usize)
1554        });
1555        for (alpha, at) in mask.iter_mut().zip(under) {
1556          *alpha = mul(*alpha, 255 - cut.data()[at]);
1557        }
1558      }
1559      let width = run.len() as u32;
1560      let height = rows.len() as u32;
1561      let (x, y) = (run.start as i32, rows.start as i32);
1562      blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1563    }
1564  }
1565
1566  /// An inset `shadow` inside `area` with `corners`, within a border
1567  /// `border` pixels wide: the inside of the border, but for a hole of its
1568  /// shape moved, shrunk by the spread and blurred, as CSS draws one. Like
1569  /// an outer shadow, it is worked out in buffer pixels, so tiles agree.
1570  fn inset_shadow(
1571    &self,
1572    pixmap: &mut PixmapMut<'_>,
1573    (area, corners): (tiny_skia::Rect, Corners),
1574    border: f32,
1575    shadow: &Shadow,
1576  ) {
1577    let Grid {
1578      scale, left, top, ..
1579    } = self.grid;
1580    let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1581    if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1582      return;
1583    }
1584    let Some(inside) = tiny_skia::Rect::from_ltrb(
1585      area.left() + border,
1586      area.top() + border,
1587      area.right() - border,
1588      area.bottom() - border,
1589    ) else {
1590      return;
1591    };
1592    let inside_corners = inset(corners, border);
1593    if !visible(pixmap, inside) {
1594      return;
1595    }
1596    let mut path = PathBuilder::new();
1597    rounded_rect(&mut path, inside, inside_corners);
1598    let Some(path) = path.finish() else {
1599      return;
1600    };
1601    // The hole in buffer pixels; a spread that swallows it leaves none.
1602    let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1603    let hole = tiny_skia::Rect::from_ltrb(
1604      inside.left() + left + x + spread,
1605      inside.top() + top + y + spread,
1606      inside.right() + left + x - spread,
1607      inside.bottom() + top + y - spread,
1608    );
1609    let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1610    let sigma = shadow.blur.max(0.0) * scale / 2.0;
1611    let color = shadow.color;
1612    if sigma < 0.25 {
1613      let mut outside = None;
1614      if let Some((hole, corners)) = hole {
1615        let mut cut = PathBuilder::new();
1616        let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1617          return;
1618        };
1619        rounded_rect(&mut cut, moved, corners);
1620        let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1621          return;
1622        };
1623        let (rule, at) = (FillRule::Winding, Transform::identity());
1624        let Some(cut) = cut.finish() else {
1625          return;
1626        };
1627        mask.fill_path(&cut, rule, true, at);
1628        mask.invert();
1629        outside = Some(mask);
1630      }
1631      let mut paint = Paint::default();
1632      paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1633      paint.anti_alias = true;
1634      let (rule, at) = (FillRule::Winding, Transform::identity());
1635      pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1636      return;
1637    }
1638    // The inside of the border covers these pixels, and the shadow shows
1639    // where the blurred hole doesn't.
1640    let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1641      return;
1642    };
1643    mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1644    let columns = inside.left().floor().max(0.0) as u32
1645      ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1646    let rows = inside.top().floor().max(0.0) as u32
1647      ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1648    if columns.is_empty() || rows.is_empty() {
1649      return;
1650    }
1651    let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1652    let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1653    for row in rows.clone() {
1654      let start = alpha.len();
1655      match &blurred {
1656        Some(blurred) => {
1657          let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1658          blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1659        }
1660        None => alpha.resize(start + columns.len(), 0),
1661      }
1662      let stride = pixmap.width() as usize;
1663      let row = &mask.data()[row as usize * stride..];
1664      let covered = &row[columns.start as usize..columns.end as usize];
1665      for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1666        *value = mul(255 - *value, covered);
1667      }
1668    }
1669    let (width, height) = (columns.len() as u32, rows.len() as u32);
1670    let (x, y) = (columns.start as i32, rows.start as i32);
1671    blend_mask(pixmap, x, y, width, height, &alpha, color);
1672  }
1673
1674  /// How much of each of this pixmap's pixels the box `rect` with
1675  /// `style`'s corners covers, as its background fills it.
1676  fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1677    let (area, corners) = self.box_shape(rect, style)?;
1678    let mut path = PathBuilder::new();
1679    rounded_rect(&mut path, area, corners);
1680    let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1681    let (rule, at) = (FillRule::Winding, Transform::identity());
1682    mask.fill_path(&path.finish()?, rule, true, at);
1683    Some(mask)
1684  }
1685
1686  /// Glyphs, drawn as masks in their span's color or else the text's,
1687  /// then any underline and strikethrough. The baseline sits on a whole
1688  /// pixel so horizontal strokes stay sharp; glyphs keep their sub-pixel
1689  /// horizontal position.
1690  fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1691    let Grid {
1692      scale, left, top, ..
1693    } = self.grid;
1694    let origin = text.origin();
1695    let x = origin.x * scale - left;
1696    for run in text.runs() {
1697      // Rounded in buffer coordinates, so every area drawn agrees.
1698      let baseline = ((origin.y + run.line_y) * scale).round() - top;
1699      if baseline + run.line_height * scale < 0.0
1700        || baseline - run.line_height * scale > pixmap.height() as f32
1701      {
1702        continue;
1703      }
1704      // A lit link takes the hover color, if the text has one.
1705      let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1706        true => text.link_hover_color().or(span.color),
1707        false => span.color,
1708      };
1709      for glyph in run.glyphs.iter() {
1710        let span = text.span(run.line_i, glyph);
1711        let color = text.selected_color(run.line_i, glyph);
1712        let color = color.or_else(|| span.and_then(|span| span_color(span, glyph)));
1713        let color = color.unwrap_or(text.color());
1714        if color.a == 0 {
1715          continue;
1716        }
1717        let physical = glyph.physical((x, baseline), scale);
1718        let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1719          continue;
1720        };
1721        let left = physical.x + image.placement.left;
1722        let top = physical.y - image.placement.top;
1723        let (width, height) = (image.placement.width, image.placement.height);
1724        match image.content {
1725          SwashContent::Mask => {
1726            blend_mask(pixmap, left, top, width, height, &image.data, color);
1727          }
1728          SwashContent::Color => {
1729            let premultiplied = is_color_outline(image);
1730            let rgba = (image.data.as_slice(), premultiplied);
1731            blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1732          }
1733          // Not requested: there is no subpixel antialiasing.
1734          SwashContent::SubpixelMask => {}
1735        }
1736      }
1737      let origin = text.origin().x;
1738      let own = (text.underline(), text.strikethrough());
1739      if own != (false, false) {
1740        self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1741      }
1742      // A span's own lines run across its glyphs on the line, each in its
1743      // color. cosmic-text's decoration spans join two decorated spans
1744      // across the text between them, so they aren't used.
1745      let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1746        text.span(run.line_i, a),
1747        text.span(run.line_i, b),
1748      ) {
1749        (Some(a), Some(b)) => std::ptr::eq(a, b),
1750        (a, b) => a.is_none() && b.is_none(),
1751      };
1752      for glyphs in run.glyphs.chunk_by(same_span) {
1753        let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1754          continue;
1755        };
1756        let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1757        let lines = (span.underline || lit, span.strikethrough);
1758        if lines != (false, false) {
1759          let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1760          self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1761        }
1762      }
1763    }
1764  }
1765
1766  /// The underline and strikethrough across `glyphs`, each run of
1767  /// glyphs from one font at the place and thickness that font gives, so
1768  /// a fallback glyph's line sits where its own font puts it.
1769  fn decorations(
1770    &mut self,
1771    pixmap: &mut PixmapMut<'_>,
1772    origin: f32,
1773    glyphs: &[LayoutGlyph],
1774    baseline: f32,
1775    lines: (bool, bool),
1776    color: Color,
1777  ) {
1778    let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1779      (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1780    };
1781    for glyphs in glyphs.chunk_by(same_font) {
1782      self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1783    }
1784  }
1785
1786  /// The underline and strikethrough across `glyphs`, all from one font,
1787  /// at the place and thickness it gives, as cosmic-text draws them.
1788  /// Edges snap to whole pixels in the buffer, so every tile agrees, and
1789  /// each line is at least a pixel thick. A line is kept within half an
1790  /// em of the baseline, which the text's painted area covers.
1791  fn font_decorations(
1792    &mut self,
1793    pixmap: &mut PixmapMut<'_>,
1794    origin: f32,
1795    glyphs: &[LayoutGlyph],
1796    baseline: f32,
1797    (underline, strikethrough): (bool, bool),
1798    color: Color,
1799  ) {
1800    let Some(first) = glyphs.first() else {
1801      return;
1802    };
1803    let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1804      return;
1805    };
1806    let metrics = font.metrics();
1807    let em = f32::from(metrics.units_per_em);
1808    if em == 0.0 {
1809      return;
1810    }
1811    let Grid { scale, left, .. } = self.grid;
1812    let (start, end) = glyphs
1813      .iter()
1814      .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1815        (start.min(glyph.x), end.max(glyph.x + glyph.w))
1816      });
1817    let x0 = ((origin + start) * scale).round() - left;
1818    let x1 = ((origin + end) * scale).round() - left;
1819    let size = first.font_size * scale;
1820    // cosmic-text's defaults for a font that gives none.
1821    let lines = [
1822      (underline, metrics.underline, -0.125),
1823      (strikethrough, metrics.strikeout, 0.3),
1824    ];
1825    for (on, decoration, offset) in lines {
1826      if !on {
1827        continue;
1828      }
1829      let (offset, thickness) =
1830        decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1831      // The offset is to the line's top, upward from the baseline.
1832      let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1833      let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1834      if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1835        let mut path = PathBuilder::new();
1836        path.push_rect(area);
1837        fill(pixmap, path, color, FillRule::Winding);
1838      }
1839    }
1840  }
1841
1842  /// A text field, cut to its content box.
1843  fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1844    let Some(area) = self.grid.rect(input.area) else {
1845      return;
1846    };
1847    self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1848      painter.input_contents(layer, input);
1849    });
1850  }
1851
1852  /// A field's selection in its color, the text, and a caret in the
1853  /// text's color.
1854  fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1855    let color = input.text.color();
1856    self.selection(pixmap, input.selection, input.selection_color);
1857    self.text(pixmap, &input.text);
1858    for line in input.underline {
1859      if let Some(area) = self.grid.rect(*line) {
1860        let mut path = PathBuilder::new();
1861        path.push_rect(area);
1862        fill(pixmap, path, color, FillRule::Winding);
1863      }
1864    }
1865    if let Some(caret) = input.caret {
1866      // At least one pixel wide whatever the scale.
1867      let left = self.grid.x(caret.x);
1868      let right = self.grid.x(caret.right()).max(left + 1.0);
1869      if let Some(area) = tiny_skia::Rect::from_ltrb(
1870        left,
1871        self.grid.y(caret.y),
1872        right,
1873        self.grid.y(caret.bottom()),
1874      ) {
1875        let mut path = PathBuilder::new();
1876        path.push_rect(area);
1877        fill(pixmap, path, color, FillRule::Winding);
1878      }
1879    }
1880  }
1881
1882  /// A selection, behind text, in `tint`.
1883  fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], tint: Color) {
1884    for span in spans {
1885      if let Some(area) = self.grid.rect(*span) {
1886        let mut path = PathBuilder::new();
1887        path.push_rect(area);
1888        fill(pixmap, path, tint, FillRule::Winding);
1889      }
1890    }
1891  }
1892
1893  /// An image, scaled to its box in pixels.
1894  fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1895    let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1896      return;
1897    };
1898    match self.icons.image(image, (width, height), self.grid.scale) {
1899      Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1900        transition::blit(pixmap, (x, y), pixels);
1901      }
1902      // A picture of another size, while this one is decoded.
1903      Some(Drawn::One(pixels)) => {
1904        let paint = PixmapPaint {
1905          quality: FilterQuality::Bilinear,
1906          ..PixmapPaint::default()
1907        };
1908        let stretch = Transform::from_scale(
1909          width as f32 / pixels.width() as f32,
1910          height as f32 / pixels.height() as f32,
1911        )
1912        .post_translate(x as f32, y as f32);
1913        pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1914      }
1915      Some(Drawn::Two { from, to, t }) => {
1916        transition::draw(pixmap, (x, y), from, to, t, image.transition);
1917      }
1918      None => {}
1919    }
1920  }
1921
1922  /// A screencopy view's frame, scaled to its box in pixels.
1923  fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1924    let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1925      return;
1926    };
1927    let frame = capture.frame;
1928    // The same test `shown` makes, so a view that draws nothing isn't
1929    // shown.
1930    let Some([left, top, part_width, part_height]) = frame.drawn_part(capture.crop) else {
1931      return;
1932    };
1933    let crop = capture.crop.and_then(|_| {
1934      // Within the frame, which is at most 8192 pixels a side.
1935      let sides = [left, top, part_width, part_height].map(|side| side as i32);
1936      tiny_skia::IntRect::from_xywh(sides[0], sides[1], part_width, part_height)
1937    });
1938    let size = (width, height);
1939    if let Some(pixels) = self
1940      .icons
1941      .capture(capture.id, frame, size, capture.fit, crop)
1942    {
1943      transition::blit(pixmap, (x, y), pixels);
1944    }
1945  }
1946
1947  /// Where a picture in `rect` goes in the pixmap, and its size in
1948  /// pixels; `None` if it covers no pixel of it. Placed and sized apart,
1949  /// as an icon is, so a picture past the window's edge is cut there
1950  /// instead of squeezed inside it.
1951  fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1952    let Grid {
1953      scale, left, top, ..
1954    } = self.grid;
1955    let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1956    let (x, y) = (
1957      (rect.x * scale).round() - left,
1958      (rect.y * scale).round() - top,
1959    );
1960    if !(width >= 1.0 && height >= 1.0) {
1961      return None;
1962    }
1963    let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1964    // `as` saturates, so a huge box stays in range.
1965    visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1966  }
1967
1968  /// An icon, rasterized at its size in pixels.
1969  fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1970    let Grid {
1971      scale, left, top, ..
1972    } = self.grid;
1973    let side = (icon.rect.width * scale).round();
1974    if side.is_nan() || side < 1.0 {
1975      return;
1976    }
1977    let x = (icon.rect.x * scale).round() - left;
1978    let y = (icon.rect.y * scale).round() - top;
1979    // Theme directories come in whole scales; 1.5 looks for @2 icons.
1980    let size = icon.rect.width.round() as u32;
1981    let theme_scale = scale.ceil().max(1.0) as u32;
1982    let sizes = (side as u32, size, theme_scale);
1983    // Asked twice when there is a fallback; the second is a cache hit.
1984    let source = match icon.fallback {
1985      Some(fallback) if self.icons.get(icon.source, sizes, icon.tint).is_none() => fallback,
1986      _ => icon.source,
1987    };
1988    if let Some(image) = self.icons.get(source, sizes, icon.tint) {
1989      // `as` saturates, so a huge offset stays in range.
1990      transition::blit(pixmap, (x as i32, y as i32), image);
1991    }
1992  }
1993}
1994
1995/// Whether the rectangle `shape` with `corners` covers every pixel of the
1996/// pixmap whole: its edges are at or past the pixmap's, and no corner's
1997/// curve reaches into it.
1998fn covers(pixmap: &PixmapMut<'_>, shape: tiny_skia::Rect, corners: Corners) -> bool {
1999  let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2000  let (left, top, right, bottom) = (shape.left(), shape.top(), shape.right(), shape.bottom());
2001  if !(left <= 0.0 && top <= 0.0 && right >= width && bottom >= height) {
2002    return false;
2003  }
2004  // Each corner's curve stays inside the square of its radius.
2005  corners.iter().enumerate().all(|(index, &radius)| {
2006    let x = if matches!(index, 0 | 3) {
2007      left
2008    } else {
2009      right - radius
2010    };
2011    let y = if index < 2 { top } else { bottom - radius };
2012    radius <= 0.0 || x + radius <= 0.0 || x >= width || y + radius <= 0.0 || y >= height
2013  })
2014}
2015
2016/// Whether any of `area` lies inside the pixmap.
2017fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
2018  area.right() > 0.0
2019    && area.bottom() > 0.0
2020    && area.left() < pixmap.width() as f32
2021    && area.top() < pixmap.height() as f32
2022}
2023
2024fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
2025  let Some(path) = path.finish() else {
2026    return;
2027  };
2028  let mut paint = Paint::default();
2029  paint.set_color_rgba8(color.r, color.g, color.b, color.a);
2030  paint.anti_alias = true;
2031  pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
2032}
2033
2034/// Each corner's radius in pixels, from the top left clockwise.
2035type Corners = [f32; 4];
2036
2037/// Dashes `path`, `length` pixels long, by `on` and `off` stretched so a
2038/// whole number of them fits, each centered on a multiple of the period
2039/// from its start, and adds them to `all`. `false` when the pattern can't
2040/// be drawn.
2041fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
2042  let Some((on, off)) = fit_dash(length, on, off) else {
2043    return false;
2044  };
2045  let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
2046    return false;
2047  };
2048  if let Some(dashes) = path.dash(&dash, 1.0) {
2049    all.push_path(&dashes);
2050  }
2051  true
2052}
2053
2054/// Where corner `index` of `rect`, from the top left clockwise, starts
2055/// and ends going clockwise, with its quarter circle's control points
2056/// between: `[start, one, two, end]`, all one point for a square corner.
2057fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
2058  // How far a cubic curve's control points sit along the tangents to
2059  // follow a quarter circle closely.
2060  const KAPPA: f32 = 0.552_284_8;
2061  let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
2062  let radius = corners[index];
2063  let k = radius * (1.0 - KAPPA);
2064  let points = match index {
2065    0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
2066    1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
2067    2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
2068    _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
2069  };
2070  points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
2071}
2072
2073/// `corners` for a shadow's shape grown by `spread` pixels, or shrunk by
2074/// a negative one. As in CSS, a corner smaller than the spread grows by
2075/// less, so a square box keeps square corners.
2076fn spread_corners(corners: Corners, spread: f32) -> Corners {
2077  corners.map(|radius| {
2078    if spread > 0.0 && radius < spread {
2079      radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
2080    } else {
2081      (radius + spread).max(0.0)
2082    }
2083  })
2084}
2085
2086/// `corners` fitted to `area` as CSS fits them ([`Radii::fit`]).
2087fn fit(
2088  [top_left, top_right, bottom_right, bottom_left]: Corners,
2089  area: tiny_skia::Rect,
2090) -> Corners {
2091  let radii = Radii {
2092    top_left,
2093    top_right,
2094    bottom_right,
2095    bottom_left,
2096  };
2097  radii.fit(area.width(), area.height()).corners()
2098}
2099
2100/// `corners` for a shape `by` pixels inside the edge.
2101fn inset(corners: Corners, by: f32) -> Corners {
2102  corners.map(|radius| (radius - by).max(0.0))
2103}
2104
2105/// Adds a rectangle with circular `corners` to `path`, clockwise from
2106/// the end of its top-left one.
2107fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
2108  if corners.iter().all(|&radius| radius <= 0.0) {
2109    path.push_rect(rect);
2110    return;
2111  }
2112  let [.., start] = corner(rect, corners, 0);
2113  path.move_to(start.x, start.y);
2114  for index in [1, 2, 3, 0] {
2115    let [start, one, two, end] = corner(rect, corners, index);
2116    path.line_to(start.x, start.y);
2117    if corners[index] > 0.0 {
2118      path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
2119    }
2120  }
2121  path.close();
2122}
2123
2124/// `a * b / 255`, rounded.
2125fn mul(a: u8, b: u8) -> u8 {
2126  ((u16::from(a) * u16::from(b) + 127) / 255) as u8
2127}
2128
2129/// Blends a premultiplied `source` over the pixel at `index` (in bytes).
2130fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
2131  let rest = 255 - source[3];
2132  for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
2133    *channel = value.saturating_add(mul(*channel, rest));
2134  }
2135}
2136
2137/// The pixels a layer of `node` at `layer_scale` holds so that what
2138/// `to_target` maps into `shown`, or all of it, comes out whole: its inner
2139/// bounds there, and a margin where tiny-skia cuts its curves. `None` if
2140/// none show.
2141fn layer_area(
2142  node: NodeView<'_>,
2143  to_target: Transform,
2144  shown: Option<tiny_skia::Rect>,
2145  layer_scale: f32,
2146) -> Option<Area> {
2147  let inner = node.inner_bounds();
2148  let drawn = tiny_skia::Rect::from_xywh(
2149    inner.x * layer_scale,
2150    inner.y * layer_scale,
2151    inner.width * layer_scale,
2152    inner.height * layer_scale,
2153  )?;
2154  let drawn = match shown {
2155    Some(shown) => shown.transform(to_target.invert()?)?.intersect(&drawn)?,
2156    None => drawn,
2157  };
2158  let area = drawn.outset(LAYER_MARGIN, LAYER_MARGIN)?.round_out()?;
2159  Some(Area {
2160    x: area.x(),
2161    y: area.y(),
2162    width: area.width(),
2163    height: area.height(),
2164  })
2165}
2166
2167/// Blends a transformed `layer` in at `opacity`, its corner going where
2168/// `at` says, filtered bilinearly.
2169pub(crate) fn blend_transformed(
2170  pixmap: &mut PixmapMut<'_>,
2171  layer: &Pixmap,
2172  at: Transform,
2173  opacity: f32,
2174) {
2175  if at.is_identity() || at.is_translate() {
2176    // tiny-skia samples a moved pixmap at the nearest pixel, whatever the
2177    // quality asked for, which puts it at this whole-pixel offset.
2178    let offset = ((at.tx - 0.5).ceil(), (at.ty - 0.5).ceil());
2179    // `as` saturates; a layer that far off misses the pixmap.
2180    composite(
2181      pixmap,
2182      (offset.0 as i32, offset.1 as i32),
2183      layer,
2184      opacity,
2185      None,
2186    );
2187    return;
2188  }
2189  if at.kx == 0.0 && at.ky == 0.0 && at.sx > 0.0 && at.sy > 0.0 {
2190    blend_scaled(pixmap, layer, at, opacity);
2191    return;
2192  }
2193  let paint = PixmapPaint {
2194    opacity,
2195    quality: FilterQuality::Bilinear,
2196    ..PixmapPaint::default()
2197  };
2198  pixmap.draw_pixmap(0, 0, layer.as_ref(), &paint, at, None);
2199}
2200
2201/// [`blend_transformed`] for a transform that only scales and moves:
2202/// tiny-skia's pipeline gives the same within a level, twice as slow,
2203/// which a layer the size of a window notices. Each pixel whose middle
2204/// lands on the layer mixes the four layer pixels around where it lands,
2205/// the edge ones past it. Each layer row is mixed across once, for the
2206/// two pixmap rows that need it, then mixed down and blended in.
2207fn blend_scaled(pixmap: &mut PixmapMut<'_>, layer: &Pixmap, at: Transform, opacity: f32) {
2208  // Along one axis: the first pixel, then for each the two layer pixels it
2209  // mixes and how far it is from the first to the second.
2210  let taps = |scale: f32, offset: f32, length: u32, limit: u32| {
2211    let start = (offset - 0.5).ceil().max(0.0);
2212    let end = (offset + length as f32 * scale - 0.5)
2213      .ceil()
2214      .min(limit as f32);
2215    let last = length as usize - 1;
2216    // `as` saturates, so a far-off layer gives an empty range.
2217    let taps: Vec<(usize, usize, f32)> = (start as u32..end.max(start) as u32)
2218      .map(|pixel| {
2219        let x = (pixel as f32 + 0.5 - offset) / scale - 0.5;
2220        let floor = x.floor();
2221        let index = |at: f32| (at.max(0.0) as usize).min(last);
2222        (index(floor), index(floor + 1.0), x - floor)
2223      })
2224      .collect();
2225    (start as usize, taps)
2226  };
2227  let (x0, columns) = taps(at.sx, at.tx, layer.width(), pixmap.width());
2228  let (y0, rows) = taps(at.sy, at.ty, layer.height(), pixmap.height());
2229  if columns.is_empty() || rows.is_empty() {
2230    return;
2231  }
2232  let opacity = opacity.clamp(0.0, 1.0);
2233  let stride = pixmap.width() as usize;
2234  let width = layer.width() as usize;
2235  let source = layer.data().as_chunks::<4>().0;
2236  let data = pixmap.data_mut().as_chunks_mut::<4>().0;
2237  // Layer row `index` mixed across at the columns, in levels.
2238  let across = |index: usize, mixed: &mut Vec<[f32; 4]>| {
2239    let row = &source[index * width..(index + 1) * width];
2240    mixed.clear();
2241    mixed.extend(columns.iter().map(|&(left, right, t)| {
2242      let (a, b) = (row[left], row[right]);
2243      std::array::from_fn(|channel| {
2244        let (a, b) = (f32::from(a[channel]), f32::from(b[channel]));
2245        a + (b - a) * t
2246      })
2247    }));
2248  };
2249  let (mut upper, mut lower) = (Vec::new(), Vec::new());
2250  let (mut upper_row, mut lower_row) = (usize::MAX, usize::MAX);
2251  for (y, &(top, bottom, down)) in rows.iter().enumerate() {
2252    if upper_row != top {
2253      if lower_row == top {
2254        std::mem::swap(&mut upper, &mut lower);
2255        std::mem::swap(&mut upper_row, &mut lower_row);
2256      } else {
2257        across(top, &mut upper);
2258        upper_row = top;
2259      }
2260    }
2261    if lower_row != bottom {
2262      across(bottom, &mut lower);
2263      lower_row = bottom;
2264    }
2265    let (near, far) = ((1.0 - down) * opacity, down * opacity);
2266    let start = (y0 + y) * stride + x0;
2267    let target = &mut data[start..start + columns.len()];
2268    for ((to, a), b) in target.iter_mut().zip(&upper).zip(&lower) {
2269      let mixed: [f32; 4] = std::array::from_fn(|channel| a[channel] * near + b[channel] * far);
2270      // Over what is there, which keeps 1 less the alpha of itself.
2271      let rest = 1.0 - mixed[3] * (1.0 / 255.0);
2272      *to = std::array::from_fn(|channel| {
2273        // `as` saturates below 0.
2274        (mixed[channel] + f32::from(to[channel]) * rest + 0.5).min(255.0) as u8
2275      });
2276    }
2277  }
2278}
2279
2280/// Blends the premultiplied `layer` over the pixmap with its corner at
2281/// `left`, `top`, at `opacity` and through `mask`, which is the pixmap's
2282/// size. tiny-skia's `draw_pixmap` gives the same within a level at a
2283/// whole-pixel offset, through a float pipeline several times slower,
2284/// which a layer the size of the screen notices.
2285pub(crate) fn composite(
2286  pixmap: &mut PixmapMut<'_>,
2287  (left, top): (i32, i32),
2288  layer: &Pixmap,
2289  opacity: f32,
2290  mask: Option<&Mask>,
2291) {
2292  if opacity >= 1.0 && mask.is_none() {
2293    transition::blit(pixmap, (left, top), layer);
2294    return;
2295  }
2296  let width = layer.width() as usize;
2297  let Some((x0, x1, y0, y1)) = overlap(pixmap, left, top, layer.width(), layer.height()) else {
2298    return;
2299  };
2300  // In 65536ths, so an opacity near 0 or 1 isn't rounded a level off.
2301  let scale = (opacity.clamp(0.0, 1.0) * 65536.0).round() as u32;
2302  let stride = pixmap.width() as usize;
2303  let mask = mask.map(Mask::data);
2304  let data = pixmap.data_mut();
2305  let source = layer.data();
2306  // Without branches, so the loops vectorize; a clear pixel or one the
2307  // mask leaves out blends as nothing.
2308  let fade = |pixel: [u8; 4], coverage: u8| {
2309    pixel.map(|channel| mul(((u32::from(channel) * scale + 32768) >> 16) as u8, coverage))
2310  };
2311  let blend = |to: &mut [u8; 4], from: [u8; 4]| {
2312    let rest = 255 - from[3];
2313    *to = std::array::from_fn(|channel| from[channel].saturating_add(mul(to[channel], rest)));
2314  };
2315  for y in y0..y1 {
2316    // `overlap` keeps these inside the pixmap.
2317    let start =
2318      (i64::from(top) + y as i64) as usize * stride + (i64::from(left) + x0 as i64) as usize;
2319    let end = start + (x1 - x0);
2320    let row = source[(y * width + x0) * 4..(y * width + x1) * 4]
2321      .as_chunks::<4>()
2322      .0;
2323    let target = data[start * 4..end * 4].as_chunks_mut::<4>().0;
2324    match mask {
2325      Some(mask) => {
2326        for ((to, from), &coverage) in target.iter_mut().zip(row).zip(&mask[start..end]) {
2327          blend(to, fade(*from, coverage));
2328        }
2329      }
2330      None => {
2331        for (to, from) in target.iter_mut().zip(row) {
2332          blend(to, fade(*from, 255));
2333        }
2334      }
2335    }
2336  }
2337}
2338
2339/// The part of a `width` by `height` image placed at `left`, `top` that
2340/// lies inside the pixmap: the first and last column and row, as image
2341/// coordinates.
2342fn overlap(
2343  pixmap: &PixmapMut<'_>,
2344  left: i32,
2345  top: i32,
2346  width: u32,
2347  height: u32,
2348) -> Option<(usize, usize, usize, usize)> {
2349  let column_start = (-i64::from(left)).max(0);
2350  let row_start = (-i64::from(top)).max(0);
2351  let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
2352  let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
2353  (column_start < column_end && row_start < row_end).then_some((
2354    column_start as usize,
2355    column_end as usize,
2356    row_start as usize,
2357    row_end as usize,
2358  ))
2359}
2360
2361/// Blends a glyph's coverage mask in `color`.
2362fn blend_mask(
2363  pixmap: &mut PixmapMut<'_>,
2364  left: i32,
2365  top: i32,
2366  width: u32,
2367  height: u32,
2368  mask: &[u8],
2369  color: Color,
2370) {
2371  if mask.len() < width as usize * height as usize {
2372    return;
2373  }
2374  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
2375  else {
2376    return;
2377  };
2378  let stride = pixmap.width() as usize;
2379  let data = pixmap.data_mut();
2380  for row in rows..rows_end {
2381    for column in columns..columns_end {
2382      let coverage = mask[row * width as usize + column];
2383      if coverage == 0 {
2384        continue;
2385      }
2386      let alpha = mul(color.a, coverage);
2387      let source = [
2388        mul(color.r, alpha),
2389        mul(color.g, alpha),
2390        mul(color.b, alpha),
2391        alpha,
2392      ];
2393      let x = (i64::from(left) + column as i64) as usize;
2394      let y = (i64::from(top) + row as i64) as usize;
2395      over(data, (y * stride + x) * 4, source);
2396    }
2397  }
2398}
2399
2400/// How many rows a point near a corner sums.
2401const SAMPLES: usize = 8;
2402
2403/// A rectangle with rounded corners blurred by a Gaussian: how much of it
2404/// covers each point. Away from the corners it is a plain rectangle,
2405/// whose blur is the product of each axis's, from the error function.
2406/// Near a corner, each row's span is blurred across and the rows are
2407/// summed over eight samples of the Gaussian down. Each corner has its
2408/// own radius; the largest says where the corners' rows begin.
2409struct BlurredBox {
2410  middle: (f32, f32),
2411  half: (f32, f32),
2412  corners: Corners,
2413  largest: f32,
2414  sigma: f32,
2415  /// What the samples sum to where the shape covers them all, a little
2416  /// under 1, so a point the shape covers whole is covered whole.
2417  whole: f32,
2418}
2419
2420impl BlurredBox {
2421  fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
2422    let step = 6.0 * sigma / SAMPLES as f32;
2423    let whole = (0..SAMPLES)
2424      .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
2425      .sum();
2426    BlurredBox {
2427      whole,
2428      middle: (
2429        (shape.left() + shape.right()) / 2.0,
2430        (shape.top() + shape.bottom()) / 2.0,
2431      ),
2432      half: (shape.width() / 2.0, shape.height() / 2.0),
2433      corners,
2434      largest: corners.into_iter().fold(0.0, f32::max),
2435      sigma,
2436    }
2437  }
2438
2439  /// Pushes the coverage at each of `xs` on the row at `y`, out of 255,
2440  /// onto `mask`.
2441  fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
2442    let y = y - self.middle.1;
2443    let (half_width, half_height) = self.half;
2444    let reach = 3.0 * self.sigma;
2445    let down = self.along(y, half_height);
2446    let clear_of_corners = y.abs() <= half_height - self.largest - reach;
2447    let rows = if clear_of_corners {
2448      [(0.0, 0.0, 0.0); SAMPLES]
2449    } else {
2450      self.rows_near(y)
2451    };
2452    for x in xs {
2453      let x = x - self.middle.0;
2454      let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
2455        self.along(x, half_width) * down
2456      } else {
2457        let sum: f32 = rows
2458          .iter()
2459          .map(|&(left, right, weight)| self.between(x, left, right) * weight)
2460          .sum();
2461        (sum / self.whole).clamp(0.0, 1.0)
2462      };
2463      mask.push((coverage * 255.0).round() as u8);
2464    }
2465  }
2466
2467  /// The blur of the span from `-half` to `half` at `p`.
2468  fn along(&self, p: f32, half: f32) -> f32 {
2469    self.between(p, half, half)
2470  }
2471
2472  /// The blur of the span from `-left` to `right` at `p`. One the blur
2473  /// stays inside of is covered whole.
2474  fn between(&self, p: f32, left: f32, right: f32) -> f32 {
2475    let reach = 3.0 * self.sigma;
2476    if -(left - reach) <= p && p <= right - reach {
2477      return 1.0;
2478    }
2479    let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
2480    0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
2481  }
2482
2483  /// The rows of the shape a point at height `y` near a corner sums: for
2484  /// each sample within the shape and the Gaussian's reach, how far the
2485  /// row reaches left and right of the middle, and its weight.
2486  fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
2487    let (half_width, half_height) = self.half;
2488    let reach = 3.0 * self.sigma;
2489    let start = (y - half_height).clamp(-reach, reach);
2490    let end = (y + half_height).clamp(-reach, reach);
2491    let step = (end - start) / SAMPLES as f32;
2492    std::array::from_fn(|sample| {
2493      let offset = start + step * (sample as f32 + 0.5);
2494      // How far into a corner's rows this one is, and how much it
2495      // narrows there.
2496      let row = y - offset;
2497      let [top_left, top_right, bottom_right, bottom_left] = self.corners;
2498      let (left, right) = if row < 0.0 {
2499        (top_left, top_right)
2500      } else {
2501        (bottom_left, bottom_right)
2502      };
2503      let span = |radius: f32| {
2504        let into_corner = (row.abs() - (half_height - radius)).max(0.0);
2505        half_width - radius
2506          + (radius * radius - into_corner * into_corner)
2507            .max(0.0)
2508            .sqrt()
2509      };
2510      (span(left), span(right), gaussian(offset, self.sigma) * step)
2511    })
2512  }
2513}
2514
2515/// The normal distribution's density at `x`, for a deviation of `sigma`.
2516fn gaussian(x: f32, sigma: f32) -> f32 {
2517  let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
2518  (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
2519}
2520
2521/// The error function, within 5e-4, an eighth of a color level, by
2522/// Abramowitz and Stegun's 7.1.27, which needs no exponential.
2523fn erf(x: f32) -> f32 {
2524  let a = x.abs();
2525  let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
2526  let d = d * d;
2527  (1.0 - 1.0 / (d * d)).copysign(x)
2528}
2529
2530/// Whether a color glyph came from vector color layers (COLR), which swash
2531/// renders premultiplied, rather than an embedded bitmap, which it hands
2532/// over as stored: straight alpha.
2533///
2534/// cosmic-text doesn't re-export swash's `Source`, and swash isn't a
2535/// dependency of this crate, so the variant is read from its name.
2536fn is_color_outline(image: &SwashImage) -> bool {
2537  format!("{:?}", image.source).starts_with("ColorOutline")
2538}
2539
2540/// Blends a color glyph's RGBA pixels at `opacity` out of 255. `rgba` says
2541/// whether they are premultiplied already.
2542fn blend_rgba(
2543  pixmap: &mut PixmapMut<'_>,
2544  left: i32,
2545  top: i32,
2546  width: u32,
2547  height: u32,
2548  (rgba, premultiplied): (&[u8], bool),
2549  opacity: u8,
2550) {
2551  if rgba.len() < width as usize * height as usize * 4 {
2552    return;
2553  }
2554  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
2555  else {
2556    return;
2557  };
2558  let stride = pixmap.width() as usize;
2559  let data = pixmap.data_mut();
2560  for row in rows..rows_end {
2561    for column in columns..columns_end {
2562      let index = (row * width as usize + column) * 4;
2563      let alpha = mul(rgba[index + 3], opacity);
2564      if alpha == 0 {
2565        continue;
2566      }
2567      // Premultiplied colors only need the opacity; straight ones need
2568      // their own alpha too.
2569      let factor = if premultiplied { opacity } else { alpha };
2570      let source = [
2571        mul(rgba[index], factor),
2572        mul(rgba[index + 1], factor),
2573        mul(rgba[index + 2], factor),
2574        alpha,
2575      ];
2576      let x = (i64::from(left) + column as i64) as usize;
2577      let y = (i64::from(top) + row as i64) as usize;
2578      over(data, (y * stride + x) * 4, source);
2579    }
2580  }
2581}
2582
2583/// Adds `contour` to `kept` when the box around its points reaches into
2584/// `near`, given as left, top, right and bottom.
2585fn keep_near(
2586  kept: &mut PathBuilder,
2587  contour: &[PathSegment],
2588  [left, top, right, bottom]: [f32; 4],
2589) {
2590  let (mut low, mut high) = (
2591    (f32::INFINITY, f32::INFINITY),
2592    (f32::NEG_INFINITY, f32::NEG_INFINITY),
2593  );
2594  let points = contour.iter().flat_map(|segment| match *segment {
2595    PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
2596    PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
2597    PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
2598    PathSegment::Close => [None; 3],
2599  });
2600  for point in points.flatten() {
2601    low = (low.0.min(point.x), low.1.min(point.y));
2602    high = (high.0.max(point.x), high.1.max(point.y));
2603  }
2604  if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
2605    return;
2606  }
2607  for segment in contour {
2608    match *segment {
2609      PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
2610      PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
2611      PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
2612      PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
2613      PathSegment::Close => kept.close(),
2614    }
2615  }
2616}
2617
2618/// A dash of `on` pixels and a gap of `off`, stretched or squeezed so a
2619/// whole number of them goes around `perimeter`, at least one. `None` for
2620/// a pattern that can't be drawn: a number that isn't finite or is
2621/// negative, no gap, or a period shorter than a pixel.
2622pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
2623  let period = on + off;
2624  if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
2625    return None;
2626  }
2627  let count = (perimeter / period).round().max(1.0);
2628  let stretch = perimeter / (count * period);
2629  Some((on * stretch, off * stretch))
2630}
2631
2632/// Fills the whole pixmap with `color`, blended over what is there, as
2633/// tiny-skia's antialiased path fill gives a shape covering it, within a
2634/// level, without its raster pipeline. `true`, so `draw_box` chains it as
2635/// it does `fill_opaque`.
2636pub(crate) fn fill_all(pixmap: &mut PixmapMut<'_>, color: Color) -> bool {
2637  let alpha = color.a;
2638  let source = [
2639    mul(color.r, alpha),
2640    mul(color.g, alpha),
2641    mul(color.b, alpha),
2642    alpha,
2643  ];
2644  let pixels = pixmap.data_mut().as_chunks_mut::<4>().0;
2645  match alpha {
2646    0 => {}
2647    255 => pixels.fill(source),
2648    _ => {
2649      let rest = 255 - alpha;
2650      for pixel in pixels {
2651        *pixel =
2652          std::array::from_fn(|channel| source[channel].saturating_add(mul(pixel[channel], rest)));
2653      }
2654    }
2655  }
2656  true
2657}
2658
2659/// Fills `area` with the opaque `color` straight into the pixels, as
2660/// tiny-skia's path fill gives it, without its raster pipeline: a
2661/// window's background under a picture was half of a 1080p repaint.
2662/// `false`, drawing nothing, unless `color` is opaque and every edge is on
2663/// a whole pixel.
2664pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
2665  let edges = [area.left(), area.top(), area.right(), area.bottom()];
2666  if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
2667    return false;
2668  }
2669  let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
2670  let [left, top, right, bottom] = [
2671    area.left().clamp(0.0, width),
2672    area.top().clamp(0.0, height),
2673    area.right().clamp(0.0, width),
2674    area.bottom().clamp(0.0, height),
2675  ]
2676  .map(|edge| edge as usize);
2677  let stride = pixmap.width() as usize * 4;
2678  let pixel = [color.r, color.g, color.b, 255];
2679  for row in pixmap
2680    .data_mut()
2681    .chunks_exact_mut(stride)
2682    .take(bottom)
2683    .skip(top)
2684  {
2685    row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
2686  }
2687  true
2688}