Move workspace file work off the main thread and delete to the trash

Run the blocking workspace commands on the blocking thread pool.
Tauri runs a synchronous command on the main thread, so a long search
or copy froze every window. Command names, arguments, and results do
not change.

Send each workspace-event only to the windows that have its root open.
The frontend listens with its window label as the target. Do not send
access events, because the frontend ignores them. Drop watchers after
the state lock is released, because a macOS watcher waits for its
thread when it stops.

Fix these defects. Each fix has a Rust test:
- A rename that changes only the letter case works on case-insensitive
  volumes.
- New files publish with a move that never replaces a file: MoveFileExW
  on Windows, renameat2 or renamex_np on Linux and macOS, then a hard
  link, then create_new. exFAT, FAT32, and many network mounts now work.
  The Windows save recovery uses the same move.
- On macOS and Linux, existing names with a colon stay usable. New names
  reject the characters that Windows does not allow, on every platform.
- workspace_read_data_url checks the size before it reads the file.
- workspace_write_bytes uses the atomic writer. Its only caller writes
  new names, so it gets no conflict check.
- Delete and rename act on a link itself, not on its target.

Delete now moves items to the system trash. One file moves without a
confirmation. A folder or several items need one. Shift+Delete and
"Delete permanently" keep the permanent delete with its confirmation.
Windows drives without a Recycle Bin give an error instead of a silent
permanent delete. The smoke test for tree actions now checks this
behavior. The user guide describes it and the new-name rule.
This commit is contained in:
Knotty Wyvern
2026-10-27 23:15:14 -07:00
parent 2448c68abf
commit a0eef01ed0
9 changed files with 978 additions and 127 deletions
+235 -10
View File
@@ -89,20 +89,179 @@ pub fn replace_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
/// Publish a complete new file at `path` through `temp`. Fail if `path` exists,
/// so that a file created by another writer is never replaced.
///
/// The publish step moves `temp` to `path` without replacement. Some volumes (exFAT, FAT32,
/// and many network or FUSE mounts) support neither an exclusive rename nor hard links.
/// On these volumes, write the file in place with `create_new`. That write is not atomic,
/// but it still never replaces an existing file.
pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
write_temp_then(temp, bytes, || {
fs::hard_link(temp, path)?;
let _ = fs::remove_file(temp);
create_file_with(path, temp, bytes, rename_no_replace)
}
fn create_file_with(
path: &Path,
temp: &Path,
bytes: &[u8],
publish: impl FnOnce(&Path, &Path) -> io::Result<()>,
) -> io::Result<()> {
let mut unsupported = false;
let result = write_temp_then(temp, bytes, || {
publish(temp, path).inspect_err(|reason| unsupported = is_unsupported(reason))
});
if unsupported {
return write_new(path, bytes);
}
result
}
/// Create `path` with `create_new`, write `bytes`, and flush them to the disk.
/// Remove the file again if the write fails, because this call created it.
fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> {
let mut file = File::options().write(true).create_new(true).open(path)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
if written.is_err() {
let _ = fs::remove_file(path);
}
written
}
/// True when the volume does not support the operation, as opposed to a conflict or a permission problem.
fn is_unsupported(reason: &io::Error) -> bool {
if reason.kind() == io::ErrorKind::Unsupported {
return true;
}
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::{ERROR_INVALID_FUNCTION, ERROR_NOT_SUPPORTED};
matches!(reason.raw_os_error(), Some(code) if code == ERROR_INVALID_FUNCTION as i32 || code == ERROR_NOT_SUPPORTED as i32)
}
#[cfg(unix)]
{
// Linux returns EPERM from link(2) when the file system has no hard links.
matches!(reason.raw_os_error(), Some(code) if code == libc::ENOTSUP || code == libc::EOPNOTSUPP
|| code == libc::ENOSYS || code == libc::EINVAL || code == libc::EPERM)
}
#[cfg(not(any(windows, unix)))]
false
}
/// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it.
#[cfg(windows)]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::MoveFileExW;
let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::<Vec<_>>();
let (from_wide, to_wide) = (wide(from), wide(to));
// Without MOVEFILE_REPLACE_EXISTING, Windows refuses an existing destination.
if unsafe { MoveFileExW(from_wide.as_ptr(), to_wide.as_ptr(), 0) } != 0 {
Ok(())
})
} else {
Err(io::Error::last_os_error())
}
}
/// Move `from` to `to`. Fail with `AlreadyExists` if `to` exists, and never replace it.
#[cfg(unix)]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
match rename_exclusive(from, to) {
Err(reason) if is_unsupported(&reason) => {
// A hard link also refuses an existing destination. Remove the source name after it.
fs::hard_link(from, to)?;
let _ = fs::remove_file(from);
Ok(())
}
result => result,
}
}
#[cfg(target_os = "linux")]
fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes())?;
// The raw system call does not need the glibc 2.28 wrapper.
let result = unsafe {
libc::syscall(libc::SYS_renameat2, libc::AT_FDCWD, from.as_ptr(), libc::AT_FDCWD, to.as_ptr(), libc::RENAME_NOREPLACE)
};
if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
#[cfg(target_os = "macos")]
fn rename_exclusive(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes())?;
let result = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_EXCL) };
if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) }
}
#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
fn rename_exclusive(_from: &Path, _to: &Path) -> io::Result<()> {
Err(io::Error::from(io::ErrorKind::Unsupported))
}
#[cfg(not(any(windows, unix)))]
pub fn rename_no_replace(from: &Path, to: &Path) -> io::Result<()> {
fs::hard_link(from, to)?;
let _ = fs::remove_file(from);
Ok(())
}
/// True when `left` and `right` name the same directory entry, for example the same file
/// with a different letter case on a case-insensitive volume. Links are not followed.
pub fn same_entry(left: &Path, right: &Path) -> io::Result<bool> {
Ok(entry_identity(left)? == entry_identity(right)?)
}
#[cfg(unix)]
fn entry_identity(path: &Path) -> io::Result<(u64, u64)> {
use std::os::unix::fs::MetadataExt;
let metadata = fs::symlink_metadata(path)?;
Ok((metadata.dev(), metadata.ino()))
}
#[cfg(windows)]
fn entry_identity(path: &Path) -> io::Result<(u32, u64)> {
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
};
// Open the entry itself, also a folder or a link, with attribute access only.
let file = File::options()
.access_mode(FILE_READ_ATTRIBUTES)
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(file.as_raw_handle() as _, &mut info) } == 0 {
return Err(io::Error::last_os_error());
}
Ok((info.dwVolumeSerialNumber, (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow)))
}
#[cfg(not(any(unix, windows)))]
fn entry_identity(path: &Path) -> io::Result<std::path::PathBuf> {
fs::canonicalize(path)
}
/// Save `contents` at `path`. With `expected`, save only if the file still holds `expected`.
/// Write completely beside the destination, then replace it. A failed write
/// leaves the original file intact rather than truncating it.
pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result<()> {
write_checked(path, contents.as_bytes(), expected.map(str::as_bytes))
}
/// Save `bytes` at `path` with the same atomic replacement as `write_text`.
pub fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
write_checked(path, bytes, None)
}
fn write_checked(path: &Path, contents: &[u8], expected: Option<&[u8]>) -> Result<()> {
if let Some(expected) = expected {
let current = fs::read_to_string(path).map_err(|_| {
let current = fs::read(path).map_err(|_| {
Error::new("Save blocked: file was removed or cannot be read. Your edits are still open.")
})?;
if current != expected {
@@ -123,7 +282,7 @@ pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result
.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.write_all(contents).map_err(|reason| Error::new(format!("Could not write the save file for {}: {reason}", path.display())))?;
file.sync_all().map_err(|reason| Error::new(format!("Could not flush the save file for {}: {reason}", path.display())))?;
#[cfg(not(windows))]
if let Ok(metadata) = fs::metadata(path) {
@@ -132,7 +291,7 @@ pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result
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) {
if fs::read(path).ok().as_deref() != Some(expected) {
return Err(Error::new(
"Save blocked: file changed while saving. Your edits are still open.",
));
@@ -215,9 +374,8 @@ fn replace_saved_file(temp: &Path, path: &Path, allow_create: bool) -> Result<()
#[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(())
// A move without replacement also works on volumes without hard links.
rename_no_replace(backup, path)
}
#[cfg(test)]
@@ -289,6 +447,73 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_file_publishes_without_hard_links_or_replacement() {
let dir = fixture("create-exclusive");
let (from, to) = (dir.join("from.tmp"), dir.join("to.md"));
fs::write(&from, "new").unwrap();
fs::write(&to, "existing").unwrap();
assert_eq!(rename_no_replace(&from, &to).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read_to_string(&to).unwrap(), "existing");
assert_eq!(fs::read_to_string(&from).unwrap(), "new");
fs::remove_file(&to).unwrap();
rename_no_replace(&from, &to).unwrap();
assert_eq!(fs::read_to_string(&to).unwrap(), "new");
assert!(!from.exists());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn create_file_writes_in_place_on_volumes_without_an_exclusive_publish() {
// exFAT, FAT32, and many network or FUSE mounts support neither an exclusive rename nor hard links.
let unsupported = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::Unsupported));
let dir = fixture("create-fallback");
let path = dir.join("note.md");
create_file_with(&path, &dir.join("one.tmp"), b"complete note\n", unsupported).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
let error = create_file_with(&path, &dir.join("two.tmp"), b"replacement", unsupported).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::AlreadyExists);
assert_eq!(fs::read_to_string(&path).unwrap(), "complete note\n");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
// A conflict is not a missing feature: it never falls back.
let conflict = |_: &Path, _: &Path| Err(io::Error::from(io::ErrorKind::AlreadyExists));
assert!(create_file_with(&dir.join("other.md"), &dir.join("three.tmp"), b"x", conflict).is_err());
assert!(!dir.join("other.md").exists());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn same_entry_compares_items_without_following_names() {
let dir = fixture("same-entry");
fs::write(dir.join("note.md"), "note").unwrap();
fs::write(dir.join("other.md"), "other").unwrap();
fs::create_dir(dir.join("folder")).unwrap();
assert!(same_entry(&dir.join("note.md"), &dir.join("note.md")).unwrap());
assert!(!same_entry(&dir.join("note.md"), &dir.join("other.md")).unwrap());
assert!(same_entry(&dir.join("folder"), &dir.join("folder")).unwrap());
// On a case-insensitive volume another spelling names the same item.
if dir.join("NOTE.md").exists() {
assert!(same_entry(&dir.join("note.md"), &dir.join("NOTE.md")).unwrap());
}
assert!(same_entry(&dir.join("note.md"), &dir.join("missing.md")).is_err());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn binary_writes_replace_completely_and_clean_up() {
let dir = fixture("bytes");
let path = dir.join("image.png");
write_bytes(&path, b"\x89PNG first").unwrap();
write_bytes(&path, b"\x89PNG second").unwrap();
assert_eq!(fs::read(&path).unwrap(), b"\x89PNG second");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::create_dir(dir.join("folder.png")).unwrap();
assert!(write_bytes(&dir.join("folder.png"), b"x").is_err());
assert_eq!(fs::read_dir(&dir).unwrap().count(), 2);
fs::remove_dir_all(dir).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn links_are_detected_from_link_metadata() {
+535 -90
View File
@@ -6,7 +6,7 @@ use std::time::Duration;
use notify::{Config, Event, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager, State};
use tauri::{AppHandle, Emitter, EventTarget, Manager, State};
use tauri_plugin_opener::OpenerExt;
use crate::error::{Error, Result};
@@ -42,7 +42,9 @@ pub struct WorkspaceState {
struct OpenWorkspace {
root: PathBuf,
_watcher: Option<Box<dyn Watcher + Send>>,
/// The window that opened the workspace owns a watcher. A window bound to the
/// root of another window, such as a terminal window, has none.
watcher: Option<Box<dyn Watcher + Send>>,
}
impl WorkspaceState {
@@ -53,14 +55,30 @@ impl WorkspaceState {
}
pub fn close_window(&self, label: &str) {
if let Ok(mut workspaces) = self.inner.lock() { workspaces.remove(label); }
let removed = self.inner.lock().ok().and_then(|mut workspaces| workspaces.remove(label));
// Drop the watcher after the lock is released. On macOS the drop waits for the
// watcher thread, and that thread can wait for this lock to send an event.
drop(removed);
}
pub fn bind_terminal(&self, label: &str, root: PathBuf) -> Result<()> {
self.inner.lock().map_err(|_| Error::new("workspace lock"))?
.insert(label.to_owned(), OpenWorkspace { root, _watcher: None });
let replaced = self.inner.lock().map_err(|_| Error::new("workspace lock"))?
.insert(label.to_owned(), OpenWorkspace { root, watcher: None });
drop(replaced);
Ok(())
}
/// The windows that receive the events of the watcher that `owner` started for `root`:
/// the owner, and each window bound to the same root without a watcher of its own.
/// A window with its own watcher receives the events of that watcher only, so no window
/// receives the same change twice.
fn event_recipients(&self, owner: &str, root: &Path) -> Vec<String> {
let Ok(workspaces) = self.inner.lock() else { return Vec::new() };
workspaces.iter()
.filter(|(label, workspace)| workspace.root == root && (label.as_str() == owner || workspace.watcher.is_none()))
.map(|(label, _)| label.clone())
.collect()
}
}
fn last_workspace_file(app: &AppHandle) -> Result<PathBuf> {
@@ -164,6 +182,11 @@ fn load_last_workspace(app: &AppHandle) -> Option<PathBuf> {
Some(PathBuf::from(root))
}
/// Check a workspace-relative path to an existing or a new item.
///
/// On Windows a colon starts a drive prefix or an alternate data stream, so it is rejected.
/// On macOS and Linux a colon is an ordinary name character. Existing files with a colon
/// in the name stay usable there. New names follow `check_portable_name`.
pub fn check_rel(rel: &str) -> Result<()> {
if rel.contains('\0') {
return Err(Error::new("path contains a null byte"));
@@ -172,7 +195,7 @@ pub fn check_rel(rel: &str) -> Result<()> {
if normalized.starts_with('/') || normalized.starts_with('\\') {
return Err(Error::new("absolute paths are not allowed"));
}
if normalized.contains(':') {
if cfg!(windows) && normalized.contains(':') {
return Err(Error::new("drive prefixes are not allowed"));
}
for part in normalized.split('/') {
@@ -183,6 +206,40 @@ pub fn check_rel(rel: &str) -> Result<()> {
Ok(())
}
/// Characters that Windows does not allow in a file or folder name.
const WINDOWS_INVALID_CHARACTERS: &str = "<>:\"|?*";
/// Check one new file or folder name.
///
/// Portability rule: a new name (create, rename destination, copy destination) cannot contain
/// a character that Windows rejects, on every platform. A workspace that is shared through Git
/// then stays usable on Windows. Existing names are not checked, so files with such characters
/// that other tools made on macOS or Linux stay readable, writable, renamable, and deletable.
fn check_portable_name(name: &str) -> Result<()> {
if name.chars().any(|c| c.is_control() || WINDOWS_INVALID_CHARACTERS.contains(c)) {
return Err(Error::new(format!(
"The name {name} contains a character that Windows does not allow: < > : \" | ? * or a control character. Choose another name."
)));
}
Ok(())
}
/// Apply `check_portable_name` to each component of `rel` that does not exist yet below `root`.
fn check_new_components(root: &Path, rel: &str) -> Result<()> {
let normalized = rel.replace('\\', "/");
let mut path = root.to_path_buf();
let mut missing = false;
for part in normalized.split('/').filter(|part| !part.is_empty() && *part != ".") {
path.push(part);
if !missing && fs::symlink_metadata(&path).is_ok() {
continue;
}
missing = true;
check_portable_name(part)?;
}
Ok(())
}
fn join_rel(root: &Path, rel: &str) -> Result<PathBuf> {
check_rel(rel)?;
let normalized = rel.replace('\\', "/");
@@ -214,13 +271,38 @@ fn resolve_existing(root: &Path, rel: &str) -> Result<PathBuf> {
Ok(canon)
}
/// Resolve an existing item without following a link at its last component.
/// The parent folder must resolve inside the workspace. Delete and rename use this,
/// so that they act on a link itself and never on its target.
fn resolve_entry(root: &Path, rel: &str) -> Result<PathBuf> {
let joined = join_rel(root, rel)?;
if joined == root {
return Ok(joined);
}
let (Some(parent), Some(name)) = (joined.parent(), joined.file_name()) else {
return Err(Error::new("path does not exist"));
};
let parent = dunce::canonicalize(parent).map_err(|_| Error::new("path does not exist"))?;
if !is_inside(root, &parent) {
return Err(Error::new("path is outside the workspace"));
}
let path = parent.join(name);
fs::symlink_metadata(&path).map_err(|_| Error::new("path does not exist"))?;
Ok(path)
}
fn resolve_for_write(root: &Path, rel: &str) -> Result<PathBuf> {
let joined = join_rel(root, rel)?;
if joined == root {
return Err(Error::new("the workspace root cannot be modified"));
}
// Validate the nearest existing ancestor, including the target itself.
// This catches links to outside the workspace even below missing folders.
resolve_under(root, &joined)
}
/// Validate the nearest existing ancestor of `joined`, including `joined` itself.
/// Return the canonical path of an existing item, or `joined` for a missing one.
/// This catches links to outside the workspace even below missing folders.
fn resolve_under(root: &Path, joined: &Path) -> Result<PathBuf> {
for ancestor in joined.ancestors() {
if fs::symlink_metadata(ancestor).is_ok() {
let canonical = dunce::canonicalize(ancestor)?;
@@ -236,7 +318,21 @@ fn resolve_for_write(root: &Path, rel: &str) -> Result<PathBuf> {
return Err(Error::new("path is outside the workspace"));
}
}
Ok(joined)
Ok(joined.to_path_buf())
}
/// Resolve the destination of a rename. Keep the last component as the caller spelled it,
/// so that a rename can change only the letter case. Check new names for portability.
fn resolve_destination(root: &Path, rel: &str) -> Result<PathBuf> {
let joined = join_rel(root, rel)?;
if joined == root {
return Err(Error::new("the workspace root cannot be modified"));
}
let (Some(parent), Some(name)) = (joined.parent(), joined.file_name()) else {
return Err(Error::new("the workspace root cannot be modified"));
};
check_new_components(root, rel)?;
Ok(resolve_under(root, parent)?.join(name))
}
fn to_rel(root: &Path, path: &Path) -> Option<String> {
@@ -246,12 +342,9 @@ fn to_rel(root: &Path, path: &Path) -> Option<String> {
Some(rel.to_string_lossy().replace('\\', "/"))
}
/// The Windows drive type of the volume that holds `path`, such as `DRIVE_FIXED` or `DRIVE_REMOTE`.
#[cfg(windows)]
fn is_network_path(path: &Path) -> bool {
let s = path.to_string_lossy();
if s.starts_with("\\\\") || s.starts_with("//") {
return true;
}
fn drive_type(path: &Path) -> Option<u32> {
use std::os::windows::ffi::OsStrExt;
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
wide.push(0);
@@ -263,49 +356,81 @@ fn is_network_path(path: &Path) -> bool {
volume.len() as u32,
);
if ok == 0 {
return false;
return None;
}
let drive_type = windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr());
drive_type == windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE
Some(windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()))
}
}
#[cfg(windows)]
fn is_network_path(path: &Path) -> bool {
let s = path.to_string_lossy();
if s.starts_with("\\\\") || s.starts_with("//") {
return true;
}
drive_type(path) == Some(windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE)
}
#[cfg(not(windows))]
fn is_network_path(path: &Path) -> bool {
let s = path.to_string_lossy();
s.starts_with("//")
}
fn emit_watch_event(app: &AppHandle, root: &Path, event: Event) {
let kind = format!("{:?}", event.kind)
.split('(')
.next()
.unwrap_or("other")
.to_lowercase();
/// The name of a change for the frontend, such as "create" or "modify".
/// Access events are `None`: the frontend has no use for them.
fn event_kind(kind: &notify::EventKind) -> Option<String> {
if kind.is_access() {
return None;
}
Some(format!("{kind:?}").split('(').next().unwrap_or("other").to_lowercase())
}
fn emit_watch_event(app: &AppHandle, owner: &str, root: &Path, event: Event) {
let Some(kind) = event_kind(&event.kind) else { return };
let paths: Vec<String> = event.paths.iter().filter_map(|p| to_rel(root, p)).collect();
if paths.is_empty() {
return;
}
let _ = app.emit(
let recipients = app.state::<WorkspaceState>().event_recipients(owner, root);
if recipients.is_empty() {
return;
}
// The frontend listens with its own window label as the target (src/lib/workspace/api.ts).
// A listener without a target receives every event, so the filter cannot hide events from it.
let _ = app.emit_filter(
"workspace-event",
WorkspaceEvent {
root: root.to_string_lossy().into_owned(),
kind,
paths,
},
|target| event_target_label(target).is_some_and(|label| recipients.iter().any(|recipient| recipient == label)),
);
}
fn event_target_label(target: &EventTarget) -> Option<&str> {
match target {
EventTarget::AnyLabel { label }
| EventTarget::Window { label }
| EventTarget::Webview { label }
| EventTarget::WebviewWindow { label } => Some(label),
_ => None,
}
}
fn start_watcher(
app: AppHandle,
owner: String,
root: PathBuf,
network: bool,
) -> Result<Box<dyn Watcher + Send>> {
let handler_root = root.clone();
let handler_app = app.clone();
let handler_owner = owner.clone();
let handler = move |res: notify::Result<Event>| {
if let Ok(event) = res {
emit_watch_event(&handler_app, &handler_root, event);
emit_watch_event(&handler_app, &handler_owner, &handler_root, event);
}
};
@@ -329,7 +454,7 @@ fn start_watcher(
let mut watcher = PollWatcher::new(
move |res: notify::Result<Event>| {
if let Ok(event) = res {
emit_watch_event(&handler_app, &handler_root, event);
emit_watch_event(&handler_app, &owner, &handler_root, event);
}
},
Config::default().with_poll_interval(Duration::from_secs(2)),
@@ -371,7 +496,7 @@ fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf)
fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option<String>) -> Result<()> {
static NEXT_WINDOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let label = format!("workspace-{}", NEXT_WINDOW.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let watcher = start_watcher(app.clone(), root.clone(), is_network_path(&root))?;
let watcher = start_watcher(app.clone(), label.clone(), root.clone(), is_network_path(&root))?;
let mut config = app.config().app.windows.first().cloned().ok_or_else(|| Error::new("Missing window configuration"))?;
config.label = label.clone();
config.title = format!("{} — RuneStone", workspace_info(&root).name);
@@ -381,7 +506,7 @@ fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: Path
}
// Bind before building: the new frontend asks for its own root on startup.
state.inner.lock().map_err(|_| Error::new("workspace lock"))?.insert(label.clone(), OpenWorkspace {
root: root.clone(), _watcher: Some(watcher),
root: root.clone(), watcher: Some(watcher),
});
let result = (|| -> Result<()> {
let window = tauri::WebviewWindowBuilder::from_config(app, &config)
@@ -405,41 +530,63 @@ pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceSta
open_workspace_tab_window(&app, &state, root, transfer)
}
/// Run blocking file work on the blocking thread pool.
/// Tauri runs a synchronous command on the main thread, so long file work there freezes every window.
async fn blocking<T: Send + 'static>(work: impl FnOnce() -> Result<T> + Send + 'static) -> Result<T> {
tauri::async_runtime::spawn_blocking(work).await?
}
#[tauri::command]
pub fn workspace_open(
pub async fn workspace_open(
app: AppHandle,
window: tauri::Window,
state: State<WorkspaceState>,
state: State<'_, WorkspaceState>,
path: String,
) -> Result<WorkspaceInfo> {
let root = dunce::canonicalize(&path).map_err(|_| Error::new("folder does not exist"))?;
if !root.is_dir() {
return Err(Error::new("path is not a folder"));
}
if let Ok(previous) = current_root(&state, window.label()) {
if previous == root { return Ok(workspace_info(&root)); }
return Err(Error::new("Open another workspace in a new window."));
}
let network = is_network_path(&root);
let watcher = start_watcher(app.clone(), root.clone(), network)?;
save_last_workspace(&app, &root)?;
let label = window.label().to_owned();
let previous = current_root(&state, &label).ok();
let worker_app = app.clone();
let worker_label = label.clone();
// Canonicalization, the first scan of a polled network share, and the history file can block.
let (root, watcher) = blocking(move || {
let root = dunce::canonicalize(&path).map_err(|_| Error::new("folder does not exist"))?;
if !root.is_dir() {
return Err(Error::new("path is not a folder"));
}
if let Some(previous) = previous {
if previous == root { return Ok((root, None)); }
return Err(Error::new("Open another workspace in a new window."));
}
let network = is_network_path(&root);
let watcher = start_watcher(worker_app.clone(), worker_label, root.clone(), network)?;
save_last_workspace(&worker_app, &root)?;
Ok((root, Some(watcher)))
}).await?;
let Some(watcher) = watcher else { return Ok(workspace_info(&root)) };
{
let mut guard = state.inner.lock().map_err(|_| Error::new("workspace lock"))?;
guard.insert(window.label().to_owned(), OpenWorkspace {
// Another request for this window can finish first. Keep its workspace.
if let Some(current) = guard.get(&label) {
let same = current.root == root;
drop(guard);
drop(watcher);
return if same { Ok(workspace_info(&root)) } else { Err(Error::new("Open another workspace in a new window.")) };
}
guard.insert(label.clone(), OpenWorkspace {
root: root.clone(),
_watcher: Some(watcher),
watcher: Some(watcher),
});
}
let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name));
// A settings session opened before this workspace must start with its new context.
crate::settings::close_owned_window(&app, window.label());
crate::settings::close_owned_window(&app, &label);
Ok(workspace_info(&root))
}
#[tauri::command]
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String, show_internal: Option<bool>) -> Result<Vec<TreeEntry>> {
pub async fn workspace_list(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, show_internal: Option<bool>) -> Result<Vec<TreeEntry>> {
let root = current_root(&state, window.label())?;
list_entries_visible(&root, &rel, show_internal.unwrap_or(false))
blocking(move || list_entries_visible(&root, &rel, show_internal.unwrap_or(false))).await
}
fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> Result<Vec<TreeEntry>> {
@@ -473,7 +620,7 @@ fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> Result<V
if is_internal_name(&name) && !(show_internal && name == ".runestone") {
continue;
}
let rel_path = match to_rel(&root, path) {
let rel_path = match to_rel(root, path) {
Some(r) => r,
None => continue,
};
@@ -527,13 +674,15 @@ fn markdown_paths(root: &Path) -> Result<Vec<String>> {
}
#[tauri::command]
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> Result<Option<String>> {
pub async fn workspace_read(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, missing_ok: Option<bool>) -> Result<Option<String>> {
let root = current_root(&state, window.label())?;
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
if path.is_dir() {
return Err(Error::new("path is a folder"));
}
read_optional_text(&path, missing_ok.unwrap_or(false))
blocking(move || {
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
if path.is_dir() {
return Err(Error::new("path is a folder"));
}
read_optional_text(&path, missing_ok.unwrap_or(false))
}).await
}
fn read_optional_text(path: &Path, missing_ok: bool) -> Result<Option<String>> {
@@ -604,19 +753,25 @@ pub async fn workspace_read_bytes(window: tauri::Window, state: State<'_, Worksp
}
#[tauri::command]
pub fn workspace_write(
pub async fn workspace_write(
window: tauri::Window,
state: State<WorkspaceState>,
state: State<'_, WorkspaceState>,
rel: String,
contents: String,
expected: Option<String>,
) -> Result<()> {
let root = current_root(&state, window.label())?;
let path = resolve_for_write(&root, &rel)?;
blocking(move || write_workspace_text(&root, &rel, &contents, expected.as_deref())).await
}
fn write_workspace_text(root: &Path, rel: &str, contents: &str, expected: Option<&str>) -> Result<()> {
let path = resolve_for_write(root, rel)?;
// A save of an existing file keeps its name. A save that creates a file names a new item.
check_new_components(root, rel)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|reason| Error::new(format!("Could not prepare the save folder for {}: {reason}", path.display())))?;
}
fsutil::write_text(&path, &contents, expected.as_deref())
fsutil::write_text(&path, contents, expected)
}
fn is_internal_name(name: &str) -> bool {
@@ -624,16 +779,21 @@ fn is_internal_name(name: &str) -> bool {
}
#[tauri::command]
pub fn workspace_create(window: tauri::Window, state: State<WorkspaceState>, rel: String, kind: String, contents: Option<String>) -> Result<()> {
pub async fn workspace_create(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, kind: String, contents: Option<String>) -> Result<()> {
let root = current_root(&state, window.label())?;
let path = resolve_for_write(&root, &rel)?;
blocking(move || create_item(&root, &rel, &kind, contents.as_deref())).await
}
fn create_item(root: &Path, rel: &str, kind: &str, contents: Option<&str>) -> Result<()> {
let path = resolve_for_write(root, rel)?;
if path.exists() {
return Err(Error::new("path already exists"));
}
check_new_components(root, rel)?;
if kind == "folder" {
fs::create_dir_all(&path)?;
} else if let Some(contents) = contents {
create_text_if_absent(&path, &contents)?;
create_text_if_absent(&path, contents)?;
} else {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
@@ -668,15 +828,28 @@ fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Opt
}
#[tauri::command]
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String, expected_root: Option<String>) -> Result<()> {
pub async fn workspace_rename(window: tauri::Window, state: State<'_, WorkspaceState>, from: String, to: String, expected_root: Option<String>) -> Result<()> {
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
let from_path = resolve_existing(&root, &from)?;
blocking(move || rename_item(&root, &from, &to)).await
}
fn rename_item(root: &Path, from: &str, to: &str) -> Result<()> {
// Rename the item itself. A link moves as a link, and its target stays in place.
let from_path = resolve_entry(root, from)?;
if from_path == root {
return Err(Error::new("the workspace root cannot be renamed"));
}
let to_path = resolve_for_write(&root, &to)?;
if to_path.exists() {
return Err(Error::new("destination already exists"));
let to_path = resolve_destination(root, to)?;
if fs::symlink_metadata(&to_path).is_ok() {
// On a case-insensitive volume, `Note.md` already "exists" when `note.md` is renamed to it.
// Allow the rename only when the destination is the source item itself.
let case_only = from_path.file_name() != to_path.file_name()
&& fsutil::same_entry(&from_path, &to_path).unwrap_or(false);
if !case_only {
return Err(Error::new("destination already exists"));
}
fs::rename(&from_path, &to_path)?;
return Ok(());
}
if let Some(parent) = to_path.parent() {
fs::create_dir_all(parent)?;
@@ -685,19 +858,74 @@ pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, fro
Ok(())
}
/// Move an item to the trash of the operating system, or delete it permanently with `permanent`.
/// The frontend asks for confirmation before a permanent delete.
#[tauri::command]
pub fn workspace_delete(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> Result<()> {
pub async fn workspace_delete(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, permanent: Option<bool>) -> Result<()> {
let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?;
blocking(move || delete_item(&root, &rel, permanent.unwrap_or(false))).await
}
fn delete_item(root: &Path, rel: &str, permanent: bool) -> Result<()> {
// Delete the item itself. A link goes away, and its target stays in place.
let path = resolve_entry(root, rel)?;
if path == root {
return Err(Error::new("the workspace root cannot be deleted"));
}
if path.is_dir() {
fs::remove_dir_all(path)?;
if permanent {
remove_entry(&path)?;
Ok(())
} else {
fs::remove_file(path)?;
move_to_trash(&path)
}
Ok(())
}
/// Remove `path` permanently. Remove a link itself and never follow it.
fn remove_entry(path: &Path) -> std::io::Result<()> {
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() {
// A Windows folder link or junction is a directory entry. Other links are files.
#[cfg(windows)]
{
use std::os::windows::fs::MetadataExt;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY;
if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
return fs::remove_dir(path);
}
}
return fs::remove_file(path);
}
if metadata.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) }
}
/// Move `path` to the trash of the operating system. The trash moves a link itself.
fn move_to_trash(path: &Path) -> Result<()> {
// Windows deletes permanently, without a prompt, where a drive has no Recycle Bin.
// Network shares and removable drives have none, so refuse them here.
#[cfg(windows)]
if drive_type(path) != Some(windows_sys::Win32::System::WindowsProgramming::DRIVE_FIXED) {
return Err(Error::new("The trash is not available on this drive."));
}
let target = path.to_path_buf();
// A new thread has no COM state from earlier work, so the trash crate can initialize COM on Windows.
let result = std::thread::spawn(move || trash_item(&target))
.join()
.map_err(|_| Error::new("Could not move the item to the trash."))?;
result.map_err(|reason| Error::new(format!("Could not move the item to the trash: {reason}")))
}
#[cfg(target_os = "macos")]
fn trash_item(path: &Path) -> std::result::Result<(), trash::Error> {
use trash::macos::{DeleteMethod, TrashContextExtMacos};
// The file manager method needs no Finder automation permission and plays no sound.
let mut context = trash::TrashContext::default();
context.set_delete_method(DeleteMethod::NsFileManager);
context.delete(path)
}
#[cfg(not(target_os = "macos"))]
fn trash_item(path: &Path) -> std::result::Result<(), trash::Error> {
trash::delete(path)
}
const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
@@ -721,17 +949,24 @@ fn mime_from_path(path: &Path) -> Option<&'static str> {
}
#[tauri::command]
pub fn workspace_read_data_url(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> Result<String> {
pub async fn workspace_read_data_url(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String) -> Result<String> {
let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?;
blocking(move || read_data_url(&root, &rel)).await
}
fn read_data_url(root: &Path, rel: &str) -> Result<String> {
let path = resolve_existing(root, rel)?;
if path.is_dir() {
return Err(Error::new("path is a folder"));
}
let mime = mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?;
let bytes = fs::read(&path)?;
if bytes.len() > MAX_IMAGE_BYTES {
// Check the size before the read, so that a large file is never loaded into memory.
let file = fs::File::open(&path)?;
if file.metadata()?.len() > MAX_IMAGE_BYTES as u64 {
return Err(Error::new("image is too large"));
}
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
.ok_or_else(|| Error::new("image is too large"))?;
Ok(format!(
"data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
@@ -795,26 +1030,28 @@ pub struct CopyResult {
}
#[tauri::command]
pub fn workspace_copy(window: tauri::Window, state: State<WorkspaceState>, rel: String, parent: Option<String>, expected_root: Option<String>) -> Result<CopyResult> {
pub async fn workspace_copy(window: tauri::Window, state: State<'_, WorkspaceState>, rel: String, parent: Option<String>, expected_root: Option<String>) -> Result<CopyResult> {
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
copy_workspace_item(&root, &rel, parent.as_deref())
blocking(move || copy_workspace_item(&root, &rel, parent.as_deref())).await
}
fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> Result<CopyResult> {
if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() {
return Err(Error::new("Cannot copy symbolic links."));
}
let from = resolve_existing(&root, &rel)?;
let from = resolve_existing(root, rel)?;
if from == root { return Err(Error::new("Cannot copy the workspace root.")); }
let candidate = if let Some(parent) = parent {
let folder = resolve_existing(&root, &parent)?;
let folder = resolve_existing(root, parent)?;
if !folder.is_dir() { return Err(Error::new("Destination is not a folder.")); }
if from.is_dir() && folder.starts_with(&from) { return Err(Error::new("Cannot copy a folder into itself.")); }
folder.join(from.file_name().ok_or_else(|| Error::new("Cannot copy the workspace root."))?)
} else { from.clone() };
if !is_inside(&root, candidate.parent().unwrap_or(&candidate)) {
if !is_inside(root, candidate.parent().unwrap_or(&candidate)) {
return Err(Error::new("path is outside the workspace"));
}
// The copy gets a new name, so it follows the portability rule of new names.
check_portable_name(&candidate.file_name().unwrap_or_default().to_string_lossy())?;
let mut number = if parent.is_some() { 0 } else { 1 };
let dest = loop {
let dest = if number == 0 { candidate.clone() } else { copy_destination(&candidate, number) };
@@ -827,7 +1064,7 @@ fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> Result<C
}
};
let rel_path =
to_rel(&root, &dest).ok_or_else(|| Error::new("copied path is outside the workspace"))?;
to_rel(root, &dest).ok_or_else(|| Error::new("copied path is outside the workspace"))?;
let name = dest
.file_name()
.map(|n| n.to_string_lossy().into_owned())
@@ -904,9 +1141,9 @@ pub struct SearchHit {
}
#[tauri::command]
pub fn workspace_search(window: tauri::Window, state: State<WorkspaceState>, query: String) -> Result<Vec<SearchHit>> {
pub async fn workspace_search(window: tauri::Window, state: State<'_, WorkspaceState>, query: String) -> Result<Vec<SearchHit>> {
let root = current_root(&state, window.label())?;
search_entries(&root, &query)
blocking(move || search_entries(&root, &query)).await
}
fn search_entries(root: &Path, query: &str) -> Result<Vec<SearchHit>> {
@@ -933,7 +1170,7 @@ fn search_entries(root: &Path, query: &str) -> Result<Vec<SearchHit>> {
if is_internal_name(name) || !dent.file_type().is_some_and(|kind| kind.is_file()) {
continue;
}
let rel = match to_rel(&root, path) {
let rel = match to_rel(root, path) {
Some(r) => r,
None => continue,
};
@@ -977,16 +1214,24 @@ fn search_entries(root: &Path, query: &str) -> Result<Vec<SearchHit>> {
Ok(hits)
}
/// Save an image. The only caller (`insertImage` in Workbench.svelte) writes a new, unique
/// attachment name, so it has no previous contents to compare. A conflict check needs an
/// `expected` value from a caller that replaces an existing image.
#[tauri::command]
pub fn workspace_write_bytes(
pub async fn workspace_write_bytes(
window: tauri::Window,
state: State<WorkspaceState>,
state: State<'_, WorkspaceState>,
rel: String,
base64: String,
) -> Result<()> {
let root = current_root(&state, window.label())?;
let path = resolve_for_write(&root, &rel)?;
blocking(move || write_image(&root, &rel, &base64)).await
}
fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
let path = resolve_for_write(root, rel)?;
mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?;
check_new_components(root, rel)?;
let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64.trim())
.map_err(|_| Error::new("invalid image data"))?;
if bytes.len() > MAX_IMAGE_BYTES {
@@ -995,8 +1240,8 @@ pub fn workspace_write_bytes(
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, bytes)?;
Ok(())
// Write beside the destination, then replace it, so that a failed write keeps the old file.
fsutil::write_bytes(&path, &bytes)
}
#[cfg(test)]
@@ -1212,7 +1457,207 @@ mod tests {
#[test]
fn rejects_absolute_paths() {
assert!(check_rel("/etc/passwd").is_err());
assert!(check_rel("C:/Windows").is_err());
assert!(check_rel("\\Windows").is_err());
// On macOS and Linux, `C:` is an ordinary folder name below the workspace root.
assert_eq!(check_rel("C:/Windows").is_err(), cfg!(windows));
}
fn workspace_fixture(name: &str) -> PathBuf {
let root = std::env::temp_dir().join(format!("rs-{name}-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&root).unwrap();
dunce::canonicalize(root).unwrap()
}
fn names(root: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(root).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
names.sort();
names
}
#[test]
fn events_go_to_the_watcher_owner_and_bound_windows_of_the_same_root() {
let state = WorkspaceState::new();
let (notes, other) = (PathBuf::from("D:/notes"), PathBuf::from("D:/other"));
{
let mut workspaces = state.inner.lock().unwrap();
for (label, root) in [("main", &notes), ("workspace-0", &notes), ("workspace-1", &other)] {
workspaces.insert(label.into(), OpenWorkspace { root: root.clone(), watcher: Some(Box::new(notify::NullWatcher)) });
}
}
state.bind_terminal("terminal-0", notes.clone()).unwrap();
state.bind_terminal("terminal-1", other.clone()).unwrap();
let sorted = |mut labels: Vec<String>| { labels.sort(); labels };
// Each window with a watcher gets its own watcher's events once. A terminal window has no watcher.
assert_eq!(sorted(state.event_recipients("main", &notes)), ["main", "terminal-0"]);
assert_eq!(sorted(state.event_recipients("workspace-0", &notes)), ["terminal-0", "workspace-0"]);
assert_eq!(sorted(state.event_recipients("workspace-1", &other)), ["terminal-1", "workspace-1"]);
state.close_window("main");
assert_eq!(state.event_recipients("main", &notes), ["terminal-0"]);
assert_eq!(event_target_label(&EventTarget::AnyLabel { label: "main".into() }), Some("main"));
assert_eq!(event_target_label(&EventTarget::WebviewWindow { label: "main".into() }), Some("main"));
assert_eq!(event_target_label(&EventTarget::Any), None);
assert_eq!(event_target_label(&EventTarget::App), None);
}
#[test]
fn access_events_are_not_sent() {
use notify::event::{AccessKind, CreateKind, EventKind, ModifyKind};
assert_eq!(event_kind(&EventKind::Access(AccessKind::Any)), None);
assert_eq!(event_kind(&EventKind::Create(CreateKind::File)).as_deref(), Some("create"));
assert_eq!(event_kind(&EventKind::Modify(ModifyKind::Any)).as_deref(), Some("modify"));
assert_eq!(event_kind(&EventKind::Remove(notify::event::RemoveKind::Any)).as_deref(), Some("remove"));
}
#[test]
fn case_only_renames_change_the_name_of_the_same_item() {
let root = workspace_fixture("case-rename");
fs::write(root.join("note.md"), "note text").unwrap();
fs::create_dir(root.join("folder")).unwrap();
fs::write(root.join("folder/inside.md"), "inside").unwrap();
rename_item(&root, "note.md", "Note.md").unwrap();
rename_item(&root, "folder", "Folder").unwrap();
assert_eq!(names(&root), ["Folder", "Note.md"]);
assert_eq!(fs::read_to_string(root.join("Note.md")).unwrap(), "note text");
assert_eq!(fs::read_to_string(root.join("Folder/inside.md")).unwrap(), "inside");
// A different item at the destination is still a conflict.
fs::write(root.join("other.md"), "other").unwrap();
assert!(rename_item(&root, "other.md", "Note.md").unwrap_err().to_string().contains("destination already exists"));
if root.join("NOTE.MD").exists() {
// On a case-insensitive volume, another spelling of an existing name is also a conflict.
assert!(rename_item(&root, "other.md", "NOTE.MD").is_err());
}
assert_eq!(fs::read_to_string(root.join("Note.md")).unwrap(), "note text");
assert_eq!(fs::read_to_string(root.join("other.md")).unwrap(), "other");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn new_names_reject_characters_that_windows_does_not_allow() {
let root = workspace_fixture("portable-names");
fs::write(root.join("note.md"), "note").unwrap();
for name in ["a:b.md", "a?b.md", "a*b.md", "a|b.md", "a\"b.md", "a<b.md", "a>b.md", "tab\there.md", "new/a:b.md"] {
assert!(check_new_components(&root, name).is_err(), "{name}");
assert!(create_item(&root, name, "file", None).is_err(), "{name}");
assert!(rename_item(&root, "note.md", name).is_err(), "{name}");
assert!(write_workspace_text(&root, name, "text", None).is_err(), "{name}");
}
assert_eq!(names(&root), ["note.md"]);
for name in ["plain.md", "a b.md", "日本語.md", "new/nested.md"] {
assert!(check_new_components(&root, name).is_ok(), "{name}");
}
create_item(&root, "new/nested.md", "file", Some("nested")).unwrap();
assert_eq!(fs::read_to_string(root.join("new/nested.md")).unwrap(), "nested");
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn existing_names_with_a_colon_stay_usable_on_macos_and_linux() {
let root = workspace_fixture("colon-names");
fs::create_dir(root.join("2026-10-27 10:00")).unwrap();
fs::write(root.join("2026-10-27 10:00/meeting: notes.md"), "notes").unwrap();
let rel = "2026-10-27 10:00/meeting: notes.md";
assert_eq!(read_optional_text(&resolve_existing(&root, rel).unwrap(), false).unwrap().as_deref(), Some("notes"));
write_workspace_text(&root, rel, "edited", Some("notes")).unwrap();
// A new file below an existing folder with a colon is allowed. Only the new name is checked.
create_item(&root, "2026-10-27 10:00/summary.md", "file", None).unwrap();
assert!(create_item(&root, "2026-10-27 10:00/summary: draft.md", "file", None).is_err());
assert!(copy_workspace_item(&root, rel, None).is_err());
rename_item(&root, rel, "2026-10-27 10:00/meeting notes.md").unwrap();
assert_eq!(fs::read_to_string(root.join("2026-10-27 10:00/meeting notes.md")).unwrap(), "edited");
fs::write(root.join("a:b.md"), "x").unwrap();
delete_item(&root, "a:b.md", true).unwrap();
assert!(!root.join("a:b.md").exists());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn image_data_urls_check_the_size_before_reading() {
let root = workspace_fixture("data-url");
fs::write(root.join("dot.png"), b"\x89PNG").unwrap();
assert_eq!(read_data_url(&root, "dot.png").unwrap(), "data:image/png;base64,iVBORw==");
// A sparse file has the reported size without data on the disk.
fs::File::create(root.join("large.png")).unwrap().set_len(MAX_IMAGE_BYTES as u64 + 1).unwrap();
assert_eq!(read_data_url(&root, "large.png").unwrap_err().to_string(), "image is too large");
assert!(read_data_url(&root, "missing.png").is_err());
fs::remove_dir_all(root).unwrap();
}
#[test]
fn image_writes_replace_atomically() {
let root = workspace_fixture("write-image");
write_image(&root, "attachments/dot.png", "iVBORw==").unwrap();
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), b"\x89PNG");
write_image(&root, "attachments/dot.png", "AQID").unwrap();
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), [1, 2, 3]);
assert!(write_image(&root, "attachments/dot.png", "not base64!").is_err());
assert!(write_image(&root, "attachments/note.md", "AQID").is_err());
assert!(write_image(&root, "attachments/bad?.png", "AQID").is_err());
assert_eq!(fs::read(root.join("attachments/dot.png")).unwrap(), [1, 2, 3]);
assert_eq!(names(&root.join("attachments")), ["dot.png"]);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
let root = workspace_fixture("delete");
fs::create_dir_all(root.join("folder/child")).unwrap();
fs::write(root.join("folder/child/note.md"), "note").unwrap();
fs::write(root.join("file.md"), "file").unwrap();
for rel in ["", ".", "missing.md", "../outside"] {
assert!(delete_item(&root, rel, true).is_err(), "{rel}");
assert!(delete_item(&root, rel, false).is_err(), "{rel}");
}
delete_item(&root, "folder", true).unwrap();
delete_item(&root, "file.md", true).unwrap();
assert!(names(&root).is_empty());
fs::remove_dir_all(root).unwrap();
}
#[test]
#[ignore = "Moves a temporary file to the system trash."]
fn delete_moves_items_to_the_trash() {
let root = workspace_fixture("trash");
fs::write(root.join("trash-me.md"), "trash").unwrap();
fs::create_dir(root.join("trash-folder")).unwrap();
delete_item(&root, "trash-me.md", false).unwrap();
delete_item(&root, "trash-folder", false).unwrap();
assert!(names(&root).is_empty());
fs::remove_dir_all(root).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn delete_and_rename_act_on_links_and_keep_their_targets() {
let fixture = workspace_fixture("link-actions");
let root = fixture.join("workspace");
fs::create_dir_all(root.join("folder")).unwrap();
fs::write(root.join("target.md"), "inside target").unwrap();
fs::write(fixture.join("outside.md"), "outside target").unwrap();
fs::write(root.join("folder/keep.md"), "keep").unwrap();
#[cfg(unix)]
let (file_link, folder_link) = (|from: &Path, to: &Path| std::os::unix::fs::symlink(from, to), |from: &Path, to: &Path| std::os::unix::fs::symlink(from, to));
#[cfg(windows)]
let (file_link, folder_link) = (|from: &Path, to: &Path| std::os::windows::fs::symlink_file(from, to), |from: &Path, to: &Path| std::os::windows::fs::symlink_dir(from, to));
if let Err(reason) = file_link(&root.join("target.md"), &root.join("link.md")) {
#[cfg(windows)]
if reason.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) { eprintln!("Symbolic-link test requires Windows Developer Mode or symlink privilege."); fs::remove_dir_all(fixture).unwrap(); return; }
panic!("Could not prepare the link test: {reason}");
}
file_link(&fixture.join("outside.md"), &root.join("outside-link.md")).unwrap();
folder_link(&root.join("folder"), &root.join("folder-link")).unwrap();
rename_item(&root, "link.md", "renamed-link.md").unwrap();
assert!(fs::symlink_metadata(root.join("renamed-link.md")).unwrap().file_type().is_symlink());
assert_eq!(fs::read_to_string(root.join("target.md")).unwrap(), "inside target");
for rel in ["renamed-link.md", "outside-link.md", "folder-link"] {
delete_item(&root, rel, true).unwrap();
assert!(fs::symlink_metadata(root.join(rel)).is_err(), "{rel}");
}
assert_eq!(fs::read_to_string(root.join("target.md")).unwrap(), "inside target");
assert_eq!(fs::read_to_string(fixture.join("outside.md")).unwrap(), "outside target");
assert_eq!(fs::read_to_string(root.join("folder/keep.md")).unwrap(), "keep");
assert_eq!(names(&root), ["folder", "target.md"]);
fs::remove_dir_all(fixture).unwrap();
}
#[test]