lurq 0.22.2

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! Backend-neutral, bounded canvas work. No canvas-sized CPU bitmap lives here.
#![cfg_attr(
  not(any(feature = "wgpu", all(feature = "dx12", target_os = "windows"))),
  allow(dead_code)
)]
use std::{collections::HashMap, ops::Range, time::Duration};

use lyon::{math::point, path::Path as LyonPath, tessellation::*};

use super::{BlendMode, FillRule, GradientKind, path::Geometry, *};

mod cache;
pub(crate) use cache::MeshCache;

#[cfg(test)]
mod benchmark;

pub(crate) const TILE: u32 = 512;
pub(crate) const MAX_QUEUE_BYTES: usize = 64 * 1024 * 1024;
const MAX_VERTICES: usize = 1_048_576;
/// Commands one surface may hold, an open layer's own commands included.
pub(crate) const MAX_COMMANDS: usize = 8192;
/// Isolated layers that may be open at once. Each costs one tile-sized save
/// and one tile-sized layer target in the renderer, not a surface-sized one.
pub const MAX_LAYER_DEPTH: usize = 8;
static READBACKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
struct ReadbackPermit(Arc<std::sync::atomic::AtomicUsize>);
impl Drop for ReadbackPermit {
  fn drop(&mut self) {
    self.0.fetch_sub(1, Ordering::AcqRel);
    READBACKS.fetch_sub(1, Ordering::AcqRel);
  }
}

#[derive(Clone)]
pub(crate) struct Clip {
  pub path: Option<Geometry>,
  pub matrix: Transform2D,
  pub rule: FillRule,
  pub previous: Option<Arc<Clip>>,
  pub depth: u32,
  pub bytes: usize,
}

/// A gradient paint: the ramp to sample, and the map from the path's own model
/// coordinates onto the gradient's frame. The ramp is an ordinary asset, so it
/// is uploaded once and shared by every draw that names it.
#[derive(Clone)]
pub(crate) struct GradientPaint {
  pub kind: GradientKind,
  pub ramp: Asset,
  pub frame: Transform2D,
}

#[derive(Clone)]
pub(crate) struct Asset {
  pub id: u64,
  pub width: u32,
  pub height: u32,
  pub data: Arc<Vec<u8>>,
  pub premultiplied: bool,
}

pub(crate) enum Command {
  Resize {
    width: u32,
    height: u32,
    preserve: bool,
  },
  Clear,
  Path {
    path: Geometry,
    matrix: Transform2D,
    rule: FillRule,
    color: [f32; 4],
    gradient: Option<GradientPaint>,
    erase: bool,
    clip: Option<Arc<Clip>>,
    scale: f32,
  },
  Image {
    asset: Asset,
    matrix: Transform2D,
    source: [f32; 4],
    alpha: f32,
    smooth: bool,
    clip: Option<Arc<Clip>>,
    scale: f32,
  },
  /// Opens an isolated layer. Everything until the matching `EndLayer` composites
  /// into a target of its own at full alpha; the layer then composites onto its
  /// parent once, with `alpha` and `blend`.
  BeginLayer {
    alpha: f32,
    blend: BlendMode,
  },
  EndLayer,
  Readback(Completion, CanvasMetrics, u64),
}

impl Command {
  pub fn bytes(&self) -> usize {
    std::mem::size_of::<Self>()
      + match self {
        Self::Path {
          path, gradient, clip, ..
        } => {
          path.points().len() * 16
            + clip.as_ref().map_or(0, |c| c.bytes)
            + gradient.as_ref().map_or(0, |g| g.ramp.data.len())
        }
        Self::Image { asset, clip, .. } => asset.data.len() + clip.as_ref().map_or(0, |c| c.bytes),
        _ => 0,
      }
  }
}

