diff --git a/crates/engine/src/cmd/slide.rs b/crates/engine/src/cmd/slide.rs index 5f3fbc8f6..1bc3911fd 100644 --- a/crates/engine/src/cmd/slide.rs +++ b/crates/engine/src/cmd/slide.rs @@ -47,7 +47,7 @@ pub fn specs() -> Vec { "Notes", ["View"], None, - "{text | body: formatted notes (as in slide.inspect's notesBody), index?} (text as typed: untouched notes keep their formatting)", + "{text | body: formatted notes (as in slide.inspect's notesBody), index?, coalesce?: bool (default false)} (text keeps untouched formatting; coalesce joins consecutive editor changes on one slide)", has_slide, notes ), @@ -593,6 +593,7 @@ fn reset(s: &mut Session, p: &Value) -> Result { fn notes(s: &mut Session, p: &Value) -> Result { let i = index_of(s, p)?; + let coalesce = bool_or(p, "coalesce", false); // Formatted notes as a whole (the notes editors), or text: then only what was retyped // changes, so bold, levels and bullets around it survive. let body = match p.get("body") { @@ -600,14 +601,26 @@ fn notes(s: &mut Session, p: &Value) -> Result { None => None, }; let text = str_param(p, "text").unwrap_or("").to_string(); + let st = s.doc_mut()?; + let slide = st.doc.slides.get(i).ok_or_else(|| bad("slide.notes", "no such slide"))?; + let id = slide.id; + let mut replacement = body.unwrap_or_else(|| { + let mut notes = slide.notes.clone(); + deckcraft_model::edit::replace_text(&mut notes, &text); + notes + }); + if !coalesce || st.notes_run != Some(id) { + st.notes_before = None; + } + st.notes_run = coalesce.then_some(id); + if coalesce && slide.notes == replacement { + return ok(); + } s.edit(|doc, _| { if let Some(sl) = doc.slides.get_mut(i) { let sl = Arc::make_mut(sl); let notes = &mut sl.notes; - match body { - Some(b) => *notes = b, - None => deckcraft_model::edit::replace_text(notes, &text), - } + std::mem::swap(notes, &mut replacement); if !notes.is_empty() { sl.has_notes_slide = true; } @@ -747,6 +760,63 @@ mod tests { use crate::Session; + #[test] + fn consecutive_notes_edits_are_one_undo_step() { + let (mut s, _) = deck(2); + let read = |s: &Session, i: usize| s.doc().expect("doc").doc.slides[i].notes.text(); + let write = |s: &mut Session, i, text| { + s.execute("slide.notes", &json!({"index": i, "text": text, "coalesce": true})).expect("edit notes"); + }; + let initial = read(&s, 0); + for text in ["one", "one two", "one two three"] { + write(&mut s, 0, text); + } + let first_run = read(&s, 0); + s.execute("edit.undo", &json!({})).expect("undo run"); + assert_eq!(read(&s, 0), initial); + s.execute("edit.redo", &json!({})).expect("redo run"); + assert_eq!(read(&s, 0), first_run); + + write(&mut s, 0, "after redo"); + let before_command = read(&s, 0); + s.execute("slide.rename", &json!({"index": 0, "name": "named"})).expect("intervening edit"); + write(&mut s, 0, "after command"); + s.execute("edit.undo", &json!({})).expect("undo later notes"); + assert_eq!(read(&s, 0), before_command); + s.execute("edit.undo", &json!({})).expect("undo rename"); + assert_eq!(read(&s, 0), before_command); + s.execute("edit.undo", &json!({})).expect("undo post-redo run"); + assert_eq!(read(&s, 0), first_run); + + write(&mut s, 0, "slide zero"); + let zero = read(&s, 0); + let other = read(&s, 1); + write(&mut s, 1, "slide one"); + write(&mut s, 1, "slide one continued"); + s.execute("edit.undo", &json!({})).expect("undo other slide's run"); + assert_eq!(read(&s, 1), other); + assert_eq!(read(&s, 0), zero); + write(&mut s, 0, "after undo"); + s.execute("edit.undo", &json!({})).expect("undo starts a separate run"); + assert_eq!(read(&s, 0), zero); + assert!(s.doc().expect("doc").history.redo.len() < 2, "typing clears the prior redo branch"); + + write(&mut s, 0, "before navigating"); + let before_navigation = read(&s, 0); + s.execute("slide.go", &json!({"index": 0})).expect("select first"); + s.execute("slide.go", &json!({"index": 1})).expect("leave slide"); + s.execute("slide.go", &json!({"index": 0})).expect("return to slide"); + write(&mut s, 0, "after navigating"); + s.execute("edit.undo", &json!({})).expect("undo post-navigation edit"); + assert_eq!(read(&s, 0), before_navigation); + + s.execute("slide.notes", &json!({"index": 0, "text": "automation first"})).expect("default separate edit"); + let automation_first = read(&s, 0); + s.execute("slide.notes", &json!({"index": 0, "text": "automation second"})).expect("default separate edit"); + s.execute("edit.undo", &json!({})).expect("undo one automation edit"); + assert_eq!(read(&s, 0), automation_first); + } + #[test] fn invalid_index_params_are_rejected_not_defaulted_to_selection() { let mut s = Session::with_new(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index eb1ae5a85..bf91dee3e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -237,6 +237,9 @@ pub struct DocState { /// The list AutoFormat just started from a typed `* ` or `1. `, so Backspace right after /// can put the typed text back. pub auto_list: Option, + /// The slide whose editor's consecutive notes changes share one undo step. + pub notes_run: Option, + notes_before: Option>, } static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -266,6 +269,8 @@ impl DocState { compare: None, last_duplicate: None, auto_list: None, + notes_run: None, + notes_before: None, } } pub fn is_dirty(&self) -> bool { @@ -329,7 +334,7 @@ pub fn shapes_mut<'a>(doc: &'a mut Presentation, sel: &Selection) -> Option<&'a } /// Engine preferences (the UI keeps its own). -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Prefs { pub snap_to_grid: bool, @@ -482,6 +487,16 @@ pub struct Clipboard { pub pastes: u32, } +type TextEditTarget = (u64, usize, Target, ShapeId, Option<(usize, usize)>, bool); + +#[derive(Clone)] +struct TextEditSession { + target: TextEditTarget, + before: Arc, + latest: Arc, + journal_start: usize, +} + pub struct Session { docs: Vec, active: Option, @@ -517,6 +532,8 @@ pub struct Session { next_loaded: u64, /// Compositions the application settled itself (see [`Session::composition_settles`]). composition_settles: u64, + active_generation: u64, + text_edit_session: Option, } impl Default for Session { @@ -551,6 +568,8 @@ impl Session { loaded: vec![], next_loaded: 0, composition_settles: 0, + active_generation: 0, + text_edit_session: None, } } /// Hand over a presentation read on another thread ([`cmd::file::read_presentation_file`]); @@ -624,6 +643,12 @@ impl Session { fn forget_vertex_kind_unless(&mut self, was: Option) { if self.active().map(|d| d.uid) != was { self.tool.vertex_kind = None; + self.active_generation = self.active_generation.wrapping_add(1); + self.text_edit_session = None; + for st in &mut self.docs { + st.notes_run = None; + st.notes_before = None; + } } } pub fn next_untitled(&mut self) -> String { @@ -641,6 +666,32 @@ impl Session { /// failed outer command, and committing the resulting undo entry or journal record. fn execute_unguarded(&mut self, id: &str, params: &Value) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + if self.depth == 0 { + let text_input = matches!( + id, + "text.edit" + | "text.exit" + | "text.insert" + | "text.delete" + | "text.compose" + | "text.commit" + | "text.deleteSurrounding" + | "text.move" + | "text.select" + | "text.selectAll" + | "text.selectWord" + | "text.selectParagraph" + ); + if !self.text_boundary_matches() || (!text_input && (spec.undoable || spec.journal)) { + self.text_edit_session = None; + } + if (spec.undoable && id != "slide.notes") || matches!(id, "edit.undo" | "edit.redo") { + if let Some(st) = self.active_mut() { + st.notes_run = None; + st.notes_before = None; + } + } + } // Any other edit (or a click, a key, undo) settles an input method's composition first. if self.depth == 0 && (spec.journal || spec.undoable) && !matches!(id, "text.compose" | "text.commit") { self.settle_composition(); @@ -689,14 +740,32 @@ impl Session { && spec.undoable && outer { - push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind }); + let joins_notes = id == "slide.notes" + && st.notes_run.is_some() + && st.notes_before.as_ref().is_some_and(|first| st.history.undo.last().is_some_and(|e| Arc::ptr_eq(first, &e.doc))); + if joins_notes { + st.history.redo.clear(); + if let Some(first) = &st.notes_before { + st.history.costs.insert(Arc::as_ptr(first) as usize, undo_cost(first, &st.doc)); + } + } else { + let notes_before = (id == "slide.notes" && st.notes_run.is_some()).then(|| old.clone()); + push_undo(st, HistoryEntry { label: spec.label.to_string(), doc: old, selection: sel, vertex_kind }); + st.notes_before = notes_before; + } } if spec.journal && outer { self.journal.push((id.to_string(), params.clone())); if self.journal.len() > 10_000 { self.journal.drain(..1000); + if let Some(boundary) = &mut self.text_edit_session { + boundary.journal_start = boundary.journal_start.saturating_sub(1000); + } } } + if outer { + self.advance_text_boundary(); + } Ok(if outer { self.with_editing(id, r) } else { r }) } @@ -784,13 +853,21 @@ impl Session { } let owner = |sel: &Selection| sel.text.as_ref().map(|t| (sel.slide, sel.target, t.shape, t.cell, t.notes)); let before = owner(&st.selection); + let slide_before = st.selection.slide; f(&doc, &mut st.selection); clamp_selection(st); + if st.selection.slide != slide_before { + st.notes_run = None; + st.notes_before = None; + } st.revision += 1; // A composition belongs to the text body it began in: leaving that body settles it. if st.composition.is_some() && owner(&st.selection) != before { self.settle_composition(); } + if self.text_target() != self.text_edit_session.as_ref().map(|b| b.target) { + self.text_edit_session = None; + } Ok(()) } } @@ -944,8 +1021,32 @@ impl Session { /// Atomically replaces character offsets in the current flattened edited body. /// Restores text, selection, composition and history on error. pub fn replace_text_range(&mut self, range: std::ops::Range, text: &str, kind: TextReplaceKind) -> Result { - let _ = (range, text, kind); - todo!("cv.A11") + let before = self.doc()?.clone(); + let boundary = self.text_edit_session.clone(); + let journal = self.journal.clone(); + let settles = self.composition_settles; + let depth = self.depth; + let mut output = None; + let result = self.guarded("text.replaceRange", |s| { + s.begin_text_edit_session()?; + // PLAN: assumed cmd::text::replace_text_range(&mut Session, Range, &str, TextReplaceKind) -> Result (shell-w9) + output = Some(cmd::text::replace_text_range(s, range, text, kind)?); + s.advance_text_boundary(); + Ok(Value::Null) + }); + if let Err(error) = result { + if let Some(st) = self.active_mut() + && st.uid == before.uid + { + *st = before; + } + self.depth = depth; + self.text_edit_session = boundary; + self.journal = journal; + self.composition_settles = settles; + return Err(error); + } + output.ok_or_else(|| EngineError::Internal("text.replaceRange".into(), "missing replacement result".into())) } } @@ -953,7 +1054,18 @@ impl Session { /// Opens an idempotent text edit boundary for the current document and target. /// Includes any original composition snapshot without adding an undo entry. pub fn begin_text_edit_session(&mut self) -> Result<()> { - todo!("cv.A12") + let target = self.text_target().ok_or_else(|| cmd::bad("text", cmd::NO_TEXT_POINT))?; + if self.text_boundary_matches() { + return Ok(()); + } + let mut before = self.doc()?.clone(); + let latest = before.doc.clone(); + if let Some(composition) = before.composition.take() { + before.doc = composition.before; + before.selection = composition.before_selection; + } + self.text_edit_session = Some(TextEditSession { target, before: Arc::new(before), latest, journal_start: self.journal.len() }); + Ok(()) } } @@ -961,8 +1073,31 @@ impl Session { /// Finishes the current text edit boundary, optionally restoring only its edits. /// Never crosses a sealed document or target boundary. pub fn finish_text_edit_session(&mut self, cancel: bool) -> Result<()> { - let _ = cancel; - todo!("cv.A12") + let matches = self.text_boundary_matches(); + let Some(boundary) = self.text_edit_session.take() else { return Ok(()) }; + if !matches { + return Ok(()); + } + if !cancel { + self.settle_composition(); + return Ok(()); + } + if self.active().is_some_and(|st| st.composition.is_some()) { + self.composition_settles = self.composition_settles.wrapping_add(1); + } + let st = self.doc_mut()?; + if !Arc::ptr_eq(&st.doc, &boundary.before.doc) { + st.doc = boundary.before.doc.clone(); + st.selection = boundary.before.selection.clone(); + st.history = boundary.before.history.clone(); + st.composition = boundary.before.composition.clone(); + st.auto_list = boundary.before.auto_list.clone(); + st.notes_run = None; + st.notes_before = None; + st.revision = st.revision.wrapping_add(1); + self.journal.truncate(boundary.journal_start); + } + Ok(()) } } @@ -970,6 +1105,32 @@ impl Session { /// Returns the generation of actual active-document transitions. /// Same-active and invalid requests leave the generation unchanged. pub fn active_generation(&self) -> u64 { - todo!("sh.A20") + self.active_generation + } + + fn text_target(&self) -> Option { + let st = self.active()?; + let t = st.selection.text.as_ref()?; + Some((st.uid, st.selection.slide, st.selection.target, if t.notes { ShapeId::default() } else { t.shape }, t.cell, t.notes)) + } + + fn text_boundary_matches(&self) -> bool { + self.text_edit_session + .as_ref() + .is_some_and(|b| self.text_target() == Some(b.target) && self.active().is_some_and(|st| Arc::ptr_eq(&st.doc, &b.latest))) + } + + fn advance_text_boundary(&mut self) { + let target = self.text_target(); + let latest = self.active().map(|st| st.doc.clone()); + if let Some(boundary) = &mut self.text_edit_session { + if Some(boundary.target) == target { + if let Some(latest) = latest { + boundary.latest = latest; + } + } else { + self.text_edit_session = None; + } + } } } diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index c7dfa024d..9a6561c23 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -9,6 +9,7 @@ description = "DeckCraft text layout: runs to shaped glyph lines with bullets, i workspace = true [dependencies] +craft = { workspace = true, features = ["text"] } deckcraft-model = { workspace = true } deckcraft-geom = { workspace = true } deckcraft-color = { workspace = true } diff --git a/crates/text/src/autonum.rs b/crates/text/src/autonum.rs deleted file mode 100644 index c705f5490..000000000 --- a/crates/text/src/autonum.rs +++ /dev/null @@ -1,160 +0,0 @@ -fn roman(mut n: u32, upper: bool) -> String { - let table = [ - (1000, "m"), - (900, "cm"), - (500, "d"), - (400, "cd"), - (100, "c"), - (90, "xc"), - (50, "l"), - (40, "xl"), - (10, "x"), - (9, "ix"), - (5, "v"), - (4, "iv"), - (1, "i"), - ]; - let mut s = String::new(); - if n == 0 || n > 3999 { - return n.to_string(); - } - for (v, r) in table { - while n >= v { - s.push_str(r); - n -= v; - } - } - if upper { s.to_uppercase() } else { s } -} - -fn alpha_num(n: u32, upper: bool) -> String { - if n == 0 { - return String::new(); - } - let n = n - 1; - let c = (b'a' + (n % 26) as u8) as char; - let reps = (n / 26 + 1).min(50); - let s: String = std::iter::repeat_n(c, reps as usize).collect(); - if upper { s.to_uppercase() } else { s } -} - -/// Letters of a numbering alphabet: 1 → the first, past the end the letter doubles ("aa"), as -/// the Latin alphabetic schemes do. -fn letters(list: &[char], n: u32) -> String { - let len = list.len().max(1) as u32; - let Some(i) = n.checked_sub(1) else { return String::new() }; - let c = list.get((i % len) as usize).copied().unwrap_or('?'); - std::iter::repeat_n(c, (i / len + 1).min(50) as usize).collect() -} - -/// `n` written with the digits `zero..zero+9` (Thai, Devanagari, full-width digits). -fn digits_in(n: u32, zero: char) -> String { - n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| char::from_u32(zero as u32 + v)).unwrap_or(d)).collect() -} - -const CJK_DIGITS: [char; 10] = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九']; - -/// Chinese numerals: 10 → 十, 11 → 十一, 25 → 二十五, 105 → 一百零五. -pub(crate) fn chinese_num(n: u32) -> String { - if n == 0 || n > 99_999 { - return n.to_string(); - } - let units = ['\0', '十', '百', '千', '万']; - let ds: Vec = n.to_string().chars().filter_map(|c| c.to_digit(10)).collect(); - let mut out = String::new(); - let mut zero = false; - for (i, d) in ds.iter().enumerate() { - let place = ds.len() - 1 - i; - if *d == 0 { - zero = true; - continue; - } - if zero { - out.push('零'); - zero = false; - } - // "十" alone for 10–19, not "一十". - if !(*d == 1 && place == 1 && i == 0) { - out.push(CJK_DIGITS.get(*d as usize).copied().unwrap_or('?')); - } - if let Some(u) = units.get(place).filter(|u| **u != '\0') { - out.push(*u); - } - } - out -} - -/// Text of an auto-number bullet: `arabicPeriod` 3 → "3.". The East Asian, Thai, Hindi, Arabic -/// and Hebrew schemes are written as PowerPoint draws them: `ea1ChsPeriod` 10 → "十.", -/// `ea1JpnKorPeriod` 10 → "一〇." (digit by digit), `arabicDbPeriod` 13 → "13.", -/// `thaiAlphaParenR` 4 → "ง)", `hindiAlpha1Period` 1 → "क.", `arabic2Minus` 10 → "ي-" -/// (abjad order), `circleNumWdWhitePlain` 13 → "③" (those circles go to ten). -pub fn autonum(scheme: &str, n: u32) -> String { - const THAI: [char; 41] = [ - 'ก', 'ข', 'ค', 'ง', 'จ', 'ฉ', 'ช', 'ซ', 'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ', 'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ', - 'ภ', 'ม', 'ย', 'ร', 'ล', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ', - ]; - const HINDI_VOWELS: [char; 11] = ['अ', 'आ', 'इ', 'ई', 'उ', 'ऊ', 'ऋ', 'ए', 'ऐ', 'ओ', 'औ']; - const HINDI_CONSONANTS: [char; 33] = [ - 'क', 'ख', 'ग', 'घ', 'ङ', 'च', 'छ', 'ज', 'झ', 'ञ', 'ट', 'ठ', 'ड', 'ढ', 'ण', 'त', 'थ', 'द', 'ध', 'न', 'प', 'फ', 'ब', 'भ', 'म', 'य', 'र', 'ल', - 'व', 'श', 'ष', 'स', 'ह', - ]; - const ARABIC_ALPHABET: [char; 28] = - ['ا', 'ب', 'ت', 'ث', 'ج', 'ح', 'خ', 'د', 'ذ', 'ر', 'ز', 'س', 'ش', 'ص', 'ض', 'ط', 'ظ', 'ع', 'غ', 'ف', 'ق', 'ك', 'ل', 'م', 'ن', 'ه', 'و', 'ي']; - const ARABIC_ABJAD: [char; 28] = - ['ا', 'ب', 'ج', 'د', 'ه', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ']; - const HEBREW: [char; 22] = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק', 'ר', 'ש', 'ת']; - let circled = |first: u32, count: u32| char::from_u32(first + n.saturating_sub(1) % count).map(String::from).unwrap_or_else(|| n.to_string()); - let core = if scheme.starts_with("romanUc") { - roman(n, true) - } else if scheme.starts_with("romanLc") { - roman(n, false) - } else if scheme.starts_with("alphaUc") { - alpha_num(n, true) - } else if scheme.starts_with("alphaLc") { - alpha_num(n, false) - } else if scheme.starts_with("circleNumWdWhite") { - return circled(0x2460, 10); - } else if scheme.starts_with("circleNumWdBlack") { - return circled(0x2776, 10); - } else if scheme.starts_with("circleNum") { - return char::from_u32(0x2460 + n.saturating_sub(1).min(19)).map(String::from).unwrap_or_else(|| n.to_string()); - } else if scheme.starts_with("ea1Chs") || scheme.starts_with("ea1Cht") { - chinese_num(n) - } else if scheme.starts_with("ea1Jpn") { - n.to_string().chars().map(|d| d.to_digit(10).and_then(|v| CJK_DIGITS.get(v as usize).copied()).unwrap_or(d)).collect() - } else if scheme.starts_with("arabicDb") { - digits_in(n, '0') - } else if scheme.starts_with("thaiAlpha") { - letters(&THAI, n) - } else if scheme.starts_with("thaiNum") { - digits_in(n, '๐') - } else if scheme.starts_with("hindiAlpha1") { - letters(&HINDI_CONSONANTS, n) - } else if scheme.starts_with("hindiAlpha") { - letters(&HINDI_VOWELS, n) - } else if scheme.starts_with("hindiNum") { - digits_in(n, '०') - } else if scheme.starts_with("arabic1") { - letters(&ARABIC_ALPHABET, n) - } else if scheme.starts_with("arabic2") { - letters(&ARABIC_ABJAD, n) - } else if scheme.starts_with("hebrew2") { - letters(&HEBREW, n) - } else { - n.to_string() - }; - // East Asian schemes end with a full-width full stop. - let wide = scheme.starts_with("ea1") || scheme.starts_with("arabicDb"); - if scheme.ends_with("ParenBoth") { - format!("({core})") - } else if scheme.ends_with("ParenR") { - format!("{core})") - } else if scheme.ends_with("Period") { - format!("{core}{}", if wide { '.' } else { '.' }) - } else if scheme.ends_with("Minus") { - format!("{core}-") - } else { - core - } -} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 9e03a2b4d..e476bf592 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -34,7 +34,6 @@ use deckcraft_model::text::{Align, Anchor, AutoFit, BodyProps, Bullet, Caps, Par use deckcraft_model::{Fill, Shape}; use unicode_segmentation::UnicodeSegmentation; -mod autonum; mod breaking; mod layout; mod run; @@ -42,11 +41,9 @@ mod shape; mod style; mod symbol; -pub use autonum::autonum; -#[cfg(test)] -use autonum::chinese_num; #[cfg(test)] use breaking::{LINE_PITCH, break_opportunities, measure_str}; +pub use craft::text::lists::autonum; #[cfg(test)] pub(crate) use layout::LAYOUT_PASSES; pub use layout::layout; diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index d5558001d..07fd89380 100644 --- a/crates/text/src/shape.rs +++ b/crates/text/src/shape.rs @@ -1,4 +1,4 @@ -use super::autonum::autonum; +use super::autonum; use super::run::{RunEffects, TextShadow}; use super::style::{Cell, Opts, ParaShaped, Style, face_chain, make_style}; use super::symbol::{covers_symbol, is_symbol_font, map_symbol_bullet, symbol_font_char, symbol_map_char}; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index f1c7852d9..8c9352aaf 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1,8 +1,8 @@ use super::{ Affinity, Align, Anchor, Arc, AutoFit, BodyProps, Bullet, Caps, Cell, Ctx, Dash, Deco, DecoLine, FontDb, FontFace, GlyphRun, LINE_PITCH, - MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, autonum, - break_opportunities, caps_char, chinese_num, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str, - resolve, shaping_features, symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts, + MoveMode, NoFields, Opts, ParaProps, Point, Pos, Rect, Rgba, SUB_SUPER, Shape, Spacing, Strike, TextBody, TextLayout, break_opportunities, + caps_char, covers_symbol, is_symbol_font, is_upright, layout, layout_scaled, map_symbol_bullet, measure_str, resolve, shaping_features, + symbol_char, symbol_font_char, symbol_font_draw, symbol_unicode, symbol_unicode_alts, }; use deckcraft_model::Fill; use deckcraft_model::defaults; @@ -413,16 +413,6 @@ fn empty_and_hostile_bodies_never_panic() { let _ = l.selection_rects(Pos { para: 5, ch: 0 }, Pos { para: 0, ch: 3 }); } -#[test] -fn autonum_formats() { - assert_eq!(autonum("arabicPeriod", 3), "3."); - assert_eq!(autonum("romanUcPeriod", 4), "IV."); - assert_eq!(autonum("alphaLcParenR", 2), "b)"); - assert_eq!(autonum("arabicParenBoth", 1), "(1)"); - assert_eq!(autonum("alphaUcPeriod", 27), "AA."); - assert_eq!(autonum("alphaUcPeriod", u32::MAX).len(), 51); // 50 letters + '.' -} - #[test] fn numbered_list_counts() { let (p, mut sh) = setup("a\nb\nc", 400.0, 300.0); @@ -1533,41 +1523,6 @@ fn small_kana_and_closing_brackets_follow_powerpoint_kinsoku() { assert_eq!(lines[0], "あいうえ", "{lines:?}"); } -#[test] -fn autonumber_schemes_follow_powerpoint() { - // As PowerPoint's export draws them (start values as in the probe deck). - for (scheme, n, want) in [ - ("ea1ChsPlain", 4, "四"), - ("ea1ChsPeriod", 10, "十."), - ("ea1ChtPeriod", 21, "二十一."), - ("ea1JpnKorPeriod", 10, "一〇."), - ("ea1JpnChsDbPeriod", 13, "一三."), - ("arabicDbPlain", 10, "10"), - ("arabicDbPeriod", 13, "13."), - ("circleNumDbPlain", 13, "⑬"), - ("circleNumWdWhitePlain", 13, "③"), - ("circleNumWdBlackPlain", 2, "❷"), - ("thaiAlphaPeriod", 1, "ก."), - ("thaiAlphaParenR", 4, "ง)"), - ("thaiAlphaParenBoth", 7, "(ช)"), - ("thaiNumPeriod", 10, "๑๐."), - ("hindiAlphaPeriod", 4, "ई."), - ("hindiAlpha1Period", 1, "क."), - ("hindiNumParenR", 13, "१३)"), - ("hebrew2Minus", 1, "א-"), - ("arabic1Minus", 13, "ش-"), - ("arabic2Minus", 10, "ي-"), - ("arabicPlain", 10, "10"), - ] { - assert_eq!(autonum(scheme, n), want, "{scheme} {n}"); - } - assert_eq!(chinese_num(105), "一百零五"); - assert_eq!(chinese_num(20), "二十"); - // Past the end of an alphabet the letter doubles, like "aa". - assert_eq!(autonum("hebrew2Minus", 23), "אא-"); - assert_eq!(autonum("thaiAlphaPeriod", 0), "."); -} - #[test] fn east_asian_vertical_text_marks_cjk_upright() { let (p, mut sh) = setup("日本、ABC 12", 300.0, 600.0); diff --git a/crates/ui-egui/src/panels/notes.rs b/crates/ui-egui/src/panels/notes.rs index 0f46f0412..8df911cda 100644 --- a/crates/ui-egui/src/panels/notes.rs +++ b/crates/ui-egui/src/panels/notes.rs @@ -1,395 +1,185 @@ -//! Speaker notes editing (the notes pane and Notes Page view). The notes are edited as text and -//! drawn with their formatting: bold, italic, underline, strikethrough and size from the runs, -//! indents (wrapped lines included) and bullets or numbers from the paragraphs. Each edit is -//! applied to a formatted draft, so typed text takes the formatting where it lands and the rest -//! keeps its own; the draft is saved with `slide.notes {body}` once the editor loses focus. +//! Speaker notes use the shared rich-text editor. Each pass's text changes reach the document +//! immediately; the engine groups consecutive editor changes into a single undo step. -use std::sync::Arc; +use craft::text::lists::ListMarker; +use craft::text::ui::notes::{NotesEditor, NotesEditorForm, NotesFlag, NotesFlagPolicy, NotesParagraph, NotesRun, NotesText}; +use craft::theme::variant::Tone; +use craft::ui::contract::overlay::Anchor; +use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _, WordSetCx as _}; +use craft::ui::display::Divider; +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::runtime::commands::CommandRef; +use deckcraft_model::text::{Bullet, Strike, TextBody}; +use egui::{Color32, Ui}; +use serde_json::json; -use deckcraft_model::edit; -use deckcraft_model::text::{Bullet, Paragraph, RunProps, Strike, TextBody}; -use egui::text::{Galley, LayoutJob, TextFormat}; -use egui::{Align2, Color32, Stroke, Ui, vec2}; +use crate::SlideApp; -use crate::theme; - -/// Size and colour of a notes editor's text. -pub struct Look { - /// Pixels for 12 pt text, the notes' default size; indents scale with it. - pub size: f32, - /// `None` = the widget text colour. - pub color: Option, -} - -/// Notes being edited: the text in the editor and the formatted notes it stands for. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Draft { - pub text: String, - pub body: TextBody, - /// Edited since it was saved. - pub edited: bool, -} - -impl Draft { - pub fn new(body: &TextBody) -> Self { - Draft { text: body.text(), body: body.clone(), edited: false } +craft::ui::words! { + /// Speaker notes and their proofing menu. + struct NotesWords { + notes: plain = "Notes"; + spelling: plain = "Spelling"; + delete_repeated: plain = "Delete Repeated Word"; + no_suggestions: plain = "(no spelling suggestions)"; + ignore_all: plain = "Ignore All"; + add_to_dictionary: plain = "Add to Dictionary"; + suggestion: template "notes.suggestion" = "{word}"; } } -/// The draft as it reads with `text` typed in (one edit since the draft): `None` when that can't -/// be mapped onto it. -fn typed(body: &TextBody, text: &str) -> Option { - let mut b = body.clone(); - edit::replace_text(&mut b, text); - (b.text() == text).then_some(b) -} - -/// A length in points from the file as pixels, bounded. -fn px(pt: f64, k: f32) -> f32 { - if pt.is_finite() { pt.clamp(0.0, 400.0) as f32 * k } else { 0.0 } -} - -/// Where a paragraph's first line starts and its other lines start (points): a level without its -/// own margin is indented 36 pt per level, as in the default notes master. -fn indents(p: &Paragraph) -> (f64, f64) { - let margin = p.props.margin_left.unwrap_or(36.0 * f64::from(p.level.min(8))); - let first = margin + p.props.indent.unwrap_or(0.0); - (first, margin) -} - -/// Each paragraph's bullet or number, numbered as on a slide (per level, restarting after an -/// unnumbered paragraph at the same or a lower level). -fn bullets(body: &TextBody) -> Vec> { - let mut numbering = [0u32; 9]; - body.paragraphs - .iter() - .map(|p| { - let lvl = usize::from(p.level.min(8)); - if p.is_empty() { - return None; - } - let auto = matches!(p.props.bullet, Some(Bullet::AutoNum { .. })); - for (i, n) in numbering.iter_mut().enumerate().skip(lvl) { - if i > lvl || !auto { - *n = 0; - } - } - match p.props.bullet.as_ref()? { - Bullet::None => None, - Bullet::Char { char } => Some(deckcraft_text::map_symbol_bullet(char, p.props.bullet_font.as_deref())), - Bullet::AutoNum { scheme, start_at } => { - let n = numbering.get_mut(lvl)?; - *n = n.saturating_add(1); - Some(deckcraft_text::autonum(scheme, start_at.saturating_sub(1).saturating_add(*n))) - } - Bullet::Picture { .. } => Some("•".into()), - } - }) - .collect() -} - -fn format(props: &RunProps, size: f32, color: Color32) -> TextFormat { - let size = match props.size { - Some(pt) if pt.is_finite() && pt > 0.0 => (size * pt as f32 / 12.0).clamp(size * 0.75, size * 2.0), - _ => size, - }; - let font = if props.bold == Some(true) { theme::bold(size) } else { theme::font(size) }; - let mut f = TextFormat::simple(font, color); - f.italics = props.italic == Some(true); - if props.underline.as_deref().is_some_and(|u| u != "none") { - f.underline = Stroke::new(1.0, color); - } - if matches!(props.strike, Some(Strike::Single | Strike::Double)) { - f.strikethrough = Stroke::new(1.0, color); - } - f -} - -/// One paragraph to lay out: wrapped lines start at the margin (pixels), the first line's text at -/// `text`, clear of a bullet. -struct ParaLayout { - job: LayoutJob, - margin: f32, - /// x of the first line's text. - text: f32, -} - -fn para_layout(p: &Paragraph, bullet: Option<&str>, size: f32, color: Color32, wrap: f32) -> ParaLayout { - let k = size / 12.0; - let (first, margin) = indents(p); - let (first, margin) = (px(first, k), px(margin, k)); - let text = match bullet { - // The text starts at the margin, after the bullet if it's wider than the hanging indent. - Some(b) => margin.max(first + size * (0.4 + 0.6 * b.chars().count() as f32)), - None => first, - }; - let mut job = LayoutJob::default(); - job.wrap.max_width = (wrap - margin).max(size * 4.0); - let mut lead = (text - margin).max(0.0); - for r in &p.runs { - let t = r.content(); - if !t.is_empty() { - job.append(t, lead, format(&r.props, size, color)); - lead = 0.0; - } - } - if job.text.is_empty() { - job.append("", 0.0, format(&p.end_props, size, color)); - } - ParaLayout { job, margin, text } -} - -/// The whole notes as one job (the galley's text and formats). -fn job(body: &TextBody, size: f32, color: Color32, wrap: f32) -> LayoutJob { - let mut job = LayoutJob::default(); - job.wrap.max_width = wrap; - for (i, (p, bullet)) in body.paragraphs.iter().zip(bullets(body)).enumerate() { - if i > 0 { - job.append("\n", 0.0, TextFormat::simple(theme::font(size), color)); - } - let pl = para_layout(p, bullet.as_deref(), size, color, wrap); - for s in pl.job.sections { - if let Some(t) = pl.job.text.get(s.byte_range.start.0..s.byte_range.end.0) { - job.append(t, s.leading_space, s.format); - } - } - } - job -} - -/// Lay the notes out paragraph by paragraph, each moved to its indent, so wrapped lines line up -/// under the text and not under the bullet. -fn galley(ui: &Ui, body: &TextBody, size: f32, color: Color32, wrap: f32) -> Arc { - let whole = job(body, size, color, wrap); - if body.paragraphs.is_empty() { - return ui.fonts_mut(|f| f.layout_job(whole)); - } - let parts: Vec> = ui.fonts_mut(|f| { +/// Converts document notes into the shared editor's rich text. +pub fn to_notes(body: &TextBody) -> NotesText { + NotesText::new( body.paragraphs .iter() - .zip(bullets(body)) - .map(|(p, bullet)| { - let pl = para_layout(p, bullet.as_deref(), size, color, wrap); - let mut g = (*f.layout_job(pl.job)).clone(); - for (i, row) in g.rows.iter_mut().enumerate() { - // The first line already holds the gap after a bullet; a first line hanging - // left of the margin without one starts there. - row.pos.x += if i == 0 { pl.margin.min(pl.text) } else { pl.margin }; - } - Arc::new(g) + .map(|paragraph| { + let marker = match paragraph.props.bullet.as_ref() { + Some(Bullet::Char { char }) => { + Some(ListMarker::Bullet(deckcraft_text::map_symbol_bullet(char, paragraph.props.bullet_font.as_deref()))) + } + Some(Bullet::AutoNum { scheme, start_at }) => Some(ListMarker::from_autonum(scheme, *start_at)), + Some(Bullet::Picture { .. }) => Some(ListMarker::Bullet("•".into())), + Some(Bullet::None) | None => None, + }; + let runs = paragraph + .runs + .iter() + .map(|run| { + let color = match &run.props.fill { + Some(deckcraft_model::Fill::Solid { color }) => { + // PLAN: plan error: to_notes has no document colour scheme for theme-relative run fills + let base = match &color.base { + deckcraft_model::ColorBase::Rgb { rgb } => Some(*rgb), + deckcraft_model::ColorBase::System { last, .. } => Some(*last), + deckcraft_model::ColorBase::Preset { name } => deckcraft_color::preset(name), + deckcraft_model::ColorBase::Scheme { .. } => None, + }; + base.map(|c| { + let c = deckcraft_color::apply(c, &color.mods); + Color32::from_rgba_unmultiplied(c.r, c.g, c.b, c.a) + }) + } + _ => None, + }; + NotesRun::new(run.content()) + .bold(run.props.bold == Some(true)) + .italic(run.props.italic == Some(true)) + .underline(run.props.underline.as_deref().is_some_and(|value| value != "none")) + .strikethrough(matches!(run.props.strike, Some(Strike::Single | Strike::Double))) + .color(color) + }) + .collect(); + NotesParagraph::new(runs).list(paragraph.level, marker).margins(paragraph.props.margin_left, paragraph.props.indent) }) - .collect() - }); - Arc::new(Galley::concat(Arc::new(whole), &parts, ui.ctx().pixels_per_point())) + .collect(), + ) } -/// A multiline editor for the draft that draws its formatting; `configure` sets the id, hint, -/// size and frame. Edits update the draft's text and formatted body. Returns the field's output -/// (galley and caret too, for spelling marks). -pub fn editor( - ui: &mut Ui, - draft: &mut Draft, - look: &Look, - configure: impl for<'a> FnOnce(egui::TextEdit<'a>) -> egui::TextEdit<'a>, -) -> egui::text_edit::TextEditOutput { - let color = look.color.unwrap_or_else(|| ui.visuals().override_text_color.unwrap_or_else(|| ui.visuals().widgets.inactive.text_color())); - let size = look.size; - let before = draft.body.clone(); - let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap: f32| match typed(&before, text.as_str()) { - Some(b) => galley(ui, &b, size, color, wrap), - None => ui.fonts_mut(|f| f.layout_job(LayoutJob::simple(text.as_str().to_string(), theme::font(size), color, wrap))), +/// Applies text edits while preserving untouched document runs and paragraph properties. +pub fn apply(body: &TextBody, notes: &NotesText) -> TextBody { + let mut body = body.clone(); + deckcraft_model::edit::replace_text(&mut body, ¬es.plain()); + body +} + +fn notes_lang(s: &deckcraft_model::Slide) -> Option { + s.notes.paragraphs.iter().flat_map(|p| &p.runs).find_map(|r| r.props.lang.clone()) +} + +/// Shows the editable notes in the pane host's body context. +pub(crate) fn pane_body(app: &mut SlideApp, ui: &mut Ui, cx: &mut BodyCx<'_>) { + let words = cx.words::(); + let Some(st) = app.session.active() else { return }; + if st.selection.target != deckcraft_engine::Target::Slides { + return; + } + let index = st.selection.slide; + let Some(slide) = st.current_slide() else { return }; + let body = slide.notes.clone(); + let lang = notes_lang(slide).unwrap_or_else(|| "en-US".into()); + let mut notes = to_notes(&body); + let plain = notes.plain(); + // PLAN: plan error: BodyCx exposes no enclosing container Inner::settle hook for pane mutations and request drains + // All candidates keep their original indices; the editor hides the live caret's flag in paint. + // PLAN: assumed Squiggles::notes(&str, &str, Option) -> Vec<(usize, usize)> (canvas-w12) + let flags: Vec<_> = + app.squiggles.notes(&plain, &lang, None).into_iter().map(|(a, b)| NotesFlag::new(a..b, Tone::Bad)).collect(); + let out = NotesEditor::new(words.notes.clone(), &mut notes) + .form(NotesEditorForm::Pane) + .flags(&flags) + .flag_policy(NotesFlagPolicy::OutsideCaret) + .show(ui); + if out.changed { + let _ = app.run("slide.notes", json!({"body": apply(&body, ¬es), "index": index, "coalesce": true})); + } + + let requested = if app.pane_menu.as_ref().is_some_and(|(part, _)| part == "notes-word") { + app.pane_menu.take().and_then(|(_, at)| usize::try_from(at).ok()) + } else { + None }; - let out = configure(egui::TextEdit::multiline(&mut draft.text)).layouter(&mut layouter).show(ui); - if draft.body.text() != draft.text { - edit::replace_text(&mut draft.body, &draft.text); - draft.edited = true; + let hit = out.context.and_then(|context| context.flag).or(requested); + if out.context.is_some() || requested.is_some() { + app.squiggles.notes_menu = hit.and_then(|i| flags.get(i)).and_then(|flag| word_at(&plain, &lang, flag.range.start)); } - if draft.body.text() == draft.text { - paint_bullets(&ui.painter().with_clip_rect(out.text_clip_rect), &draft.body, &out.galley, out.galley_pos, size, color); + let Some(word) = app.squiggles.notes_menu.clone() else { return }; + let crate::squiggles::Tag::Notes { start } = word.tag else { return }; + let mut menu = Menu::context(words.spelling.clone(), &out.response).open(Bind::given(true)); + if let Some(context) = out.context { + menu = menu.anchor(Anchor::Point(context.at)); + } else if requested.is_some() { + menu = menu.anchor(Anchor::Point(out.response.rect.left_bottom())); } - out -} - -/// The (min y, max y) of the row holding char index `at`; `walk` (row index, chars through that -/// row) carries over between calls, so successive non-decreasing `at`s cost one pass in all. -fn row_span_at(galley: &Galley, walk: &mut (usize, usize), at: usize) -> (f32, f32) { - while walk.0 + 1 < galley.rows.len() && (walk.1 < at || (walk.1 == at && galley.rows[walk.0].char_count_including_newline().0 > 0)) { - walk.0 += 1; - walk.1 += galley.rows[walk.0].char_count_including_newline().0; - } - galley.rows.get(walk.0).map_or((0.0, 0.0), |r| (r.min_y(), r.max_y())) -} - -/// Bullets and numbers at the start of each paragraph's first line of `galley` (laid out from -/// `body`), drawn at `origin`. -fn paint_bullets(painter: &egui::Painter, body: &TextBody, galley: &Galley, origin: egui::Pos2, size: f32, color: Color32) { - let k = size / 12.0; - let mut at = 0usize; - // Paragraph starts only grow, so one forward walk over the rows finds each start's row - // (`pos_from_cursor` would rescan from the top for every bullet). - let mut walk = (0usize, galley.rows.first().map_or(0, |r| r.char_count_including_newline().0)); - for (p, bullet) in body.paragraphs.iter().zip(bullets(body)) { - if let Some(b) = bullet { - let (min_y, max_y) = row_span_at(galley, &mut walk, at); - let (center_y, height) = ((min_y + max_y) / 2.0, max_y - min_y); - let pos = origin + vec2(px(indents(p).0, k), center_y); - let font = theme::font(height.clamp(size * 0.75, size * 2.0) * 0.8); - painter.text(pos, Align2::LEFT_CENTER, b, font, color); + let mut correction = None; + let shown = menu.show(ui, |ui, _| { + if let Some(from) = word.delete_from { + if MenuItem::new(words.delete_repeated.clone()).show(ui).ran { + correction = Some((start + from, "".to_owned())); + } + } else if word.suggestions.is_empty() { + MenuItem::heading(words.no_suggestions.clone()).show(ui); + } else { + for suggestion in &word.suggestions { + if MenuItem::new(words.suggestion.fill(&[("word", suggestion)])).show(ui).ran { + correction = Some((start + word.start, suggestion.clone())); + } + } } - at += p.char_len() + 1; - } -} - -/// The notes drawn read-only with their formatting, wrapped to the available width, and -/// selectable like a label (the presenter's notes pane). -pub fn view(ui: &mut Ui, body: &TextBody, look: &Look) -> egui::Response { - let color = look.color.unwrap_or_else(|| ui.visuals().text_color()); - let g = galley(ui, body, look.size, color, ui.available_width()); - let response = ui.add(egui::Label::new(egui::WidgetText::Galley(g.clone()))); - paint_bullets(ui.painter(), body, &g, response.rect.min, look.size, color); - response -} - -#[cfg(test)] -mod tests { - #![allow(clippy::unwrap_used, clippy::expect_used)] - - use deckcraft_model::text::{ParaProps, Run}; - use egui::text::CCursor; - - use super::*; - - /// Notes as PowerPoint users write them: a bold heading, a plain line, points with a - /// Wingdings square bullet and a hanging indent (one long enough to wrap), numbered points, - /// a point with an explicit buNone, closing plain lines; Slovak text throughout. - fn notes() -> TextBody { - let props = |bullet: Bullet| ParaProps { - margin_left: Some(22.5), - indent: Some(-22.5), - bullet: Some(bullet), - bullet_font: Some("Wingdings".into()), - ..Default::default() - }; - let point = |runs: Vec, bullet: Bullet| Paragraph { level: 1, props: props(bullet), runs, ..Default::default() }; - let square = || Bullet::Char { char: "§".into() }; - let num = || Bullet::AutoNum { scheme: "arabicPeriod".into(), start_at: 1 }; - let bold = RunProps { bold: Some(true), ..Default::default() }; - TextBody { - paragraphs: vec![ - Paragraph { runs: vec![Run::with("Metodický prehľad", bold.clone())], ..Default::default() }, - Paragraph::new("Žiaci pracujú vo dvojiciach."), - point(vec![Run::with("Cieľ: ", bold), Run::new("vysvetliť cyklus")], square()), - point(vec![Run::new("Dlhý bod, ktorý sa zalomí na viac riadkov, lebo je naozaj veľmi dlhý a pokračuje ďalej.")], square()), - point(vec![Run::new("Jeden")], num()), - point(vec![Run::new("Dva")], num()), - point(vec![Run::new("Bez odrážky")], Bullet::None), - Paragraph::new("Pomôcky: počítač"), - ], - ..Default::default() + Divider::horizontal().show(ui); + if MenuItem::new(words.ignore_all.clone()).show(ui).ran { + app.squiggles.ignore(&word.word); } - } - - #[test] - fn bullets_follow_the_paragraphs() { - let b = bullets(¬es()); - assert_eq!(b, vec![None, None, Some("▪".into()), Some("▪".into()), Some("1.".into()), Some("2.".into()), None, None]); - } - - #[test] - fn notes_show_bold_runs_indents_and_wrap_under_the_text() { - let body = notes(); - let ctx = egui::Context::default(); - theme::install_fonts(&ctx); - let mut laid = None; - let mut out = ctx.run_ui(Default::default(), |ui| laid = Some(galley(ui, &body, 12.0, Color32::BLACK, 300.0))); - out.textures_delta.clear(); - let g = laid.unwrap(); - assert_eq!(g.job.text, body.text(), "the galley reads the notes"); - assert_eq!(g.rows.iter().map(|r| r.char_count_including_newline().0).sum::(), body.text().chars().count()); - // Bold where the runs are bold, regular elsewhere. - let font_of = |s: &str| { - let b = g.job.text.find(s).unwrap(); - g.job.sections.iter().find(|x| (x.byte_range.start.0..x.byte_range.end.0).contains(&b)).unwrap().format.font_id.clone() - }; - assert_eq!(font_of("Metodický"), theme::bold(12.0)); - assert_eq!(font_of("Cieľ"), theme::bold(12.0)); - assert_eq!(font_of("vysvetliť"), theme::font(12.0)); - assert_eq!(font_of("Pomôcky"), theme::font(12.0)); - // Rows: x where each paragraph's text starts. - let row_x = |s: &str| { - let at = body.text().find(s).map(|b| body.text()[..b].chars().count()).unwrap(); - g.pos_from_cursor(CCursor::new(at)).min.x - }; - assert!(row_x("Metodický") < 1.0 && row_x("Žiaci") < 1.0 && row_x("Pomôcky") < 1.0, "plain paragraphs aren't indented"); - assert!((row_x("Cieľ") - 22.5).abs() < 1.0, "bulleted text at the 22.5 pt margin: {}", row_x("Cieľ")); - assert!((row_x("Bez odrážky") - 0.0).abs() < 1.0, "buNone: no bullet, the first line hangs to 0"); - // The long point wraps, and its wrapped lines start at the margin, not under the bullet. - let long = body.text().find("Dlhý").map(|b| body.text()[..b].chars().count()).unwrap(); - let first_row = g.pos_from_cursor(CCursor::new(long)); - let wrapped: Vec<_> = - g.rows.iter().filter(|r| r.pos.y > first_row.min.y + 1.0 && r.pos.y < g.pos_from_cursor(CCursor::new(long + 80)).max.y).collect(); - assert!(!wrapped.is_empty(), "the long point wraps"); - assert!(wrapped.iter().all(|r| (r.pos.x - 22.5).abs() < 1.0), "wrapped lines align with the text"); - } - - #[test] - fn row_walk_matches_cursor_lookup_at_paragraph_starts() { - let ctx = egui::Context::default(); - let body = notes(); - let mut laid = None; - let mut out = ctx.run_ui(Default::default(), |ui| laid = Some(galley(ui, &body, 12.0, Color32::BLACK, 300.0))); - out.textures_delta.clear(); - let g = laid.unwrap(); - let mut walk = (0usize, g.rows.first().map_or(0, |r| r.char_count_including_newline().0)); - let mut at = 0usize; - for p in &body.paragraphs { - let want = g.pos_from_cursor(CCursor::new(at)); - assert_eq!(row_span_at(&g, &mut walk, at), (want.min.y, want.max.y), "paragraph at char {at}"); - at += p.char_len() + 1; + if word.delete_from.is_none() { + MenuItem::command(CommandRef::with_params("review.addToDictionary", json!({"word": word.word}))) + .label(words.add_to_dictionary.clone()) + .show(ui); } + }); + if let Some((from, replacement)) = correction { + let mut plain = notes.plain(); + let end = start + word.start + word.word.chars().count(); + let byte = |at| plain.char_indices().nth(at).map_or(plain.len(), |(b, _)| b); + let span = byte(from)..byte(end); + plain.replace_range(span, &replacement); + let mut changed = apply(&body, ¬es); + deckcraft_model::edit::replace_text(&mut changed, &plain); + let _ = app.run("slide.notes", json!({"body": changed, "index": index})); + app.squiggles.notes_menu = None; } - - #[test] - fn typing_keeps_the_formatting_around_it() { - let mut d = Draft::new(¬es()); - // Typing into the bold heading continues it in bold. - let t = d.text.replacen("prehľad", "prehľad hodiny", 1); - d.body = typed(&d.body, &t).unwrap(); - assert_eq!(d.body.paragraphs[0].runs.len(), 1); - assert_eq!(d.body.paragraphs[0].runs[0].props.bold, Some(true)); - // Enter at the end of a bulleted point starts another one with the same bullet and indent. - let t = d.body.text().replacen("cyklus", "cyklus\nnový bod", 1); - d.body = typed(&d.body, &t).unwrap(); - let new = &d.body.paragraphs[3]; - assert_eq!(new.text(), "nový bod"); - assert_eq!((new.level, &new.props), (1, ¬es().paragraphs[2].props)); - assert_eq!(d.body.paragraphs[2].runs[0].props.bold, Some(true), "the bold label stays bold"); - // Hostile sizes and indents stay bounded. - let mut wild = notes(); - wild.paragraphs[2].props.margin_left = Some(f64::NAN); - wild.paragraphs[0].runs[0].props.size = Some(f64::INFINITY); - let j = job(&wild, 12.0, Color32::BLACK, 300.0); - assert!(j.sections.iter().all(|s| s.leading_space.is_finite() && s.format.font_id.size <= 24.0)); + if shown.output.closed.is_some() { + app.squiggles.notes_menu = None; } } -/// Shows the pane body inside the pane host. -#[allow(dead_code)] // P3(panels-w7): pn.A2 -pub(crate) fn pane_body(app: &mut crate::SlideApp, ui: &mut egui::Ui, cx: &mut craft::ui::contract::BodyCx<'_>) { - let _ = (app, ui, cx); - todo!("pn.A2") -} - -/// Converts notes while preserving the document text formatting. -#[allow(dead_code)] // P3(panels-w7): pn.A4 -pub fn to_notes(body: &deckcraft_model::text::TextBody) -> craft::text::ui::notes::NotesText { - let _ = body; - todo!("pn.A4") -} - -/// Converts notes while preserving the document text formatting. -#[allow(dead_code)] // P3(panels-w7): pn.A4 -pub fn apply(body: &deckcraft_model::text::TextBody, notes: &craft::text::ui::notes::NotesText) -> deckcraft_model::text::TextBody { - let _ = (body, notes); - todo!("pn.A4") +fn word_at(plain: &str, lang: &str, at: usize) -> Option { + let mut start = 0; + for line in plain.split('\n') { + let end = start + line.chars().count(); + if at < end { + return crate::squiggles::menu_word(&deckcraft_model::Paragraph::new(line), lang, crate::squiggles::Tag::Notes { start }, at - start); + } + start = end + 1; + } + None } diff --git a/crates/ui-egui/src/status.rs b/crates/ui-egui/src/status.rs index b1ada4c43..fcec40001 100644 --- a/crates/ui-egui/src/status.rs +++ b/crates/ui-egui/src/status.rs @@ -1,426 +1,143 @@ -//! Status bar (slide counter, language, notes/comments toggles, view buttons, zoom slider) and the -//! notes pane under the slide. +//! Slide position, proofing language, view commands and zoom in the shared status bar. -use egui::{Align2, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2}; +use craft::behavior::{ZoomScheme, kurbo::Size}; +use craft::ui::bars::{Bar, BarKind, StatusMessage}; +use craft::ui::buttons::{IconButton, Link, LinkLook, ToggleButton}; +use craft::ui::choice::Segmented; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Divider, Shade, Text}; +use craft::ui::runtime::commands::CommandRef; +use craft::ui::runtime::env::{Env, with_env}; +use craft::ui::text::ZoomField; +use craft::ui::value_drag::{Slider, SliderScale}; +use egui::Ui; use serde_json::json; -use crate::icons::{self, Icon}; -use crate::theme::{self, Tokens}; +use crate::icons::Icon; use crate::{SlideApp, ViewMode}; -/// The status bar: slide counter, proofing language and status message on the left; notes, -/// comments, views and zoom on the right. +craft::ui::words! { + /// Status readouts and the names of the view and zoom controls. + struct StatusWords { + status_bar: plain = "Status Bar"; + slide_count: template "status.slideCount" = "Slide {slide} of {count}"; + slide_master: plain = "Slide Master"; + language_unchecked: template "status.languageUnchecked" = "{language} (not checked)"; + language: plain = "Language"; + notes: plain = "Notes"; + comments: plain = "Comments"; + views: plain = "Presentation Views"; + normal: plain = "Normal"; + sorter: plain = "Slide Sorter"; + reading: plain = "Reading View"; + slide_show: plain = "Slide Show"; + zoom_out: plain = "Zoom Out"; + zoom: plain = "Zoom"; + zoom_in: plain = "Zoom In"; + zoom_level: plain = "Zoom level"; + fit: plain = "Fit slide to current window"; + } +} + +/// Shows slide position, language and transient status beside the view and zoom controls. pub fn status_bar(app: &mut SlideApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); - egui::Panel::bottom("status").exact_size(28.0).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| { - let rect = ui.max_rect(); - let Some(st) = app.session.active() else { return }; - let n = st.doc.slides.len(); - let left = match st.selection.target { - deckcraft_engine::Target::Slides => format!("Slide {} of {}", (st.selection.slide + 1).min(n.max(1)), n), - _ => "Slide Master".to_string(), - }; - let p = ui.painter(); - // Left to right: slide counter, language, status message. Each starts at its usual column, or - // after the one before it when that runs long ("Slide 100 of 120", "… (not checked)"). - let sr = p.text(pos2(rect.min.x + 14.0, rect.center().y), Align2::LEFT_CENTER, &left, theme::font(12.0), t.text_dim); - shown_text(ui, sr, "status_slide", &left); - // Where the controls on the right begin; nothing on the left paints or clicks past it. - let right_x = rect.max.x - 560.0; - // The selection's proofing language; a click opens Review › Language. - let (lang, no_proof) = crate::dialogs::selected_language(app); - let name = crate::squiggles::display_lang_name(ui.ctx(), &lang) + if no_proof { " (not checked)" } else { "" }; - let lx = (rect.min.x + 120.0).max(sr.max.x + 16.0); - let lclip = Rect::from_min_max(pos2(lx - 3.0, rect.min.y), pos2(right_x.max(lx - 3.0), rect.max.y)); - let lr = p.with_clip_rect(lclip).text(pos2(lx, rect.center().y), Align2::LEFT_CENTER, &name, theme::font(12.0), t.text_dim); - let hit = lr.expand(3.0).intersect(lclip); - if hit.is_positive() { - let resp = ui.interact(hit, ui.scope_id().with("status_lang"), Sense::click()).on_hover_text("Language"); - resp.widget_info(|| named_with_value("Language", &name)); - if resp.clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("language")); - } - } - // Transient status message, clipped before the controls on the right. - if let Some(msg) = app.fresh_status() { - let mx = (rect.min.x + 290.0).max(lr.max.x + 16.0); - let clip = Rect::from_min_max(pos2(mx, rect.min.y), pos2(right_x.max(mx), rect.max.y)); - let mr = p.with_clip_rect(clip).text(pos2(mx, rect.center().y), Align2::LEFT_CENTER, &msg, theme::font(12.0), t.accent); - shown_text(ui, mr.intersect(clip), "status_message", &msg); - ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); - } - let mut right = ui.new_child( - egui::UiBuilder::new() - .max_rect(Rect::from_min_max(pos2(right_x, rect.min.y), pos2(rect.max.x - 8.0, rect.max.y))) - .layout(egui::Layout::right_to_left(egui::Align::Center)), - ); - right.spacing_mut().item_spacing.x = 4.0; - if small_icon(&mut right, Icon::FitSmall, "Fit slide to current window", false).clicked() { - app.ui.zoom = None; - } - let pct = (app.canvas_scale * 100.0).round(); - let lbl = right.add(egui::Label::new(egui::RichText::new(format!("{pct}%")).size(12.0).color(t.text_dim)).sense(Sense::click())); - lbl.widget_info(|| named_with_value("Zoom level", &format!("{pct}%"))); - if lbl.clicked() { - let _ = app.run("view.zoomDialog", json!({})); - } - if small_icon(&mut right, Icon::ZoomIn, "Zoom In", false).clicked() { - let _ = app.run("view.zoomIn", json!({})); - } - // Slider 10%–400% (log scale). - let mut z = app.ui.zoom.unwrap_or(app.canvas_scale).clamp(0.1, 4.0); - let mut zp = z * 100.0; - // egui 0.37 gives a slider its own width and the theme's control height; ask for exactly - // those so the status row stays consistent with every other control without hard-coding - // a size the slider would override anyway. - let slider_size = vec2(right.spacing().slider_width, right.spacing().interact_size.y); - let s = right.add_sized(slider_size, egui::Slider::new(&mut zp, 10.0..=400.0).logarithmic(true).show_value(false)); - // The status bar has no room for a visible "Zoom" label; name the slider for assistive - // technology only, leaving its geometry unchanged. Its value is the percentage shown. - let shown = format!("{}%", zp.round()); - let enabled = s.enabled(); - s.widget_info(|| egui::WidgetInfo { current_text_value: Some(shown.clone()), ..egui::WidgetInfo::slider(enabled, f64::from(zp), "Zoom") }); - if s.changed() { - z = zp / 100.0; - app.ui.zoom = Some(z); - } - if small_icon(&mut right, Icon::ZoomOut, "Zoom Out", false).clicked() { - let _ = app.run("view.zoomOut", json!({})); - } - right.add_space(8.0); - let view = app.ui.view; - if view_icon(&mut right, Icon::ViewShowSmall, "Slide Show", false).clicked() { - let i = app.session.active().map(|d| d.selection.slide).unwrap_or(0); - app.start_show(i, false); - } - if view_icon(&mut right, Icon::ViewReadingSmall, "Reading View", view == ViewMode::Reading).clicked() { - let _ = app.run("view.reading", json!({})); - } - if view_icon(&mut right, Icon::ViewSorterSmall, "Slide Sorter", view == ViewMode::Sorter).clicked() { - app.ui.view = ViewMode::Sorter; - } - if view_icon(&mut right, Icon::ViewNormalSmall, "Normal", view == ViewMode::Normal).clicked() { - app.ui.view = ViewMode::Normal; - } - right.add_space(8.0); - let c_on = app.ui.pane.as_deref() == Some("comments"); - if labeled(&mut right, Icon::CommentsSmall, "Comments", c_on).clicked() { - let _ = app.run("view.pane", json!({"pane": "comments", "toggle": true})); - } - let n_on = app.ui.notes; - if labeled(&mut right, Icon::NotesSmall, "Notes", n_on).clicked() { - app.ui.notes = !n_on; - } - let _ = Stroke::NONE; - }); -} - -/// Draw a small status icon with a tooltip and return its interaction response. -fn small_icon(ui: &mut Ui, icon: Icon, tip: &str, on: bool) -> egui::Response { - let resp = icon_button(ui, icon, on); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - resp.on_hover_text(tip) -} - -/// A view button: screen readers hear its name and whether its view is the one shown. -fn view_icon(ui: &mut Ui, icon: Icon, tip: &str, on: bool) -> egui::Response { - let resp = icon_button(ui, icon, on); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, tip)); - resp.on_hover_text(tip) -} - -fn icon_button(ui: &mut Ui, icon: Icon, on: bool) -> egui::Response { - let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(26.0, 20.0), Sense::click()); - if on || resp.hovered() { - ui.painter().rect_filled(r, CornerRadius::same(4), if on { t.selected } else { t.hover }); - } - icons::paint(ui.painter(), Rect::from_center_size(r.center(), vec2(16.0, 16.0)), icon, t.text_dim, false); - resp -} - -/// A clickable status-bar text: screen readers hear `label` as its name and `text` as its value. -fn named_with_value(label: &str, text: &str) -> egui::WidgetInfo { - egui::WidgetInfo { current_text_value: Some(text.to_string()), ..egui::WidgetInfo::labeled(egui::Role::Button, true, label) } -} - -/// Painted status-bar text: screen readers read `text` from a label over `rect`. -fn shown_text(ui: &Ui, rect: Rect, id: &str, text: &str) { - if rect.is_positive() { - let resp = ui.interact(rect, ui.scope_id().with(id), Sense::hover()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); - } -} - -/// Draw a labelled status icon, painting the text directly and exposing the toggle state as its -/// accessible selected state. -fn labeled(ui: &mut Ui, icon: Icon, label: &str, on: bool) -> egui::Response { - let t = Tokens::get(ui.ctx()); - let w = 22.0 + ui.fonts_mut(|f| f.layout_no_wrap(label.into(), theme::font(12.0), t.text).size().x) + 8.0; - let (r, resp) = ui.allocate_exact_size(vec2(w, 20.0), Sense::click()); - if on || resp.hovered() { - ui.painter().rect_filled(r, CornerRadius::same(4), if on { t.selected } else { t.hover }); - } - icons::paint(ui.painter(), Rect::from_center_size(pos2(r.min.x + 11.0, r.center().y), vec2(15.0, 15.0)), icon, t.text_dim, false); - ui.painter().text(pos2(r.min.x + 22.0, r.center().y), Align2::LEFT_CENTER, label, theme::font(12.0), t.text_dim); - // The visible label is painted directly, so name the interactive control explicitly and - // expose the toggle state as selected: a screen reader hears "Notes, pressed" not "Notes". - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, label)); - resp -} - -/// The language of a slide's notes: the first notes run that has one. -fn notes_lang(s: &deckcraft_model::Slide) -> Option { - s.notes.paragraphs.iter().flat_map(|p| &p.runs).find_map(|r| r.props.lang.clone()) -} - -/// The speaker notes editor under the slide. -pub fn notes_pane(app: &mut SlideApp, ui: &mut Ui) { - let t = Tokens::get(ui.ctx()); + let env = Env::of(ui); + let words = env.words::(); let Some(st) = app.session.active() else { return }; - if st.selection.target != deckcraft_engine::Target::Slides { - return; - } - let (idx, uid) = (st.selection.slide, st.uid); - // Save an edited draft once the field has lost focus or another slide is shown (before - // anything reloads it), to the slide it was written on. - let id = egui::Id::unique("notes_edit"); - let focused = ui.ctx().memory(|m| m.has_focus(id)); - if app.notes_buf.2.edited && (!focused || app.notes_buf.0 != uid || app.notes_buf.1 != idx) { - app.notes_buf.2.edited = false; - if app.notes_buf.0 == uid { - let _ = app.run("slide.notes", json!({"body": app.notes_buf.2.body, "index": app.notes_buf.1})); - } - } - let notes = app.session.active().and_then(|st| st.current_slide()).map(|s| s.notes.clone()).unwrap_or_default(); - egui::Panel::bottom("notes") - .resizable(true) - .default_size(app.ui.notes_height) - .size_range(36.0..=400.0) - .frame(egui::Frame::NONE.fill(t.chrome).inner_margin(egui::Margin::symmetric(8, 6))) - .show(ui, |ui| { - app.ui.notes_height = ui.available_height() + 12.0; - let rect = ui.max_rect(); - ui.painter() - .line_segment([pos2(rect.min.x - 8.0, rect.min.y - 6.0), pos2(rect.max.x + 8.0, rect.min.y - 6.0)], Stroke::new(1.0, t.separator)); - // Keep a local draft per slide, following the notes while the field isn't focused. - if app.notes_buf.0 != uid || app.notes_buf.1 != idx || (!focused && app.notes_buf.2.body != notes) { - app.notes_buf = (uid, idx, crate::notes::Draft::new(¬es)); - } - let mut draft = app.notes_buf.2.clone(); - let look = crate::notes::Look { size: 13.0, color: None }; - // Long notes scroll inside the pane instead of spilling over the slide (#221). - let out = egui::ScrollArea::vertical() - .max_height(ui.available_height()) - .auto_shrink([false, false]) - .show(ui, |ui| { - crate::notes::editor(ui, &mut draft, &look, |e| { - e.id(id).hint_text("Click to add notes").frame(egui::Frame::NONE).desired_width(f32::INFINITY).desired_rows(2) - }) - }) - .inner; - let r = out.response.response.clone(); - let mut buf = draft.text.clone(); - // Spelling squiggles under misspelt words of the notes. - let lang = app.session.active().and_then(|d| d.doc.slides.get(idx)).and_then(|s| notes_lang(s)).unwrap_or_else(|| "en-US".into()); - let caret = out.cursor_range.map(|c| c.primary.index.0); - for (a, b) in app.squiggles.notes(&buf, &lang, caret, Some(ui.ctx())) { - let (ra, rb) = (out.galley.pos_from_cursor(egui::text::CCursor::new(a)), out.galley.pos_from_cursor(egui::text::CCursor::new(b))); - // One underline per row the word is on (a word doesn't wrap, so normally one). - if (ra.bottom() - rb.bottom()).abs() < 1.0 { - let y = ra.bottom() - 1.0; - let o = out.galley_pos.to_vec2(); - crate::squiggles::paint(ui.painter(), egui::pos2(ra.left(), y) + o, egui::pos2(rb.left(), y) + o, 1.0); - } - } - // Right-click on a flagged word: its corrections, Ignore All, Add to Dictionary. - if r.secondary_clicked() - && let Some(pos) = r.interact_pointer_pos() - { - let at = out.galley.cursor_from_pos(pos - out.galley_pos).index.0; - let hit = app.squiggles.notes(&buf, &lang, None, None).into_iter().find(|(a, b)| at >= *a && at <= *b); - app.squiggles.notes_menu = hit.and_then(|(a, _)| { - let before: String = buf.chars().take(a).collect(); - let line_start = before.rfind('\n').map_or(0, |i| before[..i].chars().count() + 1); - let line = buf.chars().skip(line_start).take_while(|c| *c != '\n').collect::(); - crate::squiggles::menu_word( - &deckcraft_model::Paragraph::new(&line), - &lang, - crate::squiggles::Tag::Notes { start: line_start }, - a - line_start, - ) - }); - } - let mut changed: Option = None; - if app.squiggles.notes_menu.is_some() { - r.context_menu(|ui| { - let Some(w) = app.squiggles.notes_menu.clone() else { return }; - let crate::squiggles::Tag::Notes { start: ls } = w.tag else { return }; - let chars: Vec = buf.chars().collect(); - let end = ls + w.start + w.word.chars().count(); - let splice = |from: usize, to: &str| -> String { - chars[..from.min(chars.len())] - .iter() - .chain(to.chars().collect::>().iter()) - .chain(chars[end.min(chars.len())..].iter()) - .collect() - }; - if let Some(from) = w.delete_from { - if ui.button(egui::RichText::new("Delete Repeated Word").strong()).clicked() { - changed = Some(splice(ls + from, "")); - ui.close(); - } - } else if w.suggestions.is_empty() { - ui.label(egui::RichText::new("(no spelling suggestions)").weak()); - } - for to in &w.suggestions { - if ui.button(egui::RichText::new(to).strong()).clicked() { - changed = Some(splice(ls + w.start, to)); - ui.close(); - } - } - if ui.button("Ignore All").clicked() { - app.squiggles.ignore(&w.word); - ui.close(); - } - if w.delete_from.is_none() && ui.button("Add to Dictionary").clicked() { - if let Err(e) = app.session.execute("review.addToDictionary", &json!({"word": w.word})) { - app.set_status(e.to_string()); - } - ui.close(); - } - }); - } - if let Some(new) = changed { - // A correction is typed into the formatted draft, then saved. - buf = new; - app.squiggles.notes_menu = None; - draft.text = buf.clone(); - deckcraft_model::edit::replace_text(&mut draft.body, &buf); - draft.edited = false; - let _ = app.run("slide.notes", json!({"body": draft.body, "index": idx})); - } - if r.lost_focus() && draft.edited { - draft.edited = false; - let _ = app.run("slide.notes", json!({"body": draft.body, "index": idx})); - } - app.notes_buf.2 = draft; - }); -} - -#[cfg(test)] -mod tests { - #![allow(clippy::unwrap_used, clippy::expect_used)] - - use deckcraft_engine::Session; - use egui::accesskit::{Role, Toggled}; - use egui::{Event, Modifiers, PointerButton}; - use egui_kittest::{ - Harness, - kittest::{NodeT, Queryable}, + let count = st.doc.slides.len(); + let counter = if st.selection.target == deckcraft_engine::Target::Slides { + words + .slide_count + .fill(&[ + ("slide", &env.format().integer((st.selection.slide + 1).min(count.max(1)) as u64)), + ("count", &env.format().integer(count as u64)), + ]) + .into() + } else { + words.slide_master.clone() }; - use serde_json::json; - - use crate::{Services, SlideApp, ViewMode}; - - /// A long proofing language in a narrow window must not take clicks meant for the controls on - /// the right: Notes toggles the notes pane and the Language dialog stays closed. - #[test] - fn a_long_language_name_leaves_the_notes_button_clickable() { - // P3(panels-w7): sh.A2 - let mut app = SlideApp::new_base(Session::with_new(), Services::default()); - app.session.execute("shape.insert", &json!({"preset": "rect", "rect": [80, 120, 400, 100], "text": "hello"})).unwrap(); - app.session.execute("format.language", &json!({"lang": "en-US-x-a-very-long-private-use-tag"})).unwrap(); - app.ui.notes = false; - let size = egui::vec2(700.0, 800.0); - let mut h = Harness::builder().with_size(size).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(3); - assert!(!h.state().ui.notes); - { - let mut notes = h.query_all_by_role_and_label(Role::Button, "Notes"); - let button = notes.next().expect("the Notes button is there"); - assert!(notes.next().is_none(), "exactly one Notes button, not a duplicated label target"); - assert_eq!(button.accesskit_node().toggled(), Some(Toggled::False), "the Notes button reports its off state to screen readers"); - } - // The controls on the right start 560 points from the bar's right edge, which is 8 points - // inside the window (x 132); the Notes button is the leftmost of them. Its position depends - // on the interface font's widths, so the clicks use the position it was laid out at. - let right_x = size.x - 8.0 - 560.0; - let notes = h.get_by_label("Notes").rect(); - assert!(notes.left() > right_x + 2.0, "the Notes button ({notes:?}) starts after x {right_x}"); - let click = |h: &mut Harness<'_, SlideApp>, at: egui::Pos2| { - h.hover_at(at); - h.run_steps(1); - for pressed in [true, false] { - h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + let document = Size::new(st.doc.slide_size.width, st.doc.slide_size.height); + let (lang, no_proof) = crate::dialogs::selected_language(app); + let language = crate::squiggles::display_lang_name(ui.ctx(), &lang); + let language = if no_proof { words.language_unchecked.fill(&[("language", &language)]) } else { language }; + let message = app.fresh_status().map(str::to_owned); + let mut open_language = false; + Bar::new(words.status_bar.clone(), BarKind::Status) + .trailing(|ui, _| { + let env = Env::of(ui); + controls(app, ui, &env, &words, document); + }) + .show(ui, |ui, _| { + Text::new(counter.clone()).shade(Shade::Muted).show(ui); + let link = with_env( + ui, + |scope| { + scope.values.set(LinkLook::Plain); + }, + |ui| Link::new(language.clone()).tooltip(words.language.clone()).show(ui), + ); + open_language |= link.clicked(); + if let Some(message) = &message { + StatusMessage::new(message.clone()).show(ui); + ui.ctx().request_repaint_after(std::time::Duration::from_millis(500)); } - h.run_steps(3); - }; - // The gap before the controls is outside the language name's clickable area. - click(&mut h, egui::pos2((right_x + notes.left()) / 2.0, notes.center().y)); - assert!(h.state().dialog.is_none(), "the Language dialog stayed closed"); - assert!(!h.state().ui.notes, "the click in the gap did not reach the Notes button"); - click(&mut h, notes.center()); - assert!(h.state().ui.notes, "the click reached the Notes button"); - assert_eq!( - h.get_by_role_and_label(egui::Role::Button, "Notes").accesskit_node().toggled(), - Some(Toggled::True), - "the open notes pane is exposed as a pressed Notes button" - ); - assert!(h.state().dialog.is_none(), "the Language dialog stayed closed"); - } - - /// Screen readers find each status-bar control by name, hear the language and zoom it shows, - /// hear which view button is on, and read the slide counter and the status message. - #[test] - fn status_bar_controls_have_names() { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - // P3(panels-w7): sh.A2 - SlideApp::new_base(Session::with_new(), Services::default()), - ); - h.run_steps(3); - let status_y = h.get_by_role_and_label(Role::Button, "Fit slide to current window").rect().center().y; - for name in ["Fit slide to current window", "Zoom In", "Zoom Out", "Slide Show", "Reading View"] { - // The ribbon also has a "Slide Show" control. Require exactly one named button - // in the Fit button's laid-out status row, allowing the app's UI zoom. - let buttons = h.get_all_by_role_and_label(Role::Button, name).filter(|n| n.rect().y_range().contains(status_y)).count(); - assert_eq!(buttons, 1, "one {name} button in the status bar"); - } - let pct = format!("{}%", (h.state().canvas_scale * 100.0).round()); - assert_eq!(h.get_by_role_and_label(Role::Button, "Zoom level").value().as_deref(), Some(pct.as_str())); - let zoom = h.get_by_role_and_label(Role::Slider, "Zoom"); - assert_eq!(zoom.value().as_deref(), Some(pct.as_str())); - // Its number and range are in percent, as the value text is. - let node = zoom.accesskit_node(); - assert_eq!(node.numeric_value().map(f64::round), Some((h.state().canvas_scale * 100.0).round().into())); - assert_eq!((node.min_numeric_value(), node.max_numeric_value()), (Some(10.0), Some(400.0))); - assert_eq!(h.get_by_role_and_label(Role::Button, "Language").value().as_deref(), Some("English (United States)")); - let toggled = |h: &Harness<'_, SlideApp>, name: &str| h.get_by_role_and_label(Role::Button, name).accesskit_node().toggled(); - assert_eq!(toggled(&h, "Normal"), Some(Toggled::True)); - assert_eq!(toggled(&h, "Slide Sorter"), Some(Toggled::False)); - h.get_by_role_and_label(Role::Button, "Slide Sorter").click(); - h.run_steps(3); - assert_eq!(h.state().ui.view, ViewMode::Sorter, "the click by name reached the Slide Sorter button"); - assert_eq!(toggled(&h, "Slide Sorter"), Some(Toggled::True)); - assert_eq!(toggled(&h, "Normal"), Some(Toggled::False)); - assert_eq!(toggled(&h, "Reading View"), Some(Toggled::False)); - h.state_mut().ui.view = ViewMode::Reading; - h.run_steps(3); - assert_eq!(toggled(&h, "Reading View"), Some(Toggled::True)); - assert_eq!(toggled(&h, "Slide Sorter"), Some(Toggled::False)); - assert_eq!(h.get_by_value("Slide 1 of 1").accesskit_node().role(), Role::Label); - h.state_mut().set_status("Saved a copy"); - h.run_steps(3); - assert_eq!(h.get_by_value("Saved a copy").accesskit_node().role(), Role::Label); + }); + if open_language { + app.open_dialog("language", json!({})); } } + +fn controls(app: &mut SlideApp, ui: &mut Ui, env: &Env, words: &StatusWords, document: Size) { + // PLAN: plan error: ribbon-w3 must publish checked view.notes and view.pane {pane: comments, toggle: true} states + ToggleButton::command("view.notes").label(words.notes.clone()).icon(Icon::NotesSmall.id()).show(ui); + ToggleButton::command(CommandRef::with_params("view.pane", json!({"pane": "comments", "toggle": true}))) + .label(words.comments.clone()) + .icon(Icon::CommentsSmall.id()) + .show(ui); + Divider::vertical().show(ui); + let entries = [ + Entry::new(ViewMode::Normal, words.normal.clone()).icon(Icon::ViewNormalSmall.id()), + Entry::new(ViewMode::Sorter, words.sorter.clone()).icon(Icon::ViewSorterSmall.id()), + Entry::new(ViewMode::Reading, words.reading.clone()).icon(Icon::ViewReadingSmall.id()), + ]; + let views = Segmented::new(words.views.clone(), Bind::given(app.ui.view), &entries).show(ui); + if let Some(view) = views.value() { + let command = match view { + ViewMode::Normal => Some("view.normal"), + ViewMode::Sorter => Some("view.sorter"), + ViewMode::Reading => Some("view.reading"), + _ => None, + }; + if let Some(command) = command { + let _ = app.run(command, json!({})); + } + } + IconButton::command(Icon::ViewShowSmall.id(), "show.fromCurrent").label(words.slide_show.clone()).show(ui); + Divider::vertical().show(ui); + IconButton::command(Icon::ZoomOut.id(), "view.zoomOut").label(words.zoom_out.clone()).show(ui); + let scheme = env.view().get::(); + let pixels = f64::from(env.scale.0); + // PLAN: assumed SlideApp::canvas_scale(&self) -> f32 (canvas-w6) + let device = f64::from(app.canvas_scale()) * pixels; + let percent = scheme.percent(device); + let range = scheme.percent(scheme.min(document).min(device))..=scheme.percent(scheme.max_device().max(device)); + let slider = Slider::new(Bind::given(percent), range) + .scale(SliderScale::Log) + .label(words.zoom.clone()) + .value_text(env.units().zoom_percent(percent)) + .show(ui); + if let Some(percent) = slider.events.landed() { + let device = scheme.clamp(scheme.device(*percent), document); + app.ui.zoom = Some((device / pixels) as f32); + } + IconButton::command(Icon::ZoomIn.id(), "view.zoomIn").label(words.zoom_in.clone()).show(ui); + let field = ZoomField::new(words.zoom_level.clone(), Some(app.canvas_view), document).show(ui); + if let Some(view) = field.view.landed() { + app.canvas_view = *view; + app.ui.zoom = Some(view.zoom as f32); + } + if let Some(invalid) = field.invalid_zoom { + app.set_status(invalid.message(env)); + } + IconButton::command(Icon::FitSmall.id(), "view.fit").label(words.fit.clone()).show(ui); +}