Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 8 additions & 6 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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<String, String> {
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()),
Expand Down Expand Up @@ -2051,21 +2052,22 @@ fn durable_bytes_with<T: crate::durable::Durable>(
Ok(bytes)
}

/// Decodes the same data-before-text choice without opening a path.
pub(crate) fn inline_text(p: &Value) -> Result<Option<String>, 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<Option<Cow<'_, str>>, String> {
if let Some(d) = ps(p, "data") {
use base64::Engine;
if d.len() as u64 > max_file() / 3 * 4 {
return Err(too_large());
}
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),
}
Expand Down
54 changes: 43 additions & 11 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<rustgis_map::presentation::Presentation>(t).ok())
.and_then(|t| serde_json::from_str::<rustgis_map::presentation::Presentation>(&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,
Expand Down Expand Up @@ -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
Expand All @@ -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<rustgis_map::layout::Layout> {
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::<rustgis_map::layout::Layout>(t).ok())
.and_then(|t| serde_json::from_str::<rustgis_map::layout::Layout>(&t).ok())
}

/// Require only executable payloads being saved: graph files omit steps, web tools omit graphs.
Expand Down Expand Up @@ -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),
Expand All @@ -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"));
Expand Down Expand Up @@ -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),
Expand All @@ -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 [
Expand All @@ -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()]}]);
Expand All @@ -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 [
Expand Down
Loading