crabshell-render 0.9.2

Draws Crabshell windows into pixmaps: shapes, gradients, shadows, text, icons, images and damage tracking
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
//! Tests for the renderer, by area. Each test runs on its own thread, so
//! each starts with an empty reactive runtime.
//!
//! Golden images live in `tests/golden`. A test compares what it draws with
//! its image, allowing 2/255 per channel. To write the images again, on
//! purpose, run the tests with `CRABSHELL_BLESS=1` and look at every changed
//! image before committing it. They depend on this machine's fonts:
//! `sans-serif` is Noto Sans, and DejaVu Sans and DejaVu Sans Bold supply
//! the snowman.

mod animation;
mod canvas;
mod capture;
mod colors;
mod corners;
mod damage;
mod dashes;
mod decode;
mod effects;
mod filters;
mod glyphs;
mod golden;
mod icons;
mod images;
mod mask_regions;
mod pixel_images;
mod repaint;
mod shapes;
mod status;
mod theme;
mod transform;
mod transitions;

use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use crabshell_reactive::Runtime;
use crabshell_ui::{Cx, Output, PanelWindow, Size, TextSystem, Window};

use crate::{BufferAge, Canvas, DamageHistory, PixelFormat, PixelRect, Renderer};

/// A runtime, a root context, a text system and a renderer, with helpers to
/// build windows and draw them the way the platform does.
struct Scene {
  runtime: Runtime,
  cx: Cx,
  text: TextSystem,
  renderer: Renderer,
}

/// A buffer, with the frame it last held.
#[derive(Clone)]
struct Buffer {
  pixels: Vec<u8>,
  width: u32,
  height: u32,
  scale: f32,
  age: BufferAge,
}

impl Buffer {
  /// A new buffer for `window` at `scale`, all transparent.
  fn new(window: &Window, scale: f32) -> Buffer {
    let size = window.size();
    let width = (size.width * scale).ceil() as u32;
    let height = (size.height * scale).ceil() as u32;
    Buffer {
      pixels: vec![0; width as usize * height as usize * 4],
      width,
      height,
      scale,
      age: BufferAge::default(),
    }
  }

  /// The RGBA bytes of the pixel at `x`, `y`.
  fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
    let index = (y * self.width + x) as usize * 4;
    let mut pixel = [0; 4];
    pixel.copy_from_slice(&self.pixels[index..index + 4]);
    pixel
  }
}

impl Scene {
  fn new() -> Scene {
    let runtime = Runtime::current();
    Scene {
      runtime,
      cx: Cx::new(runtime.new_owner()),
      text: TextSystem::new(),
      renderer: Renderer::new(),
    }
  }

  /// A panel on output "DP-1".
  fn panel(&self) -> PanelWindow {
    PanelWindow::new(&Output::new("DP-1"))
  }

  /// Builds `panel` at `width` by `height`, runs the bindings and lays it
  /// out.
  fn window(&mut self, panel: PanelWindow, width: f32, height: f32) -> Window {
    let window = Window::new(&self.cx, panel);
    window.set_size(Size::new(width, height));
    self.frame(&window);
    window
  }

  /// One event-loop iteration: flush, then layout if needed.
  fn frame(&mut self, window: &Window) {
    self.runtime.flush();
    if window.needs_layout() {
      window.layout(&mut self.text);
    }
  }

  /// Draws the window's damage into `buffer`, which belongs to `history`,
  /// in RGBA order.
  fn draw(
    &mut self,
    window: &Window,
    history: &mut DamageHistory,
    buffer: &mut Buffer,
  ) -> Vec<PixelRect> {
    let damage = window.take_damage();
    self
      .renderer
      .draw(
        &window.view(),
        &damage,
        &mut self.text,
        history,
        Canvas {
          pixels: &mut buffer.pixels,
          width: buffer.width,
          height: buffer.height,
          scale: buffer.scale,
          format: PixelFormat::Abgr8888,
          age: &mut buffer.age,
        },
      )
      .expect("the test's canvas fits")
  }

