1#![allow(clippy::missing_safety_doc)]
9
10use glutin::config::{ConfigTemplateBuilder, GlConfig};
11use glutin::context::{ContextApi, ContextAttributesBuilder, PossiblyCurrentContext};
12use glutin::display::{Display, DisplayApiPreference, GlDisplay};
13use glutin::prelude::{GlSurface, NotCurrentGlContext};
14use glutin::surface::{Surface as GlSurfaceT, SurfaceAttributesBuilder, SwapInterval, WindowSurface};
15use mouser_engine_abi::*;
16use skia_safe::gpu::{self, DirectContext, SurfaceOrigin, backend_render_targets, gl::FramebufferInfo};
17use skia_safe::{AlphaType, Color, ColorType, Data, Image, ImageInfo, Paint, Rect, SamplingOptions, Surface, canvas::SrcRectConstraint};
18use std::collections::HashMap;
19use std::ffi::{CString, c_char, c_int, c_void};
20use std::num::NonZeroU32;
21
22const ATLAS: usize = 2048;
23
24struct Atlas {
25 pixels: Vec<u8>,
26 slots: HashMap<u64, (i32, i32, i32, i32)>,
27 x: i32,
28 y: i32,
29 row_h: i32,
30 image: Option<Image>,
31 dirty: bool,
32}
33
34impl Atlas {
35 fn new() -> Self {
36 Self { pixels: vec![0; ATLAS * ATLAS], slots: HashMap::new(), x: 0, y: 0, row_h: 0, image: None, dirty: true }
37 }
38
39 unsafe fn slot(&mut self, g: &MouserGlyph) -> Option<(i32, i32, i32, i32)> {
42 if let Some(s) = self.slots.get(&g.key) {
43 return Some(*s);
44 }
45 let (w, h) = (g.w as i32, g.h as i32);
46 if w == 0 || h == 0 || w > ATLAS as i32 || h > ATLAS as i32 || g.coverage.is_null() {
47 return None;
48 }
49 if self.x + w + 1 > ATLAS as i32 {
50 self.x = 0;
51 self.y += self.row_h + 1;
52 self.row_h = 0;
53 }
54 if self.y + h > ATLAS as i32 {
55 return None;
56 }
57 let data = unsafe { std::slice::from_raw_parts(g.coverage, (g.stride * g.h) as usize) };
59 for row in 0..h as usize {
60 let o = (self.y as usize + row) * ATLAS + self.x as usize;
61 self.pixels[o..o + w as usize].copy_from_slice(&data[row * g.stride as usize..][..w as usize]);
62 }
63 let s = (self.x, self.y, w, h);
64 self.slots.insert(g.key, s);
65 self.x += w + 1;
66 self.row_h = self.row_h.max(h);
67 self.dirty = true;
68 Some(s)
69 }
70
71 fn image(&mut self) -> Option<&Image> {
72 if self.dirty || self.image.is_none() {
73 let info = ImageInfo::new((ATLAS as i32, ATLAS as i32), ColorType::Alpha8, AlphaType::Premul, None);
74 self.image = skia_safe::images::raster_from_data(&info, Data::new_copy(&self.pixels), ATLAS);
75 self.dirty = false;
76 }
77 self.image.as_ref()
78 }
79}
80
81fn color(c: u32) -> Color {
83 Color::from_argb((255 - (c >> 24)) as u8, (c >> 16) as u8, (c >> 8) as u8, c as u8)
84}
85
86struct Gl {
87 surface: Surface,
89 gr: DirectContext,
90 fb: FramebufferInfo,
91 samples: usize,
92 stencil: usize,
93 gl_surface: GlSurfaceT<WindowSurface>,
94 gl_context: PossiblyCurrentContext,
95}
96
97impl Drop for Gl {
98 fn drop(&mut self) {
99 self.gr.release_resources_and_abandon();
100 }
101}
102
103fn nz(v: u32) -> NonZeroU32 {
104 NonZeroU32::new(v.max(1)).unwrap()
105}
106
107fn make_gl_surface(gr: &mut DirectContext, fb: FramebufferInfo, samples: usize, stencil: usize, w: u32, h: u32) -> Result<Surface, String> {
108 let target = backend_render_targets::make_gl((w.max(1) as i32, h.max(1) as i32), samples, stencil, fb);
109 gpu::surfaces::wrap_backend_render_target(gr, &target, SurfaceOrigin::BottomLeft, ColorType::RGBA8888, None, None)
110 .ok_or_else(|| "Skia could not wrap the GL framebuffer".to_string())
111}
112
113fn raster(w: u32, h: u32) -> Result<Surface, String> {
114 let info = ImageInfo::new((w.max(1) as i32, h.max(1) as i32), ColorType::RGBA8888, AlphaType::Premul, None);
115 skia_safe::surfaces::raster(&info, None, None).ok_or_else(|| "Skia raster surface".to_string())
116}
117
118enum Target {
119 Gl(Box<Gl>),
120 Raster(Surface),
121}
122
123pub struct Renderer {
125 target: Target,
126 atlas: Atlas,
127 images: HashMap<u64, Image>,
128 width: u32,
129 height: u32,
130 pub description: String,
131}
132
133impl Renderer {
134 pub fn raster(width: u32, height: u32) -> Result<Self, String> {
136 Ok(Self {
137 target: Target::Raster(raster(width, height)?),
138 atlas: Atlas::new(),
139 images: HashMap::new(),
140 width: width.max(1),
141 height: height.max(1),
142 description: "Skia raster".into(),
143 })
144 }
145
146 pub unsafe fn on_window(
151 raw_display: raw_window_handle::RawDisplayHandle,
152 raw_window: raw_window_handle::RawWindowHandle,
153 width: u32,
154 height: u32,
155 ) -> Result<Self, String> {
156 fn e(what: &'static str) -> impl Fn(glutin::error::Error) -> String {
157 move |err| format!("{what}: {err}")
158 }
159 #[cfg(all(unix, not(target_os = "macos")))]
160 let pref = DisplayApiPreference::Egl;
161 #[cfg(target_os = "macos")]
162 let pref = DisplayApiPreference::Cgl;
163 #[cfg(windows)]
164 let pref = DisplayApiPreference::WglThenEgl(Some(raw_window));
165 let display = unsafe { Display::new(raw_display, pref) }.map_err(e("GL display"))?;
167 let template = ConfigTemplateBuilder::new().compatible_with_native_window(raw_window).with_alpha_size(8).build();
168 let config = unsafe { display.find_configs(template) }
170 .map_err(e("GL configs"))?
171 .reduce(|a, c| if c.num_samples() < a.num_samples() { c } else { a })
172 .ok_or("no GL config for this window")?;
173 let attrs = ContextAttributesBuilder::new().build(Some(raw_window));
174 let gles = ContextAttributesBuilder::new().with_context_api(ContextApi::Gles(None)).build(Some(raw_window));
175 let ctx = unsafe { display.create_context(&config, &attrs).or_else(|_| display.create_context(&config, &gles)) }.map_err(e("GL context"))?;
177 let sattrs = SurfaceAttributesBuilder::<WindowSurface>::new().build(raw_window, nz(width), nz(height));
178 let gl_surface = unsafe { display.create_window_surface(&config, &sattrs) }.map_err(e("GL window surface"))?;
180 let gl_context = ctx.make_current(&gl_surface).map_err(e("making the GL context current"))?;
181 let _ = gl_surface.set_swap_interval(&gl_context, SwapInterval::DontWait);
182 let interface = skia_safe::gpu::gl::Interface::new_load_with(|name| {
183 if name == "eglGetCurrentDisplay" {
184 return std::ptr::null();
185 }
186 CString::new(name).map(|n| display.get_proc_address(&n)).unwrap_or(std::ptr::null())
187 })
188 .ok_or("Skia could not load GL")?;
189 let mut gr = gpu::direct_contexts::make_gl(interface, None).ok_or("Skia GL context")?;
190 let fb = FramebufferInfo { fboid: 0, format: skia_safe::gpu::gl::Format::RGBA8.into(), ..Default::default() };
191 let (samples, stencil) = (config.num_samples() as usize, config.stencil_size() as usize);
192 let surface = make_gl_surface(&mut gr, fb, samples, stencil, width, height)?;
193 let description = format!("Skia GL, {:?}, {samples} samples", display.version_string());
194 Ok(Self {
195 target: Target::Gl(Box::new(Gl { surface, gr, fb, samples, stencil, gl_surface, gl_context })),
196 atlas: Atlas::new(),
197 images: HashMap::new(),
198 width: width.max(1),
199 height: height.max(1),
200 description,
201 })
202 }
203
204 pub fn resize(&mut self, width: u32, height: u32) {
205 let (w, h) = (width.max(1), height.max(1));
206 if (w, h) == (self.width, self.height) {
207 return;
208 }
209 (self.width, self.height) = (w, h);
210 match &mut self.target {
211 Target::Gl(g) => {
212 g.gl_surface.resize(&g.gl_context, nz(w), nz(h));
213 if let Ok(s) = make_gl_surface(&mut g.gr, g.fb, g.samples, g.stencil, w, h) {
214 g.surface = s;
215 }
216 }
217 Target::Raster(s) => {
218 if let Ok(n) = raster(w, h) {
219 *s = n;
220 }
221 }
222 }
223 }
224
225 pub fn evict(&mut self, key: u64) {
226 self.images.remove(&key);
227 }
228
229 pub fn read_pixels(&mut self) -> Option<Vec<u32>> {
231 let Target::Raster(s) = &mut self.target else { return None };
232 let (w, h) = (self.width as i32, self.height as i32);
233 let info = ImageInfo::new((w, h), ColorType::RGBA8888, AlphaType::Premul, None);
234 let mut px = vec![0u8; (w * h * 4) as usize];
235 if !s.read_pixels(&info, &mut px, (w * 4) as usize, (0, 0)) {
236 return None;
237 }
238 Some(px.as_chunks::<4>().0.iter().map(|p| (p[0] as u32) << 16 | (p[1] as u32) << 8 | p[2] as u32).collect())
239 }
240
241 pub unsafe fn draw(&mut self, frame: &MouserFrame) -> c_int {
246 if (frame.width, frame.height) != (self.width, self.height) {
247 self.resize(frame.width, frame.height);
248 }
249 let (ops, rects, glyphs, images) = unsafe { frame.parts() };
251 let mut full = false;
252 for g in glyphs {
253 if unsafe { self.atlas.slot(g) }.is_none() && g.w > 0 && g.h > 0 {
255 full = true;
256 break;
257 }
258 }
259 if full {
260 self.atlas = Atlas::new();
261 }
262 let used: std::collections::HashSet<u64> = images.iter().map(|i| i.key).collect();
263 self.images.retain(|k, _| used.contains(k));
264 let imgs: Vec<Option<Image>> = images
265 .iter()
266 .map(|img| {
267 if let Some(i) = self.images.get(&img.key) {
268 return Some(i.clone());
269 }
270 if img.rgba.is_null() || img.img_w == 0 || img.img_h == 0 {
271 return None;
272 }
273 let rgba = unsafe { std::slice::from_raw_parts(img.rgba, (img.img_w * img.img_h * 4) as usize) };
275 let info = ImageInfo::new((img.img_w as i32, img.img_h as i32), ColorType::RGBA8888, AlphaType::Unpremul, None);
276 let i = skia_safe::images::raster_from_data(&info, Data::new_copy(rgba), img.img_w as usize * 4)?;
277 self.images.insert(img.key, i.clone());
278 Some(i)
279 })
280 .collect();
281 let atlas = self.atlas.image().cloned();
282 let canvas = match &mut self.target {
283 Target::Gl(g) => g.surface.canvas(),
284 Target::Raster(s) => s.canvas(),
285 };
286 let near = SamplingOptions::default();
287 let mut paint = Paint::default();
288 paint.set_anti_alias(false);
289 canvas.clear(color(frame.clear));
290 for op in ops {
291 let i = op.index as usize;
292 match op.kind {
293 OP_RECT => {
294 let Some(r) = rects.get(i) else { continue };
295 paint.set_color(color(r.color));
296 canvas.draw_rect(Rect::from_xywh(r.x as f32, r.y as f32, r.w as f32, r.h as f32), &paint);
297 }
298 OP_GLYPH => {
299 let Some(g) = glyphs.get(i) else { continue };
300 let (Some(a), Some(&(sx, sy, w, h))) = (&atlas, self.atlas.slots.get(&g.key)) else { continue };
301 paint.set_color(color(g.color));
302 canvas.draw_image_rect_with_sampling_options(
303 a,
304 Some((&Rect::from_xywh(sx as f32, sy as f32, w as f32, h as f32), SrcRectConstraint::Strict)),
305 Rect::from_xywh(g.x as f32, g.y as f32, w as f32, h as f32),
306 near,
307 &paint,
308 );
309 }
310 OP_IMAGE => {
311 let (Some(Some(im)), Some(d)) = (imgs.get(i), images.get(i)) else { continue };
312 paint.set_color(Color::WHITE);
313 canvas.draw_image_rect_with_sampling_options(
314 im,
315 Some((&Rect::from_xywh(d.src_x as f32, d.src_y as f32, d.src_w as f32, d.src_h as f32), SrcRectConstraint::Strict)),
316 Rect::from_xywh(d.x as f32, d.y as f32, d.w as f32, d.h as f32),
317 near,
318 &paint,
319 );
320 }
321 _ => {}
322 }
323 }
324 if let Target::Gl(g) = &mut self.target {
325 let _ = g.gr.flush_and_submit();
326 if g.gl_surface.swap_buffers(&g.gl_context).is_err() {
327 return DRAW_AGAIN;
328 }
329 }
330 DRAW_OK
331 }
332}
333
334struct Engine {
337 r: Renderer,
338 pixels: Option<*mut MouserPixels>,
339}
340
341fn raw_handles(s: &MouserSurface) -> Result<(raw_window_handle::RawDisplayHandle, raw_window_handle::RawWindowHandle), String> {
342 use raw_window_handle::*;
343 use std::ptr::NonNull;
344 let nn = |p: *mut c_void, what: &str| NonNull::new(p).ok_or(format!("null {what}"));
345 Ok(match s.kind {
346 SURFACE_WAYLAND => (
347 RawDisplayHandle::Wayland(WaylandDisplayHandle::new(nn(s.display, "wl_display")?)),
348 RawWindowHandle::Wayland(WaylandWindowHandle::new(nn(s.window, "wl_surface")?)),
349 ),
350 SURFACE_XLIB => (
351 RawDisplayHandle::Xlib(XlibDisplayHandle::new(NonNull::new(s.display), 0)),
352 RawWindowHandle::Xlib(XlibWindowHandle::new(s.window as usize as _)),
353 ),
354 SURFACE_XCB => (
355 RawDisplayHandle::Xcb(XcbDisplayHandle::new(NonNull::new(s.display), 0)),
356 RawWindowHandle::Xcb(XcbWindowHandle::new(std::num::NonZeroU32::new(s.window as usize as u32).ok_or("null xcb window")?)),
357 ),
358 SURFACE_APPKIT => {
359 (RawDisplayHandle::AppKit(AppKitDisplayHandle::new()), RawWindowHandle::AppKit(AppKitWindowHandle::new(nn(s.window, "NSView")?)))
360 }
361 SURFACE_WIN32 => {
362 let mut w = Win32WindowHandle::new(std::num::NonZeroIsize::new(s.window as isize).ok_or("null HWND")?);
363 w.hinstance = std::num::NonZeroIsize::new(s.display as isize);
364 (RawDisplayHandle::Windows(WindowsDisplayHandle::new()), RawWindowHandle::Win32(w))
365 }
366 k => return Err(format!("unsupported surface kind {k}")),
367 })
368}
369
370unsafe extern "C" fn create(surface: *const MouserSurface, w: u32, h: u32, err: *mut c_char, err_len: usize) -> *mut c_void {
371 let fail = |m: String| {
372 unsafe { write_err(err, err_len, &m) };
374 std::ptr::null_mut()
375 };
376 let Some(s) = (unsafe { surface.as_ref() }) else { return fail("no surface".into()) };
378 let made = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
379 if s.kind == SURFACE_PIXELS {
380 Renderer::raster(w, h).map(|r| Engine { r, pixels: Some(s.window as *mut MouserPixels) })
381 } else {
382 let (d, win) = raw_handles(s)?;
383 unsafe { Renderer::on_window(d, win, w, h) }.map(|r| Engine { r, pixels: None })
385 }
386 }));
387 match made {
388 Ok(Ok(e)) => Box::into_raw(Box::new(e)) as *mut c_void,
389 Ok(Err(e)) => fail(e),
390 Err(_) => fail("skia panicked while starting".into()),
391 }
392}
393
394unsafe fn engine<'a>(p: *mut c_void) -> Option<&'a mut Engine> {
395 unsafe { (p as *mut Engine).as_mut() }
397}
398
399unsafe extern "C" fn resize(e: *mut c_void, w: u32, h: u32) {
400 if let Some(e) = unsafe { engine(e) } {
401 e.r.resize(w, h);
402 }
403}
404
405unsafe extern "C" fn draw(e: *mut c_void, frame: *const MouserFrame) -> c_int {
406 let (Some(e), Some(frame)) = (unsafe { engine(e) }, unsafe { frame.as_ref() }) else { return -1 };
407 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
408 let r = unsafe { e.r.draw(frame) };
410 if let Some(px) = e.pixels
411 && let Some(out) = e.r.read_pixels()
412 && let Some(px) = unsafe { px.as_ref() }
414 {
415 let rw = e.r.width as usize;
416 let (w, h) = (px.width.min(e.r.width) as usize, px.height.min(e.r.height) as usize);
417 for y in 0..h {
418 let dst = unsafe { std::slice::from_raw_parts_mut(px.data.add(y * px.stride as usize), w) };
420 dst.copy_from_slice(&out[y * rw..][..w]);
421 }
422 }
423 r
424 }))
425 .unwrap_or(-2)
426}
427
428unsafe extern "C" fn destroy(e: *mut c_void) {
429 if !e.is_null() {
430 drop(unsafe { Box::from_raw(e as *mut Engine) });
432 }
433}
434
435unsafe extern "C" fn caps(_e: *mut c_void, caps: *mut MouserCaps) {
436 if let Some(c) = unsafe { caps.as_mut() } {
437 c.flags = CAP_DIRECT_SURFACE | CAP_PIXELS;
438 c.formats = FORMAT_XRGB8888;
439 c.max_texture = 0;
440 }
441}
442
443unsafe extern "C" fn evict(e: *mut c_void, key: u64) {
444 if let Some(e) = unsafe { engine(e) } {
445 e.r.evict(key);
446 }
447}
448
449static TABLE_V2: MouserEngineV2 = MouserEngineV2 {
450 base: MouserEngineV1 {
451 abi: MOUSER_ENGINE_ABI_V2,
452 size: std::mem::size_of::<MouserEngineV2>() as u32,
453 name: c"skia".as_ptr(),
454 create,
455 resize,
456 draw,
457 destroy,
458 },
459 abi_min: MOUSER_ENGINE_ABI_V2,
460 abi_max: MOUSER_ENGINE_ABI_V2,
461 caps: Some(caps),
462 set_scale: None,
463 evict: Some(evict),
464 set_vsync: None,
465};
466
467#[unsafe(no_mangle)]
469pub extern "C" fn mouser_engine_v2() -> *const MouserEngineV2 {
470 &TABLE_V2
471}