Files
RuneStone/src-tauri/src/lib.rs
T
Knotty Wyvern 5d5ba9e1f7 Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder.
WebView storage can be lost, and the host cannot read it. The file has
a schema number, a revision number, and one value for each section:
general, appearance, customThemes, customThemesLegacy, and language.
- settings_read gives all sections, the revision, and a one-time
  notice.
- settings_write replaces one section, writes the file atomically, and
  sends settings-changed to all windows. The limit is 8 MiB.
- settings_migrate writes the first file only when no file exists.
- The host moves a damaged file to settings.corrupt-<seconds>.json,
  starts from the defaults, and reports this one time.

Each window loads the sections before its first render. One store in
src/lib/settings/store.ts replaces the storage listeners. When no file
exists, the window normalizes the old localStorage values and migrates
them. The old keys stay in place for one release. The window layout
and the open tabs stay in localStorage on purpose. The browser preview
keeps all preferences in localStorage.

Keep tab transfer offers in host memory, not in localStorage, because
an offer can hold unsaved text. A window takes an offer once. The host
checks the workspace root and a 120 second expiry. When the receiver
accepts the tab, the host sends tab-transfer-accepted to the source
window only. A refused offer stays open, and the source tab stays open.
A new window and a drop on the tab ribbon use one check.

The smoke harness serves the new commands from one shared state for
each browser context. Tests read saved values from the mock settings
file. Rust, unit, and smoke tests cover the changes.
2026-10-27 23:56:00 -07:00

238 lines
9.8 KiB
Rust

