A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io
Rust ai-toolsclaude-codecodexdeepseek-harnessdesktop-appgrokgrokbuildhermeskimi-codemcpopen-sourceopencodepiprovider-managementrustskillsskills-managementtauriwsl-support
fix(linux): preserve main window size across restore (#10241)
Railgun85b93b1ebbf3
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 7ac66b604..002c55e97 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -36,6 +36,8 @@ mod kimi_session;mod lightweight;#[cfg(target_os = "linux")]mod linux_fix;+#[cfg(target_os = "linux")]+mod linux_window_geometry;pub mod live;#[cfg(target_os = "macos")]mod macos_tray_window;@@ -485,6 +487,7 @@ pub fn run() {.on_webview_ready(|webview| linux_fix::configure_webview(&webview)).build(),);+ builder = builder.plugin(linux_window_geometry::init());}#[cfg(target_os = "windows")]@@ -535,6 +538,12 @@ pub fn run() {});}+ let window_state = tauri_plugin_window_state::Builder::default()+ .with_state_flags(window_state_flags())+ .with_denylist(&[tray_panel::PANEL_LABEL]);+ #[cfg(target_os = "linux")]+ let window_state = window_state.skip_initial_state("main");+let builder = builder// 注册 deep-link 插件(处理 macOS AppleEvent 和其他平台的深链接).plugin(tauri_plugin_deep_link::init())@@ -576,12 +585,7 @@ pub fn run() {.plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_store::Builder::new().build())- .plugin(- tauri_plugin_window_state::Builder::default()- .with_state_flags(window_state_flags())- .with_denylist(&[tray_panel::PANEL_LABEL])- .build(),- )+ .plugin(window_state.build()).setup(|app| {let _ = rustls::crypto::ring::default_provider().install_default();@@ -722,6 +726,7 @@ pub fn run() {{let _ = window.set_skip_taskbar(false);}+ #[cfg(not(target_os = "linux"))]window_fit::fit_to_work_area(&window);let _ = window.show();let _ = window.set_focus();@@ -1539,6 +1544,7 @@ pub fn run() {}// window-state 插件恢复的位置可能压在任务栏 / Dock 下面,首次显示前收回工作区。// 放在装饰设置之后,按最终的窗口外框计算。+ #[cfg(not(target_os = "linux"))]window_fit::fit_to_work_area(&window);// 上次退出时在轻量模式:照旧只留托盘。由深链接冷启动的要给用户看导入对话框,正常启动。if settings.lightweight_mode && !startup_deeplink {@@ -1569,8 +1575,7 @@ pub fn run() {log::info!("正常启动模式:主窗口已显示");// Linux: 解决首次启动 UI 无响应问题(Tauri #10746 + wry #637)。- // 启动时 webview 未获取焦点 + surface 尺寸协商失败,导致点击无效。- // 这里做 set_focus + 伪 resize,等价于无视觉版本的"最大化-还原"。+ // 激活焦点并重新分配 WebView 的 GTK 布局。#[cfg(target_os = "linux")]{linux_fix::nudge_main_window(window.clone(), "startup");@@ -2439,12 +2444,17 @@ fn classify_exit_request(code: Option<i32>) -> ExitRequestAction {// ============================================================fn window_state_flags() -> StateFlags {- StateFlags::POSITION | StateFlags::SIZE | StateFlags::MAXIMIZED+ let flags = StateFlags::POSITION | StateFlags::MAXIMIZED;+ #[cfg(not(target_os = "linux"))]+ let flags = flags | StateFlags::SIZE;+ flags}/// 当前应用的退出路径会拦截 `ExitRequested` 并最终直接 `std::process::exit(0)`,/// 这里需要在真正结束进程前手动落盘,避免 window-state 插件的默认退出钩子被绕过。pub fn save_window_state_before_exit(app_handle: &tauri::AppHandle) {+ #[cfg(target_os = "linux")]+ linux_window_geometry::save(app_handle);if let Err(err) = app_handle.save_window_state(window_state_flags()) {log::error!("退出前保存窗口状态失败: {err}");} else {diff --git a/src-tauri/src/lightweight.rs b/src-tauri/src/lightweight.rsindex 1e4fd2151..019a7d403 100644--- a/src-tauri/src/lightweight.rs+++ b/src-tauri/src/lightweight.rs@@ -61,7 +61,7 @@ pub fn exit_lightweight_mode(app: &tauri::AppHandle) -> Result<(), String> {.map_err(|e| format!("创建主窗口失败: {e}"))?;if let Some(window) = app.get_webview_window("main") {- // 重建时 window-state 插件同样会恢复旧位置和尺寸,reveal_main_window 会在显示前调用 fit_to_work_area+ // 重建会重新注册平台的窗口状态恢复钩子。crate::tray::reveal_main_window(&window, "lightweight-recreated");}diff --git a/src-tauri/src/linux_fix.rs b/src-tauri/src/linux_fix.rsindex fc77a42f6..48ead566b 100644--- a/src-tauri/src/linux_fix.rs+++ b/src-tauri/src/linux_fix.rs@@ -21,11 +21,7 @@//! 排队请求不会延迟抢焦点;//! 2. 装饰对账:仅在与设置不一致时 `set_decorations`;//! 3. 修补 Wayland CSD `EventBox.above_child`(最大化窗口也走这条,不改几何);-//! 4. 非最大化窗口再用 `LogicalSize` ±1 逻辑像素刷新 WebKit input region。-//! 最大化窗口严禁 `set_size`(合成器硬约束,会 drift / 抖动)。-//!-//! 并发策略是 queue-latest 而不是中途取消:一旦已经 `set_size(bumped)`,-//! 必须先 restore 再处理下一轮,避免窗口永久停在 width+1。+//! 4. 请求 GTK 重新分配 WebView 的布局,刷新输入区而不改变顶层窗口尺寸。//!//! 所有「让主窗口出现在用户面前」的路径(正常启动、deeplink、//! single_instance、托盘 show_main、lightweight 退出/重建)都应在现有@@ -36,7 +32,7 @@ use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Mutex;use std::time::Duration;-use tauri::{LogicalSize, PhysicalSize, WebviewWindow};+use tauri::WebviewWindow;/// Apply the existing Linux software-rendering workaround to every newly created/// WebView, including the tray panel and the main window recreated after lightweight@@ -69,13 +65,6 @@ static PENDING_NUDGE: LatestSlot<PendingNudge> = LatestSlot::new();/// 在 webview realize 之后的延迟,等 GTK 主循环把 realize 事件处理完。const REALIZE_WAIT: Duration = Duration::from_millis(200);-/// 伪 resize 两步之间的间隔。Tao Linux 的尺寸 API 是异步的-///(`gtk_window_resize` → 合成器 configure),太短会被 coalesce。-const RESIZE_GAP: Duration = Duration::from_millis(100);--/// 尺寸对账回读前的额外等待,确保合成器处理完 resize 消息队列。-const RECONCILE_WAIT: Duration = Duration::from_millis(500);-struct PendingNudge {window: WebviewWindow,reason: &'static str,@@ -116,24 +105,6 @@ fn try_acquire_nudge() -> bool {.is_ok()}-fn calculate_nudge_sizes(- physical: PhysicalSize<u32>,- scale_factor: f64,-) -> (LogicalSize<f64>, LogicalSize<f64>) {- let scale = if scale_factor > 0.0 {- scale_factor- } else {- 1.0- };- let logical = physical.to_logical::<f64>(scale);- let bumped = LogicalSize::new(logical.width + 1.0, logical.height);- (logical, bumped)-}--fn has_size_drift(current: LogicalSize<f64>, expected: LogicalSize<f64>) -> bool {- (current.width - expected.width).abs() >= 0.5 || (current.height - expected.height).abs() >= 0.5-}-fn decorations_need_restore(current: bool, desired: bool) -> bool {current != desired}@@ -170,8 +141,7 @@ impl Drop for NudgeGuard {/// 调用是 fire-and-forget:内部 spawn 一个异步任务并立即返回,不阻塞 UI。/// `reason` 标识触发来源(startup / tray-show-main 等),用于日志排障。///-/// 同一时刻只跑一条序列。后续请求覆盖排队,当前序列(含任何已发出的-/// bump→restore)结束后再对最新窗口跑一遍。+/// 同一时刻只跑一条序列。后续请求覆盖排队,当前序列结束后再处理最新请求。pub(crate) fn nudge_main_window(window: WebviewWindow, reason: &'static str) {let _ = window.set_focus();PENDING_NUDGE.store(PendingNudge { window, reason });@@ -246,18 +216,16 @@ async fn run_nudge_sequence(// 最大化按钮会闪一下,也不是重绑 subsurface 的 API。patch_wayland_header_event_box(&window);- let is_maximized = window.is_maximized().unwrap_or(false);-- // 失效模式 B:仅非最大化窗口做 LogicalSize 微调。- // 最大化尺寸受合成器硬约束,set_size 无效且会引发 drift 与抖动。- // 一旦 bump 已经发出,后面即使窗口被隐藏也必须 restore。- if !is_maximized {- pseudo_resize_logical(&window).await;+ if let Err(error) = window.with_webview(|webview| {+ use gtk::prelude::WidgetExt;+ webview.inner().queue_resize();+ }) {+ log::warn!("Linux: 无法刷新主 WebView 的输入区: {error}");}if is_window_alive(&window) {log::info!(- "Linux: 已对主窗口执行 focus + HeaderBar 控制按钮与 surface 重激活 (reason: {reason}, maximized={is_maximized})"+ "Linux: 已对主窗口执行 focus + HeaderBar 控制按钮与 surface 重激活 (reason: {reason})");true} else {@@ -325,66 +293,6 @@ fn apply_wayland_header_event_box_patch(window: &WebviewWindow) {}}-/// 以 LogicalSize 做 ±1 逻辑像素伪 resize,避免 HiDPI 下 PhysicalSize +1-/// 被逻辑换算截断成 no-op。-///-/// 一旦 `set_size(bumped)` 已经发出,本函数保证随后 `set_size(original)`,-/// 即使窗口在 RESIZE_GAP 期间被隐藏。这是刻意不做 generation-cancel 的原因。-async fn pseudo_resize_logical(window: &WebviewWindow) {- let (physical, scale) = match (window.inner_size(), window.scale_factor()) {- (Ok(physical), Ok(scale)) => (physical, scale),- (Err(e), _) => {- log::warn!("Linux nudge: 读取 inner_size 失败,跳过伪 resize: {e}");- return;- }- (_, Err(e)) => {- log::warn!("Linux nudge: 读取 scale_factor 失败,跳过伪 resize: {e}");- return;- }- };-- let (logical, bumped) = calculate_nudge_sizes(physical, scale);- let _ = window.set_size(bumped);- tokio::time::sleep(RESIZE_GAP).await;- let _ = window.set_size(logical);-- tokio::time::sleep(RECONCILE_WAIT).await;- if !is_window_alive(window) {- return;- }-- match (window.inner_size(), window.scale_factor()) {- (Ok(after_physical), Ok(after_scale)) => {- let after_scale = if after_scale > 0.0 { after_scale } else { 1.0 };- let after_logical = after_physical.to_logical::<f64>(after_scale);- if has_size_drift(after_logical, logical) {- log::info!(- "Linux nudge 尺寸 drift: expected={:?}, got={:?},已补偿",- logical,- after_logical- );- let _ = window.set_size(logical);-- if let (Ok(final_physical), Ok(final_scale)) =- (window.inner_size(), window.scale_factor())- {- let final_scale = if final_scale > 0.0 { final_scale } else { 1.0 };- let final_logical = final_physical.to_logical::<f64>(final_scale);- if has_size_drift(final_logical, logical) {- log::warn!(- "Linux nudge 尺寸 drift 补偿后仍不一致: expected={:?}, got={:?}",- logical,- final_logical- );- }- }- }- }- (Err(e), _) => log::warn!("Linux nudge: 对账回读 inner_size 失败: {e}"),- (_, Err(e)) => log::warn!("Linux nudge: 对账回读 scale_factor 失败: {e}"),- }-}-#[cfg(test)]mod tests {use super::*;@@ -400,37 +308,6 @@ mod tests {assert_eq!(slot.take(), None);}- #[test]- fn calculate_nudge_sizes_various_hidpi_scales() {- let (logical, bumped) = calculate_nudge_sizes(PhysicalSize::new(800, 600), 1.0);- assert_eq!(logical.width, 800.0);- assert_eq!(bumped.width, 801.0);- assert_eq!(bumped.height, 600.0);-- let (logical, bumped) = calculate_nudge_sizes(PhysicalSize::new(1000, 750), 1.25);- assert_eq!(logical.width, 800.0);- assert_eq!(bumped.width, 801.0);- assert!((bumped.width - logical.width - 1.0).abs() < 1e-6);-- let (logical, bumped) = calculate_nudge_sizes(PhysicalSize::new(1600, 1200), 2.0);- assert_eq!(logical.width, 800.0);- assert_eq!(bumped.width, 801.0);- assert_eq!(bumped.height, 600.0);-- let (logical, bumped) = calculate_nudge_sizes(PhysicalSize::new(800, 600), 0.0);- assert_eq!(logical.width, 800.0);- assert_eq!(bumped.width, 801.0);- }-- #[test]- fn has_size_drift_uses_half_logical_pixel() {- let expected = LogicalSize::new(800.0, 600.0);- assert!(!has_size_drift(LogicalSize::new(800.0, 600.0), expected));- assert!(!has_size_drift(LogicalSize::new(800.3, 600.2), expected));- assert!(has_size_drift(LogicalSize::new(801.0, 600.0), expected));- assert!(has_size_drift(LogicalSize::new(800.0, 601.0), expected));- }-#[test]fn decorations_are_only_restored_on_mismatch() {assert!(!decorations_need_restore(true, true));diff --git a/src-tauri/src/linux_window_geometry.rs b/src-tauri/src/linux_window_geometry.rsnew file mode 100644index 000000000..08339b08d--- /dev/null+++ b/src-tauri/src/linux_window_geometry.rs@@ -0,0 +1,182 @@+//! Track normal content size and maximization on GTK. Tao's Linux resize+//! events can include client-side decorations, but GTK takes content sizes.++use crate::sync_utils::MutexExt;+use gtk::gdk::WindowState;+use gtk::prelude::{GtkWindowExt, ObjectExt, WidgetExt};+use serde::{Deserialize, Serialize};+use std::cell::Cell;+use std::io::ErrorKind;+use std::path::{Path, PathBuf};+use std::rc::Rc;+use std::sync::{Arc, Mutex};+use std::time::Duration;+use tauri::{AppHandle, Manager, RunEvent, Window, Wry};+use tauri_plugin_window_state::{StateFlags, WindowExt};++#[derive(Clone, Copy, Deserialize, Serialize)]+struct ContentSize {+ width: i32,+ height: i32,+}++impl ContentSize {+ fn meets_minimum(self, minimum: (i32, i32)) -> bool {+ self.width >= minimum.0 && self.height >= minimum.1+ }+}++#[derive(Clone, Copy, Default, Deserialize, Serialize)]+struct Geometry {+ normal_size: Option<ContentSize>,+ maximized: bool,+}++struct SavedGeometry {+ path: PathBuf,+ geometry: Arc<Mutex<Geometry>>,+}++pub(crate) fn init() -> tauri::plugin::TauriPlugin<Wry> {+ tauri::plugin::Builder::new("linux-window-geometry")+ .setup(|app, _| {+ let directory = app.path().app_config_dir()?;+ let path = directory.join(".linux-window-geometry.json");+ app.manage(SavedGeometry {+ geometry: Arc::new(Mutex::new(read_geometry(&path, &directory))),+ path,+ });+ Ok(())+ })+ .on_window_ready(attach)+ .on_event(|app, event| {+ if matches!(event, RunEvent::Exit) {+ save(app);+ }+ })+ .build()+}++fn read_geometry(path: &Path, directory: &Path) -> Geometry {+ match std::fs::read(path) {+ Ok(bytes) => match serde_json::from_slice(&bytes) {+ Ok(geometry) => return geometry,+ Err(error) => log::warn!("Failed to parse Linux window geometry: {error}"),+ },+ Err(error) if error.kind() == ErrorKind::NotFound => {}+ Err(error) => log::warn!("Failed to read Linux window geometry: {error}"),+ }++ // Legacy width and height can already contain several rounds of+ // decoration growth. Use the configured normal size on the first launch.+ let maximized = std::fs::read(directory.join(".window-state.json"))+ .ok()+ .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())+ .and_then(|state| state.pointer("/main/maximized")?.as_bool())+ .unwrap_or_default();+ Geometry {+ maximized,+ ..Geometry::default()+ }+}++fn attach(window: Window<Wry>) {+ if window.label() != "main" {+ return;+ }+ let app = window.app_handle();+ let saved = app.state::<SavedGeometry>();+ let Some(config) = app.config().app.windows.iter().find(|w| w.label == "main") else {+ return;+ };+ let minimum = (+ config.min_width.unwrap_or(1.0).ceil() as i32,+ config.min_height.unwrap_or(1.0).ceil() as i32,+ );++ let gtk_window = match window.gtk_window() {+ Ok(gtk_window) => gtk_window,+ Err(error) => {+ log::warn!("Failed to obtain GTK main window: {error}");+ return;+ }+ };++ if let Err(error) = window.restore_state(StateFlags::POSITION) {+ log::warn!("Failed to restore Linux window position: {error}");+ }+ let initial = *saved.geometry.lock_recover();+ if let Some(size) = initial.normal_size.filter(|s| s.meets_minimum(minimum)) {+ // Override Tao's pending config resize before the first map.+ gtk_window.resize(size.width, size.height);+ }++ let geometry = Arc::clone(&saved.geometry);+ gtk_window.connect_window_state_event(move |window, event| {+ if window.is_mapped() && event.changed_mask().contains(WindowState::MAXIMIZED) {+ geometry.lock_recover().maximized =+ event.new_window_state().contains(WindowState::MAXIMIZED);+ }+ gtk::glib::Propagation::Proceed+ });++ let fit_on_allocate = Rc::new(Cell::new(true));+ let fit_on_remap = Rc::clone(&fit_on_allocate);+ gtk_window.connect_unmap(move |_| fit_on_remap.set(true));+ let maximize_on_first_map = Rc::new(Cell::new(initial.maximized));+ let geometry = Arc::clone(&saved.geometry);+ gtk_window.connect_size_allocate(move |widget, _| {+ let Some(surface) = widget.window().filter(|_| widget.is_mapped()) else {+ return;+ };+ if fit_on_allocate.replace(false) {+ let gtk_window = widget.downgrade();+ let window = window.clone();+ let maximize_on_first_map = Rc::clone(&maximize_on_first_map);+ // Wait for GTK to finish the normal allocation before fitting or+ // maximizing so the compositor has a normal size to restore.+ gtk::glib::idle_add_local_once(move || {+ if let Some(gtk_window) = gtk_window.upgrade().filter(WidgetExt::is_mapped) {+ crate::window_fit::fit_linux_window(&window, >k_window);+ if maximize_on_first_map.get() {+ let gtk_window = gtk_window.downgrade();+ // TODO: Replace this delay when GTK/Tao exposes a signal that+ // the compositor accepted the normal window geometry.+ gtk::glib::timeout_add_local_once(Duration::from_millis(150), move || {+ if let Some(gtk_window) =+ gtk_window.upgrade().filter(WidgetExt::is_mapped)+ {+ if maximize_on_first_map.replace(false) {+ gtk_window.maximize();+ }+ }+ });+ }+ }+ });+ }+ if !surface+ .state()+ .intersects(WindowState::MAXIMIZED | WindowState::ICONIFIED | WindowState::FULLSCREEN)+ {+ let (width, height) = widget.size();+ let size = ContentSize { width, height };+ if size.meets_minimum(minimum) {+ geometry.lock_recover().normal_size = Some(size);+ }+ }+ });+}++pub(crate) fn save(app: &AppHandle) {+ let saved = app.state::<SavedGeometry>();+ let geometry = saved.geometry.lock_recover();+ match serde_json::to_vec(&*geometry) {+ Ok(bytes) => {+ if let Err(error) = crate::config::atomic_write(&saved.path, &bytes) {+ log::warn!("Failed to save Linux window geometry: {error}");+ }+ }+ Err(error) => log::warn!("Failed to encode Linux window geometry: {error}"),+ }+}diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rsindex 16a66268a..129abed8a 100644--- a/src-tauri/src/tray.rs+++ b/src-tauri/src/tray.rs@@ -3704,6 +3704,7 @@ pub(crate) fn reveal_main_window(window: &tauri::WebviewWindow, _source: &'stati#[cfg(target_os = "windows")]let _ = window.set_skip_taskbar(false);let _ = window.unminimize();+ #[cfg(not(target_os = "linux"))]crate::window_fit::fit_to_work_area(window);let _ = window.show();let _ = window.set_focus();diff --git a/src-tauri/src/window_fit.rs b/src-tauri/src/window_fit.rsindex 7479e6145..42bfd9754 100644--- a/src-tauri/src/window_fit.rs+++ b/src-tauri/src/window_fit.rs@@ -6,7 +6,9 @@//! 插件也会原样恢复异常小的非零尺寸(#9496),不能只依赖系统的最小尺寸限制。use tauri::utils::config::WindowConfig;-use tauri::{LogicalSize, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewWindow};+#[cfg(not(target_os = "linux"))]+use tauri::WebviewWindow;+use tauri::{LogicalSize, Manager, PhysicalPosition, PhysicalSize, Runtime, Window};/// 物理像素下的矩形。#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -94,7 +96,36 @@ fn fit_into(}/// 窗口状态恢复后、首次显示或从托盘唤回时调用。+#[cfg(not(target_os = "linux"))]pub fn fit_to_work_area<R: Runtime>(window: &WebviewWindow<R>) {+ fit_window_to_work_area(&window.as_ref().window(), None);+}++#[cfg(target_os = "linux")]+pub(crate) fn fit_linux_window<R: Runtime>(+ window: &Window<R>,+ gtk_window: >k::ApplicationWindow,+) {+ use gtk::prelude::{GtkWindowExt, WidgetExt};++ let Some(surface) = gtk_window.window() else {+ return;+ };+ // Tao's cached outer size is initially populated from the window origin.+ // Read both sizes from the mapped GTK surface before its first configure.+ let scale = gtk_window.scale_factor() as f64;+ let (width, height) = gtk_window.size();+ let frame = surface.frame_extents();+ let outer =+ LogicalSize::new(frame.width().max(width), frame.height().max(height)).to_physical(scale);+ let inner = LogicalSize::new(width, height).to_physical(scale);+ fit_window_to_work_area(window, Some((outer, inner)));+}++fn fit_window_to_work_area<R: Runtime>(+ window: &Window<R>,+ native_sizes: Option<(PhysicalSize<u32>, PhysicalSize<u32>)>,+) {// 不把最小化的临时尺寸当成损坏;最大化 / 全屏窗口由系统负责。if window.is_minimized().unwrap_or(false)|| window.is_maximized().unwrap_or(false)@@ -102,8 +133,13 @@ pub fn fit_to_work_area<R: Runtime>(window: &WebviewWindow<R>) {{return;}- let (Ok(size), Ok(inner)) = (window.outer_size(), window.inner_size()) else {- return;+ let (size, inner) = if let Some(sizes) = native_sizes {+ sizes+ } else {+ let (Ok(outer), Ok(inner)) = (window.outer_size(), window.inner_size()) else {+ return;+ };+ (outer, inner)};let Some(monitor) = window.current_monitor()