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 bundle (one lane per declared task type),
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 task type `T`, or `None` if the
462    /// plugin declared no `tasks:` lane of that type. Scheduling with it is
463    /// wait-free, so it is safe from the GUI thread.
464    #[must_use]
465    pub fn tasks<T: Send + 'static>(&self) -> Option<TaskSpawner<T>> {
466        self.tasks.as_ref().and_then(AnyTaskSpawner::downcast::<T>)
467    }
468
469    /// Access the underlying bridge handle. Editors that want to clone
470    /// the bridge into a worker thread without cloning the surrounding
471    /// `PluginContext` use this.
472    #[must_use]
473    pub fn bridge(&self) -> &Arc<dyn EditorBridge> {
474        &self.bridge
475    }
476
477    /// Access the typed param store as an `Arc`. Use this when you
478    /// need to capture the params in a `'static` closure (e.g. an iced
479    /// `Subscription` or a worker thread).
480    #[must_use]
481    pub fn params(&self) -> &Arc<P> {
482        &self.params
483    }
484
485    /// Replace the param-store generic parameter while reusing the
486    /// same bridge. Used by editor crates that receive the dyn-erased
487    /// `PluginContext` from [`Editor::open`] and want the typed
488    /// `PluginContext<P>` for their UI closure.
489    pub fn with_params<Q: ?Sized>(&self, params: Arc<Q>) -> PluginContext<Q> {
490        PluginContext {
491            bridge: Arc::clone(&self.bridge),
492            tasks: self.tasks.clone(),
493            params,
494        }
495    }
496
497    pub fn begin_edit(&self, id: impl Into<u32>) {
498        self.bridge.begin_edit(id.into());
499    }
500    pub fn set_param(&self, id: impl Into<u32>, normalized: f64) {
501        self.bridge.set_param(id.into(), normalized);
502    }
503    pub fn end_edit(&self, id: impl Into<u32>) {
504        self.bridge.end_edit(id.into());
505    }
506    /// Begin + set + end in one call. Use for click-to-toggle widgets
507    /// and similar single-shot edits where the gesture and the value
508    /// arrive together.
509    pub fn automate(&self, id: impl Into<u32>, normalized: f64) {
510        let id = id.into();
511        self.bridge.begin_edit(id);
512        self.bridge.set_param(id, normalized);
513        self.bridge.end_edit(id);
514    }
515    /// Ask the host to resize the editor to `(w, h)` logical points.
516    /// Returns `true` if the request was accepted.
517    ///
518    /// **Re-entrancy:** call this from your editor's own event / render loop,
519    /// not synchronously from inside an [`Editor`] method the host drives
520    /// (`open`, `set_size`, `size`, `state_changed`, `close`). Several
521    /// wrappers hold an internal editor lock across those calls, and on some
522    /// formats `request_resize` reaches back into it - directly (AU) or via a
523    /// host that answers `resizeView` synchronously (VST3). Such a re-entrant
524    /// call is deferred (applied on a later frame) rather than applied inline,
525    /// so a "correct my aspect ratio from within `set_size`" pattern won't
526    /// take effect immediately; do that shaping by returning the adjusted size
527    /// or requesting from the next frame instead.
528    #[must_use]
529    pub fn request_resize(&self, w: u32, h: u32) -> bool {
530        self.bridge.request_resize(w, h)
531    }
532    pub fn format_param(&self, id: impl Into<u32>) -> String {
533        self.bridge.format_param(id.into())
534    }
535    /// Format into a caller-owned buffer. See
536    /// [`EditorBridge::format_param_into`] for the allocation
537    /// trade-off - the caller's buffer is reused, but bridges that
538    /// don't override the default impl still allocate internally.
539    pub fn format_param_into(&self, id: impl Into<u32>, out: &mut String) {
540        self.bridge.format_param_into(id.into(), out);
541    }
542    pub fn get_meter(&self, id: impl Into<u32>) -> f32 {
543        self.bridge.get_meter(id.into())
544    }
545    #[must_use]
546    pub fn get_state(&self) -> Vec<u8> {
547        self.bridge.get_state()
548    }
549    pub fn set_state(&self, data: Vec<u8>) {
550        self.bridge.set_state(data);
551    }
552    #[must_use]
553    pub fn transport(&self) -> Option<TransportInfo> {
554        self.bridge.transport()
555    }
556}
557
558impl PluginContext<dyn Params> {
559    /// Build a dyn-erased context from a [`ClosureBridge`]. Convenience
560    /// for format wrappers that compose state inline via closures.
561    pub fn from_closures(bridge: ClosureBridge, params: Arc<dyn Params>) -> Self {
562        Self {
563            bridge: Arc::new(bridge),
564            tasks: None,
565            params,
566        }
567    }
568}
569
570impl<P: Params + 'static> PluginContext<P> {
571    /// Drop the typed `<P>` and return the dyn-erased context that
572    /// crosses the `Editor::open` trait-object boundary.
573    #[must_use]
574    pub fn dyn_erase(self) -> PluginContext<dyn Params> {
575        PluginContext {
576            bridge: self.bridge,
577            tasks: self.tasks,
578            params: self.params as Arc<dyn Params>,
579        }
580    }
581}
582
583/// Plugin authors read parameter fields directly via `Deref`:
584/// `state.gain.read()`, `state.bypass.value()`. The `state`
585/// here is `&PluginContext<MyParams>` and `Deref::Target = MyParams`.
586impl<P: ?Sized> Deref for PluginContext<P> {
587    type Target = P;
588    fn deref(&self) -> &P {
589        &self.params
590    }
591}
592
593/// Build a [`PluginContext`] backed only by `params`. All write
594/// closures are no-ops; reads delegate to the params `Arc`; the
595/// transport reports the deterministic
596/// [`crate::events::TransportInfo::for_screenshot`] state so
597/// screenshot tests stay reproducible across CI runs.
598///
599/// Used by editor backends inside their `Editor::screenshot()` impl,
600/// and re-exported from `truce-test` for plugin authors that want to
601/// drive snapshot tests directly.
602pub fn for_test_params(params: Arc<dyn Params>) -> PluginContext<dyn Params> {
603    let p_get = Arc::clone(&params);
604    let p_plain = Arc::clone(&params);
605    let p_fmt = Arc::clone(&params);
606    let transport = TransportInfo::for_screenshot();
607    PluginContext::from_closures(
608        ClosureBridge {
609            begin_edit: Box::new(|_| {}),
610            set_param: Box::new(|_, _| {}),
611            end_edit: Box::new(|_| {}),
612            request_resize: Box::new(|_, _| false),
613            get_param: Box::new(move |id| p_get.get_normalized(id).unwrap_or(0.5)),
614            get_param_plain: Box::new(move |id| p_plain.get_plain(id).unwrap_or(0.0)),
615            format_param: Box::new(move |id| {
616                let plain = p_fmt.get_plain(id).unwrap_or(0.0);
617                p_fmt
618                    .format_value(id, plain)
619                    .unwrap_or_else(|| format!("{plain:.2}"))
620            }),
621            get_meter: Box::new(|_| 0.0),
622            get_state: Box::new(Vec::new),
623            set_state: Box::new(|_| {}),
624            transport: Box::new(move || Some(transport)),
625        },
626        params,
627    )
628}
629
630// ---------------------------------------------------------------------------
631// Precision-routed parameter reads
632//
633// The editor-bridge surface is sample-agnostic (`f64` on the wire, the
634// lossless lowest-common-denominator that round-trips any host
635// automation precision). These two extension traits route the call
636// site to the user's chosen precision - same pattern as
637// `FloatParamReadF32` / `FloatParamReadF64` for the audio-thread
638// param reads. Brought into scope via `pub use ... as _;` in each
639// prelude:
640//   - `prelude` / `prelude32`        → `PluginContextReadF32`
641//   - `prelude64` / `prelude64m`     → `PluginContextReadF64`
642//
643// Single-prelude code dispatches unambiguously. Importing both
644// preludes in the same file collides on `get_param` - the right
645// error if the file hasn't committed to a precision.
646// ---------------------------------------------------------------------------
647
648/// `f32`-precision parameter reads on `PluginContext`. Brought into
649/// scope by `truce::prelude` / `truce::prelude32` / `truce::prelude64m`
650/// (the `f32`-buffer preludes). GUI binding crates (slint, egui,
651/// iced) take `f32` natively, so this is the common case.
652pub trait PluginContextReadF32 {
653    /// Normalized `[0, 1]` value of the parameter, narrowed to `f32`.
654    fn get_param(&self, id: impl Into<u32>) -> f32;
655    /// Plain (denormalized) value of the parameter, narrowed to `f32`.
656    fn get_param_plain(&self, id: impl Into<u32>) -> f32;
657}
658
659/// `f64`-precision parameter reads on `PluginContext`. Brought into
660/// scope by `truce::prelude64`. Same surface as
661/// [`PluginContextReadF32`] but returns the bridge's `f64` value
662/// directly without narrowing.
663pub trait PluginContextReadF64 {
664    /// Normalized `[0, 1]` value of the parameter.
665    fn get_param(&self, id: impl Into<u32>) -> f64;
666    /// Plain (denormalized) value of the parameter.
667    fn get_param_plain(&self, id: impl Into<u32>) -> f64;
668}
669
670impl<P: ?Sized> PluginContextReadF32 for PluginContext<P> {
671    fn get_param(&self, id: impl Into<u32>) -> f32 {
672        self.bridge.get_param(id.into()).to_f32()
673    }
674    fn get_param_plain(&self, id: impl Into<u32>) -> f32 {
675        self.bridge.get_param_plain(id.into()).to_f32()
676    }
677}
678
679impl<P: ?Sized> PluginContextReadF64 for PluginContext<P> {
680    fn get_param(&self, id: impl Into<u32>) -> f64 {
681        self.bridge.get_param(id.into())
682    }
683    fn get_param_plain(&self, id: impl Into<u32>) -> f64 {
684        self.bridge.get_param_plain(id.into())
685    }
686}
687
688/// Constrain a host-requested logical size to an editor's
689/// [`Editor::min_size`] / [`Editor::max_size`] / [`Editor::aspect_ratio`].
690/// Shared by every format wrapper so they enforce identical constraints.
691///
692/// With an aspect ratio set, fit the *largest on-ratio rectangle that fits
693/// inside* the requested box: derive height from width and keep it if it
694/// fits, otherwise the width is the limiting axis and height drives it. The
695/// result is `<=` the request on both axes, so the editor surface never
696/// exceeds the host window and can never clip - whatever odd size a host
697/// hands us (some skip an aspect pre-flight and pass raw drag dimensions),
698/// the worst case is an on-ratio letterbox inside the window. The rule is a
699/// pure function of `(w, h)` - no "which edge moved" guess - so a drag can't
700/// make the chosen axis flip and judder. `u64` arithmetic for the
701/// multiplication so a hypothetical `(u32::MAX, 1)` aspect doesn't overflow
702/// before the clamp lands.
703#[must_use]
704pub fn fit_logical_size(w: u32, h: u32, editor: &dyn Editor) -> (u32, u32) {
705    fit_size(
706        w,
707        h,
708        editor.min_size(),
709        editor.max_size(),
710        editor.aspect_ratio(),
711    )
712}
713
714/// Same fit as [`fit_logical_size`] but over raw constraints rather than
715/// an `&dyn Editor`. Lets call sites that have already captured the
716/// bounds (e.g. an Objective-C resize callback that can't carry a trait
717/// object) reuse the identical rule.
718#[must_use]
719pub fn fit_size(
720    w: u32,
721    h: u32,
722    min: (u32, u32),
723    max: (u32, u32),
724    aspect: Option<(u32, u32)>,
725) -> (u32, u32) {
726    let (min_w, min_h) = min;
727    let (max_w, max_h) = max;
728    let mut w = w.clamp(min_w.max(1), max_w);
729    let mut h = h.clamp(min_h.max(1), max_h);
730    if let Some((num64, denom64)) = ratio64(aspect) {
731        // The on-ratio height for this width. Unclamped so the comparison
732        // sees the true ratio, not a bound-pinned value.
733        let h_from_w = u64::from(w) * denom64 / num64;
734        if h_from_w <= u64::from(h) {
735            // Width is the limiting axis: shrink height onto the ratio.
736            h = derive_height(w, min_h, max_h, num64, denom64).0;
737        } else {
738            // Height is the limiting axis: shrink width onto the ratio.
739            w = derive_width(h, min_w, max_w, num64, denom64).0;
740        }
741    }
742    (w, h)
743}
744
745/// Clamp a host-committed size to the editor's `[min, max]` bounds only,
746/// leaving the aspect ratio untouched so the editor fills the host window
747/// exactly. The commit-time counterpart to [`fit_logical_size`]: on-ratio
748/// shaping already happened during the host's drag negotiation (a preflight
749/// such as VST3 `checkSizeConstraint`), so re-fitting onto the ratio here
750/// would only floor the editor a pixel under the window and leave an
751/// unpainted letterbox line. The `max` clamp keeps the surface inside the
752/// window; the `min` clamp upholds the editor's "can't render smaller than
753/// this" floor even when a host hands over a too-small box.
754#[must_use]
755pub fn clamp_logical_size(w: u32, h: u32, editor: &dyn Editor) -> (u32, u32) {
756    let (min_w, min_h) = editor.min_size();
757    let (max_w, max_h) = editor.max_size();
758    (w.clamp(min_w.max(1), max_w), h.clamp(min_h.max(1), max_h))
759}
760
761/// Enforces size constraints on host resizes that bypassed the format's
762/// negotiation hooks. Some hosts resize the plugin's embedded window
763/// directly at the windowing-system level (Bitwig on Linux/X11 resizes
764/// the embed window itself), so no `checkSizeConstraint`-style preflight
765/// ever runs - the editor's own `Resized` handler is the last place that
766/// can enforce `min_size` / `max_size` / `aspect_ratio`.
767///
768/// [`Self::fit`] returns the size the editor should render at, plus an
769/// optional corrective size to push back to the host
770/// (`PluginContext::request_resize`). Each offending host size triggers at
771/// most one correction, and the corrective size itself satisfies the
772/// constraints, so a host that refuses (or echoes) the request can't be
773/// spun into a resize feedback loop.
774#[derive(Default)]
775pub struct ResizeCorrector {
776    /// Whether we've already pushed a corrective resize back to the host
777    /// for the current out-of-bounds excursion. Latches on the first
778    /// push-back and clears only when the host hands us an in-bounds size
779    /// again. A host that bypasses negotiation and then ignores the
780    /// push-back would otherwise be re-asked every frame and spun into a
781    /// runaway resize loop: Bitwig on Linux returns success to
782    /// `request_resize` but instead *grows* the embed window a few px per
783    /// call, and jitters the size on the un-clamped axis so the fitted
784    /// target changes every frame. Latching on "have we asked since the
785    /// last in-bounds size" - rather than on the requested size - sends
786    /// exactly one request per excursion even when that target wobbles.
787    pushed_back: bool,
788}
789
790impl ResizeCorrector {
791    /// Fit a host-driven logical size against the constraints. Returns
792    /// the fitted size to render at and, when the host size was out of
793    /// bounds and we haven't already pushed back this excursion, the size
794    /// to request back.
795    pub fn fit(
796        &mut self,
797        w: u32,
798        h: u32,
799        min: (u32, u32),
800        max: (u32, u32),
801        aspect: Option<(u32, u32)>,
802    ) -> ((u32, u32), Option<(u32, u32)>) {
803        let fitted = fit_size(w, h, min, max, aspect);
804        if fitted == (w, h) {
805            // In-bounds: the host is cooperating (or the drag returned
806            // within bounds); re-arm the next excursion's one-shot push.
807            self.pushed_back = false;
808            return (fitted, None);
809        }
810        // Out of bounds: push back exactly once per excursion.
811        let request = (!self.pushed_back).then_some(fitted);
812        self.pushed_back = true;
813        (fitted, request)
814    }
815}
816
817/// A usable `(num, denom)` ratio as `u64`, or `None` when no aspect is set
818/// or either term is zero. `u64` so the on-ratio multiplications below can't
819/// overflow before the clamp lands (a hypothetical `(u32::MAX, 1)` aspect).
820fn ratio64(aspect: Option<(u32, u32)>) -> Option<(u64, u64)> {
821    match aspect {
822        Some((num, denom)) if num > 0 && denom > 0 => Some((u64::from(num), u64::from(denom))),
823        _ => None,
824    }
825}
826
827/// On-ratio height for `w`, clamped into `[min_h, max_h]`. The flag reports
828/// whether the clamp moved the value (i.e. a bound was hit), so the caller
829/// knows whether the source axis needs re-deriving to stay on-ratio.
830#[allow(clippy::cast_possible_truncation)]
831fn derive_height(w: u32, min_h: u32, max_h: u32, num64: u64, denom64: u64) -> (u32, bool) {
832    let on_ratio = (u64::from(w) * denom64 / num64).clamp(1, u64::from(u32::MAX)) as u32;
833    let clamped = on_ratio.clamp(min_h.max(1), max_h);
834    (clamped, clamped != on_ratio)
835}
836
837/// On-ratio width for `h`, clamped into `[min_w, max_w]`. Flag as in
838/// [`derive_height`].
839#[allow(clippy::cast_possible_truncation)]
840fn derive_width(h: u32, min_w: u32, max_w: u32, num64: u64, denom64: u64) -> (u32, bool) {
841    let on_ratio = (u64::from(h) * num64 / denom64).clamp(1, u64::from(u32::MAX)) as u32;
842    let clamped = on_ratio.clamp(min_w.max(1), max_w);
843    (clamped, clamped != on_ratio)
844}
845
846#[cfg(test)]
847mod corrector_tests {
848    use super::ResizeCorrector;
849
850    const MIN: (u32, u32) = (300, 200);
851    const MAX: (u32, u32) = (900, 600);
852
853    #[test]
854    fn in_bounds_size_passes_through_without_correction() {
855        let mut c = ResizeCorrector::default();
856        assert_eq!(c.fit(400, 300, MIN, MAX, None), ((400, 300), None));
857    }
858
859    #[test]
860    fn out_of_bounds_pushes_once_per_excursion() {
861        let mut c = ResizeCorrector::default();
862        // First out-of-bounds sight: fit + one push-back.
863        let (fitted, req) = c.fit(1200, 800, MIN, MAX, None);
864        assert_eq!(fitted, (900, 600));
865        assert_eq!(req, Some((900, 600)));
866        // Host refused / echoed the same size: no repeat request.
867        assert_eq!(c.fit(1200, 800, MIN, MAX, None), ((900, 600), None));
868        // Host ignores it and keeps feeding out-of-bounds sizes - crucially,
869        // even ones whose *fitted target wobbles* (a different clamp on the
870        // un-pinned axis each frame). We stay quiet, so a host that grows in
871        // response to each request (Bitwig) can't be spun into a runaway.
872        assert_eq!(c.fit(1300, 590, MIN, MAX, None), ((900, 590), None));
873        assert_eq!(c.fit(1300, 595, MIN, MAX, None), ((900, 595), None));
874        // ...even a swing to the opposite bound stays quiet mid-excursion.
875        assert_eq!(c.fit(100, 100, MIN, MAX, None), ((300, 200), None));
876        // Host finally hands us an in-bounds size: excursion over, re-arm.
877        assert_eq!(c.fit(800, 500, MIN, MAX, None), ((800, 500), None));
878        // Next excursion gets a fresh single push-back.
879        let (_, req) = c.fit(1200, 800, MIN, MAX, None);
880        assert_eq!(req, Some((900, 600)));
881    }
882
883    #[test]
884    fn honoured_correction_resets_the_guard() {
885        let mut c = ResizeCorrector::default();
886        let _ = c.fit(1200, 800, MIN, MAX, None);
887        // Host applied the corrective size: in bounds, guard resets...
888        assert_eq!(c.fit(900, 600, MIN, MAX, None), ((900, 600), None));
889        // ...so the same offending size requests again next time.
890        let (_, req) = c.fit(1200, 800, MIN, MAX, None);
891        assert_eq!(req, Some((900, 600)));
892    }
893
894    #[test]
895    fn aspect_violation_corrects_onto_ratio() {
896        let mut c = ResizeCorrector::default();
897        let ((w, h), req) = c.fit(800, 600, MIN, MAX, Some((4, 3)));
898        assert_eq!((w, h), (800, 600), "already on-ratio passes through");
899        assert_eq!(req, None);
900        let ((w, h), req) = c.fit(800, 400, MIN, MAX, Some((4, 3)));
901        assert_eq!((w, h), (533, 400), "height-limited fit onto 4:3");
902        assert_eq!(req, Some((533, 400)));
903    }
904}
905
906#[cfg(test)]
907mod fit_tests {
908    use super::{Editor, PluginContext, RawWindowHandle, fit_logical_size};
909
910    /// Minimal editor stub: only the bounds/aspect hooks
911    /// `fit_logical_size` reads carry meaning; the rest are unused.
912    struct StubEditor {
913        min: (u32, u32),
914        max: (u32, u32),
915        aspect: Option<(u32, u32)>,
916    }
917
918    impl Editor for StubEditor {
919        fn size(&self) -> (u32, u32) {
920            self.min
921        }
922        fn open(&mut self, _parent: RawWindowHandle, _context: PluginContext) {}
923        fn close(&mut self) {}
924        fn min_size(&self) -> (u32, u32) {
925            self.min
926        }
927        fn max_size(&self) -> (u32, u32) {
928            self.max
929        }
930        fn aspect_ratio(&self) -> Option<(u32, u32)> {
931            self.aspect
932        }
933    }
934
935    fn stub(aspect: Option<(u32, u32)>) -> StubEditor {
936        StubEditor {
937            min: (320, 240),
938            max: (u32::MAX, u32::MAX),
939            aspect,
940        }
941    }
942
943    #[test]
944    fn no_aspect_clamps_each_axis_to_bounds() {
945        let e = stub(None);
946        assert_eq!(fit_logical_size(800, 600, &e), (800, 600));
947        assert_eq!(fit_logical_size(100, 100, &e), (320, 240));
948    }
949
950    #[test]
951    fn tall_box_is_width_bound() {
952        // A box taller than 4:3 fits the full width; height shrinks onto
953        // the ratio so the result never overflows the box.
954        let e = stub(Some((4, 3)));
955        assert_eq!(fit_logical_size(640, 800, &e), (640, 480));
956    }
957
958    #[test]
959    fn wide_box_is_height_bound() {
960        // A box wider than 4:3 fits the full height; width shrinks instead.
961        let e = stub(Some((4, 3)));
962        assert_eq!(fit_logical_size(800, 480, &e), (640, 480));
963    }
964
965    #[test]
966    fn on_ratio_box_is_unchanged() {
967        let e = stub(Some((4, 3)));
968        assert_eq!(fit_logical_size(800, 600, &e), (800, 600));
969    }
970
971    #[test]
972    fn fit_never_exceeds_the_requested_box() {
973        // The no-clip invariant: for any box at or above `min_size`, the
974        // aspect fit stays inside it on both axes, so the editor surface
975        // can never overflow the host window. `min` is on the 16:9 ratio so
976        // the fit also stays exactly on-ratio right down to the corner.
977        let e = StubEditor {
978            min: (320, 180),
979            max: (u32::MAX, u32::MAX),
980            aspect: Some((16, 9)),
981        };
982        for &(w, h) in &[
983            (640, 800),
984            (800, 480),
985            (1000, 1000),
986            (321, 900),
987            (1920, 300),
988        ] {
989            let (rw, rh) = fit_logical_size(w, h, &e);
990            assert!(rw <= w && rh <= h, "{rw}x{rh} exceeds box {w}x{h}");
991            assert!((i64::from(rw) * 9 - i64::from(rh) * 16).abs() <= 16);
992            assert!(rw >= 320 && rh >= 180);
993        }
994    }
995}