diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs
index ee5b485f5e..8f8b8f1b26 100644
--- a/crates/engine/src/cmd/field.rs
+++ b/crates/engine/src/cmd/field.rs
@@ -40,8 +40,8 @@ pub fn is_field_package(name: &str) -> bool {
/// A field package of the active map, as (name, bytes).
///
-/// An offline area's map (` (offline)` of one of this project's areas, or the map of a
-/// project opened from a field package) is packaged as it is, to bring its edits back. Any other map is first made an offline area of this project (`extent`
+/// The map of a home offline area or of an opened field package goes as it is, so its edits
+/// can come back. Any other map is first made an offline area of this project (`extent`
/// and `name` as for `offline.download`, the view by default), whose map is packaged.
///
/// Never silent: the raster layers an offline area leaves behind, the tile layers that stay
@@ -109,15 +109,12 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<
if opened_field && s.project.maps.len() != 1 {
return Err("a returning field project must hold only its original field map: remove added maps before sending it back".into());
}
- // An offline area's map: named for one of this project's areas, or opened from a field
- // package (the phone's project holds no areas). A map only named so is packaged as any other.
- let returning = s
- .map()
- .name
- .strip_suffix(OFFLINE)
- .map(str::to_string)
- .filter(|area| opened_field || s.project.offline_areas.iter().any(|a| a.name.eq_ignore_ascii_case(area)))
- .or_else(|| opened_field.then(|| s.map().name.clone()));
+ let home_area = if opened_field { None } else { super::workspace::map_area_index(&s.project, s.project.active_map) };
+ let returning = if opened_field {
+ Some(s.map().name.strip_suffix(OFFLINE).unwrap_or(&s.map().name).to_string())
+ } else {
+ home_area.and_then(|i| s.project.offline_areas.get(i)).map(|area| area.name.clone())
+ };
// Only a map coming back from the field carries its photos. Its persisted provenance
// survives an ordinary Save As; going out, the photos named are at home.
let coming_back = returning.is_some() && opened_field;
@@ -168,9 +165,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<
false,
);
}
- let mut m = data;
- m.name = format!("{name}{OFFLINE}");
- (name, m)
+ (name, data)
}
};
let mut entries: Vec<(String, Vec)> = Vec::new();
@@ -272,7 +267,9 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<
}
s.project.field_origin.clone()
} else {
- let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(&area)).ok_or("the offline area was not found")?;
+ let ai = home_area
+ .or_else(|| s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(&area)))
+ .ok_or("the offline area was not found")?;
let new_home = s.project.origin_id.is_empty().then(crate::project::field_id).transpose()?;
let new_area = s.project.offline_areas.get(ai).is_some_and(|a| a.id.is_empty()).then(crate::project::field_id).transpose()?;
// The first package of an area gives it the state a return is checked against; later ones
@@ -317,7 +314,12 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut Vec) -> Result<
}
let mut project = crate::project::Project::new(area.clone());
project.field_origin = origin;
- // Rasters were taken out above, so the map goes as it is.
+ // The package has no home offline areas and carries its association in field_origin.
+ map.offline_area_id = None;
+ if !coming_back {
+ // Older phones also look at the outgoing title to show Send Field Package.
+ map.name = format!("{area}{OFFLINE}");
+ }
project.maps = vec![map];
let home = &s.project;
let stayed: Vec = [
diff --git a/crates/engine/src/cmd/field_audit_tests.rs b/crates/engine/src/cmd/field_audit_tests.rs
index 1c633da070..9d84476139 100644
--- a/crates/engine/src/cmd/field_audit_tests.rs
+++ b/crates/engine/src/cmd/field_audit_tests.rs
@@ -93,6 +93,125 @@ fn with_label(s: &Session, id: u32, field: &str, label: &str) -> usize {
const AREA: [f64; 4] = [-20.0, -40.0, 60.0, 40.0];
+/// A map imported from another project under an offline title is renamed, so an area of the
+/// same name here doesn't take it for its offline copy (and sync it as the area's edits).
+#[test]
+fn an_imported_offline_titled_map_is_not_taken_for_an_area_copy() {
+ let temp = Temp::new("import-offline-title");
+ let mut home = home(&temp);
+ package(&mut home, &json!({"name": "Crew", "extent": AREA})).unwrap();
+ let maps = home.project.maps.len();
+ let mut other = crate::Project::default();
+ // Another project's offline copy, saved before maps carried their area's ID.
+ other.maps[0].name = "Crew (offline)".into();
+ home.run("map.import", &json!({"text": serde_json::to_string(&other).unwrap()})).unwrap();
+ assert!(home.project.maps.iter().any(|m| m.name == "Crew (imported)" && m.offline_area_id.is_none()));
+ assert!(home.notices.iter().any(|n| n.text.contains("renamed")), "{:?}", home.notices);
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ assert_eq!(home.map().name, "Crew (offline)");
+ assert_eq!(home.project.maps.len(), maps + 2);
+}
+
+/// A map imported with its area's ID loses it, and says so; an ordinary map imports with neither
+/// notice.
+#[test]
+fn importing_maps_says_when_an_area_association_is_dropped() {
+ let temp = Temp::new("import-detach");
+ let mut home = home(&temp);
+ package(&mut home, &json!({"name": "Crew", "extent": AREA})).unwrap();
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ let path = temp.0.join("with-area.rgis");
+ home.run("project.save", &json!({"path": path})).unwrap();
+
+ let mut other = Session::new(crate::Project::default());
+ let mark = other.notice_mark();
+ other.run("map.import", &json!({"path": path})).unwrap();
+ let texts: Vec<_> = other.notices_since(mark).iter().map(|n| n.text.clone()).collect();
+ assert!(texts.iter().any(|t| t.starts_with("1 imported map(s) were detached")), "{texts:?}");
+ assert!(other.project.maps.iter().all(|m| m.offline_area_id.is_none()));
+
+ let mark = other.notice_mark();
+ other.run("map.import", &json!({"text": serde_json::to_string(&crate::Project::default()).unwrap()})).unwrap();
+ let texts: Vec<_> = other.notices_since(mark).iter().map(|n| n.text.clone()).collect();
+ assert!(!texts.iter().any(|t| t.contains("detached") || t.contains("renamed")), "{texts:?}");
+}
+
+/// Removing an area whose copy is the only map keeps the map but not its association, so the
+/// project still saves and reopens.
+#[test]
+fn removing_an_area_clears_the_association_of_the_copy_it_keeps() {
+ let temp = Temp::new("remove-only-copy");
+ let mut home = home(&temp);
+ package(&mut home, &json!({"name": "Crew", "extent": AREA})).unwrap();
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ home.project.maps.retain(|m| m.offline_area_id.is_some());
+ home.project.active_map = 0;
+ home.run("offline.remove", &json!({"name": "Crew"})).unwrap();
+ assert_eq!(home.project.maps.len(), 1);
+ assert!(home.project.maps[0].offline_area_id.is_none());
+ // Nor does its title still name the area's copy.
+ assert_eq!(home.project.maps[0].name, "Crew (kept)");
+ assert!(home.notices.iter().any(|n| n.text.contains("kept as 'Crew (kept)'")), "{:?}", home.notices);
+ let path = temp.0.join("removed.rgis");
+ home.run("project.save", &json!({"path": path})).unwrap();
+ home.run("project.open", &json!({"path": path})).unwrap();
+}
+
+/// A legacy home tab gains its association on rename, so callers still find it after save and reopen.
+#[test]
+fn bring_back_refreshes_a_renamed_home_offline_map() {
+ let temp = Temp::new("rename-home-offline");
+ let mut home = home(&temp);
+ let source = home.map().name.clone();
+ let (_, out) = package(&mut home, &json!({"name": "Crew", "extent": AREA})).unwrap();
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ // A home project saved before maps carried their area ID.
+ home.map_mut().offline_area_id = None;
+ home.run("map.rename", &json!({"name": "Renamed at home"})).unwrap();
+ let path = temp.0.join("home.rgis");
+ home.run("project.save", &json!({"path": path})).unwrap();
+ let saved: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ assert!(saved["requires"].as_array().unwrap().contains(&json!("offline-map-area-id")));
+ home.run("project.open", &json!({"path": path})).unwrap();
+ assert_eq!(home.map().name, "Renamed at home");
+
+ let mut field = phone(&temp, &out, "phone");
+ let cities = layer(&field, "Cities");
+ let name = text_field(&field, cities);
+ let count = |s: &Session, label| with_label(s, layer(s, "Cities"), &name, label);
+ add_point(&mut field, cities, &name, "Captured after rename", [10.0, 5.0]);
+ let (done, _) = bring_back(&temp, &mut field, &mut home, "phone");
+ assert_eq!(done["area"], "Crew");
+ assert_eq!(done["added"], 1);
+ assert_eq!(count(&home, "Captured after rename"), 1);
+
+ home.run("map.activate", &json!({"name": source})).unwrap();
+ assert_eq!(count(&home, "Captured after rename"), 1);
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ assert_eq!(home.map().name, "Renamed at home");
+ assert_eq!(home.project.maps.len(), 2);
+
+ // Reusing the old title for another map must not redirect Sync, Package or Remove.
+ home.run("map.new", &json!({"name": "Crew (offline)"})).unwrap();
+ home.run("offline.open", &json!({"name": "Crew"})).unwrap();
+ assert_eq!(home.map().name, "Renamed at home");
+ add_point(&mut home, cities, &name, "Edited at home", [11.0, 5.0]);
+ let (area, bytes) = package(&mut home, &Value::Null).unwrap();
+ assert_eq!(area, "Crew");
+ assert_eq!(home.project.offline_areas.len(), 1);
+ let repacked = phone(&temp, &bytes, "repacked");
+ assert_eq!(repacked.map().name, "Crew (offline)");
+ assert_eq!(count(&repacked, "Edited at home"), 1);
+ assert_eq!(repacked.project.field_origin.as_ref().unwrap().area, home.project.offline_areas[0].id);
+
+ home.run("offline.sync", &json!({"name": "Crew"})).unwrap();
+ home.run("map.activate", &json!({"name": source})).unwrap();
+ assert_eq!(count(&home, "Edited at home"), 1);
+ home.run("offline.remove", &json!({"name": "Crew"})).unwrap();
+ assert!(home.project.maps.iter().all(|map| map.name != "Renamed at home"));
+ assert!(home.project.maps.iter().any(|map| map.name == "Crew (offline)"));
+}
+
/// One package, copied to two phones (emailed to a crew, AirDropped to a second device). Each fixes
/// a city and captures a point. A is brought back first. B's copy is of a state the area has left:
/// bringing it back would undo A's fix and delete A's point (B's copy lacks it), so it is refused
diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs
index 83c8c4cfa8..224e10204c 100644
--- a/crates/engine/src/cmd/items.rs
+++ b/crates/engine/src/cmd/items.rs
@@ -535,7 +535,21 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
};
let mut names = Vec::new();
let first_map = s.project.maps.len();
+ let mut detached_offline = 0;
+ let mut renamed_offline = 0;
for mut m in maps.into_iter().take(MAX_IMPORTED_MAPS) {
+ // A map imported without its home area becomes an independent copy.
+ detached_offline += usize::from(m.offline_area_id.take().is_some());
+ // Nor may its title make it one: an older project matches its offline copy by the name
+ // " (offline)", and syncing an unrelated map would delete what it lacks.
+ let suffix = super::field::OFFLINE;
+ if m.name.len() > suffix.len()
+ && m.name.is_char_boundary(m.name.len() - suffix.len())
+ && m.name[m.name.len() - suffix.len()..].eq_ignore_ascii_case(suffix)
+ {
+ m.name = format!("{} (imported)", &m.name[..m.name.len() - suffix.len()]);
+ renamed_offline += 1;
+ }
// A binding in a file is no authority to use a login here.
crate::s3_connections::clear_bindings(m.addresses_mut());
crate::project::clear_login_bindings(m.addresses_mut());
@@ -549,6 +563,18 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult {
m.renew_instance_id();
s.project.maps.push(m);
}
+ if detached_offline > 0 {
+ s.notify(
+ format!("{detached_offline} imported map(s) were detached from their offline areas, which aren't imported with maps"),
+ false,
+ );
+ }
+ if renamed_offline > 0 {
+ s.notify(
+ format!("{renamed_offline} imported map(s) titled as offline copies were renamed \"… (imported)\", so they aren't taken for this project's offline maps"),
+ false,
+ );
+ }
if let Some(message) = super::design::display_area_messages(s.project.maps.iter().skip(first_map).flat_map(|map| map.layers.iter())) {
s.notify(message, false);
}
@@ -747,6 +773,7 @@ fn template(p: &Project) -> (Project, TemplateLosses) {
})
.saturating_add(t.tables.iter().filter(|table| table.source.is_some()).count());
for m in &mut t.maps {
+ m.offline_area_id = None;
for l in &mut m.layers {
l.dataset.features.clear();
l.selection.clear();
diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs
index 6c334da7fa..b7cb4967e2 100644
--- a/crates/engine/src/cmd/navigate.rs
+++ b/crates/engine/src/cmd/navigate.rs
@@ -197,6 +197,7 @@ pub fn commands() -> Vec {
C::new("map.rename", "Rename Map", "Layers", |s, p| {
let (i, name) = rename_choice(&super::InputSource::input_context(&*s), p)?;
let old = s.project.maps.get(i).map(|m| m.name.clone()).ok_or("no map")?;
+ super::workspace::bind_offline_map_before_rename(&mut s.project, i)?;
if let Some(m) = s.project.maps.get_mut(i) {
m.name = name.clone();
}
@@ -263,6 +264,7 @@ fn duplicate_map(s: &mut Session, p: &Value) -> CmdResult {
let i = map_at(s, p)?;
let mut m = s.project.maps.get(i).ok_or("no map")?.clone();
m.name = super::copy_name(ps(p, "name"), &m.name, |n| s.project.maps.iter().any(|x| x.name.eq_ignore_ascii_case(n)));
+ m.offline_area_id = None;
m.label_lock = None;
m.label_lock_line_anchors.clear();
m.renew_instance_id();
@@ -284,7 +286,7 @@ fn duplicate_map(s: &mut Session, p: &Value) -> CmdResult {
/// Points layout map frames, presentation map pages and offline areas at a renamed map (#287),
/// so they keep finding it.
-fn follow_renamed_map(s: &mut Session, old: &str, new: &str) {
+pub(crate) fn follow_renamed_map(s: &mut Session, old: &str, new: &str) {
let renamed = |m: &mut String| {
if m.eq_ignore_ascii_case(old) {
*m = new.to_string();
diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs
index 62dc9a43fd..9deee4afee 100644
--- a/crates/engine/src/cmd/project.rs
+++ b/crates/engine/src/cmd/project.rs
@@ -566,7 +566,7 @@ fn legacy_field_package(project: &Project) -> bool {
/// Unlinks the maps of the project just opened that hold only some of a table's rows from the
/// GeoPackage or PostGIS tables they were loaded from, as offline copies made now are, and says so:
/// every map of a field project (`field`, opened from a field package, or one with a field
-/// origin), else a home project's offline maps (` (offline)`). Saved before offline copies
+/// origin), else a home project's offline maps. Saved before offline copies
/// were unlinked, they would delete from the table every row they lack.
fn unlink_partial_copies(s: &mut Session, field: bool) {
if field || s.project.field_origin.is_some() {
diff --git a/crates/engine/src/cmd/workspace.rs b/crates/engine/src/cmd/workspace.rs
index 2eb91f78b4..f0e6c2dd8f 100644
--- a/crates/engine/src/cmd/workspace.rs
+++ b/crates/engine/src/cmd/workspace.rs
@@ -8,7 +8,7 @@ use rustgis_map::view::Keyframe;
use serde_json::{Value, json};
use super::{b, f, ps};
-use crate::project::{Job, OfflineArea};
+use crate::project::{Job, OfflineArea, Project};
use crate::{CmdResult, CommandSpec as C, Session};
/// Removes every Shapefile index not in use and says what it freed, what stayed and why, and which
@@ -268,14 +268,18 @@ pub fn commands() -> Vec {
C::new("offline.sync", "Sync", "Data › Offline", offline_sync).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"name": offline area}"#),
C::new("offline.remove", "Remove", "Data › Offline", |s, p| {
let n = ps(p, "name").ok_or("name is required")?;
- let before = s.project.offline_areas.len();
- s.project.offline_areas.retain(|a| !a.name.eq_ignore_ascii_case(n));
- if s.project.offline_areas.len() == before {
- return Err(format!("no offline area '{n}'"));
+ let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?;
+ let area = s.project.offline_areas.remove(ai);
+ let kept = offline_map_index(&s.project, &area);
+ // A copy kept as the only map is no longer the area's: neither its saved association
+ // nor its title may still claim the area that is gone.
+ for m in &mut s.project.maps {
+ if !area.id.is_empty() && m.offline_area_id.as_deref() == Some(area.id.as_str()) {
+ m.offline_area_id = None;
+ }
}
- let map_name = format!("{n} (offline)");
- if s.project.maps.len() > 1
- && let Some(i) = s.project.maps.iter().position(|m| m.name.eq_ignore_ascii_case(&map_name))
+ if let Some(i) = kept
+ && s.project.maps.len() > 1
{
s.project.maps.remove(i);
// The active map stays the same map; if it was the removed one, a neighbour.
@@ -284,24 +288,41 @@ pub fn commands() -> Vec {
if a == i {
s.active_layer = s.map().layers.first().map(|l| l.id);
}
+ } else if let Some(m) = kept.and_then(|i| s.project.maps.get_mut(i))
+ && m.name.eq_ignore_ascii_case(&offline_map_name(&area.name))
+ {
+ let old = std::mem::replace(&mut m.name, format!("{} (kept)", area.name));
+ let kept = m.name.clone();
+ // Layouts, presentations and other areas made from it follow, as on a rename.
+ super::navigate::follow_renamed_map(s, &old, &kept);
+ s.notify(format!("The offline area's map was the only one, so it was kept as '{kept}'"), false);
}
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name": offline area}"#),
C::new("offline.open", "Open Offline Map", "Data › Offline", |s, p| {
let n = ps(p, "name").ok_or("name is required")?;
- let a =
- s.project.offline_areas.iter().find(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?;
+ let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?;
+ let a = s.project.offline_areas.get_mut(ai).ok_or("no such area")?;
crate::project::ensure_map_imports_complete(&a.data)?;
- let map_name = format!("{} (offline)", a.name);
- if let Some(i) = s.project.maps.iter().position(|m| m.name.eq_ignore_ascii_case(&map_name)) {
- // An offline map saved before offline copies were unlinked from their tables.
- let unbound = s.project.maps.get_mut(i).map_or(0, unbind_map_table_edits);
- note_unbound(s, unbound, &format!("the offline map '{map_name}'"));
+ let id = ensure_area_id(a)?;
+ let a = s.project.offline_areas.get(ai).ok_or("no such area")?;
+ let extent = a.extent;
+ if let Some(i) = offline_map_index(&s.project, a) {
+ if let Some(m) = s.project.maps.get_mut(i) {
+ // Upgrade a legacy name match while the association is still known.
+ m.offline_area_id = Some(id);
+ let unbound = unbind_map_table_edits(m);
+ let copy = format!("the offline map '{}'", m.name);
+ note_unbound(s, unbound, ©);
+ }
s.project.active_map = i;
} else {
let mut m = a.data.clone();
- m.name = map_name;
+ let map_name = offline_map_name(&a.name);
+ let taken = |n: &str| s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(n));
+ m.name = if taken(&map_name) { super::numbered(&map_name, taken) } else { map_name };
+ m.offline_area_id = Some(id);
m.renew_instance_id();
// An area saved before offline copies were unlinked from their tables.
let unbound = unbind_map_table_edits(&mut m);
@@ -320,8 +341,7 @@ pub fn commands() -> Vec {
s.project.active_map = s.project.maps.len() - 1;
}
s.active_layer = s.map().layers.first().map(|l| l.id);
- let e = s.project.offline_areas.iter().find(|a| a.name.eq_ignore_ascii_case(n)).map(|a| a.extent).unwrap_or(Extent::EMPTY);
- s.zoom_to(&e);
+ s.zoom_to(&extent);
Ok(Value::Null)
}).roles(&[]).effects(crate::policy::Effects::NONE)
.params(r#"{"name": offline area}"#),
@@ -636,6 +656,7 @@ fn snapshot(m: &mut rustgis_map::Map, e: &Extent) -> rustgis_map::Map {
// feature layer is copied without its features, and only the features in the extent added.
let layers = std::mem::take(&mut m.layers);
let mut out = m.clone();
+ out.offline_area_id = None;
m.layers = layers;
for l in m.layers.iter_mut().filter(|l| !l.is_raster()) {
let features = std::mem::take(&mut l.dataset.features);
@@ -673,11 +694,57 @@ pub(crate) fn unbind_map_table_edits(m: &mut rustgis_map::Map) -> usize {
m.layers.iter_mut().map(unbind_table_edits).filter(|had| *had).count()
}
-/// [`unbind_map_table_edits`] for each of `project`'s offline areas' maps (` (offline)`),
-/// as the number of layers that had a link. The project's other maps keep theirs.
-pub(crate) fn unbind_offline_maps(project: &mut crate::project::Project) -> usize {
- let names: Vec = project.offline_areas.iter().map(|a| format!("{}{}", a.name, super::field::OFFLINE)).collect();
- project.maps.iter_mut().filter(|m| names.iter().any(|n| m.name.eq_ignore_ascii_case(n))).map(unbind_map_table_edits).sum()
+fn offline_map_name(area: &str) -> String {
+ format!("{area}{}", super::field::OFFLINE)
+}
+
+/// Legacy areas were saved without IDs. Give one an ID before binding a map to it.
+fn ensure_area_id(area: &mut OfflineArea) -> Result {
+ if area.id.is_empty() {
+ area.id = crate::project::field_id()?;
+ }
+ Ok(area.id.clone())
+}
+
+/// Finds the open copy by identity before trying the original title of an unmarked map.
+fn offline_map_index(project: &Project, area: &OfflineArea) -> Option {
+ let maps = &project.maps;
+ let by_id = maps.iter().position(|m| m.offline_area_id.as_deref().is_some_and(|id| id == area.id));
+ by_id.or_else(|| {
+ let name = offline_map_name(&area.name);
+ maps.iter()
+ .position(|m| m.offline_area_id.is_none() && m.name.eq_ignore_ascii_case(&name) && !m.name.eq_ignore_ascii_case(&area.map))
+ })
+}
+
+/// Resolves the reverse association using the same precedence as opening the area.
+pub(crate) fn map_area_index(project: &Project, map: usize) -> Option {
+ project.offline_areas.iter().position(|area| offline_map_index(project, area) == Some(map))
+}
+
+/// Before a rename takes away a legacy copy's only link to its area, record the area ID.
+pub(crate) fn bind_offline_map_before_rename(project: &mut Project, map: usize) -> Result<(), String> {
+ if project.maps.get(map).is_some_and(|m| m.offline_area_id.is_none())
+ && let Some(area) = map_area_index(project, map).and_then(|i| project.offline_areas.get_mut(i))
+ {
+ let id = ensure_area_id(area)?;
+ if let Some(m) = project.maps.get_mut(map) {
+ m.offline_area_id = Some(id);
+ }
+ }
+ Ok(())
+}
+
+/// Unlinks table edits on marked offline copies and on legacy copies matched to an area.
+pub(crate) fn unbind_offline_maps(project: &mut Project) -> usize {
+ let offline: Vec = project.offline_areas.iter().filter_map(|a| offline_map_index(project, a)).collect();
+ project
+ .maps
+ .iter_mut()
+ .enumerate()
+ .filter(|(i, m)| m.offline_area_id.is_some() || offline.contains(i))
+ .map(|(_, m)| unbind_map_table_edits(m))
+ .sum()
}
/// Says that `n` layers of an offline copy no longer save to their tables, when `n` isn't 0.
@@ -724,7 +791,7 @@ pub(crate) fn offline_download(s: &mut Session, p: &Value) -> CmdResult {
// Unique among areas, and its offline map's name (" (offline)") unused by other maps.
let taken = |s: &Session, n: &str| {
s.project.offline_areas.iter().any(|a| a.name.eq_ignore_ascii_case(n))
- || s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(&format!("{n} (offline)")))
+ || s.project.maps.iter().any(|m| m.name.eq_ignore_ascii_case(&offline_map_name(n)))
};
while taken(s, &name) {
i += 1;
@@ -769,8 +836,7 @@ fn offline_sync(s: &mut Session, p: &Value) -> CmdResult {
let n = ps(p, "name").ok_or("name is required")?;
let ai = s.project.offline_areas.iter().position(|a| a.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no offline area '{n}'"))?;
let area = s.project.offline_areas.get(ai).cloned().ok_or("no such area")?;
- let offline_map = format!("{} (offline)", area.name);
- let edited = s.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(&offline_map)).cloned().unwrap_or_else(|| area.data.clone());
+ let edited = offline_map_index(&s.project, &area).and_then(|i| s.project.maps.get(i)).cloned().unwrap_or_else(|| area.data.clone());
sync_area(s, ai, &edited)
}
@@ -786,7 +852,7 @@ fn offline_sync(s: &mut Session, p: &Value) -> CmdResult {
/// said as a conflict).
pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) -> CmdResult {
let area = s.project.offline_areas.get(ai).cloned().ok_or("no such area")?;
- let offline_map = format!("{} (offline)", area.name);
+ let offline_map = offline_map_index(&s.project, &area);
let si = s
.project
.maps
@@ -876,10 +942,11 @@ pub(crate) fn sync_area(s: &mut Session, ai: usize, edited: &rustgis_map::Map) -
}
}
let fresh = s.project.maps.get_mut(si).map(|m| snapshot(m, &area.extent)).ok_or("the source map is gone")?;
- if let Some(m) = s.project.maps.iter_mut().find(|m| m.name.eq_ignore_ascii_case(&offline_map)) {
+ if let Some(m) = offline_map.and_then(|i| s.project.maps.get_mut(i)) {
let name = m.name.clone();
*m = fresh.clone();
m.name = name;
+ m.offline_area_id = (!area.id.is_empty()).then(|| area.id.clone());
// A copy of the source map: a map, and layers, of its own.
m.renew_instance_id();
for l in &mut m.layers {
diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs
index 0b139f025b..1430b9dba7 100644
--- a/crates/engine/src/project.rs
+++ b/crates/engine/src/project.rs
@@ -90,6 +90,7 @@ pub const CAPABILITIES: &[&str] = &[
"layout-element-wrap",
"layout-chart-data",
"field-generation",
+ "offline-map-area-id",
"crs-wkt",
"zarr-window",
];
@@ -1703,6 +1704,7 @@ impl Project {
}
})?;
let mut area_ids = std::collections::HashSet::new();
+ let mut offline_map_ids = std::collections::HashSet::new();
if (!p.origin_id.is_empty() && !valid_field_id(&p.origin_id))
|| p.field_origin.as_ref().is_some_and(|origin| {
!valid_field_id(&origin.project)
@@ -1713,6 +1715,7 @@ impl Project {
(!area.id.is_empty() && (!valid_field_id(&area.id) || !area_ids.insert(area.id.as_str())))
|| (!area.generation.is_empty() && !valid_field_id(&area.generation))
})
+ || p.maps.iter().any(|map| map.offline_area_id.as_deref().is_some_and(|id| !valid_field_id(id) || !offline_map_ids.insert(id)))
{
return Err("not a RustGIS project: an offline field identity is invalid or duplicated".into());
}
diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs
index eae5fd187c..babc694c49 100644
--- a/crates/engine/src/project_capabilities.rs
+++ b/crates/engine/src/project_capabilities.rs
@@ -326,7 +326,9 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
fn map_capabilities<'a>(maps: impl IntoIterator- ) -> Vec<&'static str> {
let (mut block, mut shape, mut water, mut shore, mut relief, mut light, mut legends, mut sized, mut pictures, mut zarr) =
(false, false, false, false, false, false, false, false, false, false);
+ let mut offline_area_id = false;
for map in maps {
+ offline_area_id |= map.offline_area_id.is_some();
if let Some(t) = &map.view.terrain {
block |= t.block.is_some();
// A round block (#2318), which an older reader would draw and save as a box.
@@ -355,6 +357,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator
- ) -> Vec<&'static
(sized, super::SIZE_BY_CAPABILITY),
(pictures, "picture-markers"),
(zarr, "zarr-window"),
+ (offline_area_id, "offline-map-area-id"),
]
.into_iter()
.filter_map(|(used, name)| used.then_some(name))
diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs
index 3dfc3b5466..6a2bb6de9f 100644
--- a/crates/map/src/lib.rs
+++ b/crates/map/src/lib.rs
@@ -1597,6 +1597,9 @@ pub enum Drawn {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Map {
pub name: String,
+ /// The home project's offline area this map edits, independent of the tab title.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub offline_area_id: Option,
pub layers: Vec,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub service_groups: Vec,
@@ -1749,6 +1752,7 @@ impl Map {
pub fn new(name: impl Into) -> Self {
Map {
name: name.into(),
+ offline_area_id: None,
layers: Vec::new(),
service_groups: Vec::new(),
groups: Vec::new(),
@@ -3146,6 +3150,7 @@ impl Map {
pub fn slots(&self) -> Vec> {
let Map {
name: _,
+ offline_area_id: _,
layers,
service_groups,
groups: _,
diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs
index e13fbbb78b..02cb6689e8 100644
--- a/crates/ui-touch/src/lib.rs
+++ b/crates/ui-touch/src/lib.rs
@@ -157,7 +157,7 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) {
} else {
0
}
- + usize::from(app.session.map().name.ends_with(" (offline)"))
+ + usize::from(can_send_field_package(app))
+ copies_rows(&ctx)
}
Sheet::Capture => capture_rows(app, &ctx),
@@ -267,6 +267,20 @@ fn stop_track(app: &mut RustGisApp, ctx: &egui::Context) -> bool {
false
}
+/// Field provenance survives a tab rename. Old field packages can still have just the title. A
+/// field package goes back with its one map only, so a field project with a map added doesn't
+/// offer it (sending would refuse it).
+fn can_send_field_package(app: &RustGisApp) -> bool {
+ let map = app.session.map();
+ let project = &app.session.project;
+ if project.field_origin.is_some() {
+ return project.maps.len() == 1;
+ }
+ // An area ID with no area (a damaged file) is no copy to send.
+ let area = map.offline_area_id.as_deref().map(|id| project.offline_areas.iter().any(|a| a.id == id));
+ area.unwrap_or_else(|| map.name.ends_with(" (offline)"))
+}
+
/// Draws where the device is: a dot, in a ring as wide as the position is good to.
fn position(app: &RustGisApp, painter: &egui::Painter, fix: rustgis_ui_egui::rustgis_engine::platform::Fix, t: &Tokens) {
let Some(at) = app.lonlat_to_screen(fix.lon, fix.lat) else { return };
@@ -1459,7 +1473,7 @@ fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
}
// A map opened from a field package goes back as one: its edits and photos, for Bring Back
// on the computer it came from.
- if app.session.map().name.ends_with(" (offline)") && row(ui, t, "package", tl!("Send Field Package")) {
+ if can_send_field_package(app) && row(ui, t, "package", tl!("Send Field Package")) {
set_sheet(&ctx, Sheet::None);
run(app, "ui.saveItem", json!({"kind": "fieldPackage"}));
}
@@ -1877,6 +1891,13 @@ mod tests {
}
}
+ #[test]
+ fn a_map_naming_a_missing_area_is_not_offered_for_sending() {
+ let mut app = RustGisApp::with_sample();
+ app.session.map_mut().offline_area_id = Some("gone".into());
+ assert!(!can_send_field_package(&app));
+ }
+
#[test]
fn live_position_prefers_a_recent_accurate_android_fix() {
use rustgis_ui_egui::rustgis_engine::platform::Event;
diff --git a/schema/fixtures/offline_map_area_id.rgis b/schema/fixtures/offline_map_area_id.rgis
new file mode 100644
index 0000000000..a75663ecd9
--- /dev/null
+++ b/schema/fixtures/offline_map_area_id.rgis
@@ -0,0 +1,36 @@
+{
+ "format": 2,
+ "name": "Renamed offline map",
+ "requires": ["offline-map-area-id", "field-origin"],
+ "active_map": 1,
+ "maps": [
+ {
+ "name": "Map",
+ "layers": [],
+ "basemap": "Paper",
+ "camera": {"center": {"x": 0, "y": 0}, "res": 30000}
+ },
+ {
+ "name": "Renamed at home",
+ "offline_area_id": "00112233445566778899aabbccddeeff",
+ "layers": [],
+ "basemap": "Paper",
+ "camera": {"center": {"x": 0, "y": 0}, "res": 30000}
+ }
+ ],
+ "offline_areas": [
+ {
+ "id": "00112233445566778899aabbccddeeff",
+ "name": "Crew",
+ "map": "Map",
+ "extent": {"min_x": -20, "min_y": -40, "max_x": 60, "max_y": 40},
+ "created": 0,
+ "data": {
+ "name": "Map",
+ "layers": [],
+ "basemap": "Paper",
+ "camera": {"center": {"x": 0, "y": 0}, "res": 30000}
+ }
+ }
+ ]
+}
diff --git a/schema/project.schema.json b/schema/project.schema.json
index f89c3797cb..cb005dc112 100644
--- a/schema/project.schema.json
+++ b/schema/project.schema.json
@@ -1086,6 +1086,7 @@
"layout-element-wrap",
"layout-chart-data",
"field-generation",
+ "offline-map-area-id",
"crs-wkt",
"zarr-window"
],
@@ -1171,6 +1172,7 @@
"layout-element-wrap",
"layout-chart-data",
"field-generation",
+ "offline-map-area-id",
"crs-wkt",
"zarr-window"
],