/// An explicit asynchronous copy from the canvas. Poll on the UI thread, or
/// wait on a worker while the host continues rendering.
pub struct CanvasReadback {
  inner: Arc<ReadbackState>,
}
struct ReadbackState {
  result: Mutex<Option<Result<CanvasSnapshot, CanvasError>>>,
  ready: parking_lot::Condvar,
  permit: Mutex<Option<ReadbackPermit>>,
}
pub(crate) struct Completion(Option<Arc<ReadbackState>>);
impl CanvasReadback {
  pub(crate) fn pair() -> (Self, Completion) {
    let inner = Arc::new(ReadbackState {
      result: Mutex::new(None),
      ready: parking_lot::Condvar::new(),
      permit: Mutex::new(None),
    });
    (Self { inner: inner.clone() }, Completion(Some(inner)))
  }
  pub fn try_take(&self) -> Option<Result<CanvasSnapshot, CanvasError>> {
    self.inner.result.lock().take()
  }
  pub fn wait_timeout(&self, timeout: Duration) -> Option<Result<CanvasSnapshot, CanvasError>> {
    let mut result = self.inner.result.lock();
    let deadline = std::time::Instant::now() + timeout;
    while result.is_none() {
      if self.inner.ready.wait_until(&mut result, deadline).timed_out() {
        break;
      }
    }
    result.take()
  }
}
impl Completion {
  pub fn reserve(&mut self, pending: &Arc<std::sync::atomic::AtomicUsize>) -> bool {
    if pending
      .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < 2).then_some(n + 1))
      .is_err()
    {
      return false;
    }
    if READBACKS
      .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < 8).then_some(n + 1))
      .is_err()
    {
      pending.fetch_sub(1, Ordering::AcqRel);
      return false;
    }
    *self.0.as_ref().unwrap().permit.lock() = Some(ReadbackPermit(pending.clone()));
    true
  }
  pub fn finish(mut self, result: Result<CanvasSnapshot, CanvasError>) {
    let inner = self.0.take().unwrap();
    inner.permit.lock().take();
    *inner.result.lock() = Some(result);
    inner.ready.notify_all();
  }
}
impl Drop for Completion {
  fn drop(&mut self) {
    if let Some(inner) = &self.0 {
      inner.permit.lock().take();
      *inner.result.lock() = Some(Err(CanvasError::RendererLost));
      inner.ready.notify_all();
    }
  }
}

