From 7a9b17b095cb2aaa1225700d8db87c59cdde001f Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 10:22:10 -0600 Subject: [PATCH 01/24] fix(engine): photos named at home go out with a field package and come back to where they are A field package carried the photos a feature named only on the way back, so a crew opened a package whose photo fields named files on the office computer, and nothing said so (#2485). Going out, Package for the Field now puts the pictures a photos field names by full path into the package within the budget left after the basemaps, and the notice counts those left out: not on this computer (or not named by a full path), not pictures, or past the budget. On the phone they unpack beside the project, as returned photos do at home. Coming back, a photo that came from home is named in the package's index by its path at home, and the change list's old photo values are mapped back the same way, so Bring Back keeps the home file instead of copying it and an edit or deletion of its feature is no conflict. Part of #2485. --- crates/engine/src/cmd/field.rs | 320 +++++++++++++++++---- crates/engine/src/cmd/field_audit_tests.rs | 13 +- docs/user-guide/field-work.md | 8 +- 3 files changed, 280 insertions(+), 61 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 54831e25c4..36fe711187 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -265,23 +265,47 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not if !unread.is_empty() { archive_error(s, format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } - // Coming back, the photos taken in the field go with their features. + // The photos the features name go with them: going out, those named here; coming back, those + // taken in the field (and those that came from home, under their paths there). + let photos = take_photos(&mut map, &mut budget); + // Coming back, a photo too large for the package was always an error; going out, it stays + // home with the others left out. + let mut unread = photos.unread; if coming_back { - let photos = take_photos(&mut map, &mut budget); - if !photos.unread.is_empty() { - let unread = &photos.unread; - archive_error(s, format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + unread.extend(photos.too_large.iter().map(|path| format!("{path} (too large for the field package)"))); + } + if !unread.is_empty() { + archive_error(s, format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + } + if !photos.not_pictures.is_empty() { + let named = &photos.not_pictures; + losses.push(format!( + "{} file(s) a photos field names weren't put in the field package: only pictures go ({}): {}", + named.len(), + PICTURES.join(", "), + named.join(", ") + )); + } + if !coming_back { + if !photos.missing.is_empty() { + let named = &photos.missing; + losses.push(format!( + "{} photo(s) a photos field names aren't files on this computer by their full path, so they stayed out of the field package: {}", + named.len(), + some_of(named) + )); } - if !photos.not_pictures.is_empty() { - let named = &photos.not_pictures; + if !photos.too_large.is_empty() { + let named = &photos.too_large; losses.push(format!( - "{} file(s) a photos field names weren't put in the field package: only pictures go ({}): {}", + "{} photo(s) didn't fit in the field package with the basemaps and photos before them, so they stayed home: {}", named.len(), - PICTURES.join(", "), - named.join(", ") + some_of(named) )); } - entries.extend(photos.entries); + } + entries.extend(photos.entries); + if coming_back { // What the phone changed in the rows it was given, which Bring Back applies. let package = s.project.field_origin.as_ref().map(|o| o.package.clone()).unwrap_or_default(); match s.project.field_origin.as_ref().filter(|_| package.is_empty()) { @@ -293,7 +317,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not } if !package.is_empty() { match super::field_changes::list(s.map(), &package) { - Ok(Some(changes)) => { + Ok(Some(mut changes)) => { + photos_named_at_home(&mut changes); if !changes.gone.is_empty() { losses.push(format!( "{} layer(s) the field package gave were removed from its map, so none of their features change at home: {}", @@ -815,23 +840,51 @@ fn rewrite_photos(map: &mut rustgis_map::Map, mut rewrite: impl FnMut(&str) -> S let features = &mut l.dataset.features; for row in 0..features.len() { let rustgis_data::Value::Text(held) = features.value(row, fi) else { continue }; - // Only the paths rewritten change: the rest of the text stays as it was written, so - // a feature isn't seen as edited for its spacing. - let (mut out, mut last) = (String::new(), 0); - for r in photo_paths(held) { - let (Some(before), Some(path)) = (held.get(last..r.start), held.get(r.clone())) else { continue }; - let new = rewrite(path); - if new != path { - out.push_str(before); - out.push_str(&new); - last = r.end; - } + if let Some(out) = rewrite_paths(held, &mut rewrite) { + let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); } - if last == 0 { - continue; + } + } +} + +/// A photos field's text `held` with each path rewritten by `rewrite`, or `None` when none +/// changes. Only the paths rewritten change: the rest of the text stays as it was written, so a +/// feature isn't seen as edited for its spacing. +fn rewrite_paths(held: &str, rewrite: &mut impl FnMut(&str) -> String) -> Option { + let (mut out, mut last) = (String::new(), 0); + for r in photo_paths(held) { + let (Some(before), Some(path)) = (held.get(last..r.start), held.get(r.clone())) else { continue }; + let new = rewrite(path); + if new != path { + out.push_str(before); + out.push_str(&new); + last = r.end; + } + } + if last == 0 { + return None; + } + out.push_str(held.get(last..).unwrap_or_default()); + Some(out) +} + +/// Names each photo a package brought from home by its path at home again in the old values of +/// `changes`: the field held it at the path it was unpacked to, and Bring Back checks each old +/// value against home's. +fn photos_named_at_home(changes: &mut super::field_changes::Changes) { + let mut unpacked = Unpacked::new(); + let mut at_home = |path: &str| home_path(&mut unpacked, path); + for layer in &mut changes.layers { + for given in layer.edited.iter_mut().chain(layer.deleted.iter_mut()) { + for (field, value) in &mut given.values { + if !(field.eq_ignore_ascii_case("photos") || field.eq_ignore_ascii_case("photo")) { + continue; + } + let rustgis_data::Value::Text(held) = value else { continue }; + if let Some(out) = rewrite_paths(held, &mut at_home) { + *value = rustgis_data::Value::Text(out); + } } - out.push_str(held.get(last..).unwrap_or_default()); - let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); } } } @@ -876,18 +929,24 @@ fn photo_paths(held: &str) -> Vec> { } /// The photo files `map`'s features name that are on this device, as package entries under -/// `photos/` (within `budget`), each feature then naming its photos there; and the photos named -/// that couldn't be read. Only picture files ([`PICTURES`]) named by an absolute path go in, each -/// under a plain name ([`plain_name`]): a photos field is free text, and could name any file. A -/// photo named that isn't on this device (one named at home) is left as it is named. +/// `photos/` (within `budget`), each feature then naming its photos there, with [`INDEX`] giving +/// the path each was named by. Only picture files ([`PICTURES`]) named by an absolute path go in, +/// each under a plain name ([`plain_name`]): a photos field is free text, and could name any file. +/// A photo that isn't on this device (one named at home, in a returning package) is left as it is +/// named, and listed in [`Photos::missing`]. A photo a package brought from home goes back under +/// the path home named it by, from the [`INDEX`] unpacked beside it, so Bring Back finds it where +/// it already is instead of copying it. fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { - let (mut entries, mut unread, mut not_pictures) = (Vec::new(), Vec::new(), Vec::new()); + let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); let mut placed: std::collections::HashMap = std::collections::HashMap::new(); let mut taken = std::collections::HashSet::new(); - // The files already said (not pictures, or unread): each said once, however many name it. + // The files already said (missing, not pictures, too large, or unread): each said once, + // however many name it. let mut said = std::collections::HashSet::new(); + // The index unpacked with each folder of photos a package brought: entry → path at home. + let mut unpacked = Unpacked::new(); rewrite_photos(map, |path| { if let Some(entry) = placed.get(path) { return entry.clone(); @@ -899,23 +958,40 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { // A picture only: a photos field is free text, and could name any file on the device. let picture = file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))); if !file.is_absolute() { + said.insert(path.to_string()); + found.missing.push(path.to_string()); return path.to_string(); } - // Not on this device (a photo named at home): left as named. One there that can't be - // looked at is said, as one that can't be read is. - match std::fs::metadata(file) { - Ok(m) if m.is_file() => {} - Ok(_) => return path.to_string(), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return path.to_string(), + // Not on this device (in a returning package, a photo named at home): left as named. One + // there that can't be looked at is said, as one that can't be read is. + let size = match std::fs::metadata(file) { + Ok(m) if m.is_file() => m.len(), + // A folder, or nothing there: no photo file on this device. + Ok(_) => { + said.insert(path.to_string()); + found.missing.push(path.to_string()); + return path.to_string(); + } + // The browser has no files to look at by path: not here either. + Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::Unsupported) => { + said.insert(path.to_string()); + found.missing.push(path.to_string()); + return path.to_string(); + } Err(e) => { said.insert(path.to_string()); - unread.push(format!("{path} ({e})")); + found.unread.push(format!("{path} ({e})")); return path.to_string(); } - } + }; if !picture { said.insert(path.to_string()); - not_pictures.push(path.to_string()); + found.not_pictures.push(path.to_string()); + return path.to_string(); + } + if size > *budget { + said.insert(path.to_string()); + found.too_large.push(path.to_string()); return path.to_string(); } match crate::project::read_file(file, *budget) { @@ -930,30 +1006,74 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { name = format!("{n}-{stem}"); } let entry = format!("{PHOTOS}/{name}"); - index.push_str(&format!("{entry}\t{path}\n")); - entries.push((entry.clone(), bytes)); + // Brought from home in this package: named by its path at home again. + let named = home_path(&mut unpacked, path); + index.push_str(&format!("{entry}\t{named}\n")); + found.entries.push((entry.clone(), bytes)); placed.insert(path.to_string(), entry.clone()); entry } Err(e) => { said.insert(path.to_string()); - unread.push(format!("{path} ({e})")); + found.unread.push(format!("{path} ({e})")); path.to_string() } } }); if !index.is_empty() { - entries.push((INDEX.to_string(), index.into_bytes())); + found.entries.push((INDEX.to_string(), index.into_bytes())); } - Photos { entries, unread, not_pictures } + found } -/// What [`take_photos`] found: the package's photo entries (with [`INDEX`]), the photos that -/// couldn't be read, and the files named that aren't pictures. +/// The first few of `names`, and how many more: a photos layer can name thousands. +fn some_of(names: &[String]) -> String { + const SHOWN: usize = 10; + let first = names.iter().take(SHOWN).cloned().collect::>().join(", "); + match names.len().saturating_sub(SHOWN) { + 0 => first, + more => format!("{first} and {more} more"), + } +} + +/// The [`INDEX`] of each folder of photos a package unpacked, read once: entry → path at home. +type Unpacked = std::collections::HashMap>; + +/// The path a photo at `path` was named by at home, when a package brought it from there (the +/// [`INDEX`] unpacked beside it names it); otherwise `path` itself. +fn home_path(unpacked: &mut Unpacked, path: &str) -> String { + let file = Path::new(path); + file.parent() + .zip(file.file_name()) + .and_then(|(folder, own)| { + let index = unpacked.entry(folder.to_path_buf()).or_insert_with(|| unpacked_index(folder)); + index.get(&format!("{PHOTOS}/{}", own.to_string_lossy())).cloned() + }) + .unwrap_or_else(|| path.to_string()) +} + +/// The [`INDEX`] a package unpacked into `folder` (its `photos` folder), as entry → path named +/// by where it was packaged; empty where there is none, or it can't be read. +fn unpacked_index(folder: &Path) -> std::collections::HashMap { + if folder.file_name().is_none_or(|n| n != PHOTOS) { + return std::collections::HashMap::new(); + } + let Ok(text) = std::fs::read_to_string(folder.join(INDEX.trim_start_matches(&format!("{PHOTOS}/")))) else { + return std::collections::HashMap::new(); + }; + text.lines().filter_map(|l| l.split_once('\t')).map(|(entry, named)| (entry.to_string(), named.to_string())).collect() +} + +/// What [`take_photos`] found: the package's photo entries (with [`INDEX`]), and the photos named +/// that stay out of it: not on this device (or not named by a full path), not pictures, past the +/// package's budget, or unreadable. +#[derive(Default)] struct Photos { entries: Vec<(String, Vec)>, - unread: Vec, + missing: Vec, not_pictures: Vec, + too_large: Vec, + unread: Vec, } /// The entry listing each photo of a package and the path its feature named it by before @@ -2221,9 +2341,14 @@ mod tests { std::fs::write(&picture, b"first").unwrap(); let named = format!("{};{}", secret.display(), picture.display()); home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": named})).unwrap(); - // Going out: no photos, whatever the features name. + // Going out: the picture, under a plain name; the text file is said and stays home. + let mark = home.notice_mark(); let (_, out) = package(&mut home, &json!({"name": "Pics", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); - assert!(rustgis_data::zip::read(&out).unwrap().iter().all(|(n, _)| !n.starts_with("photos/"))); + let photos: Vec = + rustgis_data::zip::read(&out).unwrap().into_iter().map(|(n, _)| n).filter(|n| n.starts_with("photos/") && n != INDEX).collect(); + assert_eq!(photos, ["photos/_pending.jpg"]); + let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("1 file(s) a photos field names") && t.contains("notes.txt")), "{said:?}"); // Coming back: the picture only, under a plain name; the text file stays named as it was. let unpacked = temp.path().join("field"); let text = unpack_into(&out, &unpacked).unwrap().0; @@ -2291,6 +2416,97 @@ mod tests { assert!(!temp.path().join("Here photos").join("a.jpg").exists()); } + /// A photo named at home goes out with its feature, and comes back to the path it has at home: + /// an edit to its feature's photos, or the feature's deletion, is no conflict and copies + /// nothing. Photos the package can't carry are counted, going out. + #[test] + fn photos_named_at_home_go_out_and_come_back_to_their_own_paths() { + let temp = Temp::new("home-photos"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let (kept, dropped) = (temp.path().join("kept.jpg"), temp.path().join("dropped.jpg")); + std::fs::write(&kept, b"kept at home").unwrap(); + std::fs::write(&dropped, b"of a feature deleted in the field").unwrap(); + let missing = temp.path().join("not-here.jpg"); + let set = |s: &mut Session, row: usize, text: String| { + s.run("edit.setValue", &json!({"layer": cities, "row": row, "field": "photos", "value": text})).unwrap(); + }; + set(&mut home, 0, kept.display().to_string()); + set(&mut home, 1, dropped.display().to_string()); + set(&mut home, 2, format!("{};relative.jpg", missing.display())); + let (ids, before) = { + let f = &home.map().layer(cities).unwrap().dataset.features; + ([f[0].id, f[1].id], f.len()) + }; + let mark = home.notice_mark(); + let (_, out) = package(&mut home, &json!({"name": "Away", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let entries = rustgis_data::zip::read(&out).unwrap(); + assert!(entries.iter().any(|(n, b)| n == "photos/kept.jpg" && b == b"kept at home")); + assert!(entries.iter().any(|(n, b)| n == "photos/dropped.jpg" && b == b"of a feature deleted in the field")); + // The two named that aren't files here (one by no full path) are counted, for the sender + // and the crew. + let expected = "2 photo(s) a photos field names aren't files on this computer by their full path"; + let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert_eq!(said.iter().filter(|t| t.starts_with(expected) && t.contains("relative.jpg")).count(), 1, "{said:?}"); + let unpacked = temp.path().join("field"); + let (text, losses) = unpack_into(&out, &unpacked).unwrap(); + assert!(losses.iter().any(|t| t.starts_with(expected)), "{losses:?}"); + let mut field = opened(project_in(&text, &unpacked).unwrap()); + field.opened_package = Some(temp.path().join("sent.rgisfield")); + let there = unpacked.join("photos").join("kept.jpg"); + assert_eq!(Path::new(&value(&field, "Cities", 0, "photos")), there.as_path()); + // In the field: a photo added to the first feature, the second feature deleted. + let taken = temp.path().join("photo-9.jpg"); + std::fs::write(&taken, b"taken in the field").unwrap(); + set(&mut field, 0, format!("{};{}", there.display(), taken.display())); + field.run("select.rows", &json!({"layer": cities, "rows": [1]})).unwrap(); + field.run("edit.delete", &Value::Null).unwrap(); + let (_, back) = package(&mut field, &Value::Null).unwrap(); + std::fs::remove_file(&taken).unwrap(); + let sent = temp.path().join("back.rgisfield"); + std::fs::write(&sent, &back).unwrap(); + let done = home.run("offline.bringBack", &json!({"path": sent.display().to_string()})).unwrap(); + assert_eq!( + (done["updated"].as_u64(), done["deleted"].as_u64(), done["conflicts"].as_u64(), done["kept"].as_u64()), + (Some(1), Some(1), Some(0), Some(0)), + "{done}" + ); + let f = &home.map().layer(cities).unwrap().dataset.features; + assert_eq!(f.len(), before - 1); + assert!(f.iter().all(|r| r.id != ids[1])); + // The home photo keeps its own path; only the field's is copied in. + let row = f.iter().position(|r| r.id == ids[0]).unwrap(); + let copied = temp.path().join("Away photos").join("photo-9.jpg"); + assert_eq!(value(&home, "Cities", row, "photos"), format!("{};{}", kept.display(), copied.display())); + assert_eq!(std::fs::read(&copied).unwrap(), b"taken in the field"); + assert!(!temp.path().join("Away photos").join("kept.jpg").exists()); + assert!(home.project.offline_areas[0].conflicts.is_empty()); + } + + /// A photo past what the package has room for stays home, and is counted. + #[test] + fn a_photo_past_the_packages_budget_stays_home_and_is_counted() { + let temp = Temp::new("photo-budget"); + let (small, large) = (temp.path().join("small.jpg"), temp.path().join("large.jpg")); + std::fs::write(&small, [0u8; 8]).unwrap(); + std::fs::write(&large, [0u8; 64]).unwrap(); + let mut s = sample(); + let cities = layer(&s, "Cities"); + s.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let named = format!("{};{}", small.display(), large.display()); + s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": named})).unwrap(); + let mut map = s.map().clone(); + let mut budget = 32; + let photos = take_photos(&mut map, &mut budget); + assert_eq!(photos.too_large, [large.display().to_string()]); + assert_eq!(budget, 24); + let held = map.layer(cities).unwrap(); + let text = held.dataset.value(0, held.dataset.field_index("photos").unwrap()).to_string(); + assert_eq!(text, format!("photos/small.jpg;{}", large.display())); + } + #[test] fn a_photo_in_a_folder_with_a_semicolon_goes_and_other_text_is_kept_as_written() { let temp = Temp::new("semicolon"); diff --git a/crates/engine/src/cmd/field_audit_tests.rs b/crates/engine/src/cmd/field_audit_tests.rs index 0c1be29816..48a2544954 100644 --- a/crates/engine/src/cmd/field_audit_tests.rs +++ b/crates/engine/src/cmd/field_audit_tests.rs @@ -602,15 +602,16 @@ fn a_feature_with_a_photo_deleted_in_the_field_is_deleted_at_home() { home.run("offline.sync", &json!({"name": "Day"})).unwrap(); let (_, out) = package(&mut home, &Value::Null).unwrap(); home.run("map.activate", &json!({"name": home.project.offline_areas[0].map.clone()})).unwrap(); - assert!(rustgis_data::zip::read(&out).unwrap().iter().all(|(n, _)| !n.starts_with("photos/"))); + // The photo goes with its feature, and the phone names it where it was unpacked: the + // deletion's old value still matches home's, which names it where it is at home. + assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, b)| n == "photos/at-home.jpg" && b == b"home photo")); let mut a = phone(&temp, &out, "a"); - assert!(!temp.0.join("a").join("photos").exists(), "no photos folder, so project_in rewrote nothing"); let cities = layer(&a, "Cities"); let r = a.map().layer(cities).unwrap().dataset.features.iter().position(|f| f.id == id).unwrap(); - assert_eq!( - a.map().layer(cities).unwrap().dataset.value(r, a.map().layer(cities).unwrap().dataset.field_index("photos").unwrap()).to_string(), - photo.display().to_string() - ); + let unpacked = + a.map().layer(cities).unwrap().dataset.value(r, a.map().layer(cities).unwrap().dataset.field_index("photos").unwrap()).to_string(); + assert_ne!(unpacked, photo.display().to_string()); + assert_eq!(std::fs::read(&unpacked).unwrap(), b"home photo"); a.run("select.rows", &json!({"layer": cities, "rows": [r]})).unwrap(); a.run("edit.delete", &Value::Null).unwrap(); let (done, said) = bring_back(&temp, &mut a, &mut home, "a"); diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index ab62a074ae..790e82c2fc 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -144,8 +144,9 @@ field package carries the archives its map draws from. Tile layers from the web A field package (`.rgisfield`) carries a map to the phone and its edits back. 1. **On the computer**, with the map in view, **Data › Offline › Package for the Field** makes - the package: a project of that map, the features in view, and the MBTiles and PMTiles - archives its tile layers use. The package records the area it was made from in your project, + the package: a project of that map, the features in view, the MBTiles and PMTiles archives its + tile layers use, and the photos its features name (pictures named by their full path, while + they fit the package; the notice counts any left out). The package records the area it was made from in your project, so save the project after packaging. A layer read in place from a supported local file is copied within the area while it fits the package budget. The copy is for reference, and Bring Back skips edits to it. The sender gets a notice about anything left behind, including @@ -206,7 +207,8 @@ command line or Python, `offline.conflicts` lists them with the project's `state them by index with that state, refusing a list read before the project changed. Only the photos of features the phone added, or whose photos it changed, come back: a photo of a -feature whose photos it left alone is left out, and the summary says how many. +feature whose photos it left alone is left out, and the summary says how many. A photo the package +took from the computer comes back to the file it was taken from, not as a copy. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From f87263e470d627ae305f4e460cd03846e69dc9a2 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 11:11:18 -0600 Subject: [PATCH 02/24] fix(engine): photos from home go back by their home path, not carried again Review follow-up: a photo the package brought from home is named by its path at home on the way back and isn't packaged, so it takes none of the return's room and a whole-map return sees no edit in a feature the field left alone. The unpacked index is read within a bound and only coming back, an entry listed twice maps nothing, Cancel is checked before each photo, and photos named by layers copied for reference are counted as staying home. --- crates/engine/src/cmd/field.rs | 126 ++++++++++++++++++--- crates/engine/src/cmd/field_audit_tests.rs | 11 +- 2 files changed, 116 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 36fe711187..9312a4a031 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -267,7 +267,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not } // The photos the features name go with them: going out, those named here; coming back, those // taken in the field (and those that came from home, under their paths there). - let photos = take_photos(&mut map, &mut budget); + let photos = take_photos(&mut map, &mut budget, coming_back)?; // Coming back, a photo too large for the package was always an error; going out, it stays // home with the others left out. let mut unread = photos.unread; @@ -412,6 +412,25 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not .extent; let available = project_room(companion_bytes(&entries)); copied = copy_streams(&mut map, extent, stream_budget(available), &mut losses)?; + // Their photos stay home: a reference copy's edits and photos don't come back. + let named: usize = map + .layers + .iter() + .filter(|l| copied.contains(&l.id)) + .filter_map(|l| photos_field(l).map(|fi| (l, fi))) + .map(|(l, fi)| { + l.dataset + .features + .column(fi) + .filter_map(|v| if let rustgis_data::Value::Text(t) = v { Some(photo_paths(t).len()) } else { None }) + .sum::() + }) + .sum(); + if named > 0 { + losses.push(format!( + "{named} photo reference(s) of layer(s) copied for reference stayed home: those copies' photos don't go in the field package" + )); + } } // Going out, the highest id each layer has: features added in the field are given ids above it, // and so are those added here, in the area's map or its offline map, while the package is out. @@ -933,10 +952,11 @@ fn photo_paths(held: &str) -> Vec> { /// the path each was named by. Only picture files ([`PICTURES`]) named by an absolute path go in, /// each under a plain name ([`plain_name`]): a photos field is free text, and could name any file. /// A photo that isn't on this device (one named at home, in a returning package) is left as it is -/// named, and listed in [`Photos::missing`]. A photo a package brought from home goes back under -/// the path home named it by, from the [`INDEX`] unpacked beside it, so Bring Back finds it where -/// it already is instead of copying it. -fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { +/// named, and listed in [`Photos::missing`]. Coming back (`returning`), a photo a package brought +/// from home is named by its path at home again, from the [`INDEX`] unpacked beside it, and isn't +/// carried: home has it, so it takes none of the package's room, and a feature whose photos the +/// field left alone names them as home does. Cancel is checked before each photo is looked at. +fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, returning: bool) -> Result { let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); @@ -947,13 +967,26 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { let mut said = std::collections::HashSet::new(); // The index unpacked with each folder of photos a package brought: entry → path at home. let mut unpacked = Unpacked::new(); + let mut cancelled = None; rewrite_photos(map, |path| { if let Some(entry) = placed.get(path) { return entry.clone(); } - if said.contains(path) { + if said.contains(path) || cancelled.is_some() { return path.to_string(); } + if let Err(e) = rustgis_data::progress::check() { + cancelled = Some(e.to_string()); + return path.to_string(); + } + // Brought from home in this package: named where it is at home, and not carried back. + if returning { + let at_home = home_path(&mut unpacked, path); + if at_home != path { + placed.insert(path.to_string(), at_home.clone()); + return at_home; + } + } let file = Path::new(path); // A picture only: a photos field is free text, and could name any file on the device. let picture = file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))); @@ -1006,9 +1039,7 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { name = format!("{n}-{stem}"); } let entry = format!("{PHOTOS}/{name}"); - // Brought from home in this package: named by its path at home again. - let named = home_path(&mut unpacked, path); - index.push_str(&format!("{entry}\t{named}\n")); + index.push_str(&format!("{entry}\t{path}\n")); found.entries.push((entry.clone(), bytes)); placed.insert(path.to_string(), entry.clone()); entry @@ -1020,10 +1051,13 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Photos { } } }); + if let Some(e) = cancelled { + return Err(e); + } if !index.is_empty() { found.entries.push((INDEX.to_string(), index.into_bytes())); } - found + Ok(found) } /// The first few of `names`, and how many more: a photos layer can name thousands. @@ -1058,12 +1092,26 @@ fn unpacked_index(folder: &Path) -> std::collections::HashMap { if folder.file_name().is_none_or(|n| n != PHOTOS) { return std::collections::HashMap::new(); } - let Ok(text) = std::fs::read_to_string(folder.join(INDEX.trim_start_matches(&format!("{PHOTOS}/")))) else { + // A package's own index, read within a bound: one line for each photo it carried. + let Ok(bytes) = crate::project::read_file(&folder.join(INDEX.trim_start_matches(&format!("{PHOTOS}/"))), MAX_INDEX) else { return std::collections::HashMap::new(); }; - text.lines().filter_map(|l| l.split_once('\t')).map(|(entry, named)| (entry.to_string(), named.to_string())).collect() + let text = String::from_utf8_lossy(&bytes); + let mut index = std::collections::HashMap::new(); + let mut twice = std::collections::HashSet::new(); + for (entry, named) in text.lines().filter_map(|l| l.split_once('\t')) { + // An entry listed twice names no path for certain: neither is used. + if index.insert(entry.to_string(), named.to_string()).is_some() { + twice.insert(entry.to_string()); + } + } + index.retain(|entry, _| !twice.contains(entry)); + index } +/// The most a package's photo index is read: a line for each of many thousand photos. +const MAX_INDEX: u64 = 16 << 20; + /// What [`take_photos`] found: the package's photo entries (with [`INDEX`]), and the photos named /// that stay out of it: not on this device (or not named by a full path), not pictures, past the /// package's budget, or unreadable. @@ -2400,13 +2448,14 @@ mod tests { let text = unpack_into(&out, &unpacked).unwrap().0; let mut field = opened(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); - // Sent back with no edit: the picture goes in, listed with its path; the gif is said. + // Sent back with no edit: the picture, brought from home, isn't carried back; the gif is + // said. let mark = field.notice_mark(); let (_, back) = package(&mut field, &Value::Null).unwrap(); let said: Vec = field.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.contains("only pictures go") && t.contains("b.gif")), "{said:?}"); let entries = rustgis_data::zip::read(&back).unwrap(); - assert!(entries.iter().any(|(n, b)| n == INDEX && String::from_utf8_lossy(b).contains(&*photo.display().to_string()))); + assert!(entries.iter().all(|(n, _)| !n.starts_with("photos/"))); // Brought back here: the photo is where it was, so nothing changed and nothing is copied. let sent = temp.path().join("back.rgisfield"); std::fs::write(&sent, &back).unwrap(); @@ -2464,6 +2513,14 @@ mod tests { field.run("select.rows", &json!({"layer": cities, "rows": [1]})).unwrap(); field.run("edit.delete", &Value::Null).unwrap(); let (_, back) = package(&mut field, &Value::Null).unwrap(); + // Only the field's photo goes back: home has its own. + let carried: Vec = rustgis_data::zip::read(&back) + .unwrap() + .into_iter() + .map(|(n, _)| n) + .filter(|n| n.starts_with("photos/") && n != INDEX) + .collect(); + assert_eq!(carried, ["photos/photo-9.jpg"]); std::fs::remove_file(&taken).unwrap(); let sent = temp.path().join("back.rgisfield"); std::fs::write(&sent, &back).unwrap(); @@ -2485,6 +2542,45 @@ mod tests { assert!(home.project.offline_areas[0].conflicts.is_empty()); } + /// A package that goes back as a whole map (its rows weren't kept on the device) names the + /// photos it brought from home where they are at home: a feature the field left alone is no + /// edit, even when home's photo changed on disk meanwhile, so home's own edit to it stays. + #[test] + fn a_whole_map_return_leaves_a_feature_with_a_home_photo_as_home_has_it() { + let temp = Temp::new("whole-map-photo"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let photo = temp.path().join("site.jpg"); + std::fs::write(&photo, b"as it went out").unwrap(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); + let id = home.map().layer(cities).unwrap().dataset.features[0].id; + let (_, out) = package(&mut home, &json!({"name": "Whole", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let unpacked = temp.path().join("field"); + let text = unpack_into(&out, &unpacked).unwrap().0; + // Opened where its rows aren't kept: it goes back as a whole map. + let mut field = Session::new(project_in(&text, &unpacked).unwrap()); + field.opened_package = Some(temp.path().join("sent.rgisfield")); + let mark = field.notice_mark(); + let (_, back) = package(&mut field, &Value::Null).unwrap(); + assert!(field.notices_since(mark).iter().any(|n| n.text.contains("as a whole map"))); + assert!(rustgis_data::zip::read(&back).unwrap().iter().all(|(n, _)| n != "photos/site.jpg")); + // Meanwhile at home: the photo replaced on disk, and the feature's name changed. + std::fs::write(&photo, b"retaken at home").unwrap(); + let name = + home.map().layer(cities).unwrap().dataset.fields.iter().find(|f| f.ty == rustgis_data::FieldType::Text).unwrap().name.clone(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": name, "value": "Home Edit"})).unwrap(); + let sent = temp.path().join("back.rgisfield"); + std::fs::write(&sent, &back).unwrap(); + let done = home.run("offline.bringBack", &json!({"path": sent.display().to_string()})).unwrap(); + assert_eq!(done["updated"].as_u64(), Some(0), "{done}"); + let row = home.map().layer(cities).unwrap().dataset.features.iter().position(|f| f.id == id).unwrap(); + assert_eq!(value(&home, "Cities", row, &name), "Home Edit"); + assert_eq!(value(&home, "Cities", row, "photos"), photo.display().to_string()); + assert!(!temp.path().join("Whole photos").exists()); + } + /// A photo past what the package has room for stays home, and is counted. #[test] fn a_photo_past_the_packages_budget_stays_home_and_is_counted() { @@ -2499,7 +2595,7 @@ mod tests { s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": named})).unwrap(); let mut map = s.map().clone(); let mut budget = 32; - let photos = take_photos(&mut map, &mut budget); + let photos = take_photos(&mut map, &mut budget, false).unwrap(); assert_eq!(photos.too_large, [large.display().to_string()]); assert_eq!(budget, 24); let held = map.layer(cities).unwrap(); diff --git a/crates/engine/src/cmd/field_audit_tests.rs b/crates/engine/src/cmd/field_audit_tests.rs index 48a2544954..868e10b168 100644 --- a/crates/engine/src/cmd/field_audit_tests.rs +++ b/crates/engine/src/cmd/field_audit_tests.rs @@ -803,7 +803,7 @@ fn a_field_removed_at_home_is_not_added_back_by_a_later_return() { } /// A photo the field didn't change, which home no longer has where it named it, isn't stored -/// at home with nothing naming it: it is left out, and said. +/// at home with nothing naming it: the package brought it from home, so it isn't carried back. #[test] fn a_photo_the_field_didnt_change_is_not_stored_unnamed() { let temp = Temp::new("unchanged-photo"); @@ -814,21 +814,20 @@ fn a_photo_the_field_didnt_change_is_not_stored_unnamed() { std::fs::write(&photo, b"photo bytes").unwrap(); home.run("edit.setValue", &json!({"layer": hc, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); let (_, out) = package(&mut home, &json!({"name": "All", "extent": [-180.0, -90.0, 180.0, 90.0]})).unwrap(); - // The phone sees the file where home named it (a shared folder), so the photo goes back. + // The photo went out with the package; coming back it is named where home has it, and + // not carried: home has it. let mut a = phone(&temp, &out, "a"); let cities = layer(&a, "Cities"); let name = text_field(&a, cities); add_point(&mut a, cities, &name, "Captured", [10.0, 5.0]); let (_, back) = package(&mut a, &Value::Null).unwrap(); - assert!(rustgis_data::zip::read(&back).unwrap().iter().any(|(n, _)| n == "photos/shared.jpg")); + assert!(rustgis_data::zip::read(&back).unwrap().iter().all(|(n, _)| !n.starts_with("photos/"))); std::fs::remove_file(&photo).unwrap(); let path = temp.0.join("back.rgisfield"); std::fs::write(&path, &back).unwrap(); - let mark = home.notice_mark(); let done = home.run("offline.bringBack", &json!({"path": path})).unwrap(); - assert_eq!(done["photos"].as_u64(), Some(0), "{done}"); + assert_eq!((done["photos"].as_u64(), done["updated"].as_u64()), (Some(0), Some(0)), "{done}"); assert!(!temp.0.join("All photos").join("shared.jpg").exists()); - assert!(home.notices_since(mark).iter().any(|n| n.text.contains("no change it brings back names"))); } /// Sending a return spends its package: once the file is written, the rows it gave are removed From 669bbeb2ce098810b5e298ea0b590c16848eb8c9 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 11:50:29 -0600 Subject: [PATCH 03/24] fix(engine): a package carries home photos without changing its features Review follow-up: going out, the photos are collected without rewriting the features (no copy of the area's shared rows); the phone points the features at the unpacked files from the package's index. Only an outgoing package's index (beside given.v1.json) maps photos back to home, so a return opened on another device carries its photos. A name a feature already gives under photos/ is kept, the index stays within what the phone reads, a path with a tab or line break stays home and is said, and the too-large error names photos. --- crates/engine/src/cmd/field.rs | 189 ++++++++++++++++++++++++++++----- 1 file changed, 165 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 9312a4a031..ec1c4f531c 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -265,9 +265,10 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not if !unread.is_empty() { archive_error(s, format!("{} tile archive(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); } - // The photos the features name go with them: going out, those named here; coming back, those + // The photos the features name go with them: going out, those named here, the features + // naming them as before (the phone points them at the unpacked files); coming back, those // taken in the field (and those that came from home, under their paths there). - let photos = take_photos(&mut map, &mut budget, coming_back)?; + let photos = if coming_back { take_photos(&mut map, &mut budget)? } else { collect_photos(&map, &mut budget)? }; // Coming back, a photo too large for the package was always an error; going out, it stays // home with the others left out. let mut unread = photos.unread; @@ -422,7 +423,14 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not l.dataset .features .column(fi) - .filter_map(|v| if let rustgis_data::Value::Text(t) = v { Some(photo_paths(t).len()) } else { None }) + // Counted by their separators, without looking at the disk: a count for the notice. + .filter_map(|v| { + if let rustgis_data::Value::Text(t) = v { + Some(t.split(';').filter(|p| !p.trim().is_empty()).count()) + } else { + None + } + }) .sum::() }) .sum(); @@ -497,7 +505,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not ); entries.push(("README.txt".into(), readme.into_bytes())); let companions = companion_bytes(&entries); - let too_large = || "the field package would be too large: leave a tile archive or some data out".to_string(); + let too_large = || "the field package would be too large: leave a tile archive, photos or some data out".to_string(); if !copied.is_empty() { let map = project.maps.first().ok_or("the field package holds no map")?; let names: Vec<_> = copied.iter().filter_map(|id| map.layer(*id)).map(|l| l.name.as_str()).collect(); @@ -947,16 +955,105 @@ fn photo_paths(held: &str) -> Vec> { out } -/// The photo files `map`'s features name that are on this device, as package entries under +/// The photos `map`'s features name that a package going out carries: each picture named by its +/// full path on this computer, under `photos/` (within `budget`), with [`INDEX`] giving the path +/// each was named by, which the phone points the features at the unpacked file by +/// ([`project_in`]). The features aren't changed here, so the rows the map shares with the +/// offline area aren't copied. A name a feature already gives under `photos/` isn't used for +/// another. What stays out is listed by kind. Cancel is checked before each photo is looked at. +fn collect_photos(map: &rustgis_map::Map, budget: &mut u64) -> Result { + let mut found = Photos::default(); + // Every path named, once, in order; and the names already given under `photos/`, kept. + let (mut named, mut seen, mut taken) = (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); + for l in map.layers.iter().filter(|l| !l.is_raster()) { + let Some(fi) = photos_field(l) else { continue }; + for value in l.dataset.features.column(fi) { + let rustgis_data::Value::Text(held) = value else { continue }; + for r in photo_paths(held) { + let Some(path) = held.get(r) else { continue }; + if let Some(name) = path.strip_prefix(&format!("{PHOTOS}/")) { + taken.insert(name.to_ascii_lowercase()); + } + if seen.insert(path.to_string()) { + named.push(path.to_string()); + } + } + } + } + let mut index = String::new(); + for path in named { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let file = Path::new(&path); + if !file.is_absolute() { + found.missing.push(path); + continue; + } + // The index holds one path a line, its fields split by tabs. + if path.contains(['\t', '\n', '\r']) { + found.unread.push(format!("{path} (its name holds a tab or line break)")); + continue; + } + let size = match std::fs::metadata(file) { + Ok(m) if m.is_file() => m.len(), + Ok(_) => { + found.missing.push(path); + continue; + } + // The browser has no files to look at by path: not here either. + Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::Unsupported) => { + found.missing.push(path); + continue; + } + Err(e) => { + found.unread.push(format!("{path} ({e})")); + continue; + } + }; + if !file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))) { + found.not_pictures.push(path); + continue; + } + let stem = file.file_name().map(|n| plain_name(&n.to_string_lossy())).unwrap_or_else(|| "photo.jpg".into()); + let mut name = stem.clone(); + for n in 2.. { + if !taken.contains(&name.to_ascii_lowercase()) { + break; + } + name = format!("{n}-{stem}"); + } + let entry = format!("{PHOTOS}/{name}"); + let line = format!("{entry}\t{path}\n"); + // Past the budget, or past what the phone reads of the index: it stays home. + if size > *budget || (index.len() + line.len()) as u64 > MAX_INDEX { + found.too_large.push(path); + continue; + } + match crate::project::read_file(file, *budget) { + Ok(bytes) => { + *budget = budget.saturating_sub(bytes.len() as u64); + taken.insert(name.to_ascii_lowercase()); + index.push_str(&line); + found.entries.push((entry, bytes)); + } + Err(e) => found.unread.push(format!("{path} ({e})")), + } + } + if !index.is_empty() { + found.entries.push((INDEX.to_string(), index.into_bytes())); + } + Ok(found) +} + +/// Coming back, the photo files `map`'s features name that are on this device, as package entries under /// `photos/` (within `budget`), each feature then naming its photos there, with [`INDEX`] giving /// the path each was named by. Only picture files ([`PICTURES`]) named by an absolute path go in, /// each under a plain name ([`plain_name`]): a photos field is free text, and could name any file. -/// A photo that isn't on this device (one named at home, in a returning package) is left as it is -/// named, and listed in [`Photos::missing`]. Coming back (`returning`), a photo a package brought -/// from home is named by its path at home again, from the [`INDEX`] unpacked beside it, and isn't +/// A photo that isn't on this device (one named at home) is left as it is named, and listed in +/// [`Photos::missing`]. A photo a package from home brought is named by +/// its path at home again, from the [`INDEX`] unpacked beside it ([`home_path`]), and isn't /// carried: home has it, so it takes none of the package's room, and a feature whose photos the /// field left alone names them as home does. Cancel is checked before each photo is looked at. -fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, returning: bool) -> Result { +fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Result { let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); @@ -980,12 +1077,10 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, returning: bool) -> return path.to_string(); } // Brought from home in this package: named where it is at home, and not carried back. - if returning { - let at_home = home_path(&mut unpacked, path); - if at_home != path { - placed.insert(path.to_string(), at_home.clone()); - return at_home; - } + let at_home = home_path(&mut unpacked, path); + if at_home != path { + placed.insert(path.to_string(), at_home.clone()); + return at_home; } let file = Path::new(path); // A picture only: a photos field is free text, and could name any file on the device. @@ -1089,7 +1184,10 @@ fn home_path(unpacked: &mut Unpacked, path: &str) -> String { /// The [`INDEX`] a package unpacked into `folder` (its `photos` folder), as entry → path named /// by where it was packaged; empty where there is none, or it can't be read. fn unpacked_index(folder: &Path) -> std::collections::HashMap { - if folder.file_name().is_none_or(|n| n != PHOTOS) { + // Only a package from home: one that went out names the rows it gave (`given.v1.json`) beside + // its photos. A return opened elsewhere has none, so its photos go back as they are. + if folder.file_name().is_none_or(|n| n != PHOTOS) || !folder.parent().is_some_and(|dir| dir.join(super::field_changes::GIVEN).is_file()) + { return std::collections::HashMap::new(); } // A package's own index, read within a bound: one line for each photo it carried. @@ -1683,9 +1781,15 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { let photos = std::path::absolute(dir.join(PHOTOS)).map_err(|e| e.to_string())?; let mut relative = 0_usize; if photos.is_dir() { + // A package from home names its photos where they are at home; its index says which entry + // each is. + let at_home: std::collections::HashMap = + unpacked_index(&photos).into_iter().map(|(entry, named)| (named, entry)).collect(); for map in &mut project.maps { rewrite_photos(map, |path| { - if let Some(name) = path.strip_prefix("photos/").filter(|name| plain_file(name)) { + // One named where it is at home keeps that name unless its unpacked file can be named. + let (named, entry) = (path, at_home.get(path).map_or(path, String::as_str)); + if let Some(name) = entry.strip_prefix("photos/").filter(|name| plain_file(name)) { let file = photos.join(name); if file.is_file() { if let Some(path) = file.to_str() { @@ -1694,7 +1798,7 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { relative += 1; } } - path.to_string() + named.to_string() }); } } @@ -2542,6 +2646,36 @@ mod tests { assert!(home.project.offline_areas[0].conflicts.is_empty()); } + /// A return opened on another device and sent again carries the field's photos from there: + /// only a package from home maps its photos back to home's paths, so a return's own index + /// (which names the first phone's paths) never stands in for the photo. + #[test] + fn a_return_sent_again_from_another_device_carries_the_fields_photos() { + let temp = Temp::new("resent-photo"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let (_, out) = package(&mut home, &json!({"name": "Again", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let first = temp.path().join("first"); + let text = unpack_into(&out, &first).unwrap().0; + let mut phone = opened(project_in(&text, &first).unwrap()); + phone.opened_package = Some(temp.path().join("sent.rgisfield")); + let taken = temp.path().join("photo-3.jpg"); + std::fs::write(&taken, b"taken on the first phone").unwrap(); + phone.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": taken.display().to_string()})).unwrap(); + let (_, returned) = package(&mut phone, &Value::Null).unwrap(); + // Gone from the first phone; the return is opened on another device and sent from there. + std::fs::remove_file(&taken).unwrap(); + let second = temp.path().join("second"); + let text = unpack_into(&returned, &second).unwrap().0; + let mut other = Session::new(project_in(&text, &second).unwrap()); + other.opened_package = Some(temp.path().join("returned.rgisfield")); + let (_, again) = package(&mut other, &Value::Null).unwrap(); + let entries = rustgis_data::zip::read(&again).unwrap(); + assert!(entries.iter().any(|(n, b)| n == "photos/photo-3.jpg" && b == b"taken on the first phone")); + } + /// A package that goes back as a whole map (its rows weren't kept on the device) names the /// photos it brought from home where they are at home: a feature the field left alone is no /// edit, even when home's photo changed on disk meanwhile, so home's own edit to it stays. @@ -2581,7 +2715,9 @@ mod tests { assert!(!temp.path().join("Whole photos").exists()); } - /// A photo past what the package has room for stays home, and is counted. + /// Going out, a photo past what the package has room for stays home, and is counted. The + /// features aren't changed, so the map's rows stay shared with the project's; and a name a + /// feature already gives under `photos/` isn't given to another photo. #[test] fn a_photo_past_the_packages_budget_stays_home_and_is_counted() { let temp = Temp::new("photo-budget"); @@ -2593,14 +2729,19 @@ mod tests { s.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); let named = format!("{};{}", small.display(), large.display()); s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": named})).unwrap(); - let mut map = s.map().clone(); + s.run("edit.setValue", &json!({"layer": cities, "row": 1, "field": "photos", "value": "photos/small.jpg"})).unwrap(); + let map = s.map().clone(); let mut budget = 32; - let photos = take_photos(&mut map, &mut budget, false).unwrap(); + let photos = collect_photos(&map, &mut budget).unwrap(); assert_eq!(photos.too_large, [large.display().to_string()]); + assert_eq!(photos.missing, ["photos/small.jpg"]); assert_eq!(budget, 24); - let held = map.layer(cities).unwrap(); - let text = held.dataset.value(0, held.dataset.field_index("photos").unwrap()).to_string(); - assert_eq!(text, format!("photos/small.jpg;{}", large.display())); + let entries: Vec<&str> = photos.entries.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(entries, ["photos/2-small.jpg", INDEX]); + let index = String::from_utf8(photos.entries[1].1.clone()).unwrap(); + assert_eq!(index, format!("photos/2-small.jpg\t{}\n", small.display())); + let (held, home) = (&map.layer(cities).unwrap().dataset.features, &s.map().layer(cities).unwrap().dataset.features); + assert!(held.shares(home)); } #[test] From 305f93e50b4aecb4c4ae34b83a1d9beed2885d31 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 12:30:49 -0600 Subject: [PATCH 04/24] fix(engine): photos the map needs the room of stay home Review follow-up: when the map doesn't fit beside the photos going out, the package drops the photos and says how many stayed home (the features still name them here). Only this field project's own package maps photos back to home, a path holding a ; stays home and is said (the phone can't tell it from two paths), photo names are told apart whatever their case in any script, and Cancel is checked on each row of the first scan. --- crates/engine/src/cmd/field.rs | 125 ++++++++++++++++++++----- crates/engine/src/cmd/field_changes.rs | 23 +++-- 2 files changed, 120 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index ec1c4f531c..83736d694a 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -201,7 +201,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not } }; let mut entries: Vec<(String, Vec)> = Vec::new(); - let mut budget = MOST_UNPACKED as u64 / 2; + let mut budget = most_unpacked() / 2; // Each local archive goes in beside the project, its layer reading it from there. let (mut online, mut unread, mut uploaded) = (Vec::new(), Vec::new(), Vec::new()); let mut taken = std::collections::HashSet::new(); @@ -268,7 +268,11 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not // The photos the features name go with them: going out, those named here, the features // naming them as before (the phone points them at the unpacked files); coming back, those // taken in the field (and those that came from home, under their paths there). - let photos = if coming_back { take_photos(&mut map, &mut budget)? } else { collect_photos(&map, &mut budget)? }; + let photos = if coming_back { + take_photos(&mut map, &mut budget, s.project.field_origin.as_ref().map_or("", |o| o.package.as_str()))? + } else { + collect_photos(&map, &mut budget)? + }; // Coming back, a photo too large for the package was always an error; going out, it stays // home with the others left out. let mut unread = photos.unread; @@ -305,6 +309,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not )); } } + // Photos sent out are optional: dropped below if the map needs their room. + let carried = if coming_back { 0 } else { photos.entries.iter().filter(|(n, _)| n != INDEX).count() }; entries.extend(photos.entries); if coming_back { // What the phone changed in the rows it was given, which Bring Back applies. @@ -504,7 +510,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not "{area}: a RustGIS field package.\nOpen it with RustGIS on a phone or a computer (Open Project). Its basemaps are in {BASEMAPS}/.\n" ); entries.push(("README.txt".into(), readme.into_bytes())); - let companions = companion_bytes(&entries); + let mut companions = companion_bytes(&entries); let too_large = || "the field package would be too large: leave a tile archive, photos or some data out".to_string(); if !copied.is_empty() { let map = project.maps.first().ok_or("the field package holds no map")?; @@ -519,6 +525,19 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not progress::check().map_err(|e| e.to_string())?; let (mut text, mut report) = crate::durable::output(&mut project, None, |p| crate::project::json_within(p, project_room(companions + manifest.len() as u64)))?; + // The map comes first: photos it needs the room of stay home (the features still name them + // where they are here), and that is said. + if text.is_none() && carried > 0 { + entries.retain(|(n, _)| !n.starts_with(&format!("{PHOTOS}/"))); + companions = companion_bytes(&entries); + // Before the note the fallback below takes back, if it runs. + let at = losses.len() - usize::from(!copied.is_empty()); + losses.insert(at, format!("{carried} photo(s) stayed home: the map needed the field package's room for them")); + manifest = manifest_bytes(&archive_errors, &losses)?; + (text, report) = crate::durable::output(&mut project, None, |p| { + crate::project::json_within(p, project_room(companions + manifest.len() as u64)) + })?; + } if text.is_none() && !copied.is_empty() { // Row storage and encoded JSON measure different things. The package's hard limit // also includes loaded layers and basemaps, so retry once without the streamed copies. @@ -679,7 +698,16 @@ fn companion_bytes(entries: &[(String, Vec)]) -> u64 { /// The project JSON must fit its own limit and the space left in the unpacked ZIP. fn project_room(companions: u64) -> u64 { - crate::project::max_bytes().min((MOST_UNPACKED as u64).saturating_sub(companions)) + crate::project::max_bytes().min(most_unpacked().saturating_sub(companions)) +} + +/// [`MOST_UNPACKED`], or a smaller limit a test sets ([`tests::with_unpacked`]). +fn most_unpacked() -> u64 { + #[cfg(test)] + if let Some(most) = tests::UNPACKED.with(std::cell::Cell::get) { + return most; + } + MOST_UNPACKED as u64 } /// Retain one map's worth of clipped streamed rows within a shared budget. Leave some of the @@ -900,7 +928,8 @@ fn rewrite_paths(held: &str, rewrite: &mut impl FnMut(&str) -> String) -> Option /// value against home's. fn photos_named_at_home(changes: &mut super::field_changes::Changes) { let mut unpacked = Unpacked::new(); - let mut at_home = |path: &str| home_path(&mut unpacked, path); + let package = changes.package.clone(); + let mut at_home = |path: &str| home_path(&mut unpacked, &package, path); for layer in &mut changes.layers { for given in layer.edited.iter_mut().chain(layer.deleted.iter_mut()) { for (field, value) in &mut given.values { @@ -969,10 +998,12 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64) -> Result Result Result Result { *budget = budget.saturating_sub(bytes.len() as u64); - taken.insert(name.to_ascii_lowercase()); + taken.insert(name.to_lowercase()); index.push_str(&line); found.entries.push((entry, bytes)); } @@ -1053,7 +1087,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64) -> Result Result { +fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> Result { let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); @@ -1077,7 +1111,7 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64) -> Result String { +fn home_path(unpacked: &mut Unpacked, package: &str, path: &str) -> String { let file = Path::new(path); file.parent() .zip(file.file_name()) .and_then(|(folder, own)| { - let index = unpacked.entry(folder.to_path_buf()).or_insert_with(|| unpacked_index(folder)); + let index = unpacked.entry(folder.to_path_buf()).or_insert_with(|| unpacked_index(folder, package)); index.get(&format!("{PHOTOS}/{}", own.to_string_lossy())).cloned() }) .unwrap_or_else(|| path.to_string()) @@ -1183,11 +1217,11 @@ fn home_path(unpacked: &mut Unpacked, path: &str) -> String { /// The [`INDEX`] a package unpacked into `folder` (its `photos` folder), as entry → path named /// by where it was packaged; empty where there is none, or it can't be read. -fn unpacked_index(folder: &Path) -> std::collections::HashMap { - // Only a package from home: one that went out names the rows it gave (`given.v1.json`) beside - // its photos. A return opened elsewhere has none, so its photos go back as they are. - if folder.file_name().is_none_or(|n| n != PHOTOS) || !folder.parent().is_some_and(|dir| dir.join(super::field_changes::GIVEN).is_file()) - { +fn unpacked_index(folder: &Path, package: &str) -> std::collections::HashMap { + // Only this field project's package from home: one that went out names itself beside its + // photos (`given.v1.json`). A return opened elsewhere has none, and another package's photos + // aren't this one's, so their photos go back as they are. + if folder.file_name().is_none_or(|n| n != PHOTOS) || !folder.parent().is_some_and(|dir| super::field_changes::marks(dir, package)) { return std::collections::HashMap::new(); } // A package's own index, read within a bound: one line for each photo it carried. @@ -1784,7 +1818,10 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { // A package from home names its photos where they are at home; its index says which entry // each is. let at_home: std::collections::HashMap = - unpacked_index(&photos).into_iter().map(|(entry, named)| (named, entry)).collect(); + unpacked_index(&photos, project.field_origin.as_ref().map_or("", |o| o.package.as_str())) + .into_iter() + .map(|(entry, named)| (named, entry)) + .collect(); for map in &mut project.maps { rewrite_photos(map, |path| { // One named where it is at home keeps that name unless its unpacked file can be named. @@ -1890,6 +1927,52 @@ mod tests { Session::new(crate::sample::world_project()) } + thread_local! { + pub(super) static UNPACKED: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// Runs `f` with the unpacked limit of a package at `most` on this thread; put back after. + fn with_unpacked(most: u64, f: impl FnOnce() -> T) -> T { + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + UNPACKED.with(|m| m.set(None)); + } + } + UNPACKED.with(|m| m.set(Some(most))); + let _restore = Restore; + f() + } + + /// Photos the map needs the room of stay home, and that is said: a package that fit without + /// them still goes out. + #[test] + fn photos_the_map_needs_the_room_of_stay_home() { + let temp = Temp::new("photo-room"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let area = json!({"name": "Room", "extent": [-180.0, -85.0, 180.0, 85.0]}); + let map_bytes = |bytes: &[u8]| { + rustgis_data::zip::read(bytes).unwrap().into_iter().find(|(n, _)| n.ends_with(".rgis")).map(|(_, b)| b.len() as u64).unwrap() + }; + let json = map_bytes(&package(&mut home, &area).unwrap().1); + // A photo that fits the budget for archives and photos (half the limit), but not beside the map. + let photo = temp.path().join("big.jpg"); + std::fs::write(&photo, vec![0u8; (json * 6 / 10) as usize]).unwrap(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); + let mark = home.notice_mark(); + let out = with_unpacked(json * 14 / 10, || package(&mut home, &json!({"name": "Room"}))).unwrap().1; + let entries = rustgis_data::zip::read(&out).unwrap(); + assert!(entries.iter().all(|(n, _)| !n.starts_with("photos/"))); + let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("1 photo(s) stayed home: the map needed")), "{said:?}"); + // With room for both, it goes. + let out = package(&mut home, &json!({"name": "Room"})).unwrap().1; + assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, _)| n == "photos/big.jpg")); + } + #[test] fn companions_do_not_reduce_the_project_json_limit() { crate::project::with_max_bytes(1024, || { diff --git a/crates/engine/src/cmd/field_changes.rs b/crates/engine/src/cmd/field_changes.rs index dde2bc2a6d..71442e6b0c 100644 --- a/crates/engine/src/cmd/field_changes.rs +++ b/crates/engine/src/cmd/field_changes.rs @@ -268,14 +268,8 @@ impl GivenRows { /// package says it went out from home ([`GIVEN`]) under the identity `project` carries, and this /// device doesn't keep them already. pub(crate) fn in_package(dir: &Path, project: &Project) -> Option { - #[derive(Deserialize)] - struct Marker { - package: String, - } let package = project.field_origin.as_ref().map(|o| o.package.as_str()).filter(|p| !p.is_empty())?; - let marker = std::fs::read(dir.join(GIVEN)).ok().filter(|b| b.len() <= 4096)?; - let marker: Marker = serde_json::from_slice(&marker).ok()?; - let given = (marker.package == package).then(|| GivenRows::of(project, package))?; + let given = marks(dir, package).then(|| GivenRows::of(project, package))?; (!given.kept()).then_some(given) } @@ -320,6 +314,21 @@ fn is_spent(package: &str) -> bool { const ALREADY_SENT: &str = "The field package had already gone back, so the rows it gave weren't kept on this device: make a new field package for more edits"; +/// Whether `dir`, a package unpacked, went out from home as package `package`: its [`GIVEN`] names +/// it. +pub(crate) fn marks(dir: &Path, package: &str) -> bool { + #[derive(Deserialize)] + struct Marker { + package: String, + } + !package.is_empty() + && std::fs::read(dir.join(GIVEN)) + .ok() + .filter(|b| b.len() <= 4096) + .and_then(|b| serde_json::from_slice::(&b).ok()) + .is_some_and(|m| m.package == package) +} + /// What a package going out from home holds under [`GIVEN`]. pub(crate) fn given_entry(package: &str) -> Result, String> { serde_json::to_vec(&json!({"package": package})).map_err(|e| e.to_string()) From 78bb8bf7d0a3e00f9085c5cadb9ce4de0b75382b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 13:10:24 -0600 Subject: [PATCH 05/24] fix(engine): carried photos get short numbered names Review follow-up: photos going out are named home-00001.jpg and on (the index keeps the path each was named by), so no two names unpack to one file on a system that ignores case or accents, and none is too long. Photo entries stop short of the archive's entry limit, the given marker is counted in the package's room and read within a bound, and Cancel is checked on every row of the photo scans. --- crates/engine/src/cmd/field.rs | 93 ++++++++++------------ crates/engine/src/cmd/field_audit_tests.rs | 2 +- crates/engine/src/cmd/field_changes.rs | 3 +- 3 files changed, 45 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 83736d694a..498d6e45fb 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -271,7 +271,9 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not let photos = if coming_back { take_photos(&mut map, &mut budget, s.project.field_origin.as_ref().map_or("", |o| o.package.as_str()))? } else { - collect_photos(&map, &mut budget)? + // Room for the package's own entries (its project, README, notes, marker and index). + let most_entries = usize::from(u16::MAX).saturating_sub(entries.len() + 16); + collect_photos(&map, &mut budget, most_entries)? }; // Coming back, a photo too large for the package was always an error; going out, it stays // home with the others left out. @@ -419,27 +421,17 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not .extent; let available = project_room(companion_bytes(&entries)); copied = copy_streams(&mut map, extent, stream_budget(available), &mut losses)?; - // Their photos stay home: a reference copy's edits and photos don't come back. - let named: usize = map - .layers - .iter() - .filter(|l| copied.contains(&l.id)) - .filter_map(|l| photos_field(l).map(|fi| (l, fi))) - .map(|(l, fi)| { - l.dataset - .features - .column(fi) - // Counted by their separators, without looking at the disk: a count for the notice. - .filter_map(|v| { - if let rustgis_data::Value::Text(t) = v { - Some(t.split(';').filter(|p| !p.trim().is_empty()).count()) - } else { - None - } - }) - .sum::() - }) - .sum(); + // Their photos stay home: a reference copy's edits and photos don't come back. Counted by + // their separators, without looking at the disk: a count for the notice. + let mut named = 0usize; + for (l, fi) in map.layers.iter().filter(|l| copied.contains(&l.id)).filter_map(|l| photos_field(l).map(|fi| (l, fi))) { + for value in l.dataset.features.column(fi) { + progress::check().map_err(|e| e.to_string())?; + if let rustgis_data::Value::Text(t) = value { + named += t.split(';').filter(|p| !p.trim().is_empty()).count(); + } + } + } if named > 0 { losses.push(format!( "{named} photo reference(s) of layer(s) copied for reference stayed home: those copies' photos don't go in the field package" @@ -510,7 +502,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not "{area}: a RustGIS field package.\nOpen it with RustGIS on a phone or a computer (Open Project). Its basemaps are in {BASEMAPS}/.\n" ); entries.push(("README.txt".into(), readme.into_bytes())); - let mut companions = companion_bytes(&entries); + // With room for the marker a package going out ends with. + let mut companions = companion_bytes(&entries) + if coming_back { 0 } else { 4096 }; let too_large = || "the field package would be too large: leave a tile archive, photos or some data out".to_string(); if !copied.is_empty() { let map = project.maps.first().ok_or("the field package holds no map")?; @@ -529,7 +522,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not // where they are here), and that is said. if text.is_none() && carried > 0 { entries.retain(|(n, _)| !n.starts_with(&format!("{PHOTOS}/"))); - companions = companion_bytes(&entries); + companions = companion_bytes(&entries) + 4096; // Before the note the fallback below takes back, if it runs. let at = losses.len() - usize::from(!copied.is_empty()); losses.insert(at, format!("{carried} photo(s) stayed home: the map needed the field package's room for them")); @@ -990,20 +983,20 @@ fn photo_paths(held: &str) -> Vec> { /// ([`project_in`]). The features aren't changed here, so the rows the map shares with the /// offline area aren't copied. A name a feature already gives under `photos/` isn't used for /// another. What stays out is listed by kind. Cancel is checked before each photo is looked at. -fn collect_photos(map: &rustgis_map::Map, budget: &mut u64) -> Result { +fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) -> Result { let mut found = Photos::default(); // Every path named, once, in order; and the names already given under `photos/`, kept. let (mut named, mut seen, mut taken) = (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); for l in map.layers.iter().filter(|l| !l.is_raster()) { let Some(fi) = photos_field(l) else { continue }; for value in l.dataset.features.column(fi) { - let rustgis_data::Value::Text(held) = value else { continue }; // Reading a field's paths can look at the disk (a path with a `;` in it). rustgis_data::progress::check().map_err(|e| e.to_string())?; + let rustgis_data::Value::Text(held) = value else { continue }; for r in photo_paths(held) { let Some(path) = held.get(r) else { continue }; if let Some(name) = path.strip_prefix(&format!("{PHOTOS}/")) { - taken.insert(name.to_lowercase()); + taken.insert(name.to_ascii_lowercase()); } if seen.insert(path.to_string()) { named.push(path.to_string()); @@ -1011,7 +1004,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64) -> Result Result *budget || (index.len() + line.len()) as u64 > MAX_INDEX { + // Past the budget, past what the phone reads of the index, or past the entries a package + // holds: it stays home. + if size > *budget || (index.len() + line.len()) as u64 > MAX_INDEX || found.entries.len() >= most_entries { found.too_large.push(path); continue; } match crate::project::read_file(file, *budget) { Ok(bytes) => { *budget = budget.saturating_sub(bytes.len() as u64); - taken.insert(name.to_lowercase()); + taken.insert(name); index.push_str(&line); found.entries.push((entry, bytes)); } @@ -1970,7 +1963,7 @@ mod tests { assert!(said.iter().any(|t| t.starts_with("1 photo(s) stayed home: the map needed")), "{said:?}"); // With room for both, it goes. let out = package(&mut home, &json!({"name": "Room"})).unwrap().1; - assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, _)| n == "photos/big.jpg")); + assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, _)| n == "photos/home-00001.jpg")); } #[test] @@ -2581,7 +2574,7 @@ mod tests { let (_, out) = package(&mut home, &json!({"name": "Pics", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let photos: Vec = rustgis_data::zip::read(&out).unwrap().into_iter().map(|(n, _)| n).filter(|n| n.starts_with("photos/") && n != INDEX).collect(); - assert_eq!(photos, ["photos/_pending.jpg"]); + assert_eq!(photos, ["photos/home-00001.jpg"]); let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(said.iter().any(|t| t.starts_with("1 file(s) a photos field names") && t.contains("notes.txt")), "{said:?}"); // Coming back: the picture only, under a plain name; the text file stays named as it was. @@ -2679,8 +2672,8 @@ mod tests { let mark = home.notice_mark(); let (_, out) = package(&mut home, &json!({"name": "Away", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let entries = rustgis_data::zip::read(&out).unwrap(); - assert!(entries.iter().any(|(n, b)| n == "photos/kept.jpg" && b == b"kept at home")); - assert!(entries.iter().any(|(n, b)| n == "photos/dropped.jpg" && b == b"of a feature deleted in the field")); + assert!(entries.iter().any(|(n, b)| n == "photos/home-00001.jpg" && b == b"kept at home")); + assert!(entries.iter().any(|(n, b)| n == "photos/home-00002.jpg" && b == b"of a feature deleted in the field")); // The two named that aren't files here (one by no full path) are counted, for the sender // and the crew. let expected = "2 photo(s) a photos field names aren't files on this computer by their full path"; @@ -2691,7 +2684,7 @@ mod tests { assert!(losses.iter().any(|t| t.starts_with(expected)), "{losses:?}"); let mut field = opened(project_in(&text, &unpacked).unwrap()); field.opened_package = Some(temp.path().join("sent.rgisfield")); - let there = unpacked.join("photos").join("kept.jpg"); + let there = unpacked.join("photos").join("home-00001.jpg"); assert_eq!(Path::new(&value(&field, "Cities", 0, "photos")), there.as_path()); // In the field: a photo added to the first feature, the second feature deleted. let taken = temp.path().join("photo-9.jpg"); @@ -2812,17 +2805,17 @@ mod tests { s.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); let named = format!("{};{}", small.display(), large.display()); s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": named})).unwrap(); - s.run("edit.setValue", &json!({"layer": cities, "row": 1, "field": "photos", "value": "photos/small.jpg"})).unwrap(); + s.run("edit.setValue", &json!({"layer": cities, "row": 1, "field": "photos", "value": "photos/home-00001.jpg"})).unwrap(); let map = s.map().clone(); let mut budget = 32; - let photos = collect_photos(&map, &mut budget).unwrap(); + let photos = collect_photos(&map, &mut budget, usize::MAX).unwrap(); assert_eq!(photos.too_large, [large.display().to_string()]); - assert_eq!(photos.missing, ["photos/small.jpg"]); + assert_eq!(photos.missing, ["photos/home-00001.jpg"]); assert_eq!(budget, 24); let entries: Vec<&str> = photos.entries.iter().map(|(n, _)| n.as_str()).collect(); - assert_eq!(entries, ["photos/2-small.jpg", INDEX]); + assert_eq!(entries, ["photos/home-00002.jpg", INDEX]); let index = String::from_utf8(photos.entries[1].1.clone()).unwrap(); - assert_eq!(index, format!("photos/2-small.jpg\t{}\n", small.display())); + assert_eq!(index, format!("photos/home-00002.jpg\t{}\n", small.display())); let (held, home) = (&map.layer(cities).unwrap().dataset.features, &s.map().layer(cities).unwrap().dataset.features); assert!(held.shares(home)); } diff --git a/crates/engine/src/cmd/field_audit_tests.rs b/crates/engine/src/cmd/field_audit_tests.rs index 868e10b168..fa3366608c 100644 --- a/crates/engine/src/cmd/field_audit_tests.rs +++ b/crates/engine/src/cmd/field_audit_tests.rs @@ -604,7 +604,7 @@ fn a_feature_with_a_photo_deleted_in_the_field_is_deleted_at_home() { home.run("map.activate", &json!({"name": home.project.offline_areas[0].map.clone()})).unwrap(); // The photo goes with its feature, and the phone names it where it was unpacked: the // deletion's old value still matches home's, which names it where it is at home. - assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, b)| n == "photos/at-home.jpg" && b == b"home photo")); + assert!(rustgis_data::zip::read(&out).unwrap().iter().any(|(n, b)| n == "photos/home-00001.jpg" && b == b"home photo")); let mut a = phone(&temp, &out, "a"); let cities = layer(&a, "Cities"); let r = a.map().layer(cities).unwrap().dataset.features.iter().position(|f| f.id == id).unwrap(); diff --git a/crates/engine/src/cmd/field_changes.rs b/crates/engine/src/cmd/field_changes.rs index 71442e6b0c..951995f651 100644 --- a/crates/engine/src/cmd/field_changes.rs +++ b/crates/engine/src/cmd/field_changes.rs @@ -322,9 +322,8 @@ pub(crate) fn marks(dir: &Path, package: &str) -> bool { package: String, } !package.is_empty() - && std::fs::read(dir.join(GIVEN)) + && crate::project::read_file(&dir.join(GIVEN), 4096) .ok() - .filter(|b| b.len() <= 4096) .and_then(|b| serde_json::from_slice::(&b).ok()) .is_some_and(|m| m.package == package) } From 5862a29660dc7fbe484fc7e6bb0220e48c30a7c7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 13:27:46 -0600 Subject: [PATCH 06/24] fix(engine): a package's listed photos resolve only through their home paths Review follow-up: in a package from home, an entry its index lists is only the photo of the home path it names, so a reference copy naming the entry itself isn't pointed at it. The outgoing scan borrows the names it keeps from the map, and the return scan stops at the next row once cancelled. --- crates/engine/src/cmd/field.rs | 187 ++++++++++++++++++--------------- 1 file changed, 101 insertions(+), 86 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 498d6e45fb..172084ebf1 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -882,17 +882,29 @@ fn photos_field(layer: &rustgis_map::Layer) -> Option { } /// Rewrites each photos field of `map` with `rewrite` (one path in, the path to name instead out). -fn rewrite_photos(map: &mut rustgis_map::Map, mut rewrite: impl FnMut(&str) -> String) { +fn rewrite_photos(map: &mut rustgis_map::Map, rewrite: impl FnMut(&str) -> String) { + let _ = rewrite_photos_until(map, rewrite, || Ok(())); +} + +/// [`rewrite_photos`], asking `go_on` before each row and stopping with its error: Cancel, for +/// a pass whose reading of a row can look at the disk. +fn rewrite_photos_until( + map: &mut rustgis_map::Map, + mut rewrite: impl FnMut(&str) -> String, + mut go_on: impl FnMut() -> Result<(), String>, +) -> Result<(), String> { for l in map.layers.iter_mut().filter(|l| !l.is_raster()) { let Some(fi) = photos_field(l) else { continue }; let features = &mut l.dataset.features; for row in 0..features.len() { + go_on()?; let rustgis_data::Value::Text(held) = features.value(row, fi) else { continue }; if let Some(out) = rewrite_paths(held, &mut rewrite) { let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); } } } + Ok(()) } /// A photos field's text `held` with each path rewritten by `rewrite`, or `None` when none @@ -986,7 +998,9 @@ fn photo_paths(held: &str) -> Vec> { fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) -> Result { let mut found = Photos::default(); // Every path named, once, in order; and the names already given under `photos/`, kept. - let (mut named, mut seen, mut taken) = (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); + // The names are borrowed from the map's rows, not copied. + let (mut named, mut seen, mut taken): (Vec<&str>, std::collections::HashSet<&str>, std::collections::HashSet) = + (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); for l in map.layers.iter().filter(|l| !l.is_raster()) { let Some(fi) = photos_field(l) else { continue }; for value in l.dataset.features.column(fi) { @@ -998,8 +1012,8 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) if let Some(name) = path.strip_prefix(&format!("{PHOTOS}/")) { taken.insert(name.to_ascii_lowercase()); } - if seen.insert(path.to_string()) { - named.push(path.to_string()); + if seen.insert(path) { + named.push(path); } } } @@ -1009,7 +1023,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) rustgis_data::progress::check().map_err(|e| e.to_string())?; let file = Path::new(&path); if !file.is_absolute() { - found.missing.push(path); + found.missing.push(path.to_string()); continue; } // The index holds one path a line, its fields split by tabs; a photos field splits its @@ -1021,12 +1035,12 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) let size = match std::fs::metadata(file) { Ok(m) if m.is_file() => m.len(), Ok(_) => { - found.missing.push(path); + found.missing.push(path.to_string()); continue; } // The browser has no files to look at by path: not here either. Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::Unsupported) => { - found.missing.push(path); + found.missing.push(path.to_string()); continue; } Err(e) => { @@ -1035,7 +1049,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) } }; if !file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))) { - found.not_pictures.push(path); + found.not_pictures.push(path.to_string()); continue; } // A short name of plain letters and digits, numbered: two names a system takes for one @@ -1052,7 +1066,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) // Past the budget, past what the phone reads of the index, or past the entries a package // holds: it stays home. if size > *budget || (index.len() + line.len()) as u64 > MAX_INDEX || found.entries.len() >= most_entries { - found.too_large.push(path); + found.too_large.push(path.to_string()); continue; } match crate::project::read_file(file, *budget) { @@ -1091,91 +1105,89 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R let mut said = std::collections::HashSet::new(); // The index unpacked with each folder of photos a package brought: entry → path at home. let mut unpacked = Unpacked::new(); - let mut cancelled = None; - rewrite_photos(map, |path| { - if let Some(entry) = placed.get(path) { - return entry.clone(); - } - if said.contains(path) || cancelled.is_some() { - return path.to_string(); - } - if let Err(e) = rustgis_data::progress::check() { - cancelled = Some(e.to_string()); - return path.to_string(); - } - // Brought from home in this package: named where it is at home, and not carried back. - let at_home = home_path(&mut unpacked, package, path); - if at_home != path { - placed.insert(path.to_string(), at_home.clone()); - return at_home; - } - let file = Path::new(path); - // A picture only: a photos field is free text, and could name any file on the device. - let picture = file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))); - if !file.is_absolute() { - said.insert(path.to_string()); - found.missing.push(path.to_string()); - return path.to_string(); - } - // Not on this device (in a returning package, a photo named at home): left as named. One - // there that can't be looked at is said, as one that can't be read is. - let size = match std::fs::metadata(file) { - Ok(m) if m.is_file() => m.len(), - // A folder, or nothing there: no photo file on this device. - Ok(_) => { + // Cancel is looked at before each row: reading a row's paths can look at the disk. + let go_on = || rustgis_data::progress::check().map_err(|e| e.to_string()); + rewrite_photos_until( + map, + |path| { + if let Some(entry) = placed.get(path) { + return entry.clone(); + } + if said.contains(path) { + return path.to_string(); + } + // Brought from home in this package: named where it is at home, and not carried back. + let at_home = home_path(&mut unpacked, package, path); + if at_home != path { + placed.insert(path.to_string(), at_home.clone()); + return at_home; + } + let file = Path::new(path); + // A picture only: a photos field is free text, and could name any file on the device. + let picture = file.extension().is_some_and(|e| PICTURES.iter().any(|p| e.eq_ignore_ascii_case(p))); + if !file.is_absolute() { said.insert(path.to_string()); found.missing.push(path.to_string()); return path.to_string(); } - // The browser has no files to look at by path: not here either. - Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::Unsupported) => { + // Not on this device (in a returning package, a photo named at home): left as named. One + // there that can't be looked at is said, as one that can't be read is. + let size = match std::fs::metadata(file) { + Ok(m) if m.is_file() => m.len(), + // A folder, or nothing there: no photo file on this device. + Ok(_) => { + said.insert(path.to_string()); + found.missing.push(path.to_string()); + return path.to_string(); + } + // The browser has no files to look at by path: not here either. + Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::Unsupported) => { + said.insert(path.to_string()); + found.missing.push(path.to_string()); + return path.to_string(); + } + Err(e) => { + said.insert(path.to_string()); + found.unread.push(format!("{path} ({e})")); + return path.to_string(); + } + }; + if !picture { said.insert(path.to_string()); - found.missing.push(path.to_string()); + found.not_pictures.push(path.to_string()); return path.to_string(); } - Err(e) => { + if size > *budget { said.insert(path.to_string()); - found.unread.push(format!("{path} ({e})")); + found.too_large.push(path.to_string()); return path.to_string(); } - }; - if !picture { - said.insert(path.to_string()); - found.not_pictures.push(path.to_string()); - return path.to_string(); - } - if size > *budget { - said.insert(path.to_string()); - found.too_large.push(path.to_string()); - return path.to_string(); - } - match crate::project::read_file(file, *budget) { - Ok(bytes) => { - *budget = budget.saturating_sub(bytes.len() as u64); - let stem = file.file_name().map(|n| plain_name(&n.to_string_lossy())).unwrap_or_else(|| "photo.jpg".into()); - let mut name = stem.clone(); - for n in 2.. { - if taken.insert(name.to_ascii_lowercase()) { - break; + match crate::project::read_file(file, *budget) { + Ok(bytes) => { + *budget = budget.saturating_sub(bytes.len() as u64); + let stem = file.file_name().map(|n| plain_name(&n.to_string_lossy())).unwrap_or_else(|| "photo.jpg".into()); + let mut name = stem.clone(); + for n in 2.. { + if taken.insert(name.to_ascii_lowercase()) { + break; + } + name = format!("{n}-{stem}"); } - name = format!("{n}-{stem}"); + let entry = format!("{PHOTOS}/{name}"); + index.push_str(&format!("{entry}\t{path}\n")); + found.entries.push((entry.clone(), bytes)); + placed.insert(path.to_string(), entry.clone()); + entry + } + Err(e) => { + said.insert(path.to_string()); + found.unread.push(format!("{path} ({e})")); + path.to_string() } - let entry = format!("{PHOTOS}/{name}"); - index.push_str(&format!("{entry}\t{path}\n")); - found.entries.push((entry.clone(), bytes)); - placed.insert(path.to_string(), entry.clone()); - entry - } - Err(e) => { - said.insert(path.to_string()); - found.unread.push(format!("{path} ({e})")); - path.to_string() } - } - }); - if let Some(e) = cancelled { - return Err(e); - } + }, + go_on, + )?; if !index.is_empty() { found.entries.push((INDEX.to_string(), index.into_bytes())); } @@ -1810,13 +1822,16 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { if photos.is_dir() { // A package from home names its photos where they are at home; its index says which entry // each is. - let at_home: std::collections::HashMap = - unpacked_index(&photos, project.field_origin.as_ref().map_or("", |o| o.package.as_str())) - .into_iter() - .map(|(entry, named)| (named, entry)) - .collect(); + let index = unpacked_index(&photos, project.field_origin.as_ref().map_or("", |o| o.package.as_str())); + // An entry the index lists belongs to the home path it names, and to nothing else: a + // feature naming the entry itself (a reference copy's, say) isn't pointed at that photo. + let listed: std::collections::HashSet = index.keys().cloned().collect(); + let at_home: std::collections::HashMap = index.into_iter().map(|(entry, named)| (named, entry)).collect(); for map in &mut project.maps { rewrite_photos(map, |path| { + if listed.contains(path) { + return path.to_string(); + } // One named where it is at home keeps that name unless its unpacked file can be named. let (named, entry) = (path, at_home.get(path).map_or(path, String::as_str)); if let Some(name) = entry.strip_prefix("photos/").filter(|name| plain_file(name)) { From 214bb593b137f227713b64402fc38765f915ad3e Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 15:41:40 -0600 Subject: [PATCH 07/24] fix(engine): say a field photo missing from the device on the way back Review follow-up: a return says how many photos its features name that aren't on the device (their names go back alone), the not-a-picture and unreadable notices list ten names and how many more, a home photo whose unpack folder can't be named as text is named by its entry as the notice says, and the guide says a home photo isn't sent back. --- crates/engine/src/cmd/field.rs | 23 ++++++++++++++++++++--- docs/user-guide/field-work.md | 7 ++++--- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 172084ebf1..fb8c182e0c 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -282,7 +282,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not unread.extend(photos.too_large.iter().map(|path| format!("{path} (too large for the field package)"))); } if !unread.is_empty() { - archive_error(s, format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), unread.join(", "))); + archive_error(s, format!("{} photo(s) couldn't be put in the field package: {}", unread.len(), some_of(&unread))); } if !photos.not_pictures.is_empty() { let named = &photos.not_pictures; @@ -290,7 +290,17 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not "{} file(s) a photos field names weren't put in the field package: only pictures go ({}): {}", named.len(), PICTURES.join(", "), - named.join(", ") + some_of(named) + )); + } + // Coming back, photos home has are named where they are there; any other photo not on this + // device goes back as its name alone. + if coming_back && !photos.missing.is_empty() { + let named = &photos.missing; + losses.push(format!( + "{} photo(s) a photos field names aren't on this device, so the field package names them without them: {}", + named.len(), + some_of(named) )); } if !coming_back { @@ -1832,7 +1842,9 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { if listed.contains(path) { return path.to_string(); } - // One named where it is at home keeps that name unless its unpacked file can be named. + // One named where it is at home is pointed at its unpacked file: by its full path, + // or, where the unpack folder's name can't be held as text, by its entry, relative + // to the package, as one a return carries. let (named, entry) = (path, at_home.get(path).map_or(path, String::as_str)); if let Some(name) = entry.strip_prefix("photos/").filter(|name| plain_file(name)) { let file = photos.join(name); @@ -1841,6 +1853,7 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { return path.to_string(); } relative += 1; + return entry.to_string(); } } named.to_string() @@ -2707,7 +2720,11 @@ mod tests { set(&mut field, 0, format!("{};{}", there.display(), taken.display())); field.run("select.rows", &json!({"layer": cities, "rows": [1]})).unwrap(); field.run("edit.delete", &Value::Null).unwrap(); + let mark = field.notice_mark(); let (_, back) = package(&mut field, &Value::Null).unwrap(); + // The two photos that never went out aren't here either, and that is said. + let said: Vec = field.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("2 photo(s) a photos field names aren't on this device")), "{said:?}"); // Only the field's photo goes back: home has its own. let carried: Vec = rustgis_data::zip::read(&back) .unwrap() diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 790e82c2fc..22789aadff 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -206,9 +206,10 @@ project until dismissed, and Undo of the Bring Back takes them away with it. Fro command line or Python, `offline.conflicts` lists them with the project's `state`, and `offline.dismissConflicts` dismisses them by index with that state, refusing a list read before the project changed. -Only the photos of features the phone added, or whose photos it changed, come back: a photo of a -feature whose photos it left alone is left out, and the summary says how many. A photo the package -took from the computer comes back to the file it was taken from, not as a copy. +A photo the package took from the computer isn't sent back: the feature names the file it was taken +from again, and nothing is copied. Of the other photos a returned package carries (those taken in the +field), only those of features the phone added, or whose photos it changed, come back: a photo of a +feature whose photos it left alone is left out, and the summary says how many. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From 5542ff513281574bc18f4c2e614e129612c6704b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 15:58:02 -0600 Subject: [PATCH 08/24] fix(engine): leave a streamed layer's photos to its copy for reference Review follow-up: the outgoing photo scan skips streamed layers, whose rows are what the view read, not what the package holds; their copy for reference counts their photos as staying home, or the layer is left out. --- crates/engine/src/cmd/field.rs | 40 +++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index fb8c182e0c..5cfba3e3c8 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1011,7 +1011,9 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) // The names are borrowed from the map's rows, not copied. let (mut named, mut seen, mut taken): (Vec<&str>, std::collections::HashSet<&str>, std::collections::HashSet) = (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); - for l in map.layers.iter().filter(|l| !l.is_raster()) { + // A streamed layer's photos are left to its copy for reference, which counts them as staying + // home (or leaves the layer out): the rows it holds now aren't what the package will hold. + for l in map.layers.iter().filter(|l| !l.is_raster() && !l.is_streamed()) { let Some(fi) = photos_field(l) else { continue }; for value in l.dataset.features.column(fi) { // Reading a field's paths can look at the disk (a path with a `;` in it). @@ -2754,6 +2756,42 @@ mod tests { assert!(home.project.offline_areas[0].conflicts.is_empty()); } + /// A streamed layer's photos aren't packed with the home photos: its copy for reference (or + /// its absence) decides what goes, and its photos are counted as staying home. + #[test] + fn a_streamed_layers_photos_stay_home_and_are_counted() { + let temp = Temp::new("stream-photos"); + let photo = temp.path().join("site.jpg"); + std::fs::write(&photo, b"a streamed layer's photo").unwrap(); + let source = temp.path().join("sites.gpkg"); + let mut seed = Session::new(Project::default()); + let fields = vec![rustgis_data::Field::new("photos", rustgis_data::FieldType::Text)]; + let mut sites = rustgis_data::Dataset::new("Sites", rustgis_data::GeometryType::Point, fields); + sites.crs = rustgis_data::raster::Crs::from_epsg(4326); + let point = rustgis_data::Geometry::Point(rustgis_data::Coord::new(1.0, 1.0)); + sites.push(Some(point), vec![rustgis_data::Value::Text(photo.display().to_string())]); + let id = seed.map_mut().add_dataset(sites); + seed.run("share.exportLayer", &json!({"layer": id, "path": source})).unwrap(); + let mut home = Session::new(Project::default()); + home.path = Some(temp.path().join("home.rgis")); + home.run("layer.addData", &json!({"name": "Streamed", "path": source, "layer": "Sites", "stream": true})).unwrap(); + assert!(home.map().layer_by_name("Streamed").unwrap().is_streamed()); + // The rows a drawn view has read from the source, as the area's map may hold them. + let streamed = home.map_mut().layers.iter_mut().find(|l| l.name == "Streamed").unwrap(); + let point = rustgis_data::Geometry::Point(rustgis_data::Coord::new(1.0, 1.0)); + let fi = streamed.dataset.field_index("photos").unwrap(); + let mut values = vec![rustgis_data::Value::Null; streamed.dataset.fields.len()]; + values[fi] = rustgis_data::Value::Text(photo.display().to_string()); + streamed.dataset.push(Some(point), values); + let mut budget = u64::MAX; + assert!(collect_photos(home.map(), &mut budget, usize::MAX).unwrap().entries.is_empty()); + let mark = home.notice_mark(); + let (_, out) = package(&mut home, &json!({"name": "Streams", "extent": [0, 0, 2, 2]})).unwrap(); + assert!(rustgis_data::zip::read(&out).unwrap().iter().all(|(n, _)| !n.starts_with("photos/"))); + let said: Vec = home.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("1 photo reference(s) of layer(s) copied for reference stayed home")), "{said:?}"); + } + /// A return opened on another device and sent again carries the field's photos from there: /// only a package from home maps its photos back to home's paths, so a return's own index /// (which names the first phone's paths) never stands in for the photo. From 6048df6aece56ba5eb1aea143e642ffe3dd03007 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:19:51 -0600 Subject: [PATCH 09/24] docs(user-guide): only a return with its list of changes leaves unchanged photos out --- docs/user-guide/field-work.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 22789aadff..018c933abd 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -208,8 +208,9 @@ them by index with that state, refusing a list read before the project changed. A photo the package took from the computer isn't sent back: the feature names the file it was taken from again, and nothing is copied. Of the other photos a returned package carries (those taken in the -field), only those of features the phone added, or whose photos it changed, come back: a photo of a -feature whose photos it left alone is left out, and the summary says how many. +field), a return with its list of changes brings back only those of features the phone added, or whose +photos it changed: a photo of a feature whose photos it left alone is left out, and the summary says +how many. A return that goes back as a whole map brings back every photo it carries. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From 3d1ee8bb9be8b387bb3296e8e1043635c94b573b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:21:51 -0600 Subject: [PATCH 10/24] docs(user-guide): a whole-map return leaves out reference copies' photos --- docs/user-guide/field-work.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 018c933abd..10b1609038 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -210,7 +210,8 @@ A photo the package took from the computer isn't sent back: the feature names th from again, and nothing is copied. Of the other photos a returned package carries (those taken in the field), a return with its list of changes brings back only those of features the phone added, or whose photos it changed: a photo of a feature whose photos it left alone is left out, and the summary says -how many. A return that goes back as a whole map brings back every photo it carries. +how many. A return that goes back as a whole map brings back every photo it carries, except those +named only by layers copied for reference, whose edits stay in the field. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From a6b75ec31c36a34d8f619e18dd91fc69ef5bff11 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:23:49 -0600 Subject: [PATCH 11/24] docs(user-guide): and layers added in the field --- docs/user-guide/field-work.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 10b1609038..f6d3c020e3 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -211,7 +211,7 @@ from again, and nothing is copied. Of the other photos a returned package carrie field), a return with its list of changes brings back only those of features the phone added, or whose photos it changed: a photo of a feature whose photos it left alone is left out, and the summary says how many. A return that goes back as a whole map brings back every photo it carries, except those -named only by layers copied for reference, whose edits stay in the field. +named only by layers copied for reference or added in the field, whose edits stay in the field. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From 6ab51b87e0c4b8c98a22ae3e82827cbbde43737c Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:26:29 -0600 Subject: [PATCH 12/24] docs(user-guide): a return sent again from another device carries home photos --- docs/user-guide/field-work.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index f6d3c020e3..0953d0b9e0 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -207,7 +207,8 @@ command line or Python, `offline.conflicts` lists them with the project's `state them by index with that state, refusing a list read before the project changed. A photo the package took from the computer isn't sent back: the feature names the file it was taken -from again, and nothing is copied. Of the other photos a returned package carries (those taken in the +from again, and nothing is copied. (A return opened on another device and sent again from there does +carry it; Bring Back then keeps the computer's file where it still holds the same photo.) Of the other photos a returned package carries (those taken in the field), a return with its list of changes brings back only those of features the phone added, or whose photos it changed: a photo of a feature whose photos it left alone is left out, and the summary says how many. A return that goes back as a whole map brings back every photo it carries, except those From 1b61a8298e9f7473d578b721432166cf050dd977 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:32:07 -0600 Subject: [PATCH 13/24] docs(user-guide): what the notice says of a streamed layer's photos --- docs/user-guide/field-work.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 0953d0b9e0..72df8dd6e0 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -145,8 +145,10 @@ A field package (`.rgisfield`) carries a map to the phone and its edits back. 1. **On the computer**, with the map in view, **Data › Offline › Package for the Field** makes the package: a project of that map, the features in view, the MBTiles and PMTiles archives its - tile layers use, and the photos its features name (pictures named by their full path, while - they fit the package; the notice counts any left out). The package records the area it was made from in your project, + tile layers use, and the photos its loaded layers' features name (pictures named by their full + path, while they fit the package; the notice counts any left out). A layer read in place keeps + its photos at home: the notice counts them for a layer copied for reference, and names a layer + left out whole. The package records the area it was made from in your project, so save the project after packaging. A layer read in place from a supported local file is copied within the area while it fits the package budget. The copy is for reference, and Bring Back skips edits to it. The sender gets a notice about anything left behind, including From 02c82f0f162176c5772c7a82eb9adbea9d2db5ab Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 17:00:49 -0600 Subject: [PATCH 14/24] fix(engine): a returned photo's path with a tab or line break stays and is said Review follow-up: coming back, a photo whose path holds a tab or line break isn't carried, since the index couldn't hold it, and the notice says so, as going out. The marker's room is a named constant, and the guide's photo-return paragraph is split by case. --- crates/engine/src/cmd/field.rs | 43 ++++++++++++++++++++++++++++++++-- docs/user-guide/field-work.md | 16 ++++++++----- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 5cfba3e3c8..06afcbc759 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -513,7 +513,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not ); entries.push(("README.txt".into(), readme.into_bytes())); // With room for the marker a package going out ends with. - let mut companions = companion_bytes(&entries) + if coming_back { 0 } else { 4096 }; + let mut companions = companion_bytes(&entries) + if coming_back { 0 } else { MARKER_ROOM }; let too_large = || "the field package would be too large: leave a tile archive, photos or some data out".to_string(); if !copied.is_empty() { let map = project.maps.first().ok_or("the field package holds no map")?; @@ -532,7 +532,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not // where they are here), and that is said. if text.is_none() && carried > 0 { entries.retain(|(n, _)| !n.starts_with(&format!("{PHOTOS}/"))); - companions = companion_bytes(&entries) + 4096; + companions = companion_bytes(&entries) + MARKER_ROOM; // Before the note the fallback below takes back, if it runs. let at = losses.len() - usize::from(!copied.is_empty()); losses.insert(at, format!("{carried} photo(s) stayed home: the map needed the field package's room for them")); @@ -1169,6 +1169,13 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R found.not_pictures.push(path.to_string()); return path.to_string(); } + // The index holds one path a line, its fields split by tabs: one holding either would be + // read back as another path. + if path.contains(['\t', '\n', '\r']) { + said.insert(path.to_string()); + found.unread.push(format!("{path} (its name holds a tab or a line break)")); + return path.to_string(); + } if size > *budget { said.insert(path.to_string()); found.too_large.push(path.to_string()); @@ -1261,6 +1268,10 @@ fn unpacked_index(folder: &Path, package: &str) -> std::collections::HashMap = rustgis_data::zip::read(&back).unwrap().into_iter().map(|(n, _)| n).collect(); + assert!(entries.iter().any(|n| n == "photos/plain.jpg") && !entries.iter().any(|n| n.contains("odd")), "{entries:?}"); + let said: Vec = field.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("1 photo(s) couldn't be put") && t.contains("tab or a line break")), "{said:?}"); + } + /// A return opened on another device and sent again carries the field's photos from there: /// only a package from home maps its photos back to home's paths, so a return's own index /// (which names the first phone's paths) never stands in for the photo. diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 72df8dd6e0..a0e75e3e17 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -209,12 +209,16 @@ command line or Python, `offline.conflicts` lists them with the project's `state them by index with that state, refusing a list read before the project changed. A photo the package took from the computer isn't sent back: the feature names the file it was taken -from again, and nothing is copied. (A return opened on another device and sent again from there does -carry it; Bring Back then keeps the computer's file where it still holds the same photo.) Of the other photos a returned package carries (those taken in the -field), a return with its list of changes brings back only those of features the phone added, or whose -photos it changed: a photo of a feature whose photos it left alone is left out, and the summary says -how many. A return that goes back as a whole map brings back every photo it carries, except those -named only by layers copied for reference or added in the field, whose edits stay in the field. +from again, and nothing is copied. A return opened on another device and sent again from there does +carry it; Bring Back then keeps the computer's file where it still holds the same photo. + +Of the photos taken in the field, a return with its list of changes brings back only those of features +the phone added, or whose photos it changed. A photo of a feature whose photos it left alone is left +out, and the summary says how many. + +A return that goes back as a whole map brings back every photo it carries, except a photo that only +layers copied for reference or added in the field name: those layers' edits stay in the field, and so +do their photos. Bring Back refuses a package while the area's offline map is open with edits not synced yet, as renewing the area would replace them: **Sync** the area first. Syncing moves the area on, so a From 7ce75b6aeb317c3ebbaf22d45797ab3fe2c2e191 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 17:40:47 -0600 Subject: [PATCH 15/24] fix(engine): say when a package's photo index can't be read Review follow-up: a photo index that is there but can't be read is said when the package is opened and when the map is sent back, rather than its photos silently going back as copies; a package that carried no photo has none, and says nothing. --- crates/engine/src/cmd/field.rs | 83 +++++++++++++++++++++++++++++----- 1 file changed, 72 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 06afcbc759..96b318dba0 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -321,6 +321,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not )); } } + losses.extend(photos.notes.iter().cloned()); // Photos sent out are optional: dropped below if the map needs their room. let carried = if coming_back { 0 } else { photos.entries.iter().filter(|(n, _)| n != INDEX).count() }; entries.extend(photos.entries); @@ -1207,6 +1208,14 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R }, go_on, )?; + for (folder, read) in &unpacked { + if let Err(e) = read { + found.notes.push(format!( + "The photo index of the field package this map came from couldn't be read ({}: {e}): its photos go back as copies, not as the computer's own files", + folder.display() + )); + } + } if !index.is_empty() { found.entries.push((INDEX.to_string(), index.into_bytes())); } @@ -1224,7 +1233,7 @@ fn some_of(names: &[String]) -> String { } /// The [`INDEX`] of each folder of photos a package unpacked, read once: entry → path at home. -type Unpacked = std::collections::HashMap>; +type Unpacked = std::collections::HashMap, String>>; /// The path a photo at `path` was named by at home, when a package brought it from there (the /// [`INDEX`] unpacked beside it names it); otherwise `path` itself. @@ -1234,24 +1243,28 @@ fn home_path(unpacked: &mut Unpacked, package: &str, path: &str) -> String { .zip(file.file_name()) .and_then(|(folder, own)| { let index = unpacked.entry(folder.to_path_buf()).or_insert_with(|| unpacked_index(folder, package)); - index.get(&format!("{PHOTOS}/{}", own.to_string_lossy())).cloned() + index.as_ref().ok()?.get(&format!("{PHOTOS}/{}", own.to_string_lossy())).cloned() }) .unwrap_or_else(|| path.to_string()) } /// The [`INDEX`] a package unpacked into `folder` (its `photos` folder), as entry → path named -/// by where it was packaged; empty where there is none, or it can't be read. -fn unpacked_index(folder: &Path, package: &str) -> std::collections::HashMap { +/// by where it was packaged; empty where there is none. One that is there but can't be read is an +/// error, said by the caller: its photos can't be told from the field's. +fn unpacked_index(folder: &Path, package: &str) -> Result, String> { // Only this field project's package from home: one that went out names itself beside its // photos (`given.v1.json`). A return opened elsewhere has none, and another package's photos // aren't this one's, so their photos go back as they are. if folder.file_name().is_none_or(|n| n != PHOTOS) || !folder.parent().is_some_and(|dir| super::field_changes::marks(dir, package)) { - return std::collections::HashMap::new(); + return Ok(std::collections::HashMap::new()); } - // A package's own index, read within a bound: one line for each photo it carried. - let Ok(bytes) = crate::project::read_file(&folder.join(INDEX.trim_start_matches(&format!("{PHOTOS}/"))), MAX_INDEX) else { - return std::collections::HashMap::new(); - }; + // A package's own index, read within a bound: one line for each photo it carried. A package + // that carried no photo has none. + let file = folder.join(INDEX.trim_start_matches(&format!("{PHOTOS}/"))); + if matches!(std::fs::symlink_metadata(&file), Err(e) if e.kind() == std::io::ErrorKind::NotFound) { + return Ok(std::collections::HashMap::new()); + } + let bytes = crate::project::read_file(&file, MAX_INDEX)?; let text = String::from_utf8_lossy(&bytes); let mut index = std::collections::HashMap::new(); let mut twice = std::collections::HashSet::new(); @@ -1262,7 +1275,7 @@ fn unpacked_index(folder: &Path, package: &str) -> std::collections::HashMap)>, + /// What couldn't be told about the photos as a whole (a package's photo index unreadable). + notes: Vec, missing: Vec, not_pictures: Vec, too_large: Vec, @@ -1845,7 +1860,19 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { if photos.is_dir() { // A package from home names its photos where they are at home; its index says which entry // each is. - let index = unpacked_index(&photos, project.field_origin.as_ref().map_or("", |o| o.package.as_str())); + let index = match unpacked_index(&photos, project.field_origin.as_ref().map_or("", |o| o.package.as_str())) { + Ok(index) => index, + Err(e) => { + project.read_notices.push(( + crate::project::ReadPart::Maps, + crate::notice_text::NoticeText::format( + "The field package's photo index couldn't be read ({reason}): its photos keep the names they have at home, which may not be on this device.", + [("reason", e.into())], + ), + )); + Default::default() + } + }; // An entry the index lists belongs to the home path it names, and to nothing else: a // feature naming the entry itself (a reference copy's, say) isn't pointed at that photo. let listed: std::collections::HashSet = index.keys().cloned().collect(); @@ -2831,6 +2858,40 @@ mod tests { assert!(said.iter().any(|t| t.starts_with("1 photo(s) couldn't be put") && t.contains("tab or a line break")), "{said:?}"); } + /// A package from home whose photo index is there but can't be read is said, on opening and + /// on sending back: its photos can't be told from the field's. + #[test] + fn an_unreadable_photo_index_is_said_on_opening_and_on_sending_back() { + let temp = Temp::new("bad-index"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let photo = temp.path().join("site.jpg"); + std::fs::write(&photo, b"a picture").unwrap(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); + let (_, out) = package(&mut home, &json!({"name": "Bad", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let unpacked = temp.path().join("field"); + let text = unpack_into(&out, &unpacked).unwrap().0; + // The index damaged: a folder where the file was. + let index = unpacked.join("photos").join("index.tsv"); + std::fs::remove_file(&index).unwrap(); + std::fs::create_dir(&index).unwrap(); + let mut project = project_in(&text, &unpacked).unwrap(); + let opened_notes: Vec = + project.take_read_notices(&[crate::project::ReadPart::Maps]).iter().map(crate::notice_text::NoticeText::english).collect(); + assert!(opened_notes.iter().any(|t| t.starts_with("The field package's photo index couldn't be read")), "{opened_notes:?}"); + let mut field = opened(project); + field.opened_package = Some(temp.path().join("sent.rgisfield")); + // The feature names the unpacked photo: sending back can't tell it was home's. + let there = unpacked.join("photos").join("home-00001.jpg"); + field.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": there.display().to_string()})).unwrap(); + let mark = field.notice_mark(); + package(&mut field, &Value::Null).unwrap(); + let said: Vec = field.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(said.iter().any(|t| t.starts_with("The photo index of the field package this map came from couldn't be read")), "{said:?}"); + } + /// A return opened on another device and sent again carries the field's photos from there: /// only a package from home maps its photos back to home's paths, so a return's own index /// (which names the first phone's paths) never stands in for the photo. From a1f7427a025c2c494c76af7ebf304e42740a1c61 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 18:23:41 -0600 Subject: [PATCH 16/24] fix(engine): only a full path maps to home, and the mapping pass looks at Cancel Review follow-up: home_path maps only absolute paths, so a relative photo name is never looked up wherever the app runs; mapping the change list's old photo values looks at Cancel for each row. --- crates/engine/src/cmd/field.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 96b318dba0..544f2c8cfb 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -338,7 +338,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not if !package.is_empty() { match super::field_changes::list(s.map(), &package) { Ok(Some(mut changes)) => { - photos_named_at_home(&mut changes); + photos_named_at_home(&mut changes)?; if !changes.gone.is_empty() { losses.push(format!( "{} layer(s) the field package gave were removed from its map, so none of their features change at home: {}", @@ -942,12 +942,14 @@ fn rewrite_paths(held: &str, rewrite: &mut impl FnMut(&str) -> String) -> Option /// Names each photo a package brought from home by its path at home again in the old values of /// `changes`: the field held it at the path it was unpacked to, and Bring Back checks each old /// value against home's. -fn photos_named_at_home(changes: &mut super::field_changes::Changes) { +fn photos_named_at_home(changes: &mut super::field_changes::Changes) -> Result<(), String> { let mut unpacked = Unpacked::new(); let package = changes.package.clone(); let mut at_home = |path: &str| home_path(&mut unpacked, &package, path); for layer in &mut changes.layers { for given in layer.edited.iter_mut().chain(layer.deleted.iter_mut()) { + // Reading a value's paths can look at the disk: Cancel is looked at for each row. + rustgis_data::progress::check().map_err(|e| e.to_string())?; for (field, value) in &mut given.values { if !(field.eq_ignore_ascii_case("photos") || field.eq_ignore_ascii_case("photo")) { continue; @@ -959,6 +961,7 @@ fn photos_named_at_home(changes: &mut super::field_changes::Changes) { } } } + Ok(()) } /// The most pieces of a photos field (split at `;`) tried as one path with `;` in it. @@ -1239,6 +1242,11 @@ type Unpacked = std::collections::HashMap String { let file = Path::new(path); + // Only a full path names an unpacked file: a relative one would be looked for wherever the + // app runs. + if !file.is_absolute() { + return path.to_string(); + } file.parent() .zip(file.file_name()) .and_then(|(folder, own)| { From 861f016f729b0be40775550d2265ea4bf4ce170e Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 19:00:50 -0600 Subject: [PATCH 17/24] fix(engine): count the photo scan's progress, and bound the return's index Review follow-up: going out, each photo looked at is a counted step; coming back, a photo whose index line would pass what the computer reads stays on the phone and is counted, as going out; the notice of photos that didn't fit names the size, index and entry limits. --- crates/engine/src/cmd/field.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 544f2c8cfb..8f518ac0de 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -315,7 +315,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not if !photos.too_large.is_empty() { let named = &photos.too_large; losses.push(format!( - "{} photo(s) didn't fit in the field package with the basemaps and photos before them, so they stayed home: {}", + "{} photo(s) didn't fit in the field package (its size, index or entry limit), so they stayed home: {}", named.len(), some_of(named) )); @@ -1035,8 +1035,10 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) } } let (mut index, mut number) = (String::new(), 0u32); + // Each photo looked at is a step: its file is read. + rustgis_data::progress::begin(named.len()); for path in named { - rustgis_data::progress::check().map_err(|e| e.to_string())?; + rustgis_data::progress::step(1).map_err(|e| e.to_string())?; let file = Path::new(&path); if !file.is_absolute() { found.missing.push(path.to_string()); @@ -1180,7 +1182,10 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R found.unread.push(format!("{path} (its name holds a tab or a line break)")); return path.to_string(); } - if size > *budget { + // Past the budget, or past what the computer reads of the index (its line as long as it + // can be, with a numbered name): it stays on the phone. + let longest_line = PHOTOS.len() + 8 + file.file_name().map_or(0, |n| n.len()) + path.len() + 2; + if size > *budget || (index.len() + longest_line) as u64 > MAX_INDEX { said.insert(path.to_string()); found.too_large.push(path.to_string()); return path.to_string(); From 00c3d9aecd134551a248227c50d54b29f7077761 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 19:27:40 -0600 Subject: [PATCH 18/24] fix(engine): count the return's photo scan, row by row --- crates/engine/src/cmd/field.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 8f518ac0de..15316a9eee 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1123,8 +1123,11 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R let mut said = std::collections::HashSet::new(); // The index unpacked with each folder of photos a package brought: entry → path at home. let mut unpacked = Unpacked::new(); - // Cancel is looked at before each row: reading a row's paths can look at the disk. - let go_on = || rustgis_data::progress::check().map_err(|e| e.to_string()); + // Each row is a counted step, and Cancel is looked at before it: reading a row's paths can + // look at the disk. + let rows: usize = map.layers.iter().filter(|l| !l.is_raster() && photos_field(l).is_some()).map(|l| l.dataset.features.len()).sum(); + rustgis_data::progress::begin(rows); + let go_on = || rustgis_data::progress::step(1).map_err(|e| e.to_string()); rewrite_photos_until( map, |path| { From 019c98747cc66c3abfb1605afa4a81e329f29f4b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 20:06:02 -0600 Subject: [PATCH 19/24] fix(engine): a package from home with photos but no index is said Review follow-up: a photos folder from home without its index is damaged, not photo-free, so it is said like an unreadable index. The index file name is a constant, and the notes' order and the listed-entry rule say what they rely on. --- crates/engine/src/cmd/field.rs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 15316a9eee..6b23717b7e 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -535,6 +535,8 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not entries.retain(|(n, _)| !n.starts_with(&format!("{PHOTOS}/"))); companions = companion_bytes(&entries) + MARKER_ROOM; // Before the note the fallback below takes back, if it runs. + // The note of the layers copied for reference is the last one when there are any (pushed + // just before the manifest); the fallback below takes it back first. let at = losses.len() - usize::from(!copied.is_empty()); losses.insert(at, format!("{carried} photo(s) stayed home: the map needed the field package's room for them")); manifest = manifest_bytes(&archive_errors, &losses)?; @@ -1275,10 +1277,11 @@ fn unpacked_index(folder: &Path, package: &str) -> Result Result { } }; // An entry the index lists belongs to the home path it names, and to nothing else: a - // feature naming the entry itself (a reference copy's, say) isn't pointed at that photo. + // feature naming the entry itself isn't pointed at that photo. A streamed layer's copy for + // reference can: its rows are read after the photo names are given (`collect_photos` skips + // streamed layers), so a home row naming `photos/home-00001.jpg` isn't kept clear of them. let listed: std::collections::HashSet = index.keys().cloned().collect(); let at_home: std::collections::HashMap = index.into_iter().map(|(entry, named)| (named, entry)).collect(); for map in &mut project.maps { @@ -2889,9 +2897,14 @@ mod tests { let (_, out) = package(&mut home, &json!({"name": "Bad", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); let text = unpack_into(&out, &unpacked).unwrap().0; - // The index damaged: a folder where the file was. + // The index gone from beside the photos: damaged too. let index = unpacked.join("photos").join("index.tsv"); std::fs::remove_file(&index).unwrap(); + let mut missing = project_in(&text, &unpacked).unwrap(); + let said: Vec = + missing.take_read_notices(&[crate::project::ReadPart::Maps]).iter().map(crate::notice_text::NoticeText::english).collect(); + assert!(said.iter().any(|t| t.contains("missing beside the photos")), "{said:?}"); + // The index damaged: a folder where the file was. std::fs::create_dir(&index).unwrap(); let mut project = project_in(&text, &unpacked).unwrap(); let opened_notes: Vec = From 216a9b0ee7db066f283206b6ef1bf6f9a3e04979 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 20:36:49 -0600 Subject: [PATCH 20/24] fix(engine): a home photo unpacked where no text names it keeps its home name Review follow-up: when the unpack folder's name isn't UTF-8, a photo from home keeps the name it has at home, and the opening notice says it doesn't show on this device; named by its relative entry instead, a whole-map return would have taken that name for an edit and written it over home's path. --- crates/engine/src/cmd/field.rs | 49 +++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 6b23717b7e..1b5c2f4a7e 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1879,6 +1879,8 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { let mut project = Project::from_import_json(text, Some(dir))?; let photos = std::path::absolute(dir.join(PHOTOS)).map_err(|e| e.to_string())?; let mut relative = 0_usize; + // Photos from home that keep their names there, the unpack folder's name not being text. + let mut unshown = 0_usize; if photos.is_dir() { // A package from home names its photos where they are at home; its index says which entry // each is. @@ -1906,9 +1908,10 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { if listed.contains(path) { return path.to_string(); } - // One named where it is at home is pointed at its unpacked file: by its full path, - // or, where the unpack folder's name can't be held as text, by its entry, relative - // to the package, as one a return carries. + // A return's photo is pointed at its unpacked file by its full path, or by its entry, + // relative to the package, where the unpack folder's name can't be held as text. One + // named where it is at home is pointed there by its full path only: otherwise it + // keeps its name at home, so the way back can't take its name here for an edit. let (named, entry) = (path, at_home.get(path).map_or(path, String::as_str)); if let Some(name) = entry.strip_prefix("photos/").filter(|name| plain_file(name)) { let file = photos.join(name); @@ -1916,8 +1919,11 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { if let Some(path) = file.to_str() { return path.to_string(); } + if named != entry { + unshown += 1; + return named.to_string(); + } relative += 1; - return entry.to_string(); } } named.to_string() @@ -1927,6 +1933,15 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { // The rows as given, taken (sharing them) for `offline.keepRows` to keep, when this package // went out from home: a return opened here keeps none. project.given = super::field_changes::GivenRows::in_package(dir, &project).map(std::sync::Arc::new); + if unshown > 0 { + project.read_notices.push(( + crate::project::ReadPart::Maps, + crate::notice_text::NoticeText::format( + "{count} photo(s) the field package brought from home keep the names they have there, because the unpack folder is not UTF-8: they don't show on this device.", + [("count", unshown.to_string().into())], + ), + )); + } if relative > 0 { project.read_notices.push(( crate::project::ReadPart::Maps, @@ -2921,6 +2936,32 @@ mod tests { assert!(said.iter().any(|t| t.starts_with("The photo index of the field package this map came from couldn't be read")), "{said:?}"); } + /// Unpacked into a folder whose name isn't UTF-8, a photo from home keeps its name at home + /// (no path the project holds can name the unpacked file), and that is said: the way back then + /// sees no edit in it. Apple's file system refuses such a name, so this runs on other Unix + /// systems. + #[cfg(all(unix, not(target_vendor = "apple")))] + #[test] + fn a_home_photo_unpacked_where_no_text_names_it_keeps_its_home_name() { + use std::os::unix::ffi::OsStrExt as _; + let temp = Temp::new("home-photo-non-utf8"); + let mut home = sample(); + home.path = Some(temp.path().join("home.rgis")); + let cities = layer(&home, "Cities"); + home.run("edit.addField", &json!({"layer": cities, "name": "photos", "type": "text"})).unwrap(); + let photo = temp.path().join("site.jpg"); + std::fs::write(&photo, b"a picture").unwrap(); + home.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": photo.display().to_string()})).unwrap(); + let (_, out) = package(&mut home, &json!({"name": "Odd", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); + let unpacked = temp.path().join(std::ffi::OsStr::from_bytes(b"non-utf8-\xff")); + let text = unpack_into(&out, &unpacked).unwrap().0; + let mut project = project_in(&text, &unpacked).unwrap(); + let said: Vec = + project.take_read_notices(&[crate::project::ReadPart::Maps]).iter().map(crate::notice_text::NoticeText::english).collect(); + assert!(said.iter().any(|t| t.starts_with("1 photo(s) the field package brought from home keep the names")), "{said:?}"); + assert_eq!(value(&Session::new(project), "Cities", 0, "photos"), photo.display().to_string()); + } + /// A return opened on another device and sent again carries the field's photos from there: /// only a package from home maps its photos back to home's paths, so a return's own index /// (which names the first phone's paths) never stands in for the photo. From 9570940530ccbbc735f63116d798908c05459d47 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 21:20:45 -0600 Subject: [PATCH 21/24] fix(engine): a damaged photo index is said, and a listed photo not held is counted Review follow-up: an index line that isn't an entry and a path, an entry listed twice, or a photos folder that can't be listed makes the index damaged, said as an unreadable one is; a photo the index lists that the package doesn't hold is counted on opening, its feature keeping its name at home. --- crates/engine/src/cmd/field.rs | 44 ++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 1b5c2f4a7e..56256ae8b7 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1280,20 +1280,20 @@ fn unpacked_index(folder: &Path, package: &str) -> Result Result { let mut relative = 0_usize; // Photos from home that keep their names there, the unpack folder's name not being text. let mut unshown = 0_usize; + // Photos from home the index lists that the package doesn't hold. + let mut absent = 0_usize; if photos.is_dir() { // A package from home names its photos where they are at home; its index says which entry // each is. @@ -1915,6 +1917,10 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { let (named, entry) = (path, at_home.get(path).map_or(path, String::as_str)); if let Some(name) = entry.strip_prefix("photos/").filter(|name| plain_file(name)) { let file = photos.join(name); + // A photo the index lists that isn't there: the feature keeps its name at home. + if named != entry && !file.is_file() { + absent += 1; + } if file.is_file() { if let Some(path) = file.to_str() { return path.to_string(); @@ -1933,6 +1939,15 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { // The rows as given, taken (sharing them) for `offline.keepRows` to keep, when this package // went out from home: a return opened here keeps none. project.given = super::field_changes::GivenRows::in_package(dir, &project).map(std::sync::Arc::new); + if absent > 0 { + project.read_notices.push(( + crate::project::ReadPart::Maps, + crate::notice_text::NoticeText::format( + "{count} photo(s) the field package lists aren't in it: their features keep the names they have at home, which may not be on this device.", + [("count", absent.to_string().into())], + ), + )); + } if unshown > 0 { project.read_notices.push(( crate::project::ReadPart::Maps, @@ -2912,8 +2927,23 @@ mod tests { let (_, out) = package(&mut home, &json!({"name": "Bad", "extent": [-180.0, -85.0, 180.0, 85.0]})).unwrap(); let unpacked = temp.path().join("field"); let text = unpack_into(&out, &unpacked).unwrap().0; - // The index gone from beside the photos: damaged too. let index = unpacked.join("photos").join("index.tsv"); + let notes = |project: &mut Project| -> Vec { + project.take_read_notices(&[crate::project::ReadPart::Maps]).iter().map(crate::notice_text::NoticeText::english).collect() + }; + // A photo the index lists that the package doesn't hold: counted. + let listed = std::fs::read_to_string(&index).unwrap(); + let held = unpacked.join("photos").join("home-00001.jpg"); + let bytes = std::fs::read(&held).unwrap(); + std::fs::remove_file(&held).unwrap(); + let said = notes(&mut project_in(&text, &unpacked).unwrap()); + assert!(said.iter().any(|t| t.starts_with("1 photo(s) the field package lists aren't in it")), "{said:?}"); + std::fs::write(&held, bytes).unwrap(); + // An entry listed twice: the index is damaged. + std::fs::write(&index, format!("{listed}{listed}")).unwrap(); + let said = notes(&mut project_in(&text, &unpacked).unwrap()); + assert!(said.iter().any(|t| t.contains("is listed twice")), "{said:?}"); + // The index gone from beside the photos: damaged too. std::fs::remove_file(&index).unwrap(); let mut missing = project_in(&text, &unpacked).unwrap(); let said: Vec = From 611807b8a3b239d43eb9a4b06b9927776efdd108 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 21:53:58 -0600 Subject: [PATCH 22/24] fix(engine): an index that isn't UTF-8 is damaged, and absent photos are counted once Review follow-up: a photo index that isn't UTF-8 text is said as damaged, not read with replaced characters; a listed photo the package doesn't hold is counted once however many features name it; take_photos' doc says Cancel is looked at before each row. --- crates/engine/src/cmd/field.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 56256ae8b7..762296a1ba 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1113,7 +1113,8 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) /// [`Photos::missing`]. A photo a package from home brought is named by /// its path at home again, from the [`INDEX`] unpacked beside it ([`home_path`]), and isn't /// carried: home has it, so it takes none of the package's room, and a feature whose photos the -/// field left alone names them as home does. Cancel is checked before each photo is looked at. +/// field left alone names them as home does. Each row is a counted step, Cancel looked at before +/// it. fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> Result { let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. @@ -1284,7 +1285,7 @@ fn unpacked_index(folder: &Path, package: &str) -> Result Result { // Photos from home that keep their names there, the unpack folder's name not being text. let mut unshown = 0_usize; // Photos from home the index lists that the package doesn't hold. - let mut absent = 0_usize; + let mut absent = std::collections::HashSet::new(); if photos.is_dir() { // A package from home names its photos where they are at home; its index says which entry // each is. @@ -1919,7 +1920,7 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { let file = photos.join(name); // A photo the index lists that isn't there: the feature keeps its name at home. if named != entry && !file.is_file() { - absent += 1; + absent.insert(named.to_string()); } if file.is_file() { if let Some(path) = file.to_str() { @@ -1939,12 +1940,12 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { // The rows as given, taken (sharing them) for `offline.keepRows` to keep, when this package // went out from home: a return opened here keeps none. project.given = super::field_changes::GivenRows::in_package(dir, &project).map(std::sync::Arc::new); - if absent > 0 { + if !absent.is_empty() { project.read_notices.push(( crate::project::ReadPart::Maps, crate::notice_text::NoticeText::format( "{count} photo(s) the field package lists aren't in it: their features keep the names they have at home, which may not be on this device.", - [("count", absent.to_string().into())], + [("count", absent.len().to_string().into())], ), )); } @@ -2939,6 +2940,10 @@ mod tests { let said = notes(&mut project_in(&text, &unpacked).unwrap()); assert!(said.iter().any(|t| t.starts_with("1 photo(s) the field package lists aren't in it")), "{said:?}"); std::fs::write(&held, bytes).unwrap(); + // An index that isn't UTF-8 text: damaged. + std::fs::write(&index, b"photos/home-00001.jpg\t\xff\n").unwrap(); + let said = notes(&mut project_in(&text, &unpacked).unwrap()); + assert!(said.iter().any(|t| t.contains("not UTF-8 text")), "{said:?}"); // An entry listed twice: the index is damaged. std::fs::write(&index, format!("{listed}{listed}")).unwrap(); let said = notes(&mut project_in(&text, &unpacked).unwrap()); From 6a8fe2381bf19737643544ea6f78830427edcaca Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 22:25:20 -0600 Subject: [PATCH 23/24] fix(engine): a return's photos stop short of the archive's entry limit Review follow-up: coming back, photos past the entries a package holds stay on the phone and are counted, as going out; photos sharing a file name are numbered from where the last one stopped instead of each counting up from 2. --- crates/engine/src/cmd/field.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 762296a1ba..40122d80a5 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -269,7 +269,9 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not // naming them as before (the phone points them at the unpacked files); coming back, those // taken in the field (and those that came from home, under their paths there). let photos = if coming_back { - take_photos(&mut map, &mut budget, s.project.field_origin.as_ref().map_or("", |o| o.package.as_str()))? + // Room for the package's own entries, as going out. + let most_entries = usize::from(u16::MAX).saturating_sub(entries.len() + 16); + take_photos(&mut map, &mut budget, s.project.field_origin.as_ref().map_or("", |o| o.package.as_str()), most_entries)? } else { // Room for the package's own entries (its project, README, notes, marker and index). let most_entries = usize::from(u16::MAX).saturating_sub(entries.len() + 16); @@ -1115,12 +1117,14 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) /// carried: home has it, so it takes none of the package's room, and a feature whose photos the /// field left alone names them as home does. Each row is a counted step, Cancel looked at before /// it. -fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> Result { +fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str, most_entries: usize) -> Result { let mut found = Photos::default(); // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); let mut placed: std::collections::HashMap = std::collections::HashMap::new(); let mut taken = std::collections::HashSet::new(); + // The next number to try for each name: photos sharing one don't each count up from 2. + let mut next: std::collections::HashMap = std::collections::HashMap::new(); // The files already said (missing, not pictures, too large, or unread): each said once, // however many name it. let mut said = std::collections::HashSet::new(); @@ -1188,10 +1192,10 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R found.unread.push(format!("{path} (its name holds a tab or a line break)")); return path.to_string(); } - // Past the budget, or past what the computer reads of the index (its line as long as it - // can be, with a numbered name): it stays on the phone. + // Past the budget, past what the computer reads of the index (its line as long as it can + // be, with a numbered name), or past the entries a package holds: it stays on the phone. let longest_line = PHOTOS.len() + 8 + file.file_name().map_or(0, |n| n.len()) + path.len() + 2; - if size > *budget || (index.len() + longest_line) as u64 > MAX_INDEX { + if size > *budget || (index.len() + longest_line) as u64 > MAX_INDEX || found.entries.len() >= most_entries { said.insert(path.to_string()); found.too_large.push(path.to_string()); return path.to_string(); @@ -1201,8 +1205,10 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str) -> R *budget = budget.saturating_sub(bytes.len() as u64); let stem = file.file_name().map(|n| plain_name(&n.to_string_lossy())).unwrap_or_else(|| "photo.jpg".into()); let mut name = stem.clone(); - for n in 2.. { + let from = next.entry(stem.to_ascii_lowercase()).or_insert(2); + for n in *from.. { if taken.insert(name.to_ascii_lowercase()) { + *from = n; break; } name = format!("{n}-{stem}"); From 487b2e3c727d27b180cc3925560825d52e50d9a7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 22:51:01 -0600 Subject: [PATCH 24/24] fix(engine): read every photos field, and keep a return's names clear of those given Review follow-up: a layer with both a photos and a photo field has both read, going out, coming back and when counting a reference copy's photos; coming back, names features already give under photos/ are kept clear, as going out; the count of home photos that keep their names counts each once. --- crates/engine/src/cmd/field.rs | 82 +++++++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index 40122d80a5..dc83e5b3de 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -437,7 +437,7 @@ fn build_package(s: &mut Session, p: &Value, notes: &mut rustgis_data::loss::Not // Their photos stay home: a reference copy's edits and photos don't come back. Counted by // their separators, without looking at the disk: a count for the notice. let mut named = 0usize; - for (l, fi) in map.layers.iter().filter(|l| copied.contains(&l.id)).filter_map(|l| photos_field(l).map(|fi| (l, fi))) { + for (l, fi) in map.layers.iter().filter(|l| copied.contains(&l.id)).flat_map(|l| photos_fields(l).map(move |fi| (l, fi))) { for value in l.dataset.features.column(fi) { progress::check().map_err(|e| e.to_string())?; if let rustgis_data::Value::Text(t) = value { @@ -888,11 +888,17 @@ fn manifest_bytes(errors: &[String], losses: &rustgis_data::loss::Notes) -> Resu } } -/// A layer's photos field, by its place: its text field named `photos` or `photo`, whatever the -/// case (as the touch interface names it). +/// A layer's photos field, by its place: its first text field named `photos` or `photo`, whatever +/// the case (as the touch interface names it). fn photos_field(layer: &rustgis_map::Layer) -> Option { - layer.dataset.fields.iter().position(|f| { - f.ty == rustgis_data::FieldType::Text && (f.name.eq_ignore_ascii_case("photos") || f.name.eq_ignore_ascii_case("photo")) + photos_fields(layer).next() +} + +/// Each of a layer's photos fields, by place: a layer can have both a `photos` and a `photo`. +fn photos_fields(layer: &rustgis_map::Layer) -> impl Iterator + '_ { + layer.dataset.fields.iter().enumerate().filter_map(|(i, f)| { + (f.ty == rustgis_data::FieldType::Text && (f.name.eq_ignore_ascii_case("photos") || f.name.eq_ignore_ascii_case("photo"))) + .then_some(i) }) } @@ -909,13 +915,15 @@ fn rewrite_photos_until( mut go_on: impl FnMut() -> Result<(), String>, ) -> Result<(), String> { for l in map.layers.iter_mut().filter(|l| !l.is_raster()) { - let Some(fi) = photos_field(l) else { continue }; + let fields: Vec = photos_fields(l).collect(); let features = &mut l.dataset.features; - for row in 0..features.len() { - go_on()?; - let rustgis_data::Value::Text(held) = features.value(row, fi) else { continue }; - if let Some(out) = rewrite_paths(held, &mut rewrite) { - let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); + for fi in fields { + for row in 0..features.len() { + go_on()?; + let rustgis_data::Value::Text(held) = features.value(row, fi) else { continue }; + if let Some(out) = rewrite_paths(held, &mut rewrite) { + let _ = features.set_value(row, fi, rustgis_data::Value::Text(out)); + } } } } @@ -1021,8 +1029,7 @@ fn collect_photos(map: &rustgis_map::Map, budget: &mut u64, most_entries: usize) (Vec::new(), std::collections::HashSet::new(), std::collections::HashSet::new()); // A streamed layer's photos are left to its copy for reference, which counts them as staying // home (or leaves the layer out): the rows it holds now aren't what the package will hold. - for l in map.layers.iter().filter(|l| !l.is_raster() && !l.is_streamed()) { - let Some(fi) = photos_field(l) else { continue }; + for (l, fi) in map.layers.iter().filter(|l| !l.is_raster() && !l.is_streamed()).flat_map(|l| photos_fields(l).map(move |fi| (l, fi))) { for value in l.dataset.features.column(fi) { // Reading a field's paths can look at the disk (a path with a `;` in it). rustgis_data::progress::check().map_err(|e| e.to_string())?; @@ -1122,7 +1129,16 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str, most // Each photo's entry and the path it was named by, for the way back. let mut index = String::new(); let mut placed: std::collections::HashMap = std::collections::HashMap::new(); + // The names features already give under `photos/` are kept: no photo carried takes one. let mut taken = std::collections::HashSet::new(); + for (l, fi) in map.layers.iter().filter(|l| !l.is_raster()).flat_map(|l| photos_fields(l).map(move |fi| (l, fi))) { + for value in l.dataset.features.column(fi) { + let rustgis_data::Value::Text(held) = value else { continue }; + for name in held.split(';').filter_map(|p| p.trim().strip_prefix(&format!("{PHOTOS}/"))) { + taken.insert(name.to_ascii_lowercase()); + } + } + } // The next number to try for each name: photos sharing one don't each count up from 2. let mut next: std::collections::HashMap = std::collections::HashMap::new(); // The files already said (missing, not pictures, too large, or unread): each said once, @@ -1132,7 +1148,7 @@ fn take_photos(map: &mut rustgis_map::Map, budget: &mut u64, package: &str, most let mut unpacked = Unpacked::new(); // Each row is a counted step, and Cancel is looked at before it: reading a row's paths can // look at the disk. - let rows: usize = map.layers.iter().filter(|l| !l.is_raster() && photos_field(l).is_some()).map(|l| l.dataset.features.len()).sum(); + let rows: usize = map.layers.iter().filter(|l| !l.is_raster()).map(|l| photos_fields(l).count() * l.dataset.features.len()).sum(); rustgis_data::progress::begin(rows); let go_on = || rustgis_data::progress::step(1).map_err(|e| e.to_string()); rewrite_photos_until( @@ -1553,8 +1569,7 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result { // left without a reference among the layers passed to Sync. let mut unused: std::collections::HashSet<_> = photos.iter().map(|(name, _)| name.clone()).collect(); let prefix = format!("{PHOTOS}/"); - for layer in edited.layers.iter().filter(|l| !l.is_raster()) { - let Some(field) = photos_field(layer) else { continue }; + for (layer, field) in edited.layers.iter().filter(|l| !l.is_raster()).flat_map(|l| photos_fields(l).map(move |fi| (l, fi))) { for value in layer.dataset.features.column(field) { let rustgis_data::Value::Text(text) = value else { continue }; for span in photo_paths(text) { @@ -1887,7 +1902,7 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { let photos = std::path::absolute(dir.join(PHOTOS)).map_err(|e| e.to_string())?; let mut relative = 0_usize; // Photos from home that keep their names there, the unpack folder's name not being text. - let mut unshown = 0_usize; + let mut unshown = std::collections::HashSet::new(); // Photos from home the index lists that the package doesn't hold. let mut absent = std::collections::HashSet::new(); if photos.is_dir() { @@ -1933,7 +1948,7 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { return path.to_string(); } if named != entry { - unshown += 1; + unshown.insert(named.to_string()); return named.to_string(); } relative += 1; @@ -1955,12 +1970,12 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { ), )); } - if unshown > 0 { + if !unshown.is_empty() { project.read_notices.push(( crate::project::ReadPart::Maps, crate::notice_text::NoticeText::format( "{count} photo(s) the field package brought from home keep the names they have there, because the unpack folder is not UTF-8: they don't show on this device.", - [("count", unshown.to_string().into())], + [("count", unshown.len().to_string().into())], ), )); } @@ -3003,6 +3018,33 @@ mod tests { assert_eq!(value(&Session::new(project), "Cities", 0, "photos"), photo.display().to_string()); } + /// Every photos field of a layer is read going out, and coming back a name a feature already + /// gives under `photos/` isn't given to a photo carried. + #[test] + fn both_photos_fields_go_out_and_a_returns_names_keep_clear_of_those_given() { + let temp = Temp::new("two-photo-fields"); + let (one, two) = (temp.path().join("one.jpg"), temp.path().join("x.jpg")); + std::fs::write(&one, b"one").unwrap(); + std::fs::write(&two, b"two").unwrap(); + let mut s = sample(); + let cities = layer(&s, "Cities"); + for field in ["photos", "photo"] { + s.run("edit.addField", &json!({"layer": cities, "name": field, "type": "text"})).unwrap(); + } + s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photos", "value": one.display().to_string()})).unwrap(); + s.run("edit.setValue", &json!({"layer": cities, "row": 0, "field": "photo", "value": two.display().to_string()})).unwrap(); + let mut budget = u64::MAX; + let out = collect_photos(s.map(), &mut budget, usize::MAX).unwrap(); + assert_eq!(out.entries.iter().filter(|(n, _)| n != INDEX).count(), 2); + // Coming back: a feature names `photos/x.jpg` (not on this device); the field's x.jpg takes + // another name. + s.run("edit.setValue", &json!({"layer": cities, "row": 1, "field": "photos", "value": "photos/x.jpg"})).unwrap(); + let mut map = s.map().clone(); + let back = take_photos(&mut map, &mut budget, "", usize::MAX).unwrap(); + let names: Vec<&str> = back.entries.iter().map(|(n, _)| n.as_str()).filter(|n| *n != INDEX).collect(); + assert!(names.contains(&"photos/2-x.jpg") && !names.contains(&"photos/x.jpg"), "{names:?}"); + } + /// A return opened on another device and sent again carries the field's photos from there: /// only a package from home maps its photos back to home's paths, so a return's own index /// (which names the first phone's paths) never stands in for the photo.