1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
//! Plugin window management
//!
//! This module provides platform-specific window creation and management
//! for VST3 plugin GUIs.
use crate::error::{Error, Result};
use crate::plugin::Plugin;
use std::sync::{Arc, Mutex};
#[cfg(target_os = "macos")]
use objc2::{rc::Retained, MainThreadMarker, MainThreadOnly};
#[cfg(target_os = "macos")]
use objc2_app_kit::{NSBackingStoreType, NSView, NSWindow, NSWindowStyleMask};
#[cfg(target_os = "macos")]
use objc2_foundation::{NSPoint, NSRect, NSSize, NSString};
#[cfg(target_os = "windows")]
use winapi::{
shared::minwindef::{HINSTANCE, LPARAM, LRESULT, UINT, WPARAM},
shared::windef::{HWND, RECT},
um::libloaderapi::GetModuleHandleW,
um::winuser::{
CreateWindowExW, DefWindowProcW, DestroyWindow, LoadCursorW, RegisterClassExW, ShowWindow,
UpdateWindow, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, IDC_ARROW, SW_SHOW, WNDCLASSEXW,
WS_OVERLAPPEDWINDOW,
},
};
/// An X11 window (connection + window id) backing a plugin editor on Linux.
///
/// Ported from the khremeviuc1004 fork's XCB implementation.
#[cfg(target_os = "linux")]
struct XcbWindowState {
connection: xcb::Connection,
window: xcb::x::Window,
}
/// A plugin window that manages the native window and plugin editor lifecycle
pub struct PluginWindow {
plugin: Arc<Mutex<Plugin>>,
#[cfg(target_os = "macos")]
native_window: Option<Retained<NSWindow>>,
#[cfg(target_os = "windows")]
native_window: Option<HWND>,
#[cfg(target_os = "linux")]
native_window: Option<XcbWindowState>,
#[cfg(target_os = "android")]
native_window: Option<()>,
}
impl PluginWindow {
/// Create a new plugin window for the given plugin
pub fn new(plugin: Arc<Mutex<Plugin>>) -> Self {
Self {
plugin,
#[cfg(any(
target_os = "macos",
target_os = "windows",
target_os = "linux",
target_os = "android"
))]
native_window: None,
}
}
/// Open the plugin window
pub fn open(&mut self) -> Result<()> {
// Check if plugin has editor
let has_editor = self
.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.has_editor();
if !has_editor {
return Err(Error::Other(
"Plugin does not have a GUI editor".to_string(),
));
}
// Close existing window if any
if self.is_open() {
self.close();
}
// Get plugin info for window title
let plugin_info = self
.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.info()
.clone();
// Try to get editor size
let (width, height) = self
.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.get_editor_size()
.unwrap_or((800, 600));
// Create native window
#[cfg(target_os = "macos")]
{
// AppKit objects must be created on the main thread.
let mtm = MainThreadMarker::new().ok_or_else(|| {
Error::Other("plugin editor window must be opened on the main thread".to_string())
})?;
let frame = NSRect::new(
NSPoint::new(100.0, 100.0),
NSSize::new(width as f64, height as f64),
);
let style = NSWindowStyleMask::Titled
| NSWindowStyleMask::Closable
| NSWindowStyleMask::Miniaturizable;
// SAFETY: standard AppKit window/view construction on the main thread.
let window = unsafe {
NSWindow::initWithContentRect_styleMask_backing_defer(
NSWindow::alloc(mtm),
frame,
style,
NSBackingStoreType::Buffered,
false,
)
};
// Programmatic NSWindows default to `releasedWhenClosed = YES`; closing one would
// then release it while our `Retained<NSWindow>` also releases on drop — a
// double-free that crashes on close. We own the lifetime, so opt out.
// SAFETY: standard AppKit setter on the main thread.
unsafe { window.setReleasedWhenClosed(false) };
let title = NSString::from_str(&format!("{} - VST3", plugin_info.name));
window.setTitle(&title);
// A container view, sized to the editor, that the plugin attaches its view into.
let container_frame = NSRect::new(
NSPoint::new(0.0, 0.0),
NSSize::new(width as f64, height as f64),
);
let container_view = NSView::initWithFrame(NSView::alloc(mtm), container_frame);
if let Some(content_view) = window.contentView() {
content_view.addSubview(&container_view);
}
// Hand the plugin the container NSView to embed its editor in.
let window_handle = crate::plugin::WindowHandle::from_nsview(Retained::as_ptr(
&container_view,
)
as *mut std::ffi::c_void);
self.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.open_editor(window_handle)?;
// Match the window to the editor size, then show and center it.
window.setContentSize(container_frame.size);
window.makeKeyAndOrderFront(None);
window.center();
self.native_window = Some(window);
}
#[cfg(target_os = "windows")]
{
unsafe {
use std::mem;
use std::ptr;
// Register window class if not already registered
let class_name = "VST3PluginWindow\0".encode_utf16().collect::<Vec<u16>>();
let mut wc: WNDCLASSEXW = mem::zeroed();
wc.cbSize = mem::size_of::<WNDCLASSEXW>() as UINT;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = Some(DefWindowProcW);
wc.hInstance = GetModuleHandleW(ptr::null());
wc.hCursor = LoadCursorW(ptr::null_mut(), IDC_ARROW);
wc.lpszClassName = class_name.as_ptr();
// Try to register, ignore if already registered
RegisterClassExW(&wc);
// Create window
let window_title = format!("{} - VST3\0", plugin_info.name);
let window_name = window_title.encode_utf16().collect::<Vec<u16>>();
// Calculate window size including borders
let mut rect = RECT {
left: 0,
top: 0,
right: width,
bottom: height,
};
winapi::um::winuser::AdjustWindowRectEx(
&mut rect,
WS_OVERLAPPEDWINDOW,
0, // No menu
0, // No extended style
);
let window_width = rect.right - rect.left;
let window_height = rect.bottom - rect.top;
let hwnd = CreateWindowExW(
0,
class_name.as_ptr(),
window_name.as_ptr(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
window_width,
window_height,
ptr::null_mut(),
ptr::null_mut(),
GetModuleHandleW(ptr::null()),
ptr::null_mut(),
);
if hwnd.is_null() {
return Err(Error::Other("Failed to create native window".to_string()));
}
// Try to open plugin editor
let window_handle =
crate::plugin::WindowHandle::from_hwnd(hwnd as *mut std::ffi::c_void);
match self
.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.open_editor(window_handle)
{
Ok(()) => {
ShowWindow(hwnd, SW_SHOW);
UpdateWindow(hwnd);
self.native_window = Some(hwnd);
}
Err(e) => {
DestroyWindow(hwnd);
return Err(e);
}
}
}
}
#[cfg(target_os = "linux")]
{
use xcb::Xid;
// Create an X11 window via XCB and embed the plugin editor into it using the
// VST3 X11EmbedWindowID platform type (handled in plugin_impl::open_editor).
let (connection, screen_number) = xcb::Connection::connect(None)
.map_err(|e| Error::Other(format!("Failed to connect to X server: {e}")))?;
let setup = connection.get_setup();
let screen = setup
.roots()
.nth(screen_number as usize)
.ok_or_else(|| Error::Other("No X11 screen found".to_string()))?;
let window = connection.generate_id();
connection
.send_and_check_request(&xcb::x::CreateWindow {
depth: xcb::x::COPY_FROM_PARENT as u8,
wid: window,
parent: screen.root(),
x: 0,
y: 0,
width: width as u16,
height: height as u16,
border_width: 0,
class: xcb::x::WindowClass::InputOutput,
visual: screen.root_visual(),
value_list: &[
xcb::x::Cw::BackPixel(screen.white_pixel()),
xcb::x::Cw::EventMask(
xcb::x::EventMask::EXPOSURE | xcb::x::EventMask::KEY_PRESS,
),
],
})
.map_err(|e| Error::Other(format!("Failed to create X11 window: {e}")))?;
// Window title.
let title = format!("{} - VST3", plugin_info.name);
connection.send_request(&xcb::x::ChangeProperty {
mode: xcb::x::PropMode::Replace,
window,
property: xcb::x::ATOM_WM_NAME,
r#type: xcb::x::ATOM_STRING,
data: title.as_bytes(),
});
// Show the window, then attach the plugin editor to its X11 id.
connection.send_request(&xcb::x::MapWindow { window });
let _ = connection.flush();
let handle = crate::plugin::WindowHandle::from_x11(window.resource_id());
self.plugin
.lock()
.unwrap_or_else(|p| p.into_inner())
.open_editor(handle)?;
self.native_window = Some(XcbWindowState { connection, window });
}
#[cfg(target_os = "android")]
{
return Err(Error::Other(
"PluginWindow::open() is not supported on Android".to_string(),
));
}
Ok(())
}
/// Close the plugin window
pub fn close(&mut self) {
// Close the plugin editor first
if let Ok(mut plugin) = self.plugin.lock() {
let _ = plugin.close_editor();
}
// Then close the native window
#[cfg(target_os = "macos")]
{
if let Some(window) = self.native_window.take() {
window.close();
}
}
#[cfg(target_os = "windows")]
{
if let Some(hwnd) = self.native_window.take() {
unsafe {
DestroyWindow(hwnd);
}
}
}
#[cfg(target_os = "linux")]
{
if let Some(state) = self.native_window.take() {
state.connection.send_request(&xcb::x::UnmapWindow {
window: state.window,
});
state.connection.send_request(&xcb::x::DestroyWindow {
window: state.window,
});
let _ = state.connection.flush();
}
}
#[cfg(target_os = "android")]
{
let _ = self.native_window.take();
}
}
/// Check if the window is currently open
pub fn is_open(&self) -> bool {
self.native_window.is_some()
}
}
impl Drop for PluginWindow {
fn drop(&mut self) {
self.close();
}
}
/// Builder for creating plugin windows with egui integration
#[cfg(feature = "egui-widgets")]
pub struct PluginWindowBuilder {
plugin: Arc<Mutex<Plugin>>,
}
#[cfg(feature = "egui-widgets")]
impl PluginWindowBuilder {
/// Create a new builder for the given plugin
pub fn new(plugin: Arc<Mutex<Plugin>>) -> Self {
Self { plugin }
}
/// Build and open a standalone plugin window
pub fn open_standalone(&self) -> Result<PluginWindow> {
let mut window = PluginWindow::new(self.plugin.clone());
window.open()?;
Ok(window)
}
}