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, SwashCache, SwashContent, SwashImage};
12use crabshell_ui::{
13  Affine, CaptureView, Color, Content, Gradient, GradientShape, IconView, ImageView, InputView,
14  NodeView, Rect, Shadow, Size, Style, TextSystem, TextView, WindowView,
15};
16use tiny_skia::{
17  FillRule, FilterQuality, GradientStop, LineCap, LineJoin, LinearGradient, Mask, Paint,
18  PathBuilder, PathSegment, Pixmap, PixmapMut, PixmapPaint, RadialGradient, Shader, SpreadMode,
19  Stroke, StrokeDash, SweepGradient, Transform,
20};
21
22use crate::damage::{BufferAge, DamageHistory, PixelRect};
23use crate::icons::{Drawn, Icons};
24
25mod canvas;
26mod effects;
27mod transition;
28
29/// The side of a tile, in buffer pixels. tiny-skia cuts a curve where it
30/// leaves the pixmap, which changes the antialiasing beside the cut, so
31/// every pixel is drawn in the same tile whatever the damage, and a repaint
32/// matches drawing everything.
33const TILE: u32 = 64;
34
35/// How many glyph images cosmic-text's cache may hold after a draw before
36/// it is cleared. A bar needs a few hundred; the cache never shrinks itself.
37const GLYPH_CACHE_LIMIT: usize = 2048;
38
39/// The most pixels a transformed layer may hold, 16 MiB. Only a widget
40/// shrunk to a sliver of its size, so that a tile shows much of it, comes
41/// near; past this it isn't drawn.
42const LAYER_LIMIT: u64 = 1 << 22;
43
44/// Buffer pixels a transformed layer reaches past what it samples, so the
45/// edges where tiny-skia cuts its curves stay out of the picture.
46const LAYER_MARGIN: f32 = 2.0;
47
48/// How a buffer stores each pixel, as `wl_shm` names the formats. Both are
49/// 32 bits per pixel with premultiplied alpha.
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum PixelFormat {
52  /// Bytes B, G, R, A in memory. Every compositor supports it.
53  Argb8888,
54  /// Bytes R, G, B, A in memory, as tiny-skia draws. Copied as is.
55  Abgr8888,
56}
57
58/// A buffer to draw a window into.
59pub struct Canvas<'a> {
60  /// The buffer's memory: `width * height` pixels of 4 bytes, row by row.
61  pub pixels: &'a mut [u8],
62  /// The width in pixels: the window's logical width times `scale`,
63  /// rounded halfway away from zero, as `wp_fractional_scale_v1` says.
64  /// The window's edge is drawn at the buffer's edge either way.
65  pub width: u32,
66  /// The height in pixels, likewise.
67  pub height: u32,
68  /// Physical pixels per logical pixel.
69  pub scale: f32,
70  /// How the buffer stores pixels.
71  pub format: PixelFormat,
72  /// The frame the buffer last held, updated by the draw.
73  pub age: &'a mut BufferAge,
74}
75
76/// Draws windows. One serves every window; it holds the glyph and icon
77/// caches.
78pub struct Renderer {
79  glyphs: SwashCache,
80  icons: Icons,
81  /// Where each tile is drawn before it is copied into the buffer, kept
82  /// between frames.
83  scratch: Vec<u8>,
84  work: Work,
85}
86
87/// What drawing has cost so far, for tests to check that a draw stays
88/// small.
89#[derive(Clone, Copy, Default)]
90#[cfg_attr(not(test), allow(dead_code, reason = "only tests read it"))]
91struct Work {
92  /// Pixels of opacity, clip and transform layers allocated.
93  layer_pixels: u64,
94  /// Nodes drawn.
95  nodes: u64,
96  /// Pixels of alpha content shadows were blurred over.
97  blurred: u64,
98}
99
100impl Renderer {
101  /// A renderer with empty caches, looking icons up in the `hicolor`
102  /// theme.
103  pub fn new() -> Renderer {
104    Renderer {
105      glyphs: SwashCache::new(),
106      icons: Icons::new(),
107      scratch: Vec::new(),
108      work: Work::default(),
109    }
110  }
111
112  /// The number of glyph images cached, for tests.
113  #[cfg(test)]
114  pub(crate) fn cached_glyphs(&self) -> usize {
115    self.glyphs.image_cache.len()
116  }
117
118  /// The pixels of opacity layers allocated and the nodes drawn so far,
119  /// for tests.
120  #[cfg(test)]
121  pub(crate) fn work(&self) -> (u64, u64, u64) {
122    (self.work.layer_pixels, self.work.nodes, self.work.blurred)
123  }
124
125  /// A renderer that looks icon names up in `bases` instead of the
126  /// environment's directories, for tests.
127  #[cfg(test)]
128  pub(crate) fn with_icon_dirs(bases: Vec<std::path::PathBuf>) -> Renderer {
129    Renderer {
130      icons: Icons::with_themes(crate::theme::Themes::new(bases)),
131      ..Renderer::new()
132    }
133  }
134
135  /// Sets the icon theme names are looked up in.
136  pub fn set_icon_theme(&mut self, theme: impl Into<String>) {
137    self.icons.set_theme(theme.into());
138  }
139
140  /// The number of rasterized icons cached, for tests.
141  #[cfg(test)]
142  pub(crate) fn cached_icons(&self) -> usize {
143    self.icons.cached()
144  }
145
146  /// The number of times an icon was rasterized, for tests.
147  #[cfg(test)]
148  pub(crate) fn rasterized_icons(&self) -> usize {
149    self.icons.rasterized()
150  }
151
152  /// Drops the scaled frames kept for screencopy views `gone`, at once:
153  /// each is as large as its view, and an idle shell may draw nothing
154  /// for a long while.
155  pub fn forget_captures(&mut self, gone: &[u64]) {
156    self.icons.forget_captures(gone);
157  }
158
159  /// When the next frame of an animated GIF is due, counting from `now`
160  /// for one drawn since the last call. `None` while no GIF drawn plays.
161  /// The platform wakes then and calls
162  /// [`advance_images`](Self::advance_images).
163  pub fn next_image_frame(&mut self, now: std::time::Instant) -> Option<std::time::Instant> {
164    self.icons.next_frame(now)
165  }
166
167  /// Moves each GIF whose next frame is due by `now` on to it, and returns
168  /// their image ids for the platform to repaint with
169  /// [`Window::repaint_image`](crabshell_ui::Window::repaint_image). A
170  /// GIF waits for its next frame only once that one is drawn, so one no
171  /// longer shown wakes nothing more.
172  pub fn advance_images(&mut self, now: std::time::Instant) -> Vec<u64> {
173    self.icons.advance(now)
174  }
175
176  /// The number of screencopy frames kept scaled, for tests.
177  #[cfg(test)]
178  pub(crate) fn cached_captures(&self) -> usize {
179    self.icons.captures()
180  }
181
182  /// Draws the laid-out window `view` into `canvas` and returns the areas
183  /// to report with `wl_surface.damage_buffer`.
184  ///
185  /// `damage` is what the window reported since the last draw, from
186  /// [`Window::take_damage`](crabshell_ui::Window::take_damage). The draw
187  /// repaints that, plus what changed in frames this buffer missed
188  /// according to `history`, or the whole buffer when that is more than
189  /// half of it or the buffer is new. Text and glyphs come from `text`.
190  ///
191  /// Commit the buffer after every successful draw, in order: the history
192  /// counts each one as a frame the compositor showed.
193  ///
194  /// # Errors
195  ///
196  /// If `canvas` holds the wrong number of bytes for its size, or its
197  /// scale isn't a positive number. Nothing is drawn and the history
198  /// doesn't advance.
199  pub fn draw(
200    &mut self,
201    view: &WindowView<'_>,
202    damage: &[Rect],
203    text: &mut TextSystem,
204    history: &mut DamageHistory,
205    canvas: Canvas<'_>,
206  ) -> Result<Vec<PixelRect>, CanvasError> {
207    let Canvas {
208      pixels,
209      width,
210      height,
211      scale,
212      format,
213      age,
214    } = canvas;
215    if pixels.len() as u64 != u64::from(width) * u64::from(height) * 4
216      || !(scale.is_finite() && scale > 0.0)
217    {
218      return Err(CanvasError {
219        width,
220        height,
221        scale,
222        bytes: pixels.len(),
223      });
224    }
225    self.icons.start_frame(history.id());
226    let plan = history.plan(damage, scale, width, height, age);
227    let mut tiles: Vec<(u32, u32)> = Vec::new();
228    for area in plan.repaint.iter().filter(|area| area.area() > 0) {
229      for row in area.y / TILE..=(area.y + area.height - 1) / TILE {
230        tiles
231          .extend((area.x / TILE..=(area.x + area.width - 1) / TILE).map(|column| (row, column)));
232      }
233    }
234    tiles.sort_unstable();
235    tiles.dedup();
236    let mut casts = HashMap::new();
237    for (row, column) in tiles {
238      let (x, y) = (column * TILE, row * TILE);
239      let size = (width.saturating_sub(x), height.saturating_sub(y));
240      let area = PixelRect::new(x, y, TILE.min(size.0), TILE.min(size.1));
241      self.scratch.clear();
242      self.scratch.resize(area.area() as usize * 4, 0);
243      let Some(mut pixmap) = PixmapMut::from_bytes(&mut self.scratch, area.width, area.height)
244      else {
245        continue;
246      };
247      let mut painter = Painter {
248        grid: Grid {
249          scale,
250          window: view.size(),
251          width,
252          height,
253          left: area.x as f32,
254          top: area.y as f32,
255        },
256        glyphs: &mut self.glyphs,
257        icons: &mut self.icons,
258        fonts: text.font_system(),
259        work: &mut self.work,
260        casts: &mut casts,
261      };
262      painter.node(&mut pixmap, view.root());
263      copy(&self.scratch, area, pixels, width, format);
264    }
265    self.icons.end_frame();
266    if self.glyphs.image_cache.len() > GLYPH_CACHE_LIMIT {
267      self.glyphs.image_cache.clear();
268      self.glyphs.outline_command_cache.clear();
269    }
270    Ok(plan.report)
271  }
272}
273
274/// A canvas whose bytes don't fit its size, or whose scale isn't a positive
275/// number.
276#[derive(Clone, Copy, Debug, PartialEq)]
277pub struct CanvasError {
278  /// The canvas's width in pixels.
279  pub width: u32,
280  /// The canvas's height in pixels.
281  pub height: u32,
282  /// The canvas's scale.
283  pub scale: f32,
284  /// How many bytes the canvas held.
285  pub bytes: usize,
286}
287
288impl std::fmt::Display for CanvasError {
289  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290    write!(
291      f,
292      "a {}x{} canvas at scale {} needs {} bytes, but has {}",
293      self.width,
294      self.height,
295      self.scale,
296      u64::from(self.width) * u64::from(self.height) * 4,
297      self.bytes
298    )
299  }
300}
301
302impl std::error::Error for CanvasError {}
303
304impl Default for Renderer {
305  fn default() -> Self {
306    Self::new()
307  }
308}
309
310/// Copies an area drawn in RGBA into the buffer, converting byte order.
311fn copy(scratch: &[u8], area: PixelRect, pixels: &mut [u8], width: u32, format: PixelFormat) {
312  let stride = width as usize * 4;
313  let row_bytes = area.width as usize * 4;
314  for (row, source) in scratch.chunks_exact(row_bytes).enumerate() {
315    let start = (area.y as usize + row) * stride + area.x as usize * 4;
316    let target = &mut pixels[start..start + row_bytes];
317    match format {
318      PixelFormat::Abgr8888 => target.copy_from_slice(source),
319      PixelFormat::Argb8888 => {
320        let (to, _) = target.as_chunks_mut::<4>();
321        let (from, _) = source.as_chunks::<4>();
322        for (to, from) in to.iter_mut().zip(from) {
323          *to = [from[2], from[1], from[0], from[3]];
324        }
325      }
326    }
327  }
328}
329
330/// Turns logical coordinates into pixels of the area being drawn.
331#[derive(Clone, Copy)]
332struct Grid {
333  scale: f32,
334  /// The window's logical size.
335  window: Size,
336  /// The buffer's size in pixels.
337  width: u32,
338  height: u32,
339  /// Where the area being drawn starts in the buffer.
340  left: f32,
341  top: f32,
342}
343
344impl Grid {
345  /// A logical x coordinate on the pixel grid. The window's right edge is
346  /// the buffer's, even where rounding would leave a column out.
347  fn x(&self, x: f32) -> f32 {
348    let pixel = if x >= self.window.width {
349      self.width as f32
350    } else {
351      (x * self.scale).round()
352    };
353    pixel - self.left
354  }
355
356  /// A logical y coordinate on the pixel grid, likewise.
357  fn y(&self, y: f32) -> f32 {
358    let pixel = if y >= self.window.height {
359      self.height as f32
360    } else {
361      (y * self.scale).round()
362    };
363    pixel - self.top
364  }
365
366  /// The pixels of a `width` by `height` area that `rect`, in logical
367  /// pixels, touches: rounded outward, a pixel added around for
368  /// antialiasing, and cut to the area. `None` if it misses the area.
369  fn cover(&self, rect: Rect, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
370    if !(rect.width > 0.0 && rect.height > 0.0) {
371      return None;
372    }
373    // `as` saturates, so huge or negative values stay in range.
374    let left = ((rect.x * self.scale).floor() - self.left - 1.0).max(0.0) as u32;
375    let top = ((rect.y * self.scale).floor() - self.top - 1.0).max(0.0) as u32;
376    let right = (((rect.right() * self.scale).ceil() - self.left + 1.0).max(0.0) as u32).min(width);
377    let bottom =
378      (((rect.bottom() * self.scale).ceil() - self.top + 1.0).max(0.0) as u32).min(height);
379    (left < right && top < bottom).then(|| (left, top, right - left, bottom - top))
380  }
381
382  /// This grid for a pixmap placed at `x`, `y` within this one.
383  fn moved(&self, x: u32, y: u32) -> Grid {
384    Grid {
385      left: self.left + x as f32,
386      top: self.top + y as f32,
387      ..*self
388    }
389  }
390
391  /// A logical rectangle on the pixel grid, or `None` if it covers no
392  /// pixel.
393  fn rect(&self, rect: Rect) -> Option<tiny_skia::Rect> {
394    tiny_skia::Rect::from_ltrb(
395      self.x(rect.x),
396      self.y(rect.y),
397      self.x(rect.right()),
398      self.y(rect.bottom()),
399    )
400    .filter(|rect| rect.width() >= 1.0 && rect.height() >= 1.0)
401  }
402}
403
404/// What drawing needs besides the pixmap.
405struct Painter<'a> {
406  grid: Grid,
407  glyphs: &'a mut SwashCache,
408  icons: &'a mut Icons,
409  fonts: &'a mut FontSystem,
410  work: &'a mut Work,
411  /// The cells of content shadows cast in this draw.
412  casts: &'a mut HashMap<CastKey, effects::Cast>,
413}
414
415/// A cell of a content shadow cast in a draw: its widget's path, and the
416/// cell's column and row.
417type CastKey = (String, i64, i64);
418
419impl Painter<'_> {
420  /// A painter for a pixmap on `grid`, in the same space.
421  fn on(&mut self, grid: Grid) -> Painter<'_> {
422    Painter {
423      grid,
424      glyphs: &mut *self.glyphs,
425      icons: &mut *self.icons,
426      fonts: &mut *self.fonts,
427      work: &mut *self.work,
428      casts: &mut *self.casts,
429    }
430  }
431
432  /// Draws `node` and everything inside it. With an opacity below 1, a
433  /// mask or a content shadow, they are drawn into one layer first, which
434  /// is masked, given its shadow and blended in at that opacity, so
435  /// overlapping children don't show through each other.
436  fn node(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>) {
437    // Nothing the node or its descendants paint reaches this area.
438    let Some((x, y, width, height)) =
439      self
440        .grid
441        .cover(node.bounds(), pixmap.width(), pixmap.height())
442    else {
443      return;
444    };
445    let style = node.style();
446    let opacity = style.opacity.unwrap_or(1.0);
447    let opacity = if opacity.is_nan() {
448      1.0
449    } else {
450      opacity.clamp(0.0, 1.0)
451    };
452    if opacity == 0.0 {
453      return;
454    }
455    let shadow = effects::cast_by_content(&style);
456    if let Some(transform) = node.transform() {
457      self.transformed(pixmap, node, &style, transform, opacity);
458    } else if opacity < 1.0 || style.mask.is_some() || shadow.is_some() {
459      // The layer covers only what the subtree paints in this area.
460      let Some(mut layer) = Pixmap::new(width, height) else {
461        return;
462      };
463      self.work.layer_pixels += u64::from(layer.width()) * u64::from(layer.height());
464      let mut inner = self.on(self.grid.moved(x, y));
465      inner.layer_contents(&mut layer.as_mut(), node, &style, shadow);
466      let paint = PixmapPaint {
467        opacity,
468        ..PixmapPaint::default()
469      };
470      let (x, y) = (x as i32, y as i32);
471      pixmap.draw_pixmap(x, y, layer.as_ref(), &paint, Transform::identity(), None);
472    } else {
473      self.node_contents(pixmap, node, &style);
474    }
475  }
476
477  /// What `node_contents` draws into a fresh `layer`, kept only where the
478  /// style's mask is opaque, with `shadow` cast by what is left put under
479  /// it.
480  fn layer_contents(
481    &mut self,
482    layer: &mut PixmapMut<'_>,
483    node: NodeView<'_>,
484    style: &Style,
485    shadow: Option<Shadow>,
486  ) {
487    self.node_contents(layer, node, style);
488    if let Some(mask) = &style.mask {
489      self.mask(layer, node.rect(), mask);
490    }
491    if let Some(shadow) = shadow {
492      self.content_shadow(layer, node, &shadow);
493    }
494  }
495
496  /// Draws `node` and everything inside it into a layer in its own
497  /// coordinates, then blends that in through its `transform`, filtered
498  /// bilinearly, at `opacity`: one layer for both. The layer covers only
499  /// what lands in this pixmap, in the node's own buffer pixels, so a
500  /// pixel is always drawn the same way in the same tile.
501  fn transformed(
502    &mut self,
503    pixmap: &mut PixmapMut<'_>,
504    node: NodeView<'_>,
505    style: &Style,
506    transform: Affine,
507    opacity: f32,
508  ) {
509    let Affine {
510      sx,
511      ky,
512      kx,
513      sy,
514      tx,
515      ty,
516    } = transform;
517    let Grid {
518      scale, left, top, ..
519    } = self.grid;
520    // From the node's own buffer pixels to its parent's.
521    let device = Transform::from_scale(scale, scale)
522      .pre_concat(Transform::from_row(sx, ky, kx, sy, tx, ty))
523      .pre_scale(1.0 / scale, 1.0 / scale);
524    let to_pixmap = device.post_translate(-left, -top);
525    let Some(back) = to_pixmap.invert() else {
526      return;
527    };
528    let inner = node.inner_bounds();
529    let shown = tiny_skia::Rect::from_xywh(0.0, 0.0, pixmap.width() as f32, pixmap.height() as f32)
530      .and_then(|rect| rect.transform(back));
531    let drawn = tiny_skia::Rect::from_xywh(
532      inner.x * scale,
533      inner.y * scale,
534      inner.width * scale,
535      inner.height * scale,
536    );
537    let Some(area) = shown
538      .zip(drawn)
539      .and_then(|(shown, drawn)| shown.intersect(&drawn))
540      .and_then(|area| area.outset(LAYER_MARGIN, LAYER_MARGIN))
541      .and_then(|area| area.round_out())
542    else {
543      return;
544    };
545    let pixels = u64::from(area.width()) * u64::from(area.height());
546    if pixels > LAYER_LIMIT {
547      tracing::debug!(
548        "{} is transformed into a layer too large to draw",
549        node.path()
550      );
551      return;
552    }
553    let Some(mut layer) = Pixmap::new(area.width(), area.height()) else {
554      return;
555    };
556    self.work.layer_pixels += pixels;
557    let (x, y) = (area.x() as f32, area.y() as f32);
558    let mut inner = self.on(Grid {
559      left: x,
560      top: y,
561      ..self.grid
562    });
563    let shadow = effects::cast_by_content(style);
564    inner.layer_contents(&mut layer.as_mut(), node, style, shadow);
565    let paint = PixmapPaint {
566      opacity,
567      quality: FilterQuality::Bilinear,
568      ..PixmapPaint::default()
569    };
570    pixmap.draw_pixmap(
571      0,
572      0,
573      layer.as_ref(),
574      &paint,
575      to_pixmap.pre_translate(x, y),
576      None,
577    );
578  }
579
580  fn node_contents(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
581    self.work.nodes += 1;
582    // A content shadow is cast by the layer this is drawn into.
583    if let Some(shadow) = style.shadow.filter(|shadow| !shadow.follow_content) {
584      self.shadow(pixmap, node.rect(), style, &shadow);
585    }
586    self.draw_box(pixmap, node.rect(), style);
587    match node.content() {
588      Content::Text(text) => self.text(pixmap, &text),
589      Content::Icon(icon) => self.icon(pixmap, &icon),
590      Content::Image(image) => self.image(pixmap, &image),
591      Content::Capture(capture) => self.capture(pixmap, &capture),
592      Content::Input(input) => self.input(pixmap, &input),
593      Content::Canvas(canvas) => self.canvas(pixmap, &canvas, style),
594      Content::None => {}
595    }
596    if node.clips() {
597      self.clipped_children(pixmap, node, style);
598    } else {
599      for child in node.children() {
600        self.node(pixmap, child);
601      }
602    }
603  }
604
605  /// `node`'s children, drawn into a layer that is blended in through a
606  /// mask of the inside of the node's border. The mask is drawn in the
607  /// area's own pixels, on the same fixed grid as everything else, so a
608  /// repaint cuts every edge exactly as a full draw does.
609  fn clipped_children(&mut self, pixmap: &mut PixmapMut<'_>, node: NodeView<'_>, style: &Style) {
610    let Some((area, corners)) = self.box_shape(node.rect(), style) else {
611      return;
612    };
613    let width = self.border_width(style);
614    let Some(inside) = tiny_skia::Rect::from_ltrb(
615      area.left() + width,
616      area.top() + width,
617      area.right() - width,
618      area.bottom() - width,
619    ) else {
620      return;
621    };
622    let corners = inset(corners, width);
623    self.through_mask(pixmap, node.rect(), (inside, corners), |painter, layer| {
624      for child in node.children() {
625        painter.node(layer, child);
626      }
627      // A scroll view always clips; its bar is cut to its corners too.
628      if let Some((handle, bar)) = node.scroll_bar() {
629        painter.draw_box(layer, handle, &bar);
630      }
631    });
632  }
633
634  /// What `draw` paints within `cover`, a logical rectangle, blended in
635  /// through a mask of `shape`, a pixel rectangle with rounded corners.
636  fn through_mask(
637    &mut self,
638    pixmap: &mut PixmapMut<'_>,
639    cover: Rect,
640    (shape, corners): (tiny_skia::Rect, Corners),
641    draw: impl FnOnce(&mut Painter<'_>, &mut PixmapMut<'_>),
642  ) {
643    if !visible(pixmap, shape) {
644      return;
645    }
646    let (Some(mut mask), Some((x, y, layer_width, layer_height))) = (
647      Mask::new(pixmap.width(), pixmap.height()),
648      self.grid.cover(cover, pixmap.width(), pixmap.height()),
649    ) else {
650      return;
651    };
652    let Some(mut layer) = Pixmap::new(layer_width, layer_height) else {
653      return;
654    };
655    self.work.layer_pixels += u64::from(layer_width) * u64::from(layer_height);
656    let mut inner = self.on(self.grid.moved(x, y));
657    draw(&mut inner, &mut layer.as_mut());
658    let mut path = PathBuilder::new();
659    rounded_rect(&mut path, shape, corners);
660    let Some(path) = path.finish() else {
661      return;
662    };
663    mask.fill_path(&path, FillRule::Winding, true, Transform::identity());
664    pixmap.draw_pixmap(
665      x as i32,
666      y as i32,
667      layer.as_ref(),
668      &PixmapPaint::default(),
669      Transform::identity(),
670      Some(&mask),
671    );
672  }
673
674  /// A widget's rectangle on the pixel grid and each corner's radius in
675  /// pixels, clamped to half the shorter side, so two on one side never
676  /// overlap. `None` if it covers no pixel.
677  fn box_shape(&self, rect: Rect, style: &Style) -> Option<(tiny_skia::Rect, Corners)> {
678    let area = self.grid.rect(rect)?;
679    let most = area.width().min(area.height()) / 2.0;
680    let corners = style.radius.unwrap_or_default().corners().map(|radius| {
681      let radius = (radius * self.grid.scale).clamp(0.0, most);
682      if radius.is_nan() { 0.0 } else { radius }
683    });
684    Some((area, corners))
685  }
686
687  /// The border's width in pixels: as in CSS, rounded down to whole
688  /// pixels, but at least one. 0 without a border.
689  fn border_width(&self, style: &Style) -> f32 {
690    let Some(border) = style.border else {
691      return 0.0;
692    };
693    let width = (border.width * self.grid.scale).floor();
694    if border.width > 0.0 {
695      width.max(1.0)
696    } else {
697      width.max(0.0)
698    }
699  }
700
701  /// The background and border of a widget's rectangle.
702  fn draw_box(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style) {
703    if style.background.is_none() && style.gradient.is_none() && style.border.is_none() {
704      return;
705    }
706    let Some((area, corners)) = self.box_shape(rect, style) else {
707      return;
708    };
709    if !visible(pixmap, area) {
710      return;
711    }
712
713    if let Some(color) = style.background {
714      let mut path = PathBuilder::new();
715      rounded_rect(&mut path, area, corners);
716      fill(pixmap, path, color, FillRule::Winding);
717    }
718    if let Some(gradient) = style.gradient {
719      let mut path = PathBuilder::new();
720      rounded_rect(&mut path, area, corners);
721      if let (Some(path), Some(shader)) = (path.finish(), self.shader(&gradient, area)) {
722        let paint = Paint {
723          shader,
724          anti_alias: true,
725          ..Paint::default()
726        };
727        pixmap.fill_path(
728          &path,
729          &paint,
730          FillRule::Winding,
731          Transform::identity(),
732          None,
733        );
734      }
735    }
736    if let Some(border) = style.border {
737      let width = self.border_width(style);
738      let dashed = width >= 1.0
739        && style.border_dash.is_some_and(|dash| {
740          self.dashed_border(pixmap, (area, corners), width, border.color, dash)
741        });
742
743      if width >= 1.0 && !dashed {
744        // A ring: the outer shape with the inner one cut out.
745        let mut path = PathBuilder::new();
746        rounded_rect(&mut path, area, corners);
747        if let Some(inner) = tiny_skia::Rect::from_ltrb(
748          area.left() + width,
749          area.top() + width,
750          area.right() - width,
751          area.bottom() - width,
752        ) {
753          rounded_rect(&mut path, inner, inset(corners, width));
754        }
755        fill(pixmap, path, border.color, FillRule::EvenOdd);
756      }
757    }
758  }
759
760  /// A border `width` pixels wide inside `area`, dashed by `on` and `off`
761  /// logical pixels along its middle line, so the dashes follow the
762  /// corners. The line is laid out and dashed in buffer pixels and moved
763  /// onto the pixmap, so tiles cut the dashes in the same places. `false`
764  /// when the pattern or the box can't take dashes, to draw it solid.
765  fn dashed_border(
766    &self,
767    pixmap: &mut PixmapMut<'_>,
768    (area, corners): (tiny_skia::Rect, Corners),
769    width: f32,
770    color: Color,
771    (on, off): (f32, f32),
772  ) -> bool {
773    let Grid {
774      scale, left, top, ..
775    } = self.grid;
776    let half = width / 2.0;
777    let Some(middle) = tiny_skia::Rect::from_ltrb(
778      area.left() + left + half,
779      area.top() + top + half,
780      area.right() + left - half,
781      area.bottom() + top - half,
782    ) else {
783      return false;
784    };
785    let corners = inset(corners, half);
786    // Each corner trades two radii of straight line for a quarter circle.
787    let rounding: f32 = corners
788      .iter()
789      .map(|radius| (2.0 - std::f32::consts::FRAC_PI_2) * radius)
790      .sum();
791    let perimeter = 2.0 * (middle.width() + middle.height()) - rounding;
792    let Some((on, off)) = fit_dash(perimeter, on * scale, off * scale) else {
793      return false;
794    };
795    let mut path = PathBuilder::new();
796    rounded_rect(&mut path, middle, corners);
797    // The line starts at the end of the top-left corner. A dash centered
798    // there runs across the start, so tiny-skia joins its two halves
799    // with a miter, and a square corner there is filled, as CSS draws it.
800    let phase = on / 2.0;
801    let (Some(path), Some(dash)) = (path.finish(), StrokeDash::new(vec![on, off], phase)) else {
802      return false;
803    };
804    let Some(dashes) = path.dash(&dash, 1.0) else {
805      return true;
806    };
807    // Every tile the border crosses would stroke every dash, so only the
808    // dashes near this one are kept. A closed outline that misses the
809    // tile adds nothing inside it, so the pixels are the same. A miter
810    // reaches at most twice the width past its line.
811    let reach = 2.0 * width + 1.0;
812    let near = [
813      left - reach,
814      top - reach,
815      left + pixmap.width() as f32 + reach,
816      top + pixmap.height() as f32 + reach,
817    ];
818    let mut kept = PathBuilder::new();
819    let mut contour = Vec::new();
820    for segment in dashes.segments() {
821      if matches!(segment, PathSegment::MoveTo(_)) {
822        keep_near(&mut kept, &contour, near);
823        contour.clear();
824      }
825      contour.push(segment);
826    }
827    keep_near(&mut kept, &contour, near);
828    let Some(kept) = kept.finish() else {
829      return true;
830    };
831    let stroke = Stroke {
832      width,
833      // A dash of 0 is a dot.
834      line_cap: if on == 0.0 {
835        LineCap::Round
836      } else {
837        LineCap::Butt
838      },
839      line_join: LineJoin::Miter,
840      ..Stroke::default()
841    };
842    let mut paint = Paint::default();
843    paint.set_color_rgba8(color.r, color.g, color.b, color.a);
844    paint.anti_alias = true;
845    let moved = Transform::from_translate(-left, -top);
846    pixmap.stroke_path(&kept, &paint, &stroke, moved, None);
847    true
848  }
849
850  /// `shadow` of the box `rect` with `style`'s corners. A sharp one is a
851  /// filled shape; a blurred one is worked out pixel by pixel in buffer
852  /// pixels, so every tile agrees, and only within one and a half blurs
853  /// of its shape, past which it fades below a 255th.
854  fn shadow(&self, pixmap: &mut PixmapMut<'_>, rect: Rect, style: &Style, shadow: &Shadow) {
855    let Grid {
856      scale, left, top, ..
857    } = self.grid;
858    let numbers = [shadow.x, shadow.y, shadow.blur, shadow.spread];
859    if shadow.color.a == 0 || !numbers.iter().all(|n| n.is_finite()) {
860      return;
861    }
862    let Some((area, corners)) = self.box_shape(rect, style) else {
863      return;
864    };
865    // The shape in buffer pixels.
866    let spread = shadow.spread * scale;
867    let Some(shape) = tiny_skia::Rect::from_ltrb(
868      area.left() + left + shadow.x * scale - spread,
869      area.top() + top + shadow.y * scale - spread,
870      area.right() + left + shadow.x * scale + spread,
871      area.bottom() + top + shadow.y * scale + spread,
872    ) else {
873      return;
874    };
875    // As CSS: a corner smaller than the spread grows by less, so a square
876    // box keeps square corners.
877    let most = shape.width().min(shape.height()) / 2.0;
878    let corners = corners.map(|radius| {
879      let radius = if spread > 0.0 && radius < spread {
880        radius + spread * (1.0 + (radius / spread - 1.0).powi(3))
881      } else {
882        radius + spread
883      };
884      radius.clamp(0.0, most)
885    });
886    // A cut-out shadow leaves clear what the box's background covers.
887    let cut = if shadow.cut_out {
888      self.box_mask(pixmap, rect, style)
889    } else {
890      None
891    };
892    // CSS draws a blur as a Gaussian of half its length.
893    let sigma = shadow.blur.max(0.0) * scale / 2.0;
894    if sigma < 0.25 {
895      let mut path = PathBuilder::new();
896      let Some(shape) = shape.transform(Transform::from_translate(-left, -top)) else {
897        return;
898      };
899      rounded_rect(&mut path, shape, corners);
900      let Some(path) = path.finish() else {
901        return;
902      };
903      let mut paint = Paint::default();
904      let color = shadow.color;
905      paint.set_color_rgba8(color.r, color.g, color.b, color.a);
906      paint.anti_alias = true;
907      let outside = cut.map(|mut cut| {
908        cut.invert();
909        cut
910      });
911      let (rule, at) = (FillRule::Winding, Transform::identity());
912      pixmap.fill_path(&path, &paint, rule, at, outside.as_ref());
913      return;
914    }
915    let reach = 3.0 * sigma;
916    let columns = (shape.left() - reach - left).floor().max(0.0) as u32
917      ..((shape.right() + reach - left).ceil().max(0.0) as u32).min(pixmap.width());
918    let rows = (shape.top() - reach - top).floor().max(0.0) as u32
919      ..((shape.bottom() + reach - top).ceil().max(0.0) as u32).min(pixmap.height());
920    if columns.is_empty() || rows.is_empty() {
921      return;
922    }
923    let blurred = BlurredBox::new(shape, corners, sigma);
924    let mut mask = Vec::with_capacity(columns.len() * rows.len());
925    for row in rows.clone() {
926      let xs = columns.clone().map(|column| left + column as f32 + 0.5);
927      blurred.row(top + row as f32 + 0.5, xs, &mut mask);
928    }
929    if let Some(cut) = cut {
930      let stride = pixmap.width() as usize;
931      let under = rows.clone().flat_map(|row| {
932        columns
933          .clone()
934          .map(move |column| row as usize * stride + column as usize)
935      });
936      for (alpha, at) in mask.iter_mut().zip(under) {
937        *alpha = mul(*alpha, 255 - cut.data()[at]);
938      }
939    }
940    let width = columns.len() as u32;
941    let height = rows.len() as u32;
942    let (x, y) = (columns.start as i32, rows.start as i32);
943    blend_mask(pixmap, x, y, width, height, &mask, shadow.color);
944  }
945
946  /// How much of each of this pixmap's pixels the box `rect` with
947  /// `style`'s corners covers, as its background fills it.
948  fn box_mask(&self, pixmap: &PixmapMut<'_>, rect: Rect, style: &Style) -> Option<Mask> {
949    let (area, corners) = self.box_shape(rect, style)?;
950    let mut path = PathBuilder::new();
951    rounded_rect(&mut path, area, corners);
952    let mut mask = Mask::new(pixmap.width(), pixmap.height())?;
953    let (rule, at) = (FillRule::Winding, Transform::identity());
954    mask.fill_path(&path.finish()?, rule, true, at);
955    Some(mask)
956  }
957
958  /// `gradient` across `area`, a box in this pixmap's pixels. It is laid
959  /// out in buffer pixels and moved onto the pixmap, so every tile works
960  /// out the same color for a pixel.
961  fn shader(&self, gradient: &Gradient, area: tiny_skia::Rect) -> Option<Shader<'static>> {
962    let (left, top) = (area.left() + self.grid.left, area.top() + self.grid.top);
963    let (width, height) = (area.width(), area.height());
964    let middle = tiny_skia::Point::from_xy(left + width / 2.0, top + height / 2.0);
965    let given = gradient.stops();
966    let mut stops = Vec::with_capacity(given.len() * 2);
967    let stop = |at: f32, color: Color, alpha: u8| {
968      GradientStop::new(
969        at,
970        tiny_skia::Color::from_rgba8(color.r, color.g, color.b, alpha),
971      )
972    };
973    for (index, &(at, color)) in given.iter().enumerate() {
974      if color.a > 0 {
975        stops.push(stop(at, color, color.a));
976        continue;
977      }
978      // tiny-skia blends colors before their alpha, so a clear stop
979      // would fade through its own color. As in CSS, each side fades
980      // out in its neighbor's.
981      for neighbor in [index.checked_sub(1), Some(index + 1)]
982        .into_iter()
983        .flatten()
984      {
985        if let Some(&(_, near)) = given.get(neighbor) {
986          stops.push(stop(at, near, 0));
987        }
988      }
989    }
990    let moved = Transform::from_translate(-self.grid.left, -self.grid.top);
991    match gradient.shape {
992      GradientShape::Linear(angle) => {
993        // As CSS: 0 degrees points up, and the line is long enough for
994        // its ends to meet the corners.
995        let (sin, cos) = angle.to_radians().sin_cos();
996        let half = (width * sin.abs() + height * cos.abs()) / 2.0;
997        let (dx, dy) = (sin * half, -cos * half);
998        let start = tiny_skia::Point::from_xy(middle.x - dx, middle.y - dy);
999        let end = tiny_skia::Point::from_xy(middle.x + dx, middle.y + dy);
1000        LinearGradient::new(start, end, stops, SpreadMode::Pad, moved)
1001      }
1002      GradientShape::Radial => {
1003        let reach = (width * width + height * height).sqrt() / 2.0;
1004        RadialGradient::new(middle, 0.0, middle, reach, stops, SpreadMode::Pad, moved)
1005      }
1006      GradientShape::Sweep(angle) => {
1007        // As CSS: 0 degrees points up and the colors go clockwise.
1008        // tiny-skia's start at 3 o'clock, and it skips a start angle
1009        // other than 0 when the sweep is a whole turn, so it is turned.
1010        let turn = Transform::from_rotate_at(angle - 90.0, middle.x, middle.y);
1011        let at = moved.pre_concat(turn);
1012        SweepGradient::new(middle, 0.0, 360.0, stops, SpreadMode::Pad, at)
1013      }
1014    }
1015  }
1016
1017  /// Glyphs, drawn as masks in the text's color. The baseline sits on a
1018  /// whole pixel so horizontal strokes stay sharp; glyphs keep their
1019  /// sub-pixel horizontal position.
1020  fn text(&mut self, pixmap: &mut PixmapMut<'_>, text: &TextView<'_>) {
1021    let color = text.color();
1022    if color.a == 0 {
1023      return;
1024    }
1025    let Grid {
1026      scale, left, top, ..
1027    } = self.grid;
1028    let origin = text.origin();
1029    let x = origin.x * scale - left;
1030    for run in text.runs() {
1031      // Rounded in buffer coordinates, so every area drawn agrees.
1032      let baseline = ((origin.y + run.line_y) * scale).round() - top;
1033      if baseline + run.line_height * scale < 0.0
1034        || baseline - run.line_height * scale > pixmap.height() as f32
1035      {
1036        continue;
1037      }
1038      for glyph in run.glyphs {
1039        let physical = glyph.physical((x, baseline), scale);
1040        let Some(image) = self.glyphs.get_image(self.fonts, physical.cache_key) else {
1041          continue;
1042        };
1043        let left = physical.x + image.placement.left;
1044        let top = physical.y - image.placement.top;
1045        let (width, height) = (image.placement.width, image.placement.height);
1046        match image.content {
1047          SwashContent::Mask => {
1048            blend_mask(pixmap, left, top, width, height, &image.data, color);
1049          }
1050          SwashContent::Color => {
1051            let premultiplied = is_color_outline(image);
1052            let rgba = (image.data.as_slice(), premultiplied);
1053            blend_rgba(pixmap, left, top, width, height, rgba, color.a);
1054          }
1055          // Not requested: there is no subpixel antialiasing.
1056          SwashContent::SubpixelMask => {}
1057        }
1058      }
1059    }
1060  }
1061
1062  /// A text field, cut to its content box.
1063  fn input(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1064    let Some(area) = self.grid.rect(input.area) else {
1065      return;
1066    };
1067    self.through_mask(pixmap, input.area, (area, [0.0; 4]), |painter, layer| {
1068      painter.input_contents(layer, input);
1069    });
1070  }
1071
1072  /// A field's selection in a third of the text's color, the text, and a
1073  /// caret in the text's color.
1074  fn input_contents(&mut self, pixmap: &mut PixmapMut<'_>, input: &InputView<'_>) {
1075    let color = input.text.color();
1076    for selection in input.selection {
1077      let Some(area) = self.grid.rect(*selection) else {
1078        continue;
1079      };
1080      let mut path = PathBuilder::new();
1081      path.push_rect(area);
1082      let tint = Color::rgba(color.r, color.g, color.b, color.a / 3);
1083      fill(pixmap, path, tint, FillRule::Winding);
1084    }
1085    self.text(pixmap, &input.text);
1086    for line in input.underline {
1087      if let Some(area) = self.grid.rect(*line) {
1088        let mut path = PathBuilder::new();
1089        path.push_rect(area);
1090        fill(pixmap, path, color, FillRule::Winding);
1091      }
1092    }
1093    if let Some(caret) = input.caret {
1094      // At least one pixel wide whatever the scale.
1095      let left = self.grid.x(caret.x);
1096      let right = self.grid.x(caret.right()).max(left + 1.0);
1097      if let Some(area) = tiny_skia::Rect::from_ltrb(
1098        left,
1099        self.grid.y(caret.y),
1100        right,
1101        self.grid.y(caret.bottom()),
1102      ) {
1103        let mut path = PathBuilder::new();
1104        path.push_rect(area);
1105        fill(pixmap, path, color, FillRule::Winding);
1106      }
1107    }
1108  }
1109
1110  /// An image, scaled to its box in pixels.
1111  fn image(&mut self, pixmap: &mut PixmapMut<'_>, image: &ImageView<'_>) {
1112    let Some((x, y, width, height)) = self.picture_area(pixmap, image.rect) else {
1113      return;
1114    };
1115    match self.icons.image(image, (width, height), self.grid.scale) {
1116      Some(Drawn::One(pixels)) => transition::blit(pixmap, (x, y), pixels),
1117      Some(Drawn::Two { from, to, t }) => {
1118        transition::draw(pixmap, (x, y), from, to, t, image.transition);
1119      }
1120      None => {}
1121    }
1122  }
1123
1124  /// A screencopy view's frame, scaled to its box in pixels.
1125  fn capture(&mut self, pixmap: &mut PixmapMut<'_>, capture: &CaptureView<'_>) {
1126    let Some((x, y, width, height)) = self.picture_area(pixmap, capture.rect) else {
1127      return;
1128    };
1129    let frame = capture.frame;
1130    if let Some(pixels) = self
1131      .icons
1132      .capture(capture.id, frame, width, height, capture.fit)
1133    {
1134      draw_at(pixmap, x, y, pixels);
1135    }
1136  }
1137
1138  /// Where a picture in `rect` goes in the pixmap, and its size in
1139  /// pixels; `None` if it covers no pixel of it. Placed and sized apart,
1140  /// as an icon is, so a picture past the window's edge is cut there
1141  /// instead of squeezed inside it.
1142  fn picture_area(&self, pixmap: &PixmapMut<'_>, rect: Rect) -> Option<(i32, i32, u32, u32)> {
1143    let Grid {
1144      scale, left, top, ..
1145    } = self.grid;
1146    let (width, height) = ((rect.width * scale).round(), (rect.height * scale).round());
1147    let (x, y) = (
1148      (rect.x * scale).round() - left,
1149      (rect.y * scale).round() - top,
1150    );
1151    if !(width >= 1.0 && height >= 1.0) {
1152      return None;
1153    }
1154    let area = tiny_skia::Rect::from_xywh(x, y, width, height)?;
1155    // `as` saturates, so a huge box stays in range.
1156    visible(pixmap, area).then_some((x as i32, y as i32, width as u32, height as u32))
1157  }
1158
1159  /// An icon, rasterized at its size in pixels.
1160  fn icon(&mut self, pixmap: &mut PixmapMut<'_>, icon: &IconView<'_>) {
1161    let Grid {
1162      scale, left, top, ..
1163    } = self.grid;
1164    let side = (icon.rect.width * scale).round();
1165    if side.is_nan() || side < 1.0 {
1166      return;
1167    }
1168    let x = (icon.rect.x * scale).round() - left;
1169    let y = (icon.rect.y * scale).round() - top;
1170    // Theme directories come in whole scales; 1.5 looks for @2 icons.
1171    let size = icon.rect.width.round() as u32;
1172    let theme_scale = scale.ceil().max(1.0) as u32;
1173    let sizes = (side as u32, size, theme_scale);
1174    if let Some(image) = self.icons.get(icon.source, sizes, icon.tint) {
1175      pixmap.draw_pixmap(
1176        x as i32,
1177        y as i32,
1178        image.as_ref(),
1179        &PixmapPaint::default(),
1180        Transform::identity(),
1181        None,
1182      );
1183    }
1184  }
1185}
1186
1187/// Draws `pixels` unscaled with its corner at `x`, `y`.
1188fn draw_at(pixmap: &mut PixmapMut<'_>, x: i32, y: i32, pixels: &Pixmap) {
1189  let paint = PixmapPaint::default();
1190  pixmap.draw_pixmap(x, y, pixels.as_ref(), &paint, Transform::identity(), None);
1191}
1192
1193/// Whether any of `area` lies inside the pixmap.
1194fn visible(pixmap: &PixmapMut<'_>, area: tiny_skia::Rect) -> bool {
1195  area.right() > 0.0
1196    && area.bottom() > 0.0
1197    && area.left() < pixmap.width() as f32
1198    && area.top() < pixmap.height() as f32
1199}
1200
1201fn fill(pixmap: &mut PixmapMut<'_>, path: PathBuilder, color: Color, rule: FillRule) {
1202  let Some(path) = path.finish() else {
1203    return;
1204  };
1205  let mut paint = Paint::default();
1206  paint.set_color_rgba8(color.r, color.g, color.b, color.a);
1207  paint.anti_alias = true;
1208  pixmap.fill_path(&path, &paint, rule, Transform::identity(), None);
1209}
1210
1211/// Each corner's radius in pixels, from the top left clockwise.
1212type Corners = [f32; 4];
1213
1214/// `corners` for a shape `by` pixels inside the edge.
1215fn inset(corners: Corners, by: f32) -> Corners {
1216  corners.map(|radius| (radius - by).max(0.0))
1217}
1218
1219/// Adds a rectangle with circular `corners` to `path`, clockwise from
1220/// the end of its top-left one.
1221fn rounded_rect(path: &mut PathBuilder, rect: tiny_skia::Rect, corners: Corners) {
1222  if corners.iter().all(|&radius| radius <= 0.0) {
1223    path.push_rect(rect);
1224    return;
1225  }
1226  // How far a cubic curve's control points sit along the tangents to
1227  // follow a quarter circle closely.
1228  const KAPPA: f32 = 0.552_284_8;
1229  let (l, t, r, b) = (rect.left(), rect.top(), rect.right(), rect.bottom());
1230  let [top_left, top_right, bottom_right, bottom_left] = corners;
1231  let k = |radius: f32| radius * (1.0 - KAPPA);
1232  path.move_to(l + top_left, t);
1233  path.line_to(r - top_right, t);
1234  if top_right > 0.0 {
1235    let k = k(top_right);
1236    path.cubic_to(r - k, t, r, t + k, r, t + top_right);
1237  }
1238  path.line_to(r, b - bottom_right);
1239  if bottom_right > 0.0 {
1240    let k = k(bottom_right);
1241    path.cubic_to(r, b - k, r - k, b, r - bottom_right, b);
1242  }
1243  path.line_to(l + bottom_left, b);
1244  if bottom_left > 0.0 {
1245    let k = k(bottom_left);
1246    path.cubic_to(l + k, b, l, b - k, l, b - bottom_left);
1247  }
1248  path.line_to(l, t + top_left);
1249  if top_left > 0.0 {
1250    let k = k(top_left);
1251    path.cubic_to(l, t + k, l + k, t, l + top_left, t);
1252  }
1253  path.close();
1254}
1255
1256/// `a * b / 255`, rounded.
1257fn mul(a: u8, b: u8) -> u8 {
1258  ((u16::from(a) * u16::from(b) + 127) / 255) as u8
1259}
1260
1261/// Blends a premultiplied `source` over the pixel at `index` (in bytes).
1262fn over(data: &mut [u8], index: usize, source: [u8; 4]) {
1263  let rest = 255 - source[3];
1264  for (channel, value) in data[index..index + 4].iter_mut().zip(source) {
1265    *channel = value.saturating_add(mul(*channel, rest));
1266  }
1267}
1268
1269/// The part of a `width` by `height` image placed at `left`, `top` that
1270/// lies inside the pixmap: the first and last column and row, as image
1271/// coordinates.
1272fn overlap(
1273  pixmap: &PixmapMut<'_>,
1274  left: i32,
1275  top: i32,
1276  width: u32,
1277  height: u32,
1278) -> Option<(usize, usize, usize, usize)> {
1279  let column_start = (-i64::from(left)).max(0);
1280  let row_start = (-i64::from(top)).max(0);
1281  let column_end = i64::from(width).min(i64::from(pixmap.width()) - i64::from(left));
1282  let row_end = i64::from(height).min(i64::from(pixmap.height()) - i64::from(top));
1283  (column_start < column_end && row_start < row_end).then_some((
1284    column_start as usize,
1285    column_end as usize,
1286    row_start as usize,
1287    row_end as usize,
1288  ))
1289}
1290
1291/// Blends a glyph's coverage mask in `color`.
1292fn blend_mask(
1293  pixmap: &mut PixmapMut<'_>,
1294  left: i32,
1295  top: i32,
1296  width: u32,
1297  height: u32,
1298  mask: &[u8],
1299  color: Color,
1300) {
1301  if mask.len() < width as usize * height as usize {
1302    return;
1303  }
1304  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1305  else {
1306    return;
1307  };
1308  let stride = pixmap.width() as usize;
1309  let data = pixmap.data_mut();
1310  for row in rows..rows_end {
1311    for column in columns..columns_end {
1312      let coverage = mask[row * width as usize + column];
1313      if coverage == 0 {
1314        continue;
1315      }
1316      let alpha = mul(color.a, coverage);
1317      let source = [
1318        mul(color.r, alpha),
1319        mul(color.g, alpha),
1320        mul(color.b, alpha),
1321        alpha,
1322      ];
1323      let x = (i64::from(left) + column as i64) as usize;
1324      let y = (i64::from(top) + row as i64) as usize;
1325      over(data, (y * stride + x) * 4, source);
1326    }
1327  }
1328}
1329
1330/// How many rows a point near a corner sums.
1331const SAMPLES: usize = 8;
1332
1333/// A rectangle with rounded corners blurred by a Gaussian: how much of it
1334/// covers each point. Away from the corners it is a plain rectangle,
1335/// whose blur is the product of each axis's, from the error function.
1336/// Near a corner, each row's span is blurred across and the rows are
1337/// summed over eight samples of the Gaussian down. Each corner has its
1338/// own radius; the largest says where the corners' rows begin.
1339struct BlurredBox {
1340  middle: (f32, f32),
1341  half: (f32, f32),
1342  corners: Corners,
1343  largest: f32,
1344  sigma: f32,
1345}
1346
1347impl BlurredBox {
1348  fn new(shape: tiny_skia::Rect, corners: Corners, sigma: f32) -> BlurredBox {
1349    BlurredBox {
1350      middle: (
1351        (shape.left() + shape.right()) / 2.0,
1352        (shape.top() + shape.bottom()) / 2.0,
1353      ),
1354      half: (shape.width() / 2.0, shape.height() / 2.0),
1355      corners,
1356      largest: corners.into_iter().fold(0.0, f32::max),
1357      sigma,
1358    }
1359  }
1360
1361  /// Pushes the coverage at each of `xs` on the row at `y`, out of 255,
1362  /// onto `mask`.
1363  fn row(&self, y: f32, xs: impl Iterator<Item = f32>, mask: &mut Vec<u8>) {
1364    let y = y - self.middle.1;
1365    let (half_width, half_height) = self.half;
1366    let reach = 3.0 * self.sigma;
1367    let down = self.along(y, half_height);
1368    let clear_of_corners = y.abs() <= half_height - self.largest - reach;
1369    let rows = if clear_of_corners {
1370      [(0.0, 0.0, 0.0); SAMPLES]
1371    } else {
1372      self.rows_near(y)
1373    };
1374    for x in xs {
1375      let x = x - self.middle.0;
1376      let coverage = if clear_of_corners || x.abs() <= half_width - self.largest - reach {
1377        self.along(x, half_width) * down
1378      } else {
1379        let sum: f32 = rows
1380          .iter()
1381          .map(|&(left, right, weight)| self.between(x, left, right) * weight)
1382          .sum();
1383        sum.clamp(0.0, 1.0)
1384      };
1385      mask.push((coverage * 255.0).round() as u8);
1386    }
1387  }
1388
1389  /// The blur of the span from `-half` to `half` at `p`.
1390  fn along(&self, p: f32, half: f32) -> f32 {
1391    self.between(p, half, half)
1392  }
1393
1394  /// The blur of the span from `-left` to `right` at `p`. One the blur
1395  /// stays inside of is covered whole.
1396  fn between(&self, p: f32, left: f32, right: f32) -> f32 {
1397    let reach = 3.0 * self.sigma;
1398    if -(left - reach) <= p && p <= right - reach {
1399      return 1.0;
1400    }
1401    let scale = std::f32::consts::FRAC_1_SQRT_2 / self.sigma;
1402    0.5 * (erf((p + left) * scale) - erf((p - right) * scale))
1403  }
1404
1405  /// The rows of the shape a point at height `y` near a corner sums: for
1406  /// each sample within the shape and the Gaussian's reach, how far the
1407  /// row reaches left and right of the middle, and its weight.
1408  fn rows_near(&self, y: f32) -> [(f32, f32, f32); SAMPLES] {
1409    let (half_width, half_height) = self.half;
1410    let reach = 3.0 * self.sigma;
1411    let start = (y - half_height).clamp(-reach, reach);
1412    let end = (y + half_height).clamp(-reach, reach);
1413    let step = (end - start) / SAMPLES as f32;
1414    std::array::from_fn(|sample| {
1415      let offset = start + step * (sample as f32 + 0.5);
1416      // How far into a corner's rows this one is, and how much it
1417      // narrows there.
1418      let row = y - offset;
1419      let [top_left, top_right, bottom_right, bottom_left] = self.corners;
1420      let (left, right) = if row < 0.0 {
1421        (top_left, top_right)
1422      } else {
1423        (bottom_left, bottom_right)
1424      };
1425      let span = |radius: f32| {
1426        let into_corner = (row.abs() - (half_height - radius)).max(0.0);
1427        half_width - radius
1428          + (radius * radius - into_corner * into_corner)
1429            .max(0.0)
1430            .sqrt()
1431      };
1432      (span(left), span(right), gaussian(offset, self.sigma) * step)
1433    })
1434  }
1435}
1436
1437/// The normal distribution's density at `x`, for a deviation of `sigma`.
1438fn gaussian(x: f32, sigma: f32) -> f32 {
1439  let root_two_pi = (2.0 * std::f32::consts::PI).sqrt();
1440  (-(x * x) / (2.0 * sigma * sigma)).exp() / (root_two_pi * sigma)
1441}
1442
1443/// The error function, within 5e-4, an eighth of a color level, by
1444/// Abramowitz and Stegun's 7.1.27, which needs no exponential.
1445fn erf(x: f32) -> f32 {
1446  let a = x.abs();
1447  let d = 1.0 + a * (0.278_393 + a * (0.230_389 + a * (0.000_972 + a * 0.078_108)));
1448  let d = d * d;
1449  (1.0 - 1.0 / (d * d)).copysign(x)
1450}
1451
1452/// Whether a color glyph came from vector color layers (COLR), which swash
1453/// renders premultiplied, rather than an embedded bitmap, which it hands
1454/// over as stored: straight alpha.
1455///
1456/// cosmic-text doesn't re-export swash's `Source`, and swash isn't a
1457/// dependency of this crate, so the variant is read from its name.
1458fn is_color_outline(image: &SwashImage) -> bool {
1459  format!("{:?}", image.source).starts_with("ColorOutline")
1460}
1461
1462/// Blends a color glyph's RGBA pixels at `opacity` out of 255. `rgba` says
1463/// whether they are premultiplied already.
1464fn blend_rgba(
1465  pixmap: &mut PixmapMut<'_>,
1466  left: i32,
1467  top: i32,
1468  width: u32,
1469  height: u32,
1470  (rgba, premultiplied): (&[u8], bool),
1471  opacity: u8,
1472) {
1473  if rgba.len() < width as usize * height as usize * 4 {
1474    return;
1475  }
1476  let Some((columns, columns_end, rows, rows_end)) = overlap(pixmap, left, top, width, height)
1477  else {
1478    return;
1479  };
1480  let stride = pixmap.width() as usize;
1481  let data = pixmap.data_mut();
1482  for row in rows..rows_end {
1483    for column in columns..columns_end {
1484      let index = (row * width as usize + column) * 4;
1485      let alpha = mul(rgba[index + 3], opacity);
1486      if alpha == 0 {
1487        continue;
1488      }
1489      // Premultiplied colors only need the opacity; straight ones need
1490      // their own alpha too.
1491      let factor = if premultiplied { opacity } else { alpha };
1492      let source = [
1493        mul(rgba[index], factor),
1494        mul(rgba[index + 1], factor),
1495        mul(rgba[index + 2], factor),
1496        alpha,
1497      ];
1498      let x = (i64::from(left) + column as i64) as usize;
1499      let y = (i64::from(top) + row as i64) as usize;
1500      over(data, (y * stride + x) * 4, source);
1501    }
1502  }
1503}
1504
1505/// Adds `contour` to `kept` when the box around its points reaches into
1506/// `near`, given as left, top, right and bottom.
1507fn keep_near(
1508  kept: &mut PathBuilder,
1509  contour: &[PathSegment],
1510  [left, top, right, bottom]: [f32; 4],
1511) {
1512  let (mut low, mut high) = (
1513    (f32::INFINITY, f32::INFINITY),
1514    (f32::NEG_INFINITY, f32::NEG_INFINITY),
1515  );
1516  let points = contour.iter().flat_map(|segment| match *segment {
1517    PathSegment::MoveTo(a) | PathSegment::LineTo(a) => [Some(a), None, None],
1518    PathSegment::QuadTo(a, b) => [Some(a), Some(b), None],
1519    PathSegment::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
1520    PathSegment::Close => [None; 3],
1521  });
1522  for point in points.flatten() {
1523    low = (low.0.min(point.x), low.1.min(point.y));
1524    high = (high.0.max(point.x), high.1.max(point.y));
1525  }
1526  if low.0 > right || low.1 > bottom || high.0 < left || high.1 < top {
1527    return;
1528  }
1529  for segment in contour {
1530    match *segment {
1531      PathSegment::MoveTo(a) => kept.move_to(a.x, a.y),
1532      PathSegment::LineTo(a) => kept.line_to(a.x, a.y),
1533      PathSegment::QuadTo(a, b) => kept.quad_to(a.x, a.y, b.x, b.y),
1534      PathSegment::CubicTo(a, b, c) => kept.cubic_to(a.x, a.y, b.x, b.y, c.x, c.y),
1535      PathSegment::Close => kept.close(),
1536    }
1537  }
1538}
1539
1540/// A dash of `on` pixels and a gap of `off`, stretched or squeezed so a
1541/// whole number of them goes around `perimeter`, at least one. `None` for
1542/// a pattern that can't be drawn: a number that isn't finite or is
1543/// negative, no gap, or a period shorter than a pixel.
1544pub(crate) fn fit_dash(perimeter: f32, on: f32, off: f32) -> Option<(f32, f32)> {
1545  let period = on + off;
1546  if !(on >= 0.0 && off > 0.0 && period.is_finite() && period >= 1.0 && perimeter > 0.0) {
1547    return None;
1548  }
1549  let count = (perimeter / period).round().max(1.0);
1550  let stretch = perimeter / (count * period);
1551  Some((on * stretch, off * stretch))
1552}