Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 35 additions & 30 deletions crates/engine/src/cmd/data/grouping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,36 +235,41 @@ pub(super) fn subtotal(s: &mut Session, p: &Json) -> Result<Json> {
start = row;
}
}
// The totals go below each group, so the outline puts summary rows below their detail (the
// Subtotal dialog's "Summary below data"), in the same undo step.
if !sh.summary_below {
s.execute("data.outlineSettings", json!({"sheet": sheet, "summaryBelow": true}))?;
}
// Insert a total row after each group, bottom-up so indices stay valid.
let mut inserted = 0;
for (g0, g1, name) in groups.iter().rev() {
s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", g1 + 2, g1 + 2)}))?;
let row = g1 + 1;
let lbl = CellRef::new(row, group_col).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("{name} {label}")}))?;
let summary_below = sh.summary_below;
// The steps run in one undo group: a step that fails part way (the grand total past the last
// row, say) restores the sheet, so nothing is left changed that the journal doesn't hold.
s.grouped("Subtotal", |s| {
// The totals go below each group, so the outline puts summary rows below their detail (the
// Subtotal dialog's "Summary below data"), in the same undo step.
if !summary_below {
s.execute("data.outlineSettings", json!({"sheet": sheet, "summaryBelow": true}))?;
}
// Insert a total row after each group, bottom-up so indices stay valid.
let mut inserted = 0;
for (g0, g1, name) in groups.iter().rev() {
s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", g1 + 2, g1 + 2)}))?;
let row = g1 + 1;
let lbl = CellRef::new(row, group_col).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("{name} {label}")}))?;
for c in &cols {
let range = RangeRef::new(CellRef::new(*g0, *c), CellRef::new(*g1, *c)).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(row, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?;
}
s.execute(
"home.bold",
json!({"sheet": sheet, "range": RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col)).a1(), "on": true}),
)?;
s.execute("data.group", json!({"sheet": sheet, "rows": format!("{}:{}", g0 + 1, g1 + 1)}))?;
inserted += 1;
}
let last = r.end.row + inserted + 1;
let lbl = CellRef::new(last, group_col).a1();
s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", last + 1, last + 1)}))?;
s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("Grand {label}")}))?;
for c in &cols {
let range = RangeRef::new(CellRef::new(*g0, *c), CellRef::new(*g1, *c)).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(row, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?;
let range = RangeRef::new(CellRef::new(first, *c), CellRef::new(last - 1, *c)).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(last, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?;
}
s.execute(
"home.bold",
json!({"sheet": sheet, "range": RangeRef::new(CellRef::new(row, r.start.col), CellRef::new(row, r.end.col)).a1(), "on": true}),
)?;
s.execute("data.group", json!({"sheet": sheet, "rows": format!("{}:{}", g0 + 1, g1 + 1)}))?;
inserted += 1;
}
let last = r.end.row + inserted + 1;
let lbl = CellRef::new(last, group_col).a1();
s.execute("home.insertRows", json!({"sheet": sheet, "rows": format!("{}:{}", last + 1, last + 1)}))?;
s.execute("cell.set", json!({"sheet": sheet, "cell": lbl, "input": format!("Grand {label}")}))?;
for c in &cols {
let range = RangeRef::new(CellRef::new(first, *c), CellRef::new(last - 1, *c)).a1();
s.execute("cell.set", json!({"sheet": sheet, "cell": CellRef::new(last, *c).a1(), "input": format!("=SUBTOTAL({code},{range})")}))?;
}
Ok(json!({"groups": inserted}))
Ok(json!({"groups": inserted}))
})
}
16 changes: 16 additions & 0 deletions crates/engine/src/cmd/data/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ fn subtotal_puts_summary_rows_below_their_detail() {
assert_eq!(sh.value(CellRef::new(3, 0)).display(), "West");
}

