Compare commits

..
Author SHA1 Message Date
Martin BallandClaude Sonnet 5.5 4af551c178 Fix #7149 item 5: a second window drew its interface 32768 points tall
DocumentWindow\x27s fallback overlay scrolls its body by default, so the whole
interface was laid out in an unbounded-height scroll region and landed off
the window. The window opens with body_scroll(false).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-20 16:08:10 +00:00
48 changed files with 103 additions and 1282 deletions
+2 -10
View File
File diff suppressed because one or more lines are too long
+2 -7
View File
@@ -118,13 +118,8 @@ impl ResolvedChar {
font_cs: c.font_cs.clone().or_else(|| c.font.clone()).unwrap_or_else(|| crate::styles::BODY_FONT.to_string()),
font_ea: c.font_ea.clone(),
size_cs: c.size_cs.or(c.size).unwrap_or(crate::props::DEFAULT_FONT_SIZE).clamp(1.0, 1638.0),
// A run marked complex script (`w:cs`) is bold and italic only by `w:bCs` and `w:iCs`:
// Word draws Thai with `<w:b/><w:cs/>` and no `w:bCs` upright and plain (measured in
// Word for Windows). Other runs, including those no DOCX marked, still borrow the
// Latin values. The size keeps borrowing `w:sz` until generated styles carry a
// `w:szCs` (#4197).
bold_cs: c.bold_cs.or(c.bold.filter(|_| c.cs != Some(true))).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic.filter(|_| c.cs != Some(true))).unwrap_or(false),
bold_cs: c.bold_cs.or(c.bold).unwrap_or(false),
italic_cs: c.italic_cs.or(c.italic).unwrap_or(false),
}
}
/// The formatting complex-script text in this run is drawn with: the complex-script font,
@@ -142,34 +142,6 @@ fn complex_script_direct_properties_leave_latin_defaults_inherited() {
});
}
#[test]
fn complex_script_runs_take_bold_and_italic_only_from_bcs_and_ics() {
// Word draws Thai marked `w:cs` with `<w:b/><w:i/>` and no `w:bCs`/`w:iCs` neither bold nor
// italic, through a style too; a run not marked `w:cs`, as older writers leave Hebrew, still
// borrows the Latin values (Word draws such Hebrew bold). The Latin text of every run keeps
// `w:b` and `w:i`. Measured in Word for Windows.
let styles = r#"
<w:style w:type="paragraph" w:styleId="LatinBold"><w:name w:val="LatinBold"/><w:rPr><w:b/><w:i/></w:rPr></w:style>
<w:style w:type="paragraph" w:styleId="BothBold"><w:name w:val="BothBold"/><w:rPr><w:bCs/><w:iCs/></w:rPr></w:style>"#;
let cases = [
(r#"<w:b/><w:i/><w:cs/>"#, "", false),
(r#"<w:cs/>"#, r#"<w:pStyle w:val="LatinBold"/>"#, false),
(r#"<w:b/><w:i/><w:cs/>"#, r#"<w:pStyle w:val="BothBold"/>"#, true),
(r#"<w:b/><w:bCs/><w:i/><w:iCs/><w:cs/>"#, "", true),
(r#"<w:b/><w:i/>"#, "", true),
];
for (run, style, complex) in cases {
check_generations(&package(run, "", styles, style), |d| {
let p = paragraph(d);
let c = d.styles.resolve_char(p.props.style.as_deref(), &p.runs[0].props);
let cs = c.complex();
assert_eq!((cs.bold, cs.italic), (complex, complex), "{run} {style}");
let latin = run.contains("<w:b/>") || style.contains("LatinBold");
assert_eq!((c.bold, c.italic), (latin, latin), "Latin text: {run} {style}");
});
}
}
#[test]
fn tracked_formatting_keeps_independent_complex_script_values() {
let defaults = r#"<w:szCs w:val="36"/><w:bCs/><w:iCs/>"#;
-10
View File
@@ -376,12 +376,6 @@ pub fn type_text_with_lang(s: &mut Session, text: &str, language: Option<&str>)
/// right-to-left direction when its first strong letter is RTL, and returns whether content or state
/// changed.
fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>) -> Result<InsertEffect, CmdError> {
// Formatting Backspace carried over is for typing at the place it was deleted (#6518).
if enter {
s.drop_stale_carried();
} else {
s.forget_carried();
}
let mut props = s.typing_props();
if s.sel.is_collapsed() {
s.sel = crate::Selection::caret(s.doc.past_field_ends(&s.sel.focus));
@@ -443,10 +437,6 @@ fn insert_text(s: &mut Session, text: &str, enter: bool, language: Option<&str>)
}
}
}
// Formatting Backspace carried over goes on applying to the text typed after this (#6518).
if s.pending_at.is_some() {
s.pending_at = Some(at.clone());
}
s.sel = crate::Selection::caret(at);
s.goal_x = None;
let content_changed = deletion.content_changed || inserted;
+1 -7
View File
@@ -155,20 +155,14 @@ fn style_set(s: &mut Session, v: &Value) -> CmdResult {
match name {
"basic" if heading => {
st.chr.color = Some(TextColor::Rgb(Rgb(0x26, 0x26, 0x26)));
// Both scripts, as Word's own heading styles carry `w:b` with `w:bCs`: a Thai
// heading in a run marked `w:cs` is drawn bold too.
st.chr.bold = Some(true);
st.chr.bold_cs = Some(true);
}
"lines" if st.id == "Heading1" || st.id == "Title" => st.para.borders = Some(Borders { bottom: Some(line), ..Default::default() }),
"shaded" if st.id == "Heading1" => {
st.para.shading = Some(accent);
st.chr.color = Some(TextColor::Rgb(Rgb::WHITE));
}
"casual" if heading => {
st.chr.italic = Some(true);
st.chr.italic_cs = Some(true);
}
"casual" if heading => st.chr.italic = Some(true),
"centered" if heading => st.para.align = Some(wordcraft_doc::Align::Center),
"minimalist" if heading => {
st.chr.caps = Some(true);
+5 -20
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
shown_bold,
|r| r.bold,
|c, on| {
c.bold = Some(on);
c.bold_cs = Some(on);
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
toggle(
s,
v,
shown_italic,
|r| r.italic,
|c, on| {
c.italic = Some(on);
c.italic_cs = Some(on);
@@ -281,10 +281,7 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
return out;
}
}
// Formatting waiting at a caret is what the caret shows, also inside a word: after Backspace
// it is the deleted character's (#6518), as Word's buttons show it.
let waiting = s.sel.is_collapsed() && s.waiting().is_some();
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)).filter(|_| !waiting) else {
let Some((a, b)) = selected_text_box(s).or_else(|| target(s)) else {
let f = &s.sel.focus;
let style = s.doc.para_at(f).and_then(|p| p.props.style.clone());
out.push(s.doc.styles.resolve_char(style.as_deref(), &s.typing_props()));
@@ -313,18 +310,6 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Bold as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script bold.
fn shown_bold(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.bold_cs } else { r.bold }
}
/// Italic as drawn: a run marked complex script (`w:cs`) or right to left (`w:rtl`) shows its
/// complex-script italic.
fn shown_italic(r: &ResolvedChar) -> bool {
if r.cs || r.rtl { r.italic_cs } else { r.italic }
}
fn toggle(s: &mut Session, v: &Value, get: fn(&ResolvedChar) -> bool, set: fn(&mut CharProps, bool)) -> CmdResult {
let on = match p::bool(v, "value") {
Some(b) => b,
@@ -902,8 +887,8 @@ pub fn state(s: &Session) -> Value {
"fontShownAs": shown_as,
"fontEastAsia": same(&|r| json!(r.font_ea)),
"size": same(&|r| json!(r.size)),
"bold": all.iter().all(shown_bold),
"italic": all.iter().all(shown_italic),
"bold": all.iter().all(|r| r.bold),
"italic": all.iter().all(|r| r.italic),
"underline": all.iter().all(|r| r.underline != Underline::None),
"underlineColor": same(&|r| json!(r.underline_color.map_or_else(|| "auto".to_string(), |c| c.hex()))),
"strike": all.iter().all(|r| r.strike),
+1 -1
View File
@@ -114,7 +114,7 @@ fn place_picture(s: &mut Session, bytes: Vec<u8>, width: Option<f32>, alt: &str)
Err(wordcraft_geom::picture::Refusal::Unsupported(why)) => return Err(CmdError::Failed(why.into())),
Err(_) => match wordcraft_render::metafile_size(&bytes) {
Some(size) => size,
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, TIFF, WMF, EMF)".into())),
None => return Err(CmdError::Failed("not a supported image (PNG, JPEG, GIF, WebP, BMP, WMF, EMF)".into())),
},
};
let key = s.doc.add_media(bytes, ext);
+2 -17
View File
@@ -281,14 +281,6 @@ pub enum Pasted {
/// that knows another program owns the clipboard passes `privateClipboard: false`, which keeps
/// the fragment out even when the text matches.
pub fn paste_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let pasted = clipboard_content(s, v)?;
// Formatting Backspace carried over is for typing, not for what is pasted (#6518). An empty
// clipboard pastes nothing, so it stays.
s.forget_carried();
Ok(pasted)
}
fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
if owns_clipboard(v)
&& let Some(f) = &s.clipboard
@@ -338,16 +330,11 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
p.props = para.clone();
for run in &mut p.runs {
let src = std::mem::replace(&mut run.props, base.clone());
// Emphasis in either script is kept for both, as the Bold and Italic buttons set
// it: text pasted into a run marked `w:cs` (Thai from a WPS or Word file) is drawn
// with the complex-script bold and italic.
if src.bold == Some(true) || src.bold_cs == Some(true) {
if src.bold == Some(true) {
run.props.bold = Some(true);
run.props.bold_cs = Some(true);
}
if src.italic == Some(true) || src.italic_cs == Some(true) {
if src.italic == Some(true) {
run.props.italic = Some(true);
run.props.italic_cs = Some(true);
}
if src.underline.is_some_and(|u| u != wordcraft_doc::props::Underline::None) {
run.props.underline = src.underline;
@@ -367,8 +354,6 @@ pub fn merge_formatting(s: &Session, frag: &mut Fragment) {
/// Replace the selection with `frag`, marking it as an insertion under Track Changes.
pub fn insert(s: &mut Session, mut frag: Fragment) -> Result<(), CmdError> {
// The pasted text keeps its own formatting; what Backspace carried over is not for after it (#6518).
s.forget_carried();
super::controls::prepare_edit(s)?;
let at = delete_selection(s)?;
let track = s.doc.settings.track_changes;
+4 -48
View File
@@ -1,17 +1,9 @@
use super::enter_tab::tab_indent_on;
use super::{
Block, COLUMN_BREAK, CmdResult, NumRef, OBJ, PAGE_BREAK, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect,
sel_result,
};
use super::{Block, CmdResult, NumRef, OBJ, Pos, Selection, Session, StoryRef, Value, delete_selection, delete_selection_effect, sel_result};
pub(super) fn backspace(s: &mut Session, v: &Value) -> CmdResult {
let r = backspace_inner(s, v)?;
crate::cmd::controls::restore_placeholder(s)?;
// A content control's placeholder is back: typing replaces it, so nothing is carried.
if s.doc.control_at(&s.sel.focus).is_some_and(|r| r.control.showing_placeholder) {
s.pending = None;
s.pending_at = None;
}
Ok(r)
}
@@ -37,32 +29,9 @@ fn remove_number(s: &mut Session, f: &Pos, n: NumRef) -> CmdResult {
sel_result(s)
}
/// The formatting Backspace carries over from the character between `a` and `f` (#6518): only an
/// ordinary character, not an object, field or anchor marker or a page or column break. With Track
/// Changes on it carries too, as in Word: the character stays, marked deleted (or goes, when this
/// author inserted it), and the caret sits before it. Cleaned up the way the caret's own
/// formatting is: no hyperlink, symbol font, note-number style or revision marks, so typed text
/// gets its own insertion mark and never the deletion.
fn deleted_char_props(s: &Session, a: &Pos, f: &Pos) -> Option<wordcraft_doc::props::CharProps> {
let p = s.doc.para_at(f)?;
let text = p.text.get(a.off..f.off).filter(|t| !t.is_empty())?;
if text.contains([OBJ, PAGE_BREAK, COLUMN_BREAK]) {
return None;
}
let mut props = p.props_of_char(a.off).unlinked().without_symbol();
if matches!(props.style.as_deref(), Some("FootnoteReference" | "EndnoteReference")) {
props.style = None;
}
props.ins = None;
props.del = None;
props.fmt_change = None;
Some(props)
}
fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
s.goal_x = None;
// Kept for a Backspace that changes nothing, which leaves Word's carried formatting alone.
let kept = (s.pending.take(), s.pending_at.take());
s.pending = None;
if !s.sel.is_collapsed() {
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
@@ -90,8 +59,7 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
if let Some(c) = s.autocap.as_mut() {
c.note_backspace(&a, &f);
}
let carried = deleted_char_props(s, &a, &f);
s.sel = Selection { anchor: a.clone(), focus: f };
s.sel = Selection { anchor: a, focus: f };
let effect = delete_selection_effect(s)?;
s.set_ime_edit_outcome(crate::ImeEditOutcome {
classified: true,
@@ -100,12 +68,6 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
transformed: false,
selection_changed: false,
});
// As in Word, text typed next takes the deleted character's formatting until the caret
// moves (#6518): it applies here only, so whatever puts the caret elsewhere drops it.
if effect.content_changed && s.sel.is_collapsed() && s.sel.focus == a {
s.pending_at = carried.as_ref().map(|_| a.clone());
s.pending = carried;
}
return sel_result(s);
}
// At the start of a paragraph.
@@ -131,10 +93,7 @@ fn backspace_inner(s: &mut Session, _: &Value) -> CmdResult {
}
let i = f.path.last();
if i == 0 {
// Start of a story or cell: nothing changes, so formatting waiting at the caret (carried
// from a deleted character, or set there) still applies to the next typed text (Word).
(s.pending, s.pending_at) = kept;
return sel_result(s);
return sel_result(s); // start of a story or cell
}
let prev_path = f.path.with_last(i - 1);
match s.doc.block(f.story, &prev_path) {
@@ -257,9 +216,6 @@ pub(super) fn delete_word_back(s: &mut Session, v: &Value) -> CmdResult {
return backspace(s, v);
}
let a = Pos { off: para.word_start(f.off), ..f.clone() };
// Formatting a Backspace just carried over belongs to that deletion, not this one.
s.pending = None;
s.pending_at = None;
s.sel = Selection { anchor: a, focus: f };
delete_selection(s)?;
crate::cmd::controls::restore_placeholder(s)?;
-2
View File
@@ -126,8 +126,6 @@ pub(super) struct Undo {
pub(super) sel: Selection,
/// Formatting waiting at the caret (Bold with nothing selected), so Undo takes it back too.
pub(super) pending: Option<CharProps>,
/// Where that formatting applies, if Backspace carried it over (`Session::pending_at`).
pub(super) pending_at: Option<Pos>,
/// The column block or whole cells the selection was (undoing brings the selection back as
/// it was).
pub(super) column: Option<ColumnBlock>,
-5
View File
@@ -51,11 +51,6 @@ pub struct Session {
pub view: ViewState,
/// Formatting picked with a collapsed caret, applied to the next typed text.
pub pending: Option<CharProps>,
/// Where the caret was when Backspace carried [`Self::pending`] over from the character it
/// deleted (#6518), moved on as typing advances the caret. That formatting is for typing
/// there only: once the caret is anywhere else (a paste, Find, Go To or a click put it
/// there) it is dropped (see [`Self::waiting`]). `None` for formatting picked at the caret.
pub(crate) pending_at: Option<Pos>,
/// Last highlighter choice for the shortcut; palette state, outside document undo.
pub(crate) last_highlight: wordcraft_doc::props::Highlight,
pub path: Option<std::path::PathBuf>,
-5
View File
@@ -43,7 +43,6 @@ pub struct DocState {
pub(super) sel: Selection,
pub(super) view: ViewState,
pub(super) pending: Option<CharProps>,
pub(super) pending_at: Option<Pos>,
pub(super) path: Option<PathBuf>,
pub(super) file_name: Option<String>,
pub(super) dirty: bool,
@@ -100,7 +99,6 @@ impl DocState {
sel: Selection::caret(start),
view,
pending: None,
pending_at: None,
path: None,
file_name: None,
dirty: false,
@@ -204,7 +202,6 @@ impl Session {
sel: _,
view: _,
pending: _,
pending_at: _,
path: _,
file_name: _,
dirty: _,
@@ -306,7 +303,6 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -356,7 +352,6 @@ impl Session {
swap(&mut self.sel, sel);
swap(&mut self.view, view);
swap(&mut self.pending, pending);
swap(&mut self.pending_at, pending_at);
swap(&mut self.path, path);
swap(&mut self.file_name, file_name);
swap(&mut self.dirty, dirty);
+1 -11
View File
@@ -14,7 +14,6 @@ impl Session {
doc: self.doc.clone(),
sel: self.sel.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: self.column.clone(),
}));
if self.history.len() > MAX_UNDO {
@@ -35,14 +34,7 @@ impl Session {
/// Record `doc`/`sel` as their own undo step after the fact and close the typing group, so
/// Undo right after an automatic change (AutoFormat, AutoCorrect) reverts only that change.
pub fn push_undo(&mut self, label: &str, doc: Document, sel: Selection) {
self.history.push(Arc::new(Undo {
label: label.to_string(),
doc,
sel,
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
column: None,
}));
self.history.push(Arc::new(Undo { label: label.to_string(), doc, sel, pending: self.pending.clone(), column: None }));
if self.history.len() > MAX_UNDO {
self.history.remove(0);
self.undo_evicted += 1;
@@ -218,7 +210,6 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.redo.push(Arc::new(cur));
@@ -245,7 +236,6 @@ impl Session {
doc: std::mem::replace(&mut self.doc, u.doc),
sel: std::mem::replace(&mut self.sel, u.sel),
pending: std::mem::replace(&mut self.pending, u.pending),
pending_at: std::mem::replace(&mut self.pending_at, u.pending_at),
column: std::mem::replace(&mut self.column, u.column),
};
self.history.push(Arc::new(cur));
-2
View File
@@ -41,7 +41,6 @@ impl Session {
sel,
view,
pending,
pending_at,
path,
file_name,
dirty,
@@ -92,7 +91,6 @@ impl Session {
sel,
view,
pending,
pending_at,
last_highlight: wordcraft_doc::props::Highlight::Yellow,
path,
file_name,
+2 -42
View File
@@ -225,7 +225,7 @@ impl Session {
pub fn typing_props(&self) -> CharProps {
let (a, _) = self.sel.ordered();
let first = match self.doc.para_at(&a) {
Some(p) if self.waiting().is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
Some(p) if self.pending.is_none() && !self.sel.is_collapsed() && a.off < p.len() => Some(p.props_of_char(a.off)),
_ => None,
};
let mut c = match first {
@@ -243,49 +243,9 @@ impl Session {
c
}
/// The formatting waiting for the next typed text ([`Self::pending`]), unless Backspace
/// carried it over at a place the caret has since left, or a selection now stands there:
/// that formatting is for typing where the character was deleted only (#6518).
pub fn waiting(&self) -> Option<&CharProps> {
let p = self.pending.as_ref()?;
match &self.pending_at {
Some(at) if !self.sel.is_collapsed() || self.sel.focus != *at => None,
_ => Some(p),
}
}
/// Forget formatting Backspace carried over once it no longer applies ([`Self::waiting`]):
/// whatever moved the caret or selected text — a paste, Find, Go To, a click — leaves the
/// next typed text the formatting of where it lands, as in Word (#6518).
pub(crate) fn drop_stale_carried(&mut self) {
if self.pending.is_none() {
self.pending_at = None;
} else if self.pending_at.is_some() && self.waiting().is_none() {
self.pending = None;
self.pending_at = None;
}
}
/// Move the caret or select text without a command, as a front end does for a right-click,
/// a click into a header or a balloon. Formatting Backspace carried over stays only if the
/// caret is still where the character was deleted: once it has been anywhere else, coming
/// back does not bring it back (#6518). Assigning [`Self::sel`] directly skips this.
pub fn set_selection(&mut self, sel: Selection) {
self.sel = sel;
self.drop_stale_carried();
}
/// Drop formatting Backspace carried over, wherever the caret is: it is for typing, and a
/// paste is not typing, so pasted text takes the formatting where it lands (#6518).
pub(crate) fn forget_carried(&mut self) {
if self.pending_at.take().is_some() {
self.pending = None;
}
}
/// The caret's formatting, as Reveal Formatting shows it.
pub fn caret_props(&self) -> CharProps {
if let Some(p) = self.waiting() {
if let Some(p) = &self.pending {
return p.clone();
}
let f = &self.sel.focus;
+1 -29
View File
@@ -70,22 +70,7 @@ impl Session {
{
crate::cmd::md_source::before_command(self, id, mutates)?;
}
// Formatting Backspace carried over is for typing where the character was deleted: a
// caret the front end moved itself (a click elsewhere) has left it behind (#6518).
self.drop_stale_carried();
let carried_before = self.pending_at.clone().map(|at| (self.pending.clone(), at));
// The formatting waiting at the caret is not part of the document snapshot a failed
// command is rolled back to: put it back here, so a refused edit (a Backspace into a
// locked content control) leaves it as it was.
let document_before = self.document_id;
let waiting_before = (self.pending.clone(), self.pending_at.clone());
let result = self.run_command(id, params);
if result.is_ok() {
self.settle_carried(carried_before);
} else if self.document_id == document_before {
(self.pending, self.pending_at) = waiting_before;
}
result
self.run_command(id, params)
}
/// Dispatches `id` through the command registry with transactional rollback on failure,
@@ -317,19 +302,6 @@ impl Session {
result
}
/// After a command, formatting Backspace carried over stays only where typing would use it
/// (#6518). One the command left alone is dropped if the caret is elsewhere now (a paste,
/// Find, Go To); one it changed (Bold, a hyperlink's end) is for the caret it left.
fn settle_carried(&mut self, before: Option<(Option<CharProps>, Pos)>) {
if let Some((pending, at)) = before
&& self.pending_at.as_ref() == Some(&at)
&& self.pending != pending
{
self.pending_at = Some(self.sel.focus.clone());
}
self.drop_stale_carried();
}
fn finish_success(&mut self, context: SuccessContext<'_>) {
let SuccessContext {
id,
+3 -11
View File
@@ -23,7 +23,6 @@ impl Session {
self.math = None;
self.sel = Selection::caret(self.doc.start_of(StoryRef::Body));
self.pending = None;
self.pending_at = None;
self.typing = None;
self.also_selected.clear();
self.member = None;
@@ -52,7 +51,7 @@ impl Session {
/// A snapshot to put back with [`Session::restore`], for a caller that runs a command and
/// may want to take it back without a trace (cheap: the document's blocks are shared).
///
/// Covered: `doc`, `sel`, `pending` with `pending_at`, the undo stack (its length, and its oldest steps when it is near
/// Covered: `doc`, `sel`, the undo stack (its length, and its oldest steps when it is near
/// the limit), `redo`, the open typing group, the pending `join_next_undo`,
/// `join_next_equation_edit` and body replacement promises, whether the typing group has a
/// step of its own, and `dirty`. `rev`,
@@ -72,8 +71,7 @@ impl Session {
doc,
sel,
view: _,
pending,
pending_at,
pending: _,
last_highlight: _,
path: _,
file_name: _,
@@ -183,8 +181,6 @@ impl Session {
EditSnapshot {
doc: doc.clone(),
sel: sel.clone(),
pending: pending.clone(),
pending_at: pending_at.clone(),
history_len: history.len(),
evicted: *undo_evicted,
head,
@@ -200,14 +196,12 @@ impl Session {
}
/// Put a snapshot back: the commands run since leave no trace in the document, the
/// selection, the formatting waiting at the caret or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// selection or undo/redo (undo steps the limit pushed out meanwhile come back). The layout
/// is recomputed.
pub fn restore(&mut self, snap: EditSnapshot) {
let EditSnapshot {
doc,
sel,
pending,
pending_at,
history_len,
evicted,
head,
@@ -229,8 +223,6 @@ impl Session {
self.autocap = None;
self.doc = doc;
self.sel = sel;
self.pending = pending;
self.pending_at = pending_at;
self.also_selected.clear();
self.member = None;
self.history.truncate(history_len);
-9
View File
@@ -16,7 +16,6 @@ pub struct WindowView {
sel: Selection,
view: ViewState,
pending: Option<CharProps>,
pending_at: Option<Pos>,
goal_x: Option<f32>,
page_hint: usize,
hf_return: Option<Selection>,
@@ -63,7 +62,6 @@ impl Session {
sel: replace(&mut self.sel, Selection::caret(start)),
view: take(&mut self.view),
pending: self.pending.take(),
pending_at: self.pending_at.take(),
goal_x: self.goal_x.take(),
page_hint: take(&mut self.page_hint),
hf_return: self.hf_return.take(),
@@ -88,7 +86,6 @@ impl Session {
sel: self.sel.clone(),
view: self.view.clone(),
pending: self.pending.clone(),
pending_at: self.pending_at.clone(),
goal_x: self.goal_x,
page_hint: self.page_hint,
hf_return: self.hf_return.clone(),
@@ -119,7 +116,6 @@ impl Session {
sel,
view,
pending,
pending_at,
goal_x,
page_hint,
hf_return,
@@ -141,7 +137,6 @@ impl Session {
self.view = view;
self.view.follow_prefs(&self.prefs);
self.pending = pending;
self.pending_at = pending_at;
self.goal_x = goal_x;
self.page_hint = page_hint;
self.column_mode = column_mode;
@@ -166,10 +161,6 @@ impl Session {
self.equation_join_next = false;
self.ime_text_join = None;
self.typing = None;
// Formatting Backspace carried over was for the text it was deleted from (#6518).
if self.pending_at.take().is_some() {
self.pending = None;
}
self.also_selected = Vec::new();
self.column = None;
self.widened = None;
+2 -6
View File
@@ -8,15 +8,11 @@ use wordcraft_layout::{DocLayout, NumeralMode, ViewMode};
/// the undo and redo stacks (also the oldest undo steps the undo limit pushes out meanwhile), the
/// open typing group, the pending
/// [`Session::join_next_undo`]/[`Session::join_next_equation_edit`]/body IME replacement promises,
/// whether the group has a step of its own, the formatting waiting at the caret (with where
/// Backspace carried it over) and the dirty flag. See [`Session::edit_snapshot`].
/// whether the group has a step of its own, and the dirty flag. See
/// [`Session::edit_snapshot`].
pub struct EditSnapshot {
pub(super) doc: Document,
pub(super) sel: Selection,
/// `Session::pending` and `Session::pending_at` then: they go together, so a restored caret
/// gets back the formatting it had, carried by Backspace or set there (#6518).
pub(super) pending: Option<wordcraft_doc::props::CharProps>,
pub(super) pending_at: Option<wordcraft_doc::Pos>,
pub(super) history_len: usize,
/// `Session::undo_evicted` when the snapshot was taken.
pub(super) evicted: u64,
-27
View File
@@ -1675,26 +1675,6 @@ fn paste_merge_formatting_keeps_rtf_deletions() {
assert_eq!(text(&s), "xkept");
}
#[test]
fn paste_merge_formatting_keeps_bold_and_italic_in_a_complex_script_run() {
// #4852 review: with the caret in a run marked `w:cs` (Thai from a WPS or Word file), the
// pasted text takes `cs` too, so its bold and italic must be the complex-script ones as well.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "ภาษาไทย"}));
run(&mut s, "select.all", json!({}));
run(&mut s, "format.set", json!({"props": {"cs": true}}));
run(&mut s, "caret.docEnd", json!({}));
run(&mut s, "edit.pasteMerge", json!({"rtf": r"{\rtf1{\b bold}{\i slant}\par}"}));
let p = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
let at = |word: &str| p.props_of_char(p.text.find(word).unwrap() + 1).clone();
let (b, i) = (at("bold"), at("slant"));
assert_eq!((b.cs, b.bold, b.bold_cs), (Some(true), Some(true), Some(true)), "{b:?}");
assert_eq!((i.cs, i.italic, i.italic_cs), (Some(true), Some(true), Some(true)), "{i:?}");
assert_ne!(b.italic, Some(true));
let r = s.doc.styles.resolve_char(None, &b);
assert!(r.bold_cs, "drawn bold as complex script");
}
#[test]
fn pasted_rtf_sections_link_their_headers_to_the_previous() {
// #1378: the RTF's own header part ids mean nothing in this document; a pasted section
@@ -13249,13 +13229,6 @@ fn style_set_keeps_imported_styles_latent_styles_and_defaults() {
let mut s = s();
run(&mut s, "design.styleSet", json!({ "name": "title" }));
assert_eq!(s.doc.styles.get("Title").unwrap().chr.size, Some(36.0));
// #4852 review: the sets that make headings bold or italic do it in both scripts, so a Thai
// heading in a run marked `w:cs` is drawn bold or italic too.
let cs = wordcraft_doc::props::CharProps { cs: Some(true), ..Default::default() };
run(&mut s, "design.styleSet", json!({ "name": "basic" }));
assert!(s.doc.styles.resolve_char(Some("Heading1"), &cs).bold_cs, "basic");
run(&mut s, "design.styleSet", json!({ "name": "casual" }));
assert!(s.doc.styles.resolve_char(Some("Heading2"), &cs).italic_cs, "casual");
}
fn style_size(s: &Session, id: &str) -> f32 {
-35
View File
@@ -156,41 +156,6 @@ fn font_commands_override_inherited_complex_script_properties_explicitly() {
assert_eq!((c.size, c.size_cs, c.bold_cs, c.italic_cs), (Some(12.0), Some(18.0), Some(false), Some(false)));
}
#[test]
fn bold_and_italic_buttons_follow_what_a_complex_script_run_shows() {
// Thai marked `w:cs` with `w:b`/`w:i` and no `w:bCs`/`w:iCs` is drawn plain, so the buttons
// are off and the first click makes it bold and italic.
let mut s = session("ทดสอบ", false);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.cs, r.props.bold, r.props.italic) = (Some(true), Some(true), Some(true));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold_cs, c.italic_cs), (Some(true), Some(true)));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(true), Some(true)));
// A right-to-left run is drawn with its complex-script values too.
let mut s = session("שלום", true);
let p = s.doc.para_mut(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
for r in &mut p.runs {
(r.props.rtl, r.props.bold, r.props.bold_cs, r.props.italic, r.props.italic_cs) =
(Some(true), Some(true), Some(false), Some(true), Some(false));
}
run(&mut s, "select.all", json!({}));
let state = run(&mut s, "format.state", json!({}));
assert_eq!((state["bold"].as_bool(), state["italic"].as_bool()), (Some(false), Some(false)));
run(&mut s, "format.bold", json!({}));
run(&mut s, "format.italic", json!({}));
let c = s.doc.para(StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap().props_of_char(0).clone();
assert_eq!((c.bold, c.bold_cs, c.italic, c.italic_cs), (Some(true), Some(true), Some(true), Some(true)));
}
#[test]
fn arrow_keys_move_visually_in_rtl_text() {
let fa = "سلام دنیا";
-349
View File
@@ -1708,355 +1708,6 @@ fn undoing_bold_at_the_caret_turns_bold_typing_off_again() {
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(0).bold, Some(true));
}
/// `text` with the characters from `from` to `to` bold, the caret at `caret`.
fn with_bold(text: &str, from: usize, to: usize, caret: usize) -> Session {
let mut s = Session::new(wordcraft_doc::Document::from_text(text));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": from}, "focus": {"block": 0, "off": to}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": caret}}));
s
}
/// Whether the character at `off` of the first paragraph is bold.
fn bold_at(s: &Session, off: usize) -> bool {
s.doc.para_at(&Pos::body(0, 0)).unwrap().props_of_char(off).bold == Some(true)
}
/// #6518: after Backspace, Word types with the deleted character's formatting, not the one to
/// the left of the caret, and the Bold button shows it.
#[test]
fn typing_after_backspace_takes_the_deleted_characters_formatting() {
// "Abc abc", "Abc" bold: Backspace after the plain space, then X is plain.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(!bold_at(&s, 3));
// "abc Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("abc Abc", 4, 7, 5);
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "XY");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "abc XYbc");
assert!(bold_at(&s, 4) && bold_at(&s, 5));
// Several Backspaces: the last character deleted wins ("c", then the plain space).
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXabc");
assert!(bold_at(&s, 2));
// Inside a word the Bold button shows the deleted character too, not the word: in "Ab c"
// with all but the space bold, Backspace after the space leaves the caret in a bold "Abc".
let mut s = with_bold("Ab c", 0, 2, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 4}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
typ(&mut s, "\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbXc");
assert!(!bold_at(&s, 2));
}
/// #6518: the carried formatting goes once the caret moves, and Delete never carries it.
#[test]
fn backspace_formatting_is_dropped_by_a_caret_move_and_delete_does_not_carry() {
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.typing_props().bold, Some(true));
typ(&mut s, "X");
assert!(bold_at(&s, 3));
// Delete after the bold "Abc" removes the plain space: X takes the bold to its left.
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "text.delete", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "AbcXabc");
assert!(bold_at(&s, 3));
// Deleting a plain selection with Delete or Backspace carries nothing either.
for key in ["text.delete", "text.backspace"] {
let mut s = with_bold("Abc abc", 0, 3, 3);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 3}, "focus": {"block": 0, "off": 5}}));
run(&mut s, key, json!({}));
typ(&mut s, "X");
assert!(bold_at(&s, 3), "{key}");
}
// Undo takes the Backspace back, and with it the carried formatting.
let mut s = with_bold("Abc abc", 0, 3, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.sel.focus, Pos::body(0, 4));
assert_eq!(s.pending, None);
}
/// #6518: a Backspace that changes nothing, at the start of the document, keeps formatting waiting
/// at the caret; one that joins paragraphs drops it. Observed in Word for Windows.
#[test]
fn backspace_at_the_document_start_keeps_waiting_formatting() {
// "Abc def", "Abc" bold: Backspace deletes the bold A, the second one does nothing, X is bold.
let mut s = with_bold("Abc def", 0, 3, 1);
typ(&mut s, "\u{8}\u{8}");
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xbc def");
assert!(bold_at(&s, 0));
// Bold at the caret before plain "abc", then a Backspace that does nothing: X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "xyz" then bold "Abc": Backspace deletes the bold A, the second joins the paragraphs, and X
// takes the plain z to its left.
let mut s = Session::new(wordcraft_doc::Document::from_text("xyz\nAbc"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}\u{8}X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xyzXbc");
assert!(!bold_at(&s, 3) && bold_at(&s, 4));
}
/// #6518: Ctrl+Backspace that deletes nothing, at the start of the document, keeps formatting
/// waiting at the caret, as a plain Backspace there does; one that deletes a word or joins
/// paragraphs drops it. Observed in Word for Windows.
#[test]
fn ctrl_backspace_at_the_document_start_keeps_waiting_formatting() {
// "Ab def", "A" bold: Backspace deletes the bold A, Ctrl+Backspace does nothing, X is bold
// beside a plain "b".
let mut s = with_bold("Ab def", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xb def");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// Bold at the caret before plain "abc", then a Ctrl+Backspace that does nothing: X is bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abc"));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 0}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Xabc");
assert!(bold_at(&s, 0) && !bold_at(&s, 1));
// "pq xy Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace deletes "xy ", X is plain.
let mut s = with_bold("pq xy Ab", 6, 7, 7);
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pq Xb");
assert!(!bold_at(&s, 3));
// "pq" then "Ab", "A" bold: Backspace deletes the bold A, Ctrl+Backspace joins the
// paragraphs, X is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("pq\nAb"));
run(&mut s, "select.range", json!({"anchor": {"block": 1, "off": 0}, "focus": {"block": 1, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 1, "off": 1}}));
typ(&mut s, "\u{8}");
run(&mut s, "text.deleteWordBack", json!({}));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "pqXb");
assert!(!bold_at(&s, 2));
}
/// #6518 review: what Backspace carries over is for typing where the character was deleted. A
/// paste leaves the next typed text the formatting where it lands, and pasted text never takes it.
#[test]
fn backspace_formatting_is_not_kept_past_a_paste() {
// "hello wrld World", "World" bold: copy it, Backspace the plain r, paste, then ! is bold
// like the pasted text to its left.
let mut s = with_bold("hello wrld World", 11, 16, 0);
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 11}, "focus": {"block": 0, "off": 16}}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 8}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "hello wWorld!ld World");
assert!(bold_at(&s, 7) && bold_at(&s, 12), "! takes the pasted bold, not the deleted plain r");
// "ab Cd", "C" bold: Backspace the bold C, paste plain text: it takes the plain space before
// it, and so does ! after it.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
run(&mut s, "edit.paste", json!({"text": "zz"}));
typ(&mut s, "!");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab zz!d");
assert!((3..6).all(|i| !bold_at(&s, i)), "pasted text and ! are plain");
}
/// #6518 review: Find, Go To and a click elsewhere move the caret without the caret commands;
/// the formatting Backspace carried over stays behind. Observed in Word for Windows: typing over
/// a found word takes that word's formatting, and a Find with no match keeps the carried one.
#[test]
fn backspace_formatting_is_not_kept_past_find_or_go_to() {
// "Xy plain word", "X" bold: Backspace the bold X, Find "word" and type over it: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "word"}));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(false));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Q");
assert!(!bold_at(&s, 8));
// Go To a paragraph puts a caret before a plain word: Q is plain.
let mut s = Session::new(wordcraft_doc::Document::from_text("Xy plain\nword"));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
typ(&mut s, "\u{8}");
run(&mut s, "edit.goto", json!({"paragraph": 2}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(1, 0)));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(1, 0)).unwrap().text, "Qword");
assert_ne!(s.doc.para_at(&Pos::body(1, 0)).unwrap().props_of_char(0).bold, Some(true));
// A caret the front end puts elsewhere itself (a right-click in the text): Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.sel = crate::Selection::caret(Pos::body(0, 8));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "y plain Qword");
assert!(!bold_at(&s, 8));
// A Find with no match leaves the caret where it was, and the formatting with it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
run(&mut s, "edit.find", json!({"text": "zzz"}));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(bold_at(&s, 0));
}
/// #6518 review: a Paste with nothing on the clipboard pastes nothing: the formatting Backspace
/// carried over stays for the typing that follows.
#[test]
fn backspace_formatting_survives_a_paste_of_an_empty_clipboard() {
// "ab Cd", "C" bold: Backspace the bold C, Paste fails, X is bold.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(s.run("edit.paste", &json!({})).is_err(), "the clipboard is empty");
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Xd");
assert!(bold_at(&s, 3));
// What Paste would insert, asked for on its own: nothing, and the formatting stays.
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}");
assert!(crate::cmd::paste::paste_content(&mut s, &json!({})).is_err());
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
}
/// #6518 review: a front end that moves the caret itself (a right-click) goes through
/// `Session::set_selection`: once the caret has been elsewhere, putting it back where the
/// character was deleted does not bring the carried formatting back.
#[test]
fn backspace_formatting_is_not_kept_past_a_direct_caret_move_and_back() {
// "Xy plain word", "X" bold: Backspace the bold X, the caret goes to "word" and back: Q is plain.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 8)));
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
assert_ne!(s.typing_props().bold, Some(true));
typ(&mut s, "Q");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "Qy plain word");
assert!(!bold_at(&s, 0));
// Put where it already is, the caret keeps it: Q is bold.
let mut s = with_bold("Xy plain word", 0, 1, 1);
typ(&mut s, "\u{8}");
s.set_selection(crate::Selection::caret(Pos::body(0, 0)));
typ(&mut s, "Q");
assert!(bold_at(&s, 0));
}
/// #6518 review: a command that fails leaves the formatting waiting at the caret as it was: a
/// Backspace refused by a content control locked against editing keeps what an earlier Backspace
/// carried over, and Bold picked at the caret.
#[test]
fn a_refused_backspace_keeps_the_formatting_waiting_at_the_caret() {
let w = wordcraft_doc::para::OBJ.len_utf8();
// "abC" in a content control, "C" bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("abC"));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 2}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 3}}));
run(&mut s, "developer.richText", json!({"tag": "ctl"}));
let lock = |s: &mut Session| run(s, "developer.properties", json!({"control": "ctl", "lockEdit": true}));
// Backspace the bold C, lock the control: the next Backspace is refused, and X is still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 3}}));
typ(&mut s, "\u{8}");
lock(&mut s);
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true));
let before = s.doc.clone();
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.doc, before);
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, w + 2)));
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the carried bold");
// Bold picked at the caret, then a refused Backspace: still bold.
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": w + 1}}));
s.pending = Some(wordcraft_doc::props::CharProps { bold: Some(true), ..Default::default() });
assert!(s.run("text.backspace", &json!({})).is_err(), "the control is locked");
assert_eq!(s.waiting().and_then(|p| p.bold), Some(true), "the refused Backspace keeps the Bold picked at the caret");
}
/// #6518: the carried formatting goes on with the typing that follows, and Undo of that typing
/// brings it back where it was, so typing again there takes it once more.
#[test]
fn backspace_formatting_follows_typing_and_comes_back_with_undo() {
// "ab Cd", "C" bold: Backspace the bold C, then Y and X are both bold (Word).
let mut s = with_bold("ab Cd", 3, 4, 4);
typ(&mut s, "\u{8}YX");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab YXd");
assert!(bold_at(&s, 3) && bold_at(&s, 4) && !bold_at(&s, 5));
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab d");
typ(&mut s, "Z");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "ab Zd");
assert!(bold_at(&s, 3));
}
/// #6518: with Track Changes on, Backspace leaves the character in place marked deleted, and text
/// typed next still takes its formatting (a tracked insertion, never marked deleted); moving the
/// caret away and back drops it. Backspace over the author's own tracked insertion, which removes
/// it, carries it too. Observed in Word for Windows.
#[test]
fn tracked_backspace_carries_the_deleted_characters_formatting() {
// "xy Abc", "Abc" bold: Backspace after the bold A, then X is bold beside a plain space.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
assert_eq!(s.run("format.state", &json!({})).unwrap()["bold"], json!(true));
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy XAbc", "the A stays, marked deleted");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
assert!(p.props_of_char(4).del.is_some() && p.props_of_char(5).del.is_none());
// Moving the caret right and back after the Backspace drops it: X is plain.
let mut s = with_bold("xy Abc", 3, 6, 4);
run(&mut s, "review.trackChanges", json!({"value": true}));
typ(&mut s, "\u{8}");
run(&mut s, "caret.right", json!({}));
run(&mut s, "caret.left", json!({}));
assert_eq!(s.sel, crate::Selection::caret(Pos::body(0, 3)));
typ(&mut s, "X");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy XAbc");
assert!(!bold_at(&s, 3));
// A bold A this author typed with Track Changes on: Backspace removes it, X is still bold.
let mut s = Session::new(wordcraft_doc::Document::from_text("xy "));
run(&mut s, "review.trackChanges", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 3}}));
run(&mut s, "format.bold", json!({"value": true}));
typ(&mut s, "A");
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 4}}));
typ(&mut s, "\u{8}");
assert_eq!(s.doc.para_at(&Pos::body(0, 0)).unwrap().text, "xy ");
typ(&mut s, "X");
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
assert_eq!(p.text, "xy X");
let x = p.props_of_char(3);
assert!(x.bold == Some(true) && x.ins.is_some() && x.del.is_none(), "X is a bold tracked insertion: {x:?}");
}
/// Myanmar (#604): typed in memory order (consonant, medial, then the prevowel ေ that is drawn
/// before it), the caret steps over whole syllables and Backspace removes one sign at a time.
#[test]
-364
View File
@@ -1,364 +0,0 @@
//! Screen readers: what a formatting shortcut did, said as Word says it ("Bold On", "Center Off",
//! "Font 14pt"). Word raises these itself; here they go through a polite live region, which
//! screen readers read when it appears.
use egui::accesskit::{Live, Role};
use serde_json::Value;
use wordcraft_doc::Align;
use crate::WordApp;
/// How long an announcement stays in the tree: a screen reader reads its name after the
/// live-region event, so it must still be there then.
const SHOWN_MS: f64 = 3000.0;
/// An announcement for screen readers. Each one gets its own node, numbered: a live region is
/// read when it appears or its text changes, so the same text twice needs a new node.
#[derive(Clone, Debug)]
pub(crate) struct Announcement {
text: String,
serial: u64,
at: f64,
}
/// Announces what the shortcut for command `id` did, once it has run; nothing for a command Word
/// doesn't announce.
pub(crate) fn after_shortcut(app: &mut WordApp, id: &str, ctx: &egui::Context) {
let Some(text) = describe(app, id) else { return };
let serial = app.announcement.as_ref().map_or(0, |a| a.serial.wrapping_add(1));
app.announcement = Some(Announcement { text, serial, at: ctx.input(|i| i.time) * 1000.0 });
}
/// The words for what command `id` did: the command's name and whether its formatting is now on,
/// or the font size the selection now has.
fn describe(app: &WordApp, id: &str) -> Option<String> {
let on_off = |name: &str, on: bool| format!("{name} {}", if on { tl!("On") } else { tl!("Off") });
let state = || wordcraft_engine::cmd::format::state(&app.session);
let character = match id {
"format.bold" => Some(("bold", tl!("Bold"))),
"format.italic" => Some(("italic", tl!("Italic"))),
"format.underline" => Some(("underline", tl!("Underline"))),
"format.subscript" => Some(("subscript", tl!("Subscript"))),
"format.superscript" => Some(("superscript", tl!("Superscript"))),
_ => None,
};
if let Some((key, name)) = character {
return Some(on_off(name, state().get(key).and_then(Value::as_bool).unwrap_or(false)));
}
let alignment = match id {
"para.alignLeft" => Some((Align::Left, tl!("Align Left"))),
"para.alignCenter" => Some((Align::Center, tl!("Center"))),
"para.alignRight" => Some((Align::Right, tl!("Align Right"))),
"para.justify" => Some((Align::Justify, tl!("Justify"))),
_ => None,
};
if let Some((want, name)) = alignment {
// As the ribbon's buttons show it: Center twice centres, then goes back to the left. Read
// in a paragraph the command formatted: a selection ending at the next paragraph's start
// leaves that one out (#418).
let s = &app.session;
let formatted = wordcraft_engine::cmd::selected_paths(s);
let path = if formatted.contains(&s.sel.focus.path) { Some(s.sel.focus.path.clone()) } else { formatted.last().cloned() };
let at = path.map(|path| wordcraft_doc::Pos { path, off: 0, ..s.sel.focus.clone() });
let align = at.and_then(|at| s.doc.para_at(&at)).map(|p| s.doc.styles.resolve_para(&p.props)).map(|r| r.align.visual(r.bidi));
return Some(on_off(name, align == Some(want)));
}
if matches!(id, "format.growFont" | "format.shrinkFont" | "format.growFont1" | "format.shrinkFont1") {
// A selection of mixed sizes has no one size to say.
let size = state().get("size").and_then(Value::as_f64)?;
let unit = wordcraft_geom::Unit::Points;
let number = unit.number(size as f32, app.session.region().decimal());
return Some(format!("{} {number}{}", tl!("Font"), crate::options::unit_suffix(unit)));
}
None
}
/// Puts the latest announcement in the tree, as a polite live region, while it is fresh.
pub(crate) fn expose(app: &WordApp, ctx: &egui::Context) {
let Some(a) = &app.announcement else { return };
let age = ctx.input(|i| i.time) * 1000.0 - a.at;
if !(0.0..SHOWN_MS).contains(&age) {
return;
}
ctx.accesskit_node_builder(egui::Id::unique(("announcement", a.serial)), |node| {
// A label's text is its value: that is the name screen readers read (UI Automation's
// live-region event goes only to a node with a name).
node.set_role(Role::Label);
node.set_live(Live::Polite);
node.set_value(a.text.clone());
});
// A frame when it's due to go, so it leaves the tree even while nothing else happens.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((SHOWN_MS - age) / 1000.0));
}
#[cfg(test)]
mod tests {
use egui::accesskit::{Live, Role};
use egui::{Key, Modifiers};
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use crate::WordApp;
/// An announcement belongs to the window whose shortcut made it, as its status message does:
/// another window drawn within its three seconds doesn't put it in its own tree.
#[test]
fn an_announcement_stays_with_its_window() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.announcement = Some(super::Announcement { text: "Bold On".into(), serial: 0, at: 0.0 });
let mut other = crate::window_ui::WindowUi::new(app.session.document_id());
app.swap_window(&mut other);
assert!(app.announcement.is_none(), "the other window has nothing to say");
app.swap_window(&mut other);
assert_eq!(app.announcement.as_ref().map(|a| a.text.as_str()), Some("Bold On"), "it is back with its window");
}
fn harness(text: &str) -> egui_kittest::Harness<'static, WordApp> {
let app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text(text)), crate::Services::default());
let mut h = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
app,
);
let ctx = h.ctx.clone();
h.state_mut().canvas.focus_page(&ctx);
crate::test_harness::frames(&mut h, 6);
assert!(h.state().canvas.focused(&ctx), "the page has the keyboard");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
crate::test_harness::frames(&mut h, 2);
h
}
/// The live region's text and node (its id, written out), if one is in the tree. The text is
/// the label's value, which is its name to screen readers.
fn heard(h: &egui_kittest::Harness<'_, WordApp>) -> Option<(String, String)> {
let node = h.query_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite))?;
let n = node.accesskit_node();
assert!(n.label_comes_from_value(), "a label, named by its value");
Some((n.value().unwrap_or_default(), format!("{:?}", n.id())))
}
fn press(h: &mut egui_kittest::Harness<'_, WordApp>, m: Modifiers, key: Key) -> Option<(String, String)> {
h.key_press_modifiers(m, key);
crate::test_harness::frames(h, 2);
heard(h)
}
/// Ctrl+B, Ctrl+I, Ctrl+U and the alignment keys say what they did, as Word does ("Bold On",
/// then "Bold Off"), each time in a new live region, so the same words twice are heard twice.
#[test]
fn formatting_shortcuts_say_what_they_did() {
let mut h = harness("Lanterns glow");
assert_eq!(heard(&h), None, "nothing to say before a shortcut");
let (text, first) = press(&mut h, Modifiers::COMMAND, Key::B).expect("Ctrl+B is announced");
assert_eq!(text, "Bold On");
let (text, second) = press(&mut h, Modifiers::COMMAND, Key::B).expect("again");
assert_eq!(text, "Bold Off");
assert_ne!(first, second, "each announcement is a new live region");
for (key, said) in [
(Key::I, "Italic On"),
(Key::U, "Underline On"),
(Key::E, "Center On"),
(Key::E, "Center Off"),
(Key::R, "Align Right On"),
(Key::J, "Justify On"),
(Key::L, "Align Left On"),
] {
assert_eq!(press(&mut h, Modifiers::COMMAND, key).map(|(t, _)| t).as_deref(), Some(said), "{key:?}");
}
let (_, before) = heard(&h).expect("the last one");
let (text, again) = press(&mut h, Modifiers::COMMAND, Key::L).expect("Ctrl+L twice");
assert_eq!(text, "Align Left On", "left alignment stays");
assert_ne!(before, again, "the same words twice are a new live region, so they are heard again");
let grown = press(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::Period).map(|(t, _)| t).expect("Ctrl+Shift+. is announced");
assert!(grown.starts_with("Font ") && grown.ends_with(" pt"), "{grown}");
}
/// Only shortcuts are announced: a ribbon button says its own state, and a command that isn't
/// formatting says nothing. An announcement leaves the tree after three seconds.
#[test]
fn only_formatting_shortcuts_are_announced_for_a_while() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.bold", json!({})).unwrap();
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "a command run another way isn't announced");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::Z), None, "Undo isn't announced");
assert!(press(&mut h, Modifiers::COMMAND, Key::I).is_some());
if let Some(a) = &mut h.state_mut().announcement {
a.at -= super::SHOWN_MS;
}
crate::test_harness::frames(&mut h, 2);
assert_eq!(heard(&h), None, "gone after three seconds");
}
/// A selection ending at the next paragraph's start (Shift+Down from a paragraph's start)
/// formats only the paragraph it covers, as in Word: that is the one the announcement says.
#[test]
fn alignment_is_said_for_the_paragraph_the_shortcut_formatted() {
let mut h = harness("Lanterns glow\nRivers run");
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(1, 0) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center On"));
let align =
|h: &egui_kittest::Harness<'_, WordApp>, i| h.state().session.doc.para_at(&wordcraft_doc::Pos::body(i, 0)).and_then(|p| p.props.align);
assert_eq!((align(&h, 0), align(&h, 1)), (Some(wordcraft_doc::Align::Center), None), "only the first paragraph is centred");
assert_eq!(press(&mut h, Modifiers::COMMAND, Key::E).map(|(t, _)| t).as_deref(), Some("Center Off"));
}
/// The shortcut runs after the announcement's place in the frame, so the announcement goes in
/// the next frame's tree: a key asks egui for that frame itself.
#[test]
fn the_announcement_is_in_the_frame_after_the_key() {
let mut h = harness("Lanterns glow");
// The key down alone, in one frame (`key_press_modifiers` gives each event a frame).
h.input_mut().events.push(egui::Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND });
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h), None, "the key's own frame built its tree before the shortcut ran");
assert!(h.ctx.has_requested_repaint(), "the key asked for another frame");
crate::test_harness::frame(&mut h);
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold On"));
}
/// Each formatting shortcut says its own words, read from the formatting after it ran: the
/// format's name and On or Off for Ctrl+B, I, U, = (Subscript) and Shift+= (Superscript), the
/// alignment's name for Ctrl+E, R, J and L, and the size the selection now has for
/// Ctrl+Shift+. and , (Grow and Shrink Font) and Ctrl+] and [ (by 1 pt). A selection of mixed
/// sizes has no one size to say, so nothing is said.
#[test]
fn every_formatting_shortcut_says_its_own_words() {
let mut h = harness("Lanterns glow");
h.state_mut().run("format.size", json!({"size": 12})).unwrap();
crate::test_harness::frames(&mut h, 2);
let (cmd, shift) = (Modifiers::COMMAND, Modifiers::COMMAND | Modifiers::SHIFT);
for (m, key, said) in [
(cmd, Key::B, "Bold On"),
(cmd, Key::B, "Bold Off"),
(cmd, Key::I, "Italic On"),
(cmd, Key::I, "Italic Off"),
(cmd, Key::U, "Underline On"),
(cmd, Key::U, "Underline Off"),
(cmd, Key::Equals, "Subscript On"),
(cmd, Key::Equals, "Subscript Off"),
(shift, Key::Equals, "Superscript On"),
(shift, Key::Equals, "Superscript Off"),
(cmd, Key::E, "Center On"),
(cmd, Key::R, "Align Right On"),
(cmd, Key::J, "Justify On"),
(cmd, Key::L, "Align Left On"),
(shift, Key::Period, "Font 14 pt"),
(shift, Key::Comma, "Font 12 pt"),
(cmd, Key::CloseBracket, "Font 13 pt"),
(cmd, Key::OpenBracket, "Font 12 pt"),
] {
assert_eq!(press(&mut h, m, key).map(|(t, _)| t).as_deref(), Some(said), "{m:?} {key:?}");
}
let mut h = harness("Lanterns glow");
let sizes = [(0, 8, 12.0), (8, 13, 16.0)];
for (from, to, size) in sizes {
h.state_mut().session.sel =
wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, from), focus: wordcraft_doc::Pos::body(0, to) };
h.state_mut().run("format.size", json!({"size": size})).unwrap();
}
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 13) };
crate::test_harness::frames(&mut h, 2);
assert_eq!(press(&mut h, shift, Key::Period), None, "mixed sizes: nothing to say");
assert!(h.state().announcement.is_none(), "and nothing waits to be said");
}
/// The words are looked up in the interface catalogs, so each language says its own.
#[test]
fn the_words_go_through_the_interface_catalogs() {
let mut h = harness("Lanterns glow");
// These delimiters mark translations in the synthetic locale and are absent from some test fonts.
h.ctx.add_glyph_rasterizer(egui::GlyphRasterizer::new("wordcraft::announce::pseudo_markers", |request| {
matches!(request.cluster, "⟦" | "⟧").then(|| egui::RasterizedGlyph {
bitmap: egui::GlyphBitmap {
image: egui::ColorImage::new([1, 1], vec![egui::Color32::WHITE]),
offset_px: egui::Vec2::ZERO,
is_color: false,
},
advance_px: request.font_size_px.max(1.0),
})
}));
h.state_mut().ui.language = "pseudo".into();
let said = press(&mut h, Modifiers::COMMAND, Key::B).map(|(t, _)| t).unwrap_or_default();
crate::i18n::apply_language(crate::i18n::Lang::EN);
assert!(
said.split_whitespace().all(|word| word.starts_with('⟦') && word.ends_with('⟧')) && said.contains('⟦'),
"every word is marked: {said:?}"
);
}
/// Ten presses in a burst, one per frame or all in one frame (a held key, or keys typed
/// faster than frames), leave one announcement at a time, the latest, in one live region:
/// each replaces the last (`WordApp::announcement` holds one), so nothing queues up.
#[test]
fn a_burst_of_ten_presses_leaves_one_announcement_the_latest() {
let live =
|h: &egui_kittest::Harness<'_, WordApp>| h.query_all_by(|n| n.role() == Role::Label && n.data().live() == Some(Live::Polite)).count();
let mut h = harness("Lanterns glow");
let mut nodes = std::collections::HashSet::new();
for i in 0..10 {
let (text, node) = press(&mut h, Modifiers::COMMAND, Key::B).expect("each press is announced");
assert_eq!(text, if i % 2 == 0 { "Bold On" } else { "Bold Off" }, "press {i}");
assert_eq!(live(&h), 1, "press {i}: one live region in the tree");
nodes.insert(node);
}
assert_eq!(nodes.len(), 10, "each press a new node, so each is heard");
let mut h = harness("Lanterns glow");
let key = |pressed| egui::Event::Key { key: Key::B, physical_key: None, pressed, repeat: false, modifiers: Modifiers::COMMAND };
for _ in 0..10 {
h.input_mut().events.extend([key(true), key(false)]);
}
crate::test_harness::frames(&mut h, 2);
let bold = wordcraft_engine::cmd::format::state(&h.state().session).get("bold").and_then(serde_json::Value::as_bool);
assert_eq!(bold, Some(false), "ten Ctrl+B in one frame: bold on and off five times");
assert_eq!(live(&h), 1, "one live region in the tree");
assert_eq!(heard(&h).map(|(t, _)| t).as_deref(), Some("Bold Off"), "the latest is said");
}
/// The words go through the interface's catalogs (`tl!`), as the ribbon's labels do: a
/// translated interface says them in its language. Checked with a fixture language and, when
/// the craft-i18n catalogs are embedded (`CRAFT_I18N_DIR`), Turkish and Simplified Chinese.
#[test]
fn the_announcements_are_in_the_interface_language() {
let said = |app: &mut WordApp, id: &str| {
app.run(id, json!({})).unwrap();
super::describe(app, id)
};
let app = || {
let mut app =
WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Lanterns glow")), crate::Services::default());
app.session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 0), focus: wordcraft_doc::Pos::body(0, 8) };
app.run("format.size", json!({"size": 12})).unwrap();
app
};
let mut a = app();
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tBold\tBold-FX\n\tOn\tOn-FX\n\tOff\tOff-FX\n\tCenter\tCenter-FX\n\tFont\tFont-FX\n\tpt\tpt-FX\n",
));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX On-FX"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some("Bold-FX Off-FX"));
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some("Center-FX On-FX"));
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some("Font-FX 14 pt-FX"));
// The catalogs' own words: craft-i18n's `common.tsv` and `wordcraft.tsv` rows.
if crate::i18n::catalogs_embedded() {
for (code, bold, center, font) in
[("tr", "Kalın Açık", "Ortala Açık", "Yazı Tipi 14 pt"), ("zh-hans", "加粗 开", "居中 开", "字体 14 磅")]
{
let mut a = app();
crate::i18n::apply_language(crate::i18n::Lang::from_code(code).expect("an interface language"));
assert_eq!(said(&mut a, "format.bold").as_deref(), Some(bold), "{code}");
assert_eq!(said(&mut a, "para.alignCenter").as_deref(), Some(center), "{code}");
assert_eq!(said(&mut a, "format.growFont").as_deref(), Some(font), "{code}");
}
}
crate::i18n::apply_language(crate::i18n::Lang::EN);
}
}
-2
View File
@@ -53,7 +53,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -138,7 +137,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+1 -4
View File
@@ -123,7 +123,7 @@ impl WordApp {
for (id, label) in GATED_UI_COMMANDS {
defs.push(CommandDef::new(CommandRef::new(*id), tl!(*label), Scope::app()));
}
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// Word's Alt chords (Alt+Q, Alt+F7, Ctrl+Alt+1…) fire while the person types in the page:
// plain keys type, and every modified chord is offered to the keymap first.
match AppCatalog::new(defs, generation) {
Ok(catalog) => {
@@ -204,9 +204,6 @@ impl WordApp {
self.edits = host;
}
let result = if fired.source == FireSource::Automation { self.execute(id, params) } else { self.run(id, params) };
if from_key && result.is_ok() {
crate::announce::after_shortcut(self, id, ctx);
}
if let Err(error) = result {
log::debug!("command {id}: {error}");
}
+1 -1
View File
@@ -674,7 +674,7 @@ impl WordApp {
let name = file.path.as_ref().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|| file.name.clone());
let lower = name.to_ascii_lowercase();
let data = file.bytes.as_ref().map(|b| wordcraft_engine::cmd::insert::base64_encode(b.as_ref()));
let img = file_dialogs::is_picture_name(&name);
let img = [".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".wmf", ".emf"].iter().any(|e| lower.ends_with(e));
// Any recipient file ends the pending picker request, so a later .txt drop opens normally.
let asked = std::mem::take(&mut self.recipient_list_pending);
let list = lower.ends_with(".csv") || lower.ends_with(".tsv") || (lower.ends_with(".txt") && asked);
-1
View File
@@ -75,7 +75,6 @@ impl WordApp {
/// handed in as values and read back after, so no body reads a stale copy. Returns the
/// shell's regions; a window another command swapped in mid-draw returns none.
pub(super) fn paint_window(&mut self, ui: &mut egui::Ui) -> ShellRegions {
crate::announce::expose(self, ui.ctx());
let window = self.windows.shown();
let stale = |app: &WordApp| app.windows.shown() != window;
let mode = self.screen_mode();
+2 -2
View File
@@ -22,7 +22,7 @@ impl WordApp {
let Some(off) = end.off.checked_sub(wordcraft_doc::para::OBJ.len_utf8()) else { return };
let start = wordcraft_doc::Pos { off, ..end.clone() };
if self.session.doc.para_at(&start).and_then(|p| p.object_at(off)).is_some_and(|o| o.is_drawing()) {
self.session.set_selection(wordcraft_engine::Selection { anchor: start, focus: end });
self.session.sel = wordcraft_engine::Selection { anchor: start, focus: end };
}
}
@@ -38,7 +38,7 @@ impl WordApp {
/// arrive in one drop, put the caret after the picture placed by the previous file (#1592).
pub(super) fn caret_after_placed_picture(&mut self, placed: bool) {
if placed {
self.session.set_selection(wordcraft_engine::Selection::caret(self.session.sel.focus.clone()));
self.session.sel.anchor = self.session.sel.focus.clone();
}
}
+1 -1
View File
@@ -76,7 +76,7 @@ fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
_ => None,
});
if let Some(pos) = pos {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
}
CommentEdit::Edit { thread, index, text, .. } => {
+1 -1
View File
@@ -154,7 +154,7 @@ fn rows(app: &mut WordApp, ui: &mut Ui) {
let (a, b) = app.session.sel.ordered();
let trimmed = app.session.doc.para_at(&a).and_then(|p| p.text.get(a.off..b.off)).map(|t| t.trim_end().len()).unwrap_or(0);
let end = wordcraft_doc::Pos { off: a.off + trimmed, ..b };
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: end });
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: end };
let _ = app.run("text.insert", json!({"text": w, "raw": true}));
}
}
+8 -8
View File
@@ -304,13 +304,13 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
return;
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.page_hint = page;
}
}
match layout.equation_hit(page, x, y, app.session.sel.focus.story) {
Some((pos, inner)) => {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
return;
}
@@ -334,7 +334,7 @@ pub(crate) fn handle_secondary_selection(app: &mut WordApp, body: &PageBody<'_>,
}
}
if let Some(pos) = layout.hit(page, x, y, app.session.sel.focus.story) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
app.session.page_hint = page;
}
}
@@ -372,7 +372,7 @@ fn handle_primary_press(
if app.run(id, json!({ "page": page })).is_ok() {
let to = app.session.sel.focus.story;
if let Some(pos) = app.session.layout().hit(page, x, y, to) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
app.session.page_hint = page;
}
@@ -388,7 +388,7 @@ fn handle_primary_press(
if !mods.shift
&& let Some((at, inner)) = layout.equation_hit(page, x, y, story)
{
app.session.set_selection(wordcraft_engine::Selection::caret(at));
app.session.sel = wordcraft_engine::Selection::caret(at);
let _ = app.run("equation.edit", json!({"pos": serde_json::to_value(&inner).unwrap_or_default()}));
app.session.page_hint = page;
return true;
@@ -521,14 +521,14 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if app.run(id, json!({ "page": page })).is_ok()
&& let Some(pos) = app.session.layout().hit(page, x, y, app.session.sel.focus.story)
{
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
return true;
}
if matches!(story, StoryRef::Part(_)) && !in_text_box(app) && hf_zone.is_none() {
let _ = app.run("insert.closeHeader", json!({}));
if let Some(pos) = layout.hit(page, x, y, StoryRef::Body) {
app.session.set_selection(wordcraft_engine::Selection::caret(pos));
app.session.sel = wordcraft_engine::Selection::caret(pos);
}
return true;
}
@@ -536,7 +536,7 @@ fn handle_completed_click(app: &mut WordApp, pointer: &PagePointer<'_>) -> bool
if let Some(pos) = layout.hit(page, x, y, story)
&& let Some(field) = field_showing_code(app, &pos)
{
app.session.set_selection(wordcraft_engine::Selection::caret(field));
app.session.sel = wordcraft_engine::Selection::caret(field);
let _ = app.run("fields.setCode", json!({}));
return true;
}
+3 -7
View File
@@ -303,7 +303,7 @@ fn swatch_table(
current: Option<Rgb>,
) -> (Option<Rgb>, craft::behavior::Preview<Rgb>, egui::Response) {
use craft::behavior::Preview;
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(format!("#{}", c.hex())), srgba(*c))).collect();
let swatches: Vec<(Label, Srgba)> = colors.iter().map(|c| (Label::from(c.hex()), srgba(*c))).collect();
let out = SwatchTable::new(name.to_string(), &swatches)
.per_row(per_row)
.tips(true)
@@ -640,9 +640,7 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
),
};
let icon = shown.map_or_else(IconSpec::empty_swatch, IconSpec::swatch);
let spoken_value = current.map_or_else(|| text.as_str().to_string(), |c| format!("#{}", c.hex()));
let spoken = format!("{} {spoken_value}", label.as_str());
let field = SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
SplitButton::<NoValue>::body(text, |ui: &mut Ui, cx: &mut BodyCx<'_>| {
let empty_label = match empty {
ColorFieldEmpty::NoColor => Label::from(tl!("No Color").to_string()),
ColorFieldEmpty::Automatic { label, .. } => label.clone(),
@@ -666,11 +664,9 @@ pub fn color_field(ui: &mut Ui, label: &Label, value: &mut String, empty: &Color
cx.request_close();
}
})
.arrow_label(spoken.clone())
.arrow_label(label.clone())
.icon(icon)
.show(ui);
// The framework keeps the short visible value; both parts say the field and its value.
ui.ctx().accesskit_node_builder(field.response.id, |node| node.set_label(spoken));
resp
}
-91
View File
@@ -1691,94 +1691,3 @@ fn font_dialog_effects_stand_two_to_a_line_and_kerning_on_one() {
let size = h.query_all_by_label("Points and above").map(|node| node.rect()).min_by(|a, b| a.min.x.total_cmp(&b.min.x)).expect("the kerning size");
assert!((kern.center().y - size.center().y).abs() < 4.0 && kern.max.x <= size.min.x, "the kerning size is on the check box's line");
}
/// #5057: keep the accessibility contract when dialogs move onto the framework.
#[test]
fn dialogs_their_tabs_and_colour_fields_say_what_they_are() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
open_named(&mut h, "paragraph", json!({}));
assert!(h.query_by_role_and_label(Role::Dialog, "Paragraph").is_some(), "Paragraph is a dialog");
assert!(h.query_by_role_and_label(Role::Window, "Paragraph").is_none(), "not only a window");
assert_eq!(h.get_by_role_and_label(Role::Tab, "Indents and Spacing").accesskit_node().is_selected(), Some(true));
assert_eq!(h.get_by_role_and_label(Role::Tab, "Line and Page Breaks").accesskit_node().is_selected(), Some(false));
assert!(h.query_by_role_and_label(Role::Button, "Indents and Spacing").is_none(), "not a button");
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, "font", json!({}));
// The framework's split field has a face and a menu arrow; the latter opens the palette.
h.query_all_by_role_and_label(Role::Button, "Font color: Automatic").last().expect("named colour field").click();
h.run_steps(3);
assert!(h.query_by_label("#C00000").is_some(), "the swatches say their colour");
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Font color: #C00000").next().is_some(), "the field says the colour picked");
}
/// #5057: every caller retains its translated label and selected colour.
#[test]
fn colour_fields_say_their_label_and_colour_in_the_interface_language() {
use egui::accesskit::Role;
let mut app = app_with("Lanterns");
// The framework palette lists the document theme; use a known colour rather than its default.
app.session.doc.settings.theme_colors = vec![wordcraft_doc::Rgb(0xC0, 0, 0)];
let mut h = app_harness(app);
for (dialog, names) in [("font", vec!["Font color: Automatic"]), ("borders", vec!["Color: Automatic"]), ("shading", vec!["Fill No Color"])] {
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.run_steps(2);
open_named(&mut h, dialog, json!({}));
for name in names {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "{dialog}: {name}");
}
}
h.query_all_by_role_and_label(Role::Button, "Fill No Color").last().expect("shading colour field").click();
h.run_steps(3);
h.get_by_label("#C00000").click();
h.run_steps(3);
assert!(h.query_all_by_role_and_label(Role::Button, "Fill #C00000").next().is_some());
let ctx = h.ctx.clone();
close_all(h.state_mut(), &ctx);
h.state_mut().run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
open_named(&mut h, "newTableStyle", json!({}));
for name in ["Font color: No Color", "Fill color: No Color"] {
assert!(h.query_all_by_role_and_label(Role::Button, name).next().is_some(), "newTableStyle: {name}");
}
// Draw the shared app field directly: the app frame selects its configured language.
crate::i18n::apply_language(crate::i18n::fixture_lang(
"x-fixture",
"\tFont color:\tFont-color-FX:\n\tAutomatic\tAutomatic-FX\n\tFill\tFill-FX\n\tNo Color\tNo-Color-FX\n",
));
let mut h = crate::test_harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state(
|ui, values: &mut [String; 2]| {
use crate::colors::{AutoFace, ColorFieldEmpty, Palette, color_field};
use craft::ui::runtime::env::Label;
ui.push_id("font", |ui| {
let empty = ColorFieldEmpty::Automatic {
label: Label::from(tl!("Automatic")),
value: "auto",
face: AutoFace::One(craft::theme::Srgba::rgb(0.0, 0.0, 0.0)),
};
color_field(ui, &Label::from(tl!("Font color:")), &mut values[0], &empty, &Palette::default());
});
ui.push_id("fill", |ui| {
color_field(ui, &Label::from(tl!("Fill")), &mut values[1], &ColorFieldEmpty::NoColor, &Palette::default());
});
},
["auto".to_string(), String::new()],
);
h.run_steps(3);
let found: Vec<_> = ["Font-color-FX: Automatic-FX", "Fill-FX No-Color-FX"]
.into_iter()
.map(|name| (name, h.query_all_by_role_and_label(Role::Button, name).next().is_some()))
.collect();
crate::i18n::apply_language(crate::i18n::Lang::EN);
for (name, present) in found {
assert!(present, "the translated field is {name}");
}
}
+1 -54
View File
@@ -18,8 +18,7 @@ use crate::WordApp;
/// Most font files one Add Font pick tries; the rest of a bigger selection is skipped.
const MAX_FONTS_PER_PICK: usize = 2000;
/// Picture suffixes shared by native/web choosers, drop dispatch and copied-file paste.
pub const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff", "wmf", "emf"];
const PICTURES: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
const DOCUMENTS: &[&str] =
&["docx", "docm", "dotx", "dotm", "doc", "dot", "odt", "ott", "fodt", "rtf", "txt", "md", "html", "htm", "mht", "mhtml", "tex", "json", "xml"];
@@ -35,11 +34,6 @@ pub fn open_filters(purpose: &str) -> &'static [(&'static str, &'static [&'stati
}
}
/// Whether a file name has a picture suffix offered by the Insert/Change Picture chooser.
pub(crate) fn is_picture_name(name: &str) -> bool {
name.rsplit_once('.').is_some_and(|(_, ext)| PICTURES.iter().any(|known| known.eq_ignore_ascii_case(ext)))
}
/// `request` with the file types `open_filters` offers for `purpose`.
fn with_open_filters(mut request: PickRequest, purpose: &str) -> PickRequest {
for (label, exts) in open_filters(purpose) {
@@ -531,50 +525,3 @@ impl WordApp {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod picture_dispatch_tests {
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::platform::open::{DropTarget, DroppedFile, FileIntake};
use super::*;
/// Pickers, drops and copied paths must agree on TIFF suffixes after the framework cutover.
#[test]
fn tiff_suffixes_dispatch_picked_and_dropped_images_and_copied_paths_as_pictures() {
for ext in ["tif", "tiff", "TIF", "TIFF"] {
let name = format!("scan.{ext}");
// Routing depends on the supplied name; the insertion decoder probes these PNG bytes.
let bytes = crate::paste_picture::png_from_rgba(4, 4, vec![200; 4 * 4 * 4]).unwrap();
let files = Arc::new(ScriptedFiles::held());
let host = Host::builder(AppInfo { id: "wordcraft-test", name: "WordCraft", version: "0" }).files(files.clone()).build();
let session = wordcraft_engine::Session::new(wordcraft_doc::Document::new());
let mut app = WordApp::new(session, crate::Services::default()).with_host(Arc::new(host));
let document = app.session.document_id();
app.pick_picture();
let request = files.requests().pop().unwrap();
let extensions: Vec<_> = request.filters.iter().flat_map(|f| f.extensions.iter().map(String::as_str)).collect();
assert!(extensions.contains(&"tif") && extensions.contains(&"tiff") && extensions.contains(&"png"));
assert!(!extensions.contains(&"txt"));
files.answer(Picked::Contents(vec![(name.clone(), bytes.clone())]));
app.poll_file_dialog().unwrap().unwrap();
assert_eq!(app.session.document_id(), document, "picker inserts into the current document: {ext}");
let pictures = app.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "picker inserts a picture: {ext}");
let (intake, sender) = FileIntake::new(craft::host::Wake::none());
let services = crate::Services { intake: Some(intake), ..Default::default() };
let mut dropped = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), services);
let document = dropped.session.document_id();
sender.dropped(vec![DroppedFile { path: None, name, bytes: Some(bytes.into()) }], DropTarget::Elsewhere);
dropped.drain_inbox();
assert_eq!(dropped.session.document_id(), document, "drop inserts into the current document: {ext}");
let pictures = dropped.session.run("arrange.selectionPane", &json!({})).unwrap();
assert_eq!(pictures.as_array().unwrap().len(), 1, "drop inserts a picture: {ext}");
assert!(crate::paste_picture::names_picture_files(&format!("file:///tmp/scan.{ext}")));
}
assert!(!is_picture_name("notes.txt"));
}
}
+3 -4
View File
@@ -704,10 +704,9 @@ fn type_text(app: &mut WordApp, pass: &ToolPass, ctx: &egui::Context, text: &str
let start = app.session.sel.ordered().0;
let pending_before = app.session.pending.clone();
let typed = if let Some(props) = app.canvas.ime_join_text.take() {
// The replacement takes the erased text's formatting. A failed `Session::run` puts back
// what was waiting when it started, which is this formatting, so the earlier one is put
// back here: a refused replacement must not leave its formatting waiting for the next
// ordinary key.
// The replacement takes the erased text's formatting. `Session::run` does not restore
// `pending` on failure (it is not part of the document snapshot), so keep it here: a
// refused replacement must not leave its formatting waiting for the next ordinary key.
// The undo join itself is the engine's scoped body-replacement promise, consumed by
// `Session::run` only for this `text.insert` at the promised selection.
app.session.pending = Some(props);
+4 -3
View File
@@ -248,6 +248,7 @@ fn restored_placeholder_end(s: &wordcraft_engine::Session, deleted_start: usize)
struct ImeRollback {
snapshot: Option<wordcraft_engine::EditSnapshot>,
original: wordcraft_engine::Selection,
pending: Option<wordcraft_doc::props::CharProps>,
goal_x: Option<f32>,
}
@@ -257,9 +258,8 @@ impl ImeRollback {
return;
};
app.session.restore(snapshot);
// The snapshot puts back the formatting waiting at the caret, with where Backspace
// carried it over (#6518).
app.session.sel = self.original.clone();
app.session.pending = self.pending.clone();
app.session.goal_x = self.goal_x;
refuse_ime_request(app);
}
@@ -387,6 +387,7 @@ fn delete_surrounding_common(
let join = app.session.typing_open();
let props = app.session.typing_props();
let original = app.session.sel.clone();
let pending_before = app.session.pending.clone();
let goal_x_before = app.session.goal_x;
let before_stamp = ime_stamp(app);
// Both sides are one IME request: if the second half is refused (Restrict Editing, a
@@ -396,7 +397,7 @@ fn delete_surrounding_common(
// restored: `last_command`, macro recording, Go Back marks, `also_selected`, `typing`/
// `autocap` and canvas preedit (a refusal clears it).
let snapshot = app.session.edit_snapshot();
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, goal_x: goal_x_before };
let mut rollback = ImeRollback { snapshot: Some(snapshot), original, pending: pending_before, goal_x: goal_x_before };
// Stored offsets of the suffix (and of the original selection) move by the paragraph's
// signed length change. A placeholder can make that positive; subtracting a removed-byte
// count cannot describe that, and would leave the second range and the caret inside the
-28
View File
@@ -888,34 +888,6 @@ fn tracked_own_insertion_then_a_refused_side_rolls_the_whole_request_back() {
assert_eq!(h.state().session.goal_x, Some(123.0), "the Up/Down goal column is restored");
}
/// #6518 review: a refused `DeleteSurrounding` rolls back the formatting Backspace carried
/// over together with where it applies: typing at the restored caret still takes it, and a
/// caret moved away leaves it behind, as before the request.
#[test]
fn a_refused_delete_surrounding_keeps_formatting_backspace_carried() {
let mut h = alt_frame_app();
run(&mut h, "document.setText", json!({"text": "abc"}));
// Wrap `c` in a rich-text control that refuses edits, and make `b` bold.
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 2), focus: wordcraft_doc::Pos::body(0, 3) };
run(&mut h, "developer.richText", json!({"tag": "locked"}));
run(&mut h, "developer.properties", json!({"control": "locked", "lockEdit": true}));
h.state_mut().session.sel = wordcraft_engine::Selection { anchor: wordcraft_doc::Pos::body(0, 1), focus: wordcraft_doc::Pos::body(0, 2) };
run(&mut h, "format.bold", json!({"value": true}));
caret(&mut h, 2);
// Backspace the bold `b`: the caret, now after `a`, carries its bold.
run(&mut h, "text.backspace", json!({}));
assert_eq!(h.state().session.typing_props().bold, Some(true));
alt_frame(&mut h, vec![surround(1, 1)]);
assert_eq!(body(h.state()), "ac", "the request is refused and rolled back");
assert_eq!(h.state().session.sel, wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_eq!(h.state().session.typing_props().bold, Some(true), "the carried bold still applies at the restored caret");
// It is still carried over by Backspace, not picked at the caret: a caret moved elsewhere
// and back leaves it behind.
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 0)));
h.state_mut().session.set_selection(wordcraft_engine::Selection::caret(wordcraft_doc::Pos::body(0, 1)));
assert_ne!(h.state().session.typing_props().bold, Some(true), "the caret has been elsewhere");
}
/// Selects a body range, wraps it in a rich-text content control with `tag`, and sets its
/// placeholder.
fn wrap_in_control(h: &mut H, start: usize, end: usize, tag: &str, placeholder: &str) {
-3
View File
@@ -101,7 +101,6 @@ pub use dialogs::dialogs_ribbon;
pub use dialogs::dialogs_smart_art;
pub use file_dialogs::open_filters;
mod announce;
mod app;
mod services;
mod state;
@@ -417,8 +416,6 @@ pub struct WordApp {
pub spelling_review: Option<proofing_pane::SpellingForm>,
/// The status bar's message, until its `until` passes.
pub(crate) status: Option<Status>,
/// The latest formatting shortcut announcement for the active window.
pub(crate) announcement: Option<announce::Announcement>,
pub previews: previews::Previews,
/// Media key of the picture a pending Change Picture replaces (#147).
pub change_picture_target: Option<String>,
+2 -1
View File
@@ -18,6 +18,7 @@ use crate::{WordApp, system_clipboard};
pub(crate) const MAX_FILE_BYTES: u64 = 200 << 20;
/// Most picture files one paste inserts.
const MAX_FILES: usize = 20;
const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "wmf", "emf"];
/// PNG bytes for clipboard pixels, or why they can't be pasted. The platform read has checked the
/// size already.
@@ -30,7 +31,7 @@ pub fn png_from_rgba(width: usize, height: usize, rgba: Vec<u8>) -> Result<Vec<u
}
fn is_picture_file(path: &Path) -> bool {
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| crate::file_dialogs::PICTURES.iter().any(|x| x.eq_ignore_ascii_case(e)))
path.extension().and_then(std::ffi::OsStr::to_str).is_some_and(|e| IMAGE_EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
}
/// Pasted text that is only paths or `file://` addresses of picture files — what file managers
+1 -1
View File
@@ -41,7 +41,7 @@ pub fn poll(app: &mut WordApp, ctx: &egui::Context) {
let current = if reads_shown_document(app) { app.session.read_aloud.current().map(|u| u.start) } else { None };
if current != app.read_aloud_at {
if let Some(start) = &current {
app.session.set_selection(wordcraft_engine::Selection::caret(app.session.doc.clamp(start)));
app.session.sel = wordcraft_engine::Selection::caret(app.session.doc.clamp(start));
app.session.goal_x = None;
app.canvas.scroll_to_caret = true;
}
+1 -1
View File
@@ -245,7 +245,7 @@ fn enforced_ui(app: &mut WordApp, ui: &mut Ui, st: &mut RestrictPane, mode: &str
if (regions > 0 || fields > 0) && Button::new(tl!("Find Next Editable Region")).show(ui).clicked() {
let from = app.session.sel.ordered().1;
if let Some((a, b)) = wordcraft_engine::cmd::protect::next_region(&app.session, &from) {
app.session.set_selection(wordcraft_engine::Selection { anchor: a, focus: b });
app.session.sel = wordcraft_engine::Selection { anchor: a, focus: b };
app.canvas.focus_page(ui.ctx());
}
}
-5
View File
@@ -22,8 +22,6 @@ pub(crate) struct WindowUi {
pub(crate) restrict: crate::restrict_pane::RestrictPane,
pub(crate) spelling_review: Option<crate::proofing_pane::SpellingForm>,
pub(crate) status: Option<Status>,
/// Announcement belonging to this document window.
pub(crate) announcement: Option<crate::announce::Announcement>,
pub(crate) previews: previews::Previews,
pub(crate) change_picture_target: Option<String>,
pub(crate) recipient_list_pending: bool,
@@ -76,7 +74,6 @@ impl WindowUi {
restrict: Default::default(),
spelling_review: None,
status: None,
announcement: None,
previews: Default::default(),
change_picture_target: None,
recipient_list_pending: false,
@@ -187,7 +184,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
@@ -285,7 +281,6 @@ impl WordApp {
restrict,
spelling_review,
status,
announcement,
previews,
change_picture_target,
recipient_list_pending,
+19 -2
View File
@@ -94,6 +94,9 @@ pub struct Windows {
/// Whether the root OS window had focus in the last pass; a [`DocumentWindow`] reports its own gain
/// (`focus_gained`), the root's is read from the window host's facts.
root_focused: bool,
/// The room each window's last draw had, by window key (tests read it).
#[cfg(test)]
drawn: std::collections::HashMap<u64, egui::Rect>,
}
impl Windows {
@@ -101,7 +104,16 @@ impl Windows {
pub(crate) fn new(doc: u64) -> Windows {
let mut list = WindowList::new();
let id = list.open(Window::new(doc, None, None, false));
Windows { native: cfg!(not(target_arch = "wasm32")), list, root: id, shown: id, arranged: arrange::State::default(), root_focused: false }
Windows {
native: cfg!(not(target_arch = "wasm32")),
list,
root: id,
shown: id,
arranged: arrange::State::default(),
root_focused: false,
#[cfg(test)]
drawn: Default::default(),
}
}
/// Whether documents get native windows of their own.
@@ -528,7 +540,10 @@ impl WordApp {
let (raise, place) = (std::mem::take(&mut w.raise), std::mem::take(&mut w.place));
let mut window = DocumentWindow::new(Self::title_in(&menu, id))
.id(window_container_id(id))
.overlay(|overlay| overlay.size_limits(SizeLimits::at_least(MIN_SIZE)));
// The window's body is the whole interface, which lays itself out in the window's room. A
// scrolling body gives it an unbounded height instead (#7149 item 5): the interface lands
// 32768 points tall, off the window, and the window shows nothing.
.overlay(|overlay| overlay.size_limits(SizeLimits::at_least(MIN_SIZE)).body_scroll(false));
if raise {
window = window.raise();
}
@@ -586,6 +601,8 @@ impl WordApp {
if self.windows.shown() != key {
return;
}
#[cfg(test)]
self.windows.drawn.insert(key, ui.max_rect());
self.window_ui(ui);
arrange::forward_scroll(self, &ctx);
}
+18
View File
@@ -139,6 +139,24 @@ fn new_opens_a_second_window_and_each_keeps_its_state() {
assert_eq!((text(&a), a.ui.tab.as_str(), prompt(&a).as_deref()), ("Second".into(), crate::DEFAULT_TAB, None));
}
/// Each window draws its interface in the room its OS window gives it. A window's body that scrolls lays the
/// interface out 32768 points tall, so a second window opened blank (#7149 item 5).
#[test]
fn a_second_window_draws_its_interface_in_the_room_of_its_window() {
let mut rig = Rig::new();
let mut a = app("First");
rig.frames(&mut a, 3);
a.run("file.new", json!({})).unwrap();
rig.frames(&mut a, 6);
let child = a.active_viewport();
assert_ne!(child, ViewportId::ROOT);
assert!(rig.drawn.contains(&child), "the second window draws: {:?}", rig.drawn);
let key = a.windows.active().unwrap();
let room = a.windows.drawn.get(&key).copied().unwrap();
// The kit's child window is 400 by 300 points.
assert!(room.height() <= 300.0 && room.min.y >= 0.0, "the interface has the window's room, not {room:?}");
}
/// Each window has its own key, and the root window's stays `main` when it adopts another entry.
#[test]
fn window_keys_differ_and_the_root_keeps_main() {
File diff suppressed because one or more lines are too long
+2 -4
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -4
View File
File diff suppressed because one or more lines are too long