mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 02:04:59 -06:00
canvas-w12: net change of 3 commits
- canvas-w12: written by an agent - canvas-w12: finished by an agent - canvas-w12: review fixes (review-1)
This commit is contained in:
@@ -1,20 +1,21 @@
|
||||
//! Spelling squiggles: misspelt words on the current slide (shapes and table cells) and in the
|
||||
//! speaker notes get a red wavy underline. Checks run on a worker thread so typing never waits for
|
||||
//! a dictionary; the web build has no threads, so there the same checker runs on the UI thread a
|
||||
//! few milliseconds per frame until it is done. Results are for one version of the text; while a
|
||||
//! newer check runs nothing stale is drawn. The word the caret is in isn't marked, as in
|
||||
//! PowerPoint.
|
||||
//! speaker notes get a wavy underline. Checks use the host's job queue; without background lanes,
|
||||
//! the queue runs on the UI thread within a bounded budget per pass. Marks appear only when all
|
||||
//! paragraphs of the current text are checked. The word the caret is in isn't marked.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
|
||||
use craft::host::queue::{JobQueue, Priority, QueueOptions};
|
||||
use craft::host::{Jobs, Wake};
|
||||
use craft::ui::canvas_controls::SpellingMarks;
|
||||
use craft::ui::contract::Show;
|
||||
use deckcraft_engine::DocState;
|
||||
use deckcraft_geom::Point;
|
||||
use deckcraft_model::{Paragraph, ShapeId};
|
||||
|
||||
/// Milliseconds of checking per frame on the UI thread (the web build).
|
||||
/// Milliseconds of checking per pass on the UI thread (the web build).
|
||||
pub const FRAME_BUDGET_MS: f64 = 4.0;
|
||||
|
||||
/// Where a checked paragraph is.
|
||||
@@ -36,47 +37,8 @@ pub enum Tag {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Kind {
|
||||
Slide,
|
||||
Notes,
|
||||
}
|
||||
|
||||
/// What a check is for: a hash of the text's identity, and the user dictionary version.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Key {
|
||||
of: u64,
|
||||
user: u64,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
kind: Kind,
|
||||
key: Key,
|
||||
default_lang: String,
|
||||
paras: Vec<(Tag, Paragraph)>,
|
||||
repaint: Option<egui::Context>,
|
||||
}
|
||||
|
||||
/// Misspelt character ranges, per paragraph.
|
||||
struct Done {
|
||||
kind: Kind,
|
||||
key: Key,
|
||||
ranges: Vec<(Tag, usize, usize)>,
|
||||
}
|
||||
|
||||
/// Return the shared application clock in milliseconds for spelling-squiggle animation timing.
|
||||
fn now_ms() -> f64 {
|
||||
crate::now_ms()
|
||||
}
|
||||
|
||||
/// The checking itself, step by step: the newest job of each kind, a paragraph at a time, with
|
||||
/// results cached by paragraph content (typing re-checks only the paragraph typed in).
|
||||
#[derive(Default)]
|
||||
struct Checker {
|
||||
cache: HashMap<u64, Vec<(usize, usize)>>,
|
||||
user: Option<u64>,
|
||||
/// Jobs with how far they got and what they found so far.
|
||||
jobs: Vec<(Job, usize, Vec<(Tag, usize, usize)>)>,
|
||||
craft::platform::clock::monotonic_ms()
|
||||
}
|
||||
|
||||
fn hash_of(v: &impl Hash) -> u64 {
|
||||
@@ -85,72 +47,6 @@ fn hash_of(v: &impl Hash) -> u64 {
|
||||
h.finish()
|
||||
}
|
||||
|
||||
impl Checker {
|
||||
fn push(&mut self, job: Job) {
|
||||
self.jobs.retain(|(j, _, _)| j.kind != job.kind);
|
||||
self.jobs.push((job, 0, vec![]));
|
||||
}
|
||||
|
||||
fn idle(&self) -> bool {
|
||||
self.jobs.is_empty()
|
||||
}
|
||||
|
||||
/// Check until `budget_ms` is spent (or everything is done); finished jobs.
|
||||
fn step(&mut self, budget_ms: f64) -> Vec<(Done, Option<egui::Context>)> {
|
||||
let t0 = now_ms();
|
||||
let mut out = vec![];
|
||||
while let Some((job, at, found)) = self.jobs.first_mut() {
|
||||
if self.user != Some(job.key.user) {
|
||||
self.cache.clear();
|
||||
self.user = Some(job.key.user);
|
||||
}
|
||||
while *at < job.paras.len() {
|
||||
let (tag, p) = &job.paras[*at];
|
||||
let k = hash_of(&(serde_json::to_string(&p.runs).unwrap_or_default(), &job.default_lang));
|
||||
let r = self
|
||||
.cache
|
||||
.entry(k)
|
||||
.or_insert_with(|| deckcraft_engine::spell::misspelt(p, &job.default_lang, &[]).into_iter().map(|w| (w.start, w.end)).collect());
|
||||
found.extend(r.iter().map(|(a, b)| (*tag, *a, *b)));
|
||||
*at += 1;
|
||||
if now_ms() - t0 > budget_ms {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
let (job, _, ranges) = self.jobs.remove(0);
|
||||
out.push((Done { kind: job.kind, key: job.key, ranges }, job.repaint));
|
||||
}
|
||||
if self.cache.len() > 20_000 {
|
||||
self.cache.clear();
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn worker(rx: Receiver<Job>, tx: Sender<Done>) {
|
||||
let mut c = Checker::default();
|
||||
loop {
|
||||
if c.idle() {
|
||||
match rx.recv() {
|
||||
Ok(j) => c.push(j),
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
while let Ok(j) = rx.try_recv() {
|
||||
c.push(j);
|
||||
}
|
||||
// In slices, so a newer job can replace one being checked.
|
||||
for (d, repaint) in c.step(20.0) {
|
||||
if tx.send(d).is_err() {
|
||||
return;
|
||||
}
|
||||
if let Some(r) = repaint {
|
||||
r.request_repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_lang(st: &DocState) -> String {
|
||||
for sl in &st.doc.slides {
|
||||
let mut found = None;
|
||||
@@ -171,19 +67,20 @@ fn default_lang(st: &DocState) -> String {
|
||||
/// A word under a squiggle: `(tag, start, end)`.
|
||||
type Mark = (Tag, usize, usize);
|
||||
|
||||
#[derive(Default)]
|
||||
/// Checks paragraphs through the host and retains document-space spelling marks.
|
||||
pub struct Squiggles {
|
||||
tx: Option<Sender<Job>>,
|
||||
rx: Option<Receiver<Done>>,
|
||||
/// No worker thread (the web build, or forced for tests): check on the UI thread.
|
||||
inline: Option<Checker>,
|
||||
/// Check on the UI thread even where threads exist (tests of the web path).
|
||||
jobs: Arc<dyn Jobs>,
|
||||
wake: Wake,
|
||||
options: QueueOptions,
|
||||
queue: Option<JobQueue<u64, Vec<(usize, usize)>>>,
|
||||
cache: HashMap<u64, Vec<(usize, usize)>>,
|
||||
user: Option<u64>,
|
||||
/// Check on the UI thread even where threads exist; set before the first update or notes check.
|
||||
pub force_inline: bool,
|
||||
pending: [Option<Key>; 2],
|
||||
done: [Option<Done>; 2],
|
||||
/// Underlines in slide coordinates for the slide's `done`, and the key they were laid out for.
|
||||
/// Document-space underlines, independent of framework layout passes.
|
||||
lines: Vec<(Mark, Point, Point)>,
|
||||
lines_for: Option<Key>,
|
||||
// PLAN: plan error: removing Key must retain the document/revision/slide/dictionary identity of lines_for.
|
||||
lines_for: Option<(usize, u64, usize, u64)>,
|
||||
/// Off (tests or the setting).
|
||||
pub disabled: bool,
|
||||
/// The misspelt word a context menu is open on.
|
||||
@@ -263,66 +160,56 @@ pub fn menu_word(pp: &Paragraph, default: &str, tag: Tag, start: usize) -> Optio
|
||||
Some(MenuWord { tag, start, word: w.text, suggestions, delete_from: w.repeated })
|
||||
}
|
||||
|
||||
fn slot(k: Kind) -> usize {
|
||||
match k {
|
||||
Kind::Slide => 0,
|
||||
Kind::Notes => 1,
|
||||
}
|
||||
}
|
||||
|
||||
impl Squiggles {
|
||||
fn start(&mut self) -> bool {
|
||||
if self.tx.is_some() || self.inline.is_some() {
|
||||
return true;
|
||||
}
|
||||
if !cfg!(target_arch = "wasm32") && !self.force_inline {
|
||||
let (jtx, jrx) = channel();
|
||||
let (dtx, drx) = channel();
|
||||
if std::thread::Builder::new().name("spelling".into()).spawn(move || worker(jrx, dtx)).is_ok() {
|
||||
self.tx = Some(jtx);
|
||||
self.rx = Some(drx);
|
||||
return true;
|
||||
fn prepare(&mut self) -> u64 {
|
||||
let user = deckcraft_engine::spell::user_generation();
|
||||
if self.queue.is_none() || self.user != Some(user) {
|
||||
if self.queue.is_none() && self.force_inline {
|
||||
self.options.lanes = 0;
|
||||
}
|
||||
// Drop before draining: even a finished same-key result belongs to its dictionary.
|
||||
self.queue = None;
|
||||
self.queue = Some(JobQueue::new(self.jobs.clone(), self.wake.clone(), self.options.clone()));
|
||||
self.cache.clear();
|
||||
self.lines.clear();
|
||||
self.lines_for = None;
|
||||
self.user = Some(user);
|
||||
}
|
||||
self.inline = Some(Checker::default());
|
||||
true
|
||||
user
|
||||
}
|
||||
|
||||
/// Take in finished checks (and, on the UI thread, spend this frame's budget).
|
||||
fn receive(&mut self, budget_ms: f64) {
|
||||
let mut got = vec![];
|
||||
if let Some(rx) = &self.rx {
|
||||
while let Ok(d) = rx.try_recv() {
|
||||
got.push(d);
|
||||
fn check(&mut self, paras: Vec<(Tag, Paragraph)>, lang: &str) -> Option<Vec<Mark>> {
|
||||
let queue = self.queue.as_ref()?;
|
||||
while let Some(finished) = queue.try_recv() {
|
||||
self.cache.insert(finished.key, finished.result);
|
||||
}
|
||||
let mut keys = Vec::with_capacity(paras.len());
|
||||
for (tag, p) in paras {
|
||||
let key = hash_of(&(serde_json::to_string(&p.runs).unwrap_or_default(), lang));
|
||||
keys.push((tag, key));
|
||||
if !self.cache.contains_key(&key) && !queue.contains(&key) {
|
||||
let lang = lang.to_owned();
|
||||
queue.submit(key, Priority::VISIBLE, move |_| {
|
||||
deckcraft_engine::spell::misspelt(&p, &lang, &[]).into_iter().map(|w| (w.start, w.end)).collect()
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(c) = self.inline.as_mut() {
|
||||
got.extend(c.step(budget_ms).into_iter().map(|(d, _)| d));
|
||||
if self.options.lanes == 0 {
|
||||
let started = now_ms();
|
||||
while now_ms() - started < FRAME_BUDGET_MS && queue.run_inline(1) != 0 {}
|
||||
}
|
||||
for d in got {
|
||||
let i = slot(d.kind);
|
||||
if self.pending[i] == Some(d.key) {
|
||||
self.pending[i] = None;
|
||||
}
|
||||
self.done[i] = Some(d);
|
||||
while let Some(finished) = queue.try_recv() {
|
||||
self.cache.insert(finished.key, finished.result);
|
||||
}
|
||||
}
|
||||
|
||||
fn ask(&mut self, kind: Kind, key: Key, default_lang: String, paras: impl FnOnce() -> Vec<(Tag, Paragraph)>, repaint: Option<&egui::Context>) {
|
||||
let i = slot(kind);
|
||||
if self.done[i].as_ref().is_some_and(|d| d.key == key) || self.pending[i] == Some(key) {
|
||||
return;
|
||||
let mut ranges = vec![];
|
||||
// A shared paragraph key still has one tag per occurrence, in document order.
|
||||
for (tag, key) in keys {
|
||||
ranges.extend(self.cache.get(&key)?.iter().map(|&(a, b)| (tag, a, b)));
|
||||
}
|
||||
let job = Job { kind, key, default_lang, paras: paras(), repaint: repaint.cloned() };
|
||||
if let Some(c) = self.inline.as_mut() {
|
||||
c.push(job);
|
||||
self.pending[i] = Some(key);
|
||||
if let Some(r) = repaint {
|
||||
r.request_repaint();
|
||||
}
|
||||
} else if self.tx.as_ref().is_some_and(|tx| tx.send(job).is_ok()) {
|
||||
self.pending[i] = Some(key);
|
||||
if self.cache.len() > 20_000 {
|
||||
self.cache.clear();
|
||||
}
|
||||
Some(ranges)
|
||||
}
|
||||
|
||||
fn is_ignored(&self, word: &str) -> bool {
|
||||
@@ -331,14 +218,15 @@ impl Squiggles {
|
||||
|
||||
/// Ask for a check of the current slide if it changed, take in finished checks, and return the
|
||||
/// underlines to draw (slide coordinates).
|
||||
pub fn update(&mut self, st: &DocState, repaint: Option<&egui::Context>) -> Vec<(Point, Point)> {
|
||||
if self.disabled || !self.start() {
|
||||
pub fn update(&mut self, st: &DocState) -> Vec<(Point, Point)> {
|
||||
if self.disabled {
|
||||
return vec![];
|
||||
}
|
||||
self.receive(FRAME_BUDGET_MS);
|
||||
let key =
|
||||
Key { of: hash_of(&(Arc::as_ptr(&st.doc) as usize, st.revision, st.selection.slide)), user: deckcraft_engine::spell::user_generation() };
|
||||
let paras = || {
|
||||
let user = self.prepare();
|
||||
let key = (Arc::as_ptr(&st.doc) as usize, st.revision, st.selection.slide, user);
|
||||
if self.lines_for != Some(key) {
|
||||
self.lines.clear();
|
||||
self.lines_for = None;
|
||||
let mut paras = vec![];
|
||||
if let Some(sl) = st.doc.slides.get(st.selection.slide) {
|
||||
deckcraft_model::walk(&sl.shapes, &mut |sh, _| {
|
||||
@@ -361,13 +249,8 @@ impl Squiggles {
|
||||
}
|
||||
});
|
||||
}
|
||||
paras
|
||||
};
|
||||
self.ask(Kind::Slide, key, default_lang(st), paras, repaint);
|
||||
let Some(d) = self.done[0].as_ref().filter(|d| d.key == key) else { return vec![] };
|
||||
if self.lines_for != Some(key) {
|
||||
self.lines.clear();
|
||||
for &(tag, a, b) in &d.ranges {
|
||||
let Some(ranges) = self.check(paras, &default_lang(st)) else { return vec![] };
|
||||
for (tag, a, b) in ranges {
|
||||
let under = match tag {
|
||||
Tag::Shape { id, para } => deckcraft_engine::cmd::text::range_underlines(st, id, &[(para, a, b)]),
|
||||
Tag::Cell { id, row, col, para } => deckcraft_engine::cmd::text::cell_range_underlines(st, id, row, col, &[(para, a, b)]),
|
||||
@@ -399,35 +282,36 @@ impl Squiggles {
|
||||
|
||||
/// The misspelt character ranges of the notes text being shown (`caret` is the cursor's
|
||||
/// character index, whose word isn't marked); empty until the check is in.
|
||||
pub fn notes(&mut self, text: &str, lang: &str, caret: Option<usize>, repaint: Option<&egui::Context>) -> Vec<(usize, usize)> {
|
||||
if self.disabled || !self.start() {
|
||||
return vec![];
|
||||
pub fn notes(&mut self, text: &str, lang: &str, caret: Option<usize>) -> Vec<(usize, usize)> {
|
||||
self.checked_notes(text, lang, caret).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn checked_notes(&mut self, text: &str, lang: &str, caret: Option<usize>) -> Option<Vec<(usize, usize)>> {
|
||||
if self.disabled {
|
||||
return Some(vec![]);
|
||||
}
|
||||
self.receive(FRAME_BUDGET_MS);
|
||||
let key = Key { of: hash_of(&(text, lang)), user: deckcraft_engine::spell::user_generation() };
|
||||
let paras = || {
|
||||
let mut out = vec![];
|
||||
let mut start = 0;
|
||||
for line in text.split('\n') {
|
||||
out.push((Tag::Notes { start }, Paragraph::new(line)));
|
||||
start += line.chars().count() + 1;
|
||||
}
|
||||
out
|
||||
};
|
||||
self.ask(Kind::Notes, key, lang.to_string(), paras, repaint);
|
||||
let Some(d) = self.done[1].as_ref().filter(|d| d.key == key) else { return vec![] };
|
||||
self.prepare();
|
||||
let mut paras = vec![];
|
||||
let mut start = 0;
|
||||
for line in text.split('\n') {
|
||||
paras.push((Tag::Notes { start }, Paragraph::new(line)));
|
||||
start += line.chars().count() + 1;
|
||||
}
|
||||
let ranges = self.check(paras, lang)?;
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
d.ranges
|
||||
.iter()
|
||||
.filter_map(|&(tag, a, b)| match tag {
|
||||
Tag::Notes { start } => Some((start + a, start + b)),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|(a, b)| !caret.is_some_and(|c| c >= *a && c <= *b))
|
||||
.filter(|(a, b)| {
|
||||
self.ignored.is_empty() || !self.is_ignored(&chars.get(*a..*b).map(|c| c.iter().collect::<String>()).unwrap_or_default())
|
||||
})
|
||||
.collect()
|
||||
Some(
|
||||
ranges
|
||||
.iter()
|
||||
.filter_map(|&(tag, a, b)| match tag {
|
||||
Tag::Notes { start } => Some((start + a, start + b)),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|(a, b)| !caret.is_some_and(|c| c >= *a && c <= *b))
|
||||
.filter(|(a, b)| {
|
||||
self.ignored.is_empty() || !self.is_ignored(&chars.get(*a..*b).map(|c| c.iter().collect::<String>()).unwrap_or_default())
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Skip `word` everywhere for the rest of the session.
|
||||
@@ -449,8 +333,8 @@ impl Squiggles {
|
||||
/// Wait (tests) until the slide's check for `st` is in.
|
||||
pub fn settle(&mut self, st: &DocState) -> Vec<(Point, Point)> {
|
||||
for _ in 0..2000 {
|
||||
let v = self.update(st, None);
|
||||
if self.pending[0].is_none() && self.done[0].is_some() {
|
||||
let v = self.update(st);
|
||||
if self.disabled || self.lines_for.is_some() {
|
||||
return v;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
@@ -461,8 +345,7 @@ impl Squiggles {
|
||||
/// Wait (tests) until the notes check for `text` is in.
|
||||
pub fn settle_notes(&mut self, text: &str, lang: &str) -> Vec<(usize, usize)> {
|
||||
for _ in 0..2000 {
|
||||
let v = self.notes(text, lang, None, None);
|
||||
if self.pending[1].is_none() && self.done[1].is_some() {
|
||||
if let Some(v) = self.checked_notes(text, lang, None) {
|
||||
return v;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
@@ -487,39 +370,33 @@ fn word_of(st: &DocState, tag: Tag, a: usize, b: usize) -> Option<String> {
|
||||
Some(paragraph_of(st, tag)?.text().chars().skip(a).take(b - a).collect())
|
||||
}
|
||||
|
||||
/// A red wavy line from `a` to `b` (screen points).
|
||||
pub fn paint(painter: &egui::Painter, a: egui::Pos2, b: egui::Pos2, scale: f32) {
|
||||
let d = b - a;
|
||||
let len = d.length();
|
||||
if len < 1.0 {
|
||||
/// Shows spelling marks over the slide picture through the canvas environment's flag style.
|
||||
pub(crate) fn show_marks(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) {
|
||||
if app.anim_preview_active() {
|
||||
return;
|
||||
}
|
||||
let (u, n) = (d / len, egui::vec2(-d.y, d.x) / len);
|
||||
let step = (2.0 * scale).clamp(1.5, 3.0);
|
||||
let amp = step * 0.75;
|
||||
let mut pts = vec![];
|
||||
let mut t = 0.0;
|
||||
let mut up = false;
|
||||
while t <= len {
|
||||
pts.push(a + u * t + n * if up { -amp } else { amp });
|
||||
up = !up;
|
||||
t += step;
|
||||
}
|
||||
painter.add(egui::Shape::line(pts, egui::Stroke::new(1.0, egui::Color32::from_rgb(0xE0, 0x20, 0x20))));
|
||||
}
|
||||
|
||||
/// Paints or hosts this canvas part over the slide picture.
|
||||
#[allow(dead_code)] // P3(canvas-w12): cv.A3
|
||||
pub(crate) fn show_marks(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) {
|
||||
let _ = (app, ui, space);
|
||||
todo!("cv.A3")
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let lines = app.squiggles.update(st);
|
||||
let _ = SpellingMarks::new(&lines).show_at(ui, space.view.rect);
|
||||
}
|
||||
|
||||
impl Squiggles {
|
||||
/// Creates spelling work over the host job queue.
|
||||
#[allow(dead_code)] // P3(canvas-w12): cv.A10
|
||||
pub(crate) fn new(jobs: Arc<dyn craft::host::Jobs>, wake: craft::host::Wake) -> Squiggles {
|
||||
let _ = (jobs, wake);
|
||||
todo!("cv.A10")
|
||||
/// Retains host services and builds the queue lazily so callers can choose inline checking.
|
||||
pub(crate) fn new(jobs: Arc<dyn Jobs>, wake: Wake) -> Squiggles {
|
||||
Self {
|
||||
jobs,
|
||||
wake,
|
||||
options: QueueOptions { lanes: QueueOptions::default_lanes().min(1), name: "deckcraft-spelling", ..QueueOptions::default() },
|
||||
queue: None,
|
||||
cache: HashMap::new(),
|
||||
user: None,
|
||||
force_inline: false,
|
||||
lines: vec![],
|
||||
lines_for: None,
|
||||
disabled: false,
|
||||
menu_word: None,
|
||||
notes_menu: None,
|
||||
ignored: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user