Add a shared error type and shared file helpers to the Rust host

Replace the three error styles with one Error type and one Result alias in
error.rs. The error crosses IPC as the same plain string as before. The
message text does not change.

Move the shared file mechanics to fsutil.rs. These are the reserved-name
check, the link and junction check, the limited reads, and the atomic
writes. Each module keeps its own path rules, limits, and messages. The
plugin settings writer now flushes its file to disk before the rename.

Remove the current_root_path and list_entries wrappers and an unused mime
value. Use named windows-sys constants for the process, file, drive, and
error codes.

Add a test that compares the command lists in lib.rs, build.rs, and the
capability files. The settings capability must be a subset of the full list.

In Cargo.toml, set the author, keep only the rlib crate type, and remove
the unused thiserror dependency. Remove panic = "abort" from the release
profile. A panic on a worker thread then stops only that thread. It does
not stop the editor with unsaved buffers.
This commit is contained in:
Knotty Wyvern
2026-10-27 22:41:11 -07:00
parent 69f90df571
commit bd46f3a189
18 changed files with 1103 additions and 882 deletions
+1
View File
@@ -58,6 +58,7 @@ Windows is the primary platform. macOS and Linux builds are experimental.
| Module | Responsibility |
| --- | --- |
| `lib.rs` | App setup, command registration, window events |
| `error.rs`, `fsutil.rs` | The shared error type, and the shared file mechanics: name and link checks, limited reads, atomic writes |
| `workspace.rs` | The workspace root of each window, path checks, atomic saves, the file watcher, search |
| `plugins.rs` | Plugin package review, installation, enable state, removal, and recovery |
| `plugin_sources.rs` | Plugin downloads from Gitea releases |
-1
View File
@@ -3145,7 +3145,6 @@ dependencies = [
"tauri-build",
"tauri-plugin-dialog",
"tauri-plugin-opener",
"thiserror 2.0.20",
"uuid",
"webview2-com",
"windows",
+3 -5
View File
@@ -2,12 +2,12 @@
name = "runestone"
version = "0.1.44"
description = "Writing workspace plus script editor"
authors = ["you"]
authors = ["Knotty Wyvern"]
edition = "2021"
[lib]
name = "runestone_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
crate-type = ["rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
@@ -17,7 +17,6 @@ tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2.0.20"
notify = "8.2.0"
ignore = "0.4.33"
dunce = "1.0.5"
@@ -30,7 +29,7 @@ uuid = { version = "1", features = ["v4"] }
reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Input_KeyboardAndMouse"] }
webview2-com = "0.38.2"
windows = { version = "0.61.3", features = ["Win32_Foundation", "Win32_System_Com", "Win32_Globalization"] }
@@ -40,7 +39,6 @@ windows = { version = "0.61.3", features = ["Win32_Foundation", "Win32_System_Co
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true
[package.metadata.runestone]
+36 -82
View File
@@ -1,8 +1,9 @@
use crate::error::{Error, Result};
use crate::fsutil::{self, is_link};
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use std::fs::{self, File, Metadata};
use std::io::Read;
use std::fs;
use std::path::{Component, Path, PathBuf};
use tauri::{AppHandle, Manager, Window};
use tauri_plugin_dialog::DialogExt;
@@ -10,16 +11,12 @@ use tauri_plugin_dialog::DialogExt;
const IMAGE_LIMIT: u64 = 50 * 1024 * 1024;
const SETTINGS_LIMIT: u64 = 1024 * 1024;
const SETTINGS_FILE: &str = ".runestone-backgrounds.json";
type Result<T> = std::result::Result<T, String>;
#[derive(Debug, Serialize)]
pub struct BackgroundFile {
name: String,
}
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn require_plugin(app: &AppHandle, window: &Window, id: &str) -> Result<()> {
app.state::<PluginState>()
@@ -35,26 +32,13 @@ fn folder_root(folder: &Path) -> Result<PathBuf> {
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder).map_err(fail)?;
let root = dunce::canonicalize(folder)?;
if !root.is_dir() {
return Err("The background folder does not exist.".into());
}
Ok(root)
}
fn is_link(metadata: &Metadata) -> bool {
if metadata.file_type().is_symlink() {
return true;
}
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
return metadata.file_attributes() & 0x400 != 0;
}
#[cfg(not(windows))]
false
}
fn supported(name: &str) -> bool {
Path::new(name)
.extension()
@@ -81,11 +65,11 @@ fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
return Err("Supply one PNG, JPEG, GIF, or WebP filename.".into());
}
let path = root.join(name);
let metadata = fs::symlink_metadata(&path).map_err(fail)?;
let metadata = fs::symlink_metadata(&path)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
let resolved = dunce::canonicalize(&path).map_err(fail)?;
let resolved = dunce::canonicalize(&path)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
@@ -95,8 +79,8 @@ fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
fn list_images(folder: &Path) -> Result<Vec<BackgroundFile>> {
let root = folder_root(folder)?;
let mut images = Vec::new();
for entry in fs::read_dir(&root).map_err(fail)? {
let entry = entry.map_err(fail)?;
for entry in fs::read_dir(&root)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
@@ -119,16 +103,9 @@ fn raster_signature(bytes: &[u8]) -> bool {
fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
let root = folder_root(folder)?;
let path = image_path(&root, name)?;
let mut options = File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
// Open the entry itself so a replaced link cannot redirect the read.
options.custom_flags(0x00200000);
}
let file = options.open(&path).map_err(fail)?;
let metadata = file.metadata().map_err(fail)?;
// Open the entry itself so a replaced link cannot redirect the read.
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
@@ -136,13 +113,9 @@ fn read_image(folder: &Path, name: &str) -> Result<Vec<u8>> {
return Err("The background image exceeds 50 MiB.".into());
}
image_path(&root, name)?;
let mut bytes = Vec::new();
file.take(IMAGE_LIMIT + 1)
.read_to_end(&mut bytes)
.map_err(fail)?;
if bytes.len() as u64 > IMAGE_LIMIT {
let Some(bytes) = fsutil::read_to_limit(file, IMAGE_LIMIT)? else {
return Err("The background image exceeds 50 MiB.".into());
}
};
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
@@ -156,9 +129,9 @@ pub async fn backgrounds_default_folder(
id: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
let pictures = app.path().picture_dir().map_err(fail)?;
let pictures = app.path().picture_dir()?;
let folder = pictures.join("RuneStone Backgrounds");
fs::create_dir_all(&folder).map_err(fail)?;
fs::create_dir_all(&folder)?;
require_plugin(&app, &window, &id)?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
}
@@ -180,12 +153,11 @@ pub async fn backgrounds_choose_folder(
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await
.map_err(fail)?;
.await?;
require_plugin(&app, &window, &id)?;
selected
.map(|source| {
let path = source.into_path().map_err(fail)?;
let path = source.into_path().map_err(Error::from_display)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
@@ -200,8 +172,7 @@ pub async fn backgrounds_list(
) -> Result<Vec<BackgroundFile>> {
require_plugin(&app, &window, &id)?;
let result = tauri::async_runtime::spawn_blocking(move || list_images(Path::new(&folder)))
.await
.map_err(fail)??;
.await??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
@@ -217,8 +188,7 @@ pub async fn backgrounds_read(
require_plugin(&app, &window, &id)?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await
.map_err(fail)??;
.await??;
require_plugin(&app, &window, &id)?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
@@ -229,38 +199,29 @@ fn read_image_settings(folder: &Path) -> Result<Option<String>> {
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(fail(error)),
Err(error) => return Err(Error::from(error)),
};
if !metadata.is_file() || is_link(&metadata) || metadata.len() > SETTINGS_LIMIT {
return Err("Image settings must be an ordinary file within 1 MiB.".into());
}
let mut options = File::options();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
options.custom_flags(0x00200000);
}
let file = options.open(&path).map_err(fail)?;
let metadata = file.metadata().map_err(fail)?;
let file = fsutil::open_entry(&path)?;
let metadata = file.metadata()?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Image settings must be an ordinary file, not a link.".into());
}
let mut bytes = Vec::new();
file.take(SETTINGS_LIMIT + 1).read_to_end(&mut bytes).map_err(fail)?;
if bytes.len() as u64 > SETTINGS_LIMIT {
let Some(bytes) = fsutil::read_to_limit(file, SETTINGS_LIMIT)? else {
return Err("Image settings exceed 1 MiB.".into());
}
String::from_utf8(bytes).map(Some).map_err(fail)
};
String::from_utf8(bytes).map(Some).map_err(Error::from)
}
fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
static WRITE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _lock = WRITE_LOCK.lock().map_err(fail)?;
let _lock = WRITE_LOCK.lock()?;
if contents.len() as u64 > SETTINGS_LIMIT {
return Err("Image settings exceed 1 MiB.".into());
}
let value: serde_json::Value = serde_json::from_str(contents).map_err(fail)?;
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)
{
@@ -272,27 +233,18 @@ fn write_image_settings(folder: &Path, contents: &str, expected: Option<&str>) -
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
crate::workspace::write_text(&path, contents, expected).map_err(fail)
fsutil::write_text(&path, contents, expected)
} else {
// Publish a complete new file without replacing a file created by another process.
let temp = root.join(format!(".runestone-backgrounds-{}.tmp", uuid::Uuid::new_v4()));
let result = (|| -> Result<()> {
use std::io::Write;
let mut file = File::options().write(true).create_new(true).open(&temp).map_err(fail)?;
file.write_all(contents.as_bytes()).map_err(fail)?;
file.sync_all().map_err(fail)?;
drop(file);
fs::hard_link(&temp, &path).map_err(fail)
})();
let _ = fs::remove_file(temp);
result
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
}
}
#[tauri::command]
pub async fn backgrounds_read_image_settings(app: AppHandle, window: Window, id: String, folder: String) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await.map_err(fail)??;
let result = tauri::async_runtime::spawn_blocking(move || read_image_settings(Path::new(&folder))).await??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
@@ -304,7 +256,7 @@ pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id
tauri::async_runtime::spawn_blocking(move || {
require_plugin(&app, &window, &id)?;
write_image_settings(Path::new(&folder), &contents, expected.as_deref())
}).await.map_err(fail)?
}).await?
}
#[cfg(test)]
@@ -339,7 +291,7 @@ mod tests {
write_image_settings(&fixture.0, next, Some(first)).unwrap();
assert!(write_image_settings(&fixture.0, r#"{"schema":2,"images":{}}"#, Some(next)).is_err());
assert!(write_image_settings(&fixture.0, &"x".repeat(SETTINGS_LIMIT as usize + 1), Some(next)).is_err());
File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
fs::File::create(fixture.0.join(SETTINGS_FILE)).unwrap().set_len(SETTINGS_LIMIT + 1).unwrap();
assert!(read_image_settings(&fixture.0).is_err());
}
@@ -380,11 +332,13 @@ mod tests {
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.to_string()
.contains("raster"));
let file = File::create(fixture.0.join("large.png")).unwrap();
let file = fs::File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.to_string()
.contains("50 MiB"));
}
@@ -413,7 +367,7 @@ mod tests {
std::os::unix::fs::symlink(&original, &link).unwrap();
#[cfg(windows)]
if let Err(error) = std::os::windows::fs::symlink_file(&original, &link) {
if error.raw_os_error() == Some(1314) {
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.");
return;
}
+40 -44
View File
@@ -11,7 +11,8 @@ use std::{
};
use tauri::{AppHandle, Emitter, Manager, State};
type Result<T> = std::result::Result<T, String>;
use crate::error::{Error, Result};
const PLUGIN: &str = "runestone.browser";
const COMMANDS: &[&str] = &[
"state",
@@ -102,11 +103,8 @@ struct Worker {
healthy: bool,
}
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_data_dir().map_err(fail)?.join("browser"))
Ok(app.path().app_data_dir()?.join("browser"))
}
fn executable(app: &AppHandle) -> Result<PathBuf> {
let name = if cfg!(windows) {
@@ -127,8 +125,7 @@ fn executable(app: &AppHandle) -> Result<PathBuf> {
}
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.resource_dir()?
.join("browser-engine")
.join(name);
if packaged.is_file() {
@@ -141,10 +138,10 @@ fn authenticate_connection(
stream: TcpStream,
token: &str,
) -> Result<Option<(TcpStream, BufReader<TcpStream>)>> {
stream.set_nonblocking(false).map_err(fail)?;
stream.set_nodelay(true).map_err(fail)?;
stream.set_read_timeout(Some(Duration::from_secs(1))).map_err(fail)?;
let mut reader = BufReader::new(stream.try_clone().map_err(fail)?);
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)
@@ -154,18 +151,18 @@ fn authenticate_connection(
return Ok(None);
}
// Windows keeps the timeout on the cloned socket after the original changes.
reader.get_ref().set_read_timeout(None).map_err(fail)?;
stream.set_read_timeout(None).map_err(fail)?;
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)?;
fs::create_dir_all(&directory).map_err(fail)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(fail)?;
listener.set_nonblocking(true).map_err(fail)?;
let port = listener.local_addr().map_err(fail)?.port();
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(),
@@ -186,9 +183,9 @@ impl Worker {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command.spawn().map_err(fail)?;
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() {
@@ -196,7 +193,7 @@ impl Worker {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() {
if Instant::now() >= deadline || child.try_wait()?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
@@ -284,8 +281,8 @@ impl Worker {
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).map_err(fail)?;
self.input.flush().map_err(fail)?;
writeln!(self.input, "{}", message)?;
self.input.flush()?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
@@ -306,7 +303,7 @@ impl Worker {
let requested = self.request("shutdown", json!({}));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if self.child.try_wait().map_err(fail)?.is_some() {
if self.child.try_wait()?.is_some() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
@@ -332,17 +329,17 @@ fn profile_id(value: &str) -> bool {
}
fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> {
if !source.exists() {
fs::create_dir_all(target).map_err(fail)?;
fs::create_dir_all(target)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source).map_err(fail)?;
let metadata = fs::symlink_metadata(source)?;
if metadata.file_type().is_symlink() {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
fs::create_dir_all(target).map_err(fail)?;
for entry in fs::read_dir(source).map_err(fail)? {
let entry = entry.map_err(fail)?;
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)?;
}
} else if metadata.is_file() {
@@ -351,7 +348,7 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
if *files > 50_000 || *bytes > 2_000_000_000 {
return Err("This profile exceeds the duplication limit.".into());
}
fs::copy(source, target).map_err(fail)?;
fs::copy(source, target)?;
} else {
return Err("Unsupported profile entry.".into());
}
@@ -359,11 +356,11 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock().map_err(fail)?;
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().map_err(fail)?.get(owner).is_some_and(|saved| saved == token) {
if self.sessions.lock()?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
@@ -395,7 +392,7 @@ impl BrowserState {
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().map_err(fail)?;
let mut guard = self.inner.lock()?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
@@ -403,7 +400,7 @@ impl BrowserState {
*guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock().map_err(fail)?.windows.insert(owner.to_string());
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!({}))?;
@@ -411,15 +408,15 @@ impl BrowserState {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock().map_err(fail)?;
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().map_err(fail)?.snapshot(result, owner));
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", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock().map_err(fail)?.owners.get(id) {
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()),
@@ -429,26 +426,26 @@ impl BrowserState {
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().map_err(fail)?;
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(fail)?;
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 = 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).decorations(false).disable_drag_drop_handler().build();
if let Err(error) = result {
worker.routing.lock().map_err(fail)?.close(&label);
return Err(fail(error));
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().map_err(fail)?;
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" {
@@ -479,7 +476,7 @@ impl BrowserState {
copy_profile(&source, &destination, &mut 0, &mut 0)?;
*guard = Some(Worker::start(app, routing.clone())?);
let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?;
let snapshot = routing.lock().map_err(fail)?.snapshot(result, owner);
let snapshot = routing.lock()?.snapshot(result, owner);
Ok(snapshot)
}
}
@@ -507,8 +504,7 @@ pub async fn browser_request(
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
})
.await
.map_err(fail)?
.await?
}
#[tauri::command]
pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> {
+11 -9
View File
@@ -3,6 +3,8 @@ 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 {
@@ -15,7 +17,7 @@ impl CompletionState {
#[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, String> {
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()
@@ -31,7 +33,7 @@ pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState
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<(), String> {
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));
@@ -41,29 +43,29 @@ pub async fn completion_request(window: WebviewWindow, state: State<'_, Completi
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 || {
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.".to_string())?;
.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." }.to_string())?;
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); }
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.".to_string())?;
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.".to_string())?;
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.".to_string());
}).await.map_err(|_| "Local completion task stopped.");
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
result?
}
+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");
}
}
+431
View File
@@ -0,0 +1,431 @@
//! 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.
pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
write_temp_then(temp, bytes, || {
fs::hard_link(temp, path)?;
let _ = fs::remove_file(temp);
Ok(())
})
}
/// 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<()> {
if let Some(expected) = expected {
let current = fs::read_to_string(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.as_bytes()).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_to_string(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.
fs::hard_link(backup, path)?;
let _ = fs::remove_file(backup);
Ok(())
}
#[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();
}
#[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();
}
}
+49 -53
View File
@@ -1,4 +1,5 @@
use crate::workspace::{current_root_path, WorkspaceState};
use crate::error::Result;
use crate::workspace::{current_root, WorkspaceState};
use serde::Serialize;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
@@ -34,12 +35,12 @@ pub struct GitLineInfo {
summary: String,
}
fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
fn read_output(mut stream: impl Read) -> Result<Vec<u8>> {
let mut result = Vec::new();
let mut buffer = [0; 8192];
let mut overflow = false;
loop {
let count = stream.read(&mut buffer).map_err(|e| e.to_string())?;
let count = stream.read(&mut buffer)?;
if count == 0 {
break;
}
@@ -59,7 +60,7 @@ fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
}
}
fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
fn run(root: &Path, args: &[&str]) -> Result<Output> {
let mut command = Command::new("git");
command
.current_dir(root)
@@ -88,7 +89,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
command.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW);
}
let mut child = command
.spawn()
@@ -101,7 +102,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
let mut completed = None;
let status = loop {
if completed.is_none() {
completed = child.try_wait().map_err(|e| e.to_string())?;
completed = child.try_wait()?;
}
if let Some(status) = completed {
if out.is_finished() && err.is_finished() {
@@ -115,7 +116,7 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(0x08000000)
.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
@@ -136,24 +137,24 @@ fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
})
}
fn checked(root: &Path, args: &[&str]) -> Result<String, String> {
fn checked(root: &Path, args: &[&str]) -> Result<String> {
let output = run(root, args)?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
return Err(String::from_utf8_lossy(&output.stderr).trim().into());
}
String::from_utf8(output.stdout)
.map_err(|_| "Git returned a filename that is not UTF-8.".into())
}
fn repository(root: &Path) -> Result<(), String> {
fn repository(root: &Path) -> Result<()> {
let top = checked(root, &["rev-parse", "--show-toplevel"])?;
let top = dunce::canonicalize(top.trim()).map_err(|e| e.to_string())?;
let top = dunce::canonicalize(top.trim())?;
if top != root {
return Err("Open the repository root as your workspace to use Git.".into());
}
for argument in ["--absolute-git-dir", "--git-common-dir"] {
let git_dir = checked(root, &["rev-parse", argument])?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim())).map_err(|e| e.to_string())?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim()))?;
if !git_dir.starts_with(root) {
return Err(
"Git metadata must be inside the workspace. Linked worktrees are not supported."
@@ -164,7 +165,7 @@ fn repository(root: &Path) -> Result<(), String> {
Ok(())
}
fn safe_path(root: &Path, value: &str) -> Result<(), String> {
fn safe_path(root: &Path, value: &str) -> Result<()> {
if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
return Err("Choose a relative Git file path inside the workspace.".into());
}
@@ -183,19 +184,19 @@ fn safe_path(root: &Path, value: &str) -> Result<(), String> {
cursor.push(part);
match std::fs::symlink_metadata(&cursor) {
Ok(_) => {
let real = dunce::canonicalize(&cursor).map_err(|e| e.to_string())?;
let real = dunce::canonicalize(&cursor)?;
if !real.starts_with(root) {
return Err("The Git path points outside the workspace.".into());
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
Err(e) => return Err(e.to_string()),
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
fn parse_status(value: &str) -> Result<Vec<GitChange>> {
let mut records = value.split('\0').filter(|s| !s.is_empty());
let mut changes = Vec::new();
while let Some(record) = records.next() {
@@ -224,7 +225,7 @@ fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
Ok(changes)
}
fn status(root: &Path) -> Result<GitStatus, String> {
fn status(root: &Path) -> Result<GitStatus> {
let empty = |available| GitStatus {
available,
repository: false,
@@ -253,19 +254,15 @@ fn status(root: &Path) -> Result<GitStatus, String> {
})
}
fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
fn diff(root: &Path, path: &str, staged: bool) -> Result<String> {
repository(root)?;
safe_path(root, path)?;
let untracked = !staged && checked(root, &["ls-files", "--error-unmatch", "--", path]).is_err();
if untracked {
let file = std::fs::File::open(root.join(path)).map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
file.take(512 * 1024 + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 512 * 1024 {
let file = std::fs::File::open(root.join(path))?;
let Some(bytes) = crate::fsutil::read_to_limit(file, 512 * 1024)? else {
return Ok("This new file is too large to preview (512 KiB limit).".into());
}
};
if bytes.contains(&0) {
return Ok("Binary file. No text preview is available.".into());
}
@@ -297,7 +294,7 @@ fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
checked(root, &args)
}
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String> {
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<()> {
repository(root)?;
if paths.is_empty() || paths.len() > 10000 {
return Err("Choose between 1 and 10,000 files.".into());
@@ -320,7 +317,7 @@ fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String
Ok(())
}
fn commit(root: &Path, message: &str) -> Result<(), String> {
fn commit(root: &Path, message: &str) -> Result<()> {
repository(root)?;
if message.trim().is_empty() || message.len() > 65536 || message.contains('\0') {
return Err("Enter a commit message between 1 and 65,536 bytes.".into());
@@ -329,7 +326,7 @@ fn commit(root: &Path, message: &str) -> Result<(), String> {
Ok(())
}
fn upstream(root: &Path) -> Result<(String, String), String> {
fn upstream(root: &Path) -> Result<(String, String)> {
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
.map_err(|_| "Select a branch outside RuneStone before you push or pull.")?;
let branch = branch.trim();
@@ -360,7 +357,7 @@ fn upstream(root: &Path) -> Result<(String, String), String> {
Ok((remote.into(), merge.into()))
}
fn synchronize(root: &Path, push: bool) -> Result<(), String> {
fn synchronize(root: &Path, push: bool) -> Result<()> {
repository(root)?;
let (remote, reference) = upstream(root)?;
if !push && !status(root)?.changes.is_empty() {
@@ -418,7 +415,7 @@ pub struct GitGraph {
commits: Vec<GitGraphCommit>,
}
fn graph(root: &Path) -> Result<GitGraph, String> {
fn graph(root: &Path) -> Result<GitGraph> {
repository(root)?;
let has_head = run(root, &["rev-parse", "--verify", "HEAD"])?
.status
@@ -480,13 +477,13 @@ pub struct GitCommitDetails {
message: String,
files: Vec<GitCommitFile>,
}
fn commit_id(value: &str) -> Result<(), String> {
fn commit_id(value: &str) -> Result<()> {
if ![40, 64].contains(&value.len()) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err("Select a commit from the Git graph.".into());
}
Ok(())
}
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>> {
let mut records = value.split('\0').filter(|field| !field.is_empty());
let mut files = Vec::new();
while let Some(status) = records.next() {
@@ -497,7 +494,7 @@ fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
}
Ok(files)
}
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails> {
commit_id(id)?;
repository(root)?;
let metadata = checked(root, &["show", "--no-patch", "--no-show-signature", "--format=%H%x00%P%x00%an%x00%aI%x00%B", id, "--"])?;
@@ -511,7 +508,7 @@ fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
let files = parse_commit_files(&checked(root, &args)?)?;
Ok(GitCommitDetails { id: fields[0].into(), parents, author: fields[2].into(), date: fields[3].into(), message: fields[4].trim_end().into(), files })
}
fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String, String> {
fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String> {
let details = commit_details(root, id)?;
safe_path(root, path)?;
let file = details.files.iter().find(|file| file.path == path).ok_or("This file is not part of the selected commit.")?;
@@ -525,7 +522,7 @@ fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String, String> {
checked(root, &args)
}
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, String> {
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>> {
repository(root)?;
safe_path(root, path)?;
if line == 0 {
@@ -558,27 +555,25 @@ fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, Stri
}))
}
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf, String> {
dunce::canonicalize(current_root_path(state, window.label()).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf> {
Ok(dunce::canonicalize(current_root(state, window.label())?)?)
}
async fn task<T: Send + 'static>(
action: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
action: impl FnOnce() -> Result<T> + Send + 'static,
) -> Result<T> {
tauri::async_runtime::spawn_blocking(move || {
let _guard = GIT_LOCK
.lock()
.map_err(|_| "The Git service lock is unavailable.")?;
action()
})
.await
.map_err(|e| e.to_string())?
.await?
}
#[tauri::command]
pub async fn git_status(
window: Window,
state: State<'_, WorkspaceState>,
) -> Result<GitStatus, String> {
) -> Result<GitStatus> {
let root = root(&state, &window)?;
task(move || status(&root)).await
}
@@ -588,7 +583,7 @@ pub async fn git_diff(
state: State<'_, WorkspaceState>,
path: String,
staged: bool,
) -> Result<String, String> {
) -> Result<String> {
let root = root(&state, &window)?;
task(move || diff(&root, &path, staged)).await
}
@@ -597,7 +592,7 @@ pub async fn git_stage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, true)).await
}
@@ -606,7 +601,7 @@ pub async fn git_unstage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, false)).await
}
@@ -615,7 +610,7 @@ pub async fn git_commit(
window: Window,
state: State<'_, WorkspaceState>,
message: String,
) -> Result<(), String> {
) -> Result<()> {
let root = root(&state, &window)?;
task(move || commit(&root, &message)).await
}
@@ -625,37 +620,37 @@ pub async fn git_blame(
state: State<'_, WorkspaceState>,
path: String,
line: u32,
) -> Result<Option<GitLineInfo>, String> {
) -> Result<Option<GitLineInfo>> {
let root = root(&state, &window)?;
task(move || blame(&root, &path, line)).await
}
#[tauri::command]
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, true)).await
}
#[tauri::command]
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<()> {
let root = root(&state, &window)?;
task(move || synchronize(&root, false)).await
}
#[tauri::command]
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph, String> {
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph> {
let root = root(&state, &window)?;
task(move || graph(&root)).await
}
#[tauri::command]
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails, String> {
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails> {
let root = root(&state, &window)?;
task(move || commit_details(&root, &commit)).await
}
#[tauri::command]
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String, String> {
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String> {
let root = root(&state, &window)?;
task(move || commit_diff(&root, &commit, &path)).await
}
@@ -834,6 +829,7 @@ mod tests {
}
assert!(commit(&repo.0, "Must fail")
.unwrap_err()
.to_string()
.contains("Test hook rejected"));
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
}
+4
View File
@@ -114,6 +114,7 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
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(),
@@ -122,10 +123,12 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
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"]);
@@ -135,6 +138,7 @@ fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.to_string()
.contains("Push failed"));
}
+90
View File
@@ -1,3 +1,5 @@
mod error;
mod fsutil;
mod pty;
mod terminal_platform;
mod plugins;
@@ -118,3 +120,91 @@ pub fn run() {
}
});
}
#[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:?}");
}
}
+7 -11
View File
@@ -3,7 +3,8 @@ use reqwest::{blocking::Client, Url};
use serde_json::Value;
use std::{io::Read, time::Duration};
type Result<T> = std::result::Result<T, String>;
use crate::error::Result;
const MAX_METADATA: usize = 2 * 1024 * 1024;
const MAX_ARCHIVE: usize = 100 * 1024 * 1024;
@@ -86,15 +87,9 @@ pub struct Download {
}
fn read_limited(reader: impl Read, limit: usize) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
reader
.take(limit as u64 + 1)
.read_to_end(&mut bytes)
.map_err(|_| "The download was interrupted. Try again.")?;
if bytes.len() > limit {
return Err("The download exceeds its size limit.".into());
}
Ok(bytes)
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.
@@ -142,7 +137,7 @@ fn get(
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}."),
code => format!("The release server returned HTTP {code}.").into(),
});
}
if response
@@ -323,6 +318,7 @@ pub(crate) mod tests {
let url = Url::parse(&base).unwrap();
assert!(get(&client, url.clone(), &url, None, limit)
.unwrap_err()
.to_string()
.contains(message));
handle.join().unwrap();
}
+87 -150
View File
@@ -13,13 +13,12 @@ use tauri_plugin_dialog::DialogExt;
use tauri_plugin_opener::OpenerExt;
use uuid::Uuid;
type Result<T> = std::result::Result<T, String>;
use crate::error::{Error, Result};
use crate::fsutil;
const MAX_FILES: usize = 5000;
const MAX_FILE: u64 = 25 * 1024 * 1024;
const MAX_TOTAL: usize = 100 * 1024 * 1024;
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn uid() -> String {
Uuid::new_v4().to_string()
}
@@ -131,41 +130,11 @@ pub struct PluginState {
}
fn normal_component(name: &str) -> bool {
if name.is_empty() || name == "." || name == ".." || name.ends_with('.') || name.len() > 120 {
return false;
}
if !name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
{
return false;
}
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
!matches!(
stem.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
)
fsutil::is_plain_component(name)
&& name.len() <= 120
&& name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
}
fn valid_id(id: &str) -> bool {
normal_component(id)
@@ -176,18 +145,14 @@ fn valid_id(id: &str) -> bool {
}
fn relative(name: &str) -> Result<PathBuf> {
if name.len() > 180 || !name.split('/').all(normal_component) {
return Err(format!("Invalid package path: {name}"));
return Err(format!("Invalid package path: {name}").into());
}
Ok(name.split('/').collect())
}
fn plain(path: &Path) -> Result<fs::Metadata> {
let meta = fs::symlink_metadata(path).map_err(fail)?;
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
if meta.file_attributes() & 0x400 != 0 {
return Err("Links and junctions are not allowed in plugin paths.".into());
}
let meta = fs::symlink_metadata(path)?;
if fsutil::is_reparse_point(&meta) {
return Err("Links and junctions are not allowed in plugin paths.".into());
}
if meta.file_type().is_symlink() {
return Err("Links are not allowed in plugin paths.".into());
@@ -199,16 +164,8 @@ fn bounded(path: &Path, limit: u64) -> Result<Vec<u8>> {
if !meta.is_file() || meta.len() > limit {
return Err("The package contains an invalid or oversized file.".into());
}
let mut data = Vec::new();
fs::File::open(path)
.map_err(fail)?
.take(limit + 1)
.read_to_end(&mut data)
.map_err(fail)?;
if data.len() as u64 > limit {
return Err("The file exceeds the size limit.".into());
}
Ok(data)
fsutil::read_to_limit(fs::File::open(path)?, limit)?
.ok_or_else(|| "The file exceeds the size limit.".into())
}
fn add_file(
files: &mut BTreeMap<String, Vec<u8>>,
@@ -237,15 +194,14 @@ fn walk(
count: &mut usize,
) -> Result<()> {
plain(directory)?;
for entry in fs::read_dir(directory).map_err(fail)? {
let path = entry.map_err(fail)?.path();
for entry in fs::read_dir(directory)? {
let path = entry?.path();
*count += 1;
if *count > MAX_FILES {
return Err("The package contains too many entries.".into());
}
let name = path
.strip_prefix(root)
.map_err(fail)?
.strip_prefix(root)?
.to_str()
.ok_or("The package path is not UTF-8.")?
.replace('\\', "/");
@@ -300,15 +256,14 @@ fn package(source: &Path) -> Result<Package> {
return Err("The archive exceeds 100 MiB.".into());
}
let mut archive =
zip::ZipArchive::new(fs::File::open(source).map_err(fail)?).map_err(fail)?;
zip::ZipArchive::new(fs::File::open(source)?)?;
if archive.len() > MAX_FILES {
return Err("The archive contains too many entries.".into());
}
let mut archive_names = BTreeSet::new();
for index in 0..archive.len() {
let mut file = archive.by_index(index).map_err(fail)?;
let name = std::str::from_utf8(file.name_raw())
.map_err(fail)?
let mut file = archive.by_index(index)?;
let name = std::str::from_utf8(file.name_raw())?
.trim_end_matches('/')
.to_string();
relative(&name)?;
@@ -326,11 +281,8 @@ fn package(source: &Path) -> Result<Package> {
if file.size() > MAX_FILE {
return Err("An archive file exceeds 25 MiB.".into());
}
let mut bytes = Vec::new();
file.by_ref()
.take(MAX_FILE + 1)
.read_to_end(&mut bytes)
.map_err(fail)?;
let bytes = fsutil::read_to_limit(file.by_ref(), MAX_FILE)?
.ok_or("The package exceeds the file count or size limit.")?;
add_file(&mut files, &mut names, &mut total, name, bytes)?;
}
}
@@ -340,7 +292,7 @@ fn package(source: &Path) -> Result<Package> {
if bytes.len() > 64 * 1024 {
return Err("The manifest exceeds 64 KiB.".into());
}
let manifest: Manifest = serde_json::from_slice(bytes).map_err(fail)?;
let manifest: Manifest = serde_json::from_slice(bytes)?;
if !valid_id(&manifest.id) {
return Err("The plugin ID is invalid.".into());
}
@@ -369,8 +321,7 @@ fn package(source: &Path) -> Result<Package> {
files
.get(&manifest.entry)
.ok_or("The entry module is missing.")?,
)
.map_err(fail)?;
)?;
let hash = fingerprint(&files);
Ok(Package {
manifest,
@@ -394,8 +345,8 @@ fn require_zip(source: &Path) -> Result<()> {
fn safe_child(parent: &Path, child: &Path) -> Result<()> {
plain(parent)?;
plain(child)?;
let parent = dunce::canonicalize(parent).map_err(fail)?;
let resolved = dunce::canonicalize(child).map_err(fail)?;
let parent = dunce::canonicalize(parent)?;
let resolved = dunce::canonicalize(child)?;
if resolved.parent() != Some(parent.as_path()) {
return Err("The plugin path is outside its managed directory.".into());
}
@@ -405,27 +356,26 @@ fn erase(parent: &Path, target: &Path) -> Result<()> {
safe_child(parent, target)?;
fn descend(path: &Path, boundary: &Path) -> Result<()> {
let meta = plain(path)?;
if !dunce::canonicalize(path)
.map_err(fail)?
if !dunce::canonicalize(path)?
.starts_with(boundary)
{
return Err("Removal escaped its managed directory.".into());
}
if meta.is_dir() {
for item in fs::read_dir(path).map_err(fail)? {
descend(&item.map_err(fail)?.path(), boundary)?;
for item in fs::read_dir(path)? {
descend(&item?.path(), boundary)?;
}
fs::remove_dir(path).map_err(fail)
fs::remove_dir(path).map_err(Error::from)
} else {
fs::remove_file(path).map_err(fail)
fs::remove_file(path).map_err(Error::from)
}
}
let boundary = dunce::canonicalize(target).map_err(fail)?;
let boundary = dunce::canonicalize(target)?;
descend(target, &boundary)
}
impl Service {
fn open(root: PathBuf) -> Result<Self> {
fs::create_dir_all(&root).map_err(fail)?;
fs::create_dir_all(&root)?;
plain(&root)?;
for name in [
"plugins",
@@ -437,13 +387,13 @@ impl Service {
if path.exists() {
plain(&path)?;
} else {
fs::create_dir(&path).map_err(fail)?;
fs::create_dir(&path)?;
}
safe_child(&root, &path)?;
}
let state = root.join("plugin-state.json");
let catalog: Catalog = if state.exists() {
serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?).map_err(fail)?
serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?)?
} else {
Catalog::default()
};
@@ -452,7 +402,7 @@ impl Service {
return Err("The plugin catalog contains an invalid ID.".into());
}
if let Some(token) = &record.removal {
Uuid::parse_str(token).map_err(fail)?;
Uuid::parse_str(token)?;
}
}
let mut service = Self {
@@ -485,15 +435,15 @@ impl Service {
}
fn recover_updates(&mut self) -> Result<()> {
let staging = self.directory("plugin-staging")?;
for entry in fs::read_dir(&staging).map_err(fail)? {
let entry = entry.map_err(fail)?;
for entry in fs::read_dir(&staging)? {
let entry = entry?;
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with("update-") || !name.ends_with(".json") { continue; }
let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?).map_err(fail)?;
let journal: UpdateJournal = serde_json::from_slice(&bounded(&entry.path(), 128 * 1024)?)?;
let id = journal.previous.manifest.id.clone();
if !valid_id(&id) { return Err("Invalid plugin update journal.".into()); }
Uuid::parse_str(&journal.backup).map_err(fail)?;
Uuid::parse_str(&journal.staged).map_err(fail)?;
Uuid::parse_str(&journal.backup)?;
Uuid::parse_str(&journal.staged)?;
let target = self.directory("plugins")?.join(&id);
let backup = staging.join(&journal.backup);
let staged = staging.join(&journal.staged);
@@ -509,9 +459,9 @@ impl Service {
if package(&target)?.hash != journal.next_hash || staged.exists() {
return Err("Plugin update recovery requires inspection of the staging directory.".into());
}
fs::rename(&target, &staged).map_err(fail)?;
fs::rename(&target, &staged)?;
}
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&backup, &target)?;
}
}
if !committed {
@@ -536,17 +486,8 @@ impl Service {
plain(&path)?;
}
let temp = self.root.join(format!("plugin-state-{}.tmp", uid()));
let data = serde_json::to_vec_pretty(&self.catalog).map_err(fail)?;
use std::io::Write;
let mut file = fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&temp)
.map_err(fail)?;
file.write_all(&data).map_err(fail)?;
file.sync_all().map_err(fail)?;
drop(file);
fs::rename(&temp, path).map_err(fail)
let data = serde_json::to_vec_pretty(&self.catalog)?;
Ok(fsutil::replace_file(&path, &temp, &data)?)
}
fn row(&self, id: &str) -> Result<PluginRow> {
let record = self
@@ -576,7 +517,7 @@ impl Service {
Some("Plugin files changed. Review them before enabling this plugin.".into()),
),
Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()),
Err(error) => (record.hash.clone(), Some(error)),
Err(error) => (record.hash.clone(), Some(error.to_string())),
};
Ok(PluginRow {
manifest,
@@ -591,8 +532,8 @@ impl Service {
fn snapshot(&mut self) -> Result<Snapshot> {
let mut changed = false;
let directory = self.directory("plugins")?;
for entry in fs::read_dir(&directory).map_err(fail)? {
let path = entry.map_err(fail)?.path();
for entry in fs::read_dir(&directory)? {
let path = entry?.path();
let id = path
.file_name()
.unwrap_or_default()
@@ -643,7 +584,7 @@ impl Service {
fn inspect(&mut self, owner: &str, source: PathBuf) -> CandidateRow {
let token = uid();
let display = source.to_string_lossy().into_owned();
let result = (|| {
let result = (|| -> Result<Manifest> {
let current = package(&source)?;
let previous = self.catalog.plugins.get(&current.manifest.id).cloned();
if let Some(record) = &previous {
@@ -655,7 +596,7 @@ impl Service {
return Err("Refresh the plugin list before installing this package.".into());
}
let staging = self.directory("plugin-staging")?.join(&token);
fs::create_dir(&staging).map_err(fail)?;
fs::create_dir(&staging)?;
for (name, bytes) in &current.files {
let target = staging.join(relative(name)?);
if self
@@ -669,8 +610,8 @@ impl Service {
{
return Err("The installed path would exceed 240 characters.".into());
}
fs::create_dir_all(target.parent().unwrap()).map_err(fail)?;
fs::write(target, bytes).map_err(fail)?;
fs::create_dir_all(target.parent().unwrap())?;
fs::write(target, bytes)?;
}
let manifest = current.manifest.clone();
self.candidates.insert(
@@ -705,7 +646,7 @@ impl Service {
token,
source: display,
manifest: None,
error: Some(error),
error: Some(error.to_string()),
}
}
}
@@ -713,7 +654,7 @@ impl Service {
fn inspect_download(&mut self, owner: &str, download: crate::plugin_sources::Download) -> Result<CandidateRow> {
let parent = self.directory("plugin-staging")?;
let archive = parent.join(format!("{}.zip", uid()));
fs::write(&archive, download.bytes).map_err(fail)?;
fs::write(&archive, download.bytes)?;
let mut row = self.inspect(owner, archive.clone());
if let Some(candidate) = self.candidates.get_mut(&row.token) {
// Review pins the downloaded bytes. Remote releases can change independently.
@@ -753,8 +694,7 @@ impl Service {
}
safe_child(&self.directory("plugin-staging")?, &candidate.directory)?;
let installed_at = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(fail)?
.duration_since(UNIX_EPOCH)?
.as_millis() as u64;
// Persist disabled first. A crash cannot enable unreviewed or partial code.
self.catalog.plugins.insert(
@@ -776,13 +716,13 @@ impl Service {
if let Err(error) = fs::rename(&candidate.directory, &target) {
self.catalog.plugins.remove(&id);
let _ = self.persist();
return Err(fail(error));
return Err(Error::from(error));
}
if enabled {
self.catalog.plugins.get_mut(&id).unwrap().enabled = true;
if let Err(error) = self.persist() {
self.catalog.plugins.get_mut(&id).unwrap().enabled = false;
return Err(format!("Installed but disabled: {error}"));
return Err(format!("Installed but disabled: {error}").into());
}
}
Ok(candidate.manifest.name)
@@ -838,21 +778,21 @@ impl Service {
let journal = UpdateJournal { previous: previous.clone(), next_hash: candidate.hash.clone(),
backup: backup.file_name().unwrap().to_string_lossy().into_owned(),
staged: candidate.directory.file_name().unwrap().to_string_lossy().into_owned() };
fs::write(&journal_path, serde_json::to_vec(&journal).map_err(fail)?).map_err(fail)?;
fs::rename(&target, &backup).map_err(fail)?;
fs::write(&journal_path, serde_json::to_vec(&journal)?)?;
fs::rename(&target, &backup)?;
if let Err(error) = fs::rename(&candidate.directory, &target) {
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&backup, &target)?;
let _ = erase(&staging, &journal_path);
return Err(fail(error));
return Err(Error::from(error));
}
self.catalog.plugins.insert(id.clone(), Installed {
manifest: candidate.manifest.clone(), hash: candidate.hash.clone(), enabled: previous.enabled,
installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH).map_err(fail)?.as_millis() as u64),
installed_at: Some(SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis() as u64),
removal: None, removal_files: BTreeMap::new(),
});
if let Err(error) = self.persist() {
fs::rename(&target, &candidate.directory).map_err(fail)?;
fs::rename(&backup, &target).map_err(fail)?;
fs::rename(&target, &candidate.directory)?;
fs::rename(&backup, &target)?;
self.catalog.plugins.insert(id, previous);
let _ = erase(&staging, &journal_path);
return Err(error);
@@ -927,7 +867,7 @@ impl Service {
if let Some(error) = self.cleanup_errors.get(id) {
return Err(format!(
"Cleanup failed. Restart RuneStone before removal. {error}"
));
).into());
}
let parent = self.directory("plugins")?;
let target = parent.join(id);
@@ -954,7 +894,7 @@ impl Service {
if let Err(error) = fs::rename(&target, &destination) {
self.catalog.plugins.get_mut(id).unwrap().removal = None;
let _ = self.persist();
return Err(fail(error));
return Err(Error::from(error));
}
if tree_hash(&destination)? != current_hash {
return Err("Plugin files changed during removal. Inspect the removal directory before retrying.".into());
@@ -968,7 +908,7 @@ impl Service {
.get(id)
.and_then(|record| record.removal.clone())
.ok_or("No confirmed removal exists.")?;
Uuid::parse_str(&token).map_err(fail)?;
Uuid::parse_str(&token)?;
let parent = self.directory("plugin-removals")?;
let target = parent.join(&token);
if self.directory("plugins")?.join(id).exists() {
@@ -984,7 +924,7 @@ impl Service {
return Err(format!(
"Removal files changed. Inspect {} before retrying.",
target.display()
));
).into());
}
}
erase(&parent, &target)?;
@@ -1010,9 +950,9 @@ impl PluginState {
app: &AppHandle,
action: impl FnOnce(&mut Service) -> Result<T>,
) -> Result<T> {
let mut guard = self.inner.lock().map_err(fail)?;
let mut guard = self.inner.lock()?;
if guard.is_none() {
*guard = Some(Service::open(app.path().app_data_dir().map_err(fail)?)?);
*guard = Some(Service::open(app.path().app_data_dir()?)?);
}
action(guard.as_mut().unwrap())
}
@@ -1060,8 +1000,7 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec
.add_filter("Plugin ZIP archives", &["zip"])
.blocking_pick_files()
})
.await
.map_err(fail)?;
.await?;
let Some(sources) = source else {
return Ok(Vec::new());
};
@@ -1070,7 +1009,7 @@ pub async fn plugins_choose(app: AppHandle, window: tauri::Window) -> Result<Vec
}
let paths: Vec<PathBuf> = sources
.into_iter()
.map(|source| source.into_path().map_err(fail))
.map(|source| source.into_path().map_err(Error::from_display))
.collect::<Result<_>>()?;
for path in &paths {
require_zip(path)?;
@@ -1094,7 +1033,7 @@ pub async fn plugins_from_git(
// Network access never holds the plugin service lock.
let download = tauri::async_runtime::spawn_blocking(move || {
crate::plugin_sources::download(&repository, token.as_deref())
}).await.map_err(fail)??;
}).await??;
app.state::<PluginState>().with(&app, |service| {
Ok(vec![service.inspect_download(window.label(), download)?])
})
@@ -1149,7 +1088,7 @@ pub async fn plugins_install(
let start = Instant::now();
while state.with(&app, |service| Ok(service.leases.get(id).is_some_and(|windows| !windows.is_empty())))?
&& start.elapsed() < Duration::from_secs(10) {
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await.map_err(fail)?;
tauri::async_runtime::spawn_blocking(|| std::thread::sleep(Duration::from_millis(50))).await?;
}
}
let installed = state.with(&app, |service| {
@@ -1168,7 +1107,7 @@ pub async fn plugins_install(
installed.err()
}
};
result.push(InstallResult { name, error });
result.push(InstallResult { name, error: error.map(String::from) });
}
changed(&app);
Ok(result)
@@ -1236,7 +1175,7 @@ pub async fn plugins_load(
.entry(id)
.or_default()
.insert(window.label().into());
String::from_utf8(current.files[&current.manifest.entry].clone()).map_err(fail)
String::from_utf8(current.files[&current.manifest.entry].clone()).map_err(Error::from)
})
}
#[tauri::command]
@@ -1297,8 +1236,7 @@ pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String
result
})
})
.await
.map_err(fail)?;
.await?;
changed(&app);
result
}
@@ -1335,9 +1273,9 @@ pub async fn plugins_reveal(
if open_directory {
app.opener()
.open_path(path.to_string_lossy().into_owned(), None::<&str>)
.map_err(fail)
.map_err(Error::from)
} else {
app.opener().reveal_item_in_dir(path).map_err(fail)
app.opener().reveal_item_in_dir(path).map_err(Error::from)
}
}
#[tauri::command]
@@ -1355,7 +1293,7 @@ pub async fn plugins_data(
let parent = service.directory("plugin-data")?;
let dir = parent.join(&id);
if !dir.exists() {
fs::create_dir(&dir).map_err(fail)?;
fs::create_dir(&dir)?;
}
safe_child(&parent, &dir)?;
let path = dir.join("settings.json");
@@ -1363,16 +1301,15 @@ pub async fn plugins_data(
if value.len() > 1024 * 1024 {
return Err("Plugin settings exceed 1 MiB.".into());
}
serde_json::from_str::<serde_json::Value>(&value).map_err(fail)?;
serde_json::from_str::<serde_json::Value>(&value)?;
if path.exists() {
plain(&path)?;
}
let temp = dir.join(format!("{}.tmp", uid()));
fs::write(&temp, value).map_err(fail)?;
fs::rename(temp, &path).map_err(fail)?;
fsutil::replace_file(&path, &temp, value.as_bytes())?;
}
if path.exists() {
String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(fail)
String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(Error::from)
} else {
Ok("null".into())
}
@@ -1611,10 +1548,10 @@ mod tests {
let candidate = f.service.inspect("main", f.source.clone());
f.service.leases.entry(id.clone()).or_default().insert("main".into());
f.service.begin_update("main", &candidate.token).unwrap();
assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("cleanup"));
assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("cleanup"));
f.service.leases.clear();
fs::write(f.source.join("main.js"), "changed after review").unwrap();
assert!(f.service.install("main", &candidate.token, true).unwrap_err().contains("changed after review"));
assert!(f.service.install("main", &candidate.token, true).unwrap_err().to_string().contains("changed after review"));
assert_eq!(f.service.row(&id).unwrap().manifest.version, "1.0.0");
assert_eq!(fs::read_to_string(f.service.directory("plugins").unwrap().join(&id).join("main.js")).unwrap(), "export function activate() {}");
}
@@ -1684,7 +1621,7 @@ mod tests {
assert!(require_zip(&upper).is_ok());
let wrapped = f.root.join("wrapped.zip");
archive(&wrapped, &[("demo/plugin.json", b"{}")]);
assert!(package(&wrapped).unwrap_err().contains("at its root"));
assert!(package(&wrapped).unwrap_err().to_string().contains("at its root"));
}
#[test]
fn author_packager_produces_an_installable_repeatable_zip() {
@@ -1829,7 +1766,7 @@ mod tests {
assert!(package(&path).is_err());
assert!(!f.root.join("outside").exists());
archive(&path, &[("main.js", b"a"), ("MAIN.js", b"b")]);
assert!(package(&path).unwrap_err().contains("duplicate"));
assert!(package(&path).unwrap_err().to_string().contains("duplicate"));
let manifest = fs::read_to_string(f.source.join("plugin.json"))
.unwrap()
.replace("\"apiVersion\":1", "\"apiVersion\":99");
+34 -39
View File
@@ -8,15 +8,10 @@ use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager, State};
use crate::workspace::{current_root_path, WorkspaceError, WorkspaceState};
use crate::error::{Error, Result};
use crate::workspace::{current_root, WorkspaceState};
use crate::terminal_platform::find_executable;
type PtyResult<T> = Result<T, WorkspaceError>;
fn err(msg: impl Into<String>) -> WorkspaceError {
WorkspaceError::from_message(msg)
}
pub struct PtyState {
inner: Mutex<HashMap<String, OpenPty>>,
}
@@ -153,7 +148,7 @@ 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) -> PtyResult<ShellProcess> {
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 {
@@ -162,10 +157,10 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| err(e.to_string()))?;
.map_err(Error::from_display)?;
let profiles = pty_profiles();
let selected = profiles.iter().find(|p| profile.map_or(p.kind != "node", |id| p.id == id))
.ok_or_else(|| err("The selected shell is not installed. Select another terminal profile."))?;
.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() {
@@ -183,7 +178,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
}
"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(err("Unsupported shell profile")),
_ => return Err(Error::new("Unsupported shell profile")),
}
cmd.cwd(&root);
cmd.env("TERM", "xterm-256color");
@@ -191,12 +186,12 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
let reader = pair
.master
.try_clone_reader()
.map_err(|e| err(e.to_string()))?;
let writer = pair.master.take_writer().map_err(|e| err(e.to_string()))?;
.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(|e| err(e.to_string()))?;
.map_err(Error::from_display)?;
drop(pair.slave);
let session = OpenPty {
owner: owner.into(),
@@ -220,17 +215,17 @@ pub fn pty_open(
cwd: String,
profile: Option<String>,
directory: Option<String>,
) -> PtyResult<()> {
let root = current_root_path(&workspace, window.label())?;
) -> Result<()> {
let root = current_root(&workspace, window.label())?;
if root.to_string_lossy() != cwd {
return Err(err("workspace changed before the terminal started"));
return Err(Error::new("workspace changed before the terminal started"));
}
let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
if guard.contains_key(&id) {
return Err(err("terminal already exists"));
return Err(Error::new("terminal already exists"));
}
let directory = directory.map(PathBuf::from).unwrap_or(root);
if !directory.is_dir() { return Err(err("Terminal working directory does not exist")); }
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), window.label())?;
guard.insert(id.clone(), session);
drop(guard);
@@ -282,21 +277,21 @@ pub fn pty_open(
}
#[tauri::command]
pub fn pty_write(pty: State<PtyState>, id: String, data: String) -> PtyResult<()> {
let guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?;
let mut writer = session.writer.lock().map_err(|_| err("pty writer lock"))?;
pub fn pty_write(pty: State<PtyState>, id: String, data: String) -> Result<()> {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
let mut writer = session.writer.lock().map_err(|_| Error::new("pty writer lock"))?;
writer
.write_all(data.as_bytes())
.map_err(|e| err(e.to_string()))?;
.map_err(Error::from_display)?;
writer.flush().ok();
Ok(())
}
#[tauri::command]
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> PtyResult<()> {
let guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| err("terminal is not open"))?;
pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Result<()> {
let guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.get(&id).ok_or_else(|| Error::new("terminal is not open"))?;
session
.master
.resize(PtySize {
@@ -305,13 +300,13 @@ pub fn pty_resize(pty: State<PtyState>, id: String, cols: u16, rows: u16) -> Pty
pixel_width: 0,
pixel_height: 0,
})
.map_err(|e| err(e.to_string()))?;
.map_err(Error::from_display)?;
Ok(())
}
#[tauri::command]
pub fn pty_close(pty: State<PtyState>, id: String) -> PtyResult<()> {
let mut guard = pty.inner.lock().map_err(|_| err("pty lock"))?;
pub fn pty_close(pty: State<PtyState>, id: String) -> Result<()> {
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
let session = guard.remove(&id);
drop(guard);
drop(session);
@@ -319,24 +314,24 @@ pub fn pty_close(pty: State<PtyState>, id: String) -> PtyResult<()> {
}
#[tauri::command]
pub async fn pty_new_window(app: AppHandle, window: tauri::Window, workspace: State<'_, WorkspaceState>, id: String) -> PtyResult<()> {
let root = current_root_path(&workspace, window.label())?;
if !id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return Err(err("Invalid window ID")); }
let mut url = tauri::Url::parse("http://localhost/").map_err(|e| err(e.to_string()))?;
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(err("Terminal window already exists")); }
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(|e| err(e.to_string()));
.map_err(Error::from_display);
if result.is_err() { workspace.close_window(&label); }
result?;
Ok(())
}
#[tauri::command]
pub fn pty_dictation() -> PtyResult<()> {
pub fn pty_dictation() -> Result<()> {
#[cfg(windows)]
{
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{keybd_event, KEYEVENTF_KEYUP, VK_LWIN};
@@ -350,7 +345,7 @@ pub fn pty_dictation() -> PtyResult<()> {
Ok(())
}
#[cfg(not(windows))]
{ Err(err("Use your operating system's dictation shortcut with the terminal focused.")) }
{ Err(Error::new("Use your operating system's dictation shortcut with the terminal focused.")) }
}
#[cfg(test)]
+22 -21
View File
@@ -2,7 +2,8 @@ use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use tauri::{AppHandle, Manager, State};
use crate::workspace::{current_root_path, WorkspaceState};
use crate::error::Result;
use crate::workspace::{current_root, WorkspaceState};
#[derive(Default)]
pub struct SettingsState(Mutex<HashMap<String, Arc<AtomicBool>>>);
@@ -14,7 +15,7 @@ struct PendingOpen<'a> {
}
impl SettingsState {
fn reserve(&self, label: &str) -> Result<Option<PendingOpen<'_>>, String> {
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) {
@@ -45,7 +46,7 @@ impl Drop for PendingOpen<'_> {
}
}
fn settings_label(owner: &str) -> Result<String, String> {
fn settings_label(owner: &str) -> Result<String> {
if owner == "main" || owner.starts_with("workspace-") {
Ok(format!("settings-{owner}"))
} else {
@@ -53,9 +54,9 @@ fn settings_label(owner: &str) -> Result<String, String> {
}
}
fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<(), String> {
if let Ok(root) = current_root_path(workspace, owner) {
workspace.bind_terminal(label, root).map_err(|error| error.to_string())?;
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);
}
@@ -68,14 +69,14 @@ pub async fn settings_open_window(
window: tauri::Window,
state: State<'_, SettingsState>,
workspace: State<'_, WorkspaceState>,
) -> Result<(), String> {
) -> 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_path(&workspace, window.label()).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_path(&workspace, window.label()).ok(),
&root, &current_root(&workspace, window.label()).ok(),
);
if !valid() { return Err("The workspace closed while settings opened.".into()); }
bind_workspace(&workspace, window.label(), &label)?;
@@ -97,14 +98,14 @@ pub async fn settings_open_window(
.disable_drag_drop_handler()
.build() {
Ok(settings) => settings,
Err(error) => { workspace.close_window(&label); return Err(error.to_string()); }
Err(error) => { workspace.close_window(&label); return Err(error.into()); }
}
};
let result = (|| {
let result = (|| -> Result<()> {
if !valid() { return Err("The workspace changed while settings opened.".into()); }
settings.unminimize().map_err(|error| error.to_string())?;
settings.show().map_err(|error| error.to_string())?;
settings.set_focus().map_err(|error| error.to_string())?;
settings.unminimize()?;
settings.show()?;
settings.set_focus()?;
if !valid() { return Err("The workspace changed while settings opened.".into()); }
Ok(())
})();
@@ -174,7 +175,7 @@ mod tests {
#[test]
fn failed_build_releases_its_reservation_for_retry() {
let state = SettingsState::default();
let failed = || -> Result<(), String> {
let failed = || -> Result<()> {
let _pending = state.reserve("settings-main")?.unwrap();
Err("Native build failed".into())
};
@@ -203,20 +204,20 @@ mod tests {
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_path(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one"));
assert_eq!(current_root_path(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two"));
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_path(&workspace, "settings-workspace-1").is_err());
assert!(current_root_path(&workspace, "workspace-1").is_ok());
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_path(&workspace, "settings-main").is_err());
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_path(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later"));
assert_eq!(current_root(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later"));
}
}
+26 -23
View File
@@ -1,6 +1,8 @@
//! 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) }
@@ -109,13 +111,13 @@ mod native {
Ok(result)
}
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> Result<(), String> {
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().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?;
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);
@@ -143,7 +145,7 @@ mod native {
Ok(())
}));
let mut token = 0;
core.add_ContextMenuRequested(&handler, &mut token).map_err(|e| e.to_string())?;
core.add_ContextMenuRequested(&handler, &mut token)?;
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
}
Ok(())
@@ -179,21 +181,21 @@ mod native {
}
#[tauri::command]
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<(), String> {
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())); }).map_err(|e| e.to_string())?;
tauri::async_runtime::spawn_blocking(move || receive.recv().map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?
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<(), String> {
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))).map_err(|e| e.to_string())?;
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false)))?;
}
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
Ok(())
@@ -208,10 +210,10 @@ pub fn close_window(app: &tauri::AppHandle, label: &str) {
}
#[tauri::command]
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), String> {
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<()> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?;
window.with_webview(move |_| native::close(&label))?;
}
#[cfg(not(windows))] { let _ = window; }
Ok(())
@@ -223,9 +225,10 @@ 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, String>;
type Reply = Result<Suggestions>;
type Request = (String, Vec<String>, bool, mpsc::SyncSender<Reply>);
static WORKER: OnceLock<mpsc::Sender<Request>> = OnceLock::new();
@@ -233,9 +236,9 @@ mod suggestions_worker {
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| error.to_string());
let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok().map_err(Error::from);
let apartment_initialized = initialized.is_ok();
let factory: Result<ISpellCheckerFactory, String> = initialized.and_then(|_| CoCreateInstance(&SpellCheckerFactory, None, CLSCTX_INPROC_SERVER).map_err(|error| error.to_string()));
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 {
@@ -244,26 +247,26 @@ mod suggestions_worker {
if language.len() > 85 || language.contains('\0') { continue; }
if !checkers.contains_key(&language) {
let tag = HSTRING::from(&language);
if !factory.IsSupported(&tag).map_err(|error| error.to_string())?.as_bool() { continue; }
let checker = factory.CreateSpellChecker(&tag).map_err(|error| error.to_string())?;
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).map_err(|error| error.to_string())?;
checker.Add(&value)?;
return Ok(Suggestions { language, words: Vec::new(), misspelled: false });
}
let errors = checker.Check(&value).map_err(|error| error.to_string())?;
let errors = checker.Check(&value)?;
let mut error = None;
errors.Next(&mut error).ok().map_err(|error| error.to_string())?;
errors.Next(&mut error).ok()?;
if error.is_none() { return Ok(Suggestions { language, words: Vec::new(), misspelled: false }); }
let suggestions = checker.Suggest(&value).map_err(|error| error.to_string())?;
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().map_err(|error| error.to_string())?;
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); }
@@ -287,12 +290,12 @@ mod suggestions_worker {
}
#[tauri::command]
pub async fn spelling_suggestions(word: String, languages: Vec<String>, add: Option<bool>) -> Result<Suggestions, String> {
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.map_err(|error| error.to_string())?
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()) }
}
@@ -309,7 +312,7 @@ mod tests {
let first = suggestions_worker::request("recieved".into(), vec!["en-US".into()], false);
let cold = start.elapsed();
if let Err(error) = &first {
if error.contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
if error.to_string().contains("No spelling dictionary") { eprintln!("No English dictionary installed: {error}"); return; }
}
let first = first.unwrap();
assert!(first.misspelled);
+7 -5
View File
@@ -1,14 +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>, String> {
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.".to_string())?;
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 || {
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| error.to_string())?;
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.map_err(|error| error.to_string())?
}).await?
}
+142 -439
View File
File diff suppressed because it is too large Load Diff