diff --git a/crates/data/src/progress.rs b/crates/data/src/progress.rs index 0431c83916..d7420b9845 100644 --- a/crates/data/src/progress.rs +++ b/crates/data/src/progress.rs @@ -97,7 +97,7 @@ pub fn step(n: usize) -> Result<()> { /// Runs a nested writer without resetting or advancing its source's scan count. Cancellation /// still reaches every writer check; dropping the guard restores the source probe on errors too. -pub(crate) fn without_counting(run: impl FnOnce() -> T) -> T { +pub fn without_counting(run: impl FnOnce() -> T) -> T { struct CancelOnly(Arc); impl Probe for CancelOnly { fn cancelled(&self) -> bool { diff --git a/crates/engine/src/cmd/connections.rs b/crates/engine/src/cmd/connections.rs index a95265e746..0088f11314 100644 --- a/crates/engine/src/cmd/connections.rs +++ b/crates/engine/src/cmd/connections.rs @@ -232,8 +232,13 @@ fn new(s: &mut Session, p: &Value) -> CmdResult { for said in s.connections.redaction_notices_since(redactions) { s.warn(said); } - resolve_keys(s, &address_keys(&c.address)); - resolve_origins(s, &[&c]); + // A copy running a command of its session's (#2476) only records the connection: resolving + // logins would set the process's database passwords from its own, empty, logins. Its session + // makes the connection again when the command lands, and resolves them then. + if !s.web_logins.is_borrowing() { + resolve_keys(s, &address_keys(&c.address)); + resolve_origins(s, &[&c]); + } Ok(shown_stripped(s, &c, stripped, ps(p, "address").unwrap_or(""), key_hint.as_deref())) } diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 788158906e..56da232352 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -49,6 +49,28 @@ fn qgis_text(p: &Value) -> Result { String::from_utf8(bytes).map_err(|_| "not a QGIS file (it isn't text)".to_string()) } +/// The folder a project's relative paths start from: `dir` (a blank one is none, so they don't +/// start from the working directory), else the file's own (`.` for a file named without one). +fn project_dir(p: &Value) -> Option { + ps(p, "dir").filter(|d| !d.trim().is_empty()).map(str::to_string).or_else(|| file_dir(p)) +} + +/// A project read and parsed, with what its parse noted (its markers' images read). +struct Parsed { + project: qgis::Project, + report: Report, +} + +/// Reads and parses the project `p` names: one read of its file (at most [`MAX_FILE`] bytes, a +/// `.qgz` unzipped) and one parse of its XML (within [`MAX_XML`]), its markers' images read. +fn parse(p: &Value) -> Result { + let text = qgis_text(p)?; + let dir = project_dir(p); + let mut report = Report::default(); + let project = qgis::read_project(&text, dir.as_deref().unwrap_or_default(), &mut marker_images(), &mut report)?; + Ok(Parsed { project, report }) +} + /// The folder of the file `path` names (`.` for a file named without one), which its relative /// paths start from. fn file_dir(p: &Value) -> Option { @@ -143,11 +165,14 @@ fn read_file(path: &str) -> Result, String> { crate::project::read_file(std::path::Path::new(path), MAX_FILE) } -/// Imports a QGIS project as a new map. On the thread that runs it, as opening a project is, -/// because it changes the session as it goes and RustGIS has no background path yet for a command -/// that runs other commands on the session (the import as a whole off the window, with progress -/// and Cancel, would be that path): it adds layers one after another, each through the command -/// that adds its kind, and later layers, groups and relations read those added before. (A tile +/// Imports a QGIS project as a new map. It adds layers one after another, each through the command +/// that adds its kind, and later layers, groups and relations read those added before. In the +/// desktop app its file is first read and parsed on a thread of its own, with Cancel ([`scan`]), +/// the logins its services need are opened, and it then runs on a copy of the session, on a +/// thread of its own, with progress (layers done of the project's) and Cancel ([`import_ahead`]), +/// taking the project as parsed; the map it made is taken here. Run +/// anywhere else (the command line, a script, the browser) it runs here, on the thread that runs +/// it, looking at Cancel between layers (a script's or a model's). (A tile /// archive goes through that command's add itself, `tiles::add_with_metadata_wait`, with no /// wait for its metadata, as Add Data adds one.) Its work is bounded by the project: at most /// [`qgis::MAX_LAYERS`] layers, each read once by the command that adds it (a file's layers, and @@ -158,20 +183,29 @@ fn read_file(path: &str) -> Result, String> { /// for on this thread (`is_file`), which a slow network share can hold up, and a web service's /// layer (WMS, WMTS, WFS, OGC API, ArcGIS, WCS) asks its service on this thread, through /// `service.add`: its capabilities, then a WFS, OGC API or ArcGIS layer's features (each page -/// within the read limits) or a WCS coverage over the project's saved view. No step looks at -/// Cancel. +/// within the read limits) or a WCS coverage over the project's saved view. Cancel is looked at +/// between layers and by the reads within one (between a service's documents, a file's rows): one +/// document's download, one file's open, isn't. fn import_project(s: &mut Session, p: &Value) -> CmdResult { - let text = qgis_text(p)?; - // The folder relative paths start from: `dir` (a blank one is none, so they don't start - // from the working directory), else the file's own (`.` for a file named without one). - 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)?; + #[cfg(not(target_arch = "wasm32"))] + if let Some(ahead) = super::reads::take::(s, IMPORT_AHEAD) { + return land_import(s, ahead); + } + let dir = project_dir(p); + // Read and parsed already on the copy's way ([`scan`]), or here. + #[cfg(not(target_arch = "wasm32"))] + let parsed = super::reads::take::(s, PARSED); + #[cfg(target_arch = "wasm32")] + let parsed: Option = None; + let Parsed { project, mut report } = match parsed { + Some(parsed) => parsed, + None => parse(p)?, + }; // 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() }; + let name = map_name(&project); s.run_part("map.new", &json!({"name": name}))?; // QGIS draws a project on its canvas alone: no basemap, no graticule. let m = s.map_mut(); @@ -225,18 +259,29 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { // when the map couldn't take the project's coordinate system, which the view is in). let view = if projected { coverage_view(s, &project, degrees) } else { None }; let tree_layers = project.layers.iter().enumerate().rev().map(|(i, l)| (Some(i), l)); + // Layers done of the project's: what each layer's add reads counts nothing of its own. + rustgis_data::progress::begin(project.layers.len() + usize::from(project.main_annotations.is_some())); for (index, layer) in tree_layers.chain(project.main_annotations.iter().map(|l| (None, l))) { + rustgis_data::progress::check().map_err(|e| e.to_string())?; let before: std::collections::HashSet = s.map().layers.iter().map(|l| l.id).collect(); let tiles = s.map().tiles.len(); // The tiles a web tile layer landed on the map as, when it is one. let mut landed_on = None; - let result = if layer.kind == "annotation" { - add_annotations(s, layer, crs, canvas.as_ref(), dir.is_some(), &mut pictures, &mut report) - .map(|(name, d)| Some((name, Some(d)))) - } else { - add_layer(s, layer, dir.is_some(), view, &mut landed_on, &mut connections, &mut report) - .map(|name| name.map(|name| (name, None))) - }; + let result = rustgis_data::progress::without_counting(|| { + if layer.kind == "annotation" { + add_annotations(s, layer, crs, canvas.as_ref(), dir.is_some(), &mut pictures, &mut report) + .map(|(name, d)| Some((name, Some(d)))) + } else { + add_layer(s, layer, dir.is_some(), view, &mut landed_on, &mut connections, &mut report) + .map(|name| name.map(|name| (name, None))) + } + }); + // A layer whose read was cancelled ends the import: what it added goes with it. + if let Err(e) = &result + && e.contains(&rustgis_data::DataError::Cancelled.to_string()) + { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + } match result { Ok(Some((name, d))) => { drawn.push((layer.name.clone(), layer.visible, d)); @@ -274,6 +319,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { Err(e) if layer.kind == "annotation" => report.skipped(&layer.name, format!("the layer: {e}")), Err(e) => report.lost(&layer.name, NoteKind::Skipped, LossCode::DroppedFeature, format!("the layer: {e}")), } + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; } note_texts_under_layers_above(&drawn, &mut report); add_groups(s, &project, &came_in, &mut report); @@ -2075,6 +2121,274 @@ fn ahead_key(id: u32) -> String { format!("style.importQgis:{id}") } +/// What an import read ahead is taken by. +#[cfg(not(target_arch = "wasm32"))] +const IMPORT_AHEAD: &str = "project.importQgis"; + +/// A project imported on a copy of the session ([`import_ahead`]), for `project.importQgis` to +/// take: what the copy made, or why it stopped, and what it said either way. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct ImportAhead { + result: Result, + notices: Vec, + losses: Vec, + /// The saved connections when the copy was made: the ones it made are made again here only + /// while these are as they were. + connections: Vec, + /// Keeps the logins opened for it pending ([`crate::service_logins::borrow_for`]). + held: std::sync::Arc<()>, +} + +/// What an import on a copy made: its map, its tables, the layer it left active, the saved +/// connections it made (kind, address and name) and its answer. +#[cfg(not(target_arch = "wasm32"))] +struct Imported { + map: rustgis_map::Map, + /// What the map is named for: the project's title, or "QGIS project". + base: String, + /// The standalone tables it added (data without geometry), in the order it added them. + tables: Vec, + active_layer: Option, + /// A tile archive's framing still waiting for its bounds, on the map made. + style_view: Option<(rustgis_map::TileLayer, rustgis_map::Camera, u64)>, + made: Vec<(String, String, String)>, + answer: Value, +} + +/// A project's import prepared for its run on a copy ([`open_import_logins`]): the request it is +/// for, the project as parsed, what its map is named for, and the logins the copy borrows. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) struct ImportOpened { + params: Value, + parsed: Parsed, + base: String, + logins: crate::service_logins::SessionLogins, + held: std::sync::Arc<()>, + /// The files its scan read, logged as the import's inputs. + inputs: Vec, +} + +/// The key a project parsed ahead is given to the copy's import under ([`import_project`]). +#[cfg(not(target_arch = "wasm32"))] +const PARSED: &str = "project.importQgis/parsed"; + +/// A project read and parsed for its import before the import starts ([`scan`]), on a thread of +/// its own in the desktop app: with the web addresses its layers name, whose logins are opened +/// before the import is approved ([`open_import_logins`]). +#[cfg(not(target_arch = "wasm32"))] +pub struct ImportScan { + params: Value, + parsed: Parsed, + addresses: Vec, + /// The files read for it, for the processing log ([`super::reads::scan_import`]). + inputs: Vec, +} + +#[cfg(not(target_arch = "wasm32"))] +impl ImportScan { + pub(crate) fn with_inputs(mut self, inputs: Vec) -> Self { + self.inputs = inputs; + self + } +} + +/// Reads and parses the project an import of `p` imports, and finds the web addresses its layers +/// name: the import's first part, which the desktop app runs on a thread of its own, with Cancel, +/// before it opens their logins and starts the import ([`super::reads::scan_import`]). One read of +/// the file and one parse, its markers' images read between them looking at Cancel; the import +/// then reads its layers from the project as parsed here, without parsing it again. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn scan(p: &Value) -> Result { + let parsed = parse(p)?; + let addresses = parsed.project.layers.iter().filter_map(|l| web_address(&l.source)).map(str::to_string).collect(); + Ok(ImportScan { params: p.clone(), parsed, addresses, inputs: Vec::new() }) +} + +/// Opens, for an import about to run on a copy ([`import_ahead`]), the login of each web address +/// the project's layers name, as a request to it would open it (a saved login read, a choice of +/// connection asked for): before the read records the session's accounts, which an import that +/// opened one later would find changed when it lands. `None` for a project that doesn't read: the +/// import, run here, says why. +/// +/// It takes the project scanned for `p` on a thread of its own ([`scan`]; the desktop app's +/// way), which leaves it nothing to read. A caller that scanned none (a test) is scanned here, +/// on the thread that asks. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn open_import_logins(s: &mut Session, p: &Value) -> Option { + let scanned = s.import_scanned.take().filter(|scan| scan.params == *p); + let ImportScan { parsed, addresses, inputs, .. } = match scanned { + Some(scan) => scan, + None => scan(p).ok()?, + }; + let (logins, held) = crate::service_logins::borrow_for(s, addresses.iter().map(String::as_str)); + let base = map_name(&parsed.project).to_string(); + Some(ImportOpened { params: p.clone(), parsed, base, logins, held, inputs }) +} + +/// What an imported project's map is named for: its title, or "QGIS project". +fn map_name(project: &qgis::Project) -> &str { + if project.title.is_empty() { "QGIS project" } else { project.title.as_str() } +} + +/// The import `project.importQgis` makes in the desktop app, on a copy of the session on a +/// thread of its own, with progress and Cancel: the map it makes, its layers read from their files +/// and services, is taken by the command, which adds it as a map of this session's +/// ([`land_import`]); a cancelled or failed one leaves the session as it was. The logins its +/// services need were opened before ([`open_import_logins`]); the copy borrows them and opens none +/// of its own ([`crate::service_logins::borrow_for`]). Only for the user's own dispatch +/// (`native`): anything else runs the import as it always has, and so does a project that +/// couldn't be read, to say why. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn import_ahead(s: &mut Session, p: &Value, native: bool) -> Option { + // Opened for this very request before its accounts were recorded ([`open_import_logins`]). + let opened = s.import_opened.take().filter(|o| native && o.params == *p)?; + let ImportOpened { params: q, parsed, logins, base, held, inputs } = opened; + let selections: Vec<(String, String)> = + s.database_logins.web_selections().into_iter().map(|(origin, id)| (origin.to_string(), id.to_string())).collect(); + let (project, connections, extensions) = (s.project.clone(), s.connections.clone(), s.extensions().clone()); + let (view_size, active_layer, opened) = (s.view_size, s.active_layer, s.opened); + // The desktop's own settings, so what the copy adds is what an import here adds. + let (in_place_wait, raster_defaults, grids, auto_cache) = + (s.in_place_wait, s.raster_defaults.clone(), s.offers_grid_downloads, s.auto_cache); + let readers = s.undo_memory.readers(); + // Rows the copy shares stay counted while it holds them, should this session let them go. + let retained = readers.retain(crate::undo_memory::allocations(&project)); + // What it asks of servers and files goes in this session's Diagnostics, as when it runs here. + let requests = s.diagnostics.capture(); + Some(super::reads::ahead("Import QGIS Project", IMPORT_AHEAD.into(), move || { + // Held until the copy, made after it, is gone. + let _retained = retained; + let before = connections.connections.clone(); + let mut copy = Session::new(project); + copy.requests_into = Some(requests); + copy.set_extensions(extensions); + copy.connections = connections; + copy.web_logins = logins; + for (origin, id) in &selections { + copy.database_logins.select(crate::connections::WEB, origin, id); + } + (copy.view_size, copy.active_layer, copy.opened) = (view_size, active_layer, opened); + (copy.in_place_wait, copy.raster_defaults, copy.offers_grid_downloads, copy.auto_cache) = + (in_place_wait, raster_defaults, grids, auto_cache); + // The copy shares this session's rows, which this session already counts (#2431). + copy.undo_memory.memory = None; + copy.undo_memory.use_readers(readers); + copy.sync_policy_generation(); + let maps = copy.project.maps.len(); + let tables: Vec = copy.project.tables.iter().map(|t| t.id).collect(); + // The copy imports the project as parsed already, reading nothing of it again: the files + // read for it are its inputs too. + rustgis_data::provenance::record(inputs); + let result = super::reads::taking(&mut copy, PARSED, parsed, |copy| copy.run("project.importQgis", &q)).and_then(|answer| { + // The map it made, the last: one more than the copy had. + if copy.project.maps.len() != maps + 1 { + return Err("the import made no map".to_string()); + } + let map = copy.project.maps.pop().ok_or("the import made no map")?; + let made = copy + .connections + .connections + .iter() + .filter(|c| !before.iter().any(|b| b.id == c.id)) + .map(|c| (c.kind.clone(), c.address.clone(), c.name.clone())) + .collect(); + let added = copy.project.tables.iter().filter(|t| !tables.contains(&t.id)).map(|t| t.dataset.clone()).collect(); + let style_view = copy.style_view.take().filter(|(_, _, on)| *on == map.instance_id()); + Ok(Imported { map, base: base.clone(), tables: added, active_layer: copy.active_layer, style_view, made, answer }) + }); + let losses = std::mem::take(&mut copy.loss_notices); + ImportAhead { result, notices: std::mem::take(&mut copy.notices), losses, connections: before, held } + })) +} + +/// A web address a project layer's source names, which a login may be needed for. +#[cfg(not(target_arch = "wasm32"))] +fn web_address(source: &Source) -> Option<&str> { + match source { + Source::Wms { url, .. } + | Source::Wfs { url, .. } + | Source::ArcGis { url, .. } + | Source::Wcs { url, .. } + | Source::Xyz { url, .. } => Some(url), + Source::Archive { path, .. } | Source::File { path, .. } | Source::Csv { path, .. } => Some(path).filter(|p| p.contains("://")), + _ => None, + } + .map(String::as_str) +} + +/// Takes a project imported on a copy ([`import_ahead`]): says what the copy said, makes the saved +/// connections it made (while the saved ones are as they were when it started; otherwise it is +/// refused, to be imported again), and adds its map as the active map, as `map.new` adds one. +#[cfg(not(target_arch = "wasm32"))] +fn land_import(s: &mut Session, ahead: ImportAhead) -> CmdResult { + let say = |s: &mut Session, losses: Vec, notices: Vec| { + for loss in losses { + s.notify_counted(loss.code, loss.template, loss.count); + } + for notice in notices { + s.relay_notice(notice); + } + }; + let imported = match ahead.result { + Ok(imported) => imported, + Err(e) => { + say(s, ahead.losses, ahead.notices); + return Err(e); + } + }; + // (Refused, it says nothing of an import that added nothing.) + if s.connections.connections != ahead.connections && !imported.made.is_empty() { + return Err("the saved connections changed while the QGIS project was read: import it again".into()); + } + // Each tried first on a copy of the saved connections, so that none is saved unless all are, + // with the names the import gave them. + let changed = || "the saved connections changed while the QGIS project was read: import it again".to_string(); + let mut trial = s.connections.clone(); + for (kind, address, name) in &imported.made { + let c = crate::connections::Connection { kind: kind.clone(), address: address.clone(), ..Default::default() }; + if trial.add(c, false)?.0.name != *name { + return Err(changed()); + } + } + let saved = s.connections.clone(); + for (kind, address, name) in &imported.made { + let made = match s.run_part("connection.new", &json!({"kind": kind, "address": address})) { + Ok(made) if made.get("name").and_then(Value::as_str) == Some(name.as_str()) => Ok(()), + Ok(_) => Err(changed()), + Err(e) => Err(e), + }; + if let Err(e) = made { + s.connections = saved; + return Err(e); + } + } + say(s, ahead.losses, ahead.notices); + for table in imported.tables { + s.project.add_table(table); + } + let mut map = imported.map; + // Named as `map.new` names one here: for the project, unless a map has that name. + let mut name = imported.base.clone(); + let mut i = 1; + while s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(&name)) { + i += 1; + name = format!("{}{i}", imported.base); + } + map.name.clone_from(&name); + s.project.maps.push(map); + s.project.active_map = s.project.maps.len() - 1; + s.active_layer = imported.active_layer; + s.table_layer = None; + if imported.style_view.is_some() { + s.style_view = imported.style_view; + } + // The logins opened for it are this session's now: they rebind the layers already using them. + crate::service_logins::release_held(s, &ahead.held); + let mut answer = imported.answer; + answer["map"] = json!(name); + Ok(answer) +} + /// 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 of the command's own `text` or `data` (at most [`MAX_XML`] bytes or their base64) while it diff --git a/crates/engine/src/cmd/reads.rs b/crates/engine/src/cmd/reads.rs index ba3b6ab204..d0b8f25946 100644 --- a/crates/engine/src/cmd/reads.rs +++ b/crates/engine/src/cmd/reads.rs @@ -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, Column Statistics' count of a column and Import QGIS Style's file and images. [`read_ahead`] +//! Error Inspector's topology check (#1291), Source File State's hashing of a layer's file, Column Statistics' count of a column, Import QGIS Style's file and images, and Import QGIS Project's import on a copy of the session. [`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 @@ -212,6 +212,41 @@ pub fn read_ahead(s: &mut Session, command: &str, p: &Value) -> Result, + log_inputs: bool, +) -> Result { + let mut scanned = Err(String::new()); + let capture = log_inputs.then(rustgis_data::provenance::Capture::start); + let res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + rustgis_analysis::run_under("Import QGIS Project", control, || { + scanned = super::qgis::scan(p); + Ok(()) + }) + })) + .unwrap_or_else(|_| Err("Import QGIS Project failed unexpectedly".to_string())); + let inputs = capture.as_ref().map_or_else(Vec::new, rustgis_data::provenance::Capture::inputs); + res?; + scanned.map(|scan| scan.with_inputs(inputs)) +} + +/// [`read_ahead`] for `project.importQgis`, given the project [`scan_import`] read for `p`. +#[cfg(not(target_arch = "wasm32"))] +pub fn read_ahead_scanned(s: &mut Session, p: &Value, scan: super::qgis::ImportScan) -> Result { + s.import_scanned = Some(scan); + let read = s.start_read("project.importQgis", p); + s.import_scanned = None; + read +} + /// The commands whose read the desktop app makes on a thread of its own before they land /// ([`read_ahead`]), each with what its read is called, besides the table edits /// (`edit::TABLE_EDITS`). The cancel tests (`tests/cancellation.rs`) exercise every one, or name @@ -237,6 +272,7 @@ pub(crate) const IN_BACKGROUND: &[(&str, &str)] = &[ ("layer.sizeBy", "Size by Field"), ("offline.keepRows", "Keep Field Package Rows"), ("style.importQgis", "Import QGIS Style"), + ("project.importQgis", "Import QGIS Project"), ]; /// What `command`'s read is called, when it is one the app makes before the command lands @@ -331,6 +367,13 @@ pub(crate) fn prepare(s: &mut Session, op: Authorized, owner: Continu "layer.sizeBy" => (super::layer::size_by_ahead(s, params), None), "offline.keepRows" => (super::field_changes::keep_ahead(s), None), "style.importQgis" => (super::qgis::style_ahead(s, params), None), + "project.importQgis" => { + #[cfg(not(target_arch = "wasm32"))] + let work = super::qgis::import_ahead(s, params, owner.native_tool_owner()); + #[cfg(target_arch = "wasm32")] + let work = None; + (work, None) + } // Listed in IN_BACKGROUND without a read here. id => return Err(not_in_background(id)), }; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8317b20c80..c60ebe8f6c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1201,6 +1201,13 @@ pub struct Session { /// there. Its notices stay its own: the run there says them. #[cfg(not(target_arch = "wasm32"))] pub(crate) requests_into: Option, + /// A QGIS project's import prepared for the read about to run it on a copy, its logins opened + /// before the read recorded the accounts (#2476): taken at once by that read. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) import_opened: Option, + /// The project an import's first part read for it ([`cmd::reads::scan_import`]), while its read starts. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) import_scanned: Option, /// The tools run ahead that a model's run took, for the tests. #[cfg(test)] pub(crate) tools_taken: usize, @@ -1612,6 +1619,10 @@ impl Session { zones_ahead: None, #[cfg(not(target_arch = "wasm32"))] requests_into: None, + #[cfg(not(target_arch = "wasm32"))] + import_opened: None, + #[cfg(not(target_arch = "wasm32"))] + import_scanned: None, #[cfg(test)] tools_taken: 0, #[cfg(test)] @@ -2319,9 +2330,15 @@ impl Session { /// failed to start, or their worker failed): only the session still holds it. It goes back /// while nothing else changed the project since, newest set aside first so the oldest ends /// in front, and is freed and said otherwise. Run before each command run by itself, and by - /// the desktop as its background jobs end, so Undo sees it. + /// the desktop as its background jobs end, so Undo sees it. Logins opened for an import that + /// ended without landing end again here too ([`service_logins::reclaim_held`]). pub fn reclaim_rooms(&mut self) { - if self.depth > 0 || self.rooms.is_empty() { + if self.depth > 0 { + return; + } + #[cfg(not(target_arch = "wasm32"))] + service_logins::reclaim_held(self); + if self.rooms.is_empty() { return; } let (ended, running): (Vec<_>, Vec<_>) = diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 017159116e..388e206660 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -179,26 +179,47 @@ impl Session { let id = self.layer_id(&Value::Object(params.clone()))?; params.insert("layer".into(), json!(id)); } - let mut op = self.authorize(command, &Value::Object(params))?; - self.check_read_command(&op)?; - let copy_command = matches!(command, "model.run" | "script.run") && self.policy_user(); - if copy_command { - // A model's or script's native copy may read through several tools. Bind the original - // session's runtime stores, including web logins, before that copy exists. - let mut node = (*op.node).clone(); - node.auth = Some(Arc::new(super::scope::RuntimeAccounts::capture(self)?)); - op.node = Arc::new(node); + // A QGIS project's import runs on a copy that borrows the logins its services need: they + // are opened here, before its approval and its read record the accounts they are checked + // against (#2476). + #[cfg(not(target_arch = "wasm32"))] + { + self.import_opened = None; + if command == "project.importQgis" && self.policy_user() { + self.import_opened = crate::cmd::qgis::open_import_logins(self, &Value::Object(params.clone())); + } } - let node = op.node.clone(); - let mut owner = self.continuation_for(node.clone())?; - if copy_command { - owner.accounts = self.policy_accounts(); - owner.s3 = Some(vec![crate::render::rustgis_tiles::s3::account_identity()?]); + // The opened import is let go on every way out, refused or prepared: logins it opened end + // again unless the import holding them lands (`service_logins::reclaim_held`). + let prepared = (|s: &mut Self| -> Result { + let mut op = s.authorize(command, &Value::Object(params))?; + s.check_read_command(&op)?; + let copy_command = matches!(command, "model.run" | "script.run") && s.policy_user(); + if copy_command { + // A model's or script's native copy may read through several tools. Bind the original + // session's runtime stores, including web logins, before that copy exists. + #[cfg(not(target_arch = "wasm32"))] + crate::service_logins::adopt_held(s); + let mut node = (*op.node).clone(); + node.auth = Some(Arc::new(super::scope::RuntimeAccounts::capture(s)?)); + op.node = Arc::new(node); + } + let node = op.node.clone(); + let mut owner = s.continuation_for(node.clone())?; + if copy_command { + owner.accounts = s.policy_accounts(); + owner.s3 = Some(vec![crate::render::rustgis_tiles::s3::account_identity()?]); + } + owner.check()?; + let current = owner.clone(); + let still = Arc::new(move || current.check().is_ok()); + s.with_node(node, |s| crate::render::rustgis_tiles::cache::with_still(still, || crate::cmd::reads::prepare(s, op, owner))) + })(self); + #[cfg(not(target_arch = "wasm32"))] + { + self.import_opened = None; } - owner.check()?; - let current = owner.clone(); - let still = Arc::new(move || current.check().is_ok()); - self.with_node(node, |s| crate::render::rustgis_tiles::cache::with_still(still, || crate::cmd::reads::prepare(s, op, owner))) + prepared } /// Lands only the original read invocation; no result can be claimed by another command. pub(crate) fn finish_read(&mut self, read: crate::cmd::reads::Read) -> CmdResult { @@ -210,18 +231,26 @@ impl Session { CommandOp::Registered { spec, params } => (spec.id, params.clone()), _ => return Err("not a registered read command".into()), }; + // A project's import makes a map of its own: the user's own lands whichever map is shown by + // then, as a tool's project-wide output does, with every other check of its owner (#3120). + let project_wide = command == "project.importQgis" && owner.native_tool_owner(); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { self.with_deferred_downloads(|s| { s.command_epilogue(command, ¶ms, |s| { rustgis_data::provenance::record(inputs); - s.check_delivery(&owner)?; + if project_wide { + s.check_delivery_owner(&owner)?; + s.check_continuation_origin(&owner)?; + } else { + s.check_delivery(&owner)?; + } if let Some(source) = &source { let layer = s.map().layer(s.layer_id(¶ms)?).ok_or("no such layer")?; if !layer.source.as_ref().is_some_and(|current| current.same_opening(source)) { return Err("the live source changed since this read started".into()); } } - s.resume(&owner, |s| { + let land = |s: &mut Session| { if !owner.native_tool_owner() && *op.node != s.command_node(command, ¶ms)? { return Err("the read command changed since it was authorized".into()); } @@ -238,7 +267,8 @@ impl Session { s.note_source(source); } result - })? + }; + if project_wide { s.resume_checked(&owner, land) } else { s.resume(&owner, land) }? }) }) })); diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 6083e74f60..d828bc775e 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -356,7 +356,10 @@ pub fn temporary_probe(c: &Connection, secret: &str, insecure: bool, url: &str) } /// An active login belongs to one connection in one session; the token is not a secret, but -/// saved projects must never treat it as authority to use another session's login. +/// saved projects must never treat it as authority to use another session's login. The one +/// exception is a borrowing copy ([`SessionLogins::borrowing`]): a command's own run on a copy of +/// its session, which uses the logins its session opened for it and opens none. +#[derive(Clone)] struct ActiveLogin { origin: String, binding: String, @@ -390,6 +393,18 @@ pub struct SessionLogins { said: BTreeSet, /// Token generations under way, by connection id (see [`crate::service_tokens`]). pub(crate) pending: BTreeMap, + /// For a borrowing copy ([`SessionLogins::borrowing`]), why its session couldn't open the + /// login of each origin it was opened for, by origin: a login not open is refused with it. + borrowed: Option>, + /// While set, a login opened here leaves the layers and tiles of its connection as they are + /// and is recorded here instead ([`borrow_for`]). + #[cfg(not(target_arch = "wasm32"))] + holding: Option>, + /// Logins opened for a command running on a copy (Import QGIS Project) that haven't rebound + /// their connection's layers yet, with the token the running command keeps: rebound as it + /// lands ([`release_held`]), ended when it doesn't ([`reclaim_held`]). + #[cfg(not(target_arch = "wasm32"))] + held: Vec<(std::sync::Arc<()>, Vec)>, } impl SessionLogins { @@ -403,14 +418,41 @@ impl SessionLogins { failed: BTreeMap::new(), said: BTreeSet::new(), pending: BTreeMap::new(), + borrowed: None, + #[cfg(not(target_arch = "wasm32"))] + holding: None, + #[cfg(not(target_arch = "wasm32"))] + held: Vec::new(), } } + /// The logins a copy of this session uses while it runs a command of this session's on a + /// thread of its own (Import QGIS Project, #2476): those open here for `origins`, which this + /// session opened for it before it started, and why each that isn't couldn't be (`refused`, + /// by origin). The copy opens no login itself: it reads no saved login and asks for none, and a + /// login not open is refused with that reason. Dropping it ends none of the logins it borrowed, + /// which stay this session's; one logged out here meanwhile is no longer active, and its + /// requests are refused. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn borrowing(&self, origins: &BTreeSet, refused: BTreeMap) -> Self { + let mut copy = Self::new(); + copy.active = self.active.iter().filter(|(_, a)| origins.contains(&a.origin)).map(|(id, a)| (id.clone(), a.clone())).collect(); + copy.anonymous = self.anonymous; + copy.logged_out.clone_from(&self.logged_out); + copy.borrowed = Some(refused); + copy + } + /// Starts or ends [`SessionLogins::anonymous`] reads, saying what it was. pub(crate) fn set_anonymous(&mut self, on: bool) -> bool { std::mem::replace(&mut self.anonymous, on) } + /// Whether these are a borrowing copy's ([`SessionLogins::borrowing`]). + pub(crate) fn is_borrowing(&self) -> bool { + self.borrowed.is_some() + } + /// Whether [`SessionLogins::anonymous`] reads are running: nothing may pick a login for them. pub(crate) fn is_anonymous(&self) -> bool { self.anonymous @@ -450,7 +492,9 @@ pub(crate) fn anonymously(s: &mut Session, on: bool, f: impl FnOnce(&mut Sess impl Drop for SessionLogins { fn drop(&mut self) { let mut ended = false; - for active in self.active.values() { + // A borrowing copy's logins are its session's, which ends them. + let own = if self.borrowed.is_some() { BTreeMap::new() } else { std::mem::take(&mut self.active) }; + for active in own.values() { ended |= logins::deactivate(&active.binding); } for op in self.pending.values() { @@ -485,6 +529,10 @@ fn clear_cache() { /// Other sessions and other connections at this origin retain their own bindings. /// Returns the number of addresses that could not be rebound; resolution reports it once. pub(crate) fn activate(s: &mut Session, c: &Connection, secret: Option<&Secret>, insecure: bool) -> Result { + // A borrowing copy neither opens a login nor ends one of its session's. + if s.web_logins.borrowed.is_some() { + return Err(REQUIRED.into()); + } let origin = login_origin(c).ok_or(NO_ORIGIN)?; let next = match secret { Some(secret) => { @@ -502,6 +550,16 @@ pub(crate) fn activate(s: &mut Session, c: &Connection, secret: Option<&Secret>, } } retry(s, &c.id); + // Opened for an import running on a copy: its layers here wait until the import lands. (A + // login replaced here was this session's already, and its session password with it.) + #[cfg(not(target_arch = "wasm32"))] + if !replaced && let Some(held) = s.web_logins.holding.as_mut() { + held.push(c.id.clone()); + return Ok(0); + } + // Opened here by anything else: this session's, which no import's end may end. + #[cfg(not(target_arch = "wasm32"))] + unhold(s, &c.id); let failed = reselect(s, c, &origin); // Only a login that was replaced or removed leaves cached authenticated responses to drop; // a first login, or none, changes no cached tile. @@ -521,7 +579,12 @@ pub(crate) fn reselect(s: &mut Session, c: &Connection, origin: &str) -> usize { } pub(crate) fn deactivate(s: &mut Session, c: &Connection, _origin: Option) { - if let Some(old) = s.web_logins.active.remove(&c.id) { + #[cfg(not(target_arch = "wasm32"))] + unhold(s, &c.id); + // (A borrowing copy only stops using its session's login, which stays active there.) + if let Some(old) = s.web_logins.active.remove(&c.id) + && s.web_logins.borrowed.is_none() + { logins::deactivate(&old.binding); clear_cache(); } @@ -626,7 +689,9 @@ fn lapsed(c: &Connection, secret: &Secret) -> bool { /// isn't asked for the same expired payload again. The saved login itself is left as it is. /// The connection stays chosen for its origin, so asking for a new login finds it. fn expire(s: &mut Session, c: &Connection) -> String { - if let Some(old) = s.web_logins.active.remove(&c.id) { + if let Some(old) = s.web_logins.active.remove(&c.id) + && s.web_logins.borrowed.is_none() + { logins::deactivate(&old.binding); clear_cache(); } @@ -727,6 +792,23 @@ pub fn request(s: &mut Session, connection: Option<&str>, url: &str) -> Result, url: &str) -> Result(s: &mut Session, addresses: impl IntoIterator) -> (SessionLogins, std::sync::Arc<()>) { + let (mut origins, mut refused) = (BTreeSet::new(), BTreeMap::new()); + let outer = s.web_logins.holding.replace(Vec::new()); + for address in addresses { + let Some(origin) = logins::origin(logins::inner(address)) else { continue }; + if origins.insert(origin.clone()) + && let Err(e) = request(s, None, address) + { + refused.insert(origin, e); + } + } + let opened = std::mem::replace(&mut s.web_logins.holding, outer).unwrap_or_default(); + let token = std::sync::Arc::new(()); + if !opened.is_empty() { + s.web_logins.held.push((token.clone(), opened)); + } + (s.web_logins.borrowing(&origins, refused), token) +} + +/// The command holding `token` ([`borrow_for`]) landed: the logins opened for it rebind their +/// connections' layers and tiles here now, as any login opened here does. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn release_held(s: &mut Session, token: &std::sync::Arc<()>) { + let Some(i) = s.web_logins.held.iter().position(|(t, _)| std::sync::Arc::ptr_eq(t, token)) else { return }; + let (_, ids) = s.web_logins.held.remove(i); + // The session's from now on: another import still running that holds one too can't end it. + for id in &ids { + unhold(s, id); + } + rebind_held(s, &ids); +} + +/// Logins opened for a command that ended without landing (cancelled, refused, failed) end again, +/// unless another command still running holds them: what it opened leaves nothing behind. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn reclaim_held(s: &mut Session) { + if s.web_logins.held.iter().all(|(t, _)| std::sync::Arc::strong_count(t) > 1) { + return; + } + let (ended, running): (Vec<_>, Vec<_>) = + std::mem::take(&mut s.web_logins.held).into_iter().partition(|(t, _)| std::sync::Arc::strong_count(t) == 1); + s.web_logins.held = running; + let mut cleared = false; + for id in ended.into_iter().flat_map(|(_, ids)| ids) { + if s.web_logins.held.iter().any(|(_, ids)| ids.contains(&id)) { + continue; + } + if let Some(old) = s.web_logins.active.remove(&id) { + logins::deactivate(&old.binding); + s.database_logins.clear_session_password(&id); + cleared = true; + } + } + // The copy may have cached what it was sent with these logins. + if cleared { + clear_cache(); + } +} + +/// `id`'s login is no import's to end: opened, ended or used here by something else. +#[cfg(not(target_arch = "wasm32"))] +fn unhold(s: &mut Session, id: &str) { + for (_, ids) in &mut s.web_logins.held { + ids.retain(|held| held != id); + } +} + +/// Logins opened for imports still running become this session's: a model's or a script's copy +/// about to borrow every login here (`RuntimeAccounts::capture`) may outlast them. Their layers and +/// tiles rebind now. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn adopt_held(s: &mut Session) { + let ids: Vec = s.web_logins.held.iter_mut().flat_map(|(_, ids)| std::mem::take(ids)).collect(); + rebind_held(s, &ids); +} + +/// Rebinds the layers and tiles of each of `ids`' connections still logged in here. +#[cfg(not(target_arch = "wasm32"))] +fn rebind_held(s: &mut Session, ids: &[String]) { + for id in ids { + let Some(c) = s.connections.connections.iter().find(|c| c.id == *id).cloned() else { continue }; + if !logged_in(s, &c) { + continue; + } + if let Some(origin) = login_origin(&c) { + let failed = reselect(s, &c, &origin); + if failed > 0 { + s.notify( + format!("{}: {failed} address(es) could not carry the service login; their previous addresses were kept.", c.name), + true, + ); + } + } + } +} + /// Opens a service using its existing or remembered login without retrying a failed store read /// or undoing logout. A pending project connection choice is adopted only after success. pub fn open_connection(s: &mut Session, c: &Connection) -> Result<(), String> { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 386f6ac4f1..22270aac03 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -42076,6 +42076,7 @@ mod ogc_server; mod ogc_dataset; +mod qgis_import_ahead; mod qgis_services; #[path = "../../../tests/support/esripbf.rs"] diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index 57c460e779..394ae390e2 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -292,6 +292,19 @@ pub(super) fn long_commands(boundaries: bool) { "#; std::fs::write(out("pin.qml"), marker).unwrap(); read(&s, "style.importQgis", &json!({"layer": "Cities", "path": out("pin.qml")})); + // A QGIS project: imported on a copy of the session, Cancel looked at between its layers and + // within each layer's read (#2476). + let place = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [10.01, 45.01]}}]}); + std::fs::write(out("place.geojson"), place.to_string()).unwrap(); + std::fs::write(out("place.csv"), "name,x,y\nB,10.02,45.02\n").unwrap(); + let project = r#"Imported + + Place./place.geojsonPlaceogr + Tablefile:./place.csv?type=csv&xField=x&yField=yTabledelimitedtext + "#; + std::fs::write(out("import.qgs"), project).unwrap(); + read(&s, "project.importQgis", &json!({"path": out("import.qgs")})); 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(); diff --git a/crates/engine/src/tests/qgis_import_ahead.rs b/crates/engine/src/tests/qgis_import_ahead.rs new file mode 100644 index 0000000000..071feba70b --- /dev/null +++ b/crates/engine/src/tests/qgis_import_ahead.rs @@ -0,0 +1,524 @@ +//! Import QGIS Project run off the window (#2476): in the desktop app the import runs on a copy of +//! the session, on a thread of its own, and the map it made is taken when it lands. The map taken is +//! the one the import makes when it runs here; a saved web login is the session's, borrowed and +//! left open; a cancelled import leaves nothing behind (its sweep is in `cancellation.rs`). + +use super::{Project, Session, ogc_server}; +use ogc_server::{Route, Server}; +use rustgis_analysis::control::Control; +use serde_json::{Value, json}; + +/// A folder of its own for one test, removed when it ends. +struct Folder(std::path::PathBuf); + +impl Folder { + fn new(name: &str) -> Self { + let dir = std::env::temp_dir().join(format!("rustgis-qgis-ahead-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } +} + +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A WFS of three roads. +fn roads_server() -> Server { + let features: Vec<_> = [1, 2, 3] + .iter() + .map(|id| json!({"type": "Feature", "id": id, "properties": {"n": id}, "geometry": {"type": "Point", "coordinates": [*id, 1]}})) + .collect(); + let page = json!({"type": "FeatureCollection", "features": features}).to_string(); + let query = "SERVICE=WFS&VERSION=2.0.0&REQUEST=GetFeature&TYPENAMES=roads"; + let format = "OUTPUTFORMAT=application%2Fjson&SRSNAME=EPSG:4326"; + let server = Server::new(vec![ + Route::new("/wfs?SERVICE=WFS&REQUEST=GetCapabilities", ""), + Route::new(&format!("/wfs?{query}&{format}&COUNT=50000"), &page), + Route::new(&format!("/wfs?{query}&SRSNAME=EPSG:4326&RESULTTYPE=hits"), r#""#), + ]); + let base = server.base.clone(); + server.set( + "/wfs?SERVICE=WFS&REQUEST=GetCapabilities", + &format!( + r#"roadsRoads"# + ), + ); + server +} + +/// A project in `dir` with a WFS layer at `base`, a GeoJSON file beside it, a CSV without geometry +/// (a table), a PostGIS table (a saved connection made for it), a group holding the file's layer, +/// and a bookmark. +fn project(dir: &Folder, base: &str) -> std::path::PathBuf { + let towns = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [8.5, 47.4]}}, + {"type": "Feature", "properties": {"name": "B"}, "geometry": {"type": "Point", "coordinates": [7.4, 46.9]}}]}); + std::fs::write(dir.0.join("towns.geojson"), towns.to_string()).unwrap(); + // Without a geometry field: a table of its own. + std::fs::write(dir.0.join("notes.csv"), "id,note\n1,first\n2,second\n").unwrap(); + let layer = |id: &str, kind: &str, provider: &str, source: &str| { + format!( + r#"{id}{source}{id}{provider}"# + ) + }; + let qgs = format!( + r#"Ahead + + + + {}{}{}{} + EPSG:4326"#, + layer("Towns", "vector", "ogr", "./towns.geojson"), + layer("Roads", "vector", "WFS", &format!("typename='roads' url='{base}/wfs' version='2.0.0'")), + layer("Notes", "vector", "delimitedtext", "file:./notes.csv?type=csv&geomType=none"), + layer( + "Parcels", + "vector", + "postgres", + "dbname='gis' host=db.example.invalid port=5432 user='reader' table=\"public\".\"parcels\" (geom)" + ), + ); + let path = dir.0.join("ahead.qgs"); + std::fs::write(&path, qgs).unwrap(); + path +} + +/// `project.importQgis` with `p`, run as the desktop app runs it: on a copy of the session, on a +/// thread of its own (here, this one), and taken when it lands. +fn import_ahead(s: &mut Session, p: &Value, control: &std::sync::Arc) -> crate::CmdResult { + let read = crate::cmd::reads::read_ahead(s, "project.importQgis", p)?; + assert!(read.reads(), "the import runs on a copy"); + let done = read.run(control)?; + crate::cmd::reads::read_land(s, done) +} + +#[test] +fn an_import_run_on_a_copy_makes_the_map_an_import_here_makes() { + let dir = Folder::new("same"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut here = Session::new(Project::default()); + let answer_here = here.run("project.importQgis", &p).unwrap(); + let mut ahead = Session::new(Project::default()); + let answer_ahead = import_ahead(&mut ahead, &p, &Control::new()).unwrap(); + assert_eq!(answer_ahead, answer_here); + assert_eq!(answer_ahead["layers"].as_array().map(Vec::len), Some(2), "{answer_ahead}"); + // The CSV without geometry, a table here as when the import runs here (which notes its layer as + // not added). + assert_eq!(ahead.project.tables.len(), 1); + let tables = |s: &Session| s.project.tables.iter().map(|t| (t.id, t.dataset.name.clone())).collect::>(); + assert_eq!(tables(&ahead), tables(&here)); + // The whole project as saved, its maps, layers, groups and bookmarks among it. + assert!(super::cancellation::contents(&ahead.project) == super::cancellation::contents(&here.project)); + assert_eq!(ahead.project.active_map, here.project.active_map); + assert_eq!(ahead.active_layer, here.active_layer); + // The PostGIS table's saved connection, made here once the copy has landed, without a password. + assert_eq!(ahead.connections.connections, here.connections.connections); + assert_eq!(ahead.connections.connections.len(), 1); + // What it said is said here, as when it runs here. + let said = |s: &Session| s.notices.iter().map(|n| n.text.clone()).collect::>(); + assert_eq!(said(&ahead), said(&here)); + // One Undo step takes the map away again. + let maps = ahead.project.maps.len(); + ahead.run("edit.undo", &json!({})).unwrap(); + assert_eq!(ahead.project.maps.len(), maps - 1); +} + +/// A map named as the project is named again when a map took the name while it was read, as a new +/// map is; saved connections changed meanwhile refuse it, to be imported again. +#[test] +fn an_import_on_a_copy_lands_on_the_session_as_it_is_then() { + let dir = Folder::new("then"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let done = read.run(&Control::new()).unwrap(); + // (Renamed meanwhile: a map made or opened meanwhile is a change of map, which the read refuses.) + s.map_mut().name = "Ahead".into(); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer["map"], "Ahead2"); + assert_eq!(s.map().name, "Ahead2"); + assert!(s.map().layer_by_name("Towns").is_some()); + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let done = read.run(&Control::new()).unwrap(); + s.run("connection.new", &json!({"kind": "postgres", "address": "postgres:host=db2.example.invalid dbname=other"})).unwrap(); + let maps = s.project.maps.len(); + let e = crate::cmd::reads::read_land(&mut s, done).unwrap_err(); + // (Refused when it lands: by the read, which sees the account changed, or by the import.) + assert!(e.contains("changed"), "{e}"); + assert_eq!(s.project.maps.len(), maps); + assert_eq!(s.connections.connections.len(), 1); +} + +/// A service's saved login: the copy sends it as this session would, borrowing this session's +/// login, which stays open after the copy is gone; a login this session couldn't open isn't +/// opened by the copy either. +#[test] +fn an_import_on_a_copy_borrows_the_sessions_web_login() { + let dir = Folder::new("login"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let id = s + .run( + "connection.new", + &json!({"kind": "wfs", "name": "Roads", "address": format!("{}/wfs", server.base), "auth": "query", "keyName": "key"}), + ) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "RGSYNTH_ahead_key", "allowInsecure": true})).unwrap(); + let keyed = + |server: &Server| server.requests().iter().filter(|r| r.query.iter().any(|(k, v)| k == "key" && v == "RGSYNTH_ahead_key")).count(); + // (The fixture answers only the addresses it was given, so the keyed ones go unanswered and the + // layer is left out: what matters is what was sent.) + import_ahead(&mut s, &p, &Control::new()).unwrap(); + let sent = keyed(&server); + assert!(sent > 0, "the copy sent the session's login"); + // Still open here: a request now carries it, with no login asked for again. + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + assert!(crate::service_logins::logged_in(&s, &c)); + // Logged out, the session can't open it, and neither does the copy: the layer is left out, + // saying why, and nothing is sent with the key. + s.run("connection.logout", &json!({"id": id})).unwrap(); + let answer = import_ahead(&mut s, &p, &Control::new()).unwrap(); + let notes = serde_json::to_string(&answer["notes"]).unwrap(); + assert!(notes.contains(crate::service_logins::LOGGED_OUT), "{notes}"); + assert_eq!(keyed(&server), sent); +} + +/// A login saved on this computer and not yet opened this session: opened for the import before +/// it starts, so the import lands (its accounts as they were when it started) and the copy sends +/// it. +#[test] +fn an_import_on_a_copy_opens_a_saved_login_before_it_starts() { + use rustgis_data::secrets::MemorySecrets; + let dir = Folder::new("saved"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(std::sync::Arc::new(MemorySecrets::new()))); + let id = s + .run( + "connection.new", + &json!({"kind": "wfs", "name": "Roads", "address": format!("{}/wfs", server.base), "auth": "query", "keyName": "key"}), + ) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "RGSYNTH_saved_key", "allowInsecure": true, "remember": true})).unwrap(); + // Saved, but not open this session. + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + crate::service_logins::deactivate(&mut s, &c, None); + s.database_logins.clear_session_password(&id); + assert!(!crate::service_logins::logged_in(&s, &c)); + import_ahead(&mut s, &p, &Control::new()).unwrap(); + assert!(server.requests().iter().any(|r| r.query.iter().any(|(k, v)| k == "key" && v == "RGSYNTH_saved_key"))); + assert!(crate::service_logins::logged_in(&s, &c), "opened here, and still open"); +} + +/// A borrowing copy opens no login, even one saved where it could read it: it sends only what its +/// session opened for it, and refuses the rest, saying why. +#[test] +fn a_borrowing_copy_opens_no_login_of_its_own() { + use rustgis_data::secrets::MemorySecrets; + let store = std::sync::Arc::new(MemorySecrets::new()); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(store.clone())); + let origin = "https://borrowed.example.invalid"; + let id = + s.run("connection.new", &json!({"kind": "wfs", "name": "B", "address": origin, "auth": "query", "keyName": "key"})).unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "RGSYNTH_borrowed", "remember": true})).unwrap(); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + crate::service_logins::deactivate(&mut s, &c, None); + s.database_logins.clear_session_password(&id); + // Borrowed for no origin: the copy has none open, though the store it reaches holds one. + let mut copy = Session::new(Project::default()); + copy.database_logins.set_store(Some(store)); + copy.connections = s.connections.clone(); + copy.web_logins = s.web_logins.borrowing(&Default::default(), [(origin.to_string(), "why".to_string())].into()); + let url = format!("{origin}/wfs"); + assert_eq!(crate::service_logins::request(&mut copy, None, &url).unwrap_err(), "why"); + assert!(!crate::service_logins::logged_in(©, &c)); +} + +/// A session with a saved login for a WFS at `base`, not open this session, and a tile layer of +/// its connection: the connection's id and the tile's address. +fn saved_login_with_a_tile(s: &mut Session, base: &str) -> (String, String) { + s.database_logins.set_store(Some(std::sync::Arc::new(rustgis_data::secrets::MemorySecrets::new()))); + let made = s.run( + "connection.new", + &json!({"kind": "wfs", "name": "Roads", "address": format!("{base}/wfs"), "auth": "query", "keyName": "key"}), + ); + let id = made.unwrap()["id"].as_str().unwrap().to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "RGSYNTH_held_key", "allowInsecure": true, "remember": true})).unwrap(); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + crate::service_logins::deactivate(s, &c, None); + s.database_logins.clear_session_password(&id); + let mut t = rustgis_map::TileLayer::new("Tiles", rustgis_map::TileKind::Raster, format!("{base}/tiles/{{z}}/{{x}}/{{y}}.png")); + t.connection.clone_from(&id); + s.map_mut().tiles.push(t); + let url = s.map().tiles[0].url.clone(); + (id, url) +} + +/// A saved login opened for an import leaves the layers and tiles already using its connection as +/// they are while the import runs (#3120): they take it when the import lands. +#[test] +fn a_login_opened_for_an_import_rebinds_its_tiles_only_as_it_lands() { + let dir = Folder::new("held"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + assert!(crate::service_logins::logged_in(&s, &c), "opened before it starts"); + assert_eq!(s.map().tiles[0].url, before, "the tile waits for the import"); + let done = read.run(&Control::new()).unwrap(); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c), "kept while the import still holds it"); + crate::cmd::reads::read_land(&mut s, done).unwrap(); + let tile = &s.project.maps[0].tiles[0]; + assert_ne!(tile.url, before, "rebound as it landed"); + assert_eq!(crate::render::rustgis_tiles::logins::inner(&tile.url), before); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c), "the session's now"); +} + +/// An import that never lands (cancelled, refused) ends again the login opened for it, and leaves +/// the tiles of its connection as they were: it leaves nothing behind (#3120). +#[test] +fn a_login_opened_for_an_import_that_never_lands_ends_again() { + let dir = Folder::new("unheld"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + assert!(crate::service_logins::logged_in(&s, &c)); + drop(read); + s.reclaim_rooms(); + assert!(!crate::service_logins::logged_in(&s, &c), "ended again"); + assert!(s.database_logins.session_password(&id).is_none()); + assert_eq!(s.map().tiles[0].url, before); + // Cancelled while it reads: the same. + let control = Control::new(); + control.cancel(); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + assert!(read.run(&control).is_err()); + s.reclaim_rooms(); + assert!(!crate::service_logins::logged_in(&s, &c)); + assert_eq!(s.map().tiles[0].url, before); + // And it opens again for the next import, which lands. + import_ahead(&mut s, &p, &Control::new()).unwrap(); + assert!(crate::service_logins::logged_in(&s, &c)); +} + +/// An import let go before it is prepared (its request refused) holds no login: the one opened +/// for it ends again, and a read prepared holds none past its start. +#[test] +fn an_import_let_go_before_it_starts_holds_no_login() { + let dir = Folder::new("refused"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + s.import_opened = crate::cmd::qgis::open_import_logins(&mut s, &p); + assert!(s.import_opened.is_some() && crate::service_logins::logged_in(&s, &c)); + // As `capture_read` lets it go on every way out. + s.import_opened = None; + s.reclaim_rooms(); + assert!(!crate::service_logins::logged_in(&s, &c)); + assert_eq!(s.map().tiles[0].url, before); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + assert!(s.import_opened.is_none(), "taken by the read"); + drop(read); +} + +/// Saved connections an import made are made here only all together: one that can't be leaves +/// none saved and adds no map (#3120). +#[test] +fn an_import_whose_connections_cant_all_be_saved_saves_none() { + let dir = Folder::new("connections"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let done = read.run(&Control::new()).unwrap(); + // Connections from a newer RustGIS, kept whole: none can be added. + let newer = r#"{"version": 2, "next": 4, "connections": []}"#; + s.connections = crate::connections::Connections::from_json(newer); + let maps = s.project.maps.len(); + assert!(crate::cmd::reads::read_land(&mut s, done).is_err()); + assert_eq!(s.project.maps.len(), maps); + assert_eq!(s.connections.to_json(), newer); +} + +/// A login opened for an import that something else here uses meanwhile is this session's from +/// then on: its tiles take it then, and it stays open whether the import lands or not. +#[test] +fn a_login_opened_for_an_import_and_used_meanwhile_stays_open() { + let dir = Folder::new("adopted"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + crate::service_logins::request(&mut s, None, &format!("{}/wfs", server.base)).unwrap(); + assert_ne!(s.map().tiles[0].url, before, "taken as it is used here"); + drop(read); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c)); +} + +/// A login opened for one import and borrowed by a second stays open while the second runs, when +/// the first is cancelled; it ends only when neither lands. +#[test] +fn a_login_two_imports_hold_stays_open_while_one_runs() { + let dir = Folder::new("two"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, _) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let first = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let second = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + drop(first); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c), "the second still holds it"); + drop(second); + s.reclaim_rooms(); + assert!(!crate::service_logins::logged_in(&s, &c)); +} + +/// A login the user opens while an import holds it is the user's: the import's end leaves it open, +/// with the session password they gave. +#[test] +fn a_login_the_user_opens_while_an_import_holds_it_stays_open() { + let dir = Folder::new("user"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + s.run("connection.login", &json!({"id": id, "apiKey": "RGSYNTH_typed_key", "allowInsecure": true})).unwrap(); + assert_ne!(s.map().tiles[0].url, before, "rebound by the user's login"); + drop(read); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c)); + assert!(s.database_logins.session_password(&id).is_some()); +} + +/// The import makes a map of its own: another map made and shown while it reads leaves it to land +/// (#3120), as the user's own import. +#[test] +fn an_import_on_a_copy_lands_whichever_map_is_shown() { + let dir = Folder::new("shown"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let done = read.run(&Control::new()).unwrap(); + s.run("map.new", &json!({"name": "Other"})).unwrap(); + assert_eq!(s.map().name, "Other"); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer["map"], "Ahead"); + assert_eq!(s.map().name, "Ahead"); + assert_eq!(s.project.maps.len(), 3); +} + +/// A login two imports hold is the session's once one lands: the other one cancelled after leaves +/// it open, with the tiles the landing rebound to it (#3120). +#[test] +fn a_login_two_imports_hold_stays_open_when_one_lands_and_the_other_is_cancelled() { + let dir = Folder::new("landed-one"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut s = Session::new(Project::default()); + let (id, before) = saved_login_with_a_tile(&mut s, &server.base); + let c = s.connections.connections.iter().find(|c| c.id == id).unwrap().clone(); + let first = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let second = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &p).unwrap(); + let done = first.run(&Control::new()).unwrap(); + crate::cmd::reads::read_land(&mut s, done).unwrap(); + let rebound = s.project.maps[0].tiles[0].url.clone(); + assert_ne!(rebound, before); + drop(second); + s.reclaim_rooms(); + assert!(crate::service_logins::logged_in(&s, &c), "the landed import's"); + assert_eq!(s.project.maps[0].tiles[0].url, rebound); +} + +/// The desktop's way: the project read and parsed first ([`crate::cmd::reads::scan_import`]), then +/// the import started with it, which reads the file no more and makes the same map. +#[test] +fn an_import_scanned_first_makes_the_map_an_import_here_makes() { + let dir = Folder::new("scanned"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + let mut here = Session::new(Project::default()); + let made = here.run("project.importQgis", &p).unwrap(); + let mut s = Session::new(Project::default()); + let scan = crate::cmd::reads::scan_import(&p, &Control::new(), false).unwrap(); + // Gone once read: the import reads it no more. + std::fs::remove_file(&path).unwrap(); + let read = crate::cmd::reads::read_ahead_scanned(&mut s, &p, scan).unwrap(); + assert!(read.reads(), "the import runs on a copy"); + let done = read.run(&Control::new()).unwrap(); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer, made); + assert!(super::cancellation::contents(&s.project) == super::cancellation::contents(&here.project)); + // Cancelled while it reads: no project, and nothing here. + let control = Control::new(); + control.cancel(); + assert!(crate::cmd::reads::scan_import(&p, &control, false).is_err()); +} + +/// With the processing log on, the files the scan read (the project's) are the import's inputs, +/// as when it reads them itself; with it off, none is kept. +#[test] +fn an_import_scanned_first_logs_the_project_file_as_an_input() { + let dir = Folder::new("logged"); + let server = roads_server(); + let path = project(&dir, &server.base); + let p = json!({"path": path.display().to_string()}); + for on in [true, false] { + let mut s = Session::new(Project::default()); + s.log.set_on(on); + let scan = crate::cmd::reads::scan_import(&p, &Control::new(), on).unwrap(); + let read = crate::cmd::reads::read_ahead_scanned(&mut s, &p, scan).unwrap(); + let done = read.run(&Control::new()).unwrap(); + let logged = done.inputs.iter().any(|i| i.path.ends_with("ahead.qgs")); + assert_eq!(logged, on, "{:?}", done.inputs.iter().map(|i| &i.path).collect::>()); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8966523c7b..5631d644dc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -3429,6 +3429,11 @@ impl RustGisApp { if id == "style.importQgis" { return readjob::run(self, "style.importQgis", params); } + // Importing a project reads its files and asks its services for their layers: on a copy + // of the session on a thread of its own, with progress and Cancel (#2476). + if id == "project.importQgis" { + return readjob::run(self, "project.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" { diff --git a/crates/ui-egui/src/readjob.rs b/crates/ui-egui/src/readjob.rs index aeaecdb4b3..7565f74ce7 100644 --- a/crates/ui-egui/src/readjob.rs +++ b/crates/ui-egui/src/readjob.rs @@ -126,6 +126,10 @@ struct ReadJob { slot: crate::Slot>, /// A reload's target and what its file held, looked at on its thread as the read started. seen: Option<(crate::diskwatch::Target, crate::Slot)>, + /// A QGIS project's import's first part under way: its file read and parsed, before the + /// import itself starts ([`scan`]). + #[cfg(not(target_arch = "wasm32"))] + scan: Option>>, } /// Runs Add Data, Load All, Repair/Reload Data, Convert To Annotation, archive reload/repair, model/script @@ -230,15 +234,20 @@ fn run_presented( }; params.insert("layer".into(), json!(id)); } - let mut ahead = match reads::read_ahead(&mut app.session, command, &p) { - Ok(ahead) => ahead, - Err(error) => { - app.command_failed(command, &error, notice_mark); - not_run(app, then, error.clone()); - return Err(error); + // A QGIS project's import is admitted once its file has been read, on a thread ([`scan`]). + let mut ahead = if command == "project.importQgis" && cfg!(not(target_arch = "wasm32")) { + None + } else { + match reads::read_ahead(&mut app.session, command, &p) { + Ok(ahead) => Some(ahead), + Err(error) => { + app.command_failed(command, &error, notice_mark); + not_run(app, then, error.clone()); + return Err(error); + } } }; - if let Some(dataset) = preview { + if let (Some(dataset), Some(ahead)) = (preview, ahead.as_mut()) { ahead.keep_preview(dataset); } // Load All asked again for a layer it is reading already. @@ -281,7 +290,7 @@ fn run_presented( let asked = Asked { command, params: p, - ahead: Some(ahead), + ahead, what, opened: app.session.opened, map: app.session.map().instance_id(), @@ -413,6 +422,7 @@ fn called<'a>(command: &str, what: &'a str) -> &'a str { (true, "data.similar") => tl_raw!("Find Similar"), (true, "layer.sizeBy") => tl_raw!("Size by Field"), (true, "style.importQgis") => tl_raw!("Import QGIS Style"), + (true, "project.importQgis") => tl_raw!("Import QGIS Project"), (true, "service.add") => tl_raw!("Add Service Layer"), (true, "service.layers") => tl_raw!("List Service Layers"), (true, "edit.previewShapeConversion") => tl_raw!("Preview Shape Conversion"), @@ -466,7 +476,8 @@ fn placed(app: &RustGisApp, asked: &Asked) -> Result { if app.session.opened != asked.opened { return Err(Gone::Project); } - if app.session.map().instance_id() != asked.map { + // A project's import makes a map of its own: it needs none of the maps open to stay active. + if asked.command != "project.importQgis" && app.session.map().instance_id() != asked.map { return Err(Gone::Map); } if let Some((i, original)) = &asked.archive @@ -490,6 +501,10 @@ fn placed(app: &RustGisApp, asked: &Asked) -> Result { /// Starts `asked`'s read with `p`, or runs it here when it reads nothing ahead (or its thread /// can't start). fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result { + #[cfg(not(target_arch = "wasm32"))] + if asked.command == "project.importQgis" && asked.ahead.is_none() { + return scan(app, asked, p); + } let Some(ahead) = asked.ahead.take() else { return complete_here(app, asked, p, Err(tl!("This read was already started").to_string())); }; @@ -542,6 +557,7 @@ fn start(app: &mut RustGisApp, mut asked: Asked, p: Value) -> Result Result Result { + let name = called(asked.command, ""); + let control = Control::stoppable(); + let (ctl, slot) = (control.clone(), crate::Slot::default()); + let out = slot.clone(); + let params = p; + let log_inputs = app.session.log.on(); + let diagnostics = app.session.diagnostics.capture(); + let spawn = || { + std::thread::Builder::new().name(name.into()).spawn(move || { + let _diagnostics = diagnostics.enter(); + let scanned = reads::scan_import(¶ms, &ctl, log_inputs); + *out.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(scanned); + }) + }; + #[cfg(test)] + let spawn = || if app.reads.fail_spawn { Err(std::io::Error::other("worker start refused for test")) } else { spawn() }; + if let Err(e) = spawn() { + let why = crate::i18n::fmt("The background worker could not start ({error}). Retry the command.", &[("error", &e.to_string())]); + app.session.notify(why.clone(), true); + not_run_asked(app, &asked, why.clone()); + return Err(why); + } + app.reads.job = Some(ReadJob { + asked, + gone: None, + name: "Import QGIS Project", + control, + cancel_waiting: true, + slot: crate::Slot::default(), + seen: None, + scan: Some(slot), + }); + Ok(json!({"started": name})) +} + +/// A QGIS project's import whose file has been read ([`scan`]): admitted now, its logins opened, +/// it starts on a thread of its own, and `true`. One cancelled, left or failed meanwhile has its +/// outcome put in its slot for [`land`] to say, and `false`. +#[cfg(not(target_arch = "wasm32"))] +fn scanned(app: &mut RustGisApp) -> bool { + let ready = app.reads.job.as_ref().and_then(|job| job.scan.as_ref()?.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take()); + let Some(found) = ready else { return false }; + let Some(mut job) = app.reads.job.take() else { return false }; + job.scan = None; + let found = if job.gone.is_some() || job.control.is_cancelled() { + Err(tl!("cancelled").to_string()) + } else { + found.and_then(|found| match placed(app, &job.asked) { + Ok(p) => Ok((p, found)), + Err(why) => { + job.gone = Some(why); + Err(why.to_string()) + } + }) + }; + let failed = match found { + Ok((p, found)) => match reads::read_ahead_scanned(&mut app.session, &p, found) { + Ok(ahead) => { + job.asked.ahead = Some(ahead); + let _ = start(app, job.asked, p); + return true; + } + Err(e) => e, + }, + Err(e) => e, + }; + *job.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Err(failed)); + app.reads.job = Some(job); + false +} + /// Completes the admitted read, then calls its callback with the actual outcome. /// A pre-dispatch failure is reported once even when a queued start discards its error. fn complete_here(app: &mut RustGisApp, asked: Asked, p: Value, done: Result) -> Result { @@ -645,6 +747,10 @@ pub fn land(app: &mut RustGisApp) -> bool { job.control.cancel(); job.gone = Some(why); } + #[cfg(not(target_arch = "wasm32"))] + if scanned(app) { + return true; + } if let Some(job) = &app.reads.job { let done = job.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); let Some(done) = done else { return true }; @@ -731,7 +837,12 @@ pub fn stop(app: &mut RustGisApp, wait: std::time::Duration) { if let Some(job) = job { job.control.cancel(); let end = std::time::Instant::now() + wait; - while job.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() && std::time::Instant::now() < end { + // A QGIS import's first part ends in a slot of its own. + #[cfg(not(target_arch = "wasm32"))] + let ended = || job.scan.as_ref().is_some_and(|scan| scan.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_some()); + #[cfg(target_arch = "wasm32")] + let ended = || false; + while job.slot.lock().unwrap_or_else(std::sync::PoisonError::into_inner).is_none() && !ended() && std::time::Instant::now() < end { std::thread::sleep(std::time::Duration::from_millis(10)); } abandon_asked(app, &job.asked, why.clone()); @@ -1711,6 +1822,113 @@ mod tests { assert_eq!(step.params["layer"], json!("towns")); } + /// Import QGIS Project runs on a copy of the session on a thread of its own (#2476): the map it + /// made comes in when it lands, in one Undo step, with what the import says. + #[test] + fn a_qgis_project_is_imported_on_a_thread_before_it_lands() { + let dir = tempfile::tempdir().unwrap(); + let towns = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [8.5, 47.4]}}]}); + std::fs::write(dir.path().join("towns.geojson"), towns.to_string()).unwrap(); + let path = dir.path().join("towns.qgs"); + std::fs::write( + &path, + r#"Towns + + Towns./towns.geojsonTownsogr + Gone./gone.geojsonGoneogr + "#, + ) + .unwrap(); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let maps = app.session.project.maps.len(); + app.reads_off_frame = true; + let params = json!({"path": path.display().to_string()}); + assert_eq!(app.run_by_user("project.importQgis", params).unwrap()["started"], "Import QGIS Project"); + assert_eq!(app.session.project.maps.len(), maps, "a map only once it has been imported"); + let said = |app: &RustGisApp| app.session.notices.iter().filter(|n| n.text.contains("Imported 1 of 2 QGIS layers")).count(); + assert_eq!(said(&app), 0); + landed(&mut app, 60); + assert_eq!(app.session.project.maps.len(), maps + 1); + assert_eq!(app.session.map().name, "Towns"); + assert!(app.session.map().layer_by_name("Towns").is_some()); + assert_eq!(said(&app), 1, "said once, when it lands"); + app.run("edit.undo", Value::Null).unwrap(); + assert_eq!(app.session.project.maps.len(), maps); + } + + /// A project written for the import tests below, with one GeoJSON layer. + fn towns_project(dir: &std::path::Path) -> Value { + let towns = json!({"type": "FeatureCollection", "features": [ + {"type": "Feature", "properties": {"name": "A"}, "geometry": {"type": "Point", "coordinates": [8.5, 47.4]}}]}); + std::fs::write(dir.join("towns.geojson"), towns.to_string()).unwrap(); + let path = dir.join("towns.qgs"); + std::fs::write( + &path, + r#"Towns + + Towns./towns.geojsonTownsogr + "#, + ) + .unwrap(); + json!({"path": path.display().to_string()}) + } + + /// A project's import makes a map of its own (#3120): another map made active while it reads, + /// or the map an import before it made, leaves it to land. + #[test] + fn a_qgis_import_lands_whichever_map_is_active() { + let dir = tempfile::tempdir().unwrap(); + let params = towns_project(dir.path()); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.run("map.new", json!({"name": "Other"})).unwrap(); + app.session.project.active_map = 0; + let maps = app.session.project.maps.len(); + app.reads_off_frame = true; + assert_eq!(app.run_by_user("project.importQgis", params.clone()).unwrap()["started"], "Import QGIS Project"); + // The second waits behind the first, whose map is active when it starts. + app.run_by_user("project.importQgis", params).unwrap(); + app.session.project.active_map = 1; + landed(&mut app, 60); + let names: Vec<_> = app.session.project.maps.iter().map(|m| m.name.as_str()).collect(); + let said: Vec<_> = app.session.notices.iter().map(|n| n.text.as_str()).collect(); + assert_eq!(names[maps..], ["Towns", "Towns2"], "{names:?} {said:?}"); + assert!(!app.session.notices.iter().any(|n| n.text.contains("was left")), "{:?}", app.session.notices); + } + + /// A QGIS import cancelled while its file is read (its first part, on a thread of its own) + /// adds nothing and says so; the next one lands. + #[test] + fn a_qgis_import_cancelled_while_its_file_is_read_adds_nothing() { + let dir = tempfile::tempdir().unwrap(); + let params = towns_project(dir.path()); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let maps = app.session.project.maps.len(); + app.reads_off_frame = true; + assert_eq!(app.run_by_user("project.importQgis", params.clone()).unwrap()["started"], "Import QGIS Project"); + app.reads.cancel_for_tests(); + landed(&mut app, 60); + assert_eq!(app.session.project.maps.len(), maps); + assert!(app.session.notices.iter().any(|n| n.text.contains("cancelled")), "{:?}", app.session.notices); + app.run_by_user("project.importQgis", params).unwrap(); + landed(&mut app, 60); + assert_eq!(app.session.project.maps.len(), maps + 1); + } + + /// A QGIS import whose thread the system refuses is refused with it, not run on the window. + #[test] + fn a_qgis_import_whose_thread_wont_start_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let params = towns_project(dir.path()); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let maps = app.session.project.maps.len(); + app.reads_off_frame = true; + app.reads.fail_spawn = true; + let error = app.run_by_user("project.importQgis", params).unwrap_err(); + assert!(error.contains("worker could not start"), "{error}"); + assert_eq!(app.session.project.maps.len(), maps); + } + /// Import QGIS Style reads its file and its raster image and SVG markers' images on a thread first /// (#2620): the layer is styled when they have been read, with the notes the command gives. #[test] diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 522ef3246a..2c4d4ed9ee 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -285,7 +285,11 @@ with the login saved in RustGIS for it, if there is one. Other source settings R value, which may be a key written on its own, is taken as a login, never named. A service that doesn't answer, or doesn't list the layer, leaves that layer out, noted. In the web app, a web service's layer is left out, noted: add it with **Home › Add › Add Data › From Service**. On the -desktop, the import waits for each service in turn. A memory +desktop, the import runs in the background, with its progress (layers done of the project's) and +Cancel: the map comes in once every layer has been read and every service has answered, and a +cancelled import adds nothing. A service whose login RustGIS keeps is asked with that login, which +is opened first if it isn't yet (a saved login read, or a choice of connection asked for); one that +can't be opened leaves the layer out, noted. A memory layer comes in empty with its fields, as QGIS opens it (QGIS doesn't save its features). A virtual layer that selects every column of one file's layer (`SELECT * FROM t`, with or without a `WHERE` clause, its fields named with or without the table, or no query) comes in as that