  /// The whole window drawn into a new buffer at `scale`, leaving its
  /// damage for other draws.
  fn full(&mut self, window: &Window, scale: f32) -> Buffer {
    let mut buffer = Buffer::new(window, scale);
    self
      .renderer
      .draw(
        &window.view(),
        &[],
        &mut self.text,
        &mut DamageHistory::new(),
        Canvas {
          pixels: &mut buffer.pixels,
          width: buffer.width,
          height: buffer.height,
          scale,
          format: PixelFormat::Abgr8888,
          age: &mut buffer.age,
        },
      )
      .expect("the test's canvas fits");
    buffer
  }
}

/// The node at `path` under `root`, as a list of child indexes.
fn node_at<'a>(root: crabshell_ui::NodeView<'a>, path: &[usize]) -> crabshell_ui::NodeView<'a> {
  path.iter().fold(root, |node, &index| {
    node
      .children()
      .nth(index)
      .unwrap_or_else(|| panic!("{} has no child {index}", node.path()))
  })
}

/// The file at `path` as an image's source, for an `ImageView` that
/// outlives the call.
fn file_source(path: &Path) -> &'static crabshell_ui::IconSource {
  Box::leak(Box::new(crabshell_ui::IconSource::File(path.to_owned())))
}

/// A file in `tests/fixtures`.
fn fixture(name: &str) -> PathBuf {
  Path::new(env!("CARGO_MANIFEST_DIR"))
    .join("tests/fixtures")
    .join(name)
}

/// Checks `buffer` against `tests/golden/<name>.png`, allowing 2/255 per
/// premultiplied channel, or writes the image when `CRABSHELL_BLESS` is
/// set. On a mismatch the drawn image is saved under
/// `target/golden-failures`. Images are stored with straight alpha, as PNG
/// expects, and premultiplied again to compare, so faint pixels aren't
/// held to a tighter tolerance than the renderer's own rounding.
fn assert_golden(name: &str, buffer: &Buffer) {
  let straight = demultiplied(&buffer.pixels);
  let path = Path::new(env!("CARGO_MANIFEST_DIR"))
    .join("tests/golden")
    .join(format!("{name}.png"));
  if std::env::var_os("CRABSHELL_BLESS").is_some() {
    write_png(&path, &straight, buffer.width, buffer.height);
    return;
  }
  let Some((expected, width, height)) = read_png(&path) else {
    panic!(
      "no golden image {}; run with CRABSHELL_BLESS=1 to write it",
      path.display()
    );
  };
  let failure = if (width, height) != (buffer.width, buffer.height) {
    Some(format!(
      "size {}x{}, golden {width}x{height}",
      buffer.width, buffer.height
    ))
  } else {
    let mut differing = 0;
    let mut worst = 0;
    let expected = premultiplied(&expected);
    for (drawn, golden) in buffer
      .pixels
      .as_chunks::<4>()
      .0
      .iter()
      .zip(expected.as_chunks::<4>().0)
    {
      let difference = drawn
        .iter()
        .zip(golden)
        .map(|(a, b)| a.abs_diff(*b))
        .max()
        .unwrap_or(0);
      if difference > 2 {
        differing += 1;
      }
      worst = worst.max(difference);
    }
    (differing > 0)
      .then(|| format!("{differing} pixels differ by more than 2/255, the most by {worst}"))
  };
  if let Some(failure) = failure {
    let saved = Path::new(env!("CARGO_MANIFEST_DIR"))
      .join("../../target/golden-failures")
      .join(format!("{name}.png"));
    write_png(&saved, &straight, buffer.width, buffer.height);
    panic!(
      "{name} doesn't match its golden image: {failure}; drawn image saved to {}",
      saved.display()
    );
  }
}

/// Straight RGBA, as PNG stores it, premultiplied.
fn premultiplied(straight: &[u8]) -> Vec<u8> {
  let mut pixels = straight.to_vec();
  for pixel in pixels.as_chunks_mut::<4>().0 {
    let alpha = u16::from(pixel[3]);
    for channel in &mut pixel[..3] {
      *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;
    }
  }
  pixels
}

