diff --git a/crates/actions/src/as3/ir.rs b/crates/actions/src/as3/ir.rs index ec3f1978..f0055cba 100644 --- a/crates/actions/src/as3/ir.rs +++ b/crates/actions/src/as3/ir.rs @@ -375,9 +375,26 @@ pub enum Prop { /// `field.length`: a bare `text` is a variable. Text, Length, + /// A text field's text as HTML (ADR 0107): the subset Flash text fields took, read back + /// from its styled runs. + HtmlText, + /// The most characters a viewer may type into an input field (0: no limit). + MaxChars, + /// The characters a viewer may type into an input field (`null`: any), as ActionScript's + /// `TextField.restrict` writes them. + Restrict, } impl Prop { + /// A member of a text field only (`field.text`, `field.htmlText`, …). + pub fn is_field(self) -> bool { + matches!(self, Prop::Text | Prop::Length | Prop::HtmlText | Prop::MaxChars | Prop::Restrict) + } + /// A text field member a script may also set. + pub fn field_settable(self) -> bool { + matches!(self, Prop::Text | Prop::HtmlText | Prop::MaxChars | Prop::Restrict) + } + pub fn from_name(s: &str) -> Option { Some(match s { "x" => Prop::X, @@ -402,6 +419,9 @@ impl Prop { match s { "text" => Some(Prop::Text), "length" => Some(Prop::Length), + "htmlText" => Some(Prop::HtmlText), + "maxChars" => Some(Prop::MaxChars), + "restrict" => Some(Prop::Restrict), _ => Prop::from_name(s), } } @@ -422,6 +442,9 @@ impl Prop { Prop::Name => "name", Prop::Text => "text", Prop::Length => "length", + Prop::HtmlText => "htmlText", + Prop::MaxChars => "maxChars", + Prop::Restrict => "restrict", } } /// The instance property a script may also set. @@ -535,6 +558,9 @@ pub enum LValue { Prop { at: Place, p: Property }, /// A text field's text (`field.text = …`, `field.appendText(…)` as `+=`). Text { at: Place }, + /// Another member of a text field a script sets (`htmlText`, `maxChars`, `restrict`; + /// ADR 0107). + Field { at: Place, p: Prop }, } /// An expression. @@ -644,6 +670,8 @@ pub enum ListenEvent { /// `KeyboardEvent.KEY_DOWN` / `KEY_UP` on the stage. KeyDown, KeyUp, + /// `Event.CHANGE` on an input text field: the viewer changed its text (ADR 0107). + Change, } impl ListenEvent { @@ -657,6 +685,7 @@ impl ListenEvent { ListenEvent::EnterFrame => "enter_frame", ListenEvent::KeyDown => "key_down", ListenEvent::KeyUp => "key_up", + ListenEvent::Change => "change", } } /// The pointer event it is, for mouse listeners. diff --git a/crates/actions/src/as3/lower.rs b/crates/actions/src/as3/lower.rs index 385b682c..0e86e055 100644 --- a/crates/actions/src/as3/lower.rs +++ b/crates/actions/src/as3/lower.rs @@ -349,6 +349,10 @@ impl<'a> Lower<'a> { self.note(pos, "keys go to the stage here: listen with `stage.addEventListener(KeyboardEvent.KEY_DOWN, …)`; this listener is ignored"); return None; } + if event == ListenEvent::Change && (at.base == Base::Stage || (at.base == Base::This && at.path.is_this())) { + self.problem(pos, "`Event.CHANGE` comes from an input text field: listen on the field, as in `name_txt.addEventListener(Event.CHANGE, onChange)`"); + return None; + } if at.base == Base::Stage && event.mouse().is_some() { self.problem(pos, "mouse listeners on the stage aren't supported yet (on buttons and movie clips they are)"); return None; @@ -414,6 +418,7 @@ impl<'a> Lower<'a> { ("MouseEvent", "ROLL_OVER" | "MOUSE_OVER") => Some(ListenEvent::Over), ("MouseEvent", "ROLL_OUT" | "MOUSE_OUT") => Some(ListenEvent::Out), ("Event", "ENTER_FRAME") => Some(ListenEvent::EnterFrame), + ("Event", "CHANGE") => Some(ListenEvent::Change), ("KeyboardEvent", "KEY_DOWN") => Some(ListenEvent::KeyDown), ("KeyboardEvent", "KEY_UP") => Some(ListenEvent::KeyUp), _ => None, @@ -429,6 +434,7 @@ impl<'a> Lower<'a> { "rollOver" | "mouseOver" => Some(ListenEvent::Over), "rollOut" | "mouseOut" => Some(ListenEvent::Out), "enterFrame" => Some(ListenEvent::EnterFrame), + "change" => Some(ListenEvent::Change), "keyDown" => Some(ListenEvent::KeyDown), "keyUp" => Some(ListenEvent::KeyUp), _ => None, @@ -440,7 +446,7 @@ impl<'a> Lower<'a> { } }; if key.is_none() { - self.problem(e.pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT, Event.ENTER_FRAME and KeyboardEvent.KEY_DOWN and KEY_UP are)")); + self.problem(e.pos, format!("listening for {name} isn't supported yet (mouse CLICK, MOUSE_DOWN, MOUSE_UP, ROLL_OVER and ROLL_OUT, Event.ENTER_FRAME, Event.CHANGE on input text fields, and KeyboardEvent.KEY_DOWN and KEY_UP are)")); } key } @@ -649,9 +655,10 @@ impl<'a> Lower<'a> { Some(LValue::Var { n: n.clone() }) } E::Member(o, m) if m == "text" => Some(LValue::Text { at: self.field_place(o, u)? }), + E::Member(o, m) if matches!(m.as_str(), "htmlText" | "maxChars" | "restrict") => Some(LValue::Field { at: self.field_place(o, u)?, p: Prop::from_member(m)? }), E::Member(o, m) => { let Some(p) = Prop::from_member(m) else { - self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY and a text field's text are)")); + self.problem(e.pos, format!("setting `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY and a text field's text, htmlText, maxChars and restrict are)")); return None; }; let Some(p) = p.settable() else { @@ -863,10 +870,10 @@ impl<'a> Lower<'a> { return None; } let Some(p) = Prop::from_member(m) else { - self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY, name, and a text field's text and length are)")); + self.problem(e.pos, format!("reading `{m}` isn't supported yet (x, y, alpha, visible, rotation, scaleX, scaleY, currentFrame, totalFrames, currentLabel, mouseX, mouseY, name, and a text field's text, htmlText, length, maxChars and restrict are)")); return None; }; - let at = if matches!(p, Prop::Text | Prop::Length) { self.field_place(o, u)? } else { self.place(o, u)? }; + let at = if p.is_field() { self.field_place(o, u)? } else { self.place(o, u)? }; if at.base == Base::Stage && !matches!(p, Prop::MouseX | Prop::MouseY) { self.problem(e.pos, format!("`stage.{m}` isn't supported yet")); return None; diff --git a/crates/actions/src/as3/run.rs b/crates/actions/src/as3/run.rs index b137aa1b..06adca3e 100644 --- a/crates/actions/src/as3/run.rs +++ b/crates/actions/src/as3/run.rs @@ -51,6 +51,9 @@ pub trait World { fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option>; /// Sets a text field's text (ADR 0066). fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option>; + /// Sets another member of a text field (`htmlText`: text; `maxChars`: a number; + /// `restrict`: text or `null`; ADR 0107). + fn set_field(&mut self, at: &Place, p: Prop, v: Value) -> Result<(), Option>; fn trace(&mut self, line: String); /// A timeline variable's value, and writing one (the world knows its type). fn read(&mut self, name: &str) -> Result; @@ -358,6 +361,7 @@ impl Vm<'_> { self.w.get(at, prop).map_err(|message| Stop::Error { line: self.line, message }) } LValue::Text { at } => self.w.get(at, Prop::Text).map_err(|message| Stop::Error { line: self.line, message }), + LValue::Field { at, p } => self.w.get(at, *p).map_err(|message| Stop::Error { line: self.line, message }), } } @@ -391,6 +395,25 @@ impl Vm<'_> { self.w.set_text(at, v.text()).map_err(|e| lift(self.line, e))?; Ok(v) } + LValue::Field { at, p } => { + let v = match p { + Prop::HtmlText if matches!(v, Value::Null | Value::Undefined) => return self.err(format!("`htmlText` is set to text, not {}", v.text())), + Prop::HtmlText => Value::str(&v.text()), + Prop::MaxChars => { + let n = v.number(); + if !n.is_finite() { + return self.err(format!("`maxChars` is set to a number, not {}", shown(&v))); + } + // An `int`: whole, and never negative here (0 is no limit). + Value::Num(n.trunc().clamp(0.0, 2_147_483_647.0) + 0.0) + } + Prop::Restrict if matches!(v, Value::Null | Value::Undefined) => Value::Null, + Prop::Restrict => Value::str(&v.text()), + _ => return self.err(format!("`{}` can only be read", p.name())), + }; + self.w.set_field(at, *p, v.clone()).map_err(|e| lift(self.line, e))?; + Ok(v) + } } } diff --git a/crates/actions/src/as3/tests.rs b/crates/actions/src/as3/tests.rs index 24ad6119..01cbdb69 100644 --- a/crates/actions/src/as3/tests.rs +++ b/crates/actions/src/as3/tests.rs @@ -32,6 +32,8 @@ struct Mock { frame: u32, /// Text fields' text, by name. texts: BTreeMap, + /// Text fields' other members a script set (`maxChars`, `restrict`), by name. + members: BTreeMap<(String, &'static str), Value>, } impl World for Mock { @@ -50,10 +52,11 @@ impl World for Mock { Prop::CurrentFrame => Value::Num(f64::from(self.frame + 1)), Prop::Name => Value::str(&at.to_string()), Prop::Visible => Value::Bool(true), - Prop::Text | Prop::Length => { + Prop::Text | Prop::Length | Prop::HtmlText => { let t = self.texts.get(&at.path.0).ok_or_else(|| format!("“{at}” isn't a text field"))?; - if p == Prop::Text { Value::str(t) } else { Value::Num(text_len(t) as f64) } + if p == Prop::Length { Value::Num(text_len(t) as f64) } else { Value::str(t) } } + Prop::MaxChars | Prop::Restrict => self.members.get(&(at.path.0.clone(), p.name())).cloned().unwrap_or(if p == Prop::MaxChars { Value::Num(0.0) } else { Value::Null }), p => Value::Num(self.props.get(&(at.path.0.clone(), p.name())).copied().unwrap_or(0.0)), }) } @@ -79,6 +82,18 @@ impl World for Mock { self.texts.insert(at.path.0.clone(), text); Ok(()) } + fn set_field(&mut self, at: &Place, p: Prop, v: Value) -> Result<(), Option> { + if !self.texts.contains_key(&at.path.0) { + return Err(Some(format!("“{at}” isn't a text field"))); + } + self.log.push(format!("{} {at} = {}", p.name(), v.text())); + if p == Prop::HtmlText { + self.texts.insert(at.path.0.clone(), v.text()); + } else { + self.members.insert((at.path.0.clone(), p.name()), v); + } + Ok(()) + } fn trace(&mut self, line: String) { self.log.push(line); } @@ -566,3 +581,47 @@ fn surrogate_pair_escapes() { assert_eq!(lines(r#"trace("é\uD83D\uDE00");"#), vec!["é😀".to_string()]); assert_eq!(lines(r#"trace("\uD83Dx\uDE00");"#), vec!["\u{FFFD}x\u{FFFD}".to_string()]); } + +#[test] +fn scripts_set_html_text_limits_and_listen_for_changes() { + let src = r#" + name_txt.htmlText = "Hi"; + name_txt.maxChars = 8.9; + name_txt.restrict = "A-Z 0-9"; + trace(name_txt.htmlText, name_txt.maxChars, name_txt.restrict); + name_txt.restrict = null; + name_txt.maxChars += 2; + trace(name_txt.maxChars, name_txt.restrict); + function onChange(e:Event):void { trace("changed " + e.target.text); } + name_txt.addEventListener(Event.CHANGE, onChange); + name_txt.addEventListener("change", function (e:Event):void { trace("too"); }); + name_txt.removeEventListener(Event.CHANGE, onChange); + "#; + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("name_txt".into(), String::new()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert_eq!(r, Ok(()), "{:?}", m.log); + assert!(m.log.contains(&"Hi 8 A-Z 0-9".to_string()), "{:?}", m.log); + assert!(m.log.contains(&"10 null".to_string()), "{:?}", m.log); + // The IR names the event and the members (what the HTML page's player reads). + let json = serde_json::to_string(&c).unwrap(); + assert!(json.contains("\"ev\":\"change\"") && json.contains("\"p\":\"html_text\"") && json.contains("\"p\":\"max_chars\"") && json.contains("\"k\":\"field\""), "{json}"); + // What can't be: a null htmlText, a maxChars that isn't a number, writing length, and + // change listeners on the stage or the timeline. + for (src, want) in [ + ("name_txt.htmlText = null;", "`htmlText` is set to text"), + ("name_txt.maxChars = \"many\";", "`maxChars` is set to a number"), + ] { + let c = ok(src); + let mut m = Mock { decls: Decls::build([&c]), ..Mock::default() }; + m.texts.insert("name_txt".into(), String::new()); + let (_, r) = run::run_script(&mut m, &c.body, &c.inner, run::FUEL_PER_RUN); + assert!(matches!(&r, Err(Stop::Error { message, .. }) if message.contains(want)), "{src}: {r:?}"); + } + assert!(err("name_txt.length = 3;").2.contains("can only be read")); + assert!(err("function f(e:Event):void {} stage.addEventListener(Event.CHANGE, f);").2.contains("input text field")); + assert!(err("function f(e:Event):void {} addEventListener(Event.CHANGE, f);").2.contains("input text field")); + assert!(err("this.htmlText = \"x\";").2.contains("isn't a text field")); +} + diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index bfd9771a..53e3e748 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -1089,6 +1089,11 @@ fn field_items(t: &crate::TextBlock, f: &crate::TextField, live: Option<(Option< // The text: laid out by the player when it changed, else the authored outline (a field whose // text changed but couldn't be laid out shows none). match (state.and_then(|s| s.text.as_ref()), look) { + (_, Some(l)) if !l.pieces.is_empty() => { + for (color, piece) in l.pieces.iter() { + out.items.push(item(piece.clone(), text_xf, Some(Paint::Solid(*color)), None, Some(inner), None)); + } + } (_, Some(l)) => out.items.push(item(l.outline.clone(), text_xf, Some(Paint::Solid(t.color)), None, Some(inner), None)), (None, None) => text_fills(t, out, |path, color| item(path, text_xf, Some(Paint::Solid(color)), None, Some(inner), None)), (Some(_), None) => {} diff --git a/crates/doc/src/field.rs b/crates/doc/src/field.rs index b3eb7685..94c5c04e 100644 --- a/crates/doc/src/field.rs +++ b/crates/doc/src/field.rs @@ -7,7 +7,8 @@ //! [`FieldLook`] whenever a field's text changes and keeps it in the state; drawing a state then //! needs nothing else. -use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, TextBlock, TextField, TextKind}; +use crate::html_text::RichStyles; +use crate::{FIELD_GUTTER, LineType, MAX_FIELD_CHARS, Rgba, TextBlock, TextField, TextKind}; use anicraft_geom::{Path, Vec2}; use std::sync::Arc; @@ -53,6 +54,9 @@ impl CaretLine { #[derive(Clone, Debug, PartialEq)] pub struct FieldLook { pub outline: Arc, + /// The outline cut by colour, when the text has several (`htmlText`, ADR 0107): drawn in + /// place of `outline`. Empty: all of it in the field's colour. + pub pieces: Arc<[(Rgba, Arc)]>, /// Top line first; never empty. pub lines: Arc<[CaretLine]>, /// From one line's top to the next's. @@ -106,6 +110,13 @@ pub struct FieldState { pub anchor: u32, /// How far the text has scrolled to keep the caret in view (pixels, never negative). pub scroll: Vec2, + /// The text's styles once a script set `htmlText` (ADR 0107); `None`: the field's own + /// style (or, while `text` is `None`, the authored runs). + pub rich: Option>, + /// `maxChars` once a script set it (`None`: the field's own). + pub max_chars: Option, + /// `restrict` once a script set it: the characters a viewer may type (`None`: any). + pub restrict: Option, } impl FieldState { @@ -149,6 +160,45 @@ pub fn fit(field: &TextField, text: &str) -> String { text.replace("\r\n", "\n").replace('\r', "\n").chars().take(MAX_FIELD_CHARS).collect() } +/// Whether `restrict` lets a viewer type `c` (ADR 0107), as ActionScript's +/// `TextField.restrict` reads: the characters listed are allowed, `a-z` is a range, a `^` +/// turns what follows into characters that are not allowed (and back), and `\` before `-`, +/// `^` or `\` makes it a plain character. A string starting with `^` allows everything else; +/// an empty string allows nothing. +pub fn allowed(restrict: &str, c: char) -> bool { + let r: Vec = restrict.chars().take(1024).collect(); + let mut ok = r.first() == Some(&'^'); + let mut include = true; + let mut i = 0; + // One character of the list at `i` (escapes read), and the index after it. + let item = |i: usize| -> Option<(char, usize)> { + match r.get(i).copied()? { + '\\' => r.get(i + 1).map(|c| (*c, i + 2)), + ch => Some((ch, i + 1)), + } + }; + while i < r.len() { + if r.get(i) == Some(&'^') { + include = !include; + i += 1; + continue; + } + let Some((lo, next)) = item(i) else { break }; + i = next; + let mut hi = lo; + if r.get(i) == Some(&'-') + && let Some((end, after)) = item(i + 1) + { + hi = end; + i = after; + } + if (lo..=hi).contains(&c) { + ok = include; + } + } + ok +} + /// What an editing key does (the ActionScript key codes the player receives). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Edit { @@ -212,11 +262,13 @@ impl Editor<'_> { return Changed::default(); } let one = !self.field.lines.multiline(); - let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).collect(); + let restrict = self.st.restrict.clone(); + let mut add: String = s.chars().filter(|c| !c.is_control() || (*c == '\n' && !one)).filter(|c| *c == '\n' || restrict.as_deref().is_none_or(|r| allowed(r, *c))).collect(); let (a, b) = self.st.selection(); let value = self.st.value(self.block).to_string(); let kept = chars(&value) - (b - a); - let room = if self.field.max_chars > 0 { self.field.max_chars.saturating_sub(kept) } else { u32::MAX }; + let max = self.st.max_chars.unwrap_or(self.field.max_chars); + let room = if max > 0 { max.saturating_sub(kept) } else { u32::MAX }; let room = room.min((MAX_FIELD_CHARS as u32).saturating_sub(kept)); if chars(&add) > room { add = add.chars().take(room as usize).collect(); @@ -229,6 +281,12 @@ impl Editor<'_> { next.push_str(&add); next.push_str(slice(&value, b, u32::MAX)); let caret = a + chars(&add); + // Styled text keeps its runs: what is typed continues the style before it (ADR 0085). + if let Some(rich) = &self.st.rich { + let runs = crate::rich_text::type_into_runs(&rich.runs, a, b, chars(&add)); + let paragraphs = crate::rich_text::edit_paragraphs(&rich.paragraphs, &value, a, b, &add); + self.st.rich = Some(Arc::new(RichStyles { runs, paragraphs })); + } self.st.text = Some(next); self.st.caret = caret; self.st.anchor = caret; @@ -382,7 +440,7 @@ pub(crate) fn mono_look(text: &str, cw: f32, lh: f32, wrap: Option) -> Fiel } lines.push(CaretLine { start, end: i, stops }); let n = lines.len(); - FieldLook { outline: Arc::new(outline), lines: lines.into(), line_height: lh, width, height: n as f32 * lh } + FieldLook { outline: Arc::new(outline), pieces: Arc::from(Vec::new()), lines: lines.into(), line_height: lh, width, height: n as f32 * lh } } #[cfg(test)] diff --git a/crates/doc/src/field_tests.rs b/crates/doc/src/field_tests.rs index 7279e72c..dd73adf9 100644 --- a/crates/doc/src/field_tests.rs +++ b/crates/doc/src/field_tests.rs @@ -180,3 +180,22 @@ fn script_text_is_capped_and_takes_actionscript_line_ends() { assert_eq!(slice("héllo", 4, 99), "o"); assert_eq!(byte_at("héllo", 2), 3); } + +#[test] +fn restrict_reads_as_actionscript_writes_it() { + let ok = |r: &str, s: &str| s.chars().filter(|c| allowed(r, *c)).collect::(); + assert_eq!(ok("A-Z 0-9", "Ab 9-z"), "A 9"); + assert_eq!(ok("^a-z", "aBc1"), "B1", "everything but lower case"); + assert_eq!(ok("A-Z^Q", "PQR"), "PR", "capitals, but not Q"); + assert_eq!(ok("^a-z^m", "almz"), "m", "excluded, then let back in"); + assert_eq!(ok("0-9\\-", "1-2a"), "1-2", "an escaped hyphen is a character"); + assert_eq!(ok("\\^\\\\", "^\\a"), "^\\"); + assert_eq!(ok("", "abc"), "", "an empty list allows nothing"); + assert_eq!(ok("abc-", "a-c"), "a-c", "a trailing hyphen is itself"); + assert_eq!(ok("z-a", "amz"), "", "a backwards range holds nothing"); + assert_eq!(ok("é-ü😀", "é😀a"), "é😀"); + // Long and odd lists are read without trouble. + assert!(!allowed(&"^".repeat(5000), 'a') || allowed(&"^".repeat(5000), 'a')); + assert!(allowed(&"\\".repeat(1023), '\\')); +} + diff --git a/crates/doc/src/html_text.rs b/crates/doc/src/html_text.rs new file mode 100644 index 00000000..8aa80256 --- /dev/null +++ b/crates/doc/src/html_text.rs @@ -0,0 +1,489 @@ +//! `htmlText` (ADR 0107): the small HTML Flash text fields took, read into styled runs and +//! paragraphs (ADR 0085) and written back from them. +//! +//! The subset: ``, ``, ``, ``, ``, +//! `

` and `
`, with the entities `<`, `>`, `&`, `"`, `'`, +//! ` ` and numeric ones. Reading is a sanitiser as much as a parser: nothing in the input +//! is ever kept as markup. A tag outside the subset is dropped and its text kept (as Flash +//! does); `bc\";\ntrace(score_txt.text);\ntrace(score_txt.htmlText);\ntrace(name_txt.htmlText);"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 5).as_deref(), Some("Score: 12 hot")); + let st = s.state.fields.get(&vec![ElementId(5)]).unwrap(); + let rich = st.rich.as_ref().expect("styled"); + assert_eq!(rich.runs.iter().map(|r| (r.chars, r.style.bold, r.style.color.r > 0.5)).collect::>(), vec![(7, false, false), (2, true, false), (1, false, false), (3, false, true)]); + assert_eq!(rich.paragraphs[0].align, crate::TextAlign::Center); + assert!(s.output.contains(&"Score: 12 hot".to_string()), "{:?}", s.output); + // Read back in the subset, in the field's own font and size; nothing of the script tag. + let html = s.output.iter().find(|l| l.starts_with("

