Skip to main content

truce_core/
editor.rs

1use std::ops::Deref;
2use std::sync::Arc;
3
4use truce_params::Params;
5use truce_params::sample::Float;
6
7use crate::events::TransportInfo;
8use crate::tasks::{AnyTaskSpawner, TaskSpawner};
9
10/// A lock-free editor factory bound to a plugin's param store.
11///
12/// `PluginExport::editor_builder` returns one of these at instance
13/// creation; format wrappers cache it outside the plugin lock and call
14/// it when the host opens the GUI. For a static build the closure builds
15/// the editor from the concrete logic type; for a `--shell` build it
16/// rebuilds from the currently loaded dylib, so GUI edits hot-reload
17/// (picked up on the next editor close+open). `Send + Sync` so wrappers
18/// can stash it in their instance struct and call it from the GUI thread.
19pub type EditorBuilder<P> = Box<dyn Fn(Arc<P>) -> Option<Box<dyn Editor>> + Send + Sync>;
20
21/// A raw pointer wrapper that is `Send + Sync`.
22///
23/// Used to capture `*const Params` / host-handle pointers in
24/// `PluginContext` closures without the `ptr as usize` hack. The
25/// `Send`/`Sync` impls are unconditional in `T` - they have to be,
26/// because the wrapped types are typically `#[repr(C)]` host structs
27/// that are themselves `!Send + !Sync` by default. Construction is
28/// therefore `unsafe`: each call site must justify why cross-thread
29/// access to the pointed-to data is sound.
30///
31/// Justifications used in-tree:
32/// - **`P: Params`** - fields are atomic; concurrent reads from the
33///   GUI thread while the audio thread writes are safe by design.
34/// - **Format-host handles** (`clap_host`, `AEffect`, etc.) - used
35///   only from a single thread (UI), and the wrapping is purely for
36///   capturing in `Send + Sync` closures stored in `PluginContext`.
37///
38/// The pointed-to data must outlive the `SendPtr`. In the plugin
39/// context, the plugin instance (which owns the params) always
40/// outlives the editor.
41pub struct SendPtr<T>(*const T);
42
43impl<T> SendPtr<T> {
44    /// Wrap a raw pointer.
45    ///
46    /// # Safety
47    /// The caller must ensure that:
48    /// 1. The pointed-to data outlives every clone of this `SendPtr`.
49    /// 2. Cross-thread access to `*ptr` is sound - either because `T`
50    ///    is `Sync`, because access is synchronized externally
51    ///    (atomic fields, Mutex, single-thread-only access pattern),
52    ///    or because the wrapper is only ever read on a thread where
53    ///    `T: Sync` would hold.
54    pub unsafe fn new(ptr: *const T) -> Self {
55        Self(ptr)
56    }
57
58    /// Dereference the pointer.
59    ///
60    /// # Safety
61    /// The pointed-to data must still be alive.
62    #[must_use]
63    pub unsafe fn get(&self) -> &T {
64        unsafe { &*self.0 }
65    }
66
67    /// Get the raw pointer.
68    #[must_use]
69    pub fn as_ptr(&self) -> *const T {
70        self.0
71    }
72}
73
74impl<T> Clone for SendPtr<T> {
75    fn clone(&self) -> Self {
76        *self
77    }
78}
79
80impl<T> Copy for SendPtr<T> {}
81
82// SAFETY: justified at each `unsafe SendPtr::new(...)` call site.
83unsafe impl<T> Send for SendPtr<T> {}
84unsafe impl<T> Sync for SendPtr<T> {}
85
86/// Raw platform window handle for GUI parenting.
87#[derive(Clone, Copy, Debug)]
88pub enum RawWindowHandle {
89    AppKit(*mut std::ffi::c_void), // macOS NSView*
90    UiKit(*mut std::ffi::c_void),  // iOS / iPadOS UIView*
91    Win32(*mut std::ffi::c_void),  // HWND
92    X11(u64),                      // X11 Window ID
93}
94
95/// Plugin GUI editor.
96pub trait Editor: Send {
97    /// Initial window size in logical points.
98    ///
99    /// On a 2x Retina display, `(400, 300)` produces an 800x600 pixel window.
100    /// On a 1x display, it produces a 400x300 pixel window.
101    fn size(&self) -> (u32, u32);
102
103    /// Create the GUI as a child of the host-provided parent window.
104    fn open(&mut self, parent: RawWindowHandle, context: PluginContext);
105
106    /// Destroy the GUI.
107    fn close(&mut self);
108
109    /// Called ~60fps on the host's UI thread for repaint/animation.
110    fn idle(&mut self) {}
111
112    /// Host requests a resize. Return true to accept.
113    fn set_size(&mut self, _width: u32, _height: u32) -> bool {
114        false
115    }
116
117    /// Whether the plugin supports resizing.
118    fn can_resize(&self) -> bool {
119        false
120    }
121
122    /// Whether the editor permits the standalone window to be
123    /// maximized (the WM maximize button / double-click-titlebar
124    /// maximize / macOS zoom-and-fullscreen / Windows maximize box).
125    ///
126    /// Standalone-only: in CLAP / VST3 / AU the host owns the window
127    /// frame, so this is ignored there (same as `size_increment`'s
128    /// WM-snap note). Subordinate to [`Self::can_resize`] - a
129    /// non-resizable editor can never be maximized regardless of this
130    /// value, since the standalone pins min == max, which already
131    /// blocks it.
132    ///
133    /// Defaults to `false`: the standalone host removes the maximize
134    /// affordance from resizable editors, so the window stays within
135    /// the edge-drag bounds the WM already enforces and can't jump past
136    /// the editor's [`Self::max_size`] into an unpainted margin around
137    /// the clamped surface. Override to `true` for editors that render
138    /// correctly at arbitrary size (typically an unbounded `max_size`)
139    /// and want the maximize affordance.
140    fn can_maximize(&self) -> bool {
141        false
142    }
143
144    /// Minimum size the editor can render at, in logical points.
145    /// Defaults to `(1, 1)`. Wrappers consult this for CLAP's
146    /// `gui_get_resize_hints` and VST3's `checkSizeConstraint`.
147    /// Ignored when `can_resize()` returns `false`.
148    fn min_size(&self) -> (u32, u32) {
149        (1, 1)
150    }
151
152    /// Maximum size the editor can render at, in logical points.
153    /// Defaults to `(u32::MAX, u32::MAX)`. Same wrapper consumers
154    /// as `min_size`.
155    fn max_size(&self) -> (u32, u32) {
156        (u32::MAX, u32::MAX)
157    }
158
159    /// Logical-point granularity for interactive resize, or `None`
160    /// for free (pixel-precise) resizing. The standalone X11 host
161    /// maps this onto WM resize increments (`PResizeInc`) so the
162    /// window manager snaps edge-drags to whole cells - the same
163    /// mechanism terminal emulators use to snap to character cells.
164    /// The snap counts from [`Self::min_size`], which is already
165    /// cell-aligned, so every allowed size lands on a boundary.
166    /// Ignored when `can_resize()` returns `false`.
167    fn size_increment(&self) -> Option<(u32, u32)> {
168        None
169    }
170
171    /// Aspect-ratio constraint as `(numerator, denominator)`, or
172    /// `None` for free resizing. CLAP, VST3, AU v3, standalone, and
173    /// LV2 honour this; VST2 / AAX silently ignore. Integer pair
174    /// (not `f64`) avoids the Cubase-9 aspect-rounding quirk JUCE
175    /// special-cases.
176    fn aspect_ratio(&self) -> Option<(u32, u32)> {
177        None
178    }
179
180    /// Hint that the renderer prefers power-of-two surface sizes
181    /// (some GPU-backed editors). Maps onto CLAP's
182    /// `clap_gui_resize_hints.preserve_aspect_ratio` /
183    /// `aspect_ratio_width` siblings; ignored on formats without
184    /// an equivalent.
185    fn prefers_pow2(&self) -> bool {
186        false
187    }
188
189    /// Host notifies the editor of a new content scale factor.
190    ///
191    /// DPI/scale is a host→plugin concept: on VST3 Windows the host
192    /// delivers it via `IPlugViewContentScaleSupport`; on CLAP via
193    /// `clap_plugin_gui::set_scale`; on macOS/Cocoa `AppKit` handles
194    /// Retina backing automatically and hosts typically never call
195    /// this at all. Editors that need to size off-screen buffers in
196    /// physical pixels should react here, not by exposing a pull-style
197    /// `scale_factor()` method that format wrappers were tempted to
198    /// multiply `size()` by (which caused double-scaling on macOS VST3).
199    fn set_scale_factor(&mut self, _factor: f64) {}
200
201    /// Opt the editor into honoring the desktop (system) scale.
202    ///
203    /// The standalone app calls this with `true` before [`open`] because
204    /// it owns a real top-level window that should match the desktop
205    /// (`Xft.dpi` on Linux). Plugin formats leave the default: an
206    /// embedded editor drives its Linux scale from the host's
207    /// content-scale callback (default 1.0) instead of the desktop,
208    /// since a non-DPI-aware host (e.g. Bitwig on X11) runs at 1x
209    /// regardless of desktop scaling and would otherwise get a
210    /// double-sized window. No-op on macOS/Windows, where the OS
211    /// reports a reliable per-window scale.
212    ///
213    /// [`open`]: Editor::open
214    fn set_uses_system_scale(&mut self, _yes: bool) {}
215
216    /// Plugin state was restored (preset recall, undo, session load).
217    ///
218    /// Called after `load_state()` while the editor is open. Re-read any
219    /// cached state from the plugin. Parameter values are already updated
220    /// and will be picked up on the next render - this is only needed for
221    /// custom state stored outside the parameter system.
222    fn state_changed(&mut self) {}
223
224    /// Render a headless screenshot of the editor at its natural size.
225    ///
226    /// `params` is a type-erased default-state instance the caller
227    /// constructs from the plugin's `Params` type. Backends use it to
228    /// build a synthetic `PluginContext` / render context so the
229    /// screenshot reflects parameter defaults without needing a live
230    /// host.
231    ///
232    /// Returns `(rgba_pixels, physical_width, physical_height)` - RGBA8
233    /// row-major, ready to feed into `truce_test::assert_screenshot_pixels`.
234    /// Default impl returns `None`; backends that support headless
235    /// capture (built-in widgets, egui, iced, slint) override.
236    ///
237    /// Used by `truce_test::assert_screenshot::<Plugin>(...)` for one-line
238    /// snapshot regression tests. Editors backed by frameworks that
239    /// don't expose a headless render path (e.g. raw-window-handle
240    /// users wiring their own Metal/OpenGL) keep the default `None`.
241    fn screenshot(&mut self, params: Arc<dyn truce_params::Params>) -> Option<(Vec<u8>, u32, u32)> {
242        let _ = params;
243        None
244    }
245}
246
247/// Fluent terminal for `editor()` impls: box any concrete editor into
248/// the `Box<dyn Editor>` the trait returns, dropping the `Box::new(…)`
249/// wrapper.
250///
251/// ```ignore
252/// fn editor(params: Arc<MyParams>) -> Box<dyn Editor> {
253///     EguiEditor::new(params, (W, H), ui)
254///         .with_visuals(theme)
255///         .into_editor()
256/// }
257/// ```
258///
259/// Implemented for every [`Editor`] via a blanket impl and re-exported
260/// from every `truce::prelude*`, so it's in scope without an extra
261/// import - egui / iced / slint / hand-rolled editors all use it.
262/// Layout-only plugins use `truce_gui::IntoLayoutEditor` instead (its
263/// `into_editor` takes `&Arc<Params>` and picks the built-in renderer).
264pub trait IntoEditor {
265    /// Box this editor into a `Box<dyn Editor>`.
266    fn into_editor(self) -> Box<dyn Editor>;
267}
268
269impl<E: Editor + 'static> IntoEditor for E {
270    fn into_editor(self) -> Box<dyn Editor> {
271        Box::new(self)
272    }
273}
274
275/// Bridge between the editor and the host / plugin. Format wrappers
276/// (CLAP / VST3 / VST2 / AU / AAX / LV2) implement this trait - or
277/// build a [`ClosureBridge`] from per-method closures - and pass an
278/// `Arc<dyn EditorBridge>` to the editor through [`PluginContext`].
279///
280/// Editors call into the bridge for everything they can't do
281/// directly: starting / ending an automation gesture, reading or
282/// writing parameters in normalized or plain form, requesting a
283/// window resize, exchanging custom state, sampling the host's
284/// transport. Implementations carry whatever per-format pointers
285/// the work needs (`clap_host*`, `AEffect*`, an `Arc<P>` for the
286/// param store, etc.).
287///
288/// `Send + Sync` is required so editors can clone the
289/// `Arc<dyn EditorBridge>` and hand it to UI worker threads or
290/// background animation timers without forcing every implementor to
291/// rederive thread-safety bounds.
292pub trait EditorBridge: Send + Sync {
293    /// Start an automation gesture for `id`. Hosts that show "touched"
294    /// state in the automation lane use this to render the
295    /// in-progress edit.
296    fn begin_edit(&self, id: u32);
297    /// Set parameter `id` to `normalized` (clamped to `0.0..=1.0`).
298    /// Format wrappers usually plumb this through both the plugin's
299    /// own param store and the host's automation channel.
300    fn set_param(&self, id: u32, normalized: f64);
301    /// End the automation gesture started by [`Self::begin_edit`].
302    fn end_edit(&self, id: u32);
303    /// Ask the host to resize the editor window to `(w, h)` logical
304    /// points. Returns `true` if the host accepted the request.
305    fn request_resize(&self, w: u32, h: u32) -> bool;
306    /// Read the parameter's current normalized value from the plugin
307    /// (host→GUI sync path).
308    fn get_param(&self, id: u32) -> f64;
309    /// Read the parameter's current plain (denormalized) value.
310    fn get_param_plain(&self, id: u32) -> f64;
311    /// Format the parameter's current value as a display string,
312    /// applying the plugin's `format_value` impl + unit suffix.
313    fn format_param(&self, id: u32) -> String;
314    /// Format into a caller-provided buffer instead of returning a
315    /// fresh `String`. The default impl calls
316    /// [`Self::format_param`] and copies, so the *bridge-internal*
317    /// allocation still happens; the win for the caller is that the
318    /// `out` buffer's capacity is reused across calls (e.g.
319    /// `ParamCache::sync` polls one label per changed param per
320    /// frame and would otherwise drop+reallocate the cached
321    /// `String` slot every time). Bridges that produce the formatted
322    /// string from raw value bytes can override to drop the
323    /// internal allocation too.
324    fn format_param_into(&self, id: u32, out: &mut String) {
325        out.clear();
326        out.push_str(&self.format_param(id));
327    }
328    /// Read a meter value (0.0–1.0) by meter ID. Returns 0.0 if the
329    /// meter ID isn't registered.
330    fn get_meter(&self, id: u32) -> f32;
331    /// Read the plugin's custom state (everything outside the
332    /// parameter system). Returns an empty `Vec` when the plugin has
333    /// no custom state.
334    fn get_state(&self) -> Vec<u8>;
335    /// Write custom state back to the plugin (calls `load_state()`).
336    fn set_state(&self, data: Vec<u8>);
337    /// Most-recently-reported host transport state, or `None` if the
338    /// host does not expose transport to plugin editors or the plugin
339    /// has not yet received a process block.
340    ///
341    /// Format wrappers populate a shared [`TransportSlot`](crate::TransportSlot)
342    /// from their process callback; this method reads from it.
343    fn transport(&self) -> Option<TransportInfo>;
344}
345
346/// Adapter that implements [`EditorBridge`] over per-method closures.
347///
348/// Format wrappers that prefer to compose state inline via closures
349/// construct one of these and wrap it in an `Arc<dyn EditorBridge>`.
350/// Wrappers that already have a typed host-pointer struct should
351/// `impl EditorBridge` for that struct directly and skip this
352/// adapter; one less layer of indirection per call.
353pub struct ClosureBridge {
354    pub begin_edit: Box<dyn Fn(u32) + Send + Sync>,
355    pub set_param: Box<dyn Fn(u32, f64) + Send + Sync>,
356    pub end_edit: Box<dyn Fn(u32) + Send + Sync>,
357    pub request_resize: Box<dyn Fn(u32, u32) -> bool + Send + Sync>,
358    pub get_param: Box<dyn Fn(u32) -> f64 + Send + Sync>,
359    pub get_param_plain: Box<dyn Fn(u32) -> f64 + Send + Sync>,
360    pub format_param: Box<dyn Fn(u32) -> String + Send + Sync>,
361    pub get_meter: Box<dyn Fn(u32) -> f32 + Send + Sync>,
362    pub get_state: Box<dyn Fn() -> Vec<u8> + Send + Sync>,
363    pub set_state: Box<dyn Fn(Vec<u8>) + Send + Sync>,
364    pub transport: Box<dyn Fn() -> Option<TransportInfo> + Send + Sync>,
365}
366
367impl EditorBridge for ClosureBridge {
368    fn begin_edit(&self, id: u32) {
369        (self.begin_edit)(id);
370    }
371    fn set_param(&self, id: u32, normalized: f64) {
372        (self.set_param)(id, normalized);
373    }
374    fn end_edit(&self, id: u32) {
375        (self.end_edit)(id);
376    }
377    fn request_resize(&self, w: u32, h: u32) -> bool {
378        (self.request_resize)(w, h)
379    }
380    fn get_param(&self, id: u32) -> f64 {
381        (self.get_param)(id)
382    }
383    fn get_param_plain(&self, id: u32) -> f64 {
384        (self.get_param_plain)(id)
385    }
386    fn format_param(&self, id: u32) -> String {
387        (self.format_param)(id)
388    }
389    fn get_meter(&self, id: u32) -> f32 {
390        (self.get_meter)(id)
391    }
392    fn get_state(&self) -> Vec<u8> {
393        (self.get_state)()
394    }
395    fn set_state(&self, data: Vec<u8>) {
396        (self.set_state)(data);
397    }
398    fn transport(&self) -> Option<TransportInfo> {
399        (self.transport)()
400    }
401}
402
403/// Context passed to [`Editor::open`]. Carries:
404///
405/// - An `Arc<dyn EditorBridge>` - the host-plugin protocol surface
406///   (begin/set/end edit, `request_resize`, `get_state`, transport, …).
407/// - An `Arc<P>` typed parameter store - plugin authors `Deref` to
408///   `&P` and read fields directly: `state.gain.read()`.
409///
410/// The default `P = dyn Params` keeps the trait-object boundary
411/// (`Editor::open(ctx: PluginContext)`) one-typed; editor crates
412/// that want typed access (truce-egui, truce-slint, truce-iced) carry
413/// their own `<P>` and reconstitute `PluginContext<P>` internally
414/// via [`PluginContext::with_params`] using the `Arc<P>` they stored
415/// at editor construction.
416///
417/// `Clone` is two refcount bumps (bridge + params). Editors that need
418/// to hand the context to UI worker threads or animation timers clone
419/// freely.
420pub struct PluginContext<P: ?Sized = dyn Params> {
421    bridge: Arc<dyn EditorBridge>,
422    /// Background-task spawner for the plugin's `BackgroundTasks::Task`,
423    /// stamped by the format wrapper from `PluginExport::task_spawner`
424    /// when the plugin wired `tasks:`. Lets the editor schedule work via
425    /// [`Self::tasks`]. `None` for a plugin with no background tasks.
426    tasks: Option<AnyTaskSpawner>,
427    params: Arc<P>,
428}
429
430impl<P: ?Sized> Clone for PluginContext<P> {
431    fn clone(&self) -> Self {
432        Self {
433            bridge: Arc::clone(&self.bridge),
434            tasks: self.tasks.clone(),
435            params: Arc::clone(&self.params),
436        }
437    }
438}
439
440impl<P: ?Sized> PluginContext<P> {
441    /// Build a typed context from any [`EditorBridge`] implementor and
442    /// the plugin's typed param store. Add background-task scheduling
443    /// with [`Self::with_tasks`].
444    pub fn new(bridge: Arc<dyn EditorBridge>, params: Arc<P>) -> Self {
445        Self {
446            bridge,
447            tasks: None,
448            params,
449        }
450    }
451
452    /// Attach the background-task spawner (from
453    /// `PluginExport::task_spawner`). Format wrappers call this when
454    /// building the editor context.
455    #[must_use]
456    pub fn with_tasks(mut self, tasks: Option<AnyTaskSpawner>) -> Self {
457        self.tasks = tasks;
458        self
459    }
460
461    /// The background-task spawner for the plugin's
462    /// `BackgroundTasks::Task`, or `None` if the plugin wired no
463    /// `tasks:`. Scheduling with it is wait-free, so it is safe from the
464    /// GUI thread.
465    #[must_use]
466    pub fn tasks<T: Send + 'static>(&self) -> Option<TaskSpawner<T>> {
467        self.tasks.as_ref().and_then(AnyTaskSpawner::downcast::<T>)
468    }
469
470    /// Access the underlying bridge handle. Editors that want to clone
471    /// the bridge into a worker thread without cloning the surrounding
472    /// `PluginContext` use this.
473    #[must_use]
474    pub fn bridge(&self) -> &Arc<dyn EditorBridge> {
475        &self.bridge
476    }
477
478    /// Access the typed param store as an `Arc`. Use this when you
479    /// need to capture the params in a `'static` closure (e.g. an iced
480    /// `Subscription` or a worker thread).
481    #[must_use]
482    pub fn params(&self) -> &Arc<P> {
483        &self.params
484    }
485
486    /// Replace the param-store generic parameter while reusing the
487    /// same bridge. Used by editor crates that receive the dyn-erased
488    /// `PluginContext` from [`Editor::open`] and want the typed
489    /// `PluginContext<P>` for their UI closure.
490    pub fn with_params<Q: ?Sized>(&self, params: Arc<Q>) -> PluginContext<Q> {
491        PluginContext {
492            bridge: Arc::clone(&self.bridge),
493            tasks: self.tasks.clone(),
494            params,
495        }
496    }
497
498    pub fn begin_edit(&self, id: impl Into<u32>) {
499        self.bridge.begin_edit(id.into());
500    }
501    pub fn set_param(&self, id: impl Into<u32>, normalized: f64) {
502        self.bridge.set_param(id.into(), normalized);
503    }
504    pub fn end_edit(&self, id: impl Into<u32>) {
505        self.bridge.end_edit(id.into());
506    }
507    /// Begin + set + end in one call. Use for click-to-toggle widgets
508    /// and similar single-shot edits where the gesture and the value
509    /// arrive together.
510    pub fn automate(&self, id: impl Into<u32>, normalized: f64) {
511        let id = id.into();
512        self.bridge.begin_edit(id);
513        self.bridge.set_param(id, normalized);
514        self.bridge.end_edit(id);
515    }
516    #[must_use]
517    pub fn request_resize(&self, w: u32, h: u32) -> bool {
518        self.bridge.request_resize(w, h)
519    }
520    pub fn format_param(&self, id: impl Into<u32>) -> String {
521        self.bridge.format_param(id.into())
522    }
523    /// Format into a caller-owned buffer. See
524    /// [`EditorBridge::format_param_into`] for the allocation
525    /// trade-off - the caller's buffer is reused, but bridges that
526    /// don't override the default impl still allocate internally.
527    pub fn format_param_into(&self, id: impl Into<u32>, out: &mut String) {
528        self.bridge.format_param_into(id.into(), out);
529    }
530    pub fn get_meter(&self, id: impl Into<u32>) -> f32 {
531        self.bridge.get_meter(id.into())
532    }
533    #[must_use]
534    pub fn get_state(&self) -> Vec<u8> {
535        self.bridge.get_state()
536    }
537    pub fn set_state(&self, data: Vec<u8>) {
538        self.bridge.set_state(data);
539    }
540    #[must_use]
541    pub fn transport(&self) -> Option<TransportInfo> {
542        self.bridge.transport()
543    }
544}
545
546impl PluginContext<dyn Params> {
547    /// Build a dyn-erased context from a [`ClosureBridge`]. Convenience
548    /// for format wrappers that compose state inline via closures.
549    pub fn from_closures(bridge: ClosureBridge, params: Arc<dyn Params>) -> Self {
550        Self {
551            bridge: Arc::new(bridge),
552            tasks: None,
553            params,
554        }
555    }
556}
557
558impl<P: Params + 'static> PluginContext<P> {
559    /// Drop the typed `<P>` and return the dyn-erased context that
560    /// crosses the `Editor::open` trait-object boundary.
561    #[must_use]
562    pub fn dyn_erase(self) -> PluginContext<dyn Params> {
563        PluginContext {
564            bridge: self.bridge,
565            tasks: self.tasks,
566            params: self.params as Arc<dyn Params>,
567        }
568    }
569}
570
571/// Plugin authors read parameter fields directly via `Deref`:
572/// `state.gain.read()`, `state.bypass.value()`. The `state`
573/// here is `&PluginContext<MyParams>` and `Deref::Target = MyParams`.
574impl<P: ?Sized> Deref for PluginContext<P> {
575    type Target = P;
576    fn deref(&self) -> &P {
577        &self.params
578    }
579}
580
581/// Build a [`PluginContext`] backed only by `params`. All write
582/// closures are no-ops; reads delegate to the params `Arc`; the
583/// transport reports the deterministic
584/// [`crate::events::TransportInfo::for_screenshot`] state so
585/// screenshot tests stay reproducible across CI runs.
586///
587/// Used by editor backends inside their `Editor::screenshot()` impl,
588/// and re-exported from `truce-test` for plugin authors that want to
589/// drive snapshot tests directly.
590pub fn for_test_params(params: Arc<dyn Params>) -> PluginContext<dyn Params> {
591    let p_get = Arc::clone(&params);
592    let p_plain = Arc::clone(&params);
593    let p_fmt = Arc::clone(&params);
594    let transport = TransportInfo::for_screenshot();
595    PluginContext::from_closures(
596        ClosureBridge {
597            begin_edit: Box::new(|_| {}),
598            set_param: Box::new(|_, _| {}),
599            end_edit: Box::new(|_| {}),
600            request_resize: Box::new(|_, _| false),
601            get_param: Box::new(move |id| p_get.get_normalized(id).unwrap_or(0.5)),
602            get_param_plain: Box::new(move |id| p_plain.get_plain(id).unwrap_or(0.0)),
603            format_param: Box::new(move |id| {
604                let plain = p_fmt.get_plain(id).unwrap_or(0.0);
605                p_fmt
606                    .format_value(id, plain)
607                    .unwrap_or_else(|| format!("{plain:.2}"))
608            }),
609            get_meter: Box::new(|_| 0.0),
610            get_state: Box::new(Vec::new),
611            set_state: Box::new(|_| {}),
612            transport: Box::new(move || Some(transport)),
613        },
614        params,
615    )
616}
617
618// ---------------------------------------------------------------------------
619// Precision-routed parameter reads
620//
621// The editor-bridge surface is sample-agnostic (`f64` on the wire, the
622// lossless lowest-common-denominator that round-trips any host
623// automation precision). These two extension traits route the call
624// site to the user's chosen precision - same pattern as
625// `FloatParamReadF32` / `FloatParamReadF64` for the audio-thread
626// param reads. Brought into scope via `pub use ... as _;` in each
627// prelude:
628//   - `prelude` / `prelude32`        → `PluginContextReadF32`
629//   - `prelude64` / `prelude64m`     → `PluginContextReadF64`
630//
631// Single-prelude code dispatches unambiguously. Importing both
632// preludes in the same file collides on `get_param` - the right
633// error if the file hasn't committed to a precision.
634// ---------------------------------------------------------------------------
635
636/// `f32`-precision parameter reads on `PluginContext`. Brought into
637/// scope by `truce::prelude` / `truce::prelude32` / `truce::prelude64m`
638/// (the `f32`-buffer preludes). GUI binding crates (slint, egui,
639/// iced) take `f32` natively, so this is the common case.
640pub trait PluginContextReadF32 {
641    /// Normalized `[0, 1]` value of the parameter, narrowed to `f32`.
642    fn get_param(&self, id: impl Into<u32>) -> f32;
643    /// Plain (denormalized) value of the parameter, narrowed to `f32`.
644    fn get_param_plain(&self, id: impl Into<u32>) -> f32;
645}
646
647/// `f64`-precision parameter reads on `PluginContext`. Brought into
648/// scope by `truce::prelude64`. Same surface as
649/// [`PluginContextReadF32`] but returns the bridge's `f64` value
650/// directly without narrowing.
651pub trait PluginContextReadF64 {
652    /// Normalized `[0, 1]` value of the parameter.
653    fn get_param(&self, id: impl Into<u32>) -> f64;
654    /// Plain (denormalized) value of the parameter.
655    fn get_param_plain(&self, id: impl Into<u32>) -> f64;
656}
657
658impl<P: ?Sized> PluginContextReadF32 for PluginContext<P> {
659    fn get_param(&self, id: impl Into<u32>) -> f32 {
660        self.bridge.get_param(id.into()).to_f32()
661    }
662    fn get_param_plain(&self, id: impl Into<u32>) -> f32 {
663        self.bridge.get_param_plain(id.into()).to_f32()
664    }
665}
666
667impl<P: ?Sized> PluginContextReadF64 for PluginContext<P> {
668    fn get_param(&self, id: impl Into<u32>) -> f64 {
669        self.bridge.get_param(id.into())
670    }
671    fn get_param_plain(&self, id: impl Into<u32>) -> f64 {
672        self.bridge.get_param_plain(id.into())
673    }
674}
675
676/// Constrain a host-requested logical size to an editor's
677/// [`Editor::min_size`] / [`Editor::max_size`] / [`Editor::aspect_ratio`].
678/// Shared by every format wrapper so they enforce identical constraints.
679///
680/// With an aspect ratio set, fit the *largest on-ratio rectangle that fits
681/// inside* the requested box: derive height from width and keep it if it
682/// fits, otherwise the width is the limiting axis and height drives it. The
683/// result is `<=` the request on both axes, so the editor surface never
684/// exceeds the host window and can never clip - whatever odd size a host
685/// hands us (some skip an aspect pre-flight and pass raw drag dimensions),
686/// the worst case is an on-ratio letterbox inside the window. The rule is a
687/// pure function of `(w, h)` - no "which edge moved" guess - so a drag can't
688/// make the chosen axis flip and judder. `u64` arithmetic for the
689/// multiplication so a hypothetical `(u32::MAX, 1)` aspect doesn't overflow
690/// before the clamp lands.
691#[must_use]
692pub fn fit_logical_size(w: u32, h: u32, editor: &dyn Editor) -> (u32, u32) {
693    fit_size(
694        w,
695        h,
696        editor.min_size(),
697        editor.max_size(),
698        editor.aspect_ratio(),
699    )
700}
701
702/// Same fit as [`fit_logical_size`] but over raw constraints rather than
703/// an `&dyn Editor`. Lets call sites that have already captured the
704/// bounds (e.g. an Objective-C resize callback that can't carry a trait
705/// object) reuse the identical rule.
706#[must_use]
707pub fn fit_size(
708    w: u32,
709    h: u32,
710    min: (u32, u32),
711    max: (u32, u32),
712    aspect: Option<(u32, u32)>,
713) -> (u32, u32) {
714    let (min_w, min_h) = min;
715    let (max_w, max_h) = max;
716    let mut w = w.clamp(min_w.max(1), max_w);
717    let mut h = h.clamp(min_h.max(1), max_h);
718    if let Some((num64, denom64)) = ratio64(aspect) {
719        // The on-ratio height for this width. Unclamped so the comparison
720        // sees the true ratio, not a bound-pinned value.
721        let h_from_w = u64::from(w) * denom64 / num64;
722        if h_from_w <= u64::from(h) {
723            // Width is the limiting axis: shrink height onto the ratio.
724            h = derive_height(w, min_h, max_h, num64, denom64).0;
725        } else {
726            // Height is the limiting axis: shrink width onto the ratio.
727            w = derive_width(h, min_w, max_w, num64, denom64).0;
728        }
729    }
730    (w, h)
731}
732
733/// Clamp a host-committed size to the editor's `[min, max]` bounds only,
734/// leaving the aspect ratio untouched so the editor fills the host window
735/// exactly. The commit-time counterpart to [`fit_logical_size`]: on-ratio
736/// shaping already happened during the host's drag negotiation (a preflight
737/// such as VST3 `checkSizeConstraint`), so re-fitting onto the ratio here
738/// would only floor the editor a pixel under the window and leave an
739/// unpainted letterbox line. The `max` clamp keeps the surface inside the
740/// window; the `min` clamp upholds the editor's "can't render smaller than
741/// this" floor even when a host hands over a too-small box.
742#[must_use]
743pub fn clamp_logical_size(w: u32, h: u32, editor: &dyn Editor) -> (u32, u32) {
744    let (min_w, min_h) = editor.min_size();
745    let (max_w, max_h) = editor.max_size();
746    (w.clamp(min_w.max(1), max_w), h.clamp(min_h.max(1), max_h))
747}
748
749/// Enforces size constraints on host resizes that bypassed the format's
750/// negotiation hooks. Some hosts resize the plugin's embedded window
751/// directly at the windowing-system level (Bitwig on Linux/X11 resizes
752/// the embed window itself), so no `checkSizeConstraint`-style preflight
753/// ever runs - the editor's own `Resized` handler is the last place that
754/// can enforce `min_size` / `max_size` / `aspect_ratio`.
755///
756/// [`Self::fit`] returns the size the editor should render at, plus an
757/// optional corrective size to push back to the host
758/// (`PluginContext::request_resize`). Each offending host size triggers at
759/// most one correction, and the corrective size itself satisfies the
760/// constraints, so a host that refuses (or echoes) the request can't be
761/// spun into a resize feedback loop.
762#[derive(Default)]
763pub struct ResizeCorrector {
764    /// Whether we've already pushed a corrective resize back to the host
765    /// for the current out-of-bounds excursion. Latches on the first
766    /// push-back and clears only when the host hands us an in-bounds size
767    /// again. A host that bypasses negotiation and then ignores the
768    /// push-back would otherwise be re-asked every frame and spun into a
769    /// runaway resize loop: Bitwig on Linux returns success to
770    /// `request_resize` but instead *grows* the embed window a few px per
771    /// call, and jitters the size on the un-clamped axis so the fitted
772    /// target changes every frame. Latching on "have we asked since the
773    /// last in-bounds size" - rather than on the requested size - sends
774    /// exactly one request per excursion even when that target wobbles.
775    pushed_back: bool,
776}
777
778impl ResizeCorrector {
779    /// Fit a host-driven logical size against the constraints. Returns
780    /// the fitted size to render at and, when the host size was out of
781    /// bounds and we haven't already pushed back this excursion, the size
782    /// to request back.
783    pub fn fit(
784        &mut self,
785        w: u32,
786        h: u32,
787        min: (u32, u32),
788        max: (u32, u32),
789        aspect: Option<(u32, u32)>,
790    ) -> ((u32, u32), Option<(u32, u32)>) {
791        let fitted = fit_size(w, h, min, max, aspect);
792        if fitted == (w, h) {
793            // In-bounds: the host is cooperating (or the drag returned
794            // within bounds); re-arm the next excursion's one-shot push.
795            self.pushed_back = false;
796            return (fitted, None);
797        }
798        // Out of bounds: push back exactly once per excursion.
799        let request = (!self.pushed_back).then_some(fitted);
800        self.pushed_back = true;
801        (fitted, request)
802    }
803}
804
805/// A usable `(num, denom)` ratio as `u64`, or `None` when no aspect is set
806/// or either term is zero. `u64` so the on-ratio multiplications below can't
807/// overflow before the clamp lands (a hypothetical `(u32::MAX, 1)` aspect).
808fn ratio64(aspect: Option<(u32, u32)>) -> Option<(u64, u64)> {
809    match aspect {
810        Some((num, denom)) if num > 0 && denom > 0 => Some((u64::from(num), u64::from(denom))),
811        _ => None,
812    }
813}
814
815/// On-ratio height for `w`, clamped into `[min_h, max_h]`. The flag reports
816/// whether the clamp moved the value (i.e. a bound was hit), so the caller
817/// knows whether the source axis needs re-deriving to stay on-ratio.
818#[allow(clippy::cast_possible_truncation)]
819fn derive_height(w: u32, min_h: u32, max_h: u32, num64: u64, denom64: u64) -> (u32, bool) {
820    let on_ratio = (u64::from(w) * denom64 / num64).clamp(1, u64::from(u32::MAX)) as u32;
821    let clamped = on_ratio.clamp(min_h.max(1), max_h);
822    (clamped, clamped != on_ratio)
823}
824
825/// On-ratio width for `h`, clamped into `[min_w, max_w]`. Flag as in
826/// [`derive_height`].
827#[allow(clippy::cast_possible_truncation)]
828fn derive_width(h: u32, min_w: u32, max_w: u32, num64: u64, denom64: u64) -> (u32, bool) {
829    let on_ratio = (u64::from(h) * num64 / denom64).clamp(1, u64::from(u32::MAX)) as u32;
830    let clamped = on_ratio.clamp(min_w.max(1), max_w);
831    (clamped, clamped != on_ratio)
832}
833
834#[cfg(test)]
835mod corrector_tests {
836    use super::ResizeCorrector;
837
838    const MIN: (u32, u32) = (300, 200);
839    const MAX: (u32, u32) = (900, 600);
840
841    #[test]
842    fn in_bounds_size_passes_through_without_correction() {
843        let mut c = ResizeCorrector::default();
844        assert_eq!(c.fit(400, 300, MIN, MAX, None), ((400, 300), None));
845    }
846
847    #[test]
848    fn out_of_bounds_pushes_once_per_excursion() {
849        let mut c = ResizeCorrector::default();
850        // First out-of-bounds sight: fit + one push-back.
851        let (fitted, req) = c.fit(1200, 800, MIN, MAX, None);
852        assert_eq!(fitted, (900, 600));
853        assert_eq!(req, Some((900, 600)));
854        // Host refused / echoed the same size: no repeat request.
855        assert_eq!(c.fit(1200, 800, MIN, MAX, None), ((900, 600), None));
856        // Host ignores it and keeps feeding out-of-bounds sizes - crucially,
857        // even ones whose *fitted target wobbles* (a different clamp on the
858        // un-pinned axis each frame). We stay quiet, so a host that grows in
859        // response to each request (Bitwig) can't be spun into a runaway.
860        assert_eq!(c.fit(1300, 590, MIN, MAX, None), ((900, 590), None));
861        assert_eq!(c.fit(1300, 595, MIN, MAX, None), ((900, 595), None));
862        // ...even a swing to the opposite bound stays quiet mid-excursion.
863        assert_eq!(c.fit(100, 100, MIN, MAX, None), ((300, 200), None));
864        // Host finally hands us an in-bounds size: excursion over, re-arm.
865        assert_eq!(c.fit(800, 500, MIN, MAX, None), ((800, 500), None));
866        // Next excursion gets a fresh single push-back.
867        let (_, req) = c.fit(1200, 800, MIN, MAX, None);
868        assert_eq!(req, Some((900, 600)));
869    }
870
871    #[test]
872    fn honoured_correction_resets_the_guard() {
873        let mut c = ResizeCorrector::default();
874        let _ = c.fit(1200, 800, MIN, MAX, None);
875        // Host applied the corrective size: in bounds, guard resets...
876        assert_eq!(c.fit(900, 600, MIN, MAX, None), ((900, 600), None));
877        // ...so the same offending size requests again next time.
878        let (_, req) = c.fit(1200, 800, MIN, MAX, None);
879        assert_eq!(req, Some((900, 600)));
880    }
881
882    #[test]
883    fn aspect_violation_corrects_onto_ratio() {
884        let mut c = ResizeCorrector::default();
885        let ((w, h), req) = c.fit(800, 600, MIN, MAX, Some((4, 3)));
886        assert_eq!((w, h), (800, 600), "already on-ratio passes through");
887        assert_eq!(req, None);
888        let ((w, h), req) = c.fit(800, 400, MIN, MAX, Some((4, 3)));
889        assert_eq!((w, h), (533, 400), "height-limited fit onto 4:3");
890        assert_eq!(req, Some((533, 400)));
891    }
892}
893
894#[cfg(test)]
895mod fit_tests {
896    use super::{Editor, PluginContext, RawWindowHandle, fit_logical_size};
897
898    /// Minimal editor stub: only the bounds/aspect hooks
899    /// `fit_logical_size` reads carry meaning; the rest are unused.
900    struct StubEditor {
901        min: (u32, u32),
902        max: (u32, u32),
903        aspect: Option<(u32, u32)>,
904    }
905
906    impl Editor for StubEditor {
907        fn size(&self) -> (u32, u32) {
908            self.min
909        }
910        fn open(&mut self, _parent: RawWindowHandle, _context: PluginContext) {}
911        fn close(&mut self) {}
912        fn min_size(&self) -> (u32, u32) {
913            self.min
914        }
915        fn max_size(&self) -> (u32, u32) {
916            self.max
917        }
918        fn aspect_ratio(&self) -> Option<(u32, u32)> {
919            self.aspect
920        }
921    }
922
923    fn stub(aspect: Option<(u32, u32)>) -> StubEditor {
924        StubEditor {
925            min: (320, 240),
926            max: (u32::MAX, u32::MAX),
927            aspect,
928        }
929    }
930
931    #[test]
932    fn no_aspect_clamps_each_axis_to_bounds() {
933        let e = stub(None);
934        assert_eq!(fit_logical_size(800, 600, &e), (800, 600));
935        assert_eq!(fit_logical_size(100, 100, &e), (320, 240));
936    }
937
938    #[test]
939    fn tall_box_is_width_bound() {
940        // A box taller than 4:3 fits the full width; height shrinks onto
941        // the ratio so the result never overflows the box.
942        let e = stub(Some((4, 3)));
943        assert_eq!(fit_logical_size(640, 800, &e), (640, 480));
944    }
945
946    #[test]
947    fn wide_box_is_height_bound() {
948        // A box wider than 4:3 fits the full height; width shrinks instead.
949        let e = stub(Some((4, 3)));
950        assert_eq!(fit_logical_size(800, 480, &e), (640, 480));
951    }
952
953    #[test]
954    fn on_ratio_box_is_unchanged() {
955        let e = stub(Some((4, 3)));
956        assert_eq!(fit_logical_size(800, 600, &e), (800, 600));
957    }
958
959    #[test]
960    fn fit_never_exceeds_the_requested_box() {
961        // The no-clip invariant: for any box at or above `min_size`, the
962        // aspect fit stays inside it on both axes, so the editor surface
963        // can never overflow the host window. `min` is on the 16:9 ratio so
964        // the fit also stays exactly on-ratio right down to the corner.
965        let e = StubEditor {
966            min: (320, 180),
967            max: (u32::MAX, u32::MAX),
968            aspect: Some((16, 9)),
969        };
970        for &(w, h) in &[
971            (640, 800),
972            (800, 480),
973            (1000, 1000),
974            (321, 900),
975            (1920, 300),
976        ] {
977            let (rw, rh) = fit_logical_size(w, h, &e);
978            assert!(rw <= w && rh <= h, "{rw}x{rh} exceeds box {w}x{h}");
979            assert!((i64::from(rw) * 9 - i64::from(rh) * 16).abs() <= 16);
980            assert!(rw >= 320 && rh >= 180);
981        }
982    }
983}