//! Cross-window workspace state aggregator. //! //! Each window owns its own list of workspaces (tabs) in its React state. //! When that list changes, the window calls `push_window_workspaces` to //! ship a snapshot down here. This module merges every window's snapshot //! into one envelope and persists it to `workspace.json` on a debounced //! timer — same `{ version: 2, workspaces: [...] }` shape the frontend //! reads at startup. //! //! The Rust side stays agnostic of the per-tree shape: workspaces are //! stored as `serde_json::Value` so this module never needs to be updated //! when LeafNode / SplitNode fields change. //! //! Lifetime of per-window entries: //! - Created/updated on every `push_window_workspaces` call. //! - The main window pushes initially after loading from disk; detached //! windows push after takeing their pending-init payload. //! - On detached-window close (handled in lib.rs), the entry is removed //! so the next save doesn't resurrect tabs the user explicitly closed. //! The main window's entry persists across the app lifetime. use std::collections::HashMap; use std::sync::Arc; use anyhow::{Context, Result}; use parking_lot::Mutex; use serde_json::Value; use tauri::{AppHandle, Manager}; use tokio::task::JoinHandle; use tokio::time::{sleep, Duration}; const WORKSPACE_FILE: &str = "workspace.json"; const SAVE_DEBOUNCE: Duration = Duration::from_millis(500); /// The label of the main (boot) window. Matches `tauri.conf.json`'s /// `windows[0].label`. Used to decide whether a window-close should /// retain or discard that window's tabs. pub const MAIN_WINDOW_LABEL: &str = "main"; #[derive(Default)] pub struct WindowsState { per_window: Mutex>>, save_task: Mutex>>, } impl WindowsState { /// Replace this window's workspaces snapshot and schedule a debounced /// save. Subsequent calls within the debounce window cancel the /// previous save task — so a flurry of UI mutations only writes once. pub fn push( self: &Arc, app: AppHandle, label: String, workspaces: Vec, ) { self.per_window.lock().insert(label, workspaces); self.schedule_save(app); } /// Drop a window's snapshot from the aggregate. Called on close of a /// non-main window so its tabs don't reappear on next launch. pub fn forget(self: &Arc, app: AppHandle, label: &str) { let removed = self.per_window.lock().remove(label).is_some(); if removed { self.schedule_save(app); } } /// Build the on-disk envelope by concatenating every window's /// workspaces in stable label order (main first when present, then /// the rest sorted alphabetically by label — deterministic so the /// file diff stays stable across no-op saves). fn build_envelope(&self) -> Value { let map = self.per_window.lock(); let mut keys: Vec<&String> = map.keys().collect(); keys.sort_by(|a, b| { // main first, then alpha match (a.as_str(), b.as_str()) { (MAIN_WINDOW_LABEL, _) => std::cmp::Ordering::Less, (_, MAIN_WINDOW_LABEL) => std::cmp::Ordering::Greater, (x, y) => x.cmp(y), } }); let mut workspaces: Vec = Vec::new(); for k in keys { if let Some(list) = map.get(k) { for w in list { workspaces.push(w.clone()); } } } serde_json::json!({ "version": 2, "workspaces": workspaces, }) } fn schedule_save(self: &Arc, app: AppHandle) { let me = Arc::clone(self); let mut slot = self.save_task.lock(); if let Some(prev) = slot.take() { prev.abort(); } let handle = tokio::spawn(async move { sleep(SAVE_DEBOUNCE).await; if let Err(e) = me.save_now(&app).await { tracing::warn!("debounced workspace save failed: {e:#}"); } }); *slot = Some(handle); } async fn save_now(&self, app: &AppHandle) -> Result<()> { let envelope = self.build_envelope(); let json = serde_json::to_string(&envelope).context("serialize envelope")?; let dir = app .path() .app_config_dir() .map_err(|e| anyhow::anyhow!("app_config_dir: {e}"))?; std::fs::create_dir_all(&dir).context("create_dir_all")?; let path = dir.join(WORKSPACE_FILE); let tmp = dir.join(format!("{WORKSPACE_FILE}.tmp")); std::fs::write(&tmp, json.as_bytes()).context("write tmp")?; std::fs::rename(&tmp, &path).context("rename tmp -> final")?; Ok(()) } } // --------------------------------------------------------------------------- // Pane-transfer pending-init registry // --------------------------------------------------------------------------- /// Payload the source window stashes in the backend before opening a new /// window; the target window pulls it during App mount via /// `take_pending_window_init`. /// /// `leaf_json` and `workspace_name` are owned by the source — the backend /// doesn't parse the leaf shape. `pane_id` is the existing PTY id the /// target window's XtermPane should attach to (instead of spawning). #[derive(Clone, serde::Serialize, serde::Deserialize)] pub struct PendingInit { #[serde(rename = "leafJson")] pub leaf_json: String, #[serde(rename = "paneId")] pub pane_id: crate::pty::PaneId, #[serde(rename = "workspaceName")] pub workspace_name: String, } #[derive(Default)] pub struct PendingInits { pub by_label: Mutex>, }