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
+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;
}