tiletopia/src-tauri/src/window_state.rs
megaproxy e6d0040021 Fix workspace accumulation, tab-close popover, scrollbars, drag ghost
- window_state.rs: persist only the main window's workspaces. The aggregator
  flattened every window's tabs into the saved file; main then adopted the
  whole blob on launch, so detached windows' ephemeral tabs (and Pane N
  drag-out artifacts) accumulated without bound.
- TabStrip: portal the close-confirm popover to <body> with fixed,
  viewport-clamped positioning so the horizontally-scrolling strip can't clip
  it and it never runs off a window edge.
- styles.css: make themed ::-webkit-scrollbar global, not just xterm viewport.
- LeafPane: B1 drag-out ghost chip (portal, edge-pinned, orange detach state).
- App.tsx: moveToNewWindow waits briefly for pane registration instead of
  failing instantly on an in-flight spawn/adopt.
- gitignore cargo-test.lo*.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-28 20:24:09 +01:00

144 lines
5.6 KiB
Rust

//! 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<HashMap<String, Vec<Value>>>,
save_task: Mutex<Option<JoinHandle<()>>>,
}
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<Self>,
app: AppHandle,
label: String,
workspaces: Vec<Value>,
) {
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<Self>, 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 from ONLY the main window's workspaces.
///
/// Detached windows are ephemeral — their tabs are discarded on close
/// (Chrome-style), and only the main window's tabs are meant to survive
/// a restart. Persisting every window's workspaces (the original design)
/// let detached windows' tabs — and the `Pane N` adopt-targets from
/// drag-out — leak into the saved file; on the next launch the main
/// window loaded the whole blob and adopted them all, so they
/// accumulated without bound. Keying the persisted set to the main label
/// makes detached state structurally unable to pollute it.
fn build_envelope(&self) -> Value {
let map = self.per_window.lock();
let workspaces: Vec<Value> =
map.get(MAIN_WINDOW_LABEL).cloned().unwrap_or_default();
serde_json::json!({
"version": 2,
"workspaces": workspaces,
})
}
fn schedule_save(self: &Arc<Self>, 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<HashMap<String, PendingInit>>,
}