diff --git a/crates/ui-egui/src/dialogs/custom_shows.rs b/crates/ui-egui/src/dialogs/custom_shows.rs index fc0c57381..edd8679ca 100644 --- a/crates/ui-egui/src/dialogs/custom_shows.rs +++ b/crates/ui-egui/src/dialogs/custom_shows.rs @@ -1,18 +1,69 @@ -/// Opens this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w15): dl.A10 -pub(crate) fn open( - app: &mut crate::SlideApp, - ctx: &egui::Context, - host: &mut craft::ui::dialog::DialogHost, - params: &serde_json::Value, -) -> Result, String> { - let _ = (app, ctx, host, params); - todo!("dl.A10") +//! Custom show commands over the host's named-list dialog. + +use craft::ui::dialog::{DialogHost, DialogId, DialogResult, dialog_id}; +use craft::ui::patterns::form_dialogs::{ActionEnabled, HostedListManager, ListManagerAction, ListManagerEntry}; +use craft::ui::runtime::env::{Word, WordTemplate}; +use egui::Context; +use serde_json::{Value, json}; + +use crate::SlideApp; + +/// Opens the presentation's custom shows with their slide counts and creation fields. +pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result, String> { + let actions = vec![ + ListManagerAction::new("run", Word::plain("Show"), ActionEnabled::on_entry()), + ListManagerAction::new("delete", Word::plain("Delete"), ActionEnabled::on_entry()).keeps_open(), + ListManagerAction::new("create", Word::plain("Create"), ActionEnabled::OnNewName), + ]; + let dialog = HostedListManager::new("customShow", Word::plain("Custom Shows"), Word::plain("New show name:"), actions) + .entries(entries(app)) + .name(app.host.words().get(Word::plain("Custom Show 1")).into_owned()) + .field(Word::plain("Slides (e.g. 1,3,5):"), "1"); + Ok(Some(host.open(dialog))) } -/// Advances this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w15): dl.A10 -pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) { - let _ = (app, ctx, host); - todo!("dl.A10") +/// Applies custom show choices. +pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) { + let id = dialog_id("customShow"); + if let Some(choice) = host.get_mut_by_id::(id).and_then(HostedListManager::take_choice) + && choice.action == "delete" + { + let _ = app.run("show.customShow", json!({"name": choice.name, "delete": true})); + if let Some(dialog) = host.get_mut_by_id::(id) { + dialog.set_entries(entries(app)); + } + } + if let Some(DialogResult::Ok(choice)) = host.take_by_id::(id) { + match choice.action.as_str() { + "run" => { + let _ = app.run("show.start", json!({"custom": choice.name})); + } + "create" => { + let slides: Vec = choice + .field + .as_deref() + .unwrap_or_default() + .split(',') + .filter_map(|s| s.trim().parse::().ok()?.checked_sub(1)) + .collect(); + let _ = app.run("show.customShow", json!({"name": choice.name, "slides": slides})); + } + _ => {} + } + } +} + +fn entries(app: &SlideApp) -> Vec { + let words = app.host.words(); + let count = WordTemplate::new(words.get(Word::plain("({n} slides)"))); + app.session + .active() + .map(|st| { + st.doc + .custom_shows + .iter() + .map(|show| ListManagerEntry::new(&show.name, &show.name).detail(count.fill(&[("n", &show.slides.len().to_string())]))) + .collect() + }) + .unwrap_or_default() } diff --git a/crates/ui-egui/src/dialogs/spelling.rs b/crates/ui-egui/src/dialogs/spelling.rs index bf2ae97d8..89cdf9959 100644 --- a/crates/ui-egui/src/dialogs/spelling.rs +++ b/crates/ui-egui/src/dialogs/spelling.rs @@ -1,25 +1,186 @@ -/// Opens this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w15): dl.A10 -pub(crate) fn open( - app: &mut crate::SlideApp, - ctx: &egui::Context, - host: &mut craft::ui::dialog::DialogHost, - params: &serde_json::Value, -) -> Result, String> { - let _ = (app, ctx, host, params); - todo!("dl.A10") +//! Document spelling review and exact-location edits through engine commands. + +use craft::text::ui::spelling::{CheckSpellingDialog, SpellingAction, SpellingItem, SpellingScope}; +use craft::ui::dialog::{DialogHost, DialogId}; +use craft::ui::runtime::env::{Label, Word, WordTemplate, Words}; +use egui::Context; +use serde_json::{Value, json}; + +use crate::SlideApp; + +/// Opens a modeless spelling walk and reveals its first occurrence. +pub(crate) fn open(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result, String> { + let (items, locations) = items(app, &[]); + let info = app.run("review.dictionary", json!({}))?; + let dialog = CheckSpellingDialog::new(items).scope(SpellingScope::Document).note(dictionary_line(&info, &app.host.words())).modeless(); + app.dialogs.spelling = Some(SpellingRun { locations }); + reveal(app, dialog.current()); + Ok(Some(host.open(dialog))) } -/// Advances this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w15): dl.A10 -pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) { - let _ = (app, ctx, host); - todo!("dl.A10") +/// Applies spelling actions and settles completed checks, reporting whether an action was consumed. +pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) -> bool { + if host.take::().is_some() { + app.dialogs.spelling = None; + } + let Some(dialog) = host.get_mut::() else { return false }; + let Some(action) = dialog.take_action() else { return false }; + apply_action(app, action); + true } -/// The locations in the spelling review. -#[allow(dead_code)] // P3(dialogs-w15): dl.A12 +/// Refreshes the modeless check and reveals the current item after an action consumed in this pass. +pub(crate) fn refresh(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost, acted: bool) { + let Some(dialog) = host.get_mut::() else { return }; + let ignored = dialog.ignored().to_vec(); + let (items, locations) = items(app, &ignored); + app.dialogs.spelling = Some(SpellingRun { locations }); + if dialog.items() != items.as_slice() { + dialog.set_items(items); + } + if acted { + reveal(app, dialog.current()); + } +} + +/// Engine locations parallel to the dialog's items, indexed by `SpellingItem::object`. #[derive(Default)] pub(crate) struct SpellingRun { - pub(crate) locations: Vec, + /// The engine's paragraph, character offset, slide and optional shape/cell for each item. + pub(crate) locations: Vec, +} + +fn items(app: &mut SlideApp, ignored: &[String]) -> (Vec, Vec) { + let locations = app.run("review.spelling", json!({"ignore": ignored})).unwrap_or_default().as_array().cloned().unwrap_or_default(); + let items = locations + .iter() + .enumerate() + .map(|(at, location)| { + // Keep the engine order: object remains the location index even after Ignore skips it. + let suggestions = location["suggestions"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect()) + .unwrap_or_default(); + let item = SpellingItem::new( + at as u64, + index(location, "start")..index(location, "end"), + location["word"].as_str().unwrap_or_default(), + suggestions, + ); + if location["repeated"].as_bool().unwrap_or(false) && !location["notes"].as_bool().unwrap_or(false) { + item.repeated(index(location, "deleteFrom")..index(location, "end")) + } else { + item + } + }) + .collect(); + (items, locations) +} + +fn apply_action(app: &mut SlideApp, action: SpellingAction) { + match action { + SpellingAction::Change { item, to, .. } => { + if let Some(location) = location(app, &item) { + if location["notes"].as_bool().unwrap_or(false) { + change_in_notes(app, &location, &to); + } else { + change_at(app, &location, &item.word, &to, item.range.start); + } + } + } + SpellingAction::ChangeAll { item, to, .. } => { + let _ = app.run("review.spellingChange", json!({"word": item.word, "to": to, "all": true})); + } + SpellingAction::Delete { item, .. } => { + if let Some(location) = location(app, &item) + && let Some(range) = item.delete + && let Some(paragraph) = paragraph(app, &location) + { + let gap: String = paragraph.chars().skip(range.start).take(range.end.saturating_sub(range.start)).collect(); + change_at(app, &location, &gap, "", range.start); + } + } + SpellingAction::Add(word) => { + let _ = app.run("review.addToDictionary", json!({"word": word})); + } + SpellingAction::Ignore(_) | SpellingAction::Relist => {} + _ => {} + } +} + +fn location(app: &SlideApp, item: &SpellingItem) -> Option { + app.dialogs.spelling.as_ref()?.locations.get(usize::try_from(item.object).ok()?).cloned() +} + +fn index(location: &Value, key: &str) -> usize { + location[key].as_u64().and_then(|v| usize::try_from(v).ok()).unwrap_or_default() +} + +fn paragraph(app: &SlideApp, location: &Value) -> Option { + let st = app.session.active()?; + let slide = st.doc.slides.get(index(location, "slide"))?; + let shape = deckcraft_model::find_shape(&slide.shapes, deckcraft_model::ShapeId(u32::try_from(location["shape"].as_u64()?).ok()?))?; + let body = match (location.get("row"), location.get("col"), &shape.kind) { + (Some(_), Some(_), deckcraft_model::ShapeKind::Table(table)) => &table.cell(index(location, "row"), index(location, "col"))?.text, + _ => shape.text.as_ref()?, + }; + Some(body.paragraphs.get(index(location, "para"))?.text()) +} + +fn change_at(app: &mut SlideApp, location: &Value, word: &str, to: &str, start: usize) { + let mut params = json!({"shape": location["shape"], "para": location["para"], "start": start, "word": word, "to": to}); + if let (Some(row), Some(col)) = (location.get("row"), location.get("col")) { + params["row"] = row.clone(); + params["col"] = col.clone(); + } + let _ = app.run("review.spellingChange", params); +} + +fn change_in_notes(app: &mut SlideApp, location: &Value, to: &str) { + let slide = index(location, "slide"); + let notes = app.session.active().and_then(|st| st.doc.slides.get(slide)).map(|s| s.notes_text()).unwrap_or_default(); + let word = location["word"].as_str().unwrap_or_default(); + let start = index(location, "start"); + let end = start.saturating_add(word.chars().count()); + let lines: Vec = notes + .split('\n') + .enumerate() + .map(|(at, line)| { + let mut chars: Vec = line.chars().collect(); + if at == index(location, "para") && chars.get(start..end).is_some_and(|c| c.iter().collect::() == word) { + chars.splice(start..end, to.chars()); + chars.into_iter().collect() + } else { + line.to_owned() + } + }) + .collect(); + let _ = app.run("slide.notes", json!({"text": lines.join("\n"), "index": slide})); +} + +fn reveal(app: &mut SlideApp, item: Option<&SpellingItem>) { + if let Some(location) = item.and_then(|item| location(app, item)) { + let _ = app.run("slide.go", json!({"index": location["slide"]})); + if let Some(shape) = location.get("shape") { + let _ = app.run("edit.select", json!({"ids": [shape]})); + } + } +} + +fn dictionary_line(info: &Value, words: &Words) -> Label { + if info["available"].as_bool().unwrap_or(false) { + let dictionary = info["found"] + .as_str() + .map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f)) + .unwrap_or_else(|| info["lang"].as_str().unwrap_or_default()); + WordTemplate::new(words.get(Word::plain("Dictionary: {dictionary}"))).fill(&[("dictionary", dictionary)]).into() + } else { + let fallback = words.get(Word::plain("a dictionaries folder")); + let folder = info["folders"].as_array().and_then(|a| a.get(1).or(a.first())).and_then(Value::as_str).unwrap_or(&fallback); + WordTemplate::new(words.get(Word::plain( + "No {lang} dictionary is installed, so only common misspellings are found. Put a Hunspell .aff/.dic pair in {folder}.", + ))) + .fill(&[("lang", info["lang"].as_str().unwrap_or("en-US")), ("folder", folder)]) + .into() + } } diff --git a/crates/ui-egui/src/dialogs/spelling_tests.rs b/crates/ui-egui/src/dialogs/spelling_tests.rs index 60ad4b97f..46e0d30b1 100644 --- a/crates/ui-egui/src/dialogs/spelling_tests.rs +++ b/crates/ui-egui/src/dialogs/spelling_tests.rs @@ -6,6 +6,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; +use crate::test_harness::harness_with; use crate::{Services, SlideApp}; #[test] @@ -14,37 +15,50 @@ fn spelling_dialog_changes_and_ignores_words() { let aff = "SET UTF-8\nTRY esianrtolcdugmphbyfvkwzxjq\nSFX S Y 1\nSFX S 0 s .\n"; let dic = "6\nthe/S\nslide/S\nquarter/S\nplan/S\nour\nfor\n"; deckcraft_engine::spell::install("en-US", deckcraft_engine::spell::Dictionary::parse(aff.as_bytes(), dic.as_bytes())); - // P3(dialogs-w15): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - app.session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 500, 120], "text": "Our plna for teh quarter"})).unwrap(); - app.dialog = Some(crate::dialogs::Dialog::new("spelling")); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 700.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); + let mut session = Session::with_new(); + session.execute("slide.layout", &json!({"layout": "blank"})).unwrap(); + let original = "our plan\n— Our plna for teh quarter"; + let id = session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 500, 120], "text": original})).unwrap()["id"] + .as_u64() + .unwrap(); + let mut h = harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1100.0, 700.0)), |_| {}); + h.state_mut().open_dialog("spelling", json!({})); h.run_steps(3); - if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT"), h.render()) { - let _ = img.save(path); - } - h.get_by_label("plan").click(); + let words = h.state().host.words().set::(); + let count = |h: &Harness<'_, SlideApp>| super::inspect(&h.ctx)[0]["fields"]["count"].as_u64().unwrap(); + let before = count(&h); + let ctx = h.ctx.clone(); + super::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "changeTo", "value": "plan"})) + .unwrap() + .unwrap(); + // A Change must apply once in a two-pass frame. + h.ctx.on_end_pass( + "spelling input pass", + std::sync::Arc::new(|ui| { + if ui.input(|input| !input.events.is_empty()) { + ui.ctx().request_discard("spelling action within a two-pass frame"); + } + }), + ); + h.get_by_label(words.change.as_str()).click(); h.run_steps(3); let text = |h: &Harness<'_, SlideApp>| { - let st = h.state().session.active().unwrap(); - let mut out = String::new(); - deckcraft_model::walk(&st.doc.slides[0].shapes, &mut |s, _| { - if let Some(t) = &s.text { - out += &t.text(); - } - }); - out + h.state().session.active().unwrap().shape(deckcraft_model::ShapeId(id as u32)).unwrap().text.as_ref().unwrap().text() }; - assert!(text(&h).contains("Our plan for teh"), "{}", text(&h)); - h.get_by_label("Ignore All").click(); + assert_eq!(text(&h), original.replacen("plna", "plan", 1)); + assert_eq!(count(&h), before - 1); + assert!(h.state().status.is_none(), "replaying an exact-location correction must not report that its word is gone"); + h.get_by_label(words.ignore_all.as_str()).click(); h.run_steps(3); - assert!(h.query_by_label_contains("No issues found").is_some()); + let empty = count(&h); + assert!(empty < before); + assert!(!super::modal_open(&h.ctx)); + h.state_mut().session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 300, 500, 120], "text": "plna"})).unwrap(); + h.run_steps(3); + assert_eq!(count(&h), empty + 1, "modeless edits refresh the check while Ignore All remains in force"); + super::control(h.state_mut(), &ctx, "ui.dialog.confirm", &json!({"dialog": "top"})).unwrap().unwrap(); + h.run_steps(3); + assert!(super::open_keys(&h.ctx).is_empty()); } /// Misspelt words on the slide get squiggles from the background check; not the word being @@ -58,19 +72,19 @@ fn squiggles_mark_misspelt_words_in_the_background() { let dir = std::env::temp_dir().join(format!("deckcraft-ui-userdic-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); deckcraft_engine::spell::set_user_dictionary_path(dir.join("user.dic")); - // P3(dialogs-w15): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - app.session.execute("slide.layout", &json!({"layout": "blank"})).ok(); - let id = app - .session - .execute("shape.insert", &json!({"preset": "rect", "rect": [80, 120, 700, 160], "text": "Our plna for teh quarter reveiw"})) + let mut session = Session::with_new(); + session.execute("slide.layout", &json!({"layout": "blank"})).ok(); + let original = "Our plna for teh quarter reveiw"; + let correction = "plan"; + let id = session + .execute("shape.insert", &json!({"preset": "rect", "rect": [80, 120, 700, 160], "text": original})) .unwrap()["id"] .as_u64() .unwrap(); - app.session.execute("format.size", &json!({"size": 40})).unwrap(); + session.execute("format.size", &json!({"size": 40})).unwrap(); // Mark the runs' language directly (what a PPTX run's `lang` gives). let sid = deckcraft_model::ShapeId(id as u32); - app.session + session .edit(|doc, _| { let sl = std::sync::Arc::make_mut(&mut doc.slides[0]); let sh = deckcraft_model::find_shape_mut(&mut sl.shapes, sid).unwrap(); @@ -80,37 +94,36 @@ fn squiggles_mark_misspelt_words_in_the_background() { Ok(()) }) .unwrap(); - app.session.execute("edit.select", &json!({"ids": []})).unwrap(); - let st = app.session.active().unwrap().clone(); - let lines = app.squiggles.settle(&st); - assert_eq!(lines.len(), 3, "{lines:?}"); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 700.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); + session.execute("edit.select", &json!({"ids": []})).unwrap(); + let mut h = harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1100.0, 700.0)), |_| {}); h.run_steps(4); if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_SQUIGGLES"), h.render()) { let _ = img.save(path); } // The context menu's word under the first squiggle, and its correction. let st = h.state().session.active().unwrap().clone(); + let lines = h.state_mut().squiggles.settle(&st); + assert_eq!(lines.len(), 3, "{lines:?}"); let (a, _) = lines[0]; let w = h.state().squiggles.word_at(&st, deckcraft_geom::Point::new(a.x + 5.0, a.y - 5.0), 2.0).unwrap(); - assert_eq!(w.word, "plna"); - assert_eq!(w.suggestions.first().map(String::as_str), Some("plan")); - h.state_mut().session.execute("review.spellingChange", &json!({"shape": id, "para": 0, "start": w.start, "word": w.word, "to": "plan"})).unwrap(); + assert_eq!(w.word, original.split_whitespace().nth(1).unwrap()); + assert_eq!(w.suggestions.first().map(String::as_str), Some(correction)); + h.state_mut() + .session + .execute("review.spellingChange", &json!({"shape": id, "para": 0, "start": w.start, "word": w.word, "to": correction})) + .unwrap(); h.state_mut().session.execute("review.addToDictionary", &json!({"word": "reveiw"})).unwrap(); + h.run_steps(1); let st = h.state().session.active().unwrap().clone(); assert_eq!(h.state_mut().squiggles.settle(&st).len(), 1); // Typing at the end of a misspelt word: no squiggle under it until the caret leaves. h.state_mut().session.execute("edit.select", &json!({"ids": [id]})).unwrap(); h.state_mut().session.execute("text.edit", &json!({})).unwrap(); - h.state_mut().session.execute("text.select", &json!({"anchor": [0, 16], "caret": [0, 16]})).unwrap(); + let caret = original.replacen("plna", correction, 1).find("teh").unwrap() + "teh".chars().count(); + h.state_mut().session.execute("text.select", &json!({"anchor": [0, caret], "caret": [0, caret]})).unwrap(); + h.run_steps(1); let st = h.state().session.active().unwrap().clone(); - assert_eq!(st.selection.text.as_ref().map(|t| t.caret), Some((0, 16))); + assert_eq!(st.selection.text.as_ref().map(|t| t.caret), Some((0, caret))); assert_eq!(h.state_mut().squiggles.settle(&st).len(), 0, "the word being typed isn't marked"); let _ = std::fs::remove_dir_all(&dir); } @@ -123,47 +136,49 @@ fn squiggles_in_table_cells_and_notes_and_on_the_ui_thread() { let aff = "SET UTF-8\nTRY esianrtolcdugmphbyfvkwzxjq\nSFX S Y 1\nSFX S 0 s .\n"; let dic = "10\nthe/S\nplan/S\nsales\nregion/S\ntotal/S\nnorth\nsouth\nremember\nto\nshow\n"; deckcraft_engine::spell::install("xx-TB", deckcraft_engine::spell::Dictionary::parse(aff.as_bytes(), dic.as_bytes())); - // P3(dialogs-w15): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - app.squiggles.force_inline = true; - app.session.execute("slide.layout", &json!({"layout": "blank"})).ok(); - let id = app.session.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [80, 80, 600, 160]})).unwrap()["id"].as_u64().unwrap(); + let mut session = Session::with_new(); + session.execute("slide.layout", &json!({"layout": "blank"})).ok(); + let id = session.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [80, 80, 600, 160]})).unwrap()["id"].as_u64().unwrap(); let sid = deckcraft_model::ShapeId(id as u32); + let cell_word = "Regoin"; + let correction = "Region"; + let note_source = "Remmeber to show the totl"; let lang = deckcraft_model::RunProps { lang: Some("xx-TB".into()), size: Some(28.0), ..Default::default() }; - app.session + session .edit(|doc, _| { let sl = std::sync::Arc::make_mut(&mut doc.slides[0]); sl.notes = deckcraft_model::TextBody { paragraphs: vec![deckcraft_model::Paragraph { - runs: vec![deckcraft_model::Run::with("Remmeber to show the totl", lang.clone())], + runs: vec![deckcraft_model::Run::with(note_source, lang.clone())], ..Default::default() }], ..Default::default() }; let sh = deckcraft_model::find_shape_mut(&mut sl.shapes, sid).unwrap(); let deckcraft_model::ShapeKind::Table(tb) = &mut sh.kind else { panic!("not a table") }; - for (r, c, t) in [(0, 0, "Regoin"), (0, 1, "Sales"), (1, 0, "North"), (1, 1, "Soth totals")] { + for (r, c, t) in [(0, 0, cell_word), (0, 1, "Sales"), (1, 0, "North"), (1, 1, "Soth totals")] { tb.cell_mut(r, c).unwrap().text.paragraphs = vec![deckcraft_model::Paragraph { runs: vec![deckcraft_model::Run::with(t, lang.clone())], ..Default::default() }]; } Ok(()) }) .unwrap(); - app.session.execute("edit.select", &json!({"ids": []})).unwrap(); - let st = app.session.active().unwrap().clone(); - let lines = app.squiggles.settle(&st); + session.execute("edit.select", &json!({"ids": []})).unwrap(); + let mut h = harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1100.0, 760.0)), |_| {}); + h.state_mut().squiggles.force_inline = true; + h.run_steps(6); + let st = h.state().session.active().unwrap().clone(); + let lines = h.state_mut().squiggles.settle(&st); assert_eq!(lines.len(), 2, "Regoin and Soth: {lines:?}"); // Each under its own cell: the first in the top-left one, the second in the bottom-right one. assert!(lines[0].0.x < 380.0 && lines[0].0.y < 160.0 && lines[1].0.x > 380.0 && lines[1].0.y > 160.0, "{lines:?}"); - assert_eq!(app.squiggles.settle_notes("Remmeber to show the totl", "xx-TB"), vec![(0, 8), (21, 25)]); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(6); + let flags = h.state_mut().squiggles.settle_notes(note_source, "xx-TB"); + let end = note_source.chars().count(); + let first_end = note_source.split_whitespace().next().unwrap().chars().count(); + let last_start = end - note_source.split_whitespace().last().unwrap().chars().count(); + assert_eq!(flags, vec![(0, first_end), (last_start, end)]); + let flagged: Vec = flags.iter().map(|&(start, end)| note_source.chars().skip(start).take(end - start).collect()).collect(); + assert_eq!(flagged, vec![note_source.split_whitespace().next().unwrap(), note_source.split_whitespace().last().unwrap()]); if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_TABLE"), h.render()) { let _ = img.save(path); } @@ -173,17 +188,20 @@ fn squiggles_in_table_cells_and_notes_and_on_the_ui_thread() { let lines = h.state_mut().squiggles.settle(&st); let (a, _) = lines[0]; let w = h.state().squiggles.word_at(&st, deckcraft_geom::Point::new(a.x + 3.0, a.y - 5.0), 2.0).unwrap(); - assert_eq!((w.word.as_str(), w.suggestions.first().map(String::as_str)), ("Regoin", Some("Region"))); + assert_eq!((w.word.as_str(), w.suggestions.first().map(String::as_str)), (cell_word, Some(correction))); h.state_mut() .session - .execute("review.spellingChange", &json!({"shape": id, "row": 0, "col": 0, "para": 0, "start": w.start, "word": w.word, "to": "Region"})) + .execute("review.spellingChange", &json!({"shape": id, "row": 0, "col": 0, "para": 0, "start": w.start, "word": w.word, "to": correction})) .unwrap(); + h.run_steps(1); let st = h.state().session.active().unwrap().clone(); assert_eq!(h.state_mut().squiggles.settle(&st).len(), 1); // The Spelling dialog's list has the cell and the notes too. let v = h.state_mut().session.execute("review.spelling", &json!({})).unwrap(); let words: Vec<&str> = v.as_array().unwrap().iter().filter_map(|w| w["word"].as_str()).collect(); - assert_eq!(words, vec!["Soth", "Remmeber", "totl"]); + let mut expected = vec!["Soth"]; + expected.extend(flagged.iter().map(String::as_str)); + assert_eq!(words, expected); } fn right_click(h: &mut Harness<'_, SlideApp>, pos: egui::Pos2) { @@ -203,23 +221,22 @@ fn notes_menu_language_dialog_and_repeated_words() { let aff = "SET UTF-8\nTRY esianrtolcdugmphbyfvkwzxjq\n"; let dic = "6\nthe\nplan\nremember\nis\ngood\nwork\n"; deckcraft_engine::spell::install("xx-NM", deckcraft_engine::spell::Dictionary::parse(aff.as_bytes(), dic.as_bytes())); - // P3(dialogs-w15): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - app.session.execute("slide.layout", &json!({"layout": "blank"})).ok(); - let id = app - .session + let mut session = Session::with_new(); + session.execute("slide.layout", &json!({"layout": "blank"})).ok(); + let id = session .execute("shape.insert", &json!({"preset": "rect", "rect": [80, 120, 700, 160], "text": "the plan is is good wrok"})) .unwrap()["id"] .as_u64() .unwrap(); - app.session.execute("format.size", &json!({"size": 40})).unwrap(); - app.session.execute("format.language", &json!({"lang": "xx-NM"})).unwrap(); + session.execute("format.size", &json!({"size": 40})).unwrap(); + session.execute("format.language", &json!({"lang": "xx-NM"})).unwrap(); + let note_source = "Remmeber the the plan"; let lang = deckcraft_model::RunProps { lang: Some("xx-NM".into()), ..Default::default() }; - app.session + session .edit(|doc, _| { std::sync::Arc::make_mut(&mut doc.slides[0]).notes = deckcraft_model::TextBody { paragraphs: vec![deckcraft_model::Paragraph { - runs: vec![deckcraft_model::Run::with("Remmeber the the plan", lang.clone())], + runs: vec![deckcraft_model::Run::with(note_source, lang.clone())], ..Default::default() }], ..Default::default() @@ -227,35 +244,38 @@ fn notes_menu_language_dialog_and_repeated_words() { Ok(()) }) .unwrap(); - let st = app.session.active().unwrap().clone(); - // "is is" is flagged as repeated, "wrok" as misspelt. - assert_eq!(app.squiggles.settle(&st).len(), 2); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 760.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); + let mut h = harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1100.0, 760.0)), |_| {}); + h.state_mut().ui.notes = true; h.run_steps(8); + let st = h.state().session.active().unwrap().clone(); + // "is is" is flagged as repeated, "wrok" as misspelt. + assert_eq!(h.state_mut().squiggles.settle(&st).len(), 2); if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_NOTES"), h.render()) { let _ = img.save(path); } // Right-click the notes' first word, once the (background) notes check is in. - assert_eq!(h.state_mut().squiggles.settle_notes("Remmeber the the plan", "xx-NM"), vec![(0, 8), (13, 16)]); + let flags = h.state_mut().squiggles.settle_notes(note_source, "xx-NM"); + let first_end = note_source.split_whitespace().next().unwrap().chars().count(); + let repeat_start = note_source.split_whitespace().take(2).collect::>().join(" ").chars().count() + 1; + let repeat_end = repeat_start + note_source.split_whitespace().nth(2).unwrap().chars().count(); + assert_eq!(flags, vec![(0, first_end), (repeat_start, repeat_end)]); + let flagged: Vec = flags.iter().map(|&(start, end)| note_source.chars().skip(start).take(end - start).collect()).collect(); + assert_eq!(flagged, vec![note_source.split_whitespace().next().unwrap(), note_source.split_whitespace().nth(2).unwrap()]); h.run_steps(2); let notes = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).unwrap(); right_click(&mut h, egui::pos2(notes.left() + 14.0, notes.top() + 8.0)); if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_NOTES_MENU"), h.render()) { let _ = img.save(path); } - assert_eq!(h.state().squiggles.notes_menu.as_ref().map(|w| w.word.as_str()), Some("Remmeber")); - h.get_by_label("Remember").click(); + let menu_word = h.state().squiggles.notes_menu.as_ref().unwrap(); + assert_eq!(menu_word.word, note_source.split_whitespace().next().unwrap()); + let correction = menu_word.suggestions.first().unwrap().clone(); + h.get_by_label(&correction).click(); h.run_steps(3); let notes_text = |h: &Harness<'_, SlideApp>| h.state().session.active().unwrap().doc.slides[0].notes_text(); - assert_eq!(notes_text(&h), "Remember the the plan"); - // The repeated "the": its squiggle starts after "Remember the ". - h.state_mut().squiggles.settle_notes("Remember the the plan", "xx-NM"); + let corrected = note_source.replacen(note_source.split_whitespace().next().unwrap(), &correction, 1); + assert_eq!(notes_text(&h), corrected); + h.state_mut().squiggles.settle_notes(&corrected, "xx-NM"); h.run_steps(4); let x = h.query_all_by_role(Role::MultilineTextInput).next().map(|n| n.rect()).unwrap(); let mut found = false; @@ -265,24 +285,30 @@ fn notes_menu_language_dialog_and_repeated_words() { found = true; break; } - h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.key_press(egui::Key::Escape); h.run_steps(2); } assert!(found, "no repeated word menu in the notes"); - h.get_by_label("Delete Repeated Word").click(); + let words = h.state().host.words(); + let delete = words.get(craft::ui::runtime::env::Word::plain("Delete Repeated Word")); + h.get_by_label(delete.as_ref()).click(); h.run_steps(3); - assert_eq!(notes_text(&h), "Remember the plan"); + let mut expected: Vec<&str> = corrected.split_whitespace().collect(); + expected.dedup(); + assert_eq!(notes_text(&h), expected.join(" ")); // Language dialog: Do Not Check Spelling on the shape clears its squiggles. h.state_mut().session.execute("edit.select", &json!({"ids": [id]})).unwrap(); - h.state_mut().dialog = Some(crate::dialogs::Dialog::new("language")); + h.state_mut().open_dialog("language", json!({})); h.run_steps(4); if let (Ok(path), Ok(img)) = (std::env::var("DECKCRAFT_PNG_OUT_LANG"), h.render()) { let _ = img.save(path); } assert_eq!(crate::dialogs::selected_language(h.state()).0, "xx-NM"); - h.get_by_label("Do not check spelling or grammar").click(); + let no_proof = words.get(craft::ui::runtime::env::Word::plain("Do not check spelling or grammar")); + h.get_by_label(no_proof.as_ref()).click(); h.run_steps(2); - h.get_by_label("OK").click(); + let common = words.set::(); + h.get_by_label(common.ok.as_str()).click(); h.run_steps(3); assert_eq!(crate::dialogs::selected_language(h.state()), ("xx-NM".to_string(), true)); let st = h.state().session.active().unwrap().clone();