Skip to main content

truce_gui/
platform.rs

1//! Platform window bridging for baseview.
2//!
3//! Bridges truce's `RawWindowHandle` to baseview's `HasRawWindowHandle`
4//! (raw-window-handle 0.5), and provides scale factor querying and
5//! wgpu surface creation.
6
7// `HasRawDisplayHandle` / `RwhRawDisplayHandle` are only touched on
8// the Linux (X11) arm of `HasRawWindowHandle for ParentWindow`;
9// silence the macOS/Windows dead-import warning.
10#[allow(unused_imports)]
11use raw_window_handle::{
12    HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle as RwhRawDisplayHandle,
13    RawWindowHandle as RwhRawWindowHandle,
14};
15use truce_core::editor::RawWindowHandle;
16
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20/// Newtype bridging truce's `RawWindowHandle` to baseview's
21/// `HasRawWindowHandle` (raw-window-handle 0.5).
22pub struct ParentWindow(pub RawWindowHandle);
23
24unsafe impl HasRawWindowHandle for ParentWindow {
25    fn raw_window_handle(&self) -> RwhRawWindowHandle {
26        match self.0 {
27            RawWindowHandle::AppKit(ptr) => {
28                let mut handle = raw_window_handle::AppKitWindowHandle::empty();
29                handle.ns_view = ptr;
30                RwhRawWindowHandle::AppKit(handle)
31            }
32            RawWindowHandle::UiKit(ptr) => {
33                // baseview doesn't host on iOS - the iOS editor
34                // path attaches a UIView directly without going
35                // through this bridge. We surface the handle for
36                // completeness (and so future iOS-aware backends
37                // can read it) but in practice no caller on iOS
38                // reaches this arm.
39                let mut handle = raw_window_handle::UiKitWindowHandle::empty();
40                handle.ui_view = ptr;
41                RwhRawWindowHandle::UiKit(handle)
42            }
43            RawWindowHandle::Win32(ptr) => {
44                let mut handle = raw_window_handle::Win32WindowHandle::empty();
45                handle.hwnd = ptr;
46                RwhRawWindowHandle::Win32(handle)
47            }
48            RawWindowHandle::X11(window_id) => {
49                let mut handle = raw_window_handle::XlibWindowHandle::empty();
50                // rwh 0.5 field type is c_ulong: u64 on Linux/macOS, u32 on Windows.
51                // The Windows narrowing is the lossy edge - `XID` is 32-bit there.
52                #[allow(clippy::cast_possible_truncation)]
53                {
54                    handle.window = window_id as _;
55                }
56                RwhRawWindowHandle::Xlib(handle)
57            }
58        }
59    }
60}
61
62/// Query the backing scale factor from the parent `NSView`'s window.
63#[cfg(target_os = "macos")]
64#[must_use]
65pub fn query_backing_scale(parent: &RawWindowHandle) -> f64 {
66    use objc::{msg_send, sel, sel_impl};
67
68    let ns_view_ptr = match parent {
69        RawWindowHandle::AppKit(ptr) => *ptr,
70        _ => return 1.0,
71    };
72
73    if ns_view_ptr.is_null() {
74        return 1.0;
75    }
76
77    unsafe {
78        let ns_view = ns_view_ptr.cast::<objc::runtime::Object>();
79        let window: *mut objc::runtime::Object = msg_send![ns_view, window];
80        let scale: f64 = if window.is_null() {
81            let screen: *mut objc::runtime::Object = msg_send![objc::class!(NSScreen), mainScreen];
82            if screen.is_null() {
83                2.0
84            } else {
85                msg_send![screen, backingScaleFactor]
86            }
87        } else {
88            msg_send![window, backingScaleFactor]
89        };
90        if scale < 1.0 { 1.0 } else { scale }
91    }
92}
93
94#[cfg(target_os = "windows")]
95#[must_use]
96pub fn query_backing_scale(parent: &RawWindowHandle) -> f64 {
97    let hwnd = match parent {
98        RawWindowHandle::Win32(ptr) => *ptr,
99        _ => return 1.0,
100    };
101    win32_dpi_scale(hwnd)
102}
103
104#[cfg(target_os = "linux")]
105#[must_use]
106pub fn query_backing_scale(_parent: &RawWindowHandle) -> f64 {
107    main_screen_scale()
108}
109
110#[cfg(target_os = "ios")]
111#[must_use]
112pub fn query_backing_scale(parent: &RawWindowHandle) -> f64 {
113    use objc2::msg_send;
114    use objc2::runtime::AnyObject;
115
116    let ui_view_ptr = match parent {
117        RawWindowHandle::UiKit(ptr) => *ptr,
118        _ => return 1.0,
119    };
120    if ui_view_ptr.is_null() {
121        return main_screen_scale();
122    }
123    // SAFETY: UIView is a UIKit class; `contentScaleFactor` is a
124    // public Objective-C property returning CGFloat (= f64 on
125    // arm64). Called on the main thread per UIKit's threading
126    // rule, which is also where AUv3 view controllers live.
127    unsafe {
128        let ui_view: *mut AnyObject = ui_view_ptr.cast();
129        let scale: f64 = msg_send![ui_view, contentScaleFactor];
130        if scale > 0.0 { scale } else { 1.0 }
131    }
132}
133
134#[cfg(target_os = "ios")]
135#[must_use]
136pub fn main_screen_scale() -> f64 {
137    use objc2::msg_send;
138    use objc2::runtime::{AnyClass, AnyObject};
139    // SAFETY: `+[UIScreen mainScreen]` is documented to return the
140    // process's primary screen on the main thread.
141    unsafe {
142        let Some(cls) = AnyClass::get(c"UIScreen") else {
143            return 1.0;
144        };
145        let screen: *mut AnyObject = msg_send![cls, mainScreen];
146        if screen.is_null() {
147            return 1.0;
148        }
149        let scale: f64 = msg_send![screen, scale];
150        if scale > 0.0 { scale } else { 1.0 }
151    }
152}
153
154/// Query the main screen's backing scale factor (no parent window needed).
155#[cfg(target_os = "macos")]
156#[must_use]
157pub fn main_screen_scale() -> f64 {
158    use objc::{msg_send, sel, sel_impl};
159    unsafe {
160        let screen: *mut objc::runtime::Object = msg_send![objc::class!(NSScreen), mainScreen];
161        if screen.is_null() {
162            1.0
163        } else {
164            let scale: f64 = msg_send![screen, backingScaleFactor];
165            if scale < 1.0 { 1.0 } else { scale }
166        }
167    }
168}
169
170#[cfg(target_os = "windows")]
171#[must_use]
172pub fn main_screen_scale() -> f64 {
173    win32_dpi_scale(std::ptr::null_mut())
174}
175
176// `reanchor_to_superview_top` and `reanchor_all_children_to_top`
177// live in the `truce-gui-utils` crate so backends that don't pull
178// `truce-gui` (vizia) can still get at them. Re-exported here for
179// existing `truce_gui::platform::...` call sites.
180pub use truce_gui_utils::{
181    reanchor_all_children_to_top, reanchor_to_superview_top, should_skip_frame,
182};
183
184/// Shared, mutable editor scale factor.
185///
186/// Single source of truth for the live content-scale of an open plugin
187/// window. Each GUI backend (egui / iced / slint) constructs one in
188/// `Editor::open`, stores it on the editor for `set_scale_factor` to
189/// write through, and hands a clone to its baseview `WindowHandler` so
190/// the render thread can pick up changes between frames.
191///
192/// Two writers, one reader-per-frame:
193/// - `Editor::set_scale_factor` (host → editor, e.g. CLAP `set_scale`,
194///   VST3 Windows `IPlugViewContentScaleSupport`).
195/// - `WindowEvent::Resized` (baseview → handler, fired when the OS
196///   reports a new content scale, e.g. dragging the window across
197///   monitors with different DPIs).
198///
199/// Most-recent-write wins. The handler tracks a `last_applied_scale`
200/// alongside its `EditorScale` clone and, when it observes a divergence
201/// at frame start, recomputes physical sizes and reconfigures its
202/// surface / renderer.
203#[derive(Clone)]
204pub struct EditorScale {
205    inner: Arc<AtomicU64>,
206}
207
208impl EditorScale {
209    /// Construct with an initial scale. Non-finite or non-positive
210    /// values clamp to 1.0 so callers never have to defend against
211    /// `0.0 * size` collapsing the surface.
212    #[must_use]
213    pub fn new(initial: f64) -> Self {
214        let v = if initial.is_finite() && initial > 0.0 {
215            initial
216        } else {
217            1.0
218        };
219        Self {
220            inner: Arc::new(AtomicU64::new(v.to_bits())),
221        }
222    }
223
224    /// Read the current scale.
225    #[must_use]
226    pub fn get(&self) -> f64 {
227        f64::from_bits(self.inner.load(Ordering::Relaxed))
228    }
229
230    /// Read the current scale, narrowed to `f32` for renderer / DSP
231    /// use. Display scales never exceed 4.0 in practice, so the f64
232    /// → f32 narrowing is invisible.
233    #[allow(clippy::cast_possible_truncation)]
234    #[must_use]
235    pub fn get_f32(&self) -> f32 {
236        self.get() as f32
237    }
238
239    /// Update the current scale. Non-finite or non-positive values are
240    /// silently dropped - callers are forwarding numbers from hosts /
241    /// `info.scale()` where a bad value is a host bug, not something
242    /// to propagate into the surface config.
243    pub fn set(&self, scale: f64) {
244        if scale.is_finite() && scale > 0.0 {
245            self.inner.store(scale.to_bits(), Ordering::Relaxed);
246        } else {
247            // Surface the upstream bug at least in debug builds so a
248            // host that's emitting bad scales doesn't get silently
249            // ignored. Production builds drop quietly to keep the
250            // editor running.
251            log::warn!(
252                "EditorScale::set ignored a bad value ({scale}); \
253                 expected finite, positive f64",
254            );
255        }
256    }
257
258    /// Pick up a host-driven scale change since the last frame.
259    ///
260    /// Reads the current scale (narrowed to `f32`) and compares it
261    /// bit-identically against `last`. When the value moved, updates
262    /// `last` and returns `Some(cur)`; otherwise returns `None`.
263    ///
264    /// Used by every editor backend's per-frame loop to gate surface /
265    /// renderer reconfiguration on actual host scale events. Bit-equality
266    /// is the correct semantics - the cell is written verbatim from
267    /// host callbacks, never through accumulating arithmetic, so an
268    /// epsilon-based check would either thrash on noise (there is
269    /// none) or miss a legitimate `1.0 → 1.0001` host signal.
270    #[allow(clippy::cast_possible_truncation, clippy::float_cmp)]
271    pub fn take_change(&self, last: &mut f32) -> Option<f32> {
272        let cur = self.get() as f32;
273        if cur == *last {
274            None
275        } else {
276            *last = cur;
277            Some(cur)
278        }
279    }
280}
281
282/// Convert a logical extent (in points) to physical pixels.
283///
284/// Standardised rounding policy across every truce GUI backend:
285/// round to nearest, then clamp the result to `1` so a degenerate
286/// `0 × scale` doesn't collapse a wgpu surface (`width: 0` is a
287/// validation error). The `logical.max(1)` guard handles the
288/// converse - a zero-logical caller can't multiply through to `0`
289/// before the round.
290///
291/// Canonical definition lives in `truce-gui-types` so `truce-gpu`'s
292/// `WgpuBackend` can call it without a `truce-gui` dep (cycle); the
293/// re-export below preserves the historical `truce_gui::to_physical_px`
294/// path.
295pub use truce_gui_types::to_physical_px;
296
297/// Cached display scale factor on Linux, stored as f64 bits. Zero means unset.
298///
299/// Linux has no safe synchronous DPI query from plugin code - the authoritative
300/// value is read by baseview internally (from `Xft.dpi` with a screen-geometry
301/// fallback) and delivered via `WindowEvent::Resized::info.scale()` once the
302/// window is live. We cache the first value an editor sees there so that later
303/// pre-window `main_screen_scale()` calls (e.g. the next editor's `::new`)
304/// return something useful instead of 1.0.
305#[cfg(target_os = "linux")]
306static LINUX_SCALE_BITS: AtomicU64 = AtomicU64::new(0);
307
308/// Record the display scale factor observed from baseview on Linux. Editors
309/// should call this from their `WindowEvent::Resized` handlers so subsequent
310/// pre-window queries match what baseview is delivering. No-op on non-Linux.
311pub fn note_linux_scale_factor(scale: f64) {
312    #[cfg(target_os = "linux")]
313    {
314        if scale.is_finite() && scale > 0.0 {
315            LINUX_SCALE_BITS.store(scale.to_bits(), Ordering::Relaxed);
316        }
317    }
318    #[cfg(not(target_os = "linux"))]
319    {
320        let _ = scale;
321    }
322}
323
324#[cfg(target_os = "linux")]
325pub fn main_screen_scale() -> f64 {
326    // Priority: TRUCE_SCALE env var (dev/test override) → cached scale
327    // observed from baseview → 1.0 fallback. No side-channel Xlib calls -
328    // those crashed inside NVIDIA's Vulkan driver when invoked from the
329    // render thread.
330    if let Ok(s) = std::env::var("TRUCE_SCALE")
331        && let Ok(v) = s.parse::<f64>()
332        && v.is_finite()
333        && v > 0.0
334    {
335        return v;
336    }
337    let bits = LINUX_SCALE_BITS.load(Ordering::Relaxed);
338    if bits == 0 {
339        return 1.0;
340    }
341    let v = f64::from_bits(bits);
342    if v.is_finite() && v > 0.0 { v } else { 1.0 }
343}
344
345/// Query the DPI scale factor on Windows.
346/// If `hwnd` is non-null, queries per-window DPI; otherwise queries the system DPI.
347#[cfg(target_os = "windows")]
348fn win32_dpi_scale(hwnd: *mut std::ffi::c_void) -> f64 {
349    // Default DPI is 96; scale = actual_dpi / 96.
350    const DEFAULT_DPI: u32 = 96;
351
352    unsafe extern "system" {
353        fn GetDpiForWindow(hwnd: *mut std::ffi::c_void) -> u32;
354        fn GetDpiForSystem() -> u32;
355    }
356
357    let dpi = if hwnd.is_null() {
358        unsafe { GetDpiForSystem() }
359    } else {
360        let d = unsafe { GetDpiForWindow(hwnd) };
361        if d == 0 {
362            unsafe { GetDpiForSystem() }
363        } else {
364            d
365        }
366    };
367
368    if dpi == 0 {
369        1.0
370    } else {
371        f64::from(dpi) / f64::from(DEFAULT_DPI)
372    }
373}
374
375#[cfg(target_os = "windows")]
376fn current_module_hinstance() -> Option<std::num::NonZeroIsize> {
377    unsafe extern "system" {
378        fn GetModuleHandleW(lpModuleName: *const u16) -> isize;
379    }
380    // SAFETY: `GetModuleHandleW(NULL)` is documented to return the running
381    // EXE's HMODULE without acquiring a refcount; no threading or aliasing
382    // concerns. Returns 0 only in pathological cases (kernel32 missing).
383    let hmodule = unsafe { GetModuleHandleW(std::ptr::null()) };
384    std::num::NonZeroIsize::new(hmodule)
385}
386
387/// wgpu backends to use for an editor that presents into a
388/// host-owned child window. macOS is Metal-only; Windows is DX12
389/// (the only backend feature truce-gui/truce-gpu compile in on
390/// Windows - see their `Cargo.toml`); Linux keeps `PRIMARY`.
391#[must_use]
392pub fn editor_wgpu_backends() -> wgpu::Backends {
393    #[cfg(target_os = "windows")]
394    {
395        wgpu::Backends::DX12
396    }
397    #[cfg(target_os = "macos")]
398    {
399        wgpu::Backends::METAL
400    }
401    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
402    {
403        wgpu::Backends::PRIMARY
404    }
405}
406
407/// `wgpu::InstanceDescriptor` for editor surfaces, with the DX12
408/// shader compiler pinned to **FXC**.
409///
410/// wgpu 29 defaults DX12 to a dynamically-loaded **DXC**
411/// (`dxcompiler.dll`). When a host process has already loaded its own
412/// incompatible `dxcompiler.dll` - Pro Tools does - wgpu's
413/// `DxcCreateInstance` returns `E_NOINTERFACE` and the *entire* DX12
414/// backend fails to initialise, leaving the instance with zero
415/// adapters: a blank editor (egui / built-in) or a panic on the
416/// `.expect` (slint). FXC (`d3dcompiler_47.dll`, always present on
417/// Windows, never conflicts) sidesteps it. wgpu 0.19 (iced)
418/// defaulted to FXC, which is why iced was never affected.
419#[must_use]
420pub fn editor_instance_descriptor() -> wgpu::InstanceDescriptor {
421    let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
422    desc.backends = editor_wgpu_backends();
423    desc.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc;
424    desc
425}
426
427/// Bridge a baseview raw-window-handle 0.5 to a wgpu-compatible
428/// `SurfaceTargetUnsafe` using rwh 0.6 types.
429///
430/// Both `truce-gui`'s blit pipeline (cpu mode) and
431/// `truce_gpu::WgpuBackend::from_window` (gpu mode, used by
432/// `GpuEditor`) need this bridge; the two crates can't share a
433/// canonical copy without forming a dep cycle, so each carries its
434/// own ~100 LOC version. The two are kept in sync by inspection.
435///
436/// # Safety
437/// The window handle must be valid for the lifetime of the returned surface.
438#[cfg(not(target_os = "ios"))]
439#[must_use]
440pub unsafe fn create_wgpu_surface(
441    instance: &wgpu::Instance,
442    window: &baseview::Window,
443) -> Option<wgpu::Surface<'static>> {
444    unsafe {
445        let rwh = window.raw_window_handle();
446        let surface_target = match rwh {
447            #[cfg(target_os = "macos")]
448            RwhRawWindowHandle::AppKit(handle) => {
449                let ns_view = handle.ns_view;
450                if ns_view.is_null() {
451                    return None;
452                }
453                let rwh6_window = wgpu::rwh::RawWindowHandle::AppKit(
454                    wgpu::rwh::AppKitWindowHandle::new(std::ptr::NonNull::new(ns_view)?),
455                );
456                let rwh6_display =
457                    wgpu::rwh::RawDisplayHandle::AppKit(wgpu::rwh::AppKitDisplayHandle::new());
458                wgpu::SurfaceTargetUnsafe::RawHandle {
459                    raw_display_handle: Some(rwh6_display),
460                    raw_window_handle: rwh6_window,
461                }
462            }
463            #[cfg(target_os = "windows")]
464            RwhRawWindowHandle::Win32(handle) => {
465                let hwnd = handle.hwnd;
466                if hwnd.is_null() {
467                    return None;
468                }
469                let mut win32 =
470                    wgpu::rwh::Win32WindowHandle::new(std::num::NonZeroIsize::new(hwnd as isize)?);
471                // wgpu's Vulkan backend requires `hinstance` to be set
472                // (`vkCreateWin32SurfaceKHR` rejects a null HINSTANCE).
473                // baseview leaves the rwh 0.5 `hinstance` field at null,
474                // so populate it here with the running module's HMODULE.
475                win32.hinstance = current_module_hinstance();
476                let rwh6_window = wgpu::rwh::RawWindowHandle::Win32(win32);
477                let rwh6_display =
478                    wgpu::rwh::RawDisplayHandle::Windows(wgpu::rwh::WindowsDisplayHandle::new());
479                wgpu::SurfaceTargetUnsafe::RawHandle {
480                    raw_display_handle: Some(rwh6_display),
481                    raw_window_handle: rwh6_window,
482                }
483            }
484            #[cfg(target_os = "linux")]
485            RwhRawWindowHandle::Xlib(handle) => {
486                let RwhRawDisplayHandle::Xlib(display_handle) = window.raw_display_handle() else {
487                    return None;
488                };
489                let display_ptr = std::ptr::NonNull::new(display_handle.display);
490                let rwh6_window = wgpu::rwh::RawWindowHandle::Xlib(
491                    wgpu::rwh::XlibWindowHandle::new(handle.window),
492                );
493                let rwh6_display = wgpu::rwh::RawDisplayHandle::Xlib(
494                    wgpu::rwh::XlibDisplayHandle::new(display_ptr, display_handle.screen),
495                );
496                wgpu::SurfaceTargetUnsafe::RawHandle {
497                    raw_display_handle: Some(rwh6_display),
498                    raw_window_handle: rwh6_window,
499                }
500            }
501            _ => return None,
502        };
503
504        instance.create_surface_unsafe(surface_target).ok()
505    }
506}