/// A lease retains its memory charge until submission. Dropping an unsubmitted
/// lease restores commands in front of concurrent writes, preserving order.
pub(crate) struct Batch {
  canvas: CanvasHandle,
  pub commands: Vec<Command>,
  bytes: usize,
  submitted: bool,
  metrics_revision: u64,
  replayable: bool,
}
impl Batch {
  pub fn take_commands(&mut self) -> Vec<Command> {
    self.replayable = false;
    std::mem::take(&mut self.commands)
  }
  pub fn submit(mut self) {
    self.submitted = true;
    let mut s = self.canvas.inner.lock();
    s.inflight_bytes -= self.bytes;
  }
}
impl Drop for Batch {
  fn drop(&mut self) {
    if !self.submitted {
      let mut s = self.canvas.inner.lock();
      s.inflight_bytes -= self.bytes;
      if !self.replayable {
        s.error = Some(CanvasError::RendererLost);
      } else if s.attached && s.metrics.revision == self.metrics_revision {
        self.commands.append(&mut s.commands);
        s.commands = std::mem::take(&mut self.commands);
        s.command_bytes += self.bytes;
        s.pending_paint = true;
      }
    }
  }
}
impl CanvasHandle {
  pub(crate) fn take_batch(&self) -> Option<Batch> {
    let mut s = self.inner.lock();
    if s.software || s.commands.is_empty() {
      return None;
    }
    let bytes = std::mem::take(&mut s.command_bytes);
    s.inflight_bytes += bytes;
    Some(Batch {
      canvas: self.clone(),
      commands: std::mem::take(&mut s.commands),
      bytes,
      submitted: false,
      metrics_revision: s.metrics.revision,
      replayable: true,
    })
  }
  pub(crate) fn unsupported(&self) {
    let mut s = self.inner.lock();
    if !s.software {
      s.error = Some(CanvasError::UnsupportedBackend);
      for command in s.commands.drain(..) {
        if let Command::Readback(done, ..) = command {
          done.finish(Err(CanvasError::UnsupportedBackend));
        }
      }
      s.command_bytes = 0;
    }
  }
  pub(crate) fn set_gpu_bytes(&self, bytes: usize) {
    self.inner.lock().gpu_bytes = bytes;
  }
  pub(crate) fn set_gpu_error(&self, error: CanvasError) {
    self.inner.lock().error = Some(error);
  }
  pub(crate) fn record_mesh_cache(&self, before: cache::MeshCacheStats, after: cache::MeshCacheStats) {
    let mut surface = self.inner.lock();
    surface.gpu.mesh_cache_hits += after.hits - before.hits;
    surface.gpu.mesh_cache_misses += after.misses - before.misses;
    surface.gpu.mesh_cache_evictions += after.evictions - before.evictions;
    surface.gpu.mesh_cache_entries = after.entries;
    surface.gpu.mesh_cache_bytes = after.bytes;
  }
  pub(crate) fn record_gpu_update(&self, vertices: usize, tiles: usize, uploaded: usize) {
    let mut s = self.inner.lock();
    s.gpu.batches += 1;
    s.gpu.vertices += vertices as u64;
    s.gpu.tiles += tiles as u64;
    s.gpu.uploaded_bytes += uploaded as u64;
  }
  pub(crate) fn software(&self) {
    self.inner.lock().software = true;
  }
}

/// Commands recorded while an isolated layer is open. They are held here rather
/// than in the surface queue so a layer always reaches the renderer whole: a
/// batch taken mid-layer would otherwise carry an unmatched `BeginLayer`.
pub(crate) struct LayerFrame {
  pub alpha: f32,
  pub blend: BlendMode,
  pub commands: Vec<Command>,
  pub bytes: usize,
}

impl Surface {
  pub(super) fn open_layer(&mut self, alpha: f32, blend: BlendMode) -> Result<(), CanvasError> {
    if !self.attached {
      self.error = Some(CanvasError::Detached);
      return Err(CanvasError::Detached);
    }
    if self.layers.len() >= MAX_LAYER_DEPTH {
      self.error = Some(CanvasError::StateLimit);
      return Err(CanvasError::StateLimit);
    }
    self.layers.push(LayerFrame {
      alpha,
      blend,
      commands: Vec::new(),
      bytes: 0,
    });
    Ok(())
  }

  /// Closes the innermost layer and hands its recorded work to its parent as one
  /// `BeginLayer … EndLayer` run. An empty layer composites nothing and is dropped.
  pub(super) fn close_layer(&mut self) -> bool {
    let Some(frame) = self.layers.pop() else {
      return false;
    };
    self.layer_bytes -= frame.bytes;
    self.layer_commands -= frame.commands.len();
    if frame.commands.is_empty() {
      return false;
    }
    if !self.enqueue(Command::BeginLayer {
      alpha: frame.alpha,
      blend: frame.blend,
    }) {
      return false;
    }
    for command in frame.commands {
      if !self.enqueue(command) {
        return false;
      }
    }
    self.enqueue(Command::EndLayer)
  }

  pub(super) fn discard_layers(&mut self) {
    self.layers.clear();
    self.layer_bytes = 0;
    self.layer_commands = 0;
  }

