Skip to main content

crabshell_render/
draw.rs

1//! Drawing a window's view into a buffer.
2//!
3//! The areas to repaint are drawn from scratch, one tile of a fixed grid at
4//! a time, into an RGBA pixmap of the tile's size, then copied into the
5//! buffer. The pixmap clips the drawing to the tile, and the copy converts
6//! the pixels to the buffer's byte order, so tiny-skia, glyph masks, resvg
7//! and PNG decoding all work in the RGBA order they share.
8
9use std::collections::HashMap;
10
11use cosmic_text::{FontSystem, LayoutGlyph, SwashCache, SwashContent, SwashImage};
12use crabshell_ui::{
13  Affine, CaptureView, Color, Content, IconView, ImageView, InputView, NodeView, Radii, Rect,
14  Shadow, Size, Span, Style, TextSystem, TextView, WindowView,
15};
16use tiny_skia::{
17  FillRule, FilterQuality, LineCap, LineJoin, Mask, Paint, PathBuilder, PathSegment, Pixmap,
18  PixmapMut, PixmapPaint, Stroke, StrokeDash, Transform,
19};
20
21use crate::damage::{BufferAge, DamageHistory, PixelRect};
22use crate::icons::{Drawn, Icons};
23
24mod canvas;
25mod effects;
26mod gradient;
27mod transition;
28
29/// The side of a tile, in buffer pixels. tiny-skia cuts a curve where it
30/// leaves the pixmap, which changes the antialiasing beside the cut, so
31/// every pixel is drawn in the same tile whatever the damage, and a repaint
32/// matches drawing everything.
33const TILE: u32 = 64;
34
35/// How many glyph images cosmic-text's cache may hold after a draw before
36/// it is cleared. A bar needs a few hundred; the cache never shrinks itself.
37const GLYPH_CACHE_LIMIT: usize = 2048;
38
39/// The most pixels a transformed layer may hold, 16 MiB. Only a widget
40/// shrunk to a sliver of its size, so that a tile shows much of it, comes
41/// near; past this it isn't drawn.
42const LAYER_LIMIT: u64 = 1 << 22;
43
44/// Buffer pixels a transformed layer reaches past what it samples, so the
45/// edges where tiny-skia cuts its curves stay out of the picture.
46const LAYER_MARGIN: f32 = 2.0;
47
48/// How a buffer stores each pixel, as `wl_shm` names the formats. Both are
49/// 32 bits per pixel with premultiplied alpha.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum PixelFormat {
52  /// Bytes B, G, R, A in memory. Every compositor supports it.
53  Argb8888,
54  /// Bytes R, G, B, A in memory, as tiny-skia draws. Copied as is.
55  Abgr8888,
56}
57
58/// A buffer to draw a window into.
59pub struct Canvas<'a> {
60  /// The buffer's memory: `width * height` pixels of 4 bytes, row by row.
61  pub pixels: &'a mut [u8],
62  /// The width in pixels: the window's logical width times `scale`,
63  /// rounded halfway away from zero, as `wp_fractional_scale_v1` says.
64  /// The window's edge is drawn at the buffer's edge either way.
65  pub width: u32,
66  /// The height in pixels, likewise.
67  pub height: u32,
68  /// Physical pixels per logical pixel.
69  pub scale: f32,
70  /// How the buffer stores pixels.
71  pub format: PixelFormat,
72  /// The frame the buffer last held, updated by the draw.
73  pub age: &'a mut BufferAge,
74}
75
76/// Draws windows. One serves every window; it holds the glyph and icon
77/// caches.
78pub struct Renderer {
79  glyphs: SwashCache,
80  icons: Icons,
81  /// Where each tile is drawn before it is copied into the buffer, kept
82  /// between frames.
83  scratch: Vec<u8>,
84  work: Work,
85}
86
87/// What drawing has cost so far, for tests to check that a draw stays
88/// small.
89#[derive(Default)]
90#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
91struct Work {
92  /// Pixels of opacity, clip and transform layers allocated.
93  layer_pixels: u64,
94  /// Nodes drawn.
95  nodes: u64,
96  /// Pixels of alpha content shadows were blurred over.
97  blurred: u64,
98  /// Pixels gradients were worked out for. A `Cell`, since a ramp is
99  /// worked out while painting reads the rest.
100  gradient_pixels: std::cell::Cell<u64>,
101}
102
103impl Renderer {
104  /// A renderer with empty caches, looking icons up in the `hicolor`
105  /// theme.
106  pub fn new() -> Renderer {
107    Renderer {
108      glyphs: SwashCache::new(),
109      icons: Icons::new(),
110      scratch: Vec::new(),
111      work: Work::default(),
112    }
113  }
114
115  /// How many times an image's file was looked up, for tests.
116  #[cfg(test)]
117  pub(crate) fn image_lookups(&self) -> usize {
118    self.icons.lookups()
119  }
120
121  /// The number of glyph images cached, for tests.
122  #[cfg(test)]
123  pub(crate) fn cached_glyphs(&self) -> usize {
124    self.glyphs.image_cache.len()
125  }
126
127  /// The pixels of opacity layers allocated and the nodes drawn so far,
128  /// for tests.
129  #[cfg(test)]
130  pub(crate) fn work(&self) -> (u64, u64, u64) {
131    (self.work.layer_pixels, self.work.nodes, self.work.blurred)
132  }
133
134  /// The pixels gradients were worked out for so far, for tests.
135  #[cfg(test)]
136  pub(crate) fn gradient_pixels(&self) -> u64 {
137    self.work.gradient_pixels.get()
138  }
139
140  /// A renderer that looks icon names up in `bases` instead of the
141  /// environment's directories, for tests.
142  #[cfg(test)]
143  pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
144    Renderer {
145      icons: Icons::with_themes(crate::theme::Themes::new(bases)),
146      ..Renderer::new()
147    }
148  }
149
150  /// Sets the icon theme names are looked up in.
151  pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
152    self.icons.set_theme(theme.into());
153  }
154
155  /// The number of rasterized icons cached, for tests.
156  #[cfg(test)]
157  pub(crate) fn cached_icons(&self) -> usize {
158    self.icons.cached()
159  }
160
161  /// The number of times an icon was rasterized, for tests.
162  #[cfg(test)]
163  pub(crate) fn rasterized_icons(&self) -> usize {
164    self.icons.rasterized()
165  }
166
167  /// Drops the scaled frames kept for screencopy views `gone`, at once:
168  /// each is as large as its view, and an idle shell may draw nothing
169  /// for a long while.
170  pub fn forget_captures(&mut self, gone: &[u64]) {
171    self.icons.forget_captures(gone);
172  }
173
174  /// From now on, decodes image files on a worker thread, which starts
175  /// with the first and ends once none is left: a GIF's frames, a blurred
176  /// picture, and any file past 64 KiB or drawn past 256 by 256 pixels.
177  /// Until its picture comes in, an image draws the picture its
178  /// transition leaves, or the one it drew before at its size, or
179  /// nothing. Without this, as for a snapshot, each is decoded as it is
180  /// first drawn.
181  ///
182  /// The platform then follows [`decoding`](Self::decoding), and while it
183  /// holds asks to be woken with
184  /// [`wake_when_decoded`](Self::wake_when_decoded) and calls
185  /// [`take_decoded`](Self::take_decoded) when it is.
186  pub fn decode_off_thread(&mut self) {
187    self.icons.decode_off_thread();
188  }
189
190  /// Whether pictures are being decoded for images drawn, or came in and
191  /// weren't taken with [`take_decoded`](Self::take_decoded) yet.
192  pub fn decoding(&self) -> bool {
193    self.icons.decoding()
194  }
195
196  /// Calls `wake` once, from the worker thread, when a picture is
197  /// decoded, or at once if one waits to be taken. It replaces a `wake`
198  /// given before.
199  pub fn wake_when_decoded(&mut self, wake: impl FnOnce() + Send + 'static) {
200    self.icons.wake_when_decoded(Box::new(wake));
201  }
202
203  /// Whether the last draw drew an image whose picture is still being
204  /// decoded, so the platform can hold a window's first frame for it.
205  pub fn waits_for_pictures(&self) -> bool {
206    self.icons.waited()
207  }
208
209  /// Caches the pictures decoded since the last call, logging each
210  /// failure once, and returns the ids of the images that wait for them,
211  /// for the platform to repaint with
212  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image) in
213  /// every window.
214  pub fn take_decoded(&mut self) -> Vec<u64> {
215    self.icons.take_decoded()
216  }
217
218  /// When the next frame of an animated GIF is due, counting from `now`
219  /// for one drawn since the last call. `None` while no GIF drawn plays.
220  /// The platform wakes then and calls
221  /// [`advance_images`](Self::advance_images).
222  pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
223    self.icons.next_frame(now)
224  }
225
226  /// Moves each GIF whose next frame is due by `now` on to it, and returns
227  /// their image ids for the platform to repaint with
228  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image). A
229  /// GIF waits for its next frame only once that one is drawn, so one no
230  /// longer shown wakes nothing more.
231  pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
232    self.icons.advance(now)
233  }
234
235  /// How many jobs the decoding thread did, for tests.
236  #[cfg(test)]
237  pub(crate) fn decoded_off_thread(&self) -> usize {
238    self.icons.worker_work().0
239  }
240
241  /// Whether the decoding thread runs, for tests.
242  #[cfg(test)]
243  pub(crate) fn decoder_running(&self) -> bool {
244    self.icons.worker_work().1
245  }
246
247  /// The number of screencopy frames kept scaled, for tests.
248  #[cfg(test)]
249  pub(crate) fn cached_captures(&self) -> usize {
250    self.icons.captures()
251  }
252
253  /// Draws the laid-out window `view` into `canvas` and returns the areas
254  /// to report with `wl_surface.damage_buffer`.
255  ///
256  /// `damage` is what the window reported since the last draw, from
257  /// [`Window::take_damage`](crabshell_ui::Window::take_damage). The draw
258  /// repaints that, plus what changed in frames this buffer missed
259  /// according to `history`, or the whole buffer when that is more than
260  /// half of it or the buffer is new. Text and glyphs come from `text`.
261  ///
262  /// Commit the buffer after every successful draw, in order: the history
263  /// counts each one as a frame the compositor showed.
264  ///
265  /// # Errors
266  ///
267  /// If `canvas` holds the wrong number of bytes for its size, or its
268  /// scale isn't a positive number. Nothing is drawn and the history
269  /// doesn't advance.
270  pub fn draw(
271    &mut self,
272    view: &WindowView<'_>,
273    damage: &[Rect],
274    text: &mut TextSystem,
275    history: &mut DamageHistory,
276    canvas: Canvas<'_>,
277  ) -> Result<Vec<PixelRect>, CanvasError> {
278    let Canvas {
279      pixels,
280      width,
281      height,
282      scale,
283      format,
284      age,
285    } = canvas;
286    if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
287      || !(scale.is_finite() && scale > 0.0)
288    {
289      return Err(CanvasError {
290        width,
291        height,
292        scale,
293        bytes: pixels.len(),
294      });
295    }
296    self.icons.start_frame(history.id());
297    let plan = history.plan(damage, scale, width, height, age);
298    let mut tiles: Vec<(u32, u32)> = Vec::new();
299    for area in plan.repaint.iter().filter(|area| area.area() > 0) {
300      for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
301        tiles
302          .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
303      }
304    }
305    tiles.sort_unstable();
306    tiles.dedup();
307    let mut casts = HashMap::new();
308    let mut fonts = text.font_system();
309    for &(row, column) in &tiles {
310      self.icons.start_tile((row, column));
311      let (x, y) = (column * TILE, row * TILE);
312      let size = (width.saturating_sub(x), height.saturating_sub(y));
313      let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
314      self.scratch.clear();
315      self.scratch.resize(area.area() as usize * 4, 0);
316      let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
317      else {
318        continue;
319      };
320      let mut painter = Painter {
321        grid: Grid {
322          scale,
323          zoom: 1.0,
324          linear: Affine {
325            sx: 1.0,
326            ky: 0.0,
327            kx: 0.0,
328            sy: 1.0,
329            tx: 0.0,
330            ty: 0.0,
331          },
332          window: view.size(),
333          width,
334          height,
335          left: area.x as f32,
336          top: area.y as f32,
337        },
338        glyphs: &mut self.glyphs,
339        icons: &mut self.icons,
340        fonts: &mut fonts,
341        work: &mut self.work,
342        casts: &mut casts,
343      };
344      painter.node(&mut pixmap, view.root());
345      copy(&self.scratch, area, pixels, width, format);
346    }
347    self.icons.repainted(&tiles);
348    self.icons.end_frame();
349    if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
350      self.glyphs.image_cache.clear();
351      self.glyphs.outline_command_cache.clear();
352    }
353    Ok(plan.report)
354  }
355}
356
357/// A canvas whose bytes don't fit its size, or whose scale isn't a positive
358/// number.
359#[derive(Clone, Copy, Debug, PartialEq)]
360pub struct CanvasError {
361  /// The canvas's width in pixels.
362  pub width: u32,
363  /// The canvas's height in pixels.
364  pub height: u32,
365  /// The canvas's scale.
366  pub scale: f32,
367  /// How many bytes the canvas held.
368  pub bytes: usize,
369}
370
371impl std::fmt::Display for CanvasError {
372  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
373    write!(
374      f,
375      "a {}x{} canvas at scale {} needs {} bytes, but has {}",
376      self.width,
377      self.height,
378      self.scale,
379      u64::from(self.width) * u64::from(self.height) * 4,
380      self.bytes
381    )
382  }
383}
384
385impl std::error::Error for CanvasError {}
386
387impl Default for Renderer {
388  fn default() -> Self {
389    Self::new()
390  }
391}
392
393/// Copies an area drawn in RGBA into the buffer, converting byte order.
394fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
395  let stride = width as usize * 4;
396  let row_bytes = area.width as usize * 4;
397  for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
398    let start = (area.y as usize + row) * stride + area.x as usize * 4;
399    let target = &mut pixels[start..start + row_bytes];
400    match format {
401      PixelFormat::Abgr8888 => target.copy_from_slice(source),
402      PixelFormat::Argb8888 => {
403        let (to, _) = target.as_chunks_mut::<4>();
404        let (from, _) = source.as_chunks::<4>();
405        // Red and blue swapped in a whole word, which vectorizes, unlike
406        // moving the bytes one by one.
407        for (to, from) in to.iter_mut().zip(from) {
408          let pixel = u32::from_le_bytes(*from);
409          *to = (pixel & 0xff00_ff00 | (pixel >> 16) & 0xff | (pixel & 0xff) << 16).to_le_bytes();
410        }
411      }
412    }
413  }
414}
415
416/// Turns logical coordinates into pixels of the area being drawn.
417#[derive(Clone, Copy)]
418struct Grid {
419  /// Pixels a logical pixel: the output's scale times `zoom`.
420  scale: f32,
421  /// How many times its own resolution a transformed layer is drawn at,
422  /// from [`Affine::layer_zoom`]; 1 outside one.
423  zoom: f32,
424  /// The transforms around what is drawn, from its coordinates to the
425  /// window's, without their moves.
426  linear: Affine,
427  /// The window's logical size.
428  window: Size,
429  /// The buffer's size in pixels.
430  width: u32,
431  height: u32,
432  /// Where the area being drawn starts in the buffer.
433  left: f32,
434  top: f32,
435}
436
437impl Grid {
438  /// A logical x coordinate on the pixel grid. The window's right edge is
439  /// the buffer's, even where rounding would leave a column out.
440  fn x(&self, x: f32) -> f32 {
441    let pixel = if x >= self.window.width {
442      self.width as f32
443    } else {
444      (x * self.scale).round()
445    };
446    pixel - self.left
447  }
448
449  /// A logical y coordinate on the pixel grid, likewise.
450  fn y(&self, y: f32) -> f32 {
451    let pixel = if y >= self.window.height {
452      self.height as f32
453    } else {
454      (y * self.scale).round()
455    };
456    pixel - self.top
457  }
458
459  /// The pixels of a `width` by `height` area that `rect`, in logical
460  /// pixels, touches: rounded outward, a pixel added around for
461  /// antialiasing, and cut to the area. `None` if it misses the area.
462  fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
463    if !(rect.width > 0.0 && rect.height > 0.0) {
464      return None;
465    }
466    // `as` saturates, so huge or negative values stay in range.
467    let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
468    let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
469    let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
470    let bottom =
471      (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
472    (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
473  }
474
475  /// This grid for a pixmap placed at `x`, `y` within this one.
476  fn moved(&self, x: u32, y: u32) -> Grid {
477    Grid {
478      left: self.left + x as f32,
479      top: self.top + y as f32,
480      ..*self
481    }
482  }
483
484  /// A logical rectangle on the pixel grid, or `None` if it covers no
485  /// pixel.
486  fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
487    tiny_skia::Rect::from_ltrb(
488      self.x(rect.x),
489      self.y(rect.y),
490      self.x(rect.right()),
491      self.y(rect.bottom()),
492    )
493    .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
494  }
495}
496
497/// What drawing needs besides the pixmap.
498struct Painter<'a> {
499  grid: Grid,
500  glyphs: &'a mut SwashCache,
501  icons: &'a mut Icons,
502  fonts: &'a mut FontSystem,
503  work: &'a mut Work,
504  /// The cells of content shadows cast in this draw.
505  casts: &'a mut HashMap<CastKey, effects::Cast>,
506}
507
508/// A cell of a content shadow cast in a draw: its widget's path, and the
509/// cell's column and row.
510type CastKey = (String, i64, i64);
511
512impl Painter<'_> {
513  /// A painter for a pixmap on `grid`, in the same space.
514  fn on(&mut self, grid: Grid) -> Painter<'_> {
515    Painter {
516      grid,
517      glyphs: &mut *self.glyphs,
518      icons: &mut *self.icons,
519      fonts: &mut *self.fonts,
520      work: &mut *self.work,
521      casts: &mut *self.casts,
522    }
523  }
524
525  /// Draws `node` and everything inside it. With an opacity below 1, a
526  /// mask or a content shadow, they are drawn into one layer first, which
527  /// is masked, given its shadow and blended in at that opacity, so
528  /// overlapping children don't show through each other.
529  fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
530    // Nothing the node or its descendants paint reaches this area.
531    let Some((x, y, width, height)) =
532      self
533        .grid
534        .cover(node.bounds(), pixmap.width(), pixmap.height())
535    else {
536      return;
537    };
538    let style = node.style();
539    let opacity = style.opacity.unwrap_or(1.0);
540    let opacity = if opacity.is_nan() {
541      1.0
542    } else {
543      opacity.clamp(0.0, 1.0)
544    };
545    if opacity == 0.0 {
546      return;
547    }
548    let shadow = effects::cast_by_content(&style);
549    if let Some(transform) = node.transform() {
550      self.transformed(pixmap, node, &style, transform, opacity);
551    } else if opacity < 1.0 || style.mask.is_some() || shadow.is_some() {
552      // The layer covers only what the subtree paints in this area.
553      let Some(mut layer) = Pixmap::new(width, height) else {
554        return;
555      };
556      self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
557      let mut inner = self.on(self.grid.moved(x, y));
558      inner.layer_contents(&mut layer.as_mut(), node, &style, shadow);
559      let paint = PixmapPaint {
560        opacity,
561        ..PixmapPaint::default()
562      };
563      let (x, y) = (x as i32, y as i32);
564      pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
565    } else {
566      self.node_contents(pixmap, node, &style);
567    }
568  }
569
570  /// What `node_contents` draws into a fresh `layer`, kept only where the
571  /// style's mask is opaque, with `shadow` cast by what is left put under
572  /// it.
573  fn layer_contents(
574    &mut self,
575    layer: &mut PixmapMut<'_>,
576    node: NodeView<'_>,
577    style: &Style,
578    shadow: Option<Shadow>,
579  ) {
580    self.node_contents(layer, node, style);
581    if let Some(mask) = &style.mask {
582      self.mask(layer, node.rect(), mask);
583    }
584    if let Some(shadow) = shadow {
585      self.content_shadow(layer, node, &shadow);
586    }
587  }
588
589  /// Draws `node` and everything inside it into a layer in its own
590  /// coordinates, then blends that in through its `transform`, filtered
591  /// bilinearly, at `opacity`: one layer for both. The layer covers only
592  /// what lands in this pixmap, in the node's own buffer pixels times the
593  /// zoom of every transform around it, so what they scale up stays
594  /// sharp, and a pixel is always drawn the same way in the same tile.
595  fn transformed(
596    &mut self,
597    pixmap: &mut PixmapMut<'_>,
598    node: NodeView<'_>,
599    style: &Style,
600    transform: Affine,
601    opacity: f32,
602  ) {
603    let Affine {
604      sx,
605      ky,
606      kx,
607      sy,
608      tx,
609      ty,
610    } = transform;
611    let Grid {
612      scale, left, top, ..
613    } = self.grid;
614    let outer = self.grid.linear;
615    let linear = Transform::from_row(outer.sx, outer.ky, outer.kx, outer.sy, 0.0, 0.0)
616      .pre_concat(Transform::from_row(sx, ky, kx, sy, 0.0, 0.0));
617    let linear = Affine {
618      sx: linear.sx,
619      ky: linear.ky,
620      kx: linear.kx,
621      sy: linear.sy,
622      tx: 0.0,
623      ty: 0.0,
624    };
625    let zoom = linear.layer_zoom();
626    let layer_scale = scale / self.grid.zoom * zoom;
627    // From the node's own pixels, zoomed, to its parent's.
628    let device = Transform::from_scale(scale, scale)
629      .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
630      .pre_scale(1.0 / layer_scale, 1.0 / layer_scale);
631    let to_pixmap = device.post_translate(-left, -top);
632    let Some(back) = to_pixmap.invert() else {
633      return;
634    };
635    let inner = node.inner_bounds();
636    let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
637      .and_then(|rect| rect.transform(back));
638    let drawn = tiny_skia::Rect::from_xywh(
639      inner.x * layer_scale,
640      inner.y * layer_scale,
641      inner.width * layer_scale,
642      inner.height * layer_scale,
643    );
644    let Some(area) = shown
645      .zip(drawn)
646      .and_then(|(shown, drawn)| shown.intersect(&drawn))
647      .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
648      .and_then(|area| area.round_out())
649    else {
650      return;
651    };
652    let pixels = u64::from(area.width()) * u64::from(area.height());
653    if pixels > LAYER_LIMIT {
654      tracing::debug!(
655        "{} is transformed into a layer too large to draw",
656        node.path()
657      );
658      return;
659    }
660    let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
661      return;
662    };
663    self.work.layer_pixels += pixels;
664    let (x, y) = (area.x() as f32, area.y() as f32);
665    let (width, height) = if zoom == self.grid.zoom {
666      (self.grid.width, self.grid.height)
667    } else {
668      // `as` saturates; the window's edge is past any layer drawn.
669      let window = self.grid.window;
670      (
671        (window.width * layer_scale).round() as u32,
672        (window.height * layer_scale).round() as u32,
673      )
674    };
675    let mut inner = self.on(Grid {
676      scale: layer_scale,
677      zoom,
678      linear,
679      width,
680      height,
681      left: x,
682      top: y,
683      ..self.grid
684    });
685    let shadow = effects::cast_by_content(style);
686    inner.layer_contents(&mut layer.as_mut(), node, style, shadow);
687    let paint = PixmapPaint {
688      opacity,
689      quality: FilterQuality::Bilinear,
690      ..PixmapPaint::default()
691    };
692    pixmap.draw_pixmap(
693      0,
694      0,
695      layer.as_ref(),
696      &paint,
697      to_pixmap.pre_translate(x, y),
698      None,
699    );
700  }
701
702  fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
703    self.work.nodes += 1;
704    // A content shadow is cast by the layer this is drawn into, and an
705    // inset one inside the box.
706    let outside = |shadow: &Shadow| !shadow.follow_content && !shadow.inset;
707    if let Some(shadow) = style.shadow.filter(outside) {
708      self.shadow(pixmap, node.rect(), style, &shadow);
709    }
710    self.draw_box(pixmap, node.rect(), style);
711    match node.content() {
712      Content::Text(text) => {
713        self.selection(pixmap, &text.selection(), text.color());
714        self.text(pixmap, &text);
715      }
716      Content::Icon(icon) => self.icon(pixmap, &icon),
717      Content::Image(image) => self.image(pixmap, &image),
718      Content::Capture(capture) => self.capture(pixmap, &capture),
719      Content::Input(input) => self.input(pixmap, &input),
720      Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
721      Content::None => {}
722    }
723    if node.clips() {
724      self.clipped_children(pixmap, node, style);
725    } else {
726      for child in node.children() {
727        self.node(pixmap, child);
728      }
729    }
730  }
731
732  /// `node`'s children, drawn into a layer that is blended in through a
733  /// mask of the inside of the node's border. The mask is drawn in the
734  /// area's own pixels, on the same fixed grid as everything else, so a
735  /// repaint cuts every edge exactly as a full draw does.
736  fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
737    let Some((area, corners)) = self.box_shape(node.rect(), style) else {
738      return;
739    };
740    let width = self.border_width(style);
741    let Some(inside) = tiny_skia::Rect::from_ltrb(
742      area.left() + width,
743      area.top() + width,
744      area.right() - width,
745      area.bottom() - width,
746    ) else {
747      return;
748    };
749    let corners = inset(corners, width);
750    self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
751      for child in node.children() {
752        painter.node(layer, child);
753      }
754      // A scroll view always clips; its bar is cut to its corners too.
755      for (handle, bar) in node.scroll_bars() {
756        painter.draw_box(layer, handle, &bar);
757      }
758    });
759  }
760
761  /// What `draw` paints within `cover`, a logical rectangle, blended in
762  /// through a mask of `shape`, a pixel rectangle with rounded corners.
763  fn through_mask(
764    &mut self,
765    pixmap: &mut PixmapMut<'_>,
766    cover: Rect,
767    (shape, corners): (tiny_skia::Rect, Corners),
768    draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
769  ) {
770    if !visible(pixmap, shape) {
771      return;
772    }
773    let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
774      Mask::new(pixmap.width(), pixmap.height()),
775      self.grid.cover(cover, pixmap.width(), pixmap.height()),
776    ) else {
777      return;
778    };
779    let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
780      return;
781    };
782    self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
783    let mut inner = self.on(self.grid.moved(x, y));
784    draw(&mut inner, &mut layer.as_mut());
785    let mut path = PathBuilder::new();
786    rounded_rect(&mut path, shape, corners);
787    let Some(path) = path.finish() else {
788      return;
789    };
790    mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
791    pixmap.draw_pixmap(
792      x as i32,
793      y as i32,
794      layer.as_ref(),
795      &PixmapPaint::default(),
796      Transform::identity(),
797      Some(&mask),
798    );
799  }
800
801  /// A widget's rectangle on the pixel grid and each corner's radius in
802  /// pixels, fitted to it as CSS does, so two on one side never overlap.
803  /// `None` if it covers no pixel.
804  fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
805    let area = self.grid.rect(rect)?;
806    let corners = style.radius.unwrap_or_default().corners();
807    let corners = fit(corners.map(|radius| radius * self.grid.scale), area);
808    Some((area, corners))
809  }
810
811  /// The border's width in pixels: as in CSS, rounded down to whole
812  /// pixels, but at least one. 0 without a border.
813  fn border_width(&self, style: &Style) -> f32 {
814    let Some(border) = style.border else {
815      return 0.0;
816    };
817    let width = (border.width * self.grid.scale).floor();
818    if border.width > 0.0 {
819      width.max(1.0)
820    } else {
821      width.max(0.0)
822    }
823  }
824
825  /// The background, an inset shadow and the border of a widget's
826  /// rectangle.
827  fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
828    let inset_shadow = style.shadow.filter(|shadow| shadow.inset);
829    if style.background.is_none()
830      && style.gradient.is_none()
831      && style.border.is_none()
832      && inset_shadow.is_none()
833    {
834      return;
835    }
836    let Some((area, corners)) = self.box_shape(rect, style) else {
837      return;
838    };
839    if !visible(pixmap, area) {
840      return;
841    }
842
843    if let Some(color) = style.background
844      && !(corners == [0.0; 4] && fill_opaque(pixmap, area, color))
845    {
846      let mut path = PathBuilder::new();
847      rounded_rect(&mut path, area, corners);
848      fill(pixmap, path, color, FillRule::Winding);
849    }
850    if let Some(gradient) = style.gradient {
851      let mut path = PathBuilder::new();
852      rounded_rect(&mut path, area, corners);
853      let size = (pixmap.width(), pixmap.height());
854      if let (Some(path), Some(ramp)) = (path.finish(), self.ramp(&gradient, area, area, size)) {
855        ramp.fill(pixmap, &path);
856      }
857    }
858    if let Some(shadow) = inset_shadow {
859      self.inset_shadow(pixmap, (area, corners), self.border_width(style), &shadow);
860    }
861    if let Some(border) = style.border {
862      let width = self.border_width(style);
863      let dashed = width >= 1.0
864        && style.border_dash.is_some_and(|dash| {
865          self.dashed_border(pixmap, (area, corners), width, border.color, dash)
866        });
867
868      if width >= 1.0 && !dashed {
869        // A ring: the outer shape with the inner one cut out.
870        let mut path = PathBuilder::new();
871        rounded_rect(&mut path, area, corners);
872        if let Some(inner) = tiny_skia::Rect::from_ltrb(
873          area.left() + width,
874          area.top() + width,
875          area.right() - width,
876          area.bottom() - width,
877        ) {
878          rounded_rect(&mut path, inner, inset(corners, width));
879        }
880        fill(pixmap, path, border.color, FillRule::EvenOdd);
881      }
882    }
883  }
884
885  /// A border `width` pixels wide inside `area`, dashed by `on` and `off`
886  /// logical pixels along its middle line, so the dashes follow the
887  /// corners. The line is laid out and dashed in buffer pixels and moved
888  /// onto the pixmap, so tiles cut the dashes in the same places. `false`
889  /// when the pattern or the box can't take dashes, to draw it solid.
890  fn dashed_border(
891    &self,
892    pixmap: &mut PixmapMut<'_>,
893    (area, corners): (tiny_skia::Rect, Corners),
894    width: f32,
895    color: Color,
896    (on, off): (f32, f32),
897  ) -> bool {
898    let Grid {
899      scale, left, top, ..
900    } = self.grid;
901    let half = width / 2.0;
902    let Some(middle) = tiny_skia::Rect::from_ltrb(
903      area.left() + left + half,
904      area.top() + top + half,
905      area.right() + left - half,
906      area.bottom() + top - half,
907    ) else {
908      return false;
909    };
910    let corners = inset(corners, half);
911    let (on, off) = (on * scale, off * scale);
912    let mut all = PathBuilder::new();
913    let square: Vec<usize> = (0..4).filter(|&index| corners[index] <= 0.0).collect();
914    if square.is_empty() {
915      // Each corner trades two radii of straight line for a quarter
916      // circle.
917      let rounding: f32 = corners
918        .iter()
919        .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
920        .sum();
921      let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
922      let mut path = PathBuilder::new();
923      rounded_rect(&mut path, middle, corners);
924      if !dash_into(&mut all, path, perimeter, on, off) {
925        return false;
926      }
927    } else {
928      // As browsers do, each run from one square corner to the next gets
929      // its own whole number of dashes, centered on both corners.
930      for (at, &from) in square.iter().enumerate() {
931        let to = square[(at + 1) % square.len()];
932        let steps = (to + 4 - from - 1) % 4 + 1;
933        let [.., mut was] = corner(middle, corners, from);
934        let mut path = PathBuilder::new();
935        path.move_to(was.x, was.y);
936        let mut length = 0.0;
937        for index in (from + 1..=from + steps).map(|index| index % 4) {
938          let [start, one, two, end] = corner(middle, corners, index);
939          path.line_to(start.x, start.y);
940          length += was.distance(start);
941          if corners[index] > 0.0 {
942            path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
943            length += std::f32::consts::FRAC_PI_2 * corners[index];
944          }
945          was = end;
946        }
947        if !dash_into(&mut all, path, length, on, off) {
948          return false;
949        }
950      }
951      // The two half dashes meeting at a square corner end on its middle
952      // line, so the outer quarter of the corner is filled by a piece
953      // joined there with a miter. A dot is round there as anywhere.
954      if on > 0.0 {
955        // Each corner's incoming direction, clockwise from the top left.
956        const IN: [(f32, f32); 4] = [(0.0, -1.0), (1.0, 0.0), (0.0, 1.0), (-1.0, 0.0)];
957        for &index in &square {
958          let [point, ..] = corner(middle, corners, index);
959          let ((ax, ay), (bx, by)) = (IN[index], IN[(index + 1) % 4]);
960          all.move_to(point.x - half * ax, point.y - half * ay);
961          all.line_to(point.x, point.y);
962          all.line_to(point.x + half * bx, point.y + half * by);
963        }
964      }
965    }
966    let Some(dashes) = all.finish() else {
967      return true;
968    };
969    // Every tile the border crosses would stroke every dash, so only the
970    // dashes near this one are kept. A closed outline that misses the
971    // tile adds nothing inside it, so the pixels are the same. A miter
972    // reaches at most twice the width past its line.
973    let reach = 2.0 * width + 1.0;
974    let near = [
975      left - reach,
976      top - reach,
977      left + pixmap.width() as f32 + reach,
978      top + pixmap.height() as f32 + reach,
979    ];
980    let mut kept = PathBuilder::new();
981    let mut contour = Vec::new();
982    for segment in dashes.segments() {
983      if matches!(segment, PathSegment::MoveTo(_)) {
984        keep_near(&mut kept, &contour, near);
985        contour.clear();
986      }
987      contour.push(segment);
988    }
989    keep_near(&mut kept, &contour, near);
990    let Some(kept) = kept.finish() else {
991      return true;
992    };
993    let stroke = Stroke {
994      width,
995      // A dash of 0 is a dot.
996      line_cap: if on == 0.0 {
997        LineCap::Round
998      } else {
999        LineCap::Butt
1000      },
1001      line_join: LineJoin::Miter,
1002      ..Stroke::default()
1003    };
1004    let mut paint = Paint::default();
1005    paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1006    paint.anti_alias = true;
1007    let moved = Transform::from_translate(-left, -top);
1008    pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
1009    true
1010  }
1011
1012  /// `shadow` of the box `rect` with `style`'s corners. A sharp one is a
1013  /// filled shape; a blurred one is worked out pixel by pixel in buffer
1014  /// pixels, so every tile agrees, and only within one and a half blurs
1015  /// of its shape, past which it fades below a 255th.
1016  fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
1017    let Grid {
1018      scale, left, top, ..
1019    } = self.grid;
1020    let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1021    if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1022      return;
1023    }
1024    let Some((area, corners)) = self.box_shape(rect, style) else {
1025      return;
1026    };
1027    // The shape in buffer pixels.
1028    let spread = shadow.spread * scale;
1029    let Some(shape) = tiny_skia::Rect::from_ltrb(
1030      area.left() + left + shadow.x * scale - spread,
1031      area.top() + top + shadow.y * scale - spread,
1032      area.right() + left + shadow.x * scale + spread,
1033      area.bottom() + top + shadow.y * scale + spread,
1034    ) else {
1035      return;
1036    };
1037    let corners = fit(spread_corners(corners, spread), shape);
1038    // A cut-out shadow leaves clear what the box's background covers.
1039    let cut = if shadow.cut_out {
1040      self.box_mask(pixmap, rect, style)
1041    } else {
1042      None
1043    };
1044    // CSS draws a blur as a Gaussian of half its length.
1045    let sigma = shadow.blur.max(0.0) * scale / 2.0;
1046    if sigma < 0.25 {
1047      let mut path = PathBuilder::new();
1048      let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
1049        return;
1050      };
1051      rounded_rect(&mut path, shape, corners);
1052      let Some(path) = path.finish() else {
1053        return;
1054      };
1055      let mut paint = Paint::default();
1056      let color = shadow.color;
1057      paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1058      paint.anti_alias = true;
1059      let outside = cut.map(|mut cut| {
1060        cut.invert();
1061        cut
1062      });
1063      let (rule, at) = (FillRule::Winding, Transform::identity());
1064      pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1065      return;
1066    }
1067    let reach = 3.0 * sigma;
1068    let columns = (shape.left() - reach - left).floor().max(0.0) as u32
1069      ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
1070    let rows = (shape.top() - reach - top).floor().max(0.0) as u32
1071      ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
1072    if columns.is_empty() || rows.is_empty() {
1073      return;
1074    }
1075    let blurred = BlurredBox::new(shape, corners, sigma);
1076    let mut mask = Vec::with_capacity(columns.len() * rows.len());
1077    for row in rows.clone() {
1078      let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1079      blurred.row(top + row as f32 + 0.5, xs, &mut mask);
1080    }
1081    if let Some(cut) = cut {
1082      let stride = pixmap.width() as usize;
1083      let under = rows.clone().flat_map(|row| {
1084        columns
1085          .clone()
1086          .map(move |column| row as usize * stride + column as usize)
1087      });
1088      for (alpha, at) in mask.iter_mut().zip(under) {
1089        *alpha = mul(*alpha, 255 - cut.data()[at]);
1090      }
1091    }
1092    let width = columns.len() as u32;
1093    let height = rows.len() as u32;
1094    let (x, y) = (columns.start as i32, rows.start as i32);
1095    blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
1096  }
1097
1098  /// An inset `shadow` inside `area` with `corners`, within a border
1099  /// `border` pixels wide: the inside of the border, but for a hole of its
1100  /// shape moved, shrunk by the spread and blurred, as CSS draws one. Like
1101  /// an outer shadow, it is worked out in buffer pixels, so tiles agree.
1102  fn inset_shadow(
1103    &self,
1104    pixmap: &mut PixmapMut<'_>,
1105    (area, corners): (tiny_skia::Rect, Corners),
1106    border: f32,
1107    shadow: &Shadow,
1108  ) {
1109    let Grid {
1110      scale, left, top, ..
1111    } = self.grid;
1112    let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
1113    if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
1114      return;
1115    }
1116    let Some(inside) = tiny_skia::Rect::from_ltrb(
1117      area.left() + border,
1118      area.top() + border,
1119      area.right() - border,
1120      area.bottom() - border,
1121    ) else {
1122      return;
1123    };
1124    let inside_corners = inset(corners, border);
1125    if !visible(pixmap, inside) {
1126      return;
1127    }
1128    let mut path = PathBuilder::new();
1129    rounded_rect(&mut path, inside, inside_corners);
1130    let Some(path) = path.finish() else {
1131      return;
1132    };
1133    // The hole in buffer pixels; a spread that swallows it leaves none.
1134    let (x, y, spread) = (shadow.x * scale, shadow.y * scale, shadow.spread * scale);
1135    let hole = tiny_skia::Rect::from_ltrb(
1136      inside.left() + left + x + spread,
1137      inside.top() + top + y + spread,
1138      inside.right() + left + x - spread,
1139      inside.bottom() + top + y - spread,
1140    );
1141    let hole = hole.map(|hole| (hole, fit(spread_corners(inside_corners, -spread), hole)));
1142    let sigma = shadow.blur.max(0.0) * scale / 2.0;
1143    let color = shadow.color;
1144    if sigma < 0.25 {
1145      let mut outside = None;
1146      if let Some((hole, corners)) = hole {
1147        let mut cut = PathBuilder::new();
1148        let Some(moved) = hole.transform(Transform::from_translate(-left, -top)) else {
1149          return;
1150        };
1151        rounded_rect(&mut cut, moved, corners);
1152        let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1153          return;
1154        };
1155        let (rule, at) = (FillRule::Winding, Transform::identity());
1156        let Some(cut) = cut.finish() else {
1157          return;
1158        };
1159        mask.fill_path(&cut, rule, true, at);
1160        mask.invert();
1161        outside = Some(mask);
1162      }
1163      let mut paint = Paint::default();
1164      paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1165      paint.anti_alias = true;
1166      let (rule, at) = (FillRule::Winding, Transform::identity());
1167      pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
1168      return;
1169    }
1170    // The inside of the border covers these pixels, and the shadow shows
1171    // where the blurred hole doesn't.
1172    let Some(mut mask) = Mask::new(pixmap.width(), pixmap.height()) else {
1173      return;
1174    };
1175    mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
1176    let columns = inside.left().floor().max(0.0) as u32
1177      ..(inside.right().ceil().max(0.0) as u32).min(pixmap.width());
1178    let rows = inside.top().floor().max(0.0) as u32
1179      ..(inside.bottom().ceil().max(0.0) as u32).min(pixmap.height());
1180    if columns.is_empty() || rows.is_empty() {
1181      return;
1182    }
1183    let blurred = hole.map(|(hole, corners)| BlurredBox::new(hole, corners, sigma));
1184    let mut alpha = Vec::with_capacity(columns.len() * rows.len());
1185    for row in rows.clone() {
1186      let start = alpha.len();
1187      match &blurred {
1188        Some(blurred) => {
1189          let xs = columns.clone().map(|column| left + column as f32 + 0.5);
1190          blurred.row(top + row as f32 + 0.5, xs, &mut alpha);
1191        }
1192        None => alpha.resize(start + columns.len(), 0),
1193      }
1194      let stride = pixmap.width() as usize;
1195      let row = &mask.data()[row as usize * stride..];
1196      let covered = &row[columns.start as usize..columns.end as usize];
1197      for (value, &covered) in alpha[start..].iter_mut().zip(covered) {
1198        *value = mul(255 - *value, covered);
1199      }
1200    }
1201    let (width, height) = (columns.len() as u32, rows.len() as u32);
1202    let (x, y) = (columns.start as i32, rows.start as i32);
1203    blend_mask(pixmap, x, y, width, height, &alpha, color);
1204  }
1205
1206  /// How much of each of this pixmap's pixels the box `rect` with
1207  /// `style`'s corners covers, as its background fills it.
1208  fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
1209    let (area, corners) = self.box_shape(rect, style)?;
1210    let mut path = PathBuilder::new();
1211    rounded_rect(&mut path, area, corners);
1212    let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
1213    let (rule, at) = (FillRule::Winding, Transform::identity());
1214    mask.fill_path(&path.finish()?, rule, true, at);
1215    Some(mask)
1216  }
1217
1218  /// Glyphs, drawn as masks in their span's color or else the text's,
1219  /// then any underline and strikethrough. The baseline sits on a whole
1220  /// pixel so horizontal strokes stay sharp; glyphs keep their sub-pixel
1221  /// horizontal position.
1222  fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1223    let Grid {
1224      scale, left, top, ..
1225    } = self.grid;
1226    let origin = text.origin();
1227    let x = origin.x * scale - left;
1228    for run in text.runs() {
1229      // Rounded in buffer coordinates, so every area drawn agrees.
1230      let baseline = ((origin.y + run.line_y) * scale).round() - top;
1231      if baseline + run.line_height * scale < 0.0
1232        || baseline - run.line_height * scale > pixmap.height() as f32
1233      {
1234        continue;
1235      }
1236      // A lit link takes the hover color, if the text has one.
1237      let span_color = |span: &Span, glyph: &LayoutGlyph| match text.glyph_lit(run.line_i, glyph) {
1238        true => text.link_hover_color().or(span.color),
1239        false => span.color,
1240      };
1241      for glyph in run.glyphs.iter() {
1242        let span = text.span(run.line_i, glyph);
1243        let color = span.and_then(|span| span_color(span, glyph));
1244        let color = color.unwrap_or(text.color());
1245        if color.a == 0 {
1246          continue;
1247        }
1248        let physical = glyph.physical((x, baseline), scale);
1249        let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1250          continue;
1251        };
1252        let left = physical.x + image.placement.left;
1253        let top = physical.y - image.placement.top;
1254        let (width, height) = (image.placement.width, image.placement.height);
1255        match image.content {
1256          SwashContent::Mask => {
1257            blend_mask(pixmap, left, top, width, height, &image.data, color);
1258          }
1259          SwashContent::Color => {
1260            let premultiplied = is_color_outline(image);
1261            let rgba = (image.data.as_slice(), premultiplied);
1262            blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1263          }
1264          // Not requested: there is no subpixel antialiasing.
1265          SwashContent::SubpixelMask => {}
1266        }
1267      }
1268      let origin = text.origin().x;
1269      let own = (text.underline(), text.strikethrough());
1270      if own != (false, false) {
1271        self.decorations(pixmap, origin, &run.glyphs, baseline, own, text.color());
1272      }
1273      // A span's own lines run across its glyphs on the line, each in its
1274      // color. cosmic-text's decoration spans join two decorated spans
1275      // across the text between them, so they aren't used.
1276      let same_span = |a: &LayoutGlyph, b: &LayoutGlyph| match (
1277        text.span(run.line_i, a),
1278        text.span(run.line_i, b),
1279      ) {
1280        (Some(a), Some(b)) => std::ptr::eq(a, b),
1281        (a, b) => a.is_none() && b.is_none(),
1282      };
1283      for glyphs in run.glyphs.chunk_by(same_span) {
1284        let Some(span) = text.span(run.line_i, &glyphs[0]) else {
1285          continue;
1286        };
1287        let lit = text.glyph_lit(run.line_i, &glyphs[0]);
1288        let lines = (span.underline || lit, span.strikethrough);
1289        if lines != (false, false) {
1290          let color = span_color(span, &glyphs[0]).unwrap_or(text.color());
1291          self.decorations(pixmap, origin, glyphs, baseline, lines, color);
1292        }
1293      }
1294    }
1295  }
1296
1297  /// The underline and strikethrough across `glyphs`, each run of
1298  /// glyphs from one font at the place and thickness that font gives, so
1299  /// a fallback glyph's line sits where its own font puts it.
1300  fn decorations(
1301    &mut self,
1302    pixmap: &mut PixmapMut<'_>,
1303    origin: f32,
1304    glyphs: &[LayoutGlyph],
1305    baseline: f32,
1306    lines: (bool, bool),
1307    color: Color,
1308  ) {
1309    let same_font = |a: &LayoutGlyph, b: &LayoutGlyph| {
1310      (a.font_id, a.font_weight, a.font_size) == (b.font_id, b.font_weight, b.font_size)
1311    };
1312    for glyphs in glyphs.chunk_by(same_font) {
1313      self.font_decorations(pixmap, origin, glyphs, baseline, lines, color);
1314    }
1315  }
1316
1317  /// The underline and strikethrough across `glyphs`, all from one font,
1318  /// at the place and thickness it gives, as cosmic-text draws them.
1319  /// Edges snap to whole pixels in the buffer, so every tile agrees, and
1320  /// each line is at least a pixel thick. A line is kept within half an
1321  /// em of the baseline, which the text's painted area covers.
1322  fn font_decorations(
1323    &mut self,
1324    pixmap: &mut PixmapMut<'_>,
1325    origin: f32,
1326    glyphs: &[LayoutGlyph],
1327    baseline: f32,
1328    (underline, strikethrough): (bool, bool),
1329    color: Color,
1330  ) {
1331    let Some(first) = glyphs.first() else {
1332      return;
1333    };
1334    let Some(font) = self.fonts.get_font(first.font_id, first.font_weight) else {
1335      return;
1336    };
1337    let metrics = font.metrics();
1338    let em = f32::from(metrics.units_per_em);
1339    if em == 0.0 {
1340      return;
1341    }
1342    let Grid { scale, left, .. } = self.grid;
1343    let (start, end) = glyphs
1344      .iter()
1345      .fold((f32::MAX, f32::MIN), |(start, end), glyph| {
1346        (start.min(glyph.x), end.max(glyph.x + glyph.w))
1347      });
1348    let x0 = ((origin + start) * scale).round() - left;
1349    let x1 = ((origin + end) * scale).round() - left;
1350    let size = first.font_size * scale;
1351    // cosmic-text's defaults for a font that gives none.
1352    let lines = [
1353      (underline, metrics.underline, -0.125),
1354      (strikethrough, metrics.strikeout, 0.3),
1355    ];
1356    for (on, decoration, offset) in lines {
1357      if !on {
1358        continue;
1359      }
1360      let (offset, thickness) =
1361        decoration.map_or((offset, 1.0 / 14.0), |d| (d.offset / em, d.thickness / em));
1362      // The offset is to the line's top, upward from the baseline.
1363      let thickness = (thickness.clamp(0.0, 0.25) * size).round().max(1.0);
1364      let y = baseline - (offset.clamp(-0.25, 0.5) * size).round();
1365      if let Some(area) = tiny_skia::Rect::from_ltrb(x0, y, x1, y + thickness) {
1366        let mut path = PathBuilder::new();
1367        path.push_rect(area);
1368        fill(pixmap, path, color, FillRule::Winding);
1369      }
1370    }
1371  }
1372
1373  /// A text field, cut to its content box.
1374  fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1375    let Some(area) = self.grid.rect(input.area) else {
1376      return;
1377    };
1378    self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1379      painter.input_contents(layer, input);
1380    });
1381  }
1382
1383  /// A field's selection in a third of the text's color, the text, and a
1384  /// caret in the text's color.
1385  fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1386    let color = input.text.color();
1387    self.selection(pixmap, input.selection, color);
1388    self.text(pixmap, &input.text);
1389    for line in input.underline {
1390      if let Some(area) = self.grid.rect(*line) {
1391        let mut path = PathBuilder::new();
1392        path.push_rect(area);
1393        fill(pixmap, path, color, FillRule::Winding);
1394      }
1395    }
1396    if let Some(caret) = input.caret {
1397      // At least one pixel wide whatever the scale.
1398      let left = self.grid.x(caret.x);
1399      let right = self.grid.x(caret.right()).max(left + 1.0);
1400      if let Some(area) = tiny_skia::Rect::from_ltrb(
1401        left,
1402        self.grid.y(caret.y),
1403        right,
1404        self.grid.y(caret.bottom()),
1405      ) {
1406        let mut path = PathBuilder::new();
1407        path.push_rect(area);
1408        fill(pixmap, path, color, FillRule::Winding);
1409      }
1410    }
1411  }
1412
1413  /// A selection, behind text in `color`, in a third of it.
1414  fn selection(&mut self, pixmap: &mut PixmapMut<'_>, spans: &[Rect], color: Color) {
1415    let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1416    for span in spans {
1417      if let Some(area) = self.grid.rect(*span) {
1418        let mut path = PathBuilder::new();
1419        path.push_rect(area);
1420        fill(pixmap, path, tint, FillRule::Winding);
1421      }
1422    }
1423  }
1424
1425  /// An image, scaled to its box in pixels.
1426  fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1427    let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1428      return;
1429    };
1430    match self.icons.image(image, (width, height), self.grid.scale) {
1431      Some(Drawn::One(pixels)) if (pixels.width(), pixels.height()) == (width, height) => {
1432        transition::blit(pixmap, (x, y), pixels);
1433      }
1434      // A picture of another size, while this one is decoded.
1435      Some(Drawn::One(pixels)) => {
1436        let paint = PixmapPaint {
1437          quality: FilterQuality::Bilinear,
1438          ..PixmapPaint::default()
1439        };
1440        let stretch = Transform::from_scale(
1441          width as f32 / pixels.width() as f32,
1442          height as f32 / pixels.height() as f32,
1443        )
1444        .post_translate(x as f32, y as f32);
1445        pixmap.draw_pixmap(0, 0, pixels.as_ref(), &paint, stretch, None);
1446      }
1447      Some(Drawn::Two { from, to, t }) => {
1448        transition::draw(pixmap, (x, y), from, to, t, image.transition);
1449      }
1450      None => {}
1451    }
1452  }
1453
1454  /// A screencopy view's frame, scaled to its box in pixels.
1455  fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1456    let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1457      return;
1458    };
1459    let frame = capture.frame;
1460    if let Some(pixels) = self
1461      .icons
1462      .capture(capture.id, frame, width, height, capture.fit)
1463    {
1464      draw_at(pixmap, x, y, pixels);
1465    }
1466  }
1467
1468  /// Where a picture in `rect` goes in the pixmap, and its size in
1469  /// pixels; `None` if it covers no pixel of it. Placed and sized apart,
1470  /// as an icon is, so a picture past the window's edge is cut there
1471  /// instead of squeezed inside it.
1472  fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1473    let Grid {
1474      scale, left, top, ..
1475    } = self.grid;
1476    let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1477    let (x, y) = (
1478      (rect.x * scale).round() - left,
1479      (rect.y * scale).round() - top,
1480    );
1481    if !(width >= 1.0 && height >= 1.0) {
1482      return None;
1483    }
1484    let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1485    // `as` saturates, so a huge box stays in range.
1486    visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1487  }
1488
1489  /// An icon, rasterized at its size in pixels.
1490  fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1491    let Grid {
1492      scale, left, top, ..
1493    } = self.grid;
1494    let side = (icon.rect.width * scale).round();
1495    if side.is_nan() || side < 1.0 {
1496      return;
1497    }
1498    let x = (icon.rect.x * scale).round() - left;
1499    let y = (icon.rect.y * scale).round() - top;
1500    // Theme directories come in whole scales; 1.5 looks for @2 icons.
1501    let size = icon.rect.width.round() as u32;
1502    let theme_scale = scale.ceil().max(1.0) as u32;
1503    let sizes = (side as u32, size, theme_scale);
1504    if let Some(image) = self.icons.get(icon.source, sizes, icon.tint) {
1505      pixmap.draw_pixmap(
1506        x as i32,
1507        y as i32,
1508        image.as_ref(),
1509        &PixmapPaint::default(),
1510        Transform::identity(),
1511        None,
1512      );
1513    }
1514  }
1515}
1516
1517/// Draws `pixels` unscaled with its corner at `x`, `y`.
1518fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1519  let paint = PixmapPaint::default();
1520  pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1521}
1522
1523/// Whether any of `area` lies inside the pixmap.
1524fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1525  area.right() > 0.0
1526    && area.bottom() > 0.0
1527    && area.left() < pixmap.width() as f32
1528    && area.top() < pixmap.height() as f32
1529}
1530
1531fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1532  let Some(path) = path.finish() else {
1533    return;
1534  };
1535  let mut paint = Paint::default();
1536  paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1537  paint.anti_alias = true;
1538  pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1539}
1540
1541/// Each corner's radius in pixels, from the top left clockwise.
1542type Corners = [f32; 4];
1543
1544/// Dashes `path`, `length` pixels long, by `on` and `off` stretched so a
1545/// whole number of them fits, each centered on a multiple of the period
1546/// from its start, and adds them to `all`. `false` when the pattern can't
1547/// be drawn.
1548fn dash_into(all: &mut PathBuilder, path: PathBuilder, length: f32, on: f32, off: f32) -> bool {
1549  let Some((on, off)) = fit_dash(length, on, off) else {
1550    return false;
1551  };
1552  let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], on / 2.0)) else {
1553    return false;
1554  };
1555  if let Some(dashes) = path.dash(&dash, 1.0) {
1556    all.push_path(&dashes);
1557  }
1558  true
1559}
1560
1561/// Where corner `index` of `rect`, from the top left clockwise, starts
1562/// and ends going clockwise, with its quarter circle's control points
1563/// between: `[start, one, two, end]`, all one point for a square corner.
1564fn corner(rect: tiny_skia::Rect, corners: Corners, index: usize) -> [tiny_skia::Point; 4] {
1565  // How far a cubic curve's control points sit along the tangents to
1566  // follow a quarter circle closely.
1567  const KAPPA: f32 = 0.552_284_8;
1568  let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1569  let radius = corners[index];
1570  let k = radius * (1.0 - KAPPA);
1571  let points = match index {
1572    0 => [(l, t + radius), (l, t + k), (l + k, t), (l + radius, t)],
1573    1 => [(r - radius, t), (r - k, t), (r, t + k), (r, t + radius)],
1574    2 => [(r, b - radius), (r, b - k), (r - k, b), (r - radius, b)],
1575    _ => [(l + radius, b), (l + k, b), (l, b - k), (l, b - radius)],
1576  };
1577  points.map(|(x, y)| tiny_skia::Point::from_xy(x, y))
1578}
1579
1580/// `corners` for a shadow's shape grown by `spread` pixels, or shrunk by
1581/// a negative one. As in CSS, a corner smaller than the spread grows by
1582/// less, so a square box keeps square corners.
1583fn spread_corners(corners: Corners, spread: f32) -> Corners {
1584  corners.map(|radius| {
1585    if spread > 0.0 && radius < spread {
1586      radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
1587    } else {
1588      (radius + spread).max(0.0)
1589    }
1590  })
1591}
1592
1593/// `corners` fitted to `area` as CSS fits them ([`Radii::fit`]).
1594fn fit(
1595  [top_left, top_right, bottom_right, bottom_left]: Corners,
1596  area: tiny_skia::Rect,
1597) -> Corners {
1598  let radii = Radii {
1599    top_left,
1600    top_right,
1601    bottom_right,
1602    bottom_left,
1603  };
1604  radii.fit(area.width(), area.height()).corners()
1605}
1606
1607/// `corners` for a shape `by` pixels inside the edge.
1608fn inset(corners: Corners, by: f32) -> Corners {
1609  corners.map(|radius| (radius - by).max(0.0))
1610}
1611
1612/// Adds a rectangle with circular `corners` to `path`, clockwise from
1613/// the end of its top-left one.
1614fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1615  if corners.iter().all(|&radius| radius <= 0.0) {
1616    path.push_rect(rect);
1617    return;
1618  }
1619  let [.., start] = corner(rect, corners, 0);
1620  path.move_to(start.x, start.y);
1621  for index in [1, 2, 3, 0] {
1622    let [start, one, two, end] = corner(rect, corners, index);
1623    path.line_to(start.x, start.y);
1624    if corners[index] > 0.0 {
1625      path.cubic_to(one.x, one.y, two.x, two.y, end.x, end.y);
1626    }
1627  }
1628  path.close();
1629}
1630
1631/// `a * b / 255`, rounded.
1632fn mul(a: u8, b: u8) -> u8 {
1633  ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1634}
1635
1636/// Blends a premultiplied `source` over the pixel at `index` (in bytes).
1637fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1638  let rest = 255 - source[3];
1639  for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1640    *channel = value.saturating_add(mul(*channel, rest));
1641  }
1642}
1643
1644/// The part of a `width` by `height` image placed at `left`, `top` that
1645/// lies inside the pixmap: the first and last column and row, as image
1646/// coordinates.
1647fn overlap(
1648  pixmap: &PixmapMut<'_>,
1649  left: i32,
1650  top: i32,
1651  width: u32,
1652  height: u32,
1653) -> Option<(usize, usize, usize, usize)> {
1654  let column_start = (-i64::from(left)).max(0);
1655  let row_start = (-i64::from(top)).max(0);
1656  let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1657  let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1658  (column_start < column_end && row_start < row_end).then_some((
1659    column_start as usize,
1660    column_end as usize,
1661    row_start as usize,
1662    row_end as usize,
1663  ))
1664}
1665
1666/// Blends a glyph's coverage mask in `color`.
1667fn blend_mask(
1668  pixmap: &mut PixmapMut<'_>,
1669  left: i32,
1670  top: i32,
1671  width: u32,
1672  height: u32,
1673  mask: &[u8],
1674  color: Color,
1675) {
1676  if mask.len() < width as usize * height as usize {
1677    return;
1678  }
1679  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1680  else {
1681    return;
1682  };
1683  let stride = pixmap.width() as usize;
1684  let data = pixmap.data_mut();
1685  for row in rows..rows_end {
1686    for column in columns..columns_end {
1687      let coverage = mask[row * width as usize + column];
1688      if coverage == 0 {
1689        continue;
1690      }
1691      let alpha = mul(color.a, coverage);
1692      let source = [
1693        mul(color.r, alpha),
1694        mul(color.g, alpha),
1695        mul(color.b, alpha),
1696        alpha,
1697      ];
1698      let x = (i64::from(left) + column as i64) as usize;
1699      let y = (i64::from(top) + row as i64) as usize;
1700      over(data, (y * stride + x) * 4, source);
1701    }
1702  }
1703}
1704
1705/// How many rows a point near a corner sums.
1706const SAMPLES: usize = 8;
1707
1708/// A rectangle with rounded corners blurred by a Gaussian: how much of it
1709/// covers each point. Away from the corners it is a plain rectangle,
1710/// whose blur is the product of each axis's, from the error function.
1711/// Near a corner, each row's span is blurred across and the rows are
1712/// summed over eight samples of the Gaussian down. Each corner has its
1713/// own radius; the largest says where the corners' rows begin.
1714struct BlurredBox {
1715  middle: (f32, f32),
1716  half: (f32, f32),
1717  corners: Corners,
1718  largest: f32,
1719  sigma: f32,
1720  /// What the samples sum to where the shape covers them all, a little
1721  /// under 1, so a point the shape covers whole is covered whole.
1722  whole: f32,
1723}
1724
1725impl BlurredBox {
1726  fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1727    let step = 6.0 * sigma / SAMPLES as f32;
1728    let whole = (0..SAMPLES)
1729      .map(|sample| gaussian(step * (sample as f32 + 0.5) - 3.0 * sigma, sigma) * step)
1730      .sum();
1731    BlurredBox {
1732      whole,
1733      middle: (
1734        (shape.left() + shape.right()) / 2.0,
1735        (shape.top() + shape.bottom()) / 2.0,
1736      ),
1737      half: (shape.width() / 2.0, shape.height() / 2.0),
1738      corners,
1739      largest: corners.into_iter().fold(0.0, f32::max),
1740      sigma,
1741    }
1742  }
1743
1744  /// Pushes the coverage at each of `xs` on the row at `y`, out of 255,
1745  /// onto `mask`.
1746  fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1747    let y = y - self.middle.1;
1748    let (half_width, half_height) = self.half;
1749    let reach = 3.0 * self.sigma;
1750    let down = self.along(y, half_height);
1751    let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1752    let rows = if clear_of_corners {
1753      [(0.0, 0.0, 0.0); SAMPLES]
1754    } else {
1755      self.rows_near(y)
1756    };
1757    for x in xs {
1758      let x = x - self.middle.0;
1759      let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1760        self.along(x, half_width) * down
1761      } else {
1762        let sum: f32 = rows
1763          .iter()
1764          .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1765          .sum();
1766        (sum / self.whole).clamp(0.0, 1.0)
1767      };
1768      mask.push((coverage * 255.0).round() as u8);
1769    }
1770  }
1771
1772  /// The blur of the span from `-half` to `half` at `p`.
1773  fn along(&self, p: f32, half: f32) -> f32 {
1774    self.between(p, half, half)
1775  }
1776
1777  /// The blur of the span from `-left` to `right` at `p`. One the blur
1778  /// stays inside of is covered whole.
1779  fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1780    let reach = 3.0 * self.sigma;
1781    if -(left - reach) <= p && p <= right - reach {
1782      return 1.0;
1783    }
1784    let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1785    0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1786  }
1787
1788  /// The rows of the shape a point at height `y` near a corner sums: for
1789  /// each sample within the shape and the Gaussian's reach, how far the
1790  /// row reaches left and right of the middle, and its weight.
1791  fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1792    let (half_width, half_height) = self.half;
1793    let reach = 3.0 * self.sigma;
1794    let start = (y - half_height).clamp(-reach, reach);
1795    let end = (y + half_height).clamp(-reach, reach);
1796    let step = (end - start) / SAMPLES as f32;
1797    std::array::from_fn(|sample| {
1798      let offset = start + step * (sample as f32 + 0.5);
1799      // How far into a corner's rows this one is, and how much it
1800      // narrows there.
1801      let row = y - offset;
1802      let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1803      let (left, right) = if row < 0.0 {
1804        (top_left, top_right)
1805      } else {
1806        (bottom_left, bottom_right)
1807      };
1808      let span = |radius: f32| {
1809        let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1810        half_width - radius
1811          + (radius * radius - into_corner * into_corner)
1812            .max(0.0)
1813            .sqrt()
1814      };
1815      (span(left), span(right), gaussian(offset, self.sigma) * step)
1816    })
1817  }
1818}
1819
1820/// The normal distribution's density at `x`, for a deviation of `sigma`.
1821fn gaussian(x: f32, sigma: f32) -> f32 {
1822  let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1823  (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1824}
1825
1826/// The error function, within 5e-4, an eighth of a color level, by
1827/// Abramowitz and Stegun's 7.1.27, which needs no exponential.
1828fn erf(x: f32) -> f32 {
1829  let a = x.abs();
1830  let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1831  let d = d * d;
1832  (1.0 - 1.0 / (d * d)).copysign(x)
1833}
1834
1835/// Whether a color glyph came from vector color layers (COLR), which swash
1836/// renders premultiplied, rather than an embedded bitmap, which it hands
1837/// over as stored: straight alpha.
1838///
1839/// cosmic-text doesn't re-export swash's `Source`, and swash isn't a
1840/// dependency of this crate, so the variant is read from its name.
1841fn is_color_outline(image: &SwashImage) -> bool {
1842  format!("{:?}", image.source).starts_with("ColorOutline")
1843}
1844
1845/// Blends a color glyph's RGBA pixels at `opacity` out of 255. `rgba` says
1846/// whether they are premultiplied already.
1847fn blend_rgba(
1848  pixmap: &mut PixmapMut<'_>,
1849  left: i32,
1850  top: i32,
1851  width: u32,
1852  height: u32,
1853  (rgba, premultiplied): (&[u8], bool),
1854  opacity: u8,
1855) {
1856  if rgba.len() < width as usize * height as usize * 4 {
1857    return;
1858  }
1859  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1860  else {
1861    return;
1862  };
1863  let stride = pixmap.width() as usize;
1864  let data = pixmap.data_mut();
1865  for row in rows..rows_end {
1866    for column in columns..columns_end {
1867      let index = (row * width as usize + column) * 4;
1868      let alpha = mul(rgba[index + 3], opacity);
1869      if alpha == 0 {
1870        continue;
1871      }
1872      // Premultiplied colors only need the opacity; straight ones need
1873      // their own alpha too.
1874      let factor = if premultiplied { opacity } else { alpha };
1875      let source = [
1876        mul(rgba[index], factor),
1877        mul(rgba[index + 1], factor),
1878        mul(rgba[index + 2], factor),
1879        alpha,
1880      ];
1881      let x = (i64::from(left) + column as i64) as usize;
1882      let y = (i64::from(top) + row as i64) as usize;
1883      over(data, (y * stride + x) * 4, source);
1884    }
1885  }
1886}
1887
1888/// Adds `contour` to `kept` when the box around its points reaches into
1889/// `near`, given as left, top, right and bottom.
1890fn keep_near(
1891  kept: &mut PathBuilder,
1892  contour: &[PathSegment],
1893  [left, top, right, bottom]: [f32; 4],
1894) {
1895  let (mut low, mut high) = (
1896    (f32::INFINITY, f32::INFINITY),
1897    (f32::NEG_INFINITY, f32::NEG_INFINITY),
1898  );
1899  let points = contour.iter().flat_map(|segment| match *segment {
1900    PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1901    PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1902    PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1903    PathSegment::Close => [None; 3],
1904  });
1905  for point in points.flatten() {
1906    low = (low.0.min(point.x), low.1.min(point.y));
1907    high = (high.0.max(point.x), high.1.max(point.y));
1908  }
1909  if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1910    return;
1911  }
1912  for segment in contour {
1913    match *segment {
1914      PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1915      PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1916      PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1917      PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1918      PathSegment::Close => kept.close(),
1919    }
1920  }
1921}
1922
1923/// A dash of `on` pixels and a gap of `off`, stretched or squeezed so a
1924/// whole number of them goes around `perimeter`, at least one. `None` for
1925/// a pattern that can't be drawn: a number that isn't finite or is
1926/// negative, no gap, or a period shorter than a pixel.
1927pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1928  let period = on + off;
1929  if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1930    return None;
1931  }
1932  let count = (perimeter / period).round().max(1.0);
1933  let stretch = perimeter / (count * period);
1934  Some((on * stretch, off * stretch))
1935}
1936
1937/// Fills `area` with the opaque `color` straight into the pixels, as
1938/// tiny-skia's path fill gives it, without its raster pipeline: a
1939/// window's background under a picture was half of a 1080p repaint.
1940/// `false`, drawing nothing, unless `color` is opaque and every edge is on
1941/// a whole pixel.
1942pub(crate) fn fill_opaque(pixmap: &mut PixmapMut<'_>, area: tiny_skia::Rect, color: Color) -> bool {
1943  let edges = [area.left(), area.top(), area.right(), area.bottom()];
1944  if color.a != 255 || edges.iter().any(|edge| edge.fract() != 0.0) {
1945    return false;
1946  }
1947  let (width, height) = (pixmap.width() as f32, pixmap.height() as f32);
1948  let [left, top, right, bottom] = [
1949    area.left().clamp(0.0, width),
1950    area.top().clamp(0.0, height),
1951    area.right().clamp(0.0, width),
1952    area.bottom().clamp(0.0, height),
1953  ]
1954  .map(|edge| edge as usize);
1955  let stride = pixmap.width() as usize * 4;
1956  let pixel = [color.r, color.g, color.b, 255];
1957  for row in pixmap
1958    .data_mut()
1959    .chunks_exact_mut(stride)
1960    .take(bottom)
1961    .skip(top)
1962  {
1963    row[left * 4..right * 4].as_chunks_mut::<4>().0.fill(pixel);
1964  }
1965  true
1966}