Files
RuneStone/src-tauri/src/settings.rs
T
2026-11-16 04:21:21 -07:00

223 lines
8.8 KiB
Rust

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use tauri::{AppHandle, Manager, State};
use crate::error::Result;
use crate::workspace::{current_root, WorkspaceState};
#[derive(Default)]
pub struct SettingsState(Mutex<HashMap<String, Arc<AtomicBool>>>);
struct PendingOpen<'a> {
state: &'a SettingsState,
label: String,
cancelled: Arc<AtomicBool>,
}
impl SettingsState {
fn reserve(&self, label: &str) -> Result<Option<PendingOpen<'_>>> {
let mut pending = self.0.lock().map_err(|_| "Settings window lock failed.")?;
if let Some(cancelled) = pending.get(label) {
return if cancelled.load(Ordering::SeqCst) {
Err("The workspace changed while settings opened. Try again.".into())
} else { Ok(None) };
}
let cancelled = Arc::new(AtomicBool::new(false));
pending.insert(label.into(), cancelled.clone());
Ok(Some(PendingOpen { state: self, label: label.into(), cancelled }))
}
fn cancel(&self, label: &str) {
if let Ok(pending) = self.0.lock() {
if let Some(cancelled) = pending.get(label) { cancelled.store(true, Ordering::SeqCst); }
}
}
}
impl PendingOpen<'_> {
fn can_publish(&self, owner_exists: bool, expected: &Option<PathBuf>, current: &Option<PathBuf>) -> bool {
!self.cancelled.load(Ordering::SeqCst) && owner_exists && expected == current
}
}
impl Drop for PendingOpen<'_> {
fn drop(&mut self) {
if let Ok(mut pending) = self.state.0.lock() { pending.remove(&self.label); }
}
}
fn settings_label(owner: &str) -> Result<String> {
if owner == "main" || owner.starts_with("workspace-") {
Ok(format!("settings-{owner}"))
} else {
Err("Open settings from a workspace window.".into())
}
}
fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<()> {
if let Ok(root) = current_root(workspace, owner) {
workspace.bind_terminal(label, root)?;
} else {
workspace.close_window(label);
}
Ok(())
}
#[tauri::command]
pub async fn settings_open_window(
app: AppHandle,
window: tauri::Window,
state: State<'_, SettingsState>,
workspace: State<'_, WorkspaceState>,
) -> Result<()> {
let label = settings_label(window.label())?;
// The reservation survives native calls, but its mutex guard never does.
let Some(pending) = state.reserve(&label)? else { return Ok(()); };
let root = current_root(&workspace, window.label()).ok();
let valid = || pending.can_publish(
app.get_webview_window(window.label()).is_some(),
&root, &current_root(&workspace, window.label()).ok(),
);
if !valid() { return Err("The workspace closed while settings opened.".into()); }
bind_workspace(&workspace, window.label(), &label)?;
let settings = if let Some(existing) = app.get_webview_window(&label) {
existing
} else {
let title = root.as_ref()
.and_then(|root| root.file_name().map(|name| format!("Settings — {} — RuneStone", name.to_string_lossy())))
.unwrap_or_else(|| "Settings — RuneStone".into());
match crate::window_frame::title_bar(tauri::WebviewWindowBuilder::new(
&app, &label, tauri::WebviewUrl::App("?settingsWindow=true".into()),
))
.title(title)
.inner_size(920.0, 650.0)
.min_inner_size(540.0, 420.0)
.resizable(true)
.visible(false)
.disable_drag_drop_handler()
.build() {
Ok(settings) => settings,
Err(error) => { workspace.close_window(&label); return Err(error.into()); }
}
};
let result = (|| -> Result<()> {
if !valid() { return Err("The workspace changed while settings opened.".into()); }
settings.unminimize()?;
settings.show()?;
settings.set_focus()?;
if !valid() { return Err("The workspace changed while settings opened.".into()); }
Ok(())
})();
if result.is_err() {
let _ = settings.destroy();
workspace.close_window(&label);
}
result
}
pub fn close_owned_window(app: &AppHandle, owner: &str) {
if let Ok(label) = settings_label(owner) {
app.state::<SettingsState>().cancel(&label);
if let Some(window) = app.get_webview_window(&label) { let _ = window.destroy(); }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pending_opens_deduplicate_without_holding_the_state_lock() {
let state = SettingsState::default();
let first = state.reserve("settings-main").unwrap().unwrap();
assert!(state.0.try_lock().is_ok());
assert!(state.reserve("settings-main").unwrap().is_none());
assert!(state.reserve("settings-workspace-2").unwrap().is_some());
drop(first);
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn lifecycle_cancellation_does_not_wait_for_an_inflight_build() {
let state = Arc::new(SettingsState::default());
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let worker_state = state.clone();
let worker = std::thread::spawn(move || {
let pending = worker_state.reserve("settings-main").unwrap().unwrap();
started_tx.send(()).unwrap();
// Stand in for a native build waiting for the UI thread.
resume_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
assert!(!pending.can_publish(true, &None, &None));
});
started_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
state.cancel("settings-main");
assert!(state.reserve("settings-main").is_err());
resume_tx.send(()).unwrap();
worker.join().unwrap();
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn completed_build_rejects_closed_owners_and_changed_workspaces() {
let state = SettingsState::default();
let pending = state.reserve("settings-main").unwrap().unwrap();
let root = Some(PathBuf::from("/one"));
assert!(pending.can_publish(true, &root, &root));
assert!(!pending.can_publish(false, &root, &root));
assert!(!pending.can_publish(true, &None, &root));
assert!(!pending.can_publish(true, &root, &Some(PathBuf::from("/two"))));
state.cancel("settings-main");
assert!(!pending.can_publish(true, &root, &root));
}
#[test]
fn failed_build_releases_its_reservation_for_retry() {
let state = SettingsState::default();
let failed = || -> Result<()> {
let _pending = state.reserve("settings-main")?.unwrap();
Err("Native build failed".into())
};
assert!(failed().is_err());
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn each_workspace_reuses_its_own_settings_label() {
assert_eq!(settings_label("main").unwrap(), "settings-main");
assert_eq!(settings_label("workspace-12").unwrap(), "settings-workspace-12");
assert_ne!(settings_label("main").unwrap(), settings_label("workspace-12").unwrap());
}
#[test]
fn auxiliary_windows_cannot_create_settings_windows() {
for owner in ["settings-main", "terminal-123", "browser-123", "external"] {
assert!(settings_label(owner).is_err());
}
}
#[test]
fn settings_use_only_the_owners_workspace_and_release_it_on_close() {
let workspace = WorkspaceState::new();
workspace.bind_terminal("workspace-1", "/one".into()).unwrap();
workspace.bind_terminal("workspace-2", "/two".into()).unwrap();
bind_workspace(&workspace, "workspace-1", "settings-workspace-1").unwrap();
bind_workspace(&workspace, "workspace-2", "settings-workspace-2").unwrap();
assert_eq!(current_root(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one"));
assert_eq!(current_root(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two"));
workspace.close_window("settings-workspace-1");
assert!(current_root(&workspace, "settings-workspace-1").is_err());
assert!(current_root(&workspace, "workspace-1").is_ok());
}
#[test]
fn settings_without_a_workspace_never_use_the_recent_workspace() {
let workspace = WorkspaceState::new();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert!(current_root(&workspace, "settings-main").is_err());
workspace.bind_terminal("main", "/opened-later".into()).unwrap();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert_eq!(current_root(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later"));
}
}