teksilo_platform/window.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{Arc, Mutex, OnceLock, mpsc};
6
7use teksilo_canvas::wake::{RedrawWaker, WakeKind};
8
9use winit::event::WindowEvent;
10use winit::window::Window;
11
12use accesskit::ActionRequest;
13use teksilo_render::Renderer;
14
15use crate::wake::{LiveWakeStats, RequestRedraw, WindowWakeTarget};
16
17/// Error returned when surface texture acquisition fails during rendering.
18#[derive(Debug, thiserror::Error)]
19#[error("Surface error: {0}")]
20pub struct SurfaceRenderError(pub String);
21
22/// Why a window could not configure its swapchain.
23///
24/// `Surface::configure` reports nothing: it hands its error to wgpu's
25/// uncaptured-error handler, whose default is to panic. Every configure in
26/// this file goes through [`configure_surface`] instead, which catches the
27/// error and sorts it into one of these two.
28///
29/// Crate-internal: what a caller outside acts on is
30/// [`FrameOutcome::DisplayLost`] and [`PlatformWindow::display_lost`], not the
31/// classification behind them.
32#[derive(Debug, thiserror::Error)]
33pub(crate) enum SurfaceConfigureError {
34 /// The surface can no longer answer for its adapter. On every backend
35 /// that means the connection to the display server is gone: the
36 /// compositor exited or crashed, or the GPU was reset under it.
37 ///
38 /// wgpu's own wording for this is `Surface does not support the
39 /// adapter's queue family`, which reads like a hardware mismatch and has
40 /// been reported as one. It is not. The adapter was chosen with
41 /// `compatible_surface`, and `request_adapter` filters on the very query
42 /// that fails here (`wgpu_core::instance`), so it answered yes to the
43 /// same question moments earlier. What changed is the surface, not the
44 /// adapter.
45 #[error(
46 "the display server connection is gone: the window surface now reports no \
47 supported formats for an adapter that was selected for it"
48 )]
49 DisplayLost,
50 /// wgpu refused the configuration for some other reason, carrying its own
51 /// message so a genuine mistake is not relabelled as a dead compositor.
52 #[error("wgpu refused the surface configuration: {0}")]
53 Rejected(String),
54}
55
56/// Outcome of [`PlatformWindow::render_frame`]. Mirrors the wgpu
57/// surface-status cases that matter to the caller so the app loop can
58/// decide how to respond (ignore, reconfigure, log) without every frame
59/// getting logged as an error.
60#[derive(Debug)]
61pub enum FrameOutcome {
62 /// Frame was rendered and presented.
63 Rendered,
64 /// wgpu reported the window as occluded or the acquire timed out.
65 /// Per wgpu guidance, skip this frame. On macOS, the initial paint
66 /// after window creation often hits `Occluded` one or more times
67 /// before Metal finishes compositing, so the caller should still
68 /// request another redraw once, and later ones after a growing wait —
69 /// unless it knows the window is hidden (occluded or minimised), or
70 /// [`PlatformWindow::occluded_now`] says it is.
71 ///
72 /// Wayland does not report a hidden surface this way: acquire keeps
73 /// succeeding there. A hidden Wayland window is throttled by the frame
74 /// callbacks `render_frame` requests, which its compositor withholds.
75 Skipped,
76 /// Surface became outdated (resize, scale change, device switch).
77 /// Caller should reconfigure the surface and try again.
78 NeedsReconfigure,
79 /// The display server is gone, so this window can never present again.
80 /// Caller should wind the application down. It must not reconfigure or
81 /// ask for another redraw: both come straight back here, and that spin
82 /// is the whole reason this is its own outcome rather than an `Error`.
83 DisplayLost,
84 /// Acquisition failed with a non-transient error.
85 Error(SurfaceRenderError),
86}
87
88/// A platform window wrapping a winit window, wgpu surface, renderer,
89/// and AccessKit adapter for screen reader support.
90pub struct PlatformWindow {
91 window: Arc<Window>,
92 surface: wgpu::Surface<'static>,
93 surface_config: wgpu::SurfaceConfiguration,
94 /// The adapter this surface was matched against. Kept so that a configure
95 /// failure can ask the surface whether it still has formats for it, which
96 /// is how [`classify_configure_failure`] tells a departed display server
97 /// from a configuration wgpu genuinely refused.
98 adapter: wgpu::Adapter,
99 /// Latched the first time the display server is found to be gone. Every
100 /// later configure and every frame is then skipped: with no compositor
101 /// there is nothing to present to, and retrying only spins the loop.
102 display_lost: bool,
103 renderer: Renderer,
104 scale_factor: f64,
105 a11y_adapter: Option<accesskit_winit::Adapter>,
106 /// Set by the activation handler when an assistive technology asks for
107 /// the tree; cleared by the first delivery after it. Shared because the
108 /// handler may run off the main thread.
109 a11y_needs_full_tree: Arc<AtomicBool>,
110 /// Receiver for accessibility action requests from the adapter.
111 a11y_action_rx: mpsc::Receiver<ActionRequest>,
112 /// The accessibility state the adapter's off-thread handlers share with
113 /// the UI thread. See [`AccessibilityBridge`].
114 a11y_bridge: Arc<AccessibilityBridge>,
115 /// The window's wake target: what [`redraw_waker`](Self::redraw_waker)
116 /// hands out, what the accessibility handlers wake the loop through, and
117 /// what [`request_redraw`](Self::request_redraw) goes through.
118 wake: Arc<WindowWakeTarget>,
119}
120
121/// The state an AccessKit adapter's handlers share with the UI thread.
122///
123/// `accesskit_winit::Adapter::with_direct_handlers` requires every handler to
124/// be `Send` and calls it from whatever thread the platform's accessibility
125/// stack happens to use — the UIA provider thread on Windows, an AT-SPI task on
126/// Linux. A [`teksilo_core::WidgetTree`] is `!Send`, so no handler can reach
127/// one. Everything they need to say to the UI thread therefore goes through
128/// this, and everything they need to read from it is a snapshot the UI thread
129/// leaves here.
130/// The whole policy lives here rather than in the three handler types,
131/// because a handler owns an `Arc<Window>` and so cannot be built in a test
132/// without an event loop, while this can.
133#[derive(Debug, Default)]
134pub(crate) struct AccessibilityBridge {
135 /// The most recent `TreeUpdate` the UI thread published, kept so that
136 /// `request_initial_tree` can answer with the real tree instead of a
137 /// placeholder. `None` before the first frame.
138 snapshot: Mutex<Option<accesskit::TreeUpdate>>,
139 /// Whether an AccessKit client is attached right now. Set on activation,
140 /// cleared on deactivation.
141 active: std::sync::atomic::AtomicBool,
142}
143
144impl AccessibilityBridge {
145 /// Leave a tree where the activation handler can find it. Called from the
146 /// UI thread on every published update.
147 ///
148 /// A no-op while a client is attached, and that is the point: the snapshot
149 /// is read by `request_initial_tree` alone, which by definition runs while
150 /// nothing is attached — an attached client already has the live tree
151 /// through `update_if_active`. Skipping the clone there keeps the cost off
152 /// the frame path exactly when a screen reader is running and frames matter
153 /// most. The window between a detach and the next frame leaves the snapshot
154 /// one frame stale, which is a frame-old application rather than an empty
155 /// one; the deactivation handler asks for that frame.
156 pub(crate) fn publish(&self, update: &accesskit::TreeUpdate) {
157 if self.is_active() {
158 return;
159 }
160 if let Ok(mut slot) = self.snapshot.lock() {
161 *slot = Some(update.clone());
162 }
163 }
164
165 /// A client attached: record it and answer with the best tree available.
166 ///
167 /// The last published one if there is one — an assistive technology
168 /// attaching to an idle window must not be shown an empty application —
169 /// and the bare window node only before this window has ever drawn.
170 pub(crate) fn on_activate(&self) -> accesskit::TreeUpdate {
171 self.active
172 .store(true, std::sync::atomic::Ordering::Relaxed);
173 self.snapshot
174 .lock()
175 .ok()
176 .and_then(|slot| slot.clone())
177 .unwrap_or_else(empty_initial_tree)
178 }
179
180 /// The last client detached.
181 pub(crate) fn on_deactivate(&self) {
182 self.active
183 .store(false, std::sync::atomic::Ordering::Relaxed);
184 }
185
186 /// Whether a client is attached right now.
187 pub(crate) fn is_active(&self) -> bool {
188 self.active.load(std::sync::atomic::Ordering::Relaxed)
189 }
190}
191
192/// The wgpu objects every window in the process shares.
193///
194/// All three are `Arc` handles internally, so cloning one is a refcount bump,
195/// not a second GPU object.
196#[derive(Clone)]
197struct SharedGpu {
198 adapter: wgpu::Adapter,
199 device: wgpu::Device,
200 queue: wgpu::Queue,
201 /// The device's lost-device latch, installed once when it was opened and
202 /// shared by every window's renderer on it.
203 health: teksilo_render::DeviceHealth,
204}
205
206/// The platform display connection the wgpu instance is built against.
207///
208/// Installed by the app layer via [`install_display_handle`] before the first
209/// window exists, and read once by [`shared_instance`].
210static DISPLAY_HANDLE: OnceLock<winit::event_loop::OwnedDisplayHandle> = OnceLock::new();
211
212/// Hand wgpu the platform display connection, before any window is created.
213///
214/// Load-bearing for the OpenGL backend, which is the only backend a machine
215/// with no Vulkan driver has left — an older GPU, or a VM whose guest driver
216/// stops at GL. Without a display handle, wgpu-hal's GLES backend has no
217/// windowing system to bind EGL to and falls back to
218/// `EGL_MESA_platform_surfaceless`: a display that can render offscreen but can
219/// never be compatible with a *window* surface. `request_adapter` then rejects
220/// the only adapter on the machine with `incompatible_surface_backends: GL`,
221/// and the process dies before its first window. Vulkan, Metal and D3D12 ignore
222/// the handle entirely, so this costs those paths nothing.
223///
224/// Only the first call counts; later ones are ignored, because the instance is
225/// built once per process and wgpu forbids presenting a surface from a display
226/// other than the one the instance was created with.
227pub fn install_display_handle(handle: winit::event_loop::OwnedDisplayHandle) {
228 let _ = DISPLAY_HANDLE.set(handle);
229}
230
231/// The display handle [`install_display_handle`] installed, if any. The
232/// Wayland data hub keeps it to hold the connection open.
233#[cfg(all(unix, not(target_os = "macos")))]
234pub(crate) fn installed_display_handle() -> Option<&'static winit::event_loop::OwnedDisplayHandle> {
235 DISPLAY_HANDLE.get()
236}
237
238/// The one wgpu instance for this process.
239///
240/// A surface has to come from the same instance that later enumerates adapters
241/// for it, so this is the root every window hangs off. `Instance::new` is
242/// synchronous, which is why this one can be a plain `OnceLock` while the
243/// adapter and device below cannot.
244///
245/// The descriptor is built `_from_env`, so wgpu's own variables —
246/// `WGPU_BACKEND`, `WGPU_GLES_MINOR_VERSION` and the rest — work here as they
247/// do in every other wgpu application. That is the escape hatch for the machine
248/// whose preferred backend has a broken driver, and it is worth having
249/// precisely where the default choice is the thing under suspicion.
250///
251/// Its flags come from [`teksilo_render::instance_flags`] rather than from
252/// `_from_env` alone, so this instance and the offscreen one
253/// [`teksilo_render::test_support`] opens agree about them.
254///
255/// On Windows the OpenGL backend is left out when Direct3D 12 or Vulkan has
256/// an adapter, unless `WGPU_BACKEND` names the backends. wgpu's OpenGL
257/// backend there starts a thread that creates a hidden top-level window and
258/// never handles a message: every message Windows sends to all top-level
259/// windows waits on it, and a sign-out waited five seconds for its
260/// `WM_QUERYENDSESSION` answer, then ended the process, in every
261/// application, although Direct3D 12 drew. A machine with neither keeps
262/// OpenGL.
263fn shared_instance() -> &'static wgpu::Instance {
264 static INSTANCE: OnceLock<wgpu::Instance> = OnceLock::new();
265 INSTANCE.get_or_init(|| {
266 let descriptor = || {
267 let mut descriptor = match DISPLAY_HANDLE.get() {
268 Some(display) => wgpu::InstanceDescriptor::new_with_display_handle_from_env(
269 Box::new(display.clone()),
270 ),
271 // No app layer installed one: an embedder driving
272 // `PlatformWindow` itself, or a test. Offscreen work is
273 // unaffected; only a GL-backed window needs the handle.
274 None => wgpu::InstanceDescriptor::new_without_display_handle_from_env(),
275 };
276 descriptor.flags = teksilo_render::instance_flags();
277 descriptor
278 };
279 #[cfg(target_os = "windows")]
280 if std::env::var_os("WGPU_BACKEND").is_none() {
281 let mut without_gl = descriptor();
282 without_gl.backends.remove(wgpu::Backends::GL);
283 let backends = without_gl.backends;
284 let instance = wgpu::Instance::new(without_gl);
285 if !pollster::block_on(instance.enumerate_adapters(backends)).is_empty() {
286 return instance;
287 }
288 }
289 wgpu::Instance::new(descriptor())
290 })
291}
292
293/// The adapter, device and queue every window shares.
294///
295/// One device per process, not one per window. A device is a heavyweight,
296/// process-level object and a second one buys nothing: each window still needs
297/// its own surface and its own [`Renderer`] (that is where the glyph and path
298/// atlases live), but the driver objects underneath are the same for every
299/// window on the same adapter. Opening one per window duplicated the entire
300/// pipeline set and both atlas textures for every window a user opened.
301///
302/// It also closes a latent crash. Two D3D12 **WARP** devices rasterizing at the
303/// same time fault inside `d3d10warp.dll` — Microsoft's software rasterizer,
304/// and what a GPU-less Windows host actually draws with. Teksilo renders its
305/// windows sequentially on the winit main thread, so that was not reachable
306/// here; it would have become reachable the moment any window work moved off
307/// that thread. `teksilo_render::test_support` shares its offscreen device for
308/// the same reason, where it *was* reachable and did crash.
309///
310/// `surface` is used only to pick an adapter that can actually present to it.
311/// If a later window's surface turns out to be incompatible with the adapter we
312/// cached — a genuinely multi-GPU machine, where the second window opens on the
313/// other GPU — that window quietly gets its own device rather than failing.
314/// The limits a live window asks its device for.
315///
316/// Deliberately **not** [`wgpu::Limits::default`]. That set demands eight
317/// colour attachments, 64 KiB uniform bindings and 8192-pixel textures. This
318/// renderer draws every pass into a *single* colour attachment, binds at most
319/// 8 KiB of uniforms (128 animation slots of 64 bytes) and caps its path atlas
320/// at 4096 pixels. The headroom was inherited from the default, never needed.
321///
322/// On GLES-3.1 class hardware that headroom is not merely unused, it is
323/// refused: a Raspberry Pi 4's V3D driver allows four colour attachments, so
324/// `default()` failed device creation outright and the app could not open a
325/// window at all.
326///
327/// `downlevel_defaults` is wgpu's GLES-3.1 floor, which is exactly that class
328/// of hardware, and it is already what [`teksilo_render::test_support`] opens
329/// its offscreen device with, so a frame that renders in a test now renders in
330/// a window too. `using_resolution` lifts the three texture-dimension limits
331/// back to whatever this adapter really supports, because the path atlas grows
332/// past the 2048-pixel downlevel cap.
333fn window_device_limits(adapter_limits: wgpu::Limits) -> wgpu::Limits {
334 wgpu::Limits::downlevel_defaults().using_resolution(adapter_limits)
335}
336
337/// Open a device on `adapter`, preferring [`window_device_limits`] and falling
338/// back to whatever the adapter itself reports.
339///
340/// The fallback is not redundant. `downlevel_defaults` is a floor for a *class*
341/// of hardware, not a promise about any given adapter. Anything below GLES 3.1
342/// (an old GL driver, a constrained software rasterizer) can sit under it on a
343/// field `using_resolution` does not lift, and then the principled ask fails
344/// for the same reason `default()` did on the Pi. `adapter.limits()` is by
345/// construction the most that adapter can give, so it cannot be refused on
346/// limit grounds; a request that still fails has a real problem rather than a
347/// mis-sized ask, and that is the error worth propagating.
348async fn open_device(
349 adapter: &wgpu::Adapter,
350) -> Result<(wgpu::Device, wgpu::Queue), wgpu::RequestDeviceError> {
351 let descriptor = |limits| wgpu::DeviceDescriptor {
352 label: Some("teksilo_device"),
353 required_features: wgpu::Features::empty(),
354 required_limits: limits,
355 ..Default::default()
356 };
357
358 match adapter
359 .request_device(&descriptor(window_device_limits(adapter.limits())))
360 .await
361 {
362 Ok(pair) => Ok(pair),
363 Err(err) => {
364 // Say why we dropped to the adapter's own limits: a silent
365 // fallback turns "this GPU is below the GLES-3.1 floor" into an
366 // unexplained difference in behaviour between two machines.
367 eprintln!(
368 "teksilo-platform: downlevel device limits refused ({err}); \
369 retrying with the adapter's own limits"
370 );
371 adapter.request_device(&descriptor(adapter.limits())).await
372 }
373 }
374}
375
376/// The backends this platform prefers, most preferred first.
377///
378/// wgpu does not rank backends. `Instance::new` initialises them in a fixed
379/// order — Vulkan, Metal, D3D12, GLES — and `request_adapter` then sorts the
380/// adapters it collected **only** by device type, and only when a power
381/// preference is set. Ours is `PowerPreference::None` unless `WGPU_POWER_PREF`
382/// says otherwise, which is wgpu's own default and sorts nothing at all. So the
383/// winner has been "the first adapter the first initialised backend
384/// enumerated", which on Windows means D3D12 was never reached as long as any
385/// Vulkan ICD was installed, however old.
386///
387/// That is the wrong default there. D3D12 is the backend Windows GPU drivers
388/// are tested against hardest — it is what the browsers use on Windows — while
389/// Vulkan support on older Windows hardware ranges from good to a stub that
390/// enumerates an adapter it cannot really drive. The field report that prompted
391/// this is one of those: a Windows 10 machine whose Vulkan ICD cannot build
392/// wgpu's own indirect-validation pipelines (see
393/// [`teksilo_render::instance_flags`]) and, past that, cannot present at all,
394/// while D3D12 on the same machine works.
395///
396/// Elsewhere the order simply writes down what wgpu already did, so this is a
397/// change of behaviour on Windows only. An explicit `WGPU_BACKEND` still wins:
398/// it is applied at `Instance::new`, so the backends it excludes enumerate
399/// nothing here and this order silently narrows to the one that was asked for.
400fn preferred_backends() -> &'static [wgpu::Backends] {
401 #[cfg(target_os = "windows")]
402 {
403 &[
404 wgpu::Backends::DX12,
405 wgpu::Backends::VULKAN,
406 wgpu::Backends::GL,
407 ]
408 }
409 #[cfg(any(target_os = "macos", target_os = "ios"))]
410 {
411 &[
412 wgpu::Backends::METAL,
413 wgpu::Backends::VULKAN,
414 wgpu::Backends::GL,
415 ]
416 }
417 #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
418 {
419 &[wgpu::Backends::VULKAN, wgpu::Backends::GL]
420 }
421}
422
423/// The adapters on `backends` that can present to `surface`, ranked as
424/// `request_adapter` would rank them.
425///
426/// `enumerate_adapters` asks each backend for its adapters with no surface, so
427/// the "can this one actually present to this window" filter that
428/// `request_adapter` applies internally has to be applied here instead. A
429/// non-empty format list is wgpu's own answer to that question, and it is the
430/// same one [`shared_gpu_for`] uses to revalidate the cached adapter.
431///
432/// The ordering within a backend deliberately mirrors
433/// `wgpu_core::instance::request_adapter`: rank by device type under a power
434/// preference, and leave enumeration order alone under `None`. Keeping the two
435/// identical means this pass changes *which backend* is tried first and nothing
436/// else about how an adapter is chosen.
437async fn presentable_adapters(
438 surface: &wgpu::Surface<'static>,
439 backends: wgpu::Backends,
440 power_preference: wgpu::PowerPreference,
441) -> Vec<wgpu::Adapter> {
442 let mut adapters: Vec<wgpu::Adapter> = shared_instance()
443 .enumerate_adapters(backends)
444 .await
445 .into_iter()
446 .filter(|adapter| !surface.get_capabilities(adapter).formats.is_empty())
447 .collect();
448
449 let prefer_integrated = match power_preference {
450 wgpu::PowerPreference::LowPower => true,
451 wgpu::PowerPreference::HighPerformance => false,
452 // wgpu does not sort at all here, so neither do we.
453 _ => return adapters,
454 };
455 adapters
456 .sort_by_key(|adapter| device_type_rank(adapter.get_info().device_type, prefer_integrated));
457 adapters
458}
459
460/// `wgpu_core::instance::request_adapter`'s `get_order`, kept in step with it.
461///
462/// "Other" outranks the virtual and CPU types because a backend that does not
463/// report device types at all (OpenGL) lands there, and it is likelier to be
464/// real hardware than a software rasterizer is.
465fn device_type_rank(device_type: wgpu::DeviceType, prefer_integrated: bool) -> u8 {
466 match device_type {
467 wgpu::DeviceType::DiscreteGpu if prefer_integrated => 2,
468 wgpu::DeviceType::IntegratedGpu if prefer_integrated => 1,
469 wgpu::DeviceType::DiscreteGpu => 1,
470 wgpu::DeviceType::IntegratedGpu => 2,
471 wgpu::DeviceType::Other => 3,
472 wgpu::DeviceType::VirtualGpu => 4,
473 wgpu::DeviceType::Cpu => 5,
474 }
475}
476
477/// Find an adapter that can present to `surface` *and* yields a device.
478///
479/// Adapter selection is a search, not a single request — the same lesson
480/// [`teksilo_render::test_support`] already encodes for its offscreen device,
481/// which the window path did not have. A host can enumerate an adapter it
482/// cannot actually open (a VM's GL driver is the usual one) while a perfectly
483/// good software adapter sits behind `force_fallback_adapter`. Treating the
484/// first failure as fatal reports "no GPU" on a machine that has one.
485///
486/// Every pass filters on surface compatibility, so an adapter that cannot
487/// present to this window is never chosen — that is the check that failed on a
488/// machine with no Vulkan driver, and it is load-bearing, not a formality. The
489/// ordered pass tests it with [`presentable_adapters`], the fallback pass with
490/// `request_adapter`'s own `compatible_surface`; both ask wgpu the same
491/// question.
492///
493/// Panics only when *every* adapter on the machine declines, with a message
494/// naming what was tried and what the user can do about it.
495async fn open_gpu_for(
496 surface: &wgpu::Surface<'static>,
497) -> (wgpu::Adapter, wgpu::Device, wgpu::Queue) {
498 // `WGPU_POWER_PREF` is wgpu's own knob; honour it for the same reason the
499 // instance is built `_from_env`.
500 let power_preference = wgpu::PowerPreference::from_env().unwrap_or_default();
501 let mut adapter_error = None;
502 let mut device_error = None;
503
504 // First pass: this platform's own backend order (see
505 // `preferred_backends`). `request_adapter` cannot express "try D3D12
506 // before Vulkan" — its options carry no backend field — so the ordering
507 // has to be done by enumerating one backend at a time.
508 for &backends in preferred_backends() {
509 for adapter in presentable_adapters(surface, backends, power_preference).await {
510 match open_device(&adapter).await {
511 Ok((device, queue)) => return (adapter, device, queue),
512 Err(err) => {
513 eprintln!(
514 "teksilo-platform: adapter {:?} could not open a device ({err}); \
515 trying the next one",
516 adapter.get_info().name
517 );
518 device_error.get_or_insert(err);
519 }
520 }
521 }
522 }
523
524 // Second pass: whatever wgpu itself would have picked, then an explicit
525 // software adapter. The first arm is not redundant with the loop above —
526 // it reaches any backend `preferred_backends` does not name — and the
527 // second is the only way to ask for a CPU adapter, which
528 // `enumerate_adapters` cannot express.
529 for force_fallback_adapter in [false, true] {
530 let adapter = match shared_instance()
531 .request_adapter(&wgpu::RequestAdapterOptions {
532 power_preference,
533 compatible_surface: Some(surface),
534 force_fallback_adapter,
535 ..Default::default()
536 })
537 .await
538 {
539 Ok(adapter) => adapter,
540 Err(err) => {
541 adapter_error.get_or_insert(err);
542 continue;
543 }
544 };
545
546 match open_device(&adapter).await {
547 Ok((device, queue)) => return (adapter, device, queue),
548 Err(err) => {
549 // Worth saying out loud: the next pass silently landing on a
550 // software adapter is a large performance difference, and an
551 // unexplained one is the sort of thing that gets reported as
552 // "Teksilo is slow on my machine".
553 eprintln!(
554 "teksilo-platform: adapter {:?} could not open a device ({err}); \
555 trying the next one",
556 adapter.get_info().name
557 );
558 device_error.get_or_insert(err);
559 }
560 }
561 }
562
563 panic!(
564 "no usable GPU adapter for this window.\n\
565 Tried every backend wgpu was built with, then an explicit software \
566 fallback; none could both present to the window and open a device.\n\
567 adapter search: {adapter_error:?}\n\
568 device open: {device_error:?}\n\
569 Teksilo needs Vulkan, Metal, D3D12 or OpenGL (3.3 desktop / ES 3.0). \
570 On Linux, installing a Vulkan driver is usually the fix: \
571 `mesa-vulkan-drivers` carries both the hardware drivers and the \
572 software `lavapipe`. `WGPU_BACKEND=gl|vulkan|dx12|metal` forces a \
573 specific backend."
574 );
575}
576
577async fn shared_gpu_for(surface: &wgpu::Surface<'static>) -> SharedGpu {
578 static SHARED: Mutex<Option<SharedGpu>> = Mutex::new(None);
579
580 // Clone out and release the lock: it is never held across the awaits below.
581 let cached = SHARED.lock().unwrap_or_else(|e| e.into_inner()).clone();
582 if let Some(gpu) = cached {
583 // A non-empty format list is wgpu's own answer to "can this adapter
584 // present to this surface".
585 if !surface.get_capabilities(&gpu.adapter).formats.is_empty() {
586 return gpu;
587 }
588 }
589
590 let (adapter, device, queue) = open_gpu_for(surface).await;
591
592 // Installed where the device is opened, the shared one and the
593 // multi-GPU loser alike, so every renderer on it reads one latch.
594 let health = teksilo_render::DeviceHealth::install(&device);
595 let gpu = SharedGpu {
596 adapter,
597 device,
598 queue,
599 health,
600 };
601 // First one in becomes the shared device. Losing here is the multi-GPU case
602 // above (or a race that cannot happen while windows are created on one
603 // thread): the loser keeps the device it just opened, which is the old
604 // per-window behaviour and still correct.
605 let mut slot = SHARED.lock().unwrap_or_else(|e| e.into_inner());
606 if slot.is_none() {
607 *slot = Some(gpu.clone());
608 }
609 gpu
610}
611
612/// Configure `surface`, handing back the failure instead of letting wgpu's
613/// default uncaptured-error handler panic.
614///
615/// Every `Surface::configure` in this file goes through here, and the error
616/// scope is what makes that sufficient. Asking the surface whether it is still
617/// alive and *then* configuring it leaves a gap between the two in which the
618/// compositor can exit, and that gap is the bug: `request_adapter` validated
619/// this adapter against this surface with the same query `configure` runs, so
620/// only a change in between can make the second one fail. A scope catches the
621/// error from this exact call, however late the display server goes away.
622///
623/// `pop` resolves immediately on native (wgpu answers with a ready future) and
624/// wgpu's error scopes are thread-local. Both hold because every window in this
625/// process is created and drawn on the winit main thread.
626fn configure_surface(
627 surface: &wgpu::Surface<'static>,
628 adapter: &wgpu::Adapter,
629 device: &wgpu::Device,
630 config: &wgpu::SurfaceConfiguration,
631) -> Result<(), SurfaceConfigureError> {
632 let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
633 surface.configure(device, config);
634 match pollster::block_on(scope.pop()) {
635 None => Ok(()),
636 Some(err) => Err(classify_configure_failure(
637 err.to_string(),
638 !surface.get_capabilities(adapter).formats.is_empty(),
639 )),
640 }
641}
642
643/// Sort a configure failure into "the display server left" and everything
644/// else, on the one signal that separates them.
645///
646/// A live surface offers its adapter a non-empty format list; a surface whose
647/// display server has gone offers none, and that transition is observable:
648/// seven formats before the compositor exits, zero after. Deliberately not a
649/// match on wgpu's message text, which is both misleading here and free to
650/// change between releases.
651fn classify_configure_failure(
652 description: String,
653 surface_has_formats: bool,
654) -> SurfaceConfigureError {
655 if surface_has_formats {
656 SurfaceConfigureError::Rejected(description)
657 } else {
658 SurfaceConfigureError::DisplayLost
659 }
660}
661
662/// What [`PlatformWindow::surface_and_renderer`] hands to both constructors.
663struct WindowGpu {
664 surface: wgpu::Surface<'static>,
665 surface_config: wgpu::SurfaceConfiguration,
666 renderer: Renderer,
667 adapter: wgpu::Adapter,
668 display_lost: bool,
669}
670
671/// A window rendered offscreen and read back: what
672/// [`PlatformWindow::capture_offscreen`] returns.
673#[derive(Debug, Clone, PartialEq, Eq)]
674#[non_exhaustive]
675pub struct OffscreenCapture {
676 /// Tightly packed RGBA8, `width × height` pixels, no padding.
677 pub rgba: Vec<u8>,
678 pub width: u32,
679 pub height: u32,
680 /// Where these pixels sit in the window's surface, in physical pixels:
681 /// the whole surface, or the crop asked for, clamped to it. Empty when
682 /// the crop missed the surface.
683 pub region: teksilo_canvas::PixelRect,
684}
685
686/// The surface pixels a crop rect (physical pixels) covers: its edges
687/// rounded outwards, clamped to a `w × h` surface. Empty when it misses.
688fn crop_region(rect: teksilo_canvas::Rect, w: u32, h: u32) -> teksilo_canvas::PixelRect {
689 let x0 = (rect.x.floor().max(0.0) as u32).min(w);
690 let y0 = (rect.y.floor().max(0.0) as u32).min(h);
691 let x1 = ((rect.x + rect.width).ceil().max(0.0) as u32).min(w);
692 let y1 = ((rect.y + rect.height).ceil().max(0.0) as u32).min(h);
693 if x1 <= x0 || y1 <= y0 {
694 return teksilo_canvas::PixelRect::new(x0, y0, 0, 0);
695 }
696 teksilo_canvas::PixelRect::new(x0, y0, x1 - x0, y1 - y0)
697}
698
699/// The pixels of `region` out of a tightly packed RGBA buffer `w` pixels
700/// wide that contains it.
701fn crop_rgba(src: &[u8], w: u32, region: teksilo_canvas::PixelRect) -> Vec<u8> {
702 let row_bytes = region.width as usize * 4;
703 let mut out = Vec::with_capacity(row_bytes * region.height as usize);
704 for y in region.y..region.y + region.height {
705 let start = (y as usize * w as usize + region.x as usize) * 4;
706 out.extend_from_slice(&src[start..start + row_bytes]);
707 }
708 out
709}
710
711/// One refresh of the display `window` is on, when the display reports its
712/// rate.
713fn display_refresh_interval(window: &Window) -> Option<std::time::Duration> {
714 let millihertz = window.current_monitor()?.refresh_rate_millihertz()?;
715 Some(refresh_interval_from_millihertz(millihertz))
716}
717
718/// The interval of a refresh rate in millihertz. Rates below 20 Hz or above
719/// 1 kHz are read as those bounds: a frame never waits more than 50 ms for a
720/// producer, and always waits at least one millisecond.
721fn refresh_interval_from_millihertz(millihertz: u32) -> std::time::Duration {
722 let millihertz = millihertz.clamp(20_000, 1_000_000);
723 std::time::Duration::from_nanos(1_000_000_000_000 / u64::from(millihertz))
724}
725
726impl PlatformWindow {
727 /// Everything both constructors do: surface, shared device, swapchain
728 /// configuration, renderer. Kept in one place because the two entry points
729 /// differ only in whether they attach an AccessKit adapter, and sixty
730 /// duplicated lines of GPU setup is exactly the sort of thing that drifts.
731 async fn surface_and_renderer(window: &Arc<Window>) -> WindowGpu {
732 let size = window.inner_size();
733 let surface = shared_instance()
734 .create_surface(window.clone())
735 .expect("wgpu surface creation failed for the platform window");
736
737 let gpu = shared_gpu_for(&surface).await;
738
739 let surface_caps = surface.get_capabilities(&gpu.adapter);
740 // Guard the index accesses: a degenerate adapter/surface (software
741 // fallback, headless) can report empty `formats` / `alpha_modes`, and
742 // `[0]` would panic with an opaque out-of-bounds instead of degrading.
743 let surface_format = surface_caps
744 .formats
745 .iter()
746 .find(|f| f.is_srgb())
747 .copied()
748 .or_else(|| surface_caps.formats.first().copied())
749 .unwrap_or(wgpu::TextureFormat::Rgba8UnormSrgb);
750
751 let surface_config = wgpu::SurfaceConfiguration {
752 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
753 format: surface_format,
754 width: size.width.max(1),
755 height: size.height.max(1),
756 present_mode: wgpu::PresentMode::Fifo,
757 alpha_mode: surface_caps
758 .alpha_modes
759 .first()
760 .copied()
761 .unwrap_or(wgpu::CompositeAlphaMode::Auto),
762 view_formats: vec![],
763 desired_maximum_frame_latency: 2,
764 // `Auto` reproduces wgpu's pre-30 behaviour: sRGB for the
765 // non-`Rgba16Float` formats we select above.
766 color_space: wgpu::SurfaceColorSpace::Auto,
767 };
768 // A compositor that goes away while the device above is being opened
769 // lands here, because opening one is the slowest step between the
770 // adapter's validation and this call. It used to panic out of wgpu's
771 // default error handler before the window ever existed.
772 let display_lost =
773 match configure_surface(&surface, &gpu.adapter, &gpu.device, &surface_config) {
774 Ok(()) => false,
775 Err(err) => {
776 eprintln!("teksilo-platform: {err}");
777 matches!(err, SurfaceConfigureError::DisplayLost)
778 }
779 };
780
781 // The renderer stays per-window: it owns the glyph atlas, the path
782 // atlas and the blur pool, and it is `!Sync` besides.
783 let mut renderer =
784 Renderer::with_device_health(gpu.device, gpu.queue, surface_format, gpu.health);
785 if let Some(interval) = display_refresh_interval(window) {
786 renderer.set_live_refresh_interval(interval);
787 }
788 WindowGpu {
789 surface,
790 surface_config,
791 renderer,
792 adapter: gpu.adapter,
793 display_lost,
794 }
795 }
796
797 /// Create a new platform window from a winit window.
798 /// The `event_loop` parameter is needed for the AccessKit adapter.
799 ///
800 /// The window, built hidden, is shown once its adapter exists: made key
801 /// and brought to the front with `activate`, otherwise shown without
802 /// taking the focus (a dialog opened while the user is elsewhere). On
803 /// macOS the inactive show orders the window front without making it
804 /// key; on Windows it is the first show of a window built with
805 /// `with_active(false)`, which winit makes with `SW_SHOWNOACTIVATE`, so
806 /// the caller builds it so. X11 and Wayland leave focus to the window
807 /// manager or compositor either way.
808 pub async fn new_with_a11y(
809 window: Window,
810 event_loop: &winit::event_loop::ActiveEventLoop,
811 activate: bool,
812 ) -> Self {
813 let window = Arc::new(window);
814 let scale_factor = window.scale_factor();
815 let WindowGpu {
816 surface,
817 surface_config,
818 renderer,
819 adapter,
820 display_lost,
821 } = Self::surface_and_renderer(&window).await;
822
823 // Create AccessKit adapter with action channel
824 let (action_tx, action_rx) = mpsc::channel();
825
826 let a11y_needs_full_tree = Arc::new(AtomicBool::new(true));
827 let a11y_bridge = Arc::new(AccessibilityBridge::default());
828
829 // Every handler below runs off the UI thread and ends by waking the
830 // event loop, which is the *only* thing that gets what it left read:
831 // without a wakeup an action issued by Narrator or Orca would sit in
832 // the channel until some unrelated window event happened to arrive.
833 // A state wake, since what they leave must reach a window that draws
834 // nothing: see `WindowWakeTarget`.
835 let wake = WindowWakeTarget::new(Arc::clone(&window) as Arc<dyn RequestRedraw>);
836 let a11y_adapter = accesskit_winit::Adapter::with_direct_handlers(
837 event_loop,
838 &window,
839 TeksiloActivationHandler {
840 needs_full_tree: a11y_needs_full_tree.clone(),
841 bridge: Arc::clone(&a11y_bridge),
842 wake: Arc::clone(&wake),
843 },
844 TeksiloActionHandler {
845 tx: action_tx,
846 wake: Arc::clone(&wake),
847 },
848 TeksiloDeactivationHandler {
849 bridge: Arc::clone(&a11y_bridge),
850 wake: Arc::clone(&wake),
851 },
852 );
853
854 // Show the window now that the adapter is created
855 if activate {
856 window.set_visible(true);
857 } else {
858 crate::window_system::show_without_activating(&window);
859 }
860
861 Self {
862 window,
863 surface,
864 surface_config,
865 adapter,
866 display_lost,
867 renderer,
868 scale_factor,
869 a11y_adapter: Some(a11y_adapter),
870 a11y_action_rx: action_rx,
871 a11y_needs_full_tree,
872 a11y_bridge,
873 wake,
874 }
875 }
876
877 /// Create a platform window without AccessKit (for contexts without ActiveEventLoop).
878 pub async fn new(window: Window) -> Self {
879 let window = Arc::new(window);
880 let scale_factor = window.scale_factor();
881 let WindowGpu {
882 surface,
883 surface_config,
884 renderer,
885 adapter,
886 display_lost,
887 } = Self::surface_and_renderer(&window).await;
888 let (_action_tx, action_rx) = mpsc::channel();
889 let wake = WindowWakeTarget::new(Arc::clone(&window) as Arc<dyn RequestRedraw>);
890
891 Self {
892 window,
893 surface,
894 surface_config,
895 adapter,
896 display_lost,
897 renderer,
898 scale_factor,
899 a11y_adapter: None,
900 a11y_action_rx: action_rx,
901 a11y_needs_full_tree: Arc::new(AtomicBool::new(false)),
902 a11y_bridge: Arc::new(AccessibilityBridge::default()),
903 wake,
904 }
905 }
906
907 pub fn window(&self) -> &Window {
908 &self.window
909 }
910
911 /// Whether the platform says, when asked, that no part of the window is
912 /// visible now: covered entirely, or never shown, as a window created
913 /// while the display slept or the screen was locked is until both end.
914 /// macOS answers (`NSWindow`'s `occlusionState`), and `None` elsewhere,
915 /// where winit's events are all there is.
916 ///
917 /// winit sends `WindowEvent::Occluded` only when that state changes, so
918 /// a window that was never visible never hears it; and wgpu refuses
919 /// every acquire while AppKit does not show the window. Asking is how
920 /// the caller learns it. A window already showing stays visible here
921 /// while the displays sleep or the screen is locked: that is the
922 /// [session watch](crate::session)'s to hear.
923 pub fn occluded_now(&self) -> Option<bool> {
924 #[cfg(target_os = "macos")]
925 {
926 macos_occlusion::occluded(&self.window)
927 }
928 #[cfg(not(target_os = "macos"))]
929 {
930 None
931 }
932 }
933
934 /// Get a clonable `Arc` reference to the underlying winit window.
935 /// Used by `teksilo_platform::create_title_bar_host` and other components
936 /// that need shared ownership of the window.
937 pub fn window_arc(&self) -> Arc<Window> {
938 self.window.clone()
939 }
940
941 pub fn renderer(&self) -> &Renderer {
942 &self.renderer
943 }
944
945 pub fn renderer_mut(&mut self) -> &mut Renderer {
946 &mut self.renderer
947 }
948
949 pub fn scale_factor(&self) -> f64 {
950 self.scale_factor
951 }
952
953 pub fn set_scale_factor(&mut self, factor: f64) {
954 self.scale_factor = factor;
955 }
956
957 /// Read the refresh rate of the display the window is on, and have a
958 /// presented frame wait about one refresh of it for a producer holding a
959 /// live picture's lock. Done when the window is created; call it again
960 /// when the window may have moved to another display. A display that
961 /// reports no rate keeps the last one (60 Hz until one is read).
962 pub fn track_display_refresh(&mut self) {
963 if let Some(interval) = display_refresh_interval(&self.window) {
964 self.renderer.set_live_refresh_interval(interval);
965 }
966 }
967
968 /// What this window's renderer holds and uploads for live pictures.
969 pub fn live_texture_stats(&self) -> teksilo_render::LiveTextureStats {
970 self.renderer.live_texture_stats()
971 }
972
973 /// How long this window's live pass has taken, each figure over its
974 /// latest 1,024 samples: see `Renderer::live_texture_timings`. With the
975 /// `live-image-timings` feature.
976 #[cfg(feature = "live-image-timings")]
977 pub fn live_texture_timings(&self) -> teksilo_render::LiveImageTimings {
978 self.renderer.live_texture_timings()
979 }
980
981 /// Resize the surface.
982 ///
983 /// A resize that arrives once the display server has gone is dropped:
984 /// there is nothing left to present to.
985 pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
986 if self.display_lost || new_size.width == 0 || new_size.height == 0 {
987 return;
988 }
989 self.surface_config.width = new_size.width;
990 self.surface_config.height = new_size.height;
991 self.apply_surface_config();
992 }
993
994 /// Get current surface dimensions.
995 pub fn surface_size(&self) -> (u32, u32) {
996 (self.surface_config.width, self.surface_config.height)
997 }
998
999 /// Reconfigure the surface with the current config.
1000 /// Use after a Lost or Outdated surface error.
1001 ///
1002 /// Answers whether this window can still present. `false` means the
1003 /// display server is gone, and the caller should wind down rather than ask
1004 /// for another frame: the next one would come back here unchanged.
1005 pub fn reconfigure_surface(&mut self) -> bool {
1006 if self.display_lost {
1007 return false;
1008 }
1009 self.apply_surface_config();
1010 !self.display_lost
1011 }
1012
1013 /// Whether the display server has gone away under this window.
1014 pub fn display_lost(&self) -> bool {
1015 self.display_lost
1016 }
1017
1018 /// Push `surface_config` to the surface, latching a departed display
1019 /// server and reporting anything else wgpu refused.
1020 ///
1021 /// The latch is what keeps the report to one line: every later configure
1022 /// returns before reaching here.
1023 fn apply_surface_config(&mut self) {
1024 if let Err(err) = configure_surface(
1025 &self.surface,
1026 &self.adapter,
1027 self.renderer.device(),
1028 &self.surface_config,
1029 ) {
1030 eprintln!("teksilo-platform: {err}");
1031 if matches!(err, SurfaceConfigureError::DisplayLost) {
1032 self.display_lost = true;
1033 }
1034 }
1035 }
1036
1037 /// Render a frame to the surface.
1038 pub fn render_frame(
1039 &mut self,
1040 frame: &teksilo_canvas::RenderFrame,
1041 clear_color: [f32; 4],
1042 ) -> FrameOutcome {
1043 if self.display_lost {
1044 return FrameOutcome::DisplayLost;
1045 }
1046 let current = self.surface.get_current_texture();
1047 let output = match current {
1048 wgpu::CurrentSurfaceTexture::Success(tex)
1049 | wgpu::CurrentSurfaceTexture::Suboptimal(tex) => tex,
1050 wgpu::CurrentSurfaceTexture::Occluded | wgpu::CurrentSurfaceTexture::Timeout => {
1051 return FrameOutcome::Skipped;
1052 }
1053 wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
1054 return FrameOutcome::NeedsReconfigure;
1055 }
1056 other => return FrameOutcome::Error(SurfaceRenderError(format!("{other:?}"))),
1057 };
1058
1059 let view = output
1060 .texture
1061 .create_view(&wgpu::TextureViewDescriptor::default());
1062
1063 let (w, h) = self.surface_size();
1064 self.renderer
1065 .render(frame, &view, self.scale_factor as f32, w, h, clear_color);
1066
1067 // Wayland: request a frame callback with the commit this present
1068 // makes. winit then holds the next `RedrawRequested` back until the
1069 // compositor sends it, which it does not for a hidden surface, so a
1070 // minimised window stops drawing (a no-op on other platforms). winit
1071 // never cancels the request, so every call here MUST be followed by
1072 // the present on the next line: an early return in between would
1073 // leave the window waiting for a callback that never comes.
1074 self.window.pre_present_notify();
1075 self.renderer.queue().present(output);
1076 FrameOutcome::Rendered
1077 }
1078
1079 /// Render `frame` into an offscreen texture of the surface's size and
1080 /// read it back as tightly packed RGBA8.
1081 ///
1082 /// Used by the debug-only automation bridge to capture a *live* window
1083 /// without going through the swapchain — the surface texture is
1084 /// configured `RENDER_ATTACHMENT` only (no `COPY_SRC`), so it can't be
1085 /// read back directly. It renders through the window's own renderer with
1086 /// [`Renderer::render_capture`]: every live picture shows its latest
1087 /// commit, and the window's next frame draws the textures this one
1088 /// filled. The whole frame is rendered, then `crop` (physical pixels,
1089 /// clamped to the surface) is cut out on the CPU: rendering only part of
1090 /// a frame through the window's renderer would drop the textures of the
1091 /// live pictures it left out. The offscreen texture uses the window's
1092 /// own surface format so it matches the renderer's pipelines; a BGRA
1093 /// readback is swizzled to RGBA here so the output is always RGBA. A
1094 /// crop outside the surface returns an empty capture.
1095 ///
1096 /// Fails, without panicking, when the device cannot read the texture
1097 /// back (it was lost).
1098 ///
1099 /// Note: a native `WebView` subview composites *on top of* the wgpu
1100 /// surface and is invisible to this readback (a transparent hole).
1101 pub fn capture_offscreen(
1102 &mut self,
1103 frame: &teksilo_canvas::RenderFrame,
1104 clear_color: [f32; 4],
1105 crop: Option<teksilo_canvas::Rect>,
1106 ) -> Result<OffscreenCapture, teksilo_render::test_support::ReadbackError> {
1107 let (w, h) = self.surface_size();
1108 let format = self.surface_config.format;
1109 // The readback assumes a 4-byte, 8-bit RGBA/BGRA layout (the BGRA
1110 // swizzle below + `try_read_texture_rgba`'s fixed 4-bytes-per-pixel
1111 // copy). Desktop wgpu surfaces are always one of these four; a packed
1112 // (Rgb10a2) or wide (Rgba16Float) surface format would read back
1113 // garbage, so flag it loudly in debug builds.
1114 debug_assert!(
1115 matches!(
1116 format,
1117 wgpu::TextureFormat::Rgba8Unorm
1118 | wgpu::TextureFormat::Rgba8UnormSrgb
1119 | wgpu::TextureFormat::Bgra8Unorm
1120 | wgpu::TextureFormat::Bgra8UnormSrgb
1121 ),
1122 "capture_offscreen: unsupported surface format {format:?} (expected 8-bit RGBA/BGRA)"
1123 );
1124 let texture = self
1125 .renderer
1126 .device()
1127 .create_texture(&wgpu::TextureDescriptor {
1128 label: Some("teksilo-automation capture"),
1129 size: wgpu::Extent3d {
1130 width: w,
1131 height: h,
1132 depth_or_array_layers: 1,
1133 },
1134 mip_level_count: 1,
1135 sample_count: 1,
1136 dimension: wgpu::TextureDimension::D2,
1137 format,
1138 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
1139 view_formats: &[],
1140 });
1141 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
1142 self.renderer
1143 .render_capture(frame, &view, self.scale_factor as f32, w, h, clear_color);
1144 let mut bytes = teksilo_render::test_support::try_read_texture_rgba(
1145 self.renderer.device(),
1146 self.renderer.queue(),
1147 &texture,
1148 w,
1149 h,
1150 )?;
1151 // The readback copies raw channel bytes; a BGRA surface needs its B
1152 // and R swapped to become RGBA for PNG encoding.
1153 if matches!(
1154 format,
1155 wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
1156 ) {
1157 for px in bytes.as_chunks_mut::<4>().0 {
1158 px.swap(0, 2);
1159 }
1160 }
1161 let region = match crop {
1162 Some(rect) => crop_region(rect, w, h),
1163 None => teksilo_canvas::PixelRect::full(w, h),
1164 };
1165 Ok(OffscreenCapture {
1166 rgba: crop_rgba(&bytes, w, region),
1167 width: region.width,
1168 height: region.height,
1169 region,
1170 })
1171 }
1172
1173 /// Ask winit for a redraw. A no-op once the window's wake target is
1174 /// disconnected ([`disconnect_redraw_waker`](Self::disconnect_redraw_waker)),
1175 /// which is how a request after the event loop ended stays harmless.
1176 pub fn request_redraw(&self) {
1177 self.wake.request_on_slot();
1178 }
1179
1180 /// Push an AccessKit TreeUpdate to the adapter (called after layout).
1181 /// Publish a freshly built `TreeUpdate` to the adapter, and leave a copy
1182 /// where the activation handler can find it.
1183 ///
1184 /// The copy is what lets an assistive technology that attaches to an *idle*
1185 /// window see the application instead of an empty window node: the handler
1186 /// runs off the UI thread and cannot build a tree, so the last one the UI
1187 /// thread built is the best answer available synchronously.
1188 ///
1189 /// Hand it what
1190 /// [`WidgetTree::deliver_accessibility`](teksilo_core::WidgetTree::deliver_accessibility)
1191 /// returns, not `sync_accessibility`'s update: a node that left the tree a
1192 /// reader sees and came back must reach the adapter under an id it has
1193 /// never had, or a reader on AT-SPI holds it defunct and hears nothing
1194 /// from it.
1195 pub fn update_accessibility(&mut self, update: accesskit::TreeUpdate) {
1196 self.a11y_bridge.publish(&update);
1197 if let Some(adapter) = &mut self.a11y_adapter {
1198 adapter.update_if_active(|| update);
1199 }
1200 }
1201
1202 /// Push an update the adapter builds only when it is actually going to
1203 /// be delivered, and only when `build` says there is one worth sending.
1204 ///
1205 /// The caller decides *inside* the closure, because that is where the
1206 /// decision belongs: `update_if_active` runs its closure only when an
1207 /// assistive technology is attached, and on Linux it runs it under the
1208 /// adapter's own state lock. Deciding outside would build a tree for
1209 /// nobody on every frame, and would make the throttle count frames
1210 /// nothing was listening to.
1211 ///
1212 /// `build` returning `None` means "nothing to deliver": `previous` then
1213 /// gives the adapter an update that leaves its tree as it is, since
1214 /// `update_if_active` must be given one. An update with no node does
1215 /// that without the adapter comparing a node
1216 /// ([`WidgetTree::accessibility_unchanged`](teksilo_core::WidgetTree::accessibility_unchanged)).
1217 pub fn update_accessibility_with(
1218 &mut self,
1219 build: impl FnOnce() -> Option<accesskit::TreeUpdate>,
1220 previous: impl FnOnce() -> accesskit::TreeUpdate,
1221 ) {
1222 if let Some(adapter) = &mut self.a11y_adapter {
1223 adapter.update_if_active(|| build().unwrap_or_else(previous));
1224 }
1225 }
1226
1227 /// Whether an assistive technology has asked this window for its tree
1228 /// and has not yet been given a full one.
1229 ///
1230 /// Set by the activation handler, which runs on whichever thread the
1231 /// platform's accessibility layer calls it from, and cleared by the
1232 /// first delivery after it — so a reader that attaches mid-session gets
1233 /// a complete tree rather than a geometry patch onto a tree it has
1234 /// never seen.
1235 pub fn accessibility_needs_full_tree(&self) -> bool {
1236 self.a11y_needs_full_tree.load(Ordering::Relaxed)
1237 }
1238
1239 /// Clear the flag above, reporting what it was.
1240 pub fn take_accessibility_needs_full_tree(&self) -> bool {
1241 self.a11y_needs_full_tree.swap(false, Ordering::Relaxed)
1242 }
1243
1244 /// Whether an AccessKit client is attached to this window's adapter.
1245 ///
1246 /// True from the moment the platform accessibility stack asks for an
1247 /// initial tree until it says it has gone away. Read once per frame by
1248 /// `teksilo-app` and pushed into the window's tree; see
1249 /// [`WidgetTree::set_at_client_attached`](teksilo_core::WidgetTree::set_at_client_attached)
1250 /// for why attaching and detaching are read asymmetrically.
1251 ///
1252 /// Always `false` for a window built without an adapter
1253 /// ([`PlatformWindow::new`]).
1254 pub fn accessibility_active(&self) -> bool {
1255 self.a11y_bridge.is_active()
1256 }
1257
1258 /// Forward a winit WindowEvent to the AccessKit adapter.
1259 pub fn process_accessibility_event(&mut self, event: &WindowEvent) {
1260 if let Some(adapter) = &mut self.a11y_adapter {
1261 adapter.process_event(&self.window, event);
1262 }
1263 }
1264
1265 /// This window's wake target, as a waker any thread may call to have the
1266 /// window run a frame. See [`teksilo_canvas::wake`] for the two kinds of
1267 /// wake and how a burst coalesces.
1268 ///
1269 /// On macOS, winit runs a redraw requested off the main thread
1270 /// synchronously on it, so a draw wake made on another thread never asks
1271 /// winit itself there: it posts through the off-main route
1272 /// ([`set_off_main_wake_route`](Self::set_off_main_wake_route)), which
1273 /// teksilo-app installs, or with none hands the request to the main
1274 /// dispatch queue. Either way it returns without waiting for the main
1275 /// thread.
1276 pub fn redraw_waker(&self) -> Arc<dyn RedrawWaker> {
1277 self.wake.clone()
1278 }
1279
1280 /// The route a draw wake made off the main thread posts through, instead
1281 /// of asking winit for a redraw from there. Set once, before the first
1282 /// wake; later calls are ignored. teksilo-app sets it on macOS, where a
1283 /// redraw requested off the main thread waits for it, so that the wake
1284 /// reaches the event loop it runs.
1285 pub fn set_off_main_wake_route(&self, route: Arc<dyn Fn() + Send + Sync>) {
1286 self.wake.set_off_main_route(route);
1287 }
1288
1289 /// The route a state wake posts through: one post per burst, until the
1290 /// event loop takes it ([`take_posted_wake`](Self::take_posted_wake)).
1291 /// Set once; later calls are ignored. teksilo-app's seam: a posted event
1292 /// reaches a window whose redraw the compositor withholds, which a redraw
1293 /// request does not.
1294 #[doc(hidden)]
1295 pub fn set_state_wake_route(&self, route: Arc<dyn Fn() + Send + Sync>) {
1296 self.wake.set_state_route(route);
1297 }
1298
1299 /// The event loop received a posted wake of `kind`: re-arm its
1300 /// coalescing, before acting on it, so the next wake posts again. Returns
1301 /// whether one was pending.
1302 #[doc(hidden)]
1303 pub fn take_posted_wake(&self, kind: WakeKind) -> bool {
1304 self.wake.take_posted(kind)
1305 }
1306
1307 /// `true` while the window is hidden, in which case one redraw is
1308 /// requested when it is shown again: for a draw wake the event loop
1309 /// received while the window was hidden.
1310 #[doc(hidden)]
1311 pub fn defer_redraw_until_shown(&self) -> bool {
1312 self.wake.defer_until_shown()
1313 }
1314
1315 /// Make every waker [`redraw_waker`](Self::redraw_waker) handed out a
1316 /// no-op, and [`request_redraw`](Self::request_redraw) with them. Waits
1317 /// for a wake already asking winit; idempotent. Dropping the window does
1318 /// it too; teksilo-app does it for every window when the event loop ends.
1319 pub fn disconnect_redraw_waker(&self) {
1320 self.wake.disconnect();
1321 }
1322
1323 /// Record whether the window is hidden (minimised, fully covered, or
1324 /// drawing nothing because its compositor withholds its frames). While it
1325 /// is, draw wakes are dropped; showing it requests one redraw if any was.
1326 pub fn set_hidden(&self, hidden: bool) {
1327 self.wake.set_hidden(hidden);
1328 }
1329
1330 /// The window draws again and a frame is about to run: record it shown,
1331 /// without the redraw [`set_hidden`](Self::set_hidden)`(false)` requests
1332 /// for draw wakes dropped while it was hidden, which that frame serves.
1333 /// teksilo-app's seam for the redraw that ends a withheld one.
1334 #[doc(hidden)]
1335 pub fn show_for_drawing(&self) {
1336 self.wake.show_for_drawing();
1337 }
1338
1339 /// Whether the window is hidden, as last set.
1340 pub fn is_hidden(&self) -> bool {
1341 self.wake.is_hidden()
1342 }
1343
1344 /// The window's wake counters.
1345 pub fn live_wake_stats(&self) -> LiveWakeStats {
1346 self.wake.stats()
1347 }
1348
1349 /// Drain any pending AccessKit action requests from the adapter.
1350 ///
1351 /// They name nodes by the ids the adapter was handed; pass each through
1352 /// [`WidgetTree::resolve_adapter_action`](teksilo_core::WidgetTree::resolve_adapter_action)
1353 /// before looking its target up in the tree.
1354 pub fn drain_accessibility_actions(&self) -> Vec<ActionRequest> {
1355 let mut actions = Vec::new();
1356 while let Ok(req) = self.a11y_action_rx.try_recv() {
1357 actions.push(req);
1358 }
1359 actions
1360 }
1361}
1362
1363// --- AccessKit handler implementations ---
1364
1365/// Activation handler — answers with the last tree the UI thread built.
1366///
1367/// An assistive technology attaching to a window that is sitting idle used to
1368/// be shown a bare `Role::Window` node with no children, and stayed shown it
1369/// until something unrelated caused a frame. Answering from the published
1370/// snapshot fixes the common case; the redraw request covers the rest, since
1371/// the adapter is active from here on and the next
1372/// [`PlatformWindow::update_accessibility`] reaches it.
1373/// `needs_full_tree` is what makes the delivery that follows a *full*
1374/// tree rather than a geometry patch: updates are otherwise throttled to
1375/// the moves-only rate, and a reader that attaches mid-session has never
1376/// seen the tree such a patch would be applied to.
1377struct TeksiloActivationHandler {
1378 needs_full_tree: Arc<AtomicBool>,
1379 bridge: Arc<AccessibilityBridge>,
1380 wake: Arc<WindowWakeTarget>,
1381}
1382
1383/// The tree handed to a client that attached before this window ever drew.
1384///
1385/// A window node with no children — the same placeholder as before — because
1386/// there is genuinely nothing else to say yet. The accompanying redraw request
1387/// is what makes it short-lived.
1388fn empty_initial_tree() -> accesskit::TreeUpdate {
1389 let root = accesskit::Node::new(accesskit::Role::Window);
1390 let root_id = teksilo_core::accessibility::root_node_id();
1391 accesskit::TreeUpdate {
1392 nodes: vec![(root_id, root)],
1393 tree: Some(accesskit::TreeInfo::new(root_id)),
1394 tree_id: accesskit::TreeId::ROOT,
1395 focus: root_id,
1396 }
1397}
1398
1399impl accesskit::ActivationHandler for TeksiloActivationHandler {
1400 fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {
1401 self.needs_full_tree.store(true, Ordering::Relaxed);
1402 let update = self.bridge.on_activate();
1403 // Whether or not we could answer with a real tree, ask for a frame: it
1404 // is what carries the *next* update to the now-active adapter, and it
1405 // is also how the UI thread learns that a client attached.
1406 self.wake.wake_state();
1407 Some(update)
1408 }
1409}
1410
1411/// Action handler — forwards action requests to the main thread via a channel,
1412/// then wakes the loop so the channel is actually drained.
1413struct TeksiloActionHandler {
1414 tx: mpsc::Sender<ActionRequest>,
1415 wake: Arc<WindowWakeTarget>,
1416}
1417
1418impl accesskit::ActionHandler for TeksiloActionHandler {
1419 fn do_action(&mut self, request: ActionRequest) {
1420 let _ = self.tx.send(request);
1421 self.wake.wake_state();
1422 }
1423}
1424
1425/// Deactivation handler — records that the last client detached.
1426///
1427/// Unlike activation, this *is* evidence about screen readers: when no client
1428/// is attached, none of them is reading the tree either.
1429struct TeksiloDeactivationHandler {
1430 bridge: Arc<AccessibilityBridge>,
1431 wake: Arc<WindowWakeTarget>,
1432}
1433
1434impl accesskit::DeactivationHandler for TeksiloDeactivationHandler {
1435 fn deactivate_accessibility(&mut self) {
1436 self.bridge.on_deactivate();
1437 // The UI thread reads the flag once per frame, so it needs a frame.
1438 self.wake.wake_state();
1439 }
1440}
1441
1442impl Drop for PlatformWindow {
1443 /// Disconnect the wake target first: a waker another thread still holds
1444 /// must not reach a window that is going away.
1445 fn drop(&mut self) {
1446 self.wake.disconnect();
1447 }
1448}
1449
1450#[cfg(test)]
1451mod capture_tests {
1452 use super::{crop_region, crop_rgba, refresh_interval_from_millihertz};
1453 use std::time::Duration;
1454 use teksilo_canvas::{PixelRect, Rect};
1455
1456 /// A crop's edges round outwards to whole pixels and clamp to the
1457 /// surface; one that misses the surface is empty.
1458 #[test]
1459 fn a_crop_covers_every_pixel_it_touches_inside_the_surface() {
1460 assert_eq!(
1461 crop_region(Rect::new(1.5, 2.25, 3.0, 4.5), 10, 10),
1462 PixelRect::new(1, 2, 4, 5)
1463 );
1464 assert_eq!(
1465 crop_region(Rect::new(-3.0, 8.0, 20.0, 5.0), 10, 10),
1466 PixelRect::new(0, 8, 10, 2)
1467 );
1468 assert!(crop_region(Rect::new(12.0, 0.0, 4.0, 4.0), 10, 10).is_empty());
1469 assert!(crop_region(Rect::new(2.0, 2.0, 0.0, 3.0), 10, 10).is_empty());
1470 }
1471
1472 /// The crop is cut from rows of the full surface, not from its start.
1473 #[test]
1474 fn the_cropped_pixels_are_the_regions_own() {
1475 let (w, h) = (5u32, 4u32);
1476 let src: Vec<u8> = (0..w * h)
1477 .flat_map(|i| [i as u8, (i >> 8) as u8, 7, 255])
1478 .collect();
1479 let region = PixelRect::new(1, 2, 3, 2);
1480 let out = crop_rgba(&src, w, region);
1481 let firsts: Vec<u8> = out.chunks(4).map(|px| px[0]).collect();
1482 assert_eq!(firsts, vec![11, 12, 13, 16, 17, 18]);
1483 assert!(crop_rgba(&src, w, PixelRect::new(0, 0, 0, 0)).is_empty());
1484 }
1485
1486 /// One refresh of the display, its rate bounded to 20 Hz – 1 kHz.
1487 #[test]
1488 fn a_display_rate_becomes_one_refresh() {
1489 assert_eq!(
1490 refresh_interval_from_millihertz(60_000),
1491 Duration::from_nanos(16_666_666)
1492 );
1493 assert_eq!(
1494 refresh_interval_from_millihertz(144_000),
1495 Duration::from_nanos(6_944_444)
1496 );
1497 assert_eq!(
1498 refresh_interval_from_millihertz(0),
1499 Duration::from_millis(50)
1500 );
1501 assert_eq!(
1502 refresh_interval_from_millihertz(u32::MAX),
1503 Duration::from_millis(1)
1504 );
1505 }
1506}
1507
1508#[cfg(test)]
1509mod surface_configure_tests {
1510 use super::{SurfaceConfigureError, classify_configure_failure};
1511
1512 /// The defect this pins: a compositor crash reached the user as
1513 /// `Surface does not support the adapter's queue family`, and was read as
1514 /// a GPU mismatch by everyone who saw it, including the maintainer. A
1515 /// surface with no formats left for the adapter it was matched against has
1516 /// lost its display server, whatever wgpu chooses to call it.
1517 #[test]
1518 fn a_surface_with_no_formats_left_means_the_display_server_is_gone() {
1519 let err = classify_configure_failure(
1520 "Surface does not support the adapter's queue family".to_string(),
1521 false,
1522 );
1523 assert!(matches!(err, SurfaceConfigureError::DisplayLost));
1524 assert!(err.to_string().contains("display server"));
1525 }
1526
1527 /// The other half, and the reason this is not simply "any configure
1528 /// failure means the compositor left": a surface that still answers with
1529 /// formats has a real configuration problem, and its own message has to
1530 /// survive rather than be relabelled as a dead compositor.
1531 #[test]
1532 fn a_surface_that_still_has_formats_keeps_wgpus_own_message() {
1533 let err = classify_configure_failure(
1534 "Requested format Rgba8Unorm is not in the list of supported formats".to_string(),
1535 true,
1536 );
1537 assert!(matches!(err, SurfaceConfigureError::Rejected(_)));
1538 assert!(err.to_string().contains("Rgba8Unorm"));
1539 assert!(!err.to_string().contains("display server"));
1540 }
1541}
1542
1543#[cfg(test)]
1544mod accessibility_bridge_tests {
1545 use super::{AccessibilityBridge, empty_initial_tree};
1546
1547 /// A recognisable tree that is not the placeholder.
1548 fn published_tree() -> accesskit::TreeUpdate {
1549 let root_id = teksilo_core::accessibility::root_node_id();
1550 let child_id = accesskit::NodeId(4242);
1551 let mut root = accesskit::Node::new(accesskit::Role::Window);
1552 root.push_child(child_id);
1553 let mut child = accesskit::Node::new(accesskit::Role::Button);
1554 child.set_label("Save");
1555 accesskit::TreeUpdate {
1556 nodes: vec![(root_id, root), (child_id, child)],
1557 tree: Some(accesskit::TreeInfo::new(root_id)),
1558 tree_id: accesskit::TreeId::ROOT,
1559 focus: root_id,
1560 }
1561 }
1562
1563 #[test]
1564 fn a_fresh_bridge_reports_no_client() {
1565 assert!(!AccessibilityBridge::default().is_active());
1566 }
1567
1568 #[test]
1569 fn activation_before_the_first_frame_answers_with_the_placeholder() {
1570 let bridge = AccessibilityBridge::default();
1571 let update = bridge.on_activate();
1572 assert_eq!(update.nodes.len(), empty_initial_tree().nodes.len());
1573 assert_eq!(update.nodes[0].1.children().len(), 0);
1574 assert!(bridge.is_active());
1575 }
1576
1577 #[test]
1578 fn activation_after_a_frame_answers_with_the_real_tree() {
1579 // The defect this pins: an assistive technology attaching to an idle
1580 // window was shown a childless window node and nothing scheduled a
1581 // frame to replace it.
1582 let bridge = AccessibilityBridge::default();
1583 bridge.publish(&published_tree());
1584 let update = bridge.on_activate();
1585 assert_eq!(
1586 update.nodes.len(),
1587 2,
1588 "the published tree, not a placeholder"
1589 );
1590 assert_eq!(update.nodes[0].1.children().len(), 1);
1591 }
1592
1593 #[test]
1594 fn the_snapshot_is_the_latest_published_tree() {
1595 let bridge = AccessibilityBridge::default();
1596 bridge.publish(&empty_initial_tree());
1597 bridge.publish(&published_tree());
1598 assert_eq!(bridge.on_activate().nodes.len(), 2);
1599 }
1600
1601 #[test]
1602 fn publishing_while_a_client_is_attached_is_skipped() {
1603 // Not a behaviour change anyone can observe through `on_activate` —
1604 // an attached client cannot ask for an initial tree — but it is what
1605 // keeps a per-frame `TreeUpdate` clone off the frame path while a
1606 // screen reader is running.
1607 let bridge = AccessibilityBridge::default();
1608 bridge.publish(&published_tree());
1609 let _ = bridge.on_activate();
1610 bridge.publish(&empty_initial_tree());
1611 bridge.on_deactivate();
1612 assert_eq!(
1613 bridge.on_activate().nodes.len(),
1614 2,
1615 "the tree published while attached must not have replaced the snapshot"
1616 );
1617 }
1618
1619 #[test]
1620 fn deactivation_clears_the_attached_flag() {
1621 let bridge = AccessibilityBridge::default();
1622 let _ = bridge.on_activate();
1623 assert!(bridge.is_active());
1624 bridge.on_deactivate();
1625 assert!(!bridge.is_active());
1626 // And the tree it published is still there for a client that comes back.
1627 bridge.publish(&published_tree());
1628 assert_eq!(bridge.on_activate().nodes.len(), 2);
1629 assert!(bridge.is_active());
1630 }
1631}
1632
1633#[cfg(test)]
1634mod device_limits_tests {
1635 use super::*;
1636
1637 /// A Raspberry Pi 4's V3D driver in the fields that matter here: four
1638 /// colour attachments and 4096-pixel textures. This is the adapter the
1639 /// crash report came from.
1640 fn pi4_class_limits() -> wgpu::Limits {
1641 wgpu::Limits {
1642 max_texture_dimension_1d: 4096,
1643 max_texture_dimension_2d: 4096,
1644 max_texture_dimension_3d: 256,
1645 max_color_attachments: 4,
1646 ..wgpu::Limits::downlevel_defaults()
1647 }
1648 }
1649
1650 #[test]
1651 fn the_default_limits_are_refused_by_gles_class_hardware() {
1652 // The bug, stated as a test: this is what the window used to ask for,
1653 // and `check_limits` is the same comparison wgpu makes inside
1654 // `request_device`. If this ever starts passing, wgpu changed its
1655 // defaults and the fallback below is what keeps us honest.
1656 assert!(
1657 !wgpu::Limits::default().check_limits(&pi4_class_limits()),
1658 "the wgpu default limits are supposed to over-ask for a Pi-4 class \
1659 adapter; that refusal is the crash this module exists to prevent"
1660 );
1661 }
1662
1663 #[test]
1664 fn the_window_ask_is_satisfiable_on_gles_class_hardware() {
1665 let adapter = pi4_class_limits();
1666 assert!(
1667 window_device_limits(adapter.clone()).check_limits(&adapter),
1668 "a Pi-4 class adapter must be able to grant what a window asks for"
1669 );
1670 }
1671
1672 #[test]
1673 fn the_window_never_asks_past_the_downlevel_floor() {
1674 // The regression pin: whatever the adapter offers, every limit that is
1675 // not a texture dimension stays at the GLES-3.1 floor. Re-introducing
1676 // `Limits::default()` fails here on a developer's desktop rather than
1677 // only on a reviewer's Raspberry Pi.
1678 let generous = wgpu::Limits::default();
1679 let asked = window_device_limits(generous.clone());
1680 let floor = wgpu::Limits::downlevel_defaults();
1681
1682 assert_eq!(asked.max_color_attachments, floor.max_color_attachments);
1683 assert_eq!(
1684 asked.max_uniform_buffer_binding_size,
1685 floor.max_uniform_buffer_binding_size
1686 );
1687 assert_eq!(
1688 asked.max_inter_stage_shader_variables,
1689 floor.max_inter_stage_shader_variables
1690 );
1691 assert_eq!(
1692 asked.max_storage_buffers_per_shader_stage,
1693 floor.max_storage_buffers_per_shader_stage
1694 );
1695 assert_ne!(
1696 asked, generous,
1697 "asking for the full default set is exactly the regression"
1698 );
1699 }
1700
1701 #[test]
1702 fn texture_dimensions_follow_the_adapter() {
1703 // `downlevel_defaults` caps 2D textures at 2048 and the path atlas
1704 // grows to 4096, so the resolution limits, and only those, are lifted
1705 // to whatever the adapter really offers.
1706 const PATH_ATLAS_MAX: u32 = 4096;
1707
1708 for adapter in [pi4_class_limits(), wgpu::Limits::default()] {
1709 let asked = window_device_limits(adapter.clone());
1710 assert_eq!(
1711 asked.max_texture_dimension_1d,
1712 adapter.max_texture_dimension_1d
1713 );
1714 assert_eq!(
1715 asked.max_texture_dimension_2d,
1716 adapter.max_texture_dimension_2d
1717 );
1718 assert_eq!(
1719 asked.max_texture_dimension_3d,
1720 adapter.max_texture_dimension_3d
1721 );
1722 assert!(
1723 asked.max_texture_dimension_2d >= PATH_ATLAS_MAX,
1724 "the path atlas grows to {PATH_ATLAS_MAX}; a device that cannot \
1725 hold it would fail on a path-heavy frame instead of at startup"
1726 );
1727 }
1728 }
1729
1730 #[test]
1731 fn the_floor_still_covers_what_the_renderer_binds() {
1732 // What the renderer actually needs, so that lowering the ask further
1733 // fails here rather than in a frame. 128 animation slots of 64 bytes
1734 // is the largest uniform binding; every render pass has exactly one
1735 // colour attachment.
1736 const ANIM_UNIFORM_BYTES: u64 = 128 * 64;
1737 let asked = window_device_limits(pi4_class_limits());
1738
1739 assert!(asked.max_color_attachments >= 1);
1740 assert!(asked.max_uniform_buffer_binding_size >= ANIM_UNIFORM_BYTES);
1741 }
1742}
1743
1744#[cfg(all(test, not(teksilo_loom)))]
1745mod accessibility_wake_tests {
1746 use std::sync::atomic::AtomicUsize;
1747
1748 use accesskit::{ActionHandler, ActivationHandler, DeactivationHandler};
1749
1750 use super::*;
1751
1752 struct NoWindow;
1753 impl RequestRedraw for NoWindow {
1754 fn request_redraw(&self) {
1755 panic!("an accessibility handler asked for a redraw instead of posting");
1756 }
1757 }
1758
1759 fn request() -> ActionRequest {
1760 ActionRequest {
1761 action: accesskit::Action::Click,
1762 target_tree: accesskit::TreeId::ROOT,
1763 target_node: accesskit::NodeId(1),
1764 data: None,
1765 }
1766 }
1767
1768 /// What a handler leaves must reach a window that draws nothing, so all
1769 /// three wake the loop through the state route, never a redraw request;
1770 /// after the window's waker is disconnected they still enqueue, and wake
1771 /// nothing.
1772 #[test]
1773 fn accessibility_handlers_wake_through_the_state_route() {
1774 let wake = WindowWakeTarget::new(Arc::new(NoWindow));
1775 let posted = Arc::new(AtomicUsize::new(0));
1776 {
1777 let posted = posted.clone();
1778 wake.set_state_route(Arc::new(move || {
1779 posted.fetch_add(1, Ordering::SeqCst);
1780 }));
1781 }
1782 let bridge = Arc::new(AccessibilityBridge::default());
1783 let (tx, rx) = mpsc::channel();
1784 let mut action = TeksiloActionHandler {
1785 tx,
1786 wake: wake.clone(),
1787 };
1788 let mut activation = TeksiloActivationHandler {
1789 needs_full_tree: Arc::new(AtomicBool::new(false)),
1790 bridge: bridge.clone(),
1791 wake: wake.clone(),
1792 };
1793 let mut deactivation = TeksiloDeactivationHandler {
1794 bridge,
1795 wake: wake.clone(),
1796 };
1797
1798 action.do_action(request());
1799 assert!(
1800 rx.try_recv().is_ok(),
1801 "the request is queued for the UI thread"
1802 );
1803 assert_eq!(posted.load(Ordering::SeqCst), 1);
1804 assert!(wake.take_posted(WakeKind::Layout));
1805 let _ = activation.request_initial_tree();
1806 assert_eq!(posted.load(Ordering::SeqCst), 2);
1807 assert!(wake.take_posted(WakeKind::Layout));
1808 deactivation.deactivate_accessibility();
1809 assert_eq!(posted.load(Ordering::SeqCst), 3);
1810
1811 wake.disconnect();
1812 assert!(wake.take_posted(WakeKind::Layout));
1813 action.do_action(request());
1814 assert!(rx.try_recv().is_ok(), "still queued after disconnect");
1815 assert_eq!(posted.load(Ordering::SeqCst), 3, "but nothing is woken");
1816 }
1817}
1818
1819#[cfg(target_os = "macos")]
1820mod macos_occlusion {
1821 use objc2::rc::Retained;
1822 use objc2_app_kit::{NSView, NSWindowOcclusionState};
1823 use raw_window_handle::{HasWindowHandle, RawWindowHandle};
1824
1825 /// `occlusionState` of the `NSWindow` hosting `window`'s view, lacking
1826 /// *Visible*; `None` when the window has no AppKit view or no window yet.
1827 /// On the main thread, as every caller in teksilo-app is.
1828 pub(super) fn occluded(window: &winit::window::Window) -> Option<bool> {
1829 let handle = window.window_handle().ok()?;
1830 let RawWindowHandle::AppKit(raw) = handle.as_raw() else {
1831 return None;
1832 };
1833 // Re-retain the NSView winit hands us, as the title-bar host, the
1834 // drag destination and the safe-area read do.
1835 let view: Retained<NSView> = unsafe { Retained::retain(raw.ns_view.as_ptr().cast()) }?;
1836 let ns_window = view.window()?;
1837 Some(
1838 !ns_window
1839 .occlusionState()
1840 .contains(NSWindowOcclusionState::Visible),
1841 )
1842 }
1843}