truce-iced 2.0.0

Iced GUI backend for truce plugins
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Surface pump for the iced editor: owns the wgpu surface and every
//! swapchain call, on a dedicated thread on Windows and inline
//! elsewhere.
//!
//! Per-wgpu-version copy of `truce_gpu::pump` - iced pins its own wgpu
//! major through `iced_wgpu`, so the surface/device types are distinct
//! from the rest of truce and the pump can't be shared (same situation
//! as `crate::platform::create_wgpu_surface`). Keep the two in sync.
//!
//! Rationale (see `truce_gpu::pump` for the full story): on Windows
//! the editor frame loop runs on the host's GUI thread, and any wgpu
//! call that enters the graphics driver - device creation, swapchain
//! configure, acquire, present - can park that thread in the kernel
//! forever on a stalled driver, freezing the DAW. The threaded pump
//! moves all of those to its own thread and pre-acquires frames; the
//! GUI thread only encodes + submits into an already-acquired texture.

#[cfg(target_os = "windows")]
use std::sync::Condvar;
use std::sync::atomic::AtomicBool;
#[cfg(target_os = "windows")]
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};

use iced_wgpu::wgpu;

/// What the init closure returns: the GUI-side product (device
/// handles, ...) plus the device + configuration the pump needs for
/// `surface.configure`.
pub(crate) type PumpInit<T> = (T, wgpu::Device, wgpu::SurfaceConfiguration);

