Compare commits

..
Author SHA1 Message Date
Dylan M. Taylor 86352d5cf3 Reuse shared Base64 encoding for engine payloads 2026-11-15 14:34:21 -05:00
9 changed files with 56 additions and 126 deletions
Generated
+1
View File
@@ -7331,6 +7331,7 @@ dependencies = [
"chrono",
"craft-font-catalog",
"craft-font-store",
"craft-mime",
"craft-proof",
"craft-zip",
"encoding_rs",
+1
View File
@@ -15,6 +15,7 @@ workspace = true
test-support = []
[dependencies]
craft-mime.workspace = true
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
wordcraft-fonts = { workspace = true }
+1 -16
View File
@@ -71,22 +71,7 @@ pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
Some(out)
}
pub fn base64_encode(b: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
for ch in b.chunks(3) {
let n =
(ch.first().copied().unwrap_or(0) as u32) << 16 | (ch.get(1).copied().unwrap_or(0) as u32) << 8 | ch.get(2).copied().unwrap_or(0) as u32;
for i in 0..4 {
if i <= ch.len() {
out.push(T[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
pub use craft_mime::transfer::base64 as base64_encode;
pub(crate) fn picture(s: &mut Session, v: &Value) -> CmdResult {
let bytes = if let Some(d) = p::str(v, "data") {
+19
View File
@@ -415,3 +415,22 @@ fn local_civil_date_follows_the_utc_offset() {
assert!(crate::cmd::local_offset_secs(unix).abs() <= 26 * 3600);
}
}
#[test]
fn shared_base64_preserves_command_payload_bytes() {
for (plain, encoded) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foobar", "Zm9vYmFy")] {
assert_eq!(super::objects::base64_encode(plain.as_bytes()), encoded);
}
let bytes: Vec<u8> = (0..513).map(|i| (i % 256) as u8).collect();
for len in 0..=bytes.len() {
let encoded = super::objects::base64_encode(&bytes[..len]);
assert_eq!(encoded.len(), len.div_ceil(3) * 4);
assert!(!encoded.contains(['\r', '\n']));
assert_eq!(super::objects::base64_decode(&encoded), Some(bytes[..len].to_vec()));
}
assert_eq!(super::objects::base64_encode(&[251, 255, 255]), "+///");
// The existing decoder intentionally accepts URL-safe symbols, whitespace and optional padding.
assert_eq!(super::objects::base64_decode("-___"), Some(vec![251, 255, 255]));
assert_eq!(super::objects::base64_decode("Z g\n"), Some(b"f".to_vec()));
assert_eq!(super::objects::base64_decode("!!!!"), None);
}
+20 -24
View File
@@ -1,4 +1,5 @@
//! WordCraft geometry and units.
//!
//! Layout works in **points** (1/72 inch, `f32`). File formats use other units: OOXML uses
//! twentieths of a point (twips) for most lengths, half-points for font sizes, eighths of a point
//! for borders and English Metric Units (EMU, 914 400 per inch) for drawings. The conversions live
@@ -24,32 +25,26 @@ pub const EMU_PER_PT: f32 = 12_700.0;
pub const PT_PER_CM: f32 = 72.0 / 2.54;
/// Twips → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn twips(v: i64) -> f32 {
v as f32 / TWIPS_PER_PT
}
/// Points → twips (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_twips(pt: f32) -> i64 {
finite(pt * TWIPS_PER_PT).round() as i64
}
/// EMU → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn emu(v: i64) -> f32 {
v as f32 / EMU_PER_PT
}
/// Points → EMU (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_emu(pt: f32) -> i64 {
(f64::from(finite(pt)) * f64::from(EMU_PER_PT)).round() as i64
(finite(pt) as f64 * EMU_PER_PT as f64).round() as i64
}
/// Half-points (OOXML font sizes) → points.
#[expect(clippy::cast_precision_loss, reason = "The f32 return type intentionally rounds i64 inputs to f32 precision.")]
pub fn half_points(v: i64) -> f32 {
v as f32 / 2.0
}
/// Points → half-points (rounded).
#[expect(clippy::cast_possible_truncation, reason = "The value is rounded first; Rust's float-to-integer cast saturates outside the i64 range.")]
pub fn to_half_points(pt: f32) -> i64 {
(finite(pt) * 2.0).round() as i64
}
@@ -128,7 +123,8 @@ pub fn parse_measure(s: &str, default: Unit) -> Option<f32> {
"cm" => PT_PER_CM,
"mm" => PT_PER_CM / 10.0,
"pt" | "pts" | "point" | "points" => 1.0,
"pi" | "pc" | "pica" | "picas" | "li" | "line" | "lines" => 12.0,
"pi" | "pc" | "pica" | "picas" => 12.0,
"li" | "line" | "lines" => 12.0,
"px" => 0.75,
_ => return None,
};
@@ -202,7 +198,7 @@ pub fn normalize_degrees(deg: f32) -> f32 {
}
/// How a drawing is turned about its centre: mirrored first (`flip_h` left to right, `flip_v` top
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as `DrawingML`'s `a:xfrm`
/// to bottom), then rotated `deg` degrees clockwise (page space, y down), as DrawingML's `a:xfrm`
/// `flipH`, `flipV` and `rot` say (ECMA-376 §20.1.7.6).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct Spin {
@@ -223,7 +219,7 @@ impl Spin {
}
/// The linear part (a, b, c, d: x' = a·x + c·y, y' = b·x + d·y).
fn linear(self) -> [f32; 4] {
fn linear(&self) -> [f32; 4] {
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = r.sin_cos();
let fx = if self.flip_h { -1.0 } else { 1.0 };
@@ -241,17 +237,17 @@ impl Spin {
/// Where point (`x`, `y`) goes when turned about (`cx`, `cy`).
pub fn apply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + x_from_y * relative_y, cy + y_from_x * relative_x + y_from_y * relative_y)
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + c * v, cy + b * u + d * v)
}
/// The point that [`Spin::apply`] takes to (`x`, `y`).
pub fn unapply(&self, cx: f32, cy: f32, x: f32, y: f32) -> (f32, f32) {
// The linear part is orthogonal: its inverse is its transpose.
let [x_from_x, y_from_x, x_from_y, y_from_y] = self.linear();
let (relative_x, relative_y) = (x - cx, y - cy);
(cx + x_from_x * relative_x + y_from_x * relative_y, cy + x_from_y * relative_x + y_from_y * relative_y)
let [a, b, c, d] = self.linear();
let (u, v) = (x - cx, y - cy);
(cx + a * u + b * v, cy + c * u + d * v)
}
/// The axis-aligned box `r` covers once turned about its centre.
@@ -262,10 +258,10 @@ impl Spin {
/// The width and height of the box a `w` × `h` rectangle covers once turned.
pub fn extent(&self, w: f32, h: f32) -> (f32, f32) {
let (width, height) = (finite(w).abs(), finite(h).abs());
let radians = normalize_degrees(self.deg).to_radians();
let (sine, cosine) = (radians.sin().abs(), radians.cos().abs());
(width * cosine + height * sine, width * sine + height * cosine)
let (w, h) = (finite(w).abs(), finite(h).abs());
let r = normalize_degrees(self.deg).to_radians();
let (s, c) = (r.sin().abs(), r.cos().abs());
(w * c + h * s, w * s + h * c)
}
/// This spin applied inside `outer` (a group member's own spin within its group's): the one
@@ -347,11 +343,11 @@ mod tests {
#[test]
fn unit_round_trips() {
assert_eq!(twips(1440).to_bits(), 72.0f32.to_bits());
assert_eq!(twips(1440), 72.0);
assert_eq!(to_twips(72.0), 1440);
assert_eq!(emu(914_400).to_bits(), 72.0f32.to_bits());
assert_eq!(emu(914_400), 72.0);
assert_eq!(to_emu(72.0), 914_400);
assert_eq!(half_points(24).to_bits(), 12.0f32.to_bits());
assert_eq!(half_points(24), 12.0);
assert_eq!(to_half_points(10.5), 21);
assert_eq!(to_twips(f32::NAN), 0);
}
@@ -433,7 +429,7 @@ mod tests {
assert!(a.intersects(&b));
assert_eq!(a.union(&b), Rect::new(0.0, 0.0, 15.0, 15.0));
assert!(a.contains(Point::new(5.0, 5.0)));
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w.to_bits(), 0.0f32.to_bits());
assert_eq!(Rect::new(0.0, 0.0, -5.0, f32::NAN).w, 0.0);
assert_eq!(a.inset(1.0, 2.0, 3.0, 4.0), Rect::new(1.0, 2.0, 6.0, 4.0));
}
+3 -28
View File
@@ -20,9 +20,9 @@ pub enum Refusal {
NotAPicture,
/// A kind of picture that is never decoded, because its decoder can't be held to a budget.
Unsupported(&'static str),
/// Decoding would exceed the memory budget or size arithmetic overflowed.
/// Decoding it would take more memory than the budget.
TooLarge { width: u32, height: u32 },
/// The header or data is damaged, or the decoder rejects the input.
/// The header or the data is damaged.
Broken(String),
}
@@ -179,19 +179,11 @@ pub struct Probe<'a> {
}
/// TIFF compressions decoded within the caller's limits: none, CCITT Group 4, LZW, Deflate (both
/// codes) and `PackBits`. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// codes) and PackBits. The `tiff` crate decodes a JPEG strip (7) with a decoder of its own and
/// default limits, whatever size the TIFF declares, so such a TIFF is not decoded (#3645).
const TIFF_COMPRESSIONS: [u16; 6] = [1, 4, 5, 8, 32946, 32773];
/// Read a picture's header: PNG, JPEG, GIF, WebP, BMP or TIFF.
///
/// # Errors
///
/// Returns `Refusal::NotAPicture` for an unsupported format, `Refusal::Unsupported` for a TIFF
/// whose compression cannot be read or budgeted (including truncation that prevents reading
/// its compression metadata), `Refusal::TooLarge`
/// on size arithmetic overflow, and `Refusal::Broken` for other header or inspection errors,
/// including TIFF errors after compression metadata is accepted.
pub fn probe(bytes: &[u8]) -> Result<Probe<'_>, Refusal> {
let codec_fmt = detect(bytes).ok_or(Refusal::NotAPicture)?;
let format = from_codec_format(codec_fmt).ok_or(Refusal::NotAPicture)?;
@@ -295,11 +287,6 @@ fn dib_to_bmp(dib: &[u8]) -> Vec<u8> {
/// Read a DIB's header: a BMP without its 14-byte file header, as the Windows clipboard holds
/// one (`CF_DIB`, `CF_DIBV5`). Its layout is first made the one the decoder reads (see
/// [`dib_layout`]).
///
/// # Errors
///
/// Returns `Refusal::Broken` for an invalid DIB header and `Refusal::TooLarge` on size arithmetic
/// overflow.
pub fn probe_dib(dib: Vec<u8>) -> Result<Probe<'static>, Refusal> {
let dib = dib_layout(dib);
let bmp = dib_to_bmp(&dib);
@@ -362,12 +349,6 @@ impl Probe<'_> {
/// Decode, refused before anything is allocated when the peak would pass `budget` bytes. The
/// decoder is held to the header's size and to `budget` as well.
///
/// # Errors
///
/// Returns `Refusal::TooLarge` when the picture does not fit `budget` or the decoder
/// exceeds its limits, `Refusal::NotAPicture` for an unsupported format, and
/// `Refusal::Broken` for other decoding or pixel-conversion errors.
pub fn decode(&self, budget: u64) -> Result<DynamicImage, Refusal> {
if !self.fits(budget) {
return Err(Refusal::TooLarge { width: self.width, height: self.height });
@@ -383,10 +364,6 @@ impl Probe<'_> {
}
/// [`probe`], then [`Probe::decode`] within `budget` bytes.
///
/// # Errors
///
/// Returns the probing or decoding `Refusal`; see [`probe`] and [`Probe::decode`].
pub fn decode(bytes: &[u8], budget: u64) -> Result<DynamicImage, Refusal> {
probe(bytes)?.decode(budget)
}
@@ -745,7 +722,6 @@ mod tests {
let mut s = vec![8];
s.extend(h.to_be_bytes());
s.extend(w.to_be_bytes());
#[expect(clippy::cast_possible_truncation, reason = "These fixtures contain at most four three-byte component records.")]
s.push((comps.len() / 3) as u8);
s.extend(comps);
s
@@ -760,7 +736,6 @@ mod tests {
// A marker walk over SOI, an APP0 segment, SOF2, then the scan.
let mut jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 4, 0, 0, 0xFF, 0xC2];
let f = sof(64, 64, &[1, 0x11, 0]);
#[expect(clippy::cast_possible_truncation, reason = "This fixture's nine-byte frame header and length field fit u16.")]
jpeg.extend(((f.len() + 2) as u16).to_be_bytes());
jpeg.extend(&f);
jpeg.extend([0xFF, 0xDA]);
+10 -22
View File
@@ -9,7 +9,7 @@ pub const MAX_RASTER_PIXELS: u64 = 100_000_000;
/// Bytes of a `w`×`h` RGBA8 raster, None on overflow.
pub fn rgba_bytes(w: u32, h: u32) -> Option<u64> {
u64::from(w).checked_mul(u64::from(h))?.checked_mul(4)
(w as u64).checked_mul(h as u64)?.checked_mul(4)
}
/// Whether a `w`×`h` RGBA8 raster fits `budget` bytes.
@@ -29,34 +29,22 @@ pub fn decode_fits(w: u32, h: u32, budget: u64) -> bool {
/// premultiplied copy, so the peak is the larger of `native + 4` and `8` bytes a pixel.
pub fn decode_peak_fits(w: u32, h: u32, native: u64, budget: u64) -> bool {
let per_pixel = native.saturating_add(4).max(8);
w > 0 && h > 0 && u64::from(w).checked_mul(u64::from(h)).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
w > 0 && h > 0 && (w as u64).checked_mul(h as u64).and_then(|p| p.checked_mul(per_pixel)).is_some_and(|b| b <= budget)
}
/// `w`×`h` shrunk (aspect kept, each side at least 1) until it holds at most `max_pixels`.
pub fn fit_pixels(w: u32, h: u32, max_pixels: u64) -> (u32, u32) {
let (w, h) = (w.max(1), h.max(1));
let max_pixels = max_pixels.max(1);
let area = u64::from(w) * u64::from(h);
let area = w as u64 * h as u64;
if area <= max_pixels {
return (w, h);
}
#[expect(clippy::cast_precision_loss, reason = "Floating point only approximates the scale; the integer clamps below enforce every bound.")]
let scale = (max_pixels as f64 / area as f64).sqrt();
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_height = ((f64::from(h) * scale) as u64).clamp(1, u64::from(h));
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "The scale is finite and within 0..=1; truncation floors a positive dimension before clamping."
)]
let new_width = ((f64::from(w) * scale) as u64).clamp(1, u64::from(w)).min(max_pixels / new_height).max(1);
let new_height = new_height.min(max_pixels / new_width).max(1);
#[expect(clippy::cast_possible_truncation, reason = "Both dimensions are clamped to their original u32 values above.")]
(new_width as u32, new_height as u32)
let f = (max_pixels as f64 / area as f64).sqrt();
let nh = ((h as f64 * f) as u64).clamp(1, h as u64);
let nw = ((w as f64 * f) as u64).clamp(1, w as u64).min(max_pixels / nh).max(1);
let nh = nh.min(max_pixels / nw).max(1);
(nw as u32, nh as u32)
}
#[cfg(test)]
@@ -90,9 +78,9 @@ mod tests {
fn fit_pixels_keeps_normal_sizes_and_shrinks_huge_ones() {
assert_eq!(fit_pixels(612, 792, MAX_RASTER_PIXELS), (612, 792));
let (w, h) = fit_pixels(16_000, 16_000, 1_000_000);
assert!(u64::from(w) * u64::from(h) <= 1_000_000 && w >= 900, "{w}x{h}");
assert!(w as u64 * h as u64 <= 1_000_000 && w >= 900, "{w}x{h}");
let (w, h) = fit_pixels(16_000, 1, 100);
assert!(u64::from(w) * u64::from(h) <= 100 && h == 1, "{w}x{h}");
assert!(w as u64 * h as u64 <= 100 && h == 1, "{w}x{h}");
assert_eq!(fit_pixels(0, 5, 10).0, 1);
}
}
+1 -3
View File
@@ -145,9 +145,7 @@ impl WordApp {
// Web: saving and exporting become downloads.
if self.services.download.is_some() && matches!(id, "file.save" | "file.saveAs" | "file.exportPdf" | "file.exportPng") {
let name = params.get("path").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| self.web_save_name(id));
// Inspect only the suffix bytes: no full-name allocation or UTF-8 slicing.
let has_pdf_suffix = name.as_bytes().last_chunk::<4>().is_some_and(|suffix| suffix.eq_ignore_ascii_case(b".pdf"));
let name = if id == "file.exportPdf" && !has_pdf_suffix { format!("{name}.pdf") } else { name };
let name = if id == "file.exportPdf" && !name.ends_with(".pdf") { format!("{name}.pdf") } else { name };
// A save with a password encrypts this and later saves (`file.save`'s `password`).
if matches!(id, "file.save" | "file.saveAs")
&& let Some(pw) = params.get("password").filter(|v| !v.is_null())
-33
View File
@@ -465,39 +465,6 @@ fn export_pdf_without_a_path_asks_where_to_save() {
let _ = std::fs::remove_dir_all(&dir);
}
/// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case.
#[test]
fn web_pdf_export_keeps_an_existing_suffix_in_any_case() {
let downloaded = Rc::new(RefCell::new(Vec::new()));
let captured = downloaded.clone();
let services = Services {
download: Some(Box::new(move |name, bytes| {
captured.borrow_mut().push((name.to_string(), bytes.starts_with(b"%PDF")));
Ok(())
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::new()), services);
for (name, expected) in [
("Report.pdf", "Report.pdf"),
("Report.PDF", "Report.PDF"),
("Résumé.PdF", "Résumé.PdF"),
("😀.PDF", "😀.PDF"),
(".hidden.PDF", ".hidden.PDF"),
("Report..PDF", "Report..PDF"),
("é", "é.pdf"),
("😀", "😀.pdf"),
("Report.pdf.exe", "Report.pdf.exe.pdf"),
("Report.PDF", "Report.PDF.pdf"),
("Report.pdf.", "Report.pdf..pdf"),
("Report", "Report.pdf"),
] {
let result = a.execute("file.exportPdf", json!({"path": name})).unwrap();
assert_eq!(result["downloaded"], expected, "{name}");
assert_eq!(downloaded.borrow().last().cloned(), Some((expected.to_string(), true)), "{name}");
}
}
/// Open, Save As and Export PNG from the command search (no path) ask for a file the same way.
#[test]
fn file_commands_without_a_path_ask_for_one() {