diff --git a/src/apps/desktop/src/api/browser_api.rs b/src/apps/desktop/src/api/browser_api.rs index a5c4053f3e..b0122444c5 100644 --- a/src/apps/desktop/src/api/browser_api.rs +++ b/src/apps/desktop/src/api/browser_api.rs @@ -431,17 +431,22 @@ pub async fn browser_webview_create( builder = builder.devtools(true); } - let webview = window - .add_child( - builder, - tauri::LogicalPosition::new(request.x, request.y), - tauri::LogicalSize::new(request.width, request.height), - ) - .map_err(|e| format!("failed to create browser webview: {e}"))?; + let position = tauri::LogicalPosition::new(request.x, request.y); + let size = tauri::LogicalSize::new(request.width, request.height); + #[cfg(target_os = "linux")] + let webview = + crate::linux_browser_layout::create_child(window, builder, position, size).await?; + #[cfg(not(target_os = "linux"))] + let webview = { + let webview = window + .add_child(builder, position, size) + .map_err(|e| format!("failed to create browser webview: {e}"))?; + webview + .hide() + .map_err(|e| format!("failed to hide browser webview before positioning: {e}"))?; + webview + }; - webview - .hide() - .map_err(|e| format!("failed to hide browser webview before positioning: {e}"))?; let target_url = webview.url().map(|url| url.to_string()).unwrap_or_default(); register_browser_target( webview.label(), @@ -648,10 +653,16 @@ pub async fn browser_webview_set_bounds( .get_webview(&request.label) .ok_or_else(|| format!("Webview not found: {}", request.label))?; + let position = tauri::LogicalPosition::new(request.x, request.y); + let size = tauri::LogicalSize::new(request.width, request.height); + #[cfg(target_os = "linux")] + return crate::linux_browser_layout::set_bounds(&webview, position, size).await; + + #[cfg(not(target_os = "linux"))] webview .set_bounds(tauri::Rect { - position: tauri::Position::Logical(tauri::LogicalPosition::new(request.x, request.y)), - size: tauri::Size::Logical(tauri::LogicalSize::new(request.width, request.height)), + position: tauri::Position::Logical(position), + size: tauri::Size::Logical(size), }) .map_err(|e| format!("set bounds failed: {e}")) } diff --git a/src/apps/desktop/src/appearance.rs b/src/apps/desktop/src/appearance.rs index a2af3d3d8e..1e4301a298 100644 --- a/src/apps/desktop/src/appearance.rs +++ b/src/apps/desktop/src/appearance.rs @@ -711,6 +711,10 @@ pub fn create_main_window( let build_started_at = Instant::now(); match builder.build() { Ok(window) => { + #[cfg(target_os = "linux")] + if let Err(error) = crate::linux_browser_layout::install(&window) { + error!("Failed to install browser WebView layout: {error}"); + } #[cfg(target_os = "macos")] if let Err(error) = crate::macos_window_chrome::install(&window) { error!("Failed to install native fullscreen chrome synchronization: {error}"); diff --git a/src/apps/desktop/src/lib.rs b/src/apps/desktop/src/lib.rs index fd959570a7..942f0cdc49 100644 --- a/src/apps/desktop/src/lib.rs +++ b/src/apps/desktop/src/lib.rs @@ -30,6 +30,8 @@ mod embedded_relay_host; mod figure_verifier; mod frontend_asset_cache; pub mod frontend_workbench; +#[cfg(target_os = "linux")] +mod linux_browser_layout; pub mod logging; pub mod macos_menubar; #[cfg(target_os = "macos")] diff --git a/src/apps/desktop/src/linux_browser_layout.rs b/src/apps/desktop/src/linux_browser_layout.rs new file mode 100644 index 0000000000..487575c8d1 --- /dev/null +++ b/src/apps/desktop/src/linux_browser_layout.rs @@ -0,0 +1,136 @@ +//! Keep Tauri browser children out of the main WebView's vertical GTK layout. + +use gtk::prelude::*; +use gtk::{OverlaySignals, Widget}; +use tauri::{LogicalPosition, LogicalSize, Webview, WebviewWindow, Window}; +use tokio::sync::oneshot; + +const OVERLAY_NAME: &str = "openbitfun-browser-overlay"; +const BOUNDS_KEY: &str = "openbitfun-browser-overlay-bounds"; + +pub(crate) fn install(window: &WebviewWindow) -> tauri::Result<()> { + window.with_webview(|native| { + let main = native.inner(); + let Some(parent) = main.parent().and_downcast::() else { + log::error!("Main WebView is missing its GTK container"); + return; + }; + + let overlay = gtk::Overlay::new(); + overlay.set_widget_name(OVERLAY_NAME); + overlay.connect_get_child_position(|_, child| { + // SAFETY: This module exclusively uses this key for a Rectangle. + // GTK calls this on its main thread and we copy the value immediately. + unsafe { + child + .data::(BOUNDS_KEY) + .map(|value| *value.as_ref()) + } + }); + + // Only the primary child contributes to the window's size request. + parent.remove(&main); + overlay.add(&main); + parent.pack_start(&overlay, true, true, 0); + overlay.show(); + }) +} + +pub(crate) async fn create_child( + window: Window, + builder: tauri::webview::WebviewBuilder, + position: LogicalPosition, + size: LogicalSize, +) -> Result { + let (sender, receiver) = oneshot::channel(); + let host = window.clone(); + window + .run_on_main_thread(move || { + // Attach and hide in the same GTK iteration as Tauri creates the + // child so the vertical box cannot lay it out or paint it first. + let webview = host.add_child(builder.focused(false), position, size); + let result = webview + .map_err(|error| format!("failed to create browser webview: {error}")) + .and_then(|webview| { + let (attached, mut attachment) = oneshot::channel(); + // Tauri dispatches with_webview inline on its main thread. + let result = webview + .with_webview(move |native| { + let result = attach_child(&native.inner().upcast(), position, size); + let _ = attached.send(result); + }) + .map_err(|error| format!("failed to access browser webview: {error}")) + .and_then(|()| { + attachment.try_recv().map_err(|_| { + "browser webview GTK attachment did not run".to_string() + })? + }); + if let Err(error) = result { + let _ = webview.close(); + return Err(error); + } + Ok(webview) + }); + let _ = sender.send(result); + }) + .map_err(|error| format!("failed to schedule browser webview creation: {error}"))?; + receiver + .await + .map_err(|_| "browser webview creation was canceled".to_string())? +} + +fn attach_child( + child: &Widget, + position: LogicalPosition, + size: LogicalSize, +) -> Result<(), String> { + child.hide(); + let parent = child + .parent() + .and_downcast::() + .ok_or_else(|| "browser webview is missing its GTK container".to_string())?; + let overlay = parent + .children() + .into_iter() + .filter_map(|widget| widget.downcast::().ok()) + .find(|overlay| overlay.widget_name() == OVERLAY_NAME) + .ok_or_else(|| "browser webview is missing its GTK overlay".to_string())?; + + save_bounds(child, position, size); + parent.remove(child); + overlay.add_overlay(child); + Ok(()) +} + +pub(crate) async fn set_bounds( + webview: &Webview, + position: LogicalPosition, + size: LogicalSize, +) -> Result<(), String> { + let (sender, receiver) = oneshot::channel(); + webview + .with_webview(move |native| { + let child: Widget = native.inner().upcast(); + let result = child + .parent() + .and_downcast::() + .ok_or_else(|| "browser webview is missing its GTK overlay".to_string()) + .map(|overlay| { + save_bounds(&child, position, size); + overlay.queue_allocate(); + }); + let _ = sender.send(result); + }) + .map_err(|error| format!("set bounds failed: {error}"))?; + receiver + .await + .map_err(|_| "browser webview bounds update was canceled".to_string())? +} + +fn save_bounds(child: &Widget, position: LogicalPosition, size: LogicalSize) { + let position = position.cast::(); + let size = size.cast::(); + let bounds = gtk::gdk::Rectangle::new(position.x, position.y, size.width, size.height); + // SAFETY: Only this module accesses this key, always with a Rectangle. + unsafe { child.set_data(BOUNDS_KEY, bounds) } +} diff --git a/tests/e2e/scripts/run-html-preview.mjs b/tests/e2e/scripts/run-html-preview.mjs index 697db05654..6db526fae1 100644 --- a/tests/e2e/scripts/run-html-preview.mjs +++ b/tests/e2e/scripts/run-html-preview.mjs @@ -101,10 +101,15 @@ await writeFile(path.join(spa, 'assets/app.mjs'), 'const { routes } = await impo await writeFile(path.join(spa, 'assets/routes.mjs'), 'export const routes = ["/", "/evaluation", "/docs/detail"];'); await cp(path.join(workspace, 'site/dist/assets/pixel.png'), path.join(spa, 'assets/pixel.png')); const previews = []; -async function checkPage(label, marker, color) { +const viewport = () => execute(() => [window.innerWidth, window.innerHeight]); +const initialBounds = { x: 350, y: 80, width: 480, height: 320 }; +const updatedBounds = { x: 400, y: 100, width: 300, height: 200 }; +async function checkPage(label, marker, color, { bounds = initialBounds, reload = false } = {}) { + const mainViewport = process.platform === 'linux' ? await viewport() : null; await invoke('plugin:webview|webview_show', { label }); await request('/session/' + session + '/window', { handle: label }); try { + if (reload) await request('/session/' + session + '/refresh', {}); await until(() => execute((marker, color) => { const result = document.querySelector('#result'); const image = document.querySelector('#image'); @@ -116,6 +121,12 @@ async function checkPage(label, marker, color) { resources: performance.getEntriesByType('resource').map(entry => entry.name) })); assert.ok(!details.url.includes('previewToken='), 'Bootstrap token must leave the document URL'); assert.ok(details.url.endsWith('/index%20%231.html')); + if (mainViewport) { + details.viewport = await viewport(); + assert.deepEqual(details.viewport, [bounds.width, bounds.height], 'Linux preview must use its panel size'); + await request('/session/' + session + '/window', { handle: 'main' }); + assert.deepEqual(await viewport(), mainViewport, 'A visible preview must keep the main viewport size'); + } report.checks.push(details); } finally { await request('/session/' + session + '/window', { handle: 'main' }); @@ -146,14 +157,15 @@ try { filePath: path.join(workspace, directory, 'index #1.html') } }); previews.push(preview); const label = 'embedded-browser-panel-view-html-' + marker; - await invoke('browser_webview_create', { request: { label, url: preview.url, x: 350, y: 80, width: 480, height: 320 } }); + await invoke('browser_webview_create', { request: { label, url: preview.url, ...initialBounds } }); await checkPage(label, marker, color); } // The second preview must not replace the first preview's authorization cookie. - await request('/session/' + session + '/window', { handle: 'embedded-browser-panel-view-html-first' }); - await request('/session/' + session + '/refresh', {}); - await request('/session/' + session + '/window', { handle: 'main' }); - await checkPage('embedded-browser-panel-view-html-first', 'first', 'rgb(23, 81, 139)'); + const firstLabel = 'embedded-browser-panel-view-html-first'; + if (process.platform === 'linux') { + await invoke('browser_webview_set_bounds', { request: { label: firstLabel, ...updatedBounds } }); + } + await checkPage(firstLabel, 'first', 'rgb(23, 81, 139)', { bounds: updatedBounds, reload: true }); const sitePreview = await invoke('html_preview_create', { request: { workspaceId: opened.id, filePath: path.join(spa, 'index.html') } }); previews.push(sitePreview);