/// GPU init, run once the instance / adapter / surface exist (on the
/// pump thread on Windows, inline elsewhere). Returns `None` on
/// failure (editor stays blank, host survives). Must NOT configure
/// the surface - the pump does that with the returned configuration.
pub(crate) type PumpInitFn<T> = Box<
    dyn FnOnce(&wgpu::Instance, &wgpu::Adapter, &wgpu::Surface<'static>) -> Option<PumpInit<T>>
        + Send,
>;

#[cfg(target_os = "windows")]
const STATE_INIT: u8 = 0;
#[cfg(target_os = "windows")]
const STATE_READY: u8 = 1;
#[cfg(target_os = "windows")]
const STATE_FAILED: u8 = 2;

/// Latest-wins mailbox between the GUI thread and the pump thread.
// The bools are independent protocol flags (want / taken / shutdown /
// exited), not a state machine in disguise; an enum would obscure
// which combinations are legal.
#[allow(clippy::struct_excessive_bools)]
#[cfg(target_os = "windows")]
#[derive(Default)]
struct Slot {
    resize: Option<(u32, u32)>,
    held: Option<wgpu::SurfaceTexture>,
    want_frame: bool,
    present: Option<wgpu::SurfaceTexture>,
    /// A frame is out with the GUI thread (taken, not yet presented
    /// or discarded). wgpu allows only ONE outstanding acquired
    /// texture per surface, so the pump must not acquire while set.
    taken: bool,
    shutdown: bool,
    exited: bool,
}

#[cfg(target_os = "windows")]
struct Shared {
    slot: Mutex<Slot>,
    cv: Condvar,
    state: AtomicU8,
    last_acquire_nanos: AtomicU64,
}

#[cfg(target_os = "windows")]
fn lock(slot: &Mutex<Slot>) -> std::sync::MutexGuard<'_, Slot> {
    slot.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Synchronous surface owner for the platforms where swapchain calls
/// stay on the calling thread.
#[cfg(not(target_os = "windows"))]
struct InlineState {
    surface: wgpu::Surface<'static>,
    device: wgpu::Device,
    config: wgpu::SurfaceConfiguration,
    last_acquire: std::time::Duration,
}

#[cfg(not(target_os = "windows"))]
fn lock_inline(state: &Mutex<InlineState>) -> std::sync::MutexGuard<'_, InlineState> {
    state.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Cheap cloneable handle for per-frame pump operations.
#[derive(Clone)]
pub(crate) struct PumpClient {
    #[cfg(target_os = "windows")]
    shared: Arc<Shared>,
    #[cfg(not(target_os = "windows"))]
    state: Arc<Mutex<InlineState>>,
}

impl PumpClient {
    /// Reconfigure the surface (physical pixels). Queued latest-wins
    /// on Windows; inline elsewhere.
    pub(crate) fn resize(&self, phys_w: u32, phys_h: u32) {
        #[cfg(target_os = "windows")]
        {
            let mut slot = lock(&self.shared.slot);
            slot.resize = Some((phys_w, phys_h));
            drop(slot);
            self.shared.cv.notify_all();
        }
        #[cfg(not(target_os = "windows"))]
        {
            let mut state = lock_inline(&self.state);
            state.config.width = phys_w.max(1);
            state.config.height = phys_h.max(1);
            let InlineState {
                surface,
                device,
                config,
                ..
            } = &mut *state;
            surface.configure(device, config);
        }
    }

    /// Get a frame to paint into; `None` means skip this paint and
    /// retry on a later tick. Callers should verify the texture's size
    /// still matches their target and discard (drop) it on a mismatch.
    pub(crate) fn try_take_frame(&self) -> Option<wgpu::SurfaceTexture> {
        #[cfg(target_os = "windows")]
        {
            let mut slot = lock(&self.shared.slot);
            slot.want_frame = true;
            let frame = slot.held.take();
            if frame.is_some() {
                slot.taken = true;
            }
            drop(slot);
            self.shared.cv.notify_all();
            frame
        }
        #[cfg(not(target_os = "windows"))]
        {
            let mut state = lock_inline(&self.state);
            let acquire_start = std::time::Instant::now();
            let mut acquired = None;
            // `Outdated` / `Lost` persist until a reconfigure (even
            // same-size clears the flag); `Timeout` is transient.
            for _ in 0..2 {
                match state.surface.get_current_texture() {
                    Ok(frame) => {
                        acquired = Some(frame);
                        break;
                    }
                    Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                        let InlineState {
                            surface,
                            device,
                            config,
                            ..
                        } = &mut *state;
                        surface.configure(device, config);
                    }
                    Err(e) => {
                        log::warn!("iced surface acquire error: {e}");
                        break;
                    }
                }
            }
            state.last_acquire = acquire_start.elapsed();
            acquired
        }
    }

    /// Present a painted frame (handed to the pump thread on Windows,
    /// presented inline elsewhere).
    // `self` is unused inline-only; the signature is the cross-
    // platform pump API.
    #[allow(clippy::unused_self)]
    pub(crate) fn present(&self, frame: wgpu::SurfaceTexture) {
        #[cfg(target_os = "windows")]
        {
            let mut slot = lock(&self.shared.slot);
            slot.present = Some(frame);
            slot.taken = false;
            drop(slot);
            self.shared.cv.notify_all();
        }
        #[cfg(not(target_os = "windows"))]
        {
            frame.present();
        }
    }

    /// Release a taken frame that won't be painted (stale size after
    /// a raced resize), so the pump may acquire again - wgpu allows
    /// only one outstanding acquired texture per surface. On Windows
    /// the frame is presented unrendered rather than dropped: DX12
    /// replenishes the frame-latency waitable only on present, and a
    /// dropped acquire burns a slot until every acquire blocks wgpu's
    /// full 1 s timeout. The recycled old-frame content matches what
    /// the compositor is already showing mid-churn.
    // `self` is unused inline-only; the signature is the cross-
    // platform pump API.
    #[allow(clippy::unused_self)]
    pub(crate) fn discard(&self, frame: wgpu::SurfaceTexture) {
        #[cfg(target_os = "windows")]
        self.present(frame);
        #[cfg(not(target_os = "windows"))]
        drop(frame);
    }

    /// The most recent swapchain-acquire wait, for compositor pacing.
    pub(crate) fn last_acquire_wait(&self) -> std::time::Duration {
        #[cfg(target_os = "windows")]
        {
            std::time::Duration::from_nanos(self.shared.last_acquire_nanos.load(Ordering::Relaxed))
        }
        #[cfg(not(target_os = "windows"))]
        {
            lock_inline(&self.state).last_acquire
        }
    }
}

/// Owning handle for the pump. On Windows, dropping it shuts the
/// thread down (bounded join, then detach).
pub(crate) struct SurfacePump<T: Send + 'static> {
    client: PumpClient,
    init: InitDelivery<T>,
    #[cfg(target_os = "windows")]
    join: Option<std::thread::JoinHandle<()>>,
}

enum InitDelivery<T> {
    #[cfg_attr(target_os = "windows", allow(dead_code))]
    Now(Option<T>),
    #[cfg(target_os = "windows")]
    Chan(std::sync::mpsc::Receiver<T>),
}