")).expect("htmlText traced"); + assert!(html.contains("12") && html.contains("color=\"#ff0000\">hot

") && !html.contains("script"), "{html}"); + // A field no script touched reads its authored text and style. + assert!(s.output.contains(&"

".to_string()), "{:?}", s.output); + // Setting `text` afterwards puts it back in the field's own style. + let d = field_doc("score_txt.htmlText = \"a\";\nscore_txt.text = \"plain\";\ntrace(score_txt.htmlText);"); + let s = start(&d, &mut Mono); + assert!(s.state.fields.get(&vec![ElementId(5)]).unwrap().rich.is_none()); + assert!(s.output.contains(&"

plain

".to_string()), "{:?}", s.output); + // Typing into a styled input field continues the style before the caret. + let d = field_doc("stop();\nname_txt.htmlText = \"ab\";"); + let s = start(&d, &mut Mono); + let s = type_into_name(&d, &s.state, "c"); + let st = s.state.fields.get(&vec![ElementId(6)]).unwrap(); + assert_eq!(st.text.as_deref(), Some("abc")); + let runs = &st.rich.as_ref().unwrap().runs; + assert_eq!((runs.len(), runs[0].chars, runs[0].style.bold), (1, 3, true)); + // Not a field, or null: a message, and the movie goes on. + let d = field_doc("score_txt.htmlText = null;"); + assert!(start(&d, &mut Mono).output.iter().any(|l| l.contains("`htmlText` is set to text"))); +} + +#[test] +fn change_events_fire_once_per_edit_by_the_viewer() { + let d = field_doc( + "stop();\nvar n:int = 0;\nfunction onChange(e:Event):void { n++; trace(\"change \" + n + \": \" + e.target.text + \" \" + (e.currentTarget == name_txt)); }\nname_txt.addEventListener(Event.CHANGE, onChange);\nname_txt.addEventListener(Event.CHANGE, onChange);\nname_txt.text = \"set by script\";\nscore_txt.addEventListener(Event.CHANGE, onChange);", + ); + let s = start(&d, &mut Mono); + assert!(s.output.is_empty(), "a script setting text fires nothing: {:?}", s.output); + assert_eq!(s.state.listeners.get(&vec![ElementId(6)]).map(Vec::len), Some(1), "the same listener is added once"); + // Three characters: three events, each after its edit, with the field as target. + let s = type_into_name(&d, &s.state, "abc"); + let changes: Vec<&String> = s.output.iter().filter(|l| l.starts_with("change")).collect(); + assert_eq!(changes.len(), 3, "{:?}", s.output); + assert_eq!(changes[2].as_str(), "change 3: set by scriptabc true"); + // Caret moves, selecting and keys that change nothing fire nothing; a deletion fires once. + let s2 = input(&d, &s.state, &[Event::KeyDown(37), Event::KeyDown(36), Event::SelectAll, Event::KeyDown(13), Event::KeyDown(9)], &mut Mono); + assert!(s2.output.iter().all(|l| !l.starts_with("change")), "{:?}", s2.output); + let s3 = input(&d, &s.state, &[Event::KeyDown(8)], &mut Mono); + assert_eq!(s3.output.iter().filter(|l| l.starts_with("change")).count(), 1, "{:?}", s3.output); + // Backspace at the start of an empty field changes nothing and fires nothing. + let d2 = field_doc("stop();\nname_txt.addEventListener(Event.CHANGE, function (e:Event):void { trace(\"change\"); });"); + let s = start(&d2, &mut Mono); + let s = input(&d2, &s.state, &[Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(8), Event::KeyDown(46)], &mut Mono); + assert!(s.output.is_empty(), "{:?}", s.output); + // Removing the listener stops it; other instances don't send change events. + let d3 = field_doc("stop();\nfunction f(e:Event):void { trace(\"change\"); }\nname_txt.addEventListener(Event.CHANGE, f);\nname_txt.removeEventListener(Event.CHANGE, f);"); + let s = start(&d3, &mut Mono); + assert!(type_into_name(&d3, &s.state, "a").output.is_empty()); + // The same events and state give the same output (the player stays deterministic). + let s = start(&d, &mut Mono); + assert_eq!(type_into_name(&d, &s.state, "xy"), type_into_name(&d, &s.state, "xy")); +} + +#[test] +fn a_fields_change_actions_run_in_its_timeline() { + let mut d = field_doc("stop();"); + // The name field traces on every change (the action IR's side of Event.CHANGE). + let layer = Arc::make_mut(&mut Arc::make_mut(&mut d.scenes[0]).timeline.layers[0]); + let kf = Arc::make_mut(&mut layer.keyframes[0]); + for e in &mut kf.elements { + if e.id == ElementId(6) + && let ElementKind::Text(t) = &mut Arc::make_mut(e).kind + { + Arc::make_mut(t).field.as_mut().unwrap().on_change = vec![Action::Trace { message: "edited".into() }]; + } + } + let s = start(&d, &mut Mono); + let s = type_into_name(&d, &s.state, "ab"); + assert_eq!(s.output, vec!["edited".to_string(), "edited".to_string()]); + // It is saved with the field and older files open without it. + let ElementKind::Text(t) = &d.scenes[0].timeline.layers[0].keyframes[0].elements[1].kind else { panic!() }; + let json = serde_json::to_string(t.field.as_ref().unwrap()).unwrap(); + assert!(json.contains("\"on_change\""), "{json}"); + let back: TextField = serde_json::from_str(&json).unwrap(); + assert_eq!(&back, t.field.as_ref().unwrap()); + assert!(!serde_json::to_string(&TextField::new(TextKind::Input)).unwrap().contains("on_change"), "fields without one save as before"); +} + +#[test] +fn max_chars_and_restrict_limit_what_the_viewer_types() { + let d = field_doc("stop();\ntrace(name_txt.maxChars, name_txt.restrict);\nname_txt.maxChars = 4;\nname_txt.restrict = \"A-Z0-9\";\ntrace(name_txt.maxChars, name_txt.restrict);"); + let s = start(&d, &mut Mono); + assert_eq!(s.output, vec!["0 null".to_string(), "4 A-Z0-9".to_string()]); + let s = type_into_name(&d, &s.state, "aB-c1D2E3"); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("B1D2"), "only capitals and digits, four of them"); + // A script may still set anything: the limits are the viewer's. + let d = field_doc("stop();\nname_txt.restrict = \"\";\nname_txt.maxChars = 2;\nname_txt.text = \"longer than two\";"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&s.state, 6).as_deref(), Some("longer than two")); + assert_eq!(type_into_name(&d, &s.state, "x").state.fields.get(&vec![ElementId(6)]).and_then(|f| f.text.clone()).as_deref(), Some("longer than two"), "an empty restrict lets nothing in"); + // null lifts the restriction. + let d = field_doc("stop();\nname_txt.restrict = \"x\";\nname_txt.restrict = null;"); + let s = start(&d, &mut Mono); + assert_eq!(text_of(&type_into_name(&d, &s.state, "ok").state, 6).as_deref(), Some("ok")); +} + diff --git a/crates/engine/src/cmds_text.rs b/crates/engine/src/cmds_text.rs index a96a7def..faff585c 100644 --- a/crates/engine/src/cmds_text.rs +++ b/crates/engine/src/cmds_text.rs @@ -403,6 +403,18 @@ pub fn field_layout(fonts: &Fonts, style: &TextStyle, field: &TextField, box_wid field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &[run], paragraphs: &[para], width: field.wrap_width(box_width) }, style.align, field, box_width) } +/// A field's text laid out in the styles a script gave it with `htmlText` (ADR 0107), and the +/// colour each of the layout's paints stands for. Links don't cut pieces here: a colour is one +/// piece. +pub fn field_layout_rich(fonts: &Fonts, block: &TextBlock, field: &TextField, shown: &str, rich: &anicraft_doc::html_text::RichStyles) -> std::result::Result<(anicraft_text::Layout, Vec), anicraft_text::TextError> { + let mut d = TextBlock { text: shown.to_string(), runs: Vec::new(), paragraphs: Vec::new(), ..block.clone() }; + let runs = rich.runs.iter().map(|r| TextRun { chars: r.chars, style: CharStyle { url: String::new(), ..r.style.clone() } }).collect(); + d.set_styles(runs, rich.paragraphs.clone()); + let (runs, paras, paints) = rich_parts(&d); + let l = field_lay(fonts, &anicraft_text::RichText { text: shown, runs: &runs, paragraphs: ¶s, width: field.wrap_width(block.box_width) }, d.align, field, block.box_width)?; + Ok((l, paints.into_iter().map(|(c, _)| c).collect())) +} + /// `t` with its text changed to `text`, its runs and paragraphs following the change (one /// edit: what was typed continues the style before it). pub(crate) fn retext(t: &TextBlock, text: &str) -> TextBlock { diff --git a/crates/engine/src/player.rs b/crates/engine/src/player.rs index 9306aaea..128d6dd9 100644 --- a/crates/engine/src/player.rs +++ b/crates/engine/src/player.rs @@ -94,21 +94,27 @@ impl ScriptHost for ScriptRunner<'_> { } } - fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option { - field_look(block, shown) + fn lay_out_field(&mut self, block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option { + field_look(block, shown, rich) } } /// A field's text laid out with this computer's fonts, as the player draws and edits it /// (ADR 0066). -pub fn field_look(block: &TextBlock, shown: &str) -> Option { +pub fn field_look(block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option { let f = block.field.as_ref()?; - let l = crate::cmds_text::field_layout(anicraft_text::Fonts::get(), &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?; + let fonts = anicraft_text::Fonts::get(); + // Styled text (`htmlText`, ADR 0107) is laid out run by run, one piece per colour. + let (l, colors) = match rich { + Some(r) => crate::cmds_text::field_layout_rich(fonts, block, f, shown, r).ok()?, + None => (crate::cmds_text::field_layout(fonts, &crate::cmds_text::style_of(block), f, block.box_width, shown).ok()?, Vec::new()), + }; + let pieces: Vec<(anicraft_doc::Rgba, std::sync::Arc)> = if colors.len() > 1 || colors.first().is_some_and(|c| *c != block.color) { l.pieces.iter().filter_map(|(k, p)| Some((*colors.get(*k as usize)?, std::sync::Arc::new(p.clone())))).collect() } else { Vec::new() }; let mut lines: Vec = l.carets.into_iter().map(|c| CaretLine { start: c.start, end: c.end, stops: c.stops }).collect(); if lines.is_empty() { lines.push(CaretLine { start: 0, end: 0, stops: vec![(0, 0.0)] }); } - Some(FieldLook { outline: std::sync::Arc::new(l.outline), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) + Some(FieldLook { outline: std::sync::Arc::new(l.outline), pieces: pieces.into(), lines: lines.into(), line_height: l.line_height, width: l.width, height: l.height }) } /// What a running frame script talks to.