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
29 changes: 22 additions & 7 deletions crates/engine/src/cmd/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1457,7 +1457,10 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result<Value, String> {
if outbound {
return Err("this field package was made here to go to the field, not sent back from it: Bring Back reads the package the phone sends with Send Field Package. Nothing was changed".into());
}
let project = Project::from_import_json(&text, None)?;
// Held within where the package came from ([`Session::file_reach`]) before its read reads
// anything it names.
let (project, named) = Project::from_import_json_within(&text, None, s.file_reach(p))?;
named.say(s, "the field package");
let ai = if let Some(area) = legacy_area {
let raw: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?;
// Only entirely absent identities qualify. Null/empty/malformed metadata is not a
Expand Down Expand Up @@ -1871,8 +1874,9 @@ pub(crate) fn unpack_into(bytes: &[u8], dir: &Path) -> Result<(String, Vec<Strin
}
}
let text = project.ok_or("the field package holds no project")?;
// Read before anything is written: a project that can't be read leaves no folder behind.
Project::from_import_json(&text, Some(dir))?;
// Checked before anything is written: a project that can't be read leaves no folder behind.
// Nothing it names is read here; that waits for its hold ([`project_in_within`]).
Project::check_import_json(&text, Some(dir))?;
if dir.exists() {
return Err(format!("{}: the folder is already there", dir.display()));
}
Expand Down Expand Up @@ -1910,9 +1914,14 @@ fn read_manifest(bytes: &[u8]) -> Vec<String> {
/// photos stay usable after opening a recovery copy, which has no unpack directory of its own.
/// References that cannot store an absolute path are left relative and reported on open. A package
/// that went out from home has the rows it gives taken (`Project::given`), for
/// `offline.keepRows` to keep on this device.
pub(crate) fn project_in(text: &str, dir: &Path) -> Result<Project, String> {
let mut project = Project::from_import_json(text, Some(dir))?;
/// `offline.keepRows` to keep on this device. What the project names is held within `reach` before
/// anything it names is read ([`Project::from_import_json_within`]).
pub(crate) fn project_in_within(
text: &str,
dir: &Path,
reach: crate::render::rustgis_tiles::address::Reach,
) -> Result<(Project, crate::received::Named), String> {
let (mut project, named) = Project::from_import_json_within(text, Some(dir), reach)?;
let photos = std::path::absolute(dir.join(PHOTOS)).map_err(|e| e.to_string())?;
let mut relative = 0_usize;
// Photos from home that keep their names there, the unpack folder's name not being text.
Expand Down Expand Up @@ -2002,7 +2011,13 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result<Project, String> {
),
));
}
Ok(project)
Ok((project, named))
}

/// [`project_in_within`] for a package of the user's own.
#[cfg(test)]
pub(crate) fn project_in(text: &str, dir: &Path) -> Result<Project, String> {
project_in_within(text, dir, crate::render::rustgis_tiles::address::Reach::Local).map(|(p, _)| p)
}

/// Removes the offline areas past the first `had` of this project: those a field package just made,
Expand Down
60 changes: 51 additions & 9 deletions crates/engine/src/cmd/geolibre.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Opens a GeoLibre project as a new map, resolving sources through existing commands.
use super::ps;
use crate::render::rustgis_tiles::address::Reach;
use crate::{CmdResult, CommandSpec as C, Session};
use rustgis_map::geolibre::{self, Report, array, boolean, number, string};
use serde_json::{Value, json};
Expand All @@ -11,9 +12,14 @@ pub fn commands() -> Vec<C> {
)]
}