impl<T: Send + 'static> SurfacePump<T> {
    /// Build the pump for a baseview window. On Windows this spawns
    /// the pump thread and returns immediately (poll
    /// [`Self::take_init`]); elsewhere init runs synchronously and
    /// `take_init` succeeds on the first call.
    ///
    /// # Safety
    /// The window must remain valid while the pump lives (the editor
    /// drops the pump before closing its child window).
    pub(crate) unsafe fn spawn(
        window: &baseview::Window,
        device_lost: &Arc<AtomicBool>,
        init: PumpInitFn<T>,
    ) -> Option<Self> {
        #[cfg(target_os = "windows")]
        {
            use raw_window_handle::HasRawWindowHandle;
            let raw_window_handle::RawWindowHandle::Win32(handle) = window.raw_window_handle()
            else {
                return None;
            };
            let hwnd = handle.hwnd as isize;
            if hwnd == 0 {
                return None;
            }
            Self::spawn_threaded(hwnd, device_lost.clone(), init)
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = device_lost;
            let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
                backends: crate::runtime::editor_backends(),
                ..Default::default()
            });
            let surface = unsafe { crate::platform::create_wgpu_surface(&instance, window) }?;
            let adapter =
                pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
                    power_preference: wgpu::PowerPreference::HighPerformance,
                    compatible_surface: Some(&surface),
                    force_fallback_adapter: false,
                }))
                .ok()?;
            let (product, device, config) = init(&instance, &adapter, &surface)?;
            surface.configure(&device, &config);
            Some(Self {
                client: PumpClient {
                    state: Arc::new(Mutex::new(InlineState {
                        surface,
                        device,
                        config,
                        last_acquire: std::time::Duration::ZERO,
                    })),
                },
                init: InitDelivery::Now(Some(product)),
            })
        }
    }

    #[cfg(target_os = "windows")]
    fn spawn_threaded(
        hwnd: isize,
        device_lost: Arc<AtomicBool>,
        init: PumpInitFn<T>,
    ) -> Option<Self> {
        let shared = Arc::new(Shared {
            slot: Mutex::new(Slot::default()),
            cv: Condvar::new(),
            state: AtomicU8::new(STATE_INIT),
            last_acquire_nanos: AtomicU64::new(0),
        });
        let (init_tx, init_rx) = std::sync::mpsc::channel();
        let thread_shared = shared.clone();
        let spawned = std::thread::Builder::new()
            .name("truce-iced-pump".into())
            .spawn(move || run(&thread_shared, hwnd, &device_lost, init, &init_tx));
        match spawned {
            Ok(join) => Some(Self {
                client: PumpClient { shared },
                init: InitDelivery::Chan(init_rx),
                join: Some(join),
            }),
            Err(e) => {
                log::error!("iced surface pump: failed to spawn: {e}");
                None
            }
        }
    }

    /// Poll for the init closure's product (non-blocking). Returns it
    /// exactly once.
    pub(crate) fn take_init(&mut self) -> Option<T> {
        match &mut self.init {
            InitDelivery::Now(product) => product.take(),
            #[cfg(target_os = "windows")]
            InitDelivery::Chan(rx) => rx.try_recv().ok(),
        }
    }

    pub(crate) fn client(&self) -> PumpClient {
        self.client.clone()
    }
}

#[cfg(target_os = "windows")]
impl<T: Send + 'static> Drop for SurfacePump<T> {
    fn drop(&mut self) {
        let mut slot = lock(&self.client.shared.slot);
        slot.shutdown = true;
        self.client.shared.cv.notify_all();
        // Bounded wait; a thread wedged inside the driver can't notice
        // the flag, so detach instead of hanging the GUI thread.
        let (slot, timeout) = self
            .client
            .shared
            .cv
            .wait_timeout_while(slot, std::time::Duration::from_secs(1), |s| !s.exited)
            .unwrap_or_else(PoisonError::into_inner);
        drop(slot);
        if timeout.timed_out() {
            log::warn!("iced surface pump did not exit within 1s (driver stall?); detaching");
            drop(self.join.take());
        } else if let Some(join) = self.join.take() {
            let _ = join.join();
        }
    }
}

/// Create a wgpu surface for a raw Win32 HWND (`Send`-able input, so
/// the pump thread builds its own surface).
///
/// # Safety
/// `hwnd` must be a valid window handle that outlives the surface.
#[cfg(target_os = "windows")]
unsafe fn surface_from_hwnd(
    instance: &wgpu::Instance,
    hwnd: isize,
) -> Option<wgpu::Surface<'static>> {
    let mut win32 = wgpu::rwh::Win32WindowHandle::new(std::num::NonZeroIsize::new(hwnd)?);
    win32.hinstance = crate::platform::current_module_hinstance();
    let target = wgpu::SurfaceTargetUnsafe::RawHandle {
        raw_display_handle: wgpu::rwh::RawDisplayHandle::Windows(
            wgpu::rwh::WindowsDisplayHandle::new(),
        ),
        raw_window_handle: wgpu::rwh::RawWindowHandle::Win32(win32),
    };
    unsafe { instance.create_surface_unsafe(target) }.ok()
}

