From 32a7f2c8077779ffceef117fb435a75389f175ab Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 9 Feb 2026 13:18:50 -0600 Subject: [PATCH] fix(window): set system decorations before window show Move decoration setting to Rust side so the WM sees correct state when the window is first mapped. Window starts hidden (visible: false in tauri.conf.json), Rust reads the persisted setting from SQLite, applies decorations, then shows the window. Frontend now persists the setting via Tauri invoke (in addition to localStorage) so Rust can read it at startup. Inline script in app.html prevents flash of custom title bar before Svelte mounts. --- src-tauri/src/config/mod.rs | 8 ++ src-tauri/src/config/window_settings.rs | 142 ++++++++++++++++++++++++ src-tauri/src/lib.rs | 34 ++++++ src-tauri/tauri.conf.json | 1 + src/app.html | 14 +++ src/lib/stores/titleBarStore.ts | 18 +-- 6 files changed, 210 insertions(+), 7 deletions(-) create mode 100644 src-tauri/src/config/window_settings.rs diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 8d50d39dc..4f516425d 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -18,6 +18,7 @@ pub mod favorites_preferences; pub mod favorites_cache; pub mod subscription_state; pub mod tray_settings; +pub mod window_settings; pub mod legal_settings; pub mod remote_control_settings; @@ -119,3 +120,10 @@ pub use graphics_settings::{ get_graphics_settings, set_hardware_acceleration, }; + +pub use window_settings::{ + WindowSettings, + WindowSettingsState, + get_window_settings, + set_use_system_titlebar, +}; diff --git a/src-tauri/src/config/window_settings.rs b/src-tauri/src/config/window_settings.rs new file mode 100644 index 000000000..49b5ea169 --- /dev/null +++ b/src-tauri/src/config/window_settings.rs @@ -0,0 +1,142 @@ +//! Window decoration settings +//! +//! Stores user preferences for window title bar behavior: +//! - use_system_titlebar: Use OS native window decorations instead of custom CSD title bar + +use rusqlite::{Connection, params}; +use serde::{Deserialize, Serialize}; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use log::info; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WindowSettings { + /// Use OS native window decorations instead of custom title bar + pub use_system_titlebar: bool, +} + +impl Default for WindowSettings { + fn default() -> Self { + Self { + use_system_titlebar: false, + } + } +} + +pub struct WindowSettingsStore { + conn: Connection, +} + +impl WindowSettingsStore { + fn open_at(dir: &Path, db_name: &str) -> Result { + std::fs::create_dir_all(dir) + .map_err(|e| format!("Failed to create data directory: {}", e))?; + + let db_path = dir.join(db_name); + let conn = Connection::open(&db_path) + .map_err(|e| format!("Failed to open window settings database: {}", e))?; + + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS window_settings ( + id INTEGER PRIMARY KEY CHECK (id = 1), + use_system_titlebar INTEGER NOT NULL DEFAULT 0 + );" + ).map_err(|e| format!("Failed to create window settings table: {}", e))?; + + conn.execute( + "INSERT OR IGNORE INTO window_settings (id, use_system_titlebar) + VALUES (1, 0)", + [] + ).map_err(|e| format!("Failed to insert default window settings: {}", e))?; + + info!("[WindowSettings] Database initialized"); + + Ok(Self { conn }) + } + + pub fn new() -> Result { + let data_dir = dirs::data_dir() + .ok_or("Could not determine data directory")? + .join("qbz"); + Self::open_at(&data_dir, "window_settings.db") + } + + pub fn new_at(base_dir: &Path) -> Result { + Self::open_at(base_dir, "window_settings.db") + } + + pub fn get_settings(&self) -> Result { + self.conn + .query_row( + "SELECT use_system_titlebar FROM window_settings WHERE id = 1", + [], + |row| { + let use_system_titlebar: i32 = row.get(0)?; + Ok(WindowSettings { + use_system_titlebar: use_system_titlebar != 0, + }) + }, + ) + .map_err(|e| format!("Failed to get window settings: {}", e)) + } + + pub fn set_use_system_titlebar(&self, value: bool) -> Result<(), String> { + self.conn + .execute( + "UPDATE window_settings SET use_system_titlebar = ?1 WHERE id = 1", + params![if value { 1 } else { 0 }], + ) + .map_err(|e| format!("Failed to set use_system_titlebar: {}", e))?; + Ok(()) + } +} + +/// Global state wrapper for thread-safe access +pub struct WindowSettingsState { + pub store: Arc>>, +} + +impl WindowSettingsState { + pub fn new() -> Result { + let store = WindowSettingsStore::new()?; + Ok(Self { + store: Arc::new(Mutex::new(Some(store))), + }) + } + + pub fn new_empty() -> Self { + Self { + store: Arc::new(Mutex::new(None)), + } + } + + pub fn get_settings(&self) -> Result { + let guard = self.store.lock().map_err(|_| "Failed to lock window settings store".to_string())?; + let store = guard.as_ref().ok_or("Window settings store not initialized")?; + store.get_settings() + } + + pub fn set_use_system_titlebar(&self, value: bool) -> Result<(), String> { + let guard = self.store.lock().map_err(|_| "Failed to lock window settings store".to_string())?; + let store = guard.as_ref().ok_or("Window settings store not initialized")?; + store.set_use_system_titlebar(value) + } +} + +// Tauri commands + +#[tauri::command] +pub fn get_window_settings( + state: tauri::State, +) -> Result { + state.get_settings() +} + +#[tauri::command] +pub fn set_use_system_titlebar( + value: bool, + state: tauri::State, +) -> Result<(), String> { + info!("[WindowSettings] Setting use_system_titlebar to {}", value); + state.set_use_system_titlebar(value) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 534f4b868..3c0489ab3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -196,6 +196,16 @@ pub fn run() { tray_settings.close_to_tray ); + // Read window settings for decoration configuration before window creation. + let window_settings = config::window_settings::WindowSettingsStore::new() + .and_then(|store| store.get_settings()) + .unwrap_or_default(); + log::info!( + "Window settings: use_system_titlebar={}", + window_settings.use_system_titlebar + ); + let use_system_titlebar = window_settings.use_system_titlebar; + // Initialize casting state (Chromecast, DLNA) — device-level, not per-user let cast_state = cast::CastState::new() .expect("Failed to initialize Chromecast state"); @@ -247,6 +257,11 @@ pub fn run() { log::warn!("Failed to initialize graphics settings: {}. Using empty state.", e); config::graphics_settings::GraphicsSettingsState::new_empty() }); + let window_settings_state = config::window_settings::WindowSettingsState::new() + .unwrap_or_else(|e| { + log::warn!("Failed to initialize window settings: {}. Using empty state.", e); + config::window_settings::WindowSettingsState::new_empty() + }); // Clone settings for use in closures let enable_tray = tray_settings.enable_tray; @@ -262,6 +277,21 @@ pub fn run() { .manage(AppState::with_device_and_settings(saved_device, audio_settings)) .manage(user_data_paths) .setup(move |app| { + // Apply window decorations before showing the window. + // The window starts with visible:false so the WM sees correct + // decoration state when it is first mapped (shown). + if let Some(main_window) = app.get_webview_window("main") { + if use_system_titlebar { + log::info!("Enabling system window decorations (user setting)"); + if let Err(e) = main_window.set_decorations(true) { + log::error!("Failed to set window decorations: {}", e); + } + } + if let Err(e) = main_window.show() { + log::error!("Failed to show main window: {}", e); + } + } + // Initialize system tray icon (only if enabled) if enable_tray { if let Err(e) = tray::init_tray(app.handle()) { @@ -425,6 +455,7 @@ pub fn run() { .manage(blacklist_state) .manage(developer_settings_state) .manage(graphics_settings_state) + .manage(window_settings_state) .invoke_handler(tauri::generate_handler![ // Auth commands commands::init_client, @@ -935,6 +966,9 @@ pub fn run() { // Graphics settings commands config::graphics_settings::get_graphics_settings, config::graphics_settings::set_hardware_acceleration, + // Window settings commands + config::window_settings::get_window_settings, + config::window_settings::set_use_system_titlebar, // Log capture commands logging::get_backend_logs, logging::upload_logs_to_paste, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f5f6a9ac9..eade01ec6 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -20,6 +20,7 @@ "minHeight": 600, "decorations": false, "transparent": true, + "visible": false, "resizable": true, "zoomHotkeysEnabled": true } diff --git a/src/app.html b/src/app.html index bbbd3ff23..8231222c8 100644 --- a/src/app.html +++ b/src/app.html @@ -8,6 +8,20 @@ %sveltekit.head% + +
%sveltekit.body%
diff --git a/src/lib/stores/titleBarStore.ts b/src/lib/stores/titleBarStore.ts index 4d0478de9..e80a697c9 100644 --- a/src/lib/stores/titleBarStore.ts +++ b/src/lib/stores/titleBarStore.ts @@ -9,6 +9,7 @@ */ import { getCurrentWindow } from '@tauri-apps/api/window'; +import { invoke } from '@tauri-apps/api/core'; const STORAGE_KEY_HIDE = 'qbz-hide-titlebar'; const STORAGE_KEY_SYSTEM = 'qbz-use-system-titlebar'; @@ -40,12 +41,8 @@ export function initTitleBarStore(): void { if (savedSystem !== null) { useSystemTitleBar = savedSystem === 'true'; } - - if (useSystemTitleBar) { - getCurrentWindow().setDecorations(true).catch((e) => { - console.error('[TitleBarStore] Failed to enable system decorations:', e); - }); - } + // Note: decorations are set by Rust at window creation (before show), + // so no need to call setDecorations() here on init. } catch (e) { console.error('[TitleBarStore] Failed to initialize:', e); } @@ -105,7 +102,9 @@ export function setHideTitleBar(value: boolean): void { /** * Set whether to use system (OS native) title bar - * Toggles Tauri window decorations and hides the custom title bar + * Toggles Tauri window decorations and hides the custom title bar. + * Persists to both localStorage (for fast frontend init) and Rust backend + * (so decorations are set before the window is shown on next launch). */ export function setUseSystemTitleBar(value: boolean): void { useSystemTitleBar = value; @@ -114,6 +113,11 @@ export function setUseSystemTitleBar(value: boolean): void { } catch (e) { console.error('[TitleBarStore] Failed to save system titlebar setting:', e); } + // Persist to Rust backend (read at startup before window creation) + invoke('set_use_system_titlebar', { value }).catch((e) => { + console.error('[TitleBarStore] Failed to persist system titlebar to backend:', e); + }); + // Apply runtime decoration change for immediate effect getCurrentWindow().setDecorations(value).catch((e) => { console.error('[TitleBarStore] Failed to set window decorations:', e); });