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.

1540 lines
52KB

  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. static void getFilenameFromFunctionPtr(char filename[PATH_MAX], const void* const ptr)
  266. {
  267. Dl_info info = {};
  268. dladdr(ptr, &info);
  269. if (info.dli_fname[0] == '.')
  270. {
  271. getcwd(filename, PATH_MAX - 1);
  272. std::strncat(filename, info.dli_fname + 1, PATH_MAX - 1);
  273. }
  274. else if (info.dli_fname[0] != '/')
  275. {
  276. getcwd(filename, PATH_MAX - 1);
  277. std::strncat(filename, "/", PATH_MAX - 1);
  278. std::strncat(filename, info.dli_fname, PATH_MAX - 1);
  279. }
  280. else
  281. {
  282. std::strncpy(filename, info.dli_fname, PATH_MAX - 1);
  283. }
  284. }
  285. #endif
  286. struct WebViewData {
  287. #if WEB_VIEW_USING_CHOC
  288. choc::ui::WebView* webview;
  289. WebViewMessageCallback callback;
  290. void* callbackPtr;
  291. std::string url;
  292. #elif WEB_VIEW_USING_MACOS_WEBKIT
  293. NSView* view;
  294. WKWebView* webview;
  295. NSURLRequest* urlreq;
  296. WEB_VIEW_DELEGATE_CLASS_NAME* delegate;
  297. #elif WEB_VIEW_USING_X11_IPC
  298. int shmfd = 0;
  299. char shmname[128] = {};
  300. WebViewRingBuffer* shmptr = nullptr;
  301. WebViewMessageCallback callback = nullptr;
  302. void* callbackPtr = nullptr;
  303. ChildProcess p;
  304. RingBufferControl<WebViewSharedBuffer> rbctrl, rbctrl2;
  305. ::Display* display = nullptr;
  306. ::Window childWindow = 0;
  307. ::Window ourWindow = 0;
  308. #endif
  309. WebViewData() {}
  310. DISTRHO_DECLARE_NON_COPYABLE(WebViewData);
  311. };
  312. // -----------------------------------------------------------------------------------------------------------
  313. WebViewHandle webViewCreate(const char* const url,
  314. const uintptr_t windowId,
  315. const uint initialWidth,
  316. const uint initialHeight,
  317. const double scaleFactor,
  318. const WebViewOptions& options)
  319. {
  320. #if WEB_VIEW_USING_CHOC
  321. choc::ui::WebView::Options woptions;
  322. woptions.acceptsFirstMouseClick = true;
  323. woptions.enableDebugMode = true;
  324. std::unique_ptr<choc::ui::WebView> webview = std::make_unique<choc::ui::WebView>(woptions);
  325. DISTRHO_SAFE_ASSERT_RETURN(webview->loadedOK(), nullptr);
  326. void* const handle = webview->getViewHandle();
  327. DISTRHO_SAFE_ASSERT_RETURN(handle != nullptr, nullptr);
  328. if (const WebViewMessageCallback callback = options.callback)
  329. {
  330. webview->addInitScript("function postMessage(m) { js2cpp(m); }");
  331. void* const callbackPtr = options.callbackPtr;
  332. webview->bind("js2cpp", [callback, callbackPtr](const choc::value::ValueView& args) -> choc::value::Value {
  333. callback(callbackPtr, args[0].toString().data());
  334. return {};
  335. });
  336. }
  337. else
  338. {
  339. webview->addInitScript("function postMessage(m) {}");
  340. }
  341. if (options.initialJS != nullptr)
  342. webview->addInitScript(options.initialJS);
  343. webview->navigate(url);
  344. #ifdef DISTRHO_OS_MAC
  345. NSView* const view = static_cast<NSView*>(handle);
  346. [reinterpret_cast<NSView*>(windowId) addSubview:view];
  347. [view setFrame:NSMakeRect(options.offset.x,
  348. options.offset.y,
  349. DISTRHO_UI_DEFAULT_WIDTH - options.offset.x,
  350. DISTRHO_UI_DEFAULT_HEIGHT - options.offset.y)];
  351. #else
  352. const HWND hwnd = static_cast<HWND>(handle);
  353. LONG_PTR flags = GetWindowLongPtr(hwnd, -16);
  354. flags = (flags & ~WS_POPUP) | WS_CHILD;
  355. SetWindowLongPtr(hwnd, -16, flags);
  356. SetParent(hwnd, reinterpret_cast<HWND>(windowId));
  357. SetWindowPos(hwnd, nullptr,
  358. options.offset.x * scaleFactor,
  359. options.offset.y * scaleFactor,
  360. (initialWidth - options.offset.x) * scaleFactor,
  361. (initialHeight - options.offset.y) * scaleFactor,
  362. SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
  363. ShowWindow(hwnd, SW_SHOW);
  364. #endif
  365. WebViewData* const whandle = new WebViewData;
  366. whandle->webview = webview.release();
  367. whandle->callback = options.callback;
  368. whandle->callbackPtr = options.callbackPtr;
  369. whandle->url = url;
  370. return whandle;
  371. #elif WEB_VIEW_USING_MACOS_WEBKIT
  372. NSView* const view = reinterpret_cast<NSView*>(windowId);
  373. WKPreferences* const prefs = [[WKPreferences alloc] init];
  374. [prefs setValue:@YES forKey:@"javaScriptCanAccessClipboard"];
  375. [prefs setValue:@YES forKey:@"DOMPasteAllowed"];
  376. // if (debug)
  377. {
  378. [prefs setValue:@YES forKey:@"developerExtrasEnabled"];
  379. // TODO enable_write_console_messages_to_stdout
  380. }
  381. WKWebViewConfiguration* const config = [[WKWebViewConfiguration alloc] init];
  382. config.limitsNavigationsToAppBoundDomains = false;
  383. config.preferences = prefs;
  384. const CGRect rect = CGRectMake(options.offset.x / scaleFactor,
  385. options.offset.y / scaleFactor,
  386. initialWidth,
  387. initialHeight);
  388. WKWebView* const webview = [[WKWebView alloc] initWithFrame:rect
  389. configuration:config];
  390. [webview setHidden:YES];
  391. [view addSubview:webview];
  392. // TODO webkit_web_view_set_background_color
  393. WEB_VIEW_DELEGATE_CLASS_NAME* const delegate = [[WEB_VIEW_DELEGATE_CLASS_NAME alloc] init];
  394. delegate->callback = options.callback;
  395. delegate->callbackPtr = options.callbackPtr;
  396. delegate->loaded = false;
  397. if (WKUserContentController* const controller = [config userContentController])
  398. {
  399. [controller addScriptMessageHandler:delegate name:@"external"];
  400. WKUserScript* const mscript = [[WKUserScript alloc]
  401. initWithSource:(options.callback != nullptr
  402. ? @"function postMessage(m){window.webkit.messageHandlers.external.postMessage(m)}"
  403. : @"function postMessage(m){}}")
  404. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  405. forMainFrameOnly:true
  406. ];
  407. [controller addUserScript:mscript];
  408. [mscript release];
  409. if (options.initialJS != nullptr)
  410. {
  411. NSString* const nsInitialJS = [[NSString alloc] initWithBytes:options.initialJS
  412. length:std::strlen(options.initialJS)
  413. encoding:NSUTF8StringEncoding];
  414. WKUserScript* const script = [[WKUserScript alloc] initWithSource:nsInitialJS
  415. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  416. forMainFrameOnly:true];
  417. [controller addUserScript:script];
  418. [script release];
  419. [nsInitialJS release];
  420. }
  421. }
  422. [webview setNavigationDelegate:delegate];
  423. [webview setUIDelegate:delegate];
  424. NSString* const nsurl = [[NSString alloc] initWithBytes:url
  425. length:std::strlen(url)
  426. encoding:NSUTF8StringEncoding];
  427. NSURLRequest* const urlreq = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: nsurl]];
  428. d_stdout("url is '%s'", url);
  429. if (std::strncmp(url, "file://", 7) == 0)
  430. {
  431. const char* const lastsep = std::strrchr(url + 7, '/');
  432. NSString* const urlpath = [[NSString alloc] initWithBytes:url
  433. length:(lastsep - url)
  434. encoding:NSUTF8StringEncoding];
  435. [webview loadFileRequest:urlreq
  436. allowingReadAccessToURL:[NSURL URLWithString:urlpath]];
  437. [urlpath release];
  438. }
  439. else
  440. {
  441. [webview loadRequest:urlreq];
  442. }
  443. d_stdout("waiting for load");
  444. if (! delegate->loaded)
  445. {
  446. NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
  447. NSDate* const date = [NSDate dateWithTimeIntervalSinceNow:0.05];
  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. const size_t urllen = std::strlen(url);
  562. const size_t initjslen = options.initialJS != nullptr ? std::strlen(options.initialJS) + 1 : 0;
  563. handle->rbctrl.writeUInt(kWebViewMessageInitData) &&
  564. handle->rbctrl.writeULong(windowId) &&
  565. handle->rbctrl.writeUInt(initialWidth) &&
  566. handle->rbctrl.writeUInt(initialHeight) &&
  567. handle->rbctrl.writeDouble(scaleFactor) &&
  568. handle->rbctrl.writeInt(options.offset.x) &&
  569. handle->rbctrl.writeInt(options.offset.y) &&
  570. handle->rbctrl.writeUInt(urllen) &&
  571. handle->rbctrl.writeCustomData(url, urllen) &&
  572. handle->rbctrl.writeUInt(initjslen) &&
  573. initjslen != 0 &&
  574. handle->rbctrl.writeCustomData(options.initialJS, initjslen);
  575. handle->rbctrl.commitWrite();
  576. webview_wake(&handle->shmptr->client.sem);
  577. for (int i = 0; i < 5 && handle->p.isRunning(); ++i)
  578. {
  579. if (webview_timedwait(&handle->shmptr->server.sem))
  580. return handle;
  581. }
  582. d_stderr("webview client side failed to start");
  583. webViewDestroy(handle);
  584. return nullptr;
  585. #endif
  586. // maybe unused
  587. (void)windowId;
  588. (void)initialWidth;
  589. (void)initialHeight;
  590. (void)scaleFactor;
  591. (void)options;
  592. return nullptr;
  593. }
  594. void webViewDestroy(const WebViewHandle handle)
  595. {
  596. #if WEB_VIEW_USING_CHOC
  597. delete handle->webview;
  598. #elif WEB_VIEW_USING_MACOS_WEBKIT
  599. [handle->webview setHidden:YES];
  600. [handle->webview removeFromSuperview];
  601. [handle->urlreq release];
  602. // [handle->delegate release];
  603. #elif WEB_VIEW_USING_X11_IPC
  604. #ifndef __linux__
  605. sem_destroy(&handle->shmptr->client.sem);
  606. sem_destroy(&handle->shmptr->server.sem);
  607. #endif
  608. munmap(handle->shmptr, sizeof(WebViewRingBuffer));
  609. close(handle->shmfd);
  610. shm_unlink(handle->shmname);
  611. XCloseDisplay(handle->display);
  612. #endif
  613. delete handle;
  614. }
  615. void webViewIdle(const WebViewHandle handle)
  616. {
  617. #if WEB_VIEW_USING_X11_IPC
  618. uint32_t size = 0;
  619. void* buffer = nullptr;
  620. while (handle->rbctrl2.isDataAvailableForReading())
  621. {
  622. switch (handle->rbctrl2.readUInt())
  623. {
  624. case kWebViewMessageCallback:
  625. if (const uint32_t len = handle->rbctrl2.readUInt())
  626. {
  627. if (len > size)
  628. {
  629. size = len;
  630. buffer = std::realloc(buffer, len);
  631. if (buffer == nullptr)
  632. {
  633. d_stderr("server out of memory, abort!");
  634. handle->rbctrl2.flush();
  635. return;
  636. }
  637. }
  638. if (handle->rbctrl2.readCustomData(buffer, len))
  639. {
  640. d_debug("server kWebViewMessageCallback -> '%s'", static_cast<char*>(buffer));
  641. if (handle->callback != nullptr)
  642. handle->callback(handle->callbackPtr, static_cast<char*>(buffer));
  643. continue;
  644. }
  645. }
  646. break;
  647. }
  648. d_stderr("server ringbuffer data race, abort!");
  649. handle->rbctrl2.flush();
  650. return;
  651. }
  652. #else
  653. // unused
  654. (void)handle;
  655. #endif
  656. }
  657. void webViewEvaluateJS(const WebViewHandle handle, const char* const js)
  658. {
  659. #if WEB_VIEW_USING_CHOC
  660. handle->webview->evaluateJavascript(js);
  661. #elif WEB_VIEW_USING_MACOS_WEBKIT
  662. NSString* const nsjs = [[NSString alloc] initWithBytes:js
  663. length:std::strlen(js)
  664. encoding:NSUTF8StringEncoding];
  665. [handle->webview evaluateJavaScript:nsjs completionHandler:nil];
  666. [nsjs release];
  667. #elif WEB_VIEW_USING_X11_IPC
  668. d_debug("evaluateJS '%s'", js);
  669. const size_t len = std::strlen(js) + 1;
  670. handle->rbctrl.writeUInt(kWebViewMessageEvaluateJS) &&
  671. handle->rbctrl.writeUInt(len) &&
  672. handle->rbctrl.writeCustomData(js, len);
  673. if (handle->rbctrl.commitWrite())
  674. webview_wake(&handle->shmptr->client.sem);
  675. #endif
  676. // maybe unused
  677. (void)handle;
  678. (void)js;
  679. }
  680. void webViewReload(const WebViewHandle handle)
  681. {
  682. #if WEB_VIEW_USING_CHOC
  683. handle->webview->navigate(handle->url);
  684. #elif WEB_VIEW_USING_MACOS_WEBKIT
  685. [handle->webview loadRequest:handle->urlreq];
  686. #elif WEB_VIEW_USING_X11_IPC
  687. d_stdout("reload");
  688. handle->rbctrl.writeUInt(kWebViewMessageReload);
  689. if (handle->rbctrl.commitWrite())
  690. webview_wake(&handle->shmptr->client.sem);
  691. #endif
  692. // maybe unused
  693. (void)handle;
  694. }
  695. void webViewResize(const WebViewHandle handle, const uint width, const uint height, const double scaleFactor)
  696. {
  697. #if WEB_VIEW_USING_CHOC
  698. #ifdef DISTRHO_OS_MAC
  699. NSView* const view = static_cast<NSView*>(handle->webview->getViewHandle());
  700. [view setFrameSize:NSMakeSize(width / scaleFactor, height / scaleFactor)];
  701. #else
  702. const HWND hwnd = static_cast<HWND>(handle->webview->getViewHandle());
  703. SetWindowPos(hwnd, nullptr, 0, 0,
  704. width, height,
  705. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
  706. #endif
  707. #elif WEB_VIEW_USING_MACOS_WEBKIT
  708. [handle->webview setFrameSize:NSMakeSize(width / scaleFactor, height / scaleFactor)];
  709. #elif WEB_VIEW_USING_X11_IPC
  710. if (handle->childWindow == 0)
  711. {
  712. ::Window rootWindow, parentWindow;
  713. ::Window* childWindows = nullptr;
  714. uint numChildren = 0;
  715. XFlush(handle->display);
  716. XQueryTree(handle->display, handle->ourWindow, &rootWindow, &parentWindow, &childWindows, &numChildren);
  717. if (numChildren == 0 || childWindows == nullptr)
  718. return;
  719. handle->childWindow = childWindows[0];
  720. XFree(childWindows);
  721. }
  722. XResizeWindow(handle->display, handle->childWindow, width, height);
  723. XFlush(handle->display);
  724. #endif
  725. // maybe unused
  726. (void)handle;
  727. (void)width;
  728. (void)height;
  729. (void)scaleFactor;
  730. }
  731. #if WEB_VIEW_USING_X11_IPC
  732. // -----------------------------------------------------------------------------------------------------------
  733. static std::function<void(const char* js)> evaluateFn;
  734. static std::function<void()> reloadFn;
  735. static std::function<void()> terminateFn;
  736. static std::function<void(WebViewRingBuffer* rb)> wakeFn;
  737. // -----------------------------------------------------------------------------------------------------------
  738. struct GtkContainer;
  739. struct GtkPlug;
  740. struct GtkWidget;
  741. struct GtkWindow;
  742. struct JSCValue;
  743. struct WebKitJavascriptResult;
  744. struct WebKitSettings;
  745. struct WebKitUserContentManager;
  746. struct WebKitUserScript;
  747. struct WebKitWebView;
  748. typedef int gboolean;
  749. #define G_CALLBACK(p) reinterpret_cast<void*>(p)
  750. #define GTK_CONTAINER(p) reinterpret_cast<GtkContainer*>(p)
  751. #define GTK_PLUG(p) reinterpret_cast<GtkPlug*>(p)
  752. #define GTK_WINDOW(p) reinterpret_cast<GtkWindow*>(p)
  753. #define WEBKIT_WEB_VIEW(p) reinterpret_cast<WebKitWebView*>(p)
  754. // struct QApplication;
  755. // struct QUrl;
  756. // struct QWebEngineView;
  757. // struct QWindow;
  758. // -----------------------------------------------------------------------------------------------------------
  759. #define JOIN(A, B) A ## B
  760. #define AUTOSYM(S) \
  761. using JOIN(gtk3_, S) = decltype(&S); \
  762. JOIN(gtk3_, S) S = reinterpret_cast<JOIN(gtk3_, S)>(dlsym(nullptr, #S)); \
  763. DISTRHO_SAFE_ASSERT_RETURN(S != nullptr, false);
  764. #define CSYM(S, NAME) \
  765. S NAME = reinterpret_cast<S>(dlsym(nullptr, #NAME)); \
  766. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  767. #define CPPSYM(S, NAME, SN) \
  768. S NAME = reinterpret_cast<S>(dlsym(nullptr, #SN)); \
  769. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  770. // -----------------------------------------------------------------------------------------------------------
  771. // gtk3 variant
  772. static void gtk3_idle(void* const ptr)
  773. {
  774. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  775. RingBufferControl<WebViewSharedBuffer> rbctrl;
  776. rbctrl.setRingBuffer(&shmptr->client, false);
  777. uint32_t size = 0;
  778. void* buffer = nullptr;
  779. while (rbctrl.isDataAvailableForReading())
  780. {
  781. switch (rbctrl.readUInt())
  782. {
  783. case kWebViewMessageEvaluateJS:
  784. if (const uint32_t len = rbctrl.readUInt())
  785. {
  786. if (len > size)
  787. {
  788. size = len;
  789. buffer = realloc(buffer, len);
  790. if (buffer == nullptr)
  791. {
  792. d_stderr("lv2ui client out of memory, abort!");
  793. abort();
  794. }
  795. }
  796. if (rbctrl.readCustomData(buffer, len))
  797. {
  798. d_debug("client kWebViewMessageEvaluateJS -> '%s'", static_cast<char*>(buffer));
  799. evaluateFn(static_cast<char*>(buffer));
  800. continue;
  801. }
  802. }
  803. break;
  804. case kWebViewMessageReload:
  805. d_debug("client kWebViewMessageReload");
  806. reloadFn();
  807. continue;
  808. }
  809. d_stderr("client ringbuffer data race, abort!");
  810. abort();
  811. }
  812. free(buffer);
  813. }
  814. static int gtk3_js_cb(WebKitUserContentManager*, WebKitJavascriptResult* const result, void* const arg)
  815. {
  816. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(arg);
  817. using g_free_t = void (*)(void*);
  818. using jsc_value_to_string_t = char* (*)(JSCValue*);
  819. using webkit_javascript_result_get_js_value_t = JSCValue* (*)(WebKitJavascriptResult*);
  820. CSYM(g_free_t, g_free)
  821. CSYM(jsc_value_to_string_t, jsc_value_to_string)
  822. CSYM(webkit_javascript_result_get_js_value_t, webkit_javascript_result_get_js_value)
  823. JSCValue* const value = webkit_javascript_result_get_js_value(result);
  824. DISTRHO_SAFE_ASSERT_RETURN(value != nullptr, false);
  825. char* const string = jsc_value_to_string(value);
  826. DISTRHO_SAFE_ASSERT_RETURN(string != nullptr, false);
  827. d_debug("js call received with data '%s'", string);
  828. const size_t len = std::strlen(string);
  829. RingBufferControl<WebViewSharedBuffer> rbctrl2;
  830. rbctrl2.setRingBuffer(&shmptr->server, false);
  831. rbctrl2.writeUInt(kWebViewMessageCallback) &&
  832. rbctrl2.writeUInt(len) &&
  833. rbctrl2.writeCustomData(string, len);
  834. rbctrl2.commitWrite();
  835. g_free(string);
  836. return 0;
  837. }
  838. static bool gtk3(Display* const display,
  839. const Window winId,
  840. const int x,
  841. const int y,
  842. const uint width,
  843. const uint height,
  844. double scaleFactor,
  845. const char* const url,
  846. const char* const initialJS,
  847. WebViewRingBuffer* const shmptr)
  848. {
  849. void* lib;
  850. if ((lib = dlopen("libwebkit2gtk-4.0.so.37", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  851. (lib = dlopen("libwebkit2gtk-4.0.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  852. return false;
  853. using g_main_context_invoke_t = void (*)(void*, void*, void*);
  854. using g_signal_connect_data_t = ulong (*)(void*, const char*, void*, void*, void*, int);
  855. using gdk_set_allowed_backends_t = void (*)(const char*);
  856. using gtk_container_add_t = void (*)(GtkContainer*, GtkWidget*);
  857. using gtk_init_check_t = gboolean (*)(int*, char***);
  858. using gtk_main_t = void (*)();
  859. using gtk_main_quit_t = void (*)();
  860. using gtk_plug_get_id_t = Window (*)(GtkPlug*);
  861. using gtk_plug_new_t = GtkWidget* (*)(Window);
  862. using gtk_widget_show_all_t = void (*)(GtkWidget*);
  863. using gtk_window_move_t = void (*)(GtkWindow*, int, int);
  864. using gtk_window_set_default_size_t = void (*)(GtkWindow*, int, int);
  865. using webkit_settings_new_t = WebKitSettings* (*)();
  866. using webkit_settings_set_enable_developer_extras_t = void (*)(WebKitSettings*, gboolean);
  867. using webkit_settings_set_enable_write_console_messages_to_stdout_t = void (*)(WebKitSettings*, gboolean);
  868. using webkit_settings_set_hardware_acceleration_policy_t = void (*)(WebKitSettings*, int);
  869. using webkit_settings_set_javascript_can_access_clipboard_t = void (*)(WebKitSettings*, gboolean);
  870. using webkit_user_content_manager_add_script_t = void (*)(WebKitUserContentManager*, WebKitUserScript*);
  871. using webkit_user_content_manager_register_script_message_handler_t = gboolean (*)(WebKitUserContentManager*, const char*);
  872. using webkit_user_script_new_t = WebKitUserScript* (*)(const char*, int, int, const char* const*, const char* const*);
  873. using webkit_web_view_evaluate_javascript_t = void* (*)(WebKitWebView*, const char*, ssize_t, const char*, const char*, void*, void*, void*);
  874. using webkit_web_view_get_user_content_manager_t = WebKitUserContentManager* (*)(WebKitWebView*);
  875. using webkit_web_view_load_uri_t = void (*)(WebKitWebView*, const char*);
  876. using webkit_web_view_new_with_settings_t = GtkWidget* (*)(WebKitSettings*);
  877. using webkit_web_view_run_javascript_t = void* (*)(WebKitWebView*, const char*, void*, void*, void*);
  878. using webkit_web_view_set_background_color_t = void (*)(WebKitWebView*, const double*);
  879. CSYM(g_main_context_invoke_t, g_main_context_invoke)
  880. CSYM(g_signal_connect_data_t, g_signal_connect_data)
  881. CSYM(gdk_set_allowed_backends_t, gdk_set_allowed_backends)
  882. CSYM(gtk_container_add_t, gtk_container_add)
  883. CSYM(gtk_init_check_t, gtk_init_check)
  884. CSYM(gtk_main_t, gtk_main)
  885. CSYM(gtk_main_quit_t, gtk_main_quit)
  886. CSYM(gtk_plug_get_id_t, gtk_plug_get_id)
  887. CSYM(gtk_plug_new_t, gtk_plug_new)
  888. CSYM(gtk_widget_show_all_t, gtk_widget_show_all)
  889. CSYM(gtk_window_move_t, gtk_window_move)
  890. CSYM(gtk_window_set_default_size_t, gtk_window_set_default_size)
  891. CSYM(webkit_settings_new_t, webkit_settings_new)
  892. CSYM(webkit_settings_set_enable_developer_extras_t, webkit_settings_set_enable_developer_extras)
  893. CSYM(webkit_settings_set_enable_write_console_messages_to_stdout_t, webkit_settings_set_enable_write_console_messages_to_stdout)
  894. CSYM(webkit_settings_set_hardware_acceleration_policy_t, webkit_settings_set_hardware_acceleration_policy)
  895. CSYM(webkit_settings_set_javascript_can_access_clipboard_t, webkit_settings_set_javascript_can_access_clipboard)
  896. CSYM(webkit_user_content_manager_add_script_t, webkit_user_content_manager_add_script)
  897. CSYM(webkit_user_content_manager_register_script_message_handler_t, webkit_user_content_manager_register_script_message_handler)
  898. CSYM(webkit_user_script_new_t, webkit_user_script_new)
  899. CSYM(webkit_web_view_get_user_content_manager_t, webkit_web_view_get_user_content_manager)
  900. CSYM(webkit_web_view_load_uri_t, webkit_web_view_load_uri)
  901. CSYM(webkit_web_view_new_with_settings_t, webkit_web_view_new_with_settings)
  902. CSYM(webkit_web_view_set_background_color_t, webkit_web_view_set_background_color)
  903. // special case for legacy API handling
  904. 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"));
  905. 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"));
  906. DISTRHO_SAFE_ASSERT_RETURN(webkit_web_view_evaluate_javascript != nullptr || webkit_web_view_run_javascript != nullptr, false);
  907. const int gdkScale = std::fmod(scaleFactor, 1.0) >= 0.75
  908. ? static_cast<int>(scaleFactor + 0.5)
  909. : static_cast<int>(scaleFactor);
  910. if (gdkScale != 1)
  911. {
  912. char scale[8] = {};
  913. std::snprintf(scale, 7, "%d", gdkScale);
  914. setenv("GDK_SCALE", scale, 1);
  915. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.2);
  916. setenv("GDK_DPI_SCALE", scale, 1);
  917. }
  918. else if (scaleFactor > 1.0)
  919. {
  920. char scale[8] = {};
  921. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.4);
  922. setenv("GDK_DPI_SCALE", scale, 1);
  923. }
  924. scaleFactor /= gdkScale;
  925. gdk_set_allowed_backends("x11");
  926. if (! gtk_init_check (nullptr, nullptr))
  927. return false;
  928. GtkWidget* const window = gtk_plug_new(winId);
  929. DISTRHO_SAFE_ASSERT_RETURN(window != nullptr, false);
  930. gtk_window_set_default_size(GTK_WINDOW(window),
  931. (width - x) * scaleFactor,
  932. (height - y) * scaleFactor);
  933. gtk_window_move(GTK_WINDOW(window), x * scaleFactor, y * scaleFactor);
  934. WebKitSettings* const settings = webkit_settings_new();
  935. DISTRHO_SAFE_ASSERT_RETURN(settings != nullptr, false);
  936. // TODO DOMPasteAllowed
  937. webkit_settings_set_javascript_can_access_clipboard(settings, true);
  938. webkit_settings_set_hardware_acceleration_policy(settings, 2 /* WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER */);
  939. // if (debug)
  940. {
  941. webkit_settings_set_enable_developer_extras(settings, true);
  942. webkit_settings_set_enable_write_console_messages_to_stdout(settings, true);
  943. }
  944. GtkWidget* const webview = webkit_web_view_new_with_settings(settings);
  945. DISTRHO_SAFE_ASSERT_RETURN(webview != nullptr, false);
  946. const double color[] = {49.0/255, 54.0/255, 59.0/255, 1};
  947. webkit_web_view_set_background_color(WEBKIT_WEB_VIEW(webview), color);
  948. if (WebKitUserContentManager* const manager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(webview)))
  949. {
  950. g_signal_connect_data(manager, "script-message-received::external", G_CALLBACK(gtk3_js_cb), shmptr, nullptr, 0);
  951. webkit_user_content_manager_register_script_message_handler(manager, "external");
  952. WebKitUserScript* const mscript = webkit_user_script_new(
  953. "function postMessage(m){window.webkit.messageHandlers.external.postMessage(m)}", 0, 0, nullptr, nullptr);
  954. webkit_user_content_manager_add_script(manager, mscript);
  955. if (initialJS != nullptr)
  956. {
  957. WebKitUserScript* const script = webkit_user_script_new(initialJS, 0, 0, nullptr, nullptr);
  958. webkit_user_content_manager_add_script(manager, script);
  959. }
  960. }
  961. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  962. gtk_container_add(GTK_CONTAINER(window), webview);
  963. gtk_widget_show_all(window);
  964. Window wid = gtk_plug_get_id(GTK_PLUG(window));
  965. XMapWindow(display, wid);
  966. XFlush(display);
  967. evaluateFn = [=](const char* const js){
  968. if (webkit_web_view_evaluate_javascript != nullptr)
  969. webkit_web_view_evaluate_javascript(WEBKIT_WEB_VIEW(webview), js, -1,
  970. nullptr, nullptr, nullptr, nullptr, nullptr);
  971. else
  972. webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(webview), js, nullptr, nullptr, nullptr);
  973. };
  974. reloadFn = [=](){
  975. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  976. };
  977. terminateFn = [=](){
  978. d_stdout("terminateFn");
  979. static bool quit = true;
  980. if (quit)
  981. {
  982. quit = false;
  983. gtk_main_quit();
  984. }
  985. };
  986. wakeFn = [=](WebViewRingBuffer* const rb){
  987. g_main_context_invoke(NULL, G_CALLBACK(gtk3_idle), rb);
  988. };
  989. // notify server we started ok
  990. webview_wake(&shmptr->server.sem);
  991. gtk_main();
  992. d_stdout("quit");
  993. dlclose(lib);
  994. return true;
  995. }
  996. #if 0
  997. // -----------------------------------------------------------------------------------------------------------
  998. // qt5webengine variant
  999. static bool qt5webengine(const Window winId, const double scaleFactor, const char* const url)
  1000. {
  1001. void* lib;
  1002. if ((lib = dlopen("libQt5WebEngineWidgets.so.5", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  1003. (lib = dlopen("libQt5WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  1004. return false;
  1005. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  1006. using QApplication_exec_t = void (*)();
  1007. using QApplication_setAttribute_t = void (*)(Qt::ApplicationAttribute, bool);
  1008. using QString__init_t = void (*)(void*, const QChar*, ptrdiff_t);
  1009. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  1010. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  1011. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  1012. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  1013. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  1014. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  1015. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  1016. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  1017. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  1018. using QWindow_setParent_t = void (*)(QWindow*, void*);
  1019. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  1020. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  1021. CPPSYM(QApplication_setAttribute_t, QApplication_setAttribute, _ZN16QCoreApplication12setAttributeEN2Qt20ApplicationAttributeEb)
  1022. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QChari)
  1023. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  1024. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  1025. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1026. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1027. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1028. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1029. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1030. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1031. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1032. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1033. unsetenv("QT_FONT_DPI");
  1034. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1035. unsetenv("QT_USE_PHYSICAL_DPI");
  1036. setenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0", 1);
  1037. char scale[8] = {};
  1038. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1039. setenv("QT_SCALE_FACTOR", scale, 1);
  1040. QApplication_setAttribute(Qt::AA_X11InitThreads, true);
  1041. QApplication_setAttribute(Qt::AA_EnableHighDpiScaling, true);
  1042. QApplication_setAttribute(Qt::AA_UseHighDpiPixmaps, true);
  1043. static int argc = 0;
  1044. static char* argv[] = { nullptr };
  1045. uint8_t _app[64]; // sizeof(QApplication) == 16
  1046. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1047. QApplication__init(app, argc, argv, 0);
  1048. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1049. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1050. {
  1051. const size_t url_len = std::strlen(url);
  1052. QChar* const url_qchar = new QChar[url_len + 1];
  1053. for (size_t i = 0; i < url_len; ++i)
  1054. url_qchar[i] = QChar(url[i]);
  1055. url_qchar[url_len] = 0;
  1056. QString__init(qstrurl, url_qchar, url_len);
  1057. }
  1058. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1059. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1060. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1061. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1062. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1063. QWebEngineView__init(webview, nullptr);
  1064. QWebEngineView_move(webview, QPoint(0, kVerticalOffset));
  1065. QWebEngineView_resize(webview, QSize(DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT - kVerticalOffset));
  1066. QWebEngineView_winId(webview);
  1067. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1068. QWebEngineView_setUrl(webview, *qurl);
  1069. QWebEngineView_show(webview);
  1070. reloadFn = [=](){
  1071. QWebEngineView_setUrl(webview, *qurl);
  1072. };
  1073. terminateFn = [=](){
  1074. // TODO
  1075. };
  1076. QApplication_exec();
  1077. dlclose(lib);
  1078. return true;
  1079. }
  1080. // -----------------------------------------------------------------------------------------------------------
  1081. // qt6webengine variant (same as qt5 but `QString__init_t` has different arguments)
  1082. static bool qt6webengine(const Window winId, const double scaleFactor, const char* const url)
  1083. {
  1084. void* lib;
  1085. if ((lib = dlopen("libQt6WebEngineWidgets.so.6", RTLD_NOW|RTLD_GLOBAL)) == nullptr ||
  1086. (lib = dlopen("libQt6WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  1087. return false;
  1088. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  1089. using QApplication_exec_t = void (*)();
  1090. using QApplication_setAttribute_t = void (*)(Qt::ApplicationAttribute, bool);
  1091. using QString__init_t = void (*)(void*, const QChar*, long long);
  1092. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  1093. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  1094. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  1095. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  1096. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  1097. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  1098. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  1099. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  1100. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  1101. using QWindow_setParent_t = void (*)(QWindow*, void*);
  1102. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  1103. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  1104. CPPSYM(QApplication_setAttribute_t, QApplication_setAttribute, _ZN16QCoreApplication12setAttributeEN2Qt20ApplicationAttributeEb)
  1105. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QCharx)
  1106. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  1107. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  1108. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1109. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1110. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1111. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1112. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1113. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1114. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1115. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1116. unsetenv("QT_FONT_DPI");
  1117. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1118. unsetenv("QT_USE_PHYSICAL_DPI");
  1119. setenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0", 1);
  1120. char scale[8] = {};
  1121. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1122. setenv("QT_SCALE_FACTOR", scale, 1);
  1123. QApplication_setAttribute(Qt::AA_X11InitThreads, true);
  1124. QApplication_setAttribute(Qt::AA_EnableHighDpiScaling, true);
  1125. QApplication_setAttribute(Qt::AA_UseHighDpiPixmaps, true);
  1126. static int argc = 0;
  1127. static char* argv[] = { nullptr };
  1128. uint8_t _app[64]; // sizeof(QApplication) == 16
  1129. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1130. QApplication__init(app, argc, argv, 0);
  1131. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1132. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1133. {
  1134. const size_t url_len = std::strlen(url);
  1135. QChar* const url_qchar = new QChar[url_len + 1];
  1136. for (size_t i = 0; i < url_len; ++i)
  1137. url_qchar[i] = QChar(url[i]);
  1138. url_qchar[url_len] = 0;
  1139. QString__init(qstrurl, url_qchar, url_len);
  1140. }
  1141. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1142. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1143. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1144. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1145. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1146. QWebEngineView__init(webview, nullptr);
  1147. QWebEngineView_move(webview, QPoint(0, kVerticalOffset));
  1148. QWebEngineView_resize(webview, QSize(DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT - kVerticalOffset));
  1149. QWebEngineView_winId(webview);
  1150. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1151. QWebEngineView_setUrl(webview, *qurl);
  1152. QWebEngineView_show(webview);
  1153. reloadFn = [=](){
  1154. QWebEngineView_setUrl(webview, *qurl);
  1155. };
  1156. terminateFn = [=](){
  1157. // TODO
  1158. };
  1159. QApplication_exec();
  1160. dlclose(lib);
  1161. return true;
  1162. }
  1163. #endif
  1164. // -----------------------------------------------------------------------------------------------------------
  1165. // startup via ld-linux
  1166. static void signalHandler(const int sig)
  1167. {
  1168. switch (sig)
  1169. {
  1170. case SIGTERM:
  1171. terminateFn();
  1172. break;
  1173. }
  1174. }
  1175. static void* threadHandler(void* const ptr)
  1176. {
  1177. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  1178. // TODO wait until page is loaded, or something better
  1179. d_sleep(1);
  1180. while (shmptr->valid)
  1181. {
  1182. if (webview_timedwait(&shmptr->client.sem))
  1183. wakeFn(shmptr);
  1184. }
  1185. return nullptr;
  1186. }
  1187. int dpf_webview_start(const int argc, char* argv[])
  1188. {
  1189. d_stdout("started %d %s", argc, argv[1]);
  1190. if (argc != 3)
  1191. {
  1192. d_stderr("WebView entry point, nothing to see here! ;)");
  1193. return 1;
  1194. }
  1195. uselocale(newlocale(LC_NUMERIC_MASK, "C", nullptr));
  1196. Display* const display = XOpenDisplay(nullptr);
  1197. DISTRHO_SAFE_ASSERT_RETURN(display != nullptr, 1);
  1198. const char* const shmname = argv[2];
  1199. const int shmfd = shm_open(shmname, O_RDWR, 0);
  1200. if (shmfd < 0)
  1201. {
  1202. d_stderr("shm_open failed: %s", std::strerror(errno));
  1203. return 1;
  1204. }
  1205. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(mmap(nullptr,
  1206. sizeof(WebViewRingBuffer),
  1207. PROT_READ|PROT_WRITE,
  1208. MAP_SHARED,
  1209. shmfd, 0));
  1210. if (shmptr == nullptr || shmptr == nullptr)
  1211. {
  1212. d_stderr("mmap failed: %s", std::strerror(errno));
  1213. close(shmfd);
  1214. return 1;
  1215. }
  1216. RingBufferControl<WebViewSharedBuffer> rbctrl;
  1217. rbctrl.setRingBuffer(&shmptr->client, false);
  1218. // fetch initial data
  1219. bool hasInitialData = false;
  1220. Window winId = 0;
  1221. uint width = 0, height = 0;
  1222. double scaleFactor = 0;
  1223. int x = 0, y = 0;
  1224. char* url = nullptr;
  1225. char* initJS = nullptr;
  1226. while (shmptr->valid && webview_timedwait(&shmptr->client.sem))
  1227. {
  1228. if (rbctrl.isDataAvailableForReading())
  1229. {
  1230. DISTRHO_SAFE_ASSERT_RETURN(rbctrl.readUInt() == kWebViewMessageInitData, 1);
  1231. hasInitialData = true;
  1232. winId = rbctrl.readULong();
  1233. width = rbctrl.readUInt();
  1234. height = rbctrl.readUInt();
  1235. scaleFactor = rbctrl.readDouble();
  1236. x = rbctrl.readInt();
  1237. y = rbctrl.readInt();
  1238. const uint urllen = rbctrl.readUInt();
  1239. url = static_cast<char*>(std::malloc(urllen));
  1240. rbctrl.readCustomData(url, urllen);
  1241. if (const uint initjslen = rbctrl.readUInt())
  1242. {
  1243. initJS = static_cast<char*>(std::malloc(initjslen));
  1244. rbctrl.readCustomData(initJS, initjslen);
  1245. }
  1246. }
  1247. }
  1248. pthread_t thread;
  1249. if (hasInitialData && pthread_create(&thread, nullptr, threadHandler, shmptr) == 0)
  1250. {
  1251. struct sigaction sig = {};
  1252. sig.sa_handler = signalHandler;
  1253. sig.sa_flags = SA_RESTART;
  1254. sigemptyset(&sig.sa_mask);
  1255. sigaction(SIGTERM, &sig, nullptr);
  1256. // qt5webengine(winId, scaleFactor, url) ||
  1257. // qt6webengine(winId, scaleFactor, url) ||
  1258. gtk3(display, winId, x, y, width, height, scaleFactor, url, initJS, shmptr);
  1259. shmptr->valid = false;
  1260. pthread_join(thread, nullptr);
  1261. }
  1262. munmap(shmptr, sizeof(WebViewRingBuffer));
  1263. close(shmfd);
  1264. XCloseDisplay(display);
  1265. return 0;
  1266. }
  1267. // --------------------------------------------------------------------------------------------------------------------
  1268. #endif // WEB_VIEW_USING_X11_IPC
  1269. #ifdef WEB_VIEW_DGL_NAMESPACE
  1270. END_NAMESPACE_DGL
  1271. #else
  1272. END_NAMESPACE_DISTRHO
  1273. #endif
  1274. #undef MACRO_NAME
  1275. #undef MACRO_NAME2
  1276. #undef WEB_VIEW_DISTRHO_NAMESPACE
  1277. #undef WEB_VIEW_DGL_NAMESPACE