lurq 0.41.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
mod images;
mod text;

use super::*;

impl Context2D {
  pub fn canvas(&self) -> CanvasHandle {
    self.canvas.clone()
  }

  fn pixels(&self, draw: impl FnOnce(&mut Surface) -> bool) {
    let wake = {
      let mut s = self.canvas.inner.lock();
      // A refused replacement still owns the front. Only a new presentation
      // may recover it; ordinary pixel writes/reset must not publish false progress.
      if !s.software && s.presentation.is_none() && s.presentation_refused {
        return;
      }
      let was_clean = !s.pending_paint;
      if !draw(&mut s) {
        return;
      }
      s.revision += 1;
      if s.presentation.is_none() {
        s.visible_revision = s.revision;
      }
      if let Some(native) = &s.native {
        native.bump_version();
      }
      s.pending_paint = true;
      if was_clean { s.window.clone() } else { None }
    };
    if let Some(window) = wake {
      window.wake();
    }
  }

  pub fn save(&self) {
    let mut s = self.canvas.inner.lock();
    if s.stack.len() == MAX_SAVE_DEPTH {
      s.error = Some(CanvasError::StateLimit);
      return;
    }
    let state = s.state.clone();
    s.stack.push(state);
  }
  pub fn restore(&self) {
    let mut s = self.canvas.inner.lock();
    if let Some(state) = s.stack.pop() {
      s.state = state;
    }
  }
  pub fn reset(&self) {
    self.pixels(|s| {
      s.state = s.defaults.clone();
      s.stack.clear();
      s.path = Path2D::new();
      s.error = None;
      s.discard_layers();
      s.software_layers.clear();
      if !s.software {
        return s.enqueue(gpu::Command::Clear);
      }
      if let Some(pixels) = &mut s.pixels {
        pixels.fill(tiny_skia::Color::TRANSPARENT);
      }
      true
    });
  }
  /// Erases the entire surface independently of transform and clip; keeps drawing state and path.
  pub fn clear(&self) {
    self.pixels(|s| {
      if !s.software {
        return s.enqueue(gpu::Command::Clear);
      }
      // Inside a layer this erases the layer's own work, as it does on the GPU.
      if let Some(pixels) = s.target_pixels() {
        pixels.fill(tiny_skia::Color::TRANSPARENT);
        true
      } else {
        false
      }
    });
  }

  /// A colour, a parseable colour string, or a [`Paint`] carrying a gradient.
  /// A value that cannot be resolved leaves the current paint alone.
  pub fn set_fill_style(&self, paint: impl CanvasPaint) {
    if let Some(paint) = paint.canvas_paint() {
      self.canvas.inner.lock().state.fill = paint;
    }
  }
  pub fn fill_style(&self) -> Paint {
    self.canvas.inner.lock().state.fill.clone()
  }
  pub fn set_stroke_style(&self, paint: impl CanvasPaint) {
    if let Some(paint) = paint.canvas_paint() {
      self.canvas.inner.lock().state.stroke_paint = paint;
    }
  }
  pub fn stroke_style(&self) -> Paint {
    self.canvas.inner.lock().state.stroke_paint.clone()
  }

  /// The shadow cast by every following fill, stroke and text draw, or `None`.
  /// Part of the saved drawing state. An invalid shadow is ignored, as an
  /// unparseable colour is; see [`Shadow`] for the bounds it is checked against.
  pub fn set_shadow(&self, shadow: Option<Shadow>) {
    self.canvas.inner.lock().state.shadow = shadow.filter(Shadow::is_valid);
  }
  pub fn shadow(&self) -> Option<Shadow> {
    self.canvas.inner.lock().state.shadow
  }
  /// Blurs what the following draws paint. Part of the saved drawing state.
  pub fn set_filter(&self, filter: Filter) {
    if filter.is_valid() {
      self.canvas.inner.lock().state.filter = filter;
    }
  }
  pub fn filter(&self) -> Filter {
    self.canvas.inner.lock().state.filter
  }
  /// How following draws composite with what is beneath them. Part of the saved
  /// drawing state, like the global alpha. A draw with a mode other than
  /// `Normal` is isolated before it blends, so its own shadow does not blend
  /// with the shape that casts it.
  pub fn set_global_composite_operation(&self, blend: BlendMode) {
    self.canvas.inner.lock().state.blend = blend;
  }
  pub fn global_composite_operation(&self) -> BlendMode {
    self.canvas.inner.lock().state.blend
  }

