Skip to main content

crabshell_render/
draw.rs

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