mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 12:38:18 +00:00
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:
@@ -35,6 +35,7 @@ impl Document {
|
||||
char_styles,
|
||||
para_styles,
|
||||
composite_fonts,
|
||||
kinsoku_sets,
|
||||
text_threads,
|
||||
symbols,
|
||||
graph_designs,
|
||||
@@ -96,6 +97,7 @@ impl Document {
|
||||
&& *char_styles == other.char_styles
|
||||
&& *para_styles == other.para_styles
|
||||
&& *composite_fonts == other.composite_fonts
|
||||
&& *kinsoku_sets == other.kinsoku_sets
|
||||
&& *text_threads == other.text_threads
|
||||
&& symbols.len() == other.symbols.len()
|
||||
&& symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
|
||||
@@ -221,6 +223,7 @@ impl Document {
|
||||
char_styles: Default::default(),
|
||||
para_styles: Default::default(),
|
||||
composite_fonts: Default::default(),
|
||||
kinsoku_sets: Default::default(),
|
||||
text_threads: vec![],
|
||||
symbols: vec![],
|
||||
graph_designs: vec![],
|
||||
|
||||
@@ -138,7 +138,7 @@ pub use text::{
|
||||
RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap,
|
||||
VerticalAlign, WrapShape,
|
||||
};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
|
||||
pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet};
|
||||
pub use trace::TraceView;
|
||||
pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables};
|
||||
pub use vectorcraft_color as color;
|
||||
@@ -218,6 +218,10 @@ pub struct Document {
|
||||
/// Type › Composite Fonts…: the composite fonts defined in the document, by name.
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec")]
|
||||
pub composite_fonts: Shared<Vec<CompositeFont>>,
|
||||
/// Type › Kinsoku Shori Settings…: the custom Kinsoku Shori sets defined in the document, by
|
||||
/// name. A paragraph using one holds a copy of it ([`ParaStyle::kinsoku_set`]).
|
||||
#[serde(default, skip_serializing_if = "skip::is_empty_vec", deserialize_with = "text::read_kinsoku_sets")]
|
||||
pub kinsoku_sets: Shared<Vec<KinsokuSet>>,
|
||||
/// Threaded text: area-type frames one story flows through, in order.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub text_threads: Vec<Vec<NodeId>>,
|
||||
|
||||
@@ -113,6 +113,19 @@ impl Document {
|
||||
.map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::<usize>() + custom(f))
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.kinsoku_sets, &newer.kinsoku_sets, |k| {
|
||||
vec_bytes(k)
|
||||
+ k.iter()
|
||||
.map(|s: &crate::KinsokuSet| {
|
||||
s.name.capacity()
|
||||
+ vec_bytes(&s.cannot_start)
|
||||
+ vec_bytes(&s.cannot_end)
|
||||
+ vec_bytes(&s.hanging)
|
||||
+ vec_bytes(&s.inseparable)
|
||||
+ s.inseparable.iter().map(String::capacity).sum::<usize>()
|
||||
})
|
||||
.sum::<usize>()
|
||||
});
|
||||
n += shared(&self.saved_selections, &newer.saved_selections, |s| {
|
||||
vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::<usize>()
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li
|
||||
mod area;
|
||||
mod char_style;
|
||||
mod composite;
|
||||
mod kinsoku_set;
|
||||
mod object;
|
||||
mod para_style;
|
||||
mod runs;
|
||||
@@ -25,6 +26,8 @@ pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass,
|
||||
CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet,
|
||||
};
|
||||
pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets;
|
||||
pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet};
|
||||
pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
//! Type › Kinsoku Shori Settings…: a custom Kinsoku Shori set, saved with the document. Its four
|
||||
//! categories hold the characters that may not start a line, those that may not end one, the
|
||||
//! hanging punctuation that Burasagari lets stand outside a line, and the inseparable sequences
|
||||
//! that Bunri-Kinshi keeps on one line. A paragraph that uses a set holds a copy of it
|
||||
//! ([`super::ParaStyle::kinsoku_set`]).
|
||||
//!
|
||||
//! 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 and the limits are VectorCraft's own.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The longest set name, in characters.
|
||||
pub const KINSOKU_NAME_MAX: usize = 128;
|
||||
/// The most custom sets a document keeps.
|
||||
pub const KINSOKU_SETS_MAX: usize = 256;
|
||||
/// The most characters one category holds (an inseparable sequence counts each of its characters).
|
||||
pub const KINSOKU_CATEGORY_MAX: usize = 4096;
|
||||
/// The fewest and most characters of an inseparable sequence.
|
||||
pub const KINSOKU_SEQUENCE: std::ops::RangeInclusive<usize> = 2..=16;
|
||||
/// The names of the built-in sets, which no custom set may take (in any case).
|
||||
pub const KINSOKU_BUILT_IN: [&str; 3] = ["None", "Hard", "Soft"];
|
||||
|
||||
/// A custom Kinsoku Shori set. Each list of characters is sorted and holds each character once;
|
||||
/// the inseparable sequences are sorted and unique.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(from = "KinsokuSetFile", into = "KinsokuSetFile")]
|
||||
pub struct KinsokuSet {
|
||||
pub name: String,
|
||||
/// Cannot Start Line: characters that never start a line.
|
||||
pub cannot_start: Vec<char>,
|
||||
/// Cannot End Line: characters that never end a line.
|
||||
pub cannot_end: Vec<char>,
|
||||
/// Hanging Punctuation: characters that Burasagari lets hang outside a line's end.
|
||||
pub hanging: Vec<char>,
|
||||
/// Bunri-Kinshi: sequences of characters that a line never breaks inside while Bunri-Kinshi is
|
||||
/// on.
|
||||
pub inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// [`KinsokuSet`] as saved: each category of single characters as one string.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct KinsokuSetFile {
|
||||
#[serde(default, deserialize_with = "read_name")]
|
||||
name: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_start: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
cannot_end: String,
|
||||
#[serde(default, deserialize_with = "read_category")]
|
||||
hanging: String,
|
||||
#[serde(default, deserialize_with = "read_sequences")]
|
||||
inseparable: Vec<String>,
|
||||
}
|
||||
|
||||
/// The most characters of a name read from a file, spaces around it included; a longer name is
|
||||
/// not read.
|
||||
const NAME_READ_MAX: usize = KINSOKU_CATEGORY_MAX;
|
||||
/// The most characters of a category read from a file, before control and space characters are
|
||||
/// left out.
|
||||
const CATEGORY_READ_MAX: usize = KINSOKU_CATEGORY_MAX * 4;
|
||||
/// The longest inseparable sequence, as a constant for [`Capped`].
|
||||
const SEQUENCE_MAX: usize = *KINSOKU_SEQUENCE.end();
|
||||
|
||||
/// Text read from a file, copied up to `N` characters: a longer text keeps its first `N + 1`, which
|
||||
/// no rule that allows `N` takes, and is not copied whole.
|
||||
struct Capped<const N: usize>(String);
|
||||
|
||||
impl<'de, const N: usize> Deserialize<'de> for Capped<N> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Text<const N: usize>;
|
||||
impl<const N: usize> serde::de::Visitor<'_> for Text<N> {
|
||||
type Value = Capped<N>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("text")
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Capped<N>, E> {
|
||||
Ok(Capped(v.chars().take(N + 1).collect()))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Text::<N>)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's name as read from a file: empty, so not read, when it is longer than [`NAME_READ_MAX`].
|
||||
fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(name) = Capped::<NAME_READ_MAX>::deserialize(d)?;
|
||||
Ok(if name.chars().count() > NAME_READ_MAX { String::new() } else { name })
|
||||
}
|
||||
|
||||
/// A category of a set as read from a file: its first [`CATEGORY_READ_MAX`] characters.
|
||||
fn read_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
let Capped(text) = Capped::<CATEGORY_READ_MAX>::deserialize(d)?;
|
||||
Ok(text.chars().take(CATEGORY_READ_MAX).collect())
|
||||
}
|
||||
|
||||
/// Reads a list, keeping the items `keep` keeps up to `max` of them and skipping the rest of a
|
||||
/// longer list without storing it.
|
||||
struct Kept<T, F>(usize, F, std::marker::PhantomData<T>);
|
||||
|
||||
impl<'de, T: Deserialize<'de>, F: FnMut(&T) -> bool> serde::de::Visitor<'de> for Kept<T, F> {
|
||||
type Value = Vec<T>;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
f.write_str("a list")
|
||||
}
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(mut self, mut seq: A) -> Result<Vec<T>, A::Error> {
|
||||
let mut out = Vec::new();
|
||||
while out.len() < self.0 {
|
||||
match seq.next_element::<T>()? {
|
||||
Some(item) if (self.1)(&item) => out.push(item),
|
||||
Some(_) => {}
|
||||
None => return Ok(out),
|
||||
}
|
||||
}
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// A set's inseparable sequences as read from a file: those [`KinsokuSet::takes_sequence`] takes,
|
||||
/// at most [`KINSOKU_CATEGORY_MAX`]. A text longer than a sequence is not copied whole.
|
||||
fn read_sequences<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
|
||||
let keep = |s: &Capped<SEQUENCE_MAX>| KinsokuSet::takes_sequence(&s.0);
|
||||
let kept = d.deserialize_seq(Kept(KINSOKU_CATEGORY_MAX, keep, std::marker::PhantomData))?;
|
||||
Ok(kept.into_iter().map(|Capped(s)| s).collect())
|
||||
}
|
||||
|
||||
impl From<KinsokuSet> for KinsokuSetFile {
|
||||
fn from(s: KinsokuSet) -> Self {
|
||||
Self {
|
||||
name: s.name,
|
||||
cannot_start: s.cannot_start.into_iter().collect(),
|
||||
cannot_end: s.cannot_end.into_iter().collect(),
|
||||
hanging: s.hanging.into_iter().collect(),
|
||||
inseparable: s.inseparable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<KinsokuSetFile> for KinsokuSet {
|
||||
/// A set read from a file keeps what a set can hold: its name trimmed, or no name when
|
||||
/// [`KinsokuSet::clean_name`] refuses it; each category's characters sorted and unique, without
|
||||
/// control or space characters, up to [`KINSOKU_CATEGORY_MAX`]; and the inseparable sequences of
|
||||
/// [`KINSOKU_SEQUENCE`] characters, up to the same count of characters.
|
||||
fn from(f: KinsokuSetFile) -> Self {
|
||||
let chars = |s: &str| s.chars().filter(|&c| KinsokuSet::takes_char(c)).take(KINSOKU_CATEGORY_MAX * 4).collect::<Vec<char>>();
|
||||
let mut set = KinsokuSet {
|
||||
name: KinsokuSet::clean_name(&f.name).unwrap_or_default(),
|
||||
cannot_start: chars(&f.cannot_start),
|
||||
cannot_end: chars(&f.cannot_end),
|
||||
hanging: chars(&f.hanging),
|
||||
inseparable: f.inseparable,
|
||||
};
|
||||
set.normalize();
|
||||
set.cannot_start.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.cannot_end.truncate(KINSOKU_CATEGORY_MAX);
|
||||
set.hanging.truncate(KINSOKU_CATEGORY_MAX);
|
||||
let mut total = 0;
|
||||
set.inseparable.retain(|s| {
|
||||
total += s.chars().count();
|
||||
total <= KINSOKU_CATEGORY_MAX
|
||||
});
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's custom sets as read from a file: each set with a name, the first set of each name
|
||||
/// (in any case), at most [`KINSOKU_SETS_MAX`]; the sets past those are skipped without being
|
||||
/// stored.
|
||||
pub(crate) fn read_sets<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::Shared<Vec<KinsokuSet>>, D::Error> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let keep = move |s: &KinsokuSet| !s.name.is_empty() && seen.insert(s.name.to_lowercase());
|
||||
Ok(crate::Shared::new(d.deserialize_seq(Kept(KINSOKU_SETS_MAX, keep, std::marker::PhantomData))?))
|
||||
}
|
||||
|
||||
impl KinsokuSet {
|
||||
/// Do `a` and `b` name the same set: equal in any case?
|
||||
pub fn same_name(a: &str, b: &str) -> bool {
|
||||
a == b || a.to_lowercase() == b.to_lowercase()
|
||||
}
|
||||
|
||||
/// The set of `sets` (a document's custom sets) named `name`, in any case.
|
||||
pub fn named<'a>(sets: &'a [KinsokuSet], name: &str) -> Option<&'a KinsokuSet> {
|
||||
sets.iter().find(|s| Self::same_name(&s.name, name))
|
||||
}
|
||||
|
||||
/// `name` trimmed, when it can name a custom set: not empty, at most [`KINSOKU_NAME_MAX`]
|
||||
/// characters, without control characters, and none of [`KINSOKU_BUILT_IN`] in any case.
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let ok = !name.is_empty()
|
||||
&& name.chars().count() <= KINSOKU_NAME_MAX
|
||||
&& !name.chars().any(char::is_control)
|
||||
&& !KINSOKU_BUILT_IN.iter().any(|b| Self::same_name(b, name));
|
||||
ok.then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// Can a category hold character `c`: not a control character nor a space?
|
||||
pub fn takes_char(c: char) -> bool {
|
||||
!c.is_control() && !c.is_whitespace()
|
||||
}
|
||||
|
||||
/// Can `s` be an inseparable sequence: [`KINSOKU_SEQUENCE`] characters that
|
||||
/// [`Self::takes_char`] takes?
|
||||
pub fn takes_sequence(s: &str) -> bool {
|
||||
KINSOKU_SEQUENCE.contains(&s.chars().count()) && s.chars().all(Self::takes_char)
|
||||
}
|
||||
|
||||
/// Sort each category and keep each character or sequence once.
|
||||
pub fn normalize(&mut self) {
|
||||
for list in [&mut self.cannot_start, &mut self.cannot_end, &mut self.hanging] {
|
||||
list.sort_unstable();
|
||||
list.dedup();
|
||||
}
|
||||
self.inseparable.sort_unstable();
|
||||
self.inseparable.dedup();
|
||||
}
|
||||
|
||||
/// Why this set can't be used, if it can't: a name [`Self::clean_name`] refuses, a character
|
||||
/// [`Self::takes_char`] refuses, a sequence [`Self::takes_sequence`] refuses, or a category of
|
||||
/// more than [`KINSOKU_CATEGORY_MAX`] characters.
|
||||
pub fn check(&self) -> Result<(), String> {
|
||||
if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) {
|
||||
return Err(format!(
|
||||
"`{}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)",
|
||||
self.name
|
||||
));
|
||||
}
|
||||
for (key, list) in [("cannotStart", &self.cannot_start), ("cannotEnd", &self.cannot_end), ("hanging", &self.hanging)] {
|
||||
if list.len() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("{key}: at most {KINSOKU_CATEGORY_MAX} characters"));
|
||||
}
|
||||
if let Some(c) = list.iter().find(|&&c| !Self::takes_char(c)) {
|
||||
return Err(format!("{key}: U+{:04X} is a control or space character", u32::from(*c)));
|
||||
}
|
||||
}
|
||||
if let Some(s) = self.inseparable.iter().find(|s| !Self::takes_sequence(s)) {
|
||||
return Err(format!(
|
||||
"inseparable: `{s}` must be {} to {} characters, none of them control or space characters",
|
||||
KINSOKU_SEQUENCE.start(),
|
||||
KINSOKU_SEQUENCE.end()
|
||||
));
|
||||
}
|
||||
if self.inseparable.iter().map(|s| s.chars().count()).sum::<usize>() > KINSOKU_CATEGORY_MAX {
|
||||
return Err(format!("inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// May `c` not start a line?
|
||||
pub fn cannot_start(&self, c: char) -> bool {
|
||||
self.cannot_start.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` not end a line?
|
||||
pub fn cannot_end(&self, c: char) -> bool {
|
||||
self.cannot_end.binary_search(&c).is_ok()
|
||||
}
|
||||
|
||||
/// May `c` hang outside a line's end (Burasagari)?
|
||||
pub fn hangs(&self, c: char) -> bool {
|
||||
self.hanging.binary_search(&c).is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::text::{Kinsoku, ParaStyle};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A set is saved with each category as one string and read back as it was; a paragraph saves
|
||||
/// its copy of the set beside Hard, and a paragraph saved without one reads with none.
|
||||
#[test]
|
||||
fn kinsoku_sets_are_saved_with_the_paragraphs_that_use_them() {
|
||||
let mut set = KinsokuSet {
|
||||
name: "Tight".into(),
|
||||
cannot_start: "」。、".chars().collect(),
|
||||
cannot_end: vec!['「'],
|
||||
hanging: vec!['、', '。'],
|
||||
inseparable: vec!["——".into(), "あいう".into()],
|
||||
};
|
||||
set.normalize();
|
||||
let saved = serde_json::to_value(&set).unwrap();
|
||||
assert_eq!(saved, json!({"name": "Tight", "cannotStart": "、。」", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——", "あいう"]}));
|
||||
assert_eq!(serde_json::from_value::<KinsokuSet>(saved).unwrap(), set);
|
||||
let p = ParaStyle { kinsoku_set: Some(Arc::new(set.clone())), ..ParaStyle::default() };
|
||||
let v = serde_json::to_value(&p).unwrap();
|
||||
assert_eq!(v["kinsoku_set"]["name"], "Tight");
|
||||
assert!(v.get("kinsoku").is_none(), "Hard, the default, is left out");
|
||||
let back: ParaStyle = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(back.kinsoku_set.as_deref(), Some(&set));
|
||||
assert_eq!((back.kinsoku, back.kinsoku_name(), back.kinsoku_on()), (Kinsoku::Hard, "Tight", true));
|
||||
let old: ParaStyle = serde_json::from_value(json!({"justify": "Left", "kinsoku": "soft"})).unwrap();
|
||||
assert_eq!((old.kinsoku_set, old.kinsoku), (None, Kinsoku::Soft));
|
||||
assert!(serde_json::to_value(ParaStyle::default()).unwrap().get("kinsoku_set").is_none());
|
||||
}
|
||||
|
||||
/// A set read from a file keeps only what a set can hold: each character once, sorted, without
|
||||
/// control or space characters, at most 4096 to a category, and sequences of 2 to 16
|
||||
/// characters; a category left out is empty. Only the start of a longer text is read.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_from_a_file_keep_what_a_set_can_hold() {
|
||||
let long: String = (0x4E00..0x4E00 + 5000).filter_map(char::from_u32).collect();
|
||||
let v = json!({
|
||||
"name": "Odd",
|
||||
"cannotStart": "ccba \t\u{0}a",
|
||||
"cannotEnd": long,
|
||||
"inseparable": ["a", "ab", "ab", "a b", "abcdefghijklmnopq", "abcdefghijklmnop"],
|
||||
});
|
||||
let set: KinsokuSet = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(set.cannot_start, ['a', 'b', 'c']);
|
||||
assert_eq!(set.cannot_end.len(), KINSOKU_CATEGORY_MAX);
|
||||
assert!(set.hanging.is_empty());
|
||||
assert_eq!(set.inseparable, ["ab", "abcdefghijklmnop"]);
|
||||
assert!(set.check().is_ok());
|
||||
let empty: KinsokuSet = serde_json::from_value(json!({})).unwrap();
|
||||
assert!(empty.check().is_err(), "a set needs a name");
|
||||
// Only the start of a long text is read: a category's first 16384 characters, a name of at
|
||||
// most 4096 characters, spaces included, and a sequence's first 17.
|
||||
let spaces = " ".repeat(CATEGORY_READ_MAX);
|
||||
let text = format!(
|
||||
r#"{{"name": "{}Tight", "hanging": "{spaces}、", "cannotEnd": "、", "inseparable": ["{}あ"]}}"#,
|
||||
" ".repeat(NAME_READ_MAX),
|
||||
"あ".repeat(100)
|
||||
);
|
||||
let set: KinsokuSet = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!((set.name.as_str(), set.hanging.len(), set.cannot_end.len(), set.inseparable.len()), ("", 0, 1, 0));
|
||||
let set: KinsokuSet = serde_json::from_str(&format!(r#"{{"name": "{}Tight"}}"#, " ".repeat(NAME_READ_MAX - 5))).unwrap();
|
||||
assert_eq!(set.name, "Tight");
|
||||
}
|
||||
|
||||
/// A set read from a file under a name a custom set can't take (a built-in name, a blank one)
|
||||
/// is not read: a paragraph holding it keeps its Kinsoku Set, so it doesn't show as Hard while
|
||||
/// composing by other characters, and a document's list drops it. The list also keeps the
|
||||
/// first set of each name in any case, and a name read with spaces around it is trimmed. A
|
||||
/// paragraph's set read beside None or Soft is not read either.
|
||||
#[test]
|
||||
fn kinsoku_sets_read_under_names_a_set_cannot_take_are_dropped() {
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": "Hard", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set, p.kinsoku), (None, Kinsoku::Hard));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku": "none", "kinsoku_set": {"name": "Tight", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!((p.kinsoku_set.is_none(), p.kinsoku_name()), (true, "None"));
|
||||
let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": " Tight ", "cannotStart": "あ"}})).unwrap();
|
||||
assert_eq!(p.kinsoku_name(), "Tight");
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
v["kinsoku_sets"] = json!([{"name": "soft"}, {"name": " "}, {"name": "Tight", "cannotEnd": "「"}, {"name": "TIGHT"}, {"name": "Loose"}]);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
let names: Vec<&str> = d.kinsoku_sets.iter().map(|s| s.name.as_str()).collect();
|
||||
assert_eq!(names, ["Tight", "Loose"]);
|
||||
assert_eq!(d.kinsoku_sets[0].cannot_end, ['「']);
|
||||
let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap();
|
||||
// The sets past the limit are skipped unread: one that isn't a set at all doesn't fail the
|
||||
// file.
|
||||
let mut list: Vec<serde_json::Value> = (0..KINSOKU_SETS_MAX + 5).map(|i| json!({"name": format!("S{i}")})).collect();
|
||||
list.push(json!("not a set"));
|
||||
v["kinsoku_sets"] = json!(list);
|
||||
let d: crate::Document = serde_json::from_value(v).unwrap();
|
||||
assert_eq!(d.kinsoku_sets.len(), KINSOKU_SETS_MAX);
|
||||
let past: Vec<String> = (0..KINSOKU_CATEGORY_MAX + 1).map(|i| format!("あ{i}")).chain(["x".to_string()]).collect();
|
||||
let mut seqs: Vec<serde_json::Value> = past.iter().map(|s| json!(s)).collect();
|
||||
seqs.push(json!(7));
|
||||
let set: KinsokuSet = serde_json::from_value(json!({"name": "Long", "inseparable": seqs})).unwrap();
|
||||
assert!(set.check().is_ok());
|
||||
}
|
||||
|
||||
/// A name is trimmed, 1 to 128 characters without control characters, and never None, Hard or
|
||||
/// Soft in any case; names match in any case.
|
||||
#[test]
|
||||
fn kinsoku_set_names_are_checked() {
|
||||
assert_eq!(KinsokuSet::clean_name(" Tight "), Some("Tight".into()));
|
||||
for bad in ["", " ", "hard", "SOFT", "None", "a\u{7}b", &"x".repeat(KINSOKU_NAME_MAX + 1)] {
|
||||
assert_eq!(KinsokuSet::clean_name(bad), None, "{bad:?}");
|
||||
}
|
||||
assert!(KinsokuSet::clean_name(&"漢".repeat(KINSOKU_NAME_MAX)).is_some());
|
||||
assert!(KinsokuSet::same_name("Tight", "tIGHT"));
|
||||
let sets = [KinsokuSet { name: "Tight".into(), ..Default::default() }];
|
||||
assert!(KinsokuSet::named(&sets, "TIGHT").is_some() && KinsokuSet::named(&sets, "Loose").is_none());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::char_style::CharStyle;
|
||||
use super::kinsoku_set::KinsokuSet;
|
||||
use super::tabs_lists::{ParaList, TabStop};
|
||||
use super::{Deserialize, Serialize};
|
||||
|
||||
@@ -256,14 +259,18 @@ pub struct ParaStyle {
|
||||
/// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top
|
||||
/// of one line's ideographic em box to the next.
|
||||
pub leading_model: LeadingModel,
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line
|
||||
/// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// Hanging punctuation (Paragraph panel menu › Burasagari): the Kinsoku Set's hanging
|
||||
/// punctuation ending a line may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before
|
||||
/// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding
|
||||
/// punctuation on, which opens with [`Burasagari::Forced`].
|
||||
pub burasagari: Burasagari,
|
||||
/// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a
|
||||
/// line.
|
||||
pub kinsoku: Kinsoku,
|
||||
/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) chosen in Kinsoku Set: a copy of
|
||||
/// the document's set of that name, which takes the place of [`Self::kinsoku`]. A paragraph
|
||||
/// with one keeps [`Kinsoku::Hard`] in `kinsoku`, which builds without custom sets read.
|
||||
pub kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
|
||||
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
|
||||
pub kinsoku_type: KinsokuShoriType,
|
||||
@@ -310,6 +317,21 @@ impl ParaStyle {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does kinsoku apply: a custom set, or a Kinsoku Set other than None?
|
||||
pub fn kinsoku_on(&self) -> bool {
|
||||
self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None
|
||||
}
|
||||
|
||||
/// The name Kinsoku Set shows: the custom set's, or None, Hard or Soft.
|
||||
pub fn kinsoku_name(&self) -> &str {
|
||||
match (&self.kinsoku_set, self.kinsoku) {
|
||||
(Some(set), _) => &set.name,
|
||||
(None, Kinsoku::None) => "None",
|
||||
(None, Kinsoku::Hard) => "Hard",
|
||||
(None, Kinsoku::Soft) => "Soft",
|
||||
}
|
||||
}
|
||||
|
||||
/// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a
|
||||
/// list at a level past the first, [`ParaList::level_indent`] more.
|
||||
pub fn laid_out_left_indent(&self) -> f64 {
|
||||
@@ -373,6 +395,8 @@ struct ParaStyleFile {
|
||||
burasagari: Burasagari,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku: Kinsoku,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
kinsoku_set: Option<Arc<KinsokuSet>>,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
|
||||
@@ -415,6 +439,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -443,6 +468,7 @@ impl From<ParaStyle> for ParaStyleFile {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -475,6 +501,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -483,6 +510,11 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
korean_line_break_anywhere,
|
||||
..
|
||||
} = f;
|
||||
// A set whose saved name can't name a custom set (None, Hard or Soft, say) is read as no set:
|
||||
// the paragraph keeps its Kinsoku Set. A paragraph with a custom set keeps Hard, so one read
|
||||
// with None or Soft (a paragraph style written before custom sets, applied over one) has no
|
||||
// custom set.
|
||||
let kinsoku_set = kinsoku_set.filter(|s| !s.name.is_empty() && kinsoku == Kinsoku::Hard);
|
||||
Self {
|
||||
justify,
|
||||
left_indent,
|
||||
@@ -502,6 +534,7 @@ impl From<ParaStyleFile> for ParaStyle {
|
||||
leading_model,
|
||||
burasagari,
|
||||
kinsoku,
|
||||
kinsoku_set,
|
||||
kinsoku_type,
|
||||
bunri_kinshi,
|
||||
kurikaeshi_moji_shori,
|
||||
@@ -604,19 +637,21 @@ pub enum KinsokuShoriType {
|
||||
PushOutOnly,
|
||||
}
|
||||
|
||||
/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。)
|
||||
/// stands outside the line's measure, in the space its punctuation spacing gives it (half width
|
||||
/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown
|
||||
/// as None / Regular / Force.
|
||||
/// Hanging punctuation (burasagari): hanging punctuation ending a line stands outside the line's
|
||||
/// measure, in the space its punctuation spacing gives it (half width with Line-end Punctuation
|
||||
/// Half Width). With the built-in Kinsoku Sets that is an East Asian comma or full stop
|
||||
/// (、。,.、。), and closing brackets and Latin punctuation don't hang; a custom Kinsoku Set hangs
|
||||
/// the characters in its hanging category. Shown as None / Regular / Force.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Burasagari {
|
||||
/// A comma or full stop that doesn't fit goes to the next line with the character before it.
|
||||
#[default]
|
||||
None,
|
||||
/// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside.
|
||||
/// Hanging punctuation that doesn't fit hangs outside the line; punctuation that fits stays
|
||||
/// inside.
|
||||
Standard,
|
||||
/// A comma or full stop ending a line always hangs, and the rest of the line fills the measure.
|
||||
/// Hanging punctuation ending a line always hangs, and the rest of the line fills the measure.
|
||||
Forced,
|
||||
}
|
||||
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
@@ -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",
|
||||
|
||||
@@ -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")),
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ mod vertical;
|
||||
mod warichu;
|
||||
|
||||
pub(crate) use bidi::{is_rtl, para_bidi, starts_bidi};
|
||||
pub(crate) use breaking::is_hanging_punctuation;
|
||||
use breaking::tab_advance;
|
||||
#[cfg(test)]
|
||||
use breaking::{break_line, candidates};
|
||||
|
||||
@@ -1,11 +1,76 @@
|
||||
use super::region::Region;
|
||||
use super::vertical::stands_upright;
|
||||
use super::{
|
||||
Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, SGlyph,
|
||||
hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start,
|
||||
Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, ParaStyle,
|
||||
SGlyph, hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start,
|
||||
};
|
||||
use crate::justify::is_format_control;
|
||||
|
||||
/// The kinsoku rules a paragraph is composed with: a built-in Kinsoku Set (None, Hard or Soft), or
|
||||
/// a custom set (Type › Kinsoku Shori Settings…).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) enum KinsokuRules<'a> {
|
||||
BuiltIn(Kinsoku),
|
||||
Custom(&'a vectorcraft_doc::KinsokuSet),
|
||||
}
|
||||
|
||||
impl<'a> KinsokuRules<'a> {
|
||||
/// The rules of paragraph `para`: its custom set when it has one, else its Kinsoku Set.
|
||||
pub(crate) fn of(para: &'a ParaStyle) -> Self {
|
||||
match ¶.kinsoku_set {
|
||||
Some(set) => Self::Custom(set),
|
||||
None => Self::BuiltIn(para.kinsoku),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kinsoku None: no character is kept off a line's ends, and Bunri-Kinshi has no effect.
|
||||
pub(crate) fn is_none(self) -> bool {
|
||||
matches!(self, Self::BuiltIn(Kinsoku::None))
|
||||
}
|
||||
|
||||
/// May `c` not start a line? Hard: every character of [`no_line_start`]; Soft: those
|
||||
/// [`soft_line_start`] doesn't let start one; a custom set: its Cannot Start Line characters.
|
||||
pub(crate) fn cannot_start(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(Kinsoku::None) => false,
|
||||
Self::BuiltIn(Kinsoku::Hard) => no_line_start(c),
|
||||
Self::BuiltIn(Kinsoku::Soft) => no_line_start(c) && !soft_line_start(c),
|
||||
Self::Custom(set) => set.cannot_start(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// May `c` not end a line? Hard and Soft: an opening bracket ([`no_line_end`]); a custom set:
|
||||
/// its Cannot End Line characters.
|
||||
pub(crate) fn cannot_end(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(Kinsoku::None) => false,
|
||||
Self::BuiltIn(Kinsoku::Hard | Kinsoku::Soft) => no_line_end(c),
|
||||
Self::Custom(set) => set.cannot_end(c),
|
||||
}
|
||||
}
|
||||
|
||||
/// May `c` hang outside a line's end with Burasagari? An East Asian comma or full stop (、。,.
|
||||
/// and the half-width 、。), or a custom set's Hanging Punctuation characters.
|
||||
pub(crate) fn hangs(self, c: char) -> bool {
|
||||
match self {
|
||||
Self::BuiltIn(_) => is_hanging_punctuation(c),
|
||||
Self::Custom(set) => set.hangs(c),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Kinsoku> for KinsokuRules<'_> {
|
||||
fn from(k: Kinsoku) -> Self {
|
||||
Self::BuiltIn(k)
|
||||
}
|
||||
}
|
||||
|
||||
/// The punctuation Burasagari hangs with the built-in Kinsoku Sets: the East Asian comma and full
|
||||
/// stop, full width and half width.
|
||||
pub(crate) fn is_hanging_punctuation(c: char) -> bool {
|
||||
matches!(c, '、' | '。' | ',' | '.' | '、' | '。')
|
||||
}
|
||||
|
||||
/// Vertical metrics of a line: (ascent, descent, leading, cap height, x height).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Metrics {
|
||||
@@ -351,12 +416,13 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64,
|
||||
/// Width of the word starting at glyph `i`: its advances up to the first place a line may break
|
||||
/// (spaces left out, the hyphen of a soft hyphen in), the least room a line needs not to break
|
||||
/// inside it. As in [`break_line`], kinsoku keeps a character that may not end a line with the one
|
||||
/// after it, a No Break run (its spaces inside it included) is one word up to a forced line break,
|
||||
/// after it, spaces between them included, a No Break run (its spaces inside it included) is one word up to a forced line break,
|
||||
/// and a cluster is never split. A soft hyphen just before a forced line break adds no hyphen. A list marker at `i` (glyphs of length 0) counts whole, with the word after it. A word
|
||||
/// that ends where a line may end is measured as the line is set: without the spaces at its end,
|
||||
/// and with its last glyph as narrow as `line_end` sets it; one that ends at a soft hyphen or past
|
||||
/// the measured glyphs is not.
|
||||
pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kinsoku) -> f64 {
|
||||
/// the measured glyphs is not. With `burasagari`, the word may end after hanging punctuation.
|
||||
pub(super) fn word_width<'k>(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: impl Into<KinsokuRules<'k>>, burasagari: Burasagari) -> f64 {
|
||||
let kinsoku = kinsoku.into();
|
||||
/// Glyphs measured at most: a word wrapped over many lines is measured again from each line's
|
||||
/// start, and one this long is broken inside whatever cell it meets.
|
||||
const MAX_GLYPHS: usize = 1024;
|
||||
@@ -375,7 +441,15 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
if gl.is_space() && (end == start || !splits_no_break(g, end)) {
|
||||
return set(w, trailing, ink);
|
||||
// A line breaks after one of these spaces only where kinsoku allows it, as in
|
||||
// [`break_line`]; where it allows none (after 「, or before 」), the word goes on past them.
|
||||
let run = end + g[end..].iter().take(start + MAX_GLYPHS - end).take_while(|h| h.is_space()).count();
|
||||
if end == start || (end..run).any(|k| g[k].break_after() && g[k].len > 0 && kinsoku_allows(g, k, kinsoku) && !splits_no_break(g, k + 1)) {
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
let spaces: f64 = g[end..run].iter().map(|h| h.adv).sum();
|
||||
(w, trailing, end) = (w + spaces, trailing + spaces, run);
|
||||
continue;
|
||||
}
|
||||
let forced_next = g.get(end + 1).is_some_and(|n| n.ch == '\u{2028}');
|
||||
if gl.is_soft_hyphen() && !forced_next && kinsoku_allows(g, end, kinsoku) && !splits_no_break(g, end + 1) {
|
||||
@@ -389,7 +463,10 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins
|
||||
(trailing, ink) = (0.0, end);
|
||||
}
|
||||
let cluster_ends = g.get(end).is_none_or(|next| next.byte != gl.byte);
|
||||
if gl.break_after() && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) {
|
||||
// Hanging punctuation of one glyph may end the line with Burasagari, as in [`break_line`].
|
||||
let alone = cluster_ends && end.checked_sub(2).and_then(|k| g.get(k)).is_none_or(|p| p.byte != gl.byte);
|
||||
let hang_break = burasagari != Burasagari::None && alone && hangs(gl, kinsoku);
|
||||
if (gl.break_after() || hang_break) && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) {
|
||||
return set(w, trailing, ink);
|
||||
}
|
||||
}
|
||||
@@ -442,7 +519,7 @@ fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool {
|
||||
/// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits
|
||||
/// as drawn.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn break_line(
|
||||
pub(super) fn break_line<'k>(
|
||||
text: &str,
|
||||
g: &[SGlyph],
|
||||
i: usize,
|
||||
@@ -451,13 +528,14 @@ pub(super) fn break_line(
|
||||
x_start: f64,
|
||||
hyphenate: Option<(&HyphenationOptions, f64)>,
|
||||
burasagari: Burasagari,
|
||||
kinsoku: Kinsoku,
|
||||
kinsoku: impl Into<KinsokuRules<'k>>,
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
hanging: bool,
|
||||
vertical: bool,
|
||||
line_end: &[f64],
|
||||
fits: Option<&dyn Fn(usize, bool) -> bool>,
|
||||
) -> (usize, bool) {
|
||||
let kinsoku = kinsoku.into();
|
||||
let settle = |tabbed: bool, checks: usize, chosen: (usize, bool), breaks: &[(usize, bool)]| {
|
||||
craft_font_catalog::settle_line_break(tabbed, checks, i, chosen, breaks, fits)
|
||||
};
|
||||
@@ -551,13 +629,14 @@ pub(super) fn break_line(
|
||||
let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width };
|
||||
overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS;
|
||||
if j > first && !gl.is_space() && measured - end_credit > width + EPS {
|
||||
// It ends the line with the spaces after it, when the mark is all the characters kept
|
||||
// together (the line's last character is the mark, which is what hangs). Once the line
|
||||
// holds a tab and is measured as drawn, the mark hangs only where it is drawn at the
|
||||
// line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and
|
||||
// the line before it fits as drawn with no line-end trim on its last glyph; otherwise the
|
||||
// line ends at a legal break that fits as drawn.
|
||||
let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte);
|
||||
// It ends the line with the spaces after it, when it hangs alone: not with the rest of a
|
||||
// No Break run or an inseparable sequence it starts, and only as one glyph, the one the
|
||||
// line's geometry hangs. Once the line holds a tab and is measured as drawn, the mark
|
||||
// hangs only where it is drawn at the line's right end (its cluster is last in the
|
||||
// line's visual order, [`drawn_last`]) and the line before it fits as drawn with no
|
||||
// line-end trim on its last glyph; otherwise the line ends at a legal break that fits as
|
||||
// drawn.
|
||||
let alone = cluster_end == j + 1;
|
||||
let hangs_as_drawn = || match fits.filter(|_| tabbed) {
|
||||
None => true,
|
||||
Some(fits) => {
|
||||
@@ -568,7 +647,7 @@ pub(super) fn break_line(
|
||||
drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false)
|
||||
}
|
||||
};
|
||||
if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() {
|
||||
if burasagari != Burasagari::None && alone && hangs(gl, kinsoku) && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() {
|
||||
let mut end = cluster_end;
|
||||
while g.get(end).is_some_and(SGlyph::is_space) {
|
||||
end += 1;
|
||||
@@ -586,7 +665,10 @@ pub(super) fn break_line(
|
||||
ink += cluster_ink;
|
||||
back += cluster_back;
|
||||
let last = &g[cluster_end - 1];
|
||||
if last.break_after() && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) {
|
||||
// Hanging punctuation that would hang alone where it overflows may end the line where it
|
||||
// fits too: a custom set's may be a character no other rule breaks after.
|
||||
let hang_break = burasagari != Burasagari::None && cluster_end == j + 1 && hangs(last, kinsoku);
|
||||
if (last.break_after() || hang_break) && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) {
|
||||
// Once the line holds a tab, whether a break fits as drawn is settled when the line ends.
|
||||
let hyphenated = last.is_soft_hyphen();
|
||||
if !hyphenated || (tabbed && fits.is_some()) || x + hyphen_glyph(last).adv <= width + EPS {
|
||||
@@ -661,11 +743,12 @@ pub(super) fn break_line(
|
||||
}
|
||||
|
||||
/// Can glyph `g` hang outside the line (burasagari)? An East Asian comma or full stop, full width
|
||||
/// (、。,.) or half width (、。); not a closing bracket, nor Latin punctuation (Latin text keeps
|
||||
/// its line breaks and composer). Never an inline graphic (U+FFFC), nor a character of a
|
||||
/// tate-chu-yoko or warichu block.
|
||||
pub(super) fn hangs(g: &SGlyph) -> bool {
|
||||
g.inline.is_none() && matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none() && g.wari.is_none()
|
||||
/// (、。,.) or half width (、。), or with a custom set a character of its Hanging Punctuation
|
||||
/// ([`KinsokuRules::hangs`]); with the built-in sets not a closing bracket, nor Latin punctuation
|
||||
/// (Latin text keeps its line breaks and composer). Never an inline graphic (U+FFFC), nor a
|
||||
/// character of a tate-chu-yoko or warichu block.
|
||||
pub(super) fn hangs(g: &SGlyph, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
g.inline.is_none() && kinsoku.hangs(g.ch) && g.tcy.is_none() && g.wari.is_none()
|
||||
}
|
||||
|
||||
/// Optical Margin Alignment: the share of glyph `g`'s advance that hangs outside the margin when
|
||||
@@ -755,7 +838,7 @@ fn line_end_credit(g: &[SGlyph], line_end: &[f64], end: usize) -> f64 {
|
||||
|
||||
/// May [`break_line`] end a line after glyph `end - 1` (and the spaces after it)? At the paragraph's
|
||||
/// end or a forced line break, and where it records a break without a hyphen.
|
||||
fn may_end_after(g: &[SGlyph], end: usize, kinsoku: Kinsoku) -> bool {
|
||||
fn may_end_after(g: &[SGlyph], end: usize, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
let mut e = end;
|
||||
while g.get(e).is_some_and(SGlyph::is_space) {
|
||||
e += 1;
|
||||
@@ -775,20 +858,25 @@ fn splits_no_break(g: &[SGlyph], end: usize) -> bool {
|
||||
|
||||
/// Does kinsoku allow a line break after glyph `j`? Not after an opening bracket, nor before a
|
||||
/// closing one, a comma, a full stop, a small kana… (the character is pushed to the next line
|
||||
/// with the one before it).
|
||||
fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: Kinsoku) -> bool {
|
||||
g.get(j).is_some_and(|gl| kinsoku_between(gl.ch, g.get(j + 1).map(|n| n.ch), kinsoku))
|
||||
/// with the one before it). A line that breaks after spaces is drawn without them, so the
|
||||
/// character before them is the one that ends it: up to [`KINSOKU_SPACES_BACK`] spaces are looked
|
||||
/// past, and after a longer run of spaces the space itself counts.
|
||||
fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
let Some(gl) = g.get(j) else { return false };
|
||||
let before = if gl.is_space() { g[..j].iter().rev().take(KINSOKU_SPACES_BACK).find(|h| !h.is_space()).map_or(gl.ch, |h| h.ch) } else { gl.ch };
|
||||
kinsoku_between(before, g.get(j + 1).map(|n| n.ch), kinsoku)
|
||||
}
|
||||
|
||||
/// The most spaces [`kinsoku_allows`] looks past for the character that ends a line, so a long run
|
||||
/// of spaces is not read again at each of its breaks.
|
||||
const KINSOKU_SPACES_BACK: usize = 64;
|
||||
|
||||
/// Kinsoku for a break between `before` and `after` (none: the end of the paragraph): Hard keeps
|
||||
/// every character of the set off the line start and end, Soft lets 々, ー and small kana start a
|
||||
/// line, None allows the break.
|
||||
fn kinsoku_between(before: char, after: Option<char>, kinsoku: Kinsoku) -> bool {
|
||||
match kinsoku {
|
||||
Kinsoku::None => true,
|
||||
Kinsoku::Hard => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c)),
|
||||
Kinsoku::Soft => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c) || soft_line_start(c)),
|
||||
}
|
||||
/// line, a custom set keeps its own characters off them ([`KinsokuRules`]), and None allows the
|
||||
/// break.
|
||||
fn kinsoku_between(before: char, after: Option<char>, kinsoku: KinsokuRules<'_>) -> bool {
|
||||
!kinsoku.cannot_end(before) && after.is_none_or(|c| !kinsoku.cannot_start(c))
|
||||
}
|
||||
|
||||
/// The share of an em by which a push-in ([`push_in`]) may close each gap next to a CJK character
|
||||
@@ -823,13 +911,13 @@ fn push_in(
|
||||
x: f64,
|
||||
width: f64,
|
||||
pushed_out: Option<usize>,
|
||||
kinsoku: Kinsoku,
|
||||
kinsoku: KinsokuRules<'_>,
|
||||
kinsoku_type: KinsokuShoriType,
|
||||
hanging: bool,
|
||||
vertical: bool,
|
||||
line_end: &[f64],
|
||||
) -> Option<usize> {
|
||||
if kinsoku == Kinsoku::None || kinsoku_type == KinsokuShoriType::PushOutOnly {
|
||||
if kinsoku.is_none() || kinsoku_type == KinsokuShoriType::PushOutOnly {
|
||||
return None;
|
||||
}
|
||||
let before = g.get(j.checked_sub(1)?)?;
|
||||
@@ -933,13 +1021,30 @@ pub(super) fn squeeze_em(g: &SGlyph, vertical: bool) -> f64 {
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() {
|
||||
let hard = KinsokuRules::BuiltIn(Kinsoku::Hard);
|
||||
for (a, b) in [('字', '。'), ('弧', '」'), ('」', '、'), ('ャ', 'ー'), ('カ', 'ッ'), ('「', 'か'), ('(', '雅')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
}
|
||||
for (a, b) in [('。', '雅'), ('」', 'は'), ('字', '「'), ('の', '演')] {
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
}
|
||||
assert!(kinsoku_between('。', None, Kinsoku::Hard));
|
||||
assert!(kinsoku_between('。', None, hard));
|
||||
}
|
||||
|
||||
/// A custom set keeps its own characters off a line's ends, and nothing else: here 字 may not
|
||||
/// start a line and 弧 may not end one, while 。 and 「 may.
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn a_custom_kinsoku_set_keeps_its_own_characters_off_line_ends() {
|
||||
let mut set = vectorcraft_doc::KinsokuSet { name: "Custom".into(), cannot_start: vec!['字'], cannot_end: vec!['弧'], ..Default::default() };
|
||||
set.normalize();
|
||||
let custom = KinsokuRules::Custom(&set);
|
||||
assert!(!kinsoku_between('の', Some('字'), custom));
|
||||
assert!(!kinsoku_between('弧', Some('の'), custom));
|
||||
for (a, b) in [('字', '。'), ('「', 'か'), ('字', 'の')] {
|
||||
assert!(kinsoku_between(a, Some(b), custom), "{a}{b}");
|
||||
}
|
||||
assert!(!custom.is_none());
|
||||
}
|
||||
|
||||
/// Soft kinsoku lets 々, ー and small kana (JLREQ cl-09's 々, cl-10, cl-11) start a line and keeps
|
||||
@@ -947,13 +1052,14 @@ fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends()
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() {
|
||||
let [none, hard, soft] = [Kinsoku::None, Kinsoku::Hard, Kinsoku::Soft].map(KinsokuRules::BuiltIn);
|
||||
for (a, b) in [('ャ', 'ー'), ('カ', 'ッ'), ('時', '々'), ('ト', 'ㇰ'), ('か', 'ゃ')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), soft), "{a}{b}");
|
||||
}
|
||||
for (a, b) in [('字', '。'), ('弧', '」'), ('「', 'か'), ('カ', 'ッ'), ('カ', 'ー'), ('字', 'ゝ')] {
|
||||
assert!(!kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), Kinsoku::None), "{a}{b}");
|
||||
assert!(!kinsoku_between(a, Some(b), soft), "{a}{b}");
|
||||
assert!(kinsoku_between(a, Some(b), none), "{a}{b}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1001,7 +1107,13 @@ fn word_hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyp
|
||||
/// paragraph's Hyphenation options) when it is given. No break comes before a space: a line that
|
||||
/// may end after a dash, a Thai word or a space ends after the spaces that follow it, as in
|
||||
/// [`break_line`].
|
||||
pub(super) fn candidates(text: &str, g: &[SGlyph], hyphenate: Option<&HyphenationOptions>, kinsoku: Kinsoku) -> Vec<Breakpoint> {
|
||||
pub(super) fn candidates<'k>(
|
||||
text: &str,
|
||||
g: &[SGlyph],
|
||||
hyphenate: Option<&HyphenationOptions>,
|
||||
kinsoku: impl Into<KinsokuRules<'k>>,
|
||||
) -> Vec<Breakpoint> {
|
||||
let kinsoku = kinsoku.into();
|
||||
let mut v = vec![];
|
||||
let mut ws = 0;
|
||||
for (j, gl) in g.iter().enumerate() {
|
||||
|
||||
@@ -1,25 +1,32 @@
|
||||
use super::bidi::{is_rtl, para_bidi_with, visual_order};
|
||||
use super::breaking::{
|
||||
Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, optical_hangs_rtl,
|
||||
optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width,
|
||||
KinsokuRules, Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs,
|
||||
optical_hangs_rtl, optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width,
|
||||
};
|
||||
use super::region::Region;
|
||||
use super::vertical::{
|
||||
EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin,
|
||||
};
|
||||
use super::{
|
||||
Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker,
|
||||
ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph,
|
||||
is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics,
|
||||
Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, ParaStyle,
|
||||
Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, is_cjk,
|
||||
is_word_space, kashida, mark_word_ends, style_metrics,
|
||||
};
|
||||
use crate::justify::is_format_control;
|
||||
use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range};
|
||||
use crate::shape::{keep_inseparable_pairs, keep_inseparable_sequences, keep_korean_words, repeat_base, repeated_char, shape_range};
|
||||
use std::cell::Cell;
|
||||
|
||||
/// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First,
|
||||
/// with kinsoku on)?
|
||||
fn pushes_in(para: &ParaStyle) -> bool {
|
||||
para.kinsoku != Kinsoku::None && para.kinsoku_type != KinsokuShoriType::PushOutOnly
|
||||
!KinsokuRules::of(para).is_none() && para.kinsoku_type != KinsokuShoriType::PushOutOnly
|
||||
}
|
||||
|
||||
/// May paragraph `para` push one of glyphs `sg` in onto a line: does it push characters in, and
|
||||
/// hold a character its kinsoku rules keep off a line's start or end?
|
||||
pub(super) fn may_push_in(para: &ParaStyle, sg: &[SGlyph]) -> bool {
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
pushes_in(para) && sg.iter().any(|g| kinsoku.cannot_start(g.ch) || kinsoku.cannot_end(g.ch))
|
||||
}
|
||||
|
||||
/// Paragraphs longer than this (glyphs) are always broken line by line.
|
||||
@@ -55,9 +62,10 @@ fn compose_para(
|
||||
let composer = cx.opts.composer.unwrap_or(para.composer);
|
||||
// A paragraph whose commas or full stops may hang is composed line by line (as the Japanese
|
||||
// single-line composer does).
|
||||
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs);
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
let may_hang = para.burasagari != Burasagari::None && sg.iter().any(|g| hangs(g, kinsoku));
|
||||
// So is a paragraph that may push characters kinsoku keeps off a line's ends in onto a line.
|
||||
let may_push_in = pushes_in(para) && sg.iter().any(|g| no_line_start(g.ch) || no_line_end(g.ch));
|
||||
let may_push_in = may_push_in(para, sg);
|
||||
// A tab's width depends on where it falls in its line, which the composer's fixed glyph widths
|
||||
// can't follow: such a paragraph is broken line by line ([`break_line`] measures its tabs).
|
||||
// The tab of a list marker is on the first line, with the marker, and has a fixed width.
|
||||
@@ -100,7 +108,7 @@ fn compose_para(
|
||||
// Only the first line's first word is known here. Later lines are placed as the composed
|
||||
// lines need: each fits its width, so its first word does too. It is measured as the line
|
||||
// loop measures it, with Mojikumi's narrower start and end.
|
||||
let word = if first { word_width(sg, 0, line_end, para.kinsoku) - start_credit(0) } else { 0.0 };
|
||||
let word = if first { word_width(sg, 0, line_end, kinsoku, para.burasagari) - start_credit(0) } else { 0.0 };
|
||||
let Some((b, x0, x1, _)) = sim.place(m, ind_l, para.right_indent, word) else { break };
|
||||
let w = x1 - x0 - ind_l - para.right_indent;
|
||||
widths.push(w);
|
||||
@@ -119,7 +127,7 @@ fn compose_para(
|
||||
let width = |k: usize| widths.get(k).copied().unwrap_or(last);
|
||||
// Lines from `uniform_from` on are interchangeable (same width).
|
||||
let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1);
|
||||
let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), para.kinsoku);
|
||||
let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), kinsoku);
|
||||
let justify_last = para.justify == Justify::JustifyAll;
|
||||
let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX);
|
||||
let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from, hyphen_limit };
|
||||
@@ -277,8 +285,12 @@ fn prepare_paragraph<'a, 'text>(
|
||||
keep_korean_words(&mut sg);
|
||||
}
|
||||
// Bunri-Kinshi keeps inseparable pairs on one line, while kinsoku is on.
|
||||
if para.bunri_kinshi && para.kinsoku != Kinsoku::None {
|
||||
keep_inseparable_pairs(text, &mut sg);
|
||||
// A custom set keeps its own inseparable sequences instead.
|
||||
match KinsokuRules::of(para) {
|
||||
_ if !para.bunri_kinshi => {}
|
||||
KinsokuRules::Custom(set) => keep_inseparable_sequences(text, &mut sg, &set.inseparable),
|
||||
rules if !rules.is_none() => keep_inseparable_pairs(text, &mut sg),
|
||||
_ => {}
|
||||
}
|
||||
// Japanese composition (the paragraph's Mojikumi set): every punctuation mark set half width,
|
||||
// or consecutive punctuation sharing one half-em space…
|
||||
@@ -442,7 +454,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
|
||||
glyph.lead += half;
|
||||
}
|
||||
// The line's first word, as narrow as the line sets it at both ends.
|
||||
let word = word_width(sg, *i, line_end, para.kinsoku);
|
||||
let kinsoku = KinsokuRules::of(para);
|
||||
let word = word_width(sg, *i, line_end, kinsoku, para.burasagari);
|
||||
// A composed line in a frame whose lines are not all as wide is placed at its own tallest
|
||||
// metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height.
|
||||
let composed_line = composed.as_ref().and_then(|lines| lines.get(*para_line)).is_some_and(|&(end, _)| end > *i);
|
||||
@@ -502,7 +515,7 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC
|
||||
// A right-to-left paragraph draws a burasagari mark inside its line
|
||||
// ([`prepare_line_geometry`]): the line ends where it fits with the mark.
|
||||
if *rtl { Burasagari::None } else { para.burasagari },
|
||||
para.kinsoku,
|
||||
kinsoku,
|
||||
ty,
|
||||
*hanging,
|
||||
cx.vertical,
|
||||
@@ -782,7 +795,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData
|
||||
let hang = (paragraph.regions.is_some() && !paragraph.rtl && hyphen.is_none() && trimmed > index + 1)
|
||||
.then(|| sg.get(trimmed - 1))
|
||||
.flatten()
|
||||
.filter(|g| hangs(g))
|
||||
.filter(|g| hangs(g, KinsokuRules::of(para)))
|
||||
.map(|g| g.adv - end_trim)
|
||||
.filter(|_| match para.burasagari {
|
||||
Burasagari::None => false,
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::breaking::{Metrics, Pen, word_width};
|
||||
use super::breaking::{KinsokuRules, Metrics, Pen, word_width};
|
||||
use super::flow::line_indents;
|
||||
use super::{ParaStyle, SGlyph};
|
||||
use crate::composer::{Exhausted, Measure};
|
||||
@@ -278,7 +278,7 @@ fn past_end<'r>(p: &Para<'_>, start: &Start<'r>) -> Option<Placed<'r>> {
|
||||
/// frame's end ([`past_end`]) when no frame cell has room for it.
|
||||
fn place<'r>(p: &Para<'_>, start: &Start<'r>, m: Metrics) -> Result<Option<Placed<'r>>, Exhausted> {
|
||||
let (ind_l, ind_r) = line_indents(p.para, start.first, p.mirror);
|
||||
let word = word_width(p.sg, start.pos, p.line_end, p.para.kinsoku) - (p.start_credit)(start.pos);
|
||||
let word = word_width(p.sg, start.pos, p.line_end, KinsokuRules::of(p.para), p.para.burasagari) - (p.start_credit)(start.pos);
|
||||
let mut pen = start.pen.clone();
|
||||
loop {
|
||||
match pen.place(m, ind_l, ind_r, word) {
|
||||
|
||||
@@ -300,12 +300,12 @@ fn word_width_measures_across_a_soft_hyphen_inside_a_no_break_run() {
|
||||
for g in &mut glyphs {
|
||||
g.sx = 0.001;
|
||||
}
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!(plain < 30.0, "without the mark the word ends at the soft hyphen: {plain}");
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 30.0).abs() < 1e-9, "the marked run is measured whole: {marked}");
|
||||
}
|
||||
|
||||
@@ -317,7 +317,7 @@ fn word_width_stops_at_a_forced_line_break() {
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}");
|
||||
|
||||
let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 3, 5.0, '\u{2028}'), (6, 1, 10.0, 'B')]);
|
||||
@@ -325,12 +325,12 @@ fn word_width_stops_at_a_forced_line_break() {
|
||||
for g in &mut glyphs {
|
||||
g.sx = 0.001;
|
||||
}
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((plain - 10.0).abs() < 1e-9, "no hyphen before the forced line break: {plain}");
|
||||
for g in &mut glyphs {
|
||||
g.no_break = true;
|
||||
}
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None);
|
||||
let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None);
|
||||
assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}");
|
||||
}
|
||||
|
||||
@@ -1342,8 +1342,8 @@ fn korean_words_break_at_spaces_unless_line_break_anywhere() {
|
||||
let cands = candidates(text, &off, None, Kinsoku::Hard);
|
||||
assert_eq!(compose(&off, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms), Some(vec![(4, false), (7, false)]));
|
||||
// The first word is measured whole, as the line loop measures it.
|
||||
assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard), 30.0);
|
||||
assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard), 10.0);
|
||||
assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard, Burasagari::None), 30.0);
|
||||
assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0);
|
||||
// A word wider than the line still breaks, at the syllable that overflows.
|
||||
assert_eq!(greedy(&korean("가나다라마바", false), 25.0), 2);
|
||||
// A soft return still ends the line.
|
||||
@@ -1449,8 +1449,8 @@ fn bunri_kinshi_keeps_jlreq_pairs_in_both_composers() {
|
||||
};
|
||||
assert_eq!(greedy(&pairs(text, false), 35.0), 3, "off: the line ends between the dashes");
|
||||
assert_eq!(greedy(&pairs(text, true), 35.0), 2, "on: both dashes go to the next line");
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard), 20.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard), 10.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard, Burasagari::None), 20.0);
|
||||
assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0);
|
||||
let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 };
|
||||
let on = pairs("あい——う", true);
|
||||
let cands = candidates("あい——う", &on, None, Kinsoku::Hard);
|
||||
@@ -1500,6 +1500,241 @@ fn bunri_kinshi_progresses_with_an_overlong_pair_and_no_break() {
|
||||
assert_eq!(line(text, &pairs(text, true), 0, 46.5, Kinsoku::Hard, PushInFirst), 3);
|
||||
}
|
||||
|
||||
/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) with these categories.
|
||||
fn custom_set(cannot_start: &str, cannot_end: &str, hanging: &str, inseparable: &[&str]) -> vectorcraft_doc::KinsokuSet {
|
||||
let mut set = vectorcraft_doc::KinsokuSet {
|
||||
name: "Custom".into(),
|
||||
cannot_start: cannot_start.chars().collect(),
|
||||
cannot_end: cannot_end.chars().collect(),
|
||||
hanging: hanging.chars().collect(),
|
||||
inseparable: inseparable.iter().map(|s| s.to_string()).collect(),
|
||||
};
|
||||
set.normalize();
|
||||
set
|
||||
}
|
||||
|
||||
/// New Set from Hard or Soft starts with their characters: a custom set made from either breaks
|
||||
/// every line where it does, in both composers, with every Kinsoku Shori Type and with and without
|
||||
/// Burasagari, and keeps the same inseparable pairs with Bunri-Kinshi. One made from None is empty.
|
||||
#[test]
|
||||
fn a_set_made_from_hard_or_soft_breaks_lines_as_they_do() {
|
||||
use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly};
|
||||
let texts = ["一二三四五六七八九十一二三四五」六", "あカッー々ャ「か」、。(雅)", "あい——う〳〵え……カッー", "一二三四(五六)ab\u{201c}c\u{201d}。"];
|
||||
for base in [Kinsoku::Hard, Kinsoku::Soft] {
|
||||
let set = crate::shape::kinsoku_set_from(base, "From");
|
||||
let custom = breaking::KinsokuRules::Custom(&set);
|
||||
for text in texts {
|
||||
let mut built_in = full_width(text);
|
||||
crate::shape::keep_inseparable_pairs(text, &mut built_in);
|
||||
let mut own = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut own, &set.inseparable);
|
||||
let kept = |g: &[SGlyph]| g.iter().map(|g| g.keeps_next).collect::<Vec<_>>();
|
||||
assert_eq!(kept(&built_in), kept(&own), "{base:?} {text}");
|
||||
let ends = |c: Vec<Breakpoint>| c.iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends(candidates(text, &built_in, None, base)), ends(candidates(text, &own, None, custom)), "{base:?} {text}");
|
||||
for ty in [PushInFirst, PushOutFirst, PushOutOnly] {
|
||||
for burasagari in [Burasagari::None, Burasagari::Standard] {
|
||||
for width in (15..=160).step_by(5).map(f64::from) {
|
||||
let at = |g: &[SGlyph], k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, g, 0, width, &[], 0.0, None, burasagari, k, ty, false, false, &[], None).0
|
||||
};
|
||||
assert_eq!(at(&built_in, base.into()), at(&own, custom), "{base:?} {ty:?} {burasagari:?} {width} {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let empty = crate::shape::kinsoku_set_from(Kinsoku::None, "Empty");
|
||||
assert!(empty.cannot_start.is_empty() && empty.cannot_end.is_empty() && empty.hanging.is_empty() && empty.inseparable.is_empty());
|
||||
}
|
||||
|
||||
/// A custom set keeps its own Cannot Start Line characters off a line's start and its Cannot End
|
||||
/// Line characters off its end, and lets every other character start or end one: here 四 never
|
||||
/// starts a line and 三 never ends one, while 」, which Hard keeps off a line's start, may start
|
||||
/// one with an empty set.
|
||||
#[test]
|
||||
fn a_custom_set_keeps_its_own_characters_off_line_ends() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let end = |text: &str, width: f64, k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
let text = "一二三四五六";
|
||||
let start = custom_set("四", "", "", &[]);
|
||||
let finish = custom_set("", "三", "", &[]);
|
||||
let empty = custom_set("", "", "", &[]);
|
||||
assert_eq!(end(text, 35.0, Kinsoku::Hard.into()), 3);
|
||||
assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&start)), 2, "四 does not start the next line");
|
||||
assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line");
|
||||
let bracket = "一二三」四";
|
||||
assert_eq!(end(bracket, 35.0, Kinsoku::Hard.into()), 2, "Hard keeps 」 off the next line's start");
|
||||
assert_eq!(end(bracket, 35.0, breaking::KinsokuRules::Custom(&empty)), 3, "the empty set lets 」 start it");
|
||||
// A space after 三 is not drawn at the end of the line, so a break after it would still end
|
||||
// the line with 三.
|
||||
let spaced = "一二三 四";
|
||||
assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line before a space");
|
||||
assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&empty)), 4);
|
||||
let ends = candidates(text, &full_width(text), None, breaking::KinsokuRules::Custom(&start)).iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends, [1, 2, 4, 5]);
|
||||
}
|
||||
|
||||
/// The least room a word needs ([`breaking::word_width`]) runs past spaces where kinsoku allows no
|
||||
/// break after them, to the first break [`break_line`] may take: after 「 or a custom set's 三 with
|
||||
/// spaces after it, and before a 」 that follows a space. Where the break after the space is
|
||||
/// allowed, the word still ends before the space.
|
||||
#[test]
|
||||
fn word_width_runs_past_spaces_kinsoku_does_not_break_after() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let finish = custom_set("", "三", "", &[]);
|
||||
let empty = custom_set("", "", "", &[]);
|
||||
for (text, k, word) in [
|
||||
("「 四五", breaking::KinsokuRules::from(Kinsoku::Hard), 30.0),
|
||||
("「 四五", Kinsoku::Hard.into(), 40.0),
|
||||
("a 」二", Kinsoku::Hard.into(), 30.0),
|
||||
("三 四五", breaking::KinsokuRules::Custom(&finish), 30.0),
|
||||
("三 四五", breaking::KinsokuRules::Custom(&empty), 10.0),
|
||||
("一 二三", Kinsoku::Hard.into(), 10.0),
|
||||
] {
|
||||
let g = full_width(text);
|
||||
assert_eq!(breaking::word_width(&g, 0, &[], k, Burasagari::None), word, "{text}");
|
||||
// In a measure that wide, break_line's first line is that word, drawn without the spaces
|
||||
// at its end.
|
||||
let mut end = break_line(text, &g, 0, word, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0;
|
||||
while end > 0 && g[end - 1].is_space() {
|
||||
end -= 1;
|
||||
}
|
||||
assert_eq!(g[..end].iter().map(|h| h.adv).sum::<f64>(), word, "{text}");
|
||||
}
|
||||
// A No Break run of spaces after 「 longer than the glyphs a word is measured over stops the
|
||||
// measure there.
|
||||
let long: String = std::iter::once('「').chain(std::iter::repeat_n(' ', 2000)).chain(['四']).collect();
|
||||
let mut g = full_width(&long);
|
||||
for h in g.iter_mut().skip(1) {
|
||||
h.no_break = true;
|
||||
}
|
||||
assert_eq!(breaking::word_width(&g, 0, &[], Kinsoku::Hard, Burasagari::None), 10240.0);
|
||||
}
|
||||
|
||||
/// Soft and a set made from it choose the same composer: small kana and the prolonged sound mark,
|
||||
/// which Soft lets start a line, do not send a paragraph that pushes in to the single-line
|
||||
/// composer with either, while Hard, which keeps them off a line's start, does.
|
||||
#[test]
|
||||
fn soft_and_a_set_made_from_it_push_in_the_same_characters() {
|
||||
use KinsokuShoriType::{PushInFirst, PushOutOnly};
|
||||
let glyphs = full_width("あゃいーう");
|
||||
let para = |kinsoku: Kinsoku, own: bool, kinsoku_type: KinsokuShoriType| ParaStyle {
|
||||
kinsoku,
|
||||
kinsoku_set: own.then(|| Arc::new(crate::shape::kinsoku_set_from(kinsoku, "From"))),
|
||||
kinsoku_type,
|
||||
..ParaStyle::default()
|
||||
};
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &glyphs), "built-in Soft");
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Soft, true, PushInFirst), &glyphs), "a set made from Soft");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Hard, false, PushInFirst), &glyphs), "built-in Hard");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Hard, true, PushInFirst), &glyphs), "a set made from Hard");
|
||||
assert!(!flow::may_push_in(¶(Kinsoku::Hard, false, PushOutOnly), &glyphs), "Push Out Only");
|
||||
let bracket = full_width("あい」う");
|
||||
assert!(flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &bracket), "Soft keeps 」 off a line's start");
|
||||
}
|
||||
|
||||
/// With Burasagari, a custom set hangs its own Hanging Punctuation and not the comma and full stop
|
||||
/// the built-in sets hang: 、 hangs outside a full line with Hard and with a set that lists it; with
|
||||
/// a set that lists only ! it starts the next line, while ! hangs.
|
||||
#[test]
|
||||
fn a_custom_set_hangs_its_own_hanging_punctuation() {
|
||||
use KinsokuShoriType::PushOutOnly;
|
||||
let end = |text: &str, k: breaking::KinsokuRules<'_>| {
|
||||
break_line(text, &full_width(text), 0, 30.0, &[], 0.0, None, Burasagari::Standard, k, PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
let comma = custom_set("", "", "、", &[]);
|
||||
let bang = custom_set("", "", "!", &[]);
|
||||
assert_eq!(end("一二三、四", Kinsoku::Hard.into()), 4);
|
||||
assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&comma)), 4, "、 hangs");
|
||||
assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&bang)), 3, "、 does not hang");
|
||||
assert_eq!(end("一二三!四", breaking::KinsokuRules::Custom(&bang)), 4, "! hangs");
|
||||
// In a wider line where ! fits, the line still ends after it.
|
||||
let text = "一二三!四";
|
||||
let wide = |b: Burasagari| {
|
||||
break_line(text, &full_width(text), 0, 40.0, &[], 0.0, None, b, breaking::KinsokuRules::Custom(&bang), PushOutOnly, false, false, &[], None).0
|
||||
};
|
||||
assert_eq!(wide(Burasagari::Standard), 4, "! fits and ends the line");
|
||||
assert_eq!(wide(Burasagari::None), 3, "without Burasagari ! does not hang, and no line ends after it");
|
||||
// The first word, which places a line in a frame of uneven width, ends after ! as the line may.
|
||||
let word = |b: Burasagari| breaking::word_width(&full_width("AB!CD"), 0, &[], breaking::KinsokuRules::Custom(&bang), b);
|
||||
assert_eq!(word(Burasagari::Standard), 30.0);
|
||||
assert_eq!(word(Burasagari::None), 50.0);
|
||||
// A hanging character that starts an inseparable sequence kept with Bunri-Kinshi does not hang
|
||||
// the rest of the sequence with it: the sequence goes to the next line.
|
||||
let joined = custom_set("", "", "!", &["!あ"]);
|
||||
let text = "一二三!あい";
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &joined.inseparable);
|
||||
let rules = breaking::KinsokuRules::Custom(&joined);
|
||||
assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, rules, PushOutOnly, false, false, &[], None).0, 3);
|
||||
// A hanging character drawn with two glyphs does not hang: the line's geometry hangs only one
|
||||
// glyph, so the other would stay past the measure. 三 goes to the next line with it.
|
||||
let text = "一二三、四";
|
||||
let mut g = full_width(text);
|
||||
g[3].adv = 5.0;
|
||||
g.insert(3, g[3].clone());
|
||||
assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, PushOutOnly, false, false, &[], None).0, 2);
|
||||
let g = full_width("、!");
|
||||
assert!(breaking::hangs(&g[1], breaking::KinsokuRules::Custom(&bang)) && !breaking::hangs(&g[0], breaking::KinsokuRules::Custom(&bang)));
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom set: a line never breaks inside one of its inseparable sequences,
|
||||
/// which may be longer than a pair and may overlap, and the built-in pairs are kept only when the
|
||||
/// set lists them.
|
||||
#[test]
|
||||
fn a_custom_set_keeps_its_inseparable_sequences_on_one_line() {
|
||||
let marked = |text: &str, sequences: &[&str]| {
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &sequences.iter().map(|s| s.to_string()).collect::<Vec<_>>());
|
||||
g.iter().map(|g| g.keeps_next).collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(marked("かあいうえ", &["あいう"]), [false, true, true, false, false]);
|
||||
assert_eq!(marked("あいうえお", &["あい", "いう"]), [true, true, false, false, false], "overlapping sequences chain");
|
||||
assert_eq!(marked("あ——い", &["あい"]), [false; 4], "the built-in pairs are not kept by a set without them");
|
||||
assert_eq!(marked("", &["あい"]), Vec::<bool>::new());
|
||||
assert_eq!(marked("あいうえお", &["あい", "あいうえ"]), [true, true, true, false, false], "the longer of two sequences that start alike");
|
||||
assert_eq!(marked("あいう", &["あい", "あいか"]), [true, false, false], "the shorter where only it is found");
|
||||
// A set at the category limit whose sequences all start with one character.
|
||||
let many: Vec<String> = (0..2047u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect();
|
||||
let many: Vec<&str> = many.iter().map(String::as_str).chain(["あい"]).collect();
|
||||
assert_eq!(marked("あいあ一う", &many), [true, false, true, false, false]);
|
||||
let text = "かあいうえ";
|
||||
let set = custom_set("", "", "", &["あいう"]);
|
||||
let mut g = full_width(text);
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, &set.inseparable);
|
||||
let ends = candidates(text, &g, None, breaking::KinsokuRules::Custom(&set)).iter().map(|b| b.end).collect::<Vec<_>>();
|
||||
assert_eq!(ends, [1, 4]);
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom set compares at most 15 texts with the set's sequences for each
|
||||
/// character of a paragraph, however many sequences start with one character: 2048 sequences of
|
||||
/// 2 characters cost one lookup at each place, 256 of 16 characters cost 15, and a sequence longer
|
||||
/// than a set holds is not looked for.
|
||||
#[test]
|
||||
fn inseparable_sequences_cost_a_bounded_number_of_lookups() {
|
||||
let lookups = |text: &str, sequences: &[String]| {
|
||||
let mut g = full_width(text);
|
||||
crate::shape::SEQUENCE_LOOKUPS.with(|n| n.set(0));
|
||||
crate::shape::keep_inseparable_sequences(text, &mut g, sequences);
|
||||
(crate::shape::SEQUENCE_LOOKUPS.with(std::cell::Cell::get), g.iter().filter(|g| g.keeps_next).count())
|
||||
};
|
||||
// A place n characters from the paragraph's end looks up min(n, 16) - 1 texts.
|
||||
let cost = |chars: usize, longest: usize| (1..=chars).map(|n| n.min(longest) - 1).sum::<usize>();
|
||||
let text = "あ".repeat(1000);
|
||||
let pairs: Vec<String> = (0..2048u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect();
|
||||
assert_eq!(lookups(&text, &pairs), (999, 0));
|
||||
let long: Vec<String> = (0..256u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| format!("{}{c}", "あ".repeat(15))).collect();
|
||||
assert_eq!(lookups(&text, &long), (cost(1000, 16), 0));
|
||||
assert!(cost(1000, 16) <= 1000 * 15);
|
||||
let mut found = long.clone();
|
||||
found.push("あ".repeat(16));
|
||||
assert_eq!(lookups(&"あ".repeat(16), &found), (cost(16, 16), 15));
|
||||
assert_eq!(lookups(&"あ".repeat(17), &["あ".repeat(17)]), (cost(17, 16), 0), "17 characters are never found");
|
||||
}
|
||||
|
||||
/// Justification adds no gap between two glyphs of one warichu block, whichever of them is drawn
|
||||
/// first: right to left, the block's first glyph (the one that starts it) is drawn after the
|
||||
/// others. Between glyphs of two blocks, the gap stays.
|
||||
|
||||
@@ -56,7 +56,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader};
|
||||
pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout};
|
||||
use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2};
|
||||
pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled};
|
||||
pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale};
|
||||
pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale};
|
||||
pub use vectorcraft_doc::TextObject;
|
||||
|
||||
pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign};
|
||||
|
||||
@@ -438,6 +438,89 @@ pub(crate) fn keep_inseparable_pairs(text: &str, sg: &mut [SGlyph]) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many texts [`keep_inseparable_sequences`] has compared with a set's sequences on this
|
||||
/// thread.
|
||||
pub(crate) static SEQUENCE_LOOKUPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi with a custom Kinsoku Shori set: as [`keep_inseparable_pairs`], for the set's
|
||||
/// inseparable `sequences` (each [`vectorcraft_doc::text::KINSOKU_SEQUENCE`] characters): a line
|
||||
/// never breaks between two characters of one occurrence of a sequence in the paragraph's text.
|
||||
/// Occurrences may overlap. The text is read once; at each place that starts a sequence, only the
|
||||
/// text of each sequence length (at most [`vectorcraft_doc::text::KINSOKU_SEQUENCE`]'s end) is
|
||||
/// looked up, however many sequences share a first character: at most 15 lookups for each
|
||||
/// character of the paragraph. A sequence longer than a set can hold is never found.
|
||||
pub(crate) fn keep_inseparable_sequences(text: &str, sg: &mut [SGlyph], sequences: &[String]) {
|
||||
let (Some(first), Some(last)) = (sg.iter().map(|g| g.byte).min(), sg.iter().map(|g| g.byte + g.len).max()) else { return };
|
||||
let Some(longest) = sequences.iter().map(|s| s.chars().count()).max() else { return };
|
||||
let longest = longest.min(*vectorcraft_doc::text::KINSOKU_SEQUENCE.end());
|
||||
let known: std::collections::HashSet<&str> = sequences.iter().map(String::as_str).collect();
|
||||
let starts: std::collections::HashSet<char> = sequences.iter().filter_map(|s| s.chars().next()).collect();
|
||||
let Some(para) = text.get(first..last) else { return };
|
||||
// The bytes (of `text`) where a character inside an occurrence starts, after its first.
|
||||
let mut inside = std::collections::HashSet::new();
|
||||
for (at, c) in para.char_indices() {
|
||||
if !starts.contains(&c) {
|
||||
continue;
|
||||
}
|
||||
let rest = ¶[at..];
|
||||
// Every sequence found here is the start of the longest one found here, so that one marks
|
||||
// the characters of them all.
|
||||
let mut found = None;
|
||||
for end in rest.char_indices().take(longest).map(|(k, ch)| k + ch.len_utf8()).skip(1) {
|
||||
#[cfg(test)]
|
||||
SEQUENCE_LOOKUPS.with(|n| n.set(n.get() + 1));
|
||||
if known.contains(&rest[..end]) {
|
||||
found = Some(end);
|
||||
}
|
||||
}
|
||||
if let Some(end) = found {
|
||||
inside.extend(rest[..end].char_indices().skip(1).map(|(k, _)| first + at + k));
|
||||
}
|
||||
}
|
||||
if inside.is_empty() {
|
||||
return;
|
||||
}
|
||||
for k in 1..sg.len() {
|
||||
let (a, b) = (&sg[k - 1], &sg[k]);
|
||||
if a.byte == b.byte || a.inline.is_some() || b.inline.is_some() || a.byte + a.len != b.byte {
|
||||
continue;
|
||||
}
|
||||
if inside.contains(&b.byte) {
|
||||
sg[k - 1].keeps_next = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The characters, hanging punctuation and inseparable sequences of a built-in Kinsoku Set
|
||||
/// (`base`), as a custom set named `name` holds them: New Set's starting point. A set made from
|
||||
/// Hard or Soft breaks lines as that set does; one made from None is empty.
|
||||
pub fn kinsoku_set_from(base: vectorcraft_doc::Kinsoku, name: &str) -> vectorcraft_doc::KinsokuSet {
|
||||
use vectorcraft_doc::Kinsoku;
|
||||
let mut set = vectorcraft_doc::KinsokuSet { name: name.to_string(), ..Default::default() };
|
||||
if base == Kinsoku::None {
|
||||
return set;
|
||||
}
|
||||
// Every character the built-in sets name is in the Basic Multilingual Plane.
|
||||
for c in (0..=0xFFFF_u32).filter_map(char::from_u32) {
|
||||
if no_line_start(c) && !(base == Kinsoku::Soft && soft_line_start(c)) {
|
||||
set.cannot_start.push(c);
|
||||
}
|
||||
if no_line_end(c) {
|
||||
set.cannot_end.push(c);
|
||||
}
|
||||
if crate::layout::is_hanging_punctuation(c) {
|
||||
set.hanging.push(c);
|
||||
}
|
||||
}
|
||||
let pairs = [('\u{2014}', '\u{2014}'), ('\u{2026}', '\u{2026}'), ('\u{2025}', '\u{2025}'), ('\u{3033}', '\u{3035}'), ('\u{3034}', '\u{3035}')];
|
||||
set.inseparable = pairs.iter().filter(|&&(a, b)| inseparable(a, b)).map(|&(a, b)| [a, b].iter().collect()).collect();
|
||||
set.normalize();
|
||||
set
|
||||
}
|
||||
|
||||
/// Is `a` followed by `b` an inseparable pair that Bunri-Kinshi keeps on one line? VectorCraft's
|
||||
/// set is the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08): two
|
||||
/// em dashes, two horizontal ellipses, two two-dot leaders, and the upper half of a vertical kana
|
||||
|
||||
@@ -68,6 +68,7 @@ pub mod import_pdf;
|
||||
pub mod indexed_color;
|
||||
pub mod javascript_files;
|
||||
pub mod justification;
|
||||
pub mod kinsoku_sets;
|
||||
pub mod layer_options;
|
||||
pub mod layers_panel_options;
|
||||
pub mod liquify;
|
||||
@@ -388,6 +389,7 @@ registry! {
|
||||
TateChuYokoSettings: [tate_chu_yoko::KIND] => tate_chu_yoko::SPEC,
|
||||
WarichuSettings: [warichu::KIND] => warichu::SPEC,
|
||||
CompositeFonts: [composite_fonts::KIND] => composite_fonts::SPEC,
|
||||
KinsokuSets: [kinsoku_sets::KIND] => kinsoku_sets::SPEC,
|
||||
SavePdf: [save_pdf::KIND] => save_pdf::SPEC,
|
||||
SvgOptions: [svg_options::KIND] => svg_options::SPEC,
|
||||
JavaScriptFiles: [javascript_files::KIND] => javascript_files::SPEC,
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
//! Type › Kinsoku Shori Settings… (with Show East Asian Options): the active document's custom
|
||||
//! Kinsoku Shori sets, the one picked in Kinsoku shown with its four categories: Cannot Start Line,
|
||||
//! Cannot End Line, Hanging Punctuation and Inseparable Characters. New adds a set based on Hard,
|
||||
//! Soft, None or a set of the dialog, Delete takes the one picked out, and Add puts the character
|
||||
//! of a Unicode code point into a category. Nothing changes in the document until OK,
|
||||
//! which runs `type.kinsokuSets.set` with every set as one undo step; Cancel leaves them as they were.
|
||||
//!
|
||||
//! Fields: `__doc` (the uid of the document the dialog opened on, which OK sets the sets of),
|
||||
//! `__opened` (the names of that document's sets when the dialog opened; OK keeps the sets the
|
||||
//! document gained since, after the dialog's own), `sets` (the sets as `type.kinsokuSets.set` takes them, each with the name it had in the
|
||||
//! document as `from`), `selected` (the index of the one picked), `name`, `cannotStart`,
|
||||
//! `cannotEnd`, `hanging` and `inseparable` (its name and categories as typed, the inseparable
|
||||
//! sequences separated by spaces), `base` (what New starts from), `code` (the code point Add
|
||||
//! adds), `into` (the category it adds to) and `shown` (the set the name and category fields
|
||||
//! were filled from). When `sets` or `selected` is changed so the picked set is no longer `shown`,
|
||||
//! the fields are filled from the picked set again and what was typed in them is dropped.
|
||||
//!
|
||||
//! Behavior reference: the help page
|
||||
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html>.
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::KinsokuSet;
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Kinsoku Shori Settings.
|
||||
pub const KIND: &str = "kinsokuSets";
|
||||
|
||||
/// The command OK runs, and the menu item's.
|
||||
pub const COMMAND: &str = vectorcraft_engine::cmd::kinsokusets::SET;
|
||||
|
||||
/// The field that holds the uid of the document whose sets the dialog shows (`ui.dialog.set`
|
||||
/// refuses `__` fields).
|
||||
const DOC: &str = "__doc";
|
||||
|
||||
/// The field that holds the names of the document's sets when the dialog opened: OK keeps the
|
||||
/// sets the document gained since, which the dialog does not list.
|
||||
const OPENED: &str = "__opened";
|
||||
|
||||
/// The categories, as the command's keys, in the order the dialog shows them.
|
||||
const CATEGORIES: [&str; 4] = ["cannotStart", "cannotEnd", "hanging", "inseparable"];
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading: |_| tl!("Kinsoku Shori Settings").into(), body, confirm, min_width: 560.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let st = app.session.active().ok_or("no document open")?;
|
||||
let uid = st.uid;
|
||||
let sets: Vec<Value> = st.doc.kinsoku_sets.iter().map(listed).collect();
|
||||
let opened: Vec<&str> = st.doc.kinsoku_sets.iter().map(|k| k.name.as_str()).collect();
|
||||
let mut d =
|
||||
Dialog::new(KIND, json!({ DOC: uid, OPENED: opened, "sets": sets, "selected": 0, "base": "hard", "into": "cannotStart", "code": "" }));
|
||||
show_selected(&mut d);
|
||||
app.ui.dialog = Some(d);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// A set of the document as the dialog lists it: as `type.kinsokuSets.set` takes it, with its name
|
||||
/// in the document as `from`.
|
||||
fn listed(k: &KinsokuSet) -> Value {
|
||||
let mut v = json!(k);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("from".into(), json!(k.name));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// The sets the dialog holds, as the command takes them.
|
||||
fn sets(d: &Dialog) -> Vec<Map<String, Value>> {
|
||||
d.fields.get("sets").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_object().cloned()).collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Is the `sets` field a list of sets? One that is not (set with `ui.dialog.set`) is kept as it is:
|
||||
/// no frame or button replaces it, and OK sends it to the command, which refuses it.
|
||||
fn holds_sets(d: &Dialog) -> bool {
|
||||
d.fields.get("sets").and_then(Value::as_array).is_some_and(|a| a.iter().all(Value::is_object))
|
||||
}
|
||||
|
||||
fn put_sets(d: &mut Dialog, sets: &[Map<String, Value>]) {
|
||||
d.fields.insert("sets".into(), json!(sets));
|
||||
}
|
||||
|
||||
fn name_of(set: &Map<String, Value>) -> &str {
|
||||
set.get("name").and_then(Value::as_str).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The index of the set picked, within the sets (0 when there are none).
|
||||
fn selected(d: &Dialog, count: usize) -> usize {
|
||||
d.fields.get("selected").and_then(Value::as_u64).map_or(0, |i| i as usize).min(count.saturating_sub(1))
|
||||
}
|
||||
|
||||
/// Pick set `i`: its name and categories go into the fields.
|
||||
fn select(d: &mut Dialog, i: usize) {
|
||||
d.fields.insert("selected".into(), json!(i));
|
||||
show_selected(d);
|
||||
}
|
||||
|
||||
fn show_selected(d: &mut Dialog) {
|
||||
let list = sets(d);
|
||||
let set = list.get(selected(d, list.len())).cloned().unwrap_or_default();
|
||||
d.fields.insert("name".into(), json!(name_of(&set)));
|
||||
for key in CATEGORIES {
|
||||
let text = match set.get(key) {
|
||||
Some(Value::Array(seqs)) => seqs.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" "),
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
_ => String::new(),
|
||||
};
|
||||
d.fields.insert(key.into(), json!(text));
|
||||
}
|
||||
d.fields.insert("shown".into(), Value::Object(set));
|
||||
}
|
||||
|
||||
/// Do the name and category fields describe the set picked, `set`?
|
||||
fn shows(d: &Dialog, set: &Map<String, Value>) -> bool {
|
||||
d.fields.get("shown").and_then(Value::as_object) == Some(set)
|
||||
}
|
||||
|
||||
/// The set picked with the name and categories as typed: space characters are left out of the
|
||||
/// single-character categories, and the inseparable sequences are the words of their field.
|
||||
fn take_fields(d: &Dialog, set: &mut Map<String, Value>) {
|
||||
set.insert("name".into(), json!(d.str("name")));
|
||||
for key in CATEGORIES {
|
||||
let text = d.str(key);
|
||||
let v = if key == "inseparable" {
|
||||
json!(text.split_whitespace().collect::<Vec<_>>())
|
||||
} else {
|
||||
json!(text.chars().filter(|c| !c.is_whitespace()).collect::<String>())
|
||||
};
|
||||
set.insert(key.into(), v);
|
||||
}
|
||||
}
|
||||
|
||||
/// "Kinsoku Set N", the first N that no set in `sets` and no set of the document (`doc`) is named.
|
||||
/// A set Delete took out keeps its name out of New's, so OK gives its paragraphs Hard instead of
|
||||
/// the new set's characters.
|
||||
fn new_name(sets: &[Map<String, Value>], doc: &[KinsokuSet]) -> String {
|
||||
let taken = |n: &str| sets.iter().any(|s| KinsokuSet::same_name(name_of(s), n)) || doc.iter().any(|k| KinsokuSet::same_name(&k.name, n));
|
||||
(1..).map(|n| format!("Kinsoku Set {n}")).find(|n| !taken(n)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The character `code` names: `U+3001`, `u+3001` or `3001`, in hexadecimal.
|
||||
fn code_char(code: &str) -> Option<char> {
|
||||
let t = code.trim();
|
||||
let hex = t.strip_prefix("U+").or_else(|| t.strip_prefix("u+")).unwrap_or(t);
|
||||
u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|c| !c.is_control() && !c.is_whitespace())
|
||||
}
|
||||
|
||||
/// What a button asked for, done once the fields are drawn.
|
||||
enum Action {
|
||||
New,
|
||||
Delete,
|
||||
Add,
|
||||
}
|
||||
|
||||
/// New's starting points: the built-in sets, then the dialog's own.
|
||||
fn bases(list: &[Map<String, Value>]) -> Vec<(String, String)> {
|
||||
let mut v = vec![
|
||||
(tl!("Hard").to_string(), "hard".to_string()),
|
||||
(tl!("Soft").to_string(), "soft".to_string()),
|
||||
(tl!("None").to_string(), "none".to_string()),
|
||||
];
|
||||
v.extend(list.iter().map(|s| (name_of(s).to_string(), name_of(s).to_string())));
|
||||
v
|
||||
}
|
||||
|
||||
fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let mut list = sets(d);
|
||||
let i = selected(d, list.len());
|
||||
if list.get(i).is_some_and(|set| !shows(d, set)) {
|
||||
show_selected(d);
|
||||
}
|
||||
let mut act = None;
|
||||
let mut picked = None;
|
||||
let names: Vec<String> = list.iter().map(|s| name_of(s).to_string()).collect();
|
||||
let names: Vec<&str> = names.iter().map(String::as_str).collect();
|
||||
let bases = bases(&list);
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Kinsoku Set"));
|
||||
if names.is_empty() {
|
||||
widgets::dim_label(ui, tl!("None"));
|
||||
} else if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-set", names.get(i).copied().unwrap_or_default(), &names, 200.0) {
|
||||
picked = Some(k);
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
if widgets::flat_button(ui, tl!("New"), 48.0).clicked() {
|
||||
act = Some(Action::New);
|
||||
}
|
||||
widgets::dim_label(ui, tl!("Based on:"));
|
||||
let base = d.str("base");
|
||||
let shown = bases.iter().find(|b| b.1 == base).map_or(base.as_str(), |b| b.0.as_str());
|
||||
let base_names: Vec<&str> = bases.iter().map(|b| b.0.as_str()).collect();
|
||||
if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-base", shown, &base_names, 120.0)
|
||||
&& let Some(b) = bases.get(k)
|
||||
{
|
||||
d.fields.insert("base".into(), json!(b.1));
|
||||
}
|
||||
if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Delete"), 56.0)).inner.clicked() {
|
||||
act = Some(Action::Delete);
|
||||
}
|
||||
});
|
||||
if let Some(k) = picked {
|
||||
select(d, k);
|
||||
return false;
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
if let Some(set) = list.get_mut(i) {
|
||||
egui::Grid::new("kinsoku-sets-fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
widgets::dim_label(ui, tl!("Name:"));
|
||||
form::text(ui, d, "name", 260.0);
|
||||
ui.end_row();
|
||||
for (key, label) in [
|
||||
("cannotStart", tl!("Cannot Start Line")),
|
||||
("cannotEnd", tl!("Cannot End Line")),
|
||||
("hanging", tl!("Hanging Punctuation")),
|
||||
("inseparable", tl!("Inseparable Characters")),
|
||||
] {
|
||||
widgets::dim_label(ui, label);
|
||||
form::text_area(ui, d, key, 380.0, 2);
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Unicode"));
|
||||
form::text(ui, d, "code", 80.0);
|
||||
let into = d.str("into");
|
||||
let targets = [("cannotStart", tl!("Cannot Start Line")), ("cannotEnd", tl!("Cannot End Line")), ("hanging", tl!("Hanging Punctuation"))];
|
||||
let shown = targets.iter().find(|t| t.0 == into).map_or("", |t| t.1);
|
||||
if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-into", shown, &targets.map(|t| t.1), 160.0)
|
||||
&& let Some(t) = targets.get(k)
|
||||
{
|
||||
d.fields.insert("into".into(), json!(t.0));
|
||||
}
|
||||
if ui.add_enabled_ui(code_char(&d.str("code")).is_some(), |ui| widgets::flat_button(ui, tl!("Add"), 48.0)).inner.clicked() {
|
||||
act = Some(Action::Add);
|
||||
}
|
||||
});
|
||||
let was = name_of(set).to_string();
|
||||
take_fields(d, set);
|
||||
// Based on follows the set it names through a rename.
|
||||
if d.str("base") == was && name_of(set) != was {
|
||||
let now = name_of(set).to_string();
|
||||
d.fields.insert("base".into(), json!(now));
|
||||
}
|
||||
d.fields.insert("shown".into(), Value::Object(set.clone()));
|
||||
}
|
||||
if holds_sets(d) {
|
||||
put_sets(d, &list);
|
||||
}
|
||||
if let Some(a) = act
|
||||
&& let Err(e) = run(app, d, a)
|
||||
{
|
||||
app.status(e);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Do what button `act` asks for on the dialog's sets.
|
||||
fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), String> {
|
||||
if !holds_sets(d) {
|
||||
return Err("the sets must be a list of Kinsoku sets".into());
|
||||
}
|
||||
let mut list = sets(d);
|
||||
let i = selected(d, list.len());
|
||||
match act {
|
||||
Action::New => {
|
||||
let base = d.str("base");
|
||||
let mut set = match list.iter().find(|s| name_of(s) == base) {
|
||||
Some(s) => s.clone(),
|
||||
None => {
|
||||
let r = app.run("type.kinsokuSets.base", json!({ "base": base }))?;
|
||||
r["set"].as_object().cloned().ok_or("no Kinsoku set to base the new one on")?
|
||||
}
|
||||
};
|
||||
set.remove("from");
|
||||
let uid = d.fields.get(DOC).and_then(Value::as_u64);
|
||||
let doc = app.session.documents().iter().find(|t| Some(t.uid) == uid).map(|t| t.doc.kinsoku_sets.to_vec()).unwrap_or_default();
|
||||
set.insert("name".into(), json!(new_name(&list, &doc)));
|
||||
list.push(set);
|
||||
put_sets(d, &list);
|
||||
select(d, list.len() - 1);
|
||||
}
|
||||
Action::Delete => {
|
||||
if i < list.len() {
|
||||
let gone = name_of(&list[i]).to_string();
|
||||
list.remove(i);
|
||||
if d.str("base") == gone {
|
||||
d.fields.insert("base".into(), json!("hard"));
|
||||
}
|
||||
}
|
||||
put_sets(d, &list);
|
||||
select(d, i.min(list.len().saturating_sub(1)));
|
||||
}
|
||||
Action::Add => {
|
||||
let c = code_char(&d.str("code")).ok_or("give a character's Unicode code point, as U+3001")?;
|
||||
let into = d.str("into");
|
||||
let key = if CATEGORIES.contains(&into.as_str()) && into != "inseparable" { into } else { "cannotStart".into() };
|
||||
let mut text = d.str(&key);
|
||||
if !text.contains(c) {
|
||||
text.push(c);
|
||||
}
|
||||
d.fields.insert(key, json!(text));
|
||||
d.fields.insert("code".into(), json!(""));
|
||||
if let Some(set) = list.get_mut(i) {
|
||||
take_fields(d, set);
|
||||
d.fields.insert("shown".into(), Value::Object(set.clone()));
|
||||
}
|
||||
put_sets(d, &list);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
// The fields as typed, also when they were set (`ui.dialog.set`) with no frame drawn since,
|
||||
// while they still describe the set picked.
|
||||
let mut list = sets(d);
|
||||
let i = selected(d, list.len());
|
||||
if let Some(set) = list.get_mut(i)
|
||||
&& shows(d, set)
|
||||
{
|
||||
take_fields(d, set);
|
||||
}
|
||||
// The sets go to the document the dialog opened on, also when another tab is active by now; a
|
||||
// document closed since closes the dialog and changes nothing.
|
||||
let uid = d.fields.get(DOC).and_then(Value::as_u64);
|
||||
if app.session.active().map(|st| st.uid) != uid {
|
||||
let Some(index) = app.session.documents().iter().position(|doc| Some(doc.uid) == uid) else {
|
||||
app.ui.dialog = None;
|
||||
return Err("that document is no longer open".into());
|
||||
};
|
||||
app.run("document.activate", json!({ "index": index }))?;
|
||||
}
|
||||
// A `sets` field that is not a list of sets goes to the command as it is, which refuses it.
|
||||
let sets = if holds_sets(d) {
|
||||
// A set the document gained while the dialog was open (a script, another command) is
|
||||
// kept, after the dialog's sets.
|
||||
let opened: Vec<&str> =
|
||||
d.fields.get(OPENED).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
|
||||
if let Some(st) = app.session.active() {
|
||||
list.extend(st.doc.kinsoku_sets.iter().filter(|k| !opened.contains(&k.name.as_str())).filter_map(|k| listed(k).as_object().cloned()));
|
||||
}
|
||||
json!(list)
|
||||
} else {
|
||||
d.fields.get("sets").cloned().unwrap_or(Value::Null)
|
||||
};
|
||||
let r = app.run(COMMAND, json!({ "sets": sets }));
|
||||
// A name two sets share, a reserved name or a category too long keeps the dialog open to be
|
||||
// changed, with its document active.
|
||||
if r.is_ok() {
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,308 @@
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn frame(app: &mut VectorcraftApp) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
fn dialog(app: &mut VectorcraftApp) -> &mut Dialog {
|
||||
app.ui.dialog.as_mut().expect("Kinsoku Shori Settings open")
|
||||
}
|
||||
|
||||
fn doc_sets(app: &VectorcraftApp) -> Vec<KinsokuSet> {
|
||||
app.session.active().unwrap().doc.kinsoku_sets.to_vec()
|
||||
}
|
||||
|
||||
fn steps(app: &VectorcraftApp) -> usize {
|
||||
app.session.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// Do `act` with the dialog as it is, as its button does.
|
||||
fn press(app: &mut VectorcraftApp, act: Action) {
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
run(app, &mut d, act).unwrap();
|
||||
app.ui.dialog = Some(d);
|
||||
}
|
||||
|
||||
/// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its
|
||||
/// categories edited in their fields and Add putting in a character by its code point; nothing
|
||||
/// changes until OK, which sets them as one undo step; Cancel leaves them.
|
||||
#[test]
|
||||
fn kinsoku_sets_change_on_ok_as_one_undo_step() {
|
||||
let mut app = app();
|
||||
crate::menus::invoke(&mut app, COMMAND, json!({}));
|
||||
assert_eq!(dialog(&mut app).kind, KIND);
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::New);
|
||||
frame(&mut app);
|
||||
let d = dialog(&mut app);
|
||||
assert_eq!(d.str("name"), "Kinsoku Set 1");
|
||||
assert!(d.str("cannotStart").contains('ー'), "based on Hard");
|
||||
d.fields.insert("name".into(), json!("UI Tight"));
|
||||
d.fields.insert("cannotEnd".into(), json!("「 ("));
|
||||
d.fields.insert("inseparable".into(), json!("あい ——"));
|
||||
d.fields.insert("code".into(), json!("U+FF5D"));
|
||||
d.fields.insert("into".into(), json!("cannotEnd"));
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::Add);
|
||||
assert_eq!(dialog(&mut app).str("cannotEnd"), "「 (}");
|
||||
frame(&mut app);
|
||||
assert!(doc_sets(&app).is_empty());
|
||||
let before = steps(&app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
let sets = doc_sets(&app);
|
||||
assert_eq!(sets.len(), 1);
|
||||
assert_eq!((sets[0].name.as_str(), sets[0].cannot_end.clone()), ("UI Tight", vec!['「', '(', '}']));
|
||||
assert_eq!(sets[0].inseparable, ["——", "あい"]);
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
// OK with nothing changed adds no step; Cancel leaves the sets.
|
||||
open(&mut app).unwrap();
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(steps(&app), before + 1);
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::Delete);
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!(doc_sets(&app).len(), 1);
|
||||
// Renamed in the dialog, the set keeps its paragraphs; Delete and OK takes it out.
|
||||
let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("text.setFormat", json!({"kinsoku": "UI Tight"})).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
dialog(&mut app).fields.insert("name".into(), json!("UI Strict"));
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let para = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(para(&app).kinsoku_name(), "UI Strict");
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::Delete);
|
||||
assert_eq!(dialog(&mut app).str("name"), "");
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(doc_sets(&app).is_empty());
|
||||
assert_eq!(para(&app).kinsoku_name(), "Hard");
|
||||
}
|
||||
|
||||
/// New is based on the choice in Based on, the dialog's own sets included, and takes the next free
|
||||
/// name; a name two sets share, a built-in name or one left empty keeps the dialog open and changes
|
||||
/// nothing.
|
||||
#[test]
|
||||
fn shared_reserved_or_empty_names_keep_the_dialog_open() {
|
||||
let mut app = app();
|
||||
open(&mut app).unwrap();
|
||||
dialog(&mut app).fields.insert("base".into(), json!("none"));
|
||||
press(&mut app, Action::New);
|
||||
assert_eq!(dialog(&mut app).str("cannotStart"), "");
|
||||
dialog(&mut app).fields.insert("cannotStart".into(), json!("ゝ"));
|
||||
frame(&mut app);
|
||||
dialog(&mut app).fields.insert("base".into(), json!("Kinsoku Set 1"));
|
||||
press(&mut app, Action::New);
|
||||
let d = dialog(&mut app);
|
||||
assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 2".to_string(), "ゝ".to_string()));
|
||||
for bad in ["kinsoku set 1", " ", "Soft"] {
|
||||
dialog(&mut app).fields.insert("name".into(), json!(bad));
|
||||
frame(&mut app);
|
||||
assert!(super::super::confirm(&mut app).is_err(), "{bad:?}");
|
||||
assert!(app.ui.dialog.is_some());
|
||||
assert!(doc_sets(&app).is_empty());
|
||||
}
|
||||
dialog(&mut app).fields.insert("name".into(), json!("UI Loose"));
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::<Vec<_>>(), ["Kinsoku Set 1", "UI Loose"]);
|
||||
}
|
||||
|
||||
/// Based on follows a set of the dialog through a rename, so New starts from that set's
|
||||
/// characters as edited, not from the document's copy under its old name.
|
||||
#[test]
|
||||
fn based_on_follows_a_renamed_set() {
|
||||
let mut app = app();
|
||||
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Doc Set", "cannotStart": "ゝ"}]})).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
dialog(&mut app).fields.insert("base".into(), json!("Doc Set"));
|
||||
frame(&mut app);
|
||||
let d = dialog(&mut app);
|
||||
d.fields.insert("cannotStart".into(), json!("ゞ"));
|
||||
d.fields.insert("name".into(), json!("Renamed"));
|
||||
frame(&mut app);
|
||||
assert_eq!(dialog(&mut app).str("base"), "Renamed");
|
||||
press(&mut app, Action::New);
|
||||
let d = dialog(&mut app);
|
||||
assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 1".to_string(), "ゞ".to_string()));
|
||||
}
|
||||
|
||||
/// Delete then New does not give the new set the deleted set's name, so on OK the deleted set's
|
||||
/// paragraphs take Hard rather than the new set's characters.
|
||||
#[test]
|
||||
fn new_after_delete_does_not_take_the_deleted_name() {
|
||||
let mut app = app();
|
||||
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Kinsoku Set 1", "cannotStart": "ゝ"}]})).unwrap();
|
||||
let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [id]})).unwrap();
|
||||
app.run("text.setFormat", json!({"kinsoku": "Kinsoku Set 1"})).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::Delete);
|
||||
dialog(&mut app).fields.insert("base".into(), json!("none"));
|
||||
frame(&mut app);
|
||||
press(&mut app, Action::New);
|
||||
assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2");
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::<Vec<_>>(), ["Kinsoku Set 2"]);
|
||||
let para = match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
|
||||
vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(para.kinsoku_name(), "Hard");
|
||||
}
|
||||
|
||||
/// OK takes the fields as they are set (`ui.dialog.set`) even when no frame was drawn since. Once
|
||||
/// `selected` picks another set, the fields no longer describe it: OK leaves that set as it is,
|
||||
/// and the next frame fills the fields from it.
|
||||
#[test]
|
||||
fn ok_takes_fields_set_without_a_frame() {
|
||||
let mut app = app();
|
||||
let doc = json!([{"name": "Doc Set", "cannotStart": "ゝ"}, {"name": "Other", "cannotStart": "ー"}]);
|
||||
app.run("type.kinsokuSets.set", json!({ "sets": doc })).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
let d = dialog(&mut app);
|
||||
d.fields.insert("name".into(), json!("Scripted"));
|
||||
d.fields.insert("cannotStart".into(), json!("ゞ"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let sets = doc_sets(&app);
|
||||
assert_eq!((sets[0].name.as_str(), sets[0].cannot_start.clone()), ("Scripted", vec!['ゞ']));
|
||||
|
||||
let before = steps(&app);
|
||||
open(&mut app).unwrap();
|
||||
let d = dialog(&mut app);
|
||||
d.fields.insert("selected".into(), json!(1));
|
||||
d.fields.insert("cannotStart".into(), json!("ゝ"));
|
||||
let pending = app.ui.dialog.clone().unwrap();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(steps(&app), before, "the fields of the set shown before do not go into the one picked");
|
||||
assert_eq!(doc_sets(&app)[1].name, "Other");
|
||||
app.ui.dialog = Some(pending);
|
||||
frame(&mut app);
|
||||
let d = dialog(&mut app);
|
||||
assert_eq!((d.str("name"), d.str("cannotStart")), ("Other".to_string(), "ー".to_string()));
|
||||
}
|
||||
|
||||
/// OK sets the sets of the document the dialog opened on, also when another document became the
|
||||
/// active one while it was open; with that document closed, OK closes the dialog and changes no
|
||||
/// document's sets.
|
||||
#[test]
|
||||
fn ok_sets_the_document_the_dialog_opened_on() {
|
||||
let mut app = app();
|
||||
let first = app.session.active().unwrap().uid;
|
||||
app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
assert!(!super::super::accepts_field(dialog(&mut app), DOC), "`ui.dialog.set` cannot change the document");
|
||||
dialog(&mut app).fields.insert("name".into(), json!("Soft"));
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
let other = app.session.active().unwrap().uid;
|
||||
assert_ne!(other, first);
|
||||
// A name OK refuses keeps the dialog open on its document, now the active one.
|
||||
assert!(super::super::confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_some());
|
||||
assert_eq!(app.session.active().unwrap().uid, first);
|
||||
assert_eq!(doc_sets(&app)[0].name, "First");
|
||||
app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap();
|
||||
dialog(&mut app).fields.insert("name".into(), json!("Kinsoku Set 1"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(app.session.active().unwrap().uid, first);
|
||||
assert_eq!(doc_sets(&app)[0].name, "Kinsoku Set 1");
|
||||
let second = app.session.documents().iter().find(|d| d.uid != first).unwrap();
|
||||
assert!(second.doc.kinsoku_sets.is_empty(), "the other document keeps its sets");
|
||||
|
||||
// New skips the names of the dialog's document's sets, not of the active document's.
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::Delete);
|
||||
app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap();
|
||||
press(&mut app, Action::New);
|
||||
assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2");
|
||||
let i = app.session.documents().iter().position(|d| d.uid == first).unwrap();
|
||||
app.session.execute("file.close", &json!({ "index": i })).unwrap();
|
||||
assert!(super::super::confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty()));
|
||||
}
|
||||
|
||||
/// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a
|
||||
/// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the
|
||||
/// dialog open and leaves the document's sets as they are, also when a frame is drawn before OK,
|
||||
/// and New refuses to start from it.
|
||||
#[test]
|
||||
fn ok_keeps_sets_added_while_open_and_refuses_malformed_sets() {
|
||||
let mut app = app();
|
||||
app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap();
|
||||
open(&mut app).unwrap();
|
||||
let both = json!([{"name": "First", "cannotStart": "ゝ"}, {"name": "Later", "cannotStart": "ー"}]);
|
||||
app.run("type.kinsokuSets.set", json!({ "sets": both })).unwrap();
|
||||
dialog(&mut app).fields.insert("cannotStart".into(), json!("ゞ"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let sets = doc_sets(&app);
|
||||
let named = sets.iter().map(|k| (k.name.as_str(), k.cannot_start.clone())).collect::<Vec<_>>();
|
||||
assert_eq!(named, [("First", vec!['ゞ']), ("Later", vec!['ー'])]);
|
||||
open(&mut app).unwrap();
|
||||
press(&mut app, Action::Delete);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
let names = |app: &VectorcraftApp| doc_sets(app).iter().map(|k| k.name.clone()).collect::<Vec<_>>();
|
||||
assert_eq!(names(&app), ["Later"]);
|
||||
for bad in [Value::Null, json!({}), json!("Later"), json!([1]), json!([{"name": "Later", "cannotStart": "ー"}, 1])] {
|
||||
for drawn in [false, true] {
|
||||
open(&mut app).unwrap();
|
||||
dialog(&mut app).fields.insert("sets".into(), bad.clone());
|
||||
if drawn {
|
||||
frame(&mut app);
|
||||
assert_eq!(dialog(&mut app).fields.get("sets"), Some(&bad), "a frame keeps {bad} as it is");
|
||||
let mut d = app.ui.dialog.clone().unwrap();
|
||||
assert!(run(&mut app, &mut d, Action::New).is_err(), "{bad}");
|
||||
assert_eq!(d.fields.get("sets"), Some(&bad), "New keeps {bad} as it is");
|
||||
}
|
||||
assert!(super::super::confirm(&mut app).is_err(), "{bad} drawn: {drawn}");
|
||||
assert!(app.ui.dialog.is_some(), "{bad} drawn: {drawn}");
|
||||
assert_eq!(names(&app), ["Later"], "{bad} drawn: {drawn}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Add takes a code point as U+XXXX, u+xxxx or bare hexadecimal, and never a control or space
|
||||
/// character or a value that is no character.
|
||||
#[test]
|
||||
fn add_reads_unicode_code_points() {
|
||||
assert_eq!(code_char("U+3001"), Some('、'));
|
||||
assert_eq!(code_char(" u+ff5d "), Some('}'));
|
||||
assert_eq!(code_char("300c"), Some('「'));
|
||||
for bad in ["", "U+", "U+0007", "U+0020", "U+D800", "U+110000", "zz"] {
|
||||
assert_eq!(code_char(bad), None, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu item shows only with Show East Asian Options on, and needs a document.
|
||||
#[test]
|
||||
fn the_menu_item_shows_with_east_asian_options() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.prefs.show_east_asian_options = true;
|
||||
assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(false));
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(true));
|
||||
app.session.prefs.show_east_asian_options = false;
|
||||
assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})), None);
|
||||
}
|
||||
@@ -2168,6 +2168,15 @@ font-technology Variable Променливи
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Набор Kinsoku
|
||||
Kinsoku Shori Type Тип Kinsoku Shori
|
||||
Kinsoku Shori Settings… Настройки на Kinsoku Shori…
|
||||
Kinsoku Shori Settings Настройки на Kinsoku Shori
|
||||
Kinsoku Sets Набори Kinsoku
|
||||
Kinsoku Set Base Основа на набор Kinsoku
|
||||
Based on: Въз основа на:
|
||||
Cannot Start Line Не може да започва ред
|
||||
Cannot End Line Не може да завършва ред
|
||||
Hanging Punctuation Висяща пунктуация
|
||||
Inseparable Characters Неразделими знаци
|
||||
Push In First Първо прибиране
|
||||
Push Out First Първо изтласкване
|
||||
Push Out Only Само изтласкване
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2194,6 +2194,15 @@ digits Malayalam Malajalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku skup
|
||||
Kinsoku Shori Type Vrsta Kinsoku Shori
|
||||
Kinsoku Shori Settings… Postavke Kinsoku Shori…
|
||||
Kinsoku Shori Settings Postavke Kinsoku Shori
|
||||
Kinsoku Sets Kinsoku skupovi
|
||||
Kinsoku Set Base Osnova Kinsoku skupa
|
||||
Based on: Zasnovano na:
|
||||
Cannot Start Line Ne može početi red
|
||||
Cannot End Line Ne može završiti red
|
||||
Hanging Punctuation Viseća interpunkcija
|
||||
Inseparable Characters Neodvojivi znakovi
|
||||
Push In First Prvo uvlačenje
|
||||
Push Out First Prvo izbacivanje
|
||||
Push Out Only Samo izbacivanje
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2457,6 +2457,15 @@ digits Malayalam Malaiàlam
|
||||
Kind Tipus
|
||||
Kinsoku Set Conjunt Kinsoku
|
||||
Kinsoku Shori Type Tipus de Kinsoku Shori
|
||||
Kinsoku Shori Settings… Configuració de Kinsoku Shori…
|
||||
Kinsoku Shori Settings Configuració de Kinsoku Shori
|
||||
Kinsoku Sets Conjunts Kinsoku
|
||||
Kinsoku Set Base Base del conjunt Kinsoku
|
||||
Based on: Basat en:
|
||||
Cannot Start Line No pot començar la línia
|
||||
Cannot End Line No pot acabar la línia
|
||||
Hanging Punctuation Puntuació penjant
|
||||
Inseparable Characters Caràcters inseparables
|
||||
Kite Estel
|
||||
Knife Ganivet
|
||||
Knockout Group Grup knockout
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2264,6 +2264,15 @@ digits Malayalam Malajálamské
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Sada Kinsoku
|
||||
Kinsoku Shori Type Typ Kinsoku Shori
|
||||
Kinsoku Shori Settings… Nastavení Kinsoku Shori…
|
||||
Kinsoku Shori Settings Nastavení Kinsoku Shori
|
||||
Kinsoku Sets Sady Kinsoku
|
||||
Kinsoku Set Base Základ sady Kinsoku
|
||||
Based on: Založeno na:
|
||||
Cannot Start Line Nemůže začínat řádek
|
||||
Cannot End Line Nemůže končit řádek
|
||||
Hanging Punctuation Visící interpunkce
|
||||
Inseparable Characters Neoddělitelné znaky
|
||||
Push In First Nejprve vtáhnout
|
||||
Push Out First Nejprve vysunout
|
||||
Push Out Only Pouze vysunout
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4788,6 +4788,15 @@ digits Malayalam Malayalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-sæt
|
||||
Kinsoku Shori Type Kinsoku Shori-type
|
||||
Kinsoku Shori Settings… Kinsoku Shori-indstillinger…
|
||||
Kinsoku Shori Settings Kinsoku Shori-indstillinger
|
||||
Kinsoku Sets Kinsoku-sættene
|
||||
Kinsoku Set Base Grundlag for Kinsoku-sæt
|
||||
Based on: Baseret på:
|
||||
Cannot Start Line Kan ikke starte linje
|
||||
Cannot End Line Kan ikke afslutte linje
|
||||
Hanging Punctuation Hængende tegnsætning
|
||||
Inseparable Characters Uadskillelige tegn
|
||||
Push In First Skub ind først
|
||||
Push Out First Skub ud først
|
||||
Push Out Only Kun skub ud
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2262,6 +2262,15 @@ file-filter Templates Vorlagen
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-Satz
|
||||
Kinsoku Shori Type Kinsoku-Shori-Typ
|
||||
Kinsoku Shori Settings… Kinsoku-Shori-Einstellungen…
|
||||
Kinsoku Shori Settings Kinsoku-Shori-Einstellungen
|
||||
Kinsoku Sets Kinsoku-Sätze
|
||||
Kinsoku Set Base Basis des Kinsoku-Satzes
|
||||
Based on: Basierend auf:
|
||||
Cannot Start Line Kann Zeile nicht beginnen
|
||||
Cannot End Line Kann Zeile nicht beenden
|
||||
Hanging Punctuation Hängende Interpunktion
|
||||
Inseparable Characters Untrennbare Zeichen
|
||||
Push In First Zuerst einziehen
|
||||
Push Out First Zuerst hinausschieben
|
||||
Push Out Only Nur hinausschieben
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3359,6 +3359,15 @@ theme Appearance Εμφάνιση
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Σύνολο Kinsoku
|
||||
Kinsoku Shori Type Τύπος Kinsoku Shori
|
||||
Kinsoku Shori Settings… Ρυθμίσεις Kinsoku Shori…
|
||||
Kinsoku Shori Settings Ρυθμίσεις Kinsoku Shori
|
||||
Kinsoku Sets Σύνολα Kinsoku
|
||||
Kinsoku Set Base Βάση συνόλου Kinsoku
|
||||
Based on: Με βάση:
|
||||
Cannot Start Line Δεν ξεκινά γραμμή
|
||||
Cannot End Line Δεν τελειώνει γραμμή
|
||||
Hanging Punctuation Κρεμαστή στίξη
|
||||
Inseparable Characters Αδιαχώριστοι χαρακτήρες
|
||||
Push In First Πρώτα προς τα μέσα
|
||||
Push Out First Πρώτα προς τα έξω
|
||||
Push Out Only Μόνο προς τα έξω
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2261,6 +2261,15 @@ font-technology Variable Variables
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Conjunto de kinsoku
|
||||
Kinsoku Shori Type Tipo de kinsoku shori
|
||||
Kinsoku Shori Settings… Configuración de kinsoku shori…
|
||||
Kinsoku Shori Settings Configuración de kinsoku shori
|
||||
Kinsoku Sets Conjuntos de kinsoku
|
||||
Kinsoku Set Base Base del conjunto de kinsoku
|
||||
Based on: Basado en:
|
||||
Cannot Start Line No puede iniciar línea
|
||||
Cannot End Line No puede terminar línea
|
||||
Hanging Punctuation Puntuación colgante
|
||||
Inseparable Characters Caracteres inseparables
|
||||
Push In First Primero hacia dentro
|
||||
Push Out First Primero hacia fuera
|
||||
Push Out Only Solo hacia fuera
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2225,6 +2225,15 @@ digits Malayalam Malajalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-joukko
|
||||
Kinsoku Shori Type Kinsoku Shori -tyyppi
|
||||
Kinsoku Shori Settings… Kinsoku Shori -asetukset…
|
||||
Kinsoku Shori Settings Kinsoku Shori -asetukset
|
||||
Kinsoku Sets Kinsoku-joukot
|
||||
Kinsoku Set Base Kinsoku-joukon pohja
|
||||
Based on: Pohjana:
|
||||
Cannot Start Line Ei voi aloittaa riviä
|
||||
Cannot End Line Ei voi päättää riviä
|
||||
Hanging Punctuation Riippuvat välimerkit
|
||||
Inseparable Characters Erottamattomat merkit
|
||||
Push In First Ensin sisään
|
||||
Push Out First Ensin ulos
|
||||
Push Out Only Vain ulos
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2251,6 +2251,15 @@ font-technology Variable Variables
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Jeu de kinsoku
|
||||
Kinsoku Shori Type Type de kinsoku shori
|
||||
Kinsoku Shori Settings… Paramètres de kinsoku shori…
|
||||
Kinsoku Shori Settings Paramètres de kinsoku shori
|
||||
Kinsoku Sets Jeux de kinsoku
|
||||
Kinsoku Set Base Base du jeu de kinsoku
|
||||
Based on: Basé sur :
|
||||
Cannot Start Line Ne peut pas commencer une ligne
|
||||
Cannot End Line Ne peut pas terminer une ligne
|
||||
Hanging Punctuation Ponctuation suspendue
|
||||
Inseparable Characters Caractères insécables
|
||||
Push In First D’abord vers l’intérieur
|
||||
Push Out First D’abord vers l’extérieur
|
||||
Push Out Only Vers l’extérieur uniquement
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2954,6 +2954,15 @@ antiAlias Sharp शार्प
|
||||
Keywords: कीवर्ड:
|
||||
Kind प्रकार
|
||||
Kinsoku Set किनसोकू सेट
|
||||
Kinsoku Shori Settings… किनसोकू शोरी सेटिंग्स…
|
||||
Kinsoku Shori Settings किनसोकू शोरी सेटिंग्स
|
||||
Kinsoku Sets किनसोकू सेट सूची
|
||||
Kinsoku Set Base किनसोकू सेट का आधार
|
||||
Based on: इस पर आधारित:
|
||||
Cannot Start Line पंक्ति शुरू नहीं कर सकते
|
||||
Cannot End Line पंक्ति समाप्त नहीं कर सकते
|
||||
Hanging Punctuation लटकते विराम चिह्न
|
||||
Inseparable Characters अविभाज्य वर्ण
|
||||
Kite पतंग
|
||||
Knife चाकू
|
||||
Knockout Group नॉकआउट समूह
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2478,6 +2478,15 @@ file-filter Templates Sablonok
|
||||
Kind Típus
|
||||
Kinsoku Set Kinsoku-készlet
|
||||
Kinsoku Shori Type Kinsoku Shori típusa
|
||||
Kinsoku Shori Settings… Kinsoku Shori beállításai…
|
||||
Kinsoku Shori Settings Kinsoku Shori beállításai
|
||||
Kinsoku Sets Kinsoku-készletek
|
||||
Kinsoku Set Base Kinsoku-készlet alapja
|
||||
Based on: Alapja:
|
||||
Cannot Start Line Nem kezdhet sort
|
||||
Cannot End Line Nem zárhat sort
|
||||
Hanging Punctuation Függő írásjelek
|
||||
Inseparable Characters Elválaszthatatlan karakterek
|
||||
Kite Deltoid
|
||||
Knife Kés
|
||||
Knockout Group Kiütő csoport
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2012,6 +2012,15 @@ digits Malayalam Malayalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Set Kinsoku
|
||||
Kinsoku Shori Type Jenis Kinsoku Shori
|
||||
Kinsoku Shori Settings… Pengaturan Kinsoku Shori…
|
||||
Kinsoku Shori Settings Pengaturan Kinsoku Shori
|
||||
Kinsoku Sets Daftar Set Kinsoku
|
||||
Kinsoku Set Base Dasar Set Kinsoku
|
||||
Based on: Berdasarkan:
|
||||
Cannot Start Line Tidak dapat memulai baris
|
||||
Cannot End Line Tidak dapat mengakhiri baris
|
||||
Hanging Punctuation Tanda baca gantung
|
||||
Inseparable Characters Karakter tak terpisahkan
|
||||
Push In First Dorong masuk dahulu
|
||||
Push Out First Dorong keluar dahulu
|
||||
Push Out Only Hanya dorong keluar
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1011 and column 34.
|
@@ -2302,6 +2302,15 @@ file-filter Templates Modelli
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Set kinsoku
|
||||
Kinsoku Shori Type Tipo di kinsoku shori
|
||||
Kinsoku Shori Settings… Impostazioni kinsoku shori…
|
||||
Kinsoku Shori Settings Impostazioni kinsoku shori
|
||||
Kinsoku Sets Elenco set kinsoku
|
||||
Kinsoku Set Base Base del set kinsoku
|
||||
Based on: Basato su:
|
||||
Cannot Start Line Non può iniziare la riga
|
||||
Cannot End Line Non può terminare la riga
|
||||
Hanging Punctuation Punteggiatura sospesa
|
||||
Inseparable Characters Caratteri inseparabili
|
||||
Push In First Prima all'interno
|
||||
Push Out First Prima all'esterno
|
||||
Push Out Only Solo all'esterno
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -95,6 +95,15 @@ digits Malayalam マラヤーラム数字
|
||||
YakumonoZenkaku 約物全角
|
||||
Kinsoku Set 禁則処理
|
||||
Kinsoku Shori Type 禁則調整方式
|
||||
Kinsoku Shori Settings… 禁則処理設定…
|
||||
Kinsoku Shori Settings 禁則処理設定
|
||||
Kinsoku Sets 禁則処理セット
|
||||
Kinsoku Set Base 禁則処理セットの基準
|
||||
Based on: 基準:
|
||||
Cannot Start Line 行頭禁則文字
|
||||
Cannot End Line 行末禁則文字
|
||||
Hanging Punctuation ぶら下がり文字
|
||||
Inseparable Characters 分離禁止文字
|
||||
Push In First 追い込み優先
|
||||
Push Out First 追い出し優先
|
||||
Push Out Only 追い出しのみ
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4183,6 +4183,15 @@ digits Malayalam მალაიალამური
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-ის ნაკრები
|
||||
Kinsoku Shori Type Kinsoku Shori-ის ტიპი
|
||||
Kinsoku Shori Settings… Kinsoku Shori-ის პარამეტრები…
|
||||
Kinsoku Shori Settings Kinsoku Shori-ის პარამეტრები
|
||||
Kinsoku Sets Kinsoku-ის ნაკრებები
|
||||
Kinsoku Set Base Kinsoku-ის ნაკრების საფუძველი
|
||||
Based on: საფუძველი:
|
||||
Cannot Start Line ვერ დაიწყებს ხაზს
|
||||
Cannot End Line ვერ დაასრულებს ხაზს
|
||||
Hanging Punctuation დაკიდებული პუნქტუაცია
|
||||
Inseparable Characters განუყოფელი სიმბოლოები
|
||||
Push In First ჯერ შეტანა
|
||||
Push Out First ჯერ გატანა
|
||||
Push Out Only მხოლოდ გატანა
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -88,6 +88,15 @@ digits Malayalam 말라얄람어
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set 긴소쿠 세트
|
||||
Kinsoku Shori Type 긴소쿠 처리 유형
|
||||
Kinsoku Shori Settings… 긴소쿠 처리 설정…
|
||||
Kinsoku Shori Settings 긴소쿠 처리 설정
|
||||
Kinsoku Sets 긴소쿠 세트 목록
|
||||
Kinsoku Set Base 긴소쿠 세트 기준
|
||||
Based on: 기준:
|
||||
Cannot Start Line 행 시작 금지 문자
|
||||
Cannot End Line 행 끝 금지 문자
|
||||
Hanging Punctuation 매달림 문장 부호
|
||||
Inseparable Characters 분리 금지 문자
|
||||
Push In First 밀어 넣기 우선
|
||||
Push Out First 밀어내기 우선
|
||||
Push Out Only 밀어내기만
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2659,6 +2659,15 @@ digits Malayalam Malayalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-set
|
||||
Kinsoku Shori Type Kinsoku Shori-type
|
||||
Kinsoku Shori Settings… Kinsoku Shori-instellingen…
|
||||
Kinsoku Shori Settings Kinsoku Shori-instellingen
|
||||
Kinsoku Sets Kinsoku-sets
|
||||
Kinsoku Set Base Basis van Kinsoku-set
|
||||
Based on: Gebaseerd op:
|
||||
Cannot Start Line Kan regel niet beginnen
|
||||
Cannot End Line Kan regel niet beëindigen
|
||||
Hanging Punctuation Hangende interpunctie
|
||||
Inseparable Characters Onscheidbare tekens
|
||||
Push In First Eerst inschuiven
|
||||
Push Out First Eerst uitschuiven
|
||||
Push Out Only Alleen uitschuiven
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2182,6 +2182,15 @@ digits Malayalam Malajalam
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Zestaw kinsoku
|
||||
Kinsoku Shori Type Typ kinsoku shori
|
||||
Kinsoku Shori Settings… Ustawienia kinsoku shori…
|
||||
Kinsoku Shori Settings Ustawienia kinsoku shori
|
||||
Kinsoku Sets Zestawy kinsoku
|
||||
Kinsoku Set Base Podstawa zestawu kinsoku
|
||||
Based on: Na podstawie:
|
||||
Cannot Start Line Nie może zaczynać wiersza
|
||||
Cannot End Line Nie może kończyć wiersza
|
||||
Hanging Punctuation Wisząca interpunkcja
|
||||
Inseparable Characters Znaki nierozdzielne
|
||||
Push In First Najpierw wciągaj
|
||||
Push Out First Najpierw wypychaj
|
||||
Push Out Only Tylko wypychaj
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4015,6 +4015,15 @@ font-technology Variable Variáveis
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Conjunto Kinsoku
|
||||
Kinsoku Shori Type Tipo de Kinsoku Shori
|
||||
Kinsoku Shori Settings… Configurações de Kinsoku Shori…
|
||||
Kinsoku Shori Settings Configurações de Kinsoku Shori
|
||||
Kinsoku Sets Conjuntos Kinsoku
|
||||
Kinsoku Set Base Base do conjunto Kinsoku
|
||||
Based on: Com base em:
|
||||
Cannot Start Line Não pode iniciar linha
|
||||
Cannot End Line Não pode terminar linha
|
||||
Hanging Punctuation Pontuação suspensa
|
||||
Inseparable Characters Caracteres inseparáveis
|
||||
Push In First Primeiro para dentro
|
||||
Push Out First Primeiro para fora
|
||||
Push Out Only Somente para fora
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2288,6 +2288,15 @@ file-filter Templates Шаблоны
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Набор kinsoku
|
||||
Kinsoku Shori Type Тип kinsoku shori
|
||||
Kinsoku Shori Settings… Настройки kinsoku shori…
|
||||
Kinsoku Shori Settings Настройки kinsoku shori
|
||||
Kinsoku Sets Наборы kinsoku
|
||||
Kinsoku Set Base Основа набора kinsoku
|
||||
Based on: На основе:
|
||||
Cannot Start Line Не может начинать строку
|
||||
Cannot End Line Не может заканчивать строку
|
||||
Hanging Punctuation Висячая пунктуация
|
||||
Inseparable Characters Неразрывные символы
|
||||
Push In First Сначала втягивать
|
||||
Push Out First Сначала выталкивать
|
||||
Push Out Only Только выталкивать
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2190,6 +2190,15 @@ font-technology Variable Variabla
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku-uppsättning
|
||||
Kinsoku Shori Type Kinsoku Shori-typ
|
||||
Kinsoku Shori Settings… Kinsoku Shori-inställningar…
|
||||
Kinsoku Shori Settings Kinsoku Shori-inställningar
|
||||
Kinsoku Sets Kinsoku-uppsättningar
|
||||
Kinsoku Set Base Grund för Kinsoku-uppsättning
|
||||
Based on: Baserad på:
|
||||
Cannot Start Line Kan inte inleda rad
|
||||
Cannot End Line Kan inte avsluta rad
|
||||
Hanging Punctuation Hängande skiljetecken
|
||||
Inseparable Characters Oskiljbara tecken
|
||||
Push In First Skjut in först
|
||||
Push Out First Skjut ut först
|
||||
Push Out Only Skjut endast ut
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2077,6 +2077,15 @@ font-technology Variable Değişken
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku Seti
|
||||
Kinsoku Shori Type Kinsoku Shori Türü
|
||||
Kinsoku Shori Settings… Kinsoku Shori Ayarları…
|
||||
Kinsoku Shori Settings Kinsoku Shori Ayarları
|
||||
Kinsoku Sets Kinsoku Setleri
|
||||
Kinsoku Set Base Kinsoku Seti Temeli
|
||||
Based on: Temel:
|
||||
Cannot Start Line Satır Başlatamaz
|
||||
Cannot End Line Satır Bitiremez
|
||||
Hanging Punctuation Asılı Noktalama
|
||||
Inseparable Characters Ayrılmaz Karakterler
|
||||
Push In First Önce İçeri
|
||||
Push Out First Önce Dışarı
|
||||
Push Out Only Yalnızca Dışarı
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2296,6 +2296,15 @@ file-filter Templates Шаблони
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Набір kinsoku
|
||||
Kinsoku Shori Type Тип kinsoku shori
|
||||
Kinsoku Shori Settings… Налаштування kinsoku shori…
|
||||
Kinsoku Shori Settings Налаштування kinsoku shori
|
||||
Kinsoku Sets Набори kinsoku
|
||||
Kinsoku Set Base Основа набору kinsoku
|
||||
Based on: На основі:
|
||||
Cannot Start Line Не може починати рядок
|
||||
Cannot End Line Не може закінчувати рядок
|
||||
Hanging Punctuation Висяча пунктуація
|
||||
Inseparable Characters Нероздільні символи
|
||||
Push In First Спершу втягувати
|
||||
Push Out First Спершу виштовхувати
|
||||
Push Out Only Лише виштовхувати
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2332,6 +2332,15 @@ digits Hindi Hindi
|
||||
Kind Loại
|
||||
Kinsoku Set Bộ Kinsoku
|
||||
Kinsoku Shori Type Kiểu Kinsoku Shori
|
||||
Kinsoku Shori Settings… Cài đặt Kinsoku Shori…
|
||||
Kinsoku Shori Settings Cài đặt Kinsoku Shori
|
||||
Kinsoku Sets Các bộ Kinsoku
|
||||
Kinsoku Set Base Cơ sở bộ Kinsoku
|
||||
Based on: Dựa trên:
|
||||
Cannot Start Line Không được bắt đầu dòng
|
||||
Cannot End Line Không được kết thúc dòng
|
||||
Hanging Punctuation Dấu câu treo
|
||||
Inseparable Characters Ký tự không thể tách rời
|
||||
Knife Dao
|
||||
Knockout Group Nhóm Knockout
|
||||
Lab Lab
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6091,6 +6091,15 @@ font-technology Variable 可变
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku 集
|
||||
Kinsoku Shori Type Kinsoku 处理方式
|
||||
Kinsoku Shori Settings… Kinsoku 处理设置…
|
||||
Kinsoku Shori Settings Kinsoku 处理设置
|
||||
Kinsoku Sets Kinsoku 集列表
|
||||
Kinsoku Set Base Kinsoku 集基准
|
||||
Based on: 基于:
|
||||
Cannot Start Line 不能位于行首
|
||||
Cannot End Line 不能位于行尾
|
||||
Hanging Punctuation 悬挂标点
|
||||
Inseparable Characters 不可分割字符
|
||||
Push In First 先推入
|
||||
Push Out First 先推出
|
||||
Push Out Only 只推出
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -3528,6 +3528,15 @@ liquify-list-end {0}, {1} {0}和{1}
|
||||
YakumonoZenkaku YakumonoZenkaku
|
||||
Kinsoku Set Kinsoku 集
|
||||
Kinsoku Shori Type Kinsoku 處理方式
|
||||
Kinsoku Shori Settings… Kinsoku 處理設定…
|
||||
Kinsoku Shori Settings Kinsoku 處理設定
|
||||
Kinsoku Sets Kinsoku 集清單
|
||||
Kinsoku Set Base Kinsoku 集基準
|
||||
Based on: 依據:
|
||||
Cannot Start Line 不能位於行首
|
||||
Cannot End Line 不能位於行尾
|
||||
Hanging Punctuation 懸掛標點
|
||||
Inseparable Characters 不可分割字元
|
||||
Push In First 先推入
|
||||
Push Out First 先推出
|
||||
Push Out Only 只推出
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -302,6 +302,13 @@ fn open_view_dialog(app: &mut VectorcraftApp, id: &str, p: &Value) -> bool {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Kinsoku Shori Settings…: the document's custom Kinsoku sets, to edit before OK sets them.
|
||||
if id == crate::dialogs::kinsoku_sets::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) {
|
||||
if let Err(e) = crate::dialogs::kinsoku_sets::open(app) {
|
||||
app.status(e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
// Edit Custom Dictionary…: the custom dictionary's words in a list, to add, delete or change.
|
||||
if id == crate::dialogs::custom_dictionary::COMMAND && p.as_object().is_none_or(|o| o.is_empty()) {
|
||||
if let Err(e) = crate::dialogs::custom_dictionary::open(app) {
|
||||
|
||||
@@ -148,9 +148,9 @@ fn swapped_out(app: &VectorcraftApp, id: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Menu items shown only with Preferences › Type › Show East Asian Options on: Type › Composite
|
||||
/// Fonts….
|
||||
/// Fonts… and Type › Kinsoku Shori Settings….
|
||||
fn east_asian_hidden(app: &VectorcraftApp, id: &str) -> bool {
|
||||
id == crate::dialogs::composite_fonts::COMMAND && !app.session.prefs.show_east_asian_options
|
||||
[crate::dialogs::composite_fonts::COMMAND, crate::dialogs::kinsoku_sets::COMMAND].contains(&id) && !app.session.prefs.show_east_asian_options
|
||||
}
|
||||
|
||||
/// How the menus show item `id` (params `p`) now: (enabled, checked: `Some` for an item that is on
|
||||
|
||||
@@ -457,6 +457,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec<Item>)> {
|
||||
Sep,
|
||||
c("Find Font…", "type.findFont"),
|
||||
c("Composite Fonts…", crate::dialogs::composite_fonts::COMMAND),
|
||||
c("Kinsoku Shori Settings…", crate::dialogs::kinsoku_sets::COMMAND),
|
||||
sub(
|
||||
"Change Case",
|
||||
vec![
|
||||
|
||||
@@ -8,8 +8,7 @@
|
||||
use egui::{Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{
|
||||
Composer, HyphenationOptions, JustificationOptions, Justify, Kinsoku, KinsokuShoriType, Mojikumi, NodeKind, ParaDirection, ParaStyle,
|
||||
SingleWordJustify,
|
||||
Composer, HyphenationOptions, JustificationOptions, Justify, KinsokuShoriType, Mojikumi, NodeKind, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
};
|
||||
|
||||
use super::character::{Metric, Shared, text_style};
|
||||
@@ -794,14 +793,22 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Which characters may not start or end a line.
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dim_label(ui, tl!("Kinsoku Set"));
|
||||
let sets = [(tl!("None"), Kinsoku::None, "none"), (tl!("Hard"), Kinsoku::Hard, "hard"), (tl!("Soft"), Kinsoku::Soft, "soft")];
|
||||
let names = sets.map(|s| s.0);
|
||||
let current = shared_para(app, |p| p.kinsoku).and_then(|k| sets.iter().find(|s| s.1 == k).map(|s| s.0)).unwrap_or("");
|
||||
let sets = [(tl!("None"), "None", "none"), (tl!("Hard"), "Hard", "hard"), (tl!("Soft"), "Soft", "soft")];
|
||||
let custom: Vec<String> = app.session.active().map(|st| st.doc.kinsoku_sets.iter().map(|k| k.name.clone()).collect()).unwrap_or_default();
|
||||
let mut names: Vec<&str> = sets.iter().map(|s| s.0).collect();
|
||||
names.extend(custom.iter().map(String::as_str));
|
||||
names.push(tl!("Kinsoku Shori Settings…"));
|
||||
let current = shared_kinsoku_name(app);
|
||||
let current = current.as_deref().map_or("", |n| sets.iter().find(|s| s.1 == n).map_or(n, |s| s.0));
|
||||
// Already translated: shown as they are.
|
||||
if let Some(i) = widgets::dropdown_names(ui, "pa-kinsoku", current, &names, ui.available_width() - 4.0)
|
||||
&& let Some((_, _, key)) = sets.get(i)
|
||||
{
|
||||
format(app, json!({"kinsoku": key}));
|
||||
if let Some(i) = widgets::dropdown_names(ui, "pa-kinsoku", current, &names, ui.available_width() - 4.0) {
|
||||
if let Some((_, _, key)) = sets.get(i) {
|
||||
format(app, json!({"kinsoku": key}));
|
||||
} else if let Some(name) = custom.get(i - sets.len()) {
|
||||
format(app, json!({"kinsoku": name}));
|
||||
} else {
|
||||
crate::menus::invoke(app, crate::dialogs::kinsoku_sets::COMMAND, json!({}));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -931,7 +938,23 @@ fn mojikumi_sets() -> [(&'static str, Mojikumi, &'static str); 6] {
|
||||
/// Bunri-Kinshi's menu item for the paragraphs the panel acts on ([`format`]): (available, checked).
|
||||
/// It is available when none of them has kinsoku None, and checked when every one of them has it.
|
||||
fn bunri_kinshi_item(app: &VectorcraftApp) -> (bool, bool) {
|
||||
(shared_para(app, |p| p.kinsoku == Kinsoku::None) == Some(false), shared_para(app, |p| p.bunri_kinshi) == Some(true))
|
||||
(shared_para(app, ParaStyle::kinsoku_on) == Some(true), shared_para(app, |p| p.bunri_kinshi) == Some(true))
|
||||
}
|
||||
|
||||
/// The Kinsoku set every paragraph the panel acts on ([`format`]) has, by name (None, Hard, Soft or
|
||||
/// a custom set's), or `None` when they differ.
|
||||
fn shared_kinsoku_name(app: &VectorcraftApp) -> Option<String> {
|
||||
let mut first: Option<String> = None;
|
||||
let mut differ = false;
|
||||
visit_paragraphs(app, |p| match &first {
|
||||
None => first = Some(p.kinsoku_name().to_string()),
|
||||
Some(n) => differ |= n != p.kinsoku_name(),
|
||||
});
|
||||
match first {
|
||||
None => text_style(app).map(|(_, p)| p.kinsoku_name().to_string()),
|
||||
Some(_) if differ => None,
|
||||
n => n,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bunri-Kinshi (Paragraph panel menu): a click turns it off for all the paragraphs the panel acts
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use vectorcraft_doc::Kinsoku;
|
||||
use vectorcraft_doc::Mojikumi;
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_engine::Session;
|
||||
@@ -184,6 +185,25 @@ fn paragraph_mixed_kinsoku_and_mojikumi_show_blank_dropdowns() {
|
||||
assert_eq!(shared_para(&app, |p| p.mojikumi), Some(Mojikumi::LineEndHalf));
|
||||
}
|
||||
|
||||
/// Kinsoku Set shows a custom set by its name, a blank when the paragraphs' sets differ, even when
|
||||
/// each has Hard under it; Bunri-Kinshi is available with a custom set.
|
||||
#[test]
|
||||
fn kinsoku_set_shows_a_custom_set_by_name() {
|
||||
let (mut app, id) = editing_text("A\nB\n");
|
||||
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Tight", "cannotStart": "」"}]})).unwrap();
|
||||
app.run("text.setFormat", json!({"id": id, "kinsoku": "hard"})).unwrap();
|
||||
app.run("text.setFormat", json!({"id": id, "start": 2, "end": 3, "kinsoku": "tight"})).unwrap();
|
||||
app.session.set_tool_option("selectAll", &json!(true));
|
||||
assert_eq!(shared_para(&app, |p| p.kinsoku), Some(Kinsoku::Hard));
|
||||
assert_eq!(shared_kinsoku_name(&app), None);
|
||||
app.run("text.setFormat", json!({"id": id, "kinsoku": "Tight"})).unwrap();
|
||||
assert_eq!(shared_kinsoku_name(&app).as_deref(), Some("Tight"));
|
||||
assert!(bunri_kinshi_item(&app).0);
|
||||
app.run("text.setFormat", json!({"id": id, "kinsoku": "none"})).unwrap();
|
||||
assert_eq!(shared_kinsoku_name(&app).as_deref(), Some("None"));
|
||||
assert!(!bunri_kinshi_item(&app).0);
|
||||
}
|
||||
|
||||
/// The Mojikumi Set menu lists None, the four other predefined sets and Line-end Punctuation Half
|
||||
/// Width, each under its own label in every interface language. Each entry sets the selected
|
||||
/// paragraphs' set in one undo step and is shown as the current set; paragraphs with different
|
||||
|
||||
+53
-10
@@ -11052,12 +11052,50 @@ which Japanese characters may not start or end a line. **Hard** (the default; ne
|
||||
setting) keeps closing brackets, commas, full stops, middle dots, iteration marks, the prolonged sound mark ー and small
|
||||
kana off the line start, and opening brackets off the line end. **Soft** lets 々, ー and small kana start a line, as
|
||||
JLREQ's level 3 line-breaking rules do (https://www.w3.org/TR/jlreq/#addendum_a3); the rest of the set stays.
|
||||
**None** applies no kinsoku. `hard` isn't saved. One undo step.
|
||||
**None** applies no kinsoku. `hard` isn't saved. The name of a custom set of the document (`type.kinsokuSets.list`, any
|
||||
case) gives each paragraph a copy of that set, saved with the paragraph (`kinsoku_set` in `para`) beside Hard, so an
|
||||
older build reads the paragraph as Hard; a name the document has no set of fails the call and changes nothing.
|
||||
Paragraph styles carry the set; `paraStyle.new` and `paraStyle.setAttrs` given `kinsoku_set` with `kinsoku` None or Soft,
|
||||
or with a blank or built-in set name, fail and change nothing. One undo step.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"text.setFormat","params":{"kinsoku":"soft"}}}
|
||||
```
|
||||
|
||||
## Kinsoku Shori Settings
|
||||
|
||||
`type.kinsokuSets.set {sets: [{name, from?, cannotStart?, cannotEnd?, hanging?, inseparable?}]}` (Type › Kinsoku Shori
|
||||
Settings…'s OK, shown with the East Asian options) replaces the active document's custom Kinsoku Shori sets as one undo
|
||||
step, and records none when nothing changes. `cannotStart` lists the characters that never start a line, `cannotEnd`
|
||||
those that never end one, and `hanging` the punctuation that Burasagari hangs outside a line's end, each as text, one
|
||||
character after another. `inseparable` lists sequences of 2 to 16 characters that a line never breaks inside while
|
||||
Bunri-Kinshi is on. `cannotStart`, `cannotEnd` and `hanging` keep each character once, sorted; `inseparable` keeps each
|
||||
sequence once, sorted, so a sequence may repeat a character (`……`). Each category holds at most 4096 characters (a
|
||||
sequence counts each of its characters); a control or space character in a category fails the call. Names are trimmed, 1 to 128 characters, unique in any
|
||||
case and never None, Hard or Soft; a document holds at most 256 sets. These limits are VectorCraft's own. A set with
|
||||
the name of a set the document has (any case) and no `from` edits that set; `from` names the set it renames. Every
|
||||
paragraph and paragraph style using an edited set takes its new characters and name, and those using a set left out
|
||||
take Hard. An unknown key, a null value, a name used twice, a `from` the document has no set of and a sequence of one
|
||||
character fail the call and change nothing. The built-in None, Hard and Soft are not stored and can't be changed. → `{sets}`.
|
||||
|
||||
`type.kinsokuSets.list` returns the sets with how many paragraphs (`paragraphs`), paragraph styles (`styles`) and graphs
|
||||
(`graphs`, in the paragraph attributes a graph keeps for its labels) use each. `type.kinsokuSets.base {base: "hard"|"soft"|"none"|name, name?}` returns the categories a new set based on a
|
||||
built-in or custom set starts with: 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 Bunri-Kinshi pairs; None lists nothing.
|
||||
|
||||
Type › Kinsoku Shori Settings… opens a dialog on the document's sets: Kinsoku Set picks one, New adds a set based on
|
||||
the choice in Based on (Hard, Soft, None or a set of the dialog), Delete takes the one picked out, the four fields edit
|
||||
its categories (inseparable sequences separated by spaces), and Unicode with Add puts the character of a code point
|
||||
(`U+3001` or `3001`) into Cannot Start Line, Cannot End Line or Hanging Punctuation. Nothing changes until OK, which
|
||||
runs `type.kinsokuSets.set`; a refused set keeps the dialog open. The Paragraph panel's Kinsoku Set lists the custom
|
||||
sets after None, Hard and Soft, and its last entry opens the dialog. Importing and exporting sets is not available.
|
||||
The help page:
|
||||
https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"type.kinsokuSets.set","params":{"sets":[{"name":"Tight","cannotStart":"、。」ー","cannotEnd":"「(","hanging":"、。","inseparable":["——","……"]}]}}}
|
||||
```
|
||||
|
||||
## Kinsoku Shori Type
|
||||
|
||||
`text.setFormat {kinsokuType: "pushInFirst"|"pushOutFirst"|"pushOutOnly"}` (Paragraph panel menu › Kinsoku Shori Type,
|
||||
@@ -11070,8 +11108,8 @@ of the character before it and by at most a tenth of that em; a line that cannot
|
||||
tab, pushes out instead. **Push Out First** pushes in
|
||||
the same way only when pushing out would leave the line more than an em, of the character before the break, short of
|
||||
its measure. **Push Out Only** (the default: new type and documents from before the setting) moves the
|
||||
character before a prohibited line start to the next line with it. With Burasagari on, an overflowing comma or full
|
||||
stop may hang outside the margin first, leaving the preceding character on the line. With Kinsoku Set None the setting
|
||||
character before a prohibited line start to the next line with it. With Burasagari on, overflowing hanging punctuation
|
||||
of the Kinsoku Set may hang outside the margin first, leaving the preceding character on the line. With Kinsoku Set None the setting
|
||||
does nothing. When Push In First or Push Out First is selected and a paragraph contains a prohibited line-start or
|
||||
line-end character, the whole paragraph is broken line by line, as the Single-line Composer breaks it, even if no line
|
||||
ends up pushing a character in. The setting is saved
|
||||
@@ -11089,10 +11127,13 @@ on or off for the paragraphs of the selected type (or `ids`, or the paragraphs a
|
||||
line never breaks inside an inseparable pair: two em dashes (U+2014), two horizontal ellipses (U+2026), two two-dot
|
||||
leaders (U+2025), or the upper half of a vertical kana repeat mark (U+3033 or U+3034) followed by its lower half
|
||||
(U+3035), the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08), which are VectorCraft's
|
||||
set. A chain of em dashes stays together as well. A pair is two neighboring characters, whatever their fonts and
|
||||
styles; a forced line break between them ends the line as before. Both composers, vertical type, Kinsoku Shori Type,
|
||||
hyphenation and No Break follow it, and a pair wider than the line stays whole on it. Justification adds no space inside
|
||||
a pair. The setting works only with a Kinsoku Set: with Kinsoku Set None the paragraph keeps the value without effect,
|
||||
set for Hard and Soft. A chain of em dashes stays together as well. With a custom Kinsoku Set, the set's inseparable
|
||||
sequences (Kinsoku Shori Settings) replace these pairs: a line never breaks between two characters of an occurrence of
|
||||
one of them, such as `AB` or `あいう`, and occurrences may overlap. A custom set keeps a built-in pair together only
|
||||
when it lists that pair, as a set based on Hard or Soft does. A pair or sequence is neighboring characters, whatever
|
||||
their fonts and styles; a forced line break between them ends the line as before. Both composers, vertical type,
|
||||
Kinsoku Shori Type, hyphenation and No Break follow it, and a pair or sequence wider than the line stays whole on it.
|
||||
Justification adds no space inside a pair or sequence. The setting works only with a Kinsoku Set: with Kinsoku Set None the paragraph keeps the value without effect,
|
||||
and the menu item is unavailable. Off by default, for new type and for paragraphs saved before the option. It is saved
|
||||
with the paragraph (`bunri_kinshi` in `para`) only when on, paragraph styles carry it (Paragraph Style Options › East
|
||||
Asian Composition Settings), and Reset Panel turns it off. A value that is not true or false is refused. One undo
|
||||
@@ -11151,9 +11192,11 @@ help page: https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-an
|
||||
## Hanging punctuation (burasagari)
|
||||
|
||||
`text.setFormat {burasagari: "none"|"standard"|"forced"}` sets the Paragraph panel menu's Burasagari (None / Regular /
|
||||
Force) of the selected type (or `ids`): an East Asian comma or full stop ending an area type line (、。,., half-width
|
||||
、。) hangs outside the frame, Regular only when it doesn't fit, Force always (the rest of the line then fills the
|
||||
measure). Closing brackets and Latin punctuation don't hang; point type, right-to-left and hyphenated lines are left as
|
||||
Force) of the selected type (or `ids`): hanging punctuation ending an area type line hangs outside the frame, Regular
|
||||
only when it doesn't fit, Force always (the rest of the line then fills the measure). With the Kinsoku Sets None, Hard
|
||||
and Soft, the hanging punctuation is the East Asian comma and full stop (、。,., half-width 、。), and closing brackets and
|
||||
Latin punctuation don't hang. A custom Kinsoku Set hangs the characters in its `hanging` category instead (Kinsoku Shori
|
||||
Settings), closing brackets and Latin punctuation included. Point type, right-to-left and hyphenated lines are left as
|
||||
they are. The hanging mark is as wide as its punctuation spacing makes it (`mojikumi`). New type (the Type tools,
|
||||
`text.create`) takes `standard`; documents from before it and imported text keep `none`, except legacy `.ai` type
|
||||
with binding punctuation (`Tg`) on, which opens as `forced`. `none` isn't saved. One undo step.
|
||||
|
||||
@@ -1716,7 +1716,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
Optical Margin Alignment and Roman Hanging Punctuation hang right-to-left paragraphs of point and area type, and type on a path whose first paragraph runs right to left, too. Auto aligns a right-to-left line at its right, or at the end bracket of a path, so it hangs there. A right-to-left line is read from right to left: where it hangs at its left margin, `."` ending it hangs both glyphs.
|
||||
Type on a path with right-to-left text that does not fit shows the longest start of its text whose glyphs fit, also where tracking gives a letter a negative advance and a shorter start does not fit; the rest overflows or flows to the next threaded object (VectorCraft's own rule). Without hanging punctuation, and on a straight path or with no spacing, every start is measured without arranging it on the path again. With hanging punctuation, or spacing on a curve, when a letter has a negative advance, at most 32 of the starts that could fit are arranged one by one from the longest; when none of them fits, a binary search over the rest shows a start that fits, which is not always the longest (`overflowing_rtl_type_on_a_path_shows_the_longest_start_that_fits`, `the_longest_rtl_start_on_a_path_is_found_without_arranging_each_start`, `the_longest_rtl_start_on_a_path_is_the_one_each_start_gives` and `rtl_type_on_a_curve_whose_letters_take_the_line_back_is_arranged_a_bounded_number_of_times` in `crates/text/src/tests/bidi.rs`). Right-aligned and centered type on a curve with Spacing is placed by what its glyphs take where the line ends up, so text that fits is not cut off at the end bracket (`on_path_aligned_spaced_text_that_fits_shows_whole` in `crates/text/src/tests.rs`).
|
||||
The Paragraph panel menu's Kinsoku Shori Type (`text.setFormat {kinsokuType}`, with the East Asian options) picks Push In First, Push Out First or Push Out Only for each paragraph: a character the Kinsoku Set keeps off a line's start or end is set on the line, with the line's gaps next to CJK characters closed by at most a tenth of an em each to fit, or moved to the next line with the character before it. Push Out First pushes in only when pushing out would leave the line more than an em short. Push Out Only is the default, the setting is saved only when it is not, and paragraph styles carry it.
|
||||
The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; editing the set of pairs is not available.
|
||||
The Paragraph panel menu's Bunri-Kinshi (`text.setFormat {bunriKinshi}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) keeps inseparable pairs on one line in each paragraph that has it: two em dashes, two ellipses, two two-dot leaders and the two halves of a vertical kana repeat mark (the pairs of W3C JLREQ's class cl-08, VectorCraft's set). Both composers and vertical type follow it, and justification adds no space inside a pair. It works with a Kinsoku Set only, is off by default and is saved only when on; the built-in pairs can't be edited, and a custom Kinsoku set keeps its own inseparable sequences instead.
|
||||
Type › Kinsoku Shori Settings… (`type.kinsokuSets.set`, with the East Asian options) creates, edits, renames and deletes the document's custom Kinsoku Shori sets, each a list of characters that may not start a line, characters that may not end one, hanging punctuation and inseparable sequences, new ones based on Hard, Soft, None or another set, with characters added by Unicode code point. The Paragraph panel's Kinsoku Set and paragraph styles choose a custom set for each paragraph (`text.setFormat {kinsoku: name}`); editing a set changes the paragraphs that use it, and deleting one gives them Hard. Importing and exporting sets is not available ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-kinsoku-for-japanese-line-breaking.html)).
|
||||
`.ai` import reads each paragraph's Kinsoku Set (None, Hard or Soft), Kinsoku Shori Type, Burasagari and Bunri-Kinshi from the file's editable text: the paragraph's own setting, else its paragraph style's or a style that one is based on, else the document's default. A paragraph with a custom Kinsoku set takes its paragraph style's set, and the importer warns about it. A value it cannot read takes its paragraph style's value too. An `.ai` save writes all four settings for every paragraph, the normal paragraph style and the document's defaults, and lists the Hard and Soft sets, in the form that reader reads, so they reopen as set and are not reported as left out; Burasagari and Bunri-Kinshi keep their values under Kinsoku None.
|
||||
The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move.
|
||||
The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step.
|
||||
|
||||
Reference in New Issue
Block a user