Merge pull request #7229 from dotCooCoo/feat/kinsoku-sets

Type: Kinsoku Shori sets can be created, edited and chosen per paragraph
This commit is contained in:
BFlat
2026-11-19 14:54:38 +07:00
committed by GitHub
57 changed files with 3072 additions and 119 deletions
+2
View File
@@ -48,6 +48,7 @@ mod info;
pub(crate) mod inline;
mod interactivity;
mod intertwine;
pub mod kinsokusets;
pub(crate) mod layer;
mod layerpanel;
pub mod library;
@@ -335,6 +336,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(textstyles::specs());
v.extend(fonts::specs());
v.extend(compositefonts::specs());
v.extend(kinsokusets::specs());
v.extend(fontfiles::specs());
v.extend(help::specs());
v.extend(toast::specs());
+145 -2
View File
@@ -20,12 +20,14 @@ use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice,
SymbolRegistration, TextStyleDef,
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
SymbolNineSlice, SymbolRegistration, TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
use super::super::typecmd::refresh_bounds;
use super::super::patterncmds::add_pattern;
use super::super::{EngineError, Result, bad, unique_name};
@@ -517,6 +519,36 @@ fn copy_of(base: &str, name: &str) -> bool {
name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
}
/// The `i`th numbered copy of a Kinsoku Shori set's name `base` ("name 2"), within
/// [`KINSOKU_NAME_MAX`]: when it would be too long, the number takes the place of the name's last
/// characters, and spaces left at the end of what remains are dropped.
fn numbered_kinsoku_name(base: &str, i: usize) -> String {
let number = format!(" {i}");
let head: String = base.chars().take(KINSOKU_NAME_MAX.saturating_sub(number.chars().count())).collect();
format!("{}{number}", head.trim_end())
}
/// [`unique_name`] for a pasted Kinsoku Shori set among `sets` (a document's custom sets, any
/// case), with names that fit [`KINSOKU_NAME_MAX`] ([`numbered_kinsoku_name`]).
fn unique_kinsoku_name(base: &str, sets: &[KinsokuSet]) -> String {
let taken = |n: &str| KinsokuSet::named(sets, n).is_some();
if !taken(base) {
return base.to_string();
}
(2..).map(|i| numbered_kinsoku_name(base, i)).find(|n| !taken(n)).unwrap_or_else(|| base.to_string())
}
/// Is `name` (any case) the Kinsoku Shori set name `base` or a numbered copy of it, as
/// [`unique_kinsoku_name`] names one?
fn kinsoku_copy_of(base: &str, name: &str) -> bool {
KinsokuSet::same_name(base, name)
|| name.rsplit_once(' ').is_some_and(|(_, n)| {
!n.is_empty()
&& n.bytes().all(|b| b.is_ascii_digit())
&& n.parse::<usize>().is_ok_and(|i| i >= 2 && KinsokuSet::same_name(&numbered_kinsoku_name(base, i), name))
})
}
/// The document's own resource for pasted resource `name`, among the document's `names`: the
/// one of that name when `same` holds for it (or, pasting back into the source document, at all),
/// else a numbered copy of it (added by an earlier paste) that is the same. `None`: add it.
@@ -600,6 +632,9 @@ struct Relink {
styles: BTreeMap<u32, u32>,
/// Swatch (its name in the document) → the colour linked colours show at 100 %.
colors: BTreeMap<String, Color>,
/// A custom Kinsoku set the pasted paragraphs and paragraph styles hold → the document's set
/// they take, or none (Hard) when the document has no room for it ([`Clipboard::import_kinsoku_sets`]).
kinsoku: HashMap<KinsokuSet, Option<Arc<KinsokuSet>>>,
/// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]).
keep_styles: bool,
}
@@ -675,6 +710,17 @@ impl Relink {
}
}
fn attrs(&self, a: &mut Map<String, Value>) {
if let Some(to) =
a.get("kinsoku_set").and_then(|v| serde_json::from_value::<KinsokuSet>(v.clone()).ok()).and_then(|set| self.kinsoku.get(&set))
{
match to {
Some(set) => a.insert("kinsoku_set".into(), json!(set)),
None => {
a.insert("kinsoku".into(), json!(Kinsoku::Hard));
a.insert("kinsoku_set".into(), Value::Null)
}
};
}
for k in STYLE_PAINTS {
let Some(before) = style_paint(a, k) else { continue };
let mut p = before.clone();
@@ -715,6 +761,10 @@ impl Relink {
if let Some(s) = &mut pa.style_name {
self.name(Res::ParaStyle, s);
}
// A graph draws its labels again from the paragraph attributes it keeps for them.
if let Some(to) = pa.kinsoku_set.as_deref().and_then(|set| self.kinsoku.get(set)) {
pa.kinsoku_set = to.clone();
}
}
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
@@ -729,10 +779,21 @@ impl Relink {
self.name(Res::CharStyle, s);
}
}
// Lines break anew when a paragraph's set takes other characters or Hard.
let mut relaid = false;
for pa in t.para_styles_mut() {
if let Some(s) = &mut pa.style_name {
self.name(Res::ParaStyle, s);
}
if let Some(set) = pa.kinsoku_set.as_deref()
&& let Some(to) = self.kinsoku.get(set)
{
relaid |= to.as_deref().is_none_or(|to| kinsoku_chars(to) != kinsoku_chars(set));
pa.kinsoku_set = to.clone();
}
}
if relaid {
refresh_bounds(t);
}
}
NodeKind::Image(im) => self.name(Res::Image, &mut im.key),
@@ -746,6 +807,11 @@ impl Relink {
}
}
/// The characters and sequences of Kinsoku set `s`, without its name.
fn kinsoku_chars(s: &KinsokuSet) -> (&[char], &[char], &[char], &[String]) {
(&s.cannot_start, &s.cannot_end, &s.hanging, &s.inseparable)
}
/// Is `ours` (a document definition's art) the art of `theirs` (a pasted one's) once that is
/// relinked by `r`? Graphic style links don't count: they are relinked last.
fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
@@ -1183,6 +1249,7 @@ impl Clipboard {
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc_images, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
self.import_kinsoku_sets(d, used, same_doc, &mut out);
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
@@ -1329,10 +1396,86 @@ impl Clipboard {
&& out.relink.filters.is_empty()
&& out.relink.styles.is_empty()
&& out.relink.colors.is_empty()
&& out.relink.kinsoku.is_empty()
&& used.styles.is_empty());
Ok(out)
}
/// Add the custom Kinsoku sets that the pasted paragraphs and the used paragraph styles hold
/// to `d`'s sets, and record in [`Relink::kinsoku`] which set of `d` each one takes. A set
/// takes `d`'s set of its name (in any case) when that has the same characters, or, pasted
/// back into its own document, in any case; else a numbered copy of it ("Tight 2") with the
/// same characters. Any other set is added under a free name that fits [`KINSOKU_NAME_MAX`]
/// ([`unique_kinsoku_name`]), so editing `d`'s set of that name leaves the pasted paragraphs
/// alone. When `d` already holds [`KINSOKU_SETS_MAX`] sets, or the pasted set's own name is
/// longer than a name can be, the paragraphs and styles take Hard.
fn import_kinsoku_sets(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
let mut found: Vec<KinsokuSet> = vec![];
let mut seen: HashSet<KinsokuSet> = HashSet::new();
let mut note = |set: &KinsokuSet| {
if !seen.contains(set) {
seen.insert(set.clone());
found.push(set.clone());
}
};
let mut nodes = |n: &Node| {
// Opacity-mask art included.
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if let NodeKind::Text(t) = &m.kind {
t.para_styles().filter_map(|p| p.kinsoku_set.as_deref()).for_each(&mut note);
}
// The paragraph attributes a graph keeps for its labels.
if let Some(spec) = m.extras().graph.as_deref() {
let l = &spec.label_styles;
[&l.values_para, &l.categories_para, &l.legend_para]
.into_iter()
.flatten()
.filter_map(|p| p.kinsoku_set.as_deref())
.for_each(&mut note);
}
});
};
self.nodes.iter().for_each(&mut nodes);
self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).for_each(|s| nodes(s.art.as_ref()));
self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).flat_map(|p| p.art.iter()).for_each(|a| nodes(a.as_ref()));
self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).flat_map(Brush::art).for_each(&mut nodes);
let styles = self.para_styles.iter().filter(|s| used.has(Res::ParaStyle, &s.name));
for set in styles.filter_map(|s| s.attrs.get("kinsoku_set")).filter_map(|v| serde_json::from_value::<KinsokuSet>(v.clone()).ok()) {
note(&set);
}
for set in found {
let lower = set.name.to_lowercase();
let mut copies: Vec<&KinsokuSet> =
d.kinsoku_sets.iter().filter(|x| copy_of(&lower, &x.name.to_lowercase()) || kinsoku_copy_of(&set.name, &x.name)).collect();
// The set of its name first.
copies.sort_by_key(|x| !KinsokuSet::same_name(&x.name, &set.name));
let own = copies.first().copied().filter(|x| same_doc && KinsokuSet::same_name(&x.name, &set.name));
let to = match own.or_else(|| copies.iter().copied().find(|x| kinsoku_chars(x) == kinsoku_chars(&set))) {
Some(x) => {
if !KinsokuSet::same_name(&x.name, &set.name) {
out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": x.name}));
}
Some(Arc::new(x.clone()))
}
None => {
let name = unique_kinsoku_name(&set.name, &d.kinsoku_sets);
(d.kinsoku_sets.len() < KINSOKU_SETS_MAX && name.chars().count() <= KINSOKU_NAME_MAX).then(|| {
let added = KinsokuSet { name: name.clone(), ..set.clone() };
d.kinsoku_sets.push(added.clone());
out.added += 1;
if name != set.name {
out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": name}));
}
Arc::new(added)
})
}
};
if to.as_deref() != Some(&set) {
out.relink.kinsoku.insert(set, to);
}
}
}
/// 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
+353
View File
@@ -0,0 +1,353 @@
//! Type › Kinsoku Shori Settings…: the document's custom Kinsoku Shori sets
//! ([`vectorcraft_doc::KinsokuSet`]). Each set lists the characters that may not start a line,
//! those that may not end one, the hanging punctuation Burasagari hangs, and the inseparable
//! sequences Bunri-Kinshi keeps together. A paragraph chooses one by name in Kinsoku Set
//! (`text.setFormat {kinsoku: name}`) and holds a copy of it, which an edit of the set replaces.
//!
//! Behavior reference: the help page
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html>.
//! The name rules, the limits and Hard as the set a deleted set's paragraphs take are VectorCraft's
//! own.
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::graph::LabelStyles;
use vectorcraft_doc::text::{KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX};
use vectorcraft_doc::{Document, Kinsoku, KinsokuSet, Node, NodeKind, ParaStyle};
use super::textstyles::each_node_with_text_mut;
use super::typecmd::refresh_bounds;
use super::{CommandSpec, Result, Session, bad, cmd, has_doc};
/// The command Type › Kinsoku Shori Settings…'s OK runs, and the menu item's.
pub const SET: &str = "type.kinsokuSets.set";
/// The keys a set may give.
const SET_KEYS: [&str; 6] = ["name", "from", "cannotStart", "cannotEnd", "hanging", "inseparable"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "type.kinsokuSets.list",
"Kinsoku Sets",
[],
None,
"{} the active document's custom Kinsoku Shori sets, and the paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for their labels) using each → {sets: [{name, cannotStart: characters, cannotEnd: characters, hanging: characters, inseparable: [sequence], paragraphs, styles, graphs}]}",
has_doc,
list
),
cmd!(
query "type.kinsokuSets.base",
"Kinsoku Set Base",
[],
None,
"{base: \"none\"|\"hard\"|\"soft\"|name of a custom set (any case), name?} the categories of a built-in or custom set, as a new set based on it starts (Type › Kinsoku Shori Settings…'s New Set): Hard and Soft list the characters they keep off a line's start and end, the East Asian comma and full stop as hanging punctuation, and the pairs Bunri-Kinshi keeps together; None lists nothing → {set: {name, cannotStart, cannotEnd, hanging, inseparable}}",
has_doc,
base
),
cmd!(
"type.kinsokuSets.set",
"Kinsoku Shori Settings…",
["Type"],
None,
"{sets: [{name, from?: the name the set had (rename), cannotStart?: characters, cannotEnd?: characters, hanging?: characters, inseparable?: [sequence of 2..16 characters]}]} replace the active document's custom Kinsoku Shori sets (Type › Kinsoku Shori Settings…'s OK), as one undo step, none when nothing changes. Cannot Start Line characters never start a line and Cannot End Line characters never end one; Hanging Punctuation characters hang outside a line's end with Burasagari; while Bunri-Kinshi is on, a line never breaks inside an inseparable sequence. cannotStart, cannotEnd and hanging keep each character once, sorted, and inseparable keeps each sequence once, sorted (a sequence may repeat a character); each category holds at most 4096 characters (the sequences count each of their characters); a control or space character fails the call, as do an unknown key and a `from` the document has no set of. Names are trimmed, unique in any case, at most 128 characters, never None, Hard or Soft; at most 256 sets. A set given the name of a set the document has (any case) and no `from` is that set. Every paragraph and paragraph style using a set takes its new characters and name; one using a set left out takes Hard. The built-in None, Hard and Soft can't be changed or deleted → {sets}",
has_doc,
set
),
]
}
/// Call `f` with every node in `d`'s layers (opacity masks included), symbols, graph designs,
/// pattern tiles and brush art, the trees [`each_node_with_text_mut`] reaches.
fn each_node(d: &Document, f: &mut impl FnMut(&Node)) {
let brushes = vectorcraft_brush::library(d);
let trees = d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(d.graph_designs.iter().map(|g| &*g.art));
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
let trees = trees.chain(patterns.flat_map(|p| p.art.iter().map(|a| &**a))).chain(brushes.iter().flat_map(|b| b.art()));
for tree in trees {
vectorcraft_doc::swatches::walk_with_masks(tree, &mut |n| f(n));
}
}
/// Call `f` with every paragraph of the type [`each_node`] reaches.
fn each_paragraph(d: &Document, f: &mut impl FnMut(&ParaStyle)) {
each_node(d, &mut |node| {
if let NodeKind::Text(t) = &node.kind {
(0..t.paragraph_count()).for_each(|i| f(t.para_at(i)));
}
});
}
/// How many paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for
/// their labels) use each set of the document, by lowercased name.
fn uses(s: &Session) -> Result<HashMap<String, (usize, usize, usize)>> {
let mut n: HashMap<String, (usize, usize, usize)> = HashMap::new();
let d = &s.doc()?.doc;
each_paragraph(d, &mut |p| {
if let Some(set) = &p.kinsoku_set {
n.entry(set.name.to_lowercase()).or_default().0 += 1;
}
});
for st in d.para_styles.iter() {
if let Some(name) = st.attrs.get("kinsoku_set").and_then(|v| v.get("name")).and_then(Value::as_str) {
n.entry(name.to_lowercase()).or_default().1 += 1;
}
}
each_node(d, &mut |node| {
let Some(g) = node.extras().graph.as_deref() else { return };
let mut l = g.label_styles.clone();
let mut names: Vec<String> = label_paras(&mut l).filter_map(|p| p.kinsoku_set.as_ref().map(|k| k.name.to_lowercase())).collect();
names.sort();
names.dedup();
for name in names {
n.entry(name).or_default().2 += 1;
}
});
Ok(n)
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let uses = uses(s)?;
let sets: Vec<Value> = s
.doc()?
.doc
.kinsoku_sets
.iter()
.map(|set| {
let (paragraphs, styles, graphs) = uses.get(&set.name.to_lowercase()).copied().unwrap_or_default();
let mut v = json!(set);
if let Some(o) = v.as_object_mut() {
o.insert("paragraphs".into(), json!(paragraphs));
o.insert("styles".into(), json!(styles));
o.insert("graphs".into(), json!(graphs));
}
v
})
.collect();
Ok(json!({ "sets": sets }))
}
/// The set `name` names: a built-in one (`none`, `hard`, `soft`) or a custom set of `sets` (any
/// case).
fn named_base(sets: &[KinsokuSet], name: &str) -> Option<KinsokuSet> {
match name {
"none" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::None, "")),
"hard" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Hard, "")),
"soft" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Soft, "")),
_ => KinsokuSet::named(sets, name.trim()).cloned(),
}
}
fn base(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "type.kinsokuSets.base";
let from = p.get("base").and_then(Value::as_str).ok_or_else(|| bad(C, "give base: \"none\", \"hard\", \"soft\" or a set's name"))?;
let mut set = named_base(&s.doc()?.doc.kinsoku_sets, from).ok_or_else(|| bad(C, format!("no Kinsoku set named `{from}`")))?;
set.name = match p.get("name") {
None | Some(Value::Null) => String::new(),
Some(Value::String(n)) => n.clone(),
Some(_) => return Err(bad(C, "name must be text")),
};
Ok(json!({ "set": set }))
}
/// A category of single characters from `v` (text, one character after another): empty when left
/// out. Text far longer than a category holds is refused before it is read.
fn chars(v: Option<&Value>, key: &str, name: &str, c: &str) -> Result<Vec<char>> {
match v {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::String(text)) => {
if text.chars().count() > KINSOKU_CATEGORY_MAX * 4 {
return Err(bad(c, format!("`{name}`: {key} must be at most {KINSOKU_CATEGORY_MAX} characters")));
}
Ok(text.chars().collect())
}
Some(_) => Err(bad(c, format!("`{name}`: {key} must be text, one character after another"))),
}
}
/// Set `v` from command parameters, its name trimmed, with the name it had (`from`, trimmed) when
/// it gives one.
fn parse_set(v: &Value, c: &str) -> Result<(KinsokuSet, Option<String>)> {
let o = v.as_object().ok_or_else(|| bad(c, "each set must be {name, cannotStart?, cannotEnd?, hanging?, inseparable?}"))?;
if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) {
return Err(bad(c, format!("unknown key `{k}`; a set takes {}", SET_KEYS.join(", "))));
}
// A null value is refused rather than read as a key left out.
if let Some(k) = o.iter().find_map(|(k, v)| v.is_null().then_some(k)) {
return Err(bad(c, format!("`{k}` can't be null; leave it out instead")));
}
let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each set needs a name"))?;
let name = KinsokuSet::clean_name(raw).ok_or_else(|| {
bad(c, format!("`{raw}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)"))
})?;
let from = match o.get("from") {
None | Some(Value::Null) => None,
Some(Value::String(f)) => Some(f.trim().to_string()),
Some(_) => return Err(bad(c, format!("`{name}`: from must be text"))),
};
let inseparable = match o.get("inseparable") {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(list)) => {
if list.len() > KINSOKU_CATEGORY_MAX {
return Err(bad(c, format!("`{name}`: inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all")));
}
list.iter()
.map(|s| {
s.as_str().map(str::to_string).ok_or_else(|| {
bad(
c,
format!(
"`{name}`: inseparable must be a list of {} to {} characters each",
KINSOKU_SEQUENCE.start(),
KINSOKU_SEQUENCE.end()
),
)
})
})
.collect::<Result<Vec<_>>>()?
}
Some(_) => return Err(bad(c, format!("`{name}`: inseparable must be a list of sequences"))),
};
let mut set = KinsokuSet {
cannot_start: chars(o.get("cannotStart"), "cannotStart", &name, c)?,
cannot_end: chars(o.get("cannotEnd"), "cannotEnd", &name, c)?,
hanging: chars(o.get("hanging"), "hanging", &name, c)?,
inseparable,
name,
};
set.normalize();
set.check().map_err(|e| bad(c, format!("`{}`: {e}", set.name)))?;
Ok((set, from))
}
/// Make `after` the active document's custom sets, as one undo step (none when nothing changes).
/// `renamed` maps the lowercased name of each set of the document that is kept to the index in
/// `after` of what it becomes; a set it leaves out is deleted, and its paragraphs and paragraph
/// styles take Hard.
fn replace(s: &mut Session, after: Vec<KinsokuSet>, renamed: HashMap<String, usize>) -> Result<()> {
let before = s.doc()?.doc.kinsoku_sets.to_vec();
let after_arcs: Vec<Arc<KinsokuSet>> = after.iter().cloned().map(Arc::new).collect();
// The paragraph value of each set of the document as it was: the new set, or none (Hard).
let next = |old: &KinsokuSet| -> Option<Option<Arc<KinsokuSet>>> {
let key = old.name.to_lowercase();
before.iter().any(|b| b.name.to_lowercase() == key).then(|| renamed.get(&key).and_then(|&i| after_arcs.get(i).cloned()))
};
let fix = |p: &mut ParaStyle| -> bool {
let Some(old) = p.kinsoku_set.as_deref() else { return false };
let Some(new) = next(old) else { return false };
if new.as_deref() == Some(old) {
return false;
}
if new.is_none() {
p.kinsoku = Kinsoku::Hard;
}
p.kinsoku_set = new;
true
};
let mut texts_change = false;
each_paragraph(&s.doc()?.doc, &mut |p| texts_change |= !texts_change && fix(&mut p.clone()));
// A graph draws its labels again from the paragraph attributes it keeps for them.
let fix_labels = |l: &mut LabelStyles| label_paras(l).fold(false, |changed, p| fix(p) | changed);
each_node(&s.doc()?.doc, &mut |n| {
texts_change |= !texts_change && n.extras().graph.as_deref().is_some_and(|g| fix_labels(&mut g.label_styles.clone()));
});
let style_attrs = |attrs: &Map<String, Value>| -> Option<Map<String, Value>> {
let old: KinsokuSet = serde_json::from_value(attrs.get("kinsoku_set")?.clone()).ok()?;
let new = next(&old)?;
if new.as_deref() == Some(&old) {
return None;
}
let mut m = attrs.clone();
match new {
Some(set) => m.insert("kinsoku_set".into(), json!(set)),
None => {
m.insert("kinsoku".into(), json!(Kinsoku::Hard));
m.insert("kinsoku_set".into(), Value::Null)
}
};
Some(m)
};
let styles_change = s.doc()?.doc.para_styles.iter().any(|st| style_attrs(&st.attrs).is_some());
if before == after && !texts_change && !styles_change {
return Ok(());
}
s.edit("Kinsoku Shori Settings", |d, _| {
*d.kinsoku_sets = after.clone();
for st in d.para_styles.iter_mut() {
if let Some(m) = style_attrs(&st.attrs) {
st.attrs = m;
}
}
each_node_with_text_mut(d, &mut |n| {
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
fix_labels(&mut g.label_styles);
}
if let NodeKind::Text(t) = &mut n.kind {
let mut changed = false;
for p in t.para_styles_mut() {
changed |= fix(p);
}
if changed {
refresh_bounds(t);
}
}
Ok(())
})
})
}
/// The paragraph attributes graph label styles `l` keep: the value axis, the categories and the
/// legend.
fn label_paras(l: &mut LabelStyles) -> impl Iterator<Item = &mut ParaStyle> {
[&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten()
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let list =
p.get("sets").and_then(Value::as_array).ok_or_else(|| bad(SET, "give sets: [{name, cannotStart?, cannotEnd?, hanging?, inseparable?}…]"))?;
if list.len() > KINSOKU_SETS_MAX {
return Err(bad(SET, format!("a document keeps at most {KINSOKU_SETS_MAX} Kinsoku sets")));
}
let parsed = list.iter().map(|v| parse_set(v, SET)).collect::<Result<Vec<_>>>()?;
let mut names = std::collections::HashSet::new();
for (set, _) in &parsed {
if !names.insert(set.name.to_lowercase()) {
return Err(bad(SET, format!("two Kinsoku sets are named `{}`", set.name)));
}
}
let before = s.doc()?.doc.kinsoku_sets.to_vec();
let has = |n: &str| before.iter().any(|b| KinsokuSet::same_name(&b.name, n));
// Which set of the document each given set continues: the one `from` names, else the one of
// its own name that no other set's `from` claims.
let mut renamed: HashMap<String, usize> = HashMap::new();
for (i, (set, from)) in parsed.iter().enumerate() {
if let Some(f) = from {
if !has(f) {
return Err(bad(SET, format!("`{}`: the document has no Kinsoku set named `{f}`", set.name)));
}
if renamed.insert(f.to_lowercase(), i).is_some() {
return Err(bad(SET, format!("two Kinsoku sets come from `{f}`")));
}
}
}
for (i, (set, from)) in parsed.iter().enumerate() {
let key = set.name.to_lowercase();
if from.is_none() && has(&set.name) && !renamed.contains_key(&key) {
renamed.insert(key, i);
}
}
let after: Vec<KinsokuSet> = parsed.into_iter().map(|(set, _)| set).collect();
replace(s, after.clone(), renamed)?;
Ok(json!({ "sets": after }))
}
/// The custom set of the active document that `text.setFormat`'s `kinsoku` names (any case), as a
/// paragraph holds it.
pub(crate) fn chosen(s: &Session, name: &str) -> Result<Option<Arc<KinsokuSet>>> {
Ok(KinsokuSet::named(&s.doc()?.doc.kinsoku_sets, name.trim()).cloned().map(Arc::new))
}
#[cfg(test)]
mod tests;
+458
View File
@@ -0,0 +1,458 @@
use serde_json::{Value, json};
use vectorcraft_doc::{Kinsoku, NodeId, NodeKind};
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn names(s: &Session) -> Vec<String> {
s.doc().unwrap().doc.kinsoku_sets.iter().map(|k| k.name.clone()).collect()
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject {
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// Two paragraphs of area type, the second one selected by its range.
fn type_object(s: &mut Session) -> u64 {
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "あいう\nかきく", "area": {"width": 100, "height": 100}})).unwrap()["id"]
.as_u64()
.unwrap()
}
fn tight() -> Value {
json!({"name": "Tight", "cannotStart": "」。、う", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——"]})
}
/// Kinsoku Shori Settings' OK replaces the document's custom sets as one undo step (none when
/// nothing changes); each category keeps each character once, sorted; the sets are listed with
/// their users, saved with the document and undone with it.
#[test]
fn kinsoku_sets_are_set_as_one_undo_step_and_saved() {
let mut s = session();
let before = steps(&s);
let r = s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": " Loose ", "cannotStart": "ーーッ"}]})).unwrap();
assert_eq!(r["sets"][1]["name"], "Loose");
assert_eq!(r["sets"][1]["cannotStart"], "ッー");
assert_eq!(names(&s), ["Tight", "Loose"]);
assert_eq!(steps(&s), before + 1);
s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose", "cannotStart": "ッー"}]})).unwrap();
assert_eq!(steps(&s), before + 1, "the same sets again change nothing");
let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap();
assert_eq!((listed["sets"][0]["name"].clone(), listed["sets"][0]["paragraphs"].clone()), (json!("Tight"), json!(0)));
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
assert_eq!(*reopened.kinsoku_sets, *s.doc().unwrap().doc.kinsoku_sets);
s.execute("edit.undo", &json!({})).unwrap();
assert!(names(&s).is_empty());
// A document without sets saves none.
let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false);
assert!(!String::from_utf8_lossy(&saved).contains("kinsoku_sets"));
}
/// The sets are checked before anything changes: a built-in name, a blank or too-long name, two
/// sets of one name in any case, an unknown key, a sequence of one character or with a space, a
/// control character, a `from` the document has no set of, a null value, and more than 256 sets
/// all fail.
#[test]
fn kinsoku_sets_refuse_what_a_set_cannot_hold() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let before = steps(&s);
let long = "x".repeat(129);
for bad in [
json!([{"name": "Hard"}]),
json!([{"name": "soft"}]),
json!([{"name": " "}]),
json!([{"name": long}]),
json!([{"name": "A"}, {"name": "a"}]),
json!([{"name": "A", "strict": true}]),
json!([{"name": "A", "inseparable": ["あ"]}]),
json!([{"name": "A", "inseparable": ["あ い"]}]),
json!([{"name": "A", "inseparable": "あい"}]),
json!([{"name": "A", "cannotStart": "あ\u{7}"}]),
json!([{"name": "A", "cannotStart": ["あ"]}]),
json!([{"name": "A", "from": "Missing"}]),
json!([{"name": "A", "from": "Tight"}, {"name": "B", "from": "tight"}]),
json!([{"name": "Tight", "from": "Tight", "cannotStart": null}]),
json!([{"name": "Tight", "from": null}]),
json!([{"name": "A", "inseparable": null}]),
json!((0..257).map(|i| json!({"name": format!("S{i}")})).collect::<Vec<_>>()),
] {
assert!(s.execute("type.kinsokuSets.set", &json!({"sets": bad})).is_err(), "{bad}");
}
assert!(s.execute("type.kinsokuSets.set", &json!({})).is_err());
assert_eq!((names(&s), steps(&s)), (vec!["Tight".to_string()], before), "a refused call changes nothing");
}
/// Kinsoku Set chooses a custom set by name (any case) for the paragraphs `text.setFormat` sets: each
/// holds a copy of it beside Hard, in one undo step; a name the document has no set of fails the call
/// and changes nothing; a built-in set takes the custom one's place. Paragraph styles carry it.
#[test]
fn text_set_format_chooses_a_custom_set_per_paragraph() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let id = type_object(&mut s);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
assert!(s.execute("text.setFormat", &json!({"kinsoku": "Missing"})).is_err());
assert!(text(&s, id).para_at(0).kinsoku_set.is_none(), "a refused call changes nothing");
let before = steps(&s);
let second = "あいう\n".len();
s.execute("text.setFormat", &json!({"kinsoku": "tight", "start": second, "end": second})).unwrap();
assert_eq!(steps(&s), before + 1);
let t = text(&s, id);
assert!(t.para_at(0).kinsoku_set.is_none());
let p = t.para_at(1);
assert_eq!((p.kinsoku_name(), p.kinsoku), ("Tight", Kinsoku::Hard));
s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": second, "end": second})).unwrap();
assert_eq!(steps(&s), before + 1, "the set the paragraph already has records nothing");
// The file keeps the paragraph's copy.
let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
assert_eq!(back.para_at(1).kinsoku_name(), "Tight");
// A paragraph style captured from it carries the set; Soft replaces it.
s.execute("paraStyle.new", &json!({"name": "Tight Body", "id": id, "start": second, "end": second})).unwrap();
s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap();
assert!(text(&s, id).para_at(1).kinsoku_set.is_none());
assert_eq!(text(&s, id).para_at(1).kinsoku, Kinsoku::Soft);
s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap();
assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight");
assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Tight");
}
/// A paragraph style that gives only a built-in Kinsoku Set replaces a custom set on the paragraphs
/// it is applied to: the style keeps Kinsoku Set's custom set with its built-in choice. One whose
/// attributes give only a custom set (written by hand into a file) brings Hard with it.
#[test]
fn a_style_with_a_built_in_kinsoku_set_replaces_a_custom_set() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let id = type_object(&mut s);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for (style, kinsoku, name) in [("Soft Only", "soft", "Soft"), ("None Only", "none", "None"), ("Hard Only", "hard", "Hard")] {
s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap();
assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight");
s.execute("paraStyle.new", &json!({"name": style, "attrs": {"kinsoku": kinsoku}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": style, "id": id})).unwrap();
let t = text(&s, id);
assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), (name, name), "{style}");
}
s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap();
let only_set = serde_json::Map::from_iter([("kinsoku_set".to_string(), tight_set(&s))]);
let def = vectorcraft_doc::TextStyleDef { name: "Set Only".into(), attrs: only_set };
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).para_styles.push(def);
s.execute("paraStyle.apply", &json!({"name": "Set Only", "id": id})).unwrap();
assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight");
}
fn tight_set(s: &Session) -> Value {
json!(s.doc().unwrap().doc.kinsoku_sets[0])
}
/// Redefining a paragraph style's Kinsoku Set changes the paragraphs that use the style's set and
/// keeps a paragraph's own custom set: the set and Hard beside it change together.
#[test]
fn redefining_a_style_keeps_a_paragraphs_own_custom_set() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose"}]})).unwrap();
let id = type_object(&mut s);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": "Body", "id": id})).unwrap();
let second = "あいう\n".len();
s.execute("text.setFormat", &json!({"kinsoku": "Loose", "start": second, "end": second})).unwrap();
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku": "soft"}})).unwrap();
let t = text(&s, id);
assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), ("Soft", "Loose"));
}
/// A paragraph style's custom set is one of the document's, by name in any case, with the
/// document's characters; a name the document has no set of fails the call.
#[test]
fn a_styles_custom_set_is_one_of_the_documents() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
assert!(s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err());
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "tight", "cannotStart": "x"}}})).unwrap();
let listed = s.execute("paraStyle.list", &json!({})).unwrap();
let body = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Body").unwrap().clone();
assert_eq!(body["attrs"]["kinsoku_set"], tight_set(&s));
assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err());
}
/// A custom set goes with Hard and has a name a custom set can have: a paragraph style call that
/// gives one beside None or Soft, or with a blank or built-in name, fails and leaves the styles as
/// they were, and one beside Hard is kept.
#[test]
fn a_styles_custom_set_given_beside_none_or_soft_fails_the_call() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap();
let styles = |s: &Session| s.doc().unwrap().doc.para_styles.clone();
let before = styles(&s);
for kinsoku in ["none", "soft"] {
let attrs = json!({"kinsoku": kinsoku, "kinsoku_set": tight_set(&s)});
assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new with {kinsoku}");
assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs with {kinsoku}");
assert_eq!(styles(&s), before, "{kinsoku}");
}
for name in ["", " ", "Hard", "soft"] {
let attrs = json!({"kinsoku_set": {"name": name}});
assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new named `{name}`");
assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs named `{name}`");
assert_eq!(styles(&s), before, "`{name}`");
}
let attrs = json!({"kinsoku": "hard", "kinsoku_set": tight_set(&s)});
s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).unwrap();
let other = styles(&s).into_iter().find(|st| st.name == "Other").unwrap();
assert_eq!(other.attrs["kinsoku_set"], tight_set(&s));
}
/// Editing a set gives every paragraph and paragraph style using it the new characters, renaming it
/// (`from`) the new name too, and deleting it sets them to Hard: each in one undo step, which undo
/// takes back with the set. Paragraphs using no set, or another set, stay as they are.
#[test]
fn editing_renaming_and_deleting_a_set_updates_its_users() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Other", "cannotStart": "ー"}]})).unwrap();
let id = type_object(&mut s);
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let second = "あいう\n".len();
s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": 0, "end": 0})).unwrap();
s.execute("text.setFormat", &json!({"kinsoku": "Other", "start": second, "end": second})).unwrap();
s.execute("paraStyle.new", &json!({"name": "Uses Tight", "id": id, "start": 0, "end": 0})).unwrap();
let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Uses Tight").unwrap().attrs["kinsoku_set"].clone();
assert_eq!(style_set(&s)["name"], "Tight");
let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap();
assert_eq!((listed["sets"][0]["paragraphs"].clone(), listed["sets"][0]["styles"].clone()), (json!(1), json!(1)));
// Edit: 「 may end a line now, and う may start one.
let before = steps(&s);
let edited = json!({"name": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]});
s.execute("type.kinsokuSets.set", &json!({"sets": [edited, {"name": "Other", "cannotStart": "ー"}]})).unwrap();
assert_eq!(steps(&s), before + 1);
let p = text(&s, id).para_at(0).clone();
assert_eq!(p.kinsoku_set.as_ref().unwrap().cannot_start, ['、', '。', '」']);
assert!(p.kinsoku_set.as_ref().unwrap().cannot_end.is_empty());
assert_eq!(style_set(&s)["cannotStart"], "、。」");
assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other", "another set's paragraph stays");
// Rename: the users take the new name.
let renamed = json!({"name": "Strict", "from": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]});
s.execute("type.kinsokuSets.set", &json!({"sets": [renamed, {"name": "Other", "cannotStart": "ー"}]})).unwrap();
assert_eq!(names(&s), ["Strict", "Other"]);
assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict");
assert_eq!(style_set(&s)["name"], "Strict");
// Delete: its users take Hard, in one step that undo takes back.
let before = steps(&s);
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Other", "cannotStart": "ー"}]})).unwrap();
assert_eq!(steps(&s), before + 1);
let p = text(&s, id).para_at(0).clone();
assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard));
assert_eq!(style_set(&s), Value::Null);
assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict");
assert_eq!(style_set(&s)["name"], "Strict");
assert_eq!(names(&s), ["Strict", "Other"]);
}
/// Type pasted into another document brings its custom sets: a missing set is added, the
/// document's set of that name with the same characters is used, and one with other characters
/// keeps its own and the pasted set comes in under a free name, so editing the document's set
/// leaves the pasted paragraphs alone. A paragraph style that comes along takes the same set. A
/// document with no room for another set gives the pasted paragraphs Hard.
#[test]
fn pasted_type_brings_its_kinsoku_sets() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let id = type_object(&mut s);
s.execute("paraStyle.new", &json!({"name": "Tight Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap();
s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap();
let source = s.doc().unwrap().doc.kinsoku_sets[0].clone();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
let pasted = |s: &mut Session| -> (vectorcraft_doc::TextObject, Value) {
let v = s.execute("edit.paste", &json!({})).unwrap();
(text(s, v["ids"][0].as_u64().unwrap()), v)
};
let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Tight Body").unwrap().attrs["kinsoku_set"].clone();
// Pasted back after the set was edited: the document's set as it is now, laid out anew.
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotStart": "いうかきく"}]})).unwrap();
let (t, _) = pasted(&mut s);
let now = s.doc().unwrap().doc.kinsoku_sets[0].clone();
assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now));
let mut fresh = t.clone();
crate::cmd::typecmd::refresh_bounds(&mut fresh);
assert!(fresh == t, "the pasted type is laid out with the document's set");
// A document without the set.
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let (t, _) = pasted(&mut s);
assert_eq!(names(&s), ["Tight"]);
assert_eq!(t.para_at(1).kinsoku_set.as_deref(), Some(&source));
assert_eq!(style_set(&s), json!(source));
let (_, again) = pasted(&mut s);
assert_eq!((again["added"].clone(), names(&s)), (json!(0), vec!["Tight".to_string()]), "a second paste uses the set the first added");
// A document whose set of that name has other characters.
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap();
let (t, v) = pasted(&mut s);
assert_eq!(names(&s), ["TIGHT", "Tight 2"]);
let p = t.para_at(0);
assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| &k.cannot_start)), ("Tight 2", Some(&source.cannot_start)));
assert_eq!(style_set(&s)["name"], "Tight 2");
assert!(v["renamed"].as_array().unwrap().contains(&json!({"kind": "kinsokuSet", "from": "Tight", "to": "Tight 2"})), "{v}");
let kept = json!(s.doc().unwrap().doc.kinsoku_sets[1]);
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ッ"}, kept]})).unwrap();
let users = s.execute("type.kinsokuSets.list", &json!({})).unwrap();
assert_eq!(users["sets"][0]["paragraphs"], 0, "editing the document's own set leaves the pasted paragraphs alone: {users}");
// A document with no room for another set.
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
let full: Vec<Value> = (0..256).map(|i| json!({"name": format!("Set {i}")})).collect();
s.execute("type.kinsokuSets.set", &json!({"sets": full})).unwrap();
let (t, _) = pasted(&mut s);
assert_eq!(names(&s).len(), 256);
let p = t.para_at(0);
assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard));
assert_eq!(style_set(&s), Value::Null);
}
/// A pasted set whose name, at the longest a name can be, the document's set with other
/// characters already has comes in under a free name that fits: the number takes the place of the
/// name's last characters, and a space left at the end of them is dropped. A second paste uses
/// the set the first added.
#[test]
fn a_pasted_set_with_the_longest_name_comes_in_under_a_name_that_fits() {
for (long, fitted) in
[("あ".repeat(128), format!("{} 2", "あ".repeat(126))), (format!("{} いい", "あ".repeat(125)), format!("{} 2", "あ".repeat(125)))]
{
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "」"}]})).unwrap();
let id = type_object(&mut s);
s.execute("text.setFormat", &json!({"ids": [id], "kinsoku": long})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "ー"}]})).unwrap();
let v = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(names(&s), [long.clone(), fitted.clone()]);
let t = text(&s, v["ids"][0].as_u64().unwrap());
let p = t.para_at(0);
assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| k.cannot_start.clone())), (fitted.as_str(), Some(vec!['」'])));
let again = s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(
(again["added"].clone(), names(&s)),
(json!(0), vec![long.clone(), fitted.clone()]),
"a second paste uses the set the first added"
);
}
}
/// The Kinsoku Sets a graph keeps for its labels (value axis, categories, legend), and those its
/// labels are drawn with now.
fn graph_label_sets(s: &Session, id: u64) -> (Vec<String>, Vec<String>) {
let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
let l = n.extras().graph.as_deref().unwrap().label_styles.clone();
let kept = [l.values_para, l.categories_para, l.legend_para].into_iter().flatten().map(|p| p.kinsoku_name().to_string()).collect();
let mut drawn = vec![];
n.walk(&mut |m| {
if let NodeKind::Text(t) = &m.kind {
drawn.push(t.para_at(0).kinsoku_name().to_string());
}
});
(kept, drawn)
}
/// A graph's labels keep a custom set as type does. Pasted into a document whose set of that name
/// has other characters, they take the copy the paste adds, also once the graph is drawn again.
/// Editing a set gives the graph's kept attributes the new characters, and deleting it gives them
/// Hard.
#[test]
fn graph_labels_keep_their_custom_set() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let csv = ",2024,2025\nQ1,3,2\nQ2,5,4";
let id = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 300, "height": 200, "csv": csv})).unwrap()["id"]
.as_u64()
.unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap();
let (kept, drawn) = graph_label_sets(&s, id);
assert_eq!(kept, ["Tight"; 3]);
assert!(!drawn.is_empty() && drawn.iter().all(|k| k == "Tight"), "{drawn:?}");
s.execute("edit.copy", &json!({})).unwrap();
// Pasted where the set of that name has other characters: the labels take the added copy.
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap();
let pasted = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
assert_eq!(names(&s), ["TIGHT", "Tight 2"]);
s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap();
let (kept, drawn) = graph_label_sets(&s, pasted);
assert_eq!(kept, ["Tight 2"; 3]);
assert!(drawn.iter().all(|k| k == "Tight 2"), "the labels drawn again keep the copy: {drawn:?}");
// A second copy becomes a symbol's art.
let in_symbol = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].clone();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol]})).unwrap();
let symbol_starts = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.walk(&mut |n| {
if let Some(g) = n.extras().graph.as_deref() {
out.push(g.label_styles.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start.clone());
}
});
out
};
assert_eq!(symbol_starts(&s).len(), 1);
let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap();
assert_eq!((listed["sets"][1]["name"].clone(), listed["sets"][1]["graphs"].clone()), (json!("Tight 2"), json!(2)), "{listed}");
assert_eq!(listed["sets"][0]["graphs"], 0);
// Edited, then deleted: the kept attributes follow the set, so the labels drawn again do too.
let edited = json!({"name": "Tight 2", "cannotStart": "ー"});
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}, edited]})).unwrap();
let l = &s.doc().unwrap().doc.node(NodeId(pasted)).unwrap().extras().graph.as_deref().unwrap().label_styles;
assert_eq!(l.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start, ['ー']);
assert_eq!(symbol_starts(&s), [vec!['ー']], "a graph in a symbol's art too");
s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap();
s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap();
let (kept, drawn) = graph_label_sets(&s, pasted);
assert_eq!(kept, ["Hard"; 3]);
assert!(drawn.iter().all(|k| k == "Hard"), "{drawn:?}");
}
/// New Set's starting point: Hard and Soft give their characters, None gives an empty set, and a
/// custom set (any case) gives its own; an unknown base fails.
#[test]
fn a_new_set_starts_from_a_built_in_or_custom_set() {
let mut s = session();
s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap();
let hard = s.execute("type.kinsokuSets.base", &json!({"base": "hard", "name": "New"})).unwrap();
let soft = s.execute("type.kinsokuSets.base", &json!({"base": "soft"})).unwrap();
let start = |v: &Value| v["set"]["cannotStart"].as_str().unwrap().to_string();
assert!(start(&hard).contains('ー') && !start(&soft).contains('ー') && start(&soft).contains('」'));
assert_eq!(hard["set"]["name"], "New");
assert_eq!(hard["set"]["hanging"], "、。,.。、");
assert_eq!(hard["set"]["inseparable"].as_array().unwrap().len(), 5);
let none = s.execute("type.kinsokuSets.base", &json!({"base": "none"})).unwrap();
assert_eq!(none["set"]["cannotStart"], "");
let custom = s.execute("type.kinsokuSets.base", &json!({"base": "TIGHT"})).unwrap();
assert_eq!(custom["set"]["cannotEnd"], "「");
assert!(s.execute("type.kinsokuSets.base", &json!({"base": "Missing"})).is_err());
}
File diff suppressed because one or more lines are too long
@@ -686,6 +686,9 @@ pub(super) const ALLOWED: &[&str] = &[
"type.fillPlaceholder",
"type.fitHeadline",
"type.insert",
"type.kinsokuSets.base",
"type.kinsokuSets.list",
"type.kinsokuSets.set",
"type.opticalMarginAlignment",
"type.orientation.horizontal",
"type.orientation.vertical",
+96 -6
View File
@@ -39,13 +39,37 @@ impl Kind {
/// Attributes of style `name` (the Normal style is built in: empty unless redefined).
fn attrs(self, d: &Document, name: &str) -> Option<Map<String, Value>> {
match self.defs(d).iter().find(|s| s.name == name) {
Some(s) => Some(s.attrs.clone()),
Some(s) => {
let mut attrs = s.attrs.clone();
if self == Kind::Para {
kinsoku_pair(&mut attrs);
}
Some(attrs)
}
None if name == self.normal() => Some(Map::new()),
None => None,
}
}
}
/// The two keys of Kinsoku Set: a built-in set (`kinsoku`) and a custom set (`kinsoku_set`), which
/// goes with Hard.
const KINSOKU: [&str; 2] = ["kinsoku", "kinsoku_set"];
/// Paragraph style attributes `attrs` with Kinsoku Set as one attribute: one that gives only
/// `kinsoku` gets no custom set, and one that gives only `kinsoku_set` gets Hard beside it.
fn kinsoku_pair(attrs: &mut Map<String, Value>) {
match (attrs.contains_key(KINSOKU[0]), attrs.contains_key(KINSOKU[1])) {
(true, false) => {
attrs.insert(KINSOKU[1].into(), Value::Null);
}
(false, true) => {
attrs.insert(KINSOKU[0].into(), json!(vectorcraft_doc::Kinsoku::Hard));
}
_ => {}
}
}
/// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`).
const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec {
CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None }
@@ -253,6 +277,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
("leading_model", json!(v.leading_model)),
("burasagari", json!(v.burasagari)),
("kinsoku", json!(v.kinsoku)),
("kinsoku_set", json!(v.kinsoku_set)),
("kinsoku_type", json!(v.kinsoku_type)),
("bunri_kinshi", json!(v.bunri_kinshi)),
("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)),
@@ -325,6 +350,8 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
// 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() };
m.extend(attrs(cur));
let pair = |m: &Map<String, Value>| 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)) {
m.insert(k.clone(), v.clone());
@@ -338,6 +365,25 @@ fn restyle<T: Serialize + DeserializeOwned + Clone>(
m.insert(k.clone(), base_value.clone());
}
}
// Kinsoku Set's two keys change together: a paragraph whose Kinsoku Set is not the old
// style's keeps its own.
let has = |m: &Map<String, Value>| KINSOKU.iter().any(|k| m.contains_key(*k));
if has(old) || has(new) {
let follows = !has(old) || pair(old) == own;
let to = if !follows {
own
} else if has(new) {
pair(new)
} else {
pair(base)
};
for (k, v) in KINSOKU.into_iter().zip(to) {
match v {
Some(v) => m.insert(k.to_string(), v),
None => m.remove(k),
};
}
}
serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone())
}
@@ -359,16 +405,27 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map<String, Value>
/// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by
/// Cancel, and brush art, including opacity masks in those trees.
pub(crate) fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> {
each_node_with_text_mut(d, &mut |n| match &mut n.kind {
NodeKind::Text(t) => f(t),
_ => Ok(()),
})
}
/// Change the nodes [`each_text_mut`] reaches: each type object and each node holding one, and each
/// graph keeping paragraph attributes for its labels, with or without labels drawn.
pub(crate) fn each_node_with_text_mut(d: &mut Document, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> {
fn has_text(n: &Node) -> bool {
matches!(n.kind, NodeKind::Text(_))
|| n.extras().graph.as_deref().is_some_and(|g| {
let l = &g.label_styles;
l.values_para.is_some() || l.categories_para.is_some() || l.legend_para.is_some()
})
|| n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art))
|| n.children().is_some_and(|children| children.iter().any(|child| has_text(child)))
}
fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> {
if let NodeKind::Text(t) = &mut n.kind {
f(t)?;
}
fn visit(n: &mut Node, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> {
f(n)?;
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& has_text(&mask.art)
{
@@ -654,10 +711,43 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
}
para_ranges(&st, m, kept, &c)?;
sort_tabs(&mut st, m, kept);
// A custom Kinsoku set goes with Hard and has a name a custom set can have: one
// given beside None or Soft, or with a blank or built-in name, fails the call
// instead of being dropped.
if m.get("kinsoku_set").is_some_and(|v| !v.is_null()) && KINSOKU.iter().any(|k| kept.and_then(|kept| kept.get(*k)) != m.get(*k)) {
if st.kinsoku != vectorcraft_doc::Kinsoku::Hard {
return Err(bad(&c, "`kinsoku_set` goes with `kinsoku` Hard: give `kinsoku` as `hard` or leave it out"));
}
if st.kinsoku_set.is_none() {
return Err(bad(&c, "`kinsoku_set` needs the name of one of the document's Kinsoku sets"));
}
}
// A custom Kinsoku set is one of the document's, by name (any case), as
// `text.setFormat` chooses it; one the style already holds stays.
if let Some(set) = &st.kinsoku_set
&& kept.and_then(|k| k.get("kinsoku_set")) != m.get("kinsoku_set")
{
let name = set.name.clone();
let found = vectorcraft_doc::KinsokuSet::named(&d.kinsoku_sets, &name).cloned().map(std::sync::Arc::new);
st.kinsoku_set =
Some(found.ok_or_else(|| bad(&c, format!("`kinsoku_set`: the document has no Kinsoku set named `{name}`")))?);
}
para_attrs(&st)
}
};
Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect()))
let mut out: Map<String, Value> = m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect();
// A paragraph style giving one key of Kinsoku Set keeps both, so applying it replaces a
// paragraph's custom set or built-in set.
if kind == Kind::Para {
for k in KINSOKU {
if KINSOKU.iter().any(|g| m.contains_key(*g))
&& let Some(v) = full.get(k)
{
out.insert(k.into(), v.clone());
}
}
}
Ok(Some(out))
}
Some(_) => Err(bad(&kind.cmd(verb), "attrs must be an object")),
}