#[test]
fn subtotal_that_fails_part_way_changes_nothing() {
// The grand total's row pushes the marker past the last row, after the group total went in.
// The failed command must leave the sheet as it was and journal nothing.
let mut s = Session::new();
s.new_workbook();
s.execute("range.setValues", json!({"range": "A1", "values": [["Region", "Sales"], ["East", 10], ["East", 20]]})).unwrap();
s.execute("cell.set", json!({"cell": "Z1048575", "input": "marker"})).unwrap();
let journal = s.journal.len();
assert!(s.execute("data.subtotal", json!({"range": "A1:B3", "groupBy": "A", "columns": ["B"]})).is_err());
let sh = s.doc().unwrap().wb.active().unwrap().clone();
assert_eq!(sh.value(CellRef::new(3, 0)).display(), "", "no group total was left behind");
assert_eq!(sh.value(CellRef::new(1048574, 25)).display(), "marker");
assert_eq!(s.journal.len(), journal);
}

#[test]
fn filter_by_huge_numeric_column_is_rejected_not_overflowed() {
let mut s = Session::new();
Expand Down
23 changes: 14 additions & 9 deletions crates/engine/src/cmd/extra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,15 +232,20 @@ pub fn specs() -> Vec<CommandSpec> {
new_script
),
cmd!(query "automate.allScripts", "All Scripts", ["Automate", "Scripting Tools"], None, "{} → saved scripts", has_doc, all_scripts),
cmd!(
"automate.runScript",
"Run Script",
[],
None,
"{name, trusted?: bool (runs a script from an untrusted workbook this once)} — refuses scripts in a workbook opened from a file until it is trusted, and steps that reach outside the workbook (file.*, link.*, any `path` param)",
has_doc,
run_script
),
// The journal stores its exact steps as one replayable command, preserving the script's
// single undo boundary even if the stored script is later deleted.
CommandSpec {
id: "automate.runScript",
label: "Run Script",
menu: &[],
shortcut: None,
shortcut_mac: None,
params: "{name?, commands?: [{command, params}] (journal replay), trusted?: bool (runs a script from an untrusted workbook this once)} — refuses scripts in a workbook opened from a file until it is trusted, and steps that reach outside the workbook (file.*, link.*, any `path` param)",
enabled: has_doc,
run: run_script,
journal: false,
undoable: true,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
cmd!(
noundo "automate.trustScripts",
"Trust Scripts",
Expand Down
67 changes: 54 additions & 13 deletions crates/engine/src/cmd/extra/scripts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ use super::{EngineError, Json, Result, SCRIPTS_NAME, Session, Workbook, bad, boo
pub(super) fn record(s: &mut Session, p: &Json) -> Result<Json> {
if bool_param(p, "stop").unwrap_or(false) || s.recording.is_some() {
let Some(start) = s.recording.take() else { return Ok(json!({"recording": false})) };
let cmds: Vec<Json> = s
.journal
.iter()
.skip(start)
.filter(|(id, _)| !id.starts_with("automate.") && !crate::record::NOT_RECORDED.contains(&id.as_str()))
.map(|(id, p)| json!({"command": id, "params": p}))
.collect();
let mut cmds = Vec::new();
for (id, params) in s.journal.iter().skip(start) {
if id == "automate.runScript"
&& let Some(steps) = params.get("commands").and_then(Json::as_array)
{
cmds.extend(steps.iter().cloned());
} else if !id.starts_with("automate.") && !crate::record::NOT_RECORDED.contains(&id.as_str()) {
cmds.push(json!({"command": id, "params": params}));
}
}
let name = str_param(p, "name").map(str::to_string).unwrap_or_else(|| format!("Script {}", start));
s.execute("automate.newScript", json!({"name": name, "commands": cmds}))?;
return Ok(json!({"recording": false, "saved": name, "steps": cmds.len()}));
Expand Down Expand Up @@ -53,6 +56,21 @@ pub(crate) fn has_scripts(wb: &Workbook) -> bool {
stash_map(wb, SCRIPTS_NAME).as_object().is_some_and(|o| !o.is_empty())
}

fn journal_script_steps(s: &mut Session, p: &Json, commands: Vec<Json>, parent_nesting: u32) {
if parent_nesting != 0 || s.journal_paused != 0 || commands.is_empty() {
return;
}
let mut replay = crate::cmd::journal_params(p);
if !replay.is_object() {
replay = Json::Object(Default::default());
}
if let Some(params) = replay.as_object_mut() {
params.insert("commands".into(), Json::Array(commands));
params.insert("trusted".into(), Json::Bool(true));
}
s.push_journal("automate.runScript", replay);
}

/// Why a script step is refused, whatever the workbook's trust: scripts stay inside the
/// workbook. Anything that reads or writes files (`file.*`, or any `path` parameter: Get Data,
/// From Text/CSV, Insert Picture) or leaves the app (`link.*` opens URLs) is the caller's to run
Expand Down Expand Up @@ -90,10 +108,15 @@ pub(super) fn trust_scripts(s: &mut Session, p: &Json) -> Result<Json> {
/// trusted for this session (`automate.trustScripts`, or `trusted: true` on this call); steps that
/// reach outside the workbook ([`denied_script_step`]) are refused before any step runs.
pub(super) fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
let name = str_param(p, "name").ok_or_else(|| bad("automate.runScript", "missing `name`"))?;
let d = s.doc()?;
let all = stash_get(&d.wb, SCRIPTS_NAME);
let steps = all.get(name).and_then(Json::as_array).cloned().ok_or_else(|| bad("automate.runScript", "no such script"))?;
let commands = p.get("commands").and_then(Json::as_array).cloned();
let steps = if let Some(commands) = commands {
commands
} else {
let name = str_param(p, "name").ok_or_else(|| bad("automate.runScript", "missing `name`"))?;
let all = stash_get(&d.wb, SCRIPTS_NAME);
all.get(name).and_then(Json::as_array).cloned().ok_or_else(|| bad("automate.runScript", "no such script"))?
};
if !d.scripts_trusted && !bool_param(p, "trusted").unwrap_or(false) {
return Err(bad(
"automate.runScript",
Expand All @@ -112,6 +135,9 @@ pub(super) fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
// What ran, for a recorder in progress: the recording keeps these steps with the run, so
// editing or deleting the script before the recording stops does not change what it saved.
let mut ran_steps: Vec<(String, Json)> = Vec::new();
let mut journal_steps: Vec<Json> = Vec::new();
let journal_parent = s.journal_nesting;
s.journal_nesting = s.journal_nesting.saturating_add(1);
for st in &steps {
let id = st["command"].as_str().unwrap_or("");
if id.starts_with("automate.") {
Expand All @@ -127,24 +153,39 @@ pub(super) fn run_script(s: &mut Session, p: &Json) -> Result<Json> {
i += 1;
i <= before || !matches!(r, crate::UiRequest::OpenUrl(_))
});
s.journal_nesting = journal_parent;
journal_script_steps(s, p, journal_steps, journal_parent);
return Err(bad("automate.runScript", format!("scripts can't open links (`{id}`)")));
}
let result = ran?;
let result = match ran {
Ok(result) => result,
Err(error) => {
s.journal_nesting = journal_parent;
journal_script_steps(s, p, journal_steps, journal_parent);
return Err(error);
}
};
n += 1;
let journaled = crate::cmd::find_command(id).is_some_and(|spec| spec.journal);
let opened_dialog = s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::Dialog(..))));
let changed = wb_before.as_ref().is_some_and(|(uid, wb)| s.docs.iter().any(|d| d.uid == *uid && !std::sync::Arc::ptr_eq(&d.wb, wb)));
if journaled && (!opened_dialog || changed) {
journal_steps.push(json!({"command": id, "params": crate::cmd::journal_params(&st["params"])}));
}
if s.recorder.is_some() {
// The recorder's rule for each step, as for a command run on its own: a menu-style
// step that only opened a dialog is left out (playing it back would stop at the
// dialog), and a toggle keeps the state it set.
let opened_dialog = s.ui_requests.get(before..).is_some_and(|new| new.iter().any(|r| matches!(r, crate::UiRequest::Dialog(..))));
let changed = wb_before.as_ref().is_some_and(|(uid, wb)| s.docs.iter().any(|d| d.uid == *uid && !std::sync::Arc::ptr_eq(&d.wb, wb)));
if !opened_dialog || changed {
ran_steps.push((id.to_string(), crate::record::with_toggle_state(id, st["params"].clone(), &result)));
}
}
}
s.journal_nesting = journal_parent;
if s.recorder.is_some() {
s.script_ran = Some(ran_steps);
}
journal_script_steps(s, p, journal_steps, journal_parent);
Ok(json!({"ran": n}))
}

Expand Down
Loading
Loading