RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+474
View File
@@ -0,0 +1,474 @@
//! The image folder of the Background feature (`src/lib/features/background/`).
//!
//! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog
//! sets it, so the interface never sends a folder path. The commands read the image files directly in
//! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings.
//! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links,
//! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder.
use crate::error::{Error, Result};
use crate::folders;
use crate::fsutil::{self, is_link};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const FOLDER_FILE: &str = "background-folder.json";
const SIDECAR: &str = ".runestone-backgrounds.json";
/// The old plugin whose folder grant the migration takes.
const LEGACY_PLUGIN: &str = "runestone.bg-slideshow";
const FOLDER_FILE_LIMIT: u64 = 64 * 1024;
/// Serializes changes to the folder file.
static LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize, Deserialize)]
struct FolderFile {
schema: u32,
path: PathBuf,
}
/// The folder file and the plugin data of one app data folder.
struct Host {
data: PathBuf,
}
fn raster(name: &str) -> bool {
Path::new(name)
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp"))
}
fn raster_signature(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(b"\xff\xd8\xff")
|| bytes.starts_with(b"GIF87a")
|| bytes.starts_with(b"GIF89a")
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
/// Read a small JSON file. A missing file gives `None`. A link or a folder is an error.
fn read_json<T: for<'de> Deserialize<'de>>(path: &Path, limit: u64) -> Result<Option<T>> {
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || is_link(&metadata) {
return Err(Error::new(format!("{} must be an ordinary file.", path.display())));
}
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else {
return Err(Error::new(format!("{} is too large.", path.display())));
};
Ok(Some(serde_json::from_slice(&bytes)?))
}
impl Host {
fn file(&self) -> PathBuf {
self.data.join(FOLDER_FILE)
}
fn stored(&self) -> Result<Option<PathBuf>> {
let Some(file) = read_json::<FolderFile>(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) };
if file.schema != 1 {
return Err("Unknown background folder file schema.".into());
}
Ok(Some(file.path))
}
fn save(&self, path: &Path) -> Result<()> {
fs::create_dir_all(&self.data)?;
let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?;
let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?)
}
/// Keep `folder` as the background folder. It must be an existing folder, not a whole drive.
fn choose(&self, folder: &Path) -> Result<String> {
let root = folders::granted_root(folder)?;
let _lock = LOCK.lock()?;
self.save(&root)?;
Ok(root.to_string_lossy().into_owned())
}
/// The kept folder for display, or `None`.
fn folder(&self) -> Result<Option<String>> {
Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned()))
}
fn clear(&self) -> Result<()> {
let _lock = LOCK.lock()?;
match fs::remove_file(self.file()) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
/// The kept folder, still an ordinary folder at the same resolved path.
/// A folder that became a link or a file does not redirect the access.
fn root(&self) -> Result<PathBuf> {
let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?;
let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?;
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path {
return Err("The background folder changed into a link or a file. Choose the folder again.".into());
}
Ok(path)
}
/// The names of the raster images directly in the folder.
fn list(&self) -> Result<Vec<String>> {
Ok(folders::list_files(&self.root()?)?
.into_iter()
.map(|entry| entry.name)
.filter(|name| raster(name))
.collect())
}
fn read(&self, name: &str) -> Result<Vec<u8>> {
if !raster(name) {
return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into());
}
let bytes = folders::read_file(&self.root()?, name)?;
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
fn read_sidecar(&self) -> Result<Option<String>> {
folders::read_sidecar(&self.root()?, SIDECAR)
}
/// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist).
fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> {
let value: serde_json::Value = serde_json::from_str(contents)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) {
return Err("Use image settings with schema 1 and an images object.".into());
}
folders::write_sidecar(&self.root()?, SIDECAR, contents, expected)
}
/// Take the folder of the old Background Slideshow grant when the host has no folder yet.
/// Returns the folder after the migration, or `None`. It changes no plugin file.
fn migrate(&self) -> Result<Option<String>> {
let _lock = LOCK.lock()?;
if let Some(path) = self.stored()? {
return Ok(Some(path.to_string_lossy().into_owned()));
}
let plugin_data = self.data.join("plugin-data");
let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json");
let Some(value) = read_json::<serde_json::Value>(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) };
let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) };
let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) };
self.save(&path)?;
Ok(Some(path.to_string_lossy().into_owned()))
}
}
fn host(app: &AppHandle) -> Result<Host> {
Ok(Host { data: app.path().app_data_dir()? })
}
/// Run `work` on a blocking worker, because the file system calls can wait.
async fn run<T: Send + 'static>(app: &AppHandle, work: impl FnOnce(Host) -> Result<T> + Send + 'static) -> Result<T> {
let host = host(app)?;
tauri::async_runtime::spawn_blocking(move || work(host)).await?
}
/// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel.
#[tauri::command]
pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option<String>) -> Result<Option<String>> {
let (picker_app, picker_window) = (app.clone(), window.clone());
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into());
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
})
.await?;
let Some(selected) = selected else { return Ok(None) };
let folder = selected.into_path().map_err(Error::from_display)?;
run(&app, move |host| host.choose(&folder)).await.map(Some)
}
#[tauri::command]
pub async fn background_folder(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.folder()).await
}
#[tauri::command]
pub async fn background_clear_folder(app: AppHandle) -> Result<()> {
run(&app, |host| host.clear()).await
}
#[tauri::command]
pub async fn background_list(app: AppHandle) -> Result<Vec<String>> {
run(&app, |host| host.list()).await
}
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
#[tauri::command]
pub async fn background_read(app: AppHandle, name: String) -> Result<tauri::ipc::Response> {
Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?))
}
#[tauri::command]
pub async fn background_read_sidecar(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.read_sidecar()).await
}
#[tauri::command]
pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option<String>) -> Result<()> {
run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await
}
#[tauri::command]
pub async fn background_migrate(app: AppHandle) -> Result<Option<String>> {
run(&app, |host| host.migrate()).await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::folders::LIST_LIMIT;
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n";
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(dunce::canonicalize(root).unwrap())
}
fn folder(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
fs::create_dir_all(&path).unwrap();
path
}
fn host(&self) -> Host {
Host { data: self.folder("app") }
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Make a link, or return `false` when Windows does not allow links for this user.
fn link(original: &Path, link: &Path, folder: bool) -> bool {
#[cfg(unix)]
{
let _ = folder;
std::os::unix::fs::symlink(original, link).unwrap();
true
}
#[cfg(windows)]
{
let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) };
match result {
Ok(()) => true,
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
false
}
Err(error) => panic!("{error}"),
}
}
}
#[test]
fn the_host_keeps_one_folder_until_it_is_cleared() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let other = fixture.folder("other");
let host = fixture.host();
assert_eq!(host.folder().unwrap(), None);
assert!(host.list().unwrap_err().to_string().contains("Choose a background folder"));
assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy());
// A new host reads the kept folder, as after a restart.
assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned()));
host.choose(&other).unwrap();
assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned()));
host.clear().unwrap();
host.clear().unwrap();
assert_eq!(host.folder().unwrap(), None);
}
#[test]
fn the_chosen_folder_must_be_an_existing_folder() {
let fixture = Fixture::new();
let host = fixture.host();
let images = fixture.folder("images");
assert!(host.choose(Path::new("relative")).is_err());
assert!(host.choose(&images.join("..").join("images")).is_err());
assert!(host.choose(&fixture.0.join("missing")).is_err());
fs::write(fixture.0.join("file.txt"), "x").unwrap();
assert!(host.choose(&fixture.0.join("file.txt")).is_err());
let drive = images.ancestors().last().unwrap().to_path_buf();
assert!(host.choose(&drive).is_err());
assert_eq!(host.folder().unwrap(), None);
// A damaged folder file is an error, not a silent reset.
fs::write(host.file(), "{damaged").unwrap();
assert!(host.folder().is_err());
fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap();
assert!(host.folder().is_err());
}
#[test]
fn the_listing_has_only_the_raster_files_directly_in_the_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
fs::write(images.join("b.PNG"), PNG).unwrap();
fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap();
fs::write(images.join("text.svg"), b"<svg />").unwrap();
fs::write(images.join("notes.md"), b"# notes").unwrap();
fs::write(images.join(SIDECAR), b"{}").unwrap();
fixture.folder("images/nested.gif");
fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap();
assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]);
assert_eq!(host.read("b.PNG").unwrap(), PNG);
}
#[test]
fn reads_reject_other_names_other_types_and_large_files() {
let fixture = Fixture::new();
let images = fixture.folder("images");
fs::write(fixture.0.join("outside.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] {
assert!(host.read(name).is_err(), "{name}");
}
fs::write(images.join("fake.png"), b"<svg />").unwrap();
assert!(host.read("fake.png").unwrap_err().to_string().contains("raster"));
fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap();
assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB"));
}
#[test]
fn the_listing_has_a_size_limit() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
for index in 0..=LIST_LIMIT {
fs::write(images.join(format!("{index}.png")), b"").unwrap();
}
assert!(host.list().unwrap_err().to_string().contains("10000"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let outside = fixture.folder("outside");
fs::write(outside.join("secret.png"), PNG).unwrap();
let host = fixture.host();
host.choose(&images).unwrap();
if !link(&outside.join("secret.png"), &images.join("link.png"), false) {
return;
}
assert!(host.list().unwrap().is_empty());
assert!(host.read("link.png").is_err());
// A kept folder that is replaced by a link loses its access.
let moved = fixture.folder("moved");
host.choose(&moved).unwrap();
fs::remove_dir(&moved).unwrap();
assert!(link(&outside, &moved, true));
assert!(host.list().unwrap_err().to_string().contains("Choose the folder again"));
}
#[test]
fn the_sidecar_keeps_external_changes_and_needs_schema_one() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let host = fixture.host();
host.choose(&images).unwrap();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(host.read_sidecar().unwrap(), None);
host.write_sidecar(first, None).unwrap();
assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first));
assert!(host.write_sidecar(next, None).is_err());
assert!(host.write_sidecar(next, Some("stale")).is_err());
host.write_sidecar(next, Some(first)).unwrap();
assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next);
for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] {
assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}");
}
assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err());
fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap();
assert!(host.read_sidecar().is_err());
}
fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String {
let grant = uuid::Uuid::new_v4().to_string();
let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}"));
fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap();
fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap();
grant
}
#[test]
fn the_migration_takes_the_folder_of_the_old_grant() {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#);
let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN);
let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap());
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned()));
assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file.");
}
#[test]
fn the_migration_keeps_an_existing_host_folder() {
let fixture = Fixture::new();
let images = fixture.folder("images");
let chosen = fixture.folder("chosen");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
let host = fixture.host();
host.choose(&chosen).unwrap();
assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned()));
assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned()));
}
#[test]
fn the_migration_without_a_usable_grant_keeps_no_folder() {
// No plugin data.
let fixture = Fixture::new();
assert_eq!(fixture.host().migrate().unwrap(), None);
// Settings without a grant, with an unknown grant, and with damaged JSON.
for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] {
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, settings);
let host = fixture.host();
assert_eq!(host.migrate().unwrap(), None, "{settings}");
assert_eq!(host.folder().unwrap(), None);
}
// A granted folder that no longer exists.
let fixture = Fixture::new();
let images = fixture.folder("images");
seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#);
fs::remove_dir(&images).unwrap();
assert_eq!(fixture.host().migrate().unwrap(), None);
}
#[test]
fn raster_types_are_recognized() {
for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png"));
}
}
+908
View File
@@ -0,0 +1,908 @@
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
fs,
io::{BufRead, BufReader, Read, Write},
net::TcpStream,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{mpsc, Arc, Mutex},
time::{Duration, Instant},
};
use tauri::{AppHandle, Emitter, Manager, State};
use crate::error::{Error, Result};
const COMMANDS: &[&str] = &[
"state",
"newTab",
"closeTab",
"navigate",
"back",
"forward",
"reload",
"stop",
"find",
"stopFind",
"openExternal",
"moveToWindow",
"adoptTab",
"resize",
"visible",
"focus",
"input",
"insertText",
"edit",
"contextAction",
"copiedImage",
"linkAt",
"frameAck",
"createProfile",
"renameProfile",
"duplicateProfile",
"bookmark",
"removeBookmark",
"settings",
"clearData",
"webData",
"removeCookie",
"removeHistory",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
sessions: Mutex<HashMap<String, String>>,
/// Tab owners. Each engine uses this table, so a closing window can release its tabs
/// without waiting for the engine lock.
routing: Arc<Mutex<WindowTabs>>,
/// Held while a retired engine stops. A new engine starts after the old one has stopped.
stopping: Mutex<()>,
}
#[derive(Default)]
struct WindowTabs {
windows: HashSet<String>,
owners: HashMap<String, String>,
pending: HashMap<String, String>,
transfer_tokens: HashMap<String, String>,
}
impl WindowTabs {
fn snapshot(&self, mut value: Value, owner: &str) -> Value {
if let Some(tabs) = value.get_mut("tabs").and_then(Value::as_array_mut) {
tabs.retain(|tab| tab["id"].as_str().and_then(|id| self.owners.get(id)).is_some_and(|window| window == owner));
for tab in tabs {
if let Some(token) = tab["id"].as_str().and_then(|id| self.transfer_tokens.get(id)) {
tab["transferToken"] = json!(token);
}
}
}
value
}
fn close(&mut self, owner: &str) -> Vec<String> {
self.windows.remove(owner);
self.pending.retain(|_, target| target != owner);
let closed: Vec<String> = self.owners.iter().filter(|(id, window)| !self.windows.contains(*window) && !self.pending.contains_key(*id)).map(|(id, _)| id.clone()).collect();
for id in &closed { self.owners.remove(id); self.transfer_tokens.remove(id); }
closed
}
fn assign(&mut self, id: &str, owner: &str) {
self.owners.insert(id.into(), owner.into());
self.transfer_tokens.insert(id.into(), uuid::Uuid::new_v4().to_string());
}
fn adopt(&mut self, id: &str, owner: &str, token: Option<&str>) -> Result<String> {
let source = self.owners.get(id).cloned().ok_or("Unknown browser tab.")?;
if source == owner { return Err("This browser tab already belongs to this window.".into()); }
let pending = self.pending.get(id).map(String::as_str);
let dragged = pending.is_none() && token.is_some() && self.transfer_tokens.get(id).map(String::as_str) == token;
if pending != Some(owner) && !dragged { return Err("This browser tab has no valid transfer to this window.".into()); }
self.assign(id, owner);
self.pending.remove(id);
Ok(source)
}
}
struct Worker {
child: Child,
input: Box<dyn Write + Send>,
replies: mpsc::Receiver<Value>,
routing: Arc<Mutex<WindowTabs>>,
/// Requests that nobody waits for. The reader drops their replies.
discard: Arc<Mutex<HashSet<u64>>>,
sequence: u64,
healthy: bool,
}
/// Browser profiles, settings, and Chromium state. On Windows this is Local AppData,
/// so that the Chromium caches stay out of the roaming profile.
fn root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_local_data_dir()?.join("browser"))
}
/// Releases up to 0.1.48 kept the browser data in the app data folder, which roams on Windows.
fn legacy_root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_data_dir()?.join("browser"))
}
/// Move the browser data of an earlier release from `legacy` to `current`. The engine must not run.
/// Nothing moves when the paths are the same, when `legacy` does not exist, or when `current` exists.
/// When the rename fails, for example across volumes, copy the folder. `legacy` stays until the copy is complete.
fn migrate_profiles(legacy: &Path, current: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) -> Result<()> {
if legacy == current || !legacy.is_dir() || fs::symlink_metadata(current).is_ok() {
return Ok(());
}
let failed = |error: Error| -> Error {
format!("RuneStone could not move the browser profiles from {} to {}: {error}", legacy.display(), current.display()).into()
};
let parent = current.parent().ok_or("Invalid browser profile folder.")?;
fs::create_dir_all(parent).map_err(|error| failed(error.into()))?;
if rename(legacy, current).is_ok() {
return Ok(());
}
let temporary = parent.join(format!(".browser-move-{}", uuid::Uuid::new_v4().simple()));
let copied = copy_profile(legacy, &temporary, &mut 0, &mut 0, false).and_then(|()| Ok(rename(&temporary, current)?));
if let Err(error) = copied {
let _ = fs::remove_dir_all(&temporary);
return Err(failed(error));
}
// The copy is complete. If the removal fails, only an old copy stays behind.
let _ = fs::remove_dir_all(legacy);
Ok(())
}
/// The engine must speak the protocol of this host. An engine from another release can differ.
fn ready(value: &Value) -> Result<()> {
if value["event"] != "ready" {
return Err("The browser runtime did not start.".into());
}
if value["protocol"].as_u64() != Some(crate::browser_engine::PROTOCOL) {
return Err("This browser engine does not match this RuneStone version. Install the browser engine again.".into());
}
Ok(())
}
fn authenticate_connection(
stream: TcpStream,
token: &str,
) -> Result<Option<(TcpStream, BufReader<TcpStream>)>> {
stream.set_nonblocking(false)?;
stream.set_nodelay(true)?;
stream.set_read_timeout(Some(Duration::from_secs(1)))?;
let mut reader = BufReader::new(stream.try_clone()?);
let mut bytes = Vec::new();
let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes);
let received = serde_json::from_slice::<Value>(&bytes)
.ok()
.and_then(|value| value["token"].as_str().map(str::to_string));
if read.is_err() || received.as_deref() != Some(token) {
return Ok(None);
}
// Windows keeps the timeout on the cloned socket after the original changes.
reader.get_ref().set_read_timeout(None)?;
stream.set_read_timeout(None)?;
Ok(Some((stream, reader)))
}
impl Worker {
fn start(app: &AppHandle, routing: Arc<Mutex<WindowTabs>>) -> Result<Self> {
let directory = root(app)?;
migrate_profiles(&legacy_root(app)?, &directory, |from, to| fs::rename(from, to))?;
fs::create_dir_all(&directory)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0))?;
listener.set_nonblocking(true)?;
let port = listener.local_addr()?.port();
let token = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
);
let mut command = Command::new(crate::browser_engine::executable(app)?);
command
.arg(format!("--rs-connect={port}"))
.arg(format!("--rs-browser-root={}", directory.display()))
.env("RUNESTONE_BROWSER_TOKEN", &token)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
.env_remove("ELECTRON_RUN_AS_NODE")
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_DISABLE_SANDBOX");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command.spawn()?;
let deadline = Instant::now() + Duration::from_secs(30);
let (input, output): (Box<dyn Write + Send>, Box<dyn Read + Send>) = loop {
if let Ok((stream, _)) = listener.accept() {
if let Some((stream, reader)) = authenticate_connection(stream, &token)? {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait()?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
}
std::thread::sleep(Duration::from_millis(20));
};
drop(listener);
let (send, replies) = mpsc::sync_channel(16);
let handle = app.clone();
let routes = routing.clone();
let discard = Arc::new(Mutex::new(HashSet::new()));
let unanswered = discard.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(output);
loop {
let mut bytes = Vec::new();
match reader
.by_ref()
.take(6_000_001)
.read_until(b'\n', &mut bytes)
{
Ok(0) | Err(_) => break,
Ok(_) if bytes.len() > 6_000_000 || !bytes.ends_with(b"\n") => break,
_ => {}
}
let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
continue;
};
match value.get("event").and_then(Value::as_str) {
Some("frame") => {
if let Ok(routes) = routes.lock() {
if let Some(target) = value["tabId"].as_str().and_then(|id| routes.owners.get(id)) {
let _ = handle.emit_to(target, "browser-frame", &value);
}
}
}
Some("state") | Some("error") | Some("context-menu") | Some("open-link") => {
if let Ok(routes) = routes.lock() {
for target in &routes.windows {
if let Some(id) = value["tabId"].as_str() {
if routes.owners.get(id) != Some(target) { continue; }
}
let mut payload = value.clone();
if value.get("state").is_some() { payload["state"] = routes.snapshot(value["state"].clone(), target); }
let _ = handle.emit_to(target, "browser-state", &payload);
}
}
}
_ => {
let dropped = value["id"].as_u64().is_some_and(|id| {
unanswered.lock().is_ok_and(|mut ids| ids.remove(&id))
});
if !dropped && send.try_send(value).is_err() {
break;
}
}
}
}
});
let mut worker = Self {
child,
input,
replies,
routing,
discard,
sequence: 0,
healthy: true,
};
let started = worker.replies.recv_timeout(Duration::from_secs(30))
.map_err(|_| Error::from("The browser runtime did not start."))
.and_then(|value| ready(&value));
match started {
Ok(()) => Ok(worker),
Err(error) => {
let _ = worker.child.kill();
let _ = worker.child.wait();
Err(error)
}
}
}
fn request(&mut self, command: &str, args: Value) -> Result<Value> {
let response = match self.exchange(command, args) {
Ok(response) => response,
Err(error) => {
self.healthy = false;
return Err(error);
}
};
if let Some(error) = response["error"].as_str() {
return Err(error.into());
}
Ok(response["result"].clone())
}
/// Send a request and do not wait for its reply. The reader drops the reply.
fn notify(&mut self, command: &str, args: Value) -> Result<()> {
self.sequence += 1;
self.discard.lock()?.insert(self.sequence);
let message = json!({ "id": self.sequence, "command": command, "args": args });
let sent = writeln!(self.input, "{}", message).and_then(|_| self.input.flush());
if sent.is_err() {
self.healthy = false;
}
Ok(sent?)
}
fn exchange(&mut self, command: &str, args: Value) -> Result<Value> {
self.sequence += 1;
let message = json!({ "id": self.sequence, "command": command, "args": args });
writeln!(self.input, "{}", message)?;
self.input.flush()?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
.map_err(|_| {
"The browser stopped responding. Open a new browser tab to restart it.".to_string()
})?;
if response["id"].as_u64() != Some(self.sequence) {
return Err("The browser response did not match the request.".into());
}
Ok(response)
}
fn stop(&mut self) -> Result<()> {
if !self.healthy {
let _ = self.child.kill();
let _ = self.child.wait();
return Ok(());
}
let requested = self.request("shutdown", json!({}));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if self.child.try_wait()?.is_some() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
Err("The browser did not stop cleanly. Profile duplication was cancelled.".into())
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn profile_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}
/// Copy a profile folder and refuse links. `limited` applies the limit for profile duplication.
fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64, limited: bool) -> Result<()> {
if !source.exists() {
fs::create_dir_all(target)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source)?;
// A junction is not a symbolic link, but the copy would also follow it.
if crate::fsutil::is_link(&metadata) {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
fs::create_dir_all(target)?;
for entry in fs::read_dir(source)? {
let entry = entry?;
copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes, limited)?;
}
} else if metadata.is_file() {
*files += 1;
*bytes += metadata.len();
if limited && (*files > 50_000 || *bytes > 2_000_000_000) {
return Err("This profile exceeds the duplication limit.".into());
}
fs::copy(source, target)?;
} else {
return Err("Unsupported profile entry.".into());
}
Ok(())
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock()?;
Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone())
}
fn require_session(&self, owner: &str, token: &str) -> Result<()> {
if self.sessions.lock()?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
}
}
/// Revoke the window's session and release its tabs. Return the tabs to close in the engine.
/// This step never waits for the engine or for a request in progress.
pub fn release_window(&self, owner: &str) -> Vec<String> {
if let Ok(mut sessions) = self.sessions.lock() { sessions.remove(owner); }
self.routing.lock().map(|mut routes| routes.close(owner)).unwrap_or_default()
}
/// Close released tabs in the engine, and stop the engine when no window uses it.
/// This can wait for a request in progress. It never holds the engine lock while it waits for a reply.
pub fn close_tabs(&self, closed: Vec<String>) {
let (mut worker, _stopping) = {
let Ok(mut guard) = self.inner.lock() else { return; };
let Some(worker) = guard.as_mut() else { return; };
if worker.healthy {
for id in closed {
if worker.notify("closeTab", json!({ "tabId": id })).is_err() { break; }
}
}
// A request can add a window while this cleanup waits for the lock.
if !self.routing.lock().is_ok_and(|routes| routes.windows.is_empty()) { return; }
let Some(worker) = guard.take() else { return; };
// Take the stop lock before the engine lock opens, so that a new engine waits for this one.
let Ok(stopping) = self.stopping.lock() else { return; };
(worker, stopping)
};
let _ = worker.stop();
}
pub fn close_window(&self, owner: &str) {
let closed = self.release_window(owner);
self.close_tabs(closed);
}
pub fn close_all(&self) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
self.stop_engine();
}
/// Stop the engine and keep the window sessions, so that open windows can start a new engine later.
pub fn stop_engine(&self) {
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
}
}
}
fn request(&self, app: &AppHandle, owner: &str, command: &str, args: Value) -> Result<Value> {
if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() {
return Err("Invalid browser request.".into());
}
let mut guard = self.inner.lock()?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
if guard.is_none() {
// Wait until a retired engine has stopped. The new engine has no tabs yet.
let _stopped = self.stopping.lock()?;
*self.routing.lock()? = WindowTabs::default();
*guard = Some(Worker::start(app, self.routing.clone())?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock()?.windows.insert(owner.to_string());
if command == "adoptTab" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let result = worker.request("state", json!({}))?;
if !result["tabs"].as_array().is_some_and(|tabs| tabs.iter().any(|tab| tab["id"] == id)) {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock()?;
routes.adopt(id, owner, args["transferToken"].as_str())?
};
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "linkAt", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {},
Some(_) => return Err("This browser tab belongs to another window.".into()),
None => return Err("Unknown browser tab.".into()),
}
}
if command == "moveToWindow" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let label = format!("browser-{}", uuid::Uuid::new_v4());
{
let mut routes = worker.routing.lock()?;
if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); }
routes.pending.insert(id.into(), label.clone());
routes.windows.insert(label.clone());
}
let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?;
url.query_pairs_mut().append_pair("browserWindow", "true");
url.query_pairs_mut().append_pair("browserTab", id);
if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); }
let result = crate::window_frame::title_bar(tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())))
.title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).disable_drag_drop_handler().build();
if let Err(error) = result {
worker.routing.lock()?.close(&label);
return Err(Error::from(error));
}
return Ok(json!({ "windowLabel": label }));
}
if command != "duplicateProfile" {
let result = worker.request(command, args.clone())?;
let mut routes = worker.routing.lock()?;
if command == "newTab" {
if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); }
} else if command == "closeTab" {
if let Some(id) = args["tabId"].as_str() { routes.owners.remove(id); routes.pending.remove(id); routes.transfer_tokens.remove(id); }
}
return Ok(routes.snapshot(result, owner));
}
let plan = guard.as_mut().unwrap().request("prepareDuplicate", args)?;
let source_id = plan["sourceId"]
.as_str()
.filter(|id| profile_id(id))
.ok_or("Invalid source profile.")?;
let target_id = plan["id"]
.as_str()
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
.ok_or("Invalid destination profile.")?;
let mut worker = guard.take().unwrap();
let routing = worker.routing.clone();
worker.stop()?;
drop(worker);
// Chromium is fully stopped before its databases are copied.
let partitions = root(app)?.join("Partitions");
let source = partitions.join(format!("runestone-{source_id}"));
let destination = partitions.join(format!("runestone-{target_id}"));
if destination.exists() {
return Err("The destination profile already exists.".into());
}
copy_profile(&source, &destination, &mut 0, &mut 0, true)?;
*guard = Some(Worker::start(app, routing.clone())?);
let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?;
let snapshot = routing.lock()?.snapshot(result, owner);
Ok(snapshot)
}
}
#[tauri::command]
pub async fn browser_connect(state: State<'_, BrowserState>, window: tauri::Window) -> Result<String> {
state.connect(window.label())
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
session: Option<String>,
) -> Result<Value> {
let owner = window.label().to_string();
// A request can wait for the engine to start or to answer, so it runs on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<BrowserState>();
// Only the built-in browser gets a session from `browser_connect`. A request without one fails.
state.require_session(&owner, session.as_deref().unwrap_or_default())?;
state.request(&app, &owner, &command, args)
})
.await?
}
#[tauri::command]
pub async fn browser_stop(app: AppHandle, window: tauri::Window) -> Result<()> {
let owner = window.label().to_string();
tauri::async_runtime::spawn_blocking(move || app.state::<BrowserState>().close_window(&owner)).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builtin_sessions_are_scoped_to_a_window_and_revoked_on_close() {
let state = BrowserState::default();
assert!(state.require_session("main", "missing").is_err());
let token = state.connect("main").unwrap();
assert!(state.require_session("main", &token).is_ok());
assert!(state.require_session("other", &token).is_err());
state.close_window("main");
assert!(state.require_session("main", &token).is_err());
let next = state.connect("main").unwrap();
assert_ne!(next, token);
state.close_all();
assert!(state.require_session("main", &next).is_err());
}
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.assign("a", "browser-other");
let snapshot = json!({ "tabs": [{ "id": "a" }] });
let token = routes.snapshot(snapshot.clone(), "browser-other")["tabs"][0]["transferToken"].as_str().unwrap().to_string();
assert!(routes.snapshot(snapshot, "main")["tabs"].as_array().unwrap().is_empty());
assert!(routes.adopt("a", "main", None).is_err());
assert!(routes.adopt("a", "main", Some("wrong-token")).is_err());
assert_eq!(routes.owners["a"], "browser-other");
assert_eq!(routes.adopt("a", "main", Some(&token)).unwrap(), "browser-other");
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners["a"], "main");
assert_ne!(routes.transfer_tokens["a"], token);
assert_eq!(routes.close("main"), vec!["a"]);
assert!(routes.transfer_tokens.is_empty());
}
#[test]
fn a_pending_window_move_cannot_be_taken_by_a_drag() {
let mut routes = WindowTabs::default();
routes.assign("a", "main");
let token = routes.transfer_tokens["a"].clone();
routes.pending.insert("a".into(), "browser-target".into());
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert_eq!(routes.adopt("a", "browser-target", None).unwrap(), "main");
assert!(routes.pending.is_empty());
}
#[test]
fn window_routing_preserves_moved_tabs_and_filters_snapshots() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.owners.insert("b".into(), "browser-other".into());
let snapshot = json!({ "tabs": [{ "id": "a" }, { "id": "b" }], "profiles": [{ "id": "user" }] });
assert_eq!(routes.snapshot(snapshot.clone(), "main")["tabs"], json!([{ "id": "a" }]));
assert_eq!(routes.snapshot(snapshot, "browser-other")["tabs"], json!([{ "id": "b" }]));
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("main").is_empty());
assert!(routes.owners.contains_key("a"));
let mut closed = routes.close("browser-other");
closed.sort();
assert_eq!(closed, vec!["a", "b"]);
assert!(routes.owners.is_empty());
}
#[test]
fn cancelled_window_move_keeps_the_source_tab() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners.get("a").map(String::as_str), Some("main"));
assert!(routes.pending.is_empty());
}
#[test]
fn authenticated_connection_survives_idle_period() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
writeln!(stream, "{}", json!({ "token": "test-token" })).unwrap();
std::thread::sleep(Duration::from_millis(1500));
writeln!(stream, "{}", json!({ "id": 1, "result": { "tabs": [] } })).unwrap();
});
let (stream, _) = listener.accept().unwrap();
let (input, mut reader) = authenticate_connection(stream, "test-token").unwrap().unwrap();
assert_eq!(input.read_timeout().unwrap(), None);
assert_eq!(reader.get_ref().read_timeout().unwrap(), None);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
sender.join().unwrap();
}
#[test]
fn authentication_preserves_buffered_messages_and_rejects_other_tokens() {
for accepted in [false, true] {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
stream.write_all(b"{\"token\":\"test-token\"}\n{\"event\":\"ready\"}\n").unwrap();
});
let (stream, _) = listener.accept().unwrap();
let connection = authenticate_connection(stream, if accepted { "test-token" } else { "other-token" }).unwrap();
if accepted {
let (_, mut reader) = connection.unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["event"], "ready");
} else {
assert!(connection.is_none());
}
sender.join().unwrap();
}
}
fn test_worker(replies: mpsc::Receiver<Value>) -> Worker {
Worker {
child: Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(Stdio::null())
.spawn()
.unwrap(),
input: Box::new(Vec::<u8>::new()),
replies,
routing: Arc::new(Mutex::new(WindowTabs::default())),
discard: Arc::new(Mutex::new(HashSet::new())),
sequence: 0,
healthy: true,
}
}
#[derive(Clone, Default)]
struct Sink(Arc<Mutex<Vec<u8>>>);
impl Write for Sink {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn closing_a_window_releases_tabs_without_the_engine_lock() {
let state = BrowserState::default();
let token = state.connect("main").unwrap();
{
let mut routes = state.routing.lock().unwrap();
routes.windows.extend(["main".into(), "other".into()]);
routes.assign("a", "main");
routes.assign("b", "other");
}
let (send, replies) = mpsc::channel();
let sink = Sink::default();
let mut worker = test_worker(replies);
worker.input = Box::new(sink.clone());
worker.routing = state.routing.clone();
let discard = worker.discard.clone();
*state.inner.lock().unwrap() = Some(worker);
// A request in progress holds the engine lock, but the window is released at once.
let busy = state.inner.lock().unwrap();
let closed = state.release_window("main");
assert_eq!(closed, vec!["a"]);
assert!(state.require_session("main", &token).is_err());
assert!(!state.routing.lock().unwrap().owners.contains_key("a"));
drop(busy);
// No reply arrives, and the cleanup does not wait for one.
let start = Instant::now();
state.close_tabs(closed);
assert!(start.elapsed() < Duration::from_secs(5));
let sent = String::from_utf8(sink.0.lock().unwrap().clone()).unwrap();
assert!(sent.contains("\"closeTab\"") && sent.contains("\"a\""), "{sent}");
assert_eq!(discard.lock().unwrap().len(), 1);
assert!(state.inner.lock().unwrap().is_some(), "Another window still uses the engine.");
drop(send);
state.close_window("other");
assert!(state.inner.lock().unwrap().is_none(), "The last window stops the engine.");
assert!(state.routing.lock().unwrap().owners.is_empty());
}
#[test]
fn profile_copy_rejects_links_and_junctions() {
let base = std::env::temp_dir().join(format!("runestone-profile-{}", uuid::Uuid::new_v4()));
let source = base.join("source");
let outside = base.join("outside");
fs::create_dir_all(&source).unwrap();
fs::create_dir_all(&outside).unwrap();
fs::write(source.join("Cookies"), b"cookies").unwrap();
fs::write(outside.join("secret.txt"), b"secret").unwrap();
copy_profile(&source, &base.join("plain"), &mut 0, &mut 0, true).unwrap();
assert_eq!(fs::read(base.join("plain").join("Cookies")).unwrap(), b"cookies");
let link = source.join("linked");
// A junction needs no symbolic-link privilege on Windows.
#[cfg(windows)]
assert!(Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(&outside)
.stdout(Stdio::null())
.status()
.unwrap()
.success());
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
let error = copy_profile(&source, &base.join("copy"), &mut 0, &mut 0, true).unwrap_err();
assert!(error.to_string().contains("links"), "{error}");
assert!(!base.join("copy").join("linked").join("secret.txt").exists());
#[cfg(windows)]
fs::remove_dir(&link).unwrap();
#[cfg(unix)]
fs::remove_file(&link).unwrap();
assert!(outside.join("secret.txt").exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn broken_transport_requires_a_fresh_worker() {
let (send, replies) = mpsc::channel();
drop(send);
let mut worker = test_worker(replies);
assert!(worker.request("state", json!({})).is_err());
assert!(!worker.healthy);
assert!(worker.stop().is_ok());
}
#[test]
fn invalid_settings_do_not_discard_the_worker() {
let (send, replies) = mpsc::channel();
send.send(json!({ "id": 1, "error": "Invalid browser settings." })).unwrap();
send.send(json!({ "id": 2, "result": { "tabs": [] } })).unwrap();
let mut worker = test_worker(replies);
assert!(worker.request("settings", json!({})).is_err());
assert!(worker.healthy);
assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] }));
}
fn profile_fixture(base: &Path) -> (PathBuf, PathBuf) {
let legacy = base.join("Roaming").join("browser");
fs::create_dir_all(legacy.join("Partitions").join("runestone-user")).unwrap();
fs::write(legacy.join("browser.json"), b"{\"version\":1}").unwrap();
fs::write(legacy.join("Partitions").join("runestone-user").join("Cookies"), b"cookies").unwrap();
(legacy, base.join("Local").join("browser"))
}
fn temporary_base() -> PathBuf {
std::env::temp_dir().join(format!("runestone-migrate-{}", uuid::Uuid::new_v4()))
}
#[test]
fn migration_moves_profiles_and_keeps_existing_ones() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
migrate_profiles(&legacy, &current, |from, to| fs::rename(from, to)).unwrap();
assert!(!legacy.exists());
assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies");
// A second start finds no old folder.
migrate_profiles(&legacy, &current, |_, _| panic!("Nothing must move.")).unwrap();
// When both folders exist, the new one wins and the old one stays.
let (legacy, _) = profile_fixture(&base);
fs::write(current.join("browser.json"), b"current").unwrap();
migrate_profiles(&legacy, &current, |_, _| panic!("Nothing must move.")).unwrap();
assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"current");
assert!(legacy.join("browser.json").exists());
// The same path (macOS and Linux) and a missing old folder change nothing.
migrate_profiles(&current, &current, |_, _| panic!("Nothing must move.")).unwrap();
let empty = base.join("empty");
migrate_profiles(&base.join("missing"), &empty, |_, _| panic!("Nothing must move.")).unwrap();
assert!(!empty.exists());
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn migration_copies_when_the_rename_fails() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
let source = legacy.clone();
let across_volumes = |from: &Path, to: &Path| {
if from == source { Err(std::io::Error::other("not the same device")) } else { fs::rename(from, to) }
};
migrate_profiles(&legacy, &current, across_volumes).unwrap();
assert!(!legacy.exists());
assert_eq!(fs::read(current.join("browser.json")).unwrap(), b"{\"version\":1}");
assert_eq!(fs::read(current.join("Partitions").join("runestone-user").join("Cookies")).unwrap(), b"cookies");
let names: Vec<_> = fs::read_dir(base.join("Local")).unwrap().map(|entry| entry.unwrap().file_name()).collect();
assert_eq!(names, vec![std::ffi::OsString::from("browser")], "No temporary copy stays.");
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn a_failed_copy_keeps_the_old_profiles() {
let base = temporary_base();
let (legacy, current) = profile_fixture(&base);
let outside = base.join("outside");
fs::create_dir_all(&outside).unwrap();
let link = legacy.join("linked");
#[cfg(windows)]
assert!(Command::new("cmd").args(["/C", "mklink", "/J"]).arg(&link).arg(&outside).stdout(Stdio::null()).status().unwrap().success());
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, &link).unwrap();
let error = migrate_profiles(&legacy, &current, |_, _| Err(std::io::Error::other("not the same device"))).unwrap_err();
assert!(error.to_string().contains("could not move the browser profiles"), "{error}");
assert!(legacy.join("browser.json").exists());
assert!(!current.exists());
assert_eq!(fs::read_dir(base.join("Local")).unwrap().count(), 0, "No temporary copy stays.");
#[cfg(windows)]
fs::remove_dir(&link).unwrap();
#[cfg(unix)]
fs::remove_file(&link).unwrap();
fs::remove_dir_all(&base).unwrap();
}
#[test]
fn the_engine_must_send_the_protocol_of_this_host() {
assert!(ready(&json!({ "event": "ready", "protocol": crate::browser_engine::PROTOCOL, "version": "0.1.8" })).is_ok());
assert!(ready(&json!({ "event": "ready" })).unwrap_err().to_string().contains("does not match"));
assert!(ready(&json!({ "event": "ready", "protocol": crate::browser_engine::PROTOCOL + 1 })).is_err());
assert!(ready(&json!({ "event": "state" })).unwrap_err().to_string().contains("did not start"));
}
#[test]
fn profile_names_cannot_escape_storage() {
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
assert!(!profile_id(value));
}
assert!(profile_id("user"));
assert!(profile_id("a-b-123"));
}
#[test]
fn protocol_does_not_expose_raw_execution_or_copy_commands() {
for name in [
"executeJavaScript",
"shell",
"prepareDuplicate",
"commitDuplicate",
"shutdown",
] {
assert!(!COMMANDS.contains(&name));
}
}
}
+684
View File
@@ -0,0 +1,684 @@
//! The browser engine is a separate download. Each host build pins one engine version in
//! `browser-engine.json`. On request, the host downloads that engine, makes sure that its size
//! and SHA-256 match the pin, and extracts it to the local app data folder.
//! See docs/development.md#engine-download.
use reqwest::{blocking::Client, Url};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeSet, HashMap},
fs,
io::{Read, Write},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
time::{Duration, Instant},
};
use tauri::{AppHandle, Emitter, Manager};
use tauri_plugin_dialog::DialogExt;
use crate::error::{Error, Result};
/// The protocol between the host and the engine. The engine sends it with its `ready` event.
pub const PROTOCOL: u64 = 1;
const PINNED: &str = include_str!("../browser-engine.json");
/// The extracted engine of Electron 44 has 73 files and 377 MB.
const MAX_ENTRIES: usize = 10_000;
const MAX_EXTRACTED: u64 = 1024 * 1024 * 1024;
const MARKER: &str = "installed.json";
const WORK: &str = ".download";
const CANCELLED: &str = "The browser engine download was cancelled.";
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Manifest {
pub version: String,
pub protocol: u64,
#[serde(default)]
pub platforms: HashMap<String, Package>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct Package {
pub url: String,
pub bytes: u64,
pub sha256: String,
}
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct Marker {
version: String,
sha256: String,
installed_at: u64,
}
/// What the interface shows about the engine.
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Status {
/// `installed`, `missing`, `update`, `downloading`, `installing`, `unavailable`, or `development`.
pub state: String,
/// The engine version that this host needs.
pub version: String,
/// The download size in bytes.
pub bytes: u64,
pub received: u64,
pub error: Option<String>,
}
#[derive(Default)]
pub struct EngineState {
job: Mutex<Job>,
}
#[derive(Default, Clone)]
struct Job {
phase: Option<&'static str>,
received: u64,
error: Option<String>,
cancel: Arc<AtomicBool>,
}
enum Source {
Download,
File(PathBuf),
}
pub fn platform() -> String {
format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
}
pub fn executable_name() -> &'static str {
if cfg!(windows) {
"RuneStone-Browser.exe"
} else if cfg!(target_os = "macos") {
"RuneStone-Browser.app/Contents/MacOS/RuneStone-Browser"
} else {
"RuneStone-Browser"
}
}
fn valid_version(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 40
&& value.as_bytes()[0].is_ascii_digit()
&& value.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.')
&& !value.contains("..")
}
fn parse(text: &str) -> Result<Manifest> {
let manifest: Manifest = serde_json::from_str(text).map_err(|error| format!("The browser engine manifest is invalid: {error}"))?;
if !valid_version(&manifest.version) {
return Err("The browser engine manifest has an invalid version.".into());
}
// An engine of another protocol would fail at its first start. Refuse its pin before the download.
if manifest.protocol != PROTOCOL {
return Err("The browser engine manifest names another engine protocol.".into());
}
for package in manifest.platforms.values() {
let hex = package.sha256.len() == 64 && package.sha256.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c));
if !hex || package.bytes == 0 || Url::parse(&package.url).is_err() {
return Err("The browser engine manifest has an invalid package.".into());
}
}
Ok(manifest)
}
/// The manifest file of a native test. Only debug builds read it.
fn override_path() -> Option<PathBuf> {
if cfg!(debug_assertions) {
std::env::var_os("RUNESTONE_BROWSER_ENGINE_MANIFEST").map(PathBuf::from)
} else {
None
}
}
fn manifest() -> Result<Manifest> {
match override_path() {
Some(path) => parse(&fs::read_to_string(path)?),
None => parse(PINNED),
}
}
fn engines(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_local_data_dir()?.join("browser-engine"))
}
/// The engine that `pnpm browser:stage` puts in `src-tauri/browser-engine` for `pnpm tauri dev`.
/// A manifest override turns it off, so that a native test uses the download.
fn development_engine() -> Option<PathBuf> {
if !cfg!(debug_assertions) || override_path().is_some() {
return None;
}
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("browser-engine").join(executable_name());
path.is_file().then_some(path)
}
/// The installed engine that matches the pin, if any.
fn installed(root: &Path, manifest: &Manifest) -> Option<PathBuf> {
let package = manifest.platforms.get(&platform())?;
let folder = root.join(&manifest.version);
let marker: Marker = serde_json::from_slice(&fs::read(folder.join(MARKER)).ok()?).ok()?;
let executable = folder.join(executable_name());
(marker.version == manifest.version && marker.sha256 == package.sha256 && executable.is_file()).then_some(executable)
}
/// Version folders with a complete installation, also for other versions.
fn installed_versions(root: &Path) -> Vec<String> {
let Ok(entries) = fs::read_dir(root) else { return Vec::new() };
entries
.filter_map(|entry| entry.ok())
.filter(|entry| entry.path().join(MARKER).is_file())
.filter_map(|entry| entry.file_name().into_string().ok())
.collect()
}
/// The engine executable to start.
pub fn executable(app: &AppHandle) -> Result<PathBuf> {
if let Some(path) = development_engine() {
return Ok(path);
}
let manifest = manifest()?;
installed(&engines(app)?, &manifest).ok_or_else(|| "The browser engine is not installed.".into())
}
fn describe(manifest: &Result<Manifest>, root: &Path, job: &Job, development: bool) -> Status {
let manifest = match manifest {
Ok(manifest) => manifest,
Err(error) => return Status { state: "unavailable".into(), error: Some(error.to_string()), ..Status::default() },
};
let base = Status { version: manifest.version.clone(), received: job.received, error: job.error.clone(), ..Status::default() };
if development {
return Status { state: "development".into(), ..base };
}
let Some(package) = manifest.platforms.get(&platform()) else {
return Status { state: "unavailable".into(), ..base };
};
let state = match job.phase {
Some(phase) => phase,
None if installed(root, manifest).is_some() => "installed",
None if !installed_versions(root).is_empty() => "update",
None => "missing",
};
Status { state: state.into(), bytes: package.bytes, ..base }
}
fn status(app: &AppHandle) -> Result<Status> {
let job = app.state::<EngineState>().job.lock()?.clone();
Ok(describe(&manifest(), &engines(app)?, &job, development_engine().is_some()))
}
fn publish(app: &AppHandle) {
if let Ok(status) = status(app) {
let _ = app.emit("browser-engine", &status);
}
}
/// A redirect may not leave HTTPS. A native test can allow HTTP for its local server.
fn allowed(url: &Url, allow_http: bool) -> bool {
url.scheme() == "https" || (allow_http && url.scheme() == "http")
}
/// Download `package` to `target` and make sure that its size and SHA-256 match.
/// `target` must not exist. On failure, the function removes it.
fn download(package: &Package, target: &Path, allow_http: bool, cancel: &AtomicBool, report: &mut dyn FnMut(u64)) -> Result<()> {
let url = Url::parse(&package.url).map_err(|_| "The browser engine link is invalid.")?;
if !allowed(&url, allow_http) {
return Err("The browser engine link must use HTTPS.".into());
}
let client = Client::builder()
.user_agent("RuneStone-browser-engine/1")
.connect_timeout(Duration::from_secs(15))
// A limit for each read, not for the whole download.
.timeout(Duration::from_secs(60))
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 5 {
attempt.error("The download server redirected too many times.")
} else if !allowed(attempt.url(), allow_http) {
attempt.error("The download server redirected away from HTTPS.")
} else {
attempt.follow()
}
}))
.build()
.map_err(|_| "Cannot start the download client.")?;
let result = (|| -> Result<()> {
let mut response = client.get(url).send().map_err(|error| format!("Cannot reach the download server: {error}"))?;
if !response.status().is_success() {
return Err(format!("The download server answered {}.", response.status()).into());
}
if response.content_length().is_some_and(|length| length != package.bytes) {
return Err("The download does not have the expected size.".into());
}
let mut file = fs::File::options().write(true).create_new(true).open(target)?;
let (mut hasher, mut received, mut buffer) = (Sha256::new(), 0u64, vec![0; 256 * 1024]);
loop {
if cancel.load(Ordering::Relaxed) {
return Err(CANCELLED.into());
}
let read = response.read(&mut buffer).map_err(|error| format!("The download stopped: {error}"))?;
if read == 0 {
break;
}
received += read as u64;
if received > package.bytes {
return Err("The download is larger than expected.".into());
}
hasher.update(&buffer[..read]);
file.write_all(&buffer[..read])?;
report(received);
}
if received != package.bytes {
return Err("The download is incomplete.".into());
}
if format!("{:x}", hasher.finalize()) != package.sha256 {
return Err("The download does not match the expected SHA-256 hash.".into());
}
Ok(file.sync_all()?)
})();
if result.is_err() {
let _ = fs::remove_file(target);
}
result
}
/// Make sure that a local ZIP has the size and SHA-256 of the pin.
fn verify_file(path: &Path, package: &Package, cancel: &AtomicBool) -> Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.len() != package.bytes {
return Err("This file is not the browser engine that this RuneStone version needs. Its size is different.".into());
}
let (mut file, mut hasher, mut buffer) = (fs::File::open(path)?, Sha256::new(), vec![0; 256 * 1024]);
loop {
if cancel.load(Ordering::Relaxed) {
return Err(CANCELLED.into());
}
let read = file.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
if format!("{:x}", hasher.finalize()) != package.sha256 {
return Err("This file is not the browser engine that this RuneStone version needs. Its SHA-256 hash is different.".into());
}
Ok(())
}
fn valid_component(name: &str) -> bool {
crate::fsutil::is_plain_component(name)
&& name.len() <= 120
&& !name.starts_with(' ')
&& !name.ends_with(' ')
&& name.bytes().all(|c| c.is_ascii_alphanumeric() || b" ._+-".contains(&c))
}
/// Extract an engine ZIP into the new folder `target`. Refuse unsafe paths, links, and archives over `limit` bytes.
fn extract(archive: &Path, target: &Path, limit: u64) -> Result<()> {
let mut archive = zip::ZipArchive::new(fs::File::open(archive)?).map_err(|_| "The browser engine archive is not a valid ZIP file.")?;
if archive.len() > MAX_ENTRIES {
return Err("The browser engine archive contains too many entries.".into());
}
fs::create_dir(target)?;
let (mut names, mut total) = (BTreeSet::new(), 0u64);
for index in 0..archive.len() {
let mut file = archive.by_index(index)?;
let name = std::str::from_utf8(file.name_raw())?.trim_end_matches('/').to_string();
let parts: Vec<&str> = name.split('/').collect();
if parts.len() > 16 || !parts.iter().all(|part| valid_component(part)) {
return Err(format!("The browser engine archive contains an invalid path: {name}").into());
}
if !names.insert(name.to_ascii_lowercase()) {
return Err("The browser engine archive contains duplicate paths.".into());
}
let kind = file.unix_mode().map(|mode| mode & 0o170000);
if kind.is_some_and(|kind| kind != 0 && kind != 0o100000 && kind != 0o040000) || file.is_symlink() {
return Err("The browser engine archive contains links or special files.".into());
}
let path: PathBuf = parts.iter().fold(target.to_path_buf(), |path, part| path.join(part));
if file.is_dir() {
fs::create_dir_all(&path)?;
continue;
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let remaining = limit.saturating_sub(total);
let mut output = fs::File::options().write(true).create_new(true).open(&path)?;
let written = std::io::copy(&mut file.by_ref().take(remaining.saturating_add(1)), &mut output)?;
total += written;
if written > remaining {
return Err("The browser engine archive is too large.".into());
}
#[cfg(unix)]
if let Some(mode) = file.unix_mode() {
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(mode & 0o755))?;
}
}
if !target.join(executable_name()).is_file() {
return Err("The browser engine archive does not contain the engine program.".into());
}
Ok(())
}
/// Extract a verified archive and put it in the version folder of the pin.
fn install_archive(archive: &Path, root: &Path, manifest: &Manifest, package: &Package) -> Result<()> {
let work = root.join(WORK);
fs::create_dir_all(&work)?;
let staged = work.join(format!("extract-{}", uuid::Uuid::new_v4().simple()));
let result = (|| -> Result<()> {
extract(archive, &staged, MAX_EXTRACTED)?;
let installed_at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|time| time.as_millis() as u64).unwrap_or(0);
let marker = Marker { version: manifest.version.clone(), sha256: package.sha256.clone(), installed_at };
fs::write(staged.join(MARKER), serde_json::to_vec_pretty(&marker)?)?;
let target = root.join(&manifest.version);
// A folder without a valid marker is an incomplete earlier attempt. No engine runs from it.
if fs::symlink_metadata(&target).is_ok() {
fs::remove_dir_all(&target)?;
}
Ok(fs::rename(&staged, &target)?)
})();
if result.is_err() {
let _ = fs::remove_dir_all(&staged);
}
result
}
/// Remove the other version folders and the work folder. No engine runs from them.
fn remove_others(root: &Path, keep: &str) {
let Ok(entries) = fs::read_dir(root) else { return };
for entry in entries.filter_map(|entry| entry.ok()) {
if entry.file_name() != keep {
let _ = fs::remove_dir_all(entry.path());
}
}
}
/// Windows can keep the program file locked for a moment after the engine stops.
fn remove_with_retries(path: &Path) -> Result<()> {
for attempt in 0.. {
match fs::remove_dir_all(path) {
Ok(()) => return Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(_) if attempt < 10 => std::thread::sleep(Duration::from_millis(200)),
Err(error) => return Err(format!("Cannot remove the browser engine: {error}").into()),
}
}
unreachable!()
}
fn run(app: &AppHandle, source: Source, cancel: &AtomicBool) -> Result<()> {
let manifest = manifest()?;
let package = manifest.platforms.get(&platform()).cloned().ok_or("No browser engine is available for this platform.")?;
let root = engines(app)?;
if installed(&root, &manifest).is_some() {
return Ok(());
}
let work = root.join(WORK);
let _ = fs::remove_dir_all(&work);
fs::create_dir_all(&work)?;
let archive = match source {
Source::Download => {
let file = work.join("engine.zip");
let mut last = Instant::now();
download(&package, &file, override_path().is_some(), cancel, &mut |received| {
if last.elapsed() >= Duration::from_millis(250) || received == package.bytes {
last = Instant::now();
if let Ok(mut job) = app.state::<EngineState>().job.lock() { job.received = received; }
publish(app);
}
})?;
file
}
Source::File(path) => {
verify_file(&path, &package, cancel)?;
path
}
};
app.state::<EngineState>().job.lock()?.phase = Some("installing");
publish(app);
install_archive(&archive, &root, &manifest, &package)?;
remove_others(&root, &manifest.version);
Ok(())
}
fn start(app: &AppHandle, source: Source) -> Result<Status> {
let state = app.state::<EngineState>();
let cancel = {
let mut job = state.job.lock()?;
// One download at a time. A second request gets the status of the first.
if job.phase.is_none() {
let phase = if matches!(source, Source::Download) { "downloading" } else { "installing" };
*job = Job { phase: Some(phase), ..Job::default() };
Some(job.cancel.clone())
} else {
None
}
};
if let Some(cancel) = cancel {
let handle = app.clone();
std::thread::Builder::new().name("browser-engine".into()).spawn(move || {
let result = run(&handle, source, &cancel);
if let Ok(mut job) = handle.state::<EngineState>().job.lock() {
job.phase = None;
job.error = result.err().map(|error| error.to_string()).filter(|error| error != CANCELLED);
}
publish(&handle);
})?;
}
publish(app);
status(app)
}
#[tauri::command]
pub async fn browser_engine_status(app: AppHandle) -> Result<Status> {
tauri::async_runtime::spawn_blocking(move || status(&app)).await?
}
#[tauri::command]
pub async fn browser_engine_install(app: AppHandle) -> Result<Status> {
tauri::async_runtime::spawn_blocking(move || start(&app, Source::Download)).await?
}
#[tauri::command]
pub async fn browser_engine_install_file(app: AppHandle) -> Result<Status> {
tauri::async_runtime::spawn_blocking(move || {
let chosen = app.dialog().file().set_title("Install the browser engine").add_filter("Browser engine ZIP", &["zip"]).blocking_pick_file();
match chosen {
Some(path) => start(&app, Source::File(path.into_path().map_err(Error::from_display)?)),
None => status(&app),
}
})
.await?
}
#[tauri::command]
pub async fn browser_engine_cancel(app: AppHandle) -> Result<Status> {
tauri::async_runtime::spawn_blocking(move || {
app.state::<EngineState>().job.lock()?.cancel.store(true, Ordering::Relaxed);
status(&app)
})
.await?
}
/// Stop the engine and remove all engine versions. The browser profiles stay.
#[tauri::command]
pub async fn browser_engine_remove(app: AppHandle) -> Result<Status> {
tauri::async_runtime::spawn_blocking(move || {
if app.state::<EngineState>().job.lock()?.phase.is_some() {
return Err("Wait until the browser engine installation ends.".into());
}
// The windows keep their sessions, so that their tabs can start a newly installed engine.
app.state::<crate::browser::BrowserState>().stop_engine();
remove_with_retries(&engines(&app)?)?;
publish(&app);
status(&app)
})
.await?
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plugin_sources::tests::server;
fn base() -> PathBuf {
let path = std::env::temp_dir().join(format!("runestone-engine-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&path).unwrap();
path
}
fn zip(path: &Path, entries: &[(&str, &[u8])]) -> Vec<u8> {
let mut writer = zip::ZipWriter::new(fs::File::create(path).unwrap());
for (name, data) in entries {
writer.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(data).unwrap();
}
writer.finish().unwrap();
fs::read(path).unwrap()
}
fn package(url: &str, bytes: &[u8]) -> Package {
Package { url: url.into(), bytes: bytes.len() as u64, sha256: format!("{:x}", Sha256::digest(bytes)) }
}
fn manifest(version: &str, package: Package) -> Manifest {
Manifest { version: version.into(), protocol: PROTOCOL, platforms: HashMap::from([(platform(), package)]) }
}
fn engine_files() -> Vec<(&'static str, &'static [u8])> {
vec![(executable_name(), b"engine"), ("locales/en-US.pak", b"strings"), ("resources/app.asar", b"app")]
}
#[test]
fn the_pinned_manifest_parses_and_invalid_manifests_fail() {
let pinned = parse(PINNED).unwrap();
assert_eq!(pinned.protocol, PROTOCOL);
for text in [
r#"{"version":"../1","protocol":1}"#,
r#"{"version":"0.1.8","protocol":1,"platforms":{"windows-x86_64":{"url":"x","bytes":1,"sha256":"00"}}}"#,
r#"{"version":"0.1.8","protocol":1,"extra":true}"#,
r#"{"version":"0.1.8","protocol":2}"#,
] {
assert!(parse(text).is_err(), "{text}");
}
}
#[test]
fn download_checks_size_hash_scheme_and_cancel() {
let root = base();
let bytes = b"engine archive".to_vec();
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
let target = root.join("engine.zip");
let mut reports = Vec::new();
download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |received| reports.push(received)).unwrap();
assert_eq!(fs::read(&target).unwrap(), bytes);
assert_eq!(reports.last(), Some(&(bytes.len() as u64)));
handle.join().unwrap();
fs::remove_file(&target).unwrap();
let (url, handle) = server(vec![("200 OK".into(), b"engine archivX".to_vec())]);
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
assert!(error.to_string().contains("SHA-256"), "{error}");
assert!(!target.exists(), "A failed download leaves no file.");
handle.join().unwrap();
let (url, handle) = server(vec![("200 OK".into(), b"engine".to_vec())]);
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
assert!(error.to_string().contains("expected size"), "{error}");
handle.join().unwrap();
let (url, handle) = server(vec![("404 Not Found".into(), Vec::new())]);
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
assert!(error.to_string().contains("404"), "{error}");
handle.join().unwrap();
let (url, handle) = server(vec![("200 OK".into(), bytes.clone())]);
let error = download(&package(&format!("{url}/engine.zip"), &bytes), &target, true, &AtomicBool::new(true), &mut |_| {}).unwrap_err();
assert_eq!(error.to_string(), CANCELLED);
assert!(!target.exists());
handle.join().unwrap();
let error = download(&package("http://127.0.0.1:9/engine.zip", &bytes), &target, false, &AtomicBool::new(false), &mut |_| {}).unwrap_err();
assert!(error.to_string().contains("HTTPS"), "{error}");
assert!(allowed(&Url::parse("https://example.com").unwrap(), false));
assert!(!allowed(&Url::parse("http://example.com").unwrap(), false));
assert!(!allowed(&Url::parse("file:///C:/engine.zip").unwrap(), true));
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn redirects_must_stay_on_an_allowed_scheme() {
let bytes = b"engine archive".to_vec();
let (target, target_server) = server(vec![("200 OK".into(), bytes.clone())]);
let (origin, origin_server) = server(vec![(format!("302 Found\r\nLocation: {target}/engine.zip"), Vec::new())]);
let root = base();
let file = root.join("engine.zip");
download(&package(&format!("{origin}/engine.zip"), &bytes), &file, true, &AtomicBool::new(false), &mut |_| {}).unwrap();
assert_eq!(fs::read(&file).unwrap(), bytes);
origin_server.join().unwrap();
target_server.join().unwrap();
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn extraction_refuses_unsafe_archives() {
let root = base();
let good = root.join("good.zip");
zip(&good, &engine_files());
extract(&good, &root.join("good"), MAX_EXTRACTED).unwrap();
assert_eq!(fs::read(root.join("good").join("locales").join("en-US.pak")).unwrap(), b"strings");
for (index, name) in ["../evil.txt", "/absolute.txt", "a\\b.txt", "C:evil.txt", "locales/../../evil.txt", "NUL", "con.txt"].iter().enumerate() {
let archive = root.join(format!("bad-{index}.zip"));
let mut entries = engine_files();
entries.push((name, b"evil"));
zip(&archive, &entries);
assert!(extract(&archive, &root.join(format!("bad-{index}")), MAX_EXTRACTED).is_err(), "{name}");
}
assert!(!root.join("evil.txt").exists() && !root.parent().unwrap().join("evil.txt").exists());
let duplicate = root.join("duplicate.zip");
zip(&duplicate, &[(executable_name(), b"a"), ("Locales/A.pak", b"a"), ("locales/a.pak", b"b")]);
assert!(extract(&duplicate, &root.join("duplicate"), MAX_EXTRACTED).unwrap_err().to_string().contains("duplicate"));
let missing = root.join("missing.zip");
zip(&missing, &[("locales/en-US.pak", b"strings")]);
assert!(extract(&missing, &root.join("missing"), MAX_EXTRACTED).unwrap_err().to_string().contains("engine program"));
assert!(extract(&good, &root.join("small"), 8).unwrap_err().to_string().contains("too large"));
let link = root.join("link.zip");
let mut writer = zip::ZipWriter::new(fs::File::create(&link).unwrap());
writer.start_file(executable_name(), zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(b"engine").unwrap();
writer.add_symlink("resources", "../../outside", zip::write::SimpleFileOptions::default()).unwrap();
writer.finish().unwrap();
assert!(extract(&link, &root.join("link"), MAX_EXTRACTED).unwrap_err().to_string().contains("links"));
fs::write(root.join("not-a-zip.zip"), b"text").unwrap();
assert!(extract(&root.join("not-a-zip.zip"), &root.join("text"), MAX_EXTRACTED).is_err());
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn installation_marks_the_pinned_version_and_removes_older_ones() {
let root = base();
let engines = root.join("browser-engine");
let first = root.join("first.zip");
let bytes = zip(&first, &engine_files());
let old = manifest("0.1.7", package("https://example.com/first.zip", &bytes));
install_archive(&first, &engines, &old, &old.platforms[&platform()]).unwrap();
assert_eq!(installed(&engines, &old), Some(engines.join("0.1.7").join(executable_name())));
// Another pin with a different hash does not accept this folder.
let other = manifest("0.1.7", package("https://example.com/first.zip", b"other"));
assert_eq!(installed(&engines, &other), None);
let second = root.join("second.zip");
let mut entries = engine_files();
entries.push(("version", b"0.1.8"));
let bytes = zip(&second, &entries);
let new = manifest("0.1.8", package("https://example.com/second.zip", &bytes));
let job = Job::default();
assert_eq!(describe(&Ok(new.clone()), &engines, &job, false).state, "update");
verify_file(&second, &new.platforms[&platform()], &AtomicBool::new(false)).unwrap();
assert!(verify_file(&first, &new.platforms[&platform()], &AtomicBool::new(false)).is_err());
install_archive(&second, &engines, &new, &new.platforms[&platform()]).unwrap();
remove_others(&engines, &new.version);
assert!(installed(&engines, &new).is_some());
assert_eq!(installed_versions(&engines), vec!["0.1.8".to_string()]);
assert_eq!(fs::read_dir(&engines).unwrap().count(), 1, "No work folder or old version stays.");
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn status_names_each_engine_state() {
let root = base();
let bytes = b"engine".to_vec();
let pin = manifest("0.1.8", package("https://example.com/engine.zip", &bytes));
let idle = Job::default();
let state = |manifest: &Result<Manifest>, job: &Job, development: bool| describe(manifest, &root, job, development).state;
assert_eq!(state(&Ok(pin.clone()), &idle, false), "missing");
assert_eq!(describe(&Ok(pin.clone()), &root, &idle, false).bytes, bytes.len() as u64);
assert_eq!(state(&Ok(pin.clone()), &idle, true), "development");
let downloading = Job { phase: Some("downloading"), received: 3, ..Job::default() };
assert_eq!(describe(&Ok(pin.clone()), &root, &downloading, false), Status { state: "downloading".into(), version: "0.1.8".into(), bytes: 6, received: 3, error: None });
let failed = Job { error: Some("The download stopped.".into()), ..Job::default() };
assert_eq!(describe(&Ok(pin.clone()), &root, &failed, false).error.as_deref(), Some("The download stopped."));
let elsewhere = Manifest { platforms: HashMap::new(), ..pin.clone() };
assert_eq!(state(&Ok(elsewhere), &idle, false), "unavailable");
assert_eq!(state(&Err("broken".into()), &idle, false), "unavailable");
fs::remove_dir_all(&root).unwrap();
}
}
+83
View File
@@ -0,0 +1,83 @@
use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration};
use reqwest::{blocking::Client, Url};
use serde::Deserialize;
use tauri::{ipc::Channel, State, WebviewWindow};
use crate::error::Result;
#[derive(Default)]
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
impl CompletionState {
pub fn close_window(&self, window: &str) {
if let Ok(mut requests) = self.requests.lock() {
requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } });
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletionRequest { endpoint: String, route: String, body: Option<String>, timeout_ms: Option<u64> }
fn target(endpoint: &str, route: &str) -> Result<Url> {
let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?;
if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|| !matches!(url.path(), "" | "/" | "/v1" | "/v1/") {
return Err("This trial connects only to a loopback model server.".into());
}
if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); }
if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; }
url.set_path(route); Ok(url)
}
#[tauri::command]
pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) {
if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } }
}
#[tauri::command]
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<()> {
if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); }
let url = target(&request.endpoint, &request.route)?;
let flag = Arc::new(AtomicBool::new(false));
let key = format!("{}:{id}", window.label());
{
let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?;
if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); }
requests.insert(key.clone(), flag.clone());
}
let result = tauri::async_runtime::spawn_blocking(move || -> Result<()> {
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000)))
.build().map_err(|_| "Could not create a local connection.")?;
if flag.load(Ordering::Relaxed) { return Ok(()); }
let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) };
let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." })?;
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16()).into()); }
let mut reader = BufReader::new(response);
let mut total = 0;
loop {
if flag.load(Ordering::Relaxed) { return Ok(()); }
let mut bytes = Vec::new();
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.")?;
if count == 0 { break; }
total += count;
if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); }
if flag.load(Ordering::Relaxed) { return Ok(()); }
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.")?;
if on_line.send(line).is_err() { break; }
}
Ok(())
}).await.map_err(|_| "Local completion task stopped.");
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
result?
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_loopback_and_fixed_routes() {
assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models");
for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] {
assert!(target(address, "/v1/models").is_err(), "{address}");
}
assert!(target("http://127.0.0.1:8080", "/shutdown").is_err());
}
}
+113
View File
@@ -0,0 +1,113 @@
//! The one error type of the host.
//!
//! An error is a message for the user. It crosses IPC as a plain JSON string,
//! so the frontend and the plugins receive the same text as before this type existed.
//! Every conversion keeps the `Display` text of its source error without changes.
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);
pub type Result<T, E = Error> = std::result::Result<T, E>;
impl Error {
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
/// Use the text of a value that has no `From` conversion, such as an error of an indirect dependency.
pub fn from_display(error: impl fmt::Display) -> Self {
Self(error.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
}
}
impl serde::Serialize for Error {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl From<String> for Error {
fn from(message: String) -> Self {
Self(message)
}
}
impl From<&str> for Error {
fn from(message: &str) -> Self {
Self(message.to_owned())
}
}
impl From<Error> for String {
fn from(error: Error) -> Self {
error.0
}
}
impl<T> From<std::sync::PoisonError<T>> for Error {
fn from(error: std::sync::PoisonError<T>) -> Self {
Self(error.to_string())
}
}
macro_rules! from_display {
($($source:ty),* $(,)?) => {
$(impl From<$source> for Error {
fn from(error: $source) -> Self {
Self(error.to_string())
}
})*
};
}
from_display!(
std::io::Error,
std::path::StripPrefixError,
std::str::Utf8Error,
std::string::FromUtf8Error,
std::sync::mpsc::RecvError,
std::time::SystemTimeError,
serde_json::Error,
notify::Error,
tauri::Error,
tauri_plugin_opener::Error,
uuid::Error,
zip::result::ZipError,
);
#[cfg(windows)]
from_display!(windows::core::Error);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serializes_as_the_plain_message() {
let error = Error::new("Save blocked: file changed on disk.");
assert_eq!(serde_json::to_string(&error).unwrap(), r#""Save blocked: file changed on disk.""#);
assert_eq!(
serde_json::to_value(Err::<(), _>(error.clone())).unwrap(),
serde_json::to_value(Err::<(), _>("Save blocked: file changed on disk.")).unwrap(),
);
assert_eq!(error.to_string(), "Save blocked: file changed on disk.");
}
#[test]
fn conversions_keep_the_source_text() {
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing file");
assert_eq!(Error::from(io).to_string(), "missing file");
let json = serde_json::from_str::<serde_json::Value>("{").unwrap_err();
assert_eq!(Error::from(json.to_string()), Error::from(json));
assert_eq!(Error::from("text"), Error::new(String::from("text")));
assert_eq!(String::from(Error::from_display(42)), "42");
}
}
+49
View File
@@ -0,0 +1,49 @@
//! The old plugin packages of the native features. The frontend reads them one time for each feature,
//! when the `features` settings section has no switch for it (`src/lib/features/migration.ts`).
//! Nothing here changes plugin files.
use tauri::AppHandle;
use crate::error::{Error, Result};
use crate::plugins::{legacy_packages, LegacyPackage};
/// The packages that native features replace. A request for another ID fails.
pub const LEGACY_PACKAGES: [&str; 5] = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm"];
fn check(ids: &[String]) -> Result<()> {
if ids.len() > LEGACY_PACKAGES.len() {
return Err(Error::new("Too many feature packages."));
}
match ids.iter().find(|id| !LEGACY_PACKAGES.contains(&id.as_str())) {
Some(id) => Err(Error::new(format!("Unknown feature package: {id}"))),
None => Ok(()),
}
}
#[tauri::command]
pub async fn features_legacy(app: AppHandle, ids: Vec<String>) -> Result<Vec<LegacyPackage>> {
check(&ids)?;
legacy_packages(&app, ids).await
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_packages_of_native_features_are_read() {
assert!(check(&["runestone.git".into()]).is_ok());
assert!(check(&["runestone.git".into(), "runestone.bg-slideshow".into()]).is_ok());
assert!(check(&["runestone.terminal".into()]).is_ok());
assert!(check(&["runestone.pdf-viewer".into()]).is_ok());
assert!(check(&["runestone.pm".into()]).is_ok());
assert!(check(&LEGACY_PACKAGES.map(String::from)).is_ok());
assert!(check(&[]).is_ok());
for id in ["runestone.csv-viewer", "../plugin-state", "runestone.git/..", ""] {
assert!(check(&[id.into()]).is_err(), "{id}");
}
let too_many = ["runestone.git", "runestone.bg-slideshow", "runestone.terminal", "runestone.pdf-viewer", "runestone.pm", "runestone.git"].map(String::from);
assert!(too_many.len() > LEGACY_PACKAGES.len());
assert!(check(&too_many).is_err());
}
}
+560
View File
@@ -0,0 +1,560 @@
//! Folder grants for plugins.
//!
//! A plugin gets access to a folder outside the workspace only through a grant. The user makes a
//! grant with the folder picker, or the host makes one for a `RuneStone <name>` folder in Pictures.
//! Each plugin has its own grant list in its retained data (`plugin-data/<id>/folder-grants.json`).
//! A grant gives access to the ordinary files directly in its folder. Names with folder parts,
//! links, and files that resolve outside the folder are rejected. The plugin cannot supply a path.
use crate::error::{Error, Result};
use crate::fsutil::{self, is_link};
use crate::plugins::PluginState;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
const GRANTS_FILE: &str = "folder-grants.json";
const GRANT_LIMIT: usize = 64;
pub(crate) const READ_LIMIT: u64 = 64 * 1024 * 1024;
pub(crate) const SIDECAR_LIMIT: u64 = 1024 * 1024;
pub(crate) const LIST_LIMIT: usize = 10_000;
/// Serializes changes to grant files and sidecar files.
static LOCK: Mutex<()> = Mutex::new(());
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
struct StoredGrant {
id: String,
path: PathBuf,
}
#[derive(Debug, Default, Serialize, Deserialize)]
struct GrantFile {
schema: u32,
grants: Vec<StoredGrant>,
}
/// What a plugin receives: an opaque ID and the folder path for display.
#[derive(Clone, Debug, Serialize, PartialEq)]
pub struct FolderGrant {
id: String,
path: String,
name: String,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct FolderEntry {
pub(crate) name: String,
size: u64,
}
impl From<&StoredGrant> for FolderGrant {
fn from(grant: &StoredGrant) -> Self {
Self {
id: grant.id.clone(),
path: grant.path.to_string_lossy().into_owned(),
name: grant
.path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| grant.path.to_string_lossy().into_owned()),
}
}
}
/// The grant lists of all plugins, in the folder that holds the retained plugin data.
struct Grants {
data: PathBuf,
}
impl Grants {
fn plugin_folder(&self, plugin: &str, create: bool) -> Result<PathBuf> {
if plugin.is_empty()
|| plugin.len() > 128
|| !plugin.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
|| !fsutil::is_plain_component(plugin)
{
return Err("Invalid plugin ID.".into());
}
let folder = self.data.join(plugin);
match fs::symlink_metadata(&folder) {
Ok(metadata) if metadata.is_dir() && !is_link(&metadata) => Ok(folder),
Ok(_) => Err("The plugin data folder must be an ordinary folder.".into()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => {
fs::create_dir(&folder)?;
Ok(folder)
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(folder),
Err(error) => Err(error.into()),
}
}
fn load(&self, plugin: &str) -> Result<Vec<StoredGrant>> {
let path = self.plugin_folder(plugin, false)?.join(GRANTS_FILE);
let metadata = match fs::symlink_metadata(&path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
if !metadata.is_file() || is_link(&metadata) {
return Err("The folder grant list must be an ordinary file.".into());
}
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(&path)?, SIDECAR_LIMIT)? else {
return Err("The folder grant list exceeds 1 MiB.".into());
};
let file: GrantFile = serde_json::from_slice(&bytes)?;
if file.schema != 1 {
return Err("Unknown folder grant list schema.".into());
}
Ok(file.grants)
}
fn save(&self, plugin: &str, grants: Vec<StoredGrant>) -> Result<()> {
let folder = self.plugin_folder(plugin, true)?;
let bytes = serde_json::to_vec_pretty(&GrantFile { schema: 1, grants })?;
let temp = folder.join(format!("{GRANTS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::replace_file(&folder.join(GRANTS_FILE), &temp, &bytes)?)
}
/// Grant `folder` to `plugin`. Return the existing grant when the plugin already has the folder.
fn add(&self, plugin: &str, folder: &Path) -> Result<FolderGrant> {
let path = granted_root(folder)?;
let _lock = LOCK.lock()?;
let mut grants = self.load(plugin)?;
if let Some(existing) = grants.iter().find(|grant| grant.path == path) {
return Ok(existing.into());
}
if grants.len() >= GRANT_LIMIT {
return Err(format!("A plugin can keep at most {GRANT_LIMIT} folder grants. Remove a grant first.").into());
}
let grant = StoredGrant { id: uuid::Uuid::new_v4().to_string(), path };
let result = FolderGrant::from(&grant);
grants.push(grant);
self.save(plugin, grants)?;
Ok(result)
}
fn list(&self, plugin: &str) -> Result<Vec<FolderGrant>> {
Ok(self.load(plugin)?.iter().map(FolderGrant::from).collect())
}
fn revoke(&self, plugin: &str, id: &str) -> Result<bool> {
let _lock = LOCK.lock()?;
let mut grants = self.load(plugin)?;
let count = grants.len();
grants.retain(|grant| grant.id != id);
if grants.len() == count {
return Ok(false);
}
self.save(plugin, grants)?;
Ok(true)
}
/// Return the folder of a grant of this plugin. The folder must still be an ordinary folder
/// at the same resolved path, so a folder that became a link does not redirect access.
fn resolve(&self, plugin: &str, id: &str) -> Result<PathBuf> {
uuid::Uuid::parse_str(id).map_err(|_| Error::new("Invalid folder grant."))?;
let grant = self
.load(plugin)?
.into_iter()
.find(|grant| grant.id == id)
.ok_or_else(|| Error::new("This plugin has no grant for the folder. Choose the folder again."))?;
let metadata = fs::symlink_metadata(&grant.path)
.map_err(|_| Error::new("The granted folder is missing. Choose the folder again."))?;
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&grant.path)? != grant.path {
return Err("The granted folder changed into a link or a file. Choose the folder again.".into());
}
Ok(grant.path)
}
}
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
pub(crate) fn granted_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
return Err("Supply an absolute folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder)?;
if !root.is_dir() {
return Err("The folder does not exist.".into());
}
if root.parent().is_none() {
return Err("Choose a folder, not a whole drive.".into());
}
Ok(root)
}
/// The path of one ordinary file directly in `root`.
fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
if !fsutil::is_plain_component(name)
|| name.contains(['/', '\\', ':'])
|| name.ends_with(' ')
|| Path::new(name).components().count() != 1
|| !matches!(Path::new(name).components().next(), Some(Component::Normal(_)))
{
return Err("Supply one file name without folder parts.".into());
}
Ok(root.join(name))
}
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
pub(crate) fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
}
let file = fsutil::open_entry(path)?;
let opened = file.metadata()?;
if !opened.is_file() || is_link(&opened) || dunce::canonicalize(path)?.parent() != Some(root) {
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
}
Ok((file, opened.len()))
}
pub(crate) fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
let mut entries = Vec::new();
for entry in fs::read_dir(root)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue };
let Ok(metadata) = entry.metadata() else { continue };
// `DirEntry::metadata` does not follow links.
if !metadata.is_file() || is_link(&metadata) || file_path(root, &name).is_err() {
continue;
}
entries.push(FolderEntry { name, size: metadata.len() });
if entries.len() > LIST_LIMIT {
return Err(format!("The folder has more than {LIST_LIMIT} files.").into());
}
}
entries.sort_by(|a, b| a.name.cmp(&b.name));
Ok(entries)
}
pub(crate) fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
let path = file_path(root, name)?;
let (file, size) = open_plain(root, &path)?;
if size > READ_LIMIT {
return Err("The file exceeds 64 MiB.".into());
}
fsutil::read_to_limit(file, READ_LIMIT)?.ok_or_else(|| Error::new("The file exceeds 64 MiB."))
}
/// A sidecar is a small JSON file that a plugin keeps beside the user's files, such as
/// `.runestone-backgrounds.json`. Its name starts with `.runestone-` and ends with `.json`.
fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
let stem = name.strip_prefix(".runestone-").and_then(|rest| rest.strip_suffix(".json"));
if !stem.is_some_and(|stem| !stem.is_empty() && stem.len() <= 64 && stem.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')) {
return Err("A sidecar file name has the form .runestone-<name>.json.".into());
}
file_path(root, name)
}
pub(crate) fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
let path = sidecar_path(root, name)?;
match fs::symlink_metadata(&path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
Ok(_) => {}
}
let (file, size) = open_plain(root, &path)?;
if size > SIDECAR_LIMIT {
return Err("The sidecar file exceeds 1 MiB.".into());
}
let bytes = fsutil::read_to_limit(file, SIDECAR_LIMIT)?.ok_or_else(|| Error::new("The sidecar file exceeds 1 MiB."))?;
String::from_utf8(bytes).map(Some).map_err(Error::from)
}
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
pub(crate) fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
let path = sidecar_path(root, name)?;
if contents.len() as u64 > SIDECAR_LIMIT {
return Err("The sidecar file exceeds 1 MiB.".into());
}
serde_json::from_str::<serde_json::Value>(contents)?;
let _lock = LOCK.lock()?;
if read_sidecar(root, name)?.as_deref() != expected {
return Err("The sidecar file changed. Read it again before you save.".into());
}
if expected.is_some() {
fsutil::write_text(&path, contents, expected)
} else {
let temp = root.join(format!(".runestone-sidecar-{}.tmp", uuid::Uuid::new_v4()));
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
}
}
/// The folder of one grant of `plugin` in the plugin data folder `data`, with the checks of a normal access.
/// The Background feature uses it to take the folder of the old Background Slideshow plugin. It changes no file.
pub(crate) fn plugin_grant(data: &Path, plugin: &str, id: &str) -> Result<PathBuf> {
Grants { data: data.to_path_buf() }.resolve(plugin, id)
}
fn grants(app: &AppHandle) -> Result<Grants> {
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
}
/// Accept only a plugin that is enabled and loaded in the calling window.
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
async fn check(app: &AppHandle, window: &Window, plugin: &str) -> Result<()> {
let (app, label, plugin) = (app.clone(), window.label().to_owned(), plugin.to_owned());
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().require_lease(&app, &label, &plugin)).await?
}
/// Check the lease, run `work` on a blocking worker, and check the lease again,
/// so that a plugin that stopped during the work receives no result.
async fn run<T: Send + 'static>(
app: &AppHandle,
window: &Window,
plugin: &str,
work: impl FnOnce(Grants) -> Result<T> + Send + 'static,
) -> Result<T> {
check(app, window, plugin).await?;
let store = grants(app)?;
let result = tauri::async_runtime::spawn_blocking(move || work(store)).await??;
check(app, window, plugin).await?;
Ok(result)
}
#[tauri::command]
pub async fn folders_choose(app: AppHandle, window: Window, plugin: String, title: Option<String>) -> Result<Option<FolderGrant>> {
check(&app, &window, &plugin).await?;
let (picker_app, picker_window) = (app.clone(), window.clone());
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose a folder".into());
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
})
.await?;
let Some(selected) = selected else { return Ok(None) };
let folder = selected.into_path().map_err(Error::from_display)?;
let id = plugin.clone();
run(&app, &window, &plugin, move |store| store.add(&id, &folder)).await.map(Some)
}
/// Grant `RuneStone <name>` in the Pictures folder of the user. Create the folder if necessary.
#[tauri::command]
pub async fn folders_picture(app: AppHandle, window: Window, plugin: String, name: String) -> Result<FolderGrant> {
if name.is_empty() || name.len() > 64 || name.starts_with([' ', '-', '_']) || !name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) || name.ends_with(' ') {
return Err("Supply a folder name with letters, digits, spaces, hyphens, or underscores.".into());
}
let folder = app.path().picture_dir()?.join(format!("RuneStone {name}"));
let id = plugin.clone();
run(&app, &window, &plugin, move |store| {
fs::create_dir_all(&folder)?;
let metadata = fs::symlink_metadata(&folder)?;
if !metadata.is_dir() || is_link(&metadata) {
return Err("The Pictures folder entry must be an ordinary folder.".into());
}
store.add(&id, &folder)
})
.await
}
#[tauri::command]
pub async fn folders_grants(app: AppHandle, window: Window, plugin: String) -> Result<Vec<FolderGrant>> {
let id = plugin.clone();
run(&app, &window, &plugin, move |store| store.list(&id)).await
}
#[tauri::command]
pub async fn folders_revoke(app: AppHandle, window: Window, plugin: String, grant: String) -> Result<bool> {
let id = plugin.clone();
run(&app, &window, &plugin, move |store| store.revoke(&id, &grant)).await
}
#[tauri::command]
pub async fn folders_list(app: AppHandle, window: Window, plugin: String, grant: String) -> Result<Vec<FolderEntry>> {
let id = plugin.clone();
run(&app, &window, &plugin, move |store| list_files(&store.resolve(&id, &grant)?)).await
}
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
#[tauri::command]
pub async fn folders_read(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result<tauri::ipc::Response> {
let id = plugin.clone();
let bytes = run(&app, &window, &plugin, move |store| read_file(&store.resolve(&id, &grant)?, &name)).await?;
Ok(tauri::ipc::Response::new(bytes))
}
#[tauri::command]
pub async fn folders_read_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result<Option<String>> {
let id = plugin.clone();
run(&app, &window, &plugin, move |store| read_sidecar(&store.resolve(&id, &grant)?, &name)).await
}
#[tauri::command]
pub async fn folders_write_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String, contents: String, expected: Option<String>) -> Result<()> {
check(&app, &window, &plugin).await?;
let store = grants(&app)?;
// Check the lease again immediately before the write, on the blocking worker.
tauri::async_runtime::spawn_blocking(move || {
app.state::<PluginState>().require_lease(&app, window.label(), &plugin)?;
write_sidecar(&store.resolve(&plugin, &grant)?, &name, &contents, expected.as_deref())
})
.await?
}
#[cfg(test)]
mod tests {
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir().join(format!("runestone-folders-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(dunce::canonicalize(root).unwrap())
}
fn folder(&self, name: &str) -> PathBuf {
let path = self.0.join(name);
fs::create_dir_all(&path).unwrap();
path
}
fn store(&self) -> Grants {
Grants { data: self.folder("plugin-data") }
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Make a link, or return `false` when Windows does not allow links for this user.
fn link(original: &Path, link: &Path, folder: bool) -> bool {
#[cfg(unix)]
{
let _ = folder;
std::os::unix::fs::symlink(original, link).unwrap();
true
}
#[cfg(windows)]
{
let result = if folder {
std::os::windows::fs::symlink_dir(original, link)
} else {
std::os::windows::fs::symlink_file(original, link)
};
match result {
Ok(()) => true,
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
false
}
Err(error) => panic!("{error}"),
}
}
}
#[test]
fn grants_persist_per_plugin_and_can_be_revoked() {
let fixture = Fixture::new();
let images = fixture.folder("images");
fs::write(images.join("a.png"), b"png").unwrap();
let store = fixture.store();
let grant = store.add("org.test.one", &images).unwrap();
assert_eq!(grant.path, images.to_string_lossy());
assert_eq!(grant.name, "images");
// The same folder gives the same grant.
assert_eq!(store.add("org.test.one", &images).unwrap().id, grant.id);
// A new store reads the saved grants, as after a restart.
let reopened = fixture.store();
assert_eq!(reopened.list("org.test.one").unwrap(), vec![grant.clone()]);
assert_eq!(read_file(&reopened.resolve("org.test.one", &grant.id).unwrap(), "a.png").unwrap(), b"png");
// Another plugin cannot use the grant ID of the first plugin.
assert!(reopened.resolve("org.test.two", &grant.id).is_err());
assert!(reopened.list("org.test.two").unwrap().is_empty());
assert!(!reopened.revoke("org.test.two", &grant.id).unwrap());
assert!(reopened.resolve("org.test.one", &grant.id).is_ok());
assert!(reopened.revoke("org.test.one", &grant.id).unwrap());
assert!(reopened.resolve("org.test.one", &grant.id).is_err());
assert!(reopened.list("org.test.one").unwrap().is_empty());
}
#[test]
fn grants_reject_invalid_plugins_ids_and_folders() {
let fixture = Fixture::new();
let store = fixture.store();
let folder = fixture.folder("images");
for plugin in ["", "..", "../escape", "Upper", "a/b", "a\\b", "con"] {
assert!(store.add(plugin, &folder).is_err(), "{plugin}");
}
assert!(store.add("org.test.one", Path::new("relative")).is_err());
assert!(store.add("org.test.one", &folder.join("..").join("images")).is_err());
assert!(store.add("org.test.one", &fixture.0.join("missing")).is_err());
fs::write(fixture.0.join("file.txt"), "x").unwrap();
assert!(store.add("org.test.one", &fixture.0.join("file.txt")).is_err());
let drive = folder.ancestors().last().unwrap().to_path_buf();
assert!(store.add("org.test.one", &drive).is_err());
assert!(store.resolve("org.test.one", "not-a-uuid").is_err());
assert!(store.resolve("org.test.one", &uuid::Uuid::new_v4().to_string()).is_err());
}
#[test]
fn names_cannot_leave_the_granted_folder() {
let fixture = Fixture::new();
let root = fixture.folder("images");
fs::write(fixture.0.join("secret.txt"), "secret").unwrap();
fixture.folder("images/nested");
fs::write(root.join("nested/inner.png"), "inner").unwrap();
for name in ["../secret.txt", "..", ".", "nested/inner.png", "nested\\inner.png", "C:\\secret.txt", "/secret.txt", "a.png:stream", "", "nul", "trailing."] {
assert!(read_file(&root, name).is_err(), "{name}");
}
assert!(read_file(&root, "nested").is_err(), "a folder is not a file");
fs::write(root.join("b.txt"), "b").unwrap();
fs::write(root.join("a.png"), "a").unwrap();
assert_eq!(list_files(&root).unwrap(), vec![FolderEntry { name: "a.png".into(), size: 1 }, FolderEntry { name: "b.txt".into(), size: 1 }]);
}
#[test]
fn links_are_rejected() {
let fixture = Fixture::new();
let root = fixture.folder("images");
let outside = fixture.folder("outside");
fs::write(outside.join("secret.png"), "secret").unwrap();
if !link(&outside.join("secret.png"), &root.join("link.png"), false) {
return;
}
assert!(list_files(&root).unwrap().is_empty(), "the listing skips links");
assert!(read_file(&root, "link.png").is_err());
// A granted folder that is replaced by a link loses its access.
let store = fixture.store();
let moved = fixture.folder("moved");
let grant = store.add("org.test.one", &moved).unwrap();
fs::remove_dir(&moved).unwrap();
assert!(link(&outside, &moved, true));
assert!(store.resolve("org.test.one", &grant.id).is_err());
}
#[test]
fn reads_have_a_size_limit() {
let fixture = Fixture::new();
let root = fixture.folder("images");
fs::File::create(root.join("large.bin")).unwrap().set_len(READ_LIMIT + 1).unwrap();
assert!(read_file(&root, "large.bin").unwrap_err().to_string().contains("64 MiB"));
fs::File::create(root.join(".runestone-large.json")).unwrap().set_len(SIDECAR_LIMIT + 1).unwrap();
assert!(read_sidecar(&root, ".runestone-large.json").is_err());
}
#[test]
fn sidecars_keep_external_changes_and_accept_only_sidecar_names() {
let fixture = Fixture::new();
let root = fixture.folder("images");
let name = ".runestone-backgrounds.json";
let first = r#"{"schema":1,"images":{}}"#;
let next = r#"{"schema":1,"images":{"a.png":{}}}"#;
assert_eq!(read_sidecar(&root, name).unwrap(), None);
write_sidecar(&root, name, first, None).unwrap();
assert!(write_sidecar(&root, name, next, None).is_err());
assert!(write_sidecar(&root, name, next, Some("stale")).is_err());
write_sidecar(&root, name, next, Some(first)).unwrap();
assert_eq!(read_sidecar(&root, name).unwrap().as_deref(), Some(next));
assert!(write_sidecar(&root, name, "not json", Some(next)).is_err());
assert!(write_sidecar(&root, name, &format!("\"{}\"", "x".repeat(SIDECAR_LIMIT as usize)), Some(next)).is_err());
for bad in ["a.png", "settings.json", ".runestone-.json", ".runestone-a/b.json", ".runestone-a.json.png", "../.runestone-a.json"] {
assert!(write_sidecar(&root, bad, "{}", None).is_err(), "{bad}");
assert!(read_sidecar(&root, bad).is_err(), "{bad}");
}
}
}
+656
View File
@@ -0,0 +1,656 @@
//! Shared file mechanics.
//!
//! Each caller keeps its own policy: which paths and characters it accepts, its size limits,
//! and its error messages. This module holds only the mechanics that the callers share.
use std::fs::{self, File, Metadata};
use std::io::{self, Read, Write};
use std::path::Path;
use crate::error::{Error, Result};
/// True for the reserved Windows device names, also with an extension (`NUL.txt`).
pub fn is_reserved_windows_name(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| ((stem.starts_with("COM") || stem.starts_with("LPT"))
&& stem.len() == 4
&& matches!(stem.as_bytes()[3], b'1'..=b'9'))
}
/// True for a name that can be one path component on every platform: not empty,
/// not `.` or `..`, no trailing dot, and no reserved Windows name.
/// Callers add their own character and length rules.
pub fn is_plain_component(name: &str) -> bool {
!name.is_empty()
&& name != "."
&& name != ".."
&& !name.ends_with('.')
&& !is_reserved_windows_name(name)
}
/// True for a Windows reparse point, which includes symbolic links and junctions.
#[cfg(windows)]
pub fn is_reparse_point(metadata: &Metadata) -> bool {
use std::os::windows::fs::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
}
#[cfg(not(windows))]
pub fn is_reparse_point(_metadata: &Metadata) -> bool {
false
}
/// True for a symbolic link, or for a junction or other reparse point on Windows.
/// Use metadata from `fs::symlink_metadata` or from an open file.
pub fn is_link(metadata: &Metadata) -> bool {
metadata.file_type().is_symlink() || is_reparse_point(metadata)
}
/// Open a file for reading. On Windows, open a link entry itself, so that a replaced link cannot redirect the read.
pub fn open_entry(path: &Path) -> io::Result<File> {
let mut options = File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
}
options.open(path)
}
/// Read at most `limit` bytes. Return `None` when the source holds more than `limit` bytes.
pub fn read_to_limit(reader: impl Read, limit: u64) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
reader.take(limit.saturating_add(1)).read_to_end(&mut bytes)?;
Ok((bytes.len() as u64 <= limit).then_some(bytes))
}
/// Create `temp`, write `bytes`, flush them to the disk, and then call `publish`.
/// Remove `temp` if a step after its creation fails. Never remove a file that this call did not create.
fn write_temp_then(temp: &Path, bytes: &[u8], publish: impl FnOnce() -> io::Result<()>) -> io::Result<()> {
let mut file = File::options().write(true).create_new(true).open(temp)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
let result = written.and_then(|()| publish());
if result.is_err() {
let _ = fs::remove_file(temp);
}
result
}
/// Replace `path` with `bytes`. Write a complete copy at `temp` beside it first, then rename it,
/// so that a failed write leaves the previous file intact.
pub fn replace_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
write_temp_then(temp, bytes, || fs::rename(temp, path))
}
/// Publish a complete new file at `path` through `temp`. Fail if `path` exists,
/// so that a file created by another writer is never replaced.
///
/// The publish step moves `temp` to `path` without replacement. Some volumes (exFAT, FAT32,
/// and many network or FUSE mounts) support neither an exclusive rename nor hard links.
/// On these volumes, write the file in place with `create_new`. That write is not atomic,
/// but it still never replaces an existing file.
pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
create_file_with(path, temp, bytes, rename_no_replace)
}
fn create_file_with(
path: &Path,
temp: &Path,
bytes: &[u8],
publish: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let mut unsupported = false;
let result = write_temp_then(temp, bytes, || {
publish(temp, path).inspect_err(|reason| unsupported = is_unsupported(reason))
});
if unsupported {
return write_new(path, bytes);
}
result
}
/// Create `path` with `create_new`, write `bytes`, and flush them to the disk.
/// Remove the file again if the write fails, because this call created it.
fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> {
let mut file = File::options().write(true).create_new(true).open(path)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if written.is_err() {
let _ = fs::remove_file(path);
}
written
}
/// True when the volume does not support the operation, as opposed to a conflict or a permission problem.
fn is_unsupported(reason: &io::Error) -> bool {
if reason.kind() == io::ErrorKind::Unsupported {
return true;
}
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED};
matches!(reason.raw_os_error(), Some(code) if code == ERROR_INVALID_FUNCTION as i32 || code == ERROR_NOT_SUPPORTED as i32)
}
#[cfg(unix)]
{
// Linux returns EPERM from link(2) when the file system has no hard links.
matches!(reason.raw_os_error(), Some(code) if code == libc::ENOTSUP || code == libc::EOPNOTSUPP
|| code == libc::ENOSYS || code == libc::EINVAL || code == libc::EPERM)
}
#[cfg(not(any(windows, unix)))]
false
}
/// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it.
#[cfg(windows)]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::MoveFileExW;
let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::<Vec<_>>();
let (from_wide, to_wide) = (wide(from), wide(to));
// Without MOVEFILE_REPLACE_EXISTING, Windows refuses an existing destination.
if unsafe { MoveFileExW(from_wide.as_ptr(), to_wide.as_ptr(), 0) } != 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
/// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it.
#[cfg(unix)]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
match rename_exclusive(from, to) {
Err(reason) if is_unsupported(&reason) => {
// A hard link also refuses an existing destination. Remove the source name after it.
fs::hard_link(from, to)?;
let _ = fs::remove_file(from);
Ok(())
}
result => result,
}
}
#[cfg(target_os = "linux")]
fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes())?;
// The raw system call does not need the glibc 2.28 wrapper.
let result = unsafe {
libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, from.as_ptr(), libc::AT_FDCWD, to.as_ptr(), libc::RENAME_NOREPLACE)
};
if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
#[cfg(target_os = "macos")]
fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes())?;
let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_EXCL) };
if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn rename_exclusive(_from: &Path, _to: &Path) -> io::Result<()> {
Err(io::Error::from(io::ErrorKind::Unsupported))
}
#[cfg(not(any(windows, unix)))]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
fs::hard_link(from, to)?;
let _ = fs::remove_file(from);
Ok(())
}
/// True when `left` and `right` name the same directory entry, for example the same file
/// with a different letter case on a case-insensitive volume. Links are not followed.
pub fn same_entry(left: &Path, right: &Path) -> io::Result<bool> {
Ok(entry_identity(left)? == entry_identity(right)?)
}
#[cfg(unix)]
fn entry_identity(path: &Path) -> io::Result<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let metadata = fs::symlink_metadata(path)?;
Ok((metadata.dev(), metadata.ino()))
}
#[cfg(windows)]
fn entry_identity(path: &Path) -> io::Result<(u32, u64)> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
};
// Open the entry itself, also a folder or a link, with attribute access only.
let file = File::options()
.access_mode(FILE_READ_ATTRIBUTES)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok((info.dwVolumeSerialNumber, (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow)))
}
#[cfg(not(any(unix, windows)))]
fn entry_identity(path: &Path) -> io::Result<std::path::PathBuf> {
fs::canonicalize(path)
}
/// Save `contents` at `path`. With `expected`, save only if the file still holds `expected`.
/// Write completely beside the destination, then replace it. A failed write
/// leaves the original file intact rather than truncating it.
pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
write_checked(path, contents.as_bytes(), expected.map(str::as_bytes))
}
/// Save `bytes` at `path` with the same atomic replacement as `write_text`.
pub fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
write_checked(path, bytes, None)
}
fn write_checked(path: &Path, contents: &[u8], expected: Option<&[u8]>) -> Result<()> {
if let Some(expected) = expected {
let current = fs::read(path).map_err(|_| {
Error::new("Save blocked: file was removed or cannot be read. Your edits are still open.")
})?;
if current != expected {
return Err(Error::new(
"Save blocked: file changed on disk. Review the external changes before saving.",
));
}
}
static NEXT_WRITE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let parent = path.parent().ok_or_else(|| Error::new("file has no parent"))?;
let temp = parent.join(format!(
".runestone-save-{}-{}",
std::process::id(),
NEXT_WRITE.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp).map_err(|reason| Error::new(format!("Could not create a save file for {}: {reason}", path.display())))?;
let result = (|| -> Result<()> {
file.write_all(contents).map_err(|reason| Error::new(format!("Could not write the save file for {}: {reason}", path.display())))?;
file.sync_all().map_err(|reason| Error::new(format!("Could not flush the save file for {}: {reason}", path.display())))?;
#[cfg(not(windows))]
if let Ok(metadata) = fs::metadata(path) {
fs::set_permissions(&temp, metadata.permissions()).map_err(|reason| Error::new(format!("Could not preserve file permissions for {}: {reason}", path.display())))?;
}
drop(file);
// Recheck after preparing the replacement to narrow the external-write race.
if let Some(expected) = expected {
if fs::read(path).ok().as_deref() != Some(expected) {
return Err(Error::new(
"Save blocked: file changed while saving. Your edits are still open.",
));
}
}
replace_saved_file(&temp, path, expected.is_none())?;
Ok(())
})();
if result.is_err() {
let _ = fs::remove_file(&temp);
}
result
}
#[cfg(not(windows))]
fn replace_saved_file(temp: &Path, path: &Path, _allow_create: bool) -> Result<()> {
fs::rename(temp, path).map_err(|reason| Error::new(format!(
"Could not replace {}: {reason}. Your edits are still open.", path.display()
)))
}
#[cfg(windows)]
fn replace_saved_file(temp: &Path, path: &Path, allow_create: bool) -> Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::ReplaceFileW;
let metadata = match fs::metadata(path) {
Ok(metadata) => metadata,
Err(reason) if reason.kind() == io::ErrorKind::NotFound && allow_create => {
return fs::rename(temp, path).map_err(|reason| Error::new(format!(
"Could not publish {}: {reason}. Your edits are still open.", path.display()
)));
}
Err(reason) => return Err(Error::new(format!(
"Could not read the destination {}: {reason}. Your edits are still open.", path.display()
))),
};
if metadata.permissions().readonly() {
return Err(Error::new(format!("Cannot save {} because it is read-only. Your edits are still open.", path.display())));
}
// Canonical Windows paths retain the extended prefix for long filenames.
let target = fs::canonicalize(path)?;
let replacement = fs::canonicalize(temp)?;
let backup = target.parent().ok_or_else(|| Error::new("file has no parent"))?
.join(format!(".runestone-save-backup-{}", uuid::Uuid::new_v4()));
if backup.try_exists()? { return Err(Error::new("The save backup path already exists. Retry saving.")); }
let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::<Vec<_>>();
let target_wide = wide(&target);
let replacement_wide = wide(&replacement);
let backup_wide = wide(&backup);
// ReplaceFile preserves Windows file metadata. A backup allows recovery if
// Windows moves the original but cannot publish its replacement.
let replaced = unsafe { ReplaceFileW(
target_wide.as_ptr(), replacement_wide.as_ptr(), backup_wide.as_ptr(),
0, std::ptr::null(), std::ptr::null(),
) };
if replaced != 0 {
let _ = fs::remove_file(&backup);
return Ok(());
}
let reason = io::Error::last_os_error();
if backup.try_exists()? {
if !path.try_exists()? {
if let Err(restore) = restore_save_backup(&backup, path) {
return Err(Error::new(format!(
"Could not save {}: {reason}. Restore failed: {restore}. The original file remains at {}.",
path.display(), backup.display()
)));
}
} else {
return Err(Error::new(format!(
"Could not save {}: {reason}. A recovery copy remains at {}. Your edits are still open.",
path.display(), backup.display()
)));
}
}
Err(Error::new(format!("Could not replace {}: {reason}. Your edits are still open.", path.display())))
}
#[cfg(windows)]
fn restore_save_backup(backup: &Path, path: &Path) -> io::Result<()> {
// A concurrent writer must never lose its file during recovery.
// A move without replacement also works on volumes without hard links.
rename_no_replace(backup, path)
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn fixture(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("rs-fsutil-{name}-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
dir
}
#[test]
fn reserved_names_and_plain_components() {
for name in ["CON", "prn", "Aux.txt", "nul.tar.gz", "COM1", "lpt9.md"] {
assert!(is_reserved_windows_name(name), "{name}");
assert!(!is_plain_component(name), "{name}");
}
for name in ["COM0", "COM10", "LPT", "CONSOLE", "notes", "con-notes.md"] {
assert!(!is_reserved_windows_name(name), "{name}");
}
for name in ["", ".", "..", "trailing."] {
assert!(!is_plain_component(name), "{name}");
}
for name in ["notes.md", ".hidden", "a b", "COM10"] {
assert!(is_plain_component(name), "{name}");
}
}
#[test]
fn limited_reads_return_none_above_the_limit() {
assert_eq!(read_to_limit(&b"1234"[..], 4).unwrap().as_deref(), Some(&b"1234"[..]));
assert_eq!(read_to_limit(&b"12345"[..], 4).unwrap(), None);
assert_eq!(read_to_limit(&b""[..], 0).unwrap().as_deref(), Some(&b""[..]));
assert_eq!(read_to_limit(&b"1"[..], u64::MAX).unwrap().as_deref(), Some(&b"1"[..]));
}
#[test]
fn replace_file_writes_completely_and_cleans_up() {
let dir = fixture("replace");
let path = dir.join("state.json");
replace_file(&path, &dir.join("one.tmp"), b"first").unwrap();
replace_file(&path, &dir.join("two.tmp"), b"second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"second");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
// An existing temporary path is never overwritten or removed.
fs::write(dir.join("taken.tmp"), "other writer").unwrap();
assert!(replace_file(&path, &dir.join("taken.tmp"), b"third").is_err());
assert_eq!(fs::read_to_string(dir.join("taken.tmp")).unwrap(), "other writer");
assert_eq!(fs::read(&path).unwrap(), b"second");
// A failed rename removes the temporary file and keeps the destination.
fs::create_dir(dir.join("folder")).unwrap();
fs::write(dir.join("folder/keep.txt"), "keep").unwrap();
assert!(replace_file(&dir.join("folder"), &dir.join("three.tmp"), b"third").is_err());
assert!(!dir.join("three.tmp").exists());
assert_eq!(fs::read_to_string(dir.join("folder/keep.txt")).unwrap(), "keep");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_file_never_replaces_an_existing_file() {
let dir = fixture("create");
let path = dir.join("note.md");
create_file(&path, &dir.join("one.tmp"), b"complete note\n").unwrap();
assert!(create_file(&path, &dir.join("two.tmp"), b"replacement").is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_file_publishes_without_hard_links_or_replacement() {
let dir = fixture("create-exclusive");
let (from, to) = (dir.join("from.tmp"), dir.join("to.md"));
fs::write(&from, "new").unwrap();
fs::write(&to, "existing").unwrap();
assert_eq!(rename_no_replace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read_to_string(&to).unwrap(), "existing");
assert_eq!(fs::read_to_string(&from).unwrap(), "new");
fs::remove_file(&to).unwrap();
rename_no_replace(&from, &to).unwrap();
assert_eq!(fs::read_to_string(&to).unwrap(), "new");
assert!(!from.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_file_writes_in_place_on_volumes_without_an_exclusive_publish() {
// exFAT, FAT32, and many network or FUSE mounts support neither an exclusive rename nor hard links.
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
let dir = fixture("create-fallback");
let path = dir.join("note.md");
create_file_with(&path, &dir.join("one.tmp"), b"complete note\n", unsupported).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
let error = create_file_with(&path, &dir.join("two.tmp"), b"replacement", unsupported).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
// A conflict is not a missing feature: it never falls back.
let conflict = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists));
assert!(create_file_with(&dir.join("other.md"), &dir.join("three.tmp"), b"x", conflict).is_err());
assert!(!dir.join("other.md").exists());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn same_entry_compares_items_without_following_names() {
let dir = fixture("same-entry");
fs::write(dir.join("note.md"), "note").unwrap();
fs::write(dir.join("other.md"), "other").unwrap();
fs::create_dir(dir.join("folder")).unwrap();
assert!(same_entry(&dir.join("note.md"), &dir.join("note.md")).unwrap());
assert!(!same_entry(&dir.join("note.md"), &dir.join("other.md")).unwrap());
assert!(same_entry(&dir.join("folder"), &dir.join("folder")).unwrap());
// On a case-insensitive volume another spelling names the same item.
if dir.join("NOTE.md").exists() {
assert!(same_entry(&dir.join("note.md"), &dir.join("NOTE.md")).unwrap());
}
assert!(same_entry(&dir.join("note.md"), &dir.join("missing.md")).is_err());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn binary_writes_replace_completely_and_clean_up() {
let dir = fixture("bytes");
let path = dir.join("image.png");
write_bytes(&path, b"\x89PNG first").unwrap();
write_bytes(&path, b"\x89PNG second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"\x89PNG second");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::create_dir(dir.join("folder.png")).unwrap();
assert!(write_bytes(&dir.join("folder.png"), b"x").is_err());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 2);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn links_are_detected_from_link_metadata() {
let dir = fixture("links");
fs::write(dir.join("file.txt"), "file").unwrap();
assert!(!is_link(&fs::symlink_metadata(dir.join("file.txt")).unwrap()));
assert!(!is_link(&fs::symlink_metadata(&dir).unwrap()));
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(dir.join("file.txt"), dir.join("link.txt"));
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(dir.join("file.txt"), dir.join("link.txt"));
match linked {
Ok(()) => {
let metadata = fs::symlink_metadata(dir.join("link.txt")).unwrap();
assert!(is_link(&metadata));
assert_eq!(is_reparse_point(&metadata), cfg!(windows));
assert!(!is_link(&open_entry(&dir.join("file.txt")).unwrap().metadata().unwrap()));
}
#[cfg(windows)]
Err(reason) if reason.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
}
Err(reason) => panic!("Could not prepare the link test: {reason}"),
}
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn guarded_save_preserves_an_external_edit() {
let dir = fixture("save");
let path = dir.join("note.md");
fs::write(&path, "agent changed this").unwrap();
assert!(write_text(&path, "my edit", Some("original")).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "agent changed this");
write_text(&path, "merged edit", Some("agent changed this")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "merged edit");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn deleted_files_are_not_silently_recreated() {
let path = std::env::temp_dir().join(format!("rs-missing-{}.md", uuid::Uuid::new_v4()));
assert!(write_text(&path, "local edits", Some("original")).is_err());
assert!(!path.exists());
}
#[cfg(windows)]
#[test]
fn windows_card_updates_preserve_file_streams() {
let dir = fixture("card-save");
let path = dir.join("card.md");
create_file(&path, &dir.join("card.tmp"), b"original card").unwrap();
let stream = PathBuf::from(format!("{}:review-tag", path.display()));
fs::write(&stream, "keep this metadata").unwrap();
write_text(&path, "card with second image", Some("original card")).unwrap();
write_text(&path, "updated description", Some("card with second image")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "updated description");
assert_eq!(fs::read_to_string(&stream).unwrap(), "keep this metadata");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_blocked_replacement_keeps_the_original() {
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
let dir = fixture("locked-save");
let path = dir.join("card.md");
fs::write(&path, "original").unwrap();
let reader = fs::OpenOptions::new().read(true).share_mode(FILE_SHARE_READ).open(&path).unwrap();
let error = write_text(&path, "new", Some("original")).unwrap_err().to_string();
assert!(error.contains("Could not replace"), "{error}");
assert!(error.contains("card.md"), "{error}");
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
drop(reader);
write_text(&path, "new", Some("original")).unwrap();
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
// The test runs only on Windows, where this call clears the read-only attribute.
#[allow(clippy::permissions_set_readonly_false)]
fn windows_read_only_files_remain_protected() {
let dir = fixture("readonly-save");
let path = dir.join("card.md");
fs::write(&path, "original").unwrap();
let mut permissions = fs::metadata(&path).unwrap().permissions();
permissions.set_readonly(true);
fs::set_permissions(&path, permissions).unwrap();
let result = write_text(&path, "new", Some("original"));
let mut permissions = fs::metadata(&path).unwrap().permissions();
permissions.set_readonly(false);
fs::set_permissions(&path, permissions).unwrap();
assert!(result.unwrap_err().to_string().contains("read-only"));
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_save_recovery_never_overwrites_a_newer_file() {
let dir = fixture("save-recovery");
let path = dir.join("card.md");
let backup = dir.join("original.backup");
fs::write(&path, "concurrent edit").unwrap();
fs::write(&backup, "original").unwrap();
assert!(restore_save_backup(&backup, &path).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "concurrent edit");
assert_eq!(fs::read_to_string(&backup).unwrap(), "original");
fs::remove_file(&path).unwrap();
restore_save_backup(&backup, &path).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert!(!backup.exists());
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_save_supports_extended_paths() {
let root = fixture("long-save");
let mut dir = root.clone();
for _ in 0..7 { dir.push("long-workspace-directory-name-1234567890"); }
fs::create_dir_all(&dir).unwrap();
let path = dir.join("card.md");
write_text(&path, "original", None).unwrap();
write_text(&path, "updated", Some("original")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "updated");
assert!(root.starts_with(std::env::temp_dir()));
fs::remove_dir_all(root).unwrap();
}
}
+1051
View File
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root =
std::env::temp_dir().join(format!("runestone-git-sync-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).unwrap();
let fixture = Self(dunce::canonicalize(root).unwrap());
fixture.git(
".",
&["init", "--bare", "--initial-branch=main", "remote.git"],
);
fixture.git(".", &["clone", "remote.git", "local"]);
fixture.git("local", &["config", "user.name", "RuneStone Test"]);
fixture.git("local", &["config", "user.email", "[email protected]"]);
fixture
}
fn path(&self, directory: &str) -> PathBuf {
self.0.join(directory)
}
fn git(&self, directory: &str, args: &[&str]) -> String {
checked(&self.path(directory), args).unwrap()
}
fn commit(&self, directory: &str, name: &str, contents: &str) {
std::fs::write(self.path(directory).join(name), contents).unwrap();
self.git(directory, &["add", "--", name]);
self.git(
directory,
&[
"-c",
"user.name=RuneStone Test",
"-c",
"[email protected]",
"commit",
"-m",
contents,
],
);
}
fn seed(&self) {
self.commit("local", "first.txt", "Initial commit");
synchronize(&self.path("local"), true).unwrap();
self.git(".", &["clone", "remote.git", "peer"]);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn push_and_fast_forward_pull_use_only_the_upstream_branch() {
let fixture = Fixture::new();
fixture.seed();
fixture.git("local", &["branch", "unpublished"]);
fixture.git("local", &["tag", "unpublished-tag"]);
fixture.git("local", &["config", "push.default", "matching"]);
fixture.git("local", &["config", "remote.origin.mirror", "true"]);
fixture.commit("local", "second.txt", "Local change");
synchronize(&fixture.path("local"), true).unwrap();
let refs = fixture.git("remote.git", &["for-each-ref", "--format=%(refname)"]);
assert_eq!(refs.trim(), "refs/heads/main");
fixture.git("peer", &["pull", "--ff-only"]);
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.git("local", &["config", "pull.rebase", "true"]);
synchronize(&fixture.path("local"), false).unwrap();
assert_eq!(
fixture.git("local", &["rev-parse", "HEAD"]),
fixture.git("peer", &["rev-parse", "HEAD"])
);
assert_eq!(
std::fs::read_to_string(fixture.path("local").join("peer.txt")).unwrap(),
"Peer change"
);
}
#[test]
fn divergent_push_and_pull_preserve_local_and_remote_commits() {
let fixture = Fixture::new();
fixture.seed();
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.commit("local", "local.txt", "Local change");
fixture.git(
"local",
&[
"config",
"remote.origin.push",
"+refs/heads/main:refs/heads/main",
],
);
fixture.git("local", &["config", "pull.rebase", "true"]);
fixture.git("local", &["config", "pull.ff", "false"]);
let local = fixture.git("local", &["rev-parse", "HEAD"]);
let remote = fixture.git("remote.git", &["rev-parse", "HEAD"]);
assert!(synchronize(&fixture.path("local"), true).is_err());
assert!(synchronize(&fixture.path("local"), false).is_err());
assert_eq!(fixture.git("local", &["rev-parse", "HEAD"]), local);
assert_eq!(fixture.git("remote.git", &["rev-parse", "HEAD"]), remote);
assert!(!fixture.path("local/.git/MERGE_HEAD").exists());
assert!(!fixture.path("local/.git/rebase-merge").exists());
}
#[test]
fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
let fixture = Fixture::new();
fixture.seed();
std::fs::write(fixture.path("local/first.txt"), "Unsaved change").unwrap();
fixture.git("local", &["config", "merge.autoStash", "true"]);
assert!(synchronize(&fixture.path("local"), false)
.unwrap_err()
.to_string()
.contains("clean working tree"));
assert_eq!(
std::fs::read_to_string(fixture.path("local/first.txt")).unwrap(),
"Unsaved change"
);
fixture.git("local", &["branch", "--unset-upstream"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.to_string()
.contains("no remote upstream"));
fixture.git("local", &["checkout", "--detach"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.to_string()
.contains("Select a branch"));
fixture.git("local", &["checkout", "main"]);
fixture.git("local", &["branch", "--set-upstream-to=origin/main"]);
fixture.git(
"local",
&["remote", "set-url", "origin", "../missing-remote.git"],
);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.to_string()
.contains("Push failed"));
}
#[test]
fn graph_shows_branch_forks_merges_tags_and_detached_history() {
let fixture = Fixture::new();
assert!(graph(&fixture.path("local")).unwrap().commits.is_empty());
fixture.seed();
fixture.git("local", &["checkout", "-b", "feature"]);
fixture.commit("local", "feature.txt", "Feature commit");
fixture.git("local", &["checkout", "main"]);
fixture.commit("local", "main.txt", "Main commit");
fixture.git(
"local",
&["merge", "--no-ff", "feature", "-m", "Merge feature"],
);
fixture.git("local", &["tag", "test-tag"]);
let history = graph(&fixture.path("local")).unwrap();
for expected in [
"HEAD -> main",
"feature",
"test-tag",
"Merge feature",
"RuneStone Test",
] {
assert!(format!("{history:?}").contains(expected), "Missing {expected}: {history:?}");
}
let merge = history.commits.iter().find(|commit| commit.summary == "Merge feature").unwrap();
assert_eq!(merge.parents.len(), 2);
let details = commit_details(&fixture.path("local"), &merge.id).unwrap();
assert_eq!(details.files.len(), 1);
assert_eq!(details.files[0].path, "feature.txt");
assert!(commit_diff(&fixture.path("local"), &merge.id, "feature.txt").unwrap().contains("+Feature commit"));
for parent in &merge.parents {
assert!(history.commits.iter().any(|commit| &commit.id == parent));
}
fixture.git("local", &["checkout", "--detach"]);
fixture.commit("local", "detached.txt", "Detached commit");
assert!(graph(&fixture.path("local"))
.unwrap()
.commits.iter().any(|commit| commit.summary == "Detached commit"));
}
+262
View File
@@ -0,0 +1,262 @@
mod error;
mod fsutil;
mod pty;
mod terminal_platform;
mod plugins;
mod plugin_sources;
mod workspace;
mod browser;
mod browser_engine;
mod git;
mod completion;
mod settings;
mod preferences;
mod tab_transfer;
mod spelling;
mod theme;
mod backgrounds;
mod folders;
mod features;
mod window_frame;
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(browser_engine::EngineState::default())
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.manage(preferences::PreferencesState::default())
.manage(tab_transfer::TabTransferState::default())
.invoke_handler(tauri::generate_handler![
backgrounds::background_choose_folder,
backgrounds::background_folder,
backgrounds::background_clear_folder,
backgrounds::background_list,
backgrounds::background_read,
backgrounds::background_read_sidecar,
backgrounds::background_write_sidecar,
backgrounds::background_migrate,
folders::folders_choose,
folders::folders_picture,
folders::folders_grants,
folders::folders_revoke,
folders::folders_list,
folders::folders_read,
folders::folders_read_sidecar,
folders::folders_write_sidecar,
features::features_legacy,
theme::theme_export,
spelling::spelling_menu_install,
spelling::spelling_suggestions,
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
window_frame::window_snap_layouts,
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,
browser_engine::browser_engine_status,
browser_engine::browser_engine_install,
browser_engine::browser_engine_install_file,
browser_engine::browser_engine_cancel,
browser_engine::browser_engine_remove,
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_save_image_url,
workspace::workspace_download_image,
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,
pty::pty_running,
])
.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:?}");
}
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
runestone_lib::run()
}
+369
View File
@@ -0,0 +1,369 @@
//! Release downloads are separate from package validation and installation.
use reqwest::{blocking::Client, Url};
use serde_json::Value;
use std::{io::Read, time::Duration};
use crate::error::Result;
const MAX_METADATA: usize = 2 * 1024 * 1024;
const MAX_ARCHIVE: usize = 100 * 1024 * 1024;
#[derive(Debug)]
pub struct Repository {
pub url: Url,
pub api: Url,
}
fn web_url(input: &str) -> Result<Url> {
let url = Url::parse(input).map_err(|_| "Enter a complete HTTP or HTTPS link.")?;
if !matches!(url.scheme(), "http" | "https")
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
{
return Err("Use an HTTP or HTTPS link without credentials or a fragment.".into());
}
Ok(url)
}
impl Repository {
pub fn parse(input: &str, tag: &str) -> Result<Self> {
let mut url = web_url(input.trim())?;
if url.query().is_some() {
return Err("Use a repository link without a query.".into());
}
let path = url
.path()
.trim_end_matches('/')
.trim_end_matches(".git")
.to_owned();
let parts: Vec<_> = path.trim_start_matches('/').split('/').collect();
if parts.len() != 2
|| parts.iter().any(|part| {
part.is_empty()
|| *part == "."
|| *part == ".."
|| !part
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
})
{
return Err(
"Use the repository root link, such as https://host/owner/repository.".into(),
);
}
url.set_path(&path);
let mut api = url.clone();
api.set_path("/");
{
let mut segments = api
.path_segments_mut()
.map_err(|_| "Invalid repository link.")?;
segments.clear();
segments
.extend(["api", "v1", "repos"])
.extend(&parts)
.push("releases");
let tag = tag.trim();
if tag.is_empty() {
segments.push("latest");
} else {
if tag.len() > 200 || tag.chars().any(char::is_control) || matches!(tag, "." | "..")
{
return Err("Enter a release tag with at most 200 characters.".into());
}
segments.push("tags");
segments.push(tag);
}
}
Ok(Self { url, api })
}
}
pub struct Download {
pub bytes: Vec<u8>,
pub source: String,
}
fn read_limited(reader: impl Read, limit: usize) -> Result<Vec<u8>> {
crate::fsutil::read_to_limit(reader, limit as u64)
.map_err(|_| "The download was interrupted. Try again.")?
.ok_or_else(|| "The download exceeds its size limit.".into())
}
// Send credentials only to the release API's origin, including after redirects.
fn get(
client: &Client,
start: Url,
auth_origin: &Url,
authorization: Option<&str>,
limit: usize,
) -> Result<Vec<u8>> {
let mut url = start;
let started = std::time::Instant::now();
for _ in 0..=5 {
let remaining = Duration::from_secs(60)
.checked_sub(started.elapsed())
.filter(|remaining| !remaining.is_zero())
.ok_or("The download timed out. Try again.")?;
let mut request = client.get(url.clone()).timeout(remaining);
if url.origin() == auth_origin.origin() {
if let Some(value) = authorization {
request = request.header(reqwest::header::AUTHORIZATION, value);
}
}
let response = request
.send()
.map_err(|_| "Cannot reach the release server. Check the link and connection.")?;
if response.status().is_redirection() {
let location = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|value| value.to_str().ok())
.ok_or("The server returned an invalid redirect.")?;
let next = url
.join(location)
.map_err(|_| "The server returned an invalid redirect.")?;
web_url(next.as_str())?;
if url.scheme() == "https" && next.scheme() != "https" {
return Err("The server redirected a secure link to HTTP.".into());
}
url = next;
continue;
}
if !response.status().is_success() {
return Err(match response.status().as_u16() {
401 | 403 => "Access denied. Check the token and repository read access.".into(),
404 => "Release not found. Check the repository, release tag, and token for private access.".into(),
429 => "The server request limit was reached. Try again later.".into(),
code => format!("The release server returned HTTP {code}.").into(),
});
}
if response
.content_length()
.is_some_and(|size| size > limit as u64)
{
return Err("The download exceeds its size limit.".into());
}
return read_limited(response, limit);
}
Err("The server returned too many redirects.".into())
}
fn asset(metadata: &Value) -> Result<(String, Url)> {
if metadata["draft"].as_bool() == Some(true) {
return Err("Publish the release before installing its plugin.".into());
}
let tag = metadata["tag_name"]
.as_str()
.filter(|tag| !tag.is_empty())
.ok_or("The release has no tag.")?;
let assets = &metadata["assets"];
let zips: Vec<_> = assets
.as_array()
.ok_or("The release has no attached plugin ZIP.")?
.iter()
.filter(|item| {
item["name"]
.as_str()
.is_some_and(|name| name.to_ascii_lowercase().ends_with(".zip"))
})
.collect();
if zips.len() != 1 {
return Err(
"The release must contain exactly one plugin ZIP. Source archives do not count.".into(),
);
}
let item = zips[0];
let link = item["browser_download_url"]
.as_str()
.ok_or("The plugin ZIP has no download link.")?;
if item["size"]
.as_u64()
.is_some_and(|size| size > MAX_ARCHIVE as u64)
{
return Err("The archive exceeds 100 MiB.".into());
}
Ok((tag.to_owned(), web_url(link)?))
}
pub fn download(repository: &Repository, token: Option<&str>) -> Result<Download> {
let authorization = token
.filter(|value| !value.is_empty())
.map(|value| format!("token {value}"));
download_authorized(repository, authorization.as_deref())
}
fn download_authorized(repository: &Repository, authorization: Option<&str>) -> Result<Download> {
let client = Client::builder()
.user_agent("RuneStone-plugin-installer/0.1")
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(60))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|_| "Cannot start the download client.")?;
let metadata = get(
&client,
repository.api.clone(),
&repository.api,
authorization,
MAX_METADATA,
)?;
let metadata: Value = serde_json::from_slice(&metadata)
.map_err(|_| "The server did not return release metadata.")?;
let (tag, url) = asset(&metadata)?;
if repository.url.scheme() == "https" && url.scheme() != "https" {
return Err("The plugin ZIP must use HTTPS for this repository.".into());
}
let bytes = get(
&client,
url.clone(),
&repository.api,
authorization,
MAX_ARCHIVE,
)?;
// Query parameters can contain temporary download credentials.
let mut display = url;
display.set_query(None);
Ok(Download {
bytes,
source: format!("{} @ {}\n{}", repository.url, tag, display),
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use serde_json::json;
use std::{io::Write, net::TcpListener, thread, time::Instant};
pub fn server(responses: Vec<(String, Vec<u8>)>) -> (String, thread::JoinHandle<Vec<String>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let handle = thread::spawn(move || {
let mut requests = Vec::new();
for (headers, body) in responses {
let start = Instant::now();
let mut stream = loop {
match listener.accept() {
Ok((stream, _)) => break stream,
Err(error)
if error.kind() == std::io::ErrorKind::WouldBlock
&& start.elapsed() < Duration::from_secs(15) =>
{
thread::sleep(Duration::from_millis(10))
}
Err(error) => panic!("Test server did not receive a request: {error}"),
}
};
stream.set_nonblocking(false).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut request = Vec::new();
while !request.ends_with(b"\r\n\r\n") {
let mut byte = [0];
stream.read_exact(&mut byte).unwrap();
request.push(byte[0]);
assert!(request.len() < 16384);
}
requests.push(String::from_utf8(request).unwrap());
write!(
stream,
"HTTP/1.1 {headers}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
)
.unwrap();
stream.write_all(&body).unwrap();
}
requests
});
(base, handle)
}
#[test]
fn network_errors_limits_and_redirect_credentials() {
let client = Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
let (target, target_server) = server(vec![("200 OK".into(), b"zip".to_vec())]);
let (origin, origin_server) = server(vec![(
format!("302 Found\r\nLocation: {target}/download"),
vec![],
)]);
let url = Url::parse(&origin).unwrap();
assert_eq!(
get(&client, url.clone(), &url, Some("token secret"), 10).unwrap(),
b"zip"
);
assert!(origin_server.join().unwrap()[0].contains("authorization: token secret"));
assert!(!target_server.join().unwrap()[0]
.to_lowercase()
.contains("authorization:"));
for (status, body, limit, message) in [
("404 Not Found", vec![], 100, "Release not found"),
("403 Forbidden", vec![], 100, "Access denied"),
("200 OK", b"12345".to_vec(), 4, "size limit"),
(
"302 Found\r\nLocation: file:///secret",
vec![],
100,
"HTTP or HTTPS",
),
] {
let (base, handle) = server(vec![(status.into(), body)]);
let url = Url::parse(&base).unwrap();
assert!(get(&client, url.clone(), &url, None, limit)
.unwrap_err()
.to_string()
.contains(message));
handle.join().unwrap();
}
}
#[test]
fn repository_routes_and_tags() {
let cases = [
(
"https://git.example/owner/demo.git/",
"",
"https://git.example/api/v1/repos/owner/demo/releases/latest",
),
(
"http://localhost:6610/group/demo",
"trial/1",
"http://localhost:6610/api/v1/repos/group/demo/releases/tags/trial%2F1",
),
];
for (url, tag, expected) in cases {
assert_eq!(Repository::parse(url, tag).unwrap().api.as_str(), expected);
}
for bad in [
"file:///tmp/plugin",
"git@example:owner/demo",
"https://user:secret@example/a/b",
"https://example/a/b?token=secret",
"https://example/a/b/tree/main",
"https://example/a/b#main",
] {
assert!(Repository::parse(bad, "").is_err(), "{bad}");
}
}
#[test]
fn release_assets_are_explicit_and_unambiguous() {
let zip = json!({"name":"org.test.demo-1.0.0.zip", "browser_download_url":"https://example/demo.zip"});
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone()]})).is_ok());
assert!(asset(
&json!({"tag_name":"v1", "zipball_url":"https://example/source.zip", "assets":[]})
)
.is_err());
assert!(asset(&json!({"tag_name":"v1", "assets":[zip.clone(),zip.clone()]})).is_err());
assert!(asset(&json!({"tag_name":"v1", "draft":true, "assets":[zip]})).is_err());
assert!(read_limited(&b"12345"[..], 4).is_err());
assert_eq!(read_limited(&b"1234"[..], 4).unwrap(), b"1234");
}
}
File diff suppressed because it is too large Load Diff
+404
View File
@@ -0,0 +1,404 @@
//! User preferences in one file: `<app config dir>/settings.json`.
//!
//! The file holds a `schema` number, a `revision` number, and one value for each section.
//! The host does not interpret the section values. The frontend normalizes them.
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
//! Plugin settings stay in the app data folder (see `plugins.rs`).
use std::io;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use serde_json::{Map, Value};
use tauri::{AppHandle, Emitter, Manager};
use crate::error::{Error, Result};
use crate::fsutil;
pub const FILE_NAME: &str = "settings.json";
pub const SCHEMA: u64 = 1;
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
pub const CHANGED_EVENT: &str = "settings-changed";
/// All sections, as the frontend reads them at startup.
#[derive(Serialize, Clone, Debug, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Snapshot {
/// False when no settings file exists yet. The frontend then migrates its old values.
pub exists: bool,
pub revision: u64,
pub sections: Map<String, Value>,
/// A message for the user, sent once after the host replaced a damaged file.
#[serde(skip_serializing_if = "Option::is_none")]
pub notice: Option<String>,
}
/// The payload of `settings-changed`.
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Change {
pub section: String,
pub revision: u64,
pub value: Value,
}
struct Loaded {
document: Map<String, Value>,
exists: bool,
notice: Option<String>,
}
/// The settings file and its in-memory copy. One lock serializes all reads and writes.
pub struct Store {
path: PathBuf,
loaded: Option<Loaded>,
}
fn empty_document() -> Map<String, Value> {
let mut document = Map::new();
document.insert("schema".into(), SCHEMA.into());
document.insert("revision".into(), 0.into());
document
}
fn revision(document: &Map<String, Value>) -> u64 {
document.get("revision").and_then(Value::as_u64).unwrap_or(0)
}
fn check_section(section: &str) -> Result<()> {
if SECTIONS.contains(&section) { Ok(()) } else { Err(Error::new(format!("Unknown settings section: {section}"))) }
}
/// Parse the file. `None` means that the file is damaged.
fn parse(bytes: &[u8]) -> Option<Map<String, Value>> {
if bytes.len() > MAX_FILE_BYTES { return None; }
let Value::Object(document) = serde_json::from_slice(bytes).ok()? else { return None };
let schema = document.get("schema").and_then(Value::as_u64)?;
if schema == 0 { return None; }
if document.get("revision").is_some_and(|value| value.as_u64().is_none()) { return None; }
Some(document)
}
fn encode(document: &Map<String, Value>) -> Result<Vec<u8>> {
let mut bytes = serde_json::to_vec_pretty(document)?;
bytes.push(b'\n');
if bytes.len() > MAX_FILE_BYTES {
return Err(Error::new("The settings are larger than 8 MiB. Remove the background image data or some custom themes, then try again."));
}
Ok(bytes)
}
fn temp_path(path: &Path) -> Result<PathBuf> {
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
Ok(parent.join(format!(".settings-{}.tmp", uuid::Uuid::new_v4())))
}
/// Move a damaged file aside to `settings.corrupt-<seconds>.json`, with a counter if that name exists.
fn keep_damaged_copy(path: &Path) -> Result<PathBuf> {
let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
for attempt in 0..100u32 {
let name = if attempt == 0 { format!("settings.corrupt-{seconds}.json") } else { format!("settings.corrupt-{seconds}-{attempt}.json") };
let copy = parent.join(name);
match fsutil::rename_no_replace(path, &copy) {
Ok(()) => return Ok(copy),
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => continue,
Err(reason) => return Err(reason.into()),
}
}
Err(Error::new("Could not keep a copy of the damaged settings file."))
}
impl Store {
pub fn new(path: PathBuf) -> Self {
Self { path, loaded: None }
}
fn load(&mut self) -> Result<&mut Loaded> {
if self.loaded.is_none() {
self.loaded = Some(self.read_file()?);
}
Ok(self.loaded.as_mut().expect("loaded above"))
}
fn read_file(&self) -> Result<Loaded> {
let bytes = match fsutil::open_entry(&self.path) {
Ok(file) => fsutil::read_to_limit(file, MAX_FILE_BYTES as u64)?,
Err(reason) if reason.kind() == io::ErrorKind::NotFound => {
return Ok(Loaded { document: empty_document(), exists: false, notice: None });
}
Err(reason) => return Err(Error::new(format!("Could not read the settings file {}: {reason}", self.path.display()))),
};
if let Some(document) = bytes.as_deref().and_then(parse) {
return Ok(Loaded { document, exists: true, notice: None });
}
// Keep the damaged file for the user, then start again from the defaults.
let copy = keep_damaged_copy(&self.path)?;
let document = empty_document();
fsutil::create_file(&self.path, &temp_path(&self.path)?, &encode(&document)?)?;
let notice = format!(
"RuneStone could not read your settings file, so the default settings apply. A copy of the damaged file is at {}.",
copy.display()
);
Ok(Loaded { document, exists: true, notice: Some(notice) })
}
/// All known sections. The notice of a replaced file goes to the first reader only.
pub fn read(&mut self) -> Result<Snapshot> {
let loaded = self.load()?;
let sections = SECTIONS.iter()
.filter_map(|name| loaded.document.get(*name).map(|value| ((*name).to_owned(), value.clone())))
.collect();
Ok(Snapshot { exists: loaded.exists, revision: revision(&loaded.document), sections, notice: loaded.notice.take() })
}
/// Replace one section. `null` removes it. Unknown top-level keys stay in the file.
pub fn write(&mut self, section: &str, value: Value) -> Result<Change> {
check_section(section)?;
let path = self.path.clone();
let loaded = self.load()?;
let mut document = loaded.document.clone();
let next = revision(&document) + 1;
if value.is_null() { document.remove(section); } else { document.insert(section.into(), value.clone()); }
document.insert("revision".into(), next.into());
if document.get("schema").and_then(Value::as_u64).is_none_or(|schema| schema < SCHEMA) {
document.insert("schema".into(), SCHEMA.into());
}
let bytes = encode(&document)?;
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
fsutil::replace_file(&path, &temp_path(&path)?, &bytes)
.map_err(|reason| Error::new(format!("Could not save the settings file {}: {reason}", path.display())))?;
loaded.document = document;
loaded.exists = true;
Ok(Change { section: section.into(), revision: next, value })
}
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
for name in sections.keys() { check_section(name)?; }
let path = self.path.clone();
if self.load()?.exists { return self.read(); }
let mut document = empty_document();
document.insert("revision".into(), 1.into());
for (name, value) in sections {
if !value.is_null() { document.insert(name, value); }
}
let bytes = encode(&document)?;
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
match fsutil::create_file(&path, &temp_path(&path)?, &bytes) {
Ok(()) => {
let loaded = self.load()?;
loaded.document = document;
loaded.exists = true;
}
// Another process wrote the file first. Use its values.
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => self.loaded = None,
Err(reason) => return Err(Error::new(format!("Could not create the settings file {}: {reason}", path.display()))),
}
self.read()
}
}
#[derive(Default)]
pub struct PreferencesState(Mutex<Option<Store>>);
fn settings_path(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_config_dir().map_err(|reason| Error::new(format!("app config dir: {reason}")))?.join(FILE_NAME))
}
/// Run `task` with the store on a blocking thread, because it reads and writes files.
async fn with_store<T: Send + 'static>(app: &AppHandle, task: impl FnOnce(&mut Store) -> Result<T> + Send + 'static) -> Result<T> {
let app = app.clone();
tauri::async_runtime::spawn_blocking(move || {
let state = app.state::<PreferencesState>();
let mut guard = state.0.lock()?;
if guard.is_none() { *guard = Some(Store::new(settings_path(&app)?)); }
task(guard.as_mut().expect("set above"))
}).await?
}
#[tauri::command]
pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
with_store(&app, Store::read).await
}
#[tauri::command]
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
let change = with_store(&app, move |store| store.write(&section, value)).await?;
// Every window shows the same preferences, so the change goes to all of them.
let _ = app.emit(CHANGED_EVENT, &change);
Ok(change)
}
#[tauri::command]
pub async fn settings_migrate(app: AppHandle, sections: Map<String, Value>) -> Result<Snapshot> {
with_store(&app, move |store| store.migrate(sections)).await
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::fs;
fn fixture(name: &str) -> (PathBuf, PathBuf) {
let dir = std::env::temp_dir().join(format!("rs-preferences-{name}-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join(FILE_NAME);
(dir, path)
}
fn on_disk(path: &Path) -> Value {
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
}
fn files(dir: &Path) -> Vec<String> {
let mut names: Vec<_> = fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn a_missing_file_reads_as_empty_and_does_not_exist() {
let (dir, path) = fixture("missing");
let snapshot = Store::new(path.clone()).read().unwrap();
assert_eq!(snapshot, Snapshot { exists: false, revision: 0, sections: Map::new(), notice: None });
assert!(!path.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_replace_one_section_and_increase_the_revision() {
let (dir, path) = fixture("write");
let mut store = Store::new(path.clone());
let first = store.write("general", json!({ "autosaveSeconds": 7 })).unwrap();
assert_eq!(first, Change { section: "general".into(), revision: 1, value: json!({ "autosaveSeconds": 7 }) });
let second = store.write("language", json!("fr")).unwrap();
assert_eq!(second.revision, 2);
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 2, "general": { "autosaveSeconds": 7 }, "language": "fr" }));
// A new store reads the same values from the file.
let snapshot = Store::new(path.clone()).read().unwrap();
assert!(snapshot.exists);
assert_eq!(snapshot.revision, 2);
assert_eq!(Value::Object(snapshot.sections), json!({ "general": { "autosaveSeconds": 7 }, "language": "fr" }));
store.write("language", Value::Null).unwrap();
assert!(on_disk(&path).get("language").is_none());
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_reject_unknown_sections_and_values_above_the_limit() {
let (dir, path) = fixture("limits");
let mut store = Store::new(path.clone());
assert!(store.write("plugins", json!({})).is_err());
assert!(store.write("../general", json!({})).is_err());
// A data URL of 3,000,000 characters fits.
let image = format!("data:image/png;base64,{}", "A".repeat(3_000_000));
store.write("appearance", json!({ "newTabBackground": { "image": image } })).unwrap();
let before = fs::read(&path).unwrap();
let error = store.write("customThemes", json!(["x".repeat(MAX_FILE_BYTES)])).unwrap_err();
assert!(error.to_string().contains("8 MiB"), "{error}");
assert_eq!(fs::read(&path).unwrap(), before, "A refused write leaves the file unchanged");
assert_eq!(store.read().unwrap().revision, 1);
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()]);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_keep_unknown_top_level_keys() {
let (dir, path) = fixture("unknown");
fs::write(&path, r#"{ "schema": 1, "revision": 4, "future": { "a": 1 }, "general": {} }"#).unwrap();
let mut store = Store::new(path.clone());
assert_eq!(store.read().unwrap().sections.keys().collect::<Vec<_>>(), vec!["general"]);
assert_eq!(store.write("language", json!("ja")).unwrap().revision, 5);
assert_eq!(on_disk(&path)["future"], json!({ "a": 1 }));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_damaged_file_is_kept_aside_and_reported_once() {
for (name, contents) in [("syntax", "{ broken".as_bytes()), ("array", b"[1, 2]"), ("schema", br#"{ "revision": 1 }"#), ("revision", br#"{ "schema": 1, "revision": "x" }"#)] {
let (dir, path) = fixture(name);
fs::write(&path, contents).unwrap();
let mut store = Store::new(path.clone());
let snapshot = store.read().unwrap();
assert!(snapshot.exists, "{name}: no migration after a damaged file");
assert_eq!(snapshot.revision, 0);
assert!(snapshot.sections.is_empty());
let notice = snapshot.notice.expect("The first read reports the damaged file");
let copies: Vec<_> = files(&dir).into_iter().filter(|file| file.starts_with("settings.corrupt-")).collect();
assert_eq!(copies.len(), 1, "{name}");
assert!(notice.contains(&copies[0]), "{notice}");
assert_eq!(fs::read(dir.join(&copies[0])).unwrap(), contents, "{name}: the copy keeps the damaged bytes");
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 0 }));
assert_eq!(store.read().unwrap().notice, None, "Report the damaged file once");
assert_eq!(Store::new(path.clone()).read().unwrap().notice, None, "The new file is valid");
fs::remove_dir_all(dir).unwrap();
}
}
#[test]
fn a_file_above_the_limit_counts_as_damaged() {
let (dir, path) = fixture("large");
fs::write(&path, vec![b' '; MAX_FILE_BYTES + 1]).unwrap();
assert!(Store::new(path.clone()).read().unwrap().notice.is_some());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn migration_writes_the_first_file_only() {
let (dir, path) = fixture("migrate");
let mut store = Store::new(path.clone());
let sections = json!({ "general": { "autosaveEnabled": false }, "language": "fr", "customThemes": [] });
let Value::Object(sections) = sections else { unreachable!() };
let snapshot = store.migrate(sections.clone()).unwrap();
assert!(snapshot.exists);
assert_eq!(snapshot.revision, 1);
assert_eq!(snapshot.sections, sections);
assert_eq!(on_disk(&path)["language"], json!("fr"));
// A second migration, for example from a second window, keeps the existing file.
store.write("language", json!("ja")).unwrap();
let mut other = Store::new(path.clone());
let again = other.migrate(Map::from_iter([("language".to_owned(), json!("en"))])).unwrap();
assert_eq!(again.sections["language"], json!("ja"));
assert_eq!(on_disk(&path)["language"], json!("ja"));
let Value::Object(unknown) = json!({ "plugins": {} }) else { unreachable!() };
assert!(Store::new(dir.join("other.json")).migrate(unknown).is_err());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn migration_uses_a_file_that_another_writer_created_first() {
let (dir, path) = fixture("race");
let mut store = Store::new(path.clone());
assert!(!store.read().unwrap().exists);
fs::write(&path, r#"{ "schema": 1, "revision": 3, "language": "ja" }"#).unwrap();
let snapshot = store.migrate(Map::from_iter([("language".to_owned(), json!("fr"))])).unwrap();
assert_eq!(snapshot.revision, 3);
assert_eq!(snapshot.sections["language"], json!("ja"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn writes_create_a_missing_config_folder() {
let (dir, _) = fixture("folder");
let path = dir.join("nested").join(FILE_NAME);
Store::new(path.clone()).write("language", json!("fr")).unwrap();
assert_eq!(on_disk(&path)["language"], json!("fr"));
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_change_event_carries_the_section_revision_and_value() {
let change = Change { section: "language".into(), revision: 9, value: json!("fr") };
assert_eq!(serde_json::to_value(&change).unwrap(), json!({ "section": "language", "revision": 9, "value": "fr" }));
let snapshot = Snapshot { exists: true, revision: 2, sections: Map::new(), notice: None };
assert_eq!(serde_json::to_value(&snapshot).unwrap(), json!({ "exists": true, "revision": 2, "sections": {} }));
}
}
+925
View File
@@ -0,0 +1,925 @@
//! Shell sessions for the native Terminal feature of RuneStone (`src/lib/features/terminal/`).
use std::collections::{HashMap, VecDeque};
use std::io::{Read, Write};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError};
use std::sync::Mutex;
use std::thread;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::Serialize;
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
use tauri::{AppHandle, Manager, State};
use crate::error::{Error, Result};
use crate::workspace::{current_root, WorkspaceState};
use crate::terminal_platform::find_executable;
/// The largest output message in bytes.
const BATCH_BYTES: usize = 64 * 1024;
/// The longest time that output waits for more output before it goes to the webview.
const BATCH_WAIT: Duration = Duration::from_millis(8);
/// The number of retired page IDs that each window keeps.
const RETIRED_PAGES: usize = 16;
const NOT_OPEN: &str = "terminal is not open";
const RETIRED_PAGE: &str = "terminal page is no longer active";
pub struct PtyState {
inner: Mutex<Sessions>,
}
#[derive(Default)]
struct Sessions {
open: HashMap<String, OpenPty>,
/// The page IDs of each window, by window label.
pages: HashMap<String, Pages>,
}
/// The page loads of one window. Each page load of the frontend makes a new page ID.
#[derive(Default)]
struct Pages {
current: String,
retired: VecDeque<String>,
}
struct OpenPty {
owner: String,
/// A unique number for this session. A session ID can come back after a reload.
serial: u64,
integration_file: Option<PathBuf>,
master: Box<dyn MasterPty + Send>,
writer: std::sync::Arc<Mutex<Box<dyn Write + Send>>>,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
}
impl Drop for OpenPty {
fn drop(&mut self) {
let _ = self.killer.kill();
if let Some(path) = &self.integration_file { let _ = std::fs::remove_file(path); }
}
}
impl PtyState {
/// Close the window's terminals and forget its pages. Remove the terminals under the lock,
/// then stop the shells outside it.
pub fn close_window(&self, label: &str) {
let closed: Vec<OpenPty> = match self.inner.lock() {
Ok(mut sessions) => {
sessions.pages.remove(label);
take_window(&mut sessions.open, label)
}
Err(_) => return,
};
drop(closed);
}
pub fn close_all(&self) {
let sessions = self
.inner
.lock()
.ok()
.map(|mut sessions| std::mem::take(&mut *sessions));
drop(sessions);
}
pub fn new() -> Self {
Self {
inner: Mutex::new(Sessions::default()),
}
}
}
/// Remove the sessions of one window from the map. The caller stops them outside the lock.
fn take_window(open: &mut HashMap<String, OpenPty>, owner: &str) -> Vec<OpenPty> {
let ids: Vec<String> = open.iter().filter(|(_, session)| session.owner == owner).map(|(id, _)| id.clone()).collect();
ids.iter().filter_map(|id| open.remove(id)).collect()
}
/// The number of open sessions of all windows.
fn running(pty: &PtyState) -> Result<usize> {
Ok(pty.inner.lock().map_err(|_| Error::new("pty lock"))?.open.len())
}
/// A page ID has 1 to 64 ASCII letters, digits, and hyphens.
fn check_page(page: &str) -> Result<()> {
if page.is_empty() || page.len() > 64 || !page.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
return Err(Error::new("Invalid terminal page ID"));
}
Ok(())
}
/// Apply the page rule to an open request of the window `owner`. A new page is a reload of
/// the window. It retires the current page and returns the sessions of the earlier page.
/// The caller stops them outside the lock. A retired page gets an error, so a late request
/// of an old page cannot close the sessions of the new page.
fn enter_page(sessions: &mut Sessions, owner: &str, page: &str) -> Result<Vec<OpenPty>> {
let Some(pages) = sessions.pages.get_mut(owner) else {
sessions.pages.insert(owner.to_owned(), Pages { current: page.to_owned(), retired: VecDeque::new() });
return Ok(Vec::new());
};
if pages.current == page {
return Ok(Vec::new());
}
if pages.retired.iter().any(|retired| retired == page) {
return Err(Error::new(RETIRED_PAGE));
}
let earlier = std::mem::replace(&mut pages.current, page.to_owned());
pages.retired.push_back(earlier);
while pages.retired.len() > RETIRED_PAGES {
pages.retired.pop_front();
}
Ok(take_window(&mut sessions.open, owner))
}
/// The destination of the output and the exit status of one terminal session.
trait PtyOutput: Send {
fn data(&self, bytes: &[u8]);
fn exit(&self, code: Option<u32>);
}
/// A channel to the webview that opened the session. Output goes as raw bytes (an
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
struct ChannelOutput(Channel<InvokeResponseBody>);
impl PtyOutput for ChannelOutput {
fn data(&self, bytes: &[u8]) {
let _ = self.0.send(InvokeResponseBody::Raw(bytes.to_vec()));
}
fn exit(&self, code: Option<u32>) {
let _ = self.0.send(InvokeResponseBody::Json(serde_json::json!({ "exit": code }).to_string()));
}
}
/// Read the PTY until EOF and send each read to `chunks`.
fn read_chunks(mut reader: impl Read, chunks: std::sync::mpsc::Sender<Vec<u8>>) {
let mut buf = vec![0u8; 16 * 1024];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
if chunks.send(buf[..n].to_vec()).is_err() { break; }
}
}
}
}
/// Join the output chunks into messages, then send the exit status. A message starts with
/// the first chunk that arrives. It collects more chunks until `wait` after that chunk or
/// until `max_bytes`. A chunk that does not fit starts the next message. A chunk larger than
/// `max_bytes` goes in parts. When the reader stops, the loop sends the rest of the output
/// and then the exit status.
fn pump(chunks: Receiver<Vec<u8>>, exit: Receiver<Option<u32>>, output: &dyn PtyOutput, max_bytes: usize, wait: Duration) {
let max_bytes = max_bytes.max(1);
let mut next: Option<Vec<u8>> = None;
loop {
let mut message = match next.take() {
Some(chunk) => chunk,
None => match chunks.recv() {
Ok(chunk) => chunk,
Err(_) => break,
},
};
let deadline = Instant::now() + wait;
let mut ended = false;
while message.len() < max_bytes {
let now = Instant::now();
if now >= deadline { break; }
match chunks.recv_timeout(deadline - now) {
Ok(chunk) if message.len() + chunk.len() > max_bytes => {
next = Some(chunk);
break;
}
Ok(chunk) => message.extend(chunk),
Err(RecvTimeoutError::Timeout) => break,
Err(RecvTimeoutError::Disconnected) => {
ended = true;
break;
}
}
}
for part in message.chunks(max_bytes) {
output.data(part);
}
if ended { break; }
}
output.exit(exit.recv().ok().flatten());
}
type ShellProcess = (
OpenPty,
Box<dyn Read + Send>,
Box<dyn portable_pty::Child + Send + Sync>,
);
#[derive(Clone, Serialize)]
pub struct ShellProfile {
id: String,
title: String,
kind: String,
#[serde(skip)]
executable: PathBuf,
}
/// The installed shells. The search reads `PATH` folders, so it runs on a blocking worker.
#[tauri::command]
pub async fn pty_profiles() -> Result<Vec<ShellProfile>> {
Ok(tauri::async_runtime::spawn_blocking(profiles).await?)
}
fn profiles() -> Vec<ShellProfile> {
let candidates = if cfg!(windows) {
vec![("powershell", "PowerShell", "powershell", "powershell.exe"),
("pwsh", "PowerShell 7", "powershell", "pwsh.exe"),
("cmd", "Command Prompt", "cmd", "cmd.exe"),
("node", "JavaScript Debug Terminal", "node", "node.exe")]
} else {
vec![("bash", "Bash", "bash", "bash"), ("pwsh", "PowerShell", "powershell", "pwsh"),
("node", "JavaScript Debug Terminal", "node", "node")]
};
let mut profiles: Vec<_> = candidates.into_iter().filter_map(|(id, title, kind, exe)| {
find_executable(exe).map(|executable| ShellProfile { id: id.into(), title: title.into(), kind: kind.into(), executable })
}).collect();
if cfg!(windows) {
let mut paths = Vec::new();
for variable in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
if let Some(base) = std::env::var_os(variable) {
paths.push(PathBuf::from(&base).join("Git/bin/bash.exe"));
paths.push(PathBuf::from(base).join("Programs/Git/bin/bash.exe"));
}
}
if let Some(git) = find_executable("git.exe") {
if let Some(base) = git.parent().and_then(Path::parent) { paths.push(base.join("bin/bash.exe")); }
}
if let Some(executable) = paths.into_iter().find(|path| path.is_file()) {
profiles.insert(1.min(profiles.len()), ShellProfile { id: "git-bash".into(), title: "Git Bash".into(), kind: "bash".into(), executable });
}
}
profiles
}
// Prompt hooks report executed commands and directories rather than recording keystrokes
// (which could include passwords entered into a child application).
const POWERSHELL_INTEGRATION: &str = r#"
$global:__rsHistory = -1
$global:__rsOriginalPrompt = $function:prompt
function global:prompt {
$esc = [char]27; $bel = [char]7
$h = Get-History -Count 1
if ($h -and $h.Id -ne $global:__rsHistory) {
$global:__rsHistory = $h.Id
$b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($h.CommandLine))
[Console]::Write("${esc}]633;RSCommand;${b}${bel}")
}
$b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($pwd.Path))
[Console]::Write("${esc}]633;RSCwd;${b}${bel}${esc}]133;A${bel}")
$p = if ($global:__rsOriginalPrompt) { & $global:__rsOriginalPrompt } else { "PS $pwd> " }
"${p}${esc}]133;B${bel}"
}
"#;
const BASH_INTEGRATION: &str = r#"__rs_prompt() {
local entry
entry="$(HISTTIMEFORMAT= builtin history 1)"
if [[ "$entry" != "$__rs_last_history" ]]; then
__rs_last_history="$entry"
entry="$(printf '%s' "$entry" | sed 's/^ *[0-9]* *//')"
[[ -n "$entry" ]] && printf '\033]633;RSCommand;%s\007' "$(printf '%s' "$entry" | base64 | tr -d '\r\n')"
fi
printf '\033]633;RSCwd;%s\007\033]133;A\007' "$(printf '%s' "$(pwd -W 2>/dev/null || printf '%s' "$PWD")" | base64 | tr -d '\r\n')"
}
__rs_last_history="$(HISTTIMEFORMAT= builtin history 1)"
PROMPT_COMMAND=("${PROMPT_COMMAND[@]}" __rs_prompt)
PS1="${PS1}"'\[\e]133;B\a\]'
"#;
fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner: &str) -> Result<ShellProcess> {
let system = native_pty_system();
let pair = system
.openpty(PtySize {
rows: rows.max(2),
cols: cols.max(2),
pixel_width: 0,
pixel_height: 0,
})
.map_err(Error::from_display)?;
let profiles = profiles();
let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id))
.ok_or_else(|| Error::new("The selected shell is not installed. Select another terminal profile."))?;
let mut cmd = CommandBuilder::new(&selected.executable);
let mut integration_file = None;
match selected.kind.as_str() {
"powershell" => { cmd.args(["-NoLogo", "-NoExit", "-Command", POWERSHELL_INTEGRATION]); }
"bash" => {
// Use a private integration rc file; the user's bashrc still runs first.
let directory = std::env::temp_dir().join("runestone-shell");
std::fs::create_dir_all(&directory)?;
static NEXT_RC: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let sequence = NEXT_RC.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let rc = directory.join(format!("bashrc-{}-{sequence}", std::process::id()));
std::fs::write(&rc, format!("[[ -f ~/.bashrc ]] && source ~/.bashrc\n{BASH_INTEGRATION}"))?;
cmd.args(["--init-file", &rc.to_string_lossy().replace('\\', "/"), "-i"]);
integration_file = Some(rc);
}
// The cmd prompt cannot encode base64, so it reports the folder as plain text with `Cwd`.
// The Terminal feature reads both `Cwd` (plain) and `RSCwd` (base64). A Windows path
// cannot contain the escape or bell characters that end the sequence.
"cmd" => { cmd.args(["/D", "/K", "prompt $E]633;Cwd;$P$E\\$E]133;A$E\\$P$G$E]133;B$E\\"]); }
"node" => { cmd.args(["--inspect=127.0.0.1:0", "-i"]); }
_ => return Err(Error::new("Unsupported shell profile")),
}
cmd.cwd(root);
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
let reader = pair
.master
.try_clone_reader()
.map_err(Error::from_display)?;
let writer = pair.master.take_writer().map_err(Error::from_display)?;
let child = pair
.slave
.spawn_command(cmd)
.map_err(Error::from_display)?;
drop(pair.slave);
static NEXT_SERIAL: AtomicU64 = AtomicU64::new(0);
let session = OpenPty {
owner: owner.into(),
serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed),
integration_file,
master: pair.master,
writer: std::sync::Arc::new(Mutex::new(writer)),
killer: child.clone_killer(),
};
Ok((session, reader, child))
}
/// Start a shell on a blocking worker, because the start creates a process and files.
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn pty_open(
app: AppHandle,
window: tauri::Window,
webview: tauri::Webview,
workspace: State<'_, WorkspaceState>,
id: String,
page: String,
cols: u16,
rows: u16,
cwd: String,
profile: Option<String>,
directory: Option<String>,
channel: JavaScriptChannelId,
) -> Result<()> {
check_page(&page)?;
let root = current_root(&workspace, window.label())?;
if root.to_string_lossy() != cwd {
return Err(Error::new("workspace changed before the terminal started"));
}
let owner = window.label().to_owned();
let output = ChannelOutput(channel.channel_on(webview));
let request = OpenRequest { owner, page, id, cols, rows, profile, directory: directory.map(PathBuf::from).unwrap_or(root) };
tauri::async_runtime::spawn_blocking(move || open(app, request, output)).await?
}
struct OpenRequest {
owner: String,
page: String,
id: String,
cols: u16,
rows: u16,
profile: Option<String>,
directory: PathBuf,
}
/// Apply the page rule and start the shell under one lock, so two opens cannot race.
fn open(app: AppHandle, request: OpenRequest, output: impl PtyOutput + 'static) -> Result<()> {
let pty = app.state::<PtyState>();
let (left, started) = {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let left = enter_page(&mut guard, &request.owner, &request.page)?;
(left, start(&mut guard, &request))
};
// A reload left these sessions. Stop their shells outside the lock.
drop(left);
let (serial, reader, mut child) = started?;
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let wait_app = app.clone();
let wait_id = request.id;
thread::spawn(move || {
let code = child.wait().ok().map(|status| status.exit_code());
// Close ConPTY after the shell exits so the output reader reaches EOF.
// A later session can use the same ID, so remove only this session.
let session = wait_app
.state::<PtyState>()
.inner
.lock()
.ok()
.and_then(|mut sessions| match sessions.open.get(&wait_id) {
Some(session) if session.serial == serial => sessions.open.remove(&wait_id),
_ => None,
});
drop(session);
let _ = exit_tx.send(code);
});
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
thread::spawn(move || read_chunks(reader, chunk_tx));
thread::spawn(move || pump(chunk_rx, exit_rx, &output, BATCH_BYTES, BATCH_WAIT));
Ok(())
}
type StartedShell = (u64, Box<dyn Read + Send>, Box<dyn portable_pty::Child + Send + Sync>);
/// Start the shell and insert its session. The caller holds the lock.
fn start(sessions: &mut Sessions, request: &OpenRequest) -> Result<StartedShell> {
if sessions.open.contains_key(&request.id) {
return Err(Error::new("terminal already exists"));
}
if !request.directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
let (session, reader, child) = spawn_shell(&request.directory, request.cols, request.rows, request.profile.as_deref(), &request.owner)?;
let serial = session.serial;
sessions.open.insert(request.id.clone(), session);
Ok((serial, reader, child))
}
/// Find a session of the window `owner`. A session of another window gives the same error
/// as a missing session.
fn owned<'a>(sessions: &'a Sessions, owner: &str, id: &str) -> Result<&'a OpenPty> {
sessions.open.get(id).filter(|session| session.owner == owner).ok_or_else(|| Error::new(NOT_OPEN))
}
/// Write input on a blocking worker. A shell that does not read its input can fill the pipe,
/// and the write then waits. The Terminal feature waits for each write before the next one.
#[tauri::command]
pub async fn pty_write(app: AppHandle, window: tauri::Window, id: String, data: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || write(&app.state::<PtyState>(), &owner, &id, &data)).await?
}
fn write(pty: &PtyState, owner: &str, id: &str, data: &str) -> Result<()> {
let writer = {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
owned(&guard, owner, id)?.writer.clone()
};
// Other terminals stay usable while this write waits.
let mut writer = writer.lock().map_err(|_| Error::new("pty writer lock"))?;
writer
.write_all(data.as_bytes())
.map_err(Error::from_display)?;
writer.flush().ok();
Ok(())
}
#[tauri::command]
pub fn pty_resize(pty: State<PtyState>, window: tauri::Window, id: String, cols: u16, rows: u16) -> Result<()> {
resize(&pty, window.label(), &id, cols, rows)
}
fn resize(pty: &PtyState, owner: &str, id: &str, cols: u16, rows: u16) -> Result<()> {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
owned(&guard, owner, id)?
.master
.resize(PtySize {
rows: rows.max(2),
cols: cols.max(2),
pixel_width: 0,
pixel_height: 0,
})
.map_err(Error::from_display)?;
Ok(())
}
/// Stop a shell on a blocking worker. Closing a pseudo console can wait for its output.
/// A missing session and a session of another window are not an error. Neither one closes.
#[tauri::command]
pub async fn pty_close(app: AppHandle, window: tauri::Window, id: String) -> Result<()> {
let owner = window.label().to_owned();
tauri::async_runtime::spawn_blocking(move || {
let session = close(&app.state::<PtyState>(), &owner, &id)?;
drop(session);
Ok(())
})
.await?
}
/// Remove a session of the window `owner` under the lock. The caller stops it outside the lock.
fn close(pty: &PtyState, owner: &str, id: &str) -> Result<Option<OpenPty>> {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if owned(&guard, owner, id).is_err() {
return Ok(None);
}
Ok(guard.open.remove(id))
}
/// The number of open terminals of all windows. The Settings window asks before Terminal
/// goes off when shells run.
#[tauri::command]
pub fn pty_running(pty: State<PtyState>) -> Result<usize> {
running(&pty)
}
#[tauri::command]
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> Result<()> {
let root = current_root(&workspace, window.label())?;
if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(Error::new("Invalid window ID")); }
let mut url = tauri::Url::parse("http://localhost/").map_err(Error::from_display)?;
url.query_pairs_mut().append_pair("terminalWindow", &root.to_string_lossy());
let label = format!("terminal-{id}");
if app.get_webview_window(&label).is_some() { return Err(Error::new("Terminal window already exists")); }
workspace.bind_terminal(&label, root)?;
let result = tauri::WebviewWindowBuilder::new(&app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into()))
.title("RuneStone — Terminal").inner_size(1000.0, 650.0).min_inner_size(500.0, 300.0).build()
.map_err(Error::from_display);
if result.is_err() { workspace.close_window(&label); }
result?;
Ok(())
}
#[tauri::command]
pub fn pty_dictation() -> Result<()> {
#[cfg(windows)]
{
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN};
// The frontend focuses xterm before invoking Windows voice typing.
unsafe {
keybd_event(VK_LWIN as u8, 0, 0, 0);
keybd_event(b'H', 0, 0, 0);
keybd_event(b'H', 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_LWIN as u8, 0, KEYEVENTF_KEYUP, 0);
}
Ok(())
}
#[cfg(not(windows))]
{ Err(Error::new("Use your operating system's dictation shortcut with the terminal focused.")) }
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Debug, PartialEq)]
enum Sent {
Data(Vec<u8>),
Exit(Option<u32>),
}
/// Records the messages that a session sends.
#[derive(Clone, Default)]
struct Recorder(Arc<Mutex<Vec<Sent>>>);
impl PtyOutput for Recorder {
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(Sent::Data(bytes.to_vec())); }
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(Sent::Exit(code)); }
}
impl Recorder {
fn take(&self) -> Vec<Sent> { std::mem::take(&mut *self.0.lock().unwrap()) }
}
type Pump = (std::sync::mpsc::Sender<Vec<u8>>, std::sync::mpsc::Sender<Option<u32>>, Recorder, thread::JoinHandle<()>);
/// Run the batch loop on its own thread. The test sends the chunks and the exit status.
fn start_pump(max_bytes: usize, wait: Duration) -> Pump {
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
let recorder = Recorder::default();
let output = recorder.clone();
let handle = thread::spawn(move || pump(chunk_rx, exit_rx, &output, max_bytes, wait));
(chunk_tx, exit_tx, recorder, handle)
}
fn data_sizes(sent: &[Sent]) -> Vec<usize> {
sent.iter().filter_map(|message| match message { Sent::Data(bytes) => Some(bytes.len()), Sent::Exit(_) => None }).collect()
}
#[test]
fn small_chunks_within_the_wait_become_one_message() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
for _ in 0..100 { chunks.send(b"ab".to_vec()).unwrap(); }
drop(chunks);
exit.send(Some(0)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"ab".repeat(100)), Sent::Exit(Some(0))]);
}
#[test]
fn output_larger_than_the_limit_becomes_several_messages() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_secs(5));
let mut expected: Vec<u8> = Vec::new();
for index in 0..40u8 {
let chunk = vec![index; 4000];
expected.extend(&chunk);
chunks.send(chunk).unwrap();
}
// One chunk larger than the limit goes in parts.
let large = vec![b'x'; BATCH_BYTES + 100];
expected.extend(&large);
chunks.send(large).unwrap();
drop(chunks);
exit.send(None).unwrap();
handle.join().unwrap();
let sent = recorder.take();
let sizes = data_sizes(&sent);
assert!(sizes.len() > 1, "{sizes:?}");
assert!(sizes.iter().all(|&size| size > 0 && size <= BATCH_BYTES), "{sizes:?}");
let joined: Vec<u8> = sent.iter().flat_map(|message| match message { Sent::Data(bytes) => bytes.clone(), Sent::Exit(_) => Vec::new() }).collect();
assert_eq!(joined, expected);
assert_eq!(sent.last(), Some(&Sent::Exit(None)));
}
#[test]
fn a_chunk_after_a_pause_goes_in_a_new_message() {
let (chunks, exit, recorder, handle) = start_pump(BATCH_BYTES, Duration::from_millis(20));
chunks.send(b"first".to_vec()).unwrap();
thread::sleep(Duration::from_millis(300));
chunks.send(b"second".to_vec()).unwrap();
drop(chunks);
exit.send(Some(1)).unwrap();
handle.join().unwrap();
assert_eq!(recorder.take(), vec![Sent::Data(b"first".to_vec()), Sent::Data(b"second".to_vec()), Sent::Exit(Some(1))]);
}
#[test]
fn the_exit_comes_after_all_output() {
let (chunks, exit, recorder, handle) = start_pump(16, Duration::from_secs(5));
// The exit status is ready before the output ends.
exit.send(Some(9)).unwrap();
for _ in 0..10 { chunks.send(b"0123456789".to_vec()).unwrap(); }
drop(chunks);
handle.join().unwrap();
let sent = recorder.take();
assert_eq!(data_sizes(&sent).iter().sum::<usize>(), 100);
assert!(data_sizes(&sent).iter().all(|&size| size <= 16));
assert_eq!(sent.iter().position(|message| matches!(message, Sent::Exit(_))), Some(sent.len() - 1));
assert_eq!(sent.last(), Some(&Sent::Exit(Some(9))));
}
#[test]
fn a_channel_session_sends_raw_bytes_then_the_json_exit() {
let received = Arc::new(Mutex::new(Vec::new()));
let sink = received.clone();
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
let (chunk_tx, chunk_rx) = std::sync::mpsc::channel();
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
exit_tx.send(Some(3)).unwrap();
read_chunks(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), chunk_tx);
pump(chunk_rx, exit_rx, &ChannelOutput(channel), BATCH_BYTES, BATCH_WAIT);
let received = received.lock().unwrap();
assert_eq!(received.len(), 2);
match &received[0] {
InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, b"hello \xce\xbb"),
InvokeResponseBody::Json(json) => panic!("output must be raw bytes, not JSON: {json}"),
}
match &received[1] {
InvokeResponseBody::Json(json) => assert_eq!(serde_json::from_str::<serde_json::Value>(json).unwrap(), serde_json::json!({ "exit": 3 })),
InvokeResponseBody::Raw(_) => panic!("the exit status must be JSON"),
}
}
/// Start a real shell for `owner`. A thread reads its output until EOF.
fn shell(owner: &str) -> OpenPty {
let root = std::env::current_dir().unwrap();
let (session, mut reader, _child) = spawn_shell(&root, 80, 24, None, owner).unwrap();
thread::spawn(move || {
let _ = std::io::copy(&mut reader, &mut std::io::sink());
});
session
}
fn ids(pty: &PtyState) -> Vec<String> {
let mut ids: Vec<String> = pty.inner.lock().unwrap().open.keys().cloned().collect();
ids.sort();
ids
}
#[test]
fn only_the_owner_window_can_use_a_session() {
let pty = PtyState::new();
pty.inner.lock().unwrap().open.insert("t1".into(), shell("a"));
assert_eq!(write(&pty, "b", "t1", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "b", "t1", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "b", "t1").unwrap().is_none());
assert_eq!(ids(&pty), vec!["t1"]);
// A missing session gives the same results.
assert_eq!(write(&pty, "a", "t2", "\r").unwrap_err().to_string(), NOT_OPEN);
assert_eq!(resize(&pty, "a", "t2", 100, 40).unwrap_err().to_string(), NOT_OPEN);
assert!(close(&pty, "a", "t2").unwrap().is_none());
write(&pty, "a", "t1", "\r").unwrap();
resize(&pty, "a", "t1", 100, 40).unwrap();
let session = close(&pty, "a", "t1").unwrap();
assert!(session.is_some());
assert!(ids(&pty).is_empty());
drop(session);
}
#[test]
fn a_new_page_closes_the_sessions_of_its_window_only() {
let pty = PtyState::new();
let enter = |owner: &str, page: &str| enter_page(&mut pty.inner.lock().unwrap(), owner, page);
// The first page of each window becomes current.
assert!(enter("a", "page-1").unwrap().is_empty());
assert!(enter("b", "page-b").unwrap().is_empty());
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
// A second dock of the same page keeps the sessions.
assert!(enter("a", "page-1").unwrap().is_empty());
assert_eq!(ids(&pty), vec!["a1", "b1"]);
// A reload of window "a" closes its sessions. The session of window "b" stays.
let left = enter("a", "page-2").unwrap();
assert_eq!(left.iter().map(|session| session.owner.as_str()).collect::<Vec<_>>(), vec!["a"]);
drop(left);
assert_eq!(ids(&pty), vec!["b1"]);
// A late open of the old page is refused and closes nothing.
pty.inner.lock().unwrap().open.insert("a2".into(), shell("a"));
assert_eq!(enter("a", "page-1").err().map(|error| error.to_string()).as_deref(), Some(RETIRED_PAGE));
assert_eq!(ids(&pty), vec!["a2", "b1"]);
// The window forgets its pages when it closes.
pty.close_window("a");
assert_eq!(ids(&pty), vec!["b1"]);
assert!(!pty.inner.lock().unwrap().pages.contains_key("a"));
assert!(enter("a", "page-1").unwrap().is_empty());
pty.close_all();
assert!(ids(&pty).is_empty());
assert!(pty.inner.lock().unwrap().pages.is_empty());
}
#[test]
fn a_window_keeps_a_limited_number_of_retired_pages() {
let mut sessions = Sessions::default();
for index in 0..=RETIRED_PAGES + 4 {
assert!(enter_page(&mut sessions, "a", &format!("page-{index}")).unwrap().is_empty());
}
let pages = &sessions.pages["a"];
assert_eq!(pages.retired.len(), RETIRED_PAGES);
assert_eq!(pages.current, format!("page-{}", RETIRED_PAGES + 4));
assert!(enter_page(&mut sessions, "a", &format!("page-{}", RETIRED_PAGES + 3)).is_err());
}
#[test]
fn page_ids_are_checked() {
assert!(check_page("0f3c-9a1b").is_ok());
assert!(check_page(&"a".repeat(64)).is_ok());
for page in ["", "a b", "../page", "page_1", "λ"] {
assert!(check_page(page).is_err(), "{page}");
}
assert!(check_page(&"a".repeat(65)).is_err());
}
#[test]
fn running_counts_the_sessions_of_all_windows() {
let pty = PtyState::new();
assert_eq!(running(&pty).unwrap(), 0);
{
let mut sessions = pty.inner.lock().unwrap();
sessions.open.insert("a1".into(), shell("a"));
sessions.open.insert("b1".into(), shell("b"));
}
assert_eq!(running(&pty).unwrap(), 2);
pty.close_window("a");
assert_eq!(running(&pty).unwrap(), 1);
pty.close_all();
assert_eq!(running(&pty).unwrap(), 0);
}
#[test]
fn installed_profiles_start_and_report_shell_prompts() {
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
for profile in profiles() {
eprintln!("Checking {}", profile.title);
let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, Some(&profile.id), "profile-test").unwrap();
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let mut buffer = [0u8; 4096];
while let Ok(n) = reader.read(&mut buffer) {
if n == 0 || tx.send(buffer[..n].to_vec()).is_err() { break; }
}
});
let deadline = Instant::now() + Duration::from_secs(15);
let mut bytes = Vec::new();
let mut sent = false;
loop {
if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) {
bytes.extend(chunk);
if bytes.windows(4).any(|w| w == b"\x1b[6n") {
session.writer.lock().unwrap().write_all(b"\x1b[1;1R").unwrap();
// Avoid answering this same query more than once.
for i in 0..bytes.len().saturating_sub(3) { if &bytes[i..i+4] == b"\x1b[6n" { bytes[i] = b' '; } }
}
}
let output = String::from_utf8_lossy(&bytes);
let ready = if profile.kind == "node" { output.contains("Debugger listening") && output.contains('>') } else { output.contains("\x1b]133;B") };
if ready && !sent {
let command = match profile.kind.as_str() {
"powershell" => "Write-Output ('RS_' + 'PROFILE_OK')\r",
"bash" => "printf 'RS_%s\\n' PROFILE_OK\r",
"cmd" => "echo RS_PROFILE_OK\r",
_ => "console.log('RS_' + 'PROFILE_OK')\r",
};
session.writer.lock().unwrap().write_all(command.as_bytes()).unwrap();
sent = true;
}
let history = profile.kind != "powershell" && profile.kind != "bash" || output.contains("\x1b]633;RSCommand;");
if sent && output.contains("RS_PROFILE_OK") && history { break; }
if Instant::now() > deadline {
let _ = child.kill();
panic!("{} failed integration: {output}", profile.title);
}
}
drop(session);
}
}
#[test]
fn real_shell_runs_in_project_and_drains_output_on_exit() {
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
let (session, mut reader, mut child) = spawn_shell(&root, 120, 30, None, "test").unwrap();
let (tx, rx) = std::sync::mpsc::channel();
thread::spawn(move || {
let mut buf = [0u8; 4096];
while let Ok(n) = reader.read(&mut buf) {
if n == 0 {
break;
}
if tx.send(buf[..n].to_vec()).is_err() {
break;
}
}
});
session
.master
.resize(PtySize {
rows: 40,
cols: 100,
pixel_width: 0,
pixel_height: 0,
})
.unwrap();
let command = if cfg!(windows) {
"(Get-Location).Path; [Console]::WriteLine([char]0x03BB); exit 7\r\n"
} else {
"pwd; printf '\\316\\273\\n'; exit 7\n"
};
session
.writer
.lock()
.unwrap()
.write_all(command.as_bytes())
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let mut bytes = Vec::new();
let status = loop {
if let Ok(chunk) = rx.recv_timeout(Duration::from_millis(30)) {
// A real xterm answers cursor-position queries from PSReadLine.
if chunk.windows(4).any(|window| window == b"\x1b[6n") {
session
.writer
.lock()
.unwrap()
.write_all(b"\x1b[1;1R")
.unwrap();
}
bytes.extend(chunk);
}
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if Instant::now() >= deadline {
child.kill().unwrap();
panic!("shell failed to exit: {}", String::from_utf8_lossy(&bytes));
}
};
drop(session);
loop {
match rx.recv_timeout(Duration::from_secs(5)) {
Ok(chunk) => bytes.extend(chunk),
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(_) => panic!("PTY reader did not reach EOF after shell exit"),
}
}
let output = String::from_utf8(bytes).expect("terminal output must be UTF-8");
assert_eq!(status.exit_code(), 7);
assert!(
output.contains(root.to_string_lossy().as_ref()),
"wrong working directory: {output}"
);
assert!(output.contains('λ'), "Unicode output missing: {output}");
}
#[test]
fn dropping_a_session_terminates_its_shell() {
let root = std::env::current_dir().unwrap();
let (session, mut reader, mut child) = spawn_shell(&root, 80, 24, None, "test").unwrap();
thread::spawn(move || {
let _ = std::io::copy(&mut reader, &mut std::io::sink());
});
drop(session);
let deadline = Instant::now() + Duration::from_secs(5);
while child.try_wait().unwrap().is_none() {
assert!(Instant::now() < deadline, "shell survived session disposal");
thread::sleep(Duration::from_millis(30));
}
}
}
+222
View File
@@ -0,0 +1,222 @@
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"));
}
}
+363
View File
@@ -0,0 +1,363 @@
//! Display WebView2 spelling commands through the shared frontend menu.
//! Keep COM event arguments on the WebView thread until selection or cancellation.
use crate::error::Result;
#[cfg(any(windows, test))]
#[derive(Debug, PartialEq)]
enum Selection { Stale, Cancel, Native, Command(i32) }
#[cfg(any(windows, test))]
fn requires_native_label(kind: i32, label: &str) -> bool {
kind != 3 && label.trim().is_empty()
}
#[cfg(any(windows, test))]
fn excluded_command(name: &str, editable: bool) -> bool {
// WebView2 names unsupported OS tools "other", including direction and dictation.
// Keep recognized editor commands without matching localized labels or runtime IDs.
matches!(name, "share" | "writingDirection" | "voiceTyping") || (editable && name == "other")
}
#[cfg(any(windows, test))]
fn selection(current: &str, request: &str, command: Option<i32>, fallback: bool, enabled: &std::collections::HashSet<i32>) -> Selection {
if current != request { return Selection::Stale; }
if fallback { return Selection::Native; }
command.filter(|id| enabled.contains(id)).map(Selection::Command).unwrap_or(Selection::Cancel)
}
#[cfg(windows)]
mod native {
use std::{cell::RefCell, collections::{HashMap, HashSet}};
use serde::Serialize;
use tauri::{Emitter, Manager};
use webview2_com::{take_pwstr, ContextMenuRequestedEventHandler, Microsoft::Web::WebView2::Win32::*};
use windows::core::{Interface, PWSTR, BOOL};
#[derive(Clone, Serialize)]
pub struct Item {
id: i32, name: String, label: String, shortcut: String, kind: i32,
enabled: bool, checked: bool, children: Vec<Item>,
}
#[derive(Clone, Serialize)]
struct Menu { request: String, items: Vec<Item>, fallback_spelling: bool }
fn requires_native(items: &[Item]) -> bool {
items.iter().any(|item| super::requires_native_label(item.kind, &item.label) || requires_native(&item.children))
}
struct Pending {
request: String, args: ICoreWebView2ContextMenuRequestedEventArgs,
deferral: ICoreWebView2Deferral, commands: HashSet<i32>,
}
impl Drop for Pending {
fn drop(&mut self) { unsafe { let _ = self.deferral.Complete(); } }
}
thread_local! {
static PENDING: RefCell<HashMap<String, Pending>> = RefCell::new(HashMap::new());
static INSTALLED: RefCell<HashMap<String, (ICoreWebView2_11, i64)>> = RefCell::new(HashMap::new());
}
unsafe fn text(read: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
let mut value = PWSTR::null();
let result = read(&mut value);
let text = take_pwstr(value);
result.map(|_| text)
}
unsafe fn trim_menu(collection: &ICoreWebView2ContextMenuItemCollection, editable: bool) -> windows::core::Result<u32> {
let mut count = 0;
collection.Count(&mut count)?;
let mut index = 0;
let mut separator = true;
while index < count {
let item = collection.GetValueAtIndex(index)?;
let mut kind = COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND;
item.Kind(&mut kind)?;
let name = text(|value| item.Name(value))?;
let empty_submenu = kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU && trim_menu(&item.Children()?, editable)? == 0;
let is_separator = kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR;
if (!is_separator && super::excluded_command(&name, editable)) || empty_submenu || (is_separator && separator) {
collection.RemoveValueAtIndex(index)?;
count -= 1;
} else {
separator = is_separator;
index += 1;
}
}
if separator && count > 0 {
collection.RemoveValueAtIndex(count - 1)?;
count -= 1;
}
Ok(count)
}
unsafe fn items(collection: ICoreWebView2ContextMenuItemCollection, commands: &mut HashSet<i32>, parent_enabled: bool) -> windows::core::Result<Vec<Item>> {
let mut count = 0;
collection.Count(&mut count)?;
let mut result = Vec::new();
for index in 0..count {
let item = collection.GetValueAtIndex(index)?;
let (mut id, mut kind, mut enabled, mut checked) = (0, COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND, BOOL(0), BOOL(0));
item.CommandId(&mut id)?;
item.Kind(&mut kind)?;
item.IsEnabled(&mut enabled)?;
item.IsChecked(&mut checked)?;
let enabled = parent_enabled && enabled.as_bool();
let children = if kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { items(item.Children()?, commands, enabled)? } else { Vec::new() };
if enabled && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { commands.insert(id); }
result.push(Item {
id, name: text(|value| item.Name(value))?, label: text(|value| item.Label(value))?,
shortcut: text(|value| item.ShortcutKeyDescription(value))?, kind: kind.0,
enabled, checked: checked.as_bool(), children,
});
}
Ok(result)
}
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> crate::error::Result<()> {
let label = window.label().to_owned();
if INSTALLED.with(|installed| installed.borrow().contains_key(&label)) { return Ok(()); }
let app = window.app_handle().clone();
let owner = label.clone();
unsafe {
let core: ICoreWebView2_11 = controller.CoreWebView2()?.cast()?;
let handler = ContextMenuRequestedEventHandler::create(Box::new(move |_, args| {
let Some(args) = args else { return Ok(()); };
let mut editable = BOOL(0);
args.ContextMenuTarget()?.IsEditable(&mut editable)?;
// Filter the original collection so native fallback uses the same commands.
let collection = args.MenuItems()?;
trim_menu(&collection, editable.as_bool())?;
if !editable.as_bool() { return Ok(()); }
let mut commands = HashSet::new();
let entries = items(collection, &mut commands, true)?;
// Windows supplies suggestions when WebView2 omits their labels.
let fallback_spelling = requires_native(&entries) || !entries.iter().any(|item| item.name == "spellCheck" && !item.label.trim().is_empty());
let Some(window) = app.get_webview_window(&owner) else { return Ok(()); };
let pending = Pending { request: uuid::Uuid::new_v4().to_string(), args: args.clone(), deferral: args.GetDeferral()?, commands };
let menu = Menu { request: pending.request.clone(), items: entries, fallback_spelling };
args.SetHandled(true)?;
let previous = PENDING.with(|state| state.borrow_mut().insert(owner.clone(), pending));
drop(previous);
if window.emit("spelling-menu", menu).is_err() {
// Restore the native menu if the frontend cannot receive the request.
let _ = args.SetHandled(false);
let pending = PENDING.with(|state| state.borrow_mut().remove(&owner));
drop(pending);
}
Ok(())
}));
let mut token = 0;
core.add_ContextMenuRequested(&handler, &mut token)?;
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
}
Ok(())
}
pub fn select(label: &str, request: &str, command: Option<i32>, fallback: bool) {
let result = PENDING.with(|state| {
let mut state = state.borrow_mut();
let pending = state.get(label)?;
let choice = super::selection(&pending.request, request, command, fallback, &pending.commands);
if choice == super::Selection::Stale { return None; }
Some((state.remove(label)?, choice))
});
if let Some((pending, choice)) = result {
unsafe {
match choice {
super::Selection::Command(id) => { let _ = pending.args.SetSelectedCommandId(id); }
super::Selection::Native => { let _ = pending.args.SetHandled(false); }
_ => {}
}
}
// Drop completes the deferral after the selected command is set.
}
}
pub fn close(label: &str) {
let pending = PENDING.with(|state| state.borrow_mut().remove(label));
drop(pending);
if let Some((core, token)) = INSTALLED.with(|installed| installed.borrow_mut().remove(label)) {
unsafe { let _ = core.remove_ContextMenuRequested(token); }
}
}
}
#[tauri::command]
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<()> {
#[cfg(windows)] {
let (send, receive) = std::sync::mpsc::channel();
let owner = window.clone();
window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); })?;
tauri::async_runtime::spawn_blocking(move || receive.recv()?).await?
}
#[cfg(not(windows))] { let _ = window; Ok(()) }
}
#[tauri::command]
pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option<i32>, fallback: Option<bool>) -> Result<()> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false)))?;
}
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
Ok(())
}
pub fn close_window(app: &tauri::AppHandle, label: &str) {
#[cfg(windows)] {
let label = label.to_owned();
let _ = app.run_on_main_thread(move || native::close(&label));
}
#[cfg(not(windows))] { let _ = (app, label); }
}
#[tauri::command]
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<()> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::close(&label))?;
}
#[cfg(not(windows))] { let _ = window; }
Ok(())
}
#[derive(serde::Serialize)]
pub struct Suggestions { language: String, words: Vec<String>, misspelled: bool }
#[cfg(windows)]
mod suggestions_worker {
use super::Suggestions;
use crate::error::{Error, Result};
use std::{collections::HashMap, sync::{mpsc, OnceLock}};
use windows::{core::{HSTRING, PWSTR}, Win32::{Globalization::{ISpellChecker, ISpellCheckerFactory, SpellCheckerFactory}, System::Com::{CoInitializeEx, CoUninitialize, CoCreateInstance, CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED}}};
type Reply = Result<Suggestions>;
type Request = (String, Vec<String>, bool, mpsc::SyncSender<Reply>);
static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new();
pub fn request(word: String, languages: Vec<String>, add: bool) -> Reply {
let worker = WORKER.get_or_init(|| {
let (send, receive) = mpsc::channel::<Request>();
std::thread::spawn(move || unsafe {
let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(Error::from);
let apartment_initialized = initialized.is_ok();
let factory: Result<ISpellCheckerFactory> = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(Error::from));
let mut checkers = HashMap::<String, ISpellChecker>::new();
for (word, languages, add, reply) in receive {
let result = (|| -> Reply {
let factory = factory.as_ref().map_err(Clone::clone)?;
for language in languages {
if language.len() > 85 || language.contains('\0') { continue; }
if !checkers.contains_key(&language) {
let tag = HSTRING::from(&language);
if !factory.IsSupported(&tag)?.as_bool() { continue; }
let checker = factory.CreateSpellChecker(&tag)?;
checkers.insert(language.clone(), checker);
}
let checker = &checkers[&language];
let value = HSTRING::from(&word);
if add {
checker.Add(&value)?;
return Ok(Suggestions { language, words: Vec::new(), misspelled: false });
}
let errors = checker.Check(&value)?;
let mut error = None;
errors.Next(&mut error).ok()?;
if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); }
let suggestions = checker.Suggest(&value)?;
let mut words = Vec::new();
for _ in 0..8 {
let mut values = [PWSTR::null()];
let mut count = 0;
suggestions.Next(&mut values, Some(&mut count)).ok()?;
if count == 0 { break; }
let suggestion = webview2_com::take_pwstr(values[0]);
if !suggestion.is_empty() && suggestion != word { words.push(suggestion); }
}
return Ok(Suggestions { language, words, misspelled: true });
}
Err("No spelling dictionary is installed for this language.".into())
})();
let _ = reply.send(result);
}
drop(checkers);
drop(factory);
if apartment_initialized { CoUninitialize(); }
});
send
});
let (reply, receive) = mpsc::sync_channel(1);
worker.send((word, languages, add, reply)).map_err(|_| "The spelling service stopped.".to_owned())?;
receive.recv().map_err(|_| "The spelling service stopped.".to_owned())?
}
}
#[tauri::command]
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions> {
if word.is_empty() || word.len() > 256 || word.contains('\0') || languages.len() > 20 {
return Err("Invalid spelling request.".into());
}
#[cfg(windows)] {
tauri::async_runtime::spawn_blocking(move || suggestions_worker::request(word, languages, add.unwrap_or(false))).await?
}
#[cfg(not(windows))] { let _ = (word, languages, add); Err("System spelling is unavailable.".into()) }
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[cfg(windows)]
#[test]
fn spelling_worker_reuses_the_dictionary_for_repeated_requests() {
let start = std::time::Instant::now();
let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false);
let cold = start.elapsed();
if let Err(error) = &first {
if error.to_string().contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
}
let first = first.unwrap();
assert!(first.misspelled);
assert!(first.words.iter().any(|word| word == "received"));
let start = std::time::Instant::now();
for _ in 0..10 {
let next = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false).unwrap();
assert_eq!(first.words, next.words);
}
eprintln!("Spelling service: cold {cold:?}, average warm {:?}", start.elapsed() / 10);
}
#[test]
fn unrelated_browser_tools_are_removed_without_changing_editor_commands() {
for name in ["share", "writingDirection", "voiceTyping", "other"] { assert!(excluded_command(name, true)); }
assert!(!excluded_command("other", false), "Keep unrelated non-editable native actions");
for name in ["cut", "copy", "paste", "pasteAndMatchStyle", "undo", "redo", "selectAll", "spellCheck", "addToDictionary", "emoji", "copyLink", "custom"] {
assert!(!excluded_command(name, true), "Keep {name}");
}
}
#[test]
fn stale_requests_cannot_select_or_cancel_a_new_menu() {
for command in [None, Some(42)] {
assert_eq!(selection("new", "old", command, false, &HashSet::from([42])), Selection::Stale);
assert_eq!(selection("new", "old", command, true, &HashSet::from([42])), Selection::Stale);
}
}
#[test]
fn only_enabled_commands_from_the_current_request_can_run() {
let enabled = HashSet::from([42]);
assert_eq!(selection("a", "a", Some(42), false, &enabled), Selection::Command(42));
assert_eq!(selection("a", "a", Some(43), false, &enabled), Selection::Cancel);
assert_eq!(selection("a", "a", None, false, &enabled), Selection::Cancel);
}
#[test]
fn unmatched_editable_target_keeps_the_native_menu() {
assert_eq!(selection("a", "a", None, true, &HashSet::new()), Selection::Native);
}
#[test]
fn blank_commands_keep_native_suggestions_but_separators_do_not() {
assert!(requires_native_label(0, ""));
assert!(requires_native_label(0, " "));
assert!(requires_native_label(4, ""));
assert!(!requires_native_label(3, ""));
assert!(!requires_native_label(0, "received"));
}
}
+265
View File
@@ -0,0 +1,265 @@
//! Tab transfer between windows of one workspace.
//!
//! An offer holds a tab's state, including unsaved text, in memory only. It never goes to disk.
//! 1. The source window offers the tab and puts the offer ID in the drag data or the new window URL.
//! 2. The receiving window takes the offer. A take checks the workspace root and the expiry.
//! 3. The receiving window finishes the offer. If it accepted the tab, the host sends
//! `tab-transfer-accepted` to the source window only, and the source closes its tab.
//! A refused offer becomes available again. The source tab stays open until it receives the event.
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use serde::Serialize;
use tauri::{AppHandle, Emitter, State, Window};
use crate::error::{Error, Result};
/// An offer expires after this time if no window took it.
pub const EXPIRY: Duration = Duration::from_secs(120);
/// A taken offer that the receiver never finished is removed after this time.
const TAKEN_EXPIRY: Duration = Duration::from_secs(240);
/// A text buffer holds the text and its saved copy, and an image tab holds a data URL.
pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024;
const MAX_OFFERS: usize = 32;
pub const ACCEPTED_EVENT: &str = "tab-transfer-accepted";
pub const EXPIRED: &str = "This tab transfer expired. Drag the tab again.";
pub const OTHER_WORKSPACE: &str = "Move tabs only between windows of the same workspace.";
struct Offer {
source: String,
root: String,
payload: String,
created: Instant,
taker: Option<String>,
}
#[derive(Serialize, Clone, Debug, PartialEq)]
pub struct Accepted {
pub id: String,
}
#[derive(Default)]
pub struct TabTransferState(Mutex<HashMap<String, Offer>>);
fn check_id(id: &str) -> Result<()> {
uuid::Uuid::parse_str(id).map(|_| ()).map_err(|_| Error::new("Invalid tab transfer."))
}
fn prune(offers: &mut HashMap<String, Offer>, now: Instant) {
offers.retain(|_, offer| {
let age = now.saturating_duration_since(offer.created);
if offer.taker.is_some() { age < TAKEN_EXPIRY } else { age < EXPIRY }
});
}
impl TabTransferState {
/// Keep a tab offer from `source`. The source window creates the ID, because a drag needs its data at once.
pub fn offer(&self, id: &str, source: &str, root: &str, payload: String, now: Instant) -> Result<()> {
check_id(id)?;
if payload.len() > MAX_PAYLOAD_BYTES {
return Err(Error::new("This tab is too large to move to another window. Save it, then open the file in the other window."));
}
serde_json::from_str::<serde::de::IgnoredAny>(&payload).map_err(|_| Error::new("Invalid tab transfer."))?;
let mut offers = self.0.lock()?;
prune(&mut offers, now);
if offers.contains_key(id) { return Err(Error::new("Invalid tab transfer.")); }
if offers.len() >= MAX_OFFERS {
// Remove the oldest open offer. Its source tab stays open.
if let Some(oldest) = offers.iter().filter(|(_, offer)| offer.taker.is_none())
.min_by_key(|(_, offer)| offer.created).map(|(key, _)| key.clone()) {
offers.remove(&oldest);
} else {
return Err(Error::new("Too many tab transfers are in progress. Try again."));
}
}
offers.insert(id.into(), Offer { source: source.into(), root: root.into(), payload, created: now, taker: None });
Ok(())
}
/// Give the offer to `taker` once. A different workspace leaves the offer for another window.
pub fn take(&self, id: &str, taker: &str, root: &str, now: Instant) -> Result<String> {
check_id(id)?;
let mut offers = self.0.lock()?;
prune(&mut offers, now);
let offer = offers.get_mut(id).filter(|offer| offer.taker.is_none()).ok_or_else(|| Error::new(EXPIRED))?;
if offer.root != root { return Err(Error::new(OTHER_WORKSPACE)); }
offer.taker = Some(taker.into());
Ok(offer.payload.clone())
}
/// End the take of `taker`. Return the source window to acknowledge when the taker accepted the tab.
/// A refused offer stays available for another window until it expires.
pub fn finish(&self, id: &str, taker: &str, accepted: bool) -> Result<Option<String>> {
check_id(id)?;
let mut offers = self.0.lock()?;
let Some(offer) = offers.get_mut(id).filter(|offer| offer.taker.as_deref() == Some(taker)) else {
return Err(Error::new(EXPIRED));
};
if !accepted {
offer.taker = None;
return Ok(None);
}
Ok(offers.remove(id).map(|offer| offer.source))
}
/// Withdraw an open offer of `source`. A taken offer stays until its receiver finishes it.
pub fn cancel(&self, id: &str, source: &str) -> Result<()> {
check_id(id)?;
let mut offers = self.0.lock()?;
if offers.get(id).is_some_and(|offer| offer.source == source && offer.taker.is_none()) {
offers.remove(id);
}
Ok(())
}
/// Remove the offers of a closed window, and release the offers that it took.
pub fn release_window(&self, label: &str) {
let Ok(mut offers) = self.0.lock() else { return };
offers.retain(|_, offer| offer.source != label);
for offer in offers.values_mut() {
if offer.taker.as_deref() == Some(label) { offer.taker = None; }
}
}
}
#[tauri::command]
pub async fn tab_transfer_offer(window: Window, state: State<'_, TabTransferState>, id: String, root: String, payload: String) -> Result<String> {
state.offer(&id, window.label(), &root, payload, Instant::now())?;
Ok(id)
}
#[tauri::command]
pub async fn tab_transfer_take(window: Window, state: State<'_, TabTransferState>, id: String, root: String) -> Result<String> {
state.take(&id, window.label(), &root, Instant::now())
}
#[tauri::command]
pub async fn tab_transfer_finish(app: AppHandle, window: Window, state: State<'_, TabTransferState>, id: String, accepted: bool) -> Result<()> {
if let Some(source) = state.finish(&id, window.label(), accepted)? {
// Only the source window closes its tab.
app.emit_to(source.as_str(), ACCEPTED_EVENT, Accepted { id })?;
}
Ok(())
}
#[tauri::command]
pub async fn tab_transfer_cancel(window: Window, state: State<'_, TabTransferState>, id: String) -> Result<()> {
state.cancel(&id, window.label())
}
#[cfg(test)]
mod tests {
use super::*;
const ID: &str = "00000000-0000-4000-8000-000000000001";
const ROOT: &str = "C:\\workspace";
fn offered(now: Instant) -> TabTransferState {
let state = TabTransferState::default();
state.offer(ID, "main", ROOT, r#"{"buffer":{"contents":"unsaved"}}"#.into(), now).unwrap();
state
}
#[test]
fn an_offer_is_taken_once() {
let now = Instant::now();
let state = offered(now);
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap(), r#"{"buffer":{"contents":"unsaved"}}"#);
assert_eq!(state.take(ID, "workspace-3", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"));
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert_eq!(state.finish(ID, "workspace-2", true).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn an_offer_expires_after_two_minutes() {
let now = Instant::now();
let state = offered(now);
assert!(state.take(ID, "workspace-2", ROOT, now + EXPIRY - Duration::from_secs(1)).is_ok());
assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None);
assert_eq!(state.take(ID, "workspace-2", ROOT, now + EXPIRY).unwrap_err().to_string(), EXPIRED);
// A taken offer survives the expiry until its receiver finishes it.
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
state.offer("00000000-0000-4000-8000-000000000002", "main", ROOT, "{}".into(), now + EXPIRY).unwrap();
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"));
}
#[test]
fn a_different_workspace_cannot_take_the_offer_and_leaves_it_open() {
let now = Instant::now();
let state = offered(now);
assert_eq!(state.take(ID, "workspace-2", "C:\\other", now).unwrap_err().to_string(), OTHER_WORKSPACE);
assert!(state.take(ID, "workspace-3", ROOT, now).is_ok());
}
#[test]
fn only_the_taker_finishes_and_only_acceptance_acknowledges_the_source() {
let now = Instant::now();
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED);
// A refusal sends nothing, and another window can take the offer.
assert_eq!(state.finish(ID, "workspace-2", false).unwrap(), None);
state.take(ID, "workspace-3", ROOT, now).unwrap();
// The acknowledgement goes to the source window, not to the taker.
assert_eq!(state.finish(ID, "workspace-3", true).unwrap().as_deref(), Some("main"));
}
#[test]
fn offers_check_the_id_the_size_and_json() {
let now = Instant::now();
let state = TabTransferState::default();
assert!(state.offer("not-a-uuid", "main", ROOT, "{}".into(), now).is_err());
assert!(state.offer(ID, "main", ROOT, "{".into(), now).is_err());
let large = format!("\"{}\"", "x".repeat(MAX_PAYLOAD_BYTES));
assert!(state.offer(ID, "main", ROOT, large, now).unwrap_err().to_string().contains("too large"));
state.offer(ID, "main", ROOT, "{}".into(), now).unwrap();
assert!(state.offer(ID, "main", ROOT, "{}".into(), now).is_err(), "An ID is used once");
assert!(state.take("../x", "workspace-2", ROOT, now).is_err());
}
#[test]
fn the_oldest_open_offer_makes_room_for_a_new_one() {
let now = Instant::now();
let state = TabTransferState::default();
let ids: Vec<String> = (0..=MAX_OFFERS).map(|index| format!("00000000-0000-4000-8000-{index:012}")).collect();
for (index, id) in ids.iter().enumerate() {
state.offer(id, "main", ROOT, "{}".into(), now + Duration::from_millis(index as u64)).unwrap();
}
assert_eq!(state.take(&ids[0], "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
assert!(state.take(&ids[MAX_OFFERS], "workspace-2", ROOT, now).is_ok());
}
#[test]
fn the_source_cancels_only_its_open_offers() {
let now = Instant::now();
let state = offered(now);
state.cancel(ID, "workspace-2").unwrap();
assert!(state.take(ID, "workspace-2", ROOT, now).is_ok());
state.cancel(ID, "main").unwrap();
assert_eq!(state.finish(ID, "workspace-2", true).unwrap().as_deref(), Some("main"), "A taken offer stays until it finishes");
let state = offered(now);
state.cancel(ID, "main").unwrap();
assert_eq!(state.take(ID, "workspace-2", ROOT, now).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn closing_a_window_removes_its_offers_and_releases_its_takes() {
let now = Instant::now();
let state = offered(now);
state.take(ID, "workspace-2", ROOT, now).unwrap();
state.release_window("workspace-2");
assert!(state.take(ID, "workspace-3", ROOT, now).is_ok());
state.release_window("main");
assert_eq!(state.finish(ID, "workspace-3", true).unwrap_err().to_string(), EXPIRED);
}
#[test]
fn the_acknowledgement_names_the_offer() {
assert_eq!(serde_json::to_value(Accepted { id: ID.into() }).unwrap(), serde_json::json!({ "id": ID }));
}
}
+126
View File
@@ -0,0 +1,126 @@
use std::path::PathBuf;
pub(crate) fn find_executable(name: &str) -> Option<PathBuf> {
find_executable_in_path(name, &std::env::var_os("PATH").unwrap_or_default())
}
fn find_executable_in_path(name: &str, search_path: &std::ffi::OsStr) -> Option<PathBuf> {
std::env::split_paths(search_path)
.map(|dir| dir.join(name)).find(|path| {
let Ok(metadata) = path.metadata() else { return false };
if !metadata.is_file() { return false; }
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{ true }
})
}
#[cfg(all(unix, not(target_os = "macos")))]
pub(crate) fn open_external_terminal(folder: &std::path::Path) -> std::io::Result<()> {
spawn_external_terminal(folder, |command| command.spawn().map(|_| ()))
}
#[cfg(all(unix, not(target_os = "macos")))]
fn spawn_external_terminal(
folder: &std::path::Path,
mut spawn: impl FnMut(&mut std::process::Command) -> std::io::Result<()>,
) -> std::io::Result<()> {
// x-terminal-emulator is a Debian alternative, not a cross-desktop standard.
// Explicit directory flags also work with terminals using an existing server.
let candidates = [
("x-terminal-emulator", None),
("gnome-terminal", Some("--working-directory")),
("konsole", Some("--workdir")),
("xfce4-terminal", Some("--working-directory")),
("mate-terminal", Some("--working-directory")),
("lxterminal", Some("--working-directory")),
("xterm", None),
];
for (program, directory_flag) in candidates {
let mut command = std::process::Command::new(program);
command.current_dir(folder);
if let Some(flag) = directory_flag { command.arg(flag).arg(folder); }
match spawn(&mut command) {
Ok(()) => return Ok(()),
Err(reason) if reason.kind() == std::io::ErrorKind::NotFound => continue,
Err(reason) => return Err(std::io::Error::new(reason.kind(), format!("Could not start {program}: {reason}"))),
}
}
Err(std::io::Error::new(std::io::ErrorKind::NotFound,
"No supported external terminal was found. Install a supported terminal emulator or use RuneStone's Terminal plugin."))
}
// Every test here checks Unix behavior.
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn shell_lookup_skips_non_executable_files_and_directories() {
use std::os::unix::fs::PermissionsExt;
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
let root = std::env::temp_dir().join(format!("rs-shell-path-{}-{unique}", std::process::id()));
let first = root.join("first");
let second = root.join("second");
std::fs::create_dir_all(&first).unwrap();
std::fs::create_dir_all(&second).unwrap();
let blocked = first.join("bash");
let executable = second.join("bash");
for path in [&blocked, &executable] { std::fs::write(path, "#!/bin/sh\n").unwrap(); }
std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o644)).unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
let paths = std::env::join_paths([&first, &second]).unwrap();
assert_eq!(find_executable_in_path("bash", &paths), Some(executable.clone()));
std::fs::remove_file(&blocked).unwrap();
std::fs::create_dir(&blocked).unwrap();
assert_eq!(find_executable_in_path("bash", &paths), Some(executable.clone()));
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(find_executable_in_path("bash", &paths).is_none());
std::fs::remove_dir_all(root).unwrap();
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn external_terminal_falls_back_and_preserves_working_directory() {
let folder = std::path::Path::new("/tmp/workspace with spaces");
let mut attempted = Vec::new();
spawn_external_terminal(folder, |command| {
let program = command.get_program().to_string_lossy().into_owned();
attempted.push(program.clone());
assert_eq!(command.get_current_dir(), Some(folder));
if program == "gnome-terminal" {
assert_eq!(command.get_args().collect::<Vec<_>>(), vec![std::ffi::OsStr::new("--working-directory"), folder.as_os_str()]);
Ok(())
} else {
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
}
}).unwrap();
assert_eq!(attempted, ["x-terminal-emulator", "gnome-terminal"]);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn external_terminal_does_not_hide_launch_errors() {
let mut attempts = 0;
let error = spawn_external_terminal(std::path::Path::new("/tmp"), |_| {
attempts += 1;
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
}).unwrap_err();
assert_eq!(attempts, 1);
assert!(error.to_string().contains("Could not start x-terminal-emulator"));
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn external_terminal_reports_missing_emulators() {
let error = spawn_external_terminal(std::path::Path::new("/tmp"), |_| {
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
}).unwrap_err();
assert!(error.to_string().contains("No supported external terminal"));
}
}
+16
View File
@@ -0,0 +1,16 @@
use tauri_plugin_dialog::DialogExt;
use crate::error::{Error, Result};
#[tauri::command]
pub async fn theme_export(app: tauri::AppHandle, contents: String, default_name: String) -> Result<Option<String>> {
if contents.len() > 1_048_576 { return Err("The theme exceeds the 1 MB limit.".into()); }
serde_json::from_str::<serde_json::Value>(&contents).map_err(|_| "The theme contains invalid JSON.")?;
let name = std::path::Path::new(&default_name).file_name().and_then(|name| name.to_str()).unwrap_or("theme.json").to_string();
tauri::async_runtime::spawn_blocking(move || -> Result<Option<String>> {
let Some(file) = app.dialog().file().set_title("Export theme").add_filter("Theme JSON", &["json"]).set_file_name(name).blocking_save_file() else { return Ok(None); };
let path = file.into_path().map_err(Error::from_display)?;
std::fs::write(&path, contents).map_err(|error| format!("Could not export the theme: {error}"))?;
Ok(Some(path.to_string_lossy().into_owned()))
}).await?
}
+31
View File
@@ -0,0 +1,31 @@
//! The window frame: the title bar style of each platform, and Snap Layouts on Windows 11.
use crate::error::Result;
/// Give a window that RuneStone builds at run time the title bar of its platform.
/// Windows and Linux windows draw their own title bar. macOS keeps its native traffic lights over the web content.
pub fn title_bar<'a, R: tauri::Runtime, M: tauri::Manager<R>>(builder: tauri::WebviewWindowBuilder<'a, R, M>) -> tauri::WebviewWindowBuilder<'a, R, M> {
#[cfg(target_os = "macos")]
{ builder.title_bar_style(tauri::TitleBarStyle::Overlay).hidden_title(true) }
#[cfg(not(target_os = "macos"))]
{ builder.decorations(false) }
}
/// Open the Snap Layouts flyout of the focused window, as a native maximize button does on hover.
/// The custom title bar has no native caption buttons, so the host presses Win+Z. A window without focus does nothing.
#[tauri::command]
pub fn window_snap_layouts(window: tauri::Window) -> Result<()> {
#[cfg(windows)]
{
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN};
if !window.is_focused().map_err(crate::error::Error::from_display)? { return Ok(()); }
unsafe {
keybd_event(VK_LWIN as u8, 0, 0, 0);
keybd_event(b'Z', 0, 0, 0);
keybd_event(b'Z', 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_LWIN as u8, 0, KEYEVENTF_KEYUP, 0);
}
}
#[cfg(not(windows))]
{ let _ = window; }
Ok(())
}
File diff suppressed because it is too large Load Diff