Merge main into feat/scripts-xmp-objects

XMP updates flush their destination folders on Unix. The host records completed writes and refreshes open readers before reporting a folder flush error. XMPFile retains its pending packet for retry.
This commit is contained in:
dotCooCoo committed 2026-11-26 13:45:26 -08:00
commit bb439ce33b
6 files changed
+186 -18

No files matched your search

+12
View File
@@ -1940,6 +1940,8 @@ fn xmp_open(host: &Host, a: &[Data]) -> Result<Data, HostError> {
/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the
/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which
/// fails and leaves the file as it is. Open objects of the file hold the new bytes.
/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an
/// error after the written path is recorded and open readers receive the replacement packet.
fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let path = arg_text(a, 0);
let packet = arg_text(a, 1).into_bytes();
@@ -2052,6 +2054,14 @@ fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
file.dirty = false;
}
}
#[cfg(all(unix, not(target_arch = "wasm32")))]
let r = r.and_then(|()| {
#[cfg(test)]
if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
return Err(std::io::Error::other("directory flush failed"));
}
vectorcraft_format::sync_parent(&target)
});
Ok(done(r.map_err(|_| WRITE_FAILED)))
}
@@ -2686,6 +2696,8 @@ thread_local! {
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: while set, `xmpWrite` fails after its checks and before it writes.
pub(crate) static XMP_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
#[cfg(unix)]
pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it.
#[cfg(unix)]
pub(crate) static XMP_TEMP_MODE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
+39
View File
@@ -601,6 +601,45 @@ fn a_failed_write_keeps_the_packet_for_a_later_close() {
let _ = std::fs::remove_dir_all(base);
}
#[cfg(unix)]
#[test]
fn a_directory_flush_failure_keeps_the_written_packet_and_allows_retry() {
struct Reset;
impl Drop for Reset {
fn drop(&mut self) {
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
}
}
let _reset = Reset;
let base = folder("directory-flush");
let mut session = with_data(&base);
let dir = logged(&mut session, &base, "vc.log(Folder.userData.fsName);");
let path = PathBuf::from(dir[0].as_str().unwrap()).join("packet.xmp");
write(&path, format!("\u{FEFF}{PACKET}").as_bytes());
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
start_framed(
&mut session,
&base,
&format!(
"Folder.userData; var p = {:?}, reader = new File(p); reader.open('r'); reader.read(7);\n\
var kept = new XMPFile(p, XMPConst.FILE_UNKNOWN, XMPConst.OPEN_FOR_UPDATE);\n\
var meta = kept.getXMP(); meta.setProperty(XMPConst.NS_DC, 'format', 'changed'); kept.putXMP(meta);\n\
var out = []; try {{ kept.closeFile(); out.push('closed'); }} catch (e) {{ out.push(e.message, kept.getXMP().getProperty(XMPConst.NS_DC, 'format').value); }}\n\
out.push(reader.tell() === 0, reader.read().indexOf('changed') >= 0); reader.close();\n\
File.saveDialog('pause'); kept.closeFile(); out.push('closed'); vc.log(out);",
path.to_string_lossy()
),
);
let paused = pump_to_picker(&mut session);
crate::script::files::XMP_DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(paused.is_none(), "the run waits before retrying: {paused:?}");
assert!(std::fs::read_to_string(&path).unwrap().contains("<dc:format>changed</dc:format>"), "the replacement already wrote the packet");
assert!(session.script_pick(crate::script::files::PickAnswer::Deny));
let report = pump_to_picker(&mut session).unwrap().unwrap();
assert_eq!(report["log"][0], json!(["Script file could not be written", "changed", true, true, "closed"]));
assert_eq!(report["written"], json!([path.to_string_lossy()]), "the written replacement is reported once");
}
/// An `XMPFile` from an earlier run of a named engine is closed.
#[test]
fn an_xmp_file_from_an_earlier_run_is_closed() {
+121 -14
View File
@@ -1,5 +1,7 @@
//! Safe saving: a file is written to a temporary file beside it, then renamed over it, so a failed
//! or interrupted write never leaves a damaged file behind (the old one stays as it was).
//! [`write_atomic_with`] writes and flushes a temporary file, then renames it over its destination.
//! A failure while writing or flushing the temporary file leaves the original file unchanged.
//! On Unix, saves also flush the destination directory after the complete file is written.
//! An error at that step reports that the file was written.
//! [`write_new_with`] creates a file the same way without ever replacing one.
//!
//! Where a folder refuses the temporary file or the rename (some network shares, a file another
@@ -22,11 +24,29 @@ use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Whether the returned write error refuses this location. Recovery errors must still be shown:
/// their message names copies the user may need, even when their kind is PermissionDenied.
/// Reports whether a write error identifies a read-only location.
/// It returns false for recovery errors and for errors flushing a directory after a completed write, including PermissionDenied.
pub fn read_only_location(error: &io::Error) -> bool {
matches!(error.kind(), io::ErrorKind::ReadOnlyFilesystem | io::ErrorKind::PermissionDenied)
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>())
&& !error.get_ref().is_some_and(|e| e.is::<RecoveryError>() || e.is::<WrittenError>())
}
#[derive(Debug)]
struct WrittenError {
path: PathBuf,
error: io::Error,
}
impl std::fmt::Display for WrittenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "The file was written to {}. Its folder could not be flushed: {}", self.path.display(), self.error)
}
}
impl std::error::Error for WrittenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
/// Marks the existing recovery message without changing its text or the returned error kind.
@@ -46,11 +66,10 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
write_atomic_with(path, |f| f.write_all(bytes))
}
/// Write `path` atomically with `fill`, which writes the content into the temporary file. When
/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the
/// temporary file is removed and `path` is left untouched. When the
/// folder refuses the temporary file or the rename, the content is copied into `path` instead (see
/// the module docs).
/// This function writes `path` atomically with `fill`, which writes content into a temporary file.
/// A failure from `fill`, flushing that file, or cancellation ([`vectorcraft_doc::cancel`]) leaves `path` unchanged.
/// Cleanup attempts to remove the temporary file and ignores removal errors.
/// When the folder refuses the temporary file or the rename, the content is copied into `path` instead (see the module docs).
pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
// Replacing a file: its staging copy starts owner-only, so a private document is never readable
// beside the target before `keep_permissions` has run (#1712). A new file keeps the default mode.
@@ -97,7 +116,7 @@ fn write_atomic_stepping(
// Best effort: a volume without Unix permissions (SMB, FAT) refuses them, and has none
// to keep.
let _ = keep_permissions(&target, &tmp);
let Err(e) = rename(&tmp, &target) else { return Ok(()) };
let Err(e) = rename(&tmp, &target) else { return sync_written_parent(&target) };
e
}
};
@@ -137,7 +156,7 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
if let Some(old) = old {
let _ = std::fs::remove_file(old);
}
Ok(())
sync_written_parent(target)
}
(Err(e), Some(old)) => Err(io::Error::new(
e.kind(),
@@ -168,7 +187,7 @@ fn create_private(path: &Path) -> io::Result<File> {
/// (`std::fs::hard_link`, which fails with `AlreadyExists` when the name is taken, also when it was
/// taken meanwhile). The file appears whole or not at all. Where hard links fail for another
/// reason, `path` is created with `create_new` and the content copied in; a failed copy removes
/// it. The temporary file is always removed.
/// it. Cleanup attempts to remove the temporary file and ignores removal errors.
pub fn write_new_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> {
write_new_linking(path, fill, |tmp, path| std::fs::hard_link(tmp, path))
}
@@ -189,7 +208,31 @@ fn write_new_linking(
});
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&tmp);
placed
placed.and_then(|()| sync_written_parent(path))
}
fn sync_written_parent(path: &Path) -> io::Result<()> {
#[cfg(unix)]
{
sync_parent(path).map_err(|error| io::Error::new(error.kind(), WrittenError { path: path.to_path_buf(), error }))
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
/// This function flushes the directory containing `path` with `fsync`.
/// It returns errors from opening or flushing the directory.
#[cfg(unix)]
pub fn sync_parent(path: &Path) -> io::Result<()> {
#[cfg(test)]
if DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, "directory flush failed"));
}
let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
rustix::fs::fsync(&File::open(parent)?).map_err(io::Error::from)
}
/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has
@@ -272,6 +315,8 @@ const ENOTTY: i32 = 25;
#[cfg(test)]
thread_local! {
#[cfg(unix)]
static DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: every full flush on this thread fails as on an SMB share mounted by macOS.
static REFUSE_FULL_SYNC: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: the plain `fsync` fallback fails too, with this OS error.
@@ -474,6 +519,68 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_reports_the_completed_replacement() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-replace");
let path = directory.join("doc.vectorcraft");
std::fs::write(&path, b"old").unwrap();
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let result = write_atomic(&path, b"new");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(result.is_err(), "a failed directory flush was reported as success");
let error = result.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains("The file was written to"), "{error}");
assert!(!read_only_location(&error), "the file was already replaced: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
write_atomic(&path, b"retried").unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"retried");
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_preserves_the_completed_new_file() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-create");
let path = directory.join("doc.vectorcraft");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let result = write_new_with(&path, |file| file.write_all(b"created"));
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
assert!(result.is_err(), "a failed directory flush was reported as success");
let error = result.unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
assert!(error.to_string().contains("The file was written to"), "{error}");
assert!(!read_only_location(&error), "the file was already created: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"created");
assert!(leftovers(&directory, "doc.vectorcraft").is_empty());
let result = write_new_with(&path, |file| file.write_all(b"replacement"));
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::AlreadyExists);
assert_eq!(std::fs::read(&path).unwrap(), b"created");
}
#[cfg(unix)]
#[test]
fn a_directory_sync_failure_is_reported_after_copy_fallbacks() {
let directory = vectorcraft_testkit::TempDir::new("atomic-directory-sync-copy");
let path = directory.join("doc.vectorcraft");
std::fs::write(&path, b"old").unwrap();
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let replaced = write_atomic_stepping(&path, |file| file.write_all(b"new"), create_new, |_, _| denied());
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
let error = replaced.unwrap_err();
assert!(!read_only_location(&error), "the file was already replaced: {error}");
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let new_path = directory.join("new.vectorcraft");
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(true));
let created = write_new_linking(&new_path, |file| file.write_all(b"created"), |_, _| denied());
DIRECTORY_SYNC_FAILS.with(|flag| flag.set(false));
let error = created.unwrap_err();
assert!(!read_only_location(&error), "the file was already created: {error}");
assert_eq!(std::fs::read(&new_path).unwrap(), b"created");
assert_eq!(std::fs::read_dir(&*directory).unwrap().count(), 2);
}
/// A save to an SMB share (#1620): macOS refuses the full flush there with `ENOTSUP`, so the
/// file is flushed with a plain `fsync` and saved. When that fails too the save fails as before,
/// the old file stays and no temporary file is left. Elsewhere `sync_all` is already a plain
+2
View File
@@ -55,6 +55,8 @@ use serde::{Deserializer, Serialize};
use vectorcraft_brush::stored_art::StoredArt;
use vectorcraft_doc::{Document, ImageBlob};
#[cfg(all(unix, not(target_arch = "wasm32")))]
pub use atomic::sync_parent;
#[cfg(not(target_arch = "wasm32"))]
pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with};
use craft_gzip::Gz;
+9 -3
View File
@@ -1393,9 +1393,12 @@ Each coordinate goes to the nearest step of its stored binary value, and a value
zero (`0.125` at 2 places is `0.13`); `1.005` is stored as slightly less than that and is written as `1.0`. Each anchor is rounded on
its own, so a closed path stays closed and a shape smaller than one step keeps its anchors on one point. Opening the
file and saving it again does not bring back the dropped digits. The embedded preview and the PDF that `pdfCompatible: true` adds show the rounded paths. Without `precision` a save writes the coordinates exactly, and Save does not remember it. A `.ai` file ignores
`precision`. A save writes
a temporary file and renames it over the old one, so a failed save never damages the file; only the images the
document uses are written, and document keys written by a newer version are kept.
`precision`. A save first writes and flushes a temporary file, then renames it over the destination or copies the complete
content into the destination. The copy path keeps a flushed copy of any existing content before overwriting it.
A failure during that copy reports the locations of the new content and any saved original.
Only the images the document uses are written, and document keys written by a newer version are kept.
On Unix, a save flushes the destination directory after writing or replacing the file. If that flush fails,
the save reports an error stating that the file was written.
An uncompressed file is indented JSON when the document has at most 2,000 layers and objects and the indented
document, as the chosen version writes it, is at most 1 MiB; otherwise the file is compact JSON.
@@ -3421,6 +3424,9 @@ rules for these objects:
After a successful update, an open `File` reader with a UTF-8 byte order mark or UTF-16 encoding
restarts in UTF-8 at the beginning of the replacement packet. A UTF-8 reader without a byte order mark keeps its position,
limited to the replacement packet's length.
- On Unix, `closeFile()` flushes the destination folder after writing the packet. If that flush fails,
it throws `Script file could not be written`, and the file already contains the replacement packet.
Open readers use that packet, `written` names the file, and the `XMPFile` keeps its pending packet for retry.
- Registered namespace storage and expanded XML values count toward the script's heap limit.
`canPutXMP` checks string packets without retaining their expanded XML values.
- A packet over 8 MiB, one that is not well-formed XML, one with a document type declaration or an undefined entity,
+3 -1
View File
@@ -1,5 +1,7 @@
# Parity with Adobe Illustrator
Native saves on Unix flush the destination directory after writing or replacing a file. If the directory cannot be flushed, the save returns an error stating that the file was written.
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (Essentials readiness row: Shape Builder item names its remaining depth, #937's fix unconfirmed on the reporter's file, #8314; scores and estimates unchanged; previously: G12: History row context menus use shared Craft controls, snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: G12: Document Info Selection Only counts the selection, and with no artwork selected it shows (No artwork selected) and artboards the Artboard tool has selected still show; scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: M14/G12: Appearance panel: right-click item context menus for rows (Duplicate, Delete, Hide/Show, Edit Effect, Clear Appearance, Reduce to Basic Appearance) with selection handling, #8809; previously: Text styles panel: right-click item context menus for Character Styles and Paragraph Styles with Options, Duplicate, Delete, Redefine, Clear Overrides; scores and estimates unchanged; previously: G12: Actions panel item context menus for action sets (New Action…, New Set…, Duplicate Set, Delete Set, Set Options…) and actions (Play, Record, Duplicate, Delete, Action Options…, Batch…) with selection handling; clicking Duplicate on an action duplicates that action; headless tests in `crates/ui-egui/src/panels/actions.rs`; scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and esLine truncated
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
@@ -83,7 +85,7 @@ The shared assessment status line and revision history are current upstream; thi
Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard option for ordinary resizing. Fit to Artwork Bounds and Fit to Selected Art explicitly leave artwork stationary. Dialog regression coverage checks preset/orientation/typed-size intent with scaling on and off, draft cancellation, one-step Undo/Redo, and fitting while Move Artwork and Scale Artwork are enabled. This is a narrow follow-up to #3277; no parity score or estimate is reassessed.
`XMPFile` updates restart open `File` readers with a UTF-8 byte order mark or UTF-16 encoding at the beginning of the new UTF-8 packet. Unmarked UTF-8 readers keep their position, limited to the new packet's length. Native file state is separate from script properties, and a successful close or the next script file run releases its packet buffers. Registered namespaces and expanded XML values count toward the script's heap limit. String-packet validation does not retain expanded XML values. A failed `Realm::define_external_object` call can be retried; a call after a successful installation returns an internal error and preserves registered namespaces.
`XMPFile` updates restart open `File` readers with a UTF-8 byte order mark or UTF-16 encoding at the beginning of the new UTF-8 packet. Unmarked UTF-8 readers keep their position, limited to the new packet's length. Native file state is separate from script properties, and a successful close or the next script file run releases its packet buffers. Registered namespaces and expanded XML values count toward the script's heap limit. String-packet validation does not retain expanded XML values. On Unix, a folder flush failure after writing reports the written replacement and refreshes open readers while keeping the pending packet for retry. A failed `Realm::define_external_object` call can be retried; a call after a successful installation returns an internal error and preserves registered namespaces.
### Feature revisions