1use mouser_engine_abi::*;
18use raw_window_handle as rwh;
19use std::ffi::{c_char, c_int, c_void};
20use std::num::NonZeroU32;
21use std::ptr::NonNull;
22
23#[derive(Clone, Copy)]
25struct Handles {
26 display: rwh::RawDisplayHandle,
27 window: rwh::RawWindowHandle,
28}
29
30impl rwh::HasDisplayHandle for Handles {
31 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
32 Ok(unsafe { rwh::DisplayHandle::borrow_raw(self.display) })
34 }
35}
36impl rwh::HasWindowHandle for Handles {
37 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
38 Ok(unsafe { rwh::WindowHandle::borrow_raw(self.window) })
40 }
41}
42
43fn handles(s: &MouserSurface) -> Result<Handles, String> {
44 let nn = |p: *mut c_void| NonNull::new(p).ok_or_else(|| "null surface handle".to_string());
45 match s.kind {
46 SURFACE_WAYLAND => Ok(Handles {
47 display: rwh::WaylandDisplayHandle::new(nn(s.display)?).into(),
48 window: rwh::WaylandWindowHandle::new(nn(s.window)?).into(),
49 }),
50 SURFACE_XLIB => Ok(Handles {
51 display: rwh::XlibDisplayHandle::new(Some(nn(s.display)?), 0).into(),
52 window: rwh::XlibWindowHandle::new(s.window as std::ffi::c_ulong).into(),
53 }),
54 k => Err(format!("unsupported surface kind {k}")),
55 }
56}
57
58pub fn rasterize(buf: &mut [u32], width: usize, height: usize, frame: &MouserFrame) {
60 buf.fill(frame.clear);
61 let (ops, rects, glyphs, images) = unsafe { frame.parts() };
63 let blend = |d: u32, s: u32, a: u32| -> u32 {
64 let ch = |sh: u32| ((((s >> sh) & 0xff) * a + ((d >> sh) & 0xff) * (255 - a)) / 255) << sh;
65 ch(16) | ch(8) | ch(0)
66 };
67 for op in ops {
68 match op.kind {
69 OP_RECT => {
70 let Some(r) = rects.get(op.index as usize) else { continue };
71 let (x0, y0) = (r.x.max(0) as usize, r.y.max(0) as usize);
72 let x1 = ((r.x + r.w).max(0) as usize).min(width);
73 let y1 = ((r.y + r.h).max(0) as usize).min(height);
74 for y in y0..y1 {
75 if x0 < x1 {
76 buf[y * width + x0..y * width + x1].fill(r.color);
77 }
78 }
79 }
80 OP_GLYPH => {
81 let Some(g) = glyphs.get(op.index as usize) else { continue };
82 if g.coverage.is_null() {
83 continue;
84 }
85 let cov = unsafe { std::slice::from_raw_parts(g.coverage, (g.stride * g.h) as usize) };
87 for iy in 0..g.h as i32 {
88 let py = g.y + iy;
89 if py < 0 || py >= height as i32 {
90 continue;
91 }
92 for ix in 0..g.w as i32 {
93 let px = g.x + ix;
94 if px < 0 || px >= width as i32 {
95 continue;
96 }
97 let a = cov[(iy as u32 * g.stride + ix as u32) as usize] as u32;
98 if a > 0 {
99 let o = py as usize * width + px as usize;
100 buf[o] = blend(buf[o], g.color, a);
101 }
102 }
103 }
104 }
105 OP_IMAGE => {
106 let Some(im) = images.get(op.index as usize) else { continue };
107 if im.rgba.is_null() || im.img_w == 0 || im.img_h == 0 {
108 continue;
109 }
110 let px = unsafe { std::slice::from_raw_parts(im.rgba, (im.img_w * im.img_h * 4) as usize) };
112 let (dw, dh) = (im.w.max(1) as i32, im.h.max(1) as i32);
113 for y in im.y.max(0)..(im.y + dh).min(height as i32) {
114 let iy = (im.src_y + ((y - im.y) as u64 * im.src_h as u64 / dh as u64) as u32).min(im.img_h - 1);
115 for x in im.x.max(0)..(im.x + dw).min(width as i32) {
116 let ix = (im.src_x + ((x - im.x) as u64 * im.src_w as u64 / dw as u64) as u32).min(im.img_w - 1);
117 let o = ((iy * im.img_w + ix) * 4) as usize;
118 let c = (px[o] as u32) << 16 | (px[o + 1] as u32) << 8 | px[o + 2] as u32;
119 let d = y as usize * width + x as usize;
120 buf[d] = blend(buf[d], c, px[o + 3] as u32);
121 }
122 }
123 }
124 _ => {}
125 }
126 }
127}
128
129enum Target {
130 Window { _context: softbuffer::Context<Handles>, surface: softbuffer::Surface<Handles, Handles> },
131 Pixels(*const MouserPixels),
132}
133
134struct Flat {
135 target: Target,
136 width: u32,
137 height: u32,
138 frames: u64,
139}
140
141fn fail(what: &str) -> bool {
142 std::env::var("MOUSER_FLAT_FAIL").is_ok_and(|v| v == what)
143}
144
145unsafe extern "C" fn create(surface: *const MouserSurface, w: u32, h: u32, err: *mut c_char, err_len: usize) -> *mut c_void {
146 let made = (|| -> Result<Flat, String> {
147 if fail("create") {
148 return Err("MOUSER_FLAT_FAIL=create".into());
149 }
150 let s = unsafe { surface.as_ref() }.ok_or("null surface")?;
152 if s.kind == SURFACE_PIXELS {
153 if s.window.is_null() {
154 return Err("null pixel buffer".into());
155 }
156 return Ok(Flat { target: Target::Pixels(s.window as *const MouserPixels), width: w.max(1), height: h.max(1), frames: 0 });
157 }
158 let h_ = handles(s)?;
159 let context = softbuffer::Context::new(h_).map_err(|e| e.to_string())?;
160 let mut sf = softbuffer::Surface::new(&context, h_).map_err(|e| e.to_string())?;
161 sf.resize(NonZeroU32::new(w.max(1)).unwrap(), NonZeroU32::new(h.max(1)).unwrap()).map_err(|e| e.to_string())?;
162 Ok(Flat { target: Target::Window { _context: context, surface: sf }, width: w.max(1), height: h.max(1), frames: 0 })
163 })();
164 match made {
165 Ok(f) => Box::into_raw(Box::new(f)) as *mut c_void,
166 Err(e) => {
167 unsafe { write_err(err, err_len, &e) };
169 std::ptr::null_mut()
170 }
171 }
172}
173
174unsafe extern "C" fn resize(engine: *mut c_void, w: u32, h: u32) {
175 let Some(f) = (unsafe { (engine as *mut Flat).as_mut() }) else { return };
177 f.width = w.max(1);
178 f.height = h.max(1);
179 if let Target::Window { surface, .. } = &mut f.target {
180 let _ = surface.resize(NonZeroU32::new(f.width).unwrap(), NonZeroU32::new(f.height).unwrap());
181 }
182}
183
184unsafe extern "C" fn draw(engine: *mut c_void, frame: *const MouserFrame) -> c_int {
185 if fail("draw") {
186 return -1;
187 }
188 let (Some(f), Some(frame)) = (unsafe { (engine as *mut Flat).as_mut() }, unsafe { frame.as_ref() }) else { return -2 };
190 f.frames += 1;
191 if std::env::var("MOUSER_FLAT_CRASH_AT").ok().and_then(|v| v.parse::<u64>().ok()) == Some(f.frames) {
192 std::process::abort();
193 }
194 if frame.width != f.width || frame.height != f.height {
195 unsafe { resize(engine, frame.width, frame.height) };
196 }
197 match &mut f.target {
198 Target::Pixels(p) => {
199 let Some(px) = (unsafe { p.as_ref() }) else { return -3 };
201 let (w, h) = (px.width as usize, px.height as usize);
202 if px.data.is_null() || px.stride as usize != w {
203 return -4;
204 }
205 let buf = unsafe { std::slice::from_raw_parts_mut(px.data, w * h) };
206 rasterize(buf, w, h, frame);
207 DRAW_OK
208 }
209 Target::Window { surface, .. } => {
210 let (w, h) = (f.width as usize, f.height as usize);
211 let Ok(mut buf) = surface.buffer_mut() else { return DRAW_AGAIN };
212 if buf.len() < w * h {
213 return DRAW_AGAIN;
214 }
215 rasterize(&mut buf[..w * h], w, h, frame);
216 if buf.present().is_err() { DRAW_AGAIN } else { DRAW_OK }
217 }
218 }
219}
220
221unsafe extern "C" fn destroy(engine: *mut c_void) {
222 if !engine.is_null() {
223 drop(unsafe { Box::from_raw(engine as *mut Flat) });
225 }
226}
227
228static TABLE: MouserEngineV1 = MouserEngineV1 {
229 abi: MOUSER_ENGINE_ABI,
230 size: std::mem::size_of::<MouserEngineV1>() as u32,
231 name: c"flat".as_ptr(),
232 create,
233 resize,
234 draw,
235 destroy,
236};
237
238static mut ODD: MouserEngineV1 = MouserEngineV1 { abi: 0, ..TABLE };
239
240unsafe extern "C" fn caps(_engine: *mut c_void, caps: *mut MouserCaps) {
241 if let Some(c) = unsafe { caps.as_mut() } {
243 c.flags = CAP_DIRECT_SURFACE | CAP_PIXELS;
244 c.formats = FORMAT_XRGB8888;
245 c.max_texture = 0;
246 }
247}
248
249static TABLE_V2: MouserEngineV2 = MouserEngineV2 {
250 base: MouserEngineV1 { abi: MOUSER_ENGINE_ABI_V2, size: std::mem::size_of::<MouserEngineV2>() as u32, ..TABLE },
251 abi_min: MOUSER_ENGINE_ABI,
252 abi_max: MOUSER_ENGINE_ABI_V2,
253 caps: Some(caps),
254 set_scale: None,
255 evict: None,
256 set_vsync: None,
257};
258
259#[unsafe(no_mangle)]
262pub extern "C" fn mouser_engine_v2() -> *const MouserEngineV2 {
263 if std::env::var_os("MOUSER_FLAT_ABI").is_some() || std::env::var_os("MOUSER_FLAT_V1_ONLY").is_some() {
264 return std::ptr::null();
265 }
266 &TABLE_V2
267}
268
269#[unsafe(no_mangle)]
271pub extern "C" fn mouser_engine_v1() -> *const MouserEngineV1 {
272 if let Some(abi) = std::env::var("MOUSER_FLAT_ABI").ok().and_then(|v| v.parse().ok()) {
273 unsafe {
275 ODD.abi = abi;
276 return &raw const ODD;
277 }
278 }
279 &TABLE
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn rasterizes_rect_glyph_and_image() {
288 let rects = [MouserRect { x: 1, y: 1, w: 2, h: 2, color: 0xff0000 }];
289 let cov = [255u8, 0, 128, 255];
290 let glyphs = [MouserGlyph { x: 0, y: 0, w: 2, h: 2, stride: 2, color: 0x00ff00, coverage: cov.as_ptr(), key: 1 }];
291 let rgba = [0u8, 0, 255, 255];
292 let images =
293 [MouserImage { x: 3, y: 3, w: 1, h: 1, img_w: 1, img_h: 1, src_x: 0, src_y: 0, src_w: 1, src_h: 1, rgba: rgba.as_ptr(), key: 2 }];
294 let ops = [MouserOp { kind: OP_RECT, index: 0 }, MouserOp { kind: OP_GLYPH, index: 0 }, MouserOp { kind: OP_IMAGE, index: 0 }];
295 let frame = MouserFrame {
296 width: 4,
297 height: 4,
298 clear: 0x111111,
299 dirty_x: 0,
300 dirty_y: 0,
301 dirty_w: 4,
302 dirty_h: 4,
303 ops: ops.as_ptr(),
304 op_count: 3,
305 rects: rects.as_ptr(),
306 rect_count: 1,
307 glyphs: glyphs.as_ptr(),
308 glyph_count: 1,
309 images: images.as_ptr(),
310 image_count: 1,
311 };
312 let mut buf = vec![0u32; 16];
313 rasterize(&mut buf, 4, 4, &frame);
314 assert_eq!(buf[0], 0x00ff00);
315 assert_eq!(buf[1], 0x111111);
316 assert_eq!(buf[5], 0x00ff00); assert_eq!(buf[6], 0xff0000);
318 assert_eq!(buf[15], 0x0000ff);
319 }
320
321 #[test]
322 fn create_reports_errors() {
323 let mut err = [0 as c_char; 64];
324 let s = MouserSurface { kind: 99, display: std::ptr::null_mut(), window: std::ptr::null_mut() };
325 let p = unsafe { create(&s, 10, 10, err.as_mut_ptr(), err.len()) };
326 assert!(p.is_null());
327 let msg = unsafe { std::ffi::CStr::from_ptr(err.as_ptr()) }.to_string_lossy();
328 assert!(msg.contains("unsupported surface"), "{msg}");
329 }
330}