mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-15 18:40:39 -06:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
407e0e1fa9 | ||
|
|
dbdec081e2 | ||
|
|
24e40de94f | ||
|
|
44050e9447 | ||
|
|
d217e8272d | ||
|
|
f22b4ed9dd | ||
|
|
75c4b01db3 | ||
|
|
d593a8f99d | ||
|
|
569707e3f0 |
Generated
+27
-11
@@ -937,16 +937,6 @@ name = "craft-fonts-build"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=aa84415bae3b765fef6b7ef42404f66ad1cff9d9#aa84415bae3b765fef6b7ef42404f66ad1cff9d9"
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=1ff72a0445f370cdaba156ecb87013badbb58147#1ff72a0445f370cdaba156ecb87013badbb58147"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-i18n"
|
||||
version = "0.1.0"
|
||||
@@ -1017,6 +1007,17 @@ name = "craft-sheet"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=bb57d422d0bc842cbde430955825553ab7b976f4#bb57d422d0bc842cbde430955825553ab7b976f4"
|
||||
|
||||
[[package]]
|
||||
name = "craft-stream-codecs"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f7e0d7fd5577e102b4634bcbe062e649eb68165f#f7e0d7fd5577e102b4634bcbe062e649eb68165f"
|
||||
dependencies = [
|
||||
"fax",
|
||||
"hayro-ccitt",
|
||||
"hayro-jbig2",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-ui"
|
||||
version = "0.1.0"
|
||||
@@ -2214,7 +2215,6 @@ name = "gridcraft-engine"
|
||||
version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-csv",
|
||||
"craft-gridcraft-format",
|
||||
"gridcraft-calc",
|
||||
"gridcraft-chart",
|
||||
"gridcraft-core",
|
||||
@@ -2295,6 +2295,7 @@ dependencies = [
|
||||
name = "gridcraft-pdf"
|
||||
version = "0.19.1"
|
||||
dependencies = [
|
||||
"craft-stream-codecs",
|
||||
"harfrust",
|
||||
"sha2 0.11.1",
|
||||
"skrifa",
|
||||
@@ -2367,6 +2368,7 @@ dependencies = [
|
||||
"craft-offcrypto",
|
||||
"craft-opc",
|
||||
"craft-xls",
|
||||
"craft-xml",
|
||||
"gridcraft-core",
|
||||
"gridcraft-formula",
|
||||
"gridcraft-functions",
|
||||
@@ -2459,6 +2461,20 @@ dependencies = [
|
||||
"foldhash 0.2.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hayro-ccitt"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
|
||||
|
||||
[[package]]
|
||||
name = "hayro-jbig2"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=f7e0d7fd5577e102b4634bcbe062e649eb68165f#f7e0d7fd5577e102b4634bcbe062e649eb68165f"
|
||||
dependencies = [
|
||||
"hayro-ccitt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
|
||||
+3
-2
@@ -31,6 +31,8 @@ gridcraft-math = { path = "crates/math" }
|
||||
# craft-libs revision.
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "=0.1.0", features = ["egui"] }
|
||||
# PDF RunLength encoding; this revision also fixes the vendored JBIG2 dependency for Git consumers.
|
||||
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "f7e0d7fd5577e102b4634bcbe062e649eb68165f", version = "0.1.0" }
|
||||
# Compound files ([MS-CFB]) and password-encrypted OOXML packages ([MS-OFFCRYPTO]).
|
||||
craft-cfb = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-offcrypto = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
@@ -39,9 +41,8 @@ craft-opc = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0
|
||||
# Delimited text (CSV, TSV) and SYLK; `crates/xlsx/src/csv.rs` and `crates/engine/src/io/sylk.rs`
|
||||
# turn them into workbooks.
|
||||
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
# The native JSON workbook (`.json`, `.scjson`): read, written, and kept newer macros written back.
|
||||
craft-gridcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "1ff72a0445f370cdaba156ecb87013badbb58147", version = "0.1.0" }
|
||||
# Excel 97-2003 (.xls, BIFF8) workbooks; `crates/xlsx/src/xls.rs` maps them onto the model.
|
||||
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "bb57d422d0bc842cbde430955825553ab7b976f4", version = "0.1.0" }
|
||||
|
||||
# foundation
|
||||
|
||||
@@ -22,7 +22,6 @@ thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
gridcraft-xlsx = { workspace = true }
|
||||
craft-csv = { workspace = true }
|
||||
craft-gridcraft-format = { workspace = true }
|
||||
gridcraft-chart = { workspace = true }
|
||||
gridcraft-pdf = { workspace = true }
|
||||
gridcraft-math = { workspace = true }
|
||||
|
||||
+21
-1586
File diff suppressed because it is too large
Load Diff
@@ -1,17 +1,38 @@
|
||||
use super::{
|
||||
Anchor, CellRef, Chart, ChartKind, EngineError, Json, LegendPos, RangeRef, Result, Series, Session, Sheet, anchor_mode_param, bad, block,
|
||||
bool_param, cell_param_on, edit, f64_param, json, split_sheet, str_param, target_ranges, target_sheet, u32_param,
|
||||
Anchor, CellRef, Chart, ChartKind, EngineError, Json, LegendPos, MAX_COLS, MAX_ROWS, RangeRef, Result, Series, Session, Sheet, anchor_mode_param,
|
||||
bad, block, bool_param, cell_param_on, edit, f64_param, json, size_cap, split_sheet, str_param, target_ranges, target_sheet, u32_param,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compiled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn chart_areas(s: &Session, p: &Json) -> Result<Vec<RangeRef>> {
|
||||
if p.get("range").is_some() {
|
||||
return target_ranges(s, p);
|
||||
let mut areas = if p.get("range").is_some() {
|
||||
target_ranges(s, p)?
|
||||
} else if s.doc()?.selection.ranges.len() > 1 {
|
||||
s.doc()?.selection.ranges.clone()
|
||||
} else {
|
||||
vec![block(s, p)?]
|
||||
};
|
||||
// Whole columns/rows span a million cells: clip their far edges to the cells in use, so only
|
||||
// a block that really is too large gets refused. Bounded areas keep their extent as given.
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if let Some(used) = s.doc()?.wb.sheet(sheet).and_then(|sh| sh.used_range()) {
|
||||
// Areas that start outside the used range keep their extent as given.
|
||||
for r in &mut areas {
|
||||
let whole_cols = r.start.row == 0 && r.end.row >= MAX_ROWS - 1;
|
||||
let whole_rows = r.start.col == 0 && r.end.col >= MAX_COLS - 1;
|
||||
if whole_cols && r.start.row <= used.end.row {
|
||||
r.end.row = r.end.row.min(used.end.row);
|
||||
}
|
||||
if whole_rows && r.start.col <= used.end.col {
|
||||
r.end.col = r.end.col.min(used.end.col);
|
||||
}
|
||||
}
|
||||
}
|
||||
let d = s.doc()?;
|
||||
if d.selection.ranges.len() > 1 {
|
||||
return Ok(d.selection.ranges.clone());
|
||||
}
|
||||
Ok(vec![block(s, p)?])
|
||||
Ok(areas)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- charts
|
||||
@@ -263,6 +284,8 @@ pub fn build_chart(s: &Session, p: &Json) -> Result<(usize, Chart)> {
|
||||
data_table: None,
|
||||
gridlines: !matches!(kind, ChartKind::Pie | ChartKind::Doughnut | ChartKind::Treemap | ChartKind::Sunburst | ChartKind::Funnel),
|
||||
style: 1,
|
||||
hole_size: 75,
|
||||
first_slice_angle: 0,
|
||||
x_title: None,
|
||||
y_title: None,
|
||||
source: (areas.len() == 1).then(|| format!("{}!{}", gridcraft_formula::quote_sheet(&sh.name), bounds.a1())),
|
||||
@@ -308,7 +331,11 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let Some(c) = sh.charts.get_mut(ci) else { return Ok(Json::Null) };
|
||||
if let Some(t) = str_param(p, "type") {
|
||||
c.kind = chart_kind(t, str_param(p, "subtype").unwrap_or(""));
|
||||
if !c.supports_data_table() {
|
||||
c.data_table = None;
|
||||
}
|
||||
}
|
||||
update_data_table(c, p, bool_param(p, "dataTable"))?;
|
||||
if let Some(method) = quartiles {
|
||||
for series in &mut c.series {
|
||||
series.quartiles = method;
|
||||
@@ -335,6 +362,12 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
if let Some(v) = u32_param(p, "style") {
|
||||
c.style = v.clamp(1, 16);
|
||||
}
|
||||
if let Some(v) = u32_param(p, "holeSize") {
|
||||
c.hole_size = v.clamp(10, 90) as u8;
|
||||
}
|
||||
if let Some(v) = u32_param(p, "firstSliceAngle") {
|
||||
c.first_slice_angle = (v % 360) as u16;
|
||||
}
|
||||
if let Some(t) = p.get("xTitle") {
|
||||
c.x_title = t.as_str().map(str::to_string);
|
||||
}
|
||||
@@ -345,10 +378,10 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
c.anchor.cell = at;
|
||||
}
|
||||
if let Some(w) = f64_param(p, "width") {
|
||||
c.anchor.width = w.clamp(20.0, 10000.0) as f32;
|
||||
c.anchor.width = w.clamp(20.0, size_cap(c.anchor.width)) as f32;
|
||||
}
|
||||
if let Some(h) = f64_param(p, "height") {
|
||||
c.anchor.height = h.clamp(20.0, 10000.0) as f32;
|
||||
c.anchor.height = h.clamp(20.0, size_cap(c.anchor.height)) as f32;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "dx") {
|
||||
c.anchor.dx = v as f32;
|
||||
@@ -360,6 +393,32 @@ pub(super) fn chart_set(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Shared by Chart Properties and Add Chart Element; no separate UI state.
|
||||
pub(crate) fn update_data_table(c: &mut Chart, p: &Json, on: Option<bool>) -> Result<()> {
|
||||
if p.get("dataTable").is_some_and(|v| !v.is_boolean()) {
|
||||
return Err(bad("chart", "`dataTable` must be a boolean"));
|
||||
}
|
||||
if on == Some(false) {
|
||||
c.data_table = None;
|
||||
return Ok(());
|
||||
}
|
||||
let fields = ["dataTableKeys", "dataTableHorizontalBorder", "dataTableVerticalBorder", "dataTableOutline"];
|
||||
if on == Some(true) || fields.iter().any(|k| p.get(k).is_some()) {
|
||||
if !c.supports_data_table() {
|
||||
return Err(bad("chart", "data tables need a column, bar, line, area or compatible combo chart"));
|
||||
}
|
||||
let table = c.data_table.get_or_insert_with(Default::default);
|
||||
for (key, value) in
|
||||
fields.into_iter().zip([&mut table.show_keys, &mut table.horizontal_border, &mut table.vertical_border, &mut table.outline])
|
||||
{
|
||||
if let Some(v) = p.get(key) {
|
||||
*value = v.as_bool().ok_or_else(|| bad("chart", format!("`{key}` must be a boolean")))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn chart_switch(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let (si, ci) = find_chart(s, p)?;
|
||||
edit(s, |cx| {
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
use super::{
|
||||
Anchor, BorderLine, BorderStyle, Borders, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, Result, Session, Shape,
|
||||
ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges, target_sheet, u32_param,
|
||||
Anchor, BorderLine, BorderStyle, Borders, CellRef, CfOperator, CfRule, CfValueKind, Color, CondFormat, EngineError, Fill, Json, RangeRef, Result,
|
||||
Session, Shape, ShapeKind, Style, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, ok, str_param, target_ranges,
|
||||
target_sheet, u32_param,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compiled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- conditional formatting
|
||||
|
||||
fn preset_style(name: &str) -> Style {
|
||||
@@ -271,7 +277,13 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
sh.cond_formats.clear();
|
||||
} else {
|
||||
for cf in sh.cond_formats.iter_mut() {
|
||||
let before = RangeRef::top_left(&cf.ranges);
|
||||
cf.ranges.retain(|r| !ranges.iter().any(|x| x.intersects(r)));
|
||||
// The relative formulas are written for the top-left cell: when it goes, they're
|
||||
// rewritten for the new one, so the areas left keep reading the same cells.
|
||||
if let (Some(from), Some(to)) = (before, RangeRef::top_left(&cf.ranges)) {
|
||||
rebase_cf_formulas(&mut cf.rule, from, to);
|
||||
}
|
||||
}
|
||||
sh.cond_formats.retain(|c| !c.ranges.is_empty());
|
||||
}
|
||||
@@ -279,6 +291,19 @@ pub(super) fn clear_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the relative references of a rule's per-cell formulas written for `from` to `to`.
|
||||
fn rebase_cf_formulas(rule: &mut CfRule, from: CellRef, to: CellRef) {
|
||||
let mv = |f: &str| crate::cmd::data::move_rule_formula(f, from, to);
|
||||
match rule {
|
||||
CfRule::CellIs { a, b, .. } => {
|
||||
*a = mv(a);
|
||||
*b = b.as_deref().map(mv);
|
||||
}
|
||||
CfRule::Expression { formula, .. } => *formula = mv(formula),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn manage_cf(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = target_sheet(s, p)?;
|
||||
if p.get("delete").is_none() && p.get("moveUp").is_none() && p.get("moveDown").is_none() {
|
||||
|
||||
@@ -3,6 +3,11 @@ use super::{
|
||||
split_sheet, str_param, target_ranges, target_sheet,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compiled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- links & comments
|
||||
|
||||
pub(super) fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
@@ -27,8 +32,10 @@ pub(super) fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
st.font.underline = Underline::Single;
|
||||
});
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
if let Some(t) = text.clone().or_else(|| sh.value(at).is_empty().then(|| target.clone())) {
|
||||
sh.set_cell(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style });
|
||||
if let Some(t) = text.clone().or_else(|| {
|
||||
(sh.spill_anchor(at).is_none() && sh.value(at).is_empty() && sh.cell(at).is_none_or(|cell| !cell.has_content())).then(|| target.clone())
|
||||
}) {
|
||||
sh.set_cell(at, Cell { value: gridcraft_core::Value::text(t.as_str()), formula: None, style: link_style, py: None });
|
||||
} else {
|
||||
sh.set_style(at, link_style);
|
||||
}
|
||||
@@ -38,9 +45,11 @@ pub(super) fn insert_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows a link: a reference selects it, an `http`/`https`/`mailto` address is handed to the
|
||||
/// host (`UiRequest::OpenUrl`); anything else is refused ([`crate::links::classify`]). Opens no
|
||||
/// dialog; the interactive click asks for confirmation first, in the UI.
|
||||
/// Follows a link: a reference selects it; anything else is refused ([`crate::links::classify`]).
|
||||
/// An `http`/`https`/`mailto` address is refused too unless the host set
|
||||
/// [`crate::links::LinkPolicy::Allow`]: every caller of a command may be a script or an agent, so
|
||||
/// the user opens such links by clicking and confirming, and the UI then calls
|
||||
/// [`Session::open_confirmed_link`] (#2181). Opens no dialog.
|
||||
pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let target = match str_param(p, "url").or_else(|| str_param(p, "target")) {
|
||||
Some(t) => t.to_string(),
|
||||
@@ -56,6 +65,9 @@ pub(super) fn open_link(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
match crate::links::classify(&target) {
|
||||
crate::links::LinkKind::Internal(r) => crate::cmd::edit::go_to(s, &json!({"reference": r.trim_start_matches('#')})),
|
||||
crate::links::LinkKind::External(u) => {
|
||||
if s.link_policy != crate::links::LinkPolicy::Allow {
|
||||
return Err(EngineError::Other(crate::links::NEEDS_CONFIRMATION.into()));
|
||||
}
|
||||
s.ui_requests.push(crate::UiRequest::OpenUrl(u.clone()));
|
||||
Ok(json!({"opened": u}))
|
||||
}
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
use super::{
|
||||
Anchor, CellPicture, CellRef, Color, EngineError, Image, Json, PROTECTED, Result, Session, Shape, ShapeKind, Sparkline, SparklineKind,
|
||||
anchor_mode_name, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, locked_cell_error, ok, str_param, u32_param,
|
||||
Anchor, CellPicture, CellRef, Color, EngineError, Image, Json, MAX_OBJECT_OFFSET, ObjKind, ObjRef, PROTECTED, Result, Session, Shape, ShapeKind,
|
||||
Sparkline, SparklineKind, anchor_mode_name, anchor_mode_param, bad, bool_param, cell_param, edit, f64_param, json, locked_cell_error, ok,
|
||||
size_cap, str_param, u32_param,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compiled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn insert_sparkline(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let src = str_param(p, "range").ok_or_else(|| bad("insert.sparkline", "missing `range`"))?.to_string();
|
||||
let loc = cell_param(s, p, "location")?.ok_or_else(|| bad("insert.sparkline", "missing `location`"))?;
|
||||
@@ -63,6 +69,10 @@ pub(super) fn insert_picture(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
.unwrap_or_else(|| if data.starts_with(&[0x89, b'P', b'N', b'G']) { "image/png".into() } else { "image/jpeg".into() });
|
||||
let (w, h) = crate::io::image_size(&data).unwrap_or((320, 240));
|
||||
let d = s.doc()?;
|
||||
// Sheet protection locks drawing objects, as for a text box's text.
|
||||
if d.wb.active().is_some_and(|sh| sh.is_protected()) {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
}
|
||||
let id = d.wb.next_object_id();
|
||||
let at = cell_param(s, p, "at")?.unwrap_or(d.selection.active);
|
||||
let scale = (640.0 / w.max(1) as f32).min(1.0);
|
||||
@@ -176,9 +186,15 @@ pub(super) fn shape_set_text(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sheet = d.wb.active_sheet();
|
||||
let sh = d.wb.active().ok_or_else(|| bad("shape.setText", "no such text box"))?;
|
||||
let shape = sh.shapes.iter().find(|shape| shape.id == id).ok_or_else(|| bad("shape.setText", "no such text box"))?;
|
||||
if shape.kind != ShapeKind::TextBox {
|
||||
if !matches!(shape.kind, ShapeKind::TextBox | ShapeKind::WordArt) {
|
||||
return Err(bad("shape.setText", "the shape is not a text box"));
|
||||
}
|
||||
if shape.kind == ShapeKind::WordArt && text.is_empty() {
|
||||
return Err(bad("shape.setText", "WordArt text must not be empty"));
|
||||
}
|
||||
if shape.kind == ShapeKind::WordArt && text.chars().nth(crate::cmd::wordart::MAX_CHARS).is_some() {
|
||||
return Err(bad("shape.setText", format!("`text` is longer than {} characters", crate::cmd::wordart::MAX_CHARS)));
|
||||
}
|
||||
// Sheet protection locks drawing objects (there is no "edit objects" allowance yet).
|
||||
if sh.is_protected() {
|
||||
return Err(EngineError::Other(PROTECTED.into()));
|
||||
@@ -193,51 +209,50 @@ pub(super) fn shape_set_text(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The floating object a `{kind, id}` command names on the active sheet. Unknown kinds and
|
||||
/// objects are errors, so a stale id never succeeds silently.
|
||||
fn object_param(s: &Session, p: &Json, cmd: &str) -> Result<(usize, ObjRef)> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let kind =
|
||||
str_param(p, "kind").and_then(ObjKind::parse).ok_or_else(|| bad(cmd, "kind must be chart, image, shape, slicer, equation or control"))?;
|
||||
let d = s.doc()?;
|
||||
let sheet = d.wb.active_sheet();
|
||||
let o = ObjRef::new(kind, id);
|
||||
if !d.wb.sheet(sheet).is_some_and(|sh| sh.has_object(o)) {
|
||||
return Err(bad(cmd, "no such object"));
|
||||
}
|
||||
// A locked form control on a protected sheet stays as it is.
|
||||
crate::cmd::controls::check_objects_unlocked(s, sheet, kind, &[id])?;
|
||||
Ok((sheet, o))
|
||||
}
|
||||
|
||||
pub(super) fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.delete", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let (sheet, o) = object_param(s, p, "object.delete")?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
match kind.as_str() {
|
||||
"chart" => sh.charts.retain(|c| c.id != id),
|
||||
"image" => sh.images.retain(|c| c.id != id),
|
||||
"slicer" => sh.slicers.retain(|c| c.id != id),
|
||||
_ => sh.shapes.retain(|c| c.id != id),
|
||||
}
|
||||
Ok(Json::Null)
|
||||
cx.sheet_mut(sheet)?.remove_object(o);
|
||||
Ok(json!({"deleted": o}))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.move", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
let (sheet, o) = object_param(s, p, "object.move")?;
|
||||
let at = cell_param(s, p, "at")?;
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let anchor = match kind.as_str() {
|
||||
"chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"slicer" => sh.slicers.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"shape" => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
_ => None,
|
||||
};
|
||||
let Some(a) = anchor else { return Err(bad("object.move", "no such object")) };
|
||||
let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.move", "no such object")) };
|
||||
if let Some(at) = at {
|
||||
a.cell = at;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "dx") {
|
||||
a.dx = v as f32;
|
||||
a.dx = v.clamp(-MAX_OBJECT_OFFSET, MAX_OBJECT_OFFSET) as f32;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "dy") {
|
||||
a.dy = v as f32;
|
||||
a.dy = v.clamp(-MAX_OBJECT_OFFSET, MAX_OBJECT_OFFSET) as f32;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "width") {
|
||||
a.width = v.clamp(1.0, 10000.0) as f32;
|
||||
a.width = v.clamp(1.0, size_cap(a.width)) as f32;
|
||||
}
|
||||
if let Some(v) = f64_param(p, "height") {
|
||||
a.height = v.clamp(0.0, 10000.0) as f32;
|
||||
a.height = v.clamp(0.0, size_cap(a.height)) as f32;
|
||||
}
|
||||
Ok(Json::Null)
|
||||
})
|
||||
@@ -247,21 +262,10 @@ pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
/// cells" / "Don't move or size with cells"), so it follows — or ignores — its rows and columns
|
||||
/// when the sheet is sorted or edited structurally.
|
||||
pub(super) fn set_anchor_mode(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let id = u32_param(p, "id").ok_or_else(|| bad("object.setAnchorMode", "missing `id`"))?;
|
||||
let kind = str_param(p, "kind").unwrap_or("").to_string();
|
||||
if !matches!(kind.as_str(), "chart" | "image" | "shape") {
|
||||
return Err(bad("object.setAnchorMode", "kind must be chart, image or shape"));
|
||||
}
|
||||
let (sheet, o) = object_param(s, p, "object.setAnchorMode")?;
|
||||
let mode = anchor_mode_param(p).ok_or_else(|| bad("object.setAnchorMode", "mode must be moveAndSize, moveOnly or absolute"))?;
|
||||
let sheet = s.doc()?.wb.active_sheet();
|
||||
edit(s, |cx| {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
let anchor = match kind.as_str() {
|
||||
"chart" => sh.charts.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
"image" => sh.images.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
_ => sh.shapes.iter_mut().find(|c| c.id == id).map(|c| &mut c.anchor),
|
||||
};
|
||||
let Some(a) = anchor else { return Err(bad("object.setAnchorMode", "no such object")) };
|
||||
let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.setAnchorMode", "no such object")) };
|
||||
a.mode = mode;
|
||||
Ok(json!({"mode": anchor_mode_name(mode)}))
|
||||
})
|
||||
|
||||
@@ -3,6 +3,11 @@ use super::{
|
||||
block, bool_param, edit, json, rewrite, shift_cell_features, str_param, target_range, target_sheet, with,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compiled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tables
|
||||
|
||||
pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
@@ -51,7 +56,7 @@ pub(super) fn insert_table(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
let sh = cx.sheet_mut(sheet)?;
|
||||
// The header row pushes the data down one row: never off the end of the sheet.
|
||||
let last = RangeRef::new(CellRef::new(MAX_ROWS - 1, r.start.col), CellRef::new(MAX_ROWS - 1, r.end.col));
|
||||
if sh.cells.iter_range(last).any(|(_, x)| x.formula.is_some() || !x.value.is_empty()) {
|
||||
if sh.cells.iter_range(last).any(|(_, x)| x.has_content()) {
|
||||
return Err(EngineError::Other("To prevent possible loss of data, cells can't be pushed off the end of the worksheet.".into()));
|
||||
}
|
||||
sh.cells.shift_rows_in_cols(r.start.col, r.end.col, r.start.row, 1);
|
||||
@@ -211,7 +216,10 @@ fn write_totals(sh: &mut Sheet, ti: usize) {
|
||||
let c = CellRef::new(row, t.range.start.col + i as u32);
|
||||
if let Some(code) = col.totals.subtotal_code() {
|
||||
let f = format!("=SUBTOTAL({code},{}[{}])", t.name, col.name);
|
||||
sh.set_cell(c, Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c) });
|
||||
sh.set_cell(
|
||||
c,
|
||||
Cell { formula: Some(std::sync::Arc::new(Formula::new(&f))), value: gridcraft_core::Value::Empty, style: sh.style_id(c), py: None },
|
||||
);
|
||||
} else if let Some(l) = &col.totals_label {
|
||||
sh.set_value(c, gridcraft_core::Value::text(l.as_str()));
|
||||
} else {
|
||||
|
||||
@@ -42,7 +42,7 @@ impl FileKind {
|
||||
"ods" => FileKind::Ods,
|
||||
"csv" => FileKind::Csv,
|
||||
"tsv" | "tab" | "txt" => FileKind::Tsv,
|
||||
ext if craft_gridcraft_format::is_extension(ext) => FileKind::Json,
|
||||
"json" | "scjson" => FileKind::Json,
|
||||
"html" | "htm" => FileKind::Html,
|
||||
"slk" => FileKind::Sylk,
|
||||
_ => return None,
|
||||
@@ -316,7 +316,7 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
|
||||
}
|
||||
match kind {
|
||||
Some(FileKind::Json) => {
|
||||
let mut wb: Workbook = craft_gridcraft_format::read(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let mut wb: Workbook = serde_json::from_slice(bytes).map_err(|e| EngineError::Other(format!("not a GridCraft JSON workbook: {e}")))?;
|
||||
wb.styles.rebuild_index();
|
||||
if wb.sheets.is_empty() {
|
||||
// The file's macros are read after this (`macros::load`), so they come along.
|
||||
|
||||
@@ -213,7 +213,17 @@ pub fn json_bytes(wb: &Workbook) -> crate::Result<Vec<u8>> {
|
||||
for m in &wb.macros {
|
||||
check(m).map_err(crate::EngineError::Other)?;
|
||||
}
|
||||
craft_gridcraft_format::write_with_kept(wb, "macros", &wb.macros_unread).map_err(|e| crate::EngineError::Other(e.to_string()))
|
||||
let bytes = if wb.macros_unread.is_empty() {
|
||||
serde_json::to_vec_pretty(wb)
|
||||
} else {
|
||||
serde_json::to_value(wb).and_then(|mut v| {
|
||||
if let Some(list) = v.as_object_mut().map(|o| o.entry("macros").or_insert_with(|| Json::Array(vec![]))).and_then(Json::as_array_mut) {
|
||||
list.extend(wb.macros_unread.iter().cloned());
|
||||
}
|
||||
serde_json::to_vec_pretty(&v)
|
||||
})
|
||||
};
|
||||
bytes.map_err(|e| crate::EngineError::Other(e.to_string()))
|
||||
}
|
||||
|
||||
/// Whether `v` is a macro in a newer format than this build reads.
|
||||
|
||||
@@ -2401,6 +2401,35 @@ fn merging_over_a_spill_blocks_it_and_unmerging_unblocks_it() {
|
||||
assert_eq!(v(&s, "A3"), Value::Number(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_a_link_without_text_preserves_a_spill_child() {
|
||||
let mut s = s();
|
||||
s.execute("cell.set", json!({"cell": "A1", "input": "=SEQUENCE(3)"})).unwrap();
|
||||
assert_eq!(v(&s, "A2"), Value::Number(2.0));
|
||||
s.execute("insert.link", json!({"cell": "A2", "target": "https://example.org"})).unwrap();
|
||||
assert_eq!(v(&s, "A1"), Value::Number(1.0));
|
||||
assert_eq!(v(&s, "A2"), Value::Number(2.0));
|
||||
let d = s.doc().unwrap();
|
||||
let at = CellRef::parse("A2").unwrap();
|
||||
assert_eq!(d.wb.active().unwrap().hyperlinks.get(&at).map(|link| link.target.as_str()), Some("https://example.org"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_a_link_without_text_preserves_an_empty_spill_child() {
|
||||
let mut s = s();
|
||||
s.execute("range.setValues", json!({"range": "A1:C3", "values": [["a", "x", 1], ["b", "x", 2], ["a", "y", 3]]})).unwrap();
|
||||
s.execute("cell.set", json!({"cell": "K1", "input": "=PIVOTBY(A1:A3,B1:B3,C1:C3,LAMBDA(x,SUM(x)))"})).unwrap();
|
||||
assert_eq!(v(&s, "K1"), Value::Empty);
|
||||
let at = CellRef::parse("M3").unwrap();
|
||||
assert_eq!(v(&s, "M3"), Value::Empty);
|
||||
assert_eq!(s.doc().unwrap().wb.active().unwrap().spill_anchor(at), Some(CellRef::parse("K1").unwrap()));
|
||||
s.execute("insert.link", json!({"cell": "M3", "target": "https://example.org"})).unwrap();
|
||||
assert_eq!(v(&s, "K1"), Value::Empty);
|
||||
assert_eq!(v(&s, "M3"), Value::Empty);
|
||||
let d = s.doc().unwrap();
|
||||
assert_eq!(d.wb.active().unwrap().hyperlinks.get(&at).map(|link| link.target.as_str()), Some("https://example.org"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_cell_array_formulas_and_tables_dont_overlap() {
|
||||
// Found by the command-sequence fuzzer: an array over a table header lost its value to the
|
||||
@@ -6494,7 +6523,6 @@ fn a_script_cannot_switch_windows() {
|
||||
|
||||
mod controls;
|
||||
mod equation;
|
||||
mod json_golden;
|
||||
mod macros;
|
||||
mod objects;
|
||||
mod python_cells;
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
//! Byte-for-byte checks on the native JSON workbook (`.json`, `.scjson`). The files in
|
||||
//! `crates/engine/tests/golden` were written before the format moved to `craft-gridcraft-format`
|
||||
//! (storytold/craft-libs). Saving the same workbook must give the same bytes, and opening a
|
||||
//! golden file and saving it again must give it back.
|
||||
//! `GRIDCRAFT_BLESS_GOLDEN=1` rewrites them. Only do that for a deliberate format change.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::s;
|
||||
use crate::Session;
|
||||
|
||||
fn golden(name: &str) -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests").join("golden").join(name)
|
||||
}
|
||||
|
||||
fn check(name: &str, actual: &[u8]) {
|
||||
let path = golden(name);
|
||||
if std::env::var_os("GRIDCRAFT_BLESS_GOLDEN").is_some() {
|
||||
std::fs::write(&path, actual).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
return;
|
||||
}
|
||||
let expected = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
assert!(expected == actual, "{name} changed ({} bytes, golden has {})", actual.len(), expected.len());
|
||||
}
|
||||
|
||||
fn save(s: &mut Session) -> Vec<u8> {
|
||||
let r = s.execute("file.saveBytes", json!({"format": "json"})).unwrap();
|
||||
crate::io::base64_decode(r["base64"].as_str().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn open(s: &mut Session, name: &str, bytes: &[u8]) {
|
||||
s.execute("file.open", json!({"name": name, "base64": crate::io::base64_encode(bytes)})).unwrap();
|
||||
}
|
||||
|
||||
/// A workbook with text, numbers, a formula, a style, a number format, a second sheet and a macro.
|
||||
fn book() -> Session {
|
||||
let mut s = s();
|
||||
for (cell, input) in [("A1", "Item"), ("B1", "Qty"), ("A2", "Äpfel ✓"), ("B2", "3.5"), ("A3", "Pears"), ("B3", "2"), ("B4", "=SUM(B2:B3)")] {
|
||||
s.execute("cell.set", json!({"cell": cell, "input": input})).unwrap();
|
||||
}
|
||||
s.execute("home.bold", json!({"range": "A1:B1"})).unwrap();
|
||||
s.execute("home.numberFormat", json!({"range": "B2:B4", "format": "0.00"})).unwrap();
|
||||
s.execute("macro.save", json!({"name": "Fill", "steps": [{"command": "cell.set", "params": {"cell": "C1", "input": "x"}}]})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_writes_the_golden_workbook_bytes() {
|
||||
let mut s = book();
|
||||
check("book.json", &save(&mut s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_golden_workbook_opens_and_saves_back_unchanged() {
|
||||
let bytes = std::fs::read(golden("book.json")).unwrap();
|
||||
for name in ["book.json", "book.scjson"] {
|
||||
let mut s = s();
|
||||
open(&mut s, name, &bytes);
|
||||
assert_eq!(super::v(&s, "B4"), gridcraft_core::Value::Number(5.5), "{name}");
|
||||
assert!(save(&mut s) == bytes, "{name} saved back differently");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macros_in_a_newer_format_are_written_back_as_the_file_held_them() {
|
||||
// The save that splices kept macros back into `macros` goes through a JSON value.
|
||||
let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(golden("book.json")).unwrap()).unwrap();
|
||||
v["macros"].as_array_mut().unwrap().push(json!({"name": "Future", "v": gridcraft_model::MACRO_VERSION + 1, "extra": [1, 2]}));
|
||||
let mut s = s();
|
||||
open(&mut s, "kept.json", &serde_json::to_vec_pretty(&v).unwrap());
|
||||
check("kept.json", &save(&mut s));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_json_workbook_says_so() {
|
||||
let err = crate::io::open_bytes("bad.json", b"{\"sheets\": 7}").unwrap_err().to_string();
|
||||
check("bad.error.txt", err.as_bytes());
|
||||
}
|
||||
@@ -530,3 +530,16 @@ fn python_code_with_an_empty_value_counts_as_content() {
|
||||
s.execute("edit.copy", json!({"range": "T1"})).unwrap();
|
||||
assert!(s.execute("edit.paste", json!({"at": "R2"})).is_err_and(|e| e.to_string().contains("part of an array")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_a_link_without_text_preserves_an_empty_python_cell() {
|
||||
let mut s = s();
|
||||
plant_empty(&mut s, "A1");
|
||||
s.execute("insert.link", json!({"cell": "A1", "target": "https://example.org"})).unwrap();
|
||||
assert_eq!(code(&s, 0, "A1"), Some("x = 1".into()));
|
||||
let d = s.doc().unwrap();
|
||||
let sh = d.wb.sheet(0).unwrap();
|
||||
let at = CellRef::parse("A1").unwrap();
|
||||
assert_eq!(sh.value(at), Value::Empty);
|
||||
assert_eq!(sh.hyperlinks.get(&at).map(|link| link.target.as_str()), Some("https://example.org"));
|
||||
}
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
# Golden files are compared byte for byte: no line-ending conversion on checkout.
|
||||
* -text
|
||||
@@ -1 +0,0 @@
|
||||
not a GridCraft JSON workbook: invalid type: integer `7`, expected a sequence at line 1 column 12
|
||||
@@ -1,440 +0,0 @@
|
||||
{
|
||||
"sheets": [
|
||||
{
|
||||
"name": "Sheet1",
|
||||
"cells": {
|
||||
"bands": {
|
||||
"0": {
|
||||
"rows": {
|
||||
"0": {
|
||||
"0": {
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Item"
|
||||
},
|
||||
"formula": null,
|
||||
"style": 1
|
||||
},
|
||||
"1": {
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Qty"
|
||||
},
|
||||
"formula": null,
|
||||
"style": 1
|
||||
}
|
||||
},
|
||||
"1": {
|
||||
"0": {
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Äpfel ✓"
|
||||
},
|
||||
"formula": null,
|
||||
"style": 0
|
||||
},
|
||||
"1": {
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 3.5
|
||||
},
|
||||
"formula": null,
|
||||
"style": 2
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"0": {
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Pears"
|
||||
},
|
||||
"formula": null,
|
||||
"style": 0
|
||||
},
|
||||
"1": {
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 2.0
|
||||
},
|
||||
"formula": null,
|
||||
"style": 2
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"1": {
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 5.5
|
||||
},
|
||||
"formula": {
|
||||
"text": "SUM(B2:B3)",
|
||||
"array": null
|
||||
},
|
||||
"style": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"len": 7
|
||||
},
|
||||
"cols": {},
|
||||
"rows": {},
|
||||
"default_col_width": 64.0,
|
||||
"default_row_height": 20.0,
|
||||
"merges": [],
|
||||
"freeze": null,
|
||||
"tab_color": null,
|
||||
"visibility": "Visible",
|
||||
"show_gridlines": true,
|
||||
"show_headings": true,
|
||||
"show_formulas": false,
|
||||
"show_zeros": true,
|
||||
"show_outline_symbols": true,
|
||||
"summary_below": true,
|
||||
"summary_right": true,
|
||||
"right_to_left": false,
|
||||
"zoom": 100,
|
||||
"cond_formats": [],
|
||||
"validations": [],
|
||||
"tables": [],
|
||||
"autofilter": null,
|
||||
"comments": {},
|
||||
"hyperlinks": {},
|
||||
"charts": [],
|
||||
"images": [],
|
||||
"shapes": [],
|
||||
"sparklines": [],
|
||||
"slicers": [],
|
||||
"pivots": [],
|
||||
"protection": null,
|
||||
"print": {
|
||||
"orientation": "Portrait",
|
||||
"paper": "Letter",
|
||||
"margins": [
|
||||
0.7,
|
||||
0.7,
|
||||
0.75,
|
||||
0.75,
|
||||
0.3,
|
||||
0.3
|
||||
],
|
||||
"print_area": null,
|
||||
"title_rows": null,
|
||||
"title_cols": null,
|
||||
"scale": 100,
|
||||
"fit_to": null,
|
||||
"gridlines": false,
|
||||
"headings": false,
|
||||
"center_h": false,
|
||||
"center_v": false,
|
||||
"header": "",
|
||||
"footer": "",
|
||||
"row_breaks": [],
|
||||
"col_breaks": [],
|
||||
"different_first": false,
|
||||
"different_odd_even": false,
|
||||
"first_header": "",
|
||||
"first_footer": "",
|
||||
"even_header": "",
|
||||
"even_footer": "",
|
||||
"hf_scale_with_doc": true,
|
||||
"hf_align_with_margins": true,
|
||||
"page_order": "downThenOver"
|
||||
},
|
||||
"view_active": {
|
||||
"row": 0,
|
||||
"col": 0
|
||||
},
|
||||
"view_top_left": {
|
||||
"row": 0,
|
||||
"col": 0
|
||||
},
|
||||
"view": "normal"
|
||||
}
|
||||
],
|
||||
"names": [],
|
||||
"styles": {
|
||||
"styles": [
|
||||
{
|
||||
"font": {
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"underline": "None",
|
||||
"strike": false,
|
||||
"color": "Auto",
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
"fg": "Auto",
|
||||
"bg": "Auto"
|
||||
},
|
||||
"borders": {
|
||||
"left": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"right": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"top": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"bottom": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_down": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_up": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
}
|
||||
},
|
||||
"align": {
|
||||
"h": "General",
|
||||
"v": "Bottom",
|
||||
"wrap": false,
|
||||
"shrink": false,
|
||||
"indent": 0,
|
||||
"rotation": 0,
|
||||
"reading_order": null
|
||||
},
|
||||
"num_fmt": "General",
|
||||
"protection": {
|
||||
"locked": true,
|
||||
"hidden": false
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
"scheme": null,
|
||||
"protection": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"font": {
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"bold": true,
|
||||
"italic": false,
|
||||
"underline": "None",
|
||||
"strike": false,
|
||||
"color": "Auto",
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
"fg": "Auto",
|
||||
"bg": "Auto"
|
||||
},
|
||||
"borders": {
|
||||
"left": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"right": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"top": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"bottom": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_down": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_up": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
}
|
||||
},
|
||||
"align": {
|
||||
"h": "General",
|
||||
"v": "Bottom",
|
||||
"wrap": false,
|
||||
"shrink": false,
|
||||
"indent": 0,
|
||||
"rotation": 0,
|
||||
"reading_order": null
|
||||
},
|
||||
"num_fmt": "General",
|
||||
"protection": {
|
||||
"locked": true,
|
||||
"hidden": false
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
"scheme": null,
|
||||
"protection": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"font": {
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"underline": "None",
|
||||
"strike": false,
|
||||
"color": "Auto",
|
||||
"vert": "Baseline",
|
||||
"charset": null,
|
||||
"family": null,
|
||||
"minor": true
|
||||
},
|
||||
"fill": {
|
||||
"pattern": "None",
|
||||
"fg": "Auto",
|
||||
"bg": "Auto"
|
||||
},
|
||||
"borders": {
|
||||
"left": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"right": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"top": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"bottom": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_down": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
},
|
||||
"diag_up": {
|
||||
"style": "None",
|
||||
"color": "Auto"
|
||||
}
|
||||
},
|
||||
"align": {
|
||||
"h": "General",
|
||||
"v": "Bottom",
|
||||
"wrap": false,
|
||||
"shrink": false,
|
||||
"indent": 0,
|
||||
"rotation": 0,
|
||||
"reading_order": null
|
||||
},
|
||||
"num_fmt": "0.00",
|
||||
"protection": {
|
||||
"locked": true,
|
||||
"hidden": false
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"strike": false,
|
||||
"underline": false,
|
||||
"size": false,
|
||||
"name": false,
|
||||
"scheme": null,
|
||||
"protection": false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"theme": {
|
||||
"name": "Craft",
|
||||
"colors": [
|
||||
16777215,
|
||||
0,
|
||||
15263976,
|
||||
927809,
|
||||
1400962,
|
||||
15298866,
|
||||
1665828,
|
||||
1023701,
|
||||
10496915,
|
||||
5154606,
|
||||
4618374,
|
||||
9855101
|
||||
],
|
||||
"major_font": "Calibri",
|
||||
"minor_font": "Calibri",
|
||||
"major_font_ea": "",
|
||||
"minor_font_ea": "",
|
||||
"major_font_cs": "",
|
||||
"minor_font_cs": "",
|
||||
"major_font_scripts": [],
|
||||
"minor_font_scripts": []
|
||||
},
|
||||
"date_system": "D1900",
|
||||
"calc": {
|
||||
"mode": "Automatic",
|
||||
"iterative": false,
|
||||
"max_iterations": 100,
|
||||
"max_change": 0.001,
|
||||
"precision_as_displayed": false,
|
||||
"r1c1": false
|
||||
},
|
||||
"active_sheet": 0,
|
||||
"props": {
|
||||
"title": "",
|
||||
"subject": "",
|
||||
"author": "GridCraft User",
|
||||
"company": "",
|
||||
"keywords": "",
|
||||
"description": ""
|
||||
},
|
||||
"protected_structure": false,
|
||||
"custom_lists": [],
|
||||
"cell_styles": [],
|
||||
"vba_project": null,
|
||||
"macros": [
|
||||
{
|
||||
"v": 1,
|
||||
"name": "Fill",
|
||||
"description": "",
|
||||
"inputs": [],
|
||||
"steps": [
|
||||
{
|
||||
"type": "command",
|
||||
"id": "cell.set",
|
||||
"params": {
|
||||
"cell": "C1",
|
||||
"input": "x"
|
||||
}
|
||||
}
|
||||
],
|
||||
"output": {
|
||||
"onConflict": "ask"
|
||||
},
|
||||
"permissions": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,448 +0,0 @@
|
||||
{
|
||||
"active_sheet": 0,
|
||||
"calc": {
|
||||
"iterative": false,
|
||||
"max_change": 0.001,
|
||||
"max_iterations": 100,
|
||||
"mode": "Automatic",
|
||||
"precision_as_displayed": false,
|
||||
"r1c1": false
|
||||
},
|
||||
"cell_styles": [],
|
||||
"custom_lists": [],
|
||||
"date_system": "D1900",
|
||||
"macros": [
|
||||
{
|
||||
"description": "",
|
||||
"inputs": [],
|
||||
"name": "Fill",
|
||||
"output": {
|
||||
"onConflict": "ask"
|
||||
},
|
||||
"permissions": [],
|
||||
"steps": [
|
||||
{
|
||||
"id": "cell.set",
|
||||
"params": {
|
||||
"cell": "C1",
|
||||
"input": "x"
|
||||
},
|
||||
"type": "command"
|
||||
}
|
||||
],
|
||||
"v": 1
|
||||
},
|
||||
{
|
||||
"extra": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"name": "Future",
|
||||
"v": 2
|
||||
}
|
||||
],
|
||||
"names": [],
|
||||
"props": {
|
||||
"author": "GridCraft User",
|
||||
"company": "",
|
||||
"description": "",
|
||||
"keywords": "",
|
||||
"subject": "",
|
||||
"title": ""
|
||||
},
|
||||
"protected_structure": false,
|
||||
"sheets": [
|
||||
{
|
||||
"autofilter": null,
|
||||
"cells": {
|
||||
"bands": {
|
||||
"0": {
|
||||
"rows": {
|
||||
"0": {
|
||||
"0": {
|
||||
"formula": null,
|
||||
"style": 1,
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Item"
|
||||
}
|
||||
},
|
||||
"1": {
|
||||
"formula": null,
|
||||
"style": 1,
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Qty"
|
||||
}
|
||||
}
|
||||
},
|
||||
"1": {
|
||||
"0": {
|
||||
"formula": null,
|
||||
"style": 0,
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Äpfel ✓"
|
||||
}
|
||||
},
|
||||
"1": {
|
||||
"formula": null,
|
||||
"style": 2,
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 3.5
|
||||
}
|
||||
}
|
||||
},
|
||||
"2": {
|
||||
"0": {
|
||||
"formula": null,
|
||||
"style": 0,
|
||||
"value": {
|
||||
"t": "Text",
|
||||
"v": "Pears"
|
||||
}
|
||||
},
|
||||
"1": {
|
||||
"formula": null,
|
||||
"style": 2,
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 2.0
|
||||
}
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"1": {
|
||||
"formula": {
|
||||
"array": null,
|
||||
"text": "SUM(B2:B3)"
|
||||
},
|
||||
"style": 2,
|
||||
"value": {
|
||||
"t": "Number",
|
||||
"v": 5.5
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"len": 7
|
||||
},
|
||||
"charts": [],
|
||||
"cols": {},
|
||||
"comments": {},
|
||||
"cond_formats": [],
|
||||
"default_col_width": 64.0,
|
||||
"default_row_height": 20.0,
|
||||
"freeze": null,
|
||||
"hyperlinks": {},
|
||||
"images": [],
|
||||
"merges": [],
|
||||
"name": "Sheet1",
|
||||
"pivots": [],
|
||||
"print": {
|
||||
"center_h": false,
|
||||
"center_v": false,
|
||||
"col_breaks": [],
|
||||
"different_first": false,
|
||||
"different_odd_even": false,
|
||||
"even_footer": "",
|
||||
"even_header": "",
|
||||
"first_footer": "",
|
||||
"first_header": "",
|
||||
"fit_to": null,
|
||||
"footer": "",
|
||||
"gridlines": false,
|
||||
"header": "",
|
||||
"headings": false,
|
||||
"hf_align_with_margins": true,
|
||||
"hf_scale_with_doc": true,
|
||||
"margins": [
|
||||
0.699999988079071,
|
||||
0.699999988079071,
|
||||
0.75,
|
||||
0.75,
|
||||
0.30000001192092896,
|
||||
0.30000001192092896
|
||||
],
|
||||
"orientation": "Portrait",
|
||||
"page_order": "downThenOver",
|
||||
"paper": "Letter",
|
||||
"print_area": null,
|
||||
"row_breaks": [],
|
||||
"scale": 100,
|
||||
"title_cols": null,
|
||||
"title_rows": null
|
||||
},
|
||||
"protection": null,
|
||||
"right_to_left": false,
|
||||
"rows": {},
|
||||
"shapes": [],
|
||||
"show_formulas": false,
|
||||
"show_gridlines": true,
|
||||
"show_headings": true,
|
||||
"show_outline_symbols": true,
|
||||
"show_zeros": true,
|
||||
"slicers": [],
|
||||
"sparklines": [],
|
||||
"summary_below": true,
|
||||
"summary_right": true,
|
||||
"tab_color": null,
|
||||
"tables": [],
|
||||
"validations": [],
|
||||
"view": "normal",
|
||||
"view_active": {
|
||||
"col": 0,
|
||||
"row": 0
|
||||
},
|
||||
"view_top_left": {
|
||||
"col": 0,
|
||||
"row": 0
|
||||
},
|
||||
"visibility": "Visible",
|
||||
"zoom": 100
|
||||
}
|
||||
],
|
||||
"styles": {
|
||||
"styles": [
|
||||
{
|
||||
"align": {
|
||||
"h": "General",
|
||||
"indent": 0,
|
||||
"reading_order": null,
|
||||
"rotation": 0,
|
||||
"shrink": false,
|
||||
"v": "Bottom",
|
||||
"wrap": false
|
||||
},
|
||||
"borders": {
|
||||
"bottom": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_down": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_up": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"left": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"right": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"top": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
}
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
"strike": false,
|
||||
"underline": false
|
||||
},
|
||||
"fill": {
|
||||
"bg": "Auto",
|
||||
"fg": "Auto",
|
||||
"pattern": "None"
|
||||
},
|
||||
"font": {
|
||||
"bold": false,
|
||||
"charset": null,
|
||||
"color": "Auto",
|
||||
"family": null,
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
"vert": "Baseline"
|
||||
},
|
||||
"num_fmt": "General",
|
||||
"protection": {
|
||||
"hidden": false,
|
||||
"locked": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"align": {
|
||||
"h": "General",
|
||||
"indent": 0,
|
||||
"reading_order": null,
|
||||
"rotation": 0,
|
||||
"shrink": false,
|
||||
"v": "Bottom",
|
||||
"wrap": false
|
||||
},
|
||||
"borders": {
|
||||
"bottom": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_down": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_up": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"left": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"right": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"top": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
}
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
"strike": false,
|
||||
"underline": false
|
||||
},
|
||||
"fill": {
|
||||
"bg": "Auto",
|
||||
"fg": "Auto",
|
||||
"pattern": "None"
|
||||
},
|
||||
"font": {
|
||||
"bold": true,
|
||||
"charset": null,
|
||||
"color": "Auto",
|
||||
"family": null,
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
"vert": "Baseline"
|
||||
},
|
||||
"num_fmt": "General",
|
||||
"protection": {
|
||||
"hidden": false,
|
||||
"locked": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"align": {
|
||||
"h": "General",
|
||||
"indent": 0,
|
||||
"reading_order": null,
|
||||
"rotation": 0,
|
||||
"shrink": false,
|
||||
"v": "Bottom",
|
||||
"wrap": false
|
||||
},
|
||||
"borders": {
|
||||
"bottom": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_down": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"diag_up": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"left": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"right": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
},
|
||||
"top": {
|
||||
"color": "Auto",
|
||||
"style": "None"
|
||||
}
|
||||
},
|
||||
"dxf_stated": {
|
||||
"bold": false,
|
||||
"italic": false,
|
||||
"name": false,
|
||||
"protection": false,
|
||||
"scheme": null,
|
||||
"size": false,
|
||||
"strike": false,
|
||||
"underline": false
|
||||
},
|
||||
"fill": {
|
||||
"bg": "Auto",
|
||||
"fg": "Auto",
|
||||
"pattern": "None"
|
||||
},
|
||||
"font": {
|
||||
"bold": false,
|
||||
"charset": null,
|
||||
"color": "Auto",
|
||||
"family": null,
|
||||
"italic": false,
|
||||
"minor": true,
|
||||
"name": "Calibri",
|
||||
"size": 11.0,
|
||||
"strike": false,
|
||||
"underline": "None",
|
||||
"vert": "Baseline"
|
||||
},
|
||||
"num_fmt": "0.00",
|
||||
"protection": {
|
||||
"hidden": false,
|
||||
"locked": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"theme": {
|
||||
"colors": [
|
||||
16777215,
|
||||
0,
|
||||
15263976,
|
||||
927809,
|
||||
1400962,
|
||||
15298866,
|
||||
1665828,
|
||||
1023701,
|
||||
10496915,
|
||||
5154606,
|
||||
4618374,
|
||||
9855101
|
||||
],
|
||||
"major_font": "Calibri",
|
||||
"major_font_cs": "",
|
||||
"major_font_ea": "",
|
||||
"major_font_scripts": [],
|
||||
"minor_font": "Calibri",
|
||||
"minor_font_cs": "",
|
||||
"minor_font_ea": "",
|
||||
"minor_font_scripts": [],
|
||||
"name": "Craft"
|
||||
},
|
||||
"vba_project": null
|
||||
}
|
||||
@@ -10,6 +10,7 @@ readme = "README.md"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-stream-codecs.workspace = true
|
||||
harfrust = "=0.12.0"
|
||||
skrifa = { workspace = true }
|
||||
unicode-bidi = "=0.3.18"
|
||||
|
||||
+1
-33
@@ -979,39 +979,7 @@ pub struct PdfDoc {
|
||||
|
||||
/// PackBits-style run-length encoding (PDF `RunLengthDecode`).
|
||||
fn run_length(data: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(data.len() / 2 + 16);
|
||||
let mut i = 0;
|
||||
while i < data.len() {
|
||||
let b = data[i];
|
||||
let mut run = 1;
|
||||
while i + run < data.len() && run < 128 && data[i + run] == b {
|
||||
run += 1;
|
||||
}
|
||||
if run >= 2 {
|
||||
out.push((257 - run) as u8);
|
||||
out.push(b);
|
||||
i += run;
|
||||
continue;
|
||||
}
|
||||
// Literal run until the next repeat of 3+ or 128 bytes.
|
||||
let start = i;
|
||||
let mut len = 0;
|
||||
while i < data.len() && len < 128 {
|
||||
if i + 2 < data.len() && data[i] == data[i + 1] && data[i] == data[i + 2] {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
len += 1;
|
||||
}
|
||||
if len == 0 {
|
||||
// Next is a repeat; loop will handle it.
|
||||
continue;
|
||||
}
|
||||
out.push((len - 1) as u8);
|
||||
out.extend_from_slice(&data[start..start + len]);
|
||||
}
|
||||
out.push(128);
|
||||
out
|
||||
craft_stream_codecs::runlength::encode(data)
|
||||
}
|
||||
|
||||
/// Longest Info string written, in characters; longer values are cut on a character boundary.
|
||||
|
||||
@@ -1239,3 +1239,21 @@ fn symbol_text_is_never_shaped_as_arabic() -> Result<(), Box<dyn Error>> {
|
||||
assert_eq!(text_width(Font::Symbol, 10.0, "\u{03B1}ب"), f32::from(Font::Symbol.char_width('\u{03B1}') + Font::Symbol.char_width('ب')) / 100.0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_run_length_preserves_pixels_at_packet_boundaries() {
|
||||
for len in [0, 1, 2, 3, 127, 128, 129, 255, 256, 257, 1024] {
|
||||
for seed in [0u8, 127, 128, 255] {
|
||||
let repeats = vec![seed; len];
|
||||
let literals: Vec<u8> = (0..len).map(|i| seed.wrapping_add(i as u8)).collect();
|
||||
let pairs: Vec<u8> = (0..len).map(|i| (i / 2) as u8).collect();
|
||||
for pixels in [repeats, literals, pairs] {
|
||||
let encoded = run_length(&pixels);
|
||||
assert_eq!(encoded.last(), Some(&128));
|
||||
assert_eq!(rle_decode(&encoded), pixels);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Two equal bytes may now terminate a literal packet. PDF pixel values stay exact.
|
||||
assert_eq!(run_length(&[1, 2, 2, 3]), [0, 1, 255, 2, 0, 3, 128]);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ craft-csv = { workspace = true }
|
||||
craft-offcrypto = { workspace = true }
|
||||
craft-opc = { workspace = true }
|
||||
craft-xls = { workspace = true }
|
||||
craft-xml = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
+21
-48
@@ -359,31 +359,11 @@ pub fn parse_streaming(xml: &[u8], split: &[&str], cb: &mut dyn FnMut(El) -> Res
|
||||
|
||||
// ---------------------------------------------------------------- writing helpers
|
||||
|
||||
/// Escapes text content.
|
||||
pub fn esc(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
push_esc(&mut o, s);
|
||||
o
|
||||
}
|
||||
|
||||
/// Appends [`esc`]`(s)` to `o`.
|
||||
pub fn push_esc(o: &mut String, s: &str) {
|
||||
if s.bytes().all(|b| matches!(b, b'\t' | b'\n' | 0x20..=0x7E) && !matches!(b, b'&' | b'<' | b'>')) {
|
||||
o.push_str(s);
|
||||
return;
|
||||
}
|
||||
o.reserve(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'\r' => o.push_str(" "),
|
||||
c if is_xml_char(c) => o.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
// XML 1.0 byte escaping is shared; spreadsheet string and phonetic policy stays here.
|
||||
use craft_xml::is_xml_char;
|
||||
#[cfg(test)]
|
||||
use craft_xml::push_esc;
|
||||
pub use craft_xml::{esc, esc_attr};
|
||||
|
||||
/// Appends `n` in decimal.
|
||||
pub fn push_u64(o: &mut String, mut n: u64) {
|
||||
@@ -422,29 +402,6 @@ pub fn push_a1(o: &mut String, c: gridcraft_core::CellRef) {
|
||||
push_u64(o, u64::from(c.row) + 1);
|
||||
}
|
||||
|
||||
/// Escapes an attribute value (double-quoted).
|
||||
pub fn esc_attr(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'"' => o.push_str("""),
|
||||
'\n' => o.push_str(" "),
|
||||
'\r' => o.push_str(" "),
|
||||
'\t' => o.push_str("	"),
|
||||
c if is_xml_char(c) => o.push(c),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
fn is_xml_char(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\r' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}')
|
||||
}
|
||||
|
||||
/// ST_Xstring encoding for cell text: characters XML can't carry and carriage returns become
|
||||
/// `_xHHHH_`, and literal `_xHHHH_` sequences are protected with `_x005F_`. The result still needs
|
||||
/// [`esc`].
|
||||
@@ -805,3 +762,19 @@ mod tests {
|
||||
assert_eq!("1.5E20".parse::<f64>().unwrap(), 1.5e20);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_escape_parity {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn xml_content_and_attributes_preserve_grid_bytes() {
|
||||
let value = "&<>\"'\t\n\r\0\u{1f}\u{fffe}\u{ffff}é😀";
|
||||
assert_eq!(esc(value), "&<>\"'\t\n é😀");
|
||||
assert_eq!(esc_attr(value), "&<>"'	 é😀");
|
||||
let mut appended = "prefix:".to_owned();
|
||||
push_esc(&mut appended, value);
|
||||
assert_eq!(appended, format!("prefix:{}", esc(value)));
|
||||
assert_eq!(esc("plain ASCII\t\n"), "plain ASCII\t\n");
|
||||
assert_eq!(decode_xstring(&encode_xstring("_x000D_\r\0😀")), "_x000D_\r\0😀");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user