  pub(super) fn enqueue(&mut self, command: Command) -> bool {
    if !self.attached {
      self.error = Some(CanvasError::Detached);
      return false;
    }
    if matches!(command, Command::Clear) {
      if let Some(frame) = self.layers.last_mut() {
        // A layer starts transparent, so clearing it only discards its own work.
        self.layer_bytes -= frame.bytes;
        self.layer_commands -= frame.commands.len();
        frame.bytes = 0;
        frame.commands.clear();
        return true;
      }
      // Preserve snapshot barriers; everything after the last one is obsolete.
      let keep = self
        .commands
        .iter()
        .rposition(|c| matches!(c, Command::Readback(..) | Command::Resize { .. }))
        .map_or(0, |i| i + 1);
      self.commands.truncate(keep);
      self.command_bytes = self.commands.iter().map(Command::bytes).sum();
    }
    let bytes = command.bytes();
    let queued = self.commands.len() + self.layer_commands;
    if queued >= MAX_COMMANDS || self.command_bytes + self.layer_bytes + self.inflight_bytes + bytes > MAX_QUEUE_BYTES {
      self.error = Some(CanvasError::QueueFull);
      if let Command::Readback(done, ..) = command {
        done.finish(Err(CanvasError::QueueFull));
      }
      return false;
    }
    if let Some(frame) = self.layers.last_mut() {
      frame.bytes += bytes;
      frame.commands.push(command);
      self.layer_bytes += bytes;
      self.layer_commands += 1;
      return true;
    }
    self.command_bytes += bytes;
    self.commands.push(command);
    true
  }
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct Vertex {
  pub position: [f32; 2],
  pub uv: [f32; 2],
  pub color: [f32; 4],
}
/// What a draw's fragments are coloured by.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum DrawKind {
  /// The vertex colour, premultiplied.
  Solid,
  /// A premultiplied RGBA asset sampled through `uv`, scaled by the vertex colour.
  Image,
  /// A gradient ramp sampled at the parameter `uv` carries in the gradient's frame.
  Gradient(GradientKind),
}

pub(crate) struct Draw {
  pub vertices: Range<u32>,
  pub clips: Vec<Range<u32>>,
  pub bounds: [f32; 4],
  pub asset: Option<Asset>,
  pub smooth: bool,
  pub erase: bool,
  pub kind: DrawKind,
}
/// One entry of a prepared batch, in order: a draw, or an isolated layer's
/// boundary.
pub(crate) enum Step {
  Draw(Draw),
  /// `end` is the index of the matching [`Step::End`]; `bounds` covers every
  /// draw inside, so a tile the layer does not touch skips the whole run.
  Begin {
    alpha: f32,
    blend: BlendMode,
    bounds: [f32; 4],
    end: usize,
  },
  End,
}
impl Step {
  pub fn draw(&self) -> Option<&Draw> {
    match self {
      Self::Draw(draw) => Some(draw),
      _ => None,
    }
  }
}
const NO_BOUNDS: [f32; 4] = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
fn cover(into: &mut [f32; 4], with: [f32; 4]) {
  into[0] = into[0].min(with[0]);
  into[1] = into[1].min(with[1]);
  into[2] = into[2].max(with[2]);
  into[3] = into[3].max(with[3]);
}