mod error;
mod fsutil;
mod pty;
mod terminal_platform;
mod plugins;
mod plugin_sources;
mod workspace;
mod browser;
mod git;
mod completion;
mod settings;
mod preferences;
mod tab_transfer;
mod spelling;
mod theme;
mod backgrounds;
use pty::PtyState;
use tauri::Manager;
use workspace::WorkspaceState;
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
.manage(WorkspaceState::new())
.manage(PtyState::new())
.manage(plugins::PluginState::default())
.manage(browser::BrowserState::default())
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::backgrounds_choose_folder,
backgrounds::backgrounds_default_folder,
backgrounds::backgrounds_list,
backgrounds::backgrounds_read,
backgrounds::backgrounds_read_image_settings,
backgrounds::backgrounds_write_image_settings,
theme::theme_export,
spelling::spelling_menu_install,
spelling::spelling_suggestions,
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
preferences::settings_read,
preferences::settings_write,
preferences::settings_migrate,
tab_transfer::tab_transfer_offer,
tab_transfer::tab_transfer_take,
tab_transfer::tab_transfer_finish,
tab_transfer::tab_transfer_cancel,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
browser::browser_connect,
browser::browser_stop,
git::git_status,
git::git_diff,
git::git_stage,
git::git_unstage,
git::git_commit,
git::git_blame,
git::git_push,
git::git_pull,
git::git_graph,
git::git_commit_diff,
git::git_commit_details,
workspace::workspace_open,
workspace::workspace_open_window,
workspace::workspace_last_path,
workspace::workspace_recent,
workspace::workspace_forget,
workspace::workspace_new,
workspace::workspace_list,
workspace::workspace_list_markdown,
workspace::workspace_read,
workspace::workspace_read_many,
workspace::workspace_read_bytes,
workspace::workspace_write,
workspace::workspace_create,
workspace::workspace_rename,
workspace::workspace_delete,
workspace::workspace_read_data_url,
workspace::workspace_write_bytes,
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
workspace::workspace_open_terminal,
workspace::workspace_open_default,
workspace::workspace_search,
plugins::plugins_snapshot,
plugins::plugins_choose,
plugins::plugins_from_git,
plugins::plugins_cancel,
plugins::plugins_install,
plugins::plugins_set_enabled,
plugins::plugins_load,
plugins::plugins_release,
plugins::plugins_prepare_remove,
plugins::plugins_remove,
plugins::plugins_retry_remove,
plugins::plugins_reveal,
plugins::plugins_data,
plugins::plugins_asset,
pty::pty_open,
pty::pty_write,
pty::pty_resize,
pty::pty_close,
pty::pty_profiles,
pty::pty_new_window,
pty::pty_dictation,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
// This handler runs on the main thread. Here, revoke the window's access
// with short locks only. A cleanup thread stops processes and erases files.
settings::close_owned_window(app, label);
spelling::close_window(app, label);
app.state::<tab_transfer::TabTransferState>().release_window(label);
app.state::<completion::CompletionState>().close_window(label);
let browser_tabs = app.state::<browser::BrowserState>().release_window(label);
let staging = app.state::<plugins::PluginState>().try_release_window(label);
app.state::<WorkspaceState>().close_window(label);
let app = app.clone();
let label = label.clone();
let cleanup = std::thread::Builder::new().name("window-cleanup".into()).spawn(move || {
app.state::<PtyState>().close_window(&label);
app.state::<browser::BrowserState>().close_tabs(browser_tabs);
match staging {
Some(staging) => staging.erase(),
// Another plugin command held the lock. Wait for it here.
None => app.state::<plugins::PluginState>().close_window(&label),
}
});
if let Err(error) = cleanup {
eprintln!("RuneStone could not start the window cleanup: {error}");
}
}
if matches!(event, tauri::RunEvent::Exit) {
app.state::<PtyState>().close_all();
app.state::<browser::BrowserState>().close_all();
}
});
}
#[cfg(test)]
mod command_list_tests {
//! Each command is listed in four places. This test keeps the lists the same.
use std::collections::BTreeSet;
use std::path::Path;
fn read(relative: &str) -> String {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative);
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("Cannot read {}: {error}", path.display()))
}
/// Fail on a duplicate entry, which a set would hide.
fn unique(file: &str, names: impl Iterator<Item = String>) -> BTreeSet<String> {
let mut set = BTreeSet::new();
for name in names {
assert!(set.insert(name.clone()), "{file} lists the command {name} more than once.");
}
set
}
/// The text between the first `start` and the next `end` after it.
fn section<'a>(text: &'a str, start: &str, end: &str, file: &str) -> &'a str {
let from = text.find(start).unwrap_or_else(|| panic!("{file} has no `{start}`")) + start.len();
let length = text[from..].find(end).unwrap_or_else(|| panic!("{file} has no `{end}` after `{start}`"));
&text[from..from + length]
}
fn handler_commands() -> BTreeSet<String> {
let source = read("src/lib.rs");
let list = section(&source, "generate_handler![", "]", "src/lib.rs");
unique("src/lib.rs", list.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(|entry| entry.rsplit("::").next().unwrap().to_owned()))
}
fn build_commands() -> BTreeSet<String> {
let source = read("build.rs");
let list = section(&source, ".commands(&[", "]", "build.rs");
unique("build.rs", list.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(|entry| entry.trim_matches('"').to_owned()))
}
fn capability_commands(relative: &str) -> BTreeSet<String> {
let value: serde_json::Value = serde_json::from_str(&read(relative))
.unwrap_or_else(|error| panic!("{relative} is not valid JSON: {error}"));
let permissions = value["permissions"]
.as_array()
.unwrap_or_else(|| panic!("{relative} has no permissions list"))
.iter()
.filter_map(|permission| permission.as_str())
// Plugin permissions such as `core:default` have a prefix. App commands do not.
.filter(|permission| !permission.contains(':'))
.map(|permission| {
let command = permission.strip_prefix("allow-")
.unwrap_or_else(|| panic!("{relative} has an app permission without `allow-`: {permission}"));
command.replace('-', "_")
});
unique(relative, permissions)
}
fn difference(left: &BTreeSet<String>, right: &BTreeSet<String>) -> Vec<String> {
left.difference(right).cloned().collect()
}
#[test]
fn command_lists_match() {
let handler = handler_commands();
let build = build_commands();
let default = capability_commands("capabilities/default.json");
let settings = capability_commands("capabilities/settings.json");
assert!(handler.len() > 50, "Found only {} commands in generate_handler! in src/lib.rs", handler.len());
for (name, list) in [("build.rs", &build), ("capabilities/default.json", &default)] {
assert!(
&handler == list,
"The commands in {name} differ from generate_handler! in src/lib.rs.\nMissing from {name}: {:?}\nOnly in {name}: {:?}",
difference(&handler, list),
difference(list, &handler),
);
}
// The settings windows get an intentional subset of the commands.
let unknown = difference(&settings, &handler);
assert!(unknown.is_empty(), "capabilities/settings.json allows commands that generate_handler! in src/lib.rs does not register: {unknown:?}");
}
}