Update editor, themes, menus, backgrounds, and release tooling

This commit is contained in:
Knotty Wyvern
2026-10-14 16:19:51 -07:00
parent f6eaa52949
commit edef2520af
113 changed files with 5722 additions and 386 deletions
+425
View File
@@ -0,0 +1,425 @@
use crate::plugins::PluginState;
use base64::Engine;
use serde::Serialize;
use std::fs::{self, File, Metadata};
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use tauri::{AppHandle, Manager, Window};
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>()
.require_lease(app, window.label(), id)
.map_err(|_| "The plugin is not enabled in this window.".into())
}
fn folder_root(folder: &Path) -> Result<PathBuf> {
if !folder.is_absolute()
|| folder
.components()
.any(|part| matches!(part, Component::ParentDir))
{
return Err("Supply an absolute background folder path without parent segments.".into());
}
let root = dunce::canonicalize(folder).map_err(fail)?;
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()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| {
matches!(
extension.to_ascii_lowercase().as_str(),
"png" | "jpg" | "jpeg" | "gif" | "webp"
)
})
}
fn image_path(root: &Path, name: &str) -> Result<PathBuf> {
if name.is_empty()
|| name.contains(['/', '\\', ':'])
|| name.ends_with(['.', ' '])
|| !supported(name)
|| Path::new(name).components().count() != 1
|| !matches!(
Path::new(name).components().next(),
Some(Component::Normal(_))
)
{
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)?;
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)?;
if resolved.parent() != Some(root) {
return Err("The background image is outside its folder.".into());
}
Ok(path)
}
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)?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
if supported(&name) && image_path(&root, &name).is_ok() {
images.push(BackgroundFile { name });
}
}
images.sort_by(|a, b| a.name.cmp(&b.name));
Ok(images)
}
fn raster_signature(bytes: &[u8]) -> bool {
bytes.starts_with(b"\x89PNG\r\n\x1a\n")
|| bytes.starts_with(b"\xff\xd8\xff")
|| bytes.starts_with(b"GIF87a")
|| bytes.starts_with(b"GIF89a")
|| (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP")
}
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)?;
if !metadata.is_file() || is_link(&metadata) {
return Err("Background images must be ordinary files, not links.".into());
}
if metadata.len() > IMAGE_LIMIT {
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 {
return Err("The background image exceeds 50 MiB.".into());
}
if !raster_signature(&bytes) {
return Err("The file is not a supported raster image.".into());
}
Ok(bytes)
}
#[tauri::command]
pub async fn backgrounds_default_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
let pictures = app.path().picture_dir().map_err(fail)?;
let folder = pictures.join("RuneStone Backgrounds");
fs::create_dir_all(&folder).map_err(fail)?;
require_plugin(&app, &window, &id)?;
folder_root(&folder).map(|root| root.to_string_lossy().into_owned())
}
#[tauri::command]
pub async fn backgrounds_choose_folder(
app: AppHandle,
window: Window,
id: String,
) -> Result<Option<String>> {
require_plugin(&app, &window, &id)?;
let picker_app = app.clone();
let picker_window = window.clone();
let selected = tauri::async_runtime::spawn_blocking(move || {
picker_app
.dialog()
.file()
.set_parent(&picker_window)
.set_title("Choose background image folder")
.blocking_pick_folder()
})
.await
.map_err(fail)?;
require_plugin(&app, &window, &id)?;
selected
.map(|source| {
let path = source.into_path().map_err(fail)?;
folder_root(&path).map(|root| root.to_string_lossy().into_owned())
})
.transpose()
}
#[tauri::command]
pub async fn backgrounds_list(
app: AppHandle,
window: Window,
id: String,
folder: String,
) -> 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)??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_read(
app: AppHandle,
window: Window,
id: String,
folder: String,
name: String,
) -> Result<String> {
require_plugin(&app, &window, &id)?;
let result =
tauri::async_runtime::spawn_blocking(move || read_image(Path::new(&folder), &name))
.await
.map_err(fail)??;
require_plugin(&app, &window, &id)?;
Ok(base64::engine::general_purpose::STANDARD.encode(result))
}
fn read_image_settings(folder: &Path) -> Result<Option<String>> {
let root = folder_root(folder)?;
let path = root.join(SETTINGS_FILE);
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)),
};
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)?;
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 {
return Err("Image settings exceed 1 MiB.".into());
}
String::from_utf8(bytes).map(Some).map_err(fail)
}
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)?;
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)?;
if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1)
|| !value.get("images").is_some_and(serde_json::Value::is_object)
{
return Err("Use image settings with schema 1 and an images object.".into());
}
let root = folder_root(folder)?;
if read_image_settings(&root)?.as_deref() != expected {
return Err("Image settings changed. Reload them before saving.".into());
}
let path = root.join(SETTINGS_FILE);
if expected.is_some() {
crate::workspace::write_text(&path, contents, expected).map_err(fail)
} 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
}
}
#[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)??;
require_plugin(&app, &window, &id)?;
Ok(result)
}
#[tauri::command]
pub async fn backgrounds_write_image_settings(app: AppHandle, window: Window, id: String, folder: String, contents: String, expected: Option<String>) -> Result<()> {
require_plugin(&app, &window, &id)?;
// Check the lease again immediately before the write on the blocking worker.
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)?
}
#[cfg(test)]
mod tests {
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root = std::env::temp_dir()
.join(format!("runestone-backgrounds-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
Self(root)
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
#[test]
fn image_settings_preserve_external_changes_and_validate_file_limits() {
let fixture = Fixture::new();
let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#;
let next = r#"{"schema":1,"images":{}}"#;
assert_eq!(read_image_settings(&fixture.0).unwrap(), None);
write_image_settings(&fixture.0, first, None).unwrap();
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
assert!(write_image_settings(&fixture.0, next, None).is_err());
assert!(write_image_settings(&fixture.0, next, Some("stale")).is_err());
assert_eq!(read_image_settings(&fixture.0).unwrap().as_deref(), Some(first));
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();
assert!(read_image_settings(&fixture.0).is_err());
}
#[test]
fn listing_is_nonrecursive_and_filters_extensions() {
let fixture = Fixture::new();
fs::write(fixture.0.join("a.PNG"), b"\x89PNG\r\n\x1a\n").unwrap();
fs::write(fixture.0.join("b.jpg"), b"\xff\xd8\xff").unwrap();
fs::write(fixture.0.join("text.svg"), b"<svg />").unwrap();
fs::create_dir(fixture.0.join("nested.gif")).unwrap();
fs::write(fixture.0.join("nested.gif/hidden.png"), b"png").unwrap();
let names: Vec<_> = list_images(&fixture.0)
.unwrap()
.into_iter()
.map(|image| image.name)
.collect();
assert_eq!(names, vec!["a.PNG", "b.jpg"]);
assert_eq!(
read_image(&fixture.0, "a.PNG").unwrap(),
b"\x89PNG\r\n\x1a\n"
);
}
#[test]
fn reads_reject_traversal_invalid_images_and_oversized_files() {
let fixture = Fixture::new();
for name in [
"../escape.png",
"nested/image.png",
"nested\\image.png",
"C:\\image.png",
"image.png:stream",
"image.svg",
] {
assert!(read_image(&fixture.0, name).is_err(), "{name}");
}
assert!(list_images(Path::new("relative")).is_err());
fs::write(fixture.0.join("invalid.png"), b"<svg />").unwrap();
assert!(read_image(&fixture.0, "invalid.png")
.unwrap_err()
.contains("raster"));
let file = File::create(fixture.0.join("large.png")).unwrap();
file.set_len(IMAGE_LIMIT + 1).unwrap();
assert!(read_image(&fixture.0, "large.png")
.unwrap_err()
.contains("50 MiB"));
}
#[test]
fn raster_types_are_recognized() {
for bytes in [
b"\x89PNG\r\n\x1a\n".as_slice(),
b"\xff\xd8\xff",
b"GIF87a",
b"GIF89a",
b"RIFF0000WEBP",
] {
assert!(raster_signature(bytes));
}
assert!(!raster_signature(b"RIFF0000WAVE"));
}
#[test]
fn links_cannot_escape_the_folder() {
let fixture = Fixture::new();
let outside = Fixture::new();
let original = outside.0.join("outside.png");
fs::write(&original, b"\x89PNG\r\n\x1a\n").unwrap();
let link = fixture.0.join("link.png");
#[cfg(unix)]
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) {
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
return;
}
panic!("{error}");
}
assert!(list_images(&fixture.0).unwrap().is_empty());
assert!(read_image(&fixture.0, "link.png").is_err());
}
}