use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use valo::{Context, ImageDesc};
use crate::{CompositionLayer, HardwareBuffer, Image, Picture, Placement};
static GPU: OnceLock<Mutex<Context>> = OnceLock::new();
pub fn solid_image(size: [u32; 2], color: [u8; 4]) -> Image {
let [width, height] = size;
let pixels: Vec<u8> = color
.iter()
.copied()
.cycle()
.take(width as usize * height as usize * 4)
.collect();
image_from_pixels(size, &pixels)
}
pub fn image_from_pixels(size: [u32; 2], pixels: &[u8]) -> Image {
let [width, height] = size;
assert_eq!(
pixels.len(),
width as usize * height as usize * 4,
"an image needs four bytes a pixel"
);
gpu().upload_image(
ImageDesc {
size,
premultiplied: false,
mips: false,
},
pixels,
)
}
pub fn drawn_pixels(picture: Picture, size: [u32; 2]) -> Vec<u8> {
let mut gpu = gpu();
let request = gpu.request_pixels(&Arc::new(picture), size, Some(valo::Color::TRANSPARENT));
gpu.device()
.poll(wgpu::PollType::wait_indefinitely())
.expect("the test GPU device answers");
pollster::block_on(request)
.expect("the picture reads back")
.into_bytes()
}
pub fn read_image_pixels(image: &Image) -> crate::image_codecs::ImageFuture<valo::PixelBuffer> {
crate::snapshot_delegate::read_image_pixels(&mut gpu(), image, |device| {
device
.poll(wgpu::PollType::wait_indefinitely())
.expect("the test GPU device answers");
})
}
pub fn imported_pixels(pixels: valo::PixelBuffer) -> Option<Image> {
gpu().image_context().upload_pixels(pixels, false).ok()
}
pub fn open_image_codec(bytes: Arc<[u8]>) -> crate::ImageCodecFuture {
let decoders: Vec<Box<dyn valo_codec::Decoder>> =
vec![Box::new(valo_codec_software::SoftwareDecoder)];
let loader = valo_codec::ImageLoader::new(gpu().image_context().clone(), decoders);
crate::valo_images::open_image_codec(Some(loader), bytes)
}
pub fn picture_to_image(picture: &Picture, size: [u32; 2]) -> Image {
gpu().display_list_to_image(picture, size)
}
fn gpu() -> MutexGuard<'static, Context> {
GPU.get_or_init(|| Mutex::new(headless_context()))
.lock()
.expect("the test GPU device")
}
fn headless_context() -> Context {
let instance = wgpu::Instance::default();
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.expect("a GPU adapter for tests");
let (device, queue) =
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
.expect("a GPU device for tests");
let mut context = Context::new(device, queue);
context.set_hide_missing_glyphs(true);
context
}
pub fn idle_layer() -> Arc<dyn CompositionLayer> {
Arc::new(IdleLayer)
}
struct IdleLayer;
impl CompositionLayer for IdleLayer {
fn present(
&self,
_buffer: Arc<dyn HardwareBuffer>,
_children: Vec<(Arc<dyn CompositionLayer>, Placement)>,
_released: Box<dyn FnOnce() + Send + Sync>,
) {
}
fn current_picture(&self) -> Option<crate::LayerPicture> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Dispatcher, Instant, SnapshotDelegate};
struct ThreadDispatcher;
impl Dispatcher for ThreadDispatcher {
fn wake_at(&self, _timer_wakeup: Option<Instant>) {}
fn wake_now(&self) {}
#[allow(
clippy::disallowed_methods,
reason = "the test plays a host, which runs dispatched work on threads of its own"
)]
fn dispatch(&self, work: Box<dyn FnOnce() + Send>) {
std::thread::spawn(work);
}
}
#[test]
fn a_host_reads_an_image_back_with_the_gpu_waited_on_off_the_calling_thread() {
let image = solid_image([3, 2], [255, 0, 0, 255]);
let snapshots = SnapshotDelegate::new(gpu().image_context().clone());
let pixels = pollster::block_on(snapshots.read_pixels(&image, |device| {
let device = device.clone();
ThreadDispatcher.dispatch(Box::new(move || {
let _ = device.poll(wgpu::PollType::wait_indefinitely());
}));
}))
.expect("the image reads back");
assert_eq!(pixels.layout().size, [3, 2]);
assert!(
pixels
.bytes()
.chunks(4)
.all(|pixel| pixel == [255, 0, 0, 255]),
"red throughout"
);
}
}