Skip to content

Commit 8c2c258

Browse files
authored
Merge pull request #4033 from kev1n77/fix/linux-html-preview-layout
fix(desktop): keep Linux HTML previews inside the browser panel
2 parents 5676fcf + 300bc83 commit 8c2c258

5 files changed

Lines changed: 183 additions & 18 deletions

File tree

‎src/apps/desktop/src/api/browser_api.rs‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -431,17 +431,22 @@ pub async fn browser_webview_create(
431431
builder = builder.devtools(true);
432432
}
433433

434-
let webview = window
435-
.add_child(
436-
builder,
437-
tauri::LogicalPosition::new(request.x, request.y),
438-
tauri::LogicalSize::new(request.width, request.height),
439-
)
440-
.map_err(|e| format!("failed to create browser webview: {e}"))?;
434+
let position = tauri::LogicalPosition::new(request.x, request.y);
435+
let size = tauri::LogicalSize::new(request.width, request.height);
436+
#[cfg(target_os = "linux")]
437+
let webview =
438+
crate::linux_browser_layout::create_child(window, builder, position, size).await?;
439+
#[cfg(not(target_os = "linux"))]
440+
let webview = {
441+
let webview = window
442+
.add_child(builder, position, size)
443+
.map_err(|e| format!("failed to create browser webview: {e}"))?;
444+
webview
445+
.hide()
446+
.map_err(|e| format!("failed to hide browser webview before positioning: {e}"))?;
447+
webview
448+
};
441449