  /// Begins an isolated layer: following draws composite into a target of their
  /// own using the current drawing state, including global alpha.
  /// [`Context2D::end_layer`] composites that target onto the parent once, with
  /// `alpha` and `blend`. Keep global alpha at 1 when only the group's opacity
  /// should change, so overlapping shapes fade as one image.
  ///
  /// Layers nest to [`MAX_LAYER_DEPTH`]. They are not the save stack:
  /// `restore` does not close one, and a layer left open when the canvas is
  /// reset, resized or detached is discarded with its contents.
  pub fn begin_layer(&self, alpha: f32, blend: BlendMode) -> Result<(), CanvasError> {
    if !(0.0..=1.0).contains(&alpha) {
      return Err(CanvasError::InvalidGeometry);
    }
    self.canvas.inner.lock().begin_layer(alpha, blend)
  }
  /// Composites the innermost open layer. Ending a layer that was never begun
  /// is an error rather than a silent discard.
  pub fn end_layer(&self) -> Result<(), CanvasError> {
    let mut open = false;
    self.pixels(|s| {
      open = if s.software {
        !s.software_layers.is_empty()
      } else {
        !s.layers.is_empty()
      };
      open && s.end_layer()
    });
    if open {
      Ok(())
    } else {
      Err(CanvasError::UnbalancedLayer)
    }
  }
  pub fn set_global_alpha(&self, alpha: f32) {
    if (0.0..=1.0).contains(&alpha) {
      self.canvas.inner.lock().state.alpha = alpha;
    }
  }
  pub fn global_alpha(&self) -> f32 {
    self.canvas.inner.lock().state.alpha
  }
  pub fn set_line_width(&self, width: f32) {
    if width.is_finite() && width > 0.0 {
      self.canvas.inner.lock().state.stroke.width = width;
    }
  }
  pub fn line_width(&self) -> f32 {
    self.canvas.inner.lock().state.stroke.width
  }
  pub fn set_line_cap(&self, cap: LineCap) {
    self.canvas.inner.lock().state.stroke.line_cap = cap;
  }
  pub fn line_cap(&self) -> LineCap {
    self.canvas.inner.lock().state.stroke.line_cap
  }
  pub fn set_line_join(&self, join: LineJoin) {
    self.canvas.inner.lock().state.stroke.line_join = join;
  }
  pub fn line_join(&self) -> LineJoin {
    self.canvas.inner.lock().state.stroke.line_join
  }
  pub fn set_miter_limit(&self, limit: f32) {
    if limit.is_finite() && limit > 0.0 {
      self.canvas.inner.lock().state.stroke.miter_limit = limit;
    }
  }
  pub fn miter_limit(&self) -> f32 {
    self.canvas.inner.lock().state.stroke.miter_limit
  }
  pub fn set_line_dash(&self, dash: &[f32]) {
    if dash.len() > 4096 || dash.iter().any(|v| !v.is_finite() || *v < 0.0) {
      return;
    }
    let mut values = dash.to_vec();
    if values.len() % 2 == 1 {
      values.extend_from_slice(dash);
    }
    let mut s = self.canvas.inner.lock();
    s.state.stroke.dash = StrokeDash::new(values.clone(), s.state.dash_offset);
    s.state.dash = values;
  }
  pub fn line_dash(&self) -> Vec<f32> {
    self.canvas.inner.lock().state.dash.clone()
  }
  pub fn set_line_dash_offset(&self, offset: f32) {
    if !offset.is_finite() {
      return;
    }
    let mut s = self.canvas.inner.lock();
    s.state.dash_offset = offset;
    s.state.stroke.dash = StrokeDash::new(s.state.dash.clone(), offset);
  }
  pub fn line_dash_offset(&self) -> f32 {
    self.canvas.inner.lock().state.dash_offset
  }
  pub fn set_image_smoothing_enabled(&self, enabled: bool) {
    self.canvas.inner.lock().state.smoothing = enabled;
  }
  pub fn image_smoothing_enabled(&self) -> bool {
    self.canvas.inner.lock().state.smoothing
  }

