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