feat(fields): htmlText, Event.CHANGE, change actions, maxChars and restrict in the script IR and the player (M5)

This commit is contained in:
Tanish Manku committed 2026-11-20 15:07:30 -07:00
1 parent 72fd12b4c2
commit 564e4ba387
14 files changed
+1145 -29

No files matched your search

+29
View File
@@ -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<Prop> {
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.
+11 -4
View File
@@ -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;
+23
View File
@@ -51,6 +51,9 @@ pub trait World {
fn set(&mut self, at: &Place, p: Property, v: f64) -> Result<(), Option<String>>;
/// Sets a text field's text (ADR 0066).
fn set_text(&mut self, at: &Place, text: String) -> Result<(), Option<String>>;
/// 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<String>>;
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<Value, String>;
@@ -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)
}
}
}
+61 -2
View File
@@ -32,6 +32,8 @@ struct Mock {
frame: u32,
/// Text fields' text, by name.
texts: BTreeMap<String, String>,
/// 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<String>> {
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 = "<b>Hi</b>";
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(&"<b>Hi</b> 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"));
}
+5
View File
@@ -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) => {}
+62 -4
View File
@@ -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<Path>,
/// 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<Path>)]>,
/// 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<Arc<RichStyles>>,
/// `maxChars` once a script set it (`None`: the field's own).
pub max_chars: Option<u32>,
/// `restrict` once a script set it: the characters a viewer may type (`None`: any).
pub restrict: Option<String>,
}
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<char> = 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<f32>) -> 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)]
+19
View File
@@ -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::<String>();
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), '\\'));
}
+489
View File
@@ -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: `<b>`, `<i>`, `<u>`, `<font face size color letterspacing>`, `<a href>`,
//! `<p align>` and `<br>`, with the entities `&lt;`, `&gt;`, `&amp;`, `&quot;`, `&apos;`,
//! `&nbsp;` 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); `<script>` and `<style>` are dropped with what is inside them; links that could run
//! script are dropped (the text stays); sizes, spacing, lengths and nesting are bounded.
//!
//! Both directions are pure and are mirrored line by line in the HTML export's player
//! (`html/player.js`), which the parity tests hold to the same output.
use crate::rich_text::{CharStyle, ParagraphStyle, TextRun, safe_url};
use crate::{MAX_FIELD_CHARS, Rgba, TextAlign};
/// Most characters of HTML read; the rest is ignored.
pub const MAX_HTML: usize = 65_536;
/// Deepest nesting of style tags that still changes the style; deeper tags are ignored.
pub const MAX_HTML_DEPTH: usize = 64;
/// The styles of a field's text while a movie plays: runs covering the text and one style per
/// paragraph (line).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RichStyles {
pub runs: Vec<TextRun>,
pub paragraphs: Vec<ParagraphStyle>,
}
/// HTML read into text and its styles.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Parsed {
pub text: String,
pub styles: RichStyles,
}
struct Reader {
text: String,
count: usize,
runs: Vec<TextRun>,
paragraphs: Vec<ParagraphStyle>,
style: CharStyle,
para: ParagraphStyle,
base_para: ParagraphStyle,
/// The text ends with the line break a `</p>` made (dropped if nothing follows).
closed_p: bool,
}
impl Reader {
fn push(&mut self, c: char) {
if self.count >= MAX_FIELD_CHARS {
return;
}
self.text.push(c);
self.count += 1;
match self.runs.last_mut() {
Some(r) if r.style == self.style => r.chars += 1,
_ => self.runs.push(TextRun { chars: 1, style: self.style.clone() }),
}
if c == '\n' {
self.paragraphs.push(self.para);
}
}
/// The line break a `</p>` makes: in the style of the text before it (HTML has no style
/// for it), so a paragraph's last run runs to its end.
fn end_paragraph(&mut self) {
if self.count >= MAX_FIELD_CHARS {
return;
}
self.text.push('\n');
self.count += 1;
match self.runs.last_mut() {
Some(r) => r.chars += 1,
None => self.runs.push(TextRun { chars: 1, style: self.style.clone() }),
}
self.paragraphs.push(self.para);
}
fn at_line_start(&self) -> bool {
self.text.is_empty() || self.text.ends_with('\n')
}
fn text_char(&mut self, c: char) {
// Tabs and line breaks are text; other control characters are not.
if c == '\r' || (c.is_control() && c != '\n' && c != '\t') {
return;
}
self.closed_p = false;
self.push(c);
}
}
/// One entity at the start of `s` (after its `&`): the character and how many characters of
/// `s` it took (its `;` included). `None`: not an entity, the `&` is text.
fn entity(s: &[char]) -> Option<(Option<char>, usize)> {
let end = s.iter().take(12).position(|c| *c == ';')?;
let name: String = s.iter().take(end).collect();
let c = match name.as_str() {
"lt" => Some('<'),
"gt" => Some('>'),
"amp" => Some('&'),
"quot" => Some('"'),
"apos" => Some('\''),
"nbsp" => Some('\u{a0}'),
_ => {
let digits = name.strip_prefix('#')?;
let code = match digits.strip_prefix(['x', 'X']) {
Some(hex) if !hex.is_empty() && hex.chars().all(|c| c.is_ascii_hexdigit()) => u32::from_str_radix(hex, 16).ok()?,
None if !digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()) => digits.parse::<u32>().ok()?,
_ => return None,
};
// A code that isn't a character (or is a control) is dropped, not kept as text.
char::from_u32(code).filter(|c| !c.is_control() || *c == '\n' || *c == '\t')
}
};
Some((c, end + 1))
}
/// Text with its entities read.
fn unescape(s: &[char]) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(&c) = s.get(i) {
i += 1;
if c == '&'
&& let Some((ch, used)) = entity(s.get(i..).unwrap_or(&[]))
{
out.extend(ch);
i += used;
continue;
}
out.push(c);
}
out
}
/// A tag's name (lower case, `/` first when it closes) and attributes (names lower case, values
/// with their entities read), from what is between `<` and `>`.
fn tag(body: &[char]) -> (String, bool, Vec<(String, String)>) {
let mut i = 0;
let closing = body.first() == Some(&'/');
if closing {
i += 1;
}
let mut name = String::new();
while let Some(c) = body.get(i).filter(|c| c.is_ascii_alphanumeric()) {
name.push(c.to_ascii_lowercase());
i += 1;
}
let mut attrs: Vec<(String, String)> = Vec::new();
while attrs.len() < 16 {
while body.get(i).is_some_and(|c| c.is_whitespace() || *c == '/') {
i += 1;
}
let mut key = String::new();
while let Some(c) = body.get(i).filter(|c| !c.is_whitespace() && **c != '=' && **c != '/') {
key.push(c.to_ascii_lowercase());
i += 1;
}
if key.is_empty() {
break;
}
while body.get(i).is_some_and(|c| c.is_whitespace()) {
i += 1;
}
let mut value: Vec<char> = Vec::new();
if body.get(i) == Some(&'=') {
i += 1;
while body.get(i).is_some_and(|c| c.is_whitespace()) {
i += 1;
}
match body.get(i).copied().filter(|q| *q == '"' || *q == '\'') {
Some(q) => {
i += 1;
while let Some(c) = body.get(i).filter(|c| **c != q) {
value.push(*c);
i += 1;
}
i += 1;
}
None => {
while let Some(c) = body.get(i).filter(|c| !c.is_whitespace()) {
value.push(*c);
i += 1;
}
}
}
}
attrs.push((key, unescape(&value)));
}
(name, closing, attrs)
}
/// Where a tag's `>` is in what follows its `<`: the first one outside a quoted attribute
/// value. `None`: the tag never ends.
fn tag_end(rest: &[char]) -> Option<usize> {
let mut quote: Option<char> = None;
for (k, c) in rest.iter().enumerate() {
match quote {
Some(q) if *c == q => quote = None,
Some(_) => {}
None if *c == '"' || *c == '\'' => quote = Some(*c),
None if *c == '>' => return Some(k),
None => {}
}
}
None
}
/// `#RRGGBB` as a colour.
fn hex_color(s: &str) -> Option<Rgba> {
let h = s.trim().strip_prefix('#')?;
if h.len() != 6 || !h.chars().all(|c| c.is_ascii_hexdigit()) {
return None;
}
let v = u32::from_str_radix(h, 16).ok()?;
let b = |shift: u32| ((v >> shift) & 255) as f32 / 255.0;
Some(Rgba::new(b(16), b(8), b(0), 1.0))
}
/// A plain decimal number (`12`, `-1.5`, `+2`): no exponents, at most 12 characters.
fn number(s: &str) -> Option<f32> {
let s = s.trim();
let digits = s.strip_prefix(['+', '-']).unwrap_or(s);
if digits.is_empty() || s.len() > 12 || !digits.chars().all(|c| c.is_ascii_digit() || c == '.') || digits.chars().filter(|c| *c == '.').count() > 1 || digits == "." {
return None;
}
s.strip_prefix('+').unwrap_or(s).parse::<f32>().ok().filter(|v| v.is_finite())
}
fn font_tag(style: &mut CharStyle, attrs: &[(String, String)]) {
for (k, v) in attrs {
match k.as_str() {
"face" => {
let face: String = v.trim().chars().filter(|c| !c.is_control()).take(256).collect();
if !face.is_empty() {
style.font = face;
}
}
// A size, or a step from the size around it (`+2`, `-1`), as Flash reads them.
"size" => {
if let Some(n) = number(v) {
let relative = v.trim().starts_with(['+', '-']);
style.size = (if relative { style.size + n } else { n }).clamp(1.0, 2000.0);
}
}
"color" => {
if let Some(c) = hex_color(v) {
style.color = c;
}
}
"letterspacing" => {
if let Some(n) = number(v) {
style.letter_spacing = n.clamp(-1000.0, 1000.0);
}
}
_ => {}
}
}
}
/// Reads `html` (the subset above) into text, runs and paragraphs. `base` is the style text
/// outside any tag gets (the field's own), `para` every paragraph's unless `<p align>` says
/// otherwise. At most [`MAX_HTML`] characters are read and [`MAX_FIELD_CHARS`] kept.
pub fn parse(html: &str, base: &CharStyle, para: &ParagraphStyle) -> Parsed {
let src: Vec<char> = html.chars().take(MAX_HTML).collect();
let mut r = Reader { text: String::new(), count: 0, runs: Vec::new(), paragraphs: Vec::new(), style: base.clone(), para: *para, base_para: *para, closed_p: false };
// Open style tags: the tag and the style it changed.
let mut open: Vec<(String, CharStyle)> = Vec::new();
let mut i = 0;
while let Some(&c) = src.get(i) {
i += 1;
if c == '&' {
if let Some((ch, used)) = entity(src.get(i..).unwrap_or(&[])) {
i += used;
if let Some(ch) = ch {
r.text_char(ch);
}
continue;
}
r.text_char('&');
continue;
}
if c != '<' {
r.text_char(c);
continue;
}
// A comment runs to its `-->` (or the end).
if src.get(i..i + 3) == Some(&['!', '-', '-']) {
let rest = src.get(i + 3..).unwrap_or(&[]);
i = rest.windows(3).position(|w| w == ['-', '-', '>']).map_or(src.len(), |k| i + 3 + k + 3);
continue;
}
// A tag runs to its `>`; a `<` that starts none is text.
let rest = src.get(i..).unwrap_or(&[]);
let starts_tag = rest.first().is_some_and(|n| n.is_ascii_alphabetic() || *n == '/' || *n == '!' || *n == '?');
let Some(len) = tag_end(rest).filter(|_| starts_tag) else {
r.text_char('<');
continue;
};
let (name, closing, attrs) = tag(rest.get(..len).unwrap_or(&[]));
i += len + 1;
match (name.as_str(), closing) {
// Never text: skipped with everything up to its end tag (or the end).
("script" | "style", false) => {
let mut k = i;
let mut end = src.len();
while k < src.len() {
if src.get(k) == Some(&'<') && src.get(k + 1) == Some(&'/') {
let word: String = src.iter().skip(k + 2).take(name.len()).map(char::to_ascii_lowercase).collect();
if word == name {
end = src.iter().skip(k).position(|c| *c == '>').map_or(src.len(), |g| k + g + 1);
break;
}
}
k += 1;
}
i = end;
}
("br", false) => {
r.closed_p = false;
r.push('\n');
}
("p", false) => {
if !r.at_line_start() {
r.push('\n');
}
r.closed_p = false;
r.para = r.base_para;
if let Some((_, v)) = attrs.iter().find(|(k, _)| k == "align") {
r.para.align = match v.trim().to_ascii_lowercase().as_str() {
"center" => TextAlign::Center,
"right" => TextAlign::Right,
// Justified text is drawn left-aligned (ADR 0085).
"left" | "justify" => TextAlign::Left,
_ => r.para.align,
};
}
}
("p", true) => {
r.end_paragraph();
r.closed_p = true;
r.para = r.base_para;
}
("b" | "i" | "u" | "font" | "a", false) => {
if open.len() >= MAX_HTML_DEPTH {
continue;
}
open.push((name.clone(), r.style.clone()));
match name.as_str() {
"b" => r.style.bold = true,
"i" => r.style.italic = true,
"u" => r.style.underline = true,
"font" => font_tag(&mut r.style, &attrs),
_ => {
// A link that could run script is no link; its text stays.
let href = attrs.iter().find(|(k, _)| k == "href").map_or("", |(_, v)| v.as_str());
r.style.url = safe_url(href).unwrap_or_default();
}
}
}
("b" | "i" | "u" | "font" | "a", true) => {
// Closes the nearest one open (and what was opened inside it).
if let Some(k) = open.iter().rposition(|(n, _)| *n == name) {
if let Some((_, before)) = open.get(k) {
r.style = before.clone();
}
open.truncate(k);
}
}
// Any other tag is dropped; what is inside it is text.
_ => {}
}
}
if r.closed_p && r.text.ends_with('\n') {
r.text.pop();
if let Some(last) = r.runs.last_mut() {
last.chars -= 1;
if last.chars == 0 {
r.runs.pop();
}
}
// The line the `</p>` ended keeps its own alignment.
r.para = r.paragraphs.pop().unwrap_or(r.base_para);
}
r.paragraphs.push(r.para);
if r.runs.is_empty() {
r.runs.push(TextRun { chars: 0, style: base.clone() });
}
Parsed { text: r.text, styles: RichStyles { runs: r.runs, paragraphs: r.paragraphs } }
}
/// A number as HTML attributes hold it: two decimals at most, no trailing zeros.
fn attr_number(v: f32) -> String {
let v = if v.is_finite() { f64::from(v) } else { 0.0 };
format!("{}", (v * 100.0 + 0.5).floor() / 100.0)
}
fn escape(out: &mut String, s: &str, attr: bool) {
for c in s.chars() {
match c {
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'&' => out.push_str("&amp;"),
'"' if attr => out.push_str("&quot;"),
'\u{a0}' => out.push_str("&nbsp;"),
c => out.push(c),
}
}
}
/// `text` in `styles` as HTML in the subset: one `<p align>` per line, a `<font>` per run with
/// its face, size, colour and letter spacing, and `<a>`, `<b>`, `<i>` and `<u>` inside it.
/// Baseline shifts, opacity, indents, margins and line spacing have no place in this HTML and
/// are left out. [`parse`] reads it back to the same text, runs and paragraphs.
pub fn write(text: &str, styles: &RichStyles) -> String {
let mut out = String::with_capacity(text.len() * 2 + 64);
let chars: Vec<char> = text.chars().collect();
let last_style = styles.runs.last().map(|r| r.style.clone()).unwrap_or_default();
// Each character's run.
let mut run_of = styles.runs.iter().enumerate().flat_map(|(k, r)| std::iter::repeat_n(k, r.chars as usize));
let mut line: Vec<(usize, char)> = Vec::new();
let mut para = 0usize;
let flush = |line: &mut Vec<(usize, char)>, para: usize, out: &mut String| {
let align = match styles.paragraphs.get(para).or(styles.paragraphs.last()).map_or(TextAlign::Left, |p| p.align) {
TextAlign::Left => "left",
TextAlign::Center => "center",
TextAlign::Right => "right",
};
out.push_str("<p align=\"");
out.push_str(align);
out.push_str("\">");
let mut i = 0;
while let Some(&(k, _)) = line.get(i) {
let st = styles.runs.get(k).map_or(&last_style, |r| &r.style);
let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
out.push_str("<font face=\"");
escape(out, &st.font, true);
out.push_str(&format!("\" size=\"{}\" color=\"#{:02x}{:02x}{:02x}\"", attr_number(st.size), b(st.color.r), b(st.color.g), b(st.color.b)));
if st.letter_spacing != 0.0 {
out.push_str(&format!(" letterspacing=\"{}\"", attr_number(st.letter_spacing)));
}
out.push('>');
if !st.url.is_empty() {
out.push_str("<a href=\"");
escape(out, &st.url, true);
out.push_str("\">");
}
for (on, t) in [(st.bold, "<b>"), (st.italic, "<i>"), (st.underline, "<u>")] {
if on {
out.push_str(t);
}
}
let mut piece = String::new();
while let Some(&(_, c)) = line.get(i).filter(|(k2, _)| *k2 == k) {
piece.push(c);
i += 1;
}
escape(out, &piece, false);
for (on, t) in [(st.underline, "</u>"), (st.italic, "</i>"), (st.bold, "</b>")] {
if on {
out.push_str(t);
}
}
if !st.url.is_empty() {
out.push_str("</a>");
}
out.push_str("</font>");
}
out.push_str("</p>");
line.clear();
};
for c in chars {
let k = run_of.next().unwrap_or(styles.runs.len().saturating_sub(1));
if c == '\n' {
flush(&mut line, para, &mut out);
para += 1;
} else {
line.push((k, c));
}
}
flush(&mut line, para, &mut out);
out
}
#[cfg(test)]
#[path = "html_text_tests.rs"]
mod tests;
+201
View File
@@ -0,0 +1,201 @@
use super::*;
use crate::rich_text::BaselineShift;
fn base() -> CharStyle {
CharStyle { font: "Arial".into(), size: 12.0, color: Rgba::BLACK, ..CharStyle::default() }
}
fn read(html: &str) -> Parsed {
parse(html, &base(), &ParagraphStyle::default())
}
/// `(characters, what differs from the base)` per run, for short assertions.
fn runs(p: &Parsed) -> Vec<(u32, String)> {
let b = base();
p.styles
.runs
.iter()
.map(|r| {
let s = &r.style;
let mut d = Vec::new();
if s.bold {
d.push("b".to_string());
}
if s.italic {
d.push("i".to_string());
}
if s.underline {
d.push("u".to_string());
}
if s.font != b.font {
d.push(format!("face={}", s.font));
}
if s.size != b.size {
d.push(format!("size={}", s.size));
}
if s.color != b.color {
d.push(format!("color={:.0},{:.0},{:.0}", s.color.r * 255.0, s.color.g * 255.0, s.color.b * 255.0));
}
if s.letter_spacing != 0.0 {
d.push(format!("ls={}", s.letter_spacing));
}
if !s.url.is_empty() {
d.push(format!("url={}", s.url));
}
(r.chars, d.join(" "))
})
.collect()
}
fn r(n: u32, s: &str) -> (u32, String) {
(n, s.to_string())
}
#[test]
fn the_subset_becomes_runs_and_paragraphs() {
let p = read("Hello <b>bold <i>both</i></b> <u>under</u>");
assert_eq!(p.text, "Hello bold both under");
assert_eq!(runs(&p), vec![r(6, ""), r(5, "b"), r(4, "b i"), r(1, ""), r(5, "u")]);
let p = read(r##"<font face="Georgia" size="20" color="#FF8000" letterspacing="1.5">big</font> <font size="+4">up</font><font size="-2">down</font>"##);
assert_eq!(p.text, "big updown");
assert_eq!(runs(&p), vec![r(3, "face=Georgia size=20 color=255,128,0 ls=1.5"), r(1, ""), r(2, "size=16"), r(4, "size=10")]);
let p = read(r#"<a href="https://example.com/?a=1&amp;b=2">link</a> and <A HREF='page.html'>more</A>"#);
assert_eq!(runs(&p), vec![r(4, "url=https://example.com/?a=1&b=2"), r(5, ""), r(4, "url=page.html")]);
// Paragraphs and breaks are lines; each `<p>` has its alignment.
let p = read(r#"<p align="center">Title</p><p align="right">right</p>plain<br>next<br/>last"#);
assert_eq!(p.text, "Title\nright\nplain\nnext\nlast");
let aligns: Vec<TextAlign> = p.styles.paragraphs.iter().map(|q| q.align).collect();
assert_eq!(aligns, vec![TextAlign::Center, TextAlign::Right, TextAlign::Left, TextAlign::Left, TextAlign::Left]);
// A paragraph that ends the HTML adds no empty line; one opened mid-line starts a line.
assert_eq!(read("<p>one</p>").text, "one");
assert_eq!(read("a<p>b</p>").text, "a\nb");
assert_eq!(read("<p>a</p><p></p><p>b</p>").text, "a\n\nb");
assert_eq!(read("<P ALIGN=\"JUSTIFY\">j</P>").styles.paragraphs, vec![ParagraphStyle::default()]);
// Entities; an unfinished one is text.
assert_eq!(read("1 &lt; 2 &amp;&amp; 3 &gt; 2 &quot;q&quot; &apos;a&apos; a&nbsp;b &#65;&#x42; &copy; AT&T &").text, "1 < 2 && 3 > 2 \"q\" 'a' a\u{a0}b AB &copy; AT&T &");
// Empty input is an empty field in the base style.
let e = read("");
assert_eq!((e.text.as_str(), e.styles.runs.len(), e.styles.paragraphs.len()), ("", 1, 1));
assert_eq!(e.styles.runs[0].style, base());
}
#[test]
fn nothing_hostile_is_kept_as_markup_or_as_a_link() {
// Script and style go with their content; other tags go, their text stays.
assert_eq!(read("a<script>alert(1)</script>b<STYLE>p{}</STYLE >c<script>never closed").text, "abc");
assert_eq!(read("<div onclick=\"x()\">div</div><img src=x onerror=alert(1)><span class=k>span</span><textformat leading=\"2\">t</textformat>").text, "divspant");
assert_eq!(read("x<!-- <b>hidden</b> -->y<!-- open").text, "xy");
assert_eq!(read("<!DOCTYPE html><?xml version=\"1.0\"?>ok").text, "ok");
// A `<` that starts no tag is text; so is an unclosed tag's `<`.
assert_eq!(read("1 < 2 and 3 <4 <b").text, "1 < 2 and 3 <4 <b");
assert_eq!(read("a <> b").text, "a <> b");
// A `>` inside a quoted attribute doesn't end the tag; a quote left open ends nothing.
assert_eq!(read("<font face=\"a>b\">x</font>").styles.runs[0].style.font, "a>b");
assert_eq!(read("<a href=\"open>text").text, "<a href=\"open>text");
// Links that could run script are dropped; the text stays, unlinked.
for bad in ["javascript:alert(1)", " JaVaScRiPt:alert(1)", "java\tscript:alert(1)", "vbscript:x", "data:text/html,<script>1</script>", "&#106;avascript:alert(1)"] {
let p = read(&format!("<a href=\"{bad}\">click</a>"));
assert_eq!(p.text, "click", "{bad}");
assert!(p.styles.runs.iter().all(|r| r.style.url.is_empty()), "{bad}: {:?}", p.styles.runs);
}
// Wild values are ignored or clamped.
let p = read(r##"<font size="1e9" color="red" face="">a</font><font size="99999">b</font><font size="-99999">c</font><font color="#12345">d</font><font letterspacing="NaN">e</font>"##);
assert_eq!(runs(&p), vec![r(1, ""), r(1, "size=2000"), r(1, "size=1"), r(2, "")]);
// Control characters and character codes that aren't characters are dropped.
assert_eq!(read("a\u{0}b\u{7}c&#0;d&#x110000;e&#xD800;f\r\ng\th").text, "abcdef\ng\th");
// Unbalanced and stray closing tags do no harm; a close ends what was opened inside too.
let p = read("</b>a<b>b<i>c</b>d</i></font>e");
assert_eq!((p.text.as_str(), runs(&p)), ("abcde", vec![r(1, ""), r(1, "b"), r(1, "b i"), r(2, "")]));
}
#[test]
fn sizes_are_bounded() {
// Nesting past the limit stops changing the style, and closes unwind cleanly.
let deep = format!("{}x{}y", "<b><i>".repeat(500), "</i></b>".repeat(500));
let p = read(&deep);
assert_eq!(p.text, "xy");
assert!(p.styles.runs[0].style.bold && !p.styles.runs.last().unwrap().style.bold);
// Long input is cut, long text capped, with runs and paragraphs to match.
let p = read(&"ab<br>".repeat(100_000));
assert!(p.text.chars().count() <= MAX_FIELD_CHARS);
assert_eq!(p.styles.runs.iter().map(|r| r.chars as usize).sum::<usize>(), p.text.chars().count());
assert_eq!(p.styles.paragraphs.len(), p.text.matches('\n').count() + 1);
let p = read(&"x".repeat(MAX_HTML * 2));
assert_eq!(p.text.chars().count(), MAX_FIELD_CHARS);
// A tag with a great many attributes or a huge attribute is read without trouble.
let p = read(&format!("<font {} size=\"30\">a</font><a href=\"{}\">b</a>", "x=1 ".repeat(1000), "h".repeat(5000)));
assert_eq!(p.text, "ab");
assert!(p.styles.runs.iter().all(|r| r.style.url.chars().count() <= crate::rich_text::MAX_URL));
}
#[test]
fn written_html_reads_back_the_same() {
let p = read(r##"<p align="center">Score: <b>12</b> <font color="#cc0000" size="18.5" face="Georgia">red &amp; <i>big</i></font></p><p align="right"><a href="https://example.com/a?b=&quot;c&quot;"><u>go</u></a> 1 &lt; 2</p>last"##);
let html = write(&p.text, &p.styles);
assert_eq!(
html,
concat!(
r##"<p align="center"><font face="Arial" size="12" color="#000000">Score: </font><font face="Arial" size="12" color="#000000"><b>12</b></font><font face="Arial" size="12" color="#000000"> </font>"##,
r##"<font face="Georgia" size="18.5" color="#cc0000">red &amp; </font><font face="Georgia" size="18.5" color="#cc0000"><i>big</i></font></p>"##,
r##"<p align="right"><font face="Arial" size="12" color="#000000"><a href="https://example.com/a?b=&quot;c&quot;"><u>go</u></a></font><font face="Arial" size="12" color="#000000"> 1 &lt; 2</font></p>"##,
r##"<p align="left"><font face="Arial" size="12" color="#000000">last</font></p>"##
)
);
let back = read(&html);
assert_eq!(back, p, "the same text, runs and paragraphs");
// What this HTML has no place for is left out: shifts and opacity.
let mut odd = p.clone();
odd.styles.runs[0].style.shift = BaselineShift::Superscript;
odd.styles.runs[0].style.color.a = 0.5;
odd.styles.runs[0].style.letter_spacing = -0.755;
let html = write(&odd.text, &odd.styles);
let again = read(&html);
assert_eq!(again.styles.runs[0].style.shift, BaselineShift::Normal);
assert_eq!(again.styles.runs[0].style.color.a, 1.0);
assert_eq!(again.styles.runs[0].style.letter_spacing, -0.75, "two decimals");
// Plain text with markup characters survives both ways, empty lines too.
let plain = Parsed { text: "a <b> & \"c\"\n\n\u{a0}z".into(), styles: RichStyles { runs: vec![TextRun { chars: 15, style: base() }], paragraphs: vec![ParagraphStyle::default(); 3] } };
assert_eq!(read(&write(&plain.text, &plain.styles)), plain);
// Runs shorter or longer than the text never panic.
let short = RichStyles { runs: vec![TextRun { chars: 1, style: base() }], paragraphs: Vec::new() };
assert_eq!(read(&write("abc\ndef", &short)).text, "abc\ndef");
assert_eq!(read(&write("abc", &RichStyles::default())).text, "abc");
let long = RichStyles { runs: vec![TextRun { chars: u32::MAX, style: base() }], paragraphs: Vec::new() };
assert_eq!(read(&write("abc", &long)).text, "abc");
}
/// Small deterministic generator (xorshift), as the engine's fuzz tests use.
fn rng(seed: &mut u64) -> u64 {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
*seed
}
#[test]
fn any_input_reads_safely_and_settles_after_one_round_trip() {
const PIECES: [&str; 40] = [
"<", ">", "</", "/>", "&", ";", "#", "\"", "'", "=", " ", "\n", "\r", "\t", "\u{0}", "a", "Zz", "é", "😀", "<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<font size=\"+3\" color=\"#ff00ff\">", "</font>",
"<a href=\"javascript:x\">", "<a href=\"http://a.b\">", "</a>", "<p align=\"right\">", "</p>", "<br>", "<script>", "</script>", "<!--", "-->", "&lt;", "&#x41;", "&#99999999;",
];
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
for round in 0..3000 {
let n = (rng(&mut seed) % 40) as usize;
let html: String = (0..n).map(|_| PIECES[(rng(&mut seed) % PIECES.len() as u64) as usize]).collect();
let p = read(&html);
let count = p.text.chars().count();
assert_eq!(p.styles.runs.iter().map(|r| r.chars as usize).sum::<usize>(), count, "round {round}: {html:?}");
assert_eq!(p.styles.paragraphs.len(), p.text.matches('\n').count() + 1, "round {round}: {html:?}");
assert!(!p.text.contains('\u{0}') && !p.text.contains('\r'), "{html:?}");
for r in &p.styles.runs {
assert!(!r.style.url.to_ascii_lowercase().contains("javascript"), "{html:?}");
assert!((1.0..=2000.0).contains(&r.style.size));
}
// Written and read again it is the same text, and the HTML no longer changes.
let once = write(&p.text, &p.styles);
let q = read(&once);
assert_eq!(q.text, p.text, "round {round}: {html:?} -> {once:?}");
assert_eq!(write(&q.text, &q.styles), once, "round {round}: {html:?}");
assert!(!once.contains("<script") && !once.contains("javascript:"), "{once}");
}
}
+9 -2
View File
@@ -31,6 +31,7 @@ pub mod width;
pub mod stroke_style;
pub mod player;
pub mod publish;
pub mod html_text;
pub mod rich_text;
pub mod sample;
pub mod templates;
@@ -1000,6 +1001,10 @@ pub struct TextField {
/// The ActionScript 1/2 variable the field shows (kept from Animate documents, not run).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub variable: String,
/// What the field does when the viewer changes its text (input fields; ADR 0107): actions
/// run in the timeline the field is on, as an instance's event handlers are.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub on_change: Vec<actions::Action>,
}
fn black() -> Rgba {
@@ -1012,7 +1017,7 @@ fn white() -> Rgba {
impl TextField {
/// A single-line field of `kind`.
pub fn new(kind: TextKind) -> TextField {
TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new() }
TextField { kind, lines: LineType::Single, selectable: true, border: false, border_color: Rgba::BLACK, background: false, background_color: Rgba::WHITE, max_chars: 0, variable: String::new(), on_change: Vec::new() }
}
/// The width text wraps at in a box `box_width` wide, if its lines wrap.
@@ -1032,7 +1037,9 @@ impl TextField {
/// Values in range: names cut to length, at most [`MAX_FIELD_CHARS`] typed.
pub fn sanitized(&self) -> TextField {
TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), ..self.clone() }
let mut on_change = self.on_change.clone();
actions::sanitize_actions(&mut on_change);
TextField { max_chars: self.max_chars.min(MAX_FIELD_CHARS as u32), variable: self.variable.chars().take(MAX_FIELD_NAME).collect(), on_change, ..self.clone() }
}
}
+94 -11
View File
@@ -20,6 +20,7 @@ use crate::actions::as3::{Compiled, Decls, Problem};
use crate::actions::{Action, ButtonEvent, EventHandler, FrameRef, FrameScript, PluginScript, Property, Seg, Target};
use crate::eval::{Play, evaluate_shown, evaluate_symbol, guide_walk};
use crate::field::{Changed, Edit, Editor, FieldLook, FieldState, chars, fit, scroll_to_caret};
use crate::html_text::{self, RichStyles};
use crate::sound::Started;
use crate::{BlendMode, ColorTransform, DisplayList, Document, Element, ElementId, ElementKind, FIELD_GUTTER, Group, LayerKind, MAX_SYMBOL_DEPTH, Rgba, SoundSync, SymbolId, SymbolKind, TextBlock, TextField, TextKind, Timeline};
use anicraft_geom::{Affine, Vec2};
@@ -367,8 +368,10 @@ pub trait ScriptHost {
/// Lays out `shown` (a field's text as it is drawn) in `block`'s style and box (ADR 0066):
/// the fonts live above this crate. `None`: it can't, and the field keeps its authored
/// outline until its text changes (then it draws only its box).
fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option<FieldLook> {
let _ = (block, shown);
/// `rich`: the styles of the text when a script set them with `htmlText` (ADR 0107);
/// `None`: the block's own first style.
fn lay_out_field(&mut self, block: &TextBlock, shown: &str, rich: Option<&RichStyles>) -> Option<FieldLook> {
let _ = (block, shown, rich);
None
}
}
@@ -1102,13 +1105,29 @@ impl<'a, 'h> Run<'a, 'h> {
Prop::MouseX => num(short(self.st.mouse.x)),
Prop::MouseY => num(short(self.st.mouse.y)),
Prop::Name => Ok(Value::str("root1")),
Prop::Text | Prop::Length => Err("the main timeline isn't a text field".into()),
Prop::Text | Prop::Length | Prop::HtmlText | Prop::MaxChars | Prop::Restrict => Err("the main timeline isn't a text field".into()),
};
}
if matches!(p, Prop::Text | Prop::Length) {
let Some((t, _)) = n.field() else { return Err(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))) };
let v = self.st.fields.get(&n.path).map_or(t.text.as_str(), |f| f.value(t));
return Ok(if p == Prop::Text { Value::str(v) } else { Value::Num(crate::actions::as3::ir::text_len(v) as f64) });
if p.is_field() {
let Some((t, f)) = n.field() else { return Err(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))) };
let st = self.st.fields.get(&n.path);
let v = st.map_or(t.text.as_str(), |f| f.value(t));
return Ok(match p {
Prop::Text => Value::str(v),
Prop::Length => Value::Num(crate::actions::as3::ir::text_len(v) as f64),
Prop::MaxChars => Value::Num(f64::from(st.and_then(|s| s.max_chars).unwrap_or(f.max_chars))),
Prop::Restrict => st.and_then(|s| s.restrict.as_deref()).map_or(Value::Null, Value::str),
// The text's styles as HTML: what a script set, the authored runs while the
// text is the authored one, else the field's own style.
_ => {
let styles = match st {
Some(FieldState { rich: Some(r), .. }) => (**r).clone(),
Some(FieldState { text: Some(_), .. }) => RichStyles { runs: vec![crate::TextRun { chars: u32::MAX, style: t.char_style() }], paragraphs: vec![t.para_style()] },
_ => RichStyles { runs: t.styled_runs(), paragraphs: t.paragraph_styles() },
};
Value::str(&html_text::write(v, &styles))
}
});
}
let ov = self.st.props.get(&n.path).copied().unwrap_or_default();
let d = decompose64(&n.local);
@@ -1133,7 +1152,7 @@ impl<'a, 'h> Run<'a, 'h> {
let v = if p == Prop::MouseX { (m[3] * x - m[2] * y) / det } else { (m[0] * y - m[1] * x) / det };
num(fround_short(v))
}
Prop::Text | Prop::Length => Err("not a text field".into()),
Prop::Text | Prop::Length | Prop::HtmlText | Prop::MaxChars | Prop::Restrict => Err("not a text field".into()),
Prop::CurrentFrame | Prop::TotalFrames | Prop::CurrentLabel => {
if n.kind != NodeKind::MovieClip {
return Err(format!("“{}” is {}; only movie clips and the main timeline have frames", n.name, kind_name(n.kind)));
@@ -1178,10 +1197,13 @@ impl<'a, 'h> Run<'a, 'h> {
let Some(node) = self.nodes.get(i) else { return };
let ok = match event {
ListenEvent::EnterFrame => node.kind != NodeKind::Graphic,
ListenEvent::Change => node.kind == NodeKind::Text,
_ => matches!(node.kind, NodeKind::Button | NodeKind::MovieClip),
};
if !ok {
let why = if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is {}; only buttons and movie clips get pointer events", node.name, kind_name(node.kind)) };
let why = if event == ListenEvent::Change {
format!("“{}” is {}; only text fields send change events", node.name, kind_name(node.kind))
} else if node.kind == NodeKind::Root { "the main timeline doesn't get pointer events here".to_string() } else { format!("“{}” is {}; only buttons and movie clips get pointer events", node.name, kind_name(node.kind)) };
return self.out(format!("{what}: {why}"));
}
let (path, name) = (node.path.clone(), node.name.clone());
@@ -1447,7 +1469,7 @@ impl<'a, 'h> Run<'a, 'h> {
let Some(f) = t.field.as_ref() else { return };
let st = self.st.fields.entry(path.to_vec()).or_default();
let shown = f.shown(st.value(&t));
st.look = self.host.lay_out_field(&t, &shown).map(Arc::new);
st.look = self.host.lay_out_field(&t, &shown, st.rich.as_deref()).map(Arc::new);
let len = chars(st.value(&t));
st.caret = st.caret.min(len);
st.anchor = st.anchor.min(len);
@@ -1458,10 +1480,55 @@ impl<'a, 'h> Run<'a, 'h> {
fn set_field_text(&mut self, path: &[ElementId], text: &str) {
let Some((t, _)) = self.field_node(path) else { return };
let Some(f) = t.field.as_ref() else { return };
self.st.fields.entry(path.to_vec()).or_default().text = Some(fit(f, text));
let st = self.st.fields.entry(path.to_vec()).or_default();
st.text = Some(fit(f, text));
// Plain text is in the field's own style, as ActionScript's `text` is.
st.rich = None;
self.relayout(path);
}
/// A script sets another member of field `path` (ADR 0107): `htmlText` (read into text and
/// styles, sanitised), `maxChars` or `restrict`.
fn set_field_member(&mut self, path: &[ElementId], p: Prop, v: &Value) {
let Some((t, _)) = self.field_node(path) else { return };
let st = self.st.fields.entry(path.to_vec()).or_default();
match p {
Prop::HtmlText => {
let parsed = html_text::parse(&v.text(), &t.char_style(), &t.para_style());
st.text = Some(parsed.text);
st.rich = Some(Arc::new(parsed.styles));
self.relayout(path);
}
Prop::MaxChars => st.max_chars = Some((v.number().clamp(0.0, crate::MAX_FIELD_CHARS as f64)) as u32),
Prop::Restrict => st.restrict = (!matches!(v, Value::Null | Value::Undefined)).then(|| v.text().chars().take(1024).collect()),
_ => {}
}
}
/// The viewer changed field `path`'s text (ADR 0107): its change actions run in the
/// timeline it is on, then the listeners scripts added for `Event.CHANGE`, in the order
/// added. Once per edit; text a script sets fires nothing, as in ActionScript.
fn changed(&mut self, path: &[ElementId]) {
self.refresh();
let Some(n) = self.index_of(path).and_then(|i| self.nodes.get(i)) else { return };
let actions = n.field().map(|(_, f)| f.on_change.clone()).filter(|a| !a.is_empty());
let owner_path = self.nodes.get(n.owner).map(|o| o.path.clone());
let listeners: Vec<Listening> = self.st.listeners.get(path).map(|l| l.iter().filter(|l| l.event == ListenEvent::Change).cloned().collect()).unwrap_or_default();
if actions.is_none() && listeners.is_empty() {
return;
}
if let (Some(actions), Some(owner)) = (actions, owner_path) {
self.run_list(&owner, &actions, false);
}
for l in listeners {
if self.halted {
return;
}
self.call_listener(&l, EventInfo { key: None, target: Some(path.to_vec()), current: Some(path.to_vec()) });
}
self.settle();
}
/// Runs an edit on the focused field (laying it out first if it never was).
fn edit_field(&mut self, go: impl FnOnce(&mut Editor<'_>, Option<&FieldLook>) -> Changed) {
let Some(path) = self.st.focus.clone() else { return };
@@ -1475,6 +1542,7 @@ impl<'a, 'h> Run<'a, 'h> {
let changed = go(&mut Editor { block: &t, field: &f, st }, look.as_deref());
if changed.text {
self.relayout(&path);
self.changed(&path);
} else if changed.caret {
scroll_to_caret(&t, &f, self.st.fields.entry(path).or_default());
}
@@ -1750,6 +1818,21 @@ impl World for Script<'_, '_, '_> {
Ok(())
}
fn set_field(&mut self, at: &Place, p: Prop, v: Value) -> Result<(), Option<String>> {
if !self.r.budget() {
return Err(None);
}
let from = self.from().map_err(Some)?;
let i = self.r.place(from, self.ev.as_ref(), at).map_err(Some)?;
let Some(n) = i.and_then(|i| self.r.nodes.get(i)) else { return Err(Some("the stage isn't a text field".into())) };
if n.field().is_none() {
return Err(Some(format!("“{}” is {}, not a text field", n.name, kind_name(n.kind))));
}
let path = n.path.clone();
self.r.set_field_member(&path, p, &v);
Ok(())
}
fn trace(&mut self, line: String) {
if self.r.budget() {
self.r.out(line);
+119 -1
View File
@@ -715,7 +715,7 @@ impl ScriptHost for Mono {
fn run(&mut self, _: &PluginScript, _: &ScriptContext<'_>) -> ScriptRun {
ScriptRun::default()
}
fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option<FieldLook> {
fn lay_out_field(&mut self, block: &TextBlock, shown: &str, _: Option<&crate::html_text::RichStyles>) -> Option<FieldLook> {
let f = block.field.as_ref()?;
Some(crate::field::mono_look(shown, 10.0, 10.0, f.wrap_width(block.box_width)))
}
@@ -811,3 +811,121 @@ fn typing_is_deterministic() {
assert_eq!(a, b);
assert_eq!(text_of(&a.state, 6).as_deref(), Some("deterministX"));
}
// ----- htmlText, change events, maxChars and restrict (ADR 0107) ------------------------------
/// A click into the name field (element 6), End, then `typed` at the text's end.
fn type_into_name(d: &Document, st: &PlayerState, typed: &str) -> Step {
let mut ev = vec![Event::Down(Vec2::new(20.0, 55.0)), Event::Up(Vec2::new(20.0, 55.0)), Event::KeyDown(35)];
ev.extend(typed.chars().map(Event::Char));
input(d, st, &ev, &mut Mono)
}
#[test]
fn html_text_sets_styled_runs_and_reads_back() {
let d = field_doc("stop();\nscore_txt.htmlText = \"<p align=\\\"center\\\">Score: <b>12</b> <font color=\\\"#ff0000\\\">hot</font></p><script>trace(1)</script>\";\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<_>>(), 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("<p align=\"center\">")).expect("htmlText traced");
assert!(html.contains("<font face=\"Mono\" size=\"10\" color=\"#000000\"><b>12</b></font>") && html.contains("color=\"#ff0000\">hot</font></p>") && !html.contains("script"), "{html}");
// A field no script touched reads its authored text and style.
assert!(s.output.contains(&"<p align=\"left\"></p>".to_string()), "{:?}", s.output);
// Setting `text` afterwards puts it back in the field's own style.
let d = field_doc("score_txt.htmlText = \"<b>a</b>\";\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(&"<p align=\"left\"><font face=\"Mono\" size=\"10\" color=\"#000000\">plain</font></p>".to_string()), "{:?}", s.output);
// Typing into a styled input field continues the style before the caret.
let d = field_doc("stop();\nname_txt.htmlText = \"<b>ab</b>\";");
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"));
}
+12
View File
@@ -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<Rgba>), 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: &paras, 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 {
+11 -5
View File
@@ -94,21 +94,27 @@ impl ScriptHost for ScriptRunner<'_> {
}
}
fn lay_out_field(&mut self, block: &TextBlock, shown: &str) -> Option<FieldLook> {
field_look(block, shown)
fn lay_out_field(&mut self, block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option<FieldLook> {
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<FieldLook> {
pub fn field_look(block: &TextBlock, shown: &str, rich: Option<&anicraft_doc::html_text::RichStyles>) -> Option<FieldLook> {
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<anicraft_geom::Path>)> = 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<CaretLine> = 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.