  pub fn set_transform(&self, matrix: Transform2D) {
    if [matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty]
      .iter()
      .all(|v| v.is_finite())
    {
      self.canvas.inner.lock().state.transform = matrix;
    }
  }
  pub fn get_transform(&self) -> Transform2D {
    self.canvas.inner.lock().state.transform
  }
  pub fn reset_transform(&self) {
    self.set_transform(Transform2D::IDENTITY);
  }
  pub fn transform(&self, matrix: Transform2D) {
    let mut s = self.canvas.inner.lock();
    let matrix = s.state.transform.then(&matrix);
    if [matrix.a, matrix.b, matrix.c, matrix.d, matrix.tx, matrix.ty]
      .iter()
      .all(|v| v.is_finite())
    {
      s.state.transform = matrix;
    }
  }
  pub fn translate(&self, x: f32, y: f32) {
    self.transform(Transform2D::translate(x, y));
  }
  pub fn scale(&self, x: f32, y: f32) {
    self.transform(Transform2D::scale(x, y));
  }
  /// Rotation in radians.
  pub fn rotate(&self, radians: f32) {
    self.transform(Transform2D::rotate(radians));
  }

  pub fn begin_path(&self) {
    self.canvas.inner.lock().path = Path2D::new();
  }
  pub fn close_path(&self) {
    self.canvas.inner.lock().path.close_path();
  }
  pub fn move_to(&self, x: f32, y: f32) {
    let mut s = self.canvas.inner.lock();
    let p = s.state.transform.transform_point(x, y);
    s.path.move_to(p.0, p.1);
  }
  pub fn line_to(&self, x: f32, y: f32) {
    let mut s = self.canvas.inner.lock();
    let p = s.state.transform.transform_point(x, y);
    s.path.line_to(p.0, p.1);
  }
  pub fn quadratic_curve_to(&self, cx: f32, cy: f32, x: f32, y: f32) {
    let mut s = self.canvas.inner.lock();
    let m = s.state.transform;
    let (c, p) = (m.transform_point(cx, cy), m.transform_point(x, y));
    s.path.quadratic_curve_to(c.0, c.1, p.0, p.1);
  }
  pub fn bezier_curve_to(&self, ax: f32, ay: f32, bx: f32, by: f32, x: f32, y: f32) {
    let mut s = self.canvas.inner.lock();
    let m = s.state.transform;
    let (a, b, p) = (
      m.transform_point(ax, ay),
      m.transform_point(bx, by),
      m.transform_point(x, y),
    );
    s.path.bezier_curve_to(a.0, a.1, b.0, b.1, p.0, p.1);
  }
  fn path_geometry(
    &self,
    connect: bool,
    draw: impl FnOnce(&mut Path2D) -> Result<(), CanvasError>,
  ) -> Result<(), CanvasError> {
    let mut s = self.canvas.inner.lock();
    let mut path = Path2D::new();
    draw(&mut path)?;
    if let Some(path) = path.finish().and_then(|p| p.transform(transform(s.state.transform))) {
      s.path.append(&path, connect);
    }
    Ok(())
  }
  pub fn rect(&self, x: f32, y: f32, w: f32, h: f32) {
    let _ = self.path_geometry(false, |p| {
      p.rect(x, y, w, h);
      Ok(())
    });
  }
  pub fn round_rect(&self, x: f32, y: f32, w: f32, h: f32, r: f32) -> Result<(), CanvasError> {
    self.path_geometry(false, |p| p.round_rect(x, y, w, h, r))
  }
  pub fn arc(&self, x: f32, y: f32, r: f32, start: f32, end: f32, direction: ArcDirection) -> Result<(), CanvasError> {
    self.path_geometry(true, |p| p.arc(x, y, r, start, end, direction))
  }
  #[allow(clippy::too_many_arguments)]
  pub fn ellipse(
    &self,
    x: f32,
    y: f32,
    rx: f32,
    ry: f32,
    rotation: f32,
    start: f32,
    end: f32,
    direction: ArcDirection,
  ) -> Result<(), CanvasError> {
    self.path_geometry(true, |p| p.ellipse(x, y, rx, ry, rotation, start, end, direction))
  }
  pub fn arc_to(&self, x1: f32, y1: f32, x2: f32, y2: f32, r: f32) -> Result<(), CanvasError> {
    if r < 0.0 {
      return Err(CanvasError::InvalidGeometry);
    }
    let mut s = self.canvas.inner.lock();
    let mut path = Path2D::new();
    let Some(inverse) = s.state.transform.inverse_affine() else {
      return Ok(());
    };
    if let Some(current) = s.path.current() {
      let p = inverse.transform_point(current.x, current.y);
      path.move_to(p.0, p.1);
    }
    path.arc_to(x1, y1, x2, y2, r)?;
    if let Some(path) = path.finish().and_then(|p| p.transform(transform(s.state.transform))) {
      s.path.append(&path, true);
    }
    Ok(())
  }

