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