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
73 changes: 61 additions & 12 deletions crates/engine/src/cmd/qgis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,18 @@ const MARKER_READ_BYTES: usize = if cfg!(test) { 1 << 10 } else { rustgis_map::s

/// The importer's reader of raster image markers' images ([`qgis::ReadImage`]): [`marker_image`]
/// within [`MARKER_READ_BYTES`] for the import. On the import's thread, as the rest of it is
/// (`import_project` and `import_style` say why): each read is one file of at most 1.5 MiB, only
/// a regular file is opened (a pipe or a device would wait for a writer), and the bound caps them
/// all.
/// (`import_project` says why; `import_style` reads on a thread of its own in the desktop app,
/// [`style_ahead`]): each read is one file of at most 1.5 MiB, only a regular file is opened (a
/// pipe or a device would wait for a writer), and the bound caps them all. Each looks at Cancel.
fn marker_images() -> impl FnMut(&str) -> Result<(String, f32), &'static str> {
let mut read = 0;
move |source| {
// Under a Cancel (a style read on a thread of its own, a project imported by a script or model)
// a Cancel stops the images here; the import notes each as skipped, so its caller looks at
// Cancel again once the parse is done and gives the cancelled error. With none, nothing is asked.
if rustgis_data::progress::check().is_err() {
return Err("cancelled");
}
if read >= MARKER_READ_BYTES {
return Err("past the bytes of images an import reads");
}
Expand Down Expand Up @@ -160,6 +166,9 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult {
let dir = ps(p, "dir").filter(|d| !d.trim().is_empty()).map(str::to_string).or_else(|| file_dir(p));
let mut report = Report::default();
let project = qgis::read_project(&text, dir.as_deref().unwrap_or_default(), &mut marker_images(), &mut report)?;
// A script or model runs this under its Cancel: one that came during the images was noted as a
// skipped image, and no layer is added for a cancelled run.
rustgis_data::progress::check().map_err(|e| e.to_string())?;
// A map of its own, named as the project.
let name = if project.title.is_empty() { "QGIS project" } else { project.title.as_str() };
s.run_part("map.new", &json!({"name": name}))?;
Expand Down Expand Up @@ -1991,20 +2000,60 @@ fn notify_report(s: &mut Session, report: &Report) {
}
}

/// Imports a QGIS style onto a layer. On the thread that runs it: the style import isn't among
/// the commands whose reads the app makes on a thread first ([`super::reads`]), as it wasn't
/// before it read marker images. Reading the style and its images there, with Cancel, is its own
/// change. Its work is bounded by the style: one file of at most [`MAX_FILE`] bytes, its XML
/// A QGIS style file read and parsed: the style and what it couldn't carry over.
type StyleRead = Result<(qgis::Style, Report), String>;

/// Reads and parses the style file `p` names (or gives) for the layer called `layer`: its raster
/// image markers' relative files start from the style file's folder.
fn read_style_file(p: &Value, layer: &str) -> StyleRead {
let text = qgis_text(p)?;
rustgis_data::progress::check().map_err(|e| e.to_string())?;
let mut report = Report::default();
let style = qgis::read_style(&text, layer, &file_dir(p).unwrap_or_default(), &mut marker_images(), &mut report)?;
// A Cancel that came during the images was noted as a skipped image: the read is cancelled.
rustgis_data::progress::check().map_err(|e| e.to_string())?;
Ok((style, report))
}

/// A style read ahead: for the layer it was read for, as it was called then.
struct StyleAhead {
layer: String,
read: StyleRead,
}

/// The key a style read ahead is taken by (see [`super::reads`]).
fn ahead_key(id: u32) -> String {
format!("style.importQgis:{id}")
}

/// The read `style.importQgis` makes before it runs in the desktop app: on a thread of its own, with
/// Cancel. A request that is wrong gives nothing, or its error: the command says why. It holds a

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.

The doc overstates what style_ahead does with a wrong request. It returns None for a request with no usable layer, and no read is placed; the command then gives its error when it runs. A read that fails (a missing or unparseable file) is not returned here at all: it is carried inside StyleAhead and given to the command on landing. Suggested wording:

Suggested change
/// Cancel. A request that is wrong gives nothing, or its error: the command says why. It holds a
/// Cancel. A request that is wrong gives nothing: no read is placed, and the command gives its error when it runs. A read that fails lands with its error. It holds a

Category: quality

/// copy of the command's own `text` or `data` (at most [`MAX_XML`] bytes or their base64) while it
/// reads, none of the layer's.
pub(crate) fn style_ahead(s: &Session, p: &Value) -> Option<super::reads::ReadWork> {
let id = s.layer_id(p).ok()?;
let layer = s.map().layer(id)?.name.clone();
let p = p.clone();
Some(super::reads::ahead("Import QGIS Style", ahead_key(id), move || StyleAhead { read: read_style_file(&p, &layer), layer }))
}

/// Imports a QGIS style onto a layer. Its reads are made before it runs where the app can make
/// them on a thread of its own ([`super::reads`]: the desktop app, with Cancel, no progress count;
/// the style is applied only when they are done, so a cancelled import leaves the layer as it was);
/// run anywhere else (the command line, a script, the browser) it reads here, on the thread that
/// runs it. Its work is bounded by the style: one file of at most [`MAX_FILE`] bytes, its XML
/// parsed within [`MAX_XML`], and its raster image markers' images within [`MARKER_READ_BYTES`],
/// each file read once and decoded once to check it (see [`marker_images`] and [`marker_image`]).
/// Cancel is looked at before each image: the file's one read and the XML's one parse don't.
fn import_style(s: &mut Session, p: &Value) -> CmdResult {
let text = qgis_text(p)?;
let id = s.layer_id(p)?;
let name = s.map().layer(id).map(|l| l.name.clone()).ok_or("no such layer")?;
let mut report = Report::default();
// Its raster image markers' relative files start from the style file's folder.
let dir = file_dir(p).unwrap_or_default();
let style = qgis::read_style(&text, &name, &dir, &mut marker_images(), &mut report)?;
// The name is the only layer input `read_style` uses, so a style read for another name is read again by the user.
let (style, mut report) = match super::reads::take::<StyleAhead>(s, &ahead_key(id)) {
Some(a) if a.layer == name => a.read?,
Some(_) => return Err("the layer was renamed while its style was read: import it again".into()),
None => read_style_file(p, &name)?,
};
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
if l.raster.is_some() {
// A style that doesn't fit leaves the raster as it was, its opacity and scale range too.
Expand Down
4 changes: 3 additions & 1 deletion crates/engine/src/cmd/reads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! delimited text or spreadsheet read whole, a ZIP or CityJSON/CityGML model's layers, the opening
//! of a large Shapefile or GeoJSON file read in place, #2446), Repair/Reload Data, Load All
//! Features, Convert To Annotation's read of a layer read in place, native models or scripts, the
//! Error Inspector's topology check (#1291), Source File State's hashing of a layer's file and Column Statistics' count of a column. [`read_ahead`]
//! Error Inspector's topology check (#1291), Source File State's hashing of a layer's file, Column Statistics' count of a column and Import QGIS Style's file and images. [`read_ahead`]
//! takes what the read needs of the session, [`ReadAhead::run`] reads on the thread, and [`read_land`]
//! runs the admitted command under its initiating owner: the command takes
//! it instead of reading again, so what it adds, says, logs and puts in Undo is the same as when
Expand Down Expand Up @@ -235,6 +235,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str)] = &[
("table.statistics", "Column Statistics"),
("data.similar", "Find Similar"),
("layer.sizeBy", "Size by Field"),
("style.importQgis", "Import QGIS Style"),
];

/// What `command`'s read is called, when it is one the app makes before the command lands
Expand Down Expand Up @@ -327,6 +328,7 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized<CommandOp>, owner: Continu
"table.statistics" => (super::table_stats::stats_ahead(s, params), None),
"data.similar" => (super::similar::ahead(s, params), None),
"layer.sizeBy" => (super::layer::size_by_ahead(s, params), None),
"style.importQgis" => (super::qgis::style_ahead(s, params), None),
// Listed in IN_BACKGROUND without a read here.
id => return Err(not_in_background(id)),
};
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/policy/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ impl Session {
| "raster.imageGrid"
| "edit.previewShapeConversion"
| "layer.sizeBy"
| "style.importQgis"
) && (!matches!(command, "edit.previewShapeConversion" | "raster.imageGrid") || self.policy_user())
|| (command == "edit.convertField" && params.get("table").is_none_or(Value::is_null))
{
Expand Down
103 changes: 103 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3528,6 +3528,109 @@ fn qgis_raster_image_markers_read_their_files_from_the_style_folder() {
}
}

/// A QGIS style's file and its raster image markers' images are read on a thread before the
/// command lands (#2620): the landing needs neither file, says what the inline import says, can be
/// undone, and a style read for a layer that was renamed meanwhile is refused. A cancelled read
/// changes nothing.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn qgis_style_import_reads_its_files_ahead() {
use cancellation::contents;
use rustgis_analysis::control::Control;
use rustgis_map::Marker;
// Removed however the test ends.
struct Dir(std::path::PathBuf);
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let guard = Dir(std::env::temp_dir().join(format!("rustgis-qgis-style-ahead-{}", std::process::id())));
let dir = guard.0.clone();
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("pins")).unwrap();
image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])).save(dir.join("pins/pin.png")).unwrap();
std::fs::write(dir.join("pins/pin.gif"), b"GIF89a").unwrap();
let qml = |files: &[&str]| {
let layers: String = files
.iter()
.map(|f| {
format!(
r#"<layer class="RasterMarker" enabled="1"><Option type="Map"><Option name="imageFile" value="{f}"/><Option name="size" value="6"/></Option></layer>"#
)
})
.collect();
format!(
r#"<qgis version="4.2.3"><renderer-v2 type="singleSymbol"><symbols><symbol type="marker" name="0" alpha="1">{layers}</symbol></symbols></renderer-v2></qgis>"#
)
};
let notes = |r: &Value| r["notes"].as_array().unwrap().iter().map(|n| n["text"].as_str().unwrap().to_string()).collect::<Vec<_>>();
let marker = |s: &Session| s.map().layer_by_name("Cities").unwrap().symbol(0).marker;
let path = dir.join("pins.qml");
let p = json!({"layer": "Cities", "path": path.to_string_lossy()});
// A clean style says nothing; a lossy one says what the inline import says, as the same notes.
for (files, said) in [(&["pins/pin.png"][..], 0), (&["pins/pin.gif"][..], 1)] {
std::fs::write(&path, qml(files)).unwrap();
let mut inline = world();
let inline_notes = notes(&inline.run("style.importQgis", &p).unwrap());
assert_eq!(inline_notes.len(), said, "{files:?}: {inline_notes:?}");
let mut s = world();
let before = marker(&s);
let ahead = crate::cmd::reads::read_ahead(&mut s, "style.importQgis", &p).unwrap();
assert!(ahead.reads(), "{files:?}: the style is read ahead");
let read = ahead.run(&Control::stoppable()).unwrap();
// Neither file is needed once read.
std::fs::remove_file(&path).unwrap();
std::fs::remove_file(dir.join("pins/pin.png")).unwrap();
let r = crate::cmd::reads::read_land(&mut s, read).unwrap();
assert_eq!(notes(&r), inline_notes, "{files:?}");
assert_eq!(marker(&s), marker(&inline), "{files:?}");
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(marker(&s), before, "{files:?}: undone");
image::RgbImage::from_pixel(8, 4, image::Rgb([200, 30, 30])).save(dir.join("pins/pin.png")).unwrap();
}
assert!(matches!(marker(&world()), Marker::Circle));
// Cancel: no change, and the read looked at Cancel.
std::fs::write(&path, qml(&["pins/pin.png"])).unwrap();
let mut s = world();
let before = contents(&s.project);
let control = Control::cancelled_once_started();
let e = crate::cmd::reads::read_ahead(&mut s, "style.importQgis", &p).unwrap().run(&control).err().unwrap();
assert!(e.contains("cancelled"), "{e}");
assert!(control.looked() > 0, "never looks at Cancel");
assert!(contents(&s.project) == before);
// A Cancel that comes at any check (the file's, each image's, after the parse) is the cancelled
// error, not a style with its image noted as skipped; read here under the same probe as well.
let count = Control::cancelled_at_look(u64::MAX);
crate::cmd::reads::read_ahead(&mut s, "style.importQgis", &p).unwrap().run(&count).unwrap();
assert!(count.looked() >= 3, "the file, the image and the parse's end look: {}", count.looked());
for n in 1..=count.looked() {
let e = crate::cmd::reads::read_ahead(&mut s, "style.importQgis", &p).unwrap().run(&Control::cancelled_at_look(n)).err().unwrap();
assert!(e.contains("cancelled"), "check {n}: {e}");
}
let here = Control::cancelled_at_look(u64::MAX);
{
let _probe = rustgis_analysis::control::install_progress(Some(here.clone()));
s.run("style.importQgis", &p).unwrap();
}
s.run("edit.undo", &Value::Null).unwrap();
assert!(here.looked() >= 3, "read here: {}", here.looked());
for n in 1..=here.looked() {
let _probe = rustgis_analysis::control::install_progress(Some(Control::cancelled_at_look(n)));
let e = s.run("style.importQgis", &p).unwrap_err();
assert!(e.contains("cancelled"), "check {n}, read here: {e}");
assert!(contents(&s.project) == before, "check {n}");
}
// Renamed while it was read: refused, the layer as it was.
let read = crate::cmd::reads::read_ahead(&mut s, "style.importQgis", &p).unwrap().run(&Control::stoppable()).unwrap();
let id = s.layer_id(&p).unwrap();
s.run("layer.rename", &json!({"layer": id, "name": "Towns"})).unwrap();
let before = contents(&s.project);
let e = crate::cmd::reads::read_land(&mut s, read).unwrap_err();
assert!(e.contains("renamed while its style was read"), "{e}");
assert!(contents(&s.project) == before);
}