/// Pump thread body: init, then serve resize / acquire / present
/// until shutdown.
#[cfg(target_os = "windows")]
fn run<T: Send>(
    shared: &Shared,
    hwnd: isize,
    device_lost: &Arc<AtomicBool>,
    init: PumpInitFn<T>,
    init_tx: &std::sync::mpsc::Sender<T>,
) {
    let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: crate::runtime::editor_backends(),
            ..Default::default()
        });
        // SAFETY: the hwnd outlives the pump - see `SurfacePump::spawn`.
        let surface = unsafe { surface_from_hwnd(&instance, hwnd) }?;
        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: wgpu::PowerPreference::HighPerformance,
            compatible_surface: Some(&surface),
            force_fallback_adapter: false,
        }))
        .ok()?;
        let (product, device, config) = init(&instance, &adapter, &surface)?;
        surface.configure(&device, &config);
        Some((product, device, config, surface))
    }))
    .ok()
    .flatten();
    let Some((product, device, mut config, surface)) = built else {
        shared.state.store(STATE_FAILED, Ordering::Release);
        log::error!("iced surface pump: gpu init failed; editor stays blank");
        mark_exited(shared);
        return;
    };
    let _ = init_tx.send(product);
    shared.state.store(STATE_READY, Ordering::Release);

    'work: loop {
        let (resize, present, need_acquire) = {
            let mut slot = lock(&shared.slot);
            loop {
                if slot.shutdown {
                    break 'work;
                }
                let need_acquire = slot.want_frame && slot.held.is_none() && !slot.taken;
                // A resize can't be applied while a frame is out with
                // the GUI thread: `surface.configure` panics if any
                // acquired texture is still alive. The GUI's present /
                // discard clears `taken` and notifies.
                let can_resize = slot.resize.is_some() && !slot.taken;
                if can_resize || slot.present.is_some() || need_acquire {
                    break;
                }
                slot = shared.cv.wait(slot).unwrap_or_else(PoisonError::into_inner);
            }
            let need_acquire = slot.want_frame && slot.held.is_none() && !slot.taken;
            let resize = if slot.taken { None } else { slot.resize.take() };
            (resize, slot.present.take(), need_acquire)
        };
        // Everything below can block inside the driver - that is the
        // point of this thread.
        let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            if let Some(frame) = present {
                frame.present();
            }
            if let Some((w, h)) = resize {
                // A frame acquired under the old configuration can't
                // be painted meaningfully - but it must be PRESENTED,
                // not dropped: DX12 replenishes the swapchain's
                // frame-latency waitable only on present, so a dropped
                // acquire burns a latency slot and once starved every
                // subsequent acquire blocks wgpu's full 1 s timeout
                // (measured; it was the multi-second post-resize
                // stall). Its recycled old-frame content matches the
                // stretched frame the compositor is showing anyway.
                if let Some(stale) = lock(&shared.slot).held.take() {
                    stale.present();
                }
                config.width = w.max(1);
                config.height = h.max(1);
                surface.configure(&device, &config);
            }
            // A drag queues resizes faster than configure + acquire
            // can run; if another one is already waiting, coalesce it
            // first - a frame acquired now would only be discarded.
            if need_acquire && lock(&shared.slot).resize.is_none() {
                let acquire_start = std::time::Instant::now();
                let mut acquired = None;
                for _ in 0..2 {
                    match surface.get_current_texture() {
                        Ok(frame) => {
                            acquired = Some(frame);
                            break;
                        }
                        Err(wgpu::SurfaceError::Outdated | wgpu::SurfaceError::Lost) => {
                            surface.configure(&device, &config);
                        }
                        Err(e) => {
                            log::warn!("iced surface pump acquire error: {e}");
                            break;
                        }
                    }
                }
                let nanos = u64::try_from(acquire_start.elapsed().as_nanos()).unwrap_or(u64::MAX);
                shared.last_acquire_nanos.store(nanos, Ordering::Relaxed);
                if let Some(frame) = acquired {
                    let mut slot = lock(&shared.slot);
                    // A resize that raced in invalidates this frame;
                    // present it (see the resize branch - dropping
                    // burns a frame-latency slot) and let the next
                    // loop pass reconfigure + reacquire.
                    if slot.resize.is_none() {
                        slot.held = Some(frame);
                    } else {
                        drop(slot);
                        frame.present();
                    }
                }
            }
        }));
        if ok.is_err() {
            device_lost.store(true, Ordering::Release);
            shared.state.store(STATE_FAILED, Ordering::Release);
            log::error!("iced surface pump panicked; flagging device loss for rebuild");
            break;
        }
    }
    mark_exited(shared);
}

#[cfg(target_os = "windows")]
fn mark_exited(shared: &Shared) {
    let mut slot = lock(&shared.slot);
    // Frames can't outlive the surface; drop any still queued. The
    // drop itself can panic (wgpu discards the texture against a
    // surface whose configure already failed); swallow it so teardown
    // always completes.
    let held = slot.held.take();
    let present = slot.present.take();
    slot.exited = true;
    drop(slot);
    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
        drop(held);
        drop(present);
    }));
    shared.cv.notify_all();
}