//! The image folder of the Background feature (`src/lib/features/background/`). //! //! The host keeps one folder in `background-folder.json` in the app data folder. Only the folder dialog //! sets it, so the interface never sends a folder path. The commands read the image files directly in //! that folder and the sidecar file `.runestone-backgrounds.json` with the per-image settings. //! They use the rules of the plugin folder grants (`folders.rs`): plain file names only, no links, //! raster images up to 64 MiB, a sidecar up to 1 MiB, and at most 10,000 files in the folder. use crate::error::{Error, Result}; use crate::folders; use crate::fsutil::{self, is_link}; use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Mutex; use tauri::{AppHandle, Manager, Window}; use tauri_plugin_dialog::DialogExt; const FOLDER_FILE: &str = "background-folder.json"; const SIDECAR: &str = ".runestone-backgrounds.json"; /// The old plugin whose folder grant the migration takes. const LEGACY_PLUGIN: &str = "runestone.bg-slideshow"; const FOLDER_FILE_LIMIT: u64 = 64 * 1024; /// Serializes changes to the folder file. static LOCK: Mutex<()> = Mutex::new(()); #[derive(Debug, Serialize, Deserialize)] struct FolderFile { schema: u32, path: PathBuf, } /// The folder file and the plugin data of one app data folder. struct Host { data: PathBuf, } fn raster(name: &str) -> bool { Path::new(name) .extension() .and_then(|extension| extension.to_str()) .is_some_and(|extension| matches!(extension.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp")) } fn raster_signature(bytes: &[u8]) -> bool { bytes.starts_with(b"\x89PNG\r\n\x1a\n") || bytes.starts_with(b"\xff\xd8\xff") || bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") || (bytes.len() >= 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP") } /// Read a small JSON file. A missing file gives `None`. A link or a folder is an error. fn read_json Deserialize<'de>>(path: &Path, limit: u64) -> Result> { let metadata = match fs::symlink_metadata(path) { Ok(metadata) => metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(error.into()), }; if !metadata.is_file() || is_link(&metadata) { return Err(Error::new(format!("{} must be an ordinary file.", path.display()))); } let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(path)?, limit)? else { return Err(Error::new(format!("{} is too large.", path.display()))); }; Ok(Some(serde_json::from_slice(&bytes)?)) } impl Host { fn file(&self) -> PathBuf { self.data.join(FOLDER_FILE) } fn stored(&self) -> Result> { let Some(file) = read_json::(&self.file(), FOLDER_FILE_LIMIT)? else { return Ok(None) }; if file.schema != 1 { return Err("Unknown background folder file schema.".into()); } Ok(Some(file.path)) } fn save(&self, path: &Path) -> Result<()> { fs::create_dir_all(&self.data)?; let bytes = serde_json::to_vec_pretty(&FolderFile { schema: 1, path: path.to_path_buf() })?; let temp = self.data.join(format!("{FOLDER_FILE}.{}.tmp", uuid::Uuid::new_v4())); Ok(fsutil::replace_file(&self.file(), &temp, &bytes)?) } /// Keep `folder` as the background folder. It must be an existing folder, not a whole drive. fn choose(&self, folder: &Path) -> Result { let root = folders::granted_root(folder)?; let _lock = LOCK.lock()?; self.save(&root)?; Ok(root.to_string_lossy().into_owned()) } /// The kept folder for display, or `None`. fn folder(&self) -> Result> { Ok(self.stored()?.map(|path| path.to_string_lossy().into_owned())) } fn clear(&self) -> Result<()> { let _lock = LOCK.lock()?; match fs::remove_file(self.file()) { Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error.into()), _ => Ok(()), } } /// The kept folder, still an ordinary folder at the same resolved path. /// A folder that became a link or a file does not redirect the access. fn root(&self) -> Result { let path = self.stored()?.ok_or_else(|| Error::new("Choose a background folder first."))?; let metadata = fs::symlink_metadata(&path).map_err(|_| Error::new("The background folder is missing. Choose the folder again."))?; if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&path)? != path { return Err("The background folder changed into a link or a file. Choose the folder again.".into()); } Ok(path) } /// The names of the raster images directly in the folder. fn list(&self) -> Result> { Ok(folders::list_files(&self.root()?)? .into_iter() .map(|entry| entry.name) .filter(|name| raster(name)) .collect()) } fn read(&self, name: &str) -> Result> { if !raster(name) { return Err("Supply one PNG, JPEG, GIF, or WebP file name.".into()); } let bytes = folders::read_file(&self.root()?, name)?; if !raster_signature(&bytes) { return Err("The file is not a supported raster image.".into()); } Ok(bytes) } fn read_sidecar(&self) -> Result> { folders::read_sidecar(&self.root()?, SIDECAR) } /// Save the per-image settings only if the file still holds `expected` (`None` when it does not exist). fn write_sidecar(&self, contents: &str, expected: Option<&str>) -> Result<()> { let value: serde_json::Value = serde_json::from_str(contents)?; if value.get("schema").and_then(serde_json::Value::as_u64) != Some(1) || !value.get("images").is_some_and(serde_json::Value::is_object) { return Err("Use image settings with schema 1 and an images object.".into()); } folders::write_sidecar(&self.root()?, SIDECAR, contents, expected) } /// Take the folder of the old Background Slideshow grant when the host has no folder yet. /// Returns the folder after the migration, or `None`. It changes no plugin file. fn migrate(&self) -> Result> { let _lock = LOCK.lock()?; if let Some(path) = self.stored()? { return Ok(Some(path.to_string_lossy().into_owned())); } let plugin_data = self.data.join("plugin-data"); let settings = plugin_data.join(LEGACY_PLUGIN).join("settings.json"); let Some(value) = read_json::(&settings, 1024 * 1024).ok().flatten() else { return Ok(None) }; let Some(grant) = value.get("grant").and_then(serde_json::Value::as_str).filter(|grant| !grant.is_empty()) else { return Ok(None) }; let Ok(path) = folders::plugin_grant(&plugin_data, LEGACY_PLUGIN, grant) else { return Ok(None) }; self.save(&path)?; Ok(Some(path.to_string_lossy().into_owned())) } } fn host(app: &AppHandle) -> Result { Ok(Host { data: app.path().app_data_dir()? }) } /// Run `work` on a blocking worker, because the file system calls can wait. async fn run(app: &AppHandle, work: impl FnOnce(Host) -> Result + Send + 'static) -> Result { let host = host(app)?; tauri::async_runtime::spawn_blocking(move || work(host)).await? } /// Show the folder dialog and keep the chosen folder. Returns the folder for display, or `None` after Cancel. #[tauri::command] pub async fn background_choose_folder(app: AppHandle, window: Window, title: Option) -> Result> { let (picker_app, picker_window) = (app.clone(), window.clone()); let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose the background folder".into()); let selected = tauri::async_runtime::spawn_blocking(move || { picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder() }) .await?; let Some(selected) = selected else { return Ok(None) }; let folder = selected.into_path().map_err(Error::from_display)?; run(&app, move |host| host.choose(&folder)).await.map(Some) } #[tauri::command] pub async fn background_folder(app: AppHandle) -> Result> { run(&app, |host| host.folder()).await } #[tauri::command] pub async fn background_clear_folder(app: AppHandle) -> Result<()> { run(&app, |host| host.clear()).await } #[tauri::command] pub async fn background_list(app: AppHandle) -> Result> { run(&app, |host| host.list()).await } /// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text. #[tauri::command] pub async fn background_read(app: AppHandle, name: String) -> Result { Ok(tauri::ipc::Response::new(run(&app, move |host| host.read(&name)).await?)) } #[tauri::command] pub async fn background_read_sidecar(app: AppHandle) -> Result> { run(&app, |host| host.read_sidecar()).await } #[tauri::command] pub async fn background_write_sidecar(app: AppHandle, contents: String, expected: Option) -> Result<()> { run(&app, move |host| host.write_sidecar(&contents, expected.as_deref())).await } #[tauri::command] pub async fn background_migrate(app: AppHandle) -> Result> { run(&app, |host| host.migrate()).await } #[cfg(test)] mod tests { use super::*; use crate::folders::LIST_LIMIT; const PNG: &[u8] = b"\x89PNG\r\n\x1a\n"; struct Fixture(PathBuf); impl Fixture { fn new() -> Self { let root = std::env::temp_dir().join(format!("runestone-background-{}", uuid::Uuid::new_v4())); fs::create_dir(&root).unwrap(); Self(dunce::canonicalize(root).unwrap()) } fn folder(&self, name: &str) -> PathBuf { let path = self.0.join(name); fs::create_dir_all(&path).unwrap(); path } fn host(&self) -> Host { Host { data: self.folder("app") } } } impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } } /// Make a link, or return `false` when Windows does not allow links for this user. fn link(original: &Path, link: &Path, folder: bool) -> bool { #[cfg(unix)] { let _ = folder; std::os::unix::fs::symlink(original, link).unwrap(); true } #[cfg(windows)] { let result = if folder { std::os::windows::fs::symlink_dir(original, link) } else { std::os::windows::fs::symlink_file(original, link) }; match result { Ok(()) => true, Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => { eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege."); false } Err(error) => panic!("{error}"), } } } #[test] fn the_host_keeps_one_folder_until_it_is_cleared() { let fixture = Fixture::new(); let images = fixture.folder("images"); let other = fixture.folder("other"); let host = fixture.host(); assert_eq!(host.folder().unwrap(), None); assert!(host.list().unwrap_err().to_string().contains("Choose a background folder")); assert_eq!(host.choose(&images).unwrap(), images.to_string_lossy()); // A new host reads the kept folder, as after a restart. assert_eq!(fixture.host().folder().unwrap(), Some(images.to_string_lossy().into_owned())); host.choose(&other).unwrap(); assert_eq!(host.folder().unwrap(), Some(other.to_string_lossy().into_owned())); host.clear().unwrap(); host.clear().unwrap(); assert_eq!(host.folder().unwrap(), None); } #[test] fn the_chosen_folder_must_be_an_existing_folder() { let fixture = Fixture::new(); let host = fixture.host(); let images = fixture.folder("images"); assert!(host.choose(Path::new("relative")).is_err()); assert!(host.choose(&images.join("..").join("images")).is_err()); assert!(host.choose(&fixture.0.join("missing")).is_err()); fs::write(fixture.0.join("file.txt"), "x").unwrap(); assert!(host.choose(&fixture.0.join("file.txt")).is_err()); let drive = images.ancestors().last().unwrap().to_path_buf(); assert!(host.choose(&drive).is_err()); assert_eq!(host.folder().unwrap(), None); // A damaged folder file is an error, not a silent reset. fs::write(host.file(), "{damaged").unwrap(); assert!(host.folder().is_err()); fs::write(host.file(), r#"{"schema":2,"path":"C:\\"}"#).unwrap(); assert!(host.folder().is_err()); } #[test] fn the_listing_has_only_the_raster_files_directly_in_the_folder() { let fixture = Fixture::new(); let images = fixture.folder("images"); let host = fixture.host(); host.choose(&images).unwrap(); fs::write(images.join("b.PNG"), PNG).unwrap(); fs::write(images.join("a.jpg"), b"\xff\xd8\xff").unwrap(); fs::write(images.join("c.webp"), b"RIFF0000WEBP").unwrap(); fs::write(images.join("text.svg"), b"").unwrap(); fs::write(images.join("notes.md"), b"# notes").unwrap(); fs::write(images.join(SIDECAR), b"{}").unwrap(); fixture.folder("images/nested.gif"); fs::write(images.join("nested.gif/hidden.png"), PNG).unwrap(); assert_eq!(host.list().unwrap(), vec!["a.jpg", "b.PNG", "c.webp"]); assert_eq!(host.read("b.PNG").unwrap(), PNG); } #[test] fn reads_reject_other_names_other_types_and_large_files() { let fixture = Fixture::new(); let images = fixture.folder("images"); fs::write(fixture.0.join("outside.png"), PNG).unwrap(); let host = fixture.host(); host.choose(&images).unwrap(); for name in ["../outside.png", "nested/image.png", "nested\\image.png", "C:\\image.png", "image.png:stream", "image.svg", "notes.md", "", "nul.png"] { assert!(host.read(name).is_err(), "{name}"); } fs::write(images.join("fake.png"), b"").unwrap(); assert!(host.read("fake.png").unwrap_err().to_string().contains("raster")); fs::File::create(images.join("large.png")).unwrap().set_len(folders::READ_LIMIT + 1).unwrap(); assert!(host.read("large.png").unwrap_err().to_string().contains("64 MiB")); } #[test] fn the_listing_has_a_size_limit() { let fixture = Fixture::new(); let images = fixture.folder("images"); let host = fixture.host(); host.choose(&images).unwrap(); for index in 0..=LIST_LIMIT { fs::write(images.join(format!("{index}.png")), b"").unwrap(); } assert!(host.list().unwrap_err().to_string().contains("10000")); } #[test] fn links_cannot_escape_the_folder() { let fixture = Fixture::new(); let images = fixture.folder("images"); let outside = fixture.folder("outside"); fs::write(outside.join("secret.png"), PNG).unwrap(); let host = fixture.host(); host.choose(&images).unwrap(); if !link(&outside.join("secret.png"), &images.join("link.png"), false) { return; } assert!(host.list().unwrap().is_empty()); assert!(host.read("link.png").is_err()); // A kept folder that is replaced by a link loses its access. let moved = fixture.folder("moved"); host.choose(&moved).unwrap(); fs::remove_dir(&moved).unwrap(); assert!(link(&outside, &moved, true)); assert!(host.list().unwrap_err().to_string().contains("Choose the folder again")); } #[test] fn the_sidecar_keeps_external_changes_and_needs_schema_one() { let fixture = Fixture::new(); let images = fixture.folder("images"); let host = fixture.host(); host.choose(&images).unwrap(); let first = r#"{"schema":1,"images":{"portrait.png":{"fit":"blurred"}}}"#; let next = r#"{"schema":1,"images":{}}"#; assert_eq!(host.read_sidecar().unwrap(), None); host.write_sidecar(first, None).unwrap(); assert_eq!(host.read_sidecar().unwrap().as_deref(), Some(first)); assert!(host.write_sidecar(next, None).is_err()); assert!(host.write_sidecar(next, Some("stale")).is_err()); host.write_sidecar(next, Some(first)).unwrap(); assert_eq!(fs::read_to_string(images.join(SIDECAR)).unwrap(), next); for bad in [r#"{"schema":2,"images":{}}"#, r#"{"schema":1,"images":[]}"#, "not json"] { assert!(host.write_sidecar(bad, Some(next)).is_err(), "{bad}"); } assert!(host.write_sidecar(&format!(r#"{{"schema":1,"images":{{}},"x":"{}"}}"#, "x".repeat(folders::SIDECAR_LIMIT as usize)), Some(next)).is_err()); fs::File::create(images.join(SIDECAR)).unwrap().set_len(folders::SIDECAR_LIMIT + 1).unwrap(); assert!(host.read_sidecar().is_err()); } fn seed_plugin(fixture: &Fixture, folder: &Path, settings: &str) -> String { let grant = uuid::Uuid::new_v4().to_string(); let data = fixture.folder(&format!("app/plugin-data/{LEGACY_PLUGIN}")); fs::write(data.join("folder-grants.json"), serde_json::to_vec(&serde_json::json!({ "schema": 1, "grants": [{ "id": grant, "path": folder }] })).unwrap()).unwrap(); fs::write(data.join("settings.json"), settings.replace("GRANT", &grant)).unwrap(); grant } #[test] fn the_migration_takes_the_folder_of_the_old_grant() { let fixture = Fixture::new(); let images = fixture.folder("images"); seed_plugin(&fixture, &images, r#"{"grant":"GRANT","enabled":true}"#); let data = fixture.0.join("app/plugin-data").join(LEGACY_PLUGIN); let before = (fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()); let host = fixture.host(); assert_eq!(host.migrate().unwrap(), Some(images.to_string_lossy().into_owned())); assert_eq!(host.folder().unwrap(), Some(images.to_string_lossy().into_owned())); assert_eq!((fs::read(data.join("folder-grants.json")).unwrap(), fs::read(data.join("settings.json")).unwrap()), before, "The migration changes no plugin file."); } #[test] fn the_migration_keeps_an_existing_host_folder() { let fixture = Fixture::new(); let images = fixture.folder("images"); let chosen = fixture.folder("chosen"); seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#); let host = fixture.host(); host.choose(&chosen).unwrap(); assert_eq!(host.migrate().unwrap(), Some(chosen.to_string_lossy().into_owned())); assert_eq!(host.folder().unwrap(), Some(chosen.to_string_lossy().into_owned())); } #[test] fn the_migration_without_a_usable_grant_keeps_no_folder() { // No plugin data. let fixture = Fixture::new(); assert_eq!(fixture.host().migrate().unwrap(), None); // Settings without a grant, with an unknown grant, and with damaged JSON. for settings in [r#"{"folder":"D:\\Pictures"}"#, r#"{"grant":"6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90"}"#, r#"{"grant":"not-a-uuid"}"#, "{damaged"] { let fixture = Fixture::new(); let images = fixture.folder("images"); seed_plugin(&fixture, &images, settings); let host = fixture.host(); assert_eq!(host.migrate().unwrap(), None, "{settings}"); assert_eq!(host.folder().unwrap(), None); } // A granted folder that no longer exists. let fixture = Fixture::new(); let images = fixture.folder("images"); seed_plugin(&fixture, &images, r#"{"grant":"GRANT"}"#); fs::remove_dir(&images).unwrap(); assert_eq!(fixture.host().migrate().unwrap(), None); } #[test] fn raster_types_are_recognized() { for bytes in [PNG, b"\xff\xd8\xff", b"GIF87a", b"GIF89a", b"RIFF0000WEBP"] { assert!(raster_signature(bytes)); } assert!(!raster_signature(b"RIFF0000WAVE")); assert!(raster("A.JPEG") && raster("b.gif") && !raster("c.svg") && !raster("png")); } }