iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IPlugWebView_linux.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#include "IPlugWebView.h"
12#include "IPlugPaths.h"
13#include <gtk/gtkx.h>
14#include <gdk/gdkx.h>
15#include <webkit2/webkit2.h>
16#include <dlfcn.h>
17#include <cmath>
18#include <filesystem>
19#include <algorithm>
20#include <cstdint>
21#include <memory>
22#include <utility>
23#include <cstring>
24#include <cstdlib>
25
26// GTK is process-global. Host callbacks must run on the GUI/main thread.
27extern "C" void IPlugLinuxWebViewPump()
28{
29 for (int i = 0; i < 32 && g_main_context_pending(nullptr); ++i)
30 g_main_context_iteration(nullptr, FALSE);
31}
32
33// dladdr needs an address inside this module to resolve the module's path
34static void IPlugLinuxWebViewModuleAnchor() {}
35
36BEGIN_IPLUG_NAMESPACE
37
39{
40public:
41 explicit IWebViewImpl(IWebView* pOwner)
42 : mOwner(pOwner)
43 {
44 }
45
46 ~IWebViewImpl() { CloseWebView(); }
47
48 void* OpenWebView(void* pParent, float x, float y, float w, float h, float scale)
49 {
50 CloseWebView();
51
52 if (!pParent)
53 return nullptr;
54
55 // GtkPlug is X11-only. In a Wayland session GDK would otherwise prefer the
56 // Wayland backend even though the host window is an (XWayland) X11 window.
57 // No effect if the process has already opened a GDK display.
58 gdk_set_allowed_backends("x11");
59
60 // gtk_init_check() would otherwise call setlocale(LC_ALL, ""), changing
61 // e.g. the decimal separator for the host and every other plugin.
62 gtk_disable_setlocale();
63
64 if (!gtk_init_check(nullptr, nullptr))
65 return nullptr;
66
67 // Reject stale/invalid XIDs before gtk_plug_new issues X requests. GDK's
68 // own connection may otherwise turn a BadWindow into a process abort.
69 GdkDisplay* pDisplay = gdk_display_get_default();
70
71 if (!GDK_IS_X11_DISPLAY(pDisplay))
72 return nullptr;
73
74 Window parentXID = static_cast<Window>(reinterpret_cast<uintptr_t>(pParent));
75 GdkWindow* pOwnWindow = gdk_x11_window_lookup_for_display(pDisplay, parentXID);
76
77 // GDK also caches foreign wrappers for host windows from earlier opens.
78 if (pOwnWindow && gdk_window_get_window_type(pOwnWindow) != GDK_WINDOW_FOREIGN)
79 {
80 // The parent belongs to this process's GDK (standalone app). GtkPlug can
81 // only embed into a foreign window, so interpose a plain X11 child that
82 // GDK does not track, placed below the container's menu bar.
83 const char* menuOffset = getenv("IPLUG2_MENU_OFFSET");
84 mHostScale = std::max(1, gdk_window_get_scale_factor(pOwnWindow));
85 Display* pXDisplay = gdk_x11_display_get_xdisplay(pDisplay);
86 mHostChild = XCreateSimpleWindow(pXDisplay, parentXID, 0, menuOffset ? std::clamp(atoi(menuOffset), 0, 100) : 0, std::max(1, static_cast<int>(std::ceil(w * scale))) * mHostScale,
87 std::max(1, static_cast<int>(std::ceil(h * scale))) * mHostScale, 0, 0, 0);
88 XMapWindow(pXDisplay, mHostChild);
89 XSync(pXDisplay, False);
90 parentXID = mHostChild;
91 }
92
93 GdkWindow* pHostWindow = gdk_x11_window_foreign_new_for_display(pDisplay, parentXID);
94
95 if (!pHostWindow)
96 {
97 CloseWebView();
98 return nullptr;
99 }
100
101 g_object_unref(pHostWindow);
102 mPlug = gtk_plug_new(parentXID);
103
104 if (!mPlug)
105 {
106 CloseWebView();
107 return nullptr;
108 }
109
110 // GTK destroys the plug itself if the host destroys the parent window first
111 g_signal_connect(mPlug, "destroy", G_CALLBACK(OnPlugDestroyed), this);
112
113 mView = webkit_web_view_new();
114 auto* pManager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(mView));
115 webkit_user_content_manager_register_script_message_handler(pManager, "iplug");
116 g_signal_connect(pManager, "script-message-received::iplug", G_CALLBACK(OnScriptMessage), this);
117
118 auto* pBridge = webkit_user_script_new("window.IPlugSendMsg = function(msg) { window.webkit.messageHandlers.iplug.postMessage(JSON.stringify(msg)); };", WEBKIT_USER_CONTENT_INJECT_TOP_FRAME,
119 WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, nullptr, nullptr);
120 webkit_user_content_manager_add_script(pManager, pBridge);
121 webkit_user_script_unref(pBridge);
122
123 g_signal_connect(mView, "decide-policy", G_CALLBACK(OnDecidePolicy), this);
124 g_signal_connect(mView, "load-changed", G_CALLBACK(OnLoadChanged), this);
125 g_signal_connect(mView, "load-failed", G_CALLBACK(OnLoadFailed), this);
126
127 if (mHostChild)
128 {
129 // The standalone exports its effective UI scale (which may be fractional,
130 // e.g. 1.5); GDK only renders at integer factors, so zoom the difference.
131 const char* str = getenv("IPLUG2_SCREEN_SCALE");
132 char* pEnd = nullptr;
133 const double screenScale = str ? strtod(str, &pEnd) : 0.;
134
135 if (str && pEnd != str && *pEnd == '\0' && screenScale >= 1. && screenScale <= 8.)
136 webkit_web_view_set_zoom_level(WEBKIT_WEB_VIEW(mView), screenScale / mHostScale);
137 }
138
139 gtk_container_add(GTK_CONTAINER(mPlug), mView);
140 SetWebViewBounds(x, y, w, h, scale);
141 gtk_widget_show_all(mPlug);
142
143 if (!gtk_plug_get_embedded(GTK_PLUG(mPlug)))
144 {
145 CloseWebView();
146 return nullptr;
147 }
148
149 MapPlug();
150 SetWebViewBounds(x, y, w, h, scale);
151 mOwner->OnWebViewReady();
152
153 return reinterpret_cast<void*>(static_cast<uintptr_t>(gtk_plug_get_id(GTK_PLUG(mPlug))));
154 }
155
156 void CloseWebView()
157 {
158 if (mPlug)
159 {
160 g_signal_handlers_disconnect_by_data(mPlug, this);
161
162 if (mView)
163 {
164 g_signal_handlers_disconnect_by_data(mView, this);
165 auto* pManager = webkit_web_view_get_user_content_manager(WEBKIT_WEB_VIEW(mView));
166 g_signal_handlers_disconnect_by_data(pManager, this);
167 }
168
169 gtk_widget_destroy(mPlug);
170 mPlug = nullptr;
171 mView = nullptr;
172 }
173
174 if (mHostChild)
175 {
176 XDestroyWindow(gdk_x11_get_default_xdisplay(), mHostChild);
177 mHostChild = 0;
178 }
179 }
180
181 void HideWebView(bool hide)
182 {
183 if (!mPlug)
184 return;
185
186 gtk_widget_set_visible(mPlug, !hide);
187
188 if (!hide)
189 MapPlug();
190 }
191
192 void LoadHTML(const char* html)
193 {
194 if (mView)
195 webkit_web_view_load_html(WEBKIT_WEB_VIEW(mView), html, nullptr);
196 }
197
198 void LoadURL(const char* url)
199 {
200 if (mView)
201 webkit_web_view_load_uri(WEBKIT_WEB_VIEW(mView), url);
202 }
203
204 void LoadFile(const char* fileName, const char*)
205 {
206 if (!mView || !fileName)
207 return;
208
209 if (PathHasDotDotComponent(fileName))
210 return;
211
212 namespace fs = std::filesystem;
213 fs::path path(fileName);
214
215 if (!path.is_absolute())
216 {
217 Dl_info info{};
218
219 if (!dladdr(reinterpret_cast<void*>(&IPlugLinuxWebViewModuleAnchor), &info))
220 return;
221
222 fs::path directory = fs::path(info.dli_fname).parent_path();
223
224 // VST3 binaries live in <bundle>/Contents/<arch>/; CLAP uses a
225 // per-plugin .clap.resources sidecar so multiple CLAPs never collide.
226 if (directory.parent_path().filename() == "Contents")
227 directory = directory.parent_path().parent_path();
228
229 if (fs::path(info.dli_fname).extension() == ".clap")
230 path = fs::path(info.dli_fname).string() + ".resources/web/" + path.string();
231 else
232 path = directory / "Resources" / "web" / path;
233 }
234
235 // dladdr reports the path as given to dlopen, which may be relative;
236 // g_filename_to_uri only accepts absolute paths.
237 std::error_code ec;
238
239 if (fs::path absolute = fs::absolute(path, ec); !ec)
240 path = absolute;
241
242 mWebRoot.Set(path.parent_path().string().c_str());
243 GError* pError = nullptr;
244 char* uri = g_filename_to_uri(path.string().c_str(), nullptr, &pError);
245
246 if (uri && fs::exists(path, ec))
247 LoadURL(uri);
248 else
249 g_warning("iPlug2 WebView: missing file %s", path.string().c_str());
250
251 g_free(uri);
252
253 if (pError)
254 g_error_free(pError);
255 }
256
257 void ReloadPageContent()
258 {
259 if (mView)
260 webkit_web_view_reload(WEBKIT_WEB_VIEW(mView));
261 }
262
263 void EvaluateJavaScript(const char* script, IWebView::completionHandlerFunc func)
264 {
265 if (!mView)
266 return;
267
268 auto* pCallback = new IWebView::completionHandlerFunc(std::move(func));
269 webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(mView), script, nullptr, OnJavaScriptFinished, pCallback);
270 }
271
272 void EnableScroll(bool) {}
273
274 void EnableInteraction(bool enable)
275 {
276 if (mView)
277 gtk_widget_set_sensitive(mView, enable);
278 }
279
280 void SetWebViewBounds(float, float, float w, float h, float scale)
281 {
282 if (!mPlug)
283 return;
284
285 // Plugin hosts size the editor in X11 (physical) pixels. The standalone
286 // container is sized in GDK units, which GDK multiplies by its scale.
287 const int unit = mHostChild ? mHostScale : 1;
288 const int width = std::max(1, static_cast<int>(std::ceil(w * scale))) * unit;
289 const int height = std::max(1, static_cast<int>(std::ceil(h * scale))) * unit;
290
291 // GTK sizes are in GDK units; keep the X11 window at the exact pixel size.
292 const int gdkScale = std::max(1, gtk_widget_get_scale_factor(mPlug));
293 const int gtkWidth = std::max(1, (width + gdkScale - 1) / gdkScale);
294 const int gtkHeight = std::max(1, (height + gdkScale - 1) / gdkScale);
295
296 if (mHostChild)
297 XResizeWindow(gdk_x11_get_default_xdisplay(), mHostChild, width, height);
298
299 gtk_widget_set_size_request(mPlug, gtkWidth, gtkHeight);
300
301 if (gtk_widget_get_realized(mPlug))
302 {
303 gtk_window_resize(GTK_WINDOW(mPlug), gtkWidth, gtkHeight);
304 XResizeWindow(gdk_x11_get_default_xdisplay(), gtk_plug_get_id(GTK_PLUG(mPlug)), width, height);
305 }
306 }
307
308 void GetWebRoot(WDL_String& path) const { path.Set(mWebRoot.Get()); }
309
310 void GetLocalDownloadPathForFile(const char* fileName, WDL_String& path)
311 {
312 DesktopPath(path);
313 path.Append("/");
314 path.Append(fileName);
315 }
316
317private:
318 static void OnPlugDestroyed(GtkWidget*, gpointer pData)
319 {
320 auto* pSelf = static_cast<IWebViewImpl*>(pData);
321 pSelf->mPlug = nullptr;
322 pSelf->mView = nullptr;
323 }
324
325 static void OnScriptMessage(WebKitUserContentManager*, WebKitJavascriptResult* pResult, gpointer pData)
326 {
327 auto* pSelf = static_cast<IWebViewImpl*>(pData);
328 char* text = jsc_value_to_string(webkit_javascript_result_get_js_value(pResult));
329
330 if (text)
331 {
332 pSelf->mOwner->OnMessageFromWebView(text);
333 g_free(text);
334 }
335 }
336
337 static gboolean OnDecidePolicy(WebKitWebView*, WebKitPolicyDecision* pDecision, WebKitPolicyDecisionType type, gpointer pData)
338 {
339 if (type != WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION)
340 return FALSE;
341
342 const char* uri = webkit_uri_request_get_uri(webkit_navigation_policy_decision_get_request(WEBKIT_NAVIGATION_POLICY_DECISION(pDecision)));
343
344 if (static_cast<IWebViewImpl*>(pData)->mOwner->OnCanNavigateToURL(uri))
345 return FALSE;
346
347 webkit_policy_decision_ignore(pDecision);
348 return TRUE;
349 }
350
351 static void OnLoadChanged(WebKitWebView*, WebKitLoadEvent event, gpointer pData)
352 {
353 auto* pSelf = static_cast<IWebViewImpl*>(pData);
354
355 if (event == WEBKIT_LOAD_STARTED)
356 pSelf->mLoadFailed = false;
357
358 if (event == WEBKIT_LOAD_FINISHED && !pSelf->mLoadFailed)
359 pSelf->mOwner->OnWebContentLoaded();
360 }
361
362 static gboolean OnLoadFailed(WebKitWebView*, WebKitLoadEvent, const char*, GError*, gpointer pData)
363 {
364 static_cast<IWebViewImpl*>(pData)->mLoadFailed = true;
365 return FALSE;
366 }
367
368 static void OnJavaScriptFinished(GObject* pSource, GAsyncResult* pResult, gpointer pData)
369 {
370 std::unique_ptr<IWebView::completionHandlerFunc> callback(static_cast<IWebView::completionHandlerFunc*>(pData));
371 WebKitJavascriptResult* pValue = webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(pSource), pResult, nullptr);
372
373 if (pValue)
374 {
375 if (*callback)
376 {
377 char* text = jsc_value_to_string(webkit_javascript_result_get_js_value(pValue));
378 (*callback)(text);
379 g_free(text);
380 }
381
382 webkit_javascript_result_unref(pValue);
383 }
384 }
385
386 // XEMBED leaves mapping the client to the embedder (normally a GtkSocket).
387 // Plugin hosts hand over a plain X11 window, so the plug must map itself.
388 void MapPlug()
389 {
390 if (GdkWindow* pWindow = gtk_widget_get_window(mPlug))
391 gdk_window_show(pWindow);
392 }
393
394 IWebView* mOwner;
395 GtkWidget* mPlug = nullptr;
396 GtkWidget* mView = nullptr;
397 Window mHostChild = 0; // only when the parent is this process's own GDK window
398 int mHostScale = 1;
399 bool mLoadFailed = false;
400 WDL_String mWebRoot;
401};
402
403END_IPLUG_NAMESPACE
404
405#include "IPlugWebView.cpp"
Common paths useful for plug-ins.
static BEGIN_IPLUG_NAMESPACE bool PathHasDotDotComponent(const char *str)
Definition: IPlugPaths.h:25
void DesktopPath(WDL_String &path)
IWebView is a base interface for hosting a platform web view inside an IPlug plug-in's UI.
Definition: IPlugWebView.h:44
virtual bool OnCanNavigateToURL(const char *url)
Override to filter URLs.
Definition: IPlugWebView.h:119
virtual void OnWebViewReady()
Called when the web view is ready to receive navigation instructions.
Definition: IPlugWebView.h:110