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() {