mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-21 20:38:15 +00:00
Merge remote-tracking branch 'origin/main' into t4270b
# Conflicts: # packaging/linux/flatpak/cargo-sources.json
This commit is contained in:
Generated
+9
@@ -1421,6 +1421,14 @@ dependencies = [
|
||||
"roxmltree",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-plist"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bea6ed1ff031b81df2d64be470485c1ca808847e#bea6ed1ff031b81df2d64be470485c1ca808847e"
|
||||
dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
@@ -4066,6 +4074,7 @@ dependencies = [
|
||||
"craft-jxl",
|
||||
"craft-mime",
|
||||
"craft-pdf",
|
||||
"craft-plist",
|
||||
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=94777dcf7f8962476e96b049d08d22e25b9330c2)",
|
||||
"crc32fast",
|
||||
"fs4",
|
||||
|
||||
@@ -10,6 +10,7 @@ rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/lightcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-plist = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bea6ed1ff031b81df2d64be470485c1ca808847e" }
|
||||
craft-pdf-print = { package = "craft-pdf", git = "https://github.com/storytold/craft-libs", rev = "0fd30aeb3e02207d9d4c7c601540d9da45abf8de", default-features = false, features = ["write-raster"] }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7", features = ["serde"] }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "c5a1cbfb5f9049f9270955caffb5bee5997aebf7" }
|
||||
|
||||
@@ -9,6 +9,7 @@ description = "LightCraft engine: session, command registry, history, render job
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-plist = { workspace = true }
|
||||
craft-pdf-print.workspace = true
|
||||
craft-mime = { workspace = true }
|
||||
# Paths stored in a Lightroom catalog are followed only to local files or the catalog's share.
|
||||
|
||||
@@ -62,198 +62,43 @@ impl Plist {
|
||||
}
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
s: &'a str,
|
||||
i: usize,
|
||||
/// Nesting of the element being read (bounded: a hostile file must not overflow the stack).
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
/// Deepest `<dict>` / `<array>` nesting read (real looks nest a handful of levels).
|
||||
const MAX_DEPTH: usize = 64;
|
||||
|
||||
/// Index of the `;` that ends a reference starting at `rest` (its `&`). The scan stops at the first
|
||||
/// byte that cannot appear in a name or a numeric reference, so zero-padded references such as
|
||||
/// `a` are found and each run of name bytes is read once, not once per `&`.
|
||||
fn entity_end(rest: &str) -> Option<usize> {
|
||||
let n = rest.bytes().skip(1).take_while(|b| b.is_ascii_alphanumeric() || *b == b'#').count();
|
||||
(rest.as_bytes().get(n + 1) == Some(&b';')).then_some(n + 1)
|
||||
}
|
||||
|
||||
fn unescape(t: &str) -> String {
|
||||
let mut out = String::with_capacity(t.len());
|
||||
let mut rest = t;
|
||||
while let Some(p) = rest.find('&') {
|
||||
out.push_str(&rest[..p]);
|
||||
rest = &rest[p..];
|
||||
// no `;` within a reference's reach: the `&` is kept and the search goes on after it
|
||||
let Some(end) = entity_end(rest) else {
|
||||
out.push('&');
|
||||
rest = &rest[1..];
|
||||
continue;
|
||||
};
|
||||
let ent = &rest[1..end];
|
||||
let c = match ent {
|
||||
"amp" => Some('&'),
|
||||
"lt" => Some('<'),
|
||||
"gt" => Some('>'),
|
||||
"quot" => Some('"'),
|
||||
"apos" => Some('\''),
|
||||
_ => ent
|
||||
.strip_prefix("#x")
|
||||
.or_else(|| ent.strip_prefix("#X"))
|
||||
.filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.and_then(|h| u32::from_str_radix(h, 16).ok())
|
||||
.or_else(|| ent.strip_prefix('#').filter(|d| d.bytes().all(|b| b.is_ascii_digit())).and_then(|d| d.parse().ok()))
|
||||
.and_then(char::from_u32),
|
||||
};
|
||||
match c {
|
||||
Some(c) => {
|
||||
out.push(c);
|
||||
rest = &rest[end + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push('&');
|
||||
rest = &rest[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn err<T>(&self, what: &str) -> Result<T, String> {
|
||||
Err(format!("property list: {what} at byte {}", self.i))
|
||||
}
|
||||
/// Skip whitespace, the XML declaration, the doctype and comments.
|
||||
fn skip(&mut self) {
|
||||
loop {
|
||||
let r = &self.s[self.i..];
|
||||
let t = r.trim_start();
|
||||
self.i += r.len() - t.len();
|
||||
let close = if t.starts_with("<?") {
|
||||
"?>"
|
||||
} else if t.starts_with("<!--") {
|
||||
"-->"
|
||||
} else if t.starts_with("<!") {
|
||||
">"
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
match t.find(close) {
|
||||
Some(e) => self.i += e + close.len(),
|
||||
None => {
|
||||
self.i = self.s.len();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The next tag: (name, closing, self-closing).
|
||||
fn tag(&mut self) -> Result<(String, bool, bool), String> {
|
||||
self.skip();
|
||||
let r = &self.s[self.i..];
|
||||
if !r.starts_with('<') {
|
||||
return self.err("expected a tag");
|
||||
}
|
||||
let Some(end) = r.find('>') else { return self.err("unterminated tag") };
|
||||
let inner = &r[1..end];
|
||||
self.i += end + 1;
|
||||
let closing = inner.starts_with('/');
|
||||
let selfc = inner.ends_with('/');
|
||||
let name = inner.trim_start_matches('/').trim_end_matches('/').split_whitespace().next().unwrap_or("").to_string();
|
||||
Ok((name, closing, selfc))
|
||||
}
|
||||
fn peek_close(&mut self, name: &str) -> bool {
|
||||
self.skip();
|
||||
let r = &self.s[self.i..];
|
||||
let t = format!("</{name}>");
|
||||
if r.starts_with(&t) {
|
||||
self.i += t.len();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
fn text(&mut self, name: &str) -> Result<String, String> {
|
||||
let r = &self.s[self.i..];
|
||||
let t = format!("</{name}>");
|
||||
let Some(end) = r.find(&t) else { return self.err(&format!("missing {t}")) };
|
||||
self.i += end + t.len();
|
||||
Ok(unescape(&r[..end]))
|
||||
}
|
||||
fn value(&mut self) -> Result<Plist, String> {
|
||||
if self.depth >= MAX_DEPTH {
|
||||
return self.err("nested too deeply");
|
||||
}
|
||||
self.depth += 1;
|
||||
let v = self.value_inner();
|
||||
self.depth -= 1;
|
||||
v
|
||||
}
|
||||
fn value_inner(&mut self) -> Result<Plist, String> {
|
||||
let (name, closing, selfc) = self.tag()?;
|
||||
if closing {
|
||||
return self.err(&format!("unexpected </{name}>"));
|
||||
}
|
||||
let leaf = |p: &mut Self, f: &dyn Fn(String) -> Result<Plist, String>| if selfc { f(String::new()) } else { p.text(&name).and_then(f) };
|
||||
match name.as_str() {
|
||||
"plist" => {
|
||||
if selfc {
|
||||
return Ok(Plist::Dict(Vec::new()));
|
||||
}
|
||||
let v = self.value()?;
|
||||
self.peek_close("plist");
|
||||
Ok(v)
|
||||
}
|
||||
"dict" => {
|
||||
let mut m = Vec::new();
|
||||
if !selfc {
|
||||
while !self.peek_close("dict") {
|
||||
let (k, c, sc) = self.tag()?;
|
||||
if k != "key" || c {
|
||||
return self.err("expected <key>");
|
||||
}
|
||||
let key = if sc { String::new() } else { self.text("key")? };
|
||||
m.push((key, self.value()?));
|
||||
}
|
||||
}
|
||||
Ok(Plist::Dict(m))
|
||||
}
|
||||
"array" => {
|
||||
let mut a = Vec::new();
|
||||
if !selfc {
|
||||
while !self.peek_close("array") {
|
||||
a.push(self.value()?);
|
||||
}
|
||||
}
|
||||
Ok(Plist::Array(a))
|
||||
}
|
||||
"string" | "date" => leaf(self, &|t| Ok(Plist::Str(t))),
|
||||
"real" | "integer" => {
|
||||
leaf(self, &|t| t.trim().parse::<f64>().map(Plist::Num).map_err(|_| format!("property list: bad number {:?}", t.trim())))
|
||||
}
|
||||
"data" => leaf(self, &|_| Ok(Plist::Data)),
|
||||
"true" | "false" => {
|
||||
if !selfc {
|
||||
self.text(&name)?;
|
||||
}
|
||||
Ok(Plist::Bool(name == "true"))
|
||||
}
|
||||
_ => self.err(&format!("unknown element <{name}>")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an XML property list.
|
||||
/// Parse XML through the shared bounded codec; binary presets remain unsupported.
|
||||
pub fn parse_plist(bytes: &[u8]) -> Result<Plist, String> {
|
||||
if bytes.starts_with(b"bplist") {
|
||||
return Err("binary property lists are not supported".into());
|
||||
}
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let mut p = Parser { s: text.trim_start_matches('\u{feff}'), i: 0, depth: 0 };
|
||||
p.value()
|
||||
// The existing wrapped-plist limit counts the <plist> wrapper and root value.
|
||||
// ZIP expansion remains charged separately by preset_import before this parser runs.
|
||||
let limits = craft_plist::Limits {
|
||||
max_input_bytes: MAX_ZIP_ENTRY,
|
||||
max_expanded_bytes: MAX_ZIP_ENTRY.saturating_mul(2),
|
||||
max_depth: 62,
|
||||
..craft_plist::Limits::default()
|
||||
};
|
||||
let value =
|
||||
craft_plist::parse_xml_with_options(bytes, limits, craft_plist::XmlOptions { trim_date_text: false }).map_err(|error| match error {
|
||||
craft_plist::FormatError::TooLarge(_) => format!("property list: nested too deeply or exceeds resource limits: {error}"),
|
||||
_ => format!("property list: {error}"),
|
||||
})?;
|
||||
map_plist(value)
|
||||
}
|
||||
|
||||
// Luminar mapping deliberately keeps its existing value policy: dates are strings, integer
|
||||
// settings are f64, and data is a presence marker rather than an app-owned binary payload.
|
||||
fn map_plist(value: craft_plist::Value) -> Result<Plist, String> {
|
||||
use craft_plist::{DateValue, Value};
|
||||
Ok(match value {
|
||||
Value::Dict(entries) => {
|
||||
Plist::Dict(entries.into_iter().map(|(key, value)| map_plist(value).map(|value| (key, value))).collect::<Result<_, _>>()?)
|
||||
}
|
||||
Value::Array(values) => Plist::Array(values.into_iter().map(map_plist).collect::<Result<_, _>>()?),
|
||||
Value::String(value) | Value::Date(DateValue::Text(value)) => Plist::Str(value),
|
||||
Value::Integer(value) => Plist::Num(value as f64),
|
||||
Value::Real(value) => Plist::Num(value),
|
||||
Value::Bool(value) => Plist::Bool(value),
|
||||
Value::Data(_) => Plist::Data,
|
||||
_ => return Err("property list: unsupported XML value".into()),
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ mapping
|
||||
@@ -508,6 +353,10 @@ pub(crate) fn read_mplumpack_within(path: &str, bytes: &[u8], budget: &mut usize
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
fn unescape(text: &str) -> String {
|
||||
let xml = format!("<string>{text}</string>");
|
||||
super::parse_plist(xml.as_bytes()).unwrap().str().unwrap().to_string()
|
||||
}
|
||||
use super::*;
|
||||
use crate::preset_import::read_presets;
|
||||
use serde_json::json;
|
||||
@@ -731,4 +580,22 @@ mod tests {
|
||||
assert_eq!(r["imported"][0]["group"], json!("Imported Presets"), "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_plist_adapter_keeps_luminar_value_mapping() {
|
||||
let p = parse_plist(
|
||||
b"<dict><key>date</key><date> 2026-01-01T00:00:00Z </date><key>integer</key><integer>-3</integer><key>data</key><data>AAEC</data></dict>",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.get("date").and_then(Plist::str), Some(" 2026-01-01T00:00:00Z "));
|
||||
assert_eq!(p.get("integer").and_then(Plist::num), Some(-3.0));
|
||||
assert_eq!(p.get("data"), Some(&Plist::Data));
|
||||
}
|
||||
#[test]
|
||||
fn shared_plist_refuses_malformed_values_instead_of_repairing_them() {
|
||||
for xml in ["<data>not base64!</data>", "<integer>1.5</integer>", "<real>NaN</real>", "<plist><string>x</string>", "<string>x</string>junk"] {
|
||||
assert!(parse_plist(xml.as_bytes()).is_err(), "{xml}");
|
||||
}
|
||||
assert!(parse_plist(b"<string>\xff</string>").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user