mirror of
https://github.com/storytold/craft-libs.git
synced 2026-12-01 02:36:54 +01:00
Merge main into lightcraft-pr/fw-value-editing
This commit is contained in:
commit
c3d435be9d
23 files changed
+376
-45
No files matched your search
@@ -14,6 +14,7 @@ use craft_ui::form::{Field, FieldDecimals, SliderField, SliderFieldLayout};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::runtime::memory::sub;
|
||||
use craft_ui::runtime::pointer;
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use craft_ui::value_drag::{SliderThumb, TrackFace};
|
||||
@@ -351,23 +352,22 @@ impl Component for UnitsCell {
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let first = cx.id.with("units-first-click");
|
||||
let ctx = &cx.response.ctx;
|
||||
let first = sub(cx.core.id, "units-first-click");
|
||||
// A press off the cell ends the cell's click run, even when it starts a new count that the next click on the
|
||||
// cell continues.
|
||||
if pointer::frame(ctx).press.is_some_and(|press| !cx.response.rect.contains(press.origin)) {
|
||||
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
|
||||
if pointer::frame(&cx.response.ctx).press.is_some_and(|press| !cx.response.rect.contains(press.origin)) {
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = None;
|
||||
}
|
||||
let PressPhase::Release { start, click: true, .. } = cx.part(UNITS).press.phase else { return };
|
||||
// The click count also counts a press just beside the cell, on the number field, so a click is the second of a
|
||||
// double click only when the click just before it, by the count, was a click on this cell.
|
||||
let earlier = ctx.data(|data| data.get_temp::<(f64, u32)>(first));
|
||||
let earlier = *cx.core.memory.shown::<Option<(f64, u32)>>(first);
|
||||
let follows = earlier.is_some_and(|(time, clicks)| start.clicks == clicks + 1 && start.time - time <= MULTI_CLICK_TIME);
|
||||
if start.clicks >= 2 && follows {
|
||||
self.double_clicked = true;
|
||||
ctx.data_mut(|data| data.remove::<(f64, u32)>(first));
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = None;
|
||||
} else {
|
||||
ctx.data_mut(|data| data.insert_temp(first, (start.time, start.clicks)));
|
||||
*cx.core.memory.shown::<Option<(f64, u32)>>(first) = Some((start.time, start.clicks));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Bounded OpenEXR reading and writing on top of the `exr` crate (feature `decode`).
|
||||
//!
|
||||
//! - [`parts`] lists every part from the headers alone (size, windows, channels, compression,
|
||||
//! text attributes), after checking the declared sizes against [`Limits`] and the file's size.
|
||||
//! views, text attributes), after checking the declared sizes against [`Limits`] and the file's size.
|
||||
//! - [`pick_part`] chooses the part a plain picture decode shows: the best colour channel group
|
||||
//! ([`crate::channels::color_channels`]), the earliest part on a tie.
|
||||
//! - [`decode_part`] decodes the channels of one flat part that a filter keeps, in their stored
|
||||
@@ -161,6 +161,11 @@ pub struct PartInfo {
|
||||
pub name: Option<String>,
|
||||
/// The `view` attribute of a stereo part.
|
||||
pub view: Option<String>,
|
||||
/// The `multiView` attribute of a single-part stereo file: its view names, the default view
|
||||
/// first. A channel without a period is the default view's; another view's channels carry
|
||||
/// the view name before the channel's own (`right.R`, `diffuse.right.R`). Empty without the
|
||||
/// attribute.
|
||||
pub multi_view: Vec<String>,
|
||||
pub data_window: Window,
|
||||
pub display_window: Window,
|
||||
pub deep: bool,
|
||||
@@ -317,6 +322,7 @@ pub(crate) fn part_info(index: usize, header: &Header) -> PartInfo {
|
||||
index,
|
||||
name: header.own_attributes.layer_name.as_ref().map(|n| n.to_string()),
|
||||
view: header.own_attributes.view_name.as_ref().map(|v| v.to_string()),
|
||||
multi_view: header.own_attributes.multi_view_names.iter().flatten().map(|v| v.to_string()).collect(),
|
||||
data_window: Window { x: header.own_attributes.layer_position.0, y: header.own_attributes.layer_position.1, width: w, height: h },
|
||||
display_window: Window { x: display.position.0, y: display.position.1, width: dw, height: dh },
|
||||
deep: header.deep,
|
||||
|
||||
@@ -86,6 +86,32 @@ fn multi_part_files_list_and_decode_one_part() {
|
||||
assert_eq!(pick_part(&[]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_view_part_lists_its_views_default_first() {
|
||||
let mut stereo = layer(None, 3, 2, &["B", "G", "R", "right.B", "right.G", "right.R"], false, exr::prelude::Compression::ZIP1);
|
||||
stereo.attributes.multi_view_names = Some(vec![Text::from("left"), Text::from("right")]);
|
||||
let bytes = file(vec![stereo], (3, 2));
|
||||
let listed = parts(&bytes, &Limits::default()).unwrap();
|
||||
assert_eq!(listed[0].multi_view, ["left", "right"]);
|
||||
assert_eq!(listed[0].view, None);
|
||||
// The decoded part carries the same header facts.
|
||||
assert_eq!(decode_part(&bytes, 0, &all, &Limits::default()).unwrap().info.multi_view, ["left", "right"]);
|
||||
// The declared order, not a sorted one: the right view may be the default.
|
||||
let mut right_first = layer(None, 3, 2, &["B", "G", "R", "left.B", "left.G", "left.R"], false, exr::prelude::Compression::ZIP1);
|
||||
right_first.attributes.multi_view_names = Some(vec![Text::from("right"), Text::from("left")]);
|
||||
assert_eq!(parts(&file(vec![right_first], (3, 2)), &Limits::default()).unwrap()[0].multi_view, ["right", "left"]);
|
||||
|
||||
// Parts that each name their own view, and a plain file, have no `multiView`.
|
||||
let mut left = layer(Some("beauty.left"), 3, 2, &["R"], false, exr::prelude::Compression::ZIP1);
|
||||
left.attributes.view_name = Some(Text::from("left"));
|
||||
let mut right = layer(Some("beauty.right"), 3, 2, &["R"], false, exr::prelude::Compression::ZIP1);
|
||||
right.attributes.view_name = Some(Text::from("right"));
|
||||
let listed = parts(&file(vec![left, right], (3, 2)), &Limits::default()).unwrap();
|
||||
assert_eq!(listed.iter().map(|p| (p.view.as_deref(), p.multi_view.len())).collect::<Vec<_>>(), [(Some("left"), 0), (Some("right"), 0)]);
|
||||
let plain = file(vec![layer(None, 3, 2, &["R"], false, exr::prelude::Compression::ZIP1)], (3, 2));
|
||||
assert!(parts(&plain, &Limits::default()).unwrap()[0].multi_view.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn written_files_read_back() {
|
||||
let h: Vec<f16> = (0..6).map(|i| f16::from_f32(i as f32 / 4.0)).collect();
|
||||
|
||||
@@ -15,7 +15,7 @@ pub type Migration = fn(Value) -> Result<Value, String>;
|
||||
/// edit a shipped one.
|
||||
pub const MIGRATIONS: &[Migration] = &[
|
||||
v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14,
|
||||
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19,
|
||||
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19, v19_to_v20,
|
||||
];
|
||||
|
||||
/// The schema version this build writes (and the newest it reads).
|
||||
@@ -269,6 +269,12 @@ fn v18_to_v19(doc: Value) -> Result<Value, String> {
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
/// v19 → v20: effect masks may carry a colour range. Existing masks have none; older builds must
|
||||
/// refuse such projects instead of silently dropping saved colour ranges.
|
||||
fn v19_to_v20(doc: Value) -> Result<Value, String> {
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -340,10 +346,28 @@ mod tests {
|
||||
assert_eq!(file.project["items"]["2"]["kind"], script);
|
||||
assert_eq!(file.project["items"]["1"]["kind"], media);
|
||||
}
|
||||
/// Schema 20 (mask colour ranges): a v19 project upgrades with its data untouched, and a v20
|
||||
/// project with a colour range on a mask is read rather than refused as too new.
|
||||
#[test]
|
||||
fn v19_upgrades_and_v20_mask_colour_ranges_are_read() {
|
||||
let mask = json!({"mode": "add"});
|
||||
let v19 = json!({"format": FORMAT_ID, "schema_version": 19, "project": {"items": {}, "root": {}, "effects": [{"masks": [mask]}]}});
|
||||
let up = migrate_with(MIGRATIONS, v19.clone(), 19).unwrap();
|
||||
assert!(up["schema_version"].as_u64().unwrap() > 19);
|
||||
assert_eq!(up["project"], v19["project"]);
|
||||
let range = json!({"hue": [0.1, 0.2], "luma": [0.0, 0.2]});
|
||||
let mut v20 = up;
|
||||
v20["schema_version"] = json!(20);
|
||||
v20["project"]["effects"][0]["masks"][0]["color"] = range.clone();
|
||||
let bytes = serde_json::to_vec(&v20).unwrap();
|
||||
let (file, version): (EnvelopeIn<Value>, _) = decode(&bytes).unwrap();
|
||||
assert_eq!(version, 20);
|
||||
assert_eq!(file.project["effects"][0]["masks"][0]["color"], range);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_wrong_future_and_damaged_envelopes() {
|
||||
assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_))));
|
||||
assert!(matches!(detect_bytes(br#"{"schema_version":20}"#), Err(FormatError::TooNew { found: 20, supported: 19 })));
|
||||
assert!(matches!(detect_bytes(br#"{"schema_version":21}"#), Err(FormatError::TooNew { found: 21, supported: 20 })));
|
||||
assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 })));
|
||||
assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_))));
|
||||
assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. })));
|
||||
|
||||
@@ -324,6 +324,9 @@ impl Subtags {
|
||||
let base = tag.split(['.', '@']).next().unwrap_or("").replace('_', "-");
|
||||
let mut parts = base.split('-').filter(|p| !p.is_empty());
|
||||
let language = parts.next().unwrap_or("").to_owned();
|
||||
if language.len() == 1 {
|
||||
return Subtags { language, script: None, region: None };
|
||||
}
|
||||
let mut script = match tag.split_once('@').map(|(_, m)| m) {
|
||||
Some("latin") => Some("latn".to_owned()),
|
||||
Some("cyrillic") => Some("cyrl".to_owned()),
|
||||
@@ -331,6 +334,11 @@ impl Subtags {
|
||||
};
|
||||
let mut region = None;
|
||||
for part in parts {
|
||||
// Stop at BCP 47 extension or private-use singletons (`-u-`, `-t-`, `-x-`) so their
|
||||
// subtags are never mistaken for a script or region.
|
||||
if part.len() == 1 {
|
||||
break;
|
||||
}
|
||||
if part.len() == 4 && part.bytes().all(|b| b.is_ascii_alphabetic()) {
|
||||
script.get_or_insert_with(|| part.to_owned());
|
||||
} else if super::is_region(part) {
|
||||
|
||||
@@ -316,3 +316,23 @@ fn plural_forms_follow_cldr_for_every_offered_language() {
|
||||
assert_eq!(found.len(), 1, "{found:?}");
|
||||
assert!(found[0].starts_with("de/common: line 1: expected 2"), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_and_private_use_do_not_set_script_or_region() {
|
||||
use Script::{Guru, Hebr, Latn};
|
||||
for (tag, want, dir) in [
|
||||
("en-u-arab", &[Latn][..], Direction::Ltr),
|
||||
("en-u-nu-arab", &[Latn], Direction::Ltr),
|
||||
("en-t-hebr", &[Latn], Direction::Ltr),
|
||||
("en-x-arab", &[Latn], Direction::Ltr),
|
||||
("x-arab", &[Latn], Direction::Ltr),
|
||||
("x-he-arab", &[Latn], Direction::Ltr),
|
||||
("he-u-latn", &[Hebr], Direction::Rtl),
|
||||
("he-u-nu-latn", &[Hebr], Direction::Rtl),
|
||||
("sr-Latn-u-arab", &[Latn], Direction::Ltr),
|
||||
("pa-u-pk", &[Guru], Direction::Ltr),
|
||||
] {
|
||||
assert_eq!(scripts(tag), want, "{tag}");
|
||||
assert_eq!(direction(tag), dir, "{tag}");
|
||||
}
|
||||
}
|
||||
@@ -49,9 +49,12 @@ pub(crate) fn valid_time(t: NaiveDateTime) -> NaiveDateTime {
|
||||
|
||||
/// A date from `YYYY-MM-DD` or `YYYYMMDD`, years 1 to 9999.
|
||||
fn parse_iso_date(s: &str) -> Option<NaiveDate> {
|
||||
let s = s.trim();
|
||||
let digits: String = s.chars().filter(char::is_ascii_digit).collect();
|
||||
if digits.len() != 8 || s.chars().any(|c| !c.is_ascii_digit() && c != '-') {
|
||||
let digits: String = match s.len() {
|
||||
8 => s.to_string(),
|
||||
10 if s.as_bytes().get(4) == Some(&b'-') && s.as_bytes().get(7) == Some(&b'-') => s.chars().filter(char::is_ascii_digit).collect(),
|
||||
_ => return None,
|
||||
};
|
||||
if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let year: i32 = digits.get(0..4)?.parse().ok()?;
|
||||
@@ -293,6 +296,12 @@ mod tests {
|
||||
"20261312",
|
||||
"20260230",
|
||||
"00000101",
|
||||
"2026-1011",
|
||||
"-20261012",
|
||||
"20-261012",
|
||||
"20261012-",
|
||||
"2026101-2T090000",
|
||||
"20261012 T090000",
|
||||
"20261012T",
|
||||
"20261012T25",
|
||||
"20261012T240000",
|
||||
|
||||
@@ -377,7 +377,20 @@ fn tokenize(s: &str, base: &Fmt, depth: usize, refs: &Refs) -> Vec<Node> {
|
||||
}
|
||||
b'&' => {
|
||||
let rest = s.get(i..).unwrap_or("");
|
||||
match within(rest, 33).find(';').and_then(|k| decode_entity(rest.get(1..k)?).map(|ch| (ch, k))) {
|
||||
match within(rest, 33).find(';').and_then(|k| {
|
||||
let name = rest.get(1..k)?;
|
||||
// CommonMark limits numeric references to seven decimal or six hexadecimal digits.
|
||||
if let Some(num) = name.strip_prefix('#') {
|
||||
let (digits, max) = match num.strip_prefix(['x', 'X']) {
|
||||
Some(hex) => (hex, 6),
|
||||
None => (num, 7),
|
||||
};
|
||||
if digits.len() > max {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
decode_entity(name).map(|ch| (ch, k))
|
||||
}) {
|
||||
Some((ch, k)) => {
|
||||
flush!();
|
||||
push_text(&mut nodes, &ch, base);
|
||||
@@ -415,7 +428,7 @@ fn angle_inlines(s: &str, start: usize, base: &Fmt) -> Option<(usize, Vec<Node>)
|
||||
} else if matches!(lower.trim_end_matches('/').trim(), "br") {
|
||||
push_text(&mut nodes, "\n", base);
|
||||
Some((end, nodes))
|
||||
} else if lower.starts_with("a ") && rest.get(inner.len() + 1..).is_some_and(|tail| tail.to_ascii_lowercase().starts_with("</a>")) {
|
||||
} else if lower.starts_with("a ") && rest.get(inner.len() + 1..).and_then(|tail| tail.get(..4)).is_some_and(|p| p.eq_ignore_ascii_case("</a>")) {
|
||||
if let Some(name) = tag_attr(inner, "id").or_else(|| tag_attr(inner, "name")) {
|
||||
nodes.push(Node::Inl(Inline::Anchor(name)));
|
||||
}
|
||||
|
||||
@@ -21,6 +21,29 @@ fn emphasis() {
|
||||
assert!(matches!(&s[0], Inline::Text(t, f) if t == "gone" && f.strike));
|
||||
}
|
||||
|
||||
/// An empty `<a id>` or `<a name>` is an anchor whatever the case of its `</a>` (wordcraft#3715).
|
||||
#[test]
|
||||
fn empty_html_anchor() {
|
||||
let anchors = |s: &str| inl(s).into_iter().filter_map(|i| if let Inline::Anchor(a) = i { Some(a) } else { None }).collect::<Vec<_>>();
|
||||
assert_eq!(anchors(r#"x <a id="n"></a> y"#), vec!["n"]);
|
||||
assert_eq!(anchors(r#"x <a name="m"></A> y"#), vec!["m"]);
|
||||
assert_eq!(anchors(r#"<A id="p"></a>"#), vec!["p"]);
|
||||
assert!(anchors(r#"<a id="n">text</a>"#).is_empty());
|
||||
assert!(anchors(r#"<a id="n"></"#).is_empty());
|
||||
assert!(anchors(r#"<a id="n"></aé"#).is_empty());
|
||||
}
|
||||
|
||||
/// Every `<a …>` tag lower-cased a copy of the rest of its paragraph to look for `</a>`
|
||||
/// (wordcraft#3715): quadratic on a paragraph of tags.
|
||||
#[test]
|
||||
fn a_paragraph_of_anchor_tags_parses_in_linear_time() {
|
||||
let src = "<a x>".repeat(1_000_000);
|
||||
let t = std::time::Instant::now();
|
||||
inl(&src);
|
||||
// Well under a second now; the per-tag copy took 40 s in a release build.
|
||||
assert!(t.elapsed() < std::time::Duration::from_secs(10), "{:?}", t.elapsed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_code_escapes() {
|
||||
let s = inl("see [the *site*](http://x.org \"T\") and `a*b*` \\*lit\\* & <https://y.com>");
|
||||
@@ -36,6 +59,28 @@ fn links_code_escapes() {
|
||||
assert!(text.contains("*lit* & "), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_references_respect_commonmark_digit_limits() {
|
||||
for (input, expected) in [
|
||||
("�", "�"),
|
||||
("�", "�"),
|
||||
("�", "�"),
|
||||
("�", "�"),
|
||||
("A", "A"),
|
||||
("A", "A"),
|
||||
("A", "A"),
|
||||
("A", "A"),
|
||||
("A", "A"),
|
||||
("�", "\u{FFFD}"),
|
||||
("", "\u{10FFFF}"),
|
||||
("�", "\u{FFFD}"),
|
||||
("�", "\u{FFFD}"),
|
||||
("&", "&"),
|
||||
] {
|
||||
assert_eq!(spans(input), vec![(expected.into(), false, false)], "{input}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference links: `[text][label]`, `[text][]` and `[text]` take their destination from a
|
||||
/// definition line, and the definition itself leaves the document. Before, none of the three
|
||||
/// was a link and the definition stayed as a paragraph of its own (#3238).
|
||||
|
||||
@@ -94,9 +94,22 @@ fn program_stream_with_large_pes_packets_gives_back_every_frame() {
|
||||
assert_eq!(f.streams.len(), 2);
|
||||
for (s, frames) in f.streams.iter().zip([&a, &b]) {
|
||||
assert_eq!(s.units.len(), frames.len());
|
||||
// a read refills a 1 MiB window: every seventh unit and the last ones keep a debug build quick
|
||||
for (i, fr) in frames.iter().enumerate().filter(|(i, _)| i % 7 == 0 || i + 4 > frames.len()) {
|
||||
assert_eq!(&f.read_unit(&data, f.streams.iter().position(|x| std::ptr::eq(x, s)).unwrap(), i).unwrap(), fr, "mpeg1 {mpeg1} unit {i}");
|
||||
// Sparse reads keep the debug build quick; also force PES-boundary and end reads.
|
||||
let mut read_unit = frames.iter().enumerate().map(|(i, _)| i % 7 == 0 || i + 4 > frames.len()).collect::<Vec<_>>();
|
||||
for boundary in (60_000..frames.len() * 576).step_by(60_000) {
|
||||
read_unit[(boundary - 1) / 576] = true;
|
||||
if boundary % 576 == 0 {
|
||||
read_unit[boundary / 576] = true;
|
||||
}
|
||||
}
|
||||
for (i, (fr, should_read)) in frames.iter().zip(read_unit).enumerate() {
|
||||
if should_read {
|
||||
assert_eq!(
|
||||
&f.read_unit(&data, f.streams.iter().position(|x| std::ptr::eq(x, s)).unwrap(), i).unwrap(),
|
||||
fr,
|
||||
"mpeg1 {mpeg1} unit {i}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// cut inside the last packets: never panics, and the units before the cut are intact
|
||||
|
||||
@@ -44,13 +44,13 @@ pub fn parse_mailto(link: &str) -> Option<Mailto> {
|
||||
let mut m = Mailto::default();
|
||||
// Commas separate the addresses before they are decoded: an encoded comma belongs to its address.
|
||||
for address in path.split(',') {
|
||||
add(&mut m.to, &decode(address));
|
||||
add(&mut m.to, &percent_decode(address));
|
||||
}
|
||||
let (mut subject, mut body) = (None, None);
|
||||
for field in query.split('&') {
|
||||
let (name, value) = field.split_once('=').unwrap_or((field, ""));
|
||||
let value = decode(value);
|
||||
match decode(name).to_ascii_lowercase().as_str() {
|
||||
let value = percent_decode(value);
|
||||
match percent_decode(name).to_ascii_lowercase().as_str() {
|
||||
"to" => add_list(&mut m.to, &value),
|
||||
"cc" => add_list(&mut m.cc, &value),
|
||||
"bcc" => add_list(&mut m.bcc, &value),
|
||||
@@ -79,7 +79,7 @@ pub(crate) fn cut(text: &str, max: usize) -> &str {
|
||||
|
||||
/// Percent-decoding. An escape that isn't one stays as it is written, a plus sign is a plus sign
|
||||
/// (RFC 6068 section 5), and bytes that aren't UTF-8 become the replacement character.
|
||||
fn decode(text: &str) -> String {
|
||||
pub(super) fn percent_decode(text: &str) -> String {
|
||||
let bytes = text.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
|
||||
@@ -48,12 +48,14 @@ impl<'a> Resources<'a> {
|
||||
self.by_location.get(&location.to_ascii_lowercase()).copied()
|
||||
}
|
||||
|
||||
/// The part a reference in a page names: `cid:id` by `Content-ID`; anything else by
|
||||
/// `Content-Location`, as written, or resolved against `base`, the page's own location
|
||||
/// ([`resolve_location`]; empty when it has none). Nothing is fetched.
|
||||
/// The part a reference in a page names. A `cid:` URL is percent-decoded before the
|
||||
/// `Content-ID` lookup. Other references use `Content-Location`, as written or resolved
|
||||
/// against `base`, the page's own location ([`resolve_location`]). Nothing is fetched.
|
||||
pub fn find(&self, reference: &str, base: &str) -> Option<&'a Part> {
|
||||
let reference = reference.trim();
|
||||
match reference.get(..4).filter(|s| s.eq_ignore_ascii_case("cid:")).and(reference.get(4..)) {
|
||||
// RFC 2392 percent-decodes the URL, without form-style plus substitution.
|
||||
Some(id) if id.contains('%') => self.by_content_id(&crate::mailto::percent_decode(id)).or_else(|| self.by_content_id(id)),
|
||||
Some(id) => self.by_content_id(id),
|
||||
None => self.by_location(reference).or_else(|| self.by_location(&resolve_location(base, reference))),
|
||||
}
|
||||
@@ -231,6 +233,27 @@ mod tests {
|
||||
assert!(start_part(&m.root).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cid_references_decode_url_escapes_once() {
|
||||
let message = parse(
|
||||
b"Content-Type: multipart/related; boundary=b\n\n\
|
||||
--b\nContent-ID: <part+id@example.test>\n\nplus\n\
|
||||
--b\nContent-ID: <part%2Bid@example.test>\n\npercent\n\
|
||||
--b\nContent-ID: <legacy%41@example.test>\n\nlegacy\n--b--\n",
|
||||
&Limits::default(),
|
||||
);
|
||||
let resources = Resources::of(&message.root);
|
||||
for (reference, expected) in [
|
||||
("cid:part+id@example.test", "part+id@example.test"),
|
||||
("CID:part%2bid%40example.test", "part+id@example.test"),
|
||||
("cid:part%2Bid@example.test", "part+id@example.test"),
|
||||
("cid:part%252Bid@example.test", "part%2Bid@example.test"),
|
||||
("cid:legacy%41@example.test", "legacy%41@example.test"),
|
||||
] {
|
||||
assert_eq!(resources.find(reference, "").and_then(Part::content_id), Some(expected), "{reference}");
|
||||
}
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn any_reference_resolves(base in "[a-c:/?#.]{0,24}", reference in "[a-c:/?#.]{0,24}") {
|
||||
|
||||
@@ -14,7 +14,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
|
||||
| Language | Spelling | Grammar | Hyphenation |
|
||||
|---|---|---|---|
|
||||
| English (en-US, en-CA, en-AU, en-GB and the British-spelling Englishes such as en-NZ) | SCOWL 2026 Hunspell dictionary per English + `en-extra.txt`, dialect policy (`en-variants.txt`); a dictionaries-folder English first; without SCOWL the installed Hunspell English, else the built-in Moby list ([below](#english-is-always-checked)) | yes | Moby list, our patterns, heuristic |
|
||||
| Polish, Portuguese, Italian | the installed Hunspell dictionary | yes | TeX patterns (embedded, or a Language pack) |
|
||||
| Polish, Portuguese (pt-BR; pt-PT and the regions that write like Portugal, such as pt-AO and pt-MZ, read `pt_PT`), Italian | the installed Hunspell dictionary | yes | TeX patterns (embedded, or a Language pack) |
|
||||
| Croatian, Turkish, Russian, Czech, Indonesian, Spanish (es, es-MX, es-419, es-UY) | the installed Hunspell dictionary (Russian also `ru-extra.txt`) | yes | Turkish and Russian rules; English fallback otherwise |
|
||||
| French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) |
|
||||
| German | — | — | TeX patterns (embedded, or a Language pack) |
|
||||
|
||||
@@ -30,8 +30,9 @@ pub enum ProofLang {
|
||||
/// Bulgarian (`bg`, `bg-BG`): hyphenation by the Bulgarian syllable rules ([`crate::bg`]), and
|
||||
/// spelling when a Bulgarian Hunspell dictionary or `bg` pack is found. No grammar rules yet.
|
||||
Bg,
|
||||
/// Portuguese (`pt`, `pt-BR`; `pt-PT` is [`ProofLang::Pack`] `pt-pt`, with its own dictionary
|
||||
/// and these grammar rules and patterns): the installed Hunspell dictionary (VERO and
|
||||
/// Portuguese (`pt`, `pt-BR`; `pt-PT` and the regions that write like Portugal, `pt-AO`,
|
||||
/// `pt-MZ`…, are [`ProofLang::Pack`] `pt-pt`, with its own dictionary and these grammar rules
|
||||
/// and patterns): the installed Hunspell dictionary (VERO and
|
||||
/// friends, when there is one), the Portuguese grammar rules and the Portuguese hyphenation
|
||||
/// patterns.
|
||||
Pt,
|
||||
@@ -122,9 +123,11 @@ impl ProofLang {
|
||||
|
||||
/// The proofing language of a BCP 47 tag (`pl-PL`, `en_GB`, `PL`…). The primary subtag
|
||||
/// counts, and for English and Spanish the region too (`ProofLang::english`,
|
||||
/// `ProofLang::spanish`). No tag (or an empty one) is English, WordCraft's default editing
|
||||
/// language. Any other valid language tag is [`ProofLang::Pack`] with its [`PackLocale`];
|
||||
/// `x-none`, `und`, `zxx`, `mul`, `mis` and malformed tags are [`ProofLang::Other`].
|
||||
/// `ProofLang::spanish`), for Portuguese (Portugal and the regions CLDR gives `pt_PT` as
|
||||
/// parent) and for German (`CH`, `LI`). No tag (or an empty one) is English, WordCraft's
|
||||
/// default editing language. Any other valid language tag is [`ProofLang::Pack`] with its
|
||||
/// [`PackLocale`]; `x-none`, `und`, `zxx`, `mul`, `mis` and malformed tags are
|
||||
/// [`ProofLang::Other`].
|
||||
pub fn from_tag(tag: Option<&str>) -> ProofLang {
|
||||
let Some(tag) = tag.map(str::trim).filter(|t| !t.is_empty()) else { return ProofLang::En };
|
||||
let primary = tag.split(['-', '_', '.', '@']).next().unwrap_or("");
|
||||
@@ -136,7 +139,7 @@ impl ProofLang {
|
||||
ProofLang::Bg
|
||||
} else if primary.eq_ignore_ascii_case("pt") || primary.eq_ignore_ascii_case("por") {
|
||||
// European Portuguese spells differently: its own dictionary (`pt_PT`, a `pt-pt` pack).
|
||||
if region(tag).is_some_and(|r| r.eq_ignore_ascii_case("PT")) {
|
||||
if region(tag).is_some_and(|r| EUROPEAN_PORTUGUESE.iter().any(|e| e.eq_ignore_ascii_case(r))) {
|
||||
PackLocale::new("pt-PT").map_or(ProofLang::Pt, ProofLang::Pack)
|
||||
} else {
|
||||
ProofLang::Pt
|
||||
@@ -408,6 +411,12 @@ pub(crate) fn region(tag: &str) -> Option<&str> {
|
||||
const LATIN_AMERICA: [&str; 22] =
|
||||
["419", "005", "013", "029", "AR", "BO", "CL", "CO", "CR", "CU", "DO", "EC", "GT", "HN", "NI", "PA", "PE", "PR", "PY", "SV", "US", "VE"];
|
||||
|
||||
/// Regions whose Portuguese is Portugal's (the `pt-pt` [`ProofLang::Pack`]): Portugal and the
|
||||
/// regions CLDR gives `pt_PT` as their parent locale: Angola, Cape Verde, Equatorial Guinea,
|
||||
/// Guinea-Bissau, Macao, Mozambique, São Tomé and Príncipe and Timor-Leste, and Portuguese
|
||||
/// written in Switzerland, France and Luxembourg.
|
||||
const EUROPEAN_PORTUGUESE: [&str; 12] = ["PT", "AO", "CH", "CV", "FR", "GQ", "GW", "LU", "MO", "MZ", "ST", "TL"];
|
||||
|
||||
/// Regions whose English uses British spelling ([`ProofLang::EnGb`]; Australia has its own,
|
||||
/// [`ProofLang::EnAu`]): the United Kingdom (and the non-standard `UK`), Ireland, New Zealand, South Africa, India and other
|
||||
/// Commonwealth countries, the Crown dependencies and Europe (`150`).
|
||||
@@ -460,6 +469,23 @@ pub fn normalize_tag(tag: &str) -> Option<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The regions CLDR gives `pt_PT` as parent write like Portugal: they read the `pt-pt` pack,
|
||||
/// however the tag is written; other regions, no region and private use stay Brazilian.
|
||||
#[test]
|
||||
fn european_portuguese_regions_read_the_pt_pt_pack() {
|
||||
let pt_pt = ProofLang::Pack(PackLocale::new("pt-pt").unwrap());
|
||||
for tag in [" pt-PT ", "pt_PT.UTF-8", "por-PT", "pt_PT@euro", "pt-Latn-PT", "pt-AO", "pt_MZ", "PT-cv", "pt-GW", "pt-ST", "pt-TL"] {
|
||||
assert_eq!(ProofLang::from_tag(Some(tag)), pt_pt, "{tag}");
|
||||
}
|
||||
for tag in ["pt-MO", "pt-GQ", "pt-CH", "pt-FR", "pt-LU", "pt_AO.UTF-8"] {
|
||||
assert_eq!(ProofLang::from_tag(Some(tag)), pt_pt, "{tag}");
|
||||
}
|
||||
for tag in ["pt", "pt-BR", "PT_br", "pt-BR.UTF-8", "por", "pt-Latn-BR", "pt-US", "pt-x-ao"] {
|
||||
assert_eq!(ProofLang::from_tag(Some(tag)), ProofLang::Pt, "{tag}");
|
||||
}
|
||||
assert_eq!((pt_pt.built_in(), ProofLang::Pt.built_in()), (ProofLang::Pt, ProofLang::Pt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_normalize() {
|
||||
assert_eq!(normalize_tag("PL-pl").as_deref(), Some("pl-PL"));
|
||||
|
||||
@@ -228,11 +228,13 @@ fn regional_text_reads_its_own_regions_pack() {
|
||||
let (pt_br, pt_pt) = (pack("pt-br"), pack("pt-pt"));
|
||||
packs::reload();
|
||||
assert_eq!(chosen_dictionary(tag("pt-PT"), &system), Some(pt_pt.clone()));
|
||||
assert_eq!(chosen_dictionary(tag("pt-AO"), &system), Some(pt_pt.clone()), "Angola writes like Portugal");
|
||||
assert_eq!(chosen_dictionary(tag("pt-BR"), &system), Some(pt_br.clone()));
|
||||
std::fs::remove_dir_all(pt_br.parent().unwrap()).unwrap();
|
||||
let sys_pt_br = sys("pt_BR");
|
||||
packs::reload();
|
||||
assert_eq!(chosen_dictionary(tag("pt-PT"), &system), Some(pt_pt.clone()));
|
||||
assert_eq!(chosen_dictionary(tag("pt-MZ"), &system), Some(pt_pt.clone()), "never the system's Brazilian one");
|
||||
assert_eq!(chosen_dictionary(tag("pt-BR"), &system), Some(sys_pt_br), "another region's pack after the system's right region");
|
||||
std::fs::remove_dir_all(&packs_dir).unwrap();
|
||||
|
||||
|
||||
@@ -848,7 +848,12 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result<RawIma
|
||||
crop,
|
||||
orientation: Orientation::from_exif(ifd0.u16(t::ORIENTATION).unwrap_or(1)),
|
||||
// (linear YCbCr comes white-balanced: its unit multipliers have no place on the presets' curve)
|
||||
color: ColorData { kelvin_presets: if linear_rgb { None } else { sr2().and_then(sr2_kelvin_presets) }, ..Default::default() },
|
||||
color: ColorData {
|
||||
kelvin_presets: if linear_rgb { None } else { sr2().and_then(sr2_kelvin_presets) },
|
||||
// the white the data was balanced to, for a white balance scale's As Shot (storytold/lightcraft#4078)
|
||||
balanced_with: wb.filter(|_| linear_rgb),
|
||||
..Default::default()
|
||||
},
|
||||
// Sony's linear YCbCr already carries as-shot WB. Applying the CFA gains again
|
||||
// makes a neutral surface magenta. WB edits remain relative to this as-shot RGB.
|
||||
wb_multipliers: if linear_rgb { Some([1.0; 3]) } else { wb },
|
||||
@@ -897,6 +902,9 @@ mod tests {
|
||||
assert!(!full.notices.assumed_cfa);
|
||||
assert_eq!(full.data.len(), 48);
|
||||
assert_eq!(full.wb_multipliers, Some([1.0; 3]));
|
||||
// storytold/lightcraft#4078: the multipliers the data was balanced with are kept for a white balance scale's As Shot
|
||||
assert_eq!(full.color.balanced_with, Some([2.0, 1.0, 2.0]));
|
||||
assert_eq!(header.color.balanced_with, full.color.balanced_with);
|
||||
// the YCbCr data sit 512 above the recorded sensor black level; white moves with it
|
||||
assert_eq!((full.black.mean(), full.white_at(0)), (1024.0, 16895.0));
|
||||
assert_eq!((header.black.mean(), header.white_at(0)), (1024.0, 16895.0));
|
||||
|
||||
@@ -127,6 +127,7 @@ pub(crate) fn color_data(ifd0: &Ifd, raw: &Ifd, order: ByteOrder) -> ColorData {
|
||||
baseline_sharpness: get(t::BASELINE_SHARPNESS).and_then(|v| v.first().copied()).filter(|v| v.is_finite() && *v > 0.0 && *v <= 16.0),
|
||||
profile: profile_look(ifd0, raw, order),
|
||||
kelvin_presets: None,
|
||||
balanced_with: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1017,6 +1017,12 @@ pub struct ColorData {
|
||||
/// matrices a Kelvin scale ([`kelvin`]). Not a DNG tag: the DNG writer does not write it.
|
||||
#[serde(default)]
|
||||
pub kelvin_presets: Option<kelvin::KelvinPresets>,
|
||||
/// The as-shot multipliers (green = 1) the samples were already balanced with. Sony's downsized lossless (M / S)
|
||||
/// ARWs store white-balanced linear YCbCr, so their `wb_multipliers` are unit and the data renders as delivered;
|
||||
/// a white balance scale reads As Shot from these instead (storytold/lightcraft#4078). Not a DNG tag: the DNG
|
||||
/// writer does not write it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub balanced_with: Option<[f32; 3]>,
|
||||
}
|
||||
|
||||
/// Bounded diagnostics for decisions actually made by a raw decoder. An absent optional tag
|
||||
|
||||
@@ -818,5 +818,13 @@ fn special_entries(words: &FindLabels, replacing: bool, wildcards: bool) -> Vec<
|
||||
(true, false) => REPLACE_CODES.iter().collect(),
|
||||
(true, true) => std::iter::once(&FIND_EXPRESSION).chain(REPLACE_CODES.iter()).collect(),
|
||||
};
|
||||
table.into_iter().map(|(name, code)| Entry::new(*code, words.special_item.fill(&[("name", name(words)), ("code", *code)]))).collect()
|
||||
table
|
||||
.into_iter()
|
||||
.map(|(name, code)| {
|
||||
// `&` starts a menu mnemonic, so double any literal ampersands (`^&` -> `^&&`) in the label while keeping
|
||||
// the raw token as the picked value.
|
||||
let label = words.special_item.fill(&[("name", &name(words).replace('&', "&&")), ("code", &code.replace('&', "&&"))]);
|
||||
Entry::new(*code, label)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -162,3 +162,33 @@ fn special_menu_follows_focused_box_on_replace_tab() {
|
||||
assert!(fixture.by_label("Beginning of Word <").is_some(), "tab switch resets Special target to Find what");
|
||||
assert!(fixture.by_label("Find What Expression \\1").is_none());
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn special_menu_shows_and_inserts_literal_caret_ampersand() {
|
||||
let dialog = Rc::new(RefCell::new(FindReplaceDialog::new("", FindTab::Replace).word(true)));
|
||||
let shown = Rc::clone(&dialog);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = shown.borrow_mut().show(ui, &DialogStack::default());
|
||||
});
|
||||
fixture.room(egui::vec2(900.0, 1000.0)).settle();
|
||||
|
||||
press(&mut fixture, "Search Options");
|
||||
let replace_box = fixture
|
||||
.by_role(Role::TEXT_INPUT)
|
||||
.into_iter()
|
||||
.find(|input| fixture.tree().name_of(input.node) == Some("Replace with:"))
|
||||
.expect("Replace with input");
|
||||
fixture.click(&replace_box).settle();
|
||||
press(&mut fixture, "Special");
|
||||
let items: Vec<_> = fixture.by_role(Role::MENU_ITEM);
|
||||
let labels: Vec<_> = items.iter().filter_map(|item| fixture.tree().name_of(item.node).map(str::to_owned)).collect();
|
||||
assert!(labels.iter().any(|label| label == "Find What Text ^&"), "expected literal `^&` in Special menu, got {labels:?}");
|
||||
assert!(!labels.iter().any(|label| label == "Find What Text ^"), "mnemonic stripping dropped `&` from `^&` in {labels:?}");
|
||||
|
||||
let found_text =
|
||||
items.into_iter().find(|item| fixture.tree().name_of(item.node) == Some("Find What Text ^&")).expect("Find What Text ^& menu item");
|
||||
fixture.click(&found_text).settle();
|
||||
let fields = dialog.borrow().json_fields().expect("fields");
|
||||
let inserted = [fields["find"].as_str(), fields["replace"].as_str()];
|
||||
assert!(inserted.contains(&Some("^&")), "expected raw `^&` to be inserted, got {fields:?}");
|
||||
}
|
||||
@@ -222,9 +222,9 @@ pub struct FloatingGroupOutput {
|
||||
/// Whether a move of the group's window is running: set by its `Begin` and `Update` steps, cleared by its `Commit`
|
||||
/// or `Cancel` and by any step of a resize.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Gesture(bool);
|
||||
struct WindowMoving(bool);
|
||||
|
||||
/// The memory slot of [`Gesture`] under the group's id.
|
||||
/// The memory slot of [`WindowMoving`] under the group's id.
|
||||
const GESTURE: &str = "window_gesture";
|
||||
|
||||
impl Outcome for FloatingGroupOutput {
|
||||
@@ -631,7 +631,7 @@ impl Component for FloatingGroup<'_> {
|
||||
// A dock window's band double click collapses or expands its column, as a dock column's bar does.
|
||||
let collapsed = self.column.map(|column| column.collapsed.is_some());
|
||||
let iconic = collapsed.filter(|_| self.chevron || self.toggled).map(|collapsed| !collapsed);
|
||||
let gesture = &mut cx.core.memory.shown::<Gesture>(sub(cx.core.id, GESTURE)).0;
|
||||
let gesture = &mut cx.core.memory.shown::<WindowMoving>(sub(cx.core.id, GESTURE)).0;
|
||||
if let Some(change) = self.placed {
|
||||
*gesture = change.kind == PlacementKind::Move && matches!(change.phase, GesturePhase::Begin | GesturePhase::Update);
|
||||
}
|
||||
|
||||
@@ -146,10 +146,21 @@ pub fn expected_download_url(repo: &str, tag: &str, name: &str) -> Option<String
|
||||
/// `+`. GitHub serves a `+` in a download path the same either way, and links built before
|
||||
/// `%2B` (an older launcher's feed, or a release saved by an older version) write it plainly.
|
||||
/// No other escape is read, so `%2b` or `%2e` still has to match as written.
|
||||
/// For GitHub links, the owner and repository names compare case-insensitively.
|
||||
pub fn same_download_url(url: &str, expected: &str) -> bool {
|
||||
let (url, expected) = github_repository_paths(url, expected).unwrap_or((url, expected));
|
||||
url == expected || url.replace("%2B", "+") == expected.replace("%2B", "+")
|
||||
}
|
||||
|
||||
/// Compare only the GitHub repository identity, keeping the rest of the path exact.
|
||||
fn github_repository_paths<'a>(url: &'a str, expected: &'a str) -> Option<(&'a str, &'a str)> {
|
||||
let (owner, path) = url.strip_prefix("https://github.com/")?.split_once('/')?;
|
||||
let (repo, path) = path.split_once('/')?;
|
||||
let (expected_owner, expected) = expected.strip_prefix("https://github.com/")?.split_once('/')?;
|
||||
let (expected_repo, expected) = expected.split_once('/')?;
|
||||
(owner.eq_ignore_ascii_case(expected_owner) && repo.eq_ignore_ascii_case(expected_repo)).then_some((path, expected))
|
||||
}
|
||||
|
||||
/// Whether `url` is a download that truly belongs to `repo`.
|
||||
///
|
||||
/// A raw `starts_with(prefix)` check is not enough: a value such as
|
||||
@@ -159,6 +170,7 @@ pub fn same_download_url(url: &str, expected: &str) -> bool {
|
||||
/// segments with no traversal (`.`/`..`), no additional slashes, no query or fragment, and no
|
||||
/// backslash or percent-encoded separators that a client could later re-interpret.
|
||||
pub fn download_url_under(url: &str, prefix: &str) -> bool {
|
||||
let (url, prefix) = github_repository_paths(url, prefix).unwrap_or((url, prefix));
|
||||
let Some(rest) = url.strip_prefix(prefix) else { return false };
|
||||
download_suffix_ok(rest)
|
||||
}
|
||||
@@ -234,8 +246,8 @@ pub fn parse_github_release_list(json: &str, repo: &str, allow_prerelease: bool)
|
||||
}
|
||||
|
||||
/// One release object of the GitHub API, with every text capped and only the assets whose name is
|
||||
/// a plain file name and whose link is exactly [`expected_download_url`]. An API error object
|
||||
/// (`message`) becomes its text.
|
||||
/// a plain file name and whose link matches [`expected_download_url`] with a case-insensitive
|
||||
/// GitHub repository identity. An API error object (`message`) becomes its text.
|
||||
fn release_from_value(v: &serde_json::Value, repo: &str) -> Result<Release, String> {
|
||||
if let Some(msg) = v["message"].as_str() {
|
||||
return Err(if msg == "Not Found" { "no releases yet".into() } else { format!("GitHub says: {}", truncate(msg, 200)) });
|
||||
@@ -249,8 +261,13 @@ fn release_from_value(v: &serde_json::Value, repo: &str) -> Result<Release, Stri
|
||||
list.iter()
|
||||
.filter_map(|a| {
|
||||
let name = a["name"].as_str().filter(|n| valid_file_name(n))?.to_string();
|
||||
let url =
|
||||
a["browser_download_url"].as_str().filter(|u| expected_download_url(repo, &tag, &name).as_deref() == Some(*u))?.to_string();
|
||||
let url = a["browser_download_url"].as_str()?;
|
||||
let expected = expected_download_url(repo, &tag, &name)?;
|
||||
let (path, expected_path) = github_repository_paths(url, &expected)?;
|
||||
if path != expected_path {
|
||||
return None;
|
||||
}
|
||||
let url = url.to_string();
|
||||
let sha256 = a["digest"].as_str().and_then(|d| d.strip_prefix("sha256:")).filter(|h| is_hex64(h)).map(str::to_ascii_lowercase);
|
||||
Some(Asset { name, size: a["size"].as_u64().unwrap_or(0), url, sha256 })
|
||||
})
|
||||
@@ -371,6 +388,34 @@ pub(crate) mod tests {
|
||||
|
||||
const REPO: &str = "storytold/photocraft";
|
||||
|
||||
#[trial]
|
||||
fn download_url_under_preserves_exact_non_github_prefixes() {
|
||||
let prefix = "https://example.com/Releases/";
|
||||
assert!(download_url_under("https://example.com/Releases/v1/file.zip", prefix));
|
||||
assert!(!download_url_under("https://example.com/releases/v1/file.zip", prefix));
|
||||
assert!(!download_url_under("https://example.com/Releases/v1/file.zip?query=1", prefix));
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn github_download_matching_ignores_only_repository_case() {
|
||||
let repo = "Storytold/PdfCraft";
|
||||
let tag = "v0.22.0";
|
||||
let name = "PdfCraft.AppImage";
|
||||
let expected = expected_download_url(repo, tag, name).unwrap();
|
||||
let canonical = format!("https://github.com/storytold/pdfcraft/releases/download/{tag}/{name}");
|
||||
assert!(same_download_url(&canonical, &expected));
|
||||
assert!(download_url_under(&canonical, &download_prefix(repo)));
|
||||
assert!(!same_download_url(&canonical.replace(name, "pdfcraft.AppImage"), &expected));
|
||||
assert!(!same_download_url(&canonical.replace("storytold", "elsewhere"), &expected));
|
||||
let json = serde_json::json!({
|
||||
"tag_name": tag,
|
||||
"assets": [{ "name": name, "browser_download_url": canonical }],
|
||||
});
|
||||
let release = parse_github_release(&json.to_string(), repo).unwrap();
|
||||
assert_eq!(release.assets.len(), 1);
|
||||
assert_eq!(release.assets[0].url, canonical);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn repository_prefixed_tags_are_ordered_without_changing_download_links() {
|
||||
let repo = "storytold/artcraft";
|
||||
|
||||
@@ -593,7 +593,8 @@ impl Dxf {
|
||||
}
|
||||
}
|
||||
|
||||
/// `<dxf>`.
|
||||
/// `<dxf>`, its children in the `CT_Dxf` sequence: `font`, `numFmt`, `fill`, `alignment`,
|
||||
/// `border`, `protection`.
|
||||
pub fn to_el(&self) -> El {
|
||||
let mut e = El::new("dxf");
|
||||
if let Some(f) = &self.font {
|
||||
@@ -611,12 +612,12 @@ impl Dxf {
|
||||
if let Some(a) = &self.alignment {
|
||||
e.push(a.to_el());
|
||||
}
|
||||
if let Some(p) = self.protection {
|
||||
e.push(p.to_el());
|
||||
}
|
||||
if let Some(b) = &self.border {
|
||||
e.push(b.to_el());
|
||||
}
|
||||
if let Some(p) = self.protection {
|
||||
e.push(p.to_el());
|
||||
}
|
||||
e
|
||||
}
|
||||
}
|
||||
@@ -798,6 +799,23 @@ mod tests {
|
||||
assert_eq!(styles("<styleSheet/>").palette(), DEFAULT_PALETTE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dxf_children_are_written_in_schema_order() {
|
||||
// Every child CT_Dxf allows (but extLst), in its sequence; the issue's case is border then protection.
|
||||
let s = styles(
|
||||
r#"<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dxfs count="1"><dxf><font><b/></font><numFmt numFmtId="164" formatCode="0.0"/><fill><patternFill><bgColor rgb="FFFFFF00"/></patternFill></fill><alignment horizontal="center"/><border><left style="thin"><color rgb="FF000000"/></left></border><protection locked="0"/></dxf></dxfs></styleSheet>"#,
|
||||
);
|
||||
let written = styles(std::str::from_utf8(&s.to_xml()).unwrap());
|
||||
assert_eq!(written.dxfs, s.dxfs);
|
||||
let root = craft_xml::Options::local().parse(&s.to_xml()).unwrap_or_default();
|
||||
let dxf = root.child("dxfs").and_then(|d| d.child("dxf")).expect("dxf written");
|
||||
let names: Vec<&str> = dxf.elements().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["font", "numFmt", "fill", "alignment", "border", "protection"]);
|
||||
// border and protection alone keep that order too.
|
||||
let pair = Dxf { border: s.dxfs[0].border.clone(), protection: s.dxfs[0].protection, ..Dxf::default() }.to_el();
|
||||
assert_eq!(pair.elements().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["border", "protection"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_font_names_are_cut() {
|
||||
let s = styles(&format!(r#"<styleSheet><fonts><font><name val="{}"/></font></fonts></styleSheet>"#, "é".repeat(300)));
|
||||
|
||||
Reference in new issue
Block a user