/// Pictures are charged to an import's budget (1 KiB in tests) only once placed: pictures that
/// don't take to longitude and latitude leave it whole, and those past it are left out, noted.
#[test]
Expand Down
10 changes: 9 additions & 1 deletion crates/engine/src/tests/cancellation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,14 @@ pub(super) fn long_commands(boundaries: bool) {
// Automatic size bounds scan the numeric field on that queue too.
s.run("layer.symbology", &json!({"layer": "Cities", "type": "unique", "field": "name"})).unwrap();
read(&s, "layer.sizeBy", &json!({"layer": "Cities", "field": "pop_max"}));
// A QGIS style's raster image marker: the image is read on that queue, Cancel looked at before it
// (the style file's one read and its XML's one parse don't look; #2620).
image::RgbImage::from_pixel(4, 4, image::Rgb([200, 30, 30])).save(out("pin.png")).unwrap();
let marker = r#"<qgis version="4.2.3"><renderer-v2 type="singleSymbol"><symbols><symbol type="marker" name="0" alpha="1">
<layer class="RasterMarker" enabled="1"><Option type="Map"><Option name="imageFile" value="pin.png"/></Option></layer>
</symbol></symbols></renderer-v2></qgis>"#;
std::fs::write(out("pin.qml"), marker).unwrap();
read(&s, "style.importQgis", &json!({"layer": "Cities", "path": out("pin.qml")}));

s.run("layer.addDataText", &json!({"fileName": "calc.csv", "text": "n,day\n1,01/02/2024\n2,02/03/2024\n"})).unwrap();
s.run("edit.enable", &json!({"on": true})).unwrap();
Expand Down Expand Up @@ -445,7 +453,7 @@ impl Kind {
/// bits retain NaNs and signed zero. Include streamed rows omitted by project serialization;
/// normalize GP record timestamps/durations and geometry cache generations, which naturally
/// differ on a successful retry or Undo/Redo. All features, pixels and layer settings remain.
fn contents(project: &Project) -> Value {
pub(super) fn contents(project: &Project) -> Value {
let pixels: Vec<_> = project
.maps
.iter()
Expand Down
4 changes: 4 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3040,6 +3040,10 @@ impl RustGisApp {
if id == "layer.sizeBy" {
return readjob::run(self, "layer.sizeBy", params);
}
// Reading a style's file and its images' files: on a thread of its own, with Cancel.
if id == "style.importQgis" {
return readjob::run(self, "style.importQgis", params);
}
// Publishing hashes, reads and writes the whole file: on a thread of its own, with
// progress and Cancel, as an export is.
if id == "source.publish" {
Expand Down
Loading
Loading