crcbl_core/surface.rs
1//! [`SurfaceTarget`] — the one sanctioned platform leak in the engine.
2//!
3//! # Why this lives in `crcbl-core`
4//!
5//! The windowing rules in `docs/notes/backends.md` describe `SurfaceTarget` as
6//! "the *single* sanctioned platform leak": the shell produces it, a HAL backend consumes it,
7//! and nothing in between is allowed to look inside. That makes it **shared
8//! vocabulary between two crates that must not depend on each other**:
9//!
10//! ```text
11//! crcbl-core (SurfaceTarget lives here)
12//! ^ ^
13//! | |
14//! crcbl-shell crcbl-hal
15//! ^
16//! |
17//! crcbl-vk / crcbl-webgpu / …
18//! ```
19//!
20//! * `crcbl-shell` must not depend on `crcbl-hal` — a windowing library that
21//! needs a graphics HAL to compile has the dependency backwards, and
22//! `HeadlessShell` would drag a backend seam into CI-only builds.
23//! * `crcbl-hal` must not depend on `crcbl-shell` — backends are used offscreen
24//! (`crcbl screenshot`, golden-image e2e) with no window anywhere in the
25//! process, and `crcbl-shell` will grow real platform code that a headless
26//! render test has no business linking.
27//!
28//! Both already depend on `crcbl-core`, so putting the type here is the only
29//! placement that does not create a cycle or a spurious dependency. It costs
30//! `crcbl-core` nothing: the type is a plain enum of integers and raw pointers
31//! with no methods that touch them.
32//!
33//! # Safety model
34//!
35//! Constructing a `SurfaceTarget` is **safe**. Nothing here dereferences a
36//! pointer, and a wrong value is inert until a backend uses it. The obligation
37//! sits at the single point that can act on it — `crcbl-hal`'s
38//! `Instance::create_surface`, which is `unsafe` and documents the full
39//! contract (handles are live objects of the stated kind, and they outlive the
40//! surface created from them).
41//!
42//! This mirrors `raw-window-handle` 0.6 and `wgpu::Instance::create_surface_unsafe`,
43//! and it means this module — the one place platform pointers enter the engine
44//! — contains no `unsafe` at all.
45//!
46//! # Thread safety
47//!
48//! `SurfaceTarget` is deliberately **not** `Send`/`Sync` (it holds
49//! [`NonNull`]). Several of these handles are thread-affine in ways we cannot
50//! promise away — a Win32 `HWND` belongs to the thread that pumps its message
51//! queue, and an `NSView`/`CAMetalLayer` is main-thread-only on macOS. The
52//! practical consequence is the one every engine already lives with: create the
53//! HAL surface on the thread that owns the window. `raw-window-handle` reached
54//! the same conclusion in 0.6 after shipping the unsound `Send` version.
55
56use core::ffi::c_void;
57use core::ptr::NonNull;
58
59/// A window's native presentation handles, in the form a HAL backend needs to
60/// create a surface.
61///
62/// Produced by `crcbl-shell`, destructured *only* by HAL backends. Engine code,
63/// samples and the editor pass it through opaquely; a `#[cfg]` on a platform in
64/// a consumer crate is a regression.
65///
66/// # Exhaustiveness
67///
68/// This enum is intentionally **not** `#[non_exhaustive]`. Adding a platform
69/// should break every backend's `match` loudly at compile time — the whole
70/// engine is one workspace, and a silently-ignored new platform is exactly the
71/// failure this type exists to prevent.
72///
73/// # Variants and their producers
74///
75/// | Variant | Shell backend | Vulkan entry point |
76/// | --- | --- | --- |
77/// | [`Wayland`](Self::Wayland) | Wayland (P0) | `vkCreateWaylandSurfaceKHR` |
78/// | [`Xcb`](Self::Xcb) | X11 (P0) | `vkCreateXcbSurfaceKHR` |
79/// | [`Web`](Self::Web) | canvas (P5) | — (WebGPU `GPUCanvasContext`) |
80/// | [`Win32`](Self::Win32) | Win32 (P14) | `vkCreateWin32SurfaceKHR` |
81/// | [`AppKit`](Self::AppKit) | AppKit (P14) | `vkCreateMetalSurfaceEXT` |
82/// | [`Offscreen`](Self::Offscreen) | `HeadlessShell` | — (image ring, no WSI) |
83///
84/// Xlib is absent on purpose: topic 15 links `libxcb`, not `libX11`, so no
85/// shell backend can produce an `Xlib` target and a variant nobody constructs
86/// is a variant every backend still has to handle.
87///
88/// # Transparency travels here
89///
90/// Every variant that names a desktop window carries `transparent`: the shell
91/// sets it from the window's `WindowDesc::transparent` (`crcbl-shell`, named
92/// rather than linked, see the module docs), and
93/// [`transparent`](Self::transparent) reads it whatever the platform. The
94/// window is what knows it was made transparent, so the renderer learns it
95/// from the window's own handles rather than from a second statement that
96/// could disagree. A presenter that sees it asks for premultiplied alpha, and
97/// one whose surface cannot composite that way refuses rather than drawing the
98/// window opaque.
99///
100/// [`Web`](Self::Web) and [`Offscreen`](Self::Offscreen) carry no flag. The web
101/// shell refuses a transparent window, since what shows through a canvas is the
102/// page's business, so a canvas target is never one; an offscreen ring has no
103/// compositor to blend with, and its readback holds whatever alpha the frame
104/// wrote either way.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub enum SurfaceTarget {
107 /// Wayland: `wl_display*` + `wl_surface*`, as returned by
108 /// `libwayland-client` (topic 15's WSI-ABI exception — the driver calls
109 /// libwayland functions on these).
110 Wayland {
111 /// `struct wl_display *`.
112 display: NonNull<c_void>,
113 /// `struct wl_surface *`.
114 surface: NonNull<c_void>,
115 /// The window was created transparent. The compositor blends the
116 /// surface by its buffer's alpha, so a presenter asks for
117 /// premultiplied alpha; the surface itself is made the same way.
118 transparent: bool,
119 },
120 /// X11 through XCB: `xcb_connection_t*` plus the window's XID.
121 Xcb {
122 /// `xcb_connection_t *`.
123 connection: NonNull<c_void>,
124 /// `xcb_window_t` — an XID, not a pointer.
125 window: u32,
126 /// `xcb_visualid_t` of the window, needed by some backends to pick a
127 /// compatible format.
128 visual_id: u32,
129 /// The window was created transparent. The X11 shell makes every
130 /// window on the root visual, which has no alpha, and refuses a
131 /// transparent one, so it always sets this `false`; the field is here
132 /// so that a backend reads transparency the same way on every window
133 /// system.
134 transparent: bool,
135 },
136 /// Windows: module instance + window handle, and whether the window was
137 /// made for per-pixel transparency.
138 Win32 {
139 /// `HINSTANCE` of the module that registered the window class.
140 hinstance: NonNull<c_void>,
141 /// `HWND`.
142 hwnd: NonNull<c_void>,
143 /// The window was created transparent (`WS_EX_NOREDIRECTIONBITMAP`):
144 /// it has no redirection surface, so nothing presented to the `HWND`
145 /// itself is shown, and a backend must present through
146 /// DirectComposition with premultiplied alpha.
147 ///
148 /// Windows is the one window system where this changes how a backend
149 /// makes the *surface*, not only which alpha its swapchain asks for.
150 /// A backend that cannot present this way refuses the surface by name
151 /// rather than drawing into a window that shows nothing.
152 transparent: bool,
153 },
154 /// macOS/iOS: a `CAMetalLayer*`.
155 ///
156 /// The shell creates and owns the layer (attaching it to its `NSView`), so
157 /// backends never have to touch AppKit — Metal takes the layer directly and
158 /// `VK_EXT_metal_surface` takes it through MoltenVK.
159 AppKit {
160 /// `CAMetalLayer *`.
161 layer: NonNull<c_void>,
162 /// The window was created transparent: the shell made the window and
163 /// this layer non-opaque. A presenter keeps the layer non-opaque and
164 /// asks for premultiplied alpha, which is how Core Animation blends a
165 /// layer's contents.
166 transparent: bool,
167 },
168 /// Web: an integer key into the shell's JS-side canvas registry.
169 ///
170 /// Topic 15 specifies a hand-rolled JS shim rather than `wasm-bindgen`, so
171 /// the canvas is identified by a number the shim assigns — no string
172 /// allocation crosses the wasm boundary, and this variant stays `Copy`.
173 Web {
174 /// Registry key handed out by the shell's JS shim.
175 canvas_id: u32,
176 },
177 /// No window at all: render into a backend-managed image ring and read
178 /// back.
179 ///
180 /// `HeadlessShell` (topic 15) and `crcbl screenshot` (topic 11) need a
181 /// target to hand the HAL even though there is nothing to present to.
182 /// Backends implement this as a swapchain-shaped rotation of offscreen
183 /// images, which is what makes the P1 golden-image e2e run through the
184 /// *same* acquire/present code path as a real window instead of a
185 /// second, less-tested one.
186 ///
187 /// # It deliberately carries no size
188 ///
189 /// It used to carry `width` and `height`, and that was a defect. Every
190 /// other variant names *handles*, which a resize does not touch — which is
191 /// exactly why `crcbl-shell` only requires a target to be re-queried after
192 /// a **mode** change. A size made this one variant change value on every
193 /// resize, so a surface created from an earlier target silently described
194 /// the wrong extent, and the seam had one rule for five variants and
195 /// another for the sixth.
196 ///
197 /// The extent comes from where it comes from for every other target: the
198 /// shell's `WindowState::size`, passed to the backend in the swapchain
199 /// descriptor. `crcbl-hal`'s `swapchain` module states that precedence as
200 /// a backend obligation. (No intra-doc link: this crate must not depend on
201 /// `crcbl-shell` — see the module docs.)
202 Offscreen,
203}
204
205impl SurfaceTarget {
206 /// A short, stable name for the platform this target names.
207 ///
208 /// For logs and error messages — `"wayland"`, `"xcb"`, `"win32"`,
209 /// `"appkit"`, `"web"`, `"offscreen"`.
210 #[must_use]
211 pub const fn platform_name(&self) -> &'static str {
212 match self {
213 Self::Wayland { .. } => "wayland",
214 Self::Xcb { .. } => "xcb",
215 Self::Win32 { .. } => "win32",
216 Self::AppKit { .. } => "appkit",
217 Self::Web { .. } => "web",
218 Self::Offscreen => "offscreen",
219 }
220 }
221
222 /// Whether the window behind this target was created transparent, so the
223 /// desktop should show through where the frame's alpha is below one.
224 ///
225 /// Always `false` for [`Web`](Self::Web) and
226 /// [`Offscreen`](Self::Offscreen); see the type's docs for why they carry
227 /// no flag.
228 #[must_use]
229 pub const fn transparent(&self) -> bool {
230 match *self {
231 Self::Wayland { transparent, .. }
232 | Self::Xcb { transparent, .. }
233 | Self::Win32 { transparent, .. }
234 | Self::AppKit { transparent, .. } => transparent,
235 Self::Web { .. } | Self::Offscreen => false,
236 }
237 }
238
239 /// Whether this target presents to a real window server.
240 ///
241 /// `false` only for [`SurfaceTarget::Offscreen`]. Backends use it to skip
242 /// WSI extension checks and present-queue selection.
243 #[must_use]
244 pub const fn is_windowed(&self) -> bool {
245 !matches!(self, Self::Offscreen)
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 fn dangling() -> NonNull<c_void> {
254 NonNull::dangling()
255 }
256
257 #[test]
258 fn platform_names_are_distinct_and_stable() {
259 let targets = [
260 SurfaceTarget::Wayland {
261 display: dangling(),
262 surface: dangling(),
263 transparent: false,
264 },
265 SurfaceTarget::Xcb {
266 connection: dangling(),
267 window: 1,
268 visual_id: 2,
269 transparent: false,
270 },
271 SurfaceTarget::Win32 {
272 hinstance: dangling(),
273 hwnd: dangling(),
274 transparent: false,
275 },
276 SurfaceTarget::AppKit {
277 layer: dangling(),
278 transparent: false,
279 },
280 SurfaceTarget::Web { canvas_id: 7 },
281 SurfaceTarget::Offscreen,
282 ];
283 let mut names: Vec<_> = targets.iter().map(SurfaceTarget::platform_name).collect();
284 let count = names.len();
285 names.sort_unstable();
286 names.dedup();
287 assert_eq!(names.len(), count, "platform names must be unique");
288 }
289
290 #[test]
291 fn only_offscreen_is_unwindowed() {
292 assert!(
293 SurfaceTarget::Web { canvas_id: 0 }.is_windowed(),
294 "a canvas is a real presentation target"
295 );
296 assert!(!SurfaceTarget::Offscreen.is_windowed());
297 }
298
299 /// Every windowed variant answers its own flag, both ways, and the two
300 /// that carry none answer `false`.
301 #[test]
302 fn transparent_reads_each_windowed_variants_own_flag() {
303 for flag in [false, true] {
304 let targets = [
305 SurfaceTarget::Wayland {
306 display: dangling(),
307 surface: dangling(),
308 transparent: flag,
309 },
310 SurfaceTarget::Xcb {
311 connection: dangling(),
312 window: 1,
313 visual_id: 2,
314 transparent: flag,
315 },
316 SurfaceTarget::Win32 {
317 hinstance: dangling(),
318 hwnd: dangling(),
319 transparent: flag,
320 },
321 SurfaceTarget::AppKit {
322 layer: dangling(),
323 transparent: flag,
324 },
325 ];
326 for target in targets {
327 assert_eq!(target.transparent(), flag, "{target:?}");
328 }
329 }
330 assert!(!SurfaceTarget::Web { canvas_id: 0 }.transparent());
331 assert!(!SurfaceTarget::Offscreen.transparent());
332 }
333
334 #[test]
335 fn target_is_copy_and_comparable() {
336 let a = SurfaceTarget::Web { canvas_id: 3 };
337 let b = a;
338 assert_eq!(a, b);
339 assert_ne!(a, SurfaceTarget::Web { canvas_id: 4 });
340 }
341
342 // The deliberate non-`Send`/non-`Sync` property from the module docs is
343 // enforced structurally rather than by a test: [`NonNull`] is `!Send` and
344 // `!Sync`, so the only way to widen it is a hand-written `unsafe impl` in
345 // this file. Asserting the *absence* of an auto trait needs either
346 // specialization or a `trybuild` compile-fail fixture, and neither is worth
347 // a dependency to restate what the type system already guarantees. If you
348 // are here to add that `unsafe impl`, read the module docs first.
349}