mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 08:26:28 +00:00
Character panel: work out the selected stories once, not once per field
With the Selection tool, every Character and Paragraph field read its value through selected_stories, which walked the selected objects and looked up each type object's story again. With the default panels open that was 24 builds of the same list per frame. selected_stories and selected_story_texts now keep the last list, with the document (a held Weak keeps its address from being reused), its revision and a copy of the selected objects. A change to any of them builds the list again. Type objects are still resolved from the current document on every read, so the panels show the same values. Tests compare the kept list with a fresh build after an edit, a reordered or replaced selection, a selection set without a new revision, a selected group and a switch to another document at the same revision; compare what both panels draw and their field values with and without the kept list; and count one build per frame.
This commit is contained in:
@@ -2,14 +2,17 @@
|
||||
//! scale, baseline shift, character rotation, the anti-aliasing method and the All Caps, Small Caps,
|
||||
//! Superscript, Subscript, Underline and Strikethrough toggles and the Language menu.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
|
||||
use egui::{Key, Ui, vec2};
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::setup::{LANGUAGES, char_language_name};
|
||||
use vectorcraft_doc::text::TypeAntiAlias;
|
||||
use vectorcraft_doc::{CharStyle, NodeId, NodeKind};
|
||||
use vectorcraft_engine::DocState;
|
||||
use vectorcraft_tools::{Mods, ToolKey};
|
||||
|
||||
use super::{pstate, set_pstate};
|
||||
@@ -589,7 +592,62 @@ pub(crate) fn text_story(app: &VectorcraftApp) -> Option<Vec<NodeId>> {
|
||||
/// in selected groups, each with every frame of its threaded story (locked and hidden frames
|
||||
/// included), each once, the frames of a story in thread order.
|
||||
pub(crate) fn selected_stories(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
let Some(st) = app.session.active() else { return Vec::new() };
|
||||
app.session.active().map_or_else(Vec::new, |st| story_frames(st).to_vec())
|
||||
}
|
||||
|
||||
/// The last list [`selected_stories`] worked out, with the document version (its address, which
|
||||
/// the held `Weak` keeps from being reused, and its revision) and the selected objects it was
|
||||
/// worked out for. The Character and Paragraph panels read the list once for each field they show.
|
||||
struct StoryFrames {
|
||||
doc: Weak<vectorcraft_doc::Document>,
|
||||
revision: u64,
|
||||
selection: Vec<NodeId>,
|
||||
frames: Rc<[NodeId]>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STORY_FRAMES: RefCell<Option<StoryFrames>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`build_selected_stories`] ran on this thread.
|
||||
static STORY_BUILDS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Whether [`story_frames`] builds the list on every read instead of keeping it.
|
||||
static STORIES_UNKEPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// [`selected_stories`] of `st`: the kept list while `st`'s document, revision and selected
|
||||
/// objects are the ones it was worked out for, else a new one, kept in its place.
|
||||
fn story_frames(st: &DocState) -> Rc<[NodeId]> {
|
||||
#[cfg(test)]
|
||||
if STORIES_UNKEPT.get() {
|
||||
return build_selected_stories(st).into();
|
||||
}
|
||||
STORY_FRAMES.with_borrow_mut(|kept| {
|
||||
if let Some(k) = kept.as_ref()
|
||||
&& k.revision == st.revision
|
||||
&& k.doc.strong_count() > 0
|
||||
&& std::ptr::eq(k.doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
&& k.selection == st.selection.objects
|
||||
{
|
||||
return k.frames.clone();
|
||||
}
|
||||
let frames: Rc<[NodeId]> = build_selected_stories(st).into();
|
||||
*kept = Some(StoryFrames {
|
||||
doc: Arc::downgrade(&st.doc),
|
||||
revision: st.revision,
|
||||
selection: st.selection.objects.clone(),
|
||||
frames: frames.clone(),
|
||||
});
|
||||
frames
|
||||
})
|
||||
}
|
||||
|
||||
/// The list [`selected_stories`] describes, worked out from `st`'s selection.
|
||||
fn build_selected_stories(st: &DocState) -> Vec<NodeId> {
|
||||
#[cfg(test)]
|
||||
STORY_BUILDS.set(STORY_BUILDS.get() + 1);
|
||||
let mut frames = Vec::new();
|
||||
let mut taken = HashSet::new();
|
||||
for selected in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) {
|
||||
@@ -609,9 +667,9 @@ pub(crate) fn selected_stories(app: &VectorcraftApp) -> Vec<NodeId> {
|
||||
/// The type objects of [`selected_stories`].
|
||||
pub(crate) fn selected_story_texts(app: &VectorcraftApp) -> Vec<&vectorcraft_doc::TextObject> {
|
||||
let Some(st) = app.session.active() else { return Vec::new() };
|
||||
selected_stories(app)
|
||||
.into_iter()
|
||||
.filter_map(|id| match st.doc.node(id).map(|n| &n.kind) {
|
||||
story_frames(st)
|
||||
.iter()
|
||||
.filter_map(|&id| match st.doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => Some(t.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
|
||||
@@ -1971,3 +1971,160 @@ fn selected_stories_list_each_frame_once() {
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
assert!(selected_stories(&app).is_empty());
|
||||
}
|
||||
|
||||
/// Check that the kept list of the selected stories, and the type objects it resolves to, are the
|
||||
/// ones a fresh build works out.
|
||||
fn assert_stories_are_fresh(app: &VectorcraftApp, what: &str) {
|
||||
let st = app.session.active().unwrap();
|
||||
let fresh = build_selected_stories(st);
|
||||
assert_eq!(selected_stories(app), fresh, "{what}");
|
||||
let texts = selected_story_texts(app);
|
||||
let expected: Vec<_> = fresh
|
||||
.iter()
|
||||
.filter_map(|id| match &st.doc.node(*id)?.kind {
|
||||
NodeKind::Text(t) => Some(t.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts.len(), expected.len(), "{what}: type objects");
|
||||
assert!(texts.iter().zip(&expected).all(|(t, e)| std::ptr::eq(*t, *e)), "{what}: the current document's type objects, in order");
|
||||
}
|
||||
|
||||
/// The kept list of the selected stories follows every change it is worked out from: an edit, a
|
||||
/// new selection (in another order, or as long with other objects, also without a new revision),
|
||||
/// a selected group and a switch to another document at the same revision.
|
||||
#[test]
|
||||
fn kept_selected_stories_follow_the_document_and_the_selection() {
|
||||
let (mut app, [a, b, c], other) = story_selected_in_its_first_frame();
|
||||
assert_stories_are_fresh(&app, "a frame of a story");
|
||||
let builds = STORY_BUILDS.get();
|
||||
assert_eq!(selected_stories(&app), [a, b, c].map(NodeId).to_vec());
|
||||
assert_eq!(STORY_BUILDS.get(), builds, "a second read keeps the list");
|
||||
|
||||
app.run("text.setStyle", json!({"size": 9})).unwrap();
|
||||
assert_stories_are_fresh(&app, "after an edit");
|
||||
app.run("select.set", json!({"ids": [other, a]})).unwrap();
|
||||
assert_stories_are_fresh(&app, "two stories");
|
||||
app.run("select.set", json!({"ids": [a, other]})).unwrap();
|
||||
assert_stories_are_fresh(&app, "the same objects in another order");
|
||||
app.run("select.set", json!({"ids": [other, b]})).unwrap();
|
||||
assert_stories_are_fresh(&app, "as many other objects");
|
||||
app.session.doc_mut().unwrap().selection.objects = vec![NodeId(other)];
|
||||
assert_stories_are_fresh(&app, "a new selection at the same revision");
|
||||
assert_eq!(selected_stories(&app), vec![NodeId(other)]);
|
||||
|
||||
app.run("select.set", json!({"ids": [other, a]})).unwrap();
|
||||
let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("select.set", json!({"ids": [group]})).unwrap();
|
||||
assert_stories_are_fresh(&app, "a selected group");
|
||||
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
|
||||
let only = app.run("text.create", json!({"x": 20, "y": 50, "text": "Only", "size": 12})).unwrap()["id"].as_u64().unwrap();
|
||||
let st = app.session.doc_mut().unwrap();
|
||||
st.selection.objects = vec![NodeId(group)];
|
||||
st.revision = revision;
|
||||
assert_stories_are_fresh(&app, "another document with the first one's selection and revision");
|
||||
assert_ne!(selected_stories(&app), [a, b, c, other].map(NodeId).to_vec());
|
||||
app.run("select.set", json!({"ids": [only]})).unwrap();
|
||||
assert_stories_are_fresh(&app, "the other document's own type");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
assert_stories_are_fresh(&app, "back in the first document");
|
||||
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
assert!(selected_stories(&app).is_empty());
|
||||
assert!(selected_story_texts(&app).is_empty());
|
||||
}
|
||||
|
||||
/// What the Character and Paragraph panels draw, and the values of their fields, with the list of
|
||||
/// the selected stories kept and with it built for every read.
|
||||
fn panels_kept_and_unkept(app: &mut VectorcraftApp) -> [(Vec<String>, String); 2] {
|
||||
let read = |app: &mut VectorcraftApp, unkept: bool| {
|
||||
STORIES_UNKEPT.set(unkept);
|
||||
let ctx = egui::Context::default();
|
||||
let mut texts = vec![];
|
||||
for _ in 0..3 {
|
||||
texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| {
|
||||
show(app, ui);
|
||||
crate::panels::paragraph::show(app, ui);
|
||||
});
|
||||
}
|
||||
// A rect's position can be NaN, which `Rect`'s `==` refuses to compare.
|
||||
let texts: Vec<String> = texts.iter().map(|(text, rect)| format!("{text} {rect:?}")).collect();
|
||||
let fields = format!(
|
||||
"{:?} {:?}",
|
||||
[
|
||||
shared_effective(app, |s| s.size),
|
||||
shared_effective(app, |s| s.h_scale),
|
||||
shared_effective(app, |s| s.v_scale),
|
||||
shared_effective(app, |s| s.baseline_shift),
|
||||
shared_leading(app),
|
||||
shared(app, |s| s.tracking),
|
||||
],
|
||||
(
|
||||
shared(app, |s| (s.font_family.clone(), s.font_style.clone())),
|
||||
shared(app, |s| (s.all_caps, s.underline, s.strikethrough, s.position)),
|
||||
selected_fonts(app),
|
||||
any_style(app, |s| s.underline),
|
||||
selected_stories(app),
|
||||
selected_story_texts(app).len(),
|
||||
text_style(app).map(|(c, p)| (c.size, p.left_indent)),
|
||||
)
|
||||
);
|
||||
STORIES_UNKEPT.set(false);
|
||||
(texts, fields)
|
||||
};
|
||||
[read(app, true), read(app, false)]
|
||||
}
|
||||
|
||||
/// The panels show the same thing whether the list of the selected stories is kept or worked out
|
||||
/// for each field: with nothing selected, one story, several stories with mixed values and a
|
||||
/// Type tool selection inside one story.
|
||||
#[test]
|
||||
fn panels_show_the_same_with_the_kept_selected_stories() {
|
||||
let (mut app, [a, b, c], other) = story_selected_in_its_first_frame();
|
||||
let same = |app: &mut VectorcraftApp, what: &str| {
|
||||
let [unkept, kept] = panels_kept_and_unkept(app);
|
||||
assert_eq!(unkept.1, kept.1, "{what}: field values");
|
||||
assert_eq!(unkept.0, kept.0, "{what}: what the panels draw");
|
||||
unkept.1
|
||||
};
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
same(&mut app, "nothing selected");
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
let one = same(&mut app, "one story");
|
||||
app.run("text.setStyle", json!({"ids": [c], "size": 20, "tracking": 50})).unwrap();
|
||||
app.run("text.setFormat", json!({"ids": [b], "underline": true, "hScale": 120})).unwrap();
|
||||
app.run("select.set", json!({"ids": [other, a]})).unwrap();
|
||||
let mixed = same(&mut app, "several stories with mixed values");
|
||||
assert_ne!(one, mixed);
|
||||
app.session.select_tool("type", Default::default()).unwrap();
|
||||
app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 4, "caret": 15}));
|
||||
assert_eq!(text_editing(&app), Some((NodeId(a), 4, 15)));
|
||||
same(&mut app, "a Type tool selection inside one story");
|
||||
}
|
||||
|
||||
/// One frame of the Character and Paragraph panels works out the selected stories once, though
|
||||
/// many of their fields read them; a change to the document works them out again.
|
||||
#[test]
|
||||
fn panels_work_out_the_selected_stories_once_per_frame() {
|
||||
let (mut app, [a, ..], other) = story_selected_in_its_first_frame();
|
||||
app.run("select.set", json!({"ids": [other, a]})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let builds = STORY_BUILDS.get();
|
||||
super::super::tests_appearance::frame_events(&ctx, app, vec![], |app, ui| {
|
||||
show(app, ui);
|
||||
crate::panels::paragraph::show(app, ui);
|
||||
});
|
||||
STORY_BUILDS.get() - builds
|
||||
};
|
||||
frame(&mut app);
|
||||
app.run("text.setStyle", json!({"size": 9})).unwrap();
|
||||
assert_eq!(frame(&mut app), 1, "one build after an edit");
|
||||
assert_eq!(frame(&mut app), 0, "nothing changed");
|
||||
STORIES_UNKEPT.set(true);
|
||||
let reads = frame(&mut app);
|
||||
STORIES_UNKEPT.set(false);
|
||||
assert!(reads > 1, "the fields read the list {reads} times");
|
||||
}
|
||||
|
||||
@@ -1113,6 +1113,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- With the whole story of threaded text selected by Select All, the Character, Paragraph, OpenType, Tabs and Text Styles panels, the Justification dialog and the font menu change the frames that are in the edited frame's thread at the time of the change, locked and hidden frames included. A frame that has left the thread is not changed, and a frame added to the thread is (VectorCraft's own behavior; `panels::character::tests::story_changes_follow_the_edited_frames_thread_after_the_first_saved_frame_leaves`, `story_changes_leave_out_a_frame_that_left_and_take_in_a_frame_that_joined`, `story_changes_stay_in_the_edited_frame_once_its_thread_is_removed`, `story_changes_take_in_locked_and_hidden_frames`).
|
||||
- With the Selection tool, a Character or Paragraph panel change to a selected frame of threaded text changes every frame of its story, locked and hidden frames included, as one undo step. The anti-aliasing method, Variable Font axes, the Tabs panel's tab stops and both panels' Reset Panel change the whole story too, and the panels show a value only when every frame of the story has it. A story selected through several of its frames or through a group is changed once, and other type keeps its formatting (VectorCraft's own behavior; `panels::character::tests::selection_tool_changes_reach_every_frame_of_the_story`, `selection_tool_fields_read_every_frame_of_the_story`, `selected_stories_list_each_frame_once`, `panels::paragraph::tests::selection_tool_paragraph_changes_reach_every_frame_of_the_story`, `panels::tabs::tests::selection_tool_tab_stops_reach_every_frame_of_the_story`).
|
||||
- With the Selection tool, the Justification dialog, the OpenType panel, a Character or Paragraph Styles row and Type › Bullets and Numbering › Convert to Text also change every frame of a selected story, locked and hidden frames included, as one undo step. The Justification dialog acts on the story's frames as they were when it opened. When the frames differ, the OpenType panel's Figure menu shows Mixed, its checkboxes show a dash (a click turns the feature on everywhere), and the style panels highlight no row; a row shows "+" when any frame overrides its style (VectorCraft's own behavior; `dialogs::justification::tests::selection_tool_justification_reaches_every_frame_of_the_story`, `panels::opentype::tests::selection_tool_features_reach_every_frame_of_the_story`, `panels::text_styles::tests::selection_tool_styles_reach_every_frame_of_the_story`, `panels::paragraph::tests::selection_tool_convert_to_text_takes_every_frame_of_the_story`).
|
||||
- With the Selection tool, the Character and Paragraph panels work out the list of selected stories once, not once for each of the 24 fields they show by default, and reuse it until the document, its revision or the selected objects change. The panels show the same values. With 200 threads of 10 frames and 2,000 point type objects selected, one frame of both panels takes 21.7 ms of CPU time in a release build instead of 81.7 ms (`panels::character::tests::kept_selected_stories_follow_the_document_and_the_selection`, `panels_show_the_same_with_the_kept_selected_stories` and `panels_work_out_the_selected_stories_once_per_frame`).
|
||||
- Switching from a Type tool to the Eyedropper keeps a whole story selected by Select All: a pick applies to the text of every frame as one undo step, and switching back restores the story selection (VectorCraft's own behavior; `textedit::switching_to_the_eyedropper_keeps_the_whole_story_selected`).
|
||||
- While the Type tool edits text, a character typed with AltGr is typed and runs no command. Firefox on Windows reports AltGr as Ctrl and Alt held, so in the web build AltGr+L (ł on a Polish layout) does not also open Layer Options for a new layer, and AltGr+Q (@ on a German layout) does not also run Reset Tracking and Kerning. A Ctrl+Alt chord that types no character runs its command.
|
||||
- On a layout without Latin letters, a one-key shortcut goes by the position of the key that typed the character, in the web build too, where the character arrives before its key press: on a Russian layout the P key (`з`) chooses the Pen, and two keys pressed in one frame each run their own shortcut.
|
||||
|
||||
Reference in New Issue
Block a user