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;
8
9/// A raw pointer wrapper that is `Send + Sync`.
10///
11/// Used to capture `*const Params` / host-handle pointers in
12/// `PluginContext` closures without the `ptr as usize` hack. The
13/// `Send`/`Sync` impls are unconditional in `T` - they have to be,
14/// because the wrapped types are typically `#[repr(C)]` host structs
15/// that are themselves `!Send + !Sync` by default. Construction is
16/// therefore `unsafe`: each call site must justify why cross-thread
17/// access to the pointed-to data is sound.
18///
19/// Justifications used in-tree:
20/// - **`P: Params`** - fields are atomic; concurrent reads from the
21/// GUI thread while the audio thread writes are safe by design.
22/// - **Format-host handles** (`clap_host`, `AEffect`, etc.) - used
23/// only from a single thread (UI), and the wrapping is purely for
24/// capturing in `Send + Sync` closures stored in `PluginContext`.
25///
26/// The pointed-to data must outlive the `SendPtr`. In the plugin
27/// context, the plugin instance (which owns the params) always
28/// outlives the editor.
29pub struct SendPtr<T>(*const T);
30
31impl<T> SendPtr<T> {
32 /// Wrap a raw pointer.
33 ///
34 /// # Safety
35 /// The caller must ensure that:
36 /// 1. The pointed-to data outlives every clone of this `SendPtr`.
37 /// 2. Cross-thread access to `*ptr` is sound - either because `T`
38 /// is `Sync`, because access is synchronized externally
39 /// (atomic fields, Mutex, single-thread-only access pattern),
40 /// or because the wrapper is only ever read on a thread where
41 /// `T: Sync` would hold.
42 pub unsafe fn new(ptr: *const T) -> Self {
43 Self(ptr)
44 }
45
46 /// Dereference the pointer.
47 ///
48 /// # Safety
49 /// The pointed-to data must still be alive.
50 #[must_use]
51 pub unsafe fn get(&self) -> &T {
52 unsafe { &*self.0 }
53 }
54
55 /// Get the raw pointer.
56 #[must_use]
57 pub fn as_ptr(&self) -> *const T {
58 self.0
59 }
60}
61
62impl<T> Clone for SendPtr<T> {
63 fn clone(&self) -> Self {
64 *self
65 }
66}
67
68impl<T> Copy for SendPtr<T> {}
69
70// SAFETY: justified at each `unsafe SendPtr::new(...)` call site.
71unsafe impl<T> Send for SendPtr<T> {}
72unsafe impl<T> Sync for SendPtr<T> {}
73
74/// Raw platform window handle for GUI parenting.
75#[derive(Clone, Copy, Debug)]
76pub enum RawWindowHandle {
77 AppKit(*mut std::ffi::c_void), // macOS NSView*
78 UiKit(*mut std::ffi::c_void), // iOS / iPadOS UIView*
79 Win32(*mut std::ffi::c_void), // HWND
80 X11(u64), // X11 Window ID
81}
82
83/// Plugin GUI editor.
84pub trait Editor: Send {
85 /// Initial window size in logical points.
86 ///
87 /// On a 2x Retina display, `(400, 300)` produces an 800x600 pixel window.
88 /// On a 1x display, it produces a 400x300 pixel window.
89 fn size(&self) -> (u32, u32);
90
91 /// Create the GUI as a child of the host-provided parent window.
92 fn open(&mut self, parent: RawWindowHandle, context: PluginContext);
93
94 /// Destroy the GUI.
95 fn close(&mut self);
96
97 /// Called ~60fps on the host's UI thread for repaint/animation.
98 fn idle(&mut self) {}
99
100 /// Host requests a resize. Return true to accept.
101 fn set_size(&mut self, _width: u32, _height: u32) -> bool {
102 false
103 }
104
105 /// Whether the plugin supports resizing.
106 fn can_resize(&self) -> bool {
107 false
108 }
109
110 /// Host notifies the editor of a new content scale factor.
111 ///
112 /// DPI/scale is a host→plugin concept: on VST3 Windows the host
113 /// delivers it via `IPlugViewContentScaleSupport`; on CLAP via
114 /// `clap_plugin_gui::set_scale`; on macOS/Cocoa `AppKit` handles
115 /// Retina backing automatically and hosts typically never call
116 /// this at all. Editors that need to size off-screen buffers in
117 /// physical pixels should react here, not by exposing a pull-style
118 /// `scale_factor()` method that format wrappers were tempted to
119 /// multiply `size()` by (which caused double-scaling on macOS VST3).
120 fn set_scale_factor(&mut self, _factor: f64) {}
121
122 /// Plugin state was restored (preset recall, undo, session load).
123 ///
124 /// Called after `load_state()` while the editor is open. Re-read any
125 /// cached state from the plugin. Parameter values are already updated
126 /// and will be picked up on the next render - this is only needed for
127 /// custom state stored outside the parameter system.
128 fn state_changed(&mut self) {}
129
130 /// Render a headless screenshot of the editor at its natural size.
131 ///
132 /// `params` is a type-erased default-state instance the caller
133 /// constructs from the plugin's `Params` type. Backends use it to
134 /// build a synthetic `PluginContext` / render context so the
135 /// screenshot reflects parameter defaults without needing a live
136 /// host.
137 ///
138 /// Returns `(rgba_pixels, physical_width, physical_height)` - RGBA8
139 /// row-major, ready to feed into `truce_test::assert_screenshot_pixels`.
140 /// Default impl returns `None`; backends that support headless
141 /// capture (built-in widgets, egui, iced, slint) override.
142 ///
143 /// Used by `truce_test::assert_screenshot::<Plugin>(...)` for one-line
144 /// snapshot regression tests. Editors backed by frameworks that
145 /// don't expose a headless render path (e.g. raw-window-handle
146 /// users wiring their own Metal/OpenGL) keep the default `None`.
147 fn screenshot(&mut self, params: Arc<dyn truce_params::Params>) -> Option<(Vec<u8>, u32, u32)> {
148 let _ = params;
149 None
150 }
151}
152
153/// Bridge between the editor and the host / plugin. Format wrappers
154/// (CLAP / VST3 / VST2 / AU / AAX / LV2) implement this trait - or
155/// build a [`ClosureBridge`] from per-method closures - and pass an
156/// `Arc<dyn EditorBridge>` to the editor through [`PluginContext`].
157///
158/// Editors call into the bridge for everything they can't do
159/// directly: starting / ending an automation gesture, reading or
160/// writing parameters in normalized or plain form, requesting a
161/// window resize, exchanging custom state, sampling the host's
162/// transport. Implementations carry whatever per-format pointers
163/// the work needs (`clap_host*`, `AEffect*`, an `Arc<P>` for the
164/// param store, etc.).
165///
166/// `Send + Sync` is required so editors can clone the
167/// `Arc<dyn EditorBridge>` and hand it to UI worker threads or
168/// background animation timers without forcing every implementor to
169/// rederive thread-safety bounds.
170pub trait EditorBridge: Send + Sync {
171 /// Start an automation gesture for `id`. Hosts that show "touched"
172 /// state in the automation lane use this to render the
173 /// in-progress edit.
174 fn begin_edit(&self, id: u32);
175 /// Set parameter `id` to `normalized` (clamped to `0.0..=1.0`).
176 /// Format wrappers usually plumb this through both the plugin's
177 /// own param store and the host's automation channel.
178 fn set_param(&self, id: u32, normalized: f64);
179 /// End the automation gesture started by [`Self::begin_edit`].
180 fn end_edit(&self, id: u32);
181 /// Ask the host to resize the editor window to `(w, h)` logical
182 /// points. Returns `true` if the host accepted the request.
183 fn request_resize(&self, w: u32, h: u32) -> bool;
184 /// Read the parameter's current normalized value from the plugin
185 /// (host→GUI sync path).
186 fn get_param(&self, id: u32) -> f64;
187 /// Read the parameter's current plain (denormalized) value.
188 fn get_param_plain(&self, id: u32) -> f64;
189 /// Format the parameter's current value as a display string,
190 /// applying the plugin's `format_value` impl + unit suffix.
191 fn format_param(&self, id: u32) -> String;
192 /// Format into a caller-provided buffer instead of returning a
193 /// fresh `String`. The default impl calls
194 /// [`Self::format_param`] and copies, so the *bridge-internal*
195 /// allocation still happens; the win for the caller is that the
196 /// `out` buffer's capacity is reused across calls (e.g.
197 /// `ParamCache::sync` polls one label per changed param per
198 /// frame and would otherwise drop+reallocate the cached
199 /// `String` slot every time). Bridges that produce the formatted
200 /// string from raw value bytes can override to drop the
201 /// internal allocation too.
202 fn format_param_into(&self, id: u32, out: &mut String) {
203 out.clear();
204 out.push_str(&self.format_param(id));
205 }
206 /// Read a meter value (0.0–1.0) by meter ID. Returns 0.0 if the
207 /// meter ID isn't registered.
208 fn get_meter(&self, id: u32) -> f32;
209 /// Read the plugin's custom state (everything outside the
210 /// parameter system). Returns an empty `Vec` when the plugin has
211 /// no custom state.
212 fn get_state(&self) -> Vec<u8>;
213 /// Write custom state back to the plugin (calls `load_state()`).
214 fn set_state(&self, data: Vec<u8>);
215 /// Most-recently-reported host transport state, or `None` if the
216 /// host does not expose transport to plugin editors or the plugin
217 /// has not yet received a process block.
218 ///
219 /// Format wrappers populate a shared [`TransportSlot`](crate::TransportSlot)
220 /// from their process callback; this method reads from it.
221 fn transport(&self) -> Option<TransportInfo>;
222}
223
224/// Adapter that implements [`EditorBridge`] over per-method closures.
225///
226/// Format wrappers that prefer to compose state inline via closures
227/// construct one of these and wrap it in an `Arc<dyn EditorBridge>`.
228/// Wrappers that already have a typed host-pointer struct should
229/// `impl EditorBridge` for that struct directly and skip this
230/// adapter; one less layer of indirection per call.
231pub struct ClosureBridge {
232 pub begin_edit: Box<dyn Fn(u32) + Send + Sync>,
233 pub set_param: Box<dyn Fn(u32, f64) + Send + Sync>,
234 pub end_edit: Box<dyn Fn(u32) + Send + Sync>,
235 pub request_resize: Box<dyn Fn(u32, u32) -> bool + Send + Sync>,
236 pub get_param: Box<dyn Fn(u32) -> f64 + Send + Sync>,
237 pub get_param_plain: Box<dyn Fn(u32) -> f64 + Send + Sync>,
238 pub format_param: Box<dyn Fn(u32) -> String + Send + Sync>,
239 pub get_meter: Box<dyn Fn(u32) -> f32 + Send + Sync>,
240 pub get_state: Box<dyn Fn() -> Vec<u8> + Send + Sync>,
241 pub set_state: Box<dyn Fn(Vec<u8>) + Send + Sync>,
242 pub transport: Box<dyn Fn() -> Option<TransportInfo> + Send + Sync>,
243}
244
245impl EditorBridge for ClosureBridge {
246 fn begin_edit(&self, id: u32) {
247 (self.begin_edit)(id);
248 }
249 fn set_param(&self, id: u32, normalized: f64) {
250 (self.set_param)(id, normalized);
251 }
252 fn end_edit(&self, id: u32) {
253 (self.end_edit)(id);
254 }
255 fn request_resize(&self, w: u32, h: u32) -> bool {
256 (self.request_resize)(w, h)
257 }
258 fn get_param(&self, id: u32) -> f64 {
259 (self.get_param)(id)
260 }
261 fn get_param_plain(&self, id: u32) -> f64 {
262 (self.get_param_plain)(id)
263 }
264 fn format_param(&self, id: u32) -> String {
265 (self.format_param)(id)
266 }
267 fn get_meter(&self, id: u32) -> f32 {
268 (self.get_meter)(id)
269 }
270 fn get_state(&self) -> Vec<u8> {
271 (self.get_state)()
272 }
273 fn set_state(&self, data: Vec<u8>) {
274 (self.set_state)(data);
275 }
276 fn transport(&self) -> Option<TransportInfo> {
277 (self.transport)()
278 }
279}
280
281/// Context passed to [`Editor::open`]. Carries:
282///
283/// - An `Arc<dyn EditorBridge>` - the host-plugin protocol surface
284/// (begin/set/end edit, `request_resize`, `get_state`, transport, …).
285/// - An `Arc<P>` typed parameter store - plugin authors `Deref` to
286/// `&P` and read fields directly: `state.gain.read()`.
287///
288/// The default `P = dyn Params` keeps the trait-object boundary
289/// (`Editor::open(ctx: PluginContext)`) one-typed; editor crates
290/// that want typed access (truce-egui, truce-slint, truce-iced) carry
291/// their own `<P>` and reconstitute `PluginContext<P>` internally
292/// via [`PluginContext::with_params`] using the `Arc<P>` they stored
293/// at editor construction.
294///
295/// `Clone` is two refcount bumps (bridge + params). Editors that need
296/// to hand the context to UI worker threads or animation timers clone
297/// freely.
298pub struct PluginContext<P: ?Sized = dyn Params> {
299 bridge: Arc<dyn EditorBridge>,
300 params: Arc<P>,
301}
302
303impl<P: ?Sized> Clone for PluginContext<P> {
304 fn clone(&self) -> Self {
305 Self {
306 bridge: Arc::clone(&self.bridge),
307 params: Arc::clone(&self.params),
308 }
309 }
310}
311
312impl<P: ?Sized> PluginContext<P> {
313 /// Build a typed context from any [`EditorBridge`] implementor and
314 /// the plugin's typed param store.
315 pub fn new(bridge: Arc<dyn EditorBridge>, params: Arc<P>) -> Self {
316 Self { bridge, params }
317 }
318
319 /// Access the underlying bridge handle. Editors that want to clone
320 /// the bridge into a worker thread without cloning the surrounding
321 /// `PluginContext` use this.
322 #[must_use]
323 pub fn bridge(&self) -> &Arc<dyn EditorBridge> {
324 &self.bridge
325 }
326
327 /// Access the typed param store as an `Arc`. Use this when you
328 /// need to capture the params in a `'static` closure (e.g. an iced
329 /// `Subscription` or a worker thread).
330 #[must_use]
331 pub fn params(&self) -> &Arc<P> {
332 &self.params
333 }
334
335 /// Replace the param-store generic parameter while reusing the
336 /// same bridge. Used by editor crates that receive the dyn-erased
337 /// `PluginContext` from [`Editor::open`] and want the typed
338 /// `PluginContext<P>` for their UI closure.
339 pub fn with_params<Q: ?Sized>(&self, params: Arc<Q>) -> PluginContext<Q> {
340 PluginContext {
341 bridge: Arc::clone(&self.bridge),
342 params,
343 }
344 }
345
346 pub fn begin_edit(&self, id: impl Into<u32>) {
347 self.bridge.begin_edit(id.into());
348 }
349 pub fn set_param(&self, id: impl Into<u32>, normalized: f64) {
350 self.bridge.set_param(id.into(), normalized);
351 }
352 pub fn end_edit(&self, id: impl Into<u32>) {
353 self.bridge.end_edit(id.into());
354 }
355 /// Begin + set + end in one call. Use for click-to-toggle widgets
356 /// and similar single-shot edits where the gesture and the value
357 /// arrive together.
358 pub fn automate(&self, id: impl Into<u32>, normalized: f64) {
359 let id = id.into();
360 self.bridge.begin_edit(id);
361 self.bridge.set_param(id, normalized);
362 self.bridge.end_edit(id);
363 }
364 #[must_use]
365 pub fn request_resize(&self, w: u32, h: u32) -> bool {
366 self.bridge.request_resize(w, h)
367 }
368 pub fn format_param(&self, id: impl Into<u32>) -> String {
369 self.bridge.format_param(id.into())
370 }
371 /// Format into a caller-owned buffer. See
372 /// [`EditorBridge::format_param_into`] for the allocation
373 /// trade-off - the caller's buffer is reused, but bridges that
374 /// don't override the default impl still allocate internally.
375 pub fn format_param_into(&self, id: impl Into<u32>, out: &mut String) {
376 self.bridge.format_param_into(id.into(), out);
377 }
378 pub fn get_meter(&self, id: impl Into<u32>) -> f32 {
379 self.bridge.get_meter(id.into())
380 }
381 #[must_use]
382 pub fn get_state(&self) -> Vec<u8> {
383 self.bridge.get_state()
384 }
385 pub fn set_state(&self, data: Vec<u8>) {
386 self.bridge.set_state(data);
387 }
388 #[must_use]
389 pub fn transport(&self) -> Option<TransportInfo> {
390 self.bridge.transport()
391 }
392}
393
394impl PluginContext<dyn Params> {
395 /// Build a dyn-erased context from a [`ClosureBridge`]. Convenience
396 /// for format wrappers that compose state inline via closures.
397 pub fn from_closures(bridge: ClosureBridge, params: Arc<dyn Params>) -> Self {
398 Self {
399 bridge: Arc::new(bridge),
400 params,
401 }
402 }
403}
404
405impl<P: Params + 'static> PluginContext<P> {
406 /// Drop the typed `<P>` and return the dyn-erased context that
407 /// crosses the `Editor::open` trait-object boundary.
408 #[must_use]
409 pub fn dyn_erase(self) -> PluginContext<dyn Params> {
410 PluginContext {
411 bridge: self.bridge,
412 params: self.params as Arc<dyn Params>,
413 }
414 }
415}
416
417/// Plugin authors read parameter fields directly via `Deref`:
418/// `state.gain.read()`, `state.bypass.value()`. The `state`
419/// here is `&PluginContext<MyParams>` and `Deref::Target = MyParams`.
420impl<P: ?Sized> Deref for PluginContext<P> {
421 type Target = P;
422 fn deref(&self) -> &P {
423 &self.params
424 }
425}
426
427/// Build a [`PluginContext`] backed only by `params`. All write
428/// closures are no-ops; reads delegate to the params `Arc`; the
429/// transport reports the deterministic
430/// [`crate::events::TransportInfo::for_screenshot`] state so
431/// screenshot tests stay reproducible across CI runs.
432///
433/// Used by editor backends inside their `Editor::screenshot()` impl,
434/// and re-exported from `truce-test` for plugin authors that want to
435/// drive snapshot tests directly.
436pub fn for_test_params(params: Arc<dyn Params>) -> PluginContext<dyn Params> {
437 let p_get = Arc::clone(¶ms);
438 let p_plain = Arc::clone(¶ms);
439 let p_fmt = Arc::clone(¶ms);
440 let transport = TransportInfo::for_screenshot();
441 PluginContext::from_closures(
442 ClosureBridge {
443 begin_edit: Box::new(|_| {}),
444 set_param: Box::new(|_, _| {}),
445 end_edit: Box::new(|_| {}),
446 request_resize: Box::new(|_, _| false),
447 get_param: Box::new(move |id| p_get.get_normalized(id).unwrap_or(0.5)),
448 get_param_plain: Box::new(move |id| p_plain.get_plain(id).unwrap_or(0.0)),
449 format_param: Box::new(move |id| {
450 let plain = p_fmt.get_plain(id).unwrap_or(0.0);
451 p_fmt
452 .format_value(id, plain)
453 .unwrap_or_else(|| format!("{plain:.2}"))
454 }),
455 get_meter: Box::new(|_| 0.0),
456 get_state: Box::new(Vec::new),
457 set_state: Box::new(|_| {}),
458 transport: Box::new(move || Some(transport)),
459 },
460 params,
461 )
462}
463
464// ---------------------------------------------------------------------------
465// Precision-routed parameter reads
466//
467// The editor-bridge surface is sample-agnostic (`f64` on the wire, the
468// lossless lowest-common-denominator that round-trips any host
469// automation precision). These two extension traits route the call
470// site to the user's chosen precision - same pattern as
471// `FloatParamReadF32` / `FloatParamReadF64` for the audio-thread
472// param reads. Brought into scope via `pub use ... as _;` in each
473// prelude:
474// - `prelude` / `prelude32` → `PluginContextReadF32`
475// - `prelude64` / `prelude64m` → `PluginContextReadF64`
476//
477// Single-prelude code dispatches unambiguously. Importing both
478// preludes in the same file collides on `get_param` - the right
479// error if the file hasn't committed to a precision.
480// ---------------------------------------------------------------------------
481
482/// `f32`-precision parameter reads on `PluginContext`. Brought into
483/// scope by `truce::prelude` / `truce::prelude32` / `truce::prelude64m`
484/// (the `f32`-buffer preludes). GUI binding crates (slint, egui,
485/// iced) take `f32` natively, so this is the common case.
486pub trait PluginContextReadF32 {
487 /// Normalized `[0, 1]` value of the parameter, narrowed to `f32`.
488 fn get_param(&self, id: impl Into<u32>) -> f32;
489 /// Plain (denormalized) value of the parameter, narrowed to `f32`.
490 fn get_param_plain(&self, id: impl Into<u32>) -> f32;
491}
492
493/// `f64`-precision parameter reads on `PluginContext`. Brought into
494/// scope by `truce::prelude64`. Same surface as
495/// [`PluginContextReadF32`] but returns the bridge's `f64` value
496/// directly without narrowing.
497pub trait PluginContextReadF64 {
498 /// Normalized `[0, 1]` value of the parameter.
499 fn get_param(&self, id: impl Into<u32>) -> f64;
500 /// Plain (denormalized) value of the parameter.
501 fn get_param_plain(&self, id: impl Into<u32>) -> f64;
502}
503
504impl<P: ?Sized> PluginContextReadF32 for PluginContext<P> {
505 fn get_param(&self, id: impl Into<u32>) -> f32 {
506 self.bridge.get_param(id.into()).to_f32()
507 }
508 fn get_param_plain(&self, id: impl Into<u32>) -> f32 {
509 self.bridge.get_param_plain(id.into()).to_f32()
510 }
511}
512
513impl<P: ?Sized> PluginContextReadF64 for PluginContext<P> {
514 fn get_param(&self, id: impl Into<u32>) -> f64 {
515 self.bridge.get_param(id.into())
516 }
517 fn get_param_plain(&self, id: impl Into<u32>) -> f64 {
518 self.bridge.get_param_plain(id.into())
519 }
520}