Skip to main content

aura_editor/
lib.rs

1//! AURA host-facing **Editor** layer.
2//!
3//! [`AuraSlintEditor`] adapts a Slint component (living on the
4//! [`aura_baseview`] window stack) to [`aura_core::editor::Editor`], so format
5//! wrappers (CLAP / VST3 / LV2) can parent it into a host window.
6//!
7//! Window/platform/renderers stay in **`aura-baseview`** (re-exported here);
8//! only the host adapter couples to `aura-core`.
9//!
10//! # Example
11//!
12//! ```ignore
13//! use aura_editor::AuraSlintEditor;
14//!
15//! fn editor(_params: Arc<MyParams>) -> Option<Box<dyn Editor>> {
16//!     Some(
17//!         AuraSlintEditor::new(
18//!             (800, 600),
19//!             |ctx| {
20//!                 let ui = MyPluginUi::new().unwrap();
21//!                 // wire ui callbacks → ctx.bridge / ctx.params …
22//!                 ui
23//!             },
24//!             |ui, ctx| {
25//!                 // per-frame: push host param values into the component
26//!             },
27//!         )
28//!         .into_editor(),
29//!     )
30//! }
31//! ```
32
33mod parent;
34pub mod typed;
35pub mod ui_zoom;
36
37use std::sync::Arc;
38use std::sync::atomic::{AtomicU64, Ordering};
39
40use baseview::WindowSettings;
41use slint::ComponentHandle;
42
43use aura_core::editor::{Editor, PluginContext, RawWindowHandle};
44
45pub(crate) fn map_baseview_handle(
46    raw: Option<raw_window_handle::RawWindowHandle>,
47) -> Option<RawWindowHandle> {
48    use raw_window_handle::RawWindowHandle as Rwh;
49    raw.and_then(|h| match h {
50        #[cfg(target_os = "windows")]
51        Rwh::Win32(h) => Some(RawWindowHandle::Win32(h.hwnd.get() as *mut std::ffi::c_void)),
52        #[cfg(target_os = "macos")]
53        Rwh::AppKit(h) => Some(RawWindowHandle::AppKit(h.ns_view.as_ptr())),
54        #[cfg(target_os = "linux")]
55        Rwh::Xlib(h) => Some(RawWindowHandle::X11(h.window)),
56        _ => None,
57    })
58}
59
60// Window stack (Slint + baseview + renderer backends) stays reachable
61// through this crate so plugin authors need one UI dependency. Also brings
62// `SlintWindow`, `SizePolicy`, `EditorScale`, … into local scope.
63#[allow(unused_imports)]
64pub use aura_baseview::*;
65
66/// Build closure: creates the Slint component and wires UI callbacks.
67/// Called once when the host opens the editor.
68pub type BuildFn<C> = Arc<dyn Fn(PluginContext) -> C + Send + Sync>;
69
70/// Per-frame sync closure: pushes host parameter values into the component.
71pub type SyncFn<C> = Arc<dyn Fn(&C, &PluginContext) + Send + Sync>;
72
73/// Slint-based editor implementing [`aura_core::editor::Editor`].
74///
75/// Generic over the concrete Slint component type, because the GPU-backed
76/// [`SlintWindow`] needs to own the generated component.
77pub struct AuraSlintEditor<C>
78where
79    C: ComponentHandle + 'static,
80{
81    /// Design logical size (layout coordinates — host frame in v1).
82    design_size: (u32, u32),
83    build: BuildFn<C>,
84    sync: SyncFn<C>,
85    window: Option<SlintParentedWindow>,
86    can_resize: bool,
87    min_size: (u32, u32),
88    max_size: (u32, u32),
89    /// Shared content-scale cell (host `set_scale` ↔ window handler).
90    scale: EditorScale,
91    /// Packed design logical size for handler reconcile after host `set_size`.
92    pending_size: Arc<AtomicU64>,
93    /// Native widget handle of the opened child window, if available.
94    native_handle: Option<RawWindowHandle>,
95}
96
97// SAFETY: baseview::Window holds raw native window pointers (HWND/NSView)
98// and is not auto-Send. Hosts call Editor::open/close from a single GUI
99// thread, never concurrently. Same pattern as truce-slint.
100unsafe impl<C> Send for AuraSlintEditor<C> where C: ComponentHandle + 'static {}
101
102impl<C> AuraSlintEditor<C>
103where
104    C: ComponentHandle + 'static,
105{
106    /// Create a new editor adapter.
107    ///
108    /// - `size` is the fixed design size in logical pixels.
109    /// - `build` is called once when the host opens the editor. It receives a
110    ///   [`PluginContext`] (params + optional host bridge) and must return
111    ///   the concrete Slint component.
112    /// - `sync` is called every frame to copy host parameter values into the
113    ///   component.
114    pub fn new(
115        size: (u32, u32),
116        build: impl Fn(PluginContext) -> C + Send + Sync + 'static,
117        sync: impl Fn(&C, &PluginContext) + Send + Sync + 'static,
118    ) -> Self {
119        Self {
120            design_size: size,
121            build: Arc::new(build),
122            sync: Arc::new(sync),
123            window: None,
124            can_resize: false,
125            min_size: size,
126            max_size: size,
127            scale: EditorScale::new(1.0),
128            pending_size: Arc::new(AtomicU64::new(0)),
129            native_handle: None,
130        }
131    }
132
133    /// Report resizability to the host. Set real bounds with
134    /// [`Self::with_min_size`] / [`Self::with_max_size`].
135    #[must_use]
136    pub fn resizable(mut self, value: bool) -> Self {
137        self.can_resize = value;
138        self
139    }
140
141    #[must_use]
142    pub fn with_min_size(mut self, min: (u32, u32)) -> Self {
143        self.min_size = min;
144        self
145    }
146
147    #[must_use]
148    pub fn with_max_size(mut self, max: (u32, u32)) -> Self {
149        self.max_size = max;
150        self
151    }
152
153    fn size_policy(&self) -> SizePolicy {
154        // Plugins: content scale is host `set_scale` only (default 1.0),
155        // never raw OS DPI — CLAP/VST3 report HWND size as size() × host
156        // scale, so the child must match that, not GetDpiForWindow/Xft.dpi.
157        SizePolicy {
158            design_size: self.design_size,
159            min_size: self.min_size,
160            max_size: self.max_size,
161            can_resize: self.can_resize,
162            scale: self.scale.clone(),
163            host_driven_scale: true,
164            pending_size: Arc::clone(&self.pending_size),
165        }
166    }
167}
168
169impl<C> Editor for AuraSlintEditor<C>
170where
171    C: ComponentHandle + 'static,
172{
173    fn size(&self) -> (u32, u32) {
174        self.design_size
175    }
176
177    fn open(&mut self, parent: RawWindowHandle, context: PluginContext) {
178        // Drop previous window if host re-opens without close.
179        self.close();
180
181        // Reset stale set_size / native handle from a previous open.
182        self.pending_size.store(0, Ordering::Relaxed);
183        self.native_handle = None;
184
185        let parent_window = parent::ParentedWindow::from_raw(parent);
186
187        // Physical = design × host scale.
188        let (dw, dh) = self.design_size;
189        let content_scale = self.scale.get();
190        let phys_w = to_physical_px(dw, content_scale);
191        let phys_h = to_physical_px(dh, content_scale);
192
193        // FemtoVG-GL needs OpenGL (baseview opengl feature). Other backends
194        // must not require GlConfig — it is cfg'd behind baseview/opengl.
195        let options = WindowSettings::new()
196            .with_title("AURA")
197            .with_size(baseview::dpi::PhysicalSize::new(phys_w, phys_h));
198        #[cfg(feature = "backend-femtovg-gl")]
199        let options = options.with_gl_config(baseview::gl::GlConfig {
200            alpha_bits: 8,
201            ..baseview::gl::GlConfig::default()
202        });
203
204        let build = Arc::clone(&self.build);
205        let sync = Arc::clone(&self.sync);
206        let policy = self.size_policy();
207
208        // Host resize requests go through the bridge (CLAP gui_request_resize).
209        let request_resize: Option<RequestResizeFn> = context.bridge.clone().map(|bridge| {
210            Arc::new(move |w: u32, h: u32| bridge.request_resize(w, h)) as RequestResizeFn
211        });
212
213        let window = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
214            slint_window::SlintWindow::open_parented_with_policy(
215                &parent_window,
216                options,
217                context,
218                move |state: &mut PluginContext| build(state.clone()),
219                move |component: &C, state: &mut PluginContext| sync(component, state),
220                policy,
221                request_resize,
222            )
223        }));
224
225        match window {
226            Ok(Ok(w)) => {
227                let _ = w.resize(baseview::dpi::Size::Physical(
228                    baseview::dpi::PhysicalSize::new(phys_w, phys_h),
229                ));
230                self.native_handle = map_baseview_handle(w.raw_handle());
231                self.window = Some(w);
232            }
233            // Soft-fail: editor stays closed; DSP continues. Typical on old
234            // Linux/mac without OpenGL 3.2 Core / broken GLX embeds.
235            Ok(Err(e)) => {
236                log::error!(
237                    "AURA UI: window open failed ({e}) — editor left closed, audio still runs"
238                );
239            }
240            Err(_) => {
241                log::error!(
242                    "AURA UI: window open panicked — editor left closed, audio still runs. \
243                     Need OpenGL 3.2 Core (or newer) for the FemtoVG backend."
244                );
245            }
246        }
247    }
248
249    fn close(&mut self) {
250        if let Some(window) = self.window.take() {
251            window.close();
252        }
253        self.native_handle = None;
254    }
255
256    fn show(&mut self) {
257        if let Some(window) = &self.window {
258            let _ = window.show();
259        }
260    }
261
262    fn hide(&mut self) {
263        if let Some(window) = &self.window {
264            let _ = window.hide();
265        }
266    }
267
268    fn can_resize(&self) -> bool {
269        self.can_resize
270    }
271
272    fn min_size(&self) -> (u32, u32) {
273        self.min_size
274    }
275
276    fn max_size(&self) -> (u32, u32) {
277        self.max_size
278    }
279
280    fn set_scale(&mut self, scale: f64) {
281        self.scale.set(scale);
282    }
283
284    fn idle(&mut self) {
285        // X11 needs main-thread callbacks pumped; Windows/macOS are no-ops.
286        if let Some(window) = &mut self.window {
287            window.host_main_thread_callback();
288        }
289    }
290
291    fn native_handle(&self) -> Option<RawWindowHandle> {
292        self.native_handle
293    }
294
295    fn set_size(&mut self, width: u32, height: u32) -> bool {
296        if width == 0 || height == 0 {
297            return false;
298        }
299        if self.can_resize {
300            let (w, h) = aura_baseview::fit_size(width, height, self.min_size, self.max_size);
301            self.design_size = (w, h);
302            self.pending_size
303                .store(pack_size((w, h)), Ordering::Release);
304            return true;
305        }
306        // Fixed layout: host set_size from multi-monitor / pane chrome must
307        // NOT reflow the scene. Re-assert design logical for Slint.
308        if (width, height) != self.design_size {
309            self.pending_size
310                .store(pack_size(self.design_size), Ordering::Release);
311            return false;
312        }
313        true
314    }
315}
316
317impl<C> From<AuraSlintEditor<C>> for Box<dyn Editor>
318where
319    C: ComponentHandle + 'static,
320{
321    fn from(editor: AuraSlintEditor<C>) -> Self {
322        Box::new(editor)
323    }
324}