From 326b1d2afba0c5faee7e7aca2d3878a4c2da5a84 Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 11:07:48 -0800 Subject: [PATCH 1/8] fix(window): restore geometry at its save-time scale tauri-plugin-window-state saves physical pixels with no scale, and the reachable path sent them as physical, so macOS converted them at the startup screen's scale: a window saved on a 2x laptop reopened at double size when Buzz started on a 1x external, and the reverse halved it. Buzz now records the main window's scale in .window-scale.json next to the plugin's file at every plugin save (Exit, CloseRequested, and the onboarding preserve path, whose snapshot gets its own copy). On macOS and Linux, a recorded scale measures the monitors in the saved pixels and sends the result in logical units. State saved without a scale restores exactly as before. Windows is unchanged. Fixes #3083 Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/lib.rs | 6 + src-tauri/src/window_state.rs | 326 +++++++++++++++++++++++++++++----- 2 files changed, 292 insertions(+), 40 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e07eda6d63..65807aeb20 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1386,6 +1386,8 @@ pub fn run() { .on_window_event(|window, event| { if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed | tauri::WindowEvent::CloseRequested { .. }) { window.state::().cancel_all(); } if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) { window.state::().cancel_all(&window.state::()); } + // The plugin caches this window's geometry here, for its next file save. + if matches!(event, tauri::WindowEvent::CloseRequested { .. }) { window_state::save_scale(window); } #[cfg(target_os = "macos")] if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { @@ -1409,6 +1411,10 @@ pub fn run() { deep_links::focus_main(app); } if matches!(event, tauri::RunEvent::Exit) { + // The window-state plugin has just saved; record the scale it measured at. + if let Some(window) = app.get_webview_window("main") { + window_state::save_scale(&window.as_ref().window()); + } shut_down(app); #[cfg(target_os = "macos")] relaunch::on_exit(app); diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index 05597e5e67..adbd7eecd4 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -1,4 +1,4 @@ -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use std::collections::HashMap; use tauri::{LogicalSize, Manager, PhysicalPosition, PhysicalRect, PhysicalSize, Runtime, Window}; use tauri_plugin_window_state::{AppHandleExt, Builder, StateFlags, WindowExt}; @@ -20,6 +20,10 @@ pub(crate) fn builder() -> Builder { // Called from app setup, after the configured main window has been created. const INTRO_GEOMETRY: &str = "onboarding-window-restore.json"; +// The plugin saves physical pixels without the scale they were measured at. +// Buzz records it beside each save, as {"main": {"scale": 2.0}}. +const SCALE: &str = ".window-scale.json"; +const INTRO_SCALE: &str = "onboarding-window-scale.json"; /// Preserve normal geometry for the next launch, without resizing this session. #[tauri::command] @@ -48,8 +52,50 @@ pub(crate) fn onboarding_preserve_window( StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED | StateFlags::FULLSCREEN, ) .map_err(|e| e.to_string())?; + let window = window.as_ref().window(); + save_scale(&window); let bytes = std::fs::read(dir.join(app.filename())).map_err(|e| e.to_string())?; - preserve_intro_geometry(&target, &bytes) + preserve_intro_geometry(&target, &bytes)?; + if let Err(error) = write_scale(&window, INTRO_SCALE) { + eprintln!("Could not save Buzz window scale: {error}"); + } + Ok(()) +} + +/// Record the main window's scale beside the plugin's save of its geometry. +/// Call wherever the plugin saves, while the window still exists. +pub(crate) fn save_scale(window: &Window) { + if window.label() == "main" { + if let Err(error) = write_scale(window, SCALE) { + eprintln!("Could not save Buzz window scale: {error}"); + } + } +} + +fn write_scale(window: &Window, name: &str) -> tauri::Result<()> { + let dir = window.app_handle().path().app_config_dir()?; + let scale = HashMap::from([( + window.label(), + SavedScale { + scale: window.scale_factor()?, + }, + )]); + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join(name), serde_json::to_vec(&scale)?)?; + Ok(()) +} + +#[derive(Serialize, Deserialize)] +struct SavedScale { + scale: f64, +} + +fn saved_scale(bytes: &[u8], label: &str) -> Option { + serde_json::from_slice::>(bytes) + .ok()? + .remove(label) + .map(|saved| saved.scale) + .filter(|scale| scale.is_finite() && *scale > 0.0) } /// The Mac window shows `--bg-app` (tokens.css) under the page instead of the @@ -94,21 +140,19 @@ fn preserve_intro_geometry(target: &std::path::Path, bytes: &[u8]) -> Result<(), } pub(crate) fn restore(window: &Window) -> tauri::Result<()> { - let pending = window - .app_handle() - .path() - .app_config_dir()? - .join(INTRO_GEOMETRY); + let dir = window.app_handle().path().app_config_dir()?; + let pending = dir.join(INTRO_GEOMETRY); if let Ok(bytes) = std::fs::read(&pending) { if let Some(saved) = saved_geometry(&bytes, window.label()) { window.set_fullscreen(false)?; window.unmaximize()?; - restore_geometry_from(window, Some(bytes))?; + restore_geometry_from(window, Some(bytes), dir.join(INTRO_SCALE))?; window.set_fullscreen(saved.fullscreen)?; if saved.maximized { window.maximize()?; } std::fs::remove_file(pending)?; + let _ = std::fs::remove_file(dir.join(INTRO_SCALE)); return Ok(()); } } @@ -147,12 +191,14 @@ fn saved_geometry(bytes: &[u8], label: &str) -> Option { } fn restore_geometry(window: &Window) -> tauri::Result<()> { - restore_geometry_from(window, None) + let dir = window.app_handle().path().app_config_dir()?; + restore_geometry_from(window, None, dir.join(SCALE)) } fn restore_geometry_from( window: &Window, override_bytes: Option>, + scale_path: std::path::PathBuf, ) -> tauri::Result<()> { let path = window .app_handle() @@ -165,10 +211,15 @@ fn restore_geometry_from( else { return Ok(()); }; + // Windows rescales on DPI change, so it keeps sending physical pixels. + let recorded = std::fs::read(scale_path) + .ok() + .and_then(|bytes| saved_scale(&bytes, window.label())) + .filter(|_| cfg!(not(windows))); let monitors = window.available_monitors()?; let areas: Vec<_> = monitors .iter() - .map(|monitor| *monitor.work_area()) + .map(|monitor| (*monitor.work_area(), monitor.scale_factor())) .collect(); let fallback = window .primary_monitor()? @@ -183,17 +234,16 @@ fn restore_geometry_from( inner.x.saturating_sub(outer.x), inner.y.saturating_sub(outer.y), ); - // AppShell owns a 48 logical-pixel header on all desktop platforms. - let header_height = (48.0 * window.scale_factor()?).ceil() as u32; let windows = &window.config().app.windows; let config = windows.first().cloned().unwrap_or_default(); - let (position, size, relocated) = - restore_request(&saved, offset, header_height, &areas, fallback, &config); + let startup = window.scale_factor()?; + let (position, size, logical) = + restore_request(&saved, recorded, offset, startup, &areas, fallback, &config); // Validate the requested geometry BEFORE sending it. Native setters // may apply asynchronously (Linux/macOS); getters can still report the // startup frame. // Move first: Windows rescales on DPI change. macOS/GTK convert at the startup scale. - if let Some(scale) = relocated.filter(|_| cfg!(not(windows))) { + if let Some(scale) = logical.filter(|_| cfg!(not(windows))) { window.set_position(position.to_logical::(scale))?; return window.set_size(size.to_logical::(scale)); } @@ -203,14 +253,33 @@ fn restore_geometry_from( Ok(()) } +/// Plans the restore in the saved rect's pixels. With the recorded save-time +/// scale, monitors are measured in those pixels too, and the result is sent as +/// logical units at that scale. Without it, the plan is in mixed units, as before. fn restore_request( saved: &SavedGeometry, + recorded: Option, client_offset: PhysicalPosition, - header_height: u32, - areas: &[PhysicalRect], + startup: f64, + monitors: &[(PhysicalRect, f64)], (fallback, scale): (PhysicalRect, f64), config: &tauri::utils::config::WindowConfig, ) -> (PhysicalPosition, PhysicalSize, Option) { + let rebase = |(area, from): (PhysicalRect, f64)| match recorded { + Some(to) => PhysicalRect { + position: area.position.to_logical::(from).to_physical(to), + size: area.size.to_logical::(from).to_physical(to), + }, + None => area, + }; + let areas: Vec<_> = monitors.iter().copied().map(rebase).collect(); + let fallback = rebase((fallback, scale)); + let client_offset = match recorded { + Some(to) => client_offset.to_logical::(startup).to_physical(to), + None => client_offset, + }; + // AppShell owns a 48 logical-pixel header on all desktop platforms. + let header_height = (48.0 * recorded.unwrap_or(startup)).ceil() as u32; let position = if saved.maximized { PhysicalPosition::new(saved.prev_x, saved.prev_y) } else { @@ -223,17 +292,19 @@ fn restore_request( ), size: PhysicalSize::new(saved.width, saved.height), }; - // A size below the minimum at the fallback's scale (rounded as tao rounds it) was - // saved at a lower scale and would reopen below it. Windows applies the minimum to - // the frame: take off tao's shadow insets (default metrics, Windows 11 top). + // Without a recorded scale, a size below the minimum at the fallback's scale (rounded + // as tao rounds it) was saved at a lower scale and would reopen below it. Windows + // applies the minimum to the frame: take off tao's shadow insets (default metrics, + // Windows 11 top). let win = u32::from(cfg!(windows)); let side = win * (4 * (scale * 96.0).round() as u32 + 48) / 96 * 2; let top = win * scale.round() as u32; let px = |logical: Option| (logical.unwrap_or(0.0) * scale).round() as u32; - let below = saved.width < px(config.min_width).saturating_sub(2 * side) - || saved.height < px(config.min_height).saturating_sub(side + top); + let below = recorded.is_none() + && (saved.width < px(config.min_width).saturating_sub(2 * side) + || saved.height < px(config.min_height).saturating_sub(side + top)); let default = below.then(|| LogicalSize::new(config.width, config.height).to_physical(scale)); - let relocated = reachable_client(client, header_height, areas, fallback, default); + let relocated = reachable_client(client, header_height, &areas, fallback, default); let target = relocated.unwrap_or(client); ( PhysicalPosition::new( @@ -241,7 +312,7 @@ fn restore_request( target.position.y.saturating_sub(client_offset.y), ), target.size, - relocated.map(|_| scale), + recorded.or(relocated.map(|_| scale)), ) } @@ -335,13 +406,13 @@ mod tests { let laptop = rect(0, 50, 3024, 1840); let saved = decode(&saved_state(1600, 100, 602, 470)); let offset = tauri::PhysicalPosition::new(0, 0); - let request = |areas: &[tauri::PhysicalRect]| { - super::restore_request(&saved, offset, 96, areas, (laptop, 2.0), &config()) + let request = |areas: &[(tauri::PhysicalRect, f64)]| { + super::restore_request(&saved, None, offset, 2.0, areas, (laptop, 2.0), &config()) }; // The 1x external overlaps the 2x laptop's physical rect, so the scale // this rect was saved at is ambiguous. Keep it as saved. assert_eq!( - request(&[laptop, external]), + request(&[(laptop, 2.0), (external, 1.0)]), ( tauri::PhysicalPosition::new(1600, 100), tauri::PhysicalSize::new(602, 470), @@ -352,7 +423,7 @@ mod tests { // but 301x235 points is below the minimum at its known scale. Send the // default in the laptop's logical units. assert_eq!( - request(&[laptop]), + request(&[(laptop, 2.0)]), ( tauri::PhysicalPosition::new(312, 50), tauri::PhysicalSize::new(2400, 1600), @@ -361,6 +432,95 @@ mod tests { ); } + // The issue #3083 layout: a 2x laptop (1512x982 points) with a 1x external + // to its right. Their physical rects overlap from x 1512 to 3024. + fn mixed_scale_monitors() -> [(tauri::PhysicalRect, f64); 2] { + [ + (rect(0, 66, 3024, 1898), 2.0), + (rect(1512, -317, 3440, 1415), 1.0), + ] + } + + fn logical_request( + saved: &super::SavedGeometry, + recorded: Option, + startup: f64, + monitors: &[(tauri::PhysicalRect, f64)], + ) -> (tauri::LogicalPosition, tauri::LogicalSize) { + let offset = tauri::PhysicalPosition::new(0, 0); + let (position, size, scale) = super::restore_request( + saved, + recorded, + offset, + startup, + monitors, + monitors[0], + &config(), + ); + let scale = scale.expect("sent in logical units"); + (position.to_logical(scale), size.to_logical(scale)) + } + + #[test] + fn recorded_scale_restores_logical_frame_whichever_screen_starts_the_window() { + let monitors = mixed_scale_monitors(); + // Saved on the 2x laptop at 1200x750 points, relaunched on the 1x external. + let laptop = decode(&saved_state(200, 66, 2400, 1500)); + assert_eq!( + logical_request(&laptop, Some(2.0), 1.0, &monitors), + ( + tauri::LogicalPosition::new(100.0, 33.0), + tauri::LogicalSize::new(1200.0, 750.0) + ), + ); + // Saved on the 1x external, relaunched on the 2x laptop. + let external = decode(&saved_state(2212, -317, 2323, 1089)); + assert_eq!( + logical_request(&external, Some(1.0), 2.0, &monitors), + ( + tauri::LogicalPosition::new(2212.0, -317.0), + tauri::LogicalSize::new(2323.0, 1089.0) + ), + ); + // A 1x save below the minimum at 2x is kept: its points are known. + let small = decode(&saved_state(2212, 100, 602, 470)); + assert_eq!( + logical_request(&small, Some(1.0), 2.0, &monitors).1, + tauri::LogicalSize::new(602.0, 470.0), + ); + } + + #[test] + fn recorded_scale_measures_reachability_in_points_after_unplugging() { + // Saved on the 1x external, which is gone. Its pixels still fall in the + // laptop's physical rect, but its points are right of the laptop. + let saved = decode(&saved_state(2212, 100, 1000, 600)); + let laptop = &mixed_scale_monitors()[..1]; + assert_eq!( + logical_request(&saved, Some(1.0), 2.0, laptop), + ( + tauri::LogicalPosition::new(256.0, 33.0), + tauri::LogicalSize::new(1000.0, 600.0) + ), + ); + } + + #[test] + fn without_a_recorded_scale_the_request_is_unchanged() { + let monitors = mixed_scale_monitors(); + let offset = tauri::PhysicalPosition::new(0, 0); + let saved = decode(&saved_state(200, 66, 2400, 1500)); + // Reachable: sent as physical pixels, which macOS converts at the startup scale. + assert_eq!( + super::restore_request(&saved, None, offset, 1.0, &monitors, monitors[0], &config()), + ( + tauri::PhysicalPosition::new(200, 66), + tauri::PhysicalSize::new(2400, 1500), + None + ), + ); + } + #[test] fn fallback_uses_default_size_when_saved_size_is_below_minimum_at_its_scale() { let laptop = rect(0, 50, 3024, 1840); @@ -368,8 +528,15 @@ mod tests { let fallback = |width, height, area| { let saved = decode(&saved_state(5530, 100, width, height)); let offset = tauri::PhysicalPosition::new(0, 0); - let (position, size, scale) = - super::restore_request(&saved, offset, 96, &[area, left], (area, 2.0), &config()); + let (position, size, scale) = super::restore_request( + &saved, + None, + offset, + 2.0, + &[(area, 2.0), (left, 2.0)], + (area, 2.0), + &config(), + ); assert_eq!(scale, Some(2.0)); Some(tauri::PhysicalRect { position, size }) }; @@ -390,9 +557,17 @@ mod tests { let offset = tauri::PhysicalPosition::new(0, 0); let relocated = |scale, width, height| { let saved = decode(&saved_state(100, 100, width, height)); - super::restore_request(&saved, offset, 96, &[area], (area, scale), &config()) - .2 - .is_some() + super::restore_request( + &saved, + None, + offset, + 2.0, + &[(area, scale)], + (area, scale), + &config(), + ) + .2 + .is_some() }; // tao applies the 480x400 minimum to an undecorated Windows frame. The // shadow insets (size frame plus padded border on the sides and bottom, @@ -492,9 +667,10 @@ mod tests { assert_eq!( super::restore_request( &saved, + None, tauri::PhysicalPosition::new(7, 0), - 48, - &[area], + 1.0, + &[(area, 1.0)], (area, 1.0), &config() ), @@ -555,14 +731,30 @@ mod tests { ); let offset = tauri::PhysicalPosition::new(0, 0); assert_eq!( - super::restore_request(&saved, offset, 48, &[area], (area, 1.0), &config()), + super::restore_request( + &saved, + None, + offset, + 1.0, + &[(area, 1.0)], + (area, 1.0), + &config() + ), expected ); // Resize is asynchronous too: validating only startup width misses // the right-hand controls of a wider saved client. let saved = decode(&saved_state(100, 120, 1800, 800)); assert_eq!( - super::restore_request(&saved, offset, 48, &[area], (area, 1.0), &config()), + super::restore_request( + &saved, + None, + offset, + 1.0, + &[(area, 1.0)], + (area, 1.0), + &config() + ), ( area.position, tauri::PhysicalSize::new(1440, 800), @@ -577,7 +769,15 @@ mod tests { let offset = tauri::PhysicalPosition::new(7, 0); let saved = decode(&saved_state(-7, 0, 1920, 1000)); assert_eq!( - super::restore_request(&saved, offset, 48, &[area], (area, 1.0), &config()), + super::restore_request( + &saved, + None, + offset, + 1.0, + &[(area, 1.0)], + (area, 1.0), + &config() + ), ( tauri::PhysicalPosition::new(-7, 0), tauri::PhysicalSize::new(1920, 1000), @@ -589,7 +789,15 @@ mod tests { state["main"]["prev_x"] = json!(100); state["main"]["prev_y"] = json!(-450); assert_eq!( - super::restore_request(&decode(&state), offset, 48, &[area], (area, 1.0), &config()), + super::restore_request( + &decode(&state), + None, + offset, + 1.0, + &[(area, 1.0)], + (area, 1.0), + &config() + ), ( tauri::PhysicalPosition::new(473, 0), tauri::PhysicalSize::new(960, 640), @@ -600,7 +808,15 @@ mod tests { state["main"]["maximized"] = json!(false); state["main"]["fullscreen"] = json!(true); assert_eq!( - super::restore_request(&decode(&state), offset, 48, &[area], (area, 1.0), &config()), + super::restore_request( + &decode(&state), + None, + offset, + 1.0, + &[(area, 1.0)], + (area, 1.0), + &config() + ), ( tauri::PhysicalPosition::new(0, 0), tauri::PhysicalSize::new(960, 640), @@ -667,6 +883,36 @@ mod tests { assert!(!path.exists()); } + #[test] + fn onboarding_records_scale_beside_both_saves_and_restore_clears_its_copy() { + let (dir, app) = fixture(); + let state = dir.path().join(tauri_plugin_window_state::DEFAULT_FILENAME); + std::fs::write( + &state, + serde_json::to_vec(&saved_state(100, 120, 960, 640)).unwrap(), + ) + .unwrap(); + let mut plugin = super::builder().build(); + plugin.initialize(app.handle(), Value::Null).unwrap(); + let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap(); + let window = webview.as_ref().window(); + plugin.window_created(window.clone()); + super::onboarding_preserve_window(webview).unwrap(); + let scale = window.scale_factor().unwrap(); + for name in [super::SCALE, super::INTRO_SCALE] { + let bytes = std::fs::read(dir.path().join(name)).unwrap(); + assert_eq!(super::saved_scale(&bytes, "main"), Some(scale)); + assert_eq!(super::saved_scale(&bytes, "other"), None); + } + assert_eq!(super::saved_scale(br#"{"main":{"scale":0}}"#, "main"), None); + super::restore(&window).unwrap(); + assert!(!dir.path().join(super::INTRO_GEOMETRY).exists()); + assert!(!dir.path().join(super::INTRO_SCALE).exists()); + assert!(dir.path().join(super::SCALE).exists()); + } + #[test] fn exit_saves_only_the_main_window() { let (dir, app) = fixture(); From 3da2a17a5530e985e5733eebf5ffc1c7a43988bb Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 12:34:07 -0800 Subject: [PATCH 2/8] fix(window): keep the recorded scale while the plugin keeps its frame While the window is maximized or minimized, tauri-plugin-window-state keeps the normal frame it cached earlier instead of saving the current one. Writing the current scale then paired that frame with another screen's scale, for example a window maximized on a 2x laptop, dragged to a 1x external and quit. Skip the scale write under the plugin's own condition, and give the onboarding snapshot a copy of the scale file paired with the plugin file it copies. Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/window_state.rs | 59 +++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 13 deletions(-) diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index adbd7eecd4..75c59d3383 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -56,8 +56,11 @@ pub(crate) fn onboarding_preserve_window( save_scale(&window); let bytes = std::fs::read(dir.join(app.filename())).map_err(|e| e.to_string())?; preserve_intro_geometry(&target, &bytes)?; - if let Err(error) = write_scale(&window, INTRO_SCALE) { - eprintln!("Could not save Buzz window scale: {error}"); + // The snapshot copies the plugin's file, so it takes the scale paired with it. + if let Err(error) = std::fs::copy(dir.join(SCALE), dir.join(INTRO_SCALE)) { + if error.kind() != std::io::ErrorKind::NotFound { + eprintln!("Could not save Buzz window scale: {error}"); + } } Ok(()) } @@ -66,25 +69,37 @@ pub(crate) fn onboarding_preserve_window( /// Call wherever the plugin saves, while the window still exists. pub(crate) fn save_scale(window: &Window) { if window.label() == "main" { - if let Err(error) = write_scale(window, SCALE) { + if let Err(error) = write_scale(window) { eprintln!("Could not save Buzz window scale: {error}"); } } } -fn write_scale(window: &Window, name: &str) -> tauri::Result<()> { - let dir = window.app_handle().path().app_config_dir()?; - let scale = HashMap::from([( - window.label(), - SavedScale { - scale: window.scale_factor()?, - }, - )]); - std::fs::create_dir_all(&dir)?; - std::fs::write(dir.join(name), serde_json::to_vec(&scale)?)?; +fn write_scale(window: &Window) -> tauri::Result<()> { + let path = window.app_handle().path().app_config_dir()?.join(SCALE); + // The plugin's save condition: while maximized or minimized, it keeps the + // normal frame it cached earlier, so the scale recorded with it stays too. + let frame_kept = window.is_maximized()? || window.is_minimized()?; + record_scale(&path, window.label(), window.scale_factor()?, frame_kept)?; Ok(()) } +fn record_scale( + path: &std::path::Path, + label: &str, + scale: f64, + frame_kept: bool, +) -> std::io::Result<()> { + if frame_kept { + return Ok(()); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let scale = HashMap::from([(label, SavedScale { scale })]); + std::fs::write(path, serde_json::to_vec(&scale)?) +} + #[derive(Serialize, Deserialize)] struct SavedScale { scale: f64, @@ -913,6 +928,24 @@ mod tests { assert!(dir.path().join(super::SCALE).exists()); } + #[test] + fn scale_is_kept_while_the_plugin_keeps_its_cached_normal_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(super::SCALE); + let scale = || super::saved_scale(&std::fs::read(&path).unwrap(), "main"); + super::record_scale(&path, "main", 2.0, false).unwrap(); + // Maximized or minimized on a 1x screen: the plugin keeps the frame + // captured at 2x, so the 2x scale stays paired with it. + super::record_scale(&path, "main", 1.0, true).unwrap(); + assert_eq!(scale(), Some(2.0)); + super::record_scale(&path, "main", 1.0, false).unwrap(); + assert_eq!(scale(), Some(1.0)); + // With no earlier scale, none is written, and restore works as before. + let fresh = dir.path().join("fresh.json"); + super::record_scale(&fresh, "main", 1.0, true).unwrap(); + assert!(!fresh.exists()); + } + #[test] fn exit_saves_only_the_main_window() { let (dir, app) = fixture(); From 177a4ebaa56da81e4921d62b142fc1dd7e1f4914 Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 12:39:21 -0800 Subject: [PATCH 3/8] fix(window): write the scale file only where the plugin writes its file On CloseRequested the window-state plugin only updates its in-memory frame; its file is written at Exit or by our onboarding save. Writing the scale at close let a close followed by a crash or Force Quit pair the old geometry on disk with the new scale. Close now keeps the scale in memory, under the same maximized/minimized rule. Exit writes the window's current scale, or the kept one when the window is gone or its frame is kept, and nothing when neither exists. Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/lib.rs | 6 +- src-tauri/src/window_state.rs | 129 +++++++++++++++++++++++----------- 2 files changed, 91 insertions(+), 44 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 65807aeb20..a4b5e01429 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1387,7 +1387,7 @@ pub fn run() { if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed | tauri::WindowEvent::CloseRequested { .. }) { window.state::().cancel_all(); } if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) { window.state::().cancel_all(&window.state::()); } // The plugin caches this window's geometry here, for its next file save. - if matches!(event, tauri::WindowEvent::CloseRequested { .. }) { window_state::save_scale(window); } + if matches!(event, tauri::WindowEvent::CloseRequested { .. }) { window_state::keep_scale(window); } #[cfg(target_os = "macos")] if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { @@ -1412,9 +1412,7 @@ pub fn run() { } if matches!(event, tauri::RunEvent::Exit) { // The window-state plugin has just saved; record the scale it measured at. - if let Some(window) = app.get_webview_window("main") { - window_state::save_scale(&window.as_ref().window()); - } + window_state::save_scale(app); shut_down(app); #[cfg(target_os = "macos")] relaunch::on_exit(app); diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index 75c59d3383..d1deb047a1 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -52,8 +52,7 @@ pub(crate) fn onboarding_preserve_window( StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED | StateFlags::FULLSCREEN, ) .map_err(|e| e.to_string())?; - let window = window.as_ref().window(); - save_scale(&window); + save_scale(app); let bytes = std::fs::read(dir.join(app.filename())).map_err(|e| e.to_string())?; preserve_intro_geometry(&target, &bytes)?; // The snapshot copies the plugin's file, so it takes the scale paired with it. @@ -65,39 +64,58 @@ pub(crate) fn onboarding_preserve_window( Ok(()) } -/// Record the main window's scale beside the plugin's save of its geometry. -/// Call wherever the plugin saves, while the window still exists. -pub(crate) fn save_scale(window: &Window) { +/// The scale paired with the plugin's in-memory frame since the last close, +/// for an Exit after the window is gone. Only file saves write it to disk. +#[derive(Default)] +struct KeptScale(std::sync::Mutex>); + +/// On close the plugin updates only its in-memory frame, so keep the scale in memory too. +pub(crate) fn keep_scale(window: &Window) { if window.label() == "main" { - if let Err(error) = write_scale(window) { - eprintln!("Could not save Buzz window scale: {error}"); - } + let app = window.app_handle(); + app.manage(KeptScale::default()); + let kept = app.state::(); + let mut kept = kept.0.lock().unwrap(); + *kept = scale_to_save(current_scale(window), *kept); } } -fn write_scale(window: &Window) -> tauri::Result<()> { - let path = window.app_handle().path().app_config_dir()?.join(SCALE); - // The plugin's save condition: while maximized or minimized, it keeps the - // normal frame it cached earlier, so the scale recorded with it stays too. - let frame_kept = window.is_maximized()? || window.is_minimized()?; - record_scale(&path, window.label(), window.scale_factor()?, frame_kept)?; - Ok(()) +/// Record the scale beside a save of the plugin's file (Exit or onboarding). +pub(crate) fn save_scale(app: &tauri::AppHandle) { + let current = app + .get_webview_window("main") + .and_then(|window| current_scale(&window.as_ref().window())); + let kept = app + .try_state::() + .and_then(|kept| *kept.0.lock().unwrap()); + let Some(scale) = scale_to_save(current, kept) else { + return; + }; + let result = app.path().app_config_dir().and_then(|dir| { + std::fs::create_dir_all(&dir)?; + let scale = HashMap::from([("main", SavedScale { scale })]); + std::fs::write(dir.join(SCALE), serde_json::to_vec(&scale)?)?; + Ok(()) + }); + if let Err(error) = result { + eprintln!("Could not save Buzz window scale: {error}"); + } } -fn record_scale( - path: &std::path::Path, - label: &str, - scale: f64, - frame_kept: bool, -) -> std::io::Result<()> { - if frame_kept { - return Ok(()); - } - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; +/// The window's scale, and whether the plugin keeps its cached normal frame +/// instead of reading a new one (its save condition: maximized or minimized). +fn current_scale(window: &Window) -> Option<(f64, bool)> { + let kept = window.is_maximized().ok()? || window.is_minimized().ok()?; + Some((window.scale_factor().ok()?, kept)) +} + +/// A frame the plugin reads now takes the current scale; a kept frame keeps +/// the scale it was paired with. With neither, nothing is recorded. +fn scale_to_save(current: Option<(f64, bool)>, kept: Option) -> Option { + match current { + Some((scale, false)) => Some(scale), + _ => kept, } - let scale = HashMap::from([(label, SavedScale { scale })]); - std::fs::write(path, serde_json::to_vec(&scale)?) } #[derive(Serialize, Deserialize)] @@ -930,20 +948,51 @@ mod tests { #[test] fn scale_is_kept_while_the_plugin_keeps_its_cached_normal_frame() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join(super::SCALE); - let scale = || super::saved_scale(&std::fs::read(&path).unwrap(), "main"); - super::record_scale(&path, "main", 2.0, false).unwrap(); + // A normal frame is read at save time, with the current scale. + assert_eq!( + super::scale_to_save(Some((1.0, false)), Some(2.0)), + Some(1.0) + ); // Maximized or minimized on a 1x screen: the plugin keeps the frame // captured at 2x, so the 2x scale stays paired with it. - super::record_scale(&path, "main", 1.0, true).unwrap(); - assert_eq!(scale(), Some(2.0)); - super::record_scale(&path, "main", 1.0, false).unwrap(); - assert_eq!(scale(), Some(1.0)); - // With no earlier scale, none is written, and restore works as before. - let fresh = dir.path().join("fresh.json"); - super::record_scale(&fresh, "main", 1.0, true).unwrap(); - assert!(!fresh.exists()); + assert_eq!( + super::scale_to_save(Some((1.0, true)), Some(2.0)), + Some(2.0) + ); + // With no window at Exit, the scale kept at close is used. + assert_eq!(super::scale_to_save(None, Some(2.0)), Some(2.0)); + // With neither, nothing is written, and the file on disk stays. + assert_eq!(super::scale_to_save(Some((1.0, true)), None), None); + assert_eq!(super::scale_to_save(None, None), None); + } + + #[test] + fn close_without_exit_leaves_the_scale_file_paired_with_the_plugin_file() { + let (dir, app) = fixture(); + let path = dir.path().join(super::SCALE); + let disk = br#"{"main":{"scale":2.0}}"#; + std::fs::write(&path, disk).unwrap(); + let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap() + .as_ref() + .window(); + // Close only updates the plugin's cache. A crash or Force Quit before + // Exit leaves the old geometry on disk, so the old scale stays too. + super::keep_scale(&window); + assert_eq!(std::fs::read(&path).unwrap(), disk); + let kept = app.state::(); + assert_eq!( + *kept.0.lock().unwrap(), + Some(window.scale_factor().unwrap()) + ); + // Exit writes the plugin's file, and the scale beside it. + super::save_scale(app.handle()); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!( + super::saved_scale(&bytes, "main"), + window.scale_factor().ok() + ); } #[test] From 028f6a1b5c0658b21762a7ef8ffb63b221403449 Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 12:42:31 -0800 Subject: [PATCH 4/8] fix(window): keep the scale with each update of the plugin's cached frame tauri-plugin-window-state also updates its cached size on every Resized event while the window isn't maximized or minimized. Dragging a window from a 2x screen to a 1x one, maximizing and quitting left 1x pixels in its file beside the earlier 2x scale. The kept scale now starts from the scale file, as the plugin's cache starts from its file, and follows each cache update under the plugin's own condition: Resized (with its macOS decorated/resizable quirk), CloseRequested and Exit. Exit and onboarding write the kept scale if there is one, and nothing otherwise. Co-authored-by: mbot <3754f8729004d95654c46dbab3129e4ab9ef05cc2534e2a3fbfc155983bd637b@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/lib.rs | 8 +- src-tauri/src/window_state.rs | 139 ++++++++++++++++++---------------- 2 files changed, 78 insertions(+), 69 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a4b5e01429..db9d01cad0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1386,8 +1386,12 @@ pub fn run() { .on_window_event(|window, event| { if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed | tauri::WindowEvent::CloseRequested { .. }) { window.state::().cancel_all(); } if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) { window.state::().cancel_all(&window.state::()); } - // The plugin caches this window's geometry here, for its next file save. - if matches!(event, tauri::WindowEvent::CloseRequested { .. }) { window_state::keep_scale(window); } + // The plugin updates its cached geometry here, for its next file save. + match event { + tauri::WindowEvent::Resized(_) => window_state::follow_scale(window, true), + tauri::WindowEvent::CloseRequested { .. } => window_state::follow_scale(window, false), + _ => {} + } #[cfg(target_os = "macos")] if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index d1deb047a1..d9b22b5886 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -64,31 +64,57 @@ pub(crate) fn onboarding_preserve_window( Ok(()) } -/// The scale paired with the plugin's in-memory frame since the last close, -/// for an Exit after the window is gone. Only file saves write it to disk. +/// The scale of the plugin's cached frame. It starts from the scale file, as +/// the plugin's cache starts from its file, and follows each cache update. #[derive(Default)] struct KeptScale(std::sync::Mutex>); -/// On close the plugin updates only its in-memory frame, so keep the scale in memory too. -pub(crate) fn keep_scale(window: &Window) { - if window.label() == "main" { - let app = window.app_handle(); - app.manage(KeptScale::default()); - let kept = app.state::(); - let mut kept = kept.0.lock().unwrap(); - *kept = scale_to_save(current_scale(window), *kept); +fn kept_scale(app: &tauri::AppHandle) -> tauri::State<'_, KeptScale> { + if app.try_state::().is_none() { + let file = app.path().app_config_dir().ok().and_then(|dir| { + let bytes = std::fs::read(dir.join(SCALE)).ok()?; + saved_scale(&bytes, "main") + }); + app.manage(KeptScale(std::sync::Mutex::new(file))); } + app.state::() } -/// Record the scale beside a save of the plugin's file (Exit or onboarding). +/// Call where the plugin updates its cached frame: on Resized (`resized`), +/// on CloseRequested, and at Exit. +pub(crate) fn follow_scale(window: &Window, resized: bool) { + let read = || -> tauri::Result { + // tauri#5812: on Resized, the plugin treats an undecorated or fixed-size + // macOS window as never maximized. + let quirk = resized + && cfg!(target_os = "macos") + && (!window.is_decorated()? || !window.is_resizable()?); + let maximized = !quirk && window.is_maximized()?; + Ok(reads_frame(maximized, window.is_minimized()?)) + }; + if window.label() == "main" && read().unwrap_or(false) { + if let Ok(scale) = window.scale_factor() { + *kept_scale(window.app_handle()).0.lock().unwrap() = Some(scale); + } + } +} + +/// The plugin's condition for reading the window's frame into its cache. +fn reads_frame(maximized: bool, minimized: bool) -> bool { + !maximized && !minimized +} + +/// Record the scale beside a save of the plugin's file (Exit or onboarding), +/// after the plugin's save has updated its cache. pub(crate) fn save_scale(app: &tauri::AppHandle) { - let current = app - .get_webview_window("main") - .and_then(|window| current_scale(&window.as_ref().window())); - let kept = app - .try_state::() - .and_then(|kept| *kept.0.lock().unwrap()); - let Some(scale) = scale_to_save(current, kept) else { + if let Some(window) = app.get_webview_window("main") { + follow_scale(&window.as_ref().window(), false); + } + write_kept_scale(app); +} + +fn write_kept_scale(app: &tauri::AppHandle) { + let Some(scale) = *kept_scale(app).0.lock().unwrap() else { return; }; let result = app.path().app_config_dir().and_then(|dir| { @@ -102,22 +128,6 @@ pub(crate) fn save_scale(app: &tauri::AppHandle) { } } -/// The window's scale, and whether the plugin keeps its cached normal frame -/// instead of reading a new one (its save condition: maximized or minimized). -fn current_scale(window: &Window) -> Option<(f64, bool)> { - let kept = window.is_maximized().ok()? || window.is_minimized().ok()?; - Some((window.scale_factor().ok()?, kept)) -} - -/// A frame the plugin reads now takes the current scale; a kept frame keeps -/// the scale it was paired with. With neither, nothing is recorded. -fn scale_to_save(current: Option<(f64, bool)>, kept: Option) -> Option { - match current { - Some((scale, false)) => Some(scale), - _ => kept, - } -} - #[derive(Serialize, Deserialize)] struct SavedScale { scale: f64, @@ -173,6 +183,8 @@ fn preserve_intro_geometry(target: &std::path::Path, bytes: &[u8]) -> Result<(), } pub(crate) fn restore(window: &Window) -> tauri::Result<()> { + // Read the scale file before restore's own resizes update the kept scale. + kept_scale(window.app_handle()); let dir = window.app_handle().path().app_config_dir()?; let pending = dir.join(INTRO_GEOMETRY); if let Ok(bytes) = std::fs::read(&pending) { @@ -947,54 +959,47 @@ mod tests { } #[test] - fn scale_is_kept_while_the_plugin_keeps_its_cached_normal_frame() { - // A normal frame is read at save time, with the current scale. - assert_eq!( - super::scale_to_save(Some((1.0, false)), Some(2.0)), - Some(1.0) - ); - // Maximized or minimized on a 1x screen: the plugin keeps the frame - // captured at 2x, so the 2x scale stays paired with it. - assert_eq!( - super::scale_to_save(Some((1.0, true)), Some(2.0)), - Some(2.0) - ); - // With no window at Exit, the scale kept at close is used. - assert_eq!(super::scale_to_save(None, Some(2.0)), Some(2.0)); - // With neither, nothing is written, and the file on disk stays. - assert_eq!(super::scale_to_save(Some((1.0, true)), None), None); - assert_eq!(super::scale_to_save(None, None), None); - } - - #[test] - fn close_without_exit_leaves_the_scale_file_paired_with_the_plugin_file() { + fn kept_scale_follows_each_update_of_the_plugins_cached_frame() { let (dir, app) = fixture(); let path = dir.path().join(super::SCALE); let disk = br#"{"main":{"scale":2.0}}"#; std::fs::write(&path, disk).unwrap(); + let mut plugin = super::builder().build(); + plugin.initialize(app.handle(), Value::Null).unwrap(); let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) .build() .unwrap() .as_ref() .window(); + plugin.window_created(window.clone()); + let kept = || *app.state::().0.lock().unwrap(); + // The kept scale starts from the file, as the plugin's cache does. + super::restore(&window).unwrap(); + assert_eq!(kept(), Some(2.0)); // Close only updates the plugin's cache. A crash or Force Quit before - // Exit leaves the old geometry on disk, so the old scale stays too. - super::keep_scale(&window); + // Exit leaves the old geometry on disk, so the old scale stays there too. + super::follow_scale(&window, false); assert_eq!(std::fs::read(&path).unwrap(), disk); - let kept = app.state::(); - assert_eq!( - *kept.0.lock().unwrap(), - Some(window.scale_factor().unwrap()) - ); - // Exit writes the plugin's file, and the scale beside it. - super::save_scale(app.handle()); - let bytes = std::fs::read(&path).unwrap(); + // Dragged to a 1x screen (MockRuntime's scale): Resized caches 1x pixels. + super::follow_scale(&window, true); + assert_eq!(kept(), Some(1.0)); + // Maximized, then quit: Exit keeps the cached frame, and its scale. + assert!(!super::reads_frame(true, false)); + assert!(!super::reads_frame(false, true)); + super::write_kept_scale(app.handle()); assert_eq!( - super::saved_scale(&bytes, "main"), - window.scale_factor().ok() + super::saved_scale(&std::fs::read(&path).unwrap(), "main"), + Some(1.0) ); } + #[test] + fn nothing_is_written_without_a_kept_scale() { + let (dir, app) = fixture(); + super::write_kept_scale(app.handle()); + assert!(!dir.path().join(super::SCALE).exists()); + } + #[test] fn exit_saves_only_the_main_window() { let (dir, app) = fixture(); From 72617da75d669c5c396e298ece2613e064a7cdd7 Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 13:32:26 -0800 Subject: [PATCH 5/8] fix(window): track the position's scale apart from the size's The window-state plugin updates its cached position on Moved and its size on Resized, so a drag to another scale without a Resized leaves the two at different scales. Buzz now keeps a scale for the size, the position and the previous position (prev_x/prev_y), following the plugin's rules for each event, and restore converts each position from its own scale. The event mapping, the cache rules and the choice between the onboarding snapshot and the live files are now small functions with tests. Co-authored-by: Orbit Helper <0f7edbd528cce2e9ea41a9310dfea0c84e0f5f04c60551b7c3e657f8033a4a39@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/lib.rs | 6 +- src-tauri/src/window_state.rs | 429 ++++++++++++++++++++++++++-------- 2 files changed, 338 insertions(+), 97 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index db9d01cad0..28fda3af73 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1387,11 +1387,7 @@ pub fn run() { if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed | tauri::WindowEvent::CloseRequested { .. }) { window.state::().cancel_all(); } if window.label() == "main" && matches!(event, tauri::WindowEvent::Destroyed) { window.state::().cancel_all(&window.state::()); } // The plugin updates its cached geometry here, for its next file save. - match event { - tauri::WindowEvent::Resized(_) => window_state::follow_scale(window, true), - tauri::WindowEvent::CloseRequested { .. } => window_state::follow_scale(window, false), - _ => {} - } + window_state::window_event(window, event); #[cfg(target_os = "macos")] if window.label() == "main" { if let tauri::WindowEvent::CloseRequested { api, .. } = event { diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index d9b22b5886..b9622fefce 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -20,8 +20,9 @@ pub(crate) fn builder() -> Builder { // Called from app setup, after the configured main window has been created. const INTRO_GEOMETRY: &str = "onboarding-window-restore.json"; -// The plugin saves physical pixels without the scale they were measured at. -// Buzz records it beside each save, as {"main": {"scale": 2.0}}. +// The plugin saves physical pixels without the scales they were measured at. +// Buzz records them beside each save, as +// {"main": {"scale": 2.0, "position": 1.0, "prev": 2.0}} (see `SavedScale`). const SCALE: &str = ".window-scale.json"; const INTRO_SCALE: &str = "onboarding-window-scale.json"; @@ -64,10 +65,19 @@ pub(crate) fn onboarding_preserve_window( Ok(()) } -/// The scale of the plugin's cached frame. It starts from the scale file, as -/// the plugin's cache starts from its file, and follows each cache update. +/// The scales of the plugin's cached frame: its size, its position, and the +/// position before that (`prev_x`/`prev_y`, used for a maximized window). The +/// plugin updates size and position on different events, so each keeps its own. +/// They start from the scale file, as the plugin's cache starts from its file. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Kept { + size: Option, + position: Option, + prev: Option, +} + #[derive(Default)] -struct KeptScale(std::sync::Mutex>); +struct KeptScale(std::sync::Mutex); fn kept_scale(app: &tauri::AppHandle) -> tauri::State<'_, KeptScale> { if app.try_state::().is_none() { @@ -75,51 +85,112 @@ fn kept_scale(app: &tauri::AppHandle) -> tauri::State<'_, KeptSca let bytes = std::fs::read(dir.join(SCALE)).ok()?; saved_scale(&bytes, "main") }); - app.manage(KeptScale(std::sync::Mutex::new(file))); + let kept = file.map_or_else(Kept::default, |saved| Kept { + size: Some(saved.scale), + position: Some(saved.position()), + prev: Some(saved.prev()), + }); + app.manage(KeptScale(std::sync::Mutex::new(kept))); } app.state::() } -/// Call where the plugin updates its cached frame: on Resized (`resized`), -/// on CloseRequested, and at Exit. -pub(crate) fn follow_scale(window: &Window, resized: bool) { - let read = || -> tauri::Result { +/// An update of the plugin's cached frame (window-state 2.5.0). +#[derive(Clone, Copy, Debug)] +enum Update { + /// `Moved`: position, unless minimized; the old position becomes `prev`. + Moved, + /// `Resized`: size, unless minimized or maximized. + Resized, + /// `CloseRequested` and the save at Exit: size and position, unless + /// minimized or maximized. + Saved, +} + +/// What the plugin reads from the window for an update. +#[derive(Clone, Copy, Debug)] +struct Frame { + maximized: bool, + minimized: bool, + scale: f64, +} + +impl Kept { + fn apply(&mut self, update: Update, frame: Frame) { + let reads_frame = !frame.maximized && !frame.minimized; + match update { + Update::Moved if !frame.minimized => { + self.prev = self.position; + self.position = Some(frame.scale); + } + Update::Resized if reads_frame => self.size = Some(frame.scale), + Update::Saved if reads_frame => { + self.size = Some(frame.scale); + self.position = Some(frame.scale); + } + _ => {} + } + } +} + +/// Follows the plugin's cache: call it for each main-window event. +pub(crate) fn window_event(window: &Window, event: &tauri::WindowEvent) { + let update = match event { + tauri::WindowEvent::Moved(_) => Update::Moved, + tauri::WindowEvent::Resized(_) => Update::Resized, + tauri::WindowEvent::CloseRequested { .. } => Update::Saved, + _ => return, + }; + follow(window, update); +} + +fn follow(window: &Window, update: Update) { + let read = || -> tauri::Result { // tauri#5812: on Resized, the plugin treats an undecorated or fixed-size // macOS window as never maximized. - let quirk = resized + let quirk = matches!(update, Update::Resized) && cfg!(target_os = "macos") && (!window.is_decorated()? || !window.is_resizable()?); - let maximized = !quirk && window.is_maximized()?; - Ok(reads_frame(maximized, window.is_minimized()?)) + Ok(Frame { + maximized: !quirk && window.is_maximized()?, + minimized: window.is_minimized()?, + scale: window.scale_factor()?, + }) }; - if window.label() == "main" && read().unwrap_or(false) { - if let Ok(scale) = window.scale_factor() { - *kept_scale(window.app_handle()).0.lock().unwrap() = Some(scale); - } + if window.label() != "main" { + return; + } + if let Ok(frame) = read() { + kept_scale(window.app_handle()) + .0 + .lock() + .unwrap() + .apply(update, frame); } } -/// The plugin's condition for reading the window's frame into its cache. -fn reads_frame(maximized: bool, minimized: bool) -> bool { - !maximized && !minimized -} - -/// Record the scale beside a save of the plugin's file (Exit or onboarding), +/// Record the scales beside a save of the plugin's file (Exit or onboarding), /// after the plugin's save has updated its cache. pub(crate) fn save_scale(app: &tauri::AppHandle) { if let Some(window) = app.get_webview_window("main") { - follow_scale(&window.as_ref().window(), false); + follow(&window.as_ref().window(), Update::Saved); } write_kept_scale(app); } fn write_kept_scale(app: &tauri::AppHandle) { - let Some(scale) = *kept_scale(app).0.lock().unwrap() else { + let kept = *kept_scale(app).0.lock().unwrap(); + let Some(scale) = kept.size else { return; }; + let saved = SavedScale { + scale, + position: kept.position, + prev: kept.prev, + }; let result = app.path().app_config_dir().and_then(|dir| { std::fs::create_dir_all(&dir)?; - let scale = HashMap::from([("main", SavedScale { scale })]); + let scale = HashMap::from([("main", saved)]); std::fs::write(dir.join(SCALE), serde_json::to_vec(&scale)?)?; Ok(()) }); @@ -128,17 +199,33 @@ fn write_kept_scale(app: &tauri::AppHandle) { } } -#[derive(Serialize, Deserialize)] +/// `scale` is the size's. A missing `position` is at the size's scale, and a +/// missing `prev` at the position's. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] struct SavedScale { scale: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + position: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + prev: Option, +} + +impl SavedScale { + fn position(&self) -> f64 { + self.position.unwrap_or(self.scale) + } + + fn prev(&self) -> f64 { + self.prev.unwrap_or(self.position()) + } } -fn saved_scale(bytes: &[u8], label: &str) -> Option { +fn saved_scale(bytes: &[u8], label: &str) -> Option { + let valid = |scale: f64| scale.is_finite() && scale > 0.0; serde_json::from_slice::>(bytes) .ok()? .remove(label) - .map(|saved| saved.scale) - .filter(|scale| scale.is_finite() && *scale > 0.0) + .filter(|saved| valid(saved.scale) && valid(saved.position()) && valid(saved.prev())) } /// The Mac window shows `--bg-app` (tokens.css) under the page instead of the @@ -183,30 +270,51 @@ fn preserve_intro_geometry(target: &std::path::Path, bytes: &[u8]) -> Result<(), } pub(crate) fn restore(window: &Window) -> tauri::Result<()> { - // Read the scale file before restore's own resizes update the kept scale. + // Read the scale file before restore's own resizes update the kept scales. kept_scale(window.app_handle()); let dir = window.app_handle().path().app_config_dir()?; - let pending = dir.join(INTRO_GEOMETRY); - if let Ok(bytes) = std::fs::read(&pending) { - if let Some(saved) = saved_geometry(&bytes, window.label()) { - window.set_fullscreen(false)?; - window.unmaximize()?; - restore_geometry_from(window, Some(bytes), dir.join(INTRO_SCALE))?; - window.set_fullscreen(saved.fullscreen)?; - if saved.maximized { - window.maximize()?; - } - std::fs::remove_file(pending)?; - let _ = std::fs::remove_file(dir.join(INTRO_SCALE)); - return Ok(()); + let filename = window.app_handle().filename(); + if let Some((saved, scales)) = restore_input(&dir, &filename, window.label(), true) { + let (fullscreen, maximized) = (saved.fullscreen, saved.maximized); + window.set_fullscreen(false)?; + window.unmaximize()?; + restore_geometry(window, saved, scales)?; + window.set_fullscreen(fullscreen)?; + if maximized { + window.maximize()?; } + std::fs::remove_file(dir.join(INTRO_GEOMETRY))?; + let _ = std::fs::remove_file(dir.join(INTRO_SCALE)); + return Ok(()); } - if let Err(error) = restore_geometry(window) { - eprintln!("Could not restore Buzz window geometry: {error}"); + if let Some((saved, scales)) = restore_input(&dir, &filename, window.label(), false) { + if let Err(error) = restore_geometry(window, saved, scales) { + eprintln!("Could not restore Buzz window geometry: {error}"); + } } window.restore_state(StateFlags::MAXIMIZED | StateFlags::FULLSCREEN) } +/// The geometry to restore and the scales recorded with it: the onboarding +/// snapshot (`intro`) and its scale copy, or the plugin's file and Buzz's. +fn restore_input( + dir: &std::path::Path, + filename: &str, + label: &str, + intro: bool, +) -> Option<(SavedGeometry, Option)> { + let (geometry, scale) = if intro { + (INTRO_GEOMETRY, INTRO_SCALE) + } else { + (filename, SCALE) + }; + let saved = saved_geometry(&std::fs::read(dir.join(geometry)).ok()?, label)?; + let scales = std::fs::read(dir.join(scale)) + .ok() + .and_then(|bytes| saved_scale(&bytes, label)); + Some((saved, scales)) +} + // Read-only adapter for window-state 2.4.1's format: position is the outer // origin, size is the client size, and maximized windows use prev_x/prev_y. // Keep all required fields typed so corrupt state falls back just as it does @@ -235,32 +343,15 @@ fn saved_geometry(bytes: &[u8], label: &str) -> Option { .filter(|state| state.width > 0 && state.height > 0) } -fn restore_geometry(window: &Window) -> tauri::Result<()> { - let dir = window.app_handle().path().app_config_dir()?; - restore_geometry_from(window, None, dir.join(SCALE)) -} - -fn restore_geometry_from( +fn restore_geometry( window: &Window, - override_bytes: Option>, - scale_path: std::path::PathBuf, + saved: SavedGeometry, + scales: Option, ) -> tauri::Result<()> { - let path = window - .app_handle() - .path() - .app_config_dir()? - .join(window.app_handle().filename()); - let Some(saved) = override_bytes - .or_else(|| std::fs::read(path).ok()) - .and_then(|bytes| saved_geometry(&bytes, window.label())) - else { - return Ok(()); - }; // Windows rescales on DPI change, so it keeps sending physical pixels. - let recorded = std::fs::read(scale_path) - .ok() - .and_then(|bytes| saved_scale(&bytes, window.label())) - .filter(|_| cfg!(not(windows))); + let scales = scales.filter(|_| cfg!(not(windows))); + let saved = at_size_scale(saved, scales); + let recorded = scales.map(|scales| scales.scale); let monitors = window.available_monitors()?; let areas: Vec<_> = monitors .iter() @@ -298,6 +389,21 @@ fn restore_geometry_from( Ok(()) } +/// Expresses the saved positions in the size's pixels, each from its own scale. +fn at_size_scale(mut saved: SavedGeometry, scales: Option) -> SavedGeometry { + if let Some(scales) = scales { + let rescale = |x: i32, y: i32, from: f64| { + let position = PhysicalPosition::new(x, y) + .to_logical::(from) + .to_physical::(scales.scale); + (position.x, position.y) + }; + (saved.x, saved.y) = rescale(saved.x, saved.y, scales.position()); + (saved.prev_x, saved.prev_y) = rescale(saved.prev_x, saved.prev_y, scales.prev()); + } + saved +} + /// Plans the restore in the saved rect's pixels. With the recorded save-time /// scale, monitors are measured in those pixels too, and the result is sent as /// logical units at that scale. Without it, the plan is in mixed units, as before. @@ -948,7 +1054,8 @@ mod tests { let scale = window.scale_factor().unwrap(); for name in [super::SCALE, super::INTRO_SCALE] { let bytes = std::fs::read(dir.path().join(name)).unwrap(); - assert_eq!(super::saved_scale(&bytes, "main"), Some(scale)); + let saved = super::saved_scale(&bytes, "main").unwrap(); + assert_eq!((saved.scale, saved.position), (scale, Some(scale))); assert_eq!(super::saved_scale(&bytes, "other"), None); } assert_eq!(super::saved_scale(br#"{"main":{"scale":0}}"#, "main"), None); @@ -958,38 +1065,176 @@ mod tests { assert!(dir.path().join(super::SCALE).exists()); } + fn kept(size: f64, position: f64, prev: f64) -> super::Kept { + super::Kept { + size: Some(size), + position: Some(position), + prev: Some(prev), + } + } + + fn frame(maximized: bool, minimized: bool, scale: f64) -> super::Frame { + super::Frame { + maximized, + minimized, + scale, + } + } + + #[test] + fn kept_scales_follow_the_plugins_cache_rules() { + use super::Update::{Moved, Resized, Saved}; + let normal = |scale| frame(false, false, scale); + // Dragged from a 2x screen to a 1x screen without a Resized, then + // minimized and quit: the plugin keeps 2x size and 1x position. + let mut scales = kept(2.0, 2.0, 2.0); + scales.apply(Moved, normal(1.0)); + assert_eq!(scales, kept(2.0, 1.0, 2.0)); + scales.apply(Moved, frame(false, true, 2.0)); + scales.apply(Resized, frame(false, true, 2.0)); + scales.apply(Saved, frame(false, true, 2.0)); + assert_eq!(scales, kept(2.0, 1.0, 2.0)); + // Maximizing moves the window: the normal origin becomes prev. A + // maximized window keeps its cached size, through Resized and saves. + scales.apply(Moved, frame(true, false, 2.0)); + assert_eq!(scales, kept(2.0, 2.0, 1.0)); + scales.apply(Resized, frame(true, false, 1.0)); + scales.apply(Saved, frame(true, false, 1.0)); + assert_eq!(scales, kept(2.0, 2.0, 1.0)); + // A normal window's save reads both size and position, never prev. + scales.apply(Resized, normal(1.0)); + assert_eq!(scales, kept(1.0, 2.0, 1.0)); + scales.apply(Saved, normal(2.0)); + assert_eq!(scales, kept(2.0, 2.0, 1.0)); + } + + #[test] + fn position_and_size_restore_each_at_its_own_scale() { + let monitors = mixed_scale_monitors(); + let scales = |position, prev| super::SavedScale { + scale: 2.0, + position: Some(position), + prev: Some(prev), + }; + // 1200x750 points cached on the 2x laptop, then moved to (2212, -200) + // points on the 1x external without a Resized. + let saved = super::at_size_scale( + decode(&saved_state(2212, -200, 2400, 1500)), + Some(scales(1.0, 1.0)), + ); + assert_eq!( + logical_request(&saved, Some(2.0), 2.0, &monitors), + ( + tauri::LogicalPosition::new(2212.0, -200.0), + tauri::LogicalSize::new(1200.0, 750.0) + ), + ); + // Maximized: the normal origin is prev, at prev's scale. + let mut state = saved_state(0, 66, 2400, 1500); + state["main"]["maximized"] = json!(true); + state["main"]["prev_x"] = json!(2212); + state["main"]["prev_y"] = json!(-200); + let saved = super::at_size_scale(decode(&state), Some(scales(2.0, 1.0))); + assert_eq!((saved.x, saved.y), (0, 66)); + assert_eq!( + logical_request(&saved, Some(2.0), 2.0, &monitors).0, + tauri::LogicalPosition::new(2212.0, -200.0), + ); + // An older file without position scales reads them as the size's. + let only = super::saved_scale(br#"{"main":{"scale":2.0}}"#, "main").unwrap(); + assert_eq!((only.position(), only.prev()), (2.0, 2.0)); + let unchanged = super::at_size_scale(decode(&saved_state(200, 66, 2400, 1500)), Some(only)); + assert_eq!((unchanged.x, unchanged.y), (200, 66)); + assert_eq!( + super::saved_scale(br#"{"main":{"scale":2.0,"prev":0}}"#, "main"), + None + ); + } + #[test] - fn kept_scale_follows_each_update_of_the_plugins_cached_frame() { + fn restore_reads_the_snapshot_pair_while_pending_else_the_live_pair() { + let dir = tempfile::tempdir().unwrap(); + let write = + |name: &str, bytes: &[u8]| std::fs::write(dir.path().join(name), bytes).unwrap(); + let live = tauri_plugin_window_state::DEFAULT_FILENAME; + let input = |intro| super::restore_input(dir.path(), live, "main", intro); + assert!(input(true).is_none() && input(false).is_none()); + write( + live, + &serde_json::to_vec(&saved_state(100, 120, 960, 640)).unwrap(), + ); + // A plugin file without a scale file restores as on main. + assert!(input(false).unwrap().1.is_none()); + write(super::SCALE, br#"{"main":{"scale":2.0}}"#); + write( + super::INTRO_GEOMETRY, + &serde_json::to_vec(&saved_state(300, 320, 1200, 800)).unwrap(), + ); + write( + super::INTRO_SCALE, + br#"{"main":{"scale":1.0,"position":2.0}}"#, + ); + let (saved, scales) = input(true).unwrap(); + assert_eq!((saved.x, saved.width), (300, 1200)); + assert_eq!( + scales, + Some(super::SavedScale { + scale: 1.0, + position: Some(2.0), + prev: None + }) + ); + let (saved, scales) = input(false).unwrap(); + assert_eq!((saved.x, saved.width), (100, 960)); + assert_eq!(scales.map(|scales| scales.scale), Some(2.0)); + assert!(super::restore_input(dir.path(), live, "other", false).is_none()); + } + + #[test] + fn window_events_update_the_kept_scales_and_only_saves_write_them() { let (dir, app) = fixture(); let path = dir.path().join(super::SCALE); let disk = br#"{"main":{"scale":2.0}}"#; std::fs::write(&path, disk).unwrap(); let mut plugin = super::builder().build(); plugin.initialize(app.handle(), Value::Null).unwrap(); - let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) - .build() - .unwrap() - .as_ref() - .window(); - plugin.window_created(window.clone()); - let kept = || *app.state::().0.lock().unwrap(); - // The kept scale starts from the file, as the plugin's cache does. - super::restore(&window).unwrap(); - assert_eq!(kept(), Some(2.0)); - // Close only updates the plugin's cache. A crash or Force Quit before - // Exit leaves the old geometry on disk, so the old scale stays there too. - super::follow_scale(&window, false); + let mut window = |label| { + let window = tauri::WebviewWindowBuilder::new(&app, label, Default::default()) + .build() + .unwrap() + .as_ref() + .window(); + plugin.window_created(window.clone()); + window + }; + let (main, other) = (window("main"), window("other")); + let scales = || *app.state::().0.lock().unwrap(); + // The kept scales start from the file, as the plugin's cache does. + super::restore(&main).unwrap(); + assert_eq!(scales(), kept(2.0, 2.0, 2.0)); + // MockRuntime's windows are normal, at 1x. + let moved = tauri::WindowEvent::Moved(tauri::PhysicalPosition::new(2212, -200)); + let resized = tauri::WindowEvent::Resized(tauri::PhysicalSize::new(2400, 1500)); + super::window_event(&other, &moved); + super::window_event(&main, &tauri::WindowEvent::Focused(true)); + assert_eq!(scales(), kept(2.0, 2.0, 2.0)); + super::window_event(&main, &moved); + assert_eq!(scales(), kept(2.0, 1.0, 2.0)); + super::window_event(&main, &resized); + assert_eq!(scales(), kept(1.0, 1.0, 2.0)); + // Events only update the cache, like the plugin's: a crash or Force + // Quit before Exit leaves the old geometry on disk, and the old scale. assert_eq!(std::fs::read(&path).unwrap(), disk); - // Dragged to a 1x screen (MockRuntime's scale): Resized caches 1x pixels. - super::follow_scale(&window, true); - assert_eq!(kept(), Some(1.0)); - // Maximized, then quit: Exit keeps the cached frame, and its scale. - assert!(!super::reads_frame(true, false)); - assert!(!super::reads_frame(false, true)); - super::write_kept_scale(app.handle()); + // Exit: the plugin saves, then Buzz writes the scales of that save. + plugin.on_event(app.handle(), &tauri::RunEvent::Exit); + super::save_scale(app.handle()); assert_eq!( super::saved_scale(&std::fs::read(&path).unwrap(), "main"), - Some(1.0) + Some(super::SavedScale { + scale: 1.0, + position: Some(1.0), + prev: Some(2.0) + }) ); } From e1339027f90c6351e91cad0ab1e9b6dc74ab5e9c Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 14:32:46 -0800 Subject: [PATCH 6/8] fix(window): test the scale repair through the restore plan; document scales Restore now plans through one entry point, `restore_plan`, which converts the saved positions to the size's scale and builds the request. The mixed-scale tests read the files with `restore_input` and plan with `restore_plan`, so dropping the conversion from the restore path fails them. docs/shell-design.md now describes the scale file, the onboarding copy and the behaviour without a scale file. Co-authored-by: Orbit Helper <0f7edbd528cce2e9ea41a9310dfea0c84e0f5f04c60551b7c3e657f8033a4a39@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/window_state.rs | 88 ++++++++++++++++++++++++++--------- 1 file changed, 66 insertions(+), 22 deletions(-) diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index b9622fefce..c326703121 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -348,10 +348,6 @@ fn restore_geometry( saved: SavedGeometry, scales: Option, ) -> tauri::Result<()> { - // Windows rescales on DPI change, so it keeps sending physical pixels. - let scales = scales.filter(|_| cfg!(not(windows))); - let saved = at_size_scale(saved, scales); - let recorded = scales.map(|scales| scales.scale); let monitors = window.available_monitors()?; let areas: Vec<_> = monitors .iter() @@ -374,7 +370,7 @@ fn restore_geometry( let config = windows.first().cloned().unwrap_or_default(); let startup = window.scale_factor()?; let (position, size, logical) = - restore_request(&saved, recorded, offset, startup, &areas, fallback, &config); + restore_plan(saved, scales, offset, startup, &areas, fallback, &config); // Validate the requested geometry BEFORE sending it. Native setters // may apply asynchronously (Linux/macOS); getters can still report the // startup frame. @@ -389,6 +385,31 @@ fn restore_geometry( Ok(()) } +/// The restore request for saved geometry and the scales recorded with it. +fn restore_plan( + saved: SavedGeometry, + scales: Option, + client_offset: PhysicalPosition, + startup: f64, + monitors: &[(PhysicalRect, f64)], + fallback: (PhysicalRect, f64), + config: &tauri::utils::config::WindowConfig, +) -> (PhysicalPosition, PhysicalSize, Option) { + // Windows rescales on DPI change, so it keeps sending physical pixels. + let scales = scales.filter(|_| cfg!(not(windows))); + let saved = at_size_scale(saved, scales); + let recorded = scales.map(|scales| scales.scale); + restore_request( + &saved, + recorded, + client_offset, + startup, + monitors, + fallback, + config, + ) +} + /// Expresses the saved positions in the size's pixels, each from its own scale. fn at_size_scale(mut saved: SavedGeometry, scales: Option) -> SavedGeometry { if let Some(scales) = scales { @@ -1108,22 +1129,42 @@ mod tests { assert_eq!(scales, kept(2.0, 2.0, 1.0)); } + /// Reads `state` and `scale` from disk as restore does, then plans the + /// restore as restore does, in logical units. + fn planned( + state: &Value, + scale: &[u8], + startup: f64, + monitors: &[(tauri::PhysicalRect, f64)], + ) -> (tauri::LogicalPosition, tauri::LogicalSize) { + let dir = tempfile::tempdir().unwrap(); + let live = tauri_plugin_window_state::DEFAULT_FILENAME; + std::fs::write(dir.path().join(live), serde_json::to_vec(state).unwrap()).unwrap(); + std::fs::write(dir.path().join(super::SCALE), scale).unwrap(); + let (saved, scales) = super::restore_input(dir.path(), live, "main", false).unwrap(); + let offset = tauri::PhysicalPosition::new(0, 0); + let (position, size, logical) = super::restore_plan( + saved, + scales, + offset, + startup, + monitors, + monitors[0], + &config(), + ); + let logical = logical.expect("sent in logical units"); + (position.to_logical(logical), size.to_logical(logical)) + } + #[test] fn position_and_size_restore_each_at_its_own_scale() { let monitors = mixed_scale_monitors(); - let scales = |position, prev| super::SavedScale { - scale: 2.0, - position: Some(position), - prev: Some(prev), - }; // 1200x750 points cached on the 2x laptop, then moved to (2212, -200) // points on the 1x external without a Resized. - let saved = super::at_size_scale( - decode(&saved_state(2212, -200, 2400, 1500)), - Some(scales(1.0, 1.0)), - ); + let state = saved_state(2212, -200, 2400, 1500); + let split = br#"{"main":{"scale":2.0,"position":1.0,"prev":1.0}}"#; assert_eq!( - logical_request(&saved, Some(2.0), 2.0, &monitors), + planned(&state, split, 2.0, &monitors), ( tauri::LogicalPosition::new(2212.0, -200.0), tauri::LogicalSize::new(1200.0, 750.0) @@ -1134,17 +1175,20 @@ mod tests { state["main"]["maximized"] = json!(true); state["main"]["prev_x"] = json!(2212); state["main"]["prev_y"] = json!(-200); - let saved = super::at_size_scale(decode(&state), Some(scales(2.0, 1.0))); - assert_eq!((saved.x, saved.y), (0, 66)); + let prev = br#"{"main":{"scale":2.0,"position":2.0,"prev":1.0}}"#; assert_eq!( - logical_request(&saved, Some(2.0), 2.0, &monitors).0, + planned(&state, prev, 2.0, &monitors).0, tauri::LogicalPosition::new(2212.0, -200.0), ); // An older file without position scales reads them as the size's. - let only = super::saved_scale(br#"{"main":{"scale":2.0}}"#, "main").unwrap(); - assert_eq!((only.position(), only.prev()), (2.0, 2.0)); - let unchanged = super::at_size_scale(decode(&saved_state(200, 66, 2400, 1500)), Some(only)); - assert_eq!((unchanged.x, unchanged.y), (200, 66)); + let state = saved_state(200, 66, 2400, 1500); + assert_eq!( + planned(&state, br#"{"main":{"scale":2.0}}"#, 1.0, &monitors), + ( + tauri::LogicalPosition::new(100.0, 33.0), + tauri::LogicalSize::new(1200.0, 750.0) + ), + ); assert_eq!( super::saved_scale(br#"{"main":{"scale":2.0,"prev":0}}"#, "main"), None From 62e1ee7c8997b1e625b859ea52818e7ca1c3ea3e Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Fri, 20 Nov 2026 15:05:21 -0800 Subject: [PATCH 7/8] test(window): run the logical-unit restore test off Windows only Windows restores in physical pixels and ignores recorded scales, so restore_plan returns no logical scale there and the test's expect would panic on the windows-native job. Co-authored-by: Orbit Helper <0f7edbd528cce2e9ea41a9310dfea0c84e0f5f04c60551b7c3e657f8033a4a39@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/window_state.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index c326703121..3062f93280 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -1130,7 +1130,9 @@ mod tests { } /// Reads `state` and `scale` from disk as restore does, then plans the - /// restore as restore does, in logical units. + /// restore as restore does, in logical units. Windows plans in physical + /// pixels, without recorded scales. + #[cfg(not(windows))] fn planned( state: &Value, scale: &[u8], @@ -1157,6 +1159,7 @@ mod tests { } #[test] + #[cfg(not(windows))] fn position_and_size_restore_each_at_its_own_scale() { let monitors = mixed_scale_monitors(); // 1200x750 points cached on the 2x laptop, then moved to (2212, -200) From 06d1c0ab0072d52dd97601949411458357d594e6 Mon Sep 17 00:00:00 2001 From: Bradley Axen Date: Sat, 21 Nov 2026 04:06:10 -0800 Subject: [PATCH 8/8] fix(window): use a scale file only with the geometry it was saved with The scale file now records the geometry it belongs to. Restore, and the scales Buzz keeps at launch, use it only when that matches the geometry file being restored, so a geometry file written without its scales (by an older build, or an exit cut short between the two writes) restores as it did before scales, instead of taking a stale scale. Buzz also ignores Moved and Resized while the plugin's restore_state runs, as the plugin does under its restore lock. Co-authored-by: Orbit Helper <0f7edbd528cce2e9ea41a9310dfea0c84e0f5f04c60551b7c3e657f8033a4a39@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 --- src-tauri/src/window_state.rs | 204 +++++++++++++++++++++++++++------- 1 file changed, 164 insertions(+), 40 deletions(-) diff --git a/src-tauri/src/window_state.rs b/src-tauri/src/window_state.rs index 3062f93280..9698b35981 100644 --- a/src-tauri/src/window_state.rs +++ b/src-tauri/src/window_state.rs @@ -22,7 +22,10 @@ pub(crate) fn builder() -> Builder { const INTRO_GEOMETRY: &str = "onboarding-window-restore.json"; // The plugin saves physical pixels without the scales they were measured at. // Buzz records them beside each save, as -// {"main": {"scale": 2.0, "position": 1.0, "prev": 2.0}} (see `SavedScale`). +// {"main": {"scale": 2.0, "position": 1.0, "prev": 2.0, "geometry": [...]}} +// (see `SavedScale`). `geometry` names the save the scales belong to, so a +// geometry file written without them (by an older build, or before an exit +// finished) never takes a stale scale. const SCALE: &str = ".window-scale.json"; const INTRO_SCALE: &str = "onboarding-window-scale.json"; @@ -76,21 +79,30 @@ struct Kept { prev: Option, } +/// `restoring` mirrors the plugin's restore lock, held while `restore_state` +/// runs: the plugin ignores Moved and Resized meanwhile. #[derive(Default)] -struct KeptScale(std::sync::Mutex); +struct KeptScale { + kept: std::sync::Mutex, + restoring: std::sync::atomic::AtomicBool, +} fn kept_scale(app: &tauri::AppHandle) -> tauri::State<'_, KeptScale> { if app.try_state::().is_none() { - let file = app.path().app_config_dir().ok().and_then(|dir| { - let bytes = std::fs::read(dir.join(SCALE)).ok()?; - saved_scale(&bytes, "main") - }); + let file = app + .path() + .app_config_dir() + .ok() + .and_then(|dir| restore_input(&dir, &app.filename(), "main", false)?.1); let kept = file.map_or_else(Kept::default, |saved| Kept { size: Some(saved.scale), position: Some(saved.position()), prev: Some(saved.prev()), }); - app.manage(KeptScale(std::sync::Mutex::new(kept))); + app.manage(KeptScale { + kept: std::sync::Mutex::new(kept), + ..Default::default() + }); } app.state::() } @@ -160,12 +172,13 @@ fn follow(window: &Window, update: Update) { if window.label() != "main" { return; } + let kept = kept_scale(window.app_handle()); + let restoring = kept.restoring.load(std::sync::atomic::Ordering::SeqCst); + if restoring && matches!(update, Update::Moved | Update::Resized) { + return; + } if let Ok(frame) = read() { - kept_scale(window.app_handle()) - .0 - .lock() - .unwrap() - .apply(update, frame); + kept.kept.lock().unwrap().apply(update, frame); } } @@ -179,17 +192,24 @@ pub(crate) fn save_scale(app: &tauri::AppHandle) { } fn write_kept_scale(app: &tauri::AppHandle) { - let kept = *kept_scale(app).0.lock().unwrap(); + let kept = *kept_scale(app).kept.lock().unwrap(); let Some(scale) = kept.size else { return; }; - let saved = SavedScale { - scale, - position: kept.position, - prev: kept.prev, - }; let result = app.path().app_config_dir().and_then(|dir| { - std::fs::create_dir_all(&dir)?; + // Name the save these scales belong to: the plugin's file, just written. + let Some(saved) = std::fs::read(dir.join(app.filename())) + .ok() + .and_then(|bytes| saved_geometry(&bytes, "main")) + else { + return Ok(()); + }; + let saved = SavedScale { + scale, + position: kept.position, + prev: kept.prev, + geometry: Some(saved.pairing()), + }; let scale = HashMap::from([("main", saved)]); std::fs::write(dir.join(SCALE), serde_json::to_vec(&scale)?)?; Ok(()) @@ -208,6 +228,9 @@ struct SavedScale { position: Option, #[serde(default, skip_serializing_if = "Option::is_none")] prev: Option, + /// The saved geometry these scales belong to (`SavedGeometry::pairing`). + #[serde(default)] + geometry: Option<[i64; 6]>, } impl SavedScale { @@ -292,7 +315,13 @@ pub(crate) fn restore(window: &Window) -> tauri::Result<()> { eprintln!("Could not restore Buzz window geometry: {error}"); } } - window.restore_state(StateFlags::MAXIMIZED | StateFlags::FULLSCREEN) + let kept = kept_scale(window.app_handle()); + kept.restoring + .store(true, std::sync::atomic::Ordering::SeqCst); + let result = window.restore_state(StateFlags::MAXIMIZED | StateFlags::FULLSCREEN); + kept.restoring + .store(false, std::sync::atomic::Ordering::SeqCst); + result } /// The geometry to restore and the scales recorded with it: the onboarding @@ -309,9 +338,11 @@ fn restore_input( (filename, SCALE) }; let saved = saved_geometry(&std::fs::read(dir.join(geometry)).ok()?, label)?; + // Scales recorded for another save are stale: restore as without them. let scales = std::fs::read(dir.join(scale)) .ok() - .and_then(|bytes| saved_scale(&bytes, label)); + .and_then(|bytes| saved_scale(&bytes, label)) + .filter(|scales| scales.geometry == Some(saved.pairing())); Some((saved, scales)) } @@ -336,6 +367,20 @@ struct SavedGeometry { fullscreen: bool, } +impl SavedGeometry { + /// The numbers a restore converts, which name this save in the scale file. + fn pairing(&self) -> [i64; 6] { + [ + self.width.into(), + self.height.into(), + self.x.into(), + self.y.into(), + self.prev_x.into(), + self.prev_y.into(), + ] + } +} + fn saved_geometry(bytes: &[u8], label: &str) -> Option { serde_json::from_slice::>(bytes) .ok()? @@ -878,6 +923,12 @@ mod tests { super::saved_geometry(&serde_json::to_vec(state).unwrap(), "main").unwrap() } + /// A scale file with `fields`, recorded for the save `state`. + fn bound(state: &Value, mut fields: Value) -> Vec { + fields["geometry"] = json!(decode(state).pairing()); + serde_json::to_vec(&json!({ "main": fields })).unwrap() + } + #[test] fn requested_geometry_is_safe_even_while_getters_still_report_startup_bounds() { let area = rect(0, 25, 1440, 875); @@ -1077,9 +1128,16 @@ mod tests { let bytes = std::fs::read(dir.path().join(name)).unwrap(); let saved = super::saved_scale(&bytes, "main").unwrap(); assert_eq!((saved.scale, saved.position), (scale, Some(scale))); + assert!(saved.geometry.is_some()); assert_eq!(super::saved_scale(&bytes, "other"), None); } assert_eq!(super::saved_scale(br#"{"main":{"scale":0}}"#, "main"), None); + // Each scale file names the geometry file it was copied beside. + for intro in [true, false] { + let (_, scales) = + super::restore_input(dir.path(), &app.handle().filename(), "main", intro).unwrap(); + assert_eq!(scales.map(|scales| scales.scale), Some(scale)); + } super::restore(&window).unwrap(); assert!(!dir.path().join(super::INTRO_GEOMETRY).exists()); assert!(!dir.path().join(super::INTRO_SCALE).exists()); @@ -1135,14 +1193,14 @@ mod tests { #[cfg(not(windows))] fn planned( state: &Value, - scale: &[u8], + scale: Value, startup: f64, monitors: &[(tauri::PhysicalRect, f64)], ) -> (tauri::LogicalPosition, tauri::LogicalSize) { let dir = tempfile::tempdir().unwrap(); let live = tauri_plugin_window_state::DEFAULT_FILENAME; std::fs::write(dir.path().join(live), serde_json::to_vec(state).unwrap()).unwrap(); - std::fs::write(dir.path().join(super::SCALE), scale).unwrap(); + std::fs::write(dir.path().join(super::SCALE), bound(state, scale)).unwrap(); let (saved, scales) = super::restore_input(dir.path(), live, "main", false).unwrap(); let offset = tauri::PhysicalPosition::new(0, 0); let (position, size, logical) = super::restore_plan( @@ -1165,7 +1223,7 @@ mod tests { // 1200x750 points cached on the 2x laptop, then moved to (2212, -200) // points on the 1x external without a Resized. let state = saved_state(2212, -200, 2400, 1500); - let split = br#"{"main":{"scale":2.0,"position":1.0,"prev":1.0}}"#; + let split = json!({"scale": 2.0, "position": 1.0, "prev": 1.0}); assert_eq!( planned(&state, split, 2.0, &monitors), ( @@ -1178,7 +1236,7 @@ mod tests { state["main"]["maximized"] = json!(true); state["main"]["prev_x"] = json!(2212); state["main"]["prev_y"] = json!(-200); - let prev = br#"{"main":{"scale":2.0,"position":2.0,"prev":1.0}}"#; + let prev = json!({"scale": 2.0, "position": 2.0, "prev": 1.0}); assert_eq!( planned(&state, prev, 2.0, &monitors).0, tauri::LogicalPosition::new(2212.0, -200.0), @@ -1186,7 +1244,7 @@ mod tests { // An older file without position scales reads them as the size's. let state = saved_state(200, 66, 2400, 1500); assert_eq!( - planned(&state, br#"{"main":{"scale":2.0}}"#, 1.0, &monitors), + planned(&state, json!({"scale": 2.0}), 1.0, &monitors), ( tauri::LogicalPosition::new(100.0, 33.0), tauri::LogicalSize::new(1200.0, 750.0) @@ -1206,20 +1264,18 @@ mod tests { let live = tauri_plugin_window_state::DEFAULT_FILENAME; let input = |intro| super::restore_input(dir.path(), live, "main", intro); assert!(input(true).is_none() && input(false).is_none()); - write( - live, - &serde_json::to_vec(&saved_state(100, 120, 960, 640)).unwrap(), + let (state, intro) = ( + saved_state(100, 120, 960, 640), + saved_state(300, 320, 1200, 800), ); + write(live, &serde_json::to_vec(&state).unwrap()); // A plugin file without a scale file restores as on main. assert!(input(false).unwrap().1.is_none()); - write(super::SCALE, br#"{"main":{"scale":2.0}}"#); - write( - super::INTRO_GEOMETRY, - &serde_json::to_vec(&saved_state(300, 320, 1200, 800)).unwrap(), - ); + write(super::SCALE, &bound(&state, json!({"scale": 2.0}))); + write(super::INTRO_GEOMETRY, &serde_json::to_vec(&intro).unwrap()); write( super::INTRO_SCALE, - br#"{"main":{"scale":1.0,"position":2.0}}"#, + &bound(&intro, json!({"scale": 1.0, "position": 2.0})), ); let (saved, scales) = input(true).unwrap(); assert_eq!((saved.x, saved.width), (300, 1200)); @@ -1228,7 +1284,8 @@ mod tests { Some(super::SavedScale { scale: 1.0, position: Some(2.0), - prev: None + prev: None, + geometry: Some(decode(&intro).pairing()), }) ); let (saved, scales) = input(false).unwrap(); @@ -1241,8 +1298,11 @@ mod tests { fn window_events_update_the_kept_scales_and_only_saves_write_them() { let (dir, app) = fixture(); let path = dir.path().join(super::SCALE); - let disk = br#"{"main":{"scale":2.0}}"#; - std::fs::write(&path, disk).unwrap(); + let live = dir.path().join(tauri_plugin_window_state::DEFAULT_FILENAME); + let state = saved_state(200, 66, 2400, 1500); + std::fs::write(&live, serde_json::to_vec(&state).unwrap()).unwrap(); + let disk = bound(&state, json!({"scale": 2.0})); + std::fs::write(&path, &disk).unwrap(); let mut plugin = super::builder().build(); plugin.initialize(app.handle(), Value::Null).unwrap(); let mut window = |label| { @@ -1255,7 +1315,7 @@ mod tests { window }; let (main, other) = (window("main"), window("other")); - let scales = || *app.state::().0.lock().unwrap(); + let scales = || *app.state::().kept.lock().unwrap(); // The kept scales start from the file, as the plugin's cache does. super::restore(&main).unwrap(); assert_eq!(scales(), kept(2.0, 2.0, 2.0)); @@ -1269,25 +1329,89 @@ mod tests { assert_eq!(scales(), kept(2.0, 1.0, 2.0)); super::window_event(&main, &resized); assert_eq!(scales(), kept(1.0, 1.0, 2.0)); + // While the plugin's restore holds its lock, it ignores Moved and + // Resized, and so does Buzz. + let restoring = &app.state::().restoring; + restoring.store(true, std::sync::atomic::Ordering::SeqCst); + super::window_event(&main, &moved); + super::window_event(&main, &resized); + restoring.store(false, std::sync::atomic::Ordering::SeqCst); + assert_eq!(scales(), kept(1.0, 1.0, 2.0)); // Events only update the cache, like the plugin's: a crash or Force // Quit before Exit leaves the old geometry on disk, and the old scale. assert_eq!(std::fs::read(&path).unwrap(), disk); // Exit: the plugin saves, then Buzz writes the scales of that save. plugin.on_event(app.handle(), &tauri::RunEvent::Exit); super::save_scale(app.handle()); + let saved = super::saved_geometry(&std::fs::read(&live).unwrap(), "main").unwrap(); assert_eq!( super::saved_scale(&std::fs::read(&path).unwrap(), "main"), Some(super::SavedScale { scale: 1.0, position: Some(1.0), - prev: Some(2.0) + prev: Some(2.0), + geometry: Some(saved.pairing()), }) ); } + #[test] + fn a_geometry_save_without_its_scales_restores_as_before() { + let monitors = mixed_scale_monitors(); + let (dir, app) = fixture(); + let mut plugin = super::builder().build(); + plugin.initialize(app.handle(), Value::Null).unwrap(); + let live = dir.path().join(tauri_plugin_window_state::DEFAULT_FILENAME); + let path = dir.path().join(super::SCALE); + // This build quit on the 2x laptop: a 1200x750-point window. + let laptop = saved_state(200, 66, 2400, 1500); + std::fs::write(&live, serde_json::to_vec(&laptop).unwrap()).unwrap(); + std::fs::write(&path, bound(&laptop, json!({"scale": 2.0}))).unwrap(); + // Then an older build, or an exit cut short between the two writes, + // saved 1200x750 pixels on the 1x external and left the 2x scale. + let external = saved_state(2212, -317, 1200, 750); + std::fs::write(&live, serde_json::to_vec(&external).unwrap()).unwrap(); + let (saved, scales) = + super::restore_input(dir.path(), &app.handle().filename(), "main", false).unwrap(); + assert_eq!(scales, None); + // Restored as on main, in physical pixels, not halved to 600x375 points. + let offset = tauri::PhysicalPosition::new(0, 0); + assert_eq!( + super::restore_plan( + saved, + scales, + offset, + 1.0, + &monitors, + monitors[0], + &config() + ), + ( + tauri::PhysicalPosition::new(2212, -317), + tauri::PhysicalSize::new(1200, 750), + None + ), + ); + // The kept scales don't start from the stale file either, so the next + // Exit can't pair them with this save's cached frame. + let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap() + .as_ref() + .window(); + plugin.window_created(window.clone()); + super::restore(&window).unwrap(); + assert_eq!( + *app.state::().kept.lock().unwrap(), + super::Kept::default() + ); + } + #[test] fn nothing_is_written_without_a_kept_scale() { let (dir, app) = fixture(); + let mut plugin = super::builder().build(); + plugin.initialize(app.handle(), Value::Null).unwrap(); super::write_kept_scale(app.handle()); assert!(!dir.path().join(super::SCALE).exists()); }