#[derive(Default)]
pub(crate) struct Prepared {
  pub vertices: Vec<Vertex>,
  pub steps: Vec<Step>,
  pub clear: bool,
}
impl Prepared {
  pub fn new(commands: &[Command], cache: &mut MeshCache) -> Result<Self, CanvasError> {
    let mut result = Self::default();
    let mut clips = HashMap::new();
    let mut open: Vec<(usize, [f32; 4])> = Vec::new();
    for command in commands {
      match command {
        Command::Clear => {
          result = Self {
            clear: true,
            ..Self::default()
          };
          clips.clear();
          open.clear();
          continue;
        }
        Command::BeginLayer { alpha, blend } => {
          open.push((result.steps.len(), NO_BOUNDS));
          result.steps.push(Step::Begin {
            alpha: *alpha,
            blend: *blend,
            bounds: NO_BOUNDS,
            end: 0,
          });
          continue;
        }
        Command::EndLayer => {
          close_layer(&mut result.steps, &mut open);
          continue;
        }
        _ => {}
      }
      let (clip, scale) = match command {
        Command::Path { clip, scale, .. } | Command::Image { clip, scale, .. } => (clip, *scale),
        _ => continue,
      };
      let mut clip_ranges = Vec::new();
      let mut chain = Vec::new();
      let mut clip = clip.as_ref();
      while let Some(c) = clip {
        chain.push(c);
        clip = c.previous.as_ref();
      }
      for clip in chain.into_iter().rev() {
        let key = (Arc::as_ptr(clip) as usize, scale.to_bits());
        let range = if let Some(range) = clips.get(&key) {
          Range::<u32>::clone(range)
        } else {
          let start = result.vertices.len() as u32;
          if let Some(path) = &clip.path {
            cache.append(
              path,
              Transform2D::scale_uniform(scale).then(&clip.matrix),
              clip.rule,
              [0.; 4],
              None,
              &mut result.vertices,
            )?;
          }
          let range = start..result.vertices.len() as u32;
          clips.insert(key, range.clone());
          range
        };
        clip_ranges.push(range);
      }
      let start = result.vertices.len() as u32;
      let (asset, smooth, erase, kind) = match command {
        Command::Path {
          path,
          matrix,
          rule,
          color,
          gradient,
          erase,
          ..
        } => {
          cache.append(
            path,
            *matrix,
            *rule,
            *color,
            gradient.as_ref().map(|g| g.frame),
            &mut result.vertices,
          )?;
          match gradient {
            Some(gradient) => (
              Some(gradient.ramp.clone()),
              true,
              *erase,
              DrawKind::Gradient(gradient.kind),
            ),
            None => (None, false, *erase, DrawKind::Solid),
          }
        }
        Command::Image {
          asset,
          matrix,
          source: [x, y, w, h],
          alpha,
          smooth,
          ..
        } => {
          let corners = [[*x, *y], [x + w, *y], [x + w, y + h], [*x, y + h]];
          for index in [0, 1, 2, 0, 2, 3] {
            let [x, y] = corners[index];
            let (px, py) = matrix.transform_point(x, y);
            result.vertices.push(Vertex {
              position: [px, py],
              uv: [x / asset.width as f32, y / asset.height as f32],
              color: [*alpha; 4],
            });
          }
          (Some(asset.clone()), *smooth, false, DrawKind::Image)
        }
        _ => unreachable!(),
      };
      let end = result.vertices.len() as u32;
      if end as usize > MAX_VERTICES {
        return Err(CanvasError::StateLimit);
      }
      let mut bounds = NO_BOUNDS;
      for v in &result.vertices[start as usize..end as usize] {
        bounds[0] = bounds[0].min(v.position[0]);
        bounds[1] = bounds[1].min(v.position[1]);
        bounds[2] = bounds[2].max(v.position[0]);
        bounds[3] = bounds[3].max(v.position[1]);
      }
      for layer in &mut open {
        cover(&mut layer.1, bounds);
      }
      result.steps.push(Step::Draw(Draw {
        vertices: start..end,
        clips: clip_ranges,
        bounds,
        asset,
        smooth,
        erase,
        kind,
      }));
    }
    // A batch is taken whole, so an unmatched `BeginLayer` cannot normally reach
    // a backend. Closing one here keeps a backend's own layer stack balanced
    // rather than making every backend defend itself.
    while !open.is_empty() {
      close_layer(&mut result.steps, &mut open);
    }
    Ok(result)
  }
  pub fn draws(&self) -> impl Iterator<Item = &Draw> {
    self.steps.iter().filter_map(Step::draw)
  }
  pub fn tiles(&self, width: u32, height: u32) -> Vec<[u32; 4]> {
    let mut result = Vec::new();
    for y in (0..height).step_by(TILE as usize) {
      for x in (0..width).step_by(TILE as usize) {
        let tile = [x, y, TILE.min(width - x), TILE.min(height - y)];
        if self.draws().any(|d| d.intersects(tile)) {
          result.push(tile);
        }
      }
    }
    result
  }
}
fn close_layer(steps: &mut Vec<Step>, open: &mut Vec<(usize, [f32; 4])>) {
  let Some((begin, bounds)) = open.pop() else {
    return;
  };
  let end = steps.len();
  steps.push(Step::End);
  if let Some(Step::Begin {
    bounds: slot,
    end: index,
    ..
  }) = steps.get_mut(begin)
  {
    *slot = bounds;
    *index = end;
  }
  if let Some(parent) = open.last_mut() {
    cover(&mut parent.1, bounds);
  }
}
impl Draw {
  pub fn intersects(&self, tile: [u32; 4]) -> bool {
    touches(self.bounds, tile)
  }
}
/// The deepest isolation a batch opens, which is how many tile-sized copies a
/// backend has to hold while it draws it.
pub(crate) fn layer_depth(prepared: &Prepared) -> usize {
  let (mut depth, mut deepest) = (0usize, 0usize);
  for step in &prepared.steps {
    match step {
      Step::Begin { .. } => {
        depth += 1;
        deepest = deepest.max(depth);
      }
      Step::End => depth = depth.saturating_sub(1),
      Step::Draw(_) => {}
    }
  }
  deepest
}
/// Whether work bounded by `bounds` can change anything in `tile`.
pub(crate) fn touches(bounds: [f32; 4], [x, y, w, h]: [u32; 4]) -> bool {
  bounds[0] < (x + w) as f32 && bounds[1] < (y + h) as f32 && bounds[2] > x as f32 && bounds[3] > y as f32
}
fn mesh(
  path: &Path,
  rule: FillRule,
  tolerance: f32,
  color: [f32; 4],
  output: &mut Vec<Vertex>,
) -> Result<(), CanvasError> {
  let mut builder = LyonPath::builder();
  let mut open = false;
  for segment in path.segments() {
    use tiny_skia::PathSegment::*;
    match segment {
      MoveTo(p) => {
        if open {
          builder.end(true);
        }
        builder.begin(point(p.x, p.y));
        open = true;
      }
      LineTo(p) => {
        builder.line_to(point(p.x, p.y));
      }
      QuadTo(a, b) => {
        builder.quadratic_bezier_to(point(a.x, a.y), point(b.x, b.y));
      }
      CubicTo(a, b, c) => {
        builder.cubic_bezier_to(point(a.x, a.y), point(b.x, b.y), point(c.x, c.y));
      }
      Close => {
        if open {
          builder.end(true);
          open = false;
        }
      }
    }
  }
  if open {
    builder.end(true);
  }
  let path = builder.build();
  let options = FillOptions::default()
    .with_tolerance(tolerance)
    .with_fill_rule(match rule {
      FillRule::NonZero => lyon::path::FillRule::NonZero,
      FillRule::EvenOdd => lyon::path::FillRule::EvenOdd,
    });
  // The custom builder limits expansion while tessellating, including malicious
  // self-intersecting paths whose triangulation is much larger than their input.
  let mut geometry = LimitedGeometry {
    vertices: Vec::new(),
    output,
    color,
    overflow: false,
  };
  FillTessellator::new()
    .tessellate_path(&path, &options, &mut geometry)
    .map_err(|_| CanvasError::StateLimit)?;
  if geometry.overflow {
    return Err(CanvasError::StateLimit);
  }
  Ok(())
}
struct LimitedGeometry<'a> {
  vertices: Vec<[f32; 2]>,
  output: &'a mut Vec<Vertex>,
  color: [f32; 4],
  overflow: bool,
}
impl GeometryBuilder for LimitedGeometry<'_> {
  fn begin_geometry(&mut self) {}
  fn end_geometry(&mut self) {}
  fn add_triangle(&mut self, a: VertexId, b: VertexId, c: VertexId) {
    if self.output.len() + 3 <= MAX_VERTICES {
      for i in [a, b, c] {
        self.output.push(Vertex {
          position: self.vertices[i.to_usize()],
          uv: [0.; 2],
          color: self.color,
        });
      }
    } else {
      self.overflow = true;
    }
  }
  fn abort_geometry(&mut self) {}
}
impl FillGeometryBuilder for LimitedGeometry<'_> {
  fn add_fill_vertex(&mut self, vertex: FillVertex<'_>) -> Result<VertexId, GeometryBuilderError> {
    if self.vertices.len() >= MAX_VERTICES || self.output.len() + 3 > MAX_VERTICES {
      return Err(GeometryBuilderError::TooManyVertices);
    }
    let id = VertexId(self.vertices.len() as u32);
    let p = vertex.position();
    self.vertices.push([p.x, p.y]);
    Ok(id)
  }
}

