diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 0b20746fa8..c21f8dd8e3 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -2,6 +2,7 @@ //! layer templates, tasks, and 3D export (Home › Add; Data › Layer Templates and Styles; Publish › //! Package, Save As and Output; Command Search for map/template imports). +use std::borrow::Cow; use std::fmt::Write as _; use std::path::Path; @@ -457,7 +458,7 @@ pub fn can_be_step(s: &Session, id: &str) -> bool { /// The JSON of an item from `text`, or the file at `path`. pub(crate) fn read_text(p: &Value) -> Result { if let Some(text) = inline_text(p)? { - return Ok(text); + return Ok(text.into_owned()); } match (ps(p, "text"), ps(p, "path")) { (Some(t), _) if t.len() as u64 <= max_file() => Ok(t.to_string()), @@ -2051,8 +2052,9 @@ fn durable_bytes_with( Ok(bytes) } -/// Decodes the same data-before-text choice without opening a path. -pub(crate) fn inline_text(p: &Value) -> Result, String> { +/// Decodes the same data-before-text choice without opening a path. `text` is lent, not copied: +/// every save asks each capability check about it. +pub(crate) fn inline_text(p: &Value) -> Result>, String> { if let Some(d) = ps(p, "data") { use base64::Engine; if d.len() as u64 > max_file() / 3 * 4 { @@ -2060,12 +2062,12 @@ pub(crate) fn inline_text(p: &Value) -> Result, String> { } let bytes = base64::engine::general_purpose::STANDARD.decode(d.trim()).map_err(|_| "data must be base64".to_string())?; if bytes.starts_with(b"PK") { - return package_text(&bytes).map(Some); + return package_text(&bytes).map(|t| Some(t.into())); } - return String::from_utf8(bytes).map(Some).map_err(|_| "not a RustGIS file".to_string()); + return String::from_utf8(bytes).map(|t| Some(t.into())).map_err(|_| "not a RustGIS file".to_string()); } match ps(p, "text") { - Some(t) if t.len() as u64 <= max_file() => Ok(Some(t.to_string())), + Some(t) if t.len() as u64 <= max_file() => Ok(Some(t.into())), Some(_) => Err(too_large()), None => Ok(None), } diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 429eb11b31..24006c4754 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -293,11 +293,11 @@ fn command_uses_text_statistics(id: &str, params: &Value) -> bool { "presentation.mapPage" | "presentation.updatePage" => params.get("title").is_some_and(holds_statistic), // A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does. "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &STATISTIC_KEYS, text_statistics), - "presentation.import" => params - .get("text") - .and_then(Value::as_str) + "presentation.import" => crate::cmd::items::inline_text(params) + .ok() + .flatten() .filter(|t| STATISTIC_KEYS.iter().any(|key| t.contains(key)) || t.contains('\\')) - .and_then(|t| serde_json::from_str::(t).ok()) + .and_then(|t| serde_json::from_str::(&t).ok()) .is_some_and(|p| presentation_uses_text_statistics(&p)), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_text_statistics)), _ => false, @@ -788,7 +788,7 @@ fn command_uses_chart_outline(id: &str, params: &Value) -> bool { } } -/// Whether a `layout.import` carries its layout as `"text"` with an element `uses`: an older +/// Whether a command carries its layout inline with an element `uses`: an older /// reader reads it without the keys it doesn't know. One read from a `"path"` is a layout file, /// whose own header requires what it uses (#2277). Every save asks, so a text with none of the /// feature's `keys` (a saved layout writes them only when set) isn't read through, unless it has a @@ -798,14 +798,16 @@ fn imported_layout_uses(params: &Value, keys: &[&str], uses: fn(&rustgis_map::la imported_layout(params, keys).is_some_and(|l| l.elements.iter().any(uses)) } -/// A `layout.import`'s layout, read only when its text names one of `keys` (or escapes, which -/// could hide one). +/// The layout a command carries inline, read only when its text names one of `keys` (or escapes, +/// which could hide one). `data` (base64) goes before `text`, as `report.existingTemplate` reads +/// them; one it refuses is no layout. `data` is decoded for each check, rather than keeping it: +/// only a step that carries it pays, and only on a save. fn imported_layout(params: &Value, keys: &[&str]) -> Option { - params - .get("text") - .and_then(Value::as_str) + crate::cmd::items::inline_text(params) + .ok() + .flatten() .filter(|t| keys.iter().any(|key| t.contains(key)) || t.contains('\\')) - .and_then(|t| serde_json::from_str::(t).ok()) + .and_then(|t| serde_json::from_str::(&t).ok()) } /// Require only executable payloads being saved: graph files omit steps, web tools omit graphs. @@ -2254,6 +2256,10 @@ mod tests { let mut damaged = base["layouts"][0].clone(); damaged["elements"][1]["kind"]["Legend"]["fit"] = json!("adjustFrame"); damaged["elements"][1]["kind"]["Legend"]["show_layer_names"] = json!("no"); + let data = |text: &str| { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(text) + }; for (id, params, required) in [ ("layout.addElement", json!({"kind": "legend", "fit": "adjustSize"}), true), ("layout.addElement", json!({"kind": "legend", "showLayerNames": false, "fit": "shrink"}), true), @@ -2275,6 +2281,20 @@ mod tests { // A report section's template is a layout file read as `layout.import` reads it. ("report.existingTemplate", json!({"text": saved["layouts"][0].to_string()}), true), ("report.existingTemplate", json!({"text": base["layouts"][0].to_string()}), false), + // It reads `data` (base64) before `text`. + ("report.existingTemplate", json!({"data": data(&saved["layouts"][0].to_string())}), true), + ("report.existingTemplate", json!({"data": data(&base["layouts"][0].to_string())}), false), + ("report.existingTemplate", json!({"data": "not base64"}), false), + ( + "report.existingTemplate", + json!({"data": data(&saved["layouts"][0].to_string()), "text": base["layouts"][0].to_string()}), + true, + ), + ( + "report.existingTemplate", + json!({"data": data(&base["layouts"][0].to_string()), "text": saved["layouts"][0].to_string()}), + false, + ), ] { // A scale bar's fit name is its details' to require, not this. let bar = params.get("fit") == Some(&json!("adjustWidth")); @@ -3006,6 +3026,10 @@ mod tests { let base = with_text("{scale} {count:} {foo}"); assert_eq!(base.get("requires"), None); let layout = saved["layouts"][0].to_string(); + let data = { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(&layout) + }; for (id, params, required) in [ ("layout.addElement", json!({"kind": "text", "text": "{sum:Sites:visits}"}), true), ("layout.addElement", json!({"kind": "text", "text": "{scale}"}), false), @@ -3028,6 +3052,7 @@ mod tests { ("layout.import", json!({"text": layout}), true), // A report section's template is a layout file read as `layout.import` reads it. ("report.existingTemplate", json!({"text": layout}), true), + ("report.existingTemplate", json!({"data": data}), true), ] { let script = format!("{id} {params}"); for value in [ @@ -3053,6 +3078,10 @@ mod tests { let blank_page = |title: &str| json!({"title": title, "kind": {"type": "blank", "text": "", "background": [255, 255, 255, 255]}}); let presentation = |page: Value| json!({"name": "P", "width": 297, "height": 210, "pages": [page]}).to_string(); let base = serde_json::to_value(Project::default()).unwrap(); + let data = |title: &str| { + use base64::Engine; + base64::engine::general_purpose::STANDARD.encode(presentation(map_page(title))) + }; for (page, required) in [(map_page("{count:Sites}"), true), (map_page("Sites"), false), (blank_page("{count:Sites}"), false)] { let mut document = base.clone(); document["presentations"] = json!([{"name": "P", "width": 297, "height": 210, "pages": [page.clone()]}]); @@ -3068,6 +3097,9 @@ mod tests { ("presentation.import", json!({"text": presentation(map_page("{count:Sites}"))}), true), ("presentation.import", json!({"text": presentation(map_page("Sites"))}), false), ("presentation.import", json!({"text": presentation(blank_page("{count:Sites}"))}), false), + // It reads `data` (base64) before `text`. + ("presentation.import", json!({"data": data("{count:Sites}")}), true), + ("presentation.import", json!({"data": data("Sites"), "text": presentation(map_page("{count:Sites}"))}), false), ] { let script = format!("{id} {params}"); for value in [