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.

1689 lines
57KB

  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. // #undef Bool
  23. // #undef CursorShape
  24. // #undef Expose
  25. // #undef FocusIn
  26. // #undef FocusOut
  27. // #undef FontChange
  28. // #undef KeyPress
  29. // #undef KeyRelease
  30. // #undef None
  31. // #undef Status
  32. // #include <QGuiApplication>
  33. // #include <QEvent>
  34. // #include <gtk/gtk.h>
  35. // #include <gtk/gtkx.h>
  36. // #include <webkit2/webkit2.h>
  37. #ifdef DISTRHO_OS_MAC
  38. # define WEB_VIEW_USING_MACOS_WEBKIT 1
  39. #else
  40. # define WEB_VIEW_USING_MACOS_WEBKIT 0
  41. #endif
  42. #ifdef DISTRHO_OS_WINDOWS
  43. # define WEB_VIEW_USING_CHOC 1
  44. #else
  45. # define WEB_VIEW_USING_CHOC 0
  46. #endif
  47. #if defined(HAVE_X11) && defined(DISTRHO_OS_LINUX)
  48. # define WEB_VIEW_USING_X11_IPC 1
  49. #else
  50. # define WEB_VIEW_USING_X11_IPC 0
  51. #endif
  52. #if WEB_VIEW_USING_CHOC
  53. # include "WebViewWin32.hpp"
  54. # include "String.hpp"
  55. #elif WEB_VIEW_USING_MACOS_WEBKIT
  56. # include <Cocoa/Cocoa.h>
  57. # include <WebKit/WebKit.h>
  58. #elif WEB_VIEW_USING_X11_IPC
  59. // #define QT_NO_VERSION_TAGGING
  60. // #include <QtCore/QChar>
  61. // #include <QtCore/QPoint>
  62. // #include <QtCore/QSize>
  63. // #undef signals
  64. # include "ChildProcess.hpp"
  65. # include "RingBuffer.hpp"
  66. # include "String.hpp"
  67. # include <clocale>
  68. # include <cstdio>
  69. # include <functional>
  70. # include <dlfcn.h>
  71. # include <fcntl.h>
  72. # include <pthread.h>
  73. # include <unistd.h>
  74. # include <sys/mman.h>
  75. # include <X11/Xlib.h>
  76. # ifdef __linux__
  77. # include <syscall.h>
  78. # include <linux/futex.h>
  79. # include <linux/limits.h>
  80. # else
  81. # include <semaphore.h>
  82. # endif
  83. #endif
  84. // -----------------------------------------------------------------------------------------------------------
  85. #if WEB_VIEW_USING_MACOS_WEBKIT
  86. #define MACRO_NAME2(a, b, c) a ## b ## c
  87. #define MACRO_NAME(a, b, c) MACRO_NAME2(a, b, c)
  88. #define WEB_VIEW_DELEGATE_CLASS_NAME \
  89. MACRO_NAME(WebViewDelegate_, _, DISTRHO_NAMESPACE)
  90. @interface WEB_VIEW_DELEGATE_CLASS_NAME : NSObject<WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate>
  91. @end
  92. @implementation WEB_VIEW_DELEGATE_CLASS_NAME {
  93. @public
  94. WebViewMessageCallback callback;
  95. void* callbackPtr;
  96. bool loaded;
  97. }
  98. - (void)webView:(WKWebView *)webview
  99. didFinishNavigation:(WKNavigation*)navigation
  100. {
  101. d_stdout("page loaded");
  102. loaded = true;
  103. }
  104. - (void)webView:(WKWebView*)webview
  105. runJavaScriptAlertPanelWithMessage:(NSString*)message
  106. initiatedByFrame:(WKFrameInfo*)frame
  107. completionHandler:(void (^)(void))completionHandler
  108. {
  109. NSAlert* const alert = [[NSAlert alloc] init];
  110. [alert addButtonWithTitle:@"OK"];
  111. [alert setInformativeText:message];
  112. [alert setMessageText:@"Alert"];
  113. dispatch_async(dispatch_get_main_queue(), ^
  114. {
  115. [alert beginSheetModalForWindow:[webview window]
  116. completionHandler:^(NSModalResponse)
  117. {
  118. completionHandler();
  119. [alert release];
  120. }];
  121. });
  122. }
  123. - (void)webView:(WKWebView*)webview
  124. runJavaScriptConfirmPanelWithMessage:(NSString*)message
  125. initiatedByFrame:(WKFrameInfo*)frame
  126. completionHandler:(void (^)(BOOL))completionHandler
  127. {
  128. NSAlert* const alert = [[NSAlert alloc] init];
  129. [alert addButtonWithTitle:@"OK"];
  130. [alert addButtonWithTitle:@"Cancel"];
  131. [alert setInformativeText:message];
  132. [alert setMessageText:@"Confirm"];
  133. dispatch_async(dispatch_get_main_queue(), ^
  134. {
  135. [alert beginSheetModalForWindow:[webview window]
  136. completionHandler:^(NSModalResponse result)
  137. {
  138. completionHandler(result == NSAlertFirstButtonReturn);
  139. [alert release];
  140. }];
  141. });
  142. }
  143. - (void)webView:(WKWebView*)webview
  144. runJavaScriptTextInputPanelWithPrompt:(NSString*)prompt
  145. defaultText:(NSString*)defaultText
  146. initiatedByFrame:(WKFrameInfo*)frame
  147. completionHandler:(void (^)(NSString*))completionHandler
  148. {
  149. NSTextField* const input = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
  150. [input setStringValue:defaultText];
  151. NSAlert* const alert = [[NSAlert alloc] init];
  152. [alert setAccessoryView:input];
  153. [alert addButtonWithTitle:@"OK"];
  154. [alert addButtonWithTitle:@"Cancel"];
  155. [alert setInformativeText:prompt];
  156. [alert setMessageText: @"Prompt"];
  157. dispatch_async(dispatch_get_main_queue(), ^
  158. {
  159. [alert beginSheetModalForWindow:[webview window]
  160. completionHandler:^(NSModalResponse result)
  161. {
  162. [input validateEditing];
  163. completionHandler(result == NSAlertFirstButtonReturn ? [input stringValue] : nil);
  164. [alert release];
  165. }];
  166. });
  167. }
  168. - (void)webView:(WKWebView*)webview
  169. runOpenPanelWithParameters:(WKOpenPanelParameters*)params
  170. initiatedByFrame:(WKFrameInfo*)frame
  171. completionHandler:(void (^)(NSArray<NSURL*>*))completionHandler
  172. {
  173. NSOpenPanel* const panel = [[NSOpenPanel alloc] init];
  174. [panel setAllowsMultipleSelection:[params allowsMultipleSelection]];
  175. // [panel setAllowedFileTypes:(NSArray<NSString*>*)[params _allowedFileExtensions]];
  176. [panel setCanChooseDirectories:[params allowsDirectories]];
  177. [panel setCanChooseFiles:![params allowsDirectories]];
  178. dispatch_async(dispatch_get_main_queue(), ^
  179. {
  180. [panel beginSheetModalForWindow:[webview window]
  181. completionHandler:^(NSModalResponse result)
  182. {
  183. completionHandler(result == NSModalResponseOK ? [panel URLs] : nil);
  184. [panel release];
  185. }];
  186. });
  187. }
  188. - (void)userContentController:(WKUserContentController*)userContentController
  189. didReceiveScriptMessage:(WKScriptMessage*)message
  190. {
  191. NSString* const nsstring = static_cast<NSString*>([message body]);
  192. char* const string = strdup([nsstring UTF8String]);
  193. d_debug("JS call received '%s' %p", string, callback);
  194. if (callback != nullptr)
  195. callback(callbackPtr, string);
  196. std::free(string);
  197. }
  198. @end
  199. #endif // WEB_VIEW_USING_MACOS_WEBKIT
  200. // -----------------------------------------------------------------------------------------------------------
  201. #ifdef WEB_VIEW_DGL_NAMESPACE
  202. START_NAMESPACE_DGL
  203. using DISTRHO_NAMESPACE::String;
  204. #else
  205. START_NAMESPACE_DISTRHO
  206. #endif
  207. // -----------------------------------------------------------------------------------------------------------
  208. #if WEB_VIEW_USING_X11_IPC
  209. #ifdef __linux__
  210. typedef int32_t ipc_sem_t;
  211. #else
  212. typedef sem_t ipc_sem_t;
  213. #endif
  214. enum WebViewMessageType {
  215. kWebViewMessageNull,
  216. kWebViewMessageInitData,
  217. kWebViewMessageEvaluateJS,
  218. kWebViewMessageCallback,
  219. kWebViewMessageReload
  220. };
  221. struct WebViewSharedBuffer {
  222. static constexpr const uint32_t size = 0x100000;
  223. ipc_sem_t sem;
  224. uint32_t head, tail, wrtn;
  225. bool invalidateCommit;
  226. uint8_t buf[size];
  227. };
  228. struct WebViewRingBuffer {
  229. WebViewSharedBuffer server;
  230. WebViewSharedBuffer client;
  231. bool valid;
  232. };
  233. static void webview_wake(ipc_sem_t* const sem)
  234. {
  235. #ifdef __linux__
  236. if (__sync_bool_compare_and_swap(sem, 0, 1))
  237. syscall(SYS_futex, sem, FUTEX_WAKE, 1, nullptr, nullptr, 0);
  238. #else
  239. sem_post(sem);
  240. #endif
  241. }
  242. static bool webview_timedwait(ipc_sem_t* const sem)
  243. {
  244. #ifdef __linux__
  245. const struct timespec timeout = { 1, 0 };
  246. for (;;)
  247. {
  248. if (__sync_bool_compare_and_swap(sem, 1, 0))
  249. return true;
  250. if (syscall(SYS_futex, sem, FUTEX_WAIT, 0, &timeout, nullptr, 0) != 0)
  251. if (errno != EAGAIN && errno != EINTR)
  252. return false;
  253. }
  254. #else
  255. struct timespec timeout;
  256. if (clock_gettime(CLOCK_REALTIME, &timeout) != 0)
  257. return false;
  258. timeout.tv_sec += 1;
  259. for (int r;;)
  260. {
  261. r = sem_timedwait(sem, &timeout);
  262. if (r < 0)
  263. r = errno;
  264. if (r == EINTR)
  265. continue;
  266. return r == 0;
  267. }
  268. #endif
  269. }
  270. static void getFilenameFromFunctionPtr(char filename[PATH_MAX], const void* const ptr)
  271. {
  272. Dl_info info = {};
  273. dladdr(ptr, &info);
  274. if (info.dli_fname[0] == '.' && info.dli_fname[1] != '.')
  275. {
  276. if (getcwd(filename, PATH_MAX - 1) == nullptr)
  277. filename[0] = '\0';
  278. std::strncat(filename, info.dli_fname + 1, PATH_MAX - 1);
  279. }
  280. else if (info.dli_fname[0] != '/')
  281. {
  282. if (getcwd(filename, PATH_MAX - 1) == nullptr)
  283. filename[0] = '\0';
  284. else
  285. std::strncat(filename, "/", PATH_MAX - 1);
  286. std::strncat(filename, info.dli_fname, PATH_MAX - 1);
  287. }
  288. else
  289. {
  290. std::strncpy(filename, info.dli_fname, PATH_MAX - 1);
  291. }
  292. }
  293. #endif // WEB_VIEW_USING_X11_IPC
  294. // -----------------------------------------------------------------------------------------------------------
  295. struct WebViewData {
  296. #if WEB_VIEW_USING_CHOC
  297. WebView* webview;
  298. String url;
  299. #elif WEB_VIEW_USING_MACOS_WEBKIT
  300. NSView* view;
  301. WKWebView* webview;
  302. NSURLRequest* urlreq;
  303. WEB_VIEW_DELEGATE_CLASS_NAME* delegate;
  304. #elif WEB_VIEW_USING_X11_IPC
  305. int shmfd = 0;
  306. char shmname[128] = {};
  307. WebViewRingBuffer* shmptr = nullptr;
  308. WebViewMessageCallback callback = nullptr;
  309. void* callbackPtr = nullptr;
  310. ChildProcess p;
  311. RingBufferControl<WebViewSharedBuffer> rbctrl, rbctrl2;
  312. ::Display* display = nullptr;
  313. ::Window childWindow = 0;
  314. ::Window ourWindow = 0;
  315. #endif
  316. WebViewData() {}
  317. DISTRHO_DECLARE_NON_COPYABLE(WebViewData);
  318. };
  319. // -----------------------------------------------------------------------------------------------------------
  320. WebViewHandle webViewCreate(const char* const url,
  321. const uintptr_t windowId,
  322. const uint initialWidth,
  323. const uint initialHeight,
  324. const double scaleFactor,
  325. const WebViewOptions& options)
  326. {
  327. #if WEB_VIEW_USING_CHOC
  328. WebView* const webview = webview_choc_create(options);
  329. if (webview == nullptr)
  330. return nullptr;
  331. const HWND hwnd = static_cast<HWND>(webview_choc_handle(webview));
  332. LONG_PTR flags = GetWindowLongPtr(hwnd, -16);
  333. flags = (flags & ~WS_POPUP) | WS_CHILD;
  334. SetWindowLongPtr(hwnd, -16, flags);
  335. SetParent(hwnd, reinterpret_cast<HWND>(windowId));
  336. SetWindowPos(hwnd, nullptr,
  337. options.offset.x,
  338. options.offset.y,
  339. initialWidth - options.offset.x,
  340. initialHeight - options.offset.y,
  341. SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
  342. ShowWindow(hwnd, SW_SHOW);
  343. WebViewData* const whandle = new WebViewData;
  344. whandle->webview = webview;
  345. whandle->url = url;
  346. webview_choc_navigate(webview, url);
  347. return whandle;
  348. #elif WEB_VIEW_USING_MACOS_WEBKIT
  349. NSView* const view = reinterpret_cast<NSView*>(windowId);
  350. WKPreferences* const prefs = [[WKPreferences alloc] init];
  351. [prefs setValue:@YES forKey:@"javaScriptCanAccessClipboard"];
  352. [prefs setValue:@YES forKey:@"DOMPasteAllowed"];
  353. // if (debug)
  354. {
  355. [prefs setValue:@YES forKey:@"developerExtrasEnabled"];
  356. // TODO enable_write_console_messages_to_stdout
  357. }
  358. WKWebViewConfiguration* const config = [[WKWebViewConfiguration alloc] init];
  359. config.limitsNavigationsToAppBoundDomains = false;
  360. config.preferences = prefs;
  361. const CGRect rect = CGRectMake(options.offset.x / scaleFactor,
  362. options.offset.y / scaleFactor,
  363. initialWidth / scaleFactor,
  364. initialHeight / scaleFactor);
  365. WKWebView* const webview = [[WKWebView alloc] initWithFrame:rect
  366. configuration:config];
  367. [webview setHidden:YES];
  368. [view addSubview:webview];
  369. // TODO webkit_web_view_set_background_color
  370. WEB_VIEW_DELEGATE_CLASS_NAME* const delegate = [[WEB_VIEW_DELEGATE_CLASS_NAME alloc] init];
  371. delegate->callback = options.callback;
  372. delegate->callbackPtr = options.callbackPtr;
  373. delegate->loaded = false;
  374. if (WKUserContentController* const controller = [config userContentController])
  375. {
  376. [controller addScriptMessageHandler:delegate name:@"external"];
  377. WKUserScript* const mscript = [[WKUserScript alloc]
  378. initWithSource:(options.callback != nullptr
  379. ? @"function postMessage(m){window.webkit.messageHandlers.external.postMessage(m)}"
  380. : @"function postMessage(m){}")
  381. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  382. forMainFrameOnly:true
  383. ];
  384. [controller addUserScript:mscript];
  385. [mscript release];
  386. if (options.initialJS != nullptr)
  387. {
  388. NSString* const nsInitialJS = [[NSString alloc] initWithBytes:options.initialJS
  389. length:std::strlen(options.initialJS)
  390. encoding:NSUTF8StringEncoding];
  391. WKUserScript* const script = [[WKUserScript alloc] initWithSource:nsInitialJS
  392. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  393. forMainFrameOnly:true];
  394. [controller addUserScript:script];
  395. [script release];
  396. [nsInitialJS release];
  397. }
  398. }
  399. [webview setNavigationDelegate:delegate];
  400. [webview setUIDelegate:delegate];
  401. NSString* const nsurl = [[NSString alloc] initWithBytes:url
  402. length:std::strlen(url)
  403. encoding:NSUTF8StringEncoding];
  404. NSURLRequest* const urlreq = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: nsurl]];
  405. d_stdout("url is '%s'", url);
  406. if (std::strncmp(url, "file://", 7) == 0)
  407. {
  408. const char* const lastsep = std::strrchr(url + 7, '/');
  409. NSString* const urlpath = [[NSString alloc] initWithBytes:url
  410. length:(lastsep - url)
  411. encoding:NSUTF8StringEncoding];
  412. [webview loadFileRequest:urlreq
  413. allowingReadAccessToURL:[NSURL URLWithString:urlpath]];
  414. [urlpath release];
  415. }
  416. else
  417. {
  418. [webview loadRequest:urlreq];
  419. }
  420. d_stdout("waiting for load");
  421. if (! delegate->loaded)
  422. {
  423. NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
  424. NSDate* const date = [NSDate dateWithTimeIntervalSinceNow:0.05];
  425. NSEvent* event;
  426. while (! delegate->loaded)
  427. {
  428. event = [NSApp
  429. #ifdef __MAC_10_12
  430. nextEventMatchingMask:NSEventMaskAny
  431. #else
  432. nextEventMatchingMask:NSAnyEventMask
  433. #endif
  434. untilDate:date
  435. inMode:NSDefaultRunLoopMode
  436. dequeue:YES];
  437. if (event == nil)
  438. break;
  439. [NSApp sendEvent: event];
  440. }
  441. [pool release];
  442. }
  443. d_stdout("waiting done");
  444. [webview setHidden:NO];
  445. [nsurl release];
  446. [config release];
  447. [prefs release];
  448. WebViewData* const handle = new WebViewData;
  449. handle->view = view;
  450. handle->webview = webview;
  451. handle->urlreq = urlreq;
  452. handle->delegate = delegate;
  453. return handle;
  454. #elif WEB_VIEW_USING_X11_IPC
  455. // get startup paths
  456. char ldlinux[PATH_MAX] = {};
  457. getFilenameFromFunctionPtr(ldlinux, dlsym(nullptr, "_rtld_global"));
  458. char filename[PATH_MAX] = {};
  459. getFilenameFromFunctionPtr(filename, reinterpret_cast<const void*>(webViewCreate));
  460. d_stdout("ld-linux is '%s'", ldlinux);
  461. d_stdout("filename is '%s'", filename);
  462. // setup shared memory
  463. int shmfd;
  464. char shmname[128];
  465. void* shmptr;
  466. for (int i = 0; i < 9999; ++i)
  467. {
  468. snprintf(shmname, sizeof(shmname) - 1, "/dpf-webview-%d", i + 1);
  469. shmfd = shm_open(shmname, O_CREAT|O_EXCL|O_RDWR, 0666);
  470. if (shmfd < 0)
  471. continue;
  472. if (ftruncate(shmfd, sizeof(WebViewRingBuffer)) != 0)
  473. {
  474. close(shmfd);
  475. shm_unlink(shmname);
  476. continue;
  477. }
  478. break;
  479. }
  480. if (shmfd < 0)
  481. {
  482. d_stderr("shm_open failed: %s", strerror(errno));
  483. return nullptr;
  484. }
  485. shmptr = mmap(nullptr, sizeof(WebViewRingBuffer), PROT_READ|PROT_WRITE, MAP_SHARED, shmfd, 0);
  486. if (shmptr == nullptr || shmptr == MAP_FAILED)
  487. {
  488. d_stderr("mmap failed: %s", strerror(errno));
  489. close(shmfd);
  490. shm_unlink(shmname);
  491. return nullptr;
  492. }
  493. #ifndef __linux__
  494. sem_init(&handle->shmptr->client.sem, 1, 0);
  495. sem_init(&handle->shmptr->server.sem, 1, 0);
  496. #endif
  497. ::Display* const display = XOpenDisplay(nullptr);
  498. DISTRHO_SAFE_ASSERT_RETURN(display != nullptr, nullptr);
  499. // set up custom child environment
  500. uint envsize = 0;
  501. while (environ[envsize] != nullptr)
  502. ++envsize;
  503. char** const envp = new char*[envsize + 5];
  504. {
  505. uint e = 0;
  506. for (uint i = 0; i < envsize; ++i)
  507. {
  508. if (std::strncmp(environ[i], "LD_PRELOAD=", 11) == 0)
  509. continue;
  510. if (std::strncmp(environ[i], "LD_LIBRARY_PATH=", 16) == 0)
  511. continue;
  512. envp[e++] = strdup(environ[i]);
  513. }
  514. envp[e++] = strdup("LANG=en_US.UTF-8");
  515. envp[e++] = ("DPF_WEB_VIEW_SCALE_FACTOR=" + String(scaleFactor)).getAndReleaseBuffer();
  516. envp[e++] = ("DPF_WEB_VIEW_WIN_ID=" +String(windowId)).getAndReleaseBuffer();
  517. for (uint i = e; i < envsize + 5; ++i)
  518. envp[e++] = nullptr;
  519. }
  520. WebViewData* const handle = new WebViewData;
  521. handle->callback = options.callback;
  522. handle->callbackPtr = options.callbackPtr;
  523. handle->shmfd = shmfd;
  524. handle->shmptr = static_cast<WebViewRingBuffer*>(shmptr);
  525. handle->display = display;
  526. handle->ourWindow = windowId;
  527. std::memcpy(handle->shmname, shmname, sizeof(shmname));
  528. handle->shmptr->valid = true;
  529. handle->rbctrl.setRingBuffer(&handle->shmptr->client, false);
  530. handle->rbctrl.flush();
  531. handle->rbctrl2.setRingBuffer(&handle->shmptr->server, false);
  532. handle->rbctrl2.flush();
  533. const char* const args[] = { ldlinux, filename, "dpf-ld-linux-webview", shmname, nullptr };
  534. handle->p.start(args, envp);
  535. for (uint i = 0; envp[i] != nullptr; ++i)
  536. std::free(envp[i]);
  537. delete[] envp;
  538. const size_t urllen = std::strlen(url);
  539. const size_t initjslen = options.initialJS != nullptr ? std::strlen(options.initialJS) + 1 : 0;
  540. handle->rbctrl.writeUInt(kWebViewMessageInitData) &&
  541. handle->rbctrl.writeULong(windowId) &&
  542. handle->rbctrl.writeUInt(initialWidth) &&
  543. handle->rbctrl.writeUInt(initialHeight) &&
  544. handle->rbctrl.writeDouble(scaleFactor) &&
  545. handle->rbctrl.writeInt(options.offset.x) &&
  546. handle->rbctrl.writeInt(options.offset.y) &&
  547. handle->rbctrl.writeUInt(urllen) &&
  548. handle->rbctrl.writeCustomData(url, urllen) &&
  549. handle->rbctrl.writeUInt(initjslen) &&
  550. initjslen != 0 &&
  551. handle->rbctrl.writeCustomData(options.initialJS, initjslen);
  552. handle->rbctrl.commitWrite();
  553. webview_wake(&handle->shmptr->client.sem);
  554. for (int i = 0; i < 5 && handle->p.isRunning(); ++i)
  555. {
  556. if (webview_timedwait(&handle->shmptr->server.sem))
  557. return handle;
  558. }
  559. d_stderr("webview client side failed to start");
  560. webViewDestroy(handle);
  561. return nullptr;
  562. #endif
  563. // maybe unused
  564. (void)windowId;
  565. (void)initialWidth;
  566. (void)initialHeight;
  567. (void)scaleFactor;
  568. (void)options;
  569. return nullptr;
  570. }
  571. void webViewDestroy(const WebViewHandle handle)
  572. {
  573. #if WEB_VIEW_USING_CHOC
  574. webview_choc_destroy(handle->webview);
  575. #elif WEB_VIEW_USING_MACOS_WEBKIT
  576. [handle->webview setHidden:YES];
  577. [handle->webview removeFromSuperview];
  578. [handle->urlreq release];
  579. // [handle->delegate release];
  580. #elif WEB_VIEW_USING_X11_IPC
  581. #ifndef __linux__
  582. sem_destroy(&handle->shmptr->client.sem);
  583. sem_destroy(&handle->shmptr->server.sem);
  584. #endif
  585. munmap(handle->shmptr, sizeof(WebViewRingBuffer));
  586. close(handle->shmfd);
  587. shm_unlink(handle->shmname);
  588. XCloseDisplay(handle->display);
  589. #endif
  590. delete handle;
  591. }
  592. void webViewIdle(const WebViewHandle handle)
  593. {
  594. #if WEB_VIEW_USING_X11_IPC
  595. uint32_t size = 0;
  596. void* buffer = nullptr;
  597. while (handle->rbctrl2.isDataAvailableForReading())
  598. {
  599. switch (handle->rbctrl2.readUInt())
  600. {
  601. case kWebViewMessageCallback:
  602. if (const uint32_t len = handle->rbctrl2.readUInt())
  603. {
  604. if (len > size)
  605. {
  606. size = len;
  607. buffer = std::realloc(buffer, len);
  608. if (buffer == nullptr)
  609. {
  610. d_stderr("server out of memory, abort!");
  611. handle->rbctrl2.flush();
  612. return;
  613. }
  614. }
  615. if (handle->rbctrl2.readCustomData(buffer, len))
  616. {
  617. d_debug("server kWebViewMessageCallback -> '%s'", static_cast<char*>(buffer));
  618. if (handle->callback != nullptr)
  619. handle->callback(handle->callbackPtr, static_cast<char*>(buffer));
  620. continue;
  621. }
  622. }
  623. break;
  624. }
  625. d_stderr("server ringbuffer data race, abort!");
  626. handle->rbctrl2.flush();
  627. return;
  628. }
  629. #else
  630. // unused
  631. (void)handle;
  632. #endif
  633. }
  634. void webViewEvaluateJS(const WebViewHandle handle, const char* const js)
  635. {
  636. #if WEB_VIEW_USING_CHOC
  637. webview_choc_eval(handle->webview, js);
  638. #elif WEB_VIEW_USING_MACOS_WEBKIT
  639. NSString* const nsjs = [[NSString alloc] initWithBytes:js
  640. length:std::strlen(js)
  641. encoding:NSUTF8StringEncoding];
  642. [handle->webview evaluateJavaScript:nsjs completionHandler:nil];
  643. [nsjs release];
  644. #elif WEB_VIEW_USING_X11_IPC
  645. d_debug("evaluateJS '%s'", js);
  646. const size_t len = std::strlen(js) + 1;
  647. handle->rbctrl.writeUInt(kWebViewMessageEvaluateJS) &&
  648. handle->rbctrl.writeUInt(len) &&
  649. handle->rbctrl.writeCustomData(js, len);
  650. if (handle->rbctrl.commitWrite())
  651. webview_wake(&handle->shmptr->client.sem);
  652. #endif
  653. // maybe unused
  654. (void)handle;
  655. (void)js;
  656. }
  657. void webViewReload(const WebViewHandle handle)
  658. {
  659. #if WEB_VIEW_USING_CHOC
  660. webview_choc_navigate(handle->webview, handle->url);
  661. #elif WEB_VIEW_USING_MACOS_WEBKIT
  662. [handle->webview loadRequest:handle->urlreq];
  663. #elif WEB_VIEW_USING_X11_IPC
  664. d_stdout("reload");
  665. handle->rbctrl.writeUInt(kWebViewMessageReload);
  666. if (handle->rbctrl.commitWrite())
  667. webview_wake(&handle->shmptr->client.sem);
  668. #endif
  669. // maybe unused
  670. (void)handle;
  671. }
  672. void webViewResize(const WebViewHandle handle, const uint width, const uint height, const double scaleFactor)
  673. {
  674. #if WEB_VIEW_USING_CHOC
  675. const HWND hwnd = static_cast<HWND>(webview_choc_handle(handle->webview));
  676. SetWindowPos(hwnd, nullptr, 0, 0, width, height, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
  677. #elif WEB_VIEW_USING_MACOS_WEBKIT
  678. [handle->webview setFrameSize:NSMakeSize(width / scaleFactor, height / scaleFactor)];
  679. #elif WEB_VIEW_USING_X11_IPC
  680. if (handle->childWindow == 0)
  681. {
  682. ::Window rootWindow, parentWindow;
  683. ::Window* childWindows = nullptr;
  684. uint numChildren = 0;
  685. XFlush(handle->display);
  686. XQueryTree(handle->display, handle->ourWindow, &rootWindow, &parentWindow, &childWindows, &numChildren);
  687. if (numChildren == 0 || childWindows == nullptr)
  688. return;
  689. handle->childWindow = childWindows[0];
  690. XFree(childWindows);
  691. }
  692. XResizeWindow(handle->display, handle->childWindow, width, height);
  693. XFlush(handle->display);
  694. #endif
  695. // maybe unused
  696. (void)handle;
  697. (void)width;
  698. (void)height;
  699. (void)scaleFactor;
  700. }
  701. #if WEB_VIEW_USING_X11_IPC
  702. // -----------------------------------------------------------------------------------------------------------
  703. static bool running = false;
  704. static std::function<void(const char* js)> evaluateFn;
  705. static std::function<void()> reloadFn;
  706. static std::function<void()> terminateFn;
  707. static std::function<void(WebViewRingBuffer* rb)> wakeFn;
  708. // -----------------------------------------------------------------------------------------------------------
  709. struct GtkContainer;
  710. struct GtkPlug;
  711. struct GtkWidget;
  712. struct GtkWindow;
  713. struct JSCValue;
  714. struct WebKitJavascriptResult;
  715. struct WebKitSettings;
  716. struct WebKitUserContentManager;
  717. struct WebKitUserScript;
  718. struct WebKitWebView;
  719. typedef int gboolean;
  720. #define G_CALLBACK(p) reinterpret_cast<void*>(p)
  721. #define GTK_CONTAINER(p) reinterpret_cast<GtkContainer*>(p)
  722. #define GTK_PLUG(p) reinterpret_cast<GtkPlug*>(p)
  723. #define GTK_WINDOW(p) reinterpret_cast<GtkWindow*>(p)
  724. #define WEBKIT_WEB_VIEW(p) reinterpret_cast<WebKitWebView*>(p)
  725. // -----------------------------------------------------------------------------------------------------------
  726. class QApplication;
  727. class QChar;
  728. class QEvent;
  729. class QMetaMethod;
  730. class QMetaObject;
  731. class QString;
  732. class QUrl;
  733. class QWebEngineView;
  734. class QWindow;
  735. struct QPoint {
  736. int x, y;
  737. };
  738. struct QSize {
  739. int w, h;
  740. };
  741. // -----------------------------------------------------------------------------------------------------------
  742. #define JOIN(A, B) A ## B
  743. #define AUTOSYM(S) \
  744. using JOIN(gtk3_, S) = decltype(&S); \
  745. JOIN(gtk3_, S) S = reinterpret_cast<JOIN(gtk3_, S)>(dlsym(nullptr, #S)); \
  746. DISTRHO_SAFE_ASSERT_RETURN(S != nullptr, false);
  747. #define CSYM(S, NAME) \
  748. S NAME = reinterpret_cast<S>(dlsym(nullptr, #NAME)); \
  749. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  750. #define CPPSYM(S, NAME, SN) \
  751. S NAME = reinterpret_cast<S>(dlsym(nullptr, #SN)); \
  752. DISTRHO_SAFE_ASSERT_RETURN(NAME != nullptr, false);
  753. static void web_wake_idle(void* const ptr)
  754. {
  755. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  756. RingBufferControl<WebViewSharedBuffer> rbctrl;
  757. rbctrl.setRingBuffer(&shmptr->client, false);
  758. uint32_t size = 0;
  759. void* buffer = nullptr;
  760. while (rbctrl.isDataAvailableForReading())
  761. {
  762. switch (rbctrl.readUInt())
  763. {
  764. case kWebViewMessageEvaluateJS:
  765. if (const uint32_t len = rbctrl.readUInt())
  766. {
  767. if (len > size)
  768. {
  769. size = len;
  770. buffer = realloc(buffer, len);
  771. if (buffer == nullptr)
  772. {
  773. d_stderr("lv2ui client out of memory, abort!");
  774. abort();
  775. }
  776. }
  777. if (rbctrl.readCustomData(buffer, len))
  778. {
  779. d_debug("client kWebViewMessageEvaluateJS -> '%s'", static_cast<char*>(buffer));
  780. evaluateFn(static_cast<char*>(buffer));
  781. continue;
  782. }
  783. }
  784. break;
  785. case kWebViewMessageReload:
  786. d_debug("client kWebViewMessageReload");
  787. reloadFn();
  788. continue;
  789. }
  790. d_stderr("client ringbuffer data race, abort!");
  791. abort();
  792. }
  793. free(buffer);
  794. }
  795. // -----------------------------------------------------------------------------------------------------------
  796. // gtk3 variant
  797. static int gtk3_js_cb(WebKitUserContentManager*, WebKitJavascriptResult* const result, void* const arg)
  798. {
  799. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(arg);
  800. using g_free_t = void (*)(void*);
  801. using jsc_value_to_string_t = char* (*)(JSCValue*);
  802. using webkit_javascript_result_get_js_value_t = JSCValue* (*)(WebKitJavascriptResult*);
  803. CSYM(g_free_t, g_free)
  804. CSYM(jsc_value_to_string_t, jsc_value_to_string)
  805. CSYM(webkit_javascript_result_get_js_value_t, webkit_javascript_result_get_js_value)
  806. JSCValue* const value = webkit_javascript_result_get_js_value(result);
  807. DISTRHO_SAFE_ASSERT_RETURN(value != nullptr, false);
  808. char* const string = jsc_value_to_string(value);
  809. DISTRHO_SAFE_ASSERT_RETURN(string != nullptr, false);
  810. d_debug("js call received with data '%s'", string);
  811. const size_t len = std::strlen(string);
  812. RingBufferControl<WebViewSharedBuffer> rbctrl2;
  813. rbctrl2.setRingBuffer(&shmptr->server, false);
  814. rbctrl2.writeUInt(kWebViewMessageCallback) &&
  815. rbctrl2.writeUInt(len) &&
  816. rbctrl2.writeCustomData(string, len);
  817. rbctrl2.commitWrite();
  818. g_free(string);
  819. return 0;
  820. }
  821. static bool gtk3(Display* const display,
  822. const Window winId,
  823. const int x,
  824. const int y,
  825. const uint width,
  826. const uint height,
  827. double scaleFactor,
  828. const char* const url,
  829. const char* const initialJS,
  830. WebViewRingBuffer* const shmptr)
  831. {
  832. void* lib;
  833. if ((lib = dlopen("libwebkit2gtk-4.0.so.37", RTLD_NOW|RTLD_GLOBAL)) == nullptr &&
  834. (lib = dlopen("libwebkit2gtk-4.0.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  835. {
  836. d_stdout("WebView gtk3 platform not available: %s", dlerror());
  837. return false;
  838. }
  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_add_script_t = void (*)(WebKitUserContentManager*, WebKitUserScript*);
  857. using webkit_user_content_manager_register_script_message_handler_t = gboolean (*)(WebKitUserContentManager*, const char*);
  858. using webkit_user_script_new_t = WebKitUserScript* (*)(const char*, int, int, const char* const*, const char* const*);
  859. using webkit_web_view_evaluate_javascript_t = void* (*)(WebKitWebView*, const char*, ssize_t, const char*, const char*, void*, void*, void*);
  860. using webkit_web_view_get_user_content_manager_t = WebKitUserContentManager* (*)(WebKitWebView*);
  861. using webkit_web_view_load_uri_t = void (*)(WebKitWebView*, const char*);
  862. using webkit_web_view_new_with_settings_t = GtkWidget* (*)(WebKitSettings*);
  863. using webkit_web_view_run_javascript_t = void* (*)(WebKitWebView*, const char*, void*, void*, void*);
  864. using webkit_web_view_set_background_color_t = void (*)(WebKitWebView*, const double*);
  865. CSYM(g_main_context_invoke_t, g_main_context_invoke)
  866. CSYM(g_signal_connect_data_t, g_signal_connect_data)
  867. CSYM(gdk_set_allowed_backends_t, gdk_set_allowed_backends)
  868. CSYM(gtk_container_add_t, gtk_container_add)
  869. CSYM(gtk_init_check_t, gtk_init_check)
  870. CSYM(gtk_main_t, gtk_main)
  871. CSYM(gtk_main_quit_t, gtk_main_quit)
  872. CSYM(gtk_plug_get_id_t, gtk_plug_get_id)
  873. CSYM(gtk_plug_new_t, gtk_plug_new)
  874. CSYM(gtk_widget_show_all_t, gtk_widget_show_all)
  875. CSYM(gtk_window_move_t, gtk_window_move)
  876. CSYM(gtk_window_set_default_size_t, gtk_window_set_default_size)
  877. CSYM(webkit_settings_new_t, webkit_settings_new)
  878. CSYM(webkit_settings_set_enable_developer_extras_t, webkit_settings_set_enable_developer_extras)
  879. CSYM(webkit_settings_set_enable_write_console_messages_to_stdout_t, webkit_settings_set_enable_write_console_messages_to_stdout)
  880. CSYM(webkit_settings_set_hardware_acceleration_policy_t, webkit_settings_set_hardware_acceleration_policy)
  881. CSYM(webkit_settings_set_javascript_can_access_clipboard_t, webkit_settings_set_javascript_can_access_clipboard)
  882. CSYM(webkit_user_content_manager_add_script_t, webkit_user_content_manager_add_script)
  883. CSYM(webkit_user_content_manager_register_script_message_handler_t, webkit_user_content_manager_register_script_message_handler)
  884. CSYM(webkit_user_script_new_t, webkit_user_script_new)
  885. CSYM(webkit_web_view_get_user_content_manager_t, webkit_web_view_get_user_content_manager)
  886. CSYM(webkit_web_view_load_uri_t, webkit_web_view_load_uri)
  887. CSYM(webkit_web_view_new_with_settings_t, webkit_web_view_new_with_settings)
  888. CSYM(webkit_web_view_set_background_color_t, webkit_web_view_set_background_color)
  889. // special case for legacy API handling
  890. 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"));
  891. 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"));
  892. DISTRHO_SAFE_ASSERT_RETURN(webkit_web_view_evaluate_javascript != nullptr || webkit_web_view_run_javascript != nullptr, false);
  893. const int gdkScale = std::fmod(scaleFactor, 1.0) >= 0.75
  894. ? static_cast<int>(scaleFactor + 0.5)
  895. : static_cast<int>(scaleFactor);
  896. if (gdkScale != 1)
  897. {
  898. char scale[8] = {};
  899. std::snprintf(scale, 7, "%d", gdkScale);
  900. setenv("GDK_SCALE", scale, 1);
  901. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.2);
  902. setenv("GDK_DPI_SCALE", scale, 1);
  903. }
  904. else if (scaleFactor > 1.0)
  905. {
  906. char scale[8] = {};
  907. std::snprintf(scale, 7, "%.2f", (1.0 / scaleFactor) * 1.4);
  908. setenv("GDK_DPI_SCALE", scale, 1);
  909. }
  910. scaleFactor /= gdkScale;
  911. gdk_set_allowed_backends("x11");
  912. if (! gtk_init_check(nullptr, nullptr))
  913. {
  914. d_stderr("WebView gtk_init_check failed");
  915. return false;
  916. }
  917. GtkWidget* const window = gtk_plug_new(winId);
  918. DISTRHO_SAFE_ASSERT_RETURN(window != nullptr, false);
  919. gtk_window_set_default_size(GTK_WINDOW(window),
  920. (width - x) * scaleFactor,
  921. (height - y) * scaleFactor);
  922. gtk_window_move(GTK_WINDOW(window), x * scaleFactor, y * scaleFactor);
  923. WebKitSettings* const settings = webkit_settings_new();
  924. DISTRHO_SAFE_ASSERT_RETURN(settings != nullptr, false);
  925. // TODO DOMPasteAllowed
  926. webkit_settings_set_javascript_can_access_clipboard(settings, true);
  927. webkit_settings_set_hardware_acceleration_policy(settings, 2 /* WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER */);
  928. // if (debug)
  929. {
  930. webkit_settings_set_enable_developer_extras(settings, true);
  931. webkit_settings_set_enable_write_console_messages_to_stdout(settings, true);
  932. }
  933. GtkWidget* const webview = webkit_web_view_new_with_settings(settings);
  934. DISTRHO_SAFE_ASSERT_RETURN(webview != nullptr, false);
  935. const double color[] = {49.0/255, 54.0/255, 59.0/255, 1};
  936. webkit_web_view_set_background_color(WEBKIT_WEB_VIEW(webview), color);
  937. if (WebKitUserContentManager* const manager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(webview)))
  938. {
  939. g_signal_connect_data(manager, "script-message-received::external", G_CALLBACK(gtk3_js_cb), shmptr, nullptr, 0);
  940. webkit_user_content_manager_register_script_message_handler(manager, "external");
  941. WebKitUserScript* const mscript = webkit_user_script_new(
  942. "function postMessage(m){window.webkit.messageHandlers.external.postMessage(m)}", 0, 0, nullptr, nullptr);
  943. webkit_user_content_manager_add_script(manager, mscript);
  944. if (initialJS != nullptr)
  945. {
  946. WebKitUserScript* const script = webkit_user_script_new(initialJS, 0, 0, nullptr, nullptr);
  947. webkit_user_content_manager_add_script(manager, script);
  948. }
  949. }
  950. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  951. gtk_container_add(GTK_CONTAINER(window), webview);
  952. gtk_widget_show_all(window);
  953. Window wid = gtk_plug_get_id(GTK_PLUG(window));
  954. XMapWindow(display, wid);
  955. XFlush(display);
  956. evaluateFn = [=](const char* const js){
  957. if (webkit_web_view_evaluate_javascript != nullptr)
  958. webkit_web_view_evaluate_javascript(WEBKIT_WEB_VIEW(webview), js, -1,
  959. nullptr, nullptr, nullptr, nullptr, nullptr);
  960. else
  961. webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(webview), js, nullptr, nullptr, nullptr);
  962. };
  963. reloadFn = [=](){
  964. webkit_web_view_load_uri(WEBKIT_WEB_VIEW(webview), url);
  965. };
  966. terminateFn = [=](){
  967. if (running)
  968. {
  969. running = false;
  970. webview_wake(&shmptr->client.sem);
  971. gtk_main_quit();
  972. }
  973. };
  974. wakeFn = [=](WebViewRingBuffer* const rb){
  975. g_main_context_invoke(NULL, G_CALLBACK(web_wake_idle), rb);
  976. };
  977. // notify server we started ok
  978. webview_wake(&shmptr->server.sem);
  979. d_stdout("WebView gtk3 main loop started");
  980. gtk_main();
  981. d_stdout("WebView gtk3 main loop quit");
  982. dlclose(lib);
  983. return true;
  984. }
  985. // -----------------------------------------------------------------------------------------------------------
  986. // qt common code
  987. // VTable compatible with real QObject
  988. class QObject
  989. {
  990. public:
  991. using QObject__init_t = void (*)(QObject*, QObject*);
  992. QObject(const QObject__init_t init)
  993. {
  994. init(this, nullptr);
  995. }
  996. virtual const QMetaObject* metaObject() const
  997. {
  998. static const uint8_t mdata[56 * 2] = {}; // sizeof(QMetaObject) == 56
  999. return static_cast<const QMetaObject*>(static_cast<const void*>(mdata));
  1000. }
  1001. virtual void* qt_metacast(const char*) { return 0; }
  1002. virtual int qt_metacall(void* /* QMetaObject::Call */, int, void**) { return 0; }
  1003. virtual ~QObject() {}
  1004. virtual bool event(QEvent *e) { return false; }
  1005. virtual bool eventFilter(QObject*, QEvent*) { return false; }
  1006. virtual void timerEvent(void*) {}
  1007. virtual void childEvent(void*) {}
  1008. virtual void customEvent(void*) {}
  1009. virtual void connectNotify(const QMetaMethod&) {}
  1010. virtual void disconnectNotify(const QMetaMethod&) {}
  1011. private:
  1012. uint8_t _[8 * 2];
  1013. };
  1014. // QObject subclass for receiving events on main thread
  1015. class EventFilterQObject : public QObject
  1016. {
  1017. WebViewRingBuffer* const _rb;
  1018. public:
  1019. EventFilterQObject(const QObject__init_t init, WebViewRingBuffer* const rb)
  1020. : QObject(init),
  1021. _rb(rb) {}
  1022. bool event(QEvent * e) override
  1023. {
  1024. printf("custom event YES\n");
  1025. web_wake_idle(_rb);
  1026. return false;
  1027. }
  1028. };
  1029. // -----------------------------------------------------------------------------------------------------------
  1030. // qt5webengine variant
  1031. static bool qt5webengine(Display* const display,
  1032. const Window winId,
  1033. const int x,
  1034. const int y,
  1035. const uint width,
  1036. const uint height,
  1037. double scaleFactor,
  1038. const char* const url,
  1039. const char* const initialJS,
  1040. WebViewRingBuffer* const shmptr)
  1041. {
  1042. void* lib;
  1043. if ((lib = dlopen("libQt5WebEngineWidgets.so.5", RTLD_NOW|RTLD_GLOBAL)) == nullptr &&
  1044. (lib = dlopen("libQt5WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  1045. {
  1046. d_stdout("WebView Qt5 platform not available: %s", dlerror());
  1047. return false;
  1048. }
  1049. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  1050. using QApplication_exec_t = void (*)();
  1051. using QApplication_postEvent_t = void (*)(QObject*, QEvent*, int);
  1052. using QApplication_quit_t = void (*)();
  1053. using QApplication_setAttribute_t = void (*)(int, bool);
  1054. using QEvent__init_t = void (*)(QEvent*, int);
  1055. using QObject__init_t = void (*)(QObject*, QObject*);
  1056. using QString__init_t = void (*)(void*, const QChar*, ptrdiff_t);
  1057. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  1058. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  1059. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  1060. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  1061. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  1062. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  1063. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  1064. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  1065. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  1066. using QWindow_setParent_t = void (*)(QWindow*, void*);
  1067. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  1068. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  1069. CPPSYM(QApplication_postEvent_t, QApplication_postEvent, _ZN16QCoreApplication9postEventEP7QObjectP6QEventi)
  1070. CPPSYM(QApplication_quit_t, QApplication_quit, _ZN16QCoreApplication4quitEv)
  1071. CPPSYM(QApplication_setAttribute_t, QApplication_setAttribute, _ZN16QCoreApplication12setAttributeEN2Qt20ApplicationAttributeEb)
  1072. CPPSYM(QEvent__init_t, QEvent__init, _ZN6QEventC1ENS_4TypeE)
  1073. CPPSYM(QObject__init_t, QObject__init, _ZN7QObjectC1EPS_)
  1074. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QChari)
  1075. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  1076. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  1077. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1078. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1079. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1080. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1081. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1082. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1083. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1084. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1085. unsetenv("QT_FONT_DPI");
  1086. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1087. unsetenv("QT_USE_PHYSICAL_DPI");
  1088. setenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0", 1);
  1089. setenv("QT_QPA_PLATFORM", "xcb", 1);
  1090. char scale[8] = {};
  1091. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1092. setenv("QT_SCALE_FACTOR", scale, 1);
  1093. QApplication_setAttribute(10 /* Qt::AA_X11InitThreads */, true);
  1094. QApplication_setAttribute(13 /* Qt::AA_UseHighDpiPixmaps */, true);
  1095. QApplication_setAttribute(20 /* Qt::AA_EnableHighDpiScaling */, true);
  1096. static int argc = 1;
  1097. static char argv0[] = "dpf-webview";
  1098. static char* argv[] = { argv0, nullptr };
  1099. uint8_t _app[64]; // sizeof(QApplication) == 16
  1100. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1101. QApplication__init(app, argc, argv, 0);
  1102. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1103. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1104. {
  1105. const size_t url_len = std::strlen(url);
  1106. ushort* const url_qchar = new ushort[url_len + 1];
  1107. for (size_t i = 0; i < url_len; ++i)
  1108. url_qchar[i] = url[i];
  1109. url_qchar[url_len] = 0;
  1110. QString__init(qstrurl, reinterpret_cast<QChar*>(url_qchar), url_len);
  1111. }
  1112. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1113. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1114. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1115. EventFilterQObject eventFilter(QObject__init, shmptr);
  1116. EventFilterQObject* const eventFilterPtr = &eventFilter;
  1117. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1118. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1119. QWebEngineView__init(webview, nullptr);
  1120. QWebEngineView_move(webview, QPoint{x, y});
  1121. QWebEngineView_resize(webview, QSize{DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT});
  1122. QWebEngineView_winId(webview);
  1123. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1124. QWebEngineView_setUrl(webview, *qurl);
  1125. QWebEngineView_show(webview);
  1126. evaluateFn = [=](const char* const js){
  1127. // TODO
  1128. };
  1129. reloadFn = [=](){
  1130. QWebEngineView_setUrl(webview, *qurl);
  1131. };
  1132. terminateFn = [=](){
  1133. if (running)
  1134. {
  1135. running = false;
  1136. webview_wake(&shmptr->client.sem);
  1137. QApplication_quit();
  1138. }
  1139. };
  1140. wakeFn = [=](WebViewRingBuffer* const rb){
  1141. d_stdout("wakeFn");
  1142. // NOTE event pointer is deleted by Qt
  1143. typedef struct { uint8_t _[16 * 2]; } uint8_64_t; // sizeof(QEvent) == 16
  1144. QEvent* const qevent = reinterpret_cast<QEvent*>(new uint8_64_t);
  1145. QEvent__init(qevent, 1000 /* QEvent::User */);
  1146. QApplication_postEvent(eventFilterPtr, qevent, 1 /* Qt::HighEventPriority */);
  1147. };
  1148. // notify server we started ok
  1149. webview_wake(&shmptr->server.sem);
  1150. d_stdout("WebView Qt5 main loop started");
  1151. QApplication_exec();
  1152. d_stdout("WebView Qt5 main loop quit");
  1153. dlclose(lib);
  1154. return true;
  1155. }
  1156. // -----------------------------------------------------------------------------------------------------------
  1157. // qt6webengine variant (same as qt5 but `QString__init_t` has different arguments)
  1158. static bool qt6webengine(Display* const display,
  1159. const Window winId,
  1160. const int x,
  1161. const int y,
  1162. const uint width,
  1163. const uint height,
  1164. double scaleFactor,
  1165. const char* const url,
  1166. const char* const initialJS,
  1167. WebViewRingBuffer* const shmptr)
  1168. {
  1169. void* lib;
  1170. if ((lib = dlopen("libQt6WebEngineWidgets.so.6", RTLD_NOW|RTLD_GLOBAL)) == nullptr &&
  1171. (lib = dlopen("libQt6WebEngineWidgets.so", RTLD_NOW|RTLD_GLOBAL)) == nullptr)
  1172. {
  1173. d_stdout("WebView Qt6 platform not available: %s", dlerror());
  1174. return false;
  1175. }
  1176. using QApplication__init_t = void (*)(QApplication*, int&, char**, int);
  1177. using QApplication_exec_t = void (*)();
  1178. using QApplication_postEvent_t = void (*)(QObject*, QEvent*, int);
  1179. using QApplication_quit_t = void (*)();
  1180. using QEvent__init_t = void (*)(QEvent*, int);
  1181. using QObject__init_t = void (*)(QObject*, QObject*);
  1182. using QString__init_t = void (*)(QString*, const QChar*, long long);
  1183. using QUrl__init_t = void (*)(void*, const QString&, int /* QUrl::ParsingMode */);
  1184. using QWebEngineView__init_t = void (*)(QWebEngineView*, void*);
  1185. using QWebEngineView_move_t = void (*)(QWebEngineView*, const QPoint&);
  1186. using QWebEngineView_resize_t = void (*)(QWebEngineView*, const QSize&);
  1187. using QWebEngineView_setUrl_t = void (*)(QWebEngineView*, const QUrl&);
  1188. using QWebEngineView_show_t = void (*)(QWebEngineView*);
  1189. using QWebEngineView_winId_t = ulonglong (*)(QWebEngineView*);
  1190. using QWebEngineView_windowHandle_t = QWindow* (*)(QWebEngineView*);
  1191. using QWindow_fromWinId_t = QWindow* (*)(ulonglong);
  1192. using QWindow_setParent_t = void (*)(QWindow*, void*);
  1193. CPPSYM(QApplication__init_t, QApplication__init, _ZN12QApplicationC1ERiPPci)
  1194. CPPSYM(QApplication_exec_t, QApplication_exec, _ZN15QGuiApplication4execEv)
  1195. CPPSYM(QApplication_postEvent_t, QApplication_postEvent, _ZN16QCoreApplication9postEventEP7QObjectP6QEventi)
  1196. CPPSYM(QApplication_quit_t, QApplication_quit, _ZN16QCoreApplication4quitEv)
  1197. CPPSYM(QEvent__init_t, QEvent__init, _ZN6QEventC1ENS_4TypeE)
  1198. CPPSYM(QObject__init_t, QObject__init, _ZN7QObjectC1EPS_)
  1199. CPPSYM(QString__init_t, QString__init, _ZN7QStringC2EPK5QCharx)
  1200. CPPSYM(QUrl__init_t, QUrl__init, _ZN4QUrlC1ERK7QStringNS_11ParsingModeE)
  1201. CPPSYM(QWebEngineView__init_t, QWebEngineView__init, _ZN14QWebEngineViewC1EP7QWidget)
  1202. CPPSYM(QWebEngineView_move_t, QWebEngineView_move, _ZN7QWidget4moveERK6QPoint)
  1203. CPPSYM(QWebEngineView_resize_t, QWebEngineView_resize, _ZN7QWidget6resizeERK5QSize)
  1204. CPPSYM(QWebEngineView_setUrl_t, QWebEngineView_setUrl, _ZN14QWebEngineView6setUrlERK4QUrl)
  1205. CPPSYM(QWebEngineView_show_t, QWebEngineView_show, _ZN7QWidget4showEv)
  1206. CPPSYM(QWebEngineView_winId_t, QWebEngineView_winId, _ZNK7QWidget5winIdEv)
  1207. CPPSYM(QWebEngineView_windowHandle_t, QWebEngineView_windowHandle, _ZNK7QWidget12windowHandleEv)
  1208. CPPSYM(QWindow_fromWinId_t, QWindow_fromWinId, _ZN7QWindow9fromWinIdEy)
  1209. CPPSYM(QWindow_setParent_t, QWindow_setParent, _ZN7QWindow9setParentEPS_)
  1210. unsetenv("QT_FONT_DPI");
  1211. unsetenv("QT_SCREEN_SCALE_FACTORS");
  1212. unsetenv("QT_USE_PHYSICAL_DPI");
  1213. setenv("QT_ENABLE_HIGHDPI_SCALING", "0", 1);
  1214. setenv("QT_QPA_PLATFORM", "xcb", 1);
  1215. char scale[8] = {};
  1216. std::snprintf(scale, 7, "%.2f", scaleFactor);
  1217. setenv("QT_SCALE_FACTOR", scale, 1);
  1218. static int argc = 1;
  1219. static char argv0[] = "dpf-webview";
  1220. static char* argv[] = { argv0, nullptr };
  1221. uint8_t _app[64]; // sizeof(QApplication) == 16
  1222. QApplication* const app = reinterpret_cast<QApplication*>(_app);
  1223. QApplication__init(app, argc, argv, 0);
  1224. uint8_t _qstrurl[32]; // sizeof(QString) == 8
  1225. QString* const qstrurl(reinterpret_cast<QString*>(_qstrurl));
  1226. {
  1227. const size_t url_len = std::strlen(url);
  1228. ushort* const url_qchar = new ushort[url_len + 1];
  1229. for (size_t i = 0; i < url_len; ++i)
  1230. url_qchar[i] = url[i];
  1231. url_qchar[url_len] = 0;
  1232. QString__init(qstrurl, reinterpret_cast<QChar*>(url_qchar), url_len);
  1233. }
  1234. uint8_t _qurl[32]; // sizeof(QUrl) == 8
  1235. QUrl* const qurl(reinterpret_cast<QUrl*>(_qurl));
  1236. QUrl__init(qurl, *qstrurl, 1 /* QUrl::StrictMode */);
  1237. EventFilterQObject eventFilter(QObject__init, shmptr);
  1238. EventFilterQObject* const eventFilterPtr = &eventFilter;
  1239. uint8_t _webview[128]; // sizeof(QWebEngineView) == 56
  1240. QWebEngineView* const webview = reinterpret_cast<QWebEngineView*>(_webview);
  1241. QWebEngineView__init(webview, nullptr);
  1242. QWebEngineView_move(webview, QPoint{x, y});
  1243. QWebEngineView_resize(webview, QSize{DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT});
  1244. QWebEngineView_winId(webview);
  1245. QWindow_setParent(QWebEngineView_windowHandle(webview), QWindow_fromWinId(winId));
  1246. QWebEngineView_setUrl(webview, *qurl);
  1247. // FIXME Qt6 seems to need some forcing..
  1248. XReparentWindow(display, QWebEngineView_winId(webview), winId, x, y);
  1249. XFlush(display);
  1250. QWebEngineView_show(webview);
  1251. evaluateFn = [=](const char* const js){
  1252. // TODO
  1253. };
  1254. reloadFn = [=](){
  1255. QWebEngineView_setUrl(webview, *qurl);
  1256. };
  1257. terminateFn = [=](){
  1258. if (running)
  1259. {
  1260. running = false;
  1261. webview_wake(&shmptr->client.sem);
  1262. QApplication_quit();
  1263. }
  1264. };
  1265. wakeFn = [=](WebViewRingBuffer* const rb){
  1266. d_stdout("wakeFn");
  1267. // NOTE event pointer is deleted by Qt
  1268. typedef struct { uint8_t _[16 * 2]; } uint8_64_t; // sizeof(QEvent) == 16
  1269. QEvent* const qevent = reinterpret_cast<QEvent*>(new uint8_64_t);
  1270. QEvent__init(qevent, 1000 /* QEvent::User */);
  1271. QApplication_postEvent(eventFilterPtr, qevent, 1 /* Qt::HighEventPriority */);
  1272. };
  1273. // notify server we started ok
  1274. webview_wake(&shmptr->server.sem);
  1275. d_stdout("WebView Qt6 main loop started");
  1276. QApplication_exec();
  1277. d_stdout("WebView Qt6 main loop quit");
  1278. dlclose(lib);
  1279. return true;
  1280. }
  1281. // -----------------------------------------------------------------------------------------------------------
  1282. // startup via ld-linux
  1283. static void signalHandler(const int sig)
  1284. {
  1285. switch (sig)
  1286. {
  1287. case SIGTERM:
  1288. terminateFn();
  1289. break;
  1290. }
  1291. }
  1292. static void* threadHandler(void* const ptr)
  1293. {
  1294. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(ptr);
  1295. while (running && shmptr->valid)
  1296. {
  1297. if (webview_timedwait(&shmptr->client.sem) && running)
  1298. wakeFn(shmptr);
  1299. }
  1300. return nullptr;
  1301. }
  1302. int dpf_webview_start(const int argc, char* argv[])
  1303. {
  1304. if (argc != 3)
  1305. {
  1306. d_stderr("WebView entry point, nothing to see here! ;)");
  1307. return 1;
  1308. }
  1309. d_stdout("starting... %d '%s' '%s'", argc, argv[1], argv[2]);
  1310. uselocale(newlocale(LC_NUMERIC_MASK, "C", nullptr));
  1311. Display* const display = XOpenDisplay(nullptr);
  1312. DISTRHO_SAFE_ASSERT_RETURN(display != nullptr, 1);
  1313. const char* const shmname = argv[2];
  1314. const int shmfd = shm_open(shmname, O_RDWR, 0);
  1315. if (shmfd < 0)
  1316. {
  1317. d_stderr("shm_open failed: %s", std::strerror(errno));
  1318. return 1;
  1319. }
  1320. WebViewRingBuffer* const shmptr = static_cast<WebViewRingBuffer*>(mmap(nullptr,
  1321. sizeof(WebViewRingBuffer),
  1322. PROT_READ|PROT_WRITE,
  1323. MAP_SHARED,
  1324. shmfd, 0));
  1325. if (shmptr == nullptr || shmptr == nullptr)
  1326. {
  1327. d_stderr("mmap failed: %s", std::strerror(errno));
  1328. close(shmfd);
  1329. return 1;
  1330. }
  1331. RingBufferControl<WebViewSharedBuffer> rbctrl;
  1332. rbctrl.setRingBuffer(&shmptr->client, false);
  1333. // fetch initial data
  1334. bool hasInitialData = false;
  1335. Window winId = 0;
  1336. uint width = 0, height = 0;
  1337. double scaleFactor = 0;
  1338. int x = 0, y = 0;
  1339. char* url = nullptr;
  1340. char* initJS = nullptr;
  1341. while (shmptr->valid && webview_timedwait(&shmptr->client.sem))
  1342. {
  1343. if (rbctrl.isDataAvailableForReading())
  1344. {
  1345. DISTRHO_SAFE_ASSERT_RETURN(rbctrl.readUInt() == kWebViewMessageInitData, 1);
  1346. hasInitialData = running = true;
  1347. winId = rbctrl.readULong();
  1348. width = rbctrl.readUInt();
  1349. height = rbctrl.readUInt();
  1350. scaleFactor = rbctrl.readDouble();
  1351. x = rbctrl.readInt();
  1352. y = rbctrl.readInt();
  1353. const uint urllen = rbctrl.readUInt();
  1354. url = static_cast<char*>(std::malloc(urllen));
  1355. rbctrl.readCustomData(url, urllen);
  1356. if (const uint initjslen = rbctrl.readUInt())
  1357. {
  1358. initJS = static_cast<char*>(std::malloc(initjslen));
  1359. rbctrl.readCustomData(initJS, initjslen);
  1360. }
  1361. }
  1362. }
  1363. pthread_t thread;
  1364. if (hasInitialData && pthread_create(&thread, nullptr, threadHandler, shmptr) == 0)
  1365. {
  1366. d_stdout("WebView IPC in place, starting engine...");
  1367. struct sigaction sig = {};
  1368. sig.sa_handler = signalHandler;
  1369. sig.sa_flags = SA_RESTART;
  1370. sigemptyset(&sig.sa_mask);
  1371. sigaction(SIGTERM, &sig, nullptr);
  1372. if (! qt5webengine(display, winId, x, y, width, height, scaleFactor, url, initJS, shmptr) &&
  1373. ! qt6webengine(display, winId, x, y, width, height, scaleFactor, url, initJS, shmptr) &&
  1374. ! gtk3(display, winId, x, y, width, height, scaleFactor, url, initJS, shmptr))
  1375. {
  1376. d_stderr("Failed to find usable WebView platform");
  1377. }
  1378. shmptr->valid = running = false;
  1379. pthread_join(thread, nullptr);
  1380. }
  1381. else
  1382. {
  1383. d_stderr("Failed to setup WebView IPC");
  1384. }
  1385. std::free(initJS);
  1386. munmap(shmptr, sizeof(WebViewRingBuffer));
  1387. close(shmfd);
  1388. XCloseDisplay(display);
  1389. return 0;
  1390. }
  1391. // --------------------------------------------------------------------------------------------------------------------
  1392. #endif // WEB_VIEW_USING_X11_IPC
  1393. #ifdef WEB_VIEW_DGL_NAMESPACE
  1394. END_NAMESPACE_DGL
  1395. #else
  1396. END_NAMESPACE_DISTRHO
  1397. #endif
  1398. #undef MACRO_NAME
  1399. #undef MACRO_NAME2
  1400. #undef WEB_VIEW_DISTRHO_NAMESPACE
  1401. #undef WEB_VIEW_DGL_NAMESPACE