1use sctk::compositor::{CompositorHandler, CompositorState};
15use sctk::output::{OutputHandler, OutputState};
16use sctk::reexports::client::globals::{GlobalList, registry_queue_init};
17use sctk::reexports::client::protocol::{wl_output, wl_shm, wl_surface};
18use sctk::reexports::client::{Connection, Dispatch, EventQueue, QueueHandle};
19use sctk::reexports::protocols::wp::viewporter::client::{wp_viewport, wp_viewporter};
20use sctk::registry::{ProvidesRegistryState, RegistryState, SimpleGlobal};
21use sctk::shell::WaylandSurface;
22use sctk::shell::wlr_layer::{
23 Anchor, KeyboardInteractivity, Layer, LayerShell, LayerShellHandler, LayerSurface,
24 LayerSurfaceConfigure,
25};
26use sctk::shm::slot::{Buffer, SlotPool};
27use sctk::shm::{Shm, ShmHandler};
28use sctk::{
29 delegate_compositor, delegate_layer, delegate_output, delegate_registry, delegate_shm,
30 delegate_simple, registry_handlers,
31};
32use smithay_client_toolkit as sctk;
33use std::os::fd::AsRawFd;
34use std::path::Path;
35use std::sync::Mutex;
36use std::sync::mpsc;
37use std::time::Duration;
38
39const NAMESPACE: &str = "clairlune";
41const MAX_RECTS: usize = 64;
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct Rect {
47 pub x: u32,
48 pub y: u32,
49 pub w: u32,
50 pub h: u32,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct Output {
56 pub name: String,
58 pub width: u32,
60 pub height: u32,
61}
62
63pub fn fill_crop(image: (u32, u32), output: (u32, u32)) -> (f64, f64, f64, f64) {
67 let (iw, ih) = (f64::from(image.0), f64::from(image.1));
68 let (ow, oh) = (f64::from(output.0.max(1)), f64::from(output.1.max(1)));
69 let scale = (iw / ow).min(ih / oh);
70 let (w, h) = (ow * scale, oh * scale);
71 ((iw - w) / 2.0, (ih - h) / 2.0, w, h)
72}
73
74fn add_damage(list: &mut Vec<Rect>, more: &[Rect]) {
78 list.extend_from_slice(more);
79 if list.len() > MAX_RECTS {
80 *list = bounded(std::mem::take(list));
81 }
82}
83
84fn bounded(rects: Vec<Rect>) -> Vec<Rect> {
87 if rects.len() <= MAX_RECTS {
88 return rects;
89 }
90 let x0 = rects.iter().map(|r| r.x).min().unwrap_or(0);
91 let y0 = rects.iter().map(|r| r.y).min().unwrap_or(0);
92 let x1 = rects.iter().map(|r| r.x + r.w).max().unwrap_or(0);
93 let y1 = rects.iter().map(|r| r.y + r.h).max().unwrap_or(0);
94 vec![Rect {
95 x: x0,
96 y: y0,
97 w: x1 - x0,
98 h: y1 - y0,
99 }]
100}
101
102pub fn output_sizes() -> Result<Vec<(u32, u32)>, String> {
105 let conn = Connection::connect_to_env().map_err(|e| format!("Wayland: {e}"))?;
106 let (globals, mut queue) =
107 registry_queue_init::<State>(&conn).map_err(|e| format!("Wayland: {e}"))?;
108 let qh = queue.handle();
109 let mut state = bind(&globals, &qh, (0, 0))?;
110 for _ in 0..2 {
111 queue
112 .roundtrip(&mut state)
113 .map_err(|e| format!("Wayland: {e}"))?;
114 }
115 let mut sizes: Vec<(u32, u32)> = state
116 .outputs
117 .outputs()
118 .filter(|o| state.outputs.info(o).is_some())
119 .map(|o| state.physical(&o))
120 .filter(|&(w, h)| w > 1 && h > 1)
121 .collect();
122 sizes.sort_by_key(|&(w, h)| std::cmp::Reverse(u64::from(w) * u64::from(h)));
123 Ok(sizes)
124}
125
126pub fn available() -> Result<(), String> {
129 if std::env::var_os("WAYLAND_DISPLAY").is_none() {
130 return Err("not a Wayland session".into());
131 }
132 let conn = Connection::connect_to_env().map_err(|e| format!("Wayland: {e}"))?;
133 let (globals, _queue) =
134 registry_queue_init::<Probe>(&conn).map_err(|e| format!("Wayland: {e}"))?;
135 let names: Vec<String> = globals
136 .contents()
137 .with_list(|l| l.iter().map(|g| g.interface.clone()).collect());
138 for needed in ["zwlr_layer_shell_v1", "wl_shm", "wp_viewporter"] {
139 if !names.iter().any(|n| n == needed) {
140 return Err(format!("the compositor has no `{needed}`"));
141 }
142 }
143 Ok(())
144}
145
146struct Probe;
148impl
149 Dispatch<
150 sctk::reexports::client::protocol::wl_registry::WlRegistry,
151 sctk::reexports::client::globals::GlobalListContents,
152 > for Probe
153{
154 fn event(
155 _: &mut Self,
156 _: &sctk::reexports::client::protocol::wl_registry::WlRegistry,
157 _: sctk::reexports::client::protocol::wl_registry::Event,
158 _: &sctk::reexports::client::globals::GlobalListContents,
159 _: &Connection,
160 _: &QueueHandle<Self>,
161 ) {
162 }
163}
164
165struct Slotted {
167 buffer: Buffer,
168 stale: Vec<Rect>,
169}
170
171struct Entry {
173 output: wl_output::WlOutput,
174 layer: LayerSurface,
175 viewport: wp_viewport::WpViewport,
176 size: Option<(u32, u32)>,
178 physical: (u32, u32),
180 waiting: bool,
182 damage: Vec<Rect>,
185 fresh: bool,
186 buffers: Vec<Slotted>,
187}
188
189impl Drop for Entry {
190 fn drop(&mut self) {
192 self.viewport.destroy();
193 }
194}
195
196struct State {
197 registry: RegistryState,
198 outputs: OutputState,
199 compositor: CompositorState,
200 layer_shell: LayerShell,
201 shm: Shm,
202 viewporter: SimpleGlobal<wp_viewporter::WpViewporter, 1>,
203 entries: Vec<Entry>,
204 image: (u32, u32),
205 started: bool,
208}
209
210impl State {
211 fn physical(&self, output: &wl_output::WlOutput) -> (u32, u32) {
212 let Some(info) = self.outputs.info(output) else {
213 return self.image;
214 };
215 let mode = info
216 .modes
217 .iter()
218 .find(|m| m.current)
219 .map(|m| m.dimensions)
220 .or_else(|| {
221 info.logical_size
222 .map(|(w, h)| (w * info.scale_factor, h * info.scale_factor))
223 })
224 .unwrap_or((self.image.0 as i32, self.image.1 as i32));
225 let (w, h) = (mode.0.max(1) as u32, mode.1.max(1) as u32);
226 match info.transform {
228 wl_output::Transform::_90
229 | wl_output::Transform::_270
230 | wl_output::Transform::Flipped90
231 | wl_output::Transform::Flipped270 => (h, w),
232 _ => (w, h),
233 }
234 }
235
236 fn add(&mut self, qh: &QueueHandle<State>, output: wl_output::WlOutput) {
237 if self.entries.iter().any(|e| e.output == output) {
238 return;
239 }
240 let Ok(viewporter) = self.viewporter.get() else {
241 return;
242 };
243 let surface = self.compositor.create_surface(qh);
244 let viewport = viewporter.get_viewport(&surface, qh, ());
245 let layer = self.layer_shell.create_layer_surface(
246 qh,
247 surface,
248 Layer::Background,
249 Some(NAMESPACE),
250 Some(&output),
251 );
252 layer.set_anchor(Anchor::TOP | Anchor::BOTTOM | Anchor::LEFT | Anchor::RIGHT);
253 layer.set_exclusive_zone(-1);
255 layer.set_keyboard_interactivity(KeyboardInteractivity::None);
256 layer.set_size(0, 0);
257 if let Ok(region) = sctk::compositor::Region::new(&self.compositor) {
259 layer
260 .wl_surface()
261 .set_input_region(Some(region.wl_region()));
262 }
263 layer.commit();
264 let physical = self.physical(&output);
265 self.entries.push(Entry {
266 output,
267 layer,
268 viewport,
269 size: None,
270 physical,
271 waiting: false,
272 damage: Vec::new(),
273 fresh: true,
274 buffers: Vec::new(),
275 });
276 }
277}
278
279pub struct Surfaces {
281 queue: EventQueue<State>,
282 state: State,
283 pool: SlotPool,
284}
285
286impl Surfaces {
287 pub fn new(size: (u32, u32)) -> Result<Surfaces, String> {
290 let conn = Connection::connect_to_env().map_err(|e| format!("Wayland: {e}"))?;
291 let (globals, queue) =
292 registry_queue_init::<State>(&conn).map_err(|e| format!("Wayland: {e}"))?;
293 let qh = queue.handle();
294 let state = bind(&globals, &qh, size)?;
295 let pool = SlotPool::new((size.0 * size.1 * 4) as usize, &state.shm)
296 .map_err(|e| format!("shared memory: {e}"))?;
297 let mut s = Surfaces { queue, state, pool };
298 for _ in 0..2 {
301 s.queue
302 .roundtrip(&mut s.state)
303 .map_err(|e| format!("Wayland: {e}"))?;
304 }
305 let outputs: Vec<_> = s.state.outputs.outputs().collect();
306 for o in outputs {
307 s.state.add(&qh, o);
308 }
309 s.state.started = true;
310 s.queue
311 .roundtrip(&mut s.state)
312 .map_err(|e| format!("Wayland: {e}"))?;
313 if s.state.entries.is_empty() {
314 return Err("no outputs".into());
315 }
316 Ok(s)
317 }
318
319 pub fn image_size(&self) -> (u32, u32) {
321 self.state.image
322 }
323
324 pub fn outputs(&self) -> Vec<Output> {
326 self.state
327 .entries
328 .iter()
329 .map(|e| {
330 let info = self.state.outputs.info(&e.output);
331 Output {
332 name: info
333 .as_ref()
334 .and_then(|i| i.name.clone())
335 .unwrap_or_else(|| format!("wl-output-{}", info.map_or(0, |i| i.id))),
336 width: e.physical.0,
337 height: e.physical.1,
338 }
339 })
340 .collect()
341 }
342
343 pub fn dispatch(&mut self, wait: Duration) -> Result<(), String> {
346 self.queue.flush().map_err(|e| format!("Wayland: {e}"))?;
347 if let Some(guard) = self.queue.prepare_read() {
348 let mut fd = libc::pollfd {
349 fd: guard.connection_fd().as_raw_fd(),
350 events: libc::POLLIN,
351 revents: 0,
352 };
353 let ms = wait.as_millis().min(i32::MAX as u128) as i32;
354 let ready = unsafe { libc::poll(&mut fd, 1, ms) };
356 if ready > 0 {
357 guard.read().map_err(|e| format!("Wayland: {e}"))?;
358 }
359 }
360 self.queue
361 .dispatch_pending(&mut self.state)
362 .map_err(|e| format!("Wayland: {e}"))?;
363 Ok(())
364 }
365
366 pub fn pending(&self) -> usize {
368 self.state.entries.iter().filter(|e| e.fresh).count()
369 }
370
371 pub fn present(
377 &mut self,
378 changed: &[Rect],
379 fill: &mut dyn FnMut(Rect, &mut [u8], usize),
380 ) -> Result<usize, String> {
381 let qh = self.queue.handle();
382 let (iw, ih) = self.state.image;
383 let whole = Rect {
384 x: 0,
385 y: 0,
386 w: iw,
387 h: ih,
388 };
389 let stride = iw as usize * 4;
390 let mut drawn = 0;
391 for e in &mut self.state.entries {
392 add_damage(&mut e.damage, changed);
393 for b in &mut e.buffers {
394 add_damage(&mut b.stale, changed);
395 }
396 let Some((lw, lh)) = e.size else { continue };
397 if e.waiting || (e.damage.is_empty() && !e.fresh) {
398 continue;
399 }
400 let free = e
402 .buffers
403 .iter()
404 .position(|b| b.buffer.canvas(&mut self.pool).is_some());
405 let i = match free {
406 Some(i) => i,
407 None if e.buffers.len() < 2 => {
408 let (buffer, _) = self
409 .pool
410 .create_buffer(
411 iw as i32,
412 ih as i32,
413 stride as i32,
414 wl_shm::Format::Xrgb8888,
415 )
416 .map_err(|err| format!("shared memory: {err}"))?;
417 e.buffers.push(Slotted {
418 buffer,
419 stale: vec![whole],
420 });
421 e.buffers.len() - 1
422 }
423 None => continue, };
425 let slot = &mut e.buffers[i];
426 let canvas = slot
427 .buffer
428 .canvas(&mut self.pool)
429 .ok_or("a free buffer has no canvas")?;
430 for r in bounded(std::mem::take(&mut slot.stale)) {
431 fill(r, canvas, stride);
432 }
433 let surface = e.layer.wl_surface();
434 let damage = if e.fresh {
435 vec![whole]
436 } else {
437 bounded(std::mem::take(&mut e.damage))
438 };
439 for r in damage {
440 surface.damage_buffer(r.x as i32, r.y as i32, r.w as i32, r.h as i32);
441 }
442 e.damage.clear();
443 let (sx, sy, sw, sh) = fill_crop((iw, ih), e.physical);
444 e.viewport.set_source(sx, sy, sw, sh);
445 e.viewport.set_destination(lw as i32, lh as i32);
446 surface.frame(&qh, surface.clone());
447 slot.buffer
448 .attach_to(surface)
449 .map_err(|err| format!("attach: {err:?}"))?;
450 e.layer.commit();
451 e.waiting = true;
452 e.fresh = false;
453 drawn += 1;
454 }
455 self.queue.flush().map_err(|e| format!("Wayland: {e}"))?;
456 Ok(drawn)
457 }
458}
459
460fn bind(globals: &GlobalList, qh: &QueueHandle<State>, image: (u32, u32)) -> Result<State, String> {
461 Ok(State {
462 registry: RegistryState::new(globals),
463 outputs: OutputState::new(globals, qh),
464 compositor: CompositorState::bind(globals, qh)
465 .map_err(|e| format!("wl_compositor: {e}"))?,
466 layer_shell: LayerShell::bind(globals, qh)
467 .map_err(|e| format!("the compositor has no layer shell: {e}"))?,
468 shm: Shm::bind(globals, qh).map_err(|e| format!("wl_shm: {e}"))?,
469 viewporter: SimpleGlobal::bind(globals, qh).map_err(|e| format!("wp_viewporter: {e}"))?,
470 entries: Vec::new(),
471 image,
472 started: false,
473 })
474}
475
476impl CompositorHandler for State {
477 fn scale_factor_changed(
478 &mut self,
479 _: &Connection,
480 _: &QueueHandle<Self>,
481 _: &wl_surface::WlSurface,
482 _: i32,
483 ) {
484 }
485
486 fn transform_changed(
487 &mut self,
488 _: &Connection,
489 _: &QueueHandle<Self>,
490 _: &wl_surface::WlSurface,
491 _: wl_output::Transform,
492 ) {
493 }
494
495 fn frame(
496 &mut self,
497 _: &Connection,
498 _: &QueueHandle<Self>,
499 surface: &wl_surface::WlSurface,
500 _: u32,
501 ) {
502 if let Some(e) = self
503 .entries
504 .iter_mut()
505 .find(|e| e.layer.wl_surface() == surface)
506 {
507 e.waiting = false;
508 }
509 }
510
511 fn surface_enter(
512 &mut self,
513 _: &Connection,
514 _: &QueueHandle<Self>,
515 _: &wl_surface::WlSurface,
516 _: &wl_output::WlOutput,
517 ) {
518 }
519
520 fn surface_leave(
521 &mut self,
522 _: &Connection,
523 _: &QueueHandle<Self>,
524 _: &wl_surface::WlSurface,
525 _: &wl_output::WlOutput,
526 ) {
527 }
528}
529
530impl OutputHandler for State {
531 fn output_state(&mut self) -> &mut OutputState {
532 &mut self.outputs
533 }
534
535 fn new_output(&mut self, _: &Connection, qh: &QueueHandle<Self>, output: wl_output::WlOutput) {
537 if self.started {
538 self.add(qh, output);
539 }
540 }
541
542 fn update_output(
543 &mut self,
544 _: &Connection,
545 _: &QueueHandle<Self>,
546 output: wl_output::WlOutput,
547 ) {
548 let physical = self.physical(&output);
549 if let Some(e) = self.entries.iter_mut().find(|e| e.output == output) {
550 e.physical = physical;
551 e.fresh = true;
552 }
553 }
554
555 fn output_destroyed(
556 &mut self,
557 _: &Connection,
558 _: &QueueHandle<Self>,
559 output: wl_output::WlOutput,
560 ) {
561 self.entries.retain(|e| e.output != output);
562 }
563}
564
565impl LayerShellHandler for State {
566 fn closed(&mut self, _: &Connection, _: &QueueHandle<Self>, layer: &LayerSurface) {
567 self.entries.retain(|e| &e.layer != layer);
568 }
569
570 fn configure(
571 &mut self,
572 _: &Connection,
573 _: &QueueHandle<Self>,
574 layer: &LayerSurface,
575 configure: LayerSurfaceConfigure,
576 _: u32,
577 ) {
578 let logical = self
580 .entries
581 .iter()
582 .find(|e| &e.layer == layer)
583 .and_then(|e| self.outputs.info(&e.output))
584 .and_then(|i| i.logical_size)
585 .map(|(w, h)| (w.max(1) as u32, h.max(1) as u32));
586 if let Some(e) = self.entries.iter_mut().find(|e| &e.layer == layer) {
587 let (w, h) = configure.new_size;
588 let (lw, lh) = logical.unwrap_or(e.physical);
589 let size = (if w == 0 { lw } else { w }, if h == 0 { lh } else { h });
590 if e.size != Some(size) {
591 e.size = Some(size);
592 e.fresh = true;
593 }
594 }
595 }
596}
597
598impl ShmHandler for State {
599 fn shm_state(&mut self) -> &mut Shm {
600 &mut self.shm
601 }
602}
603
604impl ProvidesRegistryState for State {
605 fn registry(&mut self) -> &mut RegistryState {
606 &mut self.registry
607 }
608 registry_handlers![OutputState];
609}
610
611impl AsMut<SimpleGlobal<wp_viewporter::WpViewporter, 1>> for State {
612 fn as_mut(&mut self) -> &mut SimpleGlobal<wp_viewporter::WpViewporter, 1> {
613 &mut self.viewporter
614 }
615}
616
617impl Dispatch<wp_viewport::WpViewport, ()> for State {
618 fn event(
619 _: &mut Self,
620 _: &wp_viewport::WpViewport,
621 _: wp_viewport::Event,
622 _: &(),
623 _: &Connection,
624 _: &QueueHandle<Self>,
625 ) {
626 }
628}
629
630delegate_compositor!(State);
631delegate_output!(State);
632delegate_shm!(State);
633delegate_layer!(State);
634delegate_registry!(State);
635delegate_simple!(State, wp_viewporter::WpViewporter, 1);
636
637struct Image {
641 width: u32,
642 height: u32,
643 pixels: Vec<u32>,
644}
645
646enum Command {
647 Show(Image),
648 Stop,
649}
650
651struct StillThread {
652 tx: mpsc::Sender<Command>,
653}
654
655static STILL: Mutex<Option<StillThread>> = Mutex::new(None);
656
657fn decode(path: &Path) -> Result<Image, String> {
659 let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
660 let mut dec = png::Decoder::new(std::io::BufReader::new(file));
661 dec.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
662 let mut reader = dec
663 .read_info()
664 .map_err(|e| format!("{}: {e}", path.display()))?;
665 let mut buf = vec![0u8; reader.output_buffer_size().unwrap_or(0)];
666 let info = reader
667 .next_frame(&mut buf)
668 .map_err(|e| format!("{}: {e}", path.display()))?;
669 let channels = info.color_type.samples();
670 let pixels = buf[..info.buffer_size()]
671 .chunks_exact(channels)
672 .map(|p| match channels {
673 1 | 2 => u32::from(p[0]) * 0x01_0101,
674 _ => (u32::from(p[0]) << 16) | (u32::from(p[1]) << 8) | u32::from(p[2]),
675 })
676 .collect();
677 Ok(Image {
678 width: info.width,
679 height: info.height,
680 pixels,
681 })
682}
683
684pub fn show_still(path: &Path) -> Result<(), String> {
687 let image = decode(path)?;
688 let mut held = STILL.lock().map_err(|_| "the still thread panicked")?;
689 if let Some(t) = held.as_ref() {
690 match t.tx.send(Command::Show(image)) {
691 Ok(()) => return Ok(()),
692 Err(mpsc::SendError(Command::Show(img))) => return start(&mut held, img),
694 Err(_) => unreachable!("only Show is sent here"),
695 }
696 }
697 start(&mut held, image)
698}
699
700pub fn hide_still() {
702 if let Ok(mut held) = STILL.lock()
703 && let Some(t) = held.take()
704 {
705 let _ = t.tx.send(Command::Stop);
706 }
707}
708
709fn start(held: &mut Option<StillThread>, image: Image) -> Result<(), String> {
710 let (tx, rx) = mpsc::channel();
711 let (ready_tx, ready_rx) = mpsc::channel();
712 std::thread::Builder::new()
713 .name("clairlune-wlr-still".into())
714 .spawn(move || still_loop(image, &rx, &ready_tx))
715 .map_err(|e| format!("still thread: {e}"))?;
716 ready_rx
717 .recv()
718 .map_err(|_| "the still thread ended".to_string())??;
719 *held = Some(StillThread { tx });
720 Ok(())
721}
722
723fn still_loop(
724 first: Image,
725 rx: &mpsc::Receiver<Command>,
726 ready: &mpsc::Sender<Result<(), String>>,
727) {
728 let open = |img: &Image| Surfaces::new((img.width, img.height));
729 let mut surfaces = match open(&first) {
730 Ok(s) => {
731 let _ = ready.send(Ok(()));
732 s
733 }
734 Err(e) => {
735 let _ = ready.send(Err(e));
736 return;
737 }
738 };
739 let mut image = first;
740 let mut changed = true;
741 loop {
742 match rx.try_recv() {
743 Ok(Command::Show(img)) => {
744 if (img.width, img.height) != surfaces.image_size() {
745 match open(&img) {
746 Ok(s) => surfaces = s,
747 Err(e) => {
748 tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces");
749 return;
750 }
751 }
752 }
753 image = img;
754 changed = true;
755 }
756 Ok(Command::Stop) | Err(mpsc::TryRecvError::Disconnected) => return,
757 Err(mpsc::TryRecvError::Empty) => {}
758 }
759 if let Err(e) = surfaces.dispatch(Duration::from_millis(250)) {
760 tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces lost");
761 return;
762 }
763 let whole = Rect {
764 x: 0,
765 y: 0,
766 w: image.width,
767 h: image.height,
768 };
769 let rects = if changed { vec![whole] } else { Vec::new() };
770 let img = ℑ
771 let result = surfaces.present(&rects, &mut |r, canvas, stride| {
772 copy_rect(&img.pixels, img.width, r, canvas, stride);
773 });
774 if let Err(e) = result {
775 tracing::warn!(target: "clairlune_platform", error = %e, "still surfaces");
776 return;
777 }
778 changed = false;
779 }
780}
781
782pub fn copy_rect(pixels: &[u32], width: u32, r: Rect, canvas: &mut [u8], stride: usize) {
785 for y in r.y..r.y + r.h {
786 let src = &pixels[(y * width + r.x) as usize..][..r.w as usize];
787 let dst = &mut canvas[y as usize * stride + r.x as usize * 4..][..r.w as usize * 4];
788 for (d, s) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) {
789 d.copy_from_slice(&s.to_le_bytes());
790 }
791 }
792}
793
794#[cfg(test)]
795mod tests {
796 use super::*;
797
798 #[test]
799 fn a_wider_screen_shows_a_band_across_the_middle() {
800 let (x, y, w, h) = fill_crop((1920, 1080), (2560, 1080));
802 assert_eq!((x, w), (0.0, 1920.0));
803 assert!((h - 810.0).abs() < 1e-9 && (y - 135.0).abs() < 1e-9);
804 assert_eq!(
806 fill_crop((1920, 1080), (3840, 2160)),
807 (0.0, 0.0, 1920.0, 1080.0)
808 );
809 let (x, _, w, h) = fill_crop((1920, 1080), (1080, 1920));
811 assert_eq!(h, 1080.0);
812 assert!((w - 607.5).abs() < 1e-9 && (x - 656.25).abs() < 1e-9);
813 }
814
815 #[test]
816 fn damage_waiting_for_a_frame_stays_bounded() {
817 let r = |x| Rect {
818 x,
819 y: 0,
820 w: 1,
821 h: 1,
822 };
823 let mut list = Vec::new();
824 for i in 0..10_000 {
825 add_damage(&mut list, &[r(i), r(i + 1)]);
826 assert!(list.len() <= MAX_RECTS + 2);
827 }
828 let x0 = list.iter().map(|r| r.x).min().unwrap();
830 let x1 = list.iter().map(|r| r.x + r.w).max().unwrap();
831 assert_eq!((x0, x1), (0, 10_001));
832 }
833
834 #[test]
835 fn many_rects_become_one_around_them() {
836 let few = vec![
837 Rect {
838 x: 1,
839 y: 2,
840 w: 3,
841 h: 4
842 };
843 3
844 ];
845 assert_eq!(bounded(few.clone()), few);
846 let many: Vec<Rect> = (0..100)
847 .map(|i| Rect {
848 x: i,
849 y: 10 + i,
850 w: 2,
851 h: 1,
852 })
853 .collect();
854 assert_eq!(
855 bounded(many),
856 vec![Rect {
857 x: 0,
858 y: 10,
859 w: 101,
860 h: 100
861 }]
862 );
863 }
864
865 #[test]
866 fn rects_copy_as_little_endian_xrgb() {
867 let pixels = vec![
868 0x00_11_22_33u32,
869 0x00_44_55_66,
870 0x00_77_88_99,
871 0x00_AA_BB_CC,
872 ];
873 let mut canvas = vec![0u8; 16];
874 copy_rect(
875 &pixels,
876 2,
877 Rect {
878 x: 1,
879 y: 1,
880 w: 1,
881 h: 1,
882 },
883 &mut canvas,
884 8,
885 );
886 assert_eq!(&canvas[12..16], &[0xCC, 0xBB, 0xAA, 0x00]);
887 assert!(canvas[..12].iter().all(|&b| b == 0));
888 }
889}