lurq 0.65.1

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
use super::*;
impl CanvasHandle {
  pub(crate) fn new() -> Self {
    Self {
      inner: Arc::new(Mutex::new(Surface {
        id: CanvasId(NEXT_CANVAS_ID.fetch_add(1, Ordering::Relaxed)),
        metrics: CanvasMetrics {
          size: Size::new(0.0, 0.0),
          pixel_width: 0,
          pixel_height: 0,
          scale_factor: 1.0,
          revision: 0,
        },
        pixels: None,
        software: false,
        commands: Vec::new(),
        command_bytes: 0,
        layers: Vec::new(),
        layer_bytes: 0,
        layer_commands: 0,
        software_layers: Vec::new(),
        presentation_pixels: None,
        artwork_pixels: None,
        next_artwork_pixels: None,
        presentation_revision: 0,
        visible_revision: 0,
        presentation_serial: 0,
        presentation_refused: false,
        presentation: None,
        inflight_bytes: 0,
        gpu_bytes: 0,
        gpu: CanvasGpuStats::default(),
        native: None,
        readbacks: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        state: DrawingState::default(),
        defaults: DrawingState::default(),
        stack: Vec::new(),
        path: Path2D::new(),
        revision: 0,
        exported_revision: 0,
        pending_paint: false,
        image: None,
        attached: false,
        window: None,
        to_window: Transform2D::IDENTITY,
        observers: Vec::new(),
        text: None,
        error: None,
        items: Arc::from([]),
        warned_duplicates: None,
        painted: None,
        shown: None,
        run: None,
      })),
    }
  }