442-
webview
443-
.hide()
444-
.map_err(|e| format!("failed to hide browser webview before positioning: {e}"))?;
445450
let target_url = webview.url().map(|url| url.to_string()).unwrap_or_default();
446451
register_browser_target(
447452
webview.label(),
@@ -648,10 +653,16 @@ pub async fn browser_webview_set_bounds(
648653
.get_webview(&request.label)
649654
.ok_or_else(|| format!("Webview not found: {}", request.label))?;
650655

656+
let position = tauri::LogicalPosition::new(request.x, request.y);
657+
let size = tauri::LogicalSize::new(request.width, request.height);
658+
#[cfg(target_os = "linux")]
659+
return crate::linux_browser_layout::set_bounds(&webview, position, size).await;
660+
661+
#[cfg(not(target_os = "linux"))]
651662
webview
652663
.set_bounds(tauri::Rect {
653-
position: tauri::Position::Logical(tauri::LogicalPosition::new(request.x, request.y)),
654-
size: tauri::Size::Logical(tauri::LogicalSize::new(request.width, request.height)),
664+
position: tauri::Position::Logical(position),
665+
size: tauri::Size::Logical(size),
655666
})
656667
.map_err(|e| format!("set bounds failed: {e}"))
657668
}

‎src/apps/desktop/src/appearance.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,10 @@ pub fn create_main_window(
711711
let build_started_at = Instant::now();
712712
match builder.build() {
713713
Ok(window) => {
714+
#[cfg(target_os = "linux")]
715+
if let Err(error) = crate::linux_browser_layout::install(&window) {
716+
error!("Failed to install browser WebView layout: {error}");
717+
}
714718
#[cfg(target_os = "macos")]
715719
if let Err(error) = crate::macos_window_chrome::install(&window) {
716720
error!("Failed to install native fullscreen chrome synchronization: {error}");

‎src/apps/desktop/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ mod embedded_relay_host;
3030
mod figure_verifier;
3131
mod frontend_asset_cache;
3232
pub mod frontend_workbench;
33+
#[cfg(target_os = "linux")]
34+
mod linux_browser_layout;
3335
pub mod logging;
3436
pub mod macos_menubar;
3537
#[cfg(target_os = "macos")]
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
//! Keep Tauri browser children out of the main WebView's vertical GTK layout.
2+
3+
use gtk::prelude::*;
4+
use gtk::{OverlaySignals, Widget};
5+
use tauri::{LogicalPosition, LogicalSize, Webview, WebviewWindow, Window};
6+
use tokio::sync::oneshot;
7+
8+
const OVERLAY_NAME: &str = "openbitfun-browser-overlay";
9+
const BOUNDS_KEY: &str = "openbitfun-browser-overlay-bounds";
10+
11+
pub(crate) fn install(window: &WebviewWindow) -> tauri::Result<()> {
12+
window.with_webview(|native| {
13+
let main = native.inner();
14+
let Some(parent) = main.parent().and_downcast::<gtk::Box>() else {
15+
log::error!("Main WebView is missing its GTK container");
16+
return;
17+
};
18+
19+
let overlay = gtk::Overlay::new();
20+
overlay.set_widget_name(OVERLAY_NAME);
21+
overlay.connect_get_child_position(|_, child| {
22+
// SAFETY: This module exclusively uses this key for a Rectangle.
23+
// GTK calls this on its main thread and we copy the value immediately.
24+
unsafe {
25+
child
26+
.data::<gtk::gdk::Rectangle>(BOUNDS_KEY)
27+
.map(|value| *value.as_ref())
28+
}
29+
});
30+
31+
// Only the primary child contributes to the window's size request.
32+
parent.remove(&main);
33+
overlay.add(&main);
34+
parent.pack_start(&overlay, true, true, 0);
35+
overlay.show();
36+
})
37+
}
38+
39+
pub(crate) async fn create_child(
40+
window: Window,
41+
builder: tauri::webview::WebviewBuilder<tauri::Wry>,
42+
position: LogicalPosition<f64>,
43+
size: LogicalSize<f64>,
44+
) -> Result<Webview, String> {
45+
let (sender, receiver) = oneshot::channel();
46+
let host = window.clone();
47+
window
48+
.run_on_main_thread(move || {
49+
// Attach and hide in the same GTK iteration as Tauri creates the
50+
// child so the vertical box cannot lay it out or paint it first.
51+
let webview = host.add_child(builder.focused(false), position, size);
52+
let result = webview
53+
.map_err(|error| format!("failed to create browser webview: {error}"))
54+
.and_then(|webview| {
55+
let (attached, mut attachment) = oneshot::channel();
56+
// Tauri dispatches with_webview inline on its main thread.
57+
let result = webview
58+
.with_webview(move |native| {
59+
let result = attach_child(&native.inner().upcast(), position, size);
60+
let _ = attached.send(result);
61+
})
62+
.map_err(|error| format!("failed to access browser webview: {error}"))
63+
.and_then(|()| {
64+
attachment.try_recv().map_err(|_| {
65+
"browser webview GTK attachment did not run".to_string()
66+
})?
67+
});
68+
if let Err(error) = result {
69+
let _ = webview.close();
70+
return Err(error);
71+
}
72+
Ok(webview)
73+
});
74+
let _ = sender.send(result);
75+
})
76+
.map_err(|error| format!("failed to schedule browser webview creation: {error}"))?;
77+
receiver
78+
.await
79+
.map_err(|_| "browser webview creation was canceled".to_string())?
80+
}
81+
82+
fn attach_child(
83+
child: &Widget,
84+
position: LogicalPosition<f64>,
85+
size: LogicalSize<f64>,
86+
) -> Result<(), String> {
87+
child.hide();
88+
let parent = child
89+
.parent()
90+
.and_downcast::<gtk::Box>()
91+
.ok_or_else(|| "browser webview is missing its GTK container".to_string())?;
92+
let overlay = parent
93+
.children()
94+
.into_iter()
95+
.filter_map(|widget| widget.downcast::<gtk::Overlay>().ok())
96+
.find(|overlay| overlay.widget_name() == OVERLAY_NAME)
97+
.ok_or_else(|| "browser webview is missing its GTK overlay".to_string())?;
98+
99+
save_bounds(child, position, size);
100+
parent.remove(child);
101+
overlay.add_overlay(child);
102+
Ok(())
103+
}
104+
105+
pub(crate) async fn set_bounds(
106+
webview: &Webview,
107+
position: LogicalPosition<f64>,
108+
size: LogicalSize<f64>,
109+
) -> Result<(), String> {
110+
let (sender, receiver) = oneshot::channel();
111+
webview
112+
.with_webview(move |native| {
113+
let child: Widget = native.inner().upcast();
114+
let result = child
115+
.parent()
116+
.and_downcast::<gtk::Overlay>()
117+
.ok_or_else(|| "browser webview is missing its GTK overlay".to_string())
118+
.map(|overlay| {
119+
save_bounds(&child, position, size);
120+
overlay.queue_allocate();
121+
});
122+
let _ = sender.send(result);
123+
})
124+
.map_err(|error| format!("set bounds failed: {error}"))?;
125+
receiver
126+
.await
127+
.map_err(|_| "browser webview bounds update was canceled".to_string())?
128+
}
129+
130+
fn save_bounds(child: &Widget, position: LogicalPosition<f64>, size: LogicalSize<f64>) {
131+
let position = position.cast::<i32>();
132+
let size = size.cast::<i32>();
133+
let bounds = gtk::gdk::Rectangle::new(position.x, position.y, size.width, size.height);
134+
// SAFETY: Only this module accesses this key, always with a Rectangle.
135+
unsafe { child.set_data(BOUNDS_KEY, bounds) }
136+
}

‎tests/e2e/scripts/run-html-preview.mjs‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,15 @@ await writeFile(path.join(spa, 'assets/app.mjs'), 'const { routes } = await impo
101101
await writeFile(path.join(spa, 'assets/routes.mjs'), 'export const routes = ["/", "/evaluation", "/docs/detail"];');
102102
await cp(path.join(workspace, 'site/dist/assets/pixel.png'), path.join(spa, 'assets/pixel.png'));
103103
const previews = [];
104-
async function checkPage(label, marker, color) {
104+
const viewport = () => execute(() => [window.innerWidth, window.innerHeight]);
105+
const initialBounds = { x: 350, y: 80, width: 480, height: 320 };
106+
const updatedBounds = { x: 400, y: 100, width: 300, height: 200 };
107+
async function checkPage(label, marker, color, { bounds = initialBounds, reload = false } = {}) {
108+
const mainViewport = process.platform === 'linux' ? await viewport() : null;
105109
await invoke('plugin:webview|webview_show', { label });
106110
await request('/session/' + session + '/window', { handle: label });
107111
try {
112+
if (reload) await request('/session/' + session + '/refresh', {});
108113
await until(() => execute((marker, color) => {
109114
const result = document.querySelector('#result');
110115
const image = document.querySelector('#image');
@@ -116,6 +121,12 @@ async function checkPage(label, marker, color) {
116121
resources: performance.getEntriesByType('resource').map(entry => entry.name) }));
117122
assert.ok(!details.url.includes('previewToken='), 'Bootstrap token must leave the document URL');
118123
assert.ok(details.url.endsWith('/index%20%231.html'));
124+
if (mainViewport) {
125+
details.viewport = await viewport();
126+
assert.deepEqual(details.viewport, [bounds.width, bounds.height], 'Linux preview must use its panel size');
127+
await request('/session/' + session + '/window', { handle: 'main' });
128+
assert.deepEqual(await viewport(), mainViewport, 'A visible preview must keep the main viewport size');
129+
}
119130
report.checks.push(details);
120131
} finally {
121132
await request('/session/' + session + '/window', { handle: 'main' });
@@ -146,14 +157,15 @@ try {
146157
filePath: path.join(workspace, directory, 'index #1.html') } });
147158
previews.push(preview);
148159
const label = 'embedded-browser-panel-view-html-' + marker;
149-
await invoke('browser_webview_create', { request: { label, url: preview.url, x: 350, y: 80, width: 480, height: 320 } });
160+
await invoke('browser_webview_create', { request: { label, url: preview.url, ...initialBounds } });
150161
await checkPage(label, marker, color);
151162
}
152163
// The second preview must not replace the first preview's authorization cookie.
153-
await request('/session/' + session + '/window', { handle: 'embedded-browser-panel-view-html-first' });
154-
await request('/session/' + session + '/refresh', {});
155-
await request('/session/' + session + '/window', { handle: 'main' });
156-
await checkPage('embedded-browser-panel-view-html-first', 'first', 'rgb(23, 81, 139)');
164+
const firstLabel = 'embedded-browser-panel-view-html-first';
165+
if (process.platform === 'linux') {
166+
await invoke('browser_webview_set_bounds', { request: { label: firstLabel, ...updatedBounds } });
167+
}
168+
await checkPage(firstLabel, 'first', 'rgb(23, 81, 139)', { bounds: updatedBounds, reload: true });
157169
const sitePreview = await invoke('html_preview_create', { request: { workspaceId: opened.id,
158170
filePath: path.join(spa, 'index.html') } });
159171
previews.push(sitePreview);

0 commit comments

Comments
 (0)