DISTRHO Plugin Framework
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1496 lines
51KB

  1. /*
  2. * DISTRHO Plugin Framework (DPF)
  3. * Copyright (C) 2012-2024 Filipe Coelho <falktx@falktx.com>
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. * or without fee is hereby granted, provided that the above copyright notice and this
  7. * permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  10. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  11. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  12. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  13. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  14. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. #if !defined(DISTRHO_WEB_VIEW_HPP_INCLUDED) && !defined(DGL_WEB_VIEW_HPP_INCLUDED)
  17. # error bad include
  18. #endif
  19. #if !defined(WEB_VIEW_DISTRHO_NAMESPACE) && !defined(WEB_VIEW_DGL_NAMESPACE)
  20. # error bad usage
  21. #endif
  22. // #include <gtk/gtk.h>
  23. // #include <gtk/gtkx.h>
  24. // #include <webkit2/webkit2.h>
  25. #define WEB_VIEW_USING_CHOC 0
  26. #ifndef WEB_VIEW_USING_CHOC
  27. # define WEB_VIEW_USING_CHOC 0
  28. #elif WEB_VIEW_USING_CHOC && !(defined(DISTRHO_OS_MAC) || defined(DISTRHO_OS_WINDOWS))
  29. # undef WEB_VIEW_USING_CHOC
  30. # define WEB_VIEW_USING_CHOC 0
  31. #endif
  32. #if defined(DISTRHO_OS_MAC) && !WEB_VIEW_USING_CHOC
  33. # undef WEB_VIEW_USING_MACOS_WEBKIT
  34. # define WEB_VIEW_USING_MACOS_WEBKIT 1
  35. #else
  36. # undef WEB_VIEW_USING_MACOS_WEBKIT
  37. # define WEB_VIEW_USING_MACOS_WEBKIT 0
  38. #endif
  39. #if defined(HAVE_X11) && defined(DISTRHO_OS_LINUX)
  40. # undef WEB_VIEW_USING_X11_IPC
  41. # define WEB_VIEW_USING_X11_IPC 1
  42. #else
  43. # undef WEB_VIEW_USING_X11_IPC
  44. # define WEB_VIEW_USING_X11_IPC 0
  45. #endif
  46. #if WEB_VIEW_USING_CHOC
  47. # define WC_ERR_INVALID_CHARS 0
  48. # include "../CHOC/gui/choc_WebView.h"
  49. #elif WEB_VIEW_USING_MACOS_WEBKIT
  50. # include <Cocoa/Cocoa.h>
  51. # include <WebKit/WebKit.h>
  52. #elif WEB_VIEW_USING_X11_IPC
  53. // #define QT_NO_VERSION_TAGGING
  54. // #include <QtCore/QChar>
  55. // #include <QtCore/QPoint>
  56. // #include <QtCore/QSize>
  57. // #undef signals
  58. # include "ChildProcess.hpp"
  59. # include "RingBuffer.hpp"
  60. # include "String.hpp"
  61. # include <clocale>
  62. # include <cstdio>
  63. # include <functional>
  64. # include <dlfcn.h>
  65. # include <fcntl.h>
  66. # include <pthread.h>
  67. # include <unistd.h>
  68. # include <sys/mman.h>
  69. # include <X11/Xlib.h>
  70. # ifdef __linux__
  71. # include <syscall.h>
  72. # include <linux/futex.h>
  73. # include <linux/limits.h>
  74. # else
  75. # include <semaphore.h>
  76. # endif
  77. #endif
  78. // -----------------------------------------------------------------------------------------------------------
  79. #if WEB_VIEW_USING_MACOS_WEBKIT
  80. #define MACRO_NAME2(a, b, c) a ## b ## c
  81. #define MACRO_NAME(a, b, c) MACRO_NAME2(a, b, c)
  82. #define WEB_VIEW_DELEGATE_CLASS_NAME \
  83. MACRO_NAME(WebViewDelegate_, _, DISTRHO_NAMESPACE)
  84. @interface WEB_VIEW_DELEGATE_CLASS_NAME : NSObject<WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate>
  85. @end
  86. @implementation WEB_VIEW_DELEGATE_CLASS_NAME {
  87. @public
  88. WebViewMessageCallback callback;
  89. void* callbackPtr;
  90. bool loaded;
  91. }
  92. - (void)webView:(WKWebView *)webview
  93. didFinishNavigation:(WKNavigation*)navigation
  94. {
  95. d_stdout("page loaded");
  96. loaded = true;
  97. }
  98. - (void)webView:(WKWebView*)webview
  99. runJavaScriptAlertPanelWithMessage:(NSString*)message
  100. initiatedByFrame:(WKFrameInfo*)frame
  101. completionHandler:(void (^)(void))completionHandler
  102. {
  103. NSAlert* const alert = [[NSAlert alloc] init];
  104. [alert addButtonWithTitle:@"OK"];
  105. [alert setInformativeText:message];
  106. [alert setMessageText:@"Alert"];
  107. dispatch_async(dispatch_get_main_queue(), ^
  108. {
  109. [alert beginSheetModalForWindow:[webview window]
  110. completionHandler:^(NSModalResponse)
  111. {
  112. completionHandler();
  113. [alert release];
  114. }];
  115. });
  116. }
  117. - (void)webView:(WKWebView*)webview
  118. runJavaScriptConfirmPanelWithMessage:(NSString*)message
  119. initiatedByFrame:(WKFrameInfo*)frame
  120. completionHandler:(void (^)(BOOL))completionHandler
  121. {
  122. NSAlert* const alert = [[NSAlert alloc] init];
  123. [alert addButtonWithTitle:@"OK"];
  124. [alert addButtonWithTitle:@"Cancel"];
  125. [alert setInformativeText:message];
  126. [alert setMessageText:@"Confirm"];
  127. dispatch_async(dispatch_get_main_queue(), ^
  128. {
  129. [alert beginSheetModalForWindow:[webview window]
  130. completionHandler:^(NSModalResponse result)
  131. {
  132. completionHandler(result == NSAlertFirstButtonReturn);
  133. [alert release];
  134. }];
  135. });
  136. }
  137. - (void)webView:(WKWebView*)webview
  138. runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt
  139. defaultText:(NSString*)defaultText
  140. initiatedByFrame:(WKFrameInfo*)frame
  141. completionHandler:(void (^)(NSString*))completionHandler
  142. {
  143. NSTextField* const input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
  144. [input setStringValue:defaultText];
  145. NSAlert* const alert = [[NSAlert alloc] init];
  146. [alert setAccessoryView:input];
  147. [alert addButtonWithTitle:@"OK"];
  148. [alert addButtonWithTitle:@"Cancel"];
  149. [alert setInformativeText:prompt];
  150. [alert setMessageText: @"Prompt"];
  151. dispatch_async(dispatch_get_main_queue(), ^
  152. {
  153. [alert beginSheetModalForWindow:[webview window]
  154. completionHandler:^(NSModalResponse result)
  155. {
  156. [input validateEditing];
  157. completionHandler(result == NSAlertFirstButtonReturn ? [input stringValue] : nil);
  158. [alert release];
  159. }];
  160. });
  161. }
  162. - (void)webView:(WKWebView*)webview
  163. runOpenPanelWithParameters:(WKOpenPanelParameters*)params
  164. initiatedByFrame:(WKFrameInfo*)frame
  165. completionHandler:(void (^)(NSArray<NSURL*>*))completionHandler
  166. {
  167. NSOpenPanel* const panel = [[NSOpenPanel alloc] init];
  168. [panel setAllowsMultipleSelection:[params allowsMultipleSelection]];
  169. // [panel setAllowedFileTypes:(NSArray<NSString*>*)[params _allowedFileExtensions]];
  170. [panel setCanChooseDirectories:[params allowsDirectories]];
  171. [panel setCanChooseFiles:![params allowsDirectories]];
  172. dispatch_async(dispatch_get_main_queue(), ^
  173. {
  174. [panel beginSheetModalForWindow:[webview window]
  175. completionHandler:^(NSModalResponse result)
  176. {
  177. completionHandler(result == NSModalResponseOK ? [panel URLs] : nil);
  178. [panel release];
  179. }];
  180. });
  181. }
  182. - (void)userContentController:(WKUserContentController*)userContentController
  183. didReceiveScriptMessage:(WKScriptMessage*)message
  184. {
  185. NSString* const nsstring = static_cast<NSString*>([message body]);
  186. char* const string = strdup([nsstring UTF8String]);
  187. d_debug("JS call received '%s' %p", string, callback);
  188. if (callback != nullptr)
  189. callback(callbackPtr, string);
  190. std::free(string);
  191. }
  192. @end
  193. #elif WEB_VIEW_USING_X11_IPC
  194. #endif // WEB_VIEW_USING_MACOS_WEBKIT
  195. // -----------------------------------------------------------------------------------------------------------
  196. #ifdef WEB_VIEW_DGL_NAMESPACE
  197. START_NAMESPACE_DGL
  198. using DISTRHO_NAMESPACE::String;
  199. #else
  200. START_NAMESPACE_DISTRHO
  201. #endif
  202. // -----------------------------------------------------------------------------------------------------------
  203. #if WEB_VIEW_USING_X11_IPC
  204. #ifdef __linux__
  205. typedef int32_t ipc_sem_t;
  206. #else
  207. typedef sem_t ipc_sem_t;
  208. #endif
  209. enum WebViewMessageType {
  210. kWebViewMessageNull,
  211. kWebViewMessageInitData,
  212. kWebViewMessageEvaluateJS,
  213. kWebViewMessageCallback,
  214. kWebViewMessageReload
  215. };
  216. struct WebViewSharedBuffer {
  217. static constexpr const uint32_t size = 0x100000;
  218. ipc_sem_t sem;
  219. uint32_t head, tail, wrtn;
  220. bool invalidateCommit;
  221. uint8_t buf[size];
  222. };
  223. struct WebViewRingBuffer {
  224. WebViewSharedBuffer server;
  225. WebViewSharedBuffer client;
  226. bool valid;
  227. };
  228. static void webview_wake(ipc_sem_t* const sem)
  229. {
  230. #ifdef __linux__
  231. if (__sync_bool_compare_and_swap(sem, 0, 1))
  232. syscall(SYS_futex, sem, FUTEX_WAKE, 1, nullptr, nullptr, 0);
  233. #else
  234. sem_post(sem);
  235. #endif
  236. }
  237. static bool webview_timedwait(ipc_sem_t* const sem)
  238. {
  239. #ifdef __linux__
  240. const struct timespec timeout = { 1, 0 };
  241. for (;;)
  242. {
  243. if (__sync_bool_compare_and_swap(sem, 1, 0))
  244. return true;
  245. if (syscall(SYS_futex, sem, FUTEX_WAIT, 0, &timeout, nullptr, 0) != 0)
  246. if (errno != EAGAIN && errno != EINTR)
  247. return false;
  248. }
  249. #else
  250. struct timespec timeout;
  251. if (clock_gettime(CLOCK_REALTIME, &timeout) != 0)
  252. return false;
  253. timeout.tv_sec += 1;
  254. for (int r;;)
  255. {
  256. r = sem_timedwait(sem, &timeout);
  257. if (r < 0)
  258. r = errno;
  259. if (r == EINTR)
  260. continue;
  261. return r == 0;
  262. }
  263. #endif
  264. }
  265. #endif
  266. struct WebViewData {
  267. #if WEB_VIEW_USING_CHOC
  268. choc::ui::WebView* const webview;
  269. #elif WEB_VIEW_USING_MACOS_WEBKIT
  270. NSView* view;
  271. WKWebView* webview;
  272. NSURLRequest* urlreq;
  273. WEB_VIEW_DELEGATE_CLASS_NAME* delegate;
  274. #elif WEB_VIEW_USING_X11_IPC
  275. int shmfd = 0;
  276. char shmname[128] = {};
  277. WebViewRingBuffer* shmptr = nullptr;
  278. WebViewMessageCallback callback = nullptr;
  279. void* callbackPtr = nullptr;
  280. ChildProcess p;
  281. RingBufferControl<WebViewSharedBuffer> rbctrl, rbctrl2;
  282. ::Display* display = nullptr;
  283. ::Window childWindow = 0;
  284. ::Window ourWindow = 0;
  285. #endif
  286. WebViewData() {}
  287. DISTRHO_DECLARE_NON_COPYABLE(WebViewData);
  288. };
  289. // -----------------------------------------------------------------------------------------------------------
  290. #if WEB_VIEW_USING_CHOC
  291. static std::optional<choc::ui::WebView::Options::Resource> fetch_resource(const std::string& path)
  292. {
  293. d_stdout("requested path %s", path.c_str());
  294. if (path == "/")
  295. {
  296. const std::string html = R"PREFIX(
  297. <html>
  298. <head>
  299. <style>
  300. html, body { background: black; background-image: url(img.svg); }
  301. </style>
  302. <script>
  303. function parameterChanged(index, value) {
  304. console.log("parameterChanged received", index, value);
  305. }
  306. </script>
  307. </head>
  308. <body>
  309. hello world!
  310. </body>
  311. </html>
  312. )PREFIX";
  313. const std::vector<uint8_t> data(html.begin(), html.end());
  314. return choc::ui::WebView::Options::Resource{ data, "text/html" };
  315. }
  316. if (path == "/img.svg")
  317. {
  318. const std::string html = R"PREFIX(<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  319. <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
  320. <!-- based on https://github.com/n0jo/rackwindows/blob/master/res/components/rw_knob_large_dark.svg -->
  321. <svg width="47px" height="47px" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;">
  322. <g id="knobLDark">
  323. <path id="path3832" d="M23.521,45.109c-7.674,0 -3.302,3.9 -10.224,0.498c-6.922,-3.403 -1.202,-2.341 -5.997,-8.501c-4.795,-6.159 -5.059,-0.201 -6.763,-7.827c-1.704,-7.625 1.043,-2.42 2.76,-10.046c1.718,-7.626 -2.998,-4.102 1.797,-10.221c4.795,-6.12 2.51,-0.673 9.432,-4.035c6.921,-3.363 1.321,-4.977 8.995,-4.977c7.675,0 2.087,1.574 8.996,4.977c6.909,3.402 4.636,-2.045 9.432,4.035c4.795,6.078 0.079,2.689 1.796,10.26c1.717,7.572 4.465,2.422 2.761,10.048c-1.704,7.625 -1.982,1.708 -6.763,7.827c-4.782,6.119 0.924,5.057 -5.998,8.46c-6.921,3.402 -2.549,-0.498 -10.224,-0.498Z" style="fill:#ccc;fill-rule:nonzero;"/>
  324. </g>
  325. </svg>
  326. )PREFIX";
  327. const std::vector<uint8_t> data(html.begin(), html.end());
  328. return choc::ui::WebView::Options::Resource{ data, "image/svg+xml" };
  329. }
  330. return {};
  331. }
  332. #elif WEB_VIEW_USING_X11_IPC
  333. static void getFilenameFromFunctionPtr(char filename[PATH_MAX], const void* const ptr)
  334. {
  335. Dl_info info = {};
  336. dladdr(ptr, &info);
  337. if (info.dli_fname[0] == '.')
  338. {
  339. getcwd(filename, PATH_MAX - 1);
  340. std::strncat(filename, info.dli_fname + 1, PATH_MAX - 1);
  341. }
  342. else if (info.dli_fname[0] != '/')
  343. {
  344. getcwd(filename, PATH_MAX - 1);
  345. std::strncat(filename, "/", PATH_MAX - 1);
  346. std::strncat(filename, info.dli_fname, PATH_MAX - 1);
  347. }
  348. else
  349. {
  350. std::strncpy(filename, info.dli_fname, PATH_MAX - 1);
  351. }
  352. }
  353. #endif
  354. // -----------------------------------------------------------------------------------------------------------
  355. WebViewHandle webViewCreate(const uintptr_t windowId,
  356. const uint initialWidth,
  357. const uint initialHeight,
  358. const double scaleFactor,
  359. const WebViewOptions& options)
  360. {
  361. #if WEB_VIEW_USING_CHOC
  362. choc::ui::WebView::Options woptions;
  363. woptions.acceptsFirstMouseClick = true;
  364. woptions.enableDebugMode = true;
  365. woptions.fetchResource = fetch_resource;
  366. std::unique_ptr<choc::ui::WebView> webview = std::make_unique<choc::ui::WebView>(woptions);
  367. DISTRHO_SAFE_ASSERT_RETURN(webview->loadedOK(), nullptr);
  368. void* const handle = webview->getViewHandle();
  369. DISTRHO_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  370. choc::ui::WebView* const www = webview.get();
  371. webview->bind("setParameterValue", [www](const choc::value::ValueView&) -> choc::value::Value {
  372. static int pp = 0;
  373. std::string toeval = "typeof(parameterChanged) === 'function' && parameterChanged(";
  374. toeval += std::to_string(++pp);
  375. toeval += ", 0.1)";
  376. d_stdout("param received | %s", toeval.c_str());
  377. www->evaluateJavascript(toeval);
  378. return {};
  379. });
  380. #ifdef DISTRHO_OS_MAC
  381. NSView* const view = static_cast<NSView*>(handle);
  382. [reinterpret_cast<NSView*>(windowId) addSubview:view];
  383. [view setFrame:NSMakeRect(options.offset.x,
  384. options.offset.y,
  385. DISTRHO_UI_DEFAULT_WIDTH - options.offset.x,
  386. DISTRHO_UI_DEFAULT_HEIGHT - options.offset.y)];
  387. #else
  388. const HWND hwnd = static_cast<HWND>(handle);
  389. LONG_PTR flags = GetWindowLongPtr(hwnd, -16);
  390. flags = (flags & ~WS_POPUP) | WS_CHILD;
  391. SetWindowLongPtr(hwnd, -16, flags);
  392. SetParent(hwnd, reinterpret_cast<HWND>(windowId));
  393. SetWindowPos(hwnd, nullptr,
  394. options.offset.x * scaleFactor,
  395. options.offset.y * scaleFactor,
  396. (initialWidth - options.offset.x) * scaleFactor,
  397. (initialHeight - options.offset.y) * scaleFactor,
  398. SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
  399. ShowWindow(hwnd, SW_SHOW);
  400. #endif
  401. return new WebViewData{options.callback, webview.release()};
  402. #elif WEB_VIEW_USING_MACOS_WEBKIT
  403. NSView* const view = reinterpret_cast<NSView*>(windowId);
  404. const CGRect rect = CGRectMake(options.offset.x,
  405. options.offset.y,
  406. (initialWidth - options.offset.x),
  407. (initialHeight - options.offset.y));
  408. WKPreferences* const prefs = [[WKPreferences alloc] init];
  409. [prefs setValue:@YES forKey:@"javaScriptCanAccessClipboard"];
  410. [prefs setValue:@YES forKey:@"DOMPasteAllowed"];
  411. // if (debug)
  412. {
  413. [prefs setValue:@YES forKey:@"developerExtrasEnabled"];
  414. // TODO enable_write_console_messages_to_stdout
  415. }
  416. WKWebViewConfiguration* const config = [[WKWebViewConfiguration alloc] init];
  417. config.limitsNavigationsToAppBoundDomains = false;
  418. config.preferences = prefs;
  419. WKWebView* const webview = [[WKWebView alloc] initWithFrame:rect
  420. configuration:config];
  421. [webview setHidden:YES];
  422. [view addSubview:webview];
  423. // TODO webkit_web_view_set_background_color
  424. WEB_VIEW_DELEGATE_CLASS_NAME* const delegate = [[WEB_VIEW_DELEGATE_CLASS_NAME alloc] init];
  425. delegate->callback = options.callback;
  426. delegate->callbackPtr = options.callbackPtr;
  427. delegate->loaded = false;
  428. webview.navigationDelegate = delegate;
  429. webview.UIDelegate = delegate;
  430. if (WKUserContentController* const controller = [config userContentController])
  431. {
  432. [controller retain];
  433. [controller addScriptMessageHandler:delegate name:@"external"];
  434. }
  435. const char* const url = "file:///Users/falktx/Source/DISTRHO/DPF/examples/WebMeters/index.html";
  436. NSString* const nsurl = [[NSString alloc] initWithBytes:url
  437. length:std::strlen(url)
  438. encoding:NSUTF8StringEncoding];
  439. NSURLRequest* const urlreq = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: nsurl]];
  440. // [webview loadRequest:urlreq];
  441. [webview loadFileRequest:urlreq
  442. allowingReadAccessToURL:[NSURL URLWithString:@"file:///Users/falktx/Source/DISTRHO/DPF/examples/WebMeters/"]];
  443. d_stdout("waiting for load");
  444. if (! delegate->loaded)
  445. {
  446. NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
  447. NSDate* const date = [NSDate distantFuture];
  448. NSEvent* event;
  449. while (! delegate->loaded)
  450. {
  451. event = [NSApp
  452. #ifdef __MAC_10_12
  453. nextEventMatchingMask:NSEventMaskAny
  454. #else
  455. nextEventMatchingMask:NSAnyEventMask
  456. #endif
  457. untilDate:date
  458. inMode:NSDefaultRunLoopMode
  459. dequeue:YES];
  460. if (event == nil)
  461. break;
  462. [NSApp sendEvent: event];
  463. }
  464. [pool release];
  465. }
  466. d_stdout("waiting done");
  467. [webview setHidden:NO];
  468. [nsurl release];
  469. [config release];
  470. [prefs release];
  471. WebViewData* const handle = new WebViewData;
  472. handle->view = view;
  473. handle->webview = webview;
  474. handle->urlreq = urlreq;
  475. handle->delegate = delegate;
  476. return handle;
  477. #elif WEB_VIEW_USING_X11_IPC
  478. // get startup paths
  479. char ldlinux[PATH_MAX] = {};
  480. getFilenameFromFunctionPtr(ldlinux, dlsym(nullptr, "_rtld_global"));
  481. char filename[PATH_MAX] = {};
  482. getFilenameFromFunctionPtr(filename, reinterpret_cast<const void*>(webViewCreate));
  483. d_stdout("ld-linux is '%s'", ldlinux);
  484. d_stdout("filename is '%s'", filename);
  485. // setup shared memory
  486. int shmfd;
  487. char shmname[128];
  488. void* shmptr;
  489. for (int i = 0; i < 9999; ++i)
  490. {
  491. snprintf(shmname, sizeof(shmname) - 1, "/dpf-webview-%d", i + 1);
  492. shmfd = shm_open(shmname, O_CREAT|O_EXCL|O_RDWR, 0666);
  493. if (shmfd < 0)
  494. continue;
  495. if (ftruncate(shmfd, sizeof(WebViewRingBuffer)) != 0)
  496. {
  497. close(shmfd);
  498. shm_unlink(shmname);
  499. continue;
  500. }
  501. break;
  502. }
  503. if (shmfd < 0)
  504. {
  505. d_stderr("shm_open failed: %s", strerror(errno));
  506. return nullptr;
  507. }
  508. shmptr = mmap(nullptr, sizeof(WebViewRingBuffer), PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0);
  509. if (shmptr == nullptr || shmptr == MAP_FAILED)
  510. {
  511. d_stderr("mmap failed: %s", strerror(errno));
  512. close(shmfd);
  513. shm_unlink(shmname);
  514. return nullptr;
  515. }
  516. #ifndef __linux__
  517. sem_init(&handle->shmptr->client.sem, 1, 0);
  518. sem_init(&handle->shmptr->server.sem, 1, 0);
  519. #endif
  520. ::Display* const display = XOpenDisplay(nullptr);
  521. DISTRHO_SAFE_ASSERT_RETURN(display != nullptr, nullptr);
  522. // set up custom child environment
  523. uint envsize = 0;
  524. while (environ[envsize] != nullptr)
  525. ++envsize;
  526. char** const envp = new char*[envsize + 5];
  527. {
  528. uint e = 0;
  529. for (uint i = 0; i < envsize; ++i)
  530. {
  531. if (std::strncmp(environ[i], "LD_PRELOAD=", 11) == 0)
  532. continue;
  533. if (std::strncmp(environ[i], "LD_LIBRARY_PATH=", 16) == 0)
  534. continue;
  535. envp[e++] = strdup(environ[i]);
  536. }
  537. envp[e++] = strdup("LANG=en_US.UTF-8");
  538. envp[e++] = ("DPF_WEB_VIEW_SCALE_FACTOR=" + String(scaleFactor)).getAndReleaseBuffer();
  539. envp[e++] = ("DPF_WEB_VIEW_WIN_ID=" +String(windowId)).getAndReleaseBuffer();
  540. for (uint i = e; i < envsize + 5; ++i)
  541. envp[e++] = nullptr;
  542. }
  543. WebViewData* const handle = new WebViewData;
  544. handle->callback = options.callback;
  545. handle->callbackPtr = options.callbackPtr;
  546. handle->shmfd = shmfd;
  547. handle->shmptr = static_cast<WebViewRingBuffer*>(shmptr);
  548. handle->display = display;
  549. handle->ourWindow = windowId;
  550. std::memcpy(handle->shmname, shmname, sizeof(shmname));
  551. handle->shmptr->valid = true;
  552. handle->rbctrl.setRingBuffer(&handle->shmptr->client, false);
  553. handle->rbctrl.flush();
  554. handle->rbctrl2.setRingBuffer(&handle->shmptr->server, false);
  555. handle->rbctrl2.flush();
  556. const char* const args[] = { ldlinux, filename, "dpf-ld-linux-webview", shmname, nullptr };
  557. handle->p.start(args, envp);
  558. for (uint i = 0; envp[i] != nullptr; ++i)
  559. std::free(envp[i]);
  560. delete[] envp;
  561. handle->rbctrl.writeUInt(kWebViewMessageInitData) &&
  562. handle->rbctrl.writeULong(windowId) &&
  563. handle->rbctrl.writeUInt(initialWidth) &&
  564. handle->rbctrl.writeUInt(initialHeight) &&
  565. handle->rbctrl.writeDouble(scaleFactor) &&
  566. handle->rbctrl.writeInt(options.offset.x) &&
  567. handle->rbctrl.writeInt(options.offset.y);
  568. handle->rbctrl.commitWrite();
  569. webview_wake(&handle->shmptr->client.sem);
  570. for (int i = 0; i < 5 && handle->p.isRunning(); ++i)
  571. {
  572. if (webview_timedwait(&handle->shmptr->server.sem))
  573. return handle;
  574. }
  575. d_stderr("webview client side failed to start");
  576. webViewDestroy(handle);
  577. return nullptr;
  578. #endif
  579. // maybe unused
  580. (void)windowId;
  581. (void)initialWidth;
  582. (void)initialHeight;
  583. (void)scaleFactor;
  584. (void)options;
  585. return nullptr;
  586. }
  587. void webViewDestroy(const WebViewHandle handle)
  588. {
  589. #if WEB_VIEW_USING_CHOC
  590. delete handle->webview;
  591. #elif WEB_VIEW_USING_MACOS_WEBKIT
  592. [handle->webview setHidden:YES];
  593. [handle->webview removeFromSuperview];
  594. [handle->urlreq release];
  595. [handle->delegate release];
  596. #elif WEB_VIEW_USING_X11_IPC
  597. munmap(handle->shmptr, sizeof(WebViewRingBuffer));
  598. close(handle->shmfd);
  599. shm_unlink(handle->shmname);
  600. XCloseDisplay(handle->display);
  601. #endif
  602. delete handle;
  603. }
  604. void webViewIdle(const WebViewHandle handle)
  605. {
  606. #if WEB_VIEW_USING_X11_IPC
  607. uint32_t size = 0;
  608. void* buffer = nullptr;
  609. while (handle->rbctrl2.isDataAvailableForReading())
  610. {
  611. switch (handle->rbctrl2.readUInt())
  612. {
  613. case kWebViewMessageCallback:
  614. if (const uint32_t len = handle->rbctrl2.readUInt())
  615. {
  616. if (len > size)
  617. {
  618. size = len;
  619. buffer = std::realloc(buffer, len);
  620. if (buffer == nullptr)
  621. {
  622. d_stderr("server out of memory, abort!");
  623. handle->rbctrl2.flush();
  624. return;
  625. }
  626. }
  627. if (handle->rbctrl2.readCustomData(buffer, len))
  628. {
  629. d_debug("server kWebViewMessageCallback -> '%s'", static_cast<char*>(buffer));
  630. if (handle->callback != nullptr)
  631. handle->callback(handle->callbackPtr, static_cast<char*>(buffer));
  632. continue;
  633. }
  634. }
  635. break;
  636. }
  637. d_stderr("server ringbuffer data race, abort!");
  638. handle->rbctrl2.flush();
  639. return;
  640. }
  641. #else
  642. // unused
  643. (void)handle;
  644. #endif
  645. }
  646. void webViewEvaluateJS(const WebViewHandle handle, const char* const js)
  647. {
  648. #if WEB_VIEW_USING_CHOC
  649. #elif WEB_VIEW_USING_MACOS_WEBKIT
  650. NSString* const nsjs = [[NSString alloc] initWithBytes:js
  651. length:std::strlen(js)
  652. encoding:NSUTF8StringEncoding];
  653. [handle->webview evaluateJavaScript:nsjs completionHandler:nil];
  654. [nsjs release];
  655. #elif WEB_VIEW_USING_X11_IPC
  656. d_debug("evaluateJS '%s'", js);
  657. const size_t len = std::strlen(js) + 1;
  658. handle->rbctrl.writeUInt(kWebViewMessageEvaluateJS) &&
  659. handle->rbctrl.writeUInt(len) &&
  660. handle->rbctrl.writeCustomData(js, len);
  661. if (handle->rbctrl.commitWrite())
  662. webview_wake(&handle->shmptr->client.sem);
  663. #endif
  664. // maybe unused
  665. (void)handle;
  666. (void)js;
  667. }
  668. void webViewReload(const WebViewHandle handle)
  669. {
  670. #if WEB_VIEW_USING_CHOC
  671. #elif WEB_VIEW_USING_MACOS_WEBKIT
  672. [handle->webview loadRequest:handle->urlreq];
  673. #elif WEB_VIEW_USING_X11_IPC
  674. d_stdout("reload");
  675. handle->rbctrl.writeUInt(kWebViewMessageReload);
  676. if (handle->rbctrl.commitWrite())
  677. webview_wake(&handle->shmptr->client.sem);
  678. #endif
  679. // maybe unused
  680. (void)handle;
  681. }
  682. void webViewResize(const WebViewHandle handle, const uint width, const uint height, const double scaleFactor)
  683. {
  684. #if WEB_VIEW_USING_CHOC
  685. #ifdef DISTRHO_OS_MAC
  686. NSView* const view = static_cast<NSView*>(handle->webview->getViewHandle());
  687. [view setFrameSize:NSMakeSize(width, height)];
  688. #else
  689. const HWND hwnd = static_cast<HWND>(handle->webview->getViewHandle());
  690. SetWindowPos(hwnd, nullptr, 0, 0,
  691. width * scaleFactor,
  692. height * scaleFactor,
  693. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
  694. #endif
  695. #elif WEB_VIEW_USING_MACOS_WEBKIT
  696. [handle->webview setFrameSize:NSMakeSize(width, height)];
  697. #elif WEB_VIEW_USING_X11_IPC
  698. if (handle->childWindow == 0)
  699. {
  700. ::Window rootWindow, parentWindow;
  701. ::Window* childWindows = nullptr;
  702. uint numChildren = 0;
  703. XFlush(handle->display);
  704. XQueryTree(handle->display, handle->ourWindow, &rootWindow, &parentWindow, &childWindows, &numChildren);
  705. if (numChildren == 0 || childWindows == nullptr)
  706. return;
  707. handle->childWindow = childWindows[0];
  708. XFree(childWindows);
  709. }
  710. XResizeWindow(handle->display, handle->childWindow, width, height);
  711. XFlush(handle->display);
  712. #endif
  713. // maybe unused
  714. (void)handle;
  715. (void)width;
  716. (void)height;
  717. (void)scaleFactor;
  718. }
  719. #if WEB_VIEW_USING_X11_IPC
  720. // -----------------------------------------------------------------------------------------------------------
  721. static std::function<void(const char* js)> evaluateFn;
  722. static std::function<void()> reloadFn;
  723. static std::function<void()> terminateFn;
  724. static std::function<void(WebViewRingBuffer* rb)> wakeFn;
  725. // -----------------------------------------------------------------------------------------------------------
  726. struct GtkContainer;
  727. struct GtkPlug;
  728. struct GtkWidget;
  729. struct GtkWindow;
  730. struct JSCValue;
  731. struct WebKitJavascriptResult;
  732. struct WebKitSettings;
  733. struct WebKitUserContentManager;
  734. struct WebKitWebView;
  735. typedef int gboolean;
  736. #define G_CALLBACK(p) reinterpret_cast<void*>(p)
  737. #define GTK_CONTAINER(p) reinterpret_cast<GtkContainer*>(p)
  738. #define GTK_PLUG(p) reinterpret_cast<GtkPlug*>(p)
  739. #define GTK_WINDOW(p) reinterpret_cast<GtkWindow*>(p)
  740. #define WEBKIT_WEB_VIEW(p) reinterpret_cast<WebKitWebView*>(p)
  741. // struct QApplication;
  742. // struct QUrl;
  743. // struct QWebEngineView;
  744. // struct QWindow;
  745. // -----------------------------------------------------------------------------------------------------------
  746. #define JOIN(A, B) A ## B
  747. #define AUTOSYM(S) \
  748. using JOIN(gtk3_, S) = decltype(&S); \
  749. JOIN(gtk3_, S) S = reinterpret_cast<JOIN(gtk3_, S)>(dlsym(nullptr, #S)); \
  750. DISTRHO_SAFE_ASSERT_RETURN(S != nullptr, false);
  751. #define CSYM(S, NAME) \
  752. S NAME = reinterpret_cast<S>(dlsym(nullptr, #NAME)); \
  753. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  754. #define CPPSYM(S, NAME, SN) \
  755. S NAME = reinterpret_cast<S>(dlsym(nullptr, #SN)); \
  756. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  757. // -----------------------------------------------------------------------------------------------------------
  758. // gtk3 variant
  759. static void gtk3_idle(void* const ptr)
  760. {
  761. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  762. RingBufferControl<WebViewSharedBuffer> rbctrl;
  763. rbctrl.setRingBuffer(&shmptr->client, false);
  764. uint32_t size = 0;
  765. void* buffer = nullptr;
  766. while (rbctrl.isDataAvailableForReading())
  767. {
  768. switch (rbctrl.readUInt())
  769. {
  770. case kWebViewMessageEvaluateJS:
  771. if (const uint32_t len = rbctrl.readUInt())
  772. {
  773. if (len > size)
  774. {
  775. size = len;
  776. buffer = realloc(buffer, len);
  777. if (buffer == nullptr)
  778. {
  779. d_stderr("lv2ui client out of memory, abort!");
  780. abort();
  781. }
  782. }
  783. if (rbctrl.readCustomData(buffer, len))
  784. {
  785. d_debug("client kWebViewMessageEvaluateJS -> '%s'", static_cast<char*>(buffer));
  786. evaluateFn(static_cast<char*>(buffer));
  787. continue;
  788. }
  789. }
  790. break;
  791. case kWebViewMessageReload:
  792. d_debug("client kWebViewMessageReload");
  793. reloadFn();
  794. continue;
  795. }
  796. d_stderr("client ringbuffer data race, abort!");
  797. abort();
  798. }
  799. free(buffer);
  800. }
  801. static int gtk3_js_cb(WebKitUserContentManager*, WebKitJavascriptResult* const result, void* const arg)
  802. {
  803. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(arg);
  804. using g_free_t = void (*)(void*);
  805. using jsc_value_to_string_t = char* (*)(JSCValue*);
  806. using webkit_javascript_result_get_js_value_t = JSCValue* (*)(WebKitJavascriptResult*);
  807. CSYM(g_free_t, g_free)
  808. CSYM(jsc_value_to_string_t, jsc_value_to_string)
  809. CSYM(webkit_javascript_result_get_js_value_t, webkit_javascript_result_get_js_value)
  810. JSCValue* const value = webkit_javascript_result_get_js_value(result);
  811. DISTRHO_SAFE_ASSERT_RETURN(value != nullptr, false);
  812. char* const string = jsc_value_to_string(value);
  813. DISTRHO_SAFE_ASSERT_RETURN(string != nullptr, false);
  814. d_debug("js call received with data '%s'", string);
  815. const size_t len = std::strlen(string);
  816. RingBufferControl<WebViewSharedBuffer> rbctrl2;
  817. rbctrl2.setRingBuffer(&shmptr->server, false);
  818. rbctrl2.writeUInt(kWebViewMessageCallback) &&
  819. rbctrl2.writeUInt(len) &&
  820. rbctrl2.writeCustomData(string, len);
  821. rbctrl2.commitWrite();
  822. g_free(string);
  823. return 0;
  824. }
  825. static bool gtk3(Display* const display,
  826. const Window winId,
  827. const int x,
  828. const int y,
  829. const uint width,
  830. const uint height,
  831. double scaleFactor,
  832. const char* const url,
  833. WebViewRingBuffer* const shmptr)
  834. {
  835. void* lib;
  836. if ((lib = dlopen("libwebkit2gtk-4.0.so.37", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  837. (lib = dlopen("libwebkit2gtk-4.0.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  838. return false;
  839. using g_main_context_invoke_t = void (*)(void*, void*, void*);
  840. using g_signal_connect_data_t = ulong (*)(void*, const char*, void*, void*, void*, int);
  841. using gdk_set_allowed_backends_t = void (*)(const char*);
  842. using gtk_container_add_t = void (*)(GtkContainer*, GtkWidget*);
  843. using gtk_init_check_t = gboolean (*)(int*, char***);
  844. using gtk_main_t = void (*)();
  845. using gtk_main_quit_t = void (*)();
  846. using gtk_plug_get_id_t = Window (*)(GtkPlug*);
  847. using gtk_plug_new_t = GtkWidget* (*)(Window);
  848. using gtk_widget_show_all_t = void (*)(GtkWidget*);
  849. using gtk_window_move_t = void (*)(GtkWindow*, int, int);
  850. using gtk_window_set_default_size_t = void (*)(GtkWindow*, int, int);
  851. using webkit_settings_new_t = WebKitSettings* (*)();
  852. using webkit_settings_set_enable_developer_extras_t = void (*)(WebKitSettings*, gboolean);
  853. using webkit_settings_set_enable_write_console_messages_to_stdout_t = void (*)(WebKitSettings*, gboolean);
  854. using webkit_settings_set_hardware_acceleration_policy_t = void (*)(WebKitSettings*, int);
  855. using webkit_settings_set_javascript_can_access_clipboard_t = void (*)(WebKitSettings*, gboolean);
  856. using webkit_user_content_manager_register_script_message_handler_t = gboolean (*)(WebKitUserContentManager*, const char*);
  857. using webkit_web_view_evaluate_javascript_t = void* (*)(WebKitWebView*, const char*, ssize_t, const char*, const char*, void*, void*, void*);
  858. using webkit_web_view_get_user_content_manager_t = WebKitUserContentManager* (*)(WebKitWebView*);
  859. using webkit_web_view_load_uri_t = void (*)(WebKitWebView*, const char*);
  860. using webkit_web_view_new_with_settings_t = GtkWidget* (*)(WebKitSettings*);
  861. using webkit_web_view_run_javascript_t = void* (*)(WebKitWebView*, const char*, void*, void*, void*);
  862. using webkit_web_view_set_background_color_t = void (*)(WebKitWebView*, const double*);
  863. CSYM(g_main_context_invoke_t, g_main_context_invoke)
  864. CSYM(g_signal_connect_data_t, g_signal_connect_data)
  865. CSYM(gdk_set_allowed_backends_t, gdk_set_allowed_backends)
  866. CSYM(gtk_container_add_t, gtk_container_add)
  867. CSYM(gtk_init_check_t, gtk_init_check)
  868. CSYM(gtk_main_t, gtk_main)
  869. CSYM(gtk_main_quit_t, gtk_main_quit)
  870. CSYM(gtk_plug_get_id_t, gtk_plug_get_id)
  871. CSYM(gtk_plug_new_t, gtk_plug_new)
  872. CSYM(gtk_widget_show_all_t, gtk_widget_show_all)
  873. CSYM(gtk_window_move_t, gtk_window_move)
  874. CSYM(gtk_window_set_default_size_t, gtk_window_set_default_size)
  875. CSYM(webkit_settings_new_t, webkit_settings_new)
  876. CSYM(webkit_settings_set_enable_developer_extras_t, webkit_settings_set_enable_developer_extras)
  877. CSYM(webkit_settings_set_enable_write_console_messages_to_stdout_t, webkit_settings_set_enable_write_console_messages_to_stdout)
  878. CSYM(webkit_settings_set_hardware_acceleration_policy_t, webkit_settings_set_hardware_acceleration_policy)
  879. CSYM(webkit_settings_set_javascript_can_access_clipboard_t, webkit_settings_set_javascript_can_access_clipboard)
  880. CSYM(webkit_user_content_manager_register_script_message_handler_t, webkit_user_content_manager_register_script_message_handler)
  881. CSYM(webkit_web_view_get_user_content_manager_t, webkit_web_view_get_user_content_manager)
  882. CSYM(webkit_web_view_load_uri_t, webkit_web_view_load_uri)
  883. CSYM(webkit_web_view_new_with_settings_t, webkit_web_view_new_with_settings)
  884. CSYM(webkit_web_view_set_background_color_t, webkit_web_view_set_background_color)
  885. // special case for legacy API handling
  886. webkit_web_view_evaluate_javascript_t webkit_web_view_evaluate_javascript = reinterpret_cast<webkit_web_view_evaluate_javascript_t>(dlsym(nullptr, "webkit_web_view_evaluate_javascript"));
  887. webkit_web_view_run_javascript_t webkit_web_view_run_javascript = reinterpret_cast<webkit_web_view_run_javascript_t>(dlsym(nullptr, "webkit_web_view_run_javascript"));
  888. DISTRHO_SAFE_ASSERT_RETURN(webkit_web_view_evaluate_javascript != nullptr || webkit_web_view_run_javascript != nullptr, false);
  889. const int gdkScale = std::fmod(scaleFactor, 1.0) >= 0.75
  890. ? static_cast<int>(scaleFactor + 0.5)
  891. : static_cast<int>(scaleFactor);
  892. if (gdkScale != 1)
  893. {
  894. char scale[8] = {};
  895. std::snprintf(scale, 7, "%d", gdkScale);
  896. setenv("GDK_SCALE", scale, 1);
  897. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.2);
  898. setenv("GDK_DPI_SCALE", scale, 1);
  899. }
  900. else if (scaleFactor > 1.0)
  901. {
  902. char scale[8] = {};
  903. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.4);
  904. setenv("GDK_DPI_SCALE", scale, 1);
  905. }
  906. scaleFactor /= gdkScale;
  907. gdk_set_allowed_backends("x11");
  908. if (! gtk_init_check (nullptr, nullptr))
  909. return false;
  910. GtkWidget* const window = gtk_plug_new(winId);
  911. DISTRHO_SAFE_ASSERT_RETURN(window != nullptr, false);
  912. gtk_window_set_default_size(GTK_WINDOW(window),
  913. (width - x) * scaleFactor,
  914. (height - y) * scaleFactor);
  915. gtk_window_move(GTK_WINDOW(window), x * scaleFactor, y * scaleFactor);
  916. WebKitSettings* const settings = webkit_settings_new();
  917. DISTRHO_SAFE_ASSERT_RETURN(settings != nullptr, false);
  918. // TODO DOMPasteAllowed
  919. webkit_settings_set_javascript_can_access_clipboard(settings, true);
  920. webkit_settings_set_hardware_acceleration_policy(settings, 2 /* WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER */);
  921. // if (debug)
  922. {
  923. webkit_settings_set_enable_developer_extras(settings, true);
  924. webkit_settings_set_enable_write_console_messages_to_stdout(settings, true);
  925. }
  926. GtkWidget* const webview = webkit_web_view_new_with_settings(settings);
  927. DISTRHO_SAFE_ASSERT_RETURN(webview != nullptr, false);
  928. const double color[] = {49.0/255, 54.0/255, 59.0/255, 1};
  929. webkit_web_view_set_background_color(WEBKIT_WEB_VIEW(webview), color);
  930. if (WebKitUserContentManager* const manager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(webview)))
  931. {
  932. g_signal_connect_data(manager, "script-message-received::external", G_CALLBACK(gtk3_js_cb), shmptr, nullptr, 0);
  933. webkit_user_content_manager_register_script_message_handler(manager, "external");
  934. }
  935. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  936. gtk_container_add(GTK_CONTAINER(window), webview);
  937. gtk_widget_show_all(window);
  938. Window wid = gtk_plug_get_id(GTK_PLUG(window));
  939. XMapWindow(display, wid);
  940. XFlush(display);
  941. evaluateFn = [=](const char* const js){
  942. if (webkit_web_view_evaluate_javascript != nullptr)
  943. webkit_web_view_evaluate_javascript(WEBKIT_WEB_VIEW(webview), js, -1,
  944. nullptr, nullptr, nullptr, nullptr, nullptr);
  945. else
  946. webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(webview), js, nullptr, nullptr, nullptr);
  947. };
  948. reloadFn = [=](){
  949. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  950. };
  951. terminateFn = [=](){
  952. d_stdout("terminateFn");
  953. static bool quit = true;
  954. if (quit)
  955. {
  956. quit = false;
  957. gtk_main_quit();
  958. }
  959. };
  960. wakeFn = [=](WebViewRingBuffer* const rb){
  961. g_main_context_invoke(NULL, G_CALLBACK(gtk3_idle), rb);
  962. };
  963. // notify server we started ok
  964. webview_wake(&shmptr->server.sem);
  965. gtk_main();
  966. d_stdout("quit");
  967. dlclose(lib);
  968. return true;
  969. }
  970. #if 0
  971. // -----------------------------------------------------------------------------------------------------------
  972. // qt5webengine variant
  973. static bool qt5webengine(const Window winId, const double scaleFactor, const char* const url)
  974. {
  975. void* lib;
  976. if ((lib = dlopen("libQt5WebEngineWidgets.so.5", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  977. (lib = dlopen("libQt5WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  978. return false;
  979. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  980. using QApplication_exec_t = void (*)();
  981. using QApplication_setAttribute_t = void (*)(Qt::ApplicationAttribute, bool);
  982. using QString__init_t = void (*)(void*, const QChar*, ptrdiff_t);
  983. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  984. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  985. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  986. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  987. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  988. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  989. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  990. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  991. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  992. using QWindow_setParent_t = void (*)(QWindow*, void*);
  993. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  994. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  995. CPPSYM(QApplication_setAttribute_t, QApplication_setAttribute, _ZN16QCoreApplication12setAttributeEN2Qt20ApplicationAttributeEb)
  996. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QChari)
  997. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  998. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  999. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1000. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1001. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1002. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1003. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1004. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1005. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1006. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1007. unsetenv("QT_FONT_DPI");
  1008. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1009. unsetenv("QT_USE_PHYSICAL_DPI");
  1010. setenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0", 1);
  1011. char scale[8] = {};
  1012. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1013. setenv("QT_SCALE_FACTOR", scale, 1);
  1014. QApplication_setAttribute(Qt::AA_X11InitThreads, true);
  1015. QApplication_setAttribute(Qt::AA_EnableHighDpiScaling, true);
  1016. QApplication_setAttribute(Qt::AA_UseHighDpiPixmaps, true);
  1017. static int argc = 0;
  1018. static char* argv[] = { nullptr };
  1019. uint8_t _app[64]; // sizeof(QApplication) == 16
  1020. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1021. QApplication__init(app, argc, argv, 0);
  1022. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1023. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1024. {
  1025. const size_t url_len = std::strlen(url);
  1026. QChar* const url_qchar = new QChar[url_len + 1];
  1027. for (size_t i = 0; i < url_len; ++i)
  1028. url_qchar[i] = QChar(url[i]);
  1029. url_qchar[url_len] = 0;
  1030. QString__init(qstrurl, url_qchar, url_len);
  1031. }
  1032. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1033. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1034. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1035. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1036. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1037. QWebEngineView__init(webview, nullptr);
  1038. QWebEngineView_move(webview, QPoint(0, kVerticalOffset));
  1039. QWebEngineView_resize(webview, QSize(DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT - kVerticalOffset));
  1040. QWebEngineView_winId(webview);
  1041. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1042. QWebEngineView_setUrl(webview, *qurl);
  1043. QWebEngineView_show(webview);
  1044. reloadFn = [=](){
  1045. QWebEngineView_setUrl(webview, *qurl);
  1046. };
  1047. terminateFn = [=](){
  1048. // TODO
  1049. };
  1050. QApplication_exec();
  1051. dlclose(lib);
  1052. return true;
  1053. }
  1054. // -----------------------------------------------------------------------------------------------------------
  1055. // qt6webengine variant (same as qt5 but `QString__init_t` has different arguments)
  1056. static bool qt6webengine(const Window winId, const double scaleFactor, const char* const url)
  1057. {
  1058. void* lib;
  1059. if ((lib = dlopen("libQt6WebEngineWidgets.so.6", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  1060. (lib = dlopen("libQt6WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  1061. return false;
  1062. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  1063. using QApplication_exec_t = void (*)();
  1064. using QApplication_setAttribute_t = void (*)(Qt::ApplicationAttribute, bool);
  1065. using QString__init_t = void (*)(void*, const QChar*, long long);
  1066. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  1067. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  1068. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  1069. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  1070. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  1071. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  1072. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  1073. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  1074. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  1075. using QWindow_setParent_t = void (*)(QWindow*, void*);
  1076. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  1077. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  1078. CPPSYM(QApplication_setAttribute_t, QApplication_setAttribute, _ZN16QCoreApplication12setAttributeEN2Qt20ApplicationAttributeEb)
  1079. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QCharx)
  1080. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  1081. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  1082. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1083. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1084. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1085. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1086. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1087. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1088. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1089. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1090. unsetenv("QT_FONT_DPI");
  1091. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1092. unsetenv("QT_USE_PHYSICAL_DPI");
  1093. setenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0", 1);
  1094. char scale[8] = {};
  1095. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1096. setenv("QT_SCALE_FACTOR", scale, 1);
  1097. QApplication_setAttribute(Qt::AA_X11InitThreads, true);
  1098. QApplication_setAttribute(Qt::AA_EnableHighDpiScaling, true);
  1099. QApplication_setAttribute(Qt::AA_UseHighDpiPixmaps, true);
  1100. static int argc = 0;
  1101. static char* argv[] = { nullptr };
  1102. uint8_t _app[64]; // sizeof(QApplication) == 16
  1103. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1104. QApplication__init(app, argc, argv, 0);
  1105. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1106. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1107. {
  1108. const size_t url_len = std::strlen(url);
  1109. QChar* const url_qchar = new QChar[url_len + 1];
  1110. for (size_t i = 0; i < url_len; ++i)
  1111. url_qchar[i] = QChar(url[i]);
  1112. url_qchar[url_len] = 0;
  1113. QString__init(qstrurl, url_qchar, url_len);
  1114. }
  1115. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1116. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1117. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1118. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1119. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1120. QWebEngineView__init(webview, nullptr);
  1121. QWebEngineView_move(webview, QPoint(0, kVerticalOffset));
  1122. QWebEngineView_resize(webview, QSize(DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT - kVerticalOffset));
  1123. QWebEngineView_winId(webview);
  1124. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1125. QWebEngineView_setUrl(webview, *qurl);
  1126. QWebEngineView_show(webview);
  1127. reloadFn = [=](){
  1128. QWebEngineView_setUrl(webview, *qurl);
  1129. };
  1130. terminateFn = [=](){
  1131. // TODO
  1132. };
  1133. QApplication_exec();
  1134. dlclose(lib);
  1135. return true;
  1136. }
  1137. #endif
  1138. // -----------------------------------------------------------------------------------------------------------
  1139. // startup via ld-linux
  1140. static void signalHandler(const int sig)
  1141. {
  1142. switch (sig)
  1143. {
  1144. case SIGTERM:
  1145. terminateFn();
  1146. break;
  1147. }
  1148. }
  1149. static void* threadHandler(void* const ptr)
  1150. {
  1151. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  1152. // TODO wait until page is loaded, or something better
  1153. d_sleep(1);
  1154. while (shmptr->valid)
  1155. {
  1156. if (webview_timedwait(&shmptr->client.sem))
  1157. wakeFn(shmptr);
  1158. }
  1159. return nullptr;
  1160. }
  1161. int dpf_webview_start(const int argc, char* argv[])
  1162. {
  1163. d_stdout("started %d %s", argc, argv[1]);
  1164. if (argc != 3)
  1165. {
  1166. d_stderr("WebView entry point, nothing to see here! ;)");
  1167. return 1;
  1168. }
  1169. uselocale(newlocale(LC_NUMERIC_MASK, "C", nullptr));
  1170. Display* const display = XOpenDisplay(nullptr);
  1171. DISTRHO_SAFE_ASSERT_RETURN(display != nullptr, 1);
  1172. const char* const shmname = argv[2];
  1173. const int shmfd = shm_open(shmname, O_RDWR, 0);
  1174. if (shmfd < 0)
  1175. {
  1176. d_stderr("shm_open failed: %s", std::strerror(errno));
  1177. return 1;
  1178. }
  1179. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(mmap(nullptr,
  1180. sizeof(WebViewRingBuffer),
  1181. PROT_READ|PROT_WRITE,
  1182. MAP_SHARED,
  1183. shmfd, 0));
  1184. if (shmptr == nullptr || shmptr == nullptr)
  1185. {
  1186. d_stderr("mmap failed: %s", std::strerror(errno));
  1187. close(shmfd);
  1188. return 1;
  1189. }
  1190. RingBufferControl<WebViewSharedBuffer> rbctrl;
  1191. rbctrl.setRingBuffer(&shmptr->client, false);
  1192. const char* url = "file:///home/falktx/Source/DISTRHO/DPF/examples/WebMeters/index.html";
  1193. // fetch initial data
  1194. bool hasInitialData = false;
  1195. Window winId = 0;
  1196. uint width = 0, height = 0;
  1197. double scaleFactor = 0;
  1198. int x = 0, y = 0;
  1199. while (shmptr->valid && webview_timedwait(&shmptr->client.sem))
  1200. {
  1201. if (rbctrl.isDataAvailableForReading())
  1202. {
  1203. DISTRHO_SAFE_ASSERT_RETURN(rbctrl.readUInt() == kWebViewMessageInitData, 1);
  1204. hasInitialData = true;
  1205. winId = rbctrl.readULong();
  1206. width = rbctrl.readUInt();
  1207. height = rbctrl.readUInt();
  1208. scaleFactor = rbctrl.readDouble();
  1209. x = rbctrl.readInt();
  1210. y = rbctrl.readInt();
  1211. }
  1212. }
  1213. pthread_t thread;
  1214. if (hasInitialData && pthread_create(&thread, nullptr, threadHandler, shmptr) == 0)
  1215. {
  1216. struct sigaction sig = {};
  1217. sig.sa_handler = signalHandler;
  1218. sig.sa_flags = SA_RESTART;
  1219. sigemptyset(&sig.sa_mask);
  1220. sigaction(SIGTERM, &sig, nullptr);
  1221. // qt5webengine(winId, scaleFactor, url) ||
  1222. // qt6webengine(winId, scaleFactor, url) ||
  1223. gtk3(display, winId, x, y, width, height, scaleFactor, url, shmptr);
  1224. }
  1225. shmptr->valid = false;
  1226. pthread_join(thread, nullptr);
  1227. XCloseDisplay(display);
  1228. munmap(shmptr, sizeof(WebViewRingBuffer));
  1229. close(shmfd);
  1230. return 0;
  1231. }
  1232. // --------------------------------------------------------------------------------------------------------------------
  1233. #endif // WEB_VIEW_USING_X11_IPC
  1234. #ifdef WEB_VIEW_DGL_NAMESPACE
  1235. END_NAMESPACE_DGL
  1236. #else
  1237. END_NAMESPACE_DISTRHO
  1238. #endif
  1239. #undef MACRO_NAME
  1240. #undef MACRO_NAME2
  1241. #undef WEB_VIEW_DISTRHO_NAMESPACE
  1242. #undef WEB_VIEW_DGL_NAMESPACE