Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #537: Engine: report the selected text; remember recently used fonts

aionggbbd6a6c2773e
diff --cc crates/engine/src/cmd/text.rs
index 794d6262e,2781d83ab..e4c5141ff
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@@ -307,15 -253,7 +307,15 @@@ pub fn specs() -> Vec<CommandSpec>
has_text_or_frames,
break_link
),
- cmd!(query "type.selectionAttrs", "Selection Attributes", [], None, "{} → resolved character/paragraph attributes at the text selection, and its start as `selectedText` (one line, up to 60 characters)", has_doc, selection_attrs),
+ cmd!(
+ query "type.selectionAttrs",
+ "Selection Attributes",
+ [],
+ None,
- "{mixed?: bool} → resolved character/paragraph attributes at the text selection; with mixed, paraMixed lists the paragraph attributes that differ across the selected paragraphs",
++ "{mixed?: bool} → resolved character/paragraph attributes at the text selection; with mixed, paraMixed lists the paragraph attributes that differ across the selected paragraphs; the selection's start as `selectedText` (one line, up to 60 characters)",
+ has_doc,
+ selection_attrs
+ ),
]
}
@@@ -1454,7 -957,10 +1454,10 @@@ fn open_type(s: &mut Session, p: &Value
Ok(json!({"features": list, "figures": otf::figures(&list)}))
}
+ /// How much of the selected text `type.selectionAttrs` reports.
+ const SELECTED_TEXT_CHARS: usize = 60;
+
-fn selection_attrs(s: &mut Session, _p: &Value) -> Result<Value> {
+fn selection_attrs(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let targets = format_targets(s);
let Some(Target { story: sid, cell, range: r }) = targets.first().cloned() else { return Ok(Value::Null) };
@@@ -1462,93 -968,19 +1465,102 @@@
let pi = story.para_at(r.start);
let pf = &story.paras[pi];
let (pp, base) = st.doc.styles.resolve_para(pf);
- let cf = if r.is_empty() { story.char_format_at(r.start) } else { story.format_after(r.start) };
- let cp = st.doc.styles.resolve_char(&base, cf);
+ let mut cf = if r.is_empty() { story.char_format_at(r.start) } else { story.format_after(r.start) }.clone();
+ if let Some(f) = typing_format(s) {
+ apply_typing_format(&mut cf, f);
+ }
+ let cp = st.doc.styles.resolve_char(&base, &cf);
+ // The selected text (its start, on one line), for previews such as the font menu's.
+ let line: String = story
+ .text
+ .get(r.start..r.end)
+ .unwrap_or_default()
+ .chars()
+ .map(|c| if c.is_control() || c == designcraft_doc::OBJECT_MARK { ' ' } else { c })
+ .collect();
+ let selected: String = line.trim_start().chars().take(SELECTED_TEXT_CHARS).collect();
- Ok(json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,
- "paraOverrides": pf.para.count(), "charOverrides": cf.over.count(), "selectedText": selected.trim()}))
+ let mut out = json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,
- "paraOverrides": pf.para.count(), "charOverrides": cf.over.count()});
++ "paraOverrides": pf.para.count(), "charOverrides": cf.over.count(), "selectedText": selected.trim()});
+ if bool_or(p, "mixed", false) {
+ out["paraMixed"] = json!(mixed_para_attrs(&st.doc, &targets));
+ }
+ Ok(out)
+}
+
+/// The paragraph attributes whose resolved values differ across the paragraphs of `targets`.
+fn mixed_para_attrs(doc: &designcraft_doc::Document, targets: &[Target]) -> Vec<String> {
+ let mut first: Option<serde_json::Map<String, Value>> = None;
+ let mut mixed = std::collections::BTreeSet::new();
+ for t in targets {
+ let Some(story) = doc.text_story(t.story, t.cell) else { continue };
+ let a = story.para_at(t.range.start);
+ let b = story.para_at(t.range.end.max(t.range.start));
+ for pf in story.paras.get(a..=b).unwrap_or(&[]) {
+ let Ok(Value::Object(v)) = serde_json::to_value(doc.styles.resolve_para(pf).0) else { continue };
+ match &first {
+ None => first = Some(v),
+ Some(f) => mixed.extend(v.into_iter().filter(|(k, x)| f.get(k) != Some(x)).map(|(k, _)| k)),
+ }
+ }
+ }
+ mixed.into_iter().collect()
+}
+
+fn apply_typing_format(cf: &mut designcraft_doc::CharFormat, f: &TypingFormat) {
+ cf.over.merge(&f.attrs);
+ for k in &f.cleared {
+ let _ = cf.over.set_json(k, &Value::Null);
+ }
+}
+
+/// Bold (`bold`) or italic from the font family (style linking), per run of the selection: on or
+/// off as asked, else the opposite of the first selected character.
+fn link_style(s: &mut Session, p: &Value, bold: bool) -> Result<Value> {
+ let id = if bold { "type.bold" } else { "type.italic" };
+ let cur = selection_attrs(s, &json!({}))?;
+ let family = cur["chars"]["fontFamily"].as_str().unwrap_or_default().to_string();
+ let style = cur["chars"]["fontStyle"].as_str().unwrap_or_default().to_string();
+ // The document's own fonts count too.
+ let db = designcraft_fonts::FontDb::global().scoped(s.doc()?.doc.font_scope);
+ let (weight, italic) = db.traits_of(&family, &style);
+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(if bold { weight < 650.0 } else { !italic });
+ let (want_bold, want_italic) = if bold { (Some(on), None) } else { (None, Some(on)) };
+ let targets = format_targets(s);
+ // A caret: the linked style of the format there, for the next typing.
+ if let [t] = targets.as_slice()
+ && t.range.is_empty()
+ {
+ let linked = db.linked_style(&family, &style, want_bold, want_italic).ok_or_else(|| bad(id, format!("{family} has no style for that")))?;
+ format_chars(s, &json!({"fontStyle": linked}))?;
+ return Ok(json!({"on": on, "fontStyle": linked}));
+ }
+ let mut changed = 0;
+ let r = s.edit(|d, _| {
+ let styles = d.styles.clone();
+ for t in &targets {
+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };
+ for (pi, pr) in st.para_ranges().into_iter().enumerate() {
+ let (a, b) = (pr.start.max(t.range.start), pr.end.min(t.range.end));
+ if a >= b {
+ continue;
+ }
+ let Some(pf) = st.paras.get(pi) else { continue };
+ let (_, pc) = styles.resolve_para(pf);
+ st.format_chars(a..b, |f| {
+ let cp = styles.resolve_char(&pc, f);
+ if let Some(linked) = db.linked_style(&cp.font_family, &cp.font_style, want_bold, want_italic)
+ && linked != cp.font_style
+ {
+ f.over.font_style = Some(linked);
+ changed += 1;
+ }
+ });
+ }
+ }
+ ok()
+ });
+ r?;
+ Ok(json!({"on": on, "changed": changed}))
}
/// Our own filler text (not Adobe's).
diff --cc crates/engine/src/lib.rs
index 2f5040314,cfb1bb370..4b539034d
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -258,8 -235,8 +260,9 @@@ impl Default for Prefs
highlight_substituted_fonts: true,
rich_black_output: false,
favorite_fonts: Vec::new(),
+ recent_fonts: Vec::new(),
show_font_names_in_english: false,
+ cjk_features: None,
smart_text_reflow: true,
autocorrect: false,
autocorrect_list: default_autocorrect(),