Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 23 additions & 12 deletions src/apps/desktop/src/api/browser_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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}"))
}
Expand Down
4 changes: 4 additions & 0 deletions src/apps/desktop/src/appearance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
Expand Down
2 changes: 2 additions & 0 deletions src/apps/desktop/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
136 changes: 136 additions & 0 deletions src/apps/desktop/src/linux_browser_layout.rs
Original file line number Diff line number Diff line change
@@ -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::<gtk::Box>() 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::<gtk::gdk::Rectangle>(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<tauri::Wry>,
position: LogicalPosition<f64>,
size: LogicalSize<f64>,
) -> Result<Webview, String> {
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<f64>,
size: LogicalSize<f64>,
) -> Result<(), String> {
child.hide();
let parent = child
.parent()
.and_downcast::<gtk::Box>()
.ok_or_else(|| "browser webview is missing its GTK container".to_string())?;
let overlay = parent
.children()
.into_iter()
.filter_map(|widget| widget.downcast::<gtk::Overlay>().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<f64>,
size: LogicalSize<f64>,
) -> Result<(), String> {
let (sender, receiver) = oneshot::channel();
webview
.with_webview(move |native| {
let child: Widget = native.inner().upcast();
let result = child
.parent()
.and_downcast::<gtk::Overlay>()
.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<f64>, size: LogicalSize<f64>) {
let position = position.cast::<i32>();
let size = size.cast::<i32>();
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) }
}
24 changes: 18 additions & 6 deletions tests/e2e/scripts/run-html-preview.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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' });
Expand Down Expand Up @@ -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);
Expand Down
Loading