  /// A canvas of `width` by `height` logical pixels at `scale_factor` device pixels to one, in no window and drawn
  /// on the CPU: what is drawn on its [`context_2d`](Self::context_2d) is in its pixels at once, read by
  /// [`snapshot`](Self::snapshot) (ready when it returns) or as an [`ImageData`] by
  /// [`to_image_data`](Self::to_image_data). For a picture made of a drawing: a signature to store, a chart to
  /// save. It draws no text, since it has no window's fonts. `None` where the size is not a number, is nothing, or is
  /// larger than a canvas can be.
  pub fn offscreen(width: f32, height: f32, scale_factor: f32) -> Option<Self> {
    let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
      scale_factor
    } else {
      1.0
    };
    let (pixel_width, pixel_height) = (
      f64::from(width) * f64::from(scale),
      f64::from(height) * f64::from(scale),
    );
    if !pixel_width.is_finite()
      || !pixel_height.is_finite()
      || pixel_width.ceil() < 1.0
      || pixel_height.ceil() < 1.0
      || pixel_width.ceil() > 16384.0
      || pixel_height.ceil() > 16384.0
      || pixel_width.ceil() * pixel_height.ceil() > MAX_PIXELS as f64
    {
      return None;
    }
    let (pixel_width, pixel_height) = (pixel_width.ceil() as u32, pixel_height.ceil() as u32);
    let canvas = Self::new();
    {
      let mut s = canvas.inner.lock();
      s.attached = true;
      s.software = true;
      s.metrics = CanvasMetrics {
        size: Size::new(width, height),
        pixel_width,
        pixel_height,
        scale_factor: scale,
        revision: 1,
      };
      s.pixels = Some(Pixmap::new(pixel_width, pixel_height)?);
    }
    Some(canvas)
  }

  /// What the canvas shows, as an image of straight RGBA pixels: of a canvas drawn on the CPU (an
  /// [`offscreen`](Self::offscreen) one), what is drawn on it now; `None` for one drawn on the GPU, which is read by
  /// [`snapshot`](Self::snapshot), or one with no pixels yet.
  pub fn to_image_data(&self) -> Option<ImageData> {
    let s = self.inner.lock();
    if !s.software || s.metrics.pixel_width == 0 || s.metrics.pixel_height == 0 {
      return None;
    }
    s.pixels.as_ref()?;
    Some(ImageData::from_rgba(
      s.straight_pixels(),
      s.metrics.pixel_width,
      s.metrics.pixel_height,
    ))
  }

  /// Schedules an ordinary paint pass, including a retry after GPU presentation backpressure.
  pub fn request_paint(&self) {
    let mut s = self.inner.lock();
    if !s.attached {
      return;
    }
    s.pending_paint = true;
    let window = s.window.clone();
    drop(s);
    if let Some(window) = window {
      window.wake();
    }
  }
  pub fn surface_id(&self) -> CanvasId {
    self.inner.lock().id
  }
  pub fn context_2d(&self) -> Context2D {
    Context2D { canvas: self.clone() }
  }
  pub fn size(&self) -> Size {
    self.inner.lock().metrics.size
  }
  pub fn pixel_size(&self) -> (u32, u32) {
    let s = self.inner.lock();
    (s.metrics.pixel_width, s.metrics.pixel_height)
  }
  pub fn scale_factor(&self) -> f32 {
    self.inner.lock().metrics.scale_factor
  }
  pub fn metrics(&self) -> CanvasMetrics {
    self.inner.lock().metrics
  }
  pub fn is_attached(&self) -> bool {
    self.inner.lock().attached
  }
  pub fn status(&self) -> CanvasStatus {
    let s = self.inner.lock();
    CanvasStatus {
      attached: s.attached,
      metrics: s.metrics,
      content_revision: s.revision,
      error: s.error.clone(),
      pending_bytes: s.command_bytes + s.layer_bytes + s.inflight_bytes,
      gpu_bytes: s.gpu_bytes,
      software: s.software,
      gpu: s.gpu,
    }
  }

  /// Receives the current metrics immediately, then committed size/scale changes; and the metrics again, as
  /// they are, where what was drawn is gone with the graphics device it was on (the card was reset): what
  /// draws the canvas when its size changes draws it again then.
  pub fn observe_metrics(&self, callback: impl Fn(CanvasMetrics) + Send + Sync + 'static) -> CanvasObserver {
    let callback: Arc<MetricsCallback> = Arc::new(callback);
    let metrics = {
      let mut s = self.inner.lock();
      s.observers.retain(|o| o.strong_count() > 0);
      s.observers.push(Arc::downgrade(&callback));
      s.metrics
    };
    callback(metrics);
    CanvasObserver { _callback: callback }
  }

  /// Converts window-logical input to content coordinates, without undoing the drawing transform.
  pub fn point_from_window(&self, x: f32, y: f32) -> Option<(f32, f32)> {
    let s = self.inner.lock();
    if !s.attached || !x.is_finite() || !y.is_finite() {
      return None;
    }
    s.to_window.inverse_affine().map(|m| m.transform_point(x, y))
  }

  /// Queue an ordered GPU readback. Never wait for it on the rendering thread.
  pub fn snapshot(&self) -> CanvasReadback {
    let (ticket, mut done) = CanvasReadback::pair();
    let wake = {
      let mut s = self.inner.lock();
      if s.software {
        done.finish(Ok(CanvasSnapshot {
          width: s.metrics.pixel_width,
          height: s.metrics.pixel_height,
          rgba: s.straight_pixels(),
          revision: s.visible_revision,
        }));
        return ticket;
      }
      if !s.attached {
        done.finish(Err(CanvasError::Detached));
        return ticket;
      }
      if !done.reserve(&s.readbacks) {
        done.finish(Err(CanvasError::QueueFull));
        return ticket;
      }
      let (metrics, revision) = (s.metrics, s.revision);
      // Commit/abort recording may advance without publishing. Ordinary pixels()
      // updates visible_revision immediately, preserving its ordered legacy read.
      let complete = s.presentation_serial != 0 && s.visible_revision != revision;
      if s.enqueue(gpu::Command::Readback(done, metrics, revision, complete)) {
        s.pending_paint = true;
        s.window.clone()
      } else {
        None
      }
    };
    if let Some(window) = wake {
      window.wake();
    }
    ticket
  }

  pub(crate) fn update_placement(&self, matrix: Transform2D) {
    self.inner.lock().to_window = matrix;
  }

  /// Whether a painter of `key` is to draw the surface: its key is another than the one it last drew for, or the
  /// surface's metrics changed. Where it is, `key` is the one drawn for from now.
  /// Draws the canvas with `painter` if it is due: when it is first laid out, when its size or scale changed
  /// (`metrics_changed`), or when the painter's key did. A moving painter starts a motion when what it draws
  /// toward changes, and enters when first drawn, unless `still` (motion is reduced) or the canvas is being
  /// resized: a resize ends a motion on its way, and the drawing is drawn where it goes. Returns whether it drew.
  pub(crate) fn paint_with(
    &self,
    painter: &super::CanvasPainter,
    metrics_changed: bool,
    now: crate::time::Instant,
    still: bool,
  ) -> bool {
    let mut s = self.inner.lock();
    if !s.attached {
      return false;
    }
    let first = s.painted.is_none();
    let mut due = metrics_changed || s.painted != Some(painter.key);
    s.painted = Some(painter.key);
    let resized = metrics_changed && !first;
    match &painter.motion {
      Some(motion) => {
        if s.shown.as_ref().map(|(of, _)| *of) != Some(motion.of) {
          let from = s.shown.take().map(|(_, value)| value);
          s.shown = Some((motion.of, motion.value.clone()));
          let moves = !still && !resized && !motion.motion.duration.is_zero() && (first || from.is_some());
          s.run = moves.then(|| super::Run {
            from,
            started: now,
            motion: motion.motion,
            paint: painter.paint.clone(),
          });
          due = true;
        } else if resized || still {
          s.run = None;
        }
        // A drawing on its way goes on with the painter it was last given (the point under the pointer, say).
        if let Some(run) = s.run.as_mut() {
          run.paint = painter.paint.clone();
        }
      }
      None => {
        s.shown = None;
        s.run = None;
      }
    }
    if !due {
      return false;
    }
    let from = s.run.as_ref().and_then(|run| run.from.clone());
    let to = s.shown.as_ref().map(|(_, value)| value.clone());
    let progress = s.run.as_ref().map_or(1.0, |run| run.progress(now));
    if progress >= 1.0 {
      s.run = None;
    }
    drop(s);
    let frame = super::PaintFrame {
      from: if progress >= 1.0 { None } else { from.as_ref() },
      to: to.as_ref(),
      progress,
    };
    (painter.paint)(self, &frame);
    true
  }

  /// Whether the canvas's drawing is on its way somewhere: it is drawn again at each frame until it gets there.
  pub(crate) fn moving(&self) -> bool {
    let s = self.inner.lock();
    s.attached && s.run.is_some()
  }

  /// Draws a moving canvas where it is at `now`, and ends its motion once it is there. Returns whether it drew.
  pub(crate) fn advance_motion(&self, now: crate::time::Instant) -> bool {
    let mut s = self.inner.lock();
    if !s.attached {
      return false;
    }
    let Some(run) = s.run.as_ref() else {
      return false;
    };
    let progress = run.progress(now);
    let paint = run.paint.clone();
    let from = run.from.clone();
    let to = s.shown.as_ref().map(|(_, value)| value.clone());
    if progress >= 1.0 {
      s.run = None;
    }
    s.pending_paint = true;
    drop(s);
    let frame = super::PaintFrame {
      from: if progress >= 1.0 { None } else { from.as_ref() },
      to: to.as_ref(),
      progress,
    };
    paint(self, &frame);
    true
  }

  pub(crate) fn clone_empty(&self) -> Self {
    let next = Self::new();
    next.inner.lock().software = self.inner.lock().software;
    next
  }
  pub(crate) fn downgrade(&self) -> CanvasWeak {
    CanvasWeak {
      inner: Arc::downgrade(&self.inner),
    }
  }
  /// What the canvas held is gone with the renderer that drew it: its graphics device was lost, and another
  /// renderer draws the window now, with an empty surface for this canvas. A canvas that has a painter is
  /// drawn again by it at the tree's next pass, and who observes the canvas's metrics is told them again, to
  /// draw as when the size changes. One drawn on the CPU has lost nothing.
  pub(crate) fn content_lost(&self) {
    let (metrics, observers) = {
      let mut s = self.inner.lock();
      if !s.attached || s.software {
        return;
      }
      s.painted = None;
      if s.error == Some(CanvasError::RendererLost) {
        s.error = None;
      }
      // What was on its way to the lost renderer is not waited for, as when the canvas is of another size.
      s.presentation_pixels = None;
      s.next_artwork_pixels = None;
      s.presentation = None;
      s.presentation_refused = false;
      s.presentation_serial = s.presentation_serial.saturating_add(1);
      s.pending_paint = true;
      let observers: Vec<_> = s.observers.iter().filter_map(Weak::upgrade).collect();
      (s.metrics, observers)
    };
    for observer in observers {
      observer(metrics);
    }
  }
  pub(crate) fn dirty(&self) -> bool {
    let s = self.inner.lock();
    s.attached && s.pending_paint
  }
  pub(crate) fn consume_paint(&self) -> bool {
    let mut s = self.inner.lock();
    let pending = s.attached && s.pending_paint;
    s.pending_paint = false;
    pending
  }
  pub(crate) fn detach(&self) {
    let mut s = self.inner.lock();
    s.attached = false;
    s.run = None;
    s.window = None;
    s.commands.clear();
    s.command_bytes = 0;
    s.discard_layers();
    s.software_layers.clear();
    s.presentation_pixels = None;
    s.artwork_pixels = None;
    s.next_artwork_pixels = None;
    s.presentation = None;
    s.presentation_serial = s.presentation_serial.saturating_add(1);
  }

  pub(crate) fn bind_layout(
    &self,
    size: Size,
    scale: f32,
    to_window: Transform2D,
    window: Window,
    font: CanvasFont,
    text: Arc<Mutex<CanvasTextEngine>>,
  ) -> Option<(CanvasMetrics, Vec<Arc<MetricsCallback>>)> {
    let mut s = self.inner.lock();
    s.attached = true;
    s.window = Some(window);
    s.to_window = to_window;
    s.text = Some(text);
    let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
    let size = Size::new(size.width.max(0.0), size.height.max(0.0));
    if s.metrics.revision != 0 && s.metrics.size == size && s.metrics.scale_factor == scale {
      return None;
    }
    let first = s.metrics.revision == 0;
    let resized = first || s.metrics.size != size;
    let old_scale = s.metrics.scale_factor;
    let dims = (
      f64::from(size.width) * f64::from(scale),
      f64::from(size.height) * f64::from(scale),
    );
    let valid = dims.0.is_finite()
      && dims.1.is_finite()
      && dims.0.ceil() <= 16384.0
      && dims.1.ceil() <= 16384.0
      && dims.0.ceil() * dims.1.ceil() <= MAX_PIXELS as f64;
    let (width, height) = if valid {
      (dims.0.ceil() as u32, dims.1.ceil() as u32)
    } else {
      (0, 0)
    };
    let mut next = if s.software && width > 0 && height > 0 {
      Pixmap::new(width, height)
    } else {
      None
    };
    s.error = if !valid || (s.software && width > 0 && height > 0 && next.is_none()) {
      Some(CanvasError::SurfaceTooLarge)
    } else {
      None
    };
    if !resized && s.error.is_some() {
      // A display-scale allocation failure must not discard the old bitmap.
      return None;
    }
    if !s.software
      && !resized
      && (s.commands.len() + s.layer_commands >= gpu::MAX_COMMANDS
        || s.command_bytes + s.layer_bytes + s.inflight_bytes + std::mem::size_of::<gpu::Command>()
          > gpu::MAX_QUEUE_BYTES)
    {
      s.error = Some(CanvasError::QueueFull);
      return None;
    }
    if resized {
      if first {
        s.defaults.font = font;
      }
      s.state = s.defaults.clone();
      s.stack.clear();
      s.path = Path2D::new();
      s.discard_layers();
      s.software_layers.clear();
      // The pixels the items described are gone; the redraw registers new ones.
      s.items = Arc::from([]);
    } else if s.software {
      if let (Some(old), Some(next)) = (s.pixels.as_ref(), next.as_mut()) {
        next.draw_pixmap(
          0,
          0,
          old.as_ref(),
          &PixmapPaint {
            quality: tiny_skia::FilterQuality::Bilinear,
            ..Default::default()
          },
          tiny_skia::Transform::from_scale(scale / old_scale, scale / old_scale),
          None,
        );
      }
      let factor = scale / old_scale;
      let mut masks = std::collections::HashMap::new();
      for state in s.stack.iter().chain(std::iter::once(&s.state)) {
        if let Some(mask) = &state.clip {
          masks.entry(Arc::as_ptr(mask)).or_insert_with(|| mask.clone());
        }
      }
      // Keep the previous backing scale if saved clips cannot fit at the new scale.
      // Shared clips remain shared, including after a display-scale transition.
      if u64::from(width) * u64::from(height) * masks.len() as u64 > MAX_CLIP_BYTES as u64 {
        s.error = Some(CanvasError::StateLimit);
        return None;
      }
      let masks: std::collections::HashMap<_, _> = masks
        .into_iter()
        .map(|(key, mask)| (key, rescale_clip(&mask, width, height, factor)))
        .collect();
      for state in &mut s.stack {
        if let Some(mask) = &state.clip {
          state.clip = masks[&Arc::as_ptr(mask)].clone();
        }
      }
      if let Some(mask) = &s.state.clip {
        s.state.clip = masks[&Arc::as_ptr(mask)].clone();
      }
    }
    if !s.software {
      if resized {
        s.commands.clear();
        s.command_bytes = 0;
      }
      s.enqueue(gpu::Command::Resize {
        width,
        height,
        preserve: !resized,
      });
      s.native = None;
      s.pending_paint = true;
    }
    s.presentation_pixels = None;
    s.next_artwork_pixels = None;
    s.presentation = None;
    s.presentation_serial = s.presentation_serial.saturating_add(1);
    s.pixels = next;
    s.image = None;
    s.revision += 1;
    s.metrics = CanvasMetrics {
      size,
      pixel_width: width,
      pixel_height: height,
      scale_factor: scale,
      revision: s.metrics.revision + 1,
    };
    let callbacks = s.observers.iter().filter_map(Weak::upgrade).collect();
    Some((s.metrics, callbacks))
  }

  pub(crate) fn image_data(&self) -> Option<ImageData> {
    let mut s = self.inner.lock();
    s.pending_paint = false;
    if !s.software {
      if s.metrics.pixel_width == 0 || s.metrics.pixel_height == 0 {
        return None;
      }
      if s.native.is_none() {
        s.native = Some(NativeImageData::new(
          s.metrics.pixel_width,
          s.metrics.pixel_height,
          ImagePixelFormat::Rgba8,
          NativeImageBackend::Canvas,
          self.downgrade(),
        ));
      }
      return s.native.as_ref().map(NativeImageData::image_data);
    }
    s.pixels.as_ref()?;
    if s.image.is_none() || s.revision != s.exported_revision {
      let data = s.straight_pixels();
      if let Some(image) = &s.image {
        image.set_rgba(data);
      } else {
        s.image = Some(StreamingImage::new_rgba_manual_redraw(
          data,
          s.metrics.pixel_width,
          s.metrics.pixel_height,
        ));
      }
      s.exported_revision = s.revision;
    }
    s.image.as_ref().map(StreamingImage::image_data)
  }
}

/// One open isolated layer on the software backend. The GPU backends keep their
/// layers as recorded commands instead; see `gpu::LayerFrame`.
pub(super) struct SoftwareLayer {
  /// `None` only for a zero-sized surface, where the layer still has to exist so
  /// that `end_layer` stays balanced with `begin_layer`.
  pub(super) pixels: Option<Pixmap>,
  pub(super) alpha: f32,
  pub(super) blend: BlendMode,
}

/// A paint with its geometry resolved against the box it was given and the
/// transform in force: what both backends draw from.
pub(super) enum ResolvedPaint {
  Solid(Color),
  Gradient {
    gradient: Gradient,
    /// Model coordinates to the gradient's own frame, for GPU vertices.
    frame_from_model: Transform2D,
    /// The gradient's own frame to user coordinates, for a software shader.
    user_from_frame: Transform2D,
  },
}