710 "hasEditor is true but `static const char* editorHtml()` is missing");
713 static constexpr bool kAvailable = (DSPARK_WEBVIEW_BACKEND != 0);
724#if DSPARK_WEBVIEW_BACKEND == 3
725 return gtk_glue::api().ok;
740#if DSPARK_WEBVIEW_BACKEND == 3
759 bool create(
void* parentWindow,
const std::atomic<double>* shadows,
762 if (created_ || parentWindow ==
nullptr)
return false;
765 parent_ = parentWindow;
766 created_ = createPlatform(parentWindow);
773 if (!created_)
return;
781 if (created_ && width > 0 && height > 0)
782 setBoundsPlatform(width, height);
789 setVisiblePlatform(visible);
805 return queryParentSizePlatform(width, height);
808 [[nodiscard]]
bool created() const noexcept {
return created_; }
811 static constexpr size_t kNumParams = P::parameters.size();
813 std::atomic<double>
const* shadows_ =
nullptr;
815 void* parent_ =
nullptr;
816 bool created_ =
false;
818 static int indexOfId(
const char*
id)
noexcept
820 for (
size_t i = 0; i < kNumParams; ++i)
821 if (std::strcmp(P::parameters[i].
id,
id) == 0)
return static_cast<int>(i);
825 [[nodiscard]]
double plainOf(
size_t index)
const noexcept
827 return toPlain(P::parameters[index],
828 shadows_[index].load(std::memory_order_relaxed));
833 void handlePost(
const char* json)
noexcept
837 if (std::strcmp(msg.op,
"poll") == 0)
839 sendValues(msg.tokens >= 3 ? msg.value : 0.0);
841 else if (std::strcmp(msg.op,
"set") == 0)
843 const int idx = indexOfId(msg.id);
844 if (idx >= 0 && msg.tokens >= 3 && host_.
setParam !=
nullptr)
847 else if (std::strcmp(msg.op,
"begin") == 0)
849 const int idx = indexOfId(msg.id);
850 if (idx >= 0 && host_.
beginEdit !=
nullptr)
853 else if (std::strcmp(msg.op,
"end") == 0)
855 const int idx = indexOfId(msg.id);
856 if (idx >= 0 && host_.
endEdit !=
nullptr)
859 else if (std::strcmp(msg.op,
"ready") == 0)
864 evalPlatform(
"window.__dsparkPost('metric','innerWidth',window.innerWidth);"
865 "window.__dsparkPost('metric','innerHeight',window.innerHeight);"
866 "window.__dsparkPost('metric','dpr',window.devicePixelRatio||1);");
868 else if (std::strcmp(msg.op,
"metric") == 0)
870 debugLog(
"page metric %s = %.2f", msg.id, msg.value);
876 std::string json =
"{\"type\":\"params\",\"params\":[";
879 const Param& p = P::parameters[i];
880 if (i > 0) json +=
',';
883 json +=
",\"name\":";
891 json +=
",\"unit\":";
893 json +=
",\"steps\":";
895 if (p.labels !=
nullptr)
897 json +=
",\"labels\":[";
898 for (
int k = 0; k <= p.steps; ++k)
900 if (k > 0) json +=
',';
905 json +=
",\"value\":";
909 json +=
"],\"design\":{\"width\":";
911 json +=
",\"height\":";
913 json +=
",\"keepAspect\":";
924 void sendValues(
double seq)
926 std::string json =
"{\"type\":\"values\",\"seq\":";
928 json +=
",\"values\":{";
931 if (i > 0) json +=
',';
940 void sendRecv(
const std::string& payloadJson)
942 std::string js =
"window.__dsparkRecv(";
948 static constexpr bool debugFlag() noexcept
950 if constexpr (HasEditorDebug<P>)
return true;
956 static std::string pageHtml()
958#if !defined(DSPARK_NO_FILE_IO)
959 if constexpr (HasEditorDevFile<P>)
961 std::FILE* f =
nullptr;
963 fopen_s(&f, P::editorDevFile(),
"rb");
965 f = std::fopen(P::editorDevFile(),
"rb");
972 while ((got = std::fread(chunk, 1,
sizeof(chunk), f)) > 0)
973 text.append(chunk, got);
977 debugLog(
"page: dev file %s (%u bytes)", P::editorDevFile(),
978 static_cast<unsigned>(text.size()));
982 debugLog(
"page: dev file %s unreadable; embedded page used",
986 return P::editorHtml();
992#if DSPARK_WEBVIEW_BACKEND == 1
994 std::unique_ptr<webview::webview> wv_;
995 void* root_ =
nullptr;
996 mutable SIZE frameChrome_ { -1, -1 };
997 bool comInitialized_ =
false;
999 bool createPlatform(
void* parentWindow)
noexcept
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 {};
1014 wv_->set_html(pageHtml());
1018 SetWindowSubclass(
static_cast<HWND
>(parentWindow), &onParentMessage,
1019 reinterpret_cast<UINT_PTR
>(
this),
1020 reinterpret_cast<DWORD_PTR
>(
this));
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));
1032 GetClientRect(
static_cast<HWND
>(parentWindow), &parentBox);
1033 debugLog(
"create: parent=%p root=%p client=%ldx%ld", parentWindow,
1034 root_, parentBox.right, parentBox.bottom);
1040 if (comInitialized_)
1043 comInitialized_ =
false;
1049 static LRESULT CALLBACK onParentMessage(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
1050 UINT_PTR, DWORD_PTR refData)
noexcept
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)));
1058 return DefSubclassProc(hwnd, msg, wp, lp);
1064 double frameDpiScale() const noexcept
1066 const UINT dpi = parent_ !=
nullptr ? GetDpiForWindow(
static_cast<HWND
>(parent_))
1068 return dpi > 0 ? dpi / 96.0 : 1.0;
1084 bool rootGuard(HWND root, SIZE& chrome)
const noexcept
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;
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;
1111 auto clampChrome = [](LONG v) -> LONG {
1112 return v < 0 ? 0 : (v > 1024 ? 1024 : v);
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)
1118 frameChrome_ = SIZE { cx, cy };
1119 debugLog(
"frame: steering host window, chrome=%ldx%ld", cx, cy);
1123 if (cx < frameChrome_.cx) frameChrome_.cx = cx;
1124 if (cy < frameChrome_.cy) frameChrome_.cy = cy;
1129 if (frameChrome_.cx < 0)
return false;
1130 chrome = frameChrome_;
1134 void applyMinMax(HWND root, MINMAXINFO* info)
const noexcept
1137 if (info ==
nullptr || !rootGuard(root, chrome))
return;
1138 const EditorSize logical = editorSizeOf<P>();
1139 const double dpi = frameDpiScale();
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);
1157 void applySizing(HWND root,
int edge, RECT* box)
const noexcept
1160 if (box ==
nullptr || !rootGuard(root, chrome))
return;
1161 const EditorSize logical = editorSizeOf<P>();
1162 const double dpi = frameDpiScale();
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);
1181 const double ratio = double(logical.width) / logical.height;
1182 if (edge == WMSZ_TOP || edge == WMSZ_BOTTOM)
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;
1192 if (edge == WMSZ_LEFT || edge == WMSZ_TOPLEFT || edge == WMSZ_BOTTOMLEFT)
1193 box->left = box->right - newW;
1195 box->right = box->left + newW;
1196 if (edge == WMSZ_TOP || edge == WMSZ_TOPLEFT || edge == WMSZ_TOPRIGHT)
1197 box->top = box->bottom - newH;
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);
1205 static LRESULT CALLBACK onRootMessage(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp,
1206 UINT_PTR, DWORD_PTR refData)
noexcept
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)
1214 editor->applySizing(hwnd,
static_cast<int>(wp),
1215 reinterpret_cast<RECT*
>(lp));
1221 void destroyPlatform() noexcept
1223 if (parent_ !=
nullptr)
1224 RemoveWindowSubclass(
static_cast<HWND
>(parent_), &onParentMessage,
1225 reinterpret_cast<UINT_PTR
>(
this));
1226 if (root_ !=
nullptr)
1228 RemoveWindowSubclass(
static_cast<HWND
>(root_), &onRootMessage,
1229 reinterpret_cast<UINT_PTR
>(
this));
1232 try { wv_.reset(); }
1234 if (comInitialized_)
1237 comInitialized_ =
false;
1241 void setBoundsPlatform(
int width,
int height)
noexcept
1246 const int requestedW = width;
1247 const int requestedH = height;
1249 if (parent_ !=
nullptr && GetClientRect(
static_cast<HWND
>(parent_), &rect)
1250 && rect.right > 0 && rect.bottom > 0)
1252 width =
static_cast<int>(rect.right);
1253 height =
static_cast<int>(rect.bottom);
1255 debugLog(
"setBounds(%d,%d) -> widget %dx%d", requestedW, requestedH,
1259 if (
auto widget = wv_->widget(); widget.ok())
1260 MoveWindow(
static_cast<HWND
>(widget.value()), 0, 0, width, height, TRUE);
1265 void setVisiblePlatform(
bool visible)
noexcept
1269 if (
auto widget = wv_->widget(); widget.ok())
1270 ShowWindow(
static_cast<HWND
>(widget.value()), visible ? SW_SHOW : SW_HIDE);
1275 bool queryParentSizePlatform(
int& width,
int& height)
const noexcept
1278 if (parent_ ==
nullptr || !GetClientRect(
static_cast<HWND
>(parent_), &rect))
1280 if (rect.right <= 0 || rect.bottom <= 0)
return false;
1281 width =
static_cast<int>(rect.right);
1282 height =
static_cast<int>(rect.bottom);
1286 void evalPlatform(
const std::string& js)
noexcept
1290 if (wv_) wv_->eval(js);
1298#elif DSPARK_WEBVIEW_BACKEND == 2
1300 objc_glue::ObjId webView_ =
nullptr;
1301 objc_glue::ObjId configuration_ =
nullptr;
1302 objc_glue::ObjId relay_ =
nullptr;
1303 objc_glue::MessageSink sink_ {};
1305 static void sinkTrampoline(
void* context,
const char* json)
noexcept
1307 static_cast<Editor*
>(context)->handlePost(json);
1310 bool createPlatform(
void* parentWindow)
noexcept
1312 namespace og = objc_glue;
1313 if (!og::loadWebKit())
return false;
1314 Class relayCls = og::relayClass();
1315 if (relayCls ==
nullptr)
return false;
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_);
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"));
1328 std::string bootstrap =
1329 "window.__dsparkPost=function(){"
1330 "window.webkit.messageHandlers.dspark.postMessage("
1331 "JSON.stringify(Array.prototype.slice.call(arguments)));};";
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) ,
1337 static_cast<signed char>(1));
1338 og::call<void>(contentController,
"addUserScript:", script);
1339 og::call<void>(script,
"release");
1341 const og::Rect frame {};
1342 webView_ = og::call(og::call(og::cls(
"WKWebView"),
"alloc"),
1343 "initWithFrame:configuration:", frame, configuration_);
1344 if (webView_ ==
nullptr)
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));
1357 void destroyPlatform() noexcept
1359 namespace og = objc_glue;
1360 if (configuration_ !=
nullptr)
1362 og::ObjId contentController = og::call(configuration_,
"userContentController");
1363 og::call<void>(contentController,
"removeScriptMessageHandlerForName:",
1364 og::nsString(
"dspark"));
1366 if (webView_ !=
nullptr)
1368 og::call<void>(webView_,
"removeFromSuperview");
1369 og::call<void>(webView_,
"release");
1372 if (configuration_ !=
nullptr)
1374 og::call<void>(configuration_,
"release");
1375 configuration_ =
nullptr;
1377 if (relay_ !=
nullptr)
1379 og::call<void>(relay_,
"release");
1384 void setBoundsPlatform(
int width,
int height)
noexcept
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);
1391 void setVisiblePlatform(
bool visible)
noexcept
1393 objc_glue::call<void>(webView_,
"setHidden:",
1394 static_cast<signed char>(visible ? 0 : 1));
1397 bool queryParentSizePlatform(
int&,
int&)
const noexcept
1404 void evalPlatform(
const std::string& js)
noexcept
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));
1415#elif DSPARK_WEBVIEW_BACKEND == 3
1417 void* plug_ =
nullptr;
1418 void* webView_ =
nullptr;
1419 void* contentManager_ =
nullptr;
1420 unsigned long messageSignal_ = 0;
1422 static void onScriptMessage(
void*,
void* jsResult,
void* userData)
noexcept
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)
1431 self->handlePost(text);
1436 bool createPlatform(
void* parentWindow)
noexcept
1438 const auto& gtk = gtk_glue::api();
1439 if (!gtk.ok)
return false;
1442 if (!gtk.gtkInitCheck(
nullptr,
nullptr))
1444 debugLog(
"linux create: gtk_init_check failed (no display)");
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)
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);
1464 std::string bootstrap =
1465 "window.__dsparkPost=function(){"
1466 "window.webkit.messageHandlers.dspark.postMessage("
1467 "JSON.stringify(Array.prototype.slice.call(arguments)));};";
1469 void* script = gtk.userScriptNew(bootstrap.c_str(),
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);
1483 void destroyPlatform() noexcept
1485 const auto& gtk = gtk_glue::api();
1486 if (!gtk.ok)
return;
1487 if (contentManager_ !=
nullptr)
1489 if (messageSignal_ != 0)
1490 gtk.signalHandlerDisconnect(contentManager_, messageSignal_);
1491 gtk.contentManagerUnregisterHandler(contentManager_,
"dspark");
1493 if (plug_ !=
nullptr)
1494 gtk.widgetDestroy(plug_);
1497 contentManager_ =
nullptr;
1502 void setBoundsPlatform(
int width,
int height)
noexcept
1504 const auto& gtk = gtk_glue::api();
1505 if (plug_ ==
nullptr)
return;
1506 gtk.windowSetDefaultSize(plug_, width, height);
1507 gtk.windowResize(plug_, width, height);
1511 void setVisiblePlatform(
bool visible)
noexcept
1513 if (plug_ !=
nullptr)
1514 gtk_glue::api().widgetSetVisible(plug_, visible ? 1 : 0);
1517 bool queryParentSizePlatform(
int&,
int&)
const noexcept
1524 void evalPlatform(
const std::string& js)
noexcept
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);
1531 gtk.evalJs(webView_, js.c_str(), -1,
nullptr,
nullptr,
1532 nullptr,
nullptr,
nullptr);
1535 void pumpPlatform() noexcept
1537 const auto& gtk = gtk_glue::api();
1538 if (!gtk.ok)
return;
1542 for (
int i = 0; i < kMaxPumpIterations && gtk.mainContextPending(
nullptr) != 0; ++i)
1543 gtk.mainContextIteration(
nullptr, 0);
1546 static constexpr int kMaxPumpIterations = 256;
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 {}