  pub fn fill_rect(&self, x: f32, y: f32, w: f32, h: f32) {
    self.paint_rect(x, y, w, h, false, false);
  }
  pub fn stroke_rect(&self, x: f32, y: f32, w: f32, h: f32) {
    self.paint_rect(x, y, w, h, true, false);
  }
  pub fn clear_rect(&self, x: f32, y: f32, w: f32, h: f32) {
    self.paint_rect(x, y, w, h, false, true);
  }
  fn paint_rect(&self, x: f32, y: f32, w: f32, h: f32, stroke: bool, clear: bool) {
    let mut path = Path2D::new();
    path.rect(x, y, w, h);
    let Some(path) = path.geometry() else {
      return;
    };
    self.pixels(|s| s.paint_path(&path, s.state.transform, stroke, clear, FillRule::NonZero));
  }
  pub fn fill(&self) {
    self.fill_with_rule(FillRule::NonZero);
  }
  pub fn fill_with_rule(&self, rule: FillRule) {
    self.pixels(|s| {
      let Some(path) = s.path.geometry() else {
        return false;
      };
      s.paint_path(&path, Transform2D::IDENTITY, false, false, rule)
    });
  }
  pub fn stroke(&self) {
    self.pixels(|s| {
      let Some(path) = current_stroke_path(s) else {
        return false;
      };
      s.paint_path(
        &path::Geometry::new(path),
        s.state.transform,
        true,
        false,
        FillRule::NonZero,
      )
    });
  }
  pub fn fill_path(&self, path: &Path2D, rule: FillRule) {
    let Some(path) = path.geometry() else {
      return;
    };
    self.pixels(|s| s.paint_path(&path, s.state.transform, false, false, rule));
  }
  pub fn stroke_path(&self, path: &Path2D) {
    let Some(path) = path.geometry() else {
      return;
    };
    self.pixels(|s| s.paint_path(&path, s.state.transform, true, false, FillRule::NonZero));
  }

  pub fn clip(&self) {
    self.clip_with_rule(FillRule::NonZero);
  }
  pub fn clip_with_rule(&self, rule: FillRule) {
    let mut s = self.canvas.inner.lock();
    let path = s.path.geometry();
    apply_clip(&mut s, path, Transform2D::IDENTITY, rule);
  }
  pub fn clip_path(&self, path: &Path2D, rule: FillRule) {
    let mut s = self.canvas.inner.lock();
    let m = s.state.transform;
    apply_clip(&mut s, path.geometry(), m, rule);
  }
  /// Point coordinates are canvas-logical, unaffected by the current drawing transform.
  pub fn is_point_in_path(&self, x: f32, y: f32, rule: FillRule) -> bool {
    self
      .canvas
      .inner
      .lock()
      .path
      .finish()
      .is_some_and(|p| path::contains(&p, Point::from_xy(x, y), rule))
  }
  pub fn is_point_in_path2d(&self, path: &Path2D, x: f32, y: f32, rule: FillRule) -> bool {
    let s = self.canvas.inner.lock();
    path
      .finish()
      .and_then(|p| p.transform(transform(s.state.transform)))
      .is_some_and(|p| path::contains(&p, Point::from_xy(x, y), rule))
  }
  pub fn is_point_in_stroke(&self, x: f32, y: f32) -> bool {
    let s = self.canvas.inner.lock();
    current_stroke_path(&s)
      .and_then(|p| stroke_outline(&p, &s.state.stroke))
      .and_then(|p| p.transform(transform(s.state.transform)))
      .is_some_and(|p| path::contains(&p, Point::from_xy(x, y), FillRule::NonZero))
  }
  pub fn is_point_in_stroke_path(&self, path: &Path2D, x: f32, y: f32) -> bool {
    let s = self.canvas.inner.lock();
    path
      .finish()
      .and_then(|p| stroke_outline(&p, &s.state.stroke))
      .and_then(|p| p.transform(transform(s.state.transform)))
      .is_some_and(|p| path::contains(&p, Point::from_xy(x, y), FillRule::NonZero))
  }
}

fn current_stroke_path(s: &Surface) -> Option<Path> {
  s.path
    .finish()?
    .transform(transform(s.state.transform.inverse_affine()?))
}
pub(super) fn stroke_outline(path: &Path, stroke: &Stroke) -> Option<Path> {
  if let Some(dash) = &stroke.dash {
    path.dash(dash, 1.0)?.stroke(stroke, 1.0)
  } else {
    path.stroke(stroke, 1.0)
  }
}