/// Reads at most 64 MiB, before decoding or parsing hostile project data.
fn project_text(p: &Value) -> Result<String, String> {
/// Reads at most 64 MiB, before decoding or parsing hostile project data. Returns the text and,
/// for one downloaded from `url`, the reach it was read at.
fn project_text(p: &Value) -> Result<(String, Option<Reach>), String> {
use std::io::Read;
#[cfg(not(target_arch = "wasm32"))]
let mut read_at = None;
#[cfg(target_arch = "wasm32")]
let read_at = None;
let bytes = if let Some(data) = ps(p, "data") {
if data.len() > geolibre::MAX_TEXT / 3 * 4 + 4 {
return Err("GeoLibre data exceeds 64 MiB".into());
Expand All @@ -24,14 +30,25 @@ fn project_text(p: &Value) -> Result<String, String> {
if text.len() > geolibre::MAX_TEXT {
return Err("GeoLibre text exceeds 64 MiB".into());
}
return Ok(text.into());
return Ok((text.into(), None));
} else if let Some(url) = ps(p, "url") {
if !rustgis_map::tiles::is_web(url) {
return Err("url must be http:// or https://".into());
}
#[cfg(not(target_arch = "wasm32"))]
{
crate::render::rustgis_tiles::cache::download_blocking_limited(&geolibre::download_url(url), geolibre::MAX_TEXT)?
use crate::render::rustgis_tiles::cache;
let url = geolibre::download_url(url);
let fetched = cache::download_blocking_with_origin_within(
&url,
geolibre::MAX_TEXT,
cache::BLOCKING_TIMEOUT,
&[],
cache::ceiling_for(&url),
)
.map_err(cache::large_file_hint)?;
read_at = Some(fetched.origin.reach());
fetched.bytes
}
#[cfg(target_arch = "wasm32")]
{
Expand All @@ -51,7 +68,8 @@ fn project_text(p: &Value) -> Result<String, String> {
if bytes.len() > geolibre::MAX_TEXT {
return Err("GeoLibre project exceeds 64 MiB".into());
}
String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON".into())
let text = String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON".to_string())?;
Ok((text, read_at))
}

/// Parses before mutating the session; an unreadable layer is noted and the others continue.
Expand All @@ -68,9 +86,15 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult {
}
return s.request_import_url(&q);
}
let text = project_text(p)?;
let (text, read_at) = project_text(p)?;
let mut report = Report::default();
let project = geolibre::read_project(&text, &mut report)?;
// What it names reaches no wider than where it came from ([`Session::file_reach`]): held
// before any of it is read.
let reach = read_at.map_or_else(|| s.file_reach(p), |read| s.file_reach(p).min(read));
let held = reach == Reach::Public;
let addresses = std::iter::once(project.basemap.as_str()).chain(project.layers.iter().map(source_address));
let named = crate::received::hold(addresses, reach);
if cfg!(target_arch = "wasm32") || s.leave_downloads {
ensure_download_capacity(s, &project.layers, cfg!(target_arch = "wasm32"))?;
}
Expand Down Expand Up @@ -112,7 +136,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult {
let requests = s.url_requests.len();
let folder = group_look(&group_index, string(record, "groupId"));
let mut layer_report = Report::default();
let completed = match add_layer(s, record, dir.as_deref(), &mut layer_report, folder) {
let completed = match add_layer(s, record, dir.as_deref(), &mut layer_report, folder, held) {
Ok(Added::Feature(id)) => {
added.push(name.to_string());
order.push(id);
Expand Down Expand Up @@ -169,6 +193,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult {
s.map_mut().camera = project.camera;
s.map_mut().bookmarks = project.bookmarks;
let skipped = project.layers.len().saturating_sub(added.len());
named.say(s, &format!("the GeoLibre project '{}'", project.name));
s.notify(
format!(
"Imported {} of {} GeoLibre layers; {} drawn differently, {skipped} left out (see the import's notes)",
Expand Down Expand Up @@ -257,7 +282,10 @@ enum Added {

/// Adds data or tiles, retaining the original layer's presentation. Tile layers have their own
/// order in RustGIS, so mixing them with features is explicitly reported.
fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, folder: (bool, f64)) -> Result<Added, String> {
/// `held`: what the project names reaches only the internet, as a document read from there
/// ([`crate::received::hold`] recorded its addresses so), and a URL layer is added as one such a
/// document names.
fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, folder: (bool, f64), held: bool) -> Result<Added, String> {
#[cfg(not(target_arch = "wasm32"))]
let _ = folder;
let name = string(r, "name");
Expand Down Expand Up @@ -307,7 +335,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report,
let mut saved = r.clone();
saved["visible"] = json!(boolean(r, "visible", true) && folder.0);
saved["opacity"] = json!(number(r, "opacity", 1.0).clamp(0.0, 1.0) * folder.1);
s.request_import_url(&json!({"url":address,"whole":true,"name":name,"geolibreLayer":{"token":token,"record":saved}}))?;
let mut q = json!({"url":address,"whole":true,"name":name,"geolibreLayer":{"token":token,"record":saved}});
if held {
q["fromDocument"] = json!(true);
}
s.request_import_url(&q)?;
report.approximated(name, "MBTiles archive is downloading; wait before saving");
}
report.approximated(name, "tile overlays draw above feature layers; tile vector styling uses RustGIS defaults");
Expand Down Expand Up @@ -379,6 +411,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report,
}
}
q["geolibreLayer"] = json!({"token":token,"record":r});
// Added, when it lands, as an address a document read from the internet named: never
// taken as the user's own, which would lift the hold.
if held {
q["fromDocument"] = json!(true);
}
s.request_import_url(&q)?;
report.approximated(name, "URL data is downloading; its saved style is applied when the download completes");
return Ok(Added::Feature(id));
Expand All @@ -394,6 +431,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report,
}
s.run_part("layer.addZarr", &q)?
} else {
// Added as an address a document read from the internet named: never taken as the
// user's own, which would lift the hold.
if remote && held {
q["fromDocument"] = json!(true);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
s.run_part(if remote { "layer.addUrl" } else { "layer.addData" }, &q)?
}
};
Expand Down
31 changes: 21 additions & 10 deletions crates/engine/src/cmd/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ pub fn commands() -> Vec<C> {
.params(r#"{"layer"?, "path": "*.rgislyr"}"#),
C::new("layer.addLayerFile", "Add Layer File", "Home › Add", |s, p| {
let text = read_text(p)?;
super::layer::add_layer_text(s, &text)
let reach = s.file_reach(p);
super::layer::add_layer_text_within(s, &text, reach)
}).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.params(r#"{"path"?: "*.rgislyr", "text"?: layer file JSON, "data"?: base64 file}"#),
// Styles.
Expand Down Expand Up @@ -225,7 +226,9 @@ pub fn commands() -> Vec<C> {
let name = super::within("name", "a project's name", name, 200)?;
let text = read_text(p)?;
super::connections::clear_active();
let mut proj = match Project::from_import_json(&text, None) {
// What it names is held within this as it is read, before anything it names is read.
let reach = s.file_reach(p);
let (mut proj, named) = match Project::from_import_json_within(&text, None, reach) {
Ok(proj) => proj,
Err(error) => {
super::connections::restore_active(s);
Expand All @@ -234,6 +237,7 @@ pub fn commands() -> Vec<C> {
};
proj.name = name;
super::project::reset_to(s, proj);
named.say(s, "the template");
s.path = None;
super::connections::resolve_project(s);
super::connections::note_waiting(s);
Expand Down Expand Up @@ -526,7 +530,10 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
crate::project::check_format(&text, "map file, project or package")?;
let dir = ps(p, "path").and_then(|path| std::path::absolute(path).ok()).and_then(|p| p.parent().map(Path::to_path_buf));
super::connections::clear_active();
let maps: Vec<Map> = match serde_json::from_str::<Map>(&text) {
// What they name is held within this before anything they name is read: a map file's before
// its maps are added, a project's as it is read.
let reach = s.file_reach(p);
let (maps, named): (Vec<Map>, _) = match serde_json::from_str::<Map>(&text) {
Ok(mut m) => {
if crate::project::ensure_map_imports_complete(&m).is_err() {
super::connections::restore_active(s);
Expand All @@ -544,10 +551,11 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
for notice in crate::project::picture_notices(&m.layers, []) {
s.notify_text(notice, false);
}
vec![m]
let named = crate::received::hold(m.addresses_mut(), reach);
(vec![m], named)
}
Err(_) => match Project::from_import_maps_json(&text, dir.as_deref(), MAX_IMPORTED_MAPS) {
Ok(mut project) => {
Err(_) => match Project::from_import_maps_json_within(&text, dir.as_deref(), MAX_IMPORTED_MAPS, reach) {
Ok((mut project, named)) => {
let parts = [crate::project::ReadPart::Labels, crate::project::ReadPart::Diagrams, crate::project::ReadPart::Maps];
for notice in project.take_read_notices(&parts) {
s.notify_text(notice, false);
Expand All @@ -557,14 +565,15 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
for (_, notice) in crate::project::label_losses::hidden(imported) {
s.notify(notice, false);
}
project.maps
(project.maps, named)
}
Err(error) => {
super::connections::restore_active(s);
return Err(not_a(error, "map file, project or package"));
}
},
};
named.say(s, "the map file");
let mut names = Vec::new();
let first_map = s.project.maps.len();
let mut detached_offline = 0;
Expand Down Expand Up @@ -706,11 +715,13 @@ fn import_styles(s: &mut Session, p: &Value) -> CmdResult {
}
m.layers
} else {
// A project parse opens sources even though this import only takes their styles.
// A project parse opens sources even though this import only takes their styles: held
// within where the file came from first ([`Session::file_reach`]).
super::connections::clear_active();
let project = Project::from_import_json(&text, None);
let project = Project::from_import_json_within(&text, None, s.file_reach(p));
super::connections::restore_active(s);
let mut project = project.map_err(|e| not_a(e, "layer file, map file or project"))?;
let (mut project, named) = project.map_err(|e| not_a(e, "layer file, map file or project"))?;
named.say(s, "the style file");
// Styles take the layers' renderers and labels, not their diagrams or the layouts.
for notice in project.take_read_notices(&[crate::project::ReadPart::Labels]) {
s.notify_text(notice, false);
Expand Down
23 changes: 21 additions & 2 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4669,8 +4669,15 @@ fn add_layer_file(s: &mut Session, path: &str) -> CmdResult {
add_layer_text(s, &text)
}

/// Adds a layer from a layer file's JSON.
/// Adds a layer from a layer file's JSON, read from the user's own disk or given by the user.
pub(crate) fn add_layer_text(s: &mut Session, text: &str) -> CmdResult {
let reach = s.file_reach(&Value::Null);
add_layer_text_within(s, text, reach)
}

/// [`add_layer_text`] for a layer file whose addresses reach no wider than `reach`
/// ([`Session::file_reach`]).
pub(crate) fn add_layer_text_within(s: &mut Session, text: &str, reach: crate::render::rustgis_tiles::address::Reach) -> CmdResult {
crate::project::check_format(text, "layer file")?;
let mut layer: rustgis_map::Layer = serde_json::from_str(text).map_err(|e| format!("not a RustGIS layer file: {e}"))?;
if layer.dataset.source.as_deref().is_some_and(|source| source.starts_with("geolibre-pending:")) {
Expand All @@ -4685,6 +4692,9 @@ pub(crate) fn add_layer_text(s: &mut Session, text: &str) -> CmdResult {
// A binding in a file is no authority to use a login here.
crate::s3_connections::clear_bindings(layer.addresses_mut());
crate::project::clear_login_bindings(layer.addresses_mut());
// Before anything it names is read (the repair below reads it).
let named = crate::received::hold(layer.addresses_mut(), reach);
named.say(s, &format!("the layer file '{}'", layer.name));
// A fresh id and a unique name in this map; the rest goes through project repair.
let base = layer.name.clone();
let mut i = 1;
Expand Down Expand Up @@ -6870,12 +6880,21 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult {
let bounds = if service { super::service::bounds_of(p.get("bounds"))? } else { None };
let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such download (it was dropped when another project opened)")?;
let (_, bytes) = s.downloaded.remove(i);
let read_at = s.downloaded_reach.iter().position(|(d, _)| *d == id).map(|i| s.downloaded_reach.remove(i).1);
if p.get("geolibreProject").and_then(Value::as_bool) == Some(true) {
if bytes.len() > rustgis_map::geolibre::MAX_TEXT {
return Err("GeoLibre project exceeds 64 MiB".into());
}
let text = String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON")?;
return s.run_part("project.importGeolibre", &json!({"text":text}));
// Received from where it was read: what it names reaches no wider ([`Session::file_reach`]).
// The app says where its download connected ([`Session::download_read_at`]; the browser's
// fetch, by its address's name); one that doesn't say reaches only the internet.
use crate::render::rustgis_tiles::{address::Reach, cache};
let reach = read_at.unwrap_or(Reach::Public).min(cache::ceiling_for(&url));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reach orders Public < Local < Forbidden (crates/tiles/src/address.rs), so min picks the narrower reach. read_at.unwrap_or(Reach::Public) is therefore always Public when no reach was observed, and .min(cache::ceiling_for(&url)) can never widen it. The result: a GeoLibre project downloaded in the browser (where download_read_at is never called) is always held to the internet, whatever its address. The comment at 6889-6891 and the PR description both say the browser's reach "comes from the address's name", which this line does not do. The effect is narrowing only (local layers of such a project are held and say so), but the documented behaviour and the code disagree. Either compute the name-based reach here (for example address::reach(&url), with the same min direction) and keep the comment true, or correct the comment and the PR description to say a browser download without an observed reach is held.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The browser does call download_read_at. The download start (RustGisApp::add_url, where geolibreProject takes download_detailed_with_origin) and the landing loop (poll_data_downloads, which calls download_read_at before add_landed) are in crates/ui-egui/src/lib.rs with no cfg, so the web app runs them too. There, download_detailed_with_origin gives Origin::named, the reach judged from the address's name (address::reach). So a browser download of http://localhost:8080/p.json lands with Local and is read as the user's own, as the comment says. unwrap_or(Reach::Public) applies only when no front end said where the download connected. That is fail-closed on purpose: CodeRabbit asked (r4680581410) that Local never be taken from the name alone in that case. The comment and the PR description describe both cases as the code does, so nothing changes here.

let was = s.receiving(Some(reach));
let r = s.run_part("project.importGeolibre", &json!({"text":text}));
s.receiving(was);
return r;
}
if p.get("geolibreLayer").is_some() {
let name = if b(p, "geolibreZarr") == Some(true) { "zarr.tif".into() } else { url_file_name(&url, &bytes)? };
Expand Down
Loading
Loading