text: bound copies of preserved style data and font names (#11046)

This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-16 21:59:36 -05:00
1 parent 43c2d1bd45
commit d71e9fd1bf
6 files changed
+299 -32

No files matched your search

+8 -2
View File
@@ -204,8 +204,14 @@ fn export_supported_document(
// as Photopea reject it (#3514). Keep the block when the file had one (round-trip its pen
// positions/extras), a layer is Optical (#1348), or a layer carries stylistic sets / other
// Txt2-only features (#10308).
let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers))
.then(|| photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi));
// A restyle that would lose a style's fill colour is refused: the file's own block stays as it
// was, and the export says so.
let txt2 = (previous.is_some() || photocraft_text::psd::needs_txt2(&text_layers)).then(|| {
photocraft_text::psd::build_txt2_at(&text_layers, previous.as_deref(), ex.dpi).unwrap_or_else(|e| {
ex.warnings.push(format!("type styles were not updated in the file's text block: {e}"));
previous.clone().unwrap_or_default()
})
});
for (sig, key, data) in preserved {
// With no type layers left the opened file's `Txt2` describes text that is gone (fonts and
// layout caches, often most of the file): Photoshop drops it, and so does the save (#9563).
+2 -2
View File
@@ -347,7 +347,7 @@ fn corpus_text_psd_legacy_objects_are_edited_in_place() {
let items = |value: &E| if let E::Dict(items) = value { items.clone() } else { Vec::new() };
// Unedited: the legacy object and the font list are as the file has them.
let unedited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &layer)], Some(&txt2), doc.resolution_dpi)).unwrap();
let unedited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &layer)], Some(&txt2), doc.resolution_dpi).unwrap()).unwrap();
assert!(legacy(&unedited) == legacy(&before), "an unedited layer leaves the legacy text object alone");
assert!(unedited.path(&["DocumentResources", "FontSet"]) == before.path(&["DocumentResources", "FontSet"]), "and the font list it indexes");
@@ -356,7 +356,7 @@ fn corpus_text_psd_legacy_objects_are_edited_in_place() {
for run in &mut bigger.runs {
run.style.size_pt += 7.0;
}
let edited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &bigger)], Some(&txt2), doc.resolution_dpi)).unwrap();
let edited = photocraft_text::psd::parse_txt2(&photocraft_text::psd::build_txt2_at(&[(0, &bigger)], Some(&txt2), doc.resolution_dpi).unwrap()).unwrap();
let (was, now) = (features(&legacy(&before)).expect("features"), features(&legacy(&edited)).expect("features"));
let size = |f: &E| f.get("FontSize").and_then(E::as_f64).expect("FontSize");
assert!((size(&now) - size(&was) - 7.0).abs() < 1e-6, "the legacy size follows the edit: {} -> {}", size(&was), size(&now));
+1 -1
View File
@@ -27,7 +27,7 @@ mod import;
#[cfg(test)]
pub(crate) use build::font_entry;
pub use build::{MAX_TEXT_INDEX, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2};
pub use build::{MAX_TEXT_INDEX, Txt2Error, build_engine_data, build_txt2, build_txt2_at, build_tysh, needs_txt2};
pub(crate) use build::{font_set, paragraph_properties, style_sheet_data};
pub use edit::{set_text_index, text_index, txt2_object_count};
#[cfg(test)]
+158 -20
View File
@@ -1,4 +1,6 @@
use super::edit::{TEMPLATE_NODES, edited_object, fits, is_stub, names_one_frame, new_object, pad_frames, td_edited_object, with_modes};
use super::edit::{
TEMPLATE_NODES, compact, copies_fit_plus, edited_object, fits, is_stub, names_one_frame, new_object, pad_frames, td_edited_object, with_modes,
};
use super::import::{OPENTYPE_KEYS, TXT2_FEATURES, TXT2_STYLISTIC_SETS, kern_units, manual, object_frame, pair_runs, parse_txt2, postscript_for, real};
use super::{
AntiAlias, Caps, CharStyle, Color, ColorMode, D, Descriptor, E, FontBaseline, Id, Kerning, Orientation, ParagraphStyle, TextAlign, TextLayer, TextShape,
@@ -206,13 +208,34 @@ fn char_spans(layer: &TextLayer) -> Vec<(usize, i64)> {
/// (`/11`). Photoshop reads the character style from here rather than from EngineData, and quit
/// on a run holding only the auto-kern mode. `None` when `base` has no style dictionary or is
/// larger than a template may be (it is copied once per run).
fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec<E>, dpi: f32, seed_empty: bool) -> Option<Vec<E>> {
fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec<E>, dpi: f32, seed_empty: bool) -> Result<Option<Vec<E>>, Txt2Error> {
if !matches!(base.path(&["0", "0", "6"]), Some(E::Dict(_))) || !fits(base, &mut { TEMPLATE_NODES }) {
return None;
return Ok(None);
}
let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 };
let runs = layer.char_runs();
let spans = char_spans(layer);
// A template too large to copy once per run is compacted rather than given up on: falling
// back would keep the file's old style runs, so the edit would not reach the saved file.
let compacted;
// Each run can gain up to TXT2_ADDED_KEYS keys the template may lack (size, leading, features...).
const TXT2_ADDED_KEYS: usize = 18;
const TXT2_ADDED_KEY_BYTES: usize = 32;
let base = if copies_fit_plus(base, spans.len(), TXT2_ADDED_KEYS, TXT2_ADDED_KEY_BYTES) {
base
} else {
let Some(c) = compact(base, &["0", "0", "6"]).filter(|c| copies_fit_plus(c, spans.len(), TXT2_ADDED_KEYS, TXT2_ADDED_KEY_BYTES)) else {
return Ok(None);
};
// The fill colour is written into the style's paint dictionary (`/53`): compacting must not
// drop it, or the saved run would have no colour at all.
let paint = ["0", "0", "6", "53"];
if base.path(&paint).is_some() && c.path(&paint).is_none() {
return Err(Txt2Error::FillColourDropped);
}
compacted = c;
&compacted
};
let default = CharStyle::default();
let mut out = Vec::with_capacity(spans.len());
let mut looked_up = std::collections::HashMap::new();
@@ -220,7 +243,7 @@ fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec<E>, dpi: f32, se
let s = runs.get(ri).map_or(&default, |r| &r.style);
let font = *looked_up.entry(postscript_for(s)).or_insert_with_key(|name| txt2_font(fonts, name, seed_empty));
let mut run = base.clone();
let style = run.get_mut("0")?.get_mut("0")?.get_mut("6")?;
let Some(style) = run.get_mut("0").and_then(|r| r.get_mut("0")).and_then(|r| r.get_mut("6")) else { return Ok(None) };
if let Some(font) = font {
style.set("0", E::Int(font));
}
@@ -247,9 +270,27 @@ fn txt2_style_runs(layer: &TextLayer, base: &E, fonts: &mut Vec<E>, dpi: f32, se
run.set("1", E::Int(n));
out.push(run);
}
Some(out)
Ok(Some(out))
}
/// Why [`build_txt2_at`] refused to write a block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Txt2Error {
/// A text style's fill-colour dictionary is too large to copy into each style run; writing the
/// runs without it would lose the requested colour.
FillColourDropped,
}
impl std::fmt::Display for Txt2Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::FillColourDropped => f.write_str("a text style's fill colour is too large to rewrite, so its style cannot be restyled"),
}
}
}
impl std::error::Error for Txt2Error {}
/// Whether the style runs of a `Txt2` text model (`/6 /0`) agree with `layer`'s character runs
/// on every key [`txt2_style_runs`] writes, the auto-kern mode aside ([`with_modes`] refits that
/// on its own): font (by name, through `fonts`, the block's font list), size, faux bold and
@@ -473,9 +514,29 @@ fn td_restyled(entry: &E, layer: &TextLayer, fonts: &mut Vec<E>, dpi: f32) -> Op
}
let k = if dpi.is_finite() && dpi > 0.0 { dpi / 72.0 } else { 1.0 };
let runs = layer.char_runs();
let spans = char_spans(layer);
// As in `txt2_style_runs`: compact a template too large to copy per run, so the edit still
// reaches this copy instead of the entry keeping its old style.
let compacted;
// Each run can gain the `Features` keys set below (17 + 7 option flags + the style-set mask), the run
// `Length`, and the paint `Type`/`Values`; a bound on their nodes and key bytes (longest key 21 bytes).
const TD_ADDED_KEYS: usize = 40;
const TD_ADDED_KEY_BYTES: usize = 1024;
let base = if copies_fit_plus(base, spans.len(), TD_ADDED_KEYS, TD_ADDED_KEY_BYTES) {
base
} else {
compacted = compact(base, &["RunData", "StyleSheet", "Features"]).filter(|c| copies_fit_plus(c, spans.len(), TD_ADDED_KEYS, TD_ADDED_KEY_BYTES))?;
// As for the Txt2 runs: a restyle that would drop the fill colour dictionary is not made, so
// the entry keeps the colour the file has rather than none.
let paint = ["RunData", "StyleSheet", "Features", "FillColor"];
if base.path(&paint).is_some() && compacted.path(&paint).is_none() {
return None;
}
&compacted
};
let default = CharStyle::default();
let mut out = Vec::new();
for (ri, n) in char_spans(layer) {
for (ri, n) in spans {
let s = runs.get(ri).map_or(&default, |r| &r.style);
let mut run = base.clone();
let features = run.get_mut("RunData")?.get_mut("StyleSheet")?.get_mut("Features")?;
@@ -655,12 +716,14 @@ fn fresh_point_text_object(frame: usize, text: &str) -> E {
/// is kept, and a block whose content comes out unchanged is returned byte for byte (#2374:
/// Photoshop refused files whose `Txt2` an unedited save had stripped).
pub fn build_txt2(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>) -> Vec<u8> {
build_txt2_at(objects, previous, 72.0)
// A refused restyle keeps the file's block as it was.
build_txt2_at(objects, previous, 72.0).unwrap_or_else(|_| previous.map(<[u8]>::to_vec).unwrap_or_default())
}
/// [`build_txt2`] for a document of `dpi` (the style runs of new and edited objects carry sizes
/// in the document's points, as EngineData does).
pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi: f32) -> Vec<u8> {
/// in the document's points, as EngineData does). An error when a restyle would lose a style's
/// fill colour ([`Txt2Error`]); nothing is written then.
pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi: f32) -> Result<Vec<u8>, Txt2Error> {
let prev = previous.and_then(parse_txt2);
let prev_objects: &[E] = prev.as_ref().and_then(|p| p.path(&["1", "1"]).and_then(E::as_array)).unwrap_or(&[]);
let mut slots: Vec<E> = prev_objects.to_vec();
@@ -791,14 +854,32 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
// from these runs, so the template's (or the old text's) would show, and come back on
// reopen. They are built on one of the object's own runs, every key Photoshop wrote kept;
// without a template run, a minimal base is filled the same way (#10308).
let styled = (!unchanged)
.then(|| {
let file_base = (!is_stub(&object)).then(|| model.path(&["6", "0"]).and_then(E::as_array).and_then(<[E]>::first).cloned()).flatten();
let base = file_base.or_else(|| native.then(minimal_txt2_style_run))?;
txt2_style_runs(layer, &base, &mut fonts, dpi, seed_empty)
})
.flatten();
let file_runs = reuse.then(|| model.path(&["6", "0"]).and_then(E::as_array)).flatten().and_then(|runs| with_modes(runs, &modes));
let styled = if unchanged {
None
} else {
let file_base = (!is_stub(&object)).then(|| model.path(&["6", "0"]).and_then(E::as_array).and_then(<[E]>::first).cloned()).flatten();
match file_base.or_else(|| native.then(minimal_txt2_style_run)) {
Some(base) => txt2_style_runs(layer, &base, &mut fonts, dpi, seed_empty)?,
None => None,
}
};
// The file's own runs, moved out of the model (it gets the runs written below), so keeping
// them copies nothing.
let file_runs = if reuse && styled.is_none() {
model
.get_mut("6")
.and_then(|r| r.get_mut("0"))
.and_then(|r| match std::mem::replace(r, E::Array(Vec::new())) {
E::Array(runs) => Some(runs),
other => {
*r = other;
None
}
})
.and_then(|runs| with_modes(runs, &modes))
} else {
None
};
let runs = styled.or(file_runs).unwrap_or_else(|| {
modes
.iter()
@@ -888,13 +969,13 @@ pub fn build_txt2_at(objects: &[(i32, &TextLayer)], previous: Option<&[u8]>, dpi
if let (Some(bytes), Some(p)) = (previous, &prev)
&& *p == outer
{
return bytes.to_vec();
return Ok(bytes.to_vec());
}
match outer {
Ok(match outer {
E::Dict(items) => ed::write_bare(&items),
// Unreachable: `parse_txt2` and the fallback above both yield a dictionary.
_ => ed::write_bare(&[]),
}
})
}
/// Updates (or creates) an EngineData tree for `layer`.
@@ -1156,3 +1237,60 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Option<
let bounds = if warped { [l, t, r, b] } else { [0.0; 4] };
write_tysh(&TySh { transform: layer.transform, text, warp, bounds })
}
#[cfg(test)]
mod copy_budget_tests {
use super::{CharStyle, E, TextLayer, td_restyled, txt2_style_runs};
use photocraft_doc::text::TextRun;
/// A style edit on a layer whose template holds an oversized value still writes the layer's
/// style (from the compacted template), rather than giving up and keeping the old runs.
#[test]
fn an_oversized_template_still_takes_the_new_style() {
let style = E::Dict(vec![("1".into(), E::Real(12.0)), ("99".into(), E::String("x".repeat(1 << 20)))]);
let base = E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), E::Dict(vec![("6".into(), style)]))])), ("1".into(), E::Int(1))]);
// 100 single-letter runs alternating sizes: 100 copies of 1 MiB are past the budget.
let text = "ab".repeat(50);
let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect();
let layer = TextLayer { text, runs, ..Default::default() };
let out = txt2_style_runs(&layer, &base, &mut Vec::new(), 72.0, false).unwrap().expect("styled runs");
assert!(out.len() >= 100);
assert!(out.iter().all(|r| r.path(&["0", "0", "6", "99"]).is_none()));
let size = |r: &E| {
r.path(&["0", "0", "6", "1"]).and_then(|v| match v {
E::Real(f) => Some(*f),
E::Int(i) => Some(*i as f64),
_ => None,
})
};
assert_eq!(size(&out[0]), Some(30.0));
assert_eq!(size(&out[1]), Some(40.0));
}
/// A template whose fill-colour dictionary is past the copy budget cannot be restyled without
/// losing the colour: refused, not written colourless.
#[test]
fn an_oversized_fill_colour_refuses_the_restyle() {
let paint = E::Dict(vec![("0".into(), E::Dict(vec![("99".into(), E::String("x".repeat(1 << 20)))]))]);
let style = E::Dict(vec![("1".into(), E::Real(12.0)), ("53".into(), paint)]);
let base = E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), E::Dict(vec![("6".into(), style)]))])), ("1".into(), E::Int(1))]);
let text = "ab".repeat(50);
let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect();
let layer = TextLayer { text, runs, ..Default::default() };
assert_eq!(txt2_style_runs(&layer, &base, &mut Vec::new(), 72.0, false), Err(super::Txt2Error::FillColourDropped));
}
/// The legacy `TextObjects` copy: an oversized fill-colour dictionary is not compacted away, so
/// the entry is left with the colour the file has instead of a colourless restyle.
#[test]
fn an_oversized_legacy_fill_colour_keeps_the_entry() {
let colour = E::Dict(vec![("Color".into(), E::Dict(vec![("Pad".into(), E::String("x".repeat(1 << 20)))]))]);
let features = E::Dict(vec![("FillColor".into(), colour)]);
let run = E::Dict(vec![("RunData".into(), E::Dict(vec![("StyleSheet".into(), E::Dict(vec![("Features".into(), features)]))]))]);
let entry = E::Dict(vec![("Model".into(), E::Dict(vec![("StyleRun".into(), E::Dict(vec![("RunArray".into(), E::Array(vec![run]))]))]))]);
let text = "ab".repeat(50);
let runs = (0..100).map(|i| TextRun { len: 1, style: CharStyle { size_pt: if i % 2 == 0 { 30.0 } else { 40.0 }, ..Default::default() } }).collect();
let layer = TextLayer { text, runs, ..Default::default() };
assert_eq!(td_restyled(&entry, &layer, &mut Vec::new(), 72.0), None);
}
}
+122 -5
View File
@@ -13,6 +13,48 @@ const MAX_REFIT_RUN_NODES: usize = 16_384;
const MAX_REFIT_RUN_BYTES: usize = 1 << 20;
/// Cumulative node and string-byte budgets for the style runs copied from one preserved run while
/// restyling (`txt2_style_runs`, `td_restyled`, [`with_modes`]): a template within
/// [`TEMPLATE_NODES`] can still hold long strings, copied once per output run.
const MAX_COPIED_NODES: usize = 1 << 22;
const MAX_COPIED_BYTES: usize = 64 << 20;
/// Whether `copies` copies of `v` fit [`MAX_COPIED_NODES`] and [`MAX_COPIED_BYTES`].
#[cfg(test)]
pub(super) fn copies_fit(v: &E, copies: usize) -> bool {
copies_fit_plus(v, copies, 0, 0)
}
/// [`copies_fit`] where each copy also gains up to `extra_nodes` nodes and `extra_bytes` key bytes
/// (keys the caller adds after copying).
pub(super) fn copies_fit_plus(v: &E, copies: usize, extra_nodes: usize, extra_bytes: usize) -> bool {
let (mut nodes, mut bytes) = (MAX_COPIED_NODES, MAX_COPIED_BYTES);
if !fits_budget(v, &mut nodes, &mut bytes) {
return false;
}
let (n, b) = (MAX_COPIED_NODES - nodes, MAX_COPIED_BYTES - bytes);
n.saturating_add(extra_nodes).checked_mul(copies).is_some_and(|t| t <= MAX_COPIED_NODES)
&& b.saturating_add(extra_bytes).checked_mul(copies).is_some_and(|t| t <= MAX_COPIED_BYTES)
}
/// Values at most this large survive [`compact`]: far above any style value Photoshop writes.
const SMALL_NODES: usize = 256;
const SMALL_BYTES: usize = 4096;
/// `v` without its oversized values, for a style run template that fails [`copies_fit`]: along
/// `path` each dictionary keeps its small entries and the next step of the path, so every
/// ordinary key is still copied into the new runs and only data no real file holds at that size
/// is left out. `None` when `v` is not a dictionary.
pub(super) fn compact(v: &E, path: &[&str]) -> Option<E> {
let E::Dict(items) = v else { return None };
let small = |k: &str, x: &E| k.len() <= SMALL_BYTES && fits_budget(x, &mut { SMALL_NODES }, &mut { SMALL_BYTES });
let kept = items.iter().filter_map(|(k, x)| match path.split_first() {
Some((head, rest)) if k == head => compact(x, rest).map(|c| (k.clone(), c)),
_ => small(k, x).then(|| (k.clone(), x.clone())),
});
Some(E::Dict(kept.collect()))
}
/// Whether `v` holds at most `budget` values, counting down `budget` (stops at the first one over).
pub(super) fn fits(v: &E, budget: &mut usize) -> bool {
let Some(left) = budget.checked_sub(1) else { return false };
@@ -243,21 +285,25 @@ fn runs_to_length(runs: &[E], total: usize, len_key: &str, nodes: &mut usize, by
/// The file's own `Txt2` style runs `runs` with the auto-kern modes `modes` (`(mode, UTF-16
/// length)`, see [`txt2_mode_runs`]) set at `/0 /0 /6 /11`, keeping every other style key. A
/// run a mode change falls inside is split there. `None` when the runs don't cover the text or
/// lack a style dictionary: the caller writes its own runs instead.
pub(super) fn with_modes(runs: &[E], modes: &[(i64, usize)]) -> Option<Vec<E>> {
/// lack a style dictionary: the caller writes its own runs instead. Runs are moved, not copied;
/// only the extra pieces a split makes are copies, charged to the copy budget, so an unchanged
/// object keeps its runs whatever their size.
pub(super) fn with_modes(runs: Vec<E>, modes: &[(i64, usize)]) -> Option<Vec<E>> {
let lens: Vec<usize> = runs.iter().map(|r| r.get("1").and_then(E::as_i64).and_then(|l| usize::try_from(l).ok())).collect::<Option<_>>()?;
let total = modes.iter().try_fold(0usize, |a, m| a.checked_add(m.1))?;
if lens.iter().try_fold(0usize, |a, l| a.checked_add(*l))? != total {
return None;
}
let mut out = Vec::with_capacity(runs.len());
let (mut nodes, mut bytes) = (MAX_COPIED_NODES, MAX_COPIED_BYTES);
let (mut mi, mut mode_end) = (0usize, modes.first()?.1);
let mut at = 0usize;
for (run, len) in runs.iter().zip(lens) {
for (run, len) in runs.into_iter().zip(lens) {
if len == 0 {
out.push(run.clone());
out.push(run);
continue;
}
let mut run = Some(run);
let end = at + len;
while at < end {
while at >= mode_end && mi + 1 < modes.len() {
@@ -268,7 +314,16 @@ pub(super) fn with_modes(runs: &[E], modes: &[(i64, usize)]) -> Option<Vec<E>> {
if piece_end <= at {
return None;
}
let mut piece = run.clone();
// The last piece takes the run itself; every earlier one (a mode boundary inside the
// run) is a copy.
let mut piece = if piece_end == end {
run.take()?
} else {
if !fits_budget(run.as_ref()?, &mut nodes, &mut bytes) {
return None;
}
run.clone()?
};
if piece_end - at != len {
piece.set("1", E::Int(i64::try_from(piece_end - at).ok()?));
}
@@ -318,3 +373,65 @@ pub fn set_text_index(tysh: &[u8], index: i32) -> Option<Vec<u8>> {
}
write_tysh(&t)
}
#[cfg(test)]
mod copy_budget_tests {
use super::{E, MAX_COPIED_BYTES, MAX_COPIED_NODES, compact, copies_fit, copies_fit_plus, with_modes};
/// `<< /0 << /0 << /6 << /11 1 /99 (filler) >> >> >> /1 len >>`, a Txt2 style run.
fn run(len: i64, filler: usize) -> E {
let style = E::Dict(vec![("11".into(), E::Int(1)), ("99".into(), E::String("x".repeat(filler)))]);
let inner = E::Dict(vec![("6".into(), style)]);
E::Dict(vec![("0".into(), E::Dict(vec![("0".into(), inner)])), ("1".into(), E::Int(len))])
}
#[test]
fn copies_of_a_large_preserved_run_are_refused() {
assert!(copies_fit(&run(1, 16), 1000));
let big = run(1, 1 << 20);
assert!(copies_fit(&big, 63));
assert!(!copies_fit(&big, MAX_COPIED_BYTES >> 20), "64 copies of 1 MiB pass the byte budget");
assert!(!copies_fit(&big, usize::MAX));
}
#[test]
fn keys_added_per_copy_count_against_the_node_budget() {
let small = run(1, 16);
let copies = MAX_COPIED_NODES / 8;
assert!(copies_fit(&small, copies), "the template alone passes");
assert!(!copies_fit_plus(&small, copies, 18, 0), "the keys each copy gains do not");
}
#[test]
fn key_bytes_added_per_copy_count_against_the_byte_budget() {
let small = run(1, 16);
let copies = 100_000;
assert!(copies_fit_plus(&small, copies, 0, 0), "the template alone passes");
assert!(!copies_fit_plus(&small, copies, 0, 700), "the key bytes each copy gains do not");
}
#[test]
fn compacting_drops_only_oversized_values() {
let big = run(5, 1 << 20);
let small = compact(&big, &["0", "0", "6"]).unwrap();
// The 1 MiB string goes; the mode key, the path and the length stay.
assert_eq!(small.path(&["0", "0", "6", "11"]).and_then(E::as_i64), Some(1));
assert!(small.path(&["0", "0", "6", "99"]).is_none());
assert_eq!(small.get("1").and_then(E::as_i64), Some(5));
assert!(copies_fit(&small, 100_000));
// An ordinary run comes back whole.
assert_eq!(compact(&run(5, 16), &["0", "0", "6"]), Some(run(5, 16)));
}
#[test]
fn mode_splits_stop_at_the_copy_budget() {
// One run, 1 MiB of preserved text, split at every one of 200 mode boundaries.
let modes: Vec<(i64, usize)> = (0..200).map(|i| (i % 2, 1)).collect();
assert!(with_modes(vec![run(200, 1 << 20)], &modes).is_none());
assert_eq!(with_modes(vec![run(200, 16)], &modes).map(|v| v.len()), Some(200));
// Unsplit runs are moved, not copied: an unchanged object keeps them whatever their size.
let kept = vec![run(100, 1 << 20), run(100, 1 << 20)];
let modes = [(1, 100), (1, 100)];
assert_eq!(with_modes(kept.clone(), &modes), Some(kept));
}
}
+8 -2
View File
@@ -390,6 +390,10 @@ fn descriptor_rect(text: &Descriptor, key: &str) -> Option<[f64; 4]> {
pub(super) const MAX_ENGINE_RUNS: usize = 65_536;
/// The longest `FontSet` name kept. PostScript names are at most 63 characters; family names in
/// the files seen are shorter than this.
const MAX_FONT_NAME: usize = 1024;
pub(crate) fn arr_f(v: Option<&E>) -> Vec<f64> {
v.and_then(E::as_array).map(|a| a.iter().take(MAX_ENGINE_RUNS).filter_map(E::as_f64).collect()).unwrap_or_default()
}
@@ -435,7 +439,9 @@ fn apply_engine_data(layer: &mut TextLayer, e: &E, txt: Option<&str>, k: f32) {
let fonts: Vec<String> = res
.and_then(|r| r.get("FontSet"))
.and_then(E::as_array)
.map(|a| a.iter().map(|f| f.get("Name").and_then(E::as_str).unwrap_or("").to_string()).collect())
// Every character run naming a font copies its name (family and PostScript name): a name
// past any real one's length is dropped, so one huge entry can't be multiplied by the runs.
.map(|a| a.iter().map(|f| f.get("Name").and_then(E::as_str).filter(|n| n.len() <= MAX_FONT_NAME).unwrap_or("").to_string()).collect())
.unwrap_or_default();
// Style resolution (#3795). A run's own `StyleSheetData` / `Properties` hold only what it
// overrides; the rest comes from its sheets, as in Photoshop:
@@ -563,7 +569,7 @@ pub(crate) fn char_style(base: &[Option<&E>], d: &E, fonts: &[String], k: f32) -
let numk = |key: &str, k: f32| num(key).map(|v| v as f32 * k).filter(|v| v.is_finite());
let flag = |key: &str| g(key).and_then(E::as_bool);
let mut s = CharStyle::default();
if let Some(ps) = g("Font").and_then(E::as_i64).and_then(|i| usize::try_from(i).ok()).and_then(|i| fonts.get(i)) {
if let Some(ps) = g("Font").and_then(E::as_i64).and_then(|i| usize::try_from(i).ok()).and_then(|i| fonts.get(i)).filter(|ps| !ps.is_empty()) {
let r = guess_from_postscript(ps);
s.font_family = r.family;
s.weight = r.weight;