/// Premultiplied RGBA as straight RGBA, as PNG stores it.
fn demultiplied(premultiplied: &[u8]) -> Vec<u8> {
  let mut straight = premultiplied.to_vec();
  for pixel in straight.as_chunks_mut::<4>().0 {
    let alpha = u16::from(pixel[3]);
    for channel in &mut pixel[..3] {
      if let Some(value) = (u16::from(*channel) * 255 + alpha / 2).checked_div(alpha) {
        *channel = value.min(255) as u8;
      }
    }
  }
  straight
}

fn write_png(path: &Path, rgba: &[u8], width: u32, height: u32) {
  if let Some(parent) = path.parent() {
    std::fs::create_dir_all(parent).expect("create the image's directory");
  }
  let file = std::fs::File::create(path).expect("create the image file");
  let mut encoder = png::Encoder::new(io::BufWriter::new(file), width, height);
  encoder.set_color(png::ColorType::Rgba);
  encoder.set_depth(png::BitDepth::Eight);
  let mut writer = encoder.write_header().expect("write the PNG header");
  writer.write_image_data(rgba).expect("write the PNG pixels");
}

/// An RGBA PNG's pixels and size, or `None` if there is no such file.
fn read_png(path: &Path) -> Option<(Vec<u8>, u32, u32)> {
  let file = std::fs::File::open(path).ok()?;
  let decoder = png::Decoder::new(io::BufReader::new(file));
  let mut reader = decoder.read_info().expect("a golden image is a PNG");
  let mut pixels = vec![0; reader.output_buffer_size().expect("a small image")];
  let info = reader
    .next_frame(&mut pixels)
    .expect("a golden image decodes");
  assert_eq!(
    info.color_type,
    png::ColorType::Rgba,
    "golden images are RGBA"
  );
  pixels.truncate(info.width as usize * info.height as usize * 4);
  Some((pixels, info.width, info.height))
}

/// Runs `f` and returns everything it logged through `tracing`.
fn capture_logs(f: impl FnOnce()) -> String {
  #[derive(Clone, Default)]
  struct Logs(Arc<Mutex<Vec<u8>>>);

  impl io::Write for Logs {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
      self
        .0
        .lock()
        .expect("log buffer lock")
        .extend_from_slice(bytes);
      Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
      Ok(())
    }
  }

  static GLOBAL: std::sync::Once = std::sync::Once::new();
  GLOBAL.call_once(|| {
    let _ = tracing::subscriber::set_global_default(Undecided);
  });
  let logs = Logs::default();
  let writer = logs.clone();
  let subscriber = tracing_subscriber::fmt()
    .with_writer(move || writer.clone())
    .finish();
  tracing::subscriber::with_default(subscriber, f);
  let bytes = logs.0.lock().expect("log buffer lock").clone();
  String::from_utf8(bytes).expect("log output is UTF-8")
}

/// The global subscriber while tests capture logs: it takes nothing, and
/// answers every callsite with "sometimes". tracing caches each callsite's
/// interest, and while it counts one subscriber it asks the thread that
/// first hits the callsite, so a thread capturing nothing could otherwise
/// turn a log line off for another thread's capture.
struct Undecided;

impl tracing::Subscriber for Undecided {
  fn register_callsite(
    &self,
    _: &'static tracing::Metadata<'static>,
  ) -> tracing::subscriber::Interest {
    tracing::subscriber::Interest::sometimes()
  }

  fn max_level_hint(&self) -> Option<tracing::level_filters::LevelFilter> {
    Some(tracing::level_filters::LevelFilter::TRACE)
  }

  fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
    false
  }

  fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
    tracing::span::Id::from_u64(1)
  }

  fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}

  fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}

  fn event(&self, _: &tracing::Event<'_>) {}

  fn enter(&self, _: &tracing::span::Id) {}

  fn exit(&self, _: &tracing::span::Id) {}
}

/// A test's file or directory, removed when the test ends, a panic
/// included, so test runs leave nothing in the temp dir.
struct Removed(std::path::PathBuf);

impl std::ops::Deref for Removed {
  type Target = std::path::PathBuf;

  fn deref(&self) -> &std::path::PathBuf {
    &self.0
  }
}

impl Drop for Removed {
  fn drop(&mut self) {
    if std::fs::remove_dir_all(&self.0).is_err() {
      let _ = std::fs::remove_file(&self.0);
    }
  }
}