Skip to content

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

Text editing: clicks, trailing spaces, bold/italic, clipboard, formatting affects text (#23)

aiongg2d6213d40d06
diff --git a/Cargo.lock b/Cargo.lock
index e5ae30382..a2b4e6f3a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -857,6 +857,7 @@ dependencies = [
name = "designcraft"
version = "0.2.1"
dependencies = [
+ "arboard",
"designcraft-engine",
"designcraft-ui-egui",
"eframe",
diff --git a/apps/designcraft/Cargo.toml b/apps/designcraft/Cargo.toml
index eaacdd328..737eb00a5 100644
--- a/apps/designcraft/Cargo.toml
+++ b/apps/designcraft/Cargo.toml
@@ -23,6 +23,7 @@ winresource = "0.1"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rfd = { workspace = true }
+arboard = { workspace = true }
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
# The same winit eframe uses: to pick the X11 backend (file drag-and-drop) in main.rs.
diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs
index 2fb3a1fb9..228e4dd9f 100644
--- a/apps/designcraft/src/main.rs
+++ b/apps/designcraft/src/main.rs
@@ -152,6 +152,7 @@ fn services() -> Services {
pick_save: Some(Box::new(|name: &str| rfd::FileDialog::new().set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()))),
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))),
+ clipboard_text: Some(Box::new(|| arboard::Clipboard::new().and_then(|mut c| c.get_text()).ok())),
..Default::default()
}
}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 9f91aa68f..25361b636 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -35,9 +35,9 @@ use designcraft_geom::{Point, Rect};
use crate::breaker::{Break, Spacing};
pub use crate::cache::Cache;
use crate::notes::Notes;
-pub use crate::notes::{find_note, hit_note, note_caret};
+pub use crate::notes::{find_note, hit_note, hit_note_with, note_caret};
use crate::shape::{Glyph, StyleTable, SubstCtx};
-pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell};
+pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell, hit_cell_with};
/// Character appearance shared by many glyphs (indexed from [`PlacedGlyph::style`]).
#[derive(Clone, Debug, PartialEq)]
@@ -795,6 +795,15 @@ pub fn compose(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &Compo
let last = k + 1 == breaks.len();
let (mut placed, end_x, ratio) =
layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, last, b.forced && !last, f.left_page);
+ // The spaces the break trimmed off the end follow the line undrawn, so the caret
+ // and the selection reach them; alignment and justification ignore them.
+ if !placed.iter().any(|g| g.rtl) {
+ let mut x = end_x;
+ for g in glyphs.get(e..(g0 + b.next).min(glyphs.len())).unwrap_or(&[]).iter().filter(|g| g.is_space()) {
+ placed.push(PlacedGlyph { visible: false, ..place(g, x) });
+ x += g.adv;
+ }
+ }
ruby::annotate(&styles_tab, &mut placed);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
@@ -2047,6 +2056,8 @@ pub fn caret_x(l: &Line, pos: usize) -> f64 {
}
match l.glyphs.iter().rev().find(|g| g.len > 0) {
Some(g) if g.rtl => g.x,
+ // After the spaces that end the line.
+ Some(g) if !g.visible && g.x >= l.end_x - 1e-9 => g.x + g.adv,
_ => l.end_x,
}
}
@@ -2080,19 +2091,42 @@ pub fn line_rtl(cs: &ComposedStory, pos: usize) -> bool {
caret_line(cs, pos).and_then(|(_, l)| l.glyphs.iter().find(|g| g.len > 0)).is_some_and(|g| g.rtl)
}
+/// The line of frame `ft` closest to point `p` vertically (within its column).
+fn hit_line(ft: &FrameText, p: Point) -> Option<&Line> {
+ ft.lines
+ .iter()
+ .filter(|l| p.x >= l.x0 - 20.0 && p.x <= l.x1 + 20.0 || ft.columns.len() <= 1)
+ .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)))
+ .or_else(|| ft.lines.first())
+}
+
+/// Story byte of the character drawn under point `p` (frame inner space) in frame `fi`: the
+/// glyph whose advance spans `p.x` on the closest line, else the one nearest it. For selecting
+/// the word (or the spaces) under a double click; [`hit`] finds a caret position instead.
+pub fn hit_char(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {
+ let ft = cs.frames.get(fi)?;
+ let Some(l) = hit_line(ft, p) else { return Some(ft.range.start) };
+ let dist = |g: &&PlacedGlyph| {
+ let (a, b) = (g.x.min(g.x + g.adv), g.x.max(g.x + g.adv));
+ if p.x < a {
+ a - p.x
+ } else if p.x >= b {
+ p.x - b
+ } else {
+ 0.0
+ }
+ };
+ let under = l.glyphs.iter().filter(|g| g.len > 0).min_by(|a, b| dist(a).total_cmp(&dist(b)));
+ Some(under.map_or(l.range.start, |g| g.byte))
+}
+
/// Story byte nearest to point `p` (frame inner space) in frame `fi`.
pub fn hit(cs: &ComposedStory, fi: usize, p: Point) -> Option<usize> {
let ft = cs.frames.get(fi)?;
if ft.lines.is_empty() {
return Some(ft.range.start);
}
- // Closest line vertically (within its column).
- let l = ft
- .lines
- .iter()
- .filter(|l| p.x >= l.x0 - 20.0 && p.x <= l.x1 + 20.0 || ft.columns.len() <= 1)
- .min_by(|a, b| line_dist(a, p.y).total_cmp(&line_dist(b, p.y)))
- .or_else(|| ft.lines.first())?;
+ let l = hit_line(ft, p)?;
if l.glyphs.iter().any(|g| g.rtl) {
// Bidi: the caret position drawn nearest the point.
return caret_stops(l).into_iter().min_by(|a, b| (a.1 - p.x).abs().total_cmp(&(b.1 - p.x).abs())).map(|s| s.0);
diff --git a/crates/compose/src/notes.rs b/crates/compose/src/notes.rs
index d806b5460..4fe538fd6 100644
--- a/crates/compose/src/notes.rs
+++ b/crates/compose/src/notes.rs
@@ -196,10 +196,15 @@ pub fn find_note(cs: &ComposedStory, id: u64) -> Option<(usize, &PlacedNote)> {
/// Footnote text hit at frame-inner point `p`: (footnote id, byte in the footnote's story).
pub fn hit_note(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize)> {
+ hit_note_with(cs, fi, p, crate::hit)
+}
+
+/// [`hit_note`] with the hit test for the note's text (see [`crate::hit_cell_with`]).
+pub fn hit_note_with(cs: &ComposedStory, fi: usize, p: Point, hit: fn(&ComposedStory, usize, Point) -> Option<usize>) -> Option<(u64, usize)> {
let ft = cs.frames.get(fi)?;
let n = ft.notes.iter().find(|n| n.rect.contains(p))?;
let local = Point::new(p.x - n.origin.x, p.y - n.origin.y);
- Some((n.id, crate::hit(&n.text, 0, local).unwrap_or(0)))
+ Some((n.id, hit(&n.text, 0, local).unwrap_or(0)))
}
/// Caret geometry for byte `pos` of a footnote's story, in frame inner space:
diff --git a/crates/compose/src/table.rs b/crates/compose/src/table.rs
index bda001820..0a7ca62fb 100644
--- a/crates/compose/src/table.rs
+++ b/crates/compose/src/table.rs
@@ -428,6 +428,17 @@ fn emit(
/// The cell under `p` (frame inner space) in frame `fi`: (table, row, col, story byte in the cell).
pub fn hit_cell(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize, usize, usize)> {
+ hit_cell_with(cs, fi, p, crate::hit)
+}
+
+/// [`hit_cell`] with the hit test for the cell's text: [`crate::hit`] (caret position) or
+/// [`crate::hit_char`] (character under the point).
+pub fn hit_cell_with(
+ cs: &ComposedStory,
+ fi: usize,
+ p: Point,
+ hit: fn(&ComposedStory, usize, Point) -> Option<usize>,
+) -> Option<(u64, usize, usize, usize)> {
let ft = cs.frames.get(fi)?;
for t in &ft.tables {
if !t.rect.contains(p) {
@@ -436,7 +447,7 @@ pub fn hit_cell(cs: &ComposedStory, fi: usize, p: Point) -> Option<(u64, usize,
for c in &t.cells {
if c.rect.contains(p) {
let local = Point::new(p.x - c.origin.x, p.y - c.origin.y);
- let b = crate::hit(&c.text, 0, local).unwrap_or(0);
+ let b = hit(&c.text, 0, local).unwrap_or(0);
return Some((t.table, c.row, c.col, b));
}
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 511a703a5..1d7588cf8 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1027,3 +1027,29 @@ fn only_english_text_gets_english_hyphenation() {
st.format_chars(0..n, |f| f.over.language = Some("French".into()));
assert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");
}
+
+#[test]
+fn caret_follows_spaces_typed_at_the_end() {
+ let x_at_end = |text: &str| {
+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let end_x = cs.frames[0].lines[0].end_x;
+ (caret(&cs, text.len()).unwrap().1, end_x)
+ };
+ let (word, word_end) = x_at_end("Word");
+ let (one, one_end) = x_at_end("Word ");
+ let (two, _) = x_at_end("Word ");
+ assert!(one > word + 1.0 && two > one + 1.0, "{word} {one} {two}");
+ // The spaces don't count for the line's own length (alignment, justification).
+ assert!((one_end - word_end).abs() < 1e-9);
+ // Wrapped lines keep their spaces too: a caret between two spaces at a line end sits after
+ // the first one.
+ let text = "Lorem ipsum dolor sit amet consectetur";
+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 140.0, 100.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l0 = &cs.frames[0].lines[0];
+ if l0.range.end == text.find("consectetur").unwrap() {
+ let mid = text.find(" ").unwrap() + 1;
+ assert!(caret(&cs, mid).unwrap().1 > l0.end_x, "between the trailing spaces");
+ }
+}
diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs
index d1fccebf7..2dd112206 100644
--- a/crates/engine/src/cmd/style.rs
+++ b/crates/engine/src/cmd/style.rs
@@ -127,8 +127,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Color",
[],
None,
- "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection",
- super::has_selection,
+ "{color: \"#rrggbb\"|{c,m,y,k}(0..100)|[r,g,b](0..255), target?: fill|stroke, text?: bool, ids?} — an unnamed colour (not in the Swatches panel until Add to Swatches) on the selection; `text`: on the selected text, or the text of the selected frames (Formatting Affects Text)",
+ |s| super::has_text(s).or_else(|_| super::has_selection(s)),
apply_color
),
cmd!(
@@ -821,8 +821,11 @@ fn apply_gradient(s: &mut Session, p: &Value) -> Result<Value> {
fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {
let color = p.get("color").and_then(parse_color).ok_or_else(|| bad("object.color", "missing or bad color"))?;
let stroke = str_param(p, "target") == Some("stroke");
- let ids = super::targets(s, p)?;
- s.edit(|d, _| {
+ let text = p.get("text").and_then(Value::as_bool).unwrap_or(false) || s.doc()?.selection.text.is_some();
+ let (ids, texts) = if text { (vec![], super::text::format_targets_pub(s)) } else { (super::targets(s, p)?, vec![]) };
+ // A caret: the colour is for the next typing (once the swatch exists).
+ let caret = matches!(texts.as_slice(), [t] if t.range.is_empty());
+ let r = s.edit(|d, _| {
// Reuse a swatch holding exactly this colour, else add an unnamed one.
let existing = d
.swatches
@@ -854,8 +857,21 @@ fn apply_color(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
+ if !caret {
+ let a = if stroke {
+ CharAttrs { stroke: Some(name.clone()), stroke_tint: Some(1.0), ..Default::default() }
+ } else {
+ CharAttrs { fill: Some(name.clone()), fill_tint: Some(1.0), ..Default::default() }
+ };
+ super::text::apply_char_attrs(d, &texts, &a, &[]);
+ }
Ok(json!({"swatch": name}))
- })
+ })?;
+ if caret && let Some(name) = r.get("swatch").cloned() {
+ let attrs = if stroke { json!({"stroke": name, "strokeTint": 1.0}) } else { json!({"fill": name, "fillTint": 1.0}) };
+ super::text::format_chars(s, &attrs)?;
+ }
+ Ok(r)
}
fn add_to_swatches(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index a3cb09ca3..553e27721 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -22,15 +22,18 @@ pub fn specs() -> Vec<CommandSpec> {
release
),
cmd!(noundo "text.extendTo", "Extend Text Selection", [], None, "{frame, point}", has_doc, |s, p| place(s, p, true)),
- cmd!(noundo "text.selectWord", "Select Word", [], None, "{frame, point}", has_doc, |s, p| {
- place(s, p, false)?;
- let st = s.doc_mut()?;
- let Some(t) = st.selection.text else { return ok() };
- let text = &st.doc.text_story(t.story, t.cell).map(|x| x.text.clone()).unwrap_or_default();
- let (a, b) = word_bounds(text, t.focus);
- st.selection.text = Some(TextSel { anchor: a, focus: b, ..t });
- ok()
+ cmd!(noundo "text.selectWord", "Select Word", [], None, "{frame, point} — the word (or run of spaces) under the point", has_doc, |s, p| {
+ select_at(s, p, "word")
}),
+ cmd!(
+ noundo "text.selectAt",
+ "Select Text Unit",
+ [],
+ None,
+ "{frame, point, unit: word|line|paragraph|story} — what a double, triple, quadruple or quintuple click selects: the word (or run of spaces) under the point, its line, paragraph or the whole story",
+ has_doc,
+ |s, p| select_at(s, p, str_param(p, "unit").unwrap_or("word"))
+ ),
cmd!(noundo "text.select", "Select Text", [], None, "{story, anchor, focus} (UTF-8 byte offsets into the story text, as find.find reports them: á or — counts 2 or 3)", has_doc, |s, p| {
let sid = StoryId(p.get("story").and_then(Value::as_u64).unwrap_or(0));
let st = s.doc_mut()?;
@@ -132,8 +135,24 @@ pub fn specs() -> Vec<CommandSpec> {
s,
&json!({"align": "leftJustified"})
)),
- cmd!("type.bold", "Bold", [], Some("Cmd+Shift+B"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"fontStyle": "Bold"}))),
- cmd!("type.italic", "Italic", [], Some("Cmd+Shift+I"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"fontStyle": "Italic"}))),
+ cmd!(
+ "type.bold",
+ "Bold",
+ [],
+ Some("Cmd+Shift+B"),
+ "{on?: bool} — the family's bold style, keeping italic (style linking); toggles when `on` is left out",
+ has_text_or_frames,
+ |s, p| link_style(s, p, true)
+ ),
+ cmd!(
+ "type.italic",
+ "Italic",
+ [],
+ Some("Cmd+Shift+I"),
+ "{on?: bool} — the family's italic style, keeping the weight (style linking); toggles when `on` is left out",
+ has_text_or_frames,
+ |s, p| link_style(s, p, false)
+ ),
cmd!("type.underline", "Underline", [], Some("Cmd+Shift+U"), "{}", has_text_or_frames, |s, _| format_chars(s, &json!({"underline": true}))),
cmd!("type.allCaps", "All Caps", [], Some("Cmd+Shift+K"), "{}", has_text_or_frames, |s, _| format_chars(
s,
@@ -233,6 +252,17 @@ pub(crate) fn story_of(s: &Session, p: &Value) -> Option<StoryId> {
/// Story byte at spread point `pt` in text frame `frame` (in a table cell's story when the point is in a cell).
fn hit_byte(s: &Session, frame: ItemId, pt: Point) -> Option<(StoryId, usize, Option<CellAddr>)> {
+ hit_byte_with(s, frame, pt, compose::hit)
+}
+
+/// [`hit_byte`] with the hit test: [`compose::hit`] (caret position) or [`compose::hit_char`]
+/// (the character under the point).
+fn hit_byte_with(
+ s: &Session,
+ frame: ItemId,
+ pt: Point,
+ hit: fn(&compose::ComposedStory, usize, Point) -> Option<usize>,
+) -> Option<(StoryId, usize, Option<CellAddr>)> {
let st = s.active()?;
let loc = st.doc.find(frame)?;
let it = st.doc.item_at(&loc)?;
@@ -241,16 +271,76 @@ fn hit_byte(s: &Session, frame: ItemId, pt: Point) -> Option<(StoryId, usize, Op
let inner = xf.inverse() * pt;
let cs = s.cache.get(&st.doc, sid, None);
let fi = cs.frames.iter().position(|f| f.frame == frame)?;
- if let Some((table, row, col, b)) = compose::hit_cell(&cs, fi, inner) {
+ if let Some((table, row, col, b)) = compose::hit_cell_with(&cs, fi, inner, hit) {
return Some((sid, b, Some(CellAddr { table, row, col })));
}
- if let Some((id, b)) = compose::hit_note(&cs, fi, inner) {
+ if let Some((id, b)) = compose::hit_note_with(&cs, fi, inner, hit) {
return Some((sid, b, Some(CellAddr::footnote(id))));
}
- let b = compose::hit(&cs, fi, inner).unwrap_or(0);
+ let b = hit(&cs, fi, inner).unwrap_or(0);
Some((sid, b, None))
}
+/// Select the word, line, paragraph or story at `point` in `frame` (multiple clicks).
+fn select_at(s: &mut Session, p: &Value, unit: &str) -> Result<Value> {
+ const ID: &str = "text.selectAt";
+ let frame = id_param(p, "frame").ok_or_else(|| bad(ID, "missing frame"))?;
+ let pt = point_param(p, "point").unwrap_or(Point::ZERO);
+ let (sid, b, cell) = hit_byte_with(s, frame, pt, compose::hit_char).ok_or_else(|| bad(ID, "not a text frame"))?;
+ let st = s.doc()?;
+ let story = st.doc.text_story(sid, cell).ok_or(designcraft_doc::DocError::NoStory(sid))?;
+ let text = story.text.as_str();
+ let b = floor_char_boundary(text, b);
+ let (a, e) = match unit {
+ "word" => word_or_spaces_at(text, b),
+ "line" => {
+ let cs = s.cache.get(&st.doc, sid, None);
+ line_at(&text_composition(cs, cell), b).unwrap_or((b, b))
+ }
+ "paragraph" => story.para_ranges().get(story.para_at(b)).map_or((b, b), |r| (r.start, r.end)),
+ "story" => (0, text.len()),
+ other => return Err(bad(ID, format!("unknown unit `{other}` (word, line, paragraph or story)"))),
+ };
+ s.text_drag = false;
+ let st = s.doc_mut()?;
+ st.selection = Selection::text(TextSel { story: sid, anchor: a, focus: e, frame: Some(frame), cell });
+ st.revision += 1;
+ Ok(json!({"story": sid.0, "anchor": a, "focus": e}))
+}
+
+/// The word at byte `i`; on spaces the run of spaces; on anything else that one character. At
+/// the end of a paragraph, what ends it.
+fn word_or_spaces_at(s: &str, i: usize) -> (usize, usize) {
+ let at = |i: usize| s.get(i..).and_then(|r| r.chars().next()).filter(|c| *c != '\n');
+ let i = if at(i).is_none() && i > 0 { prev_char(s, i) } else { i };
+ let Some(c) = at(i) else { return (i, i) };
+ let space = |c: char| c.is_whitespace() && c != '\n';
+ if is_word(c) {
+ word_bounds(s, i)
+ } else if space(c) {
+ let a = s[..i].char_indices().rev().take_while(|(_, c)| space(*c)).last().map_or(i, |(k, _)| k);
+ let e = s[i..].char_indices().find(|(_, c)| !space(*c)).map_or(s.len(), |(k, _)| i + k);
+ (a, e)
+ } else {
+ (i, i + c.len_utf8())
+ }
+}
+
+/// The composition whose lines hold a story's text: the story's own, a table cell's or a footnote's.
+fn text_composition(cs: std::sync::Arc<compose::ComposedStory>, cell: Option<CellAddr>) -> std::sync::Arc<compose::ComposedStory> {
+ match cell {
+ Some(c) if c.footnote_id().is_some() => compose::find_note(&cs, c.row as u64).map(|(_, n)| n.text.clone()).unwrap_or(cs),
+ Some(c) => compose::find_cell(&cs, c.table, c.row, c.col).map(|(_, _, pc)| pc.text.clone()).unwrap_or(cs),
+ None => cs,
+ }
+}
+
+/// The composed line holding the character at byte `pos`.
+fn line_at(cs: &compose::ComposedStory, pos: usize) -> Option<(usize, usize)> {
+ let lines = || cs.frames.iter().flat_map(|f| f.lines.iter());
+ lines().find(|l| l.range.contains(&pos)).map(|l| (l.range.start, l.range.end)).or_else(|| line_of(cs, pos))
+}
+
fn place(s: &mut Session, p: &Value, extend: bool) -> Result<Value> {
let frame = id_param(p, "frame").ok_or_else(|| bad("text.placeCaret", "missing frame"))?;
let pt = point_param(p, "point").unwrap_or(Point::ZERO);
@@ -336,6 +426,8 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
let text = if s.prefs.typographers_quotes && !raw { smart_quotes(s, &text) } else { text };
let tracking = s.doc()?.doc.settings.track_changes;
let autocorrect = (s.prefs.autocorrect && !tracking && !raw).then(|| s.prefs.autocorrect_list.clone());
+ let typing = typing_format(s).cloned();
+ s.typing_format = None;
s.edit(|d, sel| {
let t = sel.text.ok_or_else(|| bad("text.insert", "no insertion point"))?;
let st = d.text_story_mut(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?;
@@ -383,6 +475,9 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
// Track Changes: the replaced text is marked deleted, the typing inserted after it.
let at = super::changes::mark_deleted(st, r.clone());
let mut fmt = st.char_format_at(at).clone();
+ if let Some(f) = &typing {
+ apply_typing_format(&mut fmt, f);
+ }
fmt.over.change = Some(designcraft_doc::ChangeMark::Inserted);
st.insert_with(at, &text, fmt);
let pos = at + text.len() - trail;
@@ -390,6 +485,11 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({"pos": pos}));
}
st.replace(r.clone(), &text);
+ if let Some(f) = &typing
+ && !text.is_empty()
+ {
+ st.format_chars(r.start..r.start + text.len(), |fmt| apply_typing_format(fmt, f));
+ }
let pos = r.start + text.len() - trail;
sel.text = Some(TextSel { anchor: pos, focus: pos, ..t });
Ok(json!({"pos": pos}))
@@ -582,13 +682,8 @@ fn move_caret(s: &mut Session, p: &Value) -> Result<Value> {
let t = st.selection.text.ok_or_else(|| bad("text.move", "no caret"))?;
let story = st.doc.text_story(t.story, t.cell).ok_or(designcraft_doc::DocError::NoStory(t.story))?;
let text = story.text.clone();
- let cs = s.cache.get(&st.doc, t.story, None);
// In a cell, lines come from the cell's own composition.
- let cs = match t.cell {
- Some(c) if c.footnote_id().is_some() => compose::find_note(&cs, c.row as u64).map(|(_, n)| n.text.clone()).unwrap_or(cs),
- Some(c) => compose::find_cell(&cs, c.table, c.row, c.col).map(|(_, _, pc)| pc.text.clone()).unwrap_or(cs),
- None => cs,
- };
+ let cs = text_composition(s.cache.get(&st.doc, t.story, None), t.cell);
let pos = t.focus.min(text.len());
let collapse_to = |left: bool| if left { t.range().start } else { t.range().end };
let new = match dir.as_str() {
@@ -680,6 +775,23 @@ pub(crate) fn format_targets(s: &Session) -> Vec<Target> {
v
}
+/// Character formatting chosen at a bare caret in text: applied to what is typed there next.
+#[derive(Clone, Debug)]
+pub(crate) struct TypingFormat {
+ doc: u64,
+ at: TextSel,
+ attrs: CharAttrs,
+ /// Overrides removed (`null` in `type.char`).
+ cleared: Vec<String>,
+}
+
+/// The typing format for the active document's caret, if it was chosen at this caret.
+fn typing_format(s: &Session) -> Option<&TypingFormat> {
+ let st = s.active()?;
+ let t = st.selection.text?;
+ s.typing_format.as_ref().filter(|f| f.doc == st.uid && f.at.story == t.story && f.at.cell == t.cell && f.at.range() == t.range())
+}
+
pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {
let mut a = CharAttrs::default();
if let Some(o) = attrs.as_object() {
@@ -689,32 +801,50 @@ pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {
}
let cleared: Vec<String> = attrs.as_object().map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect()).unwrap_or_default();
let targets = format_targets(s);
+ // A caret in text: the format is for the next typing.
+ if let [t] = targets.as_slice()
+ && t.range.is_empty()
+ && let Some(at) = s.doc()?.selection.text
+ && s.doc()?.doc.text_story(t.story, t.cell).is_some_and(|st| !st.is_empty())
+ {
+ let doc = s.doc()?.uid;
+ let mut f = typing_format(s).cloned().unwrap_or(TypingFormat { doc, at, attrs: CharAttrs::default(), cleared: vec![] });
+ f.attrs.merge(&a);
+ f.cleared.retain(|k| !attrs.get(k).is_some_and(|v| !v.is_null()) && !cleared.contains(k));
+ f.cleared.extend(cleared);
+ s.typing_format = Some(f);
+ return ok();
+ }
s.edit(|d, _| {
- for t in &targets {
- let r = &t.range;
- let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };
- if r.is_empty() {
- // Caret: change the typing format (the empty run at the caret).
- let pos = r.start;
- if st.is_empty() {
- st.chars[0].format.over.merge(&a);
- st.rev += 1;
- } else {
- let _ = pos;
- }
- continue;
- }
- st.format_chars(r.clone(), |f| {
- f.over.merge(&a);
- for k in &cleared {
- let _ = f.over.set_json(k, &Value::Null);
- }
- });
- }
+ apply_char_attrs(d, &targets, &a, &cleared);
ok()
})
}
+/// Character attributes `a` (and the overrides `cleared` removed) over each target's text.
+pub(crate) fn apply_char_attrs(d: &mut designcraft_doc::Document, targets: &[Target], a: &CharAttrs, cleared: &[String]) {
+ for t in targets {
+ let r = &t.range;
+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };
+ if r.is_empty() {
+ // An empty story: its one (empty) run is the format typing takes.
+ if st.is_empty()
+ && let Some(run) = st.chars.first_mut()
+ {
+ run.format.over.merge(a);
+ st.rev += 1;
+ }
+ continue;
+ }
+ st.format_chars(r.clone(), |f| {
+ f.over.merge(a);
+ for k in cleared {
+ let _ = f.over.set_json(k, &Value::Null);
+ }
+ });
+ }
+}
+
pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {
let mut a = ParaAttrs::default();
if let Some(o) = attrs.as_object() {
@@ -818,12 +948,71 @@ fn selection_attrs(s: &mut Session, _p: &Value) -> Result<Value> {
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);
Ok(json!({"story": sid.0, "paragraphStyle": pf.style, "characterStyle": cf.style, "para": pp, "chars": cp,
"paraOverrides": pf.para.count(), "charOverrides": cf.over.count()}))
}
+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();
+ let db = designcraft_fonts::FontDb::global();
+ 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).
pub const PLACEHOLDER: &str = "Ovid ellum quisque arcet velut tempora sint, ne veriora pareant laudemque fieri. Lorem novum strata ponet amicos, \
et tamen uti ferrum caelo tempus mollit. Quisque sinat oppida retro, nec tenuere longas animi semper vias. \
@@ -1092,6 +1281,133 @@ mod nested_style_tests {
}
}
+#[cfg(test)]
+mod multi_click_tests {
+ use serde_json::{Value, json};
+
+ use crate::Session;
+
+ #[test]
+ fn clicks_select_words_spaces_lines_paragraphs_and_the_story() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let text = "Hello brave world.\nSecond paragraph here.";
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 200], "content": "text", "text": text})).unwrap();
+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());
+ // Spread point over the right half of the glyph at byte `b`.
+ let at = |s: &Session, b: usize| {
+ let d = &s.doc().unwrap().doc;
+ let cs = designcraft_compose::compose_story(d, designcraft_doc::StoryId(sid), &Default::default());
+ let (l, g) = cs.frames[0].lines.iter().find_map(|l| l.glyphs.iter().find(|g| g.byte == b && g.len > 0).map(|g| (l, g))).unwrap();
+ json!([g.x + g.adv * 0.75, l.baseline - 3.0])
+ };
+ let mut select = |unit: &str, b: usize| {
+ let p = at(&s, b);
+ let r: Value = s.execute("text.selectAt", &json!({"frame": fid, "point": p, "unit": unit})).unwrap();
+ (r["anchor"].as_u64().unwrap() as usize, r["focus"].as_u64().unwrap() as usize)
+ };
+ assert_eq!(select("word", 1), (0, 5), "inside a word");
+ assert_eq!(select("word", 4), (0, 5), "its last letter");
+ assert_eq!(select("word", 5), (5, 7), "the run of spaces after it");
+ assert_eq!(select("word", 18), (18, 19), "punctuation alone");
+ assert_eq!(select("line", 9), (0, 19));
+ assert_eq!(select("paragraph", 9), (0, 19));
+ assert_eq!(select("paragraph", 22), (20, text.len()));
+ assert_eq!(select("story", 9), (0, text.len()));
+ // A second click inside the selected word selects again rather than starting a text drag.
+ s.execute("text.select", &json!({"story": sid, "anchor": 7, "focus": 12})).unwrap();
+ let p = at(&s, 9);
+ s.execute("text.selectAt", &json!({"frame": fid, "point": p, "unit": "line"})).unwrap();
+ let t = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.anchor, t.focus), (0, 19));
+ s.execute("text.release", &json!({"frame": fid, "point": p, "moved": false})).unwrap();
+ let t = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.anchor, t.focus), (0, 19), "releasing keeps it");
+ // The older word command agrees.
+ let p = at(&s, 8);
+ s.execute("text.selectWord", &json!({"frame": fid, "point": p})).unwrap();
+ let t = s.doc().unwrap().selection.text.unwrap();
+ assert_eq!((t.anchor, t.focus), (7, 12));
+ assert!(s.execute("text.selectAt", &json!({"frame": fid, "point": p, "unit": "sentence"})).is_err());
+ }
+}
+
+#[cfg(test)]
+mod style_link_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn bold_and_italic_follow_the_family_and_toggle() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 500, 200], "content": "text", "text": "plain words here"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ let style_at = |s: &mut Session, b: usize| {
+ s.execute("text.select", &json!({"story": sid, "anchor": b, "focus": b + 1})).unwrap();
+ s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fontStyle"].as_str().unwrap().to_string()
+ };
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 5})).unwrap();
+ s.execute("type.italic", &json!({})).unwrap();
+ assert_eq!(style_at(&mut s, 0), "Italic");
+ // Bold over italic and plain text: each run takes its own linked style.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 11})).unwrap();
+ s.execute("type.bold", &json!({})).unwrap();
+ assert_eq!(style_at(&mut s, 0), "Bold Italic");
+ assert_eq!(style_at(&mut s, 7), "Bold");
+ // Again: off, back to each run's regular weight.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 11})).unwrap();
+ s.execute("type.bold", &json!({})).unwrap();
+ assert_eq!(style_at(&mut s, 0), "Italic");
+ assert_eq!(style_at(&mut s, 7), "Regular");
+ // At a caret the style is for what is typed next.
+ let end = "plain words here".len();
+ s.execute("text.select", &json!({"story": sid, "anchor": end, "focus": end})).unwrap();
+ s.execute("type.bold", &json!({})).unwrap();
+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["fontStyle"], "Bold");
+ s.execute("text.insert", &json!({"text": " now"})).unwrap();
+ assert_eq!(style_at(&mut s, end + 1), "Bold");
+ assert_eq!(style_at(&mut s, end - 1), "Regular", "text before the caret is unchanged");
+ // Moving the caret forgets it.
+ s.execute("text.select", &json!({"story": sid, "anchor": 2, "focus": 2})).unwrap();
+ s.execute("type.char", &json!({"attrs": {"size": 30}})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();
+ s.execute("text.insert", &json!({"text": "x"})).unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 3, "focus": 4})).unwrap();
+ assert_eq!(s.execute("type.selectionAttrs", &json!({})).unwrap()["chars"]["size"], 12.0);
+ }
+}
+
+#[cfg(test)]
+mod text_color_tests {
+ use serde_json::json;
+
+ use crate::Session;
+
+ #[test]
+ fn unnamed_colours_go_to_text_when_asked() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 200], "content": "text", "text": "colour me", "caret": false})).unwrap();
+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());
+ s.execute("selection.set", &json!({"ids": [fid]})).unwrap();
+ let fill_of_frame = |s: &Session| s.doc().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();
+ let before = fill_of_frame(&s);
+ let r = s.execute("object.color", &json!({"color": "#ff0000", "text": true})).unwrap();
+ let red = r["swatch"].as_str().unwrap().to_string();
+ assert_eq!(fill_of_frame(&s), before, "the frame keeps its fill");
+ let story = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();
+ assert_eq!(story.char_format_at(3).over.fill.as_deref(), Some(red.as_str()));
+ // A text selection takes it without asking.
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": 3})).unwrap();
+ let r = s.execute("object.color", &json!({"color": "#00ff00", "target": "stroke"})).unwrap();
+ let story = s.doc().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();
+ assert_eq!(story.format_after(0).over.stroke.as_deref(), r["swatch"].as_str());
+ assert_eq!(s.doc().unwrap().history.undo.len(), 3, "the frame, then one undo step per colour");
+ }
+}
+
#[cfg(test)]
mod drag_text_tests {
use serde_json::json;
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 03562bbf1..922cabda5 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -242,6 +242,8 @@ pub struct Session {
pub(crate) transforms: (Vec<(String, Value)>, Vec<designcraft_doc::ItemId>, bool),
/// Drag and drop text editing: the press landed in the selected text.
pub(crate) text_drag: bool,
+ /// Character formatting chosen at a bare caret, for the text typed there next.
+ pub(crate) typing_format: Option<cmd::text::TypingFormat>,
/// The open Object Library (File › New / Open Library).
pub library: Option<cmd::library::Library>,
/// The open book (File › Open Book).
@@ -273,6 +275,7 @@ impl Session {
loaded: None,
transforms: Default::default(),
text_drag: false,
+ typing_format: None,
library: None,
conveyor: Vec::new(),
book: None,
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index f67ff593d..d6072a435 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -566,6 +566,50 @@ impl FontDb {
/// Style names available for `family` (Regular first, then by weight).
pub fn styles(&self, family: &str) -> Vec<String> {
+ self.style_traits(family).into_iter().map(|t| t.2).collect()
+ }
+
+ /// Weight and italic of a style of `family`: from the font when it is known, else from the
+ /// style's name.
+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {
+ let base = base_style(style);
+ self.style_traits(family)
+ .into_iter()
+ .find(|t| t.2.eq_ignore_ascii_case(base))
+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))
+ }
+
+ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked
+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the
+ /// family has no such style.
+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {
+ let (weight, cur_italic) = self.traits_of(family, current);
+ let want_italic = italic.unwrap_or(cur_italic);
+ let want_weight = match bold {
+ Some(true) => 700.0,
+ Some(false) => 400.0,
+ None => weight,
+ };
+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.
+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];
+ let widths = |s: &str| {
+ let n = norm(s);
+ WIDTHS.iter().filter(|w| n.contains(*w)).count()
+ };
+ let cur_widths = widths(current);
+ self.style_traits(family)
+ .into_iter()
+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))
+ .min_by(|a, b| {
+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());
+ let (ka, kb) = (key(a), key(b));
+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))
+ })
+ .map(|t| t.2)
+ }
+
+ /// `(italic, weight, name)` of each style of `family`, Regular first, then by weight.
+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {
let mut v: Vec<(bool, f32, String)> = self
.read_faces()
.iter()
@@ -580,7 +624,7 @@ impl FontDb {
}
v.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)).then(a.2.cmp(&b.2)));
v.dedup_by(|a, b| a.2 == b.2);
- v.into_iter().map(|t| t.2).collect()
+ v
}
/// Add a user font (TTF/OTF/TTC bytes). Returns the number of faces added (0 if unparseable or
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index 60c13f232..4936aa1f3 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -203,6 +203,22 @@ mod tests {
}
}
+ #[test]
+ fn style_linking_finds_bold_and_italic_in_the_family() {
+ let db = FontDb::with_font_dirs(vec![]);
+ let link = |cur: &str, bold: Option<bool>, italic: Option<bool>| db.linked_style("Source Serif 4", cur, bold, italic);
+ assert_eq!(link("Regular", Some(true), None).as_deref(), Some("Bold"));
+ assert_eq!(link("Italic", Some(true), None).as_deref(), Some("Bold Italic"), "keeps the italic");
+ assert_eq!(link("Bold", None, Some(true)).as_deref(), Some("Bold Italic"), "keeps the weight");
+ assert_eq!(link("Bold Italic", Some(false), None).as_deref(), Some("Italic"));
+ assert_eq!(link("Bold Italic", None, Some(false)).as_deref(), Some("Bold"));
+ assert_eq!(link("Semibold", Some(false), None).as_deref(), Some("Regular"));
+ assert_eq!(db.traits_of("Source Serif 4", "Bold Italic"), (700.0, true));
+ // Source Sans 3 is bundled without a bold italic.
+ assert_eq!(db.linked_style("Source Sans 3", "Italic", Some(true), None), None);
+ assert_eq!(db.linked_style("No Such Family", "Regular", Some(true), None), None);
+ }
+
#[test]
fn shaping_produces_clusters_and_advances() {
let face = FontDb::global().face(DEFAULT_FAMILY, "Regular");
diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs
index ee9d11d19..60bc57707 100644
--- a/crates/mcp/src/headless.rs
+++ b/crates/mcp/src/headless.rs
@@ -123,7 +123,8 @@ impl Headless {
let x = e.get("x").and_then(Value::as_f64).ok_or("pointer event needs numeric `x`")?;
let y = e.get("y").and_then(Value::as_f64).ok_or("pointer event needs numeric `y`")?;
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base);
- self.session.pointer(&PointerEvent { kind, pos: Point::new(x, y), mods }, VIEW).map_err(|e| e.to_string())?;
+ let clicks = e.get("clicks").and_then(Value::as_u64).map_or(1, |n| n.clamp(1, 255) as u8);
+ self.session.pointer(&PointerEvent { kind, pos: Point::new(x, y), mods, clicks }, VIEW).map_err(|e| e.to_string())?;
}
let requests: Vec<Value> = self.session.ui_requests.drain(..).map(|r| serde_json::to_value(r).unwrap_or_default()).collect();
Ok(json!({"selection": self.selection(), "tool": self.session.tool_id(), "requests": requests}))
diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs
index dc2604c5b..2bf90c36b 100644
--- a/crates/mcp/src/tools.rs
+++ b/crates/mcp/src/tools.rs
@@ -277,6 +277,7 @@ pub fn tool_definitions() -> Vec<Value> {
"y": num("y (pt)"),
"space": {"type": "string", "enum": ["doc", "screen"], "description": "Coordinate space (default doc)"},
"mods": mods_schema(),
+ "clicks": {"type": "integer", "minimum": 1, "description": "On a down: presses in a row it completes (2 double, 3 triple…; default 1)"},
}), &["kind", "x", "y"]),
},
"mods": mods_schema(),
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index 247494f84..016df8783 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -63,16 +63,28 @@ pub struct PointerEvent {
pub pos: Point,
#[serde(default)]
pub mods: Mods,
+ /// On a press: how many presses in quick succession at this spot it completes (2 = the
+ /// second of a double click, 3 = a triple click…). 0 counts as 1.
+ #[serde(default)]
+ pub clicks: u8,
}
impl PointerEvent {
pub fn new(kind: PointerKind, x: f64, y: f64) -> Self {
- Self { kind, pos: Point::new(x, y), mods: Mods::default() }
+ Self { kind, pos: Point::new(x, y), mods: Mods::default(), clicks: 1 }
}
pub fn with_mods(mut self, m: Mods) -> Self {
self.mods = m;
self
}
+ pub fn with_clicks(mut self, n: u8) -> Self {
+ self.clicks = n;
+ self
+ }
+ /// Presses in a row: at least 2 for [`PointerKind::DoubleClick`], at least 1 otherwise.
+ pub fn click_count(&self) -> u8 {
+ if self.kind == PointerKind::DoubleClick { self.clicks.max(2) } else { self.clicks.max(1) }
+ }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs
index 8f59c3503..457625fc6 100644
--- a/crates/tools/src/select.rs
+++ b/crates/tools/src/select.rs
@@ -371,6 +371,14 @@ impl Tool for SelectionTool {
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
let p = ev.pos;
+ // The second press of a double click on a text frame: edit its text.
+ if matches!(ev.kind, PointerKind::Down | PointerKind::DoubleClick)
+ && ev.click_count() == 2
+ && let Some(actions) = edit_text_at(cx, p)
+ {
+ self.drag = Drag::None;
+ return actions;
+ }
match ev.kind {
PointerKind::Move => {
self.hover_handle = handle_at(cx, p);
@@ -706,19 +714,7 @@ impl Tool for SelectionTool {
Drag::None => vec![],
}
}
- PointerKind::DoubleClick => {
- if let Some((_, id)) = cx.hit(p)
- && cx.doc.item(id).is_some_and(|i| i.is_text_frame())
- {
- let (sr, sp) = cx.layout.spread_at(p).unwrap_or((SpreadRef::Doc(0), p));
- let _ = sr;
- return vec![
- Action::SwitchTool("type".into()),
- Action::Exec("text.placeCaret".into(), json!({"frame": id.0, "point": [sp.x, sp.y]})),
- ];
- }
- vec![]
- }
+ PointerKind::DoubleClick => vec![],
}
}
@@ -777,3 +773,13 @@ fn handle_cursor(h: usize) -> Cursor {
_ => Cursor::ResizeH,
}
}
+
+/// Switch to the Type tool with the caret at `p` when it is over a text frame.
+fn edit_text_at(cx: &ToolContext, p: Point) -> Option<Vec<Action>> {
+ let (_, id) = cx.hit(p)?;
+ if !cx.doc.item(id).is_some_and(|i| i.is_text_frame()) {
+ return None;
+ }
+ let (_, sp) = cx.layout.spread_at(p).unwrap_or((SpreadRef::Doc(0), p));
+ Some(vec![Action::SwitchTool("type".into()), Action::Exec("text.placeCaret".into(), json!({"frame": id.0, "point": [sp.x, sp.y]}))])
+}
diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs
index 6c75b0da6..902c44949 100644
--- a/crates/tools/src/tests.rs
+++ b/crates/tools/src/tests.rs
@@ -705,3 +705,38 @@ fn pen_click_snaps_to_a_guide() {
let x = p["anchors"][0]["p"][0].as_f64().unwrap();
assert!((x - 100.0).abs() < 1e-6, "anchor x {x}");
}
+
+#[test]
+fn clicks_in_a_row_edit_and_select_text() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (fid, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 300.0, 200.0), lid, "Two words", ParaFormat::default()).unwrap();
+ let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false));
+ let cx = ctx(&d, &s, &c, &l);
+ let off = l.xf(SpreadRef::Doc(0)).translation();
+ let (x, y) = (150.0 + off.x, 110.0 + off.y);
+ let press = |n: u8| PointerEvent::new(PointerKind::Down, x, y).with_clicks(n);
+ // Selection tool: the second press of a double click edits the text there.
+ let mut t = create("selection");
+ let a = t.pointer(&cx, &press(1));
+ assert!(matches!(&a[0], Action::Exec(id, _) if id == "selection.set"), "{a:?}");
+ t.pointer(&cx, &PointerEvent::new(PointerKind::Up, x, y));
+ let a = t.pointer(&cx, &press(2));
+ assert_eq!(a.first(), Some(&Action::SwitchTool("type".into())));
+ assert!(matches!(&a[1], Action::Exec(id, p) if id == "text.placeCaret" && p["frame"] == fid.0), "{a:?}");
+ // Type tool: word, line, paragraph, then the story.
+ let mut t = create("type");
+ let unit = |a: Vec<Action>| match a.as_slice() {
+ [Action::Exec(id, p)] if id == "text.selectAt" => p["unit"].as_str().map(str::to_string),
+ [Action::Exec(id, _)] if id == "text.placeCaret" => None,
+ other => panic!("{other:?}"),
+ };
+ assert_eq!(unit(t.pointer(&cx, &press(1))), None);
+ for (n, want) in [(2, "word"), (3, "line"), (4, "paragraph"), (5, "story"), (9, "story")] {
+ assert_eq!(unit(t.pointer(&cx, &press(n))).as_deref(), Some(want), "{n} clicks");
+ }
+ // A double click sent as such (control channel) selects a word too.
+ assert_eq!(unit(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, x, y))).as_deref(), Some("word"));
+ // Moving a little while pressed keeps the unit selected.
+ assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x + 2.0, y)).is_empty());
+}
diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs
index 13a93f23a..e84f2644c 100644
--- a/crates/tools/src/text.rs
+++ b/crates/tools/src/text.rs
@@ -17,6 +17,8 @@ pub struct TypeTool {
/// A press on a table whose whole rows or columns are selected: (frame, press point in
/// spread space) — a drag moves them, a click places the caret.
cell_drag: Option<(u64, Point)>,
+ /// The press selected a word, line, paragraph or story (several clicks): drags keep it.
+ unit_selected: bool,
}
/// Are whole rows or whole columns of a table selected?
@@ -45,31 +47,39 @@ impl Tool for TypeTool {
self.drawing = false;
self.selecting = None;
self.cell_drag = None;
+ self.unit_selected = false;
if let Some((_, id)) = cx.hit(ev.pos)
&& let Some(it) = cx.doc.item(id)
&& !matches!(it.content, designcraft_doc::Content::Graphic(_) | designcraft_doc::Content::Group { .. })
{
let sp = cx.layout.spread_at(ev.pos).map(|(_, p)| p).unwrap_or(ev.pos);
+ let clicks = ev.click_count();
// Whole rows/columns selected: wait to see whether this is a drag.
- if ev.kind == PointerKind::Down && !ev.mods.shift && whole_rows_or_cols(cx) {
+ if clicks == 1 && !ev.mods.shift && whole_rows_or_cols(cx) {
self.cell_drag = Some((id.0, sp));
return vec![];
}
self.selecting = Some(id.0);
- let cmd = if ev.kind == PointerKind::DoubleClick {
- "text.selectWord"
- } else if ev.mods.shift {
- "text.extendTo"
- } else {
- "text.placeCaret"
- };
+ // Two presses select a word (or a run of spaces), three a line, four a
+ // paragraph, five the story.
+ if clicks >= 2 {
+ self.unit_selected = true;
+ let unit = match clicks {
+ 2 => "word",
+ 3 => "line",
+ 4 => "paragraph",
+ _ => "story",
+ };
+ return vec![Action::Exec("text.selectAt".into(), json!({"frame": id.0, "point": [sp.x, sp.y], "unit": unit}))];
+ }
+ let cmd = if ev.mods.shift { "text.extendTo" } else { "text.placeCaret" };
return vec![Action::Exec(cmd.into(), json!({"frame": id.0, "point": [sp.x, sp.y]}))];
}
vec![]
}
PointerKind::Drag => {
let Some(a) = self.start else { return vec![] };
- if self.cell_drag.is_some() {
+ if self.cell_drag.is_some() || self.unit_selected {
return vec![];
}
if let Some(fid) = self.selecting {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index e1562c602..22b833cd1 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1364,20 +1364,21 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
let mut events: Vec<PointerEvent> = Vec::new();
let down_id = egui::Id::new(("canvas_pointer_down", app.pane));
let mut down: bool = ui.data(|d| d.get_temp(down_id)).unwrap_or(false);
- let (pressed, released, origin, latest, dbl) = ui.input(|i| {
- (
- i.pointer.primary_pressed(),
- i.pointer.primary_released(),
- i.pointer.press_origin(),
- i.pointer.latest_pos(),
- i.pointer.button_double_clicked(egui::PointerButton::Primary),
- )
- });
+ let clicks_id = egui::Id::new(("canvas_clicks", app.pane));
+ let (pressed, released, origin, latest, now) =
+ ui.input(|i| (i.pointer.primary_pressed(), i.pointer.primary_released(), i.pointer.press_origin(), i.pointer.latest_pos(), i.time));
if pressed
&& !space
&& let Some(o) = origin.filter(|o| (if xf.rot == 0 { rect.contains(*o) } else { resp.rect.contains(*o) }) && resp.hovered())
{
- events.push(PointerEvent { kind: if dbl { PointerKind::DoubleClick } else { PointerKind::Down }, pos: pos(o), mods: m });
+ // Count presses in a row here: egui reports double and triple clicks only on release and
+ // stops at three, but a press must know (word, line, paragraph, story).
+ // Like egui, the next press must come within the double-click delay of the last release.
+ let (delay, dist) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist));
+ let (released_at, last_pos, last_n): (f64, Pos2, u8) = ui.data(|d| d.get_temp(clicks_id)).unwrap_or((f64::NEG_INFINITY, o, 0));
+ let n = if now - released_at <= delay && (o - last_pos).length() <= dist { last_n.saturating_add(1) } else { 1 };
+ ui.data_mut(|d| d.insert_temp(clicks_id, (f64::NEG_INFINITY, o, n)));
+ events.push(PointerEvent { kind: PointerKind::Down, pos: pos(o), mods: m, clicks: n });
down = true;
}
if down
@@ -1385,7 +1386,7 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
&& resp.drag_delta() != egui::Vec2::ZERO
&& let Some(p) = latest
{
- events.push(PointerEvent { kind: PointerKind::Drag, pos: pos(p), mods: m });
+ events.push(PointerEvent { kind: PointerKind::Drag, pos: pos(p), mods: m, clicks: 1 });
}
// Power Zoom: holding the Hand tool still for half a second turns the press into one.
let hold_id = egui::Id::new(("canvas_hold", app.pane));
@@ -1395,8 +1396,8 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
let still = origin_pos.zip(latest).is_some_and(|(o, l)| (o - l).length() < 3.0);
if !fired && still && now - start >= 0.5 {
let p = pos(latest.unwrap_or(rect.center()));
- events.push(PointerEvent { kind: PointerKind::Up, pos: p, mods: m });
- events.push(PointerEvent { kind: PointerKind::Down, pos: p, mods: Mods { alt: true, ..m } });
+ events.push(PointerEvent { kind: PointerKind::Up, pos: p, mods: m, clicks: 1 });
+ events.push(PointerEvent { kind: PointerKind::Down, pos: p, mods: Mods { alt: true, ..m }, clicks: 1 });
ui.data_mut(|d| d.insert_temp(hold_id, (start, true)));
} else {
ui.data_mut(|d| d.insert_temp(hold_id, (start, fired)));
@@ -1408,11 +1409,14 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
ui.data_mut(|d| d.remove::<(f64, bool)>(hold_id));
}
if down && released {
+ if let Some((_, at, n)) = ui.data(|d| d.get_temp::<(f64, Pos2, u8)>(clicks_id)) {
+ ui.data_mut(|d| d.insert_temp(clicks_id, (now, at, n)));
+ }
let p = latest.unwrap_or(rect.center());
- events.push(PointerEvent { kind: PointerKind::Up, pos: pos(p), mods: m });
+ events.push(PointerEvent { kind: PointerKind::Up, pos: pos(p), mods: m, clicks: 1 });
down = false;
} else if !down && let Some(p) = resp.hover_pos() {
- events.push(PointerEvent { kind: PointerKind::Move, pos: pos(p), mods: m });
+ events.push(PointerEvent { kind: PointerKind::Move, pos: pos(p), mods: m, clicks: 1 });
}
ui.data_mut(|d| d.insert_temp(down_id, down));
for e in events {
@@ -1442,11 +1446,19 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r
let _ = app.run(id, json!({"text": t}));
}
egui::Event::Copy | egui::Event::Cut if wants_text => {
+ // `run` puts the copied text on the system clipboard.
let id = if matches!(e, egui::Event::Cut) { "edit.cut" } else { "edit.copy" };
- if let Ok(r) = app.run(id, json!({}))
- && let Some(t) = r.get("text").and_then(serde_json::Value::as_str)
- {
- ui.ctx().copy_text(t.to_string());
+ let _ = app.run(id, json!({}));
+ }
+ // Without a native menu bar the copy and paste keys arrive only as these events.
+ egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) if !app.native_menu => {
+ let id = match e {
+ egui::Event::Copy => "edit.copy",
+ egui::Event::Cut => "edit.cut",
+ _ => "edit.paste",
+ };
+ if crate::menus::enabled(app, id) {
+ crate::menus::activate(app, id, &serde_json::Value::Null);
}
}
egui::Event::Key { key, pressed: true, modifiers, .. } => {
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 7ff3d79c8..9afde404e 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -146,7 +146,8 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) ->
designcraft_geom::Point::new(x, y)
};
let mods = e.get("mods").and_then(|m| serde_json::from_value(m.clone()).ok()).unwrap_or(base_mods);
- if let Err(e) = app.session.pointer(&PointerEvent { kind, pos, mods }, view) {
+ let clicks = e.get("clicks").and_then(Value::as_u64).map_or(1, |n| n.clamp(1, 255) as u8);
+ if let Err(e) = app.session.pointer(&PointerEvent { kind, pos, mods, clicks }, view) {
return err(e);
}
app.after_engine();
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index bfa83d4a9..ac512894b 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -1478,7 +1478,7 @@ pub fn confirm(app: &mut DesignApp) -> Result<Value, String> {
}
"colorPicker" => {
let hex = d.s("hex");
- app.run("object.color", json!({"color": hex, "target": d.s("target")}))
+ app.run("object.color", json!({"color": hex, "target": d.s("target"), "text": d.b("text")}))
}
"layerOptions" => {
let hidden: Vec<Value> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect()).unwrap_or_default();
diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs
index 60fae75f3..7329f93ec 100644
--- a/crates/ui-egui/src/i18n.rs
+++ b/crates/ui-egui/src/i18n.rs
@@ -1680,13 +1680,13 @@ const TABLE: &[(&str, [&str; 5])] = &[
],
),
(
- "Select an object to color its fill or stroke.",
+ "Select an object or text to color its fill or stroke.",
[
- "Select an object to color its fill or stroke.",
- "Select an object to color its fill or stroke.",
- "Select an object to color its fill or stroke.",
- "Select an object to color its fill or stroke.",
- "选择一个对象以设置其填色或描边颜色。",
+ "Select an object or text to color its fill or stroke.",
+ "Select an object or text to color its fill or stroke.",
+ "Select an object or text to color its fill or stroke.",
+ "Select an object or text to color its fill or stroke.",
+ "选择一个对象或文本以设置其填色或描边颜色。",
],
),
(
diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs
index 03f97a62b..72d43ea54 100644
--- a/crates/ui-egui/src/i18n/ar.rs
+++ b/crates/ui-egui/src/i18n/ar.rs
@@ -912,7 +912,7 @@ pub(super) const TABLE: &[(&str, &str)] = &[
"Select a placed video or sound (File › Place a .mp4, .mov, .mp3, .wav …).",
"حدد فيديو أو صوتًا مدرجًا (ملف › إدراج ملف .mp4 أو .mov أو .mp3 أو .wav …).",
),
- ("Select an object to color its fill or stroke.", "حدد كائنًا لتلوين تعبئته أو حده."),
+ ("Select an object or text to color its fill or stroke.", "حدد كائنًا أو نصًا لتلوين تعبئته أو حده."),
("Select an object to give its fill a gradient.", "حدد كائنًا لإضافة تدرج إلى تعبئته."),
("Select an object to make it a button.", "حدد كائنًا لتحويله إلى زر."),
("Select an object.", "حدد كائنًا."),
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 10a600089..47557a871 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -39,6 +39,7 @@ pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
pub type PickFn = Box<dyn FnMut(&str) -> Option<String>>;
pub type OpenAsyncFn = Box<dyn FnMut(&str)>;
pub type DownloadFn = Box<dyn FnMut(&str, &[u8])>;
+pub type ClipboardFn = Box<dyn FnMut() -> Option<String>>;
/// Files `(name, bytes)` delivered asynchronously by the host (web file picker, dropped files).
pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;
@@ -60,6 +61,9 @@ pub struct Services {
/// Files delivered asynchronously, drained every frame: `.designcraft` → `file.openBytes`,
/// anything else → `file.place`.
pub inbox: Option<Inbox>,
+ /// The system clipboard's text, for Paste chosen from a menu (egui only delivers it with the
+ /// paste keys, which a native menu bar takes first).
+ pub clipboard_text: Option<ClipboardFn>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
@@ -186,6 +190,9 @@ pub struct UiState {
pub smart_spacing: bool,
#[serde(default = "default_zone")]
pub snap_zone: f64,
+ /// Tools panel: Formatting Affects Text (J): with text frames selected, colour edits go to
+ /// their text instead of the frames.
+ pub formatting_affects_text: bool,
/// Window > Contextual Task Bar.
pub task_bar: bool,
/// Help › About DesignCraft is open.
@@ -259,6 +266,7 @@ impl Default for UiState {
smart_dimensions: true,
smart_spacing: true,
snap_zone: 4.0,
+ formatting_affects_text: false,
task_bar: true,
about: false,
pending_urls: Vec::new(),
@@ -413,6 +421,8 @@ pub struct DesignApp {
last_time: f64,
/// When recovery data was last written (seconds, egui time).
pub last_recovery: f64,
+ /// The egui context (set by the first frame): copied text goes to the system clipboard through it.
+ egui_ctx: Option<egui::Context>,
}
impl DesignApp {
@@ -449,6 +459,7 @@ impl DesignApp {
native_shortcuts: Default::default(),
last_time: 0.0,
last_recovery: 0.0,
+ egui_ctx: None,
}
}
@@ -492,14 +503,37 @@ impl DesignApp {
if let Some(r) = menus::run_ui(self, id, &params) {
return r;
}
+ let params = self.with_system_clipboard(id, params);
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.after_engine();
- if let Err(e) = &r {
- self.status(e.clone());
+ match &r {
+ Err(e) => self.status(e.clone()),
+ // Copied text goes to the system clipboard too, whichever way Copy was chosen.
+ Ok(v) if matches!(id, "edit.copy" | "edit.cut") => {
+ if let (Some(t), Some(ctx)) = (v.get("text").and_then(Value::as_str), &self.egui_ctx) {
+ ctx.copy_text(t.to_string());
+ ctx.request_repaint();
+ }
+ }
+ Ok(_) => {}
}
r
}
+ /// Paste into text without the clipboard's text (a menu, not the paste keys): read it here.
+ fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Value {
+ let typing = self.session.active().is_some_and(|d| d.selection.text.is_some());
+ if typing
+ && matches!(id, "edit.paste" | "edit.pasteWithoutFormatting")
+ && params.get("text").is_none()
+ && let Some(text) = self.services.clipboard_text.as_mut().and_then(|f| f())
+ && let Some(o) = params.as_object_mut()
+ {
+ o.insert("text".into(), Value::String(text));
+ }
+ params
+ }
+
/// Handle requests produced by tools/commands (dialogs, view changes, file pickers).
pub fn after_engine(&mut self) {
let reqs = std::mem::take(&mut self.session.ui_requests);
@@ -575,6 +609,9 @@ impl DesignApp {
/// Per-frame logic before layout.
pub fn logic(&mut self, ctx: &egui::Context) {
+ if self.egui_ctx.is_none() {
+ self.egui_ctx = Some(ctx.clone());
+ }
if !self.color_applied {
self.color_applied = true;
if let Some(cs) = self.ui.color_settings.clone() {
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index c7b9f1928..8d929976a 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -79,6 +79,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[
("view.zoom", "Zoom To", None, "{zoom: 1.0 = 100%}"),
("view.screenMode", "Screen Mode", None, "{mode: normal|preview|bleed|slug|presentation}"),
("view.togglePreview", "Toggle Normal/Preview", Some("W"), "{}"),
+ (
+ "app.formattingAffectsText",
+ "Formatting Affects Text",
+ Some("J"),
+ "{on?: bool} — with text frames selected, colours go to their text (on) or the frames (off); toggles without `on`",
+ ),
("view.frameEdges", "Show/Hide Frame Edges", Some("Cmd+H"), "{}"),
("view.rulers", "Show/Hide Rulers", Some("Cmd+R"), "{}"),
("view.guides", "Show/Hide Guides", Some("Cmd+;"), "{}"),
@@ -1222,6 +1228,10 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option<Result<Value,
"zone": ui.snap_zone,
}))
}
+ "app.formattingAffectsText" => {
+ app.ui.formatting_affects_text = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.formatting_affects_text);
+ Ok(json!({"on": app.ui.formatting_affects_text}))
+ }
"window.richBlack" => {
app.ui.rich_black = p.get("on").and_then(Value::as_bool).unwrap_or(!app.ui.rich_black);
app.canvas.shown = None;
@@ -1996,6 +2006,31 @@ mod tests {
}
}
+ #[test]
+ fn formatting_affects_text_sends_swatches_to_the_text() {
+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({})).unwrap();
+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap();
+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());
+ app.run("selection.set", json!({"ids": [fid]})).unwrap();
+ let text_fill = |app: &crate::DesignApp| {
+ let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();
+ st.char_format_at(2).over.fill.clone()
+ };
+ let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();
+ assert!(!crate::panels::colors_affect_text(&app));
+ crate::panels::apply_swatch(&mut app, false, "Cyan", None).unwrap();
+ assert_eq!(frame_fill(&app), "Cyan");
+ assert_eq!(text_fill(&app), None);
+ let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap();
+ assert_eq!(r["on"], true, "toggles on");
+ assert!(crate::panels::colors_affect_text(&app));
+ crate::panels::apply_swatch(&mut app, false, "Magenta", Some(0.5)).unwrap();
+ assert_eq!(frame_fill(&app), "Cyan", "the frame is left alone");
+ assert_eq!(text_fill(&app).as_deref(), Some("Magenta"));
+ assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("Magenta".to_string(), 0.5)));
+ }
+
#[test]
fn snap_preferences_are_a_command() {
let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs
index 0ef125619..706b22521 100644
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@ -45,6 +45,44 @@ pub struct SelInfo {
pub locked: bool,
}
+/// Colour edits go to text: text is selected, or text frames are selected with Formatting
+/// Affects Text on.
+pub fn colors_affect_text(app: &DesignApp) -> bool {
+ let Some(st) = app.session.active() else { return false };
+ st.selection.text.is_some()
+ || (app.ui.formatting_affects_text && st.selection.items.iter().any(|id| st.doc.item(*id).is_some_and(|i| i.is_text_frame())))
+}
+
+/// Fill and stroke swatches and tints of what colour edits apply to: the text (see
+/// [`colors_affect_text`]) or the first selected object.
+pub fn color_target(app: &mut DesignApp) -> Option<(String, f32, String, f32)> {
+ if colors_affect_text(app) {
+ let a = text_attrs(app)?;
+ let c = &a["chars"];
+ let tint = |k: &str| c[k].as_f64().unwrap_or(1.0) as f32;
+ return Some((c["fill"].as_str()?.to_string(), tint("fillTint"), c["stroke"].as_str()?.to_string(), tint("strokeTint")));
+ }
+ let i = sel_info(app)?;
+ Some((i.fill, sel_tint(app, false), i.stroke, sel_tint(app, true)))
+}
+
+/// Apply a swatch (and tint) to the fill or stroke of what colour edits apply to.
+pub fn apply_swatch(app: &mut DesignApp, stroke: bool, swatch: &str, tint: Option<f32>) -> Result<Value, String> {
+ if colors_affect_text(app) {
+ let (k, kt) = if stroke { ("stroke", "strokeTint") } else { ("fill", "fillTint") };
+ let mut attrs = json!({k: swatch});
+ if let Some(t) = tint {
+ attrs[kt] = json!(t);
+ }
+ return app.run("type.char", json!({ "attrs": attrs }));
+ }
+ let mut p = json!({"swatch": swatch});
+ if let Some(t) = tint {
+ p["tint"] = json!(t);
+ }
+ app.run(if stroke { "object.stroke" } else { "object.fill" }, p)
+}
+
/// Fill (or stroke) tint of the first selected item (1 = 100%).
pub fn sel_tint(app: &DesignApp, stroke: bool) -> f32 {
let Some(st) = app.session.active() else { return 1.0 };
diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs
index bf3f0b3af..b9d5c0b35 100644
--- a/crates/ui-egui/src/panels/properties.rs
+++ b/crates/ui-egui/src/panels/properties.rs
@@ -1287,6 +1287,35 @@ pub fn character_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
crate::rtl::label(ui, c["fill"].as_str().unwrap_or(""));
});
ui.horizontal(|ui| {
+ // Bold and Italic pick the family's own styles (style linking).
+ let (weight, italic) =
+ designcraft_fonts::FontDb::global().traits_of(c["fontFamily"].as_str().unwrap_or_default(), c["fontStyle"].as_str().unwrap_or_default());
+ let tip = |app: &DesignApp, name: &str, id: &str| {
+ let name = crate::i18n::tr(&app.ui.language, name);
+ match crate::menus::shortcut_of(app, id) {
+ Some(sc) => format!("{name} ({})", crate::menus::shortcut_text(&sc)),
+ None => name.to_string(),
+ }
+ };
+ let (bold_tip, italic_tip) = (tip(app, "Bold", "type.bold"), tip(app, "Italic", "type.italic"));
+ if ui
+ .selectable_label(weight >= 650.0, egui::RichText::new("B").strong())
+ .on_hover_ui(|ui| {
+ crate::rtl::label(ui, bold_tip);
+ })
+ .clicked()
+ {
+ let _ = app.run("type.bold", json!({}));
+ }
+ if ui
+ .selectable_label(italic, egui::RichText::new("I").italics())
+ .on_hover_ui(|ui| {
+ crate::rtl::label(ui, italic_tip);
+ })
+ .clicked()
+ {
+ let _ = app.run("type.italic", json!({}));
+ }
let caps = c["capitalization"].as_str() == Some("allCaps");
if ui
.selectable_label(caps, "TT")
diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs
index d80b72883..f3e0a5ce7 100644
--- a/crates/ui-egui/src/panels/swatches.rs
+++ b/crates/ui-egui/src/panels/swatches.rs
@@ -11,8 +11,8 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Some(st) = app.session.active() else { return };
let doc = st.doc.clone();
- let text = st.selection.text.is_some();
- let fill_cur = super::sel_info(app).map(|i| i.fill);
+ let text = super::colors_affect_text(app);
+ let fill_cur = super::color_target(app).map(|t| t.0);
ui.horizontal(|ui| {
crate::rtl::label(
ui,
@@ -25,7 +25,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
// colour groups are listed under their folder.
let grouped: Vec<&str> = doc.color_groups.iter().flat_map(|g| g.swatches.iter().map(String::as_str)).collect();
for sw in doc.swatches.iter().filter(|w| !w.hidden && !grouped.contains(&w.name.as_str())) {
- swatch_row(app, ui, &doc, sw, 0.0, fill_cur.as_deref(), text);
+ swatch_row(app, ui, &doc, sw, 0.0, fill_cur.as_deref());
}
for g in &doc.color_groups {
let open_id = egui::Id::new(("color_group_open", &g.name));
@@ -58,7 +58,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
if open {
for n in &g.swatches {
if let Some(sw) = doc.swatches.iter().find(|w| w.name == *n) {
- swatch_row(app, ui, &doc, sw, 16.0, fill_cur.as_deref(), text);
+ swatch_row(app, ui, &doc, sw, 16.0, fill_cur.as_deref());
}
}
}
@@ -112,8 +112,8 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
});
}
-/// One Swatches panel row: chip, name, type; click applies to fill (or text), the context menu
-/// to stroke, colour groups and delete.
+/// One Swatches panel row: chip, name, type; click applies to the fill (of the frames or their
+/// text, see [`super::colors_affect_text`]), the context menu to the stroke, colour groups and delete.
fn swatch_row(
app: &mut DesignApp,
ui: &mut egui::Ui,
@@ -121,7 +121,6 @@ fn swatch_row(
sw: &designcraft_color::swatch::Swatch,
indent: f32,
fill_cur: Option<&str>,
- text: bool,
) {
let t = Tokens::get(ui.ctx());
let (row, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click());
@@ -153,12 +152,11 @@ fn swatch_row(
}
ui.painter().text(row.right_center() - vec2(6.0, 0.0), egui::Align2::RIGHT_CENTER, kind, egui::FontId::proportional(10.5), t.text_dim);
if resp.clicked() {
- let r = if text { app.run("type.char", json!({"attrs": {"fill": sw.name}})) } else { app.run("object.fill", json!({"swatch": sw.name})) };
- let _ = r;
+ let _ = super::apply_swatch(app, false, &sw.name, None);
}
resp.context_menu(|ui| {
if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Apply to Stroke"))).clicked() {
- let _ = app.run("object.stroke", json!({"swatch": sw.name}));
+ let _ = super::apply_swatch(app, true, &sw.name, None);
ui.close();
}
if !sw.locked {
@@ -199,13 +197,14 @@ pub enum ColorMode {
/// swatch), the spectrum ramp, Add to Swatches. Edits apply unnamed colours (`object.color`).
pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
- let Some(i) = super::sel_info(app) else {
+ let Some((fill, fill_tint, stroke_sw, stroke_tint)) = super::color_target(app) else {
ui.label(crate::rtl::widget(
ui,
- egui::RichText::new(crate::i18n::tr(&app.ui.language, "Select an object to color its fill or stroke.")).color(t.text_dim),
+ egui::RichText::new(crate::i18n::tr(&app.ui.language, "Select an object or text to color its fill or stroke.")).color(t.text_dim),
));
return;
};
+ let text = super::colors_affect_text(app);
let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
let stroke_id = egui::Id::new("color_panel_stroke");
let mode_id = egui::Id::new("color_panel_mode");
@@ -213,11 +212,11 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
let default_mode = if doc.settings.intent == designcraft_doc::Intent::Print { ColorMode::Cmyk } else { ColorMode::Rgb };
let mut mode: ColorMode = ui.data(|d| d.get_temp(mode_id)).unwrap_or(default_mode);
let target = if stroke { "stroke" } else { "fill" };
- let name = if stroke { i.stroke.clone() } else { i.fill.clone() };
+ let name = if stroke { stroke_sw.clone() } else { fill.clone() };
// Proxy: fill (front) and stroke chips; click to choose, double-click for the Color Picker.
ui.horizontal(|ui| {
for (k, label) in [(false, "Fill"), (true, "Stroke")] {
- let n = if k { &i.stroke } else { &i.fill };
+ let n = if k { &stroke_sw } else { &fill };
let (c, g) = crate::widgets::swatch_colors(&doc, n, 1.0);
let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click());
crate::widgets::paint_chip(ui.painter(), r.shrink(2.0), c, g);
@@ -232,7 +231,8 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
let rgb = doc.resolve_color(n, 1.0).map(|c| c.to_rgb()).unwrap_or([0.0; 3]);
let hex =
format!("#{:02x}{:02x}{:02x}", (rgb[0] * 255.0).round() as u8, (rgb[1] * 255.0).round() as u8, (rgb[2] * 255.0).round() as u8);
- app.ui.dialog = Some(crate::dialogs::Dialog::new("colorPicker", json!({"target": if k { "stroke" } else { "fill" }, "hex": hex})));
+ app.ui.dialog =
+ Some(crate::dialogs::Dialog::new("colorPicker", json!({"target": if k { "stroke" } else { "fill" }, "hex": hex, "text": text})));
}
}
ui.label(egui::RichText::new(&name).size(11.0).color(t.text_dim));
@@ -266,13 +266,12 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
};
// A named swatch shows its tint; mixing its values makes an unnamed colour.
if let Some(sw) = sw.as_ref().filter(|w| !w.hidden && !w.locked) {
- let cur = if stroke { super::sel_tint(app, true) } else { super::sel_tint(app, false) };
+ let cur = if stroke { stroke_tint } else { fill_tint };
let mut tint = cur * 100.0;
ui.horizontal(|ui| {
ui.label("T");
if ui.add(egui::Slider::new(&mut tint, 0.0..=100.0).suffix("%").integer()).drag_stopped() {
- let cmd = if stroke { "object.stroke" } else { "object.fill" };
- let _ = app.run(cmd, json!({"swatch": sw.name, "tint": tint / 100.0}));
+ let _ = super::apply_swatch(app, stroke, &sw.name, Some(tint / 100.0));
}
});
}
@@ -308,13 +307,13 @@ pub fn color_panel(app: &mut DesignApp, ui: &mut egui::Ui) {
}
}
if let Some(color) = send {
- let _ = app.run("object.color", json!({"color": color, "target": target}));
+ let _ = app.run("object.color", json!({"color": color, "target": target, "text": text}));
}
spectrum(app, ui, target);
ui.horizontal(|ui| {
let unnamed = sw.as_ref().is_some_and(|w| w.hidden);
if ui.add_enabled(unnamed, egui::Button::new(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Add to Swatches")))).clicked() {
- let _ = app.run("swatch.addToSwatches", json!({"target": target}));
+ let _ = app.run("swatch.addToSwatches", json!({"swatch": name, "target": target}));
}
});
}
@@ -384,7 +383,11 @@ fn spectrum(app: &mut DesignApp, ui: &mut egui::Ui, target: &str) {
&& let Some(p) = resp.interact_pointer_pos()
{
let c = at(((p.x - r.min.x) / r.width()).clamp(0.0, 1.0), ((p.y - r.min.y) / r.height()).clamp(0.0, 1.0));
- let _ = app.run("object.color", json!({"color": [(c[0] * 255.0).round(), (c[1] * 255.0).round(), (c[2] * 255.0).round()], "target": target}));
+ let text = super::colors_affect_text(app);
+ let _ = app.run(
+ "object.color",
+ json!({"color": [(c[0] * 255.0).round(), (c[1] * 255.0).round(), (c[2] * 255.0).round()], "target": target, "text": text}),
+ );
}
}
diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs
index 4f110df4d..fe3163d9b 100644
--- a/crates/ui-egui/src/toolbar.rs
+++ b/crates/ui-egui/src/toolbar.rs
@@ -173,14 +173,13 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) {
/// utility button and the Screen Mode well.
fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {
let t = Tokens::get(ui.ctx());
- let info = crate::panels::sel_info(app);
+ let target = crate::panels::color_target(app);
let doc = app.session.active().map(|d| d.doc.clone());
let stroke_front_id = egui::Id::new("proxy_stroke_front");
- let text_id = egui::Id::new("proxy_text");
let stroke_front: bool = ui.data(|d| d.get_temp(stroke_front_id)).unwrap_or(false);
- let text_mode: bool = ui.data(|d| d.get_temp(text_id)).unwrap_or(false);
- let (fill_sw, stroke_sw) = match &info {
- Some(i) => (i.fill.clone(), i.stroke.clone()),
+ let text_mode = crate::panels::colors_affect_text(app) || app.ui.formatting_affects_text;
+ let (fill_sw, stroke_sw) = match &target {
+ Some((fill, _, stroke, _)) => (fill.clone(), stroke.clone()),
None => ("[None]".to_string(), "[Black]".to_string()),
};
let x0 = ui.max_rect().min.x + (width - 30.0) / 2.0;
@@ -195,8 +194,10 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {
})
.clicked()
{
- let _ = app.run("object.fill", json!({"swatch": "[None]"}));
- let _ = app.run("object.stroke", json!({"swatch": "[Black]"}));
+ // Text defaults to a black fill and no stroke; objects to no fill and a black stroke.
+ let (fill, stroke) = if crate::panels::colors_affect_text(app) { ("[Black]", "[None]") } else { ("[None]", "[Black]") };
+ let _ = crate::panels::apply_swatch(app, false, fill, None);
+ let _ = crate::panels::apply_swatch(app, true, stroke, None);
}
let swap = egui::Rect::from_min_size(egui::pos2(x0 + 19.0, row.min.y), vec2(11.0, 11.0));
icons::paint(ui.painter(), swap, "swap", t.icon);
@@ -207,8 +208,8 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {
})
.clicked()
{
- let _ = app.run("object.fill", json!({"swatch": stroke_sw}));
- let _ = app.run("object.stroke", json!({"swatch": fill_sw}));
+ let _ = crate::panels::apply_swatch(app, false, &stroke_sw, None);
+ let _ = crate::panels::apply_swatch(app, true, &fill_sw, None);
}
ui.add_space(2.0);
// Proxy: 19.5 pt squares, fill top-left, stroke bottom-right.
@@ -279,7 +280,7 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {
})
.clicked()
{
- ui.data_mut(|d| d.insert_temp(text_id, k == 1));
+ let _ = app.run("app.formattingAffectsText", json!({"on": k == 1}));
}
}
ui.add_space(5.0);
@@ -293,14 +294,13 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) {
let chip = egui::Rect::from_center_size(well.center(), vec2(14.0, 14.0));
crate::widgets::paint_chip(ui.painter(), chip, None, None);
flyout_triangle(ui.painter(), well, t.icon);
- let target = if stroke_front { "object.stroke" } else { "object.fill" };
if resp.clicked() {
- let _ = app.run(target, json!({"swatch": "[None]"}));
+ let _ = crate::panels::apply_swatch(app, stroke_front, "[None]", None);
}
egui::Popup::context_menu(&resp).show(|ui| {
for (label, sw) in [("Apply Color", "[Black]"), ("Apply None", "[None]")] {
if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {
- let _ = app.run(target, json!({"swatch": sw}));
+ let _ = crate::panels::apply_swatch(app, stroke_front, sw, None);
ui.close();
}
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 0c6f334e1..86364b50c 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -16,7 +16,7 @@ Start the app with `--control <port>` (or `DESIGNCRAFT_CONTROL_PORT`). The serve
| `ui.inspect` | — | Tool, UI state, view (zoom/origin), canvas rect, perf |
| `ui.menu.list` / `ui.tool.list` | — | Menu tree / Tools panel groups |
| `ui.tool.select` | `{tool}` | Select a tool (`selection`, `type`, `rectangleFrame`, …) |
-| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas"}], mods?}` | Drive the active tool through the same code path as the mouse |
+| `ui.pointer` | `{events:[{kind: down\|drag\|up\|move\|doubleclick, x, y, space?: "screen"\|"canvas", clicks?}], mods?}` | Drive the active tool through the same code path as the mouse; `clicks` on a `down` is the press count (3 = triple click) |
| `ui.key` / `ui.text` | `{key, shift?, alt?, cmd?}` / `{text}` | Synthetic keyboard input (typing into a text frame) |
| `ui.move` / `ui.click` / `ui.drag` | screen points | Real egui pointer input — reaches every widget, menu and panel |
| `ui.set` | `{brightness?, panel?, rulers?, guides?, frameEdges?, baselineGrid?, textThreads?, screenMode?, zoom?, page?, fit?}` | UI state |