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
+16 -1
View File
@@ -51,7 +51,21 @@ Right-click a file or folder for more actions, such as **Make a copy**, **Copy w
With the navigator focused, Ctrl+X, Ctrl+C, and Ctrl+V cut, copy, and paste files. With the navigator focused, Ctrl+X, Ctrl+C, and Ctrl+V cut, copy, and paste files.
Ctrl+Z undoes a file move or rename, and Ctrl+Shift+Z or Ctrl+Y repeats it. Ctrl+Z undoes a file move or rename, and Ctrl+Shift+Z or Ctrl+Y repeats it.
**Delete** removes files permanently. It does not use the Recycle Bin or Trash, and Ctrl+Z cannot restore the files. ### Delete files
**Delete** moves the selected items to the Recycle Bin or Trash. To get them back, restore them from there. Ctrl+Z does not restore deleted files.
- Select items in the navigator and press Delete, or right-click and choose **Delete**. On macOS, you can also press Cmd+Backspace.
- RuneStone asks for confirmation before it moves a folder or several items. One file moves without a question.
- **Delete permanently** (Shift+Delete, or Cmd+Option+Backspace on macOS) removes the items from the disk. RuneStone always asks first.
- A link is deleted as a link. The file or folder that it points to stays.
Network drives, removable drives, and some Linux setups have no trash. There, **Delete** shows an error and keeps the files. Use **Delete permanently** if you want to remove them.
### Names of new files
A new name cannot contain these characters: `< > : " | ? *`. Windows does not allow them. This rule applies on every platform, so that a workspace that you share, for example through Git, also opens on Windows.
On macOS and Linux, you can still open, edit, rename, and delete existing files whose names contain these characters.
## Edit documents ## Edit documents
@@ -197,6 +211,7 @@ This table lists the Windows and Linux keys.
| Switch Writer and IDE | Ctrl+E | | Switch Writer and IDE | Ctrl+E |
| Show or hide the sidebar | Ctrl+B | | Show or hide the sidebar | Ctrl+B |
| Rename | F2 | | Rename | F2 |
| Delete to the trash / Delete permanently | Delete / Shift+Delete |
| Context menu | Shift+F10 | | Context menu | Shift+F10 |
| Settings / Help and about | Ctrl+, / F1 | | Settings / Help and about | Ctrl+, / F1 |
+90 -13
View File
@@ -3135,6 +3135,7 @@ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
"ignore", "ignore",
"libc",
"notify", "notify",
"portable-pty", "portable-pty",
"reqwest", "reqwest",
@@ -3145,9 +3146,10 @@ dependencies = [
"tauri-build", "tauri-build",
"tauri-plugin-dialog", "tauri-plugin-dialog",
"tauri-plugin-opener", "tauri-plugin-opener",
"trash",
"uuid", "uuid",
"webview2-com", "webview2-com",
"windows", "windows 0.61.3",
"windows-sys 0.61.2", "windows-sys 0.61.2",
"zip", "zip",
] ]
@@ -3763,7 +3765,7 @@ dependencies = [
"tao-macros", "tao-macros",
"unicode-segmentation", "unicode-segmentation",
"url", "url",
"windows", "windows 0.61.3",
"windows-core 0.61.2", "windows-core 0.61.2",
"windows-version", "windows-version",
"x11-dl", "x11-dl",
@@ -3834,7 +3836,7 @@ dependencies = [
"webkit2gtk", "webkit2gtk",
"webview2-com", "webview2-com",
"window-vibrancy", "window-vibrancy",
"windows", "windows 0.61.3",
] ]
[[package]] [[package]]
@@ -3975,7 +3977,7 @@ dependencies = [
"tauri-plugin", "tauri-plugin",
"thiserror 2.0.20", "thiserror 2.0.20",
"url", "url",
"windows", "windows 0.61.3",
"zbus", "zbus",
] ]
@@ -4001,7 +4003,7 @@ dependencies = [
"url", "url",
"webkit2gtk", "webkit2gtk",
"webview2-com", "webview2-com",
"windows", "windows 0.61.3",
] ]
[[package]] [[package]]
@@ -4026,7 +4028,7 @@ dependencies = [
"url", "url",
"webkit2gtk", "webkit2gtk",
"webview2-com", "webview2-com",
"windows", "windows 0.61.3",
"wry", "wry",
] ]
@@ -4420,6 +4422,24 @@ dependencies = [
"once_cell", "once_cell",
] ]
[[package]]
name = "trash"
version = "5.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be89b3fe156965d29ac4f8522f3a640c655affdd9f21cb4f36857f0c92c00317"
dependencies = [
"chrono",
"libc",
"log",
"objc2",
"objc2-foundation",
"once_cell",
"percent-encoding",
"scopeguard",
"urlencoding",
"windows 0.62.2",
]
[[package]] [[package]]
name = "tray-icon" name = "tray-icon"
version = "0.24.2" version = "0.24.2"
@@ -4543,6 +4563,12 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "urlencoding"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
[[package]] [[package]]
name = "urlpattern" name = "urlpattern"
version = "0.3.0" version = "0.3.0"
@@ -4787,7 +4813,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
dependencies = [ dependencies = [
"webview2-com-macros", "webview2-com-macros",
"webview2-com-sys", "webview2-com-sys",
"windows", "windows 0.61.3",
"windows-core 0.61.2", "windows-core 0.61.2",
"windows-implement", "windows-implement",
"windows-interface", "windows-interface",
@@ -4811,7 +4837,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
dependencies = [ dependencies = [
"thiserror 2.0.20", "thiserror 2.0.20",
"windows", "windows 0.61.3",
"windows-core 0.61.2", "windows-core 0.61.2",
] ]
@@ -4867,11 +4893,23 @@ version = "0.61.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [ dependencies = [
"windows-collections", "windows-collections 0.2.0",
"windows-core 0.61.2", "windows-core 0.61.2",
"windows-future", "windows-future 0.2.1",
"windows-link 0.1.3", "windows-link 0.1.3",
"windows-numerics", "windows-numerics 0.2.0",
]
[[package]]
name = "windows"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
dependencies = [
"windows-collections 0.3.2",
"windows-core 0.62.2",
"windows-future 0.3.2",
"windows-numerics 0.3.1",
] ]
[[package]] [[package]]
@@ -4883,6 +4921,15 @@ dependencies = [
"windows-core 0.61.2", "windows-core 0.61.2",
] ]
[[package]]
name = "windows-collections"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
dependencies = [
"windows-core 0.62.2",
]
[[package]] [[package]]
name = "windows-core" name = "windows-core"
version = "0.61.2" version = "0.61.2"
@@ -4917,7 +4964,18 @@ checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [ dependencies = [
"windows-core 0.61.2", "windows-core 0.61.2",
"windows-link 0.1.3", "windows-link 0.1.3",
"windows-threading", "windows-threading 0.1.0",
]
[[package]]
name = "windows-future"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
"windows-threading 0.2.1",
] ]
[[package]] [[package]]
@@ -4964,6 +5022,16 @@ dependencies = [
"windows-link 0.1.3", "windows-link 0.1.3",
] ]
[[package]]
name = "windows-numerics"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
dependencies = [
"windows-core 0.62.2",
"windows-link 0.2.1",
]
[[package]] [[package]]
name = "windows-result" name = "windows-result"
version = "0.3.4" version = "0.3.4"
@@ -5093,6 +5161,15 @@ dependencies = [
"windows-link 0.1.3", "windows-link 0.1.3",
] ]
[[package]]
name = "windows-threading"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [
"windows-link 0.2.1",
]
[[package]] [[package]]
name = "windows-version" name = "windows-version"
version = "0.1.7" version = "0.1.7"
@@ -5333,7 +5410,7 @@ dependencies = [
"webkit2gtk", "webkit2gtk",
"webkit2gtk-sys", "webkit2gtk-sys",
"webview2-com", "webview2-com",
"windows", "windows 0.61.3",
"windows-core 0.61.2", "windows-core 0.61.2",
"windows-version", "windows-version",
"x11-dl", "x11-dl",
+4
View File
@@ -27,6 +27,10 @@ zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
sha2 = "0.10" sha2 = "0.10"
uuid = { version = "1", features = ["v4"] } uuid = { version = "1", features = ["v4"] }
reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] } reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] }
trash = "5.2.9"
[target.'cfg(unix)'.dependencies]
libc = "0.2.189"
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Input_KeyboardAndMouse"] } windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Threading", "Win32_System_WindowsProgramming", "Win32_UI_Input_KeyboardAndMouse"] }
+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, /// Publish a complete new file at `path` through `temp`. Fail if `path` exists,
/// so that a file created by another writer is never replaced. /// 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<()> { pub fn create_file(path: &Path, temp: &Path, bytes: &[u8]) -> io::Result<()> {
write_temp_then(temp, bytes, || { create_file_with(path, temp, bytes, rename_no_replace)
fs::hard_link(temp, path)?; }
let _ = fs::remove_file(temp);
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(()) 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`. /// 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 /// Write completely beside the destination, then replace it. A failed write
/// leaves the original file intact rather than truncating it. /// leaves the original file intact rather than truncating it.
pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result<()> { 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 { 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.") Error::new("Save blocked: file was removed or cannot be read. Your edits are still open.")
})?; })?;
if current != expected { if current != expected {
@@ -123,7 +282,7 @@ pub fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> Result
.create_new(true) .create_new(true)
.open(&temp).map_err(|reason| Error::new(format!("Could not create a save file for {}: {reason}", path.display())))?; .open(&temp).map_err(|reason| Error::new(format!("Could not create a save file for {}: {reason}", path.display())))?;
let result = (|| -> Result<()> { 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())))?; file.sync_all().map_err(|reason| Error::new(format!("Could not flush the save file for {}: {reason}", path.display())))?;
#[cfg(not(windows))] #[cfg(not(windows))]
if let Ok(metadata) = fs::metadata(path) { 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); drop(file);
// Recheck after preparing the replacement to narrow the external-write race. // Recheck after preparing the replacement to narrow the external-write race.
if let Some(expected) = expected { 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( return Err(Error::new(
"Save blocked: file changed while saving. Your edits are still open.", "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)] #[cfg(windows)]
fn restore_save_backup(backup: &Path, path: &Path) -> io::Result<()> { fn restore_save_backup(backup: &Path, path: &Path) -> io::Result<()> {
// A concurrent writer must never lose its file during recovery. // A concurrent writer must never lose its file during recovery.
fs::hard_link(backup, path)?; // A move without replacement also works on volumes without hard links.
let _ = fs::remove_file(backup); rename_no_replace(backup, path)
Ok(())
} }
#[cfg(test)] #[cfg(test)]
@@ -289,6 +447,73 @@ mod tests {
fs::remove_dir_all(dir).unwrap(); 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))] #[cfg(any(unix, windows))]
#[test] #[test]
fn links_are_detected_from_link_metadata() { 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 notify::{Config, Event, PollWatcher, RecommendedWatcher, RecursiveMode, Watcher};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, Manager, State}; use tauri::{AppHandle, Emitter, EventTarget, Manager, State};
use tauri_plugin_opener::OpenerExt; use tauri_plugin_opener::OpenerExt;
use crate::error::{Error, Result}; use crate::error::{Error, Result};
@@ -42,7 +42,9 @@ pub struct WorkspaceState {
struct OpenWorkspace { struct OpenWorkspace {
root: PathBuf, 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 { impl WorkspaceState {
@@ -53,14 +55,30 @@ impl WorkspaceState {
} }
pub fn close_window(&self, label: &str) { 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<()> { pub fn bind_terminal(&self, label: &str, root: PathBuf) -> Result<()> {
self.inner.lock().map_err(|_| Error::new("workspace lock"))? let replaced = self.inner.lock().map_err(|_| Error::new("workspace lock"))?
.insert(label.to_owned(), OpenWorkspace { root, _watcher: None }); .insert(label.to_owned(), OpenWorkspace { root, watcher: None });
drop(replaced);
Ok(()) 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> { fn last_workspace_file(app: &AppHandle) -> Result<PathBuf> {
@@ -164,6 +182,11 @@ fn load_last_workspace(app: &AppHandle) -> Option<PathBuf> {
Some(PathBuf::from(root)) 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<()> { pub fn check_rel(rel: &str) -> Result<()> {
if rel.contains('\0') { if rel.contains('\0') {
return Err(Error::new("path contains a null byte")); 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('\\') { if normalized.starts_with('/') || normalized.starts_with('\\') {
return Err(Error::new("absolute paths are not allowed")); 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")); return Err(Error::new("drive prefixes are not allowed"));
} }
for part in normalized.split('/') { for part in normalized.split('/') {
@@ -183,6 +206,40 @@ pub fn check_rel(rel: &str) -> Result<()> {
Ok(()) 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> { fn join_rel(root: &Path, rel: &str) -> Result<PathBuf> {
check_rel(rel)?; check_rel(rel)?;
let normalized = rel.replace('\\', "/"); let normalized = rel.replace('\\', "/");
@@ -214,13 +271,38 @@ fn resolve_existing(root: &Path, rel: &str) -> Result<PathBuf> {
Ok(canon) 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> { fn resolve_for_write(root: &Path, rel: &str) -> Result<PathBuf> {
let joined = join_rel(root, rel)?; let joined = join_rel(root, rel)?;
if joined == root { if joined == root {
return Err(Error::new("the workspace root cannot be modified")); return Err(Error::new("the workspace root cannot be modified"));
} }
// Validate the nearest existing ancestor, including the target itself. resolve_under(root, &joined)
// This catches links to outside the workspace even below missing folders. }
/// 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() { for ancestor in joined.ancestors() {
if fs::symlink_metadata(ancestor).is_ok() { if fs::symlink_metadata(ancestor).is_ok() {
let canonical = dunce::canonicalize(ancestor)?; 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")); 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> { 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('\\', "/")) 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)] #[cfg(windows)]
fn is_network_path(path: &Path) -> bool { fn drive_type(path: &Path) -> Option<u32> {
let s = path.to_string_lossy();
if s.starts_with("\\\\") || s.starts_with("//") {
return true;
}
use std::os::windows::ffi::OsStrExt; use std::os::windows::ffi::OsStrExt;
let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect(); let mut wide: Vec<u16> = path.as_os_str().encode_wide().collect();
wide.push(0); wide.push(0);
@@ -263,49 +356,81 @@ fn is_network_path(path: &Path) -> bool {
volume.len() as u32, volume.len() as u32,
); );
if ok == 0 { if ok == 0 {
return false; return None;
} }
let drive_type = windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()); Some(windows_sys::Win32::Storage::FileSystem::GetDriveTypeW(volume.as_ptr()))
drive_type == windows_sys::Win32::System::WindowsProgramming::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;
}
drive_type(path) == Some(windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE)
}
#[cfg(not(windows))] #[cfg(not(windows))]
fn is_network_path(path: &Path) -> bool { fn is_network_path(path: &Path) -> bool {
let s = path.to_string_lossy(); let s = path.to_string_lossy();
s.starts_with("//") s.starts_with("//")
} }
fn emit_watch_event(app: &AppHandle, root: &Path, event: Event) { /// The name of a change for the frontend, such as "create" or "modify".
let kind = format!("{:?}", event.kind) /// Access events are `None`: the frontend has no use for them.
.split('(') fn event_kind(kind: &notify::EventKind) -> Option<String> {
.next() if kind.is_access() {
.unwrap_or("other") return None;
.to_lowercase(); }
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(); let paths: Vec<String> = event.paths.iter().filter_map(|p| to_rel(root, p)).collect();
if paths.is_empty() { if paths.is_empty() {
return; 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", "workspace-event",
WorkspaceEvent { WorkspaceEvent {
root: root.to_string_lossy().into_owned(), root: root.to_string_lossy().into_owned(),
kind, kind,
paths, 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( fn start_watcher(
app: AppHandle, app: AppHandle,
owner: String,
root: PathBuf, root: PathBuf,
network: bool, network: bool,
) -> Result<Box<dyn Watcher + Send>> { ) -> Result<Box<dyn Watcher + Send>> {
let handler_root = root.clone(); let handler_root = root.clone();
let handler_app = app.clone(); let handler_app = app.clone();
let handler_owner = owner.clone();
let handler = move |res: notify::Result<Event>| { let handler = move |res: notify::Result<Event>| {
if let Ok(event) = res { 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( let mut watcher = PollWatcher::new(
move |res: notify::Result<Event>| { move |res: notify::Result<Event>| {
if let Ok(event) = res { 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)), 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<()> { 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); 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 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"))?; let mut config = app.config().app.windows.first().cloned().ok_or_else(|| Error::new("Missing window configuration"))?;
config.label = label.clone(); config.label = label.clone();
config.title = format!("{} — RuneStone", workspace_info(&root).name); 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. // 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 { 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 result = (|| -> Result<()> {
let window = tauri::WebviewWindowBuilder::from_config(app, &config) 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) 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] #[tauri::command]
pub fn workspace_open( pub async fn workspace_open(
app: AppHandle, app: AppHandle,
window: tauri::Window, window: tauri::Window,
state: State<WorkspaceState>, state: State<'_, WorkspaceState>,
path: String, path: String,
) -> Result<WorkspaceInfo> { ) -> Result<WorkspaceInfo> {
let root = dunce::canonicalize(&path).map_err(|_| Error::new("folder does not exist"))?; let label = window.label().to_owned();
if !root.is_dir() { let previous = current_root(&state, &label).ok();
return Err(Error::new("path is not a folder")); let worker_app = app.clone();
} let worker_label = label.clone();
if let Ok(previous) = current_root(&state, window.label()) { // Canonicalization, the first scan of a polled network share, and the history file can block.
if previous == root { return Ok(workspace_info(&root)); } let (root, watcher) = blocking(move || {
return Err(Error::new("Open another workspace in a new window.")); let root = dunce::canonicalize(&path).map_err(|_| Error::new("folder does not exist"))?;
} if !root.is_dir() {
let network = is_network_path(&root); return Err(Error::new("path is not a folder"));
let watcher = start_watcher(app.clone(), root.clone(), network)?; }
save_last_workspace(&app, &root)?; 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"))?; 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(), root: root.clone(),
_watcher: Some(watcher), watcher: Some(watcher),
}); });
} }
let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name)); let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name));
// A settings session opened before this workspace must start with its new context. // 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)) Ok(workspace_info(&root))
} }
#[tauri::command] #[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())?; 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>> { 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") { if is_internal_name(&name) && !(show_internal && name == ".runestone") {
continue; continue;
} }
let rel_path = match to_rel(&root, path) { let rel_path = match to_rel(root, path) {
Some(r) => r, Some(r) => r,
None => continue, None => continue,
}; };
@@ -527,13 +674,15 @@ fn markdown_paths(root: &Path) -> Result<Vec<String>> {
} }
#[tauri::command] #[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 root = current_root(&state, window.label())?;
let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? }; blocking(move || {
if path.is_dir() { let path = if missing_ok.unwrap_or(false) { resolve_for_write(&root, &rel)? } else { resolve_existing(&root, &rel)? };
return Err(Error::new("path is a folder")); if path.is_dir() {
} return Err(Error::new("path is a folder"));
read_optional_text(&path, missing_ok.unwrap_or(false)) }
read_optional_text(&path, missing_ok.unwrap_or(false))
}).await
} }
fn read_optional_text(path: &Path, missing_ok: bool) -> Result<Option<String>> { 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] #[tauri::command]
pub fn workspace_write( pub async fn workspace_write(
window: tauri::Window, window: tauri::Window,
state: State<WorkspaceState>, state: State<'_, WorkspaceState>,
rel: String, rel: String,
contents: String, contents: String,
expected: Option<String>, expected: Option<String>,
) -> Result<()> { ) -> Result<()> {
let root = current_root(&state, window.label())?; 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() { 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())))?; 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 { fn is_internal_name(name: &str) -> bool {
@@ -624,16 +779,21 @@ fn is_internal_name(name: &str) -> bool {
} }
#[tauri::command] #[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 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() { if path.exists() {
return Err(Error::new("path already exists")); return Err(Error::new("path already exists"));
} }
check_new_components(root, rel)?;
if kind == "folder" { if kind == "folder" {
fs::create_dir_all(&path)?; fs::create_dir_all(&path)?;
} else if let Some(contents) = contents { } else if let Some(contents) = contents {
create_text_if_absent(&path, &contents)?; create_text_if_absent(&path, contents)?;
} else { } else {
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
@@ -668,15 +828,28 @@ fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Opt
} }
#[tauri::command] #[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 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 { if from_path == root {
return Err(Error::new("the workspace root cannot be renamed")); return Err(Error::new("the workspace root cannot be renamed"));
} }
let to_path = resolve_for_write(&root, &to)?; let to_path = resolve_destination(root, to)?;
if to_path.exists() { if fs::symlink_metadata(&to_path).is_ok() {
return Err(Error::new("destination already exists")); // 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() { if let Some(parent) = to_path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
@@ -685,19 +858,74 @@ pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, fro
Ok(()) 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] #[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 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 { if path == root {
return Err(Error::new("the workspace root cannot be deleted")); return Err(Error::new("the workspace root cannot be deleted"));
} }
if path.is_dir() { if permanent {
fs::remove_dir_all(path)?; remove_entry(&path)?;
Ok(())
} else { } 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; const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;
@@ -721,17 +949,24 @@ fn mime_from_path(path: &Path) -> Option<&'static str> {
} }
#[tauri::command] #[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 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() { if path.is_dir() {
return Err(Error::new("path is a folder")); 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 mime = mime_from_path(&path).ok_or_else(|| Error::new("file is not an image"))?;
let bytes = fs::read(&path)?; // Check the size before the read, so that a large file is never loaded into memory.
if bytes.len() > MAX_IMAGE_BYTES { let file = fs::File::open(&path)?;
if file.metadata()?.len() > MAX_IMAGE_BYTES as u64 {
return Err(Error::new("image is too large")); 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!( Ok(format!(
"data:{mime};base64,{}", "data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes) base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
@@ -795,26 +1030,28 @@ pub struct CopyResult {
} }
#[tauri::command] #[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())?; 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> { 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() { if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() {
return Err(Error::new("Cannot copy symbolic links.")); 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.")); } if from == root { return Err(Error::new("Cannot copy the workspace root.")); }
let candidate = if let Some(parent) = parent { 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 !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.")); } 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."))?) folder.join(from.file_name().ok_or_else(|| Error::new("Cannot copy the workspace root."))?)
} else { from.clone() }; } 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")); 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 mut number = if parent.is_some() { 0 } else { 1 };
let dest = loop { let dest = loop {
let dest = if number == 0 { candidate.clone() } else { copy_destination(&candidate, number) }; 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 = 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 let name = dest
.file_name() .file_name()
.map(|n| n.to_string_lossy().into_owned()) .map(|n| n.to_string_lossy().into_owned())
@@ -904,9 +1141,9 @@ pub struct SearchHit {
} }
#[tauri::command] #[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())?; 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>> { 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()) { if is_internal_name(name) || !dent.file_type().is_some_and(|kind| kind.is_file()) {
continue; continue;
} }
let rel = match to_rel(&root, path) { let rel = match to_rel(root, path) {
Some(r) => r, Some(r) => r,
None => continue, None => continue,
}; };
@@ -977,16 +1214,24 @@ fn search_entries(root: &Path, query: &str) -> Result<Vec<SearchHit>> {
Ok(hits) 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] #[tauri::command]
pub fn workspace_write_bytes( pub async fn workspace_write_bytes(
window: tauri::Window, window: tauri::Window,
state: State<WorkspaceState>, state: State<'_, WorkspaceState>,
rel: String, rel: String,
base64: String, base64: String,
) -> Result<()> { ) -> Result<()> {
let root = current_root(&state, window.label())?; 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"))?; 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()) let bytes = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, base64.trim())
.map_err(|_| Error::new("invalid image data"))?; .map_err(|_| Error::new("invalid image data"))?;
if bytes.len() > MAX_IMAGE_BYTES { if bytes.len() > MAX_IMAGE_BYTES {
@@ -995,8 +1240,8 @@ pub fn workspace_write_bytes(
if let Some(parent) = path.parent() { if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?; fs::create_dir_all(parent)?;
} }
fs::write(path, bytes)?; // Write beside the destination, then replace it, so that a failed write keeps the old file.
Ok(()) fsutil::write_bytes(&path, &bytes)
} }
#[cfg(test)] #[cfg(test)]
@@ -1212,7 +1457,207 @@ mod tests {
#[test] #[test]
fn rejects_absolute_paths() { fn rejects_absolute_paths() {
assert!(check_rel("/etc/passwd").is_err()); 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] #[test]
+9 -1
View File
@@ -3466,7 +3466,15 @@ export const messageRows: [string, string, string, string][] = [
"{count} éléments supprimés sur {total}", "{count} éléments supprimés sur {total}",
"{total}項目中{count}項目を削除しました", "{total}項目中{count}項目を削除しました",
"已删除 {total} 项中的 {count} 项" "已删除 {total} 项中的 {count} 项"
] ],
["Delete permanently", "Supprimer définitivement", "完全に削除", "永久删除"],
["Delete permanently ({count})", "Supprimer définitivement ({count})", "完全に削除 ({count})", "永久删除 ({count})"],
["Move to trash", "Placer dans la corbeille", "ごみ箱に移動", "移到回收站"],
["Move {name} and everything inside it to the trash?", "Placer {name} et tout son contenu dans la corbeille ?", "{name}とその中のすべてをごみ箱に移動しますか?", "将 {name} 及其全部内容移到回收站?"],
["Move {count} selected items to the trash?", "Placer les {count} éléments sélectionnés dans la corbeille ?", "選択した{count}項目をごみ箱に移動しますか?", "将所选的 {count} 项移到回收站?"],
["Move {count} selected items and all contents of selected folders to the trash?", "Placer les {count} éléments et tout le contenu des dossiers sélectionnés dans la corbeille ?", "選択した{count}項目と選択フォルダー内のすべてをごみ箱に移動しますか?", "将所选的 {count} 项及所选文件夹的全部内容移到回收站?"],
["Moved {count} of {total} items to the trash. Restore them from the system trash.", "{count} éléments sur {total} placés dans la corbeille. Restaurez-les depuis la corbeille du système.", "{total}項目中{count}項目をごみ箱に移動しました。システムのごみ箱から復元できます。", "已将 {total} 项中的 {count} 项移到回收站。可从系统回收站恢复。"],
["To delete permanently instead, select the items and press Shift+Delete.", "Pour supprimer définitivement, sélectionnez les éléments et appuyez sur Maj+Suppr.", "完全に削除するには、項目を選択して Shift+Delete を押してください。", "要永久删除,请选择这些项目并按 Shift+Delete。"]
]; ];
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = { export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])), fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
+45 -8
View File
@@ -449,6 +449,18 @@
return; return;
} }
} }
// Delete moves the selection to the trash. Shift+Delete deletes it permanently.
// macOS keyboards: Cmd+Backspace and Cmd+Option+Backspace, as in Finder.
const deleteKey = event.key === "Delete" && !event.ctrlKey && !event.metaKey && !event.altKey;
const macDeleteKey = event.key === "Backspace" && event.metaKey && !event.ctrlKey && !event.shiftKey;
if ((deleteKey || macDeleteKey) && event.target instanceof Element && treeElement?.contains(event.target)
&& !event.target.closest('input, textarea, [contenteditable="true"]')) {
const entries = [...selection.paths].map(findEntry).filter((entry): entry is TreeEntry => !!entry);
if (!entries.length) return;
event.preventDefault(); event.stopPropagation();
void deleteEntries(entries, deleteKey ? event.shiftKey : event.altKey);
return;
}
if (event.key !== "F2" || event.ctrlKey || event.metaKey || event.altKey) { if (event.key !== "F2" || event.ctrlKey || event.metaKey || event.altKey) {
return; return;
} }
@@ -682,21 +694,40 @@
onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`); onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`);
} }
async function deleteEntries(entries: TreeEntry[]) { // Delete moves items to the system trash. One file needs no confirmation, because the
// trash can restore it. A folder or several items need one. A permanent delete
// (Shift+Delete, or "Delete permanently" in the menu) always asks first.
function deleteQuestion(entries: TreeEntry[], roots: TreeEntry[], permanent: boolean): string | null {
if (entries.length === 1) {
const name = entries[0].name;
if (entries[0].kind === "folder") return $t(permanent ? "Permanently delete {name} and everything inside it?" : "Move {name} and everything inside it to the trash?", { name });
return permanent ? $t("Permanently delete {name}?", { name }) : null;
}
const folders = entries.some(entry => entry.kind === "folder");
const question = permanent
? $t(folders ? "Permanently delete {count} selected items and all contents of selected folders?" : "Permanently delete {count} selected items?", { count: entries.length })
: $t(folders ? "Move {count} selected items and all contents of selected folders to the trash?" : "Move {count} selected items to the trash?", { count: entries.length });
return question + "\n\n" + roots.map(entry => entry.rel_path).join("\n");
}
async function deleteEntries(entries: TreeEntry[], permanent = false) {
if (!entries.length) return;
const roots = selectionRoots(entries); const roots = selectionRoots(entries);
const message = entries.length === 1 const question = deleteQuestion(entries, roots, permanent);
? $t(entries[0].kind === "folder" ? "Permanently delete {name} and everything inside it?" : "Permanently delete {name}?", { name: entries[0].name })
: $t(entries.some(entry => entry.kind === "folder") ? "Permanently delete {count} selected items and all contents of selected folders?" : "Permanently delete {count} selected items?", { count: entries.length }) + "\n\n" + roots.map(entry => entry.rel_path).join("\n");
try { try {
if (!await confirm(message, { title: $t("Delete from disk"), kind: "warning" })) return; if (question && !await confirm(question, { title: $t(permanent ? "Delete from disk" : "Move to trash"), kind: "warning" })) return;
const result = await runTreeActions(roots, async entry => { const result = await runTreeActions(roots, async entry => {
await workspaceDelete(entry.rel_path); await workspaceDelete(entry.rel_path, permanent);
forgetFolder(entry.rel_path); forgetFolder(entry.rel_path);
onEntryGone?.(entry.rel_path); onEntryGone?.(entry.rel_path);
}); });
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent); for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
error = result.failures.length ? result.failures.join("\n") : null; // The trash can be unavailable, for example on a network drive. A permanent delete stays an explicit choice.
onStatus?.($t("Deleted {count} of {total} items", { count: result.completed.length, total: roots.length })); const hint = !permanent && result.failures.length ? [$t("To delete permanently instead, select the items and press Shift+Delete.")] : [];
error = result.failures.length ? [...result.failures, ...hint].join("\n") : null;
onStatus?.(permanent
? $t("Deleted {count} of {total} items", { count: result.completed.length, total: roots.length })
: $t("Moved {count} of {total} items to the trash. Restore them from the system trash.", { count: result.completed.length, total: roots.length }));
} catch (err) { } catch (err) {
error = err instanceof Error ? err.message : String(err); error = err instanceof Error ? err.message : String(err);
} }
@@ -875,6 +906,12 @@
icon: "trash", icon: "trash",
run: () => { void deleteEntries(entries); }, run: () => { void deleteEntries(entries); },
}, },
{
kind: "action",
label: multiple ? $t("Delete permanently ({count})", { count: entries.length }) : $t("Delete permanently"),
icon: "trash",
run: () => { void deleteEntries(entries, true); },
},
]; ];
} }
</script> </script>
+10 -3
View File
@@ -1,5 +1,6 @@
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event"; import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { open as openDialog } from "@tauri-apps/plugin-dialog"; import { open as openDialog } from "@tauri-apps/plugin-dialog";
import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types"; import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types";
import { tr } from "../i18n/index.ts"; import { tr } from "../i18n/index.ts";
@@ -64,8 +65,9 @@ export function workspaceRename(from: string, to: string, expectedRoot?: string)
return invoke("workspace_rename", { from, to, expectedRoot }); return invoke("workspace_rename", { from, to, expectedRoot });
} }
export function workspaceDelete(rel: string): Promise<void> { /** Move an item to the system trash, or delete it permanently with `permanent`. */
return invoke("workspace_delete", { rel }); export function workspaceDelete(rel: string, permanent = false): Promise<void> {
return invoke("workspace_delete", { rel, permanent });
} }
export function workspaceReadDataUrl(rel: string): Promise<string> { export function workspaceReadDataUrl(rel: string): Promise<string> {
@@ -107,10 +109,15 @@ export function workspaceSearch(query: string): Promise<SearchHit[]> {
return invoke("workspace_search", { query }); return invoke("workspace_search", { query });
} }
/**
* Listen to file changes in the workspace of this window. The host sends each change only to
* the windows that have its workspace open (src-tauri/src/workspace.rs `emit_watch_event`).
* The target must be this window: a listener without a target receives the events of every window.
*/
export function onWorkspaceEvent( export function onWorkspaceEvent(
handler: (event: WorkspaceEvent) => void, handler: (event: WorkspaceEvent) => void,
): Promise<UnlistenFn> { ): Promise<UnlistenFn> {
return listen<WorkspaceEvent>("workspace-event", (event) => { return listen<WorkspaceEvent>("workspace-event", (event) => {
handler(event.payload); handler(event.payload);
}); }, { target: getCurrentWindow().label });
} }
+34 -1
View File
@@ -96,6 +96,7 @@ await runSmoke("tree/actions", async ({ page }) => {
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
console.log("PASS: selection, clipboard paths, marks, copies, reveal, and single-item menus"); console.log("PASS: selection, clipboard paths, marks, copies, reveal, and single-item menus");
// Delete moves items to the trash (`permanent: false`). Several items still need one confirmation.
await reset(); await reset();
await selectFiles(); await selectFiles();
await page.evaluate(() => { window.__TEST__.answer = "Cancel"; }); await page.evaluate(() => { window.__TEST__.answer = "Cancel"; });
@@ -106,11 +107,43 @@ await runSmoke("tree/actions", async ({ page }) => {
await row("c.md").click({ modifiers: ["Control"] }); await row("c.md").click({ modifiers: ["Control"] });
await action("a.md", "Delete (3)"); await action("a.md", "Delete (3)");
await row("c.md").waitFor({ state: "detached" }); await row("c.md").waitFor({ state: "detached" });
assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["a.md", "b.md", "c.md"]); assert.deepEqual(await calls("workspace_delete"), ["a.md", "b.md", "c.md"].map(rel => ({ rel, permanent: false })));
assert.match(await page.locator(".tree .error").textContent(), /a.md: Access denied/); assert.match(await page.locator(".tree .error").textContent(), /a.md: Access denied/);
// A failed move to the trash offers a permanent delete only through Shift+Delete.
assert.match(await page.locator(".tree .error").textContent(), /press Shift\+Delete/);
assert.deepEqual(await selected(), ["a.md"]); assert.deepEqual(await selected(), ["a.md"]);
console.log("PASS: cancellation, one confirmation per batch, partial failure, and selection after deletion"); console.log("PASS: cancellation, one confirmation per batch, partial failure, and selection after deletion");
// Changed for the move to the trash: one file needs no confirmation. A permanent delete always asks.
await reset();
await action("c.md", "Delete");
await row("c.md").waitFor({ state: "detached" });
assert.deepEqual(await calls("workspace_delete"), [{ rel: "c.md", permanent: false }]);
assert.equal((await calls("plugin:dialog|message")).length, 0);
await page.evaluate(() => { window.__TEST__.answer = "Cancel"; });
await action("b.md", "Delete permanently");
assert.equal((await calls("plugin:dialog|message")).length, 1);
assert.equal((await calls("workspace_delete")).length, 1);
await page.evaluate(() => { window.__TEST__.answer = "Ok"; });
await action("b.md", "Delete permanently");
await row("b.md").waitFor({ state: "detached" });
assert.deepEqual((await calls("workspace_delete")).at(-1), { rel: "b.md", permanent: true });
console.log("PASS: one file moves to the trash without confirmation, and a permanent delete asks first");
await reset();
await row("a.md").click();
await row("a.md").focus();
await page.keyboard.press("Delete");
await row("a.md").waitFor({ state: "detached" });
assert.deepEqual(await calls("workspace_delete"), [{ rel: "a.md", permanent: false }]);
await row("b.md").click();
await row("b.md").focus();
await page.keyboard.press("Shift+Delete");
await row("b.md").waitFor({ state: "detached" });
assert.deepEqual((await calls("workspace_delete")).at(-1), { rel: "b.md", permanent: true });
assert.equal((await calls("plugin:dialog|message")).length, 1);
console.log("PASS: Delete moves the selection to the trash, and Shift+Delete deletes it permanently after confirmation");
await reset(); await reset();
await row("notes").click(); await row("notes").click();
await row("notes/nested").click(); await row("notes/nested").click();