pub(crate) fn unpremultiply(mut rgba: Vec<u8>) -> Vec<u8> {
  for p in rgba.chunks_exact_mut(4) {
    if p[3] != 0 {
      let a = u32::from(p[3]);
      for c in &mut p[..3] {
        *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8;
      }
    }
  }
  rgba
}

#[cfg(test)]
mod tests {
  use super::*;
  fn canvas() -> CanvasHandle {
    let c = CanvasHandle::new();
    {
      let mut s = c.inner.lock();
      s.attached = true;
      s.metrics.pixel_width = 100;
      s.metrics.pixel_height = 100;
    }
    c
  }
  #[test]
  fn command_leases_bound_memory_restore_order_and_retire_after_submit() {
    let c = canvas();
    let d = c.context_2d();
    d.set_fill_style("#ff000080");
    d.fill_rect(0., 0., 10., 10.);
    let bytes = c.status().pending_bytes;
    let batch = c.take_batch().unwrap();
    assert_eq!(c.status().pending_bytes, bytes);
    d.set_fill_style("#0000ff");
    d.fill_rect(10., 0., 10., 10.);
    drop(batch);
    let batch = c.take_batch().unwrap();
    assert_eq!(batch.commands.len(), 2);
    assert!(matches!(&batch.commands[0],Command::Path {color,..} if color[0]>0. && color[2]==0.));
    batch.submit();
    assert_eq!(c.status().pending_bytes, 0);
    assert!(c.take_batch().is_none());
    d.fill_rect(0., 0., 1., 1.);
    let mut failed = c.take_batch().unwrap();
    failed.take_commands();
    drop(failed);
    assert_eq!(c.status().pending_bytes, 0, "failed encoding releases its charge");
    assert_eq!(c.status().error, Some(CanvasError::RendererLost));
    for _ in 0..9000 {
      d.fill_rect(0., 0., 1., 1.);
    }
    assert_eq!(c.status().error, Some(CanvasError::QueueFull));
    assert!(c.status().pending_bytes <= MAX_QUEUE_BYTES);
    d.clear();
    assert!(c.status().pending_bytes < 1024);
  }
  #[test]
  fn readback_limit_includes_inflight_work_and_clear_keeps_barriers() {
    let c = canvas();
    let d = c.context_2d();
    d.fill_rect(0., 0., 10., 10.);
    let first = c.snapshot();
    let batch = c.take_batch().unwrap();
    let second = c.snapshot();
    d.clear();
    assert_eq!(c.snapshot().try_take().unwrap().unwrap_err(), CanvasError::QueueFull);
    drop(batch);
    let batch = c.take_batch().unwrap();
    assert_eq!(batch.commands.len(), 4);
    c.detach();
    drop(batch);
    assert!(first.try_take().unwrap().is_err());
    assert!(second.try_take().unwrap().is_err());
    assert_eq!(c.status().pending_bytes, 0);
  }
}