tauri 2 (runtime-wry build_gtk with the window's GtkBox) packs every child webview into the window box, stacked and with set_position/set_size ignored, so tab webviews landed under the shell instead of over their panes. place_child/attach_shell move them into a GtkOverlay (shell as base layer) and allocate each at its exact rect via get-child-position; placed_rect reports the placement (GTK children have no position). Windows/macOS keep set_position/set_size.
323 lines
14 KiB
Rust
323 lines
14 KiB
Rust
//! Tauri glue that does not depend on the app's own state: caller checks, shell events, tab
|
|
//! webview lookups and actions, app-data JSON files, profile data folders and the Windows system
|
|
//! menu. The app keeps its `#[tauri::command]` wrappers (so IPC names and capabilities stay the
|
|
//! app's) and calls these.
|
|
|
|
use crate::{
|
|
policy,
|
|
profiles::{self, ProfileSettings},
|
|
site::SiteSpec,
|
|
tabs::{self, TabAction, TabState},
|
|
};
|
|
use serde::Serialize;
|
|
use tauri::{AppHandle, Emitter, EventTarget, Manager, Runtime, Webview};
|
|
use url::Url;
|
|
|
|
/// Shell-only commands: the trusted local `shell` webview (debug builds also accept the dev server).
|
|
pub fn shell_only<R: Runtime>(webview: &Webview<R>) -> Result<(), String> {
|
|
let url = webview.url().map_err(|_| "FORBIDDEN: cannot verify workspace origin")?;
|
|
policy::require_local(webview.label(), &url, cfg!(debug_assertions))
|
|
}
|
|
|
|
/// Tab-chrome commands: any tab webview, speaking only about itself. Returns its tab id.
|
|
pub fn tab_only<R: Runtime>(webview: &Webview<R>) -> Result<String, String> {
|
|
policy::tab_id(webview.label())
|
|
.map(str::to_owned)
|
|
.ok_or_else(|| "FORBIDDEN: tab webview required".into())
|
|
}
|
|
|
|
/// Site-only commands: a tab webview that is exactly on the site right now. Returns its URL (the
|
|
/// webview's own, never the page's claim).
|
|
pub fn site_tab_only<R: Runtime>(site: &SiteSpec, webview: &Webview<R>) -> Result<Url, String> {
|
|
let url = webview.url().map_err(|_| "FORBIDDEN: cannot verify origin")?;
|
|
policy::require_site_tab(site, webview.label(), &url)?;
|
|
Ok(url)
|
|
}
|
|
|
|
pub fn emit_shell<R: Runtime, S: Serialize + Clone>(app: &AppHandle<R>, event: &str, payload: S) {
|
|
let _ = app.emit_to(EventTarget::webview(policy::SHELL_LABEL), event, payload);
|
|
}
|
|
|
|
pub fn emit_tab_state<R: Runtime>(app: &AppHandle<R>, state: TabState) {
|
|
emit_shell(app, tabs::EVENT_TAB_STATE, state);
|
|
}
|
|
|
|
pub fn tab_webview<R: Runtime>(app: &AppHandle<R>, id: &str) -> Option<Webview<R>> {
|
|
app.get_webview(&policy::tab_label(id))
|
|
}
|
|
|
|
/// Evaluates `script` in every tab that is on the site right now.
|
|
pub fn eval_in_site_tabs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, script: &str) {
|
|
for (label, webview) in app.webviews() {
|
|
if policy::tab_id(&label).is_some() && webview.url().is_ok_and(|url| site.is_origin(&url)) {
|
|
let _ = webview.eval(script);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn data_file<R: Runtime>(app: &AppHandle<R>, name: &str) -> Option<std::path::PathBuf> {
|
|
app.path().app_data_dir().ok().map(|dir| dir.join(name))
|
|
}
|
|
|
|
/// `read_json::<T>(app, name)`: the app-data JSON file `name`, or None when missing or invalid.
|
|
pub fn read_json<T: serde::de::DeserializeOwned>(app: &AppHandle<impl Runtime>, name: &str) -> Option<T> {
|
|
serde_json::from_str(&std::fs::read_to_string(data_file(app, name)?).ok()?).ok()
|
|
}
|
|
|
|
pub fn write_json<R: Runtime, T: Serialize>(app: &AppHandle<R>, name: &str, value: &T) -> Result<(), String> {
|
|
let path = data_file(app, name).ok_or("STORAGE: no application data directory")?;
|
|
let json = serde_json::to_string_pretty(value).map_err(|_| "STORAGE: serialization failed")?;
|
|
std::fs::write(path, json).map_err(|error| format!("STORAGE: {error}"))
|
|
}
|
|
|
|
pub fn navigate_tab<R: Runtime>(app: &AppHandle<R>, id: &str, url: &str) -> Result<(), String> {
|
|
let url = tabs::parse_web_url(url)?;
|
|
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
|
|
tab.navigate(url).map_err(|error| format!("TAB: {error}"))
|
|
}
|
|
|
|
pub fn tab_action<R: Runtime>(app: &AppHandle<R>, id: &str, action: &str) -> Result<(), String> {
|
|
let action = TabAction::parse(action)?;
|
|
let tab = tab_webview(app, id).ok_or("TAB: not found")?;
|
|
let result = match action {
|
|
TabAction::Back => tab.eval("history.back()"),
|
|
TabAction::Forward => tab.eval("history.forward()"),
|
|
TabAction::Reload => tab.reload(),
|
|
TabAction::Stop => tab.eval("window.stop()"),
|
|
TabAction::Focus => tab.set_focus(),
|
|
};
|
|
result.map_err(|error| format!("TAB: {error}"))
|
|
}
|
|
|
|
/// A browser shortcut pressed inside tab `id`, forwarded to the shell (`tab-shortcut`).
|
|
pub fn forward_shortcut<R: Runtime>(app: &AppHandle<R>, id: String, shortcut: String) -> Result<(), String> {
|
|
if !tabs::valid_shortcut(&shortcut) {
|
|
return Err("VALIDATION: unknown shortcut".into());
|
|
}
|
|
#[derive(Clone, Serialize)]
|
|
struct Shortcut {
|
|
id: String,
|
|
shortcut: String,
|
|
}
|
|
emit_shell(app, tabs::EVENT_TAB_SHORTCUT, Shortcut { id, shortcut });
|
|
Ok(())
|
|
}
|
|
|
|
/// A link drag started/entered/ended in tab `id` (`link-drag`); the link opens only as a new tab.
|
|
pub fn forward_link_drag<R: Runtime>(app: &AppHandle<R>, id: String, phase: String, url: Option<String>) -> Result<(), String> {
|
|
let url = tabs::link_drag(&phase, url)?;
|
|
#[derive(Clone, Serialize)]
|
|
struct LinkDrag {
|
|
id: String,
|
|
phase: String,
|
|
url: Option<String>,
|
|
}
|
|
emit_shell(app, tabs::EVENT_LINK_DRAG, LinkDrag { id, phase, url });
|
|
Ok(())
|
|
}
|
|
|
|
/// Deletes the WebView data folders (the logins) of removed profiles.
|
|
pub fn remove_profile_dirs<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, removed: &[String]) {
|
|
let Ok(local) = app.path().app_local_data_dir() else { return };
|
|
for id in removed {
|
|
if let Some(dir) = profiles::data_dir(&local, id) {
|
|
if let Err(error) = std::fs::remove_dir_all(&dir) {
|
|
if error.kind() != std::io::ErrorKind::NotFound {
|
|
eprintln!("{}: could not remove profile data {}: {error}", site.product, dir.display());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Deletes WebView data folders of profiles that no longer exist (see [`profiles::orphan_dirs`]).
|
|
pub fn prune_profile_dirs<R: Runtime>(app: &AppHandle<R>, settings: &ProfileSettings) {
|
|
let Ok(local) = app.path().app_local_data_dir() else { return };
|
|
for dir in profiles::orphan_dirs(&local, settings) {
|
|
let _ = std::fs::remove_dir_all(dir);
|
|
}
|
|
}
|
|
|
|
/// Moves app-data and app-local data (WebView profile, i.e. the site login) from a previous bundle
|
|
/// identifier. Never overwrites an existing new folder.
|
|
pub fn migrate_identifier<R: Runtime>(app: &AppHandle<R>, site: &SiteSpec, legacy_identifier: &str) {
|
|
let dirs = [app.path().app_data_dir(), app.path().app_local_data_dir()];
|
|
for new_dir in dirs.into_iter().flatten() {
|
|
let Some(parent) = new_dir.parent() else { continue };
|
|
let old_dir = parent.join(legacy_identifier);
|
|
if old_dir.is_dir() && !new_dir.exists() {
|
|
if let Err(error) = std::fs::rename(&old_dir, &new_dir) {
|
|
eprintln!("{}: could not migrate {}: {error}", site.product, old_dir.display());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Shows the native window system menu (Restore, Move, Size, Minimize, Maximize, Close) at a
|
|
/// screen position, for a right-click on the custom titlebar. No-op outside Windows.
|
|
pub fn system_menu<R: Runtime>(webview: &Webview<R>, x: f64, y: f64) -> Result<(), String> {
|
|
if !x.is_finite() || !y.is_finite() {
|
|
return Err("VALIDATION: non-finite position".into());
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
use windows::Win32::Foundation::{LPARAM, WPARAM};
|
|
use windows::Win32::UI::WindowsAndMessaging::{
|
|
GetSystemMenu, PostMessageW, SetForegroundWindow, TrackPopupMenu, TPM_RETURNCMD, TPM_RIGHTBUTTON,
|
|
WM_SYSCOMMAND,
|
|
};
|
|
let hwnd = webview.window().hwnd().map_err(|error| format!("WINDOW: {error}"))?;
|
|
// SAFETY: plain Win32 calls on our own top-level window handle.
|
|
unsafe {
|
|
let menu = GetSystemMenu(hwnd, false);
|
|
if menu.is_invalid() {
|
|
return Ok(());
|
|
}
|
|
let _ = SetForegroundWindow(hwnd);
|
|
let command = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_RIGHTBUTTON, x as i32, y as i32, None, hwnd, None);
|
|
if command.0 != 0 {
|
|
let _ = PostMessageW(Some(hwnd), WM_SYSCOMMAND, WPARAM(command.0 as usize), LPARAM(0));
|
|
}
|
|
}
|
|
}
|
|
#[cfg(not(windows))]
|
|
let _ = webview;
|
|
Ok(())
|
|
}
|
|
|
|
/// Places a child webview (tab, popover) at a rectangle of its window, in logical px.
|
|
///
|
|
/// Windows/macOS: the native child bounds. Linux: tauri 2 packs every child webview into the
|
|
/// window's GtkBox (`build_gtk` with a box: stacked one under another, bounds ignored), so the host
|
|
/// moves each one into the GtkOverlay made by [`attach_shell`] and places it there.
|
|
pub fn place_child<R: Runtime>(webview: &Webview<R>, x: f64, y: f64, width: f64, height: f64) {
|
|
#[cfg(target_os = "linux")]
|
|
linux::place(webview, x, y, width, height);
|
|
#[cfg(not(target_os = "linux"))]
|
|
{
|
|
let _ = webview.set_position(tauri::LogicalPosition::new(x, y));
|
|
let _ = webview.set_size(tauri::LogicalSize::new(width, height));
|
|
}
|
|
}
|
|
|
|
/// Linux: the shell webview becomes the base layer of a GtkOverlay filling the window, which
|
|
/// [`place_child`] layers tab webviews over. Call once, right after the shell is added. No-op
|
|
/// elsewhere.
|
|
pub fn attach_shell<R: Runtime>(shell: &Webview<R>) {
|
|
#[cfg(target_os = "linux")]
|
|
linux::attach_shell(shell);
|
|
#[cfg(not(target_os = "linux"))]
|
|
let _ = shell;
|
|
}
|
|
|
|
/// Where [`place_child`] last put a child webview, in logical px (x, y, width, height). Linux
|
|
/// only: there `Webview::position` is not the placement (always 0,0 outside X11 child windows).
|
|
#[cfg(target_os = "linux")]
|
|
pub fn placed_rect<R: Runtime>(webview: &Webview<R>) -> Option<(f64, f64, f64, f64)> {
|
|
linux::placed(webview.label())
|
|
}
|
|
|
|
#[cfg(target_os = "linux")]
|
|
mod linux {
|
|
use gtk::prelude::*;
|
|
use std::collections::HashMap;
|
|
use std::sync::{Mutex, OnceLock};
|
|
use tauri::{Runtime, Webview};
|
|
|
|
type Rect = (f64, f64, f64, f64);
|
|
/// A child's placement in whole px (x, y, width, height), kept on the GTK widget.
|
|
type GtkRect = (i32, i32, i32, i32);
|
|
const RECT_KEY: &str = "waybetter-rect";
|
|
|
|
fn rects() -> std::sync::MutexGuard<'static, HashMap<String, Rect>> {
|
|
static RECTS: OnceLock<Mutex<HashMap<String, Rect>>> = OnceLock::new();
|
|
RECTS.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
}
|
|
|
|
pub fn placed(label: &str) -> Option<Rect> {
|
|
rects().get(label).copied()
|
|
}
|
|
|
|
pub fn attach_shell<R: Runtime>(shell: &Webview<R>) {
|
|
let _ = shell.with_webview(|platform| {
|
|
let widget = platform.inner().upcast::<gtk::Widget>();
|
|
let Some(vbox) = widget.parent().and_then(|parent| parent.downcast::<gtk::Box>().ok()) else { return };
|
|
let overlay = gtk::Overlay::new();
|
|
// Exactly the placed rectangle: the default position uses the child's preferred size,
|
|
// which WebKit (not the placement) decides.
|
|
overlay.connect_get_child_position(|_, child| {
|
|
// SAFETY: "waybetter-rect" is only ever set by `place`, always as `GtkRect`.
|
|
let (x, y, w, h) = unsafe { *child.data::<GtkRect>(RECT_KEY)?.as_ptr() };
|
|
Some(gtk::gdk::Rectangle::new(x, y, w, h))
|
|
});
|
|
// `widget` holds a reference, so removing it from the box does not destroy it.
|
|
vbox.remove(&widget);
|
|
overlay.add(&widget);
|
|
vbox.pack_start(&overlay, true, true, 0);
|
|
overlay.show();
|
|
});
|
|
}
|
|
|
|
pub fn place<R: Runtime>(webview: &Webview<R>, x: f64, y: f64, width: f64, height: f64) {
|
|
rects().insert(webview.label().to_owned(), (x, y, width, height));
|
|
// Whole px, with the right/bottom edges rounded the same way as the left/top ones.
|
|
let (left, top) = (x.round(), y.round());
|
|
let (w, h) = (((x + width).round() - left).max(1.0), ((y + height).round() - top).max(1.0));
|
|
let _ = webview.with_webview(move |platform| {
|
|
let widget = platform.inner().upcast::<gtk::Widget>();
|
|
// SAFETY: read back only as `GtkRect` (the overlay's get-child-position handler).
|
|
unsafe { widget.set_data::<GtkRect>(RECT_KEY, (left as i32, top as i32, w as i32, h as i32)) };
|
|
let Some(parent) = widget.parent() else { return };
|
|
if parent.downcast_ref::<gtk::Overlay>().is_none() {
|
|
// First placement: out of the window box (where tauri packed it), into the overlay.
|
|
let Ok(vbox) = parent.downcast::<gtk::Box>() else { return };
|
|
let Some(overlay) = vbox.children().into_iter().find_map(|child| child.downcast::<gtk::Overlay>().ok()) else {
|
|
return;
|
|
};
|
|
vbox.remove(&widget);
|
|
overlay.add_overlay(&widget);
|
|
}
|
|
widget.queue_resize();
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Shows or hides a tab webview and sets its WebView2 memory target to match
|
|
/// ([`tabs::memory_target`]): hidden tabs run at `COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW`
|
|
/// (ICoreWebView2_19, WebView2 Runtime 114+; older runtimes just skip it). Other platforms only
|
|
/// show/hide.
|
|
pub fn set_tab_visible<R: Runtime>(webview: &Webview<R>, visible: bool, parked: bool) {
|
|
let _ = if visible { webview.show() } else { webview.hide() };
|
|
#[cfg(windows)]
|
|
{
|
|
use std::collections::HashMap;
|
|
use std::sync::{Mutex, OnceLock};
|
|
// Last target per webview label: a sync that changes nothing costs no COM call.
|
|
static LAST: OnceLock<Mutex<HashMap<String, tabs::MemoryTarget>>> = OnceLock::new();
|
|
let target = tabs::memory_target(visible, parked);
|
|
let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
|
if last.insert(webview.label().to_owned(), target) == Some(target) {
|
|
return;
|
|
}
|
|
drop(last);
|
|
let _ = webview.with_webview(move |platform| {
|
|
use webview2_com::Microsoft::Web::WebView2::Win32::{
|
|
ICoreWebView2_19, COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW, COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_NORMAL,
|
|
};
|
|
use windows::core::Interface;
|
|
let level = match target {
|
|
tabs::MemoryTarget::Low => COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_LOW,
|
|
tabs::MemoryTarget::Normal => COREWEBVIEW2_MEMORY_USAGE_TARGET_LEVEL_NORMAL,
|
|
};
|
|
// SAFETY: COM calls on the live controller of this webview, on the main thread
|
|
// (with_webview runs the closure there).
|
|
unsafe {
|
|
if let Ok(core) = platform.controller().CoreWebView2() {
|
|
if let Ok(core) = core.cast::<ICoreWebView2_19>() {
|
|
let _ = core.SetMemoryUsageTargetLevel(level);
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|