fn apply_clip(s: &mut Surface, path: Option<path::Geometry>, matrix: Transform2D, rule: FillRule) {
  if !s.software {
    let bytes = path.as_ref().map_or(0, |p| p.points().len() * 16) + s.state.gpu_clip.as_ref().map_or(0, |c| c.bytes);
    let mut retained = std::collections::HashSet::new();
    let mut retained_bytes = path.as_ref().map_or(0, |p| p.points().len() * 16);
    for state in s.stack.iter().chain(std::iter::once(&s.state)) {
      let mut clip = state.gpu_clip.as_ref();
      while let Some(c) = clip {
        if !retained.insert(Arc::as_ptr(c)) {
          break;
        }
        retained_bytes += c.path.as_ref().map_or(0, |p| p.points().len() * 16);
        clip = c.previous.as_ref();
      }
    }
    let depth = s.state.gpu_clip.as_ref().map_or(1, |c| c.depth + 1);
    if depth > MAX_SAVE_DEPTH as u32 || retained_bytes > 8 * 1024 * 1024 {
      s.error = Some(CanvasError::StateLimit);
      return;
    }
    s.state.gpu_clip = Some(Arc::new(gpu::Clip {
      path,
      matrix,
      rule,
      previous: s.state.gpu_clip.clone(),
      depth,
      bytes,
    }));
    return;
  }
  let (width, height) = (s.metrics.pixel_width, s.metrics.pixel_height);
  if width == 0 || height == 0 {
    return;
  }
  let mut retained = std::collections::HashSet::new();
  let mut bytes = width as usize * height as usize;
  for state in s.stack.iter().chain(std::iter::once(&s.state)) {
    if let Some(clip) = &state.clip
      && retained.insert(Arc::as_ptr(clip))
    {
      bytes += clip.data().len();
    }
  }
  if bytes > MAX_CLIP_BYTES {
    s.error = Some(CanvasError::StateLimit);
    return;
  }
  let Some(mut mask) = Mask::new(width, height) else {
    s.error = Some(CanvasError::SurfaceTooLarge);
    return;
  };
  if let Some(path) = path {
    mask.fill_path(
      &path,
      rule.skia(),
      true,
      transform(Transform2D::scale_uniform(s.metrics.scale_factor).then(&matrix)),
    );
  }
  if let Some(previous) = &s.state.clip {
    for (next, old) in mask.data_mut().iter_mut().zip(previous.data()) {
      *next = ((u16::from(*next) * u16::from(*old) + 127) / 255) as u8;
    }
  }
  s.state.clip = Some(Arc::new(mask));
}

pub(super) fn blit(s: &mut Surface, pixels: &Pixmap, matrix: Transform2D, clip_rect: Option<[f32; 4]>) -> bool {
  let mut mask = None;
  if let Some([x, y, w, h]) = clip_rect {
    let mut p = Path2D::new();
    p.rect(x, y, w, h);
    if let (Some(p), Some(mut m)) = (p.finish(), Mask::new(s.metrics.pixel_width, s.metrics.pixel_height)) {
      m.fill_path(
        &p,
        tiny_skia::FillRule::Winding,
        true,
        transform(Transform2D::scale_uniform(s.metrics.scale_factor).then(&s.state.transform)),
      );
      if let Some(clip) = &s.state.clip {
        for (a, b) in m.data_mut().iter_mut().zip(clip.data()) {
          *a = ((u16::from(*a) * u16::from(*b) + 127) / 255) as u8;
        }
      }
      mask = Some(m);
    }
  }
  let transform = transform(
    Transform2D::scale_uniform(s.metrics.scale_factor)
      .then(&s.state.transform)
      .then(&matrix),
  );
  let opacity = s.state.alpha;
  let smoothing = s.state.smoothing;
  let clip = s.state.clip.clone();
  let Some(target) = s.target_pixels() else {
    return false;
  };
  target.draw_pixmap(
    0,
    0,
    pixels.as_ref(),
    &PixmapPaint {
      opacity,
      quality: if smoothing {
        tiny_skia::FilterQuality::Bilinear
      } else {
        tiny_skia::FilterQuality::Nearest
      },
      ..Default::default()
    },
    transform,
    mask.as_ref().or(clip.as_deref()),
  );
  true
}