Replace the three error styles with one Error type and one Result alias in error.rs. The error crosses IPC as the same plain string as before. The message text does not change. Move the shared file mechanics to fsutil.rs. These are the reserved-name check, the link and junction check, the limited reads, and the atomic writes. Each module keeps its own path rules, limits, and messages. The plugin settings writer now flushes its file to disk before the rename. Remove the current_root_path and list_entries wrappers and an unused mime value. Use named windows-sys constants for the process, file, drive, and error codes. Add a test that compares the command lists in lib.rs, build.rs, and the capability files. The settings capability must be a subset of the full list. In Cargo.toml, set the author, keep only the rlib crate type, and remove the unused thiserror dependency. Remove panic = "abort" from the release profile. A panic on a worker thread then stops only that thread. It does not stop the editor with unsaved buffers.
224 lines
8.8 KiB
Rust
224 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, ¤t_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 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)
|
|
.decorations(false)
|
|
.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"));
|
|
}
|
|
}
|