New Document: Manage Profiles reports a linked profile as unusable

file.newProfiles and Manage Profiles checked a profile's file with
is_file, which follows a link. A profile file that was a link to a
document was listed as customized with Edit on, while file.new refuses
to read a link and gives the new document the defaults. A link that
led nowhere, or a folder, was listed as not customized, so Reset was
off and could not remove it, and Edit on a link that led nowhere wrote
the shipped profile where the link pointed.

The profile's file is now looked at without following a link:

- file.newProfiles lists a link or a folder as customized, with
  unusable: "not a plain file".
- Manage Profiles dims that profile's name, says why in its tooltip,
  and turns Edit off. Reset stays on for a link and removes the link,
  not the file it leads to. Reset is off for a folder, and
  file.newProfiles.reset gives an error instead of deleting a folder.
- file.newProfiles.edit gives an error for a link or a folder, and
  creates a missing profile file without following a link put there.

Docs: docs/mcp.md (New Document profiles) and the command help.
This commit is contained in:
dotCooCoo committed 2026-11-30 16:07:05 -08:00
1 parent 639ce5004e
commit 1ce1d2ccf2
5 files changed
+177 -28

No files matched your search

+68 -14
View File
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Document Profiles",
[],
None,
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
"{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), unusable?: why file.new does not read it (a link or a folder: new documents get the defaults, and file.newProfiles.edit refuses it), path?; customized, unusable and path left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}",
always,
list_profiles
),
@@ -63,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Profile",
[],
None,
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
"{name: a built-in category of file.newPresets (not Recent or Saved)} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first; an error when its file is a link or a folder, which file.new does not read either; under automation roots it needs write and read access to the file, and an error names the file by its file name outside the read roots → document.open's result",
always,
edit_profile
),
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reset Profile",
[],
None,
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
"{name: a built-in category of file.newPresets (not Recent or Saved)} delete the category's profile file, so the shipped profile (today's defaults) applies again (a link is removed, not the file it leads to; a folder is not deleted, an error); an open copy of it stays open; under automation roots it needs write access to the file, and an error names the file by its file name outside the read roots → {name, reset: whether a file was deleted}",
always,
reset_profile
),
@@ -996,6 +996,44 @@ pub fn profile_names() -> impl Iterator<Item = &'static str> {
CATEGORIES.iter().map(|c| c.0)
}
/// What is at a New Document profile's file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProfileFile {
/// Nothing: the shipped profile applies.
None,
/// A plain file, which `file.new` reads.
Plain,
/// A link or another entry that is not a plain file or a folder: `file.new` does not read it (the
/// new document has the defaults), `file.newProfiles.edit` does not open it and
/// `file.newProfiles.reset` removes it (a link, not what it leads to).
NotPlain,
/// A folder, which `file.new` does not read and `file.newProfiles.edit` does not open either.
/// `file.newProfiles.reset` does not delete a folder.
Folder,
}
impl ProfileFile {
/// Whether the category has a file in place of the shipped profile.
pub fn customized(self) -> bool {
self != Self::None
}
/// Whether `file.newProfiles.reset` removes what is there.
pub fn resettable(self) -> bool {
matches!(self, Self::Plain | Self::NotPlain)
}
}
/// What is at `path`, looked at without following a link.
fn profile_file(path: &std::path::Path) -> ProfileFile {
match std::fs::symlink_metadata(path) {
Ok(m) if crate::store::is_plain(&m) => ProfileFile::Plain,
Ok(m) if m.is_dir() && !crate::store::is_link_entry(&m) => ProfileFile::Folder,
Ok(_) => ProfileFile::NotPlain,
Err(_) => ProfileFile::None,
}
}
/// The profile `v` names (a built-in category, any case).
fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> {
let name = v.as_str().map(str::trim).unwrap_or_default();
@@ -1022,9 +1060,9 @@ impl Session {
Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION)))
}
/// Whether profile `name` has a file, which `file.newProfiles.reset` deletes.
pub fn new_doc_profile_customized(&self, name: &str) -> bool {
self.profile_path(name).is_some_and(|p| p.is_file())
/// What is at profile `name`'s file, looked at without following a link.
pub fn new_doc_profile_file(&self, name: &str) -> ProfileFile {
self.profile_path(name).map_or(ProfileFile::None, |p| profile_file(&p))
}
/// Profile `name`'s document, its file's path and a warning for each color profile the file
@@ -1045,7 +1083,7 @@ impl Session {
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
// A link is refused: the script's gate does not check where it leads.
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
Ok(m) if !crate::store::is_plain(&m) => return Err(crate::store::NOT_PLAIN.to_string()),
_ => {}
}
crate::file_access::check_read(&file).map_err(denied)?;
@@ -1088,7 +1126,11 @@ fn list_profiles(s: &mut Session, _: &Value) -> Result<Value> {
// A request that may not read the folder learns nothing of its files.
Some(path) => {
if let Some(p) = shown(&path) {
v["customized"] = json!(path.is_file());
let file = profile_file(&path);
v["customized"] = json!(file.customized());
if matches!(file, ProfileFile::NotPlain | ProfileFile::Folder) {
v["unusable"] = json!(crate::store::NOT_PLAIN);
}
v["path"] = json!(p);
}
}
@@ -1121,12 +1163,19 @@ fn edit_profile(s: &mut Session, p: &Value) -> Result<Value> {
let path = file.to_string_lossy().to_string();
// document.open reads it next: a profile it can't open is not written either.
crate::file_access::check_read(&path).map_err(|e| profile_error(e, &path))?;
if !file.exists() {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::write(&file, bytes))
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
match profile_file(&file) {
ProfileFile::Plain => {}
// file.new does not read a link or a folder, so it is not opened as the profile either.
ProfileFile::NotPlain | ProfileFile::Folder => return Err(profile_error(format!("{path}: {}", crate::store::NOT_PLAIN), &path)),
// Made new, so a dangling link put there since is not written through.
ProfileFile::None => {
let bytes = vectorcraft_format::save(&shipped_profile(s, name), false);
file.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.and_then(|()| std::fs::OpenOptions::new().write(true).create_new(true).open(&file))
.and_then(|mut f| std::io::Write::write_all(&mut f, &bytes))
.map_err(|e| profile_error(format!("{path}: {e}"), &path))?;
}
}
s.execute("document.open", &json!({ "path": path }))
}
@@ -1136,9 +1185,14 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result<Value> {
let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?;
let file = writable_profile(s, name, C)?;
let path = file.to_string_lossy().to_string();
if profile_file(&file) == ProfileFile::Folder {
return Err(profile_error(format!("{path}: a folder, which Reset does not delete"), &path));
}
let reset = match std::fs::remove_file(&file) {
Ok(()) => true,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
// On Windows a link to a folder, or a junction, is removed as a folder; what it leads to stays.
Err(_) if std::fs::symlink_metadata(&file).is_ok_and(|m| crate::store::is_link_entry(&m)) && std::fs::remove_dir(&file).is_ok() => true,
Err(e) => return Err(profile_error(format!("{path}: {e}"), &path)),
};
Ok(json!({ "name": name, "reset": reset }))
+12
View File
@@ -222,6 +222,18 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
/// What [`read_capped_plain`] tells a path that is not a plain file.
pub(crate) const NOT_PLAIN: &str = "not a plain file";
/// Whether `m`, read without following a link, is a plain file: not a link, a folder or (on Windows)
/// a junction or other reparse point.
pub(crate) fn is_plain(m: &std::fs::Metadata) -> bool {
m.file_type().is_file() && !reparse_point(m)
}
/// Whether `m`, read without following a link, is a link (on Windows also a junction or other
/// reparse point).
pub(crate) fn is_link_entry(m: &std::fs::Metadata) -> bool {
m.file_type().is_symlink() || reparse_point(m)
}
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
+69
View File
@@ -1181,6 +1181,75 @@ fn a_profile_that_is_a_link_is_not_followed() {
let _ = std::fs::remove_dir_all(&dir);
}
/// The listing entry of profile `name`.
fn listed_profile(s: &mut Session, name: &str) -> Value {
let listed = s.execute("file.newProfiles", &json!({})).unwrap();
listed["profiles"].as_array().unwrap().iter().find(|p| p["name"] == name).cloned().unwrap()
}
#[cfg(unix)]
#[test]
fn a_linked_profile_is_listed_as_unusable_and_reset_removes_the_link() {
use crate::cmd::newdoc::ProfileFile;
let (mut s, dir) = with_profiles("linked-listing");
s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap();
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::Plain);
assert!(listed_profile(&mut s, "Print").get("unusable").is_none());
let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-linked-{}.vectorcraft", std::process::id()));
std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap();
std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap();
// file.new does not read it, so the listing says so, and Edit does not open it.
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::NotPlain);
assert!(ProfileFile::NotPlain.resettable());
let p = listed_profile(&mut s, "Print");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
let e = s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap_err().to_string();
assert!(e.contains("not a plain file"), "{e}");
// Reset removes the link and leaves the file it led to.
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap()["reset"], true);
assert!(std::fs::symlink_metadata(dir.join("Print.vectorcraft")).is_err() && outside.is_file());
assert_eq!(s.new_doc_profile_file("Print"), ProfileFile::None);
let _ = std::fs::remove_file(&outside);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn a_profile_link_to_nothing_is_listed_and_edit_does_not_write_through_it() {
let (mut s, dir) = with_profiles("dangling");
std::fs::create_dir_all(&dir).unwrap();
let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-dangling-{}.vectorcraft", std::process::id()));
let _ = std::fs::remove_file(&outside);
std::os::unix::fs::symlink(&outside, dir.join("Web.vectorcraft")).unwrap();
let p = listed_profile(&mut s, "Web");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
assert!(s.execute("file.newProfiles.edit", &json!({"name": "Web"})).is_err());
assert!(!outside.exists(), "Edit wrote the shipped profile where the link leads");
assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Web"})).unwrap()["reset"], true);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_folder_in_a_profiles_place_is_listed_as_unusable() {
let (mut s, dir) = with_profiles("folder");
std::fs::create_dir_all(dir.join("Mobile.vectorcraft")).unwrap();
let p = listed_profile(&mut s, "Mobile");
assert_eq!((&p["customized"], &p["unusable"]), (&json!(true), &json!("not a plain file")), "{p}");
let e = s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap_err().to_string();
assert!(e.contains("not a plain file"), "{e}");
let r = s.execute("file.new", &json!({"profile": "Mobile"})).unwrap();
assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}");
// Reset does not delete a folder, and Manage Profiles turns it off.
let file = s.new_doc_profile_file("Mobile");
assert_eq!(file, crate::cmd::newdoc::ProfileFile::Folder);
assert!(file.customized() && !file.resettable());
let e = s.execute("file.newProfiles.reset", &json!({"name": "Mobile"})).unwrap_err().to_string();
assert!(e.contains("a folder"), "{e}");
assert!(dir.join("Mobile.vectorcraft").is_dir());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn profile_names_are_checked_and_editing_needs_the_folder() {
let mut s = Session::new();
+20 -10
View File
@@ -18,7 +18,7 @@ use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Background, ColorMode, Unit};
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, RASTER_PPI};
use vectorcraft_engine::cmd::newdoc::{self, ArtboardLayout, DocSettings, MAX_ARTBOARDS, PreviewMode, ProfileFile, RASTER_PPI};
use craft::behavior::{ColumnWidth, IconId};
use craft::ui::buttons::Button;
@@ -155,8 +155,8 @@ impl<'de> Deserialize<'de> for VcNewDocument {
pub(crate) struct Setup {
/// The name of the next untitled document.
untitled: String,
/// The New Document profiles, each with whether it was edited.
profiles: Vec<(&'static str, bool)>,
/// The New Document profiles, each with what is at its file.
profiles: Vec<(&'static str, ProfileFile)>,
/// Whether profiles can be edited (the web build and runs without preferences have no folder).
has_profile_folder: bool,
/// Numbers Without Units Are Points.
@@ -168,7 +168,7 @@ impl Setup {
fn of(app: &VectorcraftApp) -> Self {
Self {
untitled: app.session.peek_untitled().to_string(),
profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_customized(name))).collect(),
profiles: newdoc::profile_names().map(|name| (name, app.session.new_doc_profile_file(name))).collect(),
has_profile_folder: app.session.new_doc_profile_dir().is_some(),
bare_points: app.session.prefs.numbers_without_units_are_points,
}
@@ -618,12 +618,22 @@ fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>
Text::new(text(tl!("NEW DOCUMENT PROFILES"))).role(TypeRole::SectionCaption).shade(Shade::Muted).show(ui);
// The names in one column and the Edit and Reset buttons in columns of their own, so the buttons line up.
Grid::new(&PROFILE_COLUMNS).gap(Gap::Item).show(ui, |ui, _| {
for (name, customized) in &setup.profiles {
Text::new(text(tl!(name))).id_salt(("profile", name)).show(ui);
if clicked(&Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder).show(ui)) {
for (name, file) in &setup.profiles {
// A link or a folder in the profile's place is not read: its name is dimmed and says why, Edit
// is off, and Reset removes a link but not a folder.
let unusable = matches!(file, ProfileFile::NotPlain | ProfileFile::Folder);
let mut shown = Text::new(text(tl!(name))).id_salt(("profile", name));
if unusable {
let why = tl!("The profile's file is a link or a folder, so new documents get the default settings");
shown = shown.shade(Shade::Muted).tooltip(text(why));
}
shown.show(ui);
let edit = Button::new(text(tl!("Edit"))).id_salt(("edit", name)).enabled(setup.has_profile_folder && !unusable);
if clicked(&edit.show(ui)) {
*action = Some(format!("{EDIT_PROFILE}:{name}"));
}
if clicked(&Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(*customized).show(ui)) {
let reset = Button::new(text(tl!("Reset"))).id_salt(("reset", name)).enabled(file.resettable());
if clicked(&reset.show(ui)) {
*action = Some(format!("{RESET_PROFILE}:{name}"));
}
}
@@ -1413,11 +1423,11 @@ mod tests {
let setup = Setup::of(&app);
assert!(setup.has_profile_folder);
assert_eq!(setup.profiles.len(), newdoc::profile_names().count());
assert!(setup.profiles.iter().all(|(_, customized)| !customized));
assert!(setup.profiles.iter().all(|(_, file)| *file == ProfileFile::None));
assert!(profile_action(&mut app, "profile.edit:Print"), "Edit closes the dialog");
assert_eq!(app.session.active().unwrap().doc.title, "Print");
assert!(dir.join("Print.vectorcraft").is_file());
assert!(Setup::of(&app).profiles.iter().any(|(name, customized)| *name == "Print" && *customized));
assert!(Setup::of(&app).profiles.iter().any(|(name, file)| *name == "Print" && *file == ProfileFile::Plain));
assert!(!profile_action(&mut app, "profile.reset:Print"), "Reset leaves the dialog open");
assert!(!dir.join("Print.vectorcraft").exists());
let _ = std::fs::remove_dir_all(&dir);
+8 -4
View File
@@ -10781,13 +10781,17 @@ preferences (VectorCraft's own place and form). A category without a file has th
defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts
with the defaults.
- `file.newProfiles` lists `{profiles: [{name, customized?, path?}], folder?}`. `customized` is true when the category
has a file. A request whose read roots leave out the folder gets neither `customized` nor `path`.
- `file.newProfiles` lists `{profiles: [{name, customized?, unusable?, path?}], folder?}`. `customized` is true when the
category has a file. `unusable` is `"not a plain file"` when that file is a link or a folder: `file.new` does not
read it, so new documents of the category get the defaults. Manage Profiles dims its name and turns Edit off; Reset
stays on for a link and is off for a folder. A request whose read roots leave out the folder gets none of
`customized`, `unusable` and `path`.
- `file.newProfiles.edit {name}` opens the profile as a document and returns `document.open`'s result. A category
without a file gets the shipped profile written first. File › Save keeps the changes, and the next `file.new` reads
them.
them. A profile whose file is a link or a folder gives an error instead.
- `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns
`{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open.
`{name, reset}`. `reset` is false when there was no file. A link is removed and the file it leads to is kept; a
folder is not deleted, and the command gives an error. A copy of the profile that is open stays open.
- `file.newProfiles.applyDefaults {name}` (Use Profile Defaults, VectorCraft's own command) gives the active document
the default fill and stroke and the default font of another profile. The document's Default Graphic Style takes the
fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] takes the profile's