From 10a1be94f1800a62b030823afaefa03275cc0c81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 15:49:44 -0800 Subject: [PATCH 1/2] New Document profiles: Use Profile Defaults switches the default fill, stroke and font file.newProfiles.applyDefaults {name} gives the active document the Default Graphic Style and [Normal Character Style] of another category's New Document profile, as one undo step and none when nothing changes. The swatches, patterns, symbols and brushes the profile's style paints with come along, its colors are converted to the document's color mode, and a composite font the profile's default font names replaces the document's of that name. Objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides, as the Redefine commands do. New art and new type then start with the profile's look. This is VectorCraft's own command. - Document Color Mode now converts the fill and stroke of character and paragraph styles as well, so a document or profile switched between RGB and CMYK no longer keeps style colors in the old mode. - Art pasted again with an SVG filter that was renamed on the first paste takes the same name, instead of a new name on each paste. Refs #8350 --- crates/engine/src/cmd/clipboard/resources.rs | 46 +++++- crates/engine/src/cmd/colormgmt.rs | 14 +- crates/engine/src/cmd/compositefonts.rs | 55 ++++--- crates/engine/src/cmd/newdoc.rs | 108 ++++++++++++- crates/engine/src/cmd/paint.rs | 2 +- crates/engine/src/cmd/style.rs | 68 ++++---- crates/engine/src/cmd/textstyles.rs | 30 +++- crates/engine/src/tests/newdoc.rs | 157 +++++++++++++++++++ crates/engine/src/tests/svgfilter.rs | 18 +++ crates/engine/src/tests/swatches.rs | 16 ++ docs/mcp.md | 14 ++ docs/target-app-parity.md | 1 + 12 files changed, 465 insertions(+), 64 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index aa3cf36cba..7c1ac4b51e 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1601,7 +1601,8 @@ impl Clipboard { /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a - /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone. When that name would + /// name no filter or effect of the document gives, so editing or deleting the document's filter leaves it alone; an + /// effect of the document that draws the same definition under a name no filter has gives that name. When that name would /// make the filter too long to draw, the free name is a shorter start of its name ("Shif"), else /// a free letter, digit or other printable ASCII character; the filter's id is always its name. An error when no free name fits. fn filter_links(&self, d: &Document, same_doc: bool) -> Result> { @@ -1627,6 +1628,8 @@ impl Clipboard { } let mut taken: BTreeSet = d.svg_filters.iter().map(|f| f.name.clone()).chain(found.iter().map(|(n, _)| n.clone())).collect(); let mut effects_read = false; + // The filter effects of the document, by name and definition. + let mut held_effects = BTreeSet::new(); let mut links = BTreeMap::new(); for (name, xml) in found { let Some(held) = d.svg_filters.iter().find(|f| f.name == name).filter(|f| f.xml != xml.trim()) else { continue }; @@ -1640,14 +1643,28 @@ impl Clipboard { effects_read = true; for root in d.art_roots() { node_filter_names(root, &mut taken); + node_filters(root, &mut held_effects); } for a in vectorcraft_brush::library(d).iter().flat_map(Brush::art) { node_filter_names(a, &mut taken); + node_filters(a, &mut held_effects); } for g in &d.graphic_styles { appearance_filter_names(&g.appearance, &mut taken); + appearance_filters(&g.appearance, &mut held_effects); } } + // An effect of the document that already draws this filter under a name no filter + // of the document has (one pasted or loaded before) gives its name, so pasting or + // loading the same filter again adds no other name. + let earlier = held_effects.iter().find(|(n, x)| { + !d.svg_filters.iter().any(|f| &f.name == n) + && vectorcraft_render::effects::svg_filter::with_id(&xml, n).is_some_and(|drawn| drawn == *x) + }); + if let Some((n, x)) = earlier { + links.insert((name, xml), (n.clone(), x.clone())); + continue; + } // Free names made from the starts of the name, longest first, then free letters and // digits, then other single printable ASCII characters: the first under which the // filter still draws. @@ -1857,6 +1874,33 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// Add to `d` the swatches, patterns, symbols and brushes (and what their art uses) that the +/// appearance `look` of `src` and the character style attributes `attrs` of `src` paint with, as +/// [`import_text_styles`] adds those of loaded styles, and give back `look` and `attrs` relinked to +/// them (a resource `d` has under the same name and with the same contents is used; another is +/// added under a free name; a global or spot color whose name `d` gives another color is `d`'s; +/// an SVG filter whose name `d` gives another filter is renamed). +pub(crate) fn import_looks( + src: &Document, + d: &mut Document, + look: &Appearance, + attrs: &Map, +) -> Result<(Appearance, Map)> { + let library = OnceCell::new(); + let defs = Defs::of(src, &library); + let mut used = Used::default(); + used.follow(&defs, vec![Source::Appearance(look), Source::Attrs(attrs)]); + // The look goes on an empty path, so that its SVG filters are renamed where `d` gives their + // names other filters, as a pasted object's are. + let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone()); + let clip = Clipboard::with_used(src, &used, &library, vec![carrier]); + let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + let (mut look, mut attrs) = (look.clone(), attrs.clone()); + out.relink.appearance(&mut look); + out.relink.attrs(&mut attrs); + Ok((look, attrs)) +} + /// The resources graph designs `names` of `src` use, through the definitions they lead to. fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { let mut used = Used::default(); diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 5344159583..1ed09da2ee 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -593,10 +593,11 @@ fn mode_color(col: &Color, link: proof::Link, bases: &BTreeMap, c /// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, /// effect colors and the series paints and label styles that graphs keep included), symbols, /// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), -/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and -/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art -/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern -/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color), +/// character and paragraph styles (their fill and stroke) and swatches through the color settings +/// (`intent`, default: theirs) → how many colors of the art (opacity masks, effect colors and +/// graphs' paints included), symbols, graph designs and pattern tiles changed; the colors of +/// graphic styles, brushes and text styles convert without being counted. Gray /// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any /// other and separate through the CMYK profile, unless `grays` puts them on the black plate /// ([`mode_converter`]). Lab colors @@ -608,7 +609,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - convert_colors(d, &mode_converter(mode, intent, grays)) + let conv = mode_converter(mode, intent, grays); + let changed = convert_colors(d, &conv); + convert_style_colors(d, &conv); + changed } /// Every color of `d` that [`set_color_mode`] converts, converted with `conv` → how many colors of diff --git a/crates/engine/src/cmd/compositefonts.rs b/crates/engine/src/cmd/compositefonts.rs index 1815e33349..b9f304ddf4 100644 --- a/crates/engine/src/cmd/compositefonts.rs +++ b/crates/engine/src/cmd/compositefonts.rs @@ -204,7 +204,7 @@ fn parse_set(v: &Value, font: &str, kanji: &CompositePart, c: &str) -> Result Result<()> { +pub(crate) fn check_set(fonts: &[CompositeFont], c: &str) -> Result<()> { if fonts.len() > COMPOSITE_FONTS_MAX { return Err(bad(c, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts"))); } @@ -237,31 +237,53 @@ fn replace(s: &mut Session, label: &str, after: Vec) -> Result<() if before == after { return Ok(()); } + let changed = register(s, &before, &after); + let r = s.edit(label, |d, _| set_fonts(d, &after, &changed)); + sync(s); + r +} + +/// Before an edit makes `after` the active document's composite fonts (it has `before`), register +/// them in the font database and forget the ones taken out → the lowercased names of the fonts that +/// change, for [`set_fonts`]. Run [`sync`] after the edit, whether it was made or not. +pub(crate) fn register(s: &mut Session, before: &[CompositeFont], after: &[CompositeFont]) -> Vec { let changed: Vec = before.iter().filter(|b| !after.contains(b)).chain(after.iter().filter(|a| !before.contains(a))).map(|f| f.name.to_lowercase()).collect(); // A refused or panicked edit leaves the document without the new fonts: `sync` forgets a name // listed here that the document doesn't define. s.composite_names.extend(after.iter().map(|f| f.name.to_lowercase())); let db = FontDb::global(); - for f in &before { + for f in before { if !after.iter().any(|a| CompositeFont::same_name(&a.name, &f.name)) { db.remove_composite_font(&f.name); } } - for f in &after { + for f in after { db.set_composite_font(f); } - let r = s.edit(label, |d, _| { - *d.composite_fonts = after.clone(); - each_text_mut(d, &mut |t| { - if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { - refresh_bounds(t); - } - Ok(()) - }) - }); - sync(s); - r + changed +} + +/// Make `after` the composite fonts of `d`, and measure the type set in a font of `changed` again. +pub(crate) fn set_fonts(d: &mut vectorcraft_doc::Document, after: &[CompositeFont], changed: &[String]) -> Result<()> { + *d.composite_fonts = after.to_vec(); + each_text_mut(d, &mut |t| { + if t.runs.iter().any(|r| changed.contains(&r.style.font_family.to_lowercase())) { + refresh_bounds(t); + } + Ok(()) + }) +} + +/// `fonts` with `f` in place of the composite font of its name, or added, as Import Composite Fonts +/// adds a font. +pub(crate) fn with_font(fonts: &[CompositeFont], f: &CompositeFont) -> Vec { + let mut after = fonts.to_vec(); + match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { + Some(a) => *a = f.clone(), + None => after.push(f.clone()), + } + after } fn set(s: &mut Session, p: &Value) -> Result { @@ -377,10 +399,7 @@ fn import(s: &mut Session, p: &Value) -> Result { if apply { let mut after = s.doc()?.doc.composite_fonts.to_vec(); for f in &fonts { - match after.iter_mut().find(|a| CompositeFont::same_name(&a.name, &f.name)) { - Some(a) => *a = f.clone(), - None => after.push(f.clone()), - } + after = with_font(&after, f); } check_set(&after, C)?; replace(s, "Import Composite Fonts", after)?; diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 8272f7d8cb..63c073f02c 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -15,10 +15,10 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; pub fn specs() -> Vec { vec![ @@ -76,6 +76,15 @@ pub fn specs() -> Vec { always, reset_profile ), + cmd!( + "file.newProfiles.applyDefaults", + "Use Profile Defaults", + [], + None, + "{name: a category of file.newPresets} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when the document already has both). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}", + has_doc, + apply_defaults + ), ] } @@ -1113,3 +1122,98 @@ fn reset_profile(s: &mut Session, p: &Value) -> Result { }; Ok(json!({ "name": name, "reset": reset })) } + +/// `file.newProfiles.applyDefaults`: the active document takes the Default Graphic Style and +/// [Normal Character Style] of profile `name`, and new art is reset to them. +fn apply_defaults(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.applyDefaults"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let mode = s.doc()?.doc.color_mode; + let (mut src, warnings) = match s.read_profile(name) { + Ok(Some(p)) => (p.doc, p.warnings), + // The shipped profile: the defaults of a new document in this color mode. + Ok(None) => (Document::new_with_mode(1.0, 1.0, mode), vec![]), + Err(e) => return Err(bad(C, format!("the {name} profile can't be read: {e}"))), + }; + if src.color_mode != mode { + super::colormgmt::set_color_mode(&mut src, mode, true, None, super::colormgmt::Grays::Profile); + } + // A profile without a Default Graphic Style gives the shipped one, as a new document from it + // starts with the shipped fill and stroke. + let look = match src.graphic_style(DEFAULT_GRAPHIC_STYLE) { + Some(g) => g.clone(), + None => Document::new_with_mode(1.0, 1.0, mode).graphic_style(DEFAULT_GRAPHIC_STYLE).cloned().unwrap_or_else(shipped_default_style), + }; + let normal = super::textstyles::style_attrs(&src, false, super::textstyles::NORMAL_CHAR).unwrap_or_default(); + let chars = s.prefs.override_char_color; + // A composite font the style names comes with it, in place of the document's of its name, as + // Import Composite Fonts brings it. + let family = normal.get("font_family").and_then(Value::as_str); + let fonts_before = s.doc()?.doc.composite_fonts.to_vec(); + let fonts = family + .and_then(|f| CompositeFont::named(&src.composite_fonts, f)) + .map(|f| super::compositefonts::with_font(&fonts_before, f)) + .filter(|after| *after != fonts_before); + if let Some(after) = &fonts { + super::compositefonts::check_set(after, C)?; + } + let fonts_changed = match &fonts { + Some(after) => super::compositefonts::register(s, &fonts_before, after), + None => vec![], + }; + let apply = |d: &mut Document| -> Result<()> { + if let Some(after) = &fonts { + super::compositefonts::set_fonts(d, after, &fonts_changed)?; + } + let before = d.clone(); + let (appearance, attrs) = super::clipboard::resources::import_looks(&src, d, &look.appearance, &normal)?; + let attrs = if attrs.is_empty() { + attrs + } else { + super::textstyles::stored_style_attrs(d, false, &attrs) + .ok_or_else(|| bad(C, format!("the {name} profile's [Normal Character Style] has attributes charStyle.new does not take")))? + }; + let new = GraphicStyle { appearance, ..look.clone() }; + match d.graphic_style_index(DEFAULT_GRAPHIC_STYLE) { + Some(i) if d.graphic_styles[i].same_look(&new) => {} + Some(i) => super::style::redefine_in(d, &before, i, new, None, chars), + None => { + let id = d.next_graphic_style_id(); + d.graphic_styles.insert(0, GraphicStyle { name: DEFAULT_GRAPHIC_STYLE.to_string(), id, ..new }); + } + } + super::textstyles::redefine_normal_char(d, &attrs) + }; + // An undo step only when the document changes; Undo puts the new-art paints back too. + let paint_before = super::colormgmt::new_art_colors_before(s)?; + let mut run = || -> Result { + let mut trial = (*s.doc()?.doc).clone(); + apply(&mut trial)?; + let changed = trial != *s.doc()?.doc; + if changed { + s.edit("Use Profile Defaults", |d, _| apply(d))?; + } + Ok(changed) + }; + let changed = run(); + if fonts.is_some() { + super::compositefonts::sync(s); + } + let changed = changed?; + super::newart::reset(s); + // The selection's appearance does not replace the defaults just set. + s.note_defaults_only(); + if changed || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + super::colormgmt::record_new_art_colors(s, paint_before)?; + } + let mut out = json!({ "name": name, "changed": changed }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) +} + +/// The shipped Default Graphic Style: white fill, 1 pt black stroke. +fn shipped_default_style() -> GraphicStyle { + GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, vectorcraft_doc::Appearance::default_art()) +} diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 25ca3a60ca..ed6940d5fc 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -1159,7 +1159,7 @@ impl Session { /// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured /// while inheritance does not run (New Art Has Basic Appearance on, or the active tool painting /// with both the fill and the stroke). - fn note_defaults_only(&mut self) { + pub(crate) fn note_defaults_only(&mut self) { let inherits = !self.prefs.new_art_basic && !(self.tool_paints(false) && self.tool_paints(true)); self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None }); } diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 36f54934c0..05fa6ce85f 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -545,40 +545,50 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { - let id = d.graphic_style_id(i); - let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name: name.clone(), id, ..look }); - // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the - // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the - // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); - let (follow, edited): (Vec, Vec) = - linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); - set_link(d, &edited, None); - // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and - // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its - // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps - // its look and its link. - let mut follow_marks = super::graph::series_group_marks(d, &follow); - let edited: HashSet = edited.into_iter().collect(); - let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); - follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); - super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); - let g = d.graphic_styles[i].clone(); - let mut shared = None; - for nid in &follow_marks { - apply_style(d, *nid, &g, &mut shared, chars); - } - super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); - super::graph::capture_label_rows(d, &follow_marks); - if let Some(src) = src { - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); - } + redefine_in(d, &before, i, look, src, chars); Ok(()) })?; Ok(json!({ "name": name })) } +/// Replace graphic style `i` of `d` with the fills, strokes, effects and transparency of `look`, +/// keeping its name and id, as Redefine Graphic Style does: the objects still linked to it follow +/// the new definition, edited ones are unlinked and keep their look, and object `src` (the one the +/// look comes from, if any) becomes linked. `before` is `d` before the edit; `chars` is Override +/// Character Color. +pub(crate) fn redefine_in(d: &mut Document, before: &Document, i: usize, look: GraphicStyle, src: Option, chars: bool) { + let id = d.graphic_style_id(i); + let name = d.graphic_styles[i].name.clone(); + let old = std::mem::replace(&mut d.graphic_styles[i], GraphicStyle { name, id, ..look }); + // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the + // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the + // source or as a linked object: the graph draws it again from the design. + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); + let (follow, edited): (Vec, Vec) = + linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); + set_link(d, &edited, None); + // A linked graph series group passes the style to the paths directly inside it, so the graph stores it, and + // goes back to the empty appearance the graph draws it with; a linked Axes or Legend group does the same with its + // lines and labels. The source and the edited paths keep their look, and a member linked to another style keeps + // its look and its link. + let mut follow_marks = super::graph::series_group_marks(d, &follow); + let edited: HashSet = edited.into_iter().collect(); + let takes_style = |nid: NodeId| d.node(nid).is_some_and(|n| n.extras().graphic_style.is_none_or(|g| g == id)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid) && takes_style(*nid)); + super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); + let g = d.graphic_styles[i].clone(); + let mut shared = None; + for nid in &follow_marks { + apply_style(d, *nid, &g, &mut shared, chars); + } + super::appearance::capture_series_writes(before, d, &follow_marks, (true, true), (true, true), false, true); + super::graph::capture_label_rows(d, &follow_marks); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } +} + fn style_break_link(s: &mut Session, p: &Value) -> Result { let ids = super::appearance::whole_targets(s, p, "graphicStyle.breakLink")?; s.edit("Break Link to Graphic Style", |d, _| { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d7657df16e..f3860e358c 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -963,17 +963,31 @@ fn redefine_to(s: &mut Session, kind: Kind, name: &str, new_attrs: Map def.attrs = new_attrs.clone(), - None => kind.defs_mut(d).push(TextStyleDef { name: name.clone(), attrs: new_attrs.clone() }), - } - update_users(d, kind, &name, &old, &new_attrs)?; - Ok(()) - })?; + s.edit_named("Redefine {name}", &name, name == kind.normal(), |d, _| set_definition(d, kind, &name, &old, &new_attrs))?; ok() } +/// Give style `name` of `d` the attributes `new_attrs` (it had `old`), and the text in it that +/// follows the old definition the new one (users keep their overrides). +fn set_definition(d: &mut Document, kind: Kind, name: &str, old: &Map, new_attrs: &Map) -> Result<()> { + match kind.defs_mut(d).iter_mut().find(|s| s.name == name) { + Some(def) => def.attrs = new_attrs.clone(), + None => kind.defs_mut(d).push(TextStyleDef { name: name.to_string(), attrs: new_attrs.clone() }), + } + update_users(d, kind, name, old, new_attrs) +} + +/// Redefine `[Normal Character Style]` of `d` with `attrs` (attributes as `charStyle.new` stores +/// them), as Redefine Character Style does: the type in it takes the new attributes and keeps its +/// overrides. Nothing changes when `attrs` is the current definition. +pub(crate) fn redefine_normal_char(d: &mut Document, attrs: &Map) -> Result<()> { + let old = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); + if *attrs == old { + return Ok(()); + } + set_definition(d, Kind::Char, NORMAL_CHAR, &old, attrs) +} + fn redefine(s: &mut Session, p: &Value, kind: Kind) -> Result { let name = name_param(p, kind, "redefine")?.to_string(); let attrs = selection_attrs(s, p, kind, "redefine")?.ok_or_else(|| bad(&kind.cmd("redefine"), "select text to redefine the style from"))?; diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index b65d4a4b9a..a28a1f3aa0 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -892,6 +892,163 @@ fn a_profiles_normal_character_style_is_the_default_font() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults"); + const GLOW: &str = r#""#; + // The CMYK Print profile: no fill and a 0.25 pt stroke of the global swatch Laser Red, with + // the SVG filter Glow7653, and red type in Source Serif 4 at 9 pt. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Laser Red", "color": "#ff0000", "global": true})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": GLOW})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"swatch": "Laser Red"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Glow7653"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + let serif = + s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Serif", "font": "Source Serif 4", "size": 9, "color": "#ff0000"})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": serif["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + // An RGB document made without a profile, with another filter named Glow7653, type in the + // default font and a rectangle linked to its Default Graphic Style. + s.execute("file.new", &json!({"colorMode": "rgb"})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": r#""#})).unwrap(); + let before = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Before"})).unwrap(); + let linked = s.execute("shape.rectangle", &json!({"x": 20, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("graphicStyle.apply", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let default_font = first_run(&s, &before["id"]); + + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "print"})).unwrap(); + assert_eq!((r["name"].clone(), r["changed"].clone()), (json!("Print"), json!(true)), "{r}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // The swatch comes along, in the document's color mode, and the style paints with it. + let d = &s.doc().unwrap().doc; + let red = d.swatches.iter().find(|w| w.name == "Laser Red").cloned().expect("the style's swatch"); + assert!(matches!(red.paint, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let stroke = s.paint.stroke.clone(); + assert!(matches!(&stroke, Paint::Solid { swatch: Some(w), .. } if w == "Laser Red"), "{stroke:?}"); + // The profile's filter keeps its definition under a free name; the document's keeps its own. + let style = d.graphic_style("Default Graphic Style").cloned().unwrap(); + let filter = style.appearance.effects.iter().find(|e| e.id == "svg.filter").cloned().expect("the style's filter"); + assert_ne!(filter.params["name"], "Glow7653", "{filter:?}"); + assert!(filter.params["xml"].as_str().is_some_and(|x| x.contains("dx=\"3\"")), "{filter:?}"); + assert!(d.svg_filters.iter().any(|f| f.name == "Glow7653" && f.xml.contains("dx=\"9\""))); + // New art takes the profile's look; so does the rectangle linked to the style. + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, stroke.clone(), Some(0.25))); + assert_eq!(look(&s, linked), (Paint::None, stroke.clone(), Some(0.25))); + // New type starts in the profile's font, and type in [Normal Character Style] follows it. + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "After"})).unwrap(); + for id in [&made["id"], &before["id"]] { + let st = first_run(&s, id); + assert_eq!((st.font_family.as_str(), st.size), ("Source Serif 4", 9.0)); + // The profile's CMYK red is converted to the document's color mode. + assert!(matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", st.fill); + } + // Again: nothing changes and no undo step is recorded. + let step = s.doc().unwrap().history.step(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], false, "{r}"); + assert_eq!(s.doc().unwrap().history.step(), step); + + // A category without a profile file gives the shipped defaults back. + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let print_paint = s.paint.clone(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Web"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let st = first_run(&s, &before["id"]); + assert_eq!((st.font_family, st.size), (default_font.font_family.clone(), default_font.size)); + // Undo goes back to the Print profile's defaults in the document and for new art; Redo + // brings the shipped ones again. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first_run(&s, &before["id"]).font_family, "Source Serif 4"); + assert_eq!(s.paint, print_paint); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + s.execute("edit.undo", &json!({})).unwrap(); + + // An unknown profile is an error and changes nothing. + let step = s.doc().unwrap().history.step(); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Posters"})).is_err()); + assert!(s.execute("file.newProfiles.applyDefaults", &json!({})).is_err()); + assert_eq!(s.doc().unwrap().history.step(), step); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With New Art Has Basic Appearance off, the selected object's look does not replace the profile's +/// defaults that Use Profile Defaults has just set. +#[test] +fn profile_defaults_stay_with_an_unrelated_object_selected() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("apply-defaults-selected"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({})).unwrap(); + s.execute("prefs.set", &json!({"key": "newArtBasic", "value": false})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 30, "height": 30})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 60, "y": 80, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap(); + assert_eq!((look(&s, id).0, look(&s, id).2), (Paint::None, Some(0.25))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A profile whose [Normal Character Style] is set in one of its composite fonts gives the open +/// document that composite font too, in place of the document's of the same name. +#[test] +fn profile_defaults_bring_the_composite_font_of_the_default_font() { + let font = |roman: f64| { + json!({"name": "CF Profile 7653", "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono", "size": roman}, + }}) + }; + let (mut s, dir) = with_profiles("apply-defaults-composite"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(50.0)]})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 80, "text": "Ab", "font": "CF Profile 7653", "size": 12})).unwrap(); + s.execute("charStyle.redefine", &json!({"name": "[Normal Character Style]", "id": t["id"]})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + s.execute("file.new", &json!({"colorMode": "cmyk"})).unwrap(); + s.execute("type.compositeFonts.set", &json!({"fonts": [font(100.0)]})).unwrap(); + let profile = |s: &Session| s.doc().unwrap().doc.composite_fonts.iter().find(|f| f.name == "CF Profile 7653").map(|f| f.parts.roman.size); + assert_eq!(profile(&s), Some(100.0)); + let r = s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap(); + assert_eq!(r["changed"], true, "{r}"); + assert_eq!(profile(&s), Some(50.0), "the profile's definition"); + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Ab"})).unwrap(); + assert_eq!(first_run(&s, &made["id"]).font_family, "CF Profile 7653"); + let missing = s.execute("text.fonts", &json!({})).unwrap().as_array().unwrap().iter().filter(|f| f["missing"] == true).count(); + assert_eq!(missing, 0); + // Again: nothing changes. + let step = s.doc().unwrap().history.step(); + assert_eq!(s.execute("file.newProfiles.applyDefaults", &json!({"name": "Print"})).unwrap()["changed"], false); + assert_eq!(s.doc().unwrap().history.step(), step); + // Undone, the document's own definition is back. + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(profile(&s), Some(100.0)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let (mut s, dir) = with_profiles("errors"); diff --git a/crates/engine/src/tests/svgfilter.rs b/crates/engine/src/tests/svgfilter.rs index 41ed696c08..a02e5aad53 100644 --- a/crates/engine/src/tests/svgfilter.rs +++ b/crates/engine/src/tests/svgfilter.rs @@ -292,6 +292,24 @@ fn pasted_art_keeps_a_filter_another_of_its_name_would_replace() { assert_eq!(both, [("Shift".to_string(), SHIFT_MORE.to_string()), ("Shift".to_string(), SHIFT_MORE.to_string())]); } +/// Pasted again, art whose filter was renamed takes the name the first paste gave it, so the +/// same filter does not come in under a new name each time. +#[test] +fn pasting_a_renamed_filter_again_reuses_its_name() { + let mut s = session(); + run(&mut s, "svgFilter.define", json!({"xml": SHIFT})); + let svg = format!( + r#"{SHIFT_MORE}"# + ); + run(&mut s, "clipboard.importSvg", json!({"svg": svg})); + run(&mut s, "edit.pasteInPlace", json!({})); + run(&mut s, "edit.pasteInPlace", json!({})); + let pasted = filter_effects(&s); + assert_eq!(pasted.len(), 2); + assert_eq!(pasted[0], pasted[1], "{pasted:?}"); + assert_ne!(pasted[0].0, "Shift", "{pasted:?}"); +} + /// A pasted filter at the size limit, which "Shift 2" would make too long to draw, keeps its own /// definition under a free name no longer than its own (a free letter for a one-letter name), and /// its id is that name. diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 2d29d98a23..20144d4411 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -262,6 +262,22 @@ fn document_color_mode_converts_effect_colors() { assert_eq!((object(&s), style(&s)), before); } +/// Document Color Mode converts the fill of a character style, so type set in the style after the +/// switch paints in the new mode. +#[test] +fn document_color_mode_converts_character_style_colors() { + let mut s = session(); + let id = run(&mut s, "text.create", json!({"x": 10, "y": 40, "text": "Ink", "color": "#ff0000"}))["id"].clone(); + run(&mut s, "charStyle.new", json!({"name": "Red", "id": id})); + let fill = |s: &Session| { + let def = doc(s).char_styles.iter().find(|c| c.name == "Red").expect("the style"); + serde_json::from_value::(def.attrs["fill"].clone()).expect("a fill") + }; + assert!(matches!(fill(&s).color(), Some(Color::Rgb { .. })), "{:?}", fill(&s)); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + assert!(matches!(fill(&s).color(), Some(Color::Cmyk { .. })), "{:?}", fill(&s)); +} + /// Document Color Mode converts the series paints, label styles and line rows a graph keeps, so a /// graph drawn again after the switch paints its series, labels and lines in the new mode. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..356b4428c6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9834,6 +9834,20 @@ with the defaults. them. - `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. +- `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 + attributes, with the profile's colors converted to the document's color mode and the swatches, patterns, symbols and + brushes they paint with added. A composite font of the profile that those attributes name replaces the document's + composite font of that name, as `type.compositeFonts.import` does. A category without a file gives the shipped + defaults. The change is one undo step, which also puts back the fill and stroke new art took, and none is recorded + when the document already has both. As + `graphicStyle.redefine` and `charStyle.redefine` do, objects still linked to the Default Graphic Style and type in + [Normal Character Style] take the new definitions and keep their overrides. New art then starts as `paint.default` + gives it, and new type in the profile's font. It returns `{name, changed, warnings?}`, and an error when the + profile's file can't be read, its [Normal Character Style] has attributes `charStyle.new` does not take, or the + composite font it names can't join the document's composite fonts (`type.compositeFonts.set` checks them the same + way). - Under automation roots, `file.newProfiles.edit` needs write and read access to the profile's file and `file.newProfiles.reset` needs write access. An error names the file whole only inside the read roots, and otherwise by its file name. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e15f6be884..36af4e0ad8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -973,6 +973,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Default fill and stroke from a profile:** when a New Document profile's Default Graphic Style is redefined (for example no fill and a 0.25 pt red stroke), documents from that profile start new art with that style's fills, strokes and effects, and Default Fill and Stroke (`paint.default`, D) gives the defaults and the selection the same look in those documents (VectorCraft's own rule). Test: `tests::newdoc::a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke`. +- **Another profile's defaults in an open document:** Use Profile Defaults (`file.newProfiles.applyDefaults`, VectorCraft's own command) gives the active document the Default Graphic Style and [Normal Character Style] of another New Document profile, with the swatches they paint with, in one undo step, so new art and new type start with that profile's fill, stroke and font. Test: `tests::newdoc::an_open_document_takes_another_profiles_default_fill_stroke_and_font`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Repeated brush names in a file:** a document or brush library file whose brushes repeat a name opens with the first brush of that name as stored and each later one numbered, as "Name 2", "Name 3" and so on, skipping names the file already has. Strokes that name the brush keep drawing the first one, and `brush.list`, `brush.options`, `brush.delete`, `brush.library` and the Brushes panel then reach each brush by its own name. This numbering is VectorCraft's own rule. Tests in `crates/brush/src/tests.rs`, `tests/brushsym.rs` and `tests/brushlib.rs` cover it. From f8550c578b31aca860f67b446be0df56d9964a13 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 21:09:13 -0800 Subject: [PATCH 2/2] New Document profiles: keep overrides and kept graph designs when loading defaults - Redefining a text style keeps text with its own value of an attribute the old definition did not set. Only text that still had the value it had under the old definition (Normal's, or the default when Normal itself is redefined) takes the new one. Leadings that Block gave the text still follow the style. - Use Profile Defaults and Load Character Styles draw the graphs in the symbols they add with the document's own graph design of that name, as Paste does. - file.newProfiles commands say their name is a built-in category of file.newPresets, and Use Profile Defaults records no undo step when the document does not change. --- crates/engine/src/cmd/clipboard/resources.rs | 4 ++ crates/engine/src/cmd/graph/tests.rs | 52 ++++++++++++++++++++ crates/engine/src/cmd/newdoc.rs | 6 +-- crates/engine/src/cmd/textstyles.rs | 31 +++++++----- crates/engine/src/cmd/textstyles/tests.rs | 17 +++++++ crates/engine/src/tests/newdoc.rs | 6 ++- docs/mcp.md | 2 +- 7 files changed, 102 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 7c1ac4b51e..56cf4f5b96 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1862,6 +1862,8 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, let clip = Clipboard::with_used(src, &used, &library, vec![]); let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::>()); let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); let mut placed: Vec = vec![]; for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] { for s in list { @@ -1895,6 +1897,8 @@ pub(crate) fn import_looks( let carrier = Node::path(vectorcraft_doc::NodeId(0), vectorcraft_geom::PathData::default(), look.clone()); let clip = Clipboard::with_used(src, &used, &library, vec![carrier]); let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?; + // Graphs in the symbols added draw with the designs `d` kept, as pasted ones do. + crate::cmd::graph::redraw_symbols_with_designs(d, &out.added_symbols, &out.kept_designs); let (mut look, mut attrs) = (look.clone(), attrs.clone()); out.relink.appearance(&mut look); out.relink.attrs(&mut attrs); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 45242affa3..5ac5a3bb51 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -6013,6 +6013,58 @@ fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_tha assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); } +/// A symbol a loaded look or text style brings, through the pattern it paints with, draws its +/// graph with the document's design of that name, as a pasted one does. +#[test] +fn a_symbol_a_loaded_look_or_text_style_brings_draws_its_graph_with_the_documents_design() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].clone(); + src.execute("object.pattern.make", &json!({"name": "Charts", "edit": false, "ids": [instance]})).unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [r]})).unwrap(); + let t = src.execute("text.create", &json!({"x": 10, "y": 80, "text": "Charts"})).unwrap()["id"].clone(); + src.execute("paint.setFill", &json!({"swatch": "Charts", "ids": [t]})).unwrap(); + src.execute("charStyle.new", &json!({"name": "Charted", "id": t})).unwrap(); + let source = (*src.doc().unwrap().doc).clone(); + let look = source.node(NodeId(r)).unwrap().appearance.clone(); + assert!(source.pattern("Charts").is_some()); + + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns = |d: &vectorcraft_doc::Document| -> Vec { + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect() + }; + for styles in [false, true] { + // A document whose "Coin" is a rectangle and an ellipse. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + if styles { + crate::cmd::clipboard::resources::import_text_styles(&source, d, true, false).unwrap(); + } else { + crate::cmd::clipboard::resources::import_looks(&source, d, &look, &serde_json::Map::new()).unwrap(); + } + assert_eq!(columns(d), [2, 2, 2, 2], "styles {styles}: drawn with the document's design"); + } +} + #[test] fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 63c073f02c..c71c362a61 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -63,7 +63,7 @@ pub fn specs() -> Vec { "Edit Profile", [], None, - "{name: a category of file.newPresets} 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; 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 { "Reset Profile", [], None, - "{name: a category of file.newPresets} 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; 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 ), @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Use Profile Defaults", [], None, - "{name: a category of file.newPresets} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when the document already has both). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}", + "{name: a built-in category of file.newPresets (not Recent or Saved)} give the active document the default fill and stroke and the default font of the category's New Document profile (VectorCraft's own command; a category without a profile file gives the shipped ones): the document's Default Graphic Style takes the fills, strokes, effects and transparency of the profile's, and its [Normal Character Style] the profile's attributes (a composite font of the profile they name replaces the document's of that name, as type.compositeFonts.import does), the profile's colors converted to the document's color mode, with the swatches, patterns, symbols and brushes they paint with, in one undo step (none when applying the profile leaves the document unchanged). As Redefine Graphic Style and Redefine Character Style do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as paint.default gives it (see appearance.newArt), and new type in the profile's [Normal Character Style]. An error when the profile's file can't be read, its [Normal Character Style] has attributes charStyle.new does not take, or the composite font it names can't join the document's (as type.compositeFonts.set checks them) → {name, changed: whether the document changed, warnings?: [text] (a color profile or font the profile's file carries that can't be used)}", has_doc, apply_defaults ), diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index f3860e358c..b632dbd3ba 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -336,16 +336,17 @@ fn with_attrs(base: &T, attrs: &Map( cur: &T, attrs: fn(&T) -> Map, old: &Map, new: &Map, base: &Map, + old_base: &Map, ) -> T { // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. let Some(mut m) = to_map(cur) else { return cur.clone() }; @@ -353,7 +354,7 @@ fn restyle( let pair = |m: &Map| KINSOKU.map(|k| m.get(k).cloned()); let own = pair(&m); for (k, v) in new { - if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { + if m.get(k) == old.get(k).or_else(|| old_base.get(k)) { m.insert(k.clone(), v.clone()); } } @@ -369,7 +370,7 @@ fn restyle( // style's keeps its own. let has = |m: &Map| KINSOKU.iter().any(|k| m.contains_key(*k)); if has(old) || has(new) { - let follows = !has(old) || pair(old) == own; + let follows = pair(if has(old) { old } else { old_base }) == own; let to = if !follows { own } else if has(new) { @@ -494,10 +495,16 @@ fn uses_of(uses: &std::collections::HashMap, usize>, kind: Kind, fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map, new: &Map) -> Result<()> { let target = (name != kind.normal()).then_some(name.to_string()); let normal = kind.attrs(d, kind.normal()).unwrap_or_default(); - let base = match kind { - Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), &normal, &kind.cmd("edit"))?), - Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), &normal, &kind.cmd("edit"))?), + // What the text had under the old definition where it sets nothing: Normal's (its old + // definition when Normal is the style redefined) over the defaults. + let old_normal = if target.is_none() { old } else { &normal }; + let over_defaults = |attrs: &Map| -> Result> { + Ok(match kind { + Kind::Char => char_attrs(&with_attrs(&CharStyle::default(), attrs, &kind.cmd("edit"))?), + Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), attrs, &kind.cmd("edit"))?), + }) }; + let (base, old_base) = (over_defaults(&normal)?, over_defaults(old_normal)?); each_text_mut(d, &mut |t| { let mut changed = false; // The first character whose leading the new definition changed. @@ -505,8 +512,10 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map>(v.clone()).ok()); match kind { @@ -520,7 +529,7 @@ fn update_users(d: &mut Document, kind: Kind, name: &str, old: &Map { for pa in t.para_styles_mut() { if pa.style_name == target { - *pa = restyle(pa, para_attrs, old, new, &base); + *pa = restyle(pa, para_attrs, old, new, &base, &old_base); changed = true; } } diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index c0a92a20e3..49e50ca14c 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -525,6 +525,23 @@ fn editing_character_style_clears_removed_size_without_losing_local_override() { assert_eq!((r[0].style.size, r[1].style.size), (15.0, 31.0)); } +/// A size a style starts to set reaches the text that had the size the style left it (Normal's, +/// or the default when Normal itself is redefined), and not text with a size of its own. +#[test] +fn a_size_a_character_style_starts_to_set_keeps_local_overrides() { + for name in ["Body", NORMAL_CHAR] { + let (mut s, id) = session_with_text("One two"); + if name != NORMAL_CHAR { + s.execute("charStyle.new", &json!({"name": name, "attrs": {}})).unwrap(); + s.execute("charStyle.apply", &json!({"name": name, "id": id})).unwrap(); + } + s.execute("text.setRangeStyle", &json!({"id": id, "start": 4, "end": 7, "size": 36.0})).unwrap(); + s.execute("charStyle.setAttrs", &json!({"name": name, "attrs": {"size": 24.0}})).unwrap(); + let r = runs(&s, id); + assert_eq!((r[0].style.size, r[1].style.size), (24.0, 36.0), "{name}"); + } +} + #[test] fn replacing_character_style_attrs_clears_removed_size() { let (mut s, id) = session_with_text("Text"); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index a28a1f3aa0..f41253ec22 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -951,7 +951,11 @@ fn an_open_document_takes_another_profiles_default_fill_stroke_and_font() { let st = first_run(&s, id); assert_eq!((st.font_family.as_str(), st.size), ("Source Serif 4", 9.0)); // The profile's CMYK red is converted to the document's color mode. - assert!(matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", st.fill); + assert!( + matches!(st.fill, Paint::Solid { color: vectorcraft_color::Color::Rgb { r, g, b }, .. } if r > 0.8 && g < 0.3 && b < 0.3), + "a converted red: {:?}", + st.fill + ); } // Again: nothing changes and no undo step is recorded. let step = s.doc().unwrap().history.step(); diff --git a/docs/mcp.md b/docs/mcp.md index 356b4428c6..296ef7ba07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9841,7 +9841,7 @@ with the defaults. brushes they paint with added. A composite font of the profile that those attributes name replaces the document's composite font of that name, as `type.compositeFonts.import` does. A category without a file gives the shipped defaults. The change is one undo step, which also puts back the fill and stroke new art took, and none is recorded - when the document already has both. As + when applying the profile leaves the document unchanged. As `graphicStyle.redefine` and `charStyle.redefine` do, objects still linked to the Default Graphic Style and type in [Normal Character Style] take the new definitions and keep their overrides. New art then starts as `paint.default` gives it, and new type in the profile's font. It returns `{name, changed, warnings?}`, and an error when the