DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DSParkWebViewEditor.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
67#if defined(DSPARK_PLUGIN_VST3_INCLUDED) || defined(DSPARK_PLUGIN_CLAP_INCLUDED) \
68 || defined(DSPARK_PLUGIN_AU_INCLUDED)
69#error "Include plugin/webview/DSParkWebViewEditor.h BEFORE the plugin format headers"
70#endif
71
72#define DSPARK_PLUGIN_WEBVIEW 1
73
74#include "../DSParkPlugin.h"
75
76#include <atomic>
77#include <cmath>
78#include <cstdarg>
79#include <cstdio>
80#include <cstdlib>
81#include <cstring>
82#include <string>
83
84// -- platform backend selection --------------------------------------------------
85//
86// DSPARK_WEBVIEW_BACKEND: 1 = WebView2 via vendored webview.h (Windows),
87// 2 = WKWebView via the Objective-C runtime (macOS),
88// 3 = WebKitGTK via dlopen + GtkPlug/XEmbed (Linux/X11),
89// 0 = stub (editor reports unavailable).
90
91#if defined(_WIN32) && !defined(DSPARK_NO_EXCEPTIONS) \
92 && (defined(__cpp_exceptions) || (defined(_CPPUNWIND) && _CPPUNWIND))
93 #define DSPARK_WEBVIEW_BACKEND 1
94 #ifndef NOMINMAX
95 #define NOMINMAX // webview.h pulls <windows.h>; keep min/max sane
96 #endif
97 #if defined(_MSC_VER)
98 #pragma warning(push, 1)
99 #endif
100 #include "webview/webview.h"
101 #if defined(_MSC_VER)
102 #pragma warning(pop)
103 #endif
104 #include <commctrl.h> // SetWindowSubclass: follow host resizes reliably
105 #if defined(_MSC_VER)
106 #pragma comment(lib, "comctl32.lib")
107 #endif
108 #include <memory>
109#elif defined(__APPLE__)
110 #define DSPARK_WEBVIEW_BACKEND 2
111 #include <objc/message.h>
112 #include <objc/runtime.h>
113 #include <dlfcn.h>
114 #include <cstdint>
115#elif defined(__linux__)
116 #define DSPARK_WEBVIEW_BACKEND 3
117 #include <dlfcn.h>
118 #include <cstdint>
119 #include <type_traits>
120#else
121 #define DSPARK_WEBVIEW_BACKEND 0
122#endif
123
125
126// -- diagnostics -------------------------------------------------------------------
127//
128// Set the environment variable DSPARK_WEBVIEW_LOG to any non-empty value and
129// every editor in the process appends its host-interaction trace (attach,
130// size negotiation, parent resizes) to %TEMP%/DSParkWebView.log (or
131// $TMPDIR on POSIX). Costs nothing when the variable is absent.
132
133inline void debugLog(const char* format, ...) noexcept
134{
135 static std::FILE* file = []() -> std::FILE* {
136 char enabled[8] {};
137#if DSPARK_WEBVIEW_BACKEND == 1
138 if (GetEnvironmentVariableA("DSPARK_WEBVIEW_LOG", enabled,
139 sizeof(enabled)) == 0)
140 return nullptr;
141 char dir[MAX_PATH] {};
142 if (GetEnvironmentVariableA("TEMP", dir, sizeof(dir)) == 0)
143 dir[0] = '\0';
144 char path[MAX_PATH + 32];
145 std::snprintf(path, sizeof(path), "%s%sDSParkWebView.log",
146 dir, dir[0] != '\0' ? "\\" : "");
147 std::FILE* f = nullptr;
148 fopen_s(&f, path, "a");
149#elif defined(_WIN32)
150 // Stub backend on Windows (exceptions off): no <windows.h> here and
151 // no editor to trace, so the log stays off.
152 (void) enabled;
153 std::FILE* f = nullptr;
154#else
155 const char* env = std::getenv("DSPARK_WEBVIEW_LOG");
156 if (env == nullptr || env[0] == '\0') return nullptr;
157 (void) enabled;
158 const char* dir = std::getenv("TMPDIR");
159 char path[512];
160 std::snprintf(path, sizeof(path), "%s/DSParkWebView.log",
161 dir != nullptr ? dir : "/tmp");
162 std::FILE* f = std::fopen(path, "a");
163#endif
164 if (f != nullptr)
165 std::fprintf(f, "\n== editor session (layer built " __DATE__ " " __TIME__ ") ==\n");
166 return f;
167 }();
168 if (file == nullptr) return;
169 std::va_list args;
170 va_start(args, format);
171 std::vfprintf(file, format, args);
172 va_end(args);
173 std::fputc('\n', file);
174 std::fflush(file);
175}
176
177// -- JSON utilities ---------------------------------------------------------------
178//
179// The bridge protocol is small enough that a focused, locale-independent
180// formatter/parser beats dragging in a JSON library: host processes may run
181// with any LC_NUMERIC, where printf writes "6,5" (invalid JSON) and strtod
182// stops at the '.' - both classic plugin bugs.
183
185inline void appendJsonString(std::string& out, const char* s)
186{
187 out += '"';
188 for (const char* c = s; c != nullptr && *c != '\0'; ++c)
189 {
190 const unsigned char u = static_cast<unsigned char>(*c);
191 switch (u)
192 {
193 case '"': out += "\\\""; break;
194 case '\\': out += "\\\\"; break;
195 case '\n': out += "\\n"; break;
196 case '\r': out += "\\r"; break;
197 case '\t': out += "\\t"; break;
198 default:
199 if (u < 0x20)
200 {
201 char buf[8];
202 std::snprintf(buf, sizeof(buf), "\\u%04x", u);
203 out += buf;
204 }
205 else
206 out += static_cast<char>(u);
207 break;
208 }
209 }
210 out += '"';
211}
212
214inline void appendJsonNumber(std::string& out, double v)
215{
216 if (!std::isfinite(v))
217 {
218 out += '0';
219 return;
220 }
221 char buf[40];
222 std::snprintf(buf, sizeof(buf), "%.17g", v);
223 for (char* c = buf; *c != '\0'; ++c)
224 if (*c == ',') *c = '.'; // locale decimal comma -> JSON dot
225 out += buf;
226}
227
229inline const char* parseJsonNumber(const char* s, double& out) noexcept
230{
231 bool negative = false;
232 if (*s == '-' || *s == '+')
233 {
234 negative = (*s == '-');
235 ++s;
236 }
237 double v = 0.0;
238 bool any = false;
239 while (*s >= '0' && *s <= '9')
240 {
241 v = v * 10.0 + (*s - '0');
242 ++s;
243 any = true;
244 }
245 if (*s == '.')
246 {
247 ++s;
248 double f = 0.1;
249 while (*s >= '0' && *s <= '9')
250 {
251 v += (*s - '0') * f;
252 f *= 0.1;
253 ++s;
254 any = true;
255 }
256 }
257 if (!any) return nullptr;
258 if (*s == 'e' || *s == 'E')
259 {
260 ++s;
261 bool expNegative = false;
262 if (*s == '-' || *s == '+')
263 {
264 expNegative = (*s == '-');
265 ++s;
266 }
267 int e = 0;
268 bool eAny = false;
269 while (*s >= '0' && *s <= '9')
270 {
271 e = e * 10 + (*s - '0');
272 ++s;
273 eAny = true;
274 if (e > 308) { e = 309; } // saturate; isfinite check downstream
275 }
276 if (!eAny) return nullptr;
277 v *= std::pow(10.0, expNegative ? -e : e);
278 }
279 out = negative ? -v : v;
280 return s;
281}
282
285{
286 char op[12] {};
287 char id[64] {};
288 double value = 0.0;
289 int tokens = 0;
290};
291
293inline bool parsePostArgs(const char* s, PostArgs& out) noexcept
294{
295 auto skipWs = [&s] { while (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r') ++s; };
296 auto readString = [&s](char* dst, size_t cap) -> bool
297 {
298 ++s; // opening quote
299 size_t n = 0;
300 while (*s != '\0' && *s != '"')
301 {
302 char c = *s++;
303 if (c == '\\')
304 {
305 const char esc = *s++;
306 switch (esc)
307 {
308 case '"': c = '"'; break;
309 case '\\': c = '\\'; break;
310 case '/': c = '/'; break;
311 case 'n': c = '\n'; break;
312 case 'r': c = '\r'; break;
313 case 't': c = '\t'; break;
314 case 'b': c = '\b'; break;
315 case 'f': c = '\f'; break;
316 case 'u':
317 {
318 unsigned code = 0;
319 for (int k = 0; k < 4; ++k)
320 {
321 const char h = *s;
322 if (h >= '0' && h <= '9') code = code * 16 + unsigned(h - '0');
323 else if (h >= 'a' && h <= 'f') code = code * 16 + unsigned(h - 'a' + 10);
324 else if (h >= 'A' && h <= 'F') code = code * 16 + unsigned(h - 'A' + 10);
325 else return false;
326 ++s;
327 }
328 c = code < 128 ? static_cast<char>(code) : '?';
329 break;
330 }
331 case '\0': return false;
332 default: return false;
333 }
334 }
335 if (n + 1 < cap) dst[n++] = c;
336 }
337 if (*s != '"') return false;
338 ++s;
339 dst[n] = '\0';
340 return true;
341 };
342
343 out = PostArgs {};
344 skipWs();
345 if (*s != '[') return false;
346 ++s;
347 for (;;)
348 {
349 skipWs();
350 if (*s == ']') { ++s; return true; }
351 if (out.tokens > 0)
352 {
353 if (*s != ',') return false;
354 ++s;
355 skipWs();
356 }
357 if (*s == '"')
358 {
359 char* dst = out.tokens == 0 ? out.op : out.id;
360 const size_t cap = out.tokens == 0 ? sizeof(out.op) : sizeof(out.id);
361 if (out.tokens >= 2 || !readString(dst, cap)) return false;
362 }
363 else if (*s == 't' || *s == 'f' || *s == 'n')
364 {
365 // true/false/null can only appear as the value slot.
366 out.value = (*s == 't') ? 1.0 : 0.0;
367 while ((*s >= 'a' && *s <= 'z')) ++s;
368 }
369 else
370 {
371 const char* end = parseJsonNumber(s, out.value);
372 if (end == nullptr) return false;
373 s = end;
374 }
375 ++out.tokens;
376 if (out.tokens > 3) return false;
377 }
378}
379
380// -- the injected JS bridge ---------------------------------------------------------
381//
382// Runs at document start, before the page's own scripts. `__dsparkPost` is
383// the platform-provided uplink (a bound RPC on Windows, a WebKit message
384// handler wrapper on macOS); `__dsparkRecv` is the downlink the native side
385// drives through script evaluation. Everything user-facing lives in
386// `window.dspark`. The ~30 Hz poll starts after the native side answers the
387// "ready" handshake, and listeners replay the cached value on registration,
388// so page and native initialisation order can never race.
389
390inline constexpr const char* kBridgeJs =
391 "(function(){'use strict';"
392 "if(window.dspark){return;}"
393 "var ls={},vals={},meta=null,readyCbs=[],seq=0,lastSet={};"
394 "function fire(id,v){var c=ls[id];if(c){for(var i=0;i<c.length;i++){c[i](v);}}}"
395 "window.__dsparkRecv=function(m){"
396 "if(m.type==='params'){"
397 "meta=m.params;"
398 "for(var i=0;i<meta.length;i++){vals[meta[i].id]=meta[i].value;}"
399 // KeepAspect editors scale their whole content with the window:
400 // the page keeps its DESIGN layout and is fitted into the window
401 // by the limiting axis, centered (letterboxed) when the host lets
402 // the user distort the ratio. Nothing can ever clip.
403 "if(m.design&&m.design.keepAspect&&!window.__dsparkFit){"
404 "var dw=m.design.width,dh=m.design.height;"
405 "window.__dsparkFit=function(){"
406 "var z=Math.min(window.innerWidth/dw,window.innerHeight/dh);"
407 "if(!(z>0&&isFinite(z))){z=1;}"
408 "var s=document.body.style;"
409 "s.width=dw+'px';s.height=dh+'px';"
410 "s.position='absolute';s.margin='0';"
411 "s.transformOrigin='0 0';s.transform='scale('+z+')';"
412 "s.left=((window.innerWidth-dw*z)/2)+'px';"
413 "s.top=((window.innerHeight-dh*z)/2)+'px';};"
414 "window.addEventListener('resize',window.__dsparkFit);"
415 "window.__dsparkFit();}"
416 "var rc=readyCbs;readyCbs=[];"
417 "for(var j=0;j<rc.length;j++){rc[j](meta);}"
418 "for(var k=0;k<meta.length;k++){fire(meta[k].id,meta[k].value);}"
419 "if(!window.__dsparkTimer){"
420 "window.__dsparkTimer=setInterval(function(){window.__dsparkPost('poll','',seq);},33);}"
421 "}else if(m.type==='values'){"
422 "for(var id in m.values){"
423 // A reply snapshotted before this page's latest edit of an id
424 // must not move it back (a knob jumping to its previous value
425 // mid-drag).
426 "if(lastSet[id]!==undefined&&lastSet[id]>(m.seq||0)){continue;}"
427 "if(vals[id]!==m.values[id]){vals[id]=m.values[id];fire(id,m.values[id]);}}"
428 "}};"
429 "window.dspark={"
430 "setParam:function(id,v){v=+v;lastSet[id]=++seq;vals[id]=v;window.__dsparkPost('set',id,v);fire(id,v);},"
431 "getParam:function(id){return vals[id];},"
432 "beginEdit:function(id){window.__dsparkPost('begin',id);},"
433 "endEdit:function(id){window.__dsparkPost('end',id);},"
434 "onParam:function(id,cb){(ls[id]=ls[id]||[]).push(cb);"
435 "if(meta!==null&&(id in vals)){cb(vals[id]);}},"
436 "onReady:function(cb){if(meta!==null){cb(meta);}else{readyCbs.push(cb);}}"
437 "};"
438 "Object.defineProperty(window.dspark,'params',{get:function(){return meta;}});"
439 "function hello(){window.__dsparkPost('ready');}"
440 "if(document.readyState==='complete'||document.readyState==='interactive'){hello();}"
441 "else{document.addEventListener('DOMContentLoaded',hello);}"
442 "})();";
443
444// -- host callbacks ----------------------------------------------------------------
445
453{
454 void* context = nullptr;
455 void (*setParam)(void* context, int index, double plainValue) = nullptr;
456 void (*beginEdit)(void* context, int index) = nullptr;
457 void (*endEdit)(void* context, int index) = nullptr;
458};
459
460#if DSPARK_WEBVIEW_BACKEND == 2
461
462// -- macOS: minimal Objective-C runtime glue ---------------------------------------
463//
464// WKWebView is driven entirely through objc_msgSend, so no Apple GUI headers
465// or link flags are needed; WebKit.framework is loaded on first use. The
466// script-message relay is ONE runtime-registered class shared by every
467// editor in the process: its ivar holds a {function, context} sink, keeping
468// the IMP free of template types (two different plugins in one host would
469// otherwise race to register the same class name with different code).
470
471namespace objc_glue {
472
473using ObjId = void*;
474
475template <typename Ret = ObjId, typename... Args>
476inline Ret call(ObjId target, const char* selector, Args... args) noexcept
477{
478 using Fn = Ret (*)(ObjId, SEL, Args...);
479 return reinterpret_cast<Fn>(&objc_msgSend)(target, sel_registerName(selector), args...);
480}
481
482inline ObjId cls(const char* name) noexcept
483{
484 return reinterpret_cast<ObjId>(objc_getClass(name));
485}
486
487inline ObjId nsString(const char* utf8) noexcept
488{
489 return call(cls("NSString"), "stringWithUTF8String:", utf8 ? utf8 : "");
490}
491
492struct Rect { double x = 0, y = 0, w = 0, h = 0; }; // CGRect-compatible
493
501inline void imageUniqueClassName(const char* base, char* out, size_t cap) noexcept
502{
503 static const char anchor = 0; // one per image (inline: merged within it)
504 std::snprintf(out, cap, "%s_%llx", base,
505 static_cast<unsigned long long>(reinterpret_cast<std::uintptr_t>(&anchor)));
506}
507
508struct MessageSink
509{
510 void (*fn)(void* context, const char* json) = nullptr;
511 void* context = nullptr;
512};
513
514inline Class relayClass() noexcept;
515
516inline void onScriptMessage(ObjId self, SEL, ObjId, ObjId message) noexcept
517{
518 Ivar ivar = class_getInstanceVariable(relayClass(), "dsparkSink");
519 if (ivar == nullptr) return;
520 auto* sink = reinterpret_cast<MessageSink*>(
521 object_getIvar(static_cast<id>(self), ivar));
522 if (sink == nullptr || sink->fn == nullptr) return;
523 ObjId body = call(message, "body");
524 if (body == nullptr) return;
525 const char* utf8 = call<const char*>(body, "UTF8String");
526 if (utf8 != nullptr)
527 sink->fn(sink->context, utf8);
528}
529
530inline Class relayClass() noexcept
531{
532 static Class registered = [] {
533 static char name[96];
534 imageUniqueClassName("DSParkWebViewMessageRelay", name, sizeof(name));
535 Class c = objc_allocateClassPair(objc_getClass("NSObject"), name, 0);
536 if (c == nullptr) // this image registered it already
537 return objc_getClass(name);
538 class_addIvar(c, "dsparkSink", sizeof(void*), alignof(void*) == 8 ? 3 : 2, "^v");
539 class_addMethod(c, sel_registerName("userContentController:didReceiveScriptMessage:"),
540 reinterpret_cast<IMP>(&onScriptMessage), "v@:@@");
541 objc_registerClassPair(c);
542 return c;
543 }();
544 return registered;
545}
546
547inline void setRelaySink(ObjId relay, MessageSink* sink) noexcept
548{
549 Ivar ivar = class_getInstanceVariable(relayClass(), "dsparkSink");
550 if (ivar != nullptr)
551 object_setIvar(static_cast<id>(relay), ivar, reinterpret_cast<id>(sink));
552}
553
554inline bool loadWebKit() noexcept
555{
556 static void* handle =
557 dlopen("/System/Library/Frameworks/WebKit.framework/WebKit", RTLD_LAZY | RTLD_GLOBAL);
558 return handle != nullptr;
559}
560
561} // namespace objc_glue
562
563#endif // DSPARK_WEBVIEW_BACKEND == 2
564
565#if DSPARK_WEBVIEW_BACKEND == 3
566
567// -- Linux: WebKitGTK resolved at runtime -------------------------------------------
568//
569// Every entry point comes from ONE dlopen of libwebkit2gtk (GTK3, GLib and
570// JavaScriptCore are its dependencies, so dlsym on that handle resolves them
571// all): no GTK headers, no pkg-config, no link-time dependency - plugins
572// keep building with the plain C++ toolchain and simply report the editor
573// unavailable where WebKitGTK is missing. GTK3 is required for GtkPlug
574// (XEmbed into the host's X11 window); GTK4 removed it, which is why the
575// 4.x webkit2gtk line is used and not webkitgtk-6.0.
576
577namespace gtk_glue {
578
581struct Api
582{
583 bool ok = false;
584 // GTK3 / GLib / GObject
585 int (*gtkInitCheck)(int*, char***) = nullptr;
586 void* (*plugNew)(unsigned long) = nullptr;
587 void (*containerAdd)(void*, void*) = nullptr;
588 void (*widgetShowAll)(void*) = nullptr;
589 void (*widgetSetVisible)(void*, int) = nullptr;
590 void (*widgetDestroy)(void*) = nullptr;
591 void (*windowSetDefaultSize)(void*, int, int) = nullptr;
592 void (*windowResize)(void*, int, int) = nullptr;
593 unsigned long (*signalConnectData)(void*, const char*, void (*)(), void*,
594 void*, int) = nullptr;
595 void (*signalHandlerDisconnect)(void*, unsigned long) = nullptr;
596 int (*mainContextPending)(void*) = nullptr;
597 int (*mainContextIteration)(void*, int) = nullptr;
598 void (*gFree)(void*) = nullptr;
599 // WebKit
600 void* (*webViewNew)() = nullptr;
601 void* (*viewGetContentManager)(void*) = nullptr;
602 int (*contentManagerRegisterHandler)(void*, const char*) = nullptr;
603 void (*contentManagerUnregisterHandler)(void*, const char*) = nullptr;
604 void* (*userScriptNew)(const char*, int, int, const char* const*,
605 const char* const*) = nullptr;
606 void (*contentManagerAddScript)(void*, void*) = nullptr;
607 void (*userScriptUnref)(void*) = nullptr;
608 void (*loadHtml)(void*, const char*, const char*) = nullptr;
609 // JS eval: run_javascript exists on every 4.0/4.1 (deprecated since
610 // 2.40); evaluate_javascript replaces it from 2.40 on. Either works.
611 void (*runJs)(void*, const char*, void*, void*, void*) = nullptr;
612 void (*evalJs)(void*, const char*, long, const char*, const char*,
613 void*, void*, void*) = nullptr;
614 void* (*jsResultGetValue)(void*) = nullptr;
615 char* (*jscValueToString)(void*) = nullptr;
616};
617
618inline Api loadApi() noexcept
619{
620 Api api {};
621 void* lib = dlopen("libwebkit2gtk-4.1.so.0", RTLD_LAZY | RTLD_LOCAL);
622 if (lib == nullptr)
623 lib = dlopen("libwebkit2gtk-4.0.so.37", RTLD_LAZY | RTLD_LOCAL);
624 if (lib == nullptr)
625 {
626 debugLog("linux engine: libwebkit2gtk not found (generic UI)");
627 return api;
628 }
629 auto load = [lib](auto& fn, const char* name) {
630 fn = reinterpret_cast<std::remove_reference_t<decltype(fn)>>(dlsym(lib, name));
631 };
632 load(api.gtkInitCheck, "gtk_init_check");
633 load(api.plugNew, "gtk_plug_new");
634 load(api.containerAdd, "gtk_container_add");
635 load(api.widgetShowAll, "gtk_widget_show_all");
636 load(api.widgetSetVisible, "gtk_widget_set_visible");
637 load(api.widgetDestroy, "gtk_widget_destroy");
638 load(api.windowSetDefaultSize, "gtk_window_set_default_size");
639 load(api.windowResize, "gtk_window_resize");
640 load(api.signalConnectData, "g_signal_connect_data");
641 load(api.signalHandlerDisconnect, "g_signal_handler_disconnect");
642 load(api.mainContextPending, "g_main_context_pending");
643 load(api.mainContextIteration, "g_main_context_iteration");
644 load(api.gFree, "g_free");
645 load(api.webViewNew, "webkit_web_view_new");
646 load(api.viewGetContentManager, "webkit_web_view_get_user_content_manager");
647 load(api.contentManagerRegisterHandler,
648 "webkit_user_content_manager_register_script_message_handler");
649 load(api.contentManagerUnregisterHandler,
650 "webkit_user_content_manager_unregister_script_message_handler");
651 load(api.userScriptNew, "webkit_user_script_new");
652 load(api.contentManagerAddScript, "webkit_user_content_manager_add_script");
653 load(api.userScriptUnref, "webkit_user_script_unref");
654 load(api.loadHtml, "webkit_web_view_load_html");
655 load(api.runJs, "webkit_web_view_run_javascript");
656 load(api.evalJs, "webkit_web_view_evaluate_javascript");
657 load(api.jsResultGetValue, "webkit_javascript_result_get_js_value");
658 load(api.jscValueToString, "jsc_value_to_string");
659 api.ok = api.gtkInitCheck != nullptr && api.plugNew != nullptr
660 && api.containerAdd != nullptr && api.widgetShowAll != nullptr
661 && api.widgetSetVisible != nullptr && api.widgetDestroy != nullptr
662 && api.windowSetDefaultSize != nullptr && api.windowResize != nullptr
663 && api.signalConnectData != nullptr
664 && api.signalHandlerDisconnect != nullptr
665 && api.mainContextPending != nullptr
666 && api.mainContextIteration != nullptr && api.gFree != nullptr
667 && api.webViewNew != nullptr && api.viewGetContentManager != nullptr
668 && api.contentManagerRegisterHandler != nullptr
669 && api.contentManagerUnregisterHandler != nullptr
670 && api.userScriptNew != nullptr
671 && api.contentManagerAddScript != nullptr
672 && api.userScriptUnref != nullptr && api.loadHtml != nullptr
673 && (api.runJs != nullptr || api.evalJs != nullptr)
674 && api.jsResultGetValue != nullptr && api.jscValueToString != nullptr;
675 if (!api.ok)
676 debugLog("linux engine: libwebkit2gtk found but symbols missing");
677 return api;
678}
679
681inline const Api& api() noexcept
682{
683 static const Api loaded = loadApi();
684 return loaded;
685}
686
687} // namespace gtk_glue
688
689#endif // DSPARK_WEBVIEW_BACKEND == 3
690
691// -- the editor --------------------------------------------------------------------
692
705template <typename P>
707{
708public:
709 static_assert(!HasEditor<P> || HasEditorHtml<P>,
710 "hasEditor is true but `static const char* editorHtml()` is missing");
711
713 static constexpr bool kAvailable = (DSPARK_WEBVIEW_BACKEND != 0);
714
722 static bool available() noexcept
723 {
724#if DSPARK_WEBVIEW_BACKEND == 3
725 return gtk_glue::api().ok;
726#else
727 return kAvailable;
728#endif
729 }
730
738 void pump() noexcept
739 {
740#if DSPARK_WEBVIEW_BACKEND == 3
741 if (created_)
742 pumpPlatform();
743#endif
744 }
745
746 Editor() = default;
748
749 Editor(const Editor&) = delete;
750 Editor& operator=(const Editor&) = delete;
751
759 bool create(void* parentWindow, const std::atomic<double>* shadows,
760 const HostCallbacks& host) noexcept
761 {
762 if (created_ || parentWindow == nullptr) return false;
763 shadows_ = shadows;
764 host_ = host;
765 parent_ = parentWindow;
766 created_ = createPlatform(parentWindow);
767 return created_;
768 }
769
771 void destroy() noexcept
772 {
773 if (!created_) return;
774 created_ = false;
775 destroyPlatform();
776 }
777
779 void setBounds(int width, int height) noexcept
780 {
781 if (created_ && width > 0 && height > 0)
782 setBoundsPlatform(width, height);
783 }
784
786 void setVisible(bool visible) noexcept
787 {
788 if (created_)
789 setVisiblePlatform(visible);
790 }
791
803 bool queryParentSize(int& width, int& height) const noexcept
804 {
805 return queryParentSizePlatform(width, height);
806 }
807
808 [[nodiscard]] bool created() const noexcept { return created_; }
809
810private:
811 static constexpr size_t kNumParams = P::parameters.size();
812
813 std::atomic<double> const* shadows_ = nullptr;
814 HostCallbacks host_ {};
815 void* parent_ = nullptr;
816 bool created_ = false;
817
818 static int indexOfId(const char* id) noexcept
819 {
820 for (size_t i = 0; i < kNumParams; ++i)
821 if (std::strcmp(P::parameters[i].id, id) == 0) return static_cast<int>(i);
822 return -1;
823 }
824
825 [[nodiscard]] double plainOf(size_t index) const noexcept
826 {
827 return toPlain(P::parameters[index],
828 shadows_[index].load(std::memory_order_relaxed));
829 }
830
831 // --- bridge protocol ---------------------------------------------------------
832
833 void handlePost(const char* json) noexcept
834 {
835 PostArgs msg;
836 if (!parsePostArgs(json, msg)) return;
837 if (std::strcmp(msg.op, "poll") == 0)
838 {
839 sendValues(msg.tokens >= 3 ? msg.value : 0.0);
840 }
841 else if (std::strcmp(msg.op, "set") == 0)
842 {
843 const int idx = indexOfId(msg.id);
844 if (idx >= 0 && msg.tokens >= 3 && host_.setParam != nullptr)
845 host_.setParam(host_.context, idx, msg.value);
846 }
847 else if (std::strcmp(msg.op, "begin") == 0)
848 {
849 const int idx = indexOfId(msg.id);
850 if (idx >= 0 && host_.beginEdit != nullptr)
851 host_.beginEdit(host_.context, idx);
852 }
853 else if (std::strcmp(msg.op, "end") == 0)
854 {
855 const int idx = indexOfId(msg.id);
856 if (idx >= 0 && host_.endEdit != nullptr)
857 host_.endEdit(host_.context, idx);
858 }
859 else if (std::strcmp(msg.op, "ready") == 0)
860 {
861 sendMeta();
862 // Diagnostic: how the page actually sees the world (DPI bugs
863 // live exactly here). Logged only with DSPARK_WEBVIEW_LOG set.
864 evalPlatform("window.__dsparkPost('metric','innerWidth',window.innerWidth);"
865 "window.__dsparkPost('metric','innerHeight',window.innerHeight);"
866 "window.__dsparkPost('metric','dpr',window.devicePixelRatio||1);");
867 }
868 else if (std::strcmp(msg.op, "metric") == 0)
869 {
870 debugLog("page metric %s = %.2f", msg.id, msg.value);
871 }
872 }
873
874 void sendMeta()
875 {
876 std::string json = "{\"type\":\"params\",\"params\":[";
877 for (size_t i = 0; i < kNumParams; ++i)
878 {
879 const Param& p = P::parameters[i];
880 if (i > 0) json += ',';
881 json += "{\"id\":";
882 appendJsonString(json, p.id);
883 json += ",\"name\":";
884 appendJsonString(json, p.name);
885 json += ",\"min\":";
886 appendJsonNumber(json, p.minValue);
887 json += ",\"max\":";
888 appendJsonNumber(json, p.maxValue);
889 json += ",\"def\":";
890 appendJsonNumber(json, p.defValue);
891 json += ",\"unit\":";
892 appendJsonString(json, p.unit);
893 json += ",\"steps\":";
894 appendJsonNumber(json, p.steps);
895 if (p.labels != nullptr)
896 {
897 json += ",\"labels\":[";
898 for (int k = 0; k <= p.steps; ++k)
899 {
900 if (k > 0) json += ',';
901 appendJsonString(json, p.labels[k]);
902 }
903 json += ']';
904 }
905 json += ",\"value\":";
906 appendJsonNumber(json, plainOf(i));
907 json += '}';
908 }
909 json += "],\"design\":{\"width\":";
910 appendJsonNumber(json, editorSizeOf<P>().width);
911 json += ",\"height\":";
912 appendJsonNumber(json, editorSizeOf<P>().height);
913 json += ",\"keepAspect\":";
914 json += editorResizeOf<P>() == EditorResize::KeepAspect ? "true" : "false";
915 json += "}}";
916 sendRecv(json);
917 }
918
924 void sendValues(double seq)
925 {
926 std::string json = "{\"type\":\"values\",\"seq\":";
927 appendJsonNumber(json, seq);
928 json += ",\"values\":{";
929 for (size_t i = 0; i < kNumParams; ++i)
930 {
931 if (i > 0) json += ',';
932 appendJsonString(json, P::parameters[i].id);
933 json += ':';
934 appendJsonNumber(json, plainOf(i));
935 }
936 json += "}}";
937 sendRecv(json);
938 }
939
940 void sendRecv(const std::string& payloadJson)
941 {
942 std::string js = "window.__dsparkRecv(";
943 js += payloadJson;
944 js += ");";
945 evalPlatform(js);
946 }
947
948 static constexpr bool debugFlag() noexcept
949 {
950 if constexpr (HasEditorDebug<P>) return true;
951 else return false;
952 }
953
956 static std::string pageHtml()
957 {
958#if !defined(DSPARK_NO_FILE_IO)
959 if constexpr (HasEditorDevFile<P>)
960 {
961 std::FILE* f = nullptr;
962#if defined(_WIN32)
963 fopen_s(&f, P::editorDevFile(), "rb");
964#else
965 f = std::fopen(P::editorDevFile(), "rb");
966#endif
967 if (f != nullptr)
968 {
969 std::string text;
970 char chunk[4096];
971 size_t got = 0;
972 while ((got = std::fread(chunk, 1, sizeof(chunk), f)) > 0)
973 text.append(chunk, got);
974 std::fclose(f);
975 if (!text.empty())
976 {
977 debugLog("page: dev file %s (%u bytes)", P::editorDevFile(),
978 static_cast<unsigned>(text.size()));
979 return text;
980 }
981 }
982 debugLog("page: dev file %s unreadable; embedded page used",
983 P::editorDevFile());
984 }
985#endif
986 return P::editorHtml();
987 }
988
989 // ==============================================================================
990 // Windows - WebView2 through the vendored webview library
991 // ==============================================================================
992#if DSPARK_WEBVIEW_BACKEND == 1
993
994 std::unique_ptr<webview::webview> wv_;
995 void* root_ = nullptr; // host top-level window (frame limits)
996 mutable SIZE frameChrome_ { -1, -1 }; // historical-minimum chrome; -1 = unmeasured
997 bool comInitialized_ = false;
998
999 bool createPlatform(void* parentWindow) noexcept
1000 {
1001 try
1002 {
1003 // WebView2 needs COM STA on this (UI) thread. DAWs have it there
1004 // already (S_FALSE, harmless); bare hosts may not. Balanced in
1005 // destroyPlatform. RPC_E_CHANGED_MODE (an MTA thread) fails the
1006 // creation below and degrades to the host's generic UI.
1007 comInitialized_ = SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED));
1008 wv_ = std::make_unique<webview::webview>(debugFlag(), parentWindow);
1009 wv_->bind("__dsparkPost", [this](std::string request) -> std::string {
1010 handlePost(request.c_str());
1011 return std::string {};
1012 });
1013 wv_->init(kBridgeJs);
1014 wv_->set_html(pageHtml());
1015 // Track the host window directly: several hosts resize their
1016 // plugin area without calling the format's size callbacks, so
1017 // relying on those alone leaves the page stuck at the old size.
1018 SetWindowSubclass(static_cast<HWND>(parentWindow), &onParentMessage,
1019 reinterpret_cast<UINT_PTR>(this),
1020 reinterpret_cast<DWORD_PTR>(this));
1021 // And the host's TOP-LEVEL frame: WM_GETMINMAXINFO/WM_SIZING are
1022 // the OS-level drag limits - the only ones no host can bypass.
1023 // VST3 size negotiation only governs the inner plugin area; the
1024 // outer frame belongs to the user, so min/max/aspect must be
1025 // enforced where the WINDOW is dragged (see rootGuard for docks).
1026 root_ = GetAncestor(static_cast<HWND>(parentWindow), GA_ROOT);
1027 if (root_ != nullptr)
1028 SetWindowSubclass(static_cast<HWND>(root_), &onRootMessage,
1029 reinterpret_cast<UINT_PTR>(this),
1030 reinterpret_cast<DWORD_PTR>(this));
1031 RECT parentBox {};
1032 GetClientRect(static_cast<HWND>(parentWindow), &parentBox);
1033 debugLog("create: parent=%p root=%p client=%ldx%ld", parentWindow,
1034 root_, parentBox.right, parentBox.bottom);
1035 return true;
1036 }
1037 catch (...) // e.g. WebView2 runtime missing -> host falls back to generic UI
1038 {
1039 wv_.reset();
1040 if (comInitialized_)
1041 {
1042 CoUninitialize();
1043 comInitialized_ = false;
1044 }
1045 return false;
1046 }
1047 }
1048
1049 static LRESULT CALLBACK onParentMessage(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
1050 UINT_PTR, DWORD_PTR refData) noexcept
1051 {
1052 if (msg == WM_SIZE)
1053 {
1054 debugLog("parent WM_SIZE %dx%d", int(LOWORD(lp)), int(HIWORD(lp)));
1055 auto* editor = reinterpret_cast<Editor*>(refData);
1056 editor->setBounds(static_cast<int>(LOWORD(lp)), static_cast<int>(HIWORD(lp)));
1057 }
1058 return DefSubclassProc(hwnd, msg, wp, lp);
1059 }
1060
1061 // --- host frame limits (OS level) ----------------------------------------------
1062
1064 double frameDpiScale() const noexcept
1065 {
1066 const UINT dpi = parent_ != nullptr ? GetDpiForWindow(static_cast<HWND>(parent_))
1067 : 96u;
1068 return dpi > 0 ? dpi / 96.0 : 1.0;
1069 }
1070
1084 bool rootGuard(HWND root, SIZE& chrome) const noexcept
1085 {
1086 if (parent_ == nullptr || root == nullptr) return false;
1087 RECT rootBox {}, parentBox {};
1088 const bool measured = GetWindowRect(root, &rootBox)
1089 && GetClientRect(static_cast<HWND>(parent_), &parentBox);
1090 bool coherent = false;
1091 if (measured)
1092 {
1093 // Threshold separates plugin windows from docked editors: a
1094 // REAPER FX-chain window (plugin list beside the editor) sits
1095 // near 45-90% plugin area, an editor docked in a DAW main
1096 // window stays well under 25%.
1097 const double rootArea = double(rootBox.right - rootBox.left)
1098 * double(rootBox.bottom - rootBox.top);
1099 const double parentArea = double(parentBox.right) * double(parentBox.bottom);
1100 coherent = rootArea > 0.0 && parentArea > 0.0
1101 && parentArea / rootArea >= 1.0 / 3.0;
1102 }
1103 if (coherent)
1104 {
1105 // No tight cap here: legitimate host chrome can be large (the
1106 // REAPER FX-chain window keeps its plugin list beside the
1107 // editor, ~450px). Underestimating it lets the window shrink
1108 // past the point where the plugin minimum still fits - exactly
1109 // a clipped editor. The historical minimum below already stops
1110 // dead space from inflating these numbers over time.
1111 auto clampChrome = [](LONG v) -> LONG {
1112 return v < 0 ? 0 : (v > 1024 ? 1024 : v);
1113 };
1114 const LONG cx = clampChrome((rootBox.right - rootBox.left) - parentBox.right);
1115 const LONG cy = clampChrome((rootBox.bottom - rootBox.top) - parentBox.bottom);
1116 if (frameChrome_.cx < 0)
1117 {
1118 frameChrome_ = SIZE { cx, cy };
1119 debugLog("frame: steering host window, chrome=%ldx%ld", cx, cy);
1120 }
1121 else
1122 {
1123 if (cx < frameChrome_.cx) frameChrome_.cx = cx;
1124 if (cy < frameChrome_.cy) frameChrome_.cy = cy;
1125 }
1126 }
1127 // A truly docked editor never produces a coherent (dominant-area)
1128 // measurement, so the chrome stays unmeasured and we never steer.
1129 if (frameChrome_.cx < 0) return false;
1130 chrome = frameChrome_;
1131 return true;
1132 }
1133
1134 void applyMinMax(HWND root, MINMAXINFO* info) const noexcept
1135 {
1136 SIZE chrome {};
1137 if (info == nullptr || !rootGuard(root, chrome)) return;
1138 const EditorSize logical = editorSizeOf<P>();
1139 const double dpi = frameDpiScale();
1140 constexpr EditorResize mode = editorResizeOf<P>();
1141 const double lo = mode == EditorResize::Fixed ? 1.0 : kEditorMinSizeFactor;
1142 const double hi = mode == EditorResize::Fixed ? 1.0 : kEditorMaxSizeFactor;
1143 const LONG minW = LONG(logical.width * dpi * lo + 0.5) + chrome.cx;
1144 const LONG minH = LONG(logical.height * dpi * lo + 0.5) + chrome.cy;
1145 const LONG maxW = LONG(logical.width * dpi * hi + 0.5) + chrome.cx;
1146 const LONG maxH = LONG(logical.height * dpi * hi + 0.5) + chrome.cy;
1147 if (info->ptMinTrackSize.x < minW) info->ptMinTrackSize.x = minW;
1148 if (info->ptMinTrackSize.y < minH) info->ptMinTrackSize.y = minH;
1149 if (info->ptMaxTrackSize.x > maxW) info->ptMaxTrackSize.x = maxW;
1150 if (info->ptMaxTrackSize.y > maxH) info->ptMaxTrackSize.y = maxH;
1151 debugLog("frame minmax: track %ldx%ld .. %ldx%ld (chrome %ldx%ld)",
1152 info->ptMinTrackSize.x, info->ptMinTrackSize.y,
1153 info->ptMaxTrackSize.x, info->ptMaxTrackSize.y,
1154 chrome.cx, chrome.cy);
1155 }
1156
1157 void applySizing(HWND root, int edge, RECT* box) const noexcept
1158 {
1159 SIZE chrome {};
1160 if (box == nullptr || !rootGuard(root, chrome)) return;
1161 const EditorSize logical = editorSizeOf<P>();
1162 const double dpi = frameDpiScale();
1163 constexpr EditorResize mode = editorResizeOf<P>();
1164 // Unlike checkSizeConstraint (where the window is already fixed and
1165 // the plugin must fit INSIDE it), WM_SIZING reshapes the whole
1166 // window - so the dragged axis leads and the other may follow.
1167 const double lo = mode == EditorResize::Fixed ? 1.0 : kEditorMinSizeFactor;
1168 const double hi = mode == EditorResize::Fixed ? 1.0 : kEditorMaxSizeFactor;
1169 const double minW = logical.width * dpi * lo;
1170 const double maxW = logical.width * dpi * hi;
1171 const double minH = logical.height * dpi * lo;
1172 const double maxH = logical.height * dpi * hi;
1173 double w = double(box->right - box->left) - chrome.cx;
1174 double h = double(box->bottom - box->top) - chrome.cy;
1175 w = w < minW ? minW : (w > maxW ? maxW : w);
1176 h = h < minH ? minH : (h > maxH ? maxH : h);
1177 if constexpr (mode == EditorResize::KeepAspect)
1178 {
1179 // The dragged edge expresses the user's intent; the bounds above
1180 // are ratio-consistent, so the derived axis stays in range.
1181 const double ratio = double(logical.width) / logical.height;
1182 if (edge == WMSZ_TOP || edge == WMSZ_BOTTOM)
1183 w = h * ratio;
1184 else
1185 h = w / ratio;
1186 }
1187 const LONG newW = LONG(w + 0.5) + chrome.cx;
1188 const LONG newH = LONG(h + 0.5) + chrome.cy;
1189 const LONG oldW = box->right - box->left;
1190 const LONG oldH = box->bottom - box->top;
1191 // Anchor the side opposite to the dragged edge.
1192 if (edge == WMSZ_LEFT || edge == WMSZ_TOPLEFT || edge == WMSZ_BOTTOMLEFT)
1193 box->left = box->right - newW;
1194 else
1195 box->right = box->left + newW;
1196 if (edge == WMSZ_TOP || edge == WMSZ_TOPLEFT || edge == WMSZ_TOPRIGHT)
1197 box->top = box->bottom - newH;
1198 else
1199 box->bottom = box->top + newH;
1200 if (newW != oldW || newH != oldH)
1201 debugLog("frame sizing(edge %d): %ldx%ld -> %ldx%ld", edge,
1202 oldW, oldH, newW, newH);
1203 }
1204
1205 static LRESULT CALLBACK onRootMessage(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
1206 UINT_PTR, DWORD_PTR refData) noexcept
1207 {
1208 const LRESULT result = DefSubclassProc(hwnd, msg, wp, lp);
1209 auto* editor = reinterpret_cast<Editor*>(refData);
1210 if (msg == WM_GETMINMAXINFO)
1211 editor->applyMinMax(hwnd, reinterpret_cast<MINMAXINFO*>(lp));
1212 else if (msg == WM_SIZING)
1213 {
1214 editor->applySizing(hwnd, static_cast<int>(wp),
1215 reinterpret_cast<RECT*>(lp));
1216 return TRUE;
1217 }
1218 return result;
1219 }
1220
1221 void destroyPlatform() noexcept
1222 {
1223 if (parent_ != nullptr)
1224 RemoveWindowSubclass(static_cast<HWND>(parent_), &onParentMessage,
1225 reinterpret_cast<UINT_PTR>(this));
1226 if (root_ != nullptr)
1227 {
1228 RemoveWindowSubclass(static_cast<HWND>(root_), &onRootMessage,
1229 reinterpret_cast<UINT_PTR>(this));
1230 root_ = nullptr;
1231 }
1232 try { wv_.reset(); }
1233 catch (...) {}
1234 if (comInitialized_)
1235 {
1236 CoUninitialize();
1237 comInitialized_ = false;
1238 }
1239 }
1240
1241 void setBoundsPlatform(int width, int height) noexcept
1242 {
1243 // The parent's real client box is the single source of truth: hosts
1244 // and formats disagree about who announces sizes when, but the web
1245 // widget must simply fill whatever the host window currently is.
1246 const int requestedW = width;
1247 const int requestedH = height;
1248 RECT rect {};
1249 if (parent_ != nullptr && GetClientRect(static_cast<HWND>(parent_), &rect)
1250 && rect.right > 0 && rect.bottom > 0)
1251 {
1252 width = static_cast<int>(rect.right);
1253 height = static_cast<int>(rect.bottom);
1254 }
1255 debugLog("setBounds(%d,%d) -> widget %dx%d", requestedW, requestedH,
1256 width, height);
1257 try
1258 {
1259 if (auto widget = wv_->widget(); widget.ok())
1260 MoveWindow(static_cast<HWND>(widget.value()), 0, 0, width, height, TRUE);
1261 }
1262 catch (...) {}
1263 }
1264
1265 void setVisiblePlatform(bool visible) noexcept
1266 {
1267 try
1268 {
1269 if (auto widget = wv_->widget(); widget.ok())
1270 ShowWindow(static_cast<HWND>(widget.value()), visible ? SW_SHOW : SW_HIDE);
1271 }
1272 catch (...) {}
1273 }
1274
1275 bool queryParentSizePlatform(int& width, int& height) const noexcept
1276 {
1277 RECT rect {};
1278 if (parent_ == nullptr || !GetClientRect(static_cast<HWND>(parent_), &rect))
1279 return false;
1280 if (rect.right <= 0 || rect.bottom <= 0) return false;
1281 width = static_cast<int>(rect.right);
1282 height = static_cast<int>(rect.bottom);
1283 return true;
1284 }
1285
1286 void evalPlatform(const std::string& js) noexcept
1287 {
1288 try
1289 {
1290 if (wv_) wv_->eval(js);
1291 }
1292 catch (...) {}
1293 }
1294
1295 // ==============================================================================
1296 // macOS - WKWebView through the Objective-C runtime
1297 // ==============================================================================
1298#elif DSPARK_WEBVIEW_BACKEND == 2
1299
1300 objc_glue::ObjId webView_ = nullptr; // WKWebView (retained)
1301 objc_glue::ObjId configuration_ = nullptr; // WKWebViewConfiguration (retained)
1302 objc_glue::ObjId relay_ = nullptr; // script-message relay (retained)
1303 objc_glue::MessageSink sink_ {};
1304
1305 static void sinkTrampoline(void* context, const char* json) noexcept
1306 {
1307 static_cast<Editor*>(context)->handlePost(json);
1308 }
1309
1310 bool createPlatform(void* parentWindow) noexcept
1311 {
1312 namespace og = objc_glue;
1313 if (!og::loadWebKit()) return false;
1314 Class relayCls = og::relayClass();
1315 if (relayCls == nullptr) return false;
1316
1317 sink_ = { &sinkTrampoline, this };
1318 relay_ = og::call(og::call(reinterpret_cast<og::ObjId>(relayCls), "alloc"), "init");
1319 if (relay_ == nullptr) return false;
1320 og::setRelaySink(relay_, &sink_);
1321
1322 configuration_ = og::call(og::cls("WKWebViewConfiguration"), "new");
1323 og::ObjId contentController = og::call(configuration_, "userContentController");
1324 og::call<void>(contentController, "addScriptMessageHandler:name:",
1325 relay_, og::nsString("dspark"));
1326
1327 // The uplink + bridge run at document start, before the page scripts.
1328 std::string bootstrap =
1329 "window.__dsparkPost=function(){"
1330 "window.webkit.messageHandlers.dspark.postMessage("
1331 "JSON.stringify(Array.prototype.slice.call(arguments)));};";
1332 bootstrap += kBridgeJs;
1333 og::ObjId script = og::call(og::call(og::cls("WKUserScript"), "alloc"),
1334 "initWithSource:injectionTime:forMainFrameOnly:",
1335 og::nsString(bootstrap.c_str()),
1336 static_cast<long>(0) /* AtDocumentStart */,
1337 static_cast<signed char>(1));
1338 og::call<void>(contentController, "addUserScript:", script);
1339 og::call<void>(script, "release");
1340
1341 const og::Rect frame {}; // resized right after by the backend
1342 webView_ = og::call(og::call(og::cls("WKWebView"), "alloc"),
1343 "initWithFrame:configuration:", frame, configuration_);
1344 if (webView_ == nullptr)
1345 {
1346 destroyPlatform();
1347 return false;
1348 }
1349 // Follow the host view on resize: width + height autoresize (2 | 16).
1350 og::call<void>(webView_, "setAutoresizingMask:", static_cast<unsigned long>(18));
1351 og::call<void>(static_cast<og::ObjId>(parentWindow), "addSubview:", webView_);
1352 og::call<void>(webView_, "loadHTMLString:baseURL:",
1353 og::nsString(pageHtml().c_str()), static_cast<og::ObjId>(nullptr));
1354 return true;
1355 }
1356
1357 void destroyPlatform() noexcept
1358 {
1359 namespace og = objc_glue;
1360 if (configuration_ != nullptr)
1361 {
1362 og::ObjId contentController = og::call(configuration_, "userContentController");
1363 og::call<void>(contentController, "removeScriptMessageHandlerForName:",
1364 og::nsString("dspark"));
1365 }
1366 if (webView_ != nullptr)
1367 {
1368 og::call<void>(webView_, "removeFromSuperview");
1369 og::call<void>(webView_, "release");
1370 webView_ = nullptr;
1371 }
1372 if (configuration_ != nullptr)
1373 {
1374 og::call<void>(configuration_, "release");
1375 configuration_ = nullptr;
1376 }
1377 if (relay_ != nullptr)
1378 {
1379 og::call<void>(relay_, "release");
1380 relay_ = nullptr;
1381 }
1382 }
1383
1384 void setBoundsPlatform(int width, int height) noexcept
1385 {
1386 const objc_glue::Rect frame { 0, 0, static_cast<double>(width),
1387 static_cast<double>(height) };
1388 objc_glue::call<void>(webView_, "setFrame:", frame);
1389 }
1390
1391 void setVisiblePlatform(bool visible) noexcept
1392 {
1393 objc_glue::call<void>(webView_, "setHidden:",
1394 static_cast<signed char>(visible ? 0 : 1));
1395 }
1396
1397 bool queryParentSizePlatform(int&, int&) const noexcept
1398 {
1399 // Cocoa views are logical-size and the autoresizing mask follows the
1400 // host view, so the negotiated size is already authoritative here.
1401 return false;
1402 }
1403
1404 void evalPlatform(const std::string& js) noexcept
1405 {
1406 if (webView_ != nullptr)
1407 objc_glue::call<void>(webView_, "evaluateJavaScript:completionHandler:",
1408 objc_glue::nsString(js.c_str()),
1409 static_cast<objc_glue::ObjId>(nullptr));
1410 }
1411
1412 // ==============================================================================
1413 // Linux - WebKitGTK in a GtkPlug, embedded in the host's X11 window
1414 // ==============================================================================
1415#elif DSPARK_WEBVIEW_BACKEND == 3
1416
1417 void* plug_ = nullptr; // GtkPlug (XEmbed top-level), owns the tree
1418 void* webView_ = nullptr; // WebKitWebView widget (child of the plug)
1419 void* contentManager_ = nullptr; // WebKitUserContentManager (view-owned)
1420 unsigned long messageSignal_ = 0;
1421
1422 static void onScriptMessage(void*, void* jsResult, void* userData) noexcept
1423 {
1424 auto* self = static_cast<Editor*>(userData);
1425 const auto& gtk = gtk_glue::api();
1426 void* value = gtk.jsResultGetValue(jsResult);
1427 if (value == nullptr) return;
1428 char* text = gtk.jscValueToString(value);
1429 if (text != nullptr)
1430 {
1431 self->handlePost(text);
1432 gtk.gFree(text);
1433 }
1434 }
1435
1436 bool createPlatform(void* parentWindow) noexcept
1437 {
1438 const auto& gtk = gtk_glue::api();
1439 if (!gtk.ok) return false;
1440 // Idempotent when the host (or another plugin) initialised GTK; fails
1441 // cleanly with no usable display (Wayland-only sessions, headless).
1442 if (!gtk.gtkInitCheck(nullptr, nullptr))
1443 {
1444 debugLog("linux create: gtk_init_check failed (no display)");
1445 return false;
1446 }
1447 plug_ = gtk.plugNew(static_cast<unsigned long>(
1448 reinterpret_cast<std::uintptr_t>(parentWindow)));
1449 if (plug_ == nullptr) return false;
1450 webView_ = gtk.webViewNew();
1451 if (webView_ == nullptr)
1452 {
1453 destroyPlatform();
1454 return false;
1455 }
1456 contentManager_ = gtk.viewGetContentManager(webView_);
1457 gtk.contentManagerRegisterHandler(contentManager_, "dspark");
1458 messageSignal_ = gtk.signalConnectData(
1459 contentManager_, "script-message-received::dspark",
1460 reinterpret_cast<void (*)()>(&onScriptMessage), this, nullptr, 0);
1461 // The uplink + bridge run at document start, before the page scripts
1462 // (WebKitGTK exposes the same window.webkit.messageHandlers namespace
1463 // as WKWebView).
1464 std::string bootstrap =
1465 "window.__dsparkPost=function(){"
1466 "window.webkit.messageHandlers.dspark.postMessage("
1467 "JSON.stringify(Array.prototype.slice.call(arguments)));};";
1468 bootstrap += kBridgeJs;
1469 void* script = gtk.userScriptNew(bootstrap.c_str(),
1470 1 /* INJECT_TOP_FRAME */,
1471 0 /* INJECT_AT_DOCUMENT_START */,
1472 nullptr, nullptr);
1473 gtk.contentManagerAddScript(contentManager_, script);
1474 gtk.userScriptUnref(script);
1475 gtk.containerAdd(plug_, webView_);
1476 gtk.loadHtml(webView_, pageHtml().c_str(), nullptr);
1477 gtk.widgetShowAll(plug_);
1478 debugLog("linux create: plug for X11 window %p", parentWindow);
1479 pumpPlatform(); // realize + map promptly, before the first host tick
1480 return true;
1481 }
1482
1483 void destroyPlatform() noexcept
1484 {
1485 const auto& gtk = gtk_glue::api();
1486 if (!gtk.ok) return;
1487 if (contentManager_ != nullptr)
1488 {
1489 if (messageSignal_ != 0)
1490 gtk.signalHandlerDisconnect(contentManager_, messageSignal_);
1491 gtk.contentManagerUnregisterHandler(contentManager_, "dspark");
1492 }
1493 if (plug_ != nullptr)
1494 gtk.widgetDestroy(plug_); // destroys the whole widget tree
1495 plug_ = nullptr;
1496 webView_ = nullptr;
1497 contentManager_ = nullptr;
1498 messageSignal_ = 0;
1499 pumpPlatform(); // flush the destroy events while we still can
1500 }
1501
1502 void setBoundsPlatform(int width, int height) noexcept
1503 {
1504 const auto& gtk = gtk_glue::api();
1505 if (plug_ == nullptr) return;
1506 gtk.windowSetDefaultSize(plug_, width, height); // pre-map size
1507 gtk.windowResize(plug_, width, height); // post-map size
1508 pumpPlatform();
1509 }
1510
1511 void setVisiblePlatform(bool visible) noexcept
1512 {
1513 if (plug_ != nullptr)
1514 gtk_glue::api().widgetSetVisible(plug_, visible ? 1 : 0);
1515 }
1516
1517 bool queryParentSizePlatform(int&, int&) const noexcept
1518 {
1519 // The plug follows the host window through XEmbed configure events,
1520 // so the negotiated size is authoritative here (as on macOS).
1521 return false;
1522 }
1523
1524 void evalPlatform(const std::string& js) noexcept
1525 {
1526 const auto& gtk = gtk_glue::api();
1527 if (webView_ == nullptr) return;
1528 if (gtk.runJs != nullptr)
1529 gtk.runJs(webView_, js.c_str(), nullptr, nullptr, nullptr);
1530 else
1531 gtk.evalJs(webView_, js.c_str(), -1, nullptr, nullptr,
1532 nullptr, nullptr, nullptr);
1533 }
1534
1535 void pumpPlatform() noexcept
1536 {
1537 const auto& gtk = gtk_glue::api();
1538 if (!gtk.ok) return;
1539 // Bounded: a source that is always ready (an idle handler re-arming
1540 // itself, an animation) must not trap the host's UI thread here -
1541 // whatever is left runs on the next host tick.
1542 for (int i = 0; i < kMaxPumpIterations && gtk.mainContextPending(nullptr) != 0; ++i)
1543 gtk.mainContextIteration(nullptr, 0);
1544 }
1545
1546 static constexpr int kMaxPumpIterations = 256;
1547
1548 // ==============================================================================
1549 // Other platforms - stub (hosts fall back to their generic editor)
1550 // ==============================================================================
1551#else
1552
1553 bool createPlatform(void*) noexcept { return false; }
1554 void destroyPlatform() noexcept {}
1555 void setBoundsPlatform(int, int) noexcept {}
1556 void setVisiblePlatform(bool) noexcept {}
1557 bool queryParentSizePlatform(int&, int&) const noexcept { return false; }
1558 void evalPlatform(const std::string&) noexcept {}
1559
1560#endif
1561};
1562
1563} // namespace dspark::plugin::webview_ui
One embedded WebView editor instance for plugin class P. Owned by the format backends (the VST3 IPlug...
Editor & operator=(const Editor &)=delete
bool queryParentSize(int &width, int &height) const noexcept
void setVisible(bool visible) noexcept
bool create(void *parentWindow, const std::atomic< double > *shadows, const HostCallbacks &host) noexcept
Editor(const Editor &)=delete
void setBounds(int width, int height) noexcept
static const char* editorHtml() - the editor page (HTML/CSS/JS), usually a raw string literal....
Custom-editor switch. With hasEditor = false (or absent) hosts show their generic parameter UI....
void appendJsonNumber(std::string &out, double v)
Appends a JSON number, immune to the process locale.
void appendJsonString(std::string &out, const char *s)
Appends a JSON string literal (quotes included, control chars escaped).
const char * parseJsonNumber(const char *s, double &out) noexcept
Locale-independent number parse; returns the end pointer or nullptr.
bool parsePostArgs(const char *s, PostArgs &out) noexcept
Parses the bridge's JSON array of scalars (op + optional id/number).
void debugLog(const char *format,...) noexcept
constexpr const char * kBridgeJs
constexpr double kEditorMinSizeFactor
Resize bounds: hosts may shrink to half and grow to 3x the declared size.
EditorResize
How the host may resize the editor window. Declare static constexpr EditorResize editorResize = ....
@ Fixed
The window is exactly editorSize; hosts cannot drag-resize it.
@ KeepAspect
Drag-resizable, locked to the declared width:height ratio.
constexpr double toPlain(const Param &p, double normalized) noexcept
Normalized [0, 1] -> plain [min, max], snapped for stepped params.
constexpr double kEditorMaxSizeFactor
constexpr int kNumParams
Param
Every parameter, in the order of the parameter table.
How the editor reaches back into the format wrapper. Plain function pointers + context (no std::funct...
void(* beginEdit)(void *context, int index)
void(* endEdit)(void *context, int index)
void(* setParam)(void *context, int index, double plainValue)
One decoded bridge message: [op, id?, value?].