Skip to content
3 changes: 3 additions & 0 deletions crates/engine/src/cmd/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,9 @@ mod tests {
("38Z 444141 3684706", GridError::Polar),
("38ZMB4414084706", GridError::Polar),
("99X 1 2", GridError::Zone),
// A bad zone is judged before a polar or unknown band.
("0AAA", GridError::Zone),
("61AVE", GridError::Zone),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
("33U 1000000 5523456", GridError::OutsideZone),
] {
assert_eq!(read_grid_reference(q), Err(why), "{q}");
Expand Down
7 changes: 6 additions & 1 deletion crates/engine/src/cmd/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -327,9 +327,14 @@ pub fn map_pdf(s: &mut Session, dpi: f64) -> Result<Vec<u8>, String> {
let (w, h) = (mm(view.width), mm(view.height));
let page = if drawing.overflowed() {
Comment thread
giswqs marked this conversation as resolved.
Resolved
// Too large for vectors: the map as one picture, as it is drawn on screen.
super::layout::pictured_notices(s, &[], &[1]);
let png = rustgis_render::render_png(s.map_mut(), &view)?;
let pm = rustgis_render::decode_png(&png).ok_or("could not draw the map")?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Said once the picture is drawn. The budget counts the drawing's pictures (rasters,
// tiles) as well as its shapes.
let (mb, items) = (rustgis_render::vector::MAX_COST >> 20, rustgis_render::vector::MAX_ITEMS / 1_000_000);
s.warn(format!(

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.

Re-raising the earlier test-coverage point, because the code here has changed but the gap remains. The new overflow notice has a clean-input test (the_map_pdf_keeps_vectors_and_says_nothing_with_or_without_colour_vision), but nothing forces an overflow and checks that this notice is given once. That is the lossy half of "Test both ways".

What is new: the earlier suggestion to use rustgis_render::vector::TEST_MAX_COST will not compile from the engine crate. It is declared pub(crate) under #[cfg(test)] in crates/render/src/vector.rs, so only render's own tests can set it. Options: expose a #[doc(hidden)] setter for it behind a test-only feature, or cover the overflow notice from a render-side test that calls into the engine path. Either way, the test should assert the notice text appears exactly once when the drawing overflows.

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.

Agreed the overflow half is untested; the options named (a doc-hidden setter behind a test-only feature on rustgis-render) add a cross-crate test hook for one notice, which is a test-infrastructure change rather than a fix. Left for the release quality pass.

"The map is drawn as one picture, not vectors: kept as vectors, it would pass the drawing limit ({mb} MB or {items} million items)"
));
Comment thread
giswqs marked this conversation as resolved.
Resolved
rustgis_render::pdf::Page::new(&pm, w, h)
} else {
rustgis_render::pdf::Page::drawing(drawing, w, h)
Expand Down
25 changes: 24 additions & 1 deletion crates/engine/src/cmd/stac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,9 @@ fn add_asset(s: &mut Session, p: &Value) -> CmdResult {
let p = bound.as_ref();
let i = item(p)?;
let (key, href) = i.asset_href(ps(p, "asset"))?;
// Codes for a failed retrieval (JAXA Earth's `dn.error`), which a data cube skips but a
// single file draws as values: of the asset `asset_href` picked, by the same selector.
let codes = i.pick(ps(p, "asset")).ok().map(|a| (a.invalid.clone(), a.codes_unread)).unwrap_or_default();
let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("{} {key}", i.id));
// A Planetary Computer asset is read with its storage container's token.
#[cfg(not(target_arch = "wasm32"))]
Expand All @@ -258,7 +261,27 @@ fn add_asset(s: &mut Session, p: &Value) -> CmdResult {
if let Some(connection) = p.get("connection") {
add["connection"] = connection.clone();
}
super::layer::add_url(s, &add)
let added = super::layer::add_url(s, &add)?;
match codes {
(_, true) => s.warn(format!(
Comment thread
giswqs marked this conversation as resolved.
Resolved
"{name}: its metadata's codes for a failed retrieval (je:rasters dn.error) couldn't be read whole (not a list of numbers, or too many), so the map draws any such codes in the file as values"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
)),
(invalid, false) if !invalid.is_empty() => {
// The first few, large ones (a float's lowest, -3.4e38) in exponent form.
const SHOWN: usize = 5;
let code = |v: &f64| if v.abs() >= 1e6 { format!("{v:e}") } else { v.to_string() };
let mut listed = invalid.iter().take(SHOWN).map(code).collect::<Vec<_>>().join(", ");
if invalid.len() > SHOWN {
listed.push_str(&format!(" and {} more", invalid.len() - SHOWN));
}
s.warn(format!(
"{name}: its metadata marks failed retrievals with {} code(s) ({listed}), which the map draws as values",
invalid.len()
));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
_ => {}
}
Ok(added)
}

/// The most items a data cube on the time slider takes (its search is paged up to this).
Expand Down
14 changes: 5 additions & 9 deletions crates/engine/src/service_logins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ pub const NOT_THIS_SESSION: &str = "This request's login does not belong to this
pub const CHOOSE_CONNECTION: &str = "Several saved connections match this address. Choose a connection explicitly.";
/// A `connection` that is not a saved web-service connection's id.
pub const NO_SUCH_CONNECTION: &str = "No saved web-service connection with this id.";
/// A request's `connection` that isn't text.
pub const CONNECTION_TEXT: &str = "connection must be a saved web-service connection id (text)";
/// The commands that add layers from a service, and so may record the connection they came from
/// (their `connection` parameter, or the connection whose login their address is read with).
pub const ADD_COMMANDS: &[&str] = &[
Expand Down Expand Up @@ -364,7 +366,7 @@ pub fn request_params<'a>(s: &mut Session, p: &'a Value) -> Result<std::borrow::
None | Some(Value::Null) => None,
Some(Value::String(id)) if id.trim().is_empty() => None,
Some(Value::String(id)) => Some(id.as_str()),
Some(_) => return Err("connection is a saved web-service connection id.".into()),
Some(_) => return Err(CONNECTION_TEXT.into()),
};
if id.is_none() && (s.web_logins.anonymous || p.get("anonymous").and_then(Value::as_bool) == Some(true)) {
// An address bound to a login is no authority for it here either.
Expand Down Expand Up @@ -801,16 +803,10 @@ fn named(s: &Session, params: &Value) -> Result<Option<Connection>, String> {
None | Some(Value::Null) => Ok(None),
Some(Value::String(id)) if id.trim().is_empty() => Ok(None),
Some(Value::String(id)) => {
let c = s
.connections
.connections
.iter()
.find(|c| &c.id == id)
.filter(|c| is_service(c))
.ok_or("connection is the id of a saved web-service connection (connection.list)")?;
let c = s.connections.connections.iter().find(|c| &c.id == id).filter(|c| is_service(c)).ok_or(NO_SUCH_CONNECTION)?;
Ok(Some(c.clone()))
}
Some(_) => Err("connection is the id of a saved web-service connection (connection.list)".into()),
Some(_) => Err(CONNECTION_TEXT.into()),
}
}

Expand Down
56 changes: 56 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15961,6 +15961,62 @@ fn stac_search_and_assets() {
assert!(s.run("stac.addAsset", &json!({"item": {"type": "Feature", "id": "x", "assets": {}}})).is_err());
}

/// A single STAC asset whose metadata names codes for a failed retrieval (JAXA Earth's
/// `je:rasters` `dn.error`) draws them as values, and says so; an asset without them says nothing.
#[test]
fn a_stac_asset_with_retrieval_codes_says_they_draw_as_values() {
let item = |id: &str, extra: &str| {
format!(
r#"{{"type": "Feature", "id": "{id}", "collection": "c", "bbox": [7, 46, 8, 47], "geometry": null,
"properties": {{"datetime": "2024-06-02T10:30:00Z"}},
"assets": {{"places": {{"href": "{{base}}/data/places.geojson", "type": "application/geo+json", "roles": ["data"]{extra}}}}}}}"#
)
};
let geojson = r#"{"type": "FeatureCollection", "features": [{"type": "Feature", "properties": {"n": 1}, "geometry": {"type": "Point", "coordinates": [7.5, 46.5]}}]}"#;
let base = serve_routes(
vec![
("/items/clean", item("clean", "")),
("/items/coded", item("coded", r#", "je:rasters": {"dn": {"error": [5.0, 7.0]}}"#)),
("/items/unread", item("unread", r#", "je:rasters": {"dn": {"error": [5.0, "x"]}}"#)),
("/data/places.geojson", geojson.to_string()),
],
6,
);
let mut s = Session::new(Project::default());
let mark = s.notice_mark();
s.run("stac.addAsset", &json!({"url": format!("{base}/items/clean"), "name": "Clean"})).unwrap();
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert!(!said.iter().any(|t| t.contains("failed retrieval")), "clean input tells nothing: {said:?}");
let mark = s.notice_mark();
s.run("stac.addAsset", &json!({"url": format!("{base}/items/coded"), "name": "Coded"})).unwrap();
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
assert!(said.iter().any(|t| t.contains("Coded: its metadata marks failed retrievals with 2 code(s) (5, 7)")), "{said:?}");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Codes that can't be read whole (a word among them) say so.
let mark = s.notice_mark();
s.run("stac.addAsset", &json!({"url": format!("{base}/items/unread"), "name": "Unread"})).unwrap();
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert!(
said.iter().any(|t| t.contains("Unread: its metadata's codes for a failed retrieval (je:rasters dn.error) couldn't be read whole")),
Comment thread
giswqs marked this conversation as resolved.
Resolved
"{said:?}"
);
}

/// The Print Map PDF keeps a map within the vector budget as vectors and says nothing, a
/// colour-vision view too (exports don't simulate it, so it needn't be a picture).
#[test]
fn the_map_pdf_keeps_vectors_and_says_nothing_with_or_without_colour_vision() {
let mut s = Session::new(crate::sample::world_project());
for mode in ["normal", "deuteranopia"] {
s.run("map.colorVision", &json!({"mode": mode})).unwrap();
let mark = s.notice_mark();
let pdf = crate::cmd::share::map_pdf(&mut s, 96.0).unwrap();
let said: Vec<String> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect();
assert!(!said.iter().any(|t| t.contains("one picture")), "{mode}: {said:?}");
let text = String::from_utf8_lossy(&pdf);
assert!(!text.contains("/Subtype /Image"), "{mode}: the map as vectors, not a picture");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

/// Directions through a routing server of one's own (a local Valhalla answer here): the route
/// and its steps as layers; the app's answer can be passed in instead, and nothing is fetched.
#[test]
Expand Down
5 changes: 3 additions & 2 deletions crates/geom/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ pub const MERCATOR_R: f64 = 6_378_137.0;
/// Latitude limit of Web Mercator.
pub const MAX_LAT: f64 = 85.051_128_78;
/// How near ±90° (degrees) a latitude counts as the pole: about a centimeter, more than geometry
/// operations' rounding moves a pole vertex (around 1e-8°). For the polar edits and the features
/// meeting at a pole that build on this (#1033); here only the tests use it.
/// operations' rounding moves a pole vertex (around 1e-8°). The engine's polar edits
/// (`cmd/design.rs`) and analysis's topology, conversion and network code use it to find the
/// features meeting at a pole (#1033).
pub const POLE_TOLERANCE: f64 = 1e-7;
/// Screen pixel size assumed when converting resolution to a map scale (0.28 mm, OGC).
pub const PIXEL_M: f64 = 0.000_28;
Expand Down
6 changes: 6 additions & 0 deletions crates/geom/src/utm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,10 @@ pub fn parse_mgrs(text: &str) -> Result<Mgrs, GridError> {
}
_ => return Err(GridError::Digits),
};
// The zone first, as `parse_utm` does: `0AAA` names a bad zone, not a polar reference.
if !(1..=60).contains(&zone) {
return Err(GridError::Zone);
}
let band = band_letter(band)?;
let [column, row] = letters;
let digit = |s: &str| if s.is_empty() { Ok(0) } else { s.parse::<u32>().map_err(|_| GridError::Digits) };
Expand Down Expand Up @@ -976,6 +980,8 @@ mod tests {
("123SMB", GridError::Syntax),
("0SMB", GridError::Zone),
("61SMB", GridError::Zone),
("0AAA", GridError::Zone),
("61AVE", GridError::Zone),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// The zone is judged once the text is written as a reference: a number past 60
// before a word is ordinary text.
("75 Main St", GridError::Syntax),
Expand Down
5 changes: 3 additions & 2 deletions crates/map/src/projection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1228,8 +1228,9 @@ mod tests {
assert!(e.contains("labrd"), "{e}");
// proj4rs 0.3 added Cassini, the polyconic, Equal Earth and the oblique Mercator: their
// codes are accepted (EPSG:5880's polyconic, whose refusal was #208), and draw where PROJ
// does: 54°W 10°S lands at (5 000 000, 8 894 145.167) in pyproj 3.8.0's EPSG:5880, its
// false easting less a million-odd metres.
// does: 54°W 10°S lands at (5 000 000, 8 894 145.167) in pyproj 3.8.0's EPSG:5880. On the
// central meridian x is the false easting itself; y is the false northing (10 000 000)
// less a million-odd metres.
for ok in ["EPSG:5880", "EPSG:2057", "EPSG:3068", "EPSG:8858"] {
crate::Projection::from_code(ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
}
Expand Down
46 changes: 45 additions & 1 deletion crates/render/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,16 @@ impl Canvas {
pub fn place(&mut self, child: Canvas, transform: Transform, opacity: f32, blend: Blend, clip: Option<Clip>) {
if self.rec.is_none() || !child.is_recording() {
let paint = PixmapPaint { opacity, blend_mode: crate::blend_mode(blend), quality: tiny_skia::FilterQuality::Bilinear };
self.pixels().draw_pixmap(0, 0, child.pm.as_ref(), &paint, transform, None);
// Cut to `clip` as the recording is: a mask the size of these pixels.
let mask = match &clip {
Some(c) => {
let Some(mut m) = Mask::new(self.pm.width(), self.pm.height()) else { return };

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.

Low confidence, quality/never-silent: else { return } drops the child with no trace if the mask can't be made. I don't think this is reachable today: self.pm already exists at this size, and I expect tiny-skia's Mask::new to accept any size Pixmap::new does (I did not check tiny-skia's source here). If that holds, state the invariant in a comment so a future size change doesn't silently hide the placed picture. This is a small point; it can wait for the release quality pass.

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.

Not reachable: the mask is made at the size of a pixmap that already exists, and tiny-skia's Mask::new accepts the sizes Pixmap::new does. Stating the invariant in a comment is left for the release quality pass.

m.fill_path(&c.path, c.rule, true, c.transform);
Some(m)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
None => None,
};
self.pixels().draw_pixmap(0, 0, child.pm.as_ref(), &paint, transform, mask.as_ref());
return;
}
let Some(drawing) = child.into_drawing() else { return };
Expand Down Expand Up @@ -394,6 +403,41 @@ mod tests {
assert!(stroke.width == 2.0 && path.segments().filter(|s| matches!(s, tiny_skia::PathSegment::MoveTo(_))).count() == 10);
}

#[test]
fn placing_pixels_keeps_inside_the_clip() {
let mut c = Canvas::new(40, 20).unwrap();
let mut child = c.sub(40, 20).unwrap();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
child.pixels().fill(Color::from_rgba8(200, 0, 0, 255));
let clip = Clip {
path: PathBuilder::from_rect(Rect::from_xywh(0.0, 0.0, 20.0, 20.0).unwrap()),
rule: FillRule::Winding,
transform: Transform::identity(),
};
c.place(child, Transform::identity(), 1.0, Blend::Normal, Some(clip));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let pm = c.into_pixmap();
assert_eq!(pm.pixel(5, 10).map(|p| p.alpha()), Some(255), "inside the clip");
assert_eq!(pm.pixel(30, 10).map(|p| p.alpha()), Some(0), "outside the clip");
Comment thread
giswqs marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

#[test]
fn placing_pixels_cuts_to_the_clip_where_its_own_transform_puts_it() {
let mut c = Canvas::new(40, 20).unwrap();
let mut child = c.sub(10, 20).unwrap();
child.pixels().fill(Color::from_rgba8(200, 0, 0, 255));
// The clip covers x 20 to 30, the child x 15 to 25: only 20 to 25 is drawn.
let clip = Clip {
path: PathBuilder::from_rect(Rect::from_xywh(0.0, 0.0, 10.0, 20.0).unwrap()),
rule: FillRule::Winding,
transform: Transform::from_translate(20.0, 0.0),
};
c.place(child, Transform::from_translate(15.0, 0.0), 1.0, Blend::Normal, Some(clip));
let pm = c.into_pixmap();
let alpha = |x| pm.pixel(x, 10).map(|p| p.alpha());
assert_eq!(alpha(22), Some(255), "the child inside the clip");
assert_eq!(alpha(17), Some(0), "the child outside the clip");
assert_eq!(alpha(27), Some(0), "the clip past the child");
}

#[test]
fn a_label_keeps_its_halo_as_a_shape_and_its_text_once() {
let label = crate::PlacedLabel {
Expand Down
11 changes: 8 additions & 3 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3159,9 +3159,14 @@ fn render_frame(
record: bool,
) -> Option<RenderOutput> {
let (w, h) = view.pixel_size();
// Kept as vectors (`record`) on the CPU, for a flat frame without view effects (a pixel
// filter over the whole frame); anything else draws its pixels.
let record = record && !backend.is_gpu() && !map.projection.is_globe() && map.view.effects.is_none();
// Kept as vectors (`record`) on the CPU, for a flat frame without view effects or a
// colour-vision simulation it applies (pixel filters over the whole frame; an export,
// `full_res_rasters`, never simulates colour vision); anything else draws its pixels.
let record = record
&& !backend.is_gpu()
&& !map.projection.is_globe()
&& map.view.effects.is_none()
&& (full_res_rasters || map.view.color_vision == rustgis_map::view::ColorVision::Normal);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let mut pm = if record { Canvas::recording(w, h)? } else { Canvas::new(w, h)? };
// Streamed layers read the view: in the background for the screen, in place for an export
// (the full-resolution render), which waits for them; only the layers drawn at the view's
Expand Down
1 change: 1 addition & 0 deletions crates/ui-egui/src/connectionui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ pub(crate) fn translated(e: &str) -> String {
web::NOT_THIS_SESSION => tl!("This request's login does not belong to this session."),
web::CHOOSE_CONNECTION => tl!("Several saved connections match this address. Choose a connection explicitly."),
web::NO_SUCH_CONNECTION => tl!("No saved web-service connection with this id."),
web::CONNECTION_TEXT => tl!("connection must be a saved web-service connection id (text)"),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
other => other,
}
.